def test_logs(self):
LOG10E = math.log10(math.e)
for exp in range(10) + [100, 1000, 10000]:
value = 10 ** exp
log10 = math.log10(value)
self.assertAlmostEqual(log10, exp)
# log10(value) == exp, so log(value) == log10(value)/log10(e) ==
# exp/LOG10E
expected = exp / LOG10E
log = math.log(value)
self.assertAlmostEqual(log, expected)
for bad in -(1L << 10000), -2L, 0L:
self.assertRaises(ValueError, math.log, bad)
self.assertRaises(ValueError, math.log10, bad)
python类log10()的实例源码
def test_logs(self):
LOG10E = math.log10(math.e)
for exp in range(10) + [100, 1000, 10000]:
value = 10 ** exp
log10 = math.log10(value)
self.assertAlmostEqual(log10, exp)
# log10(value) == exp, so log(value) == log10(value)/log10(e) ==
# exp/LOG10E
expected = exp / LOG10E
log = math.log(value)
self.assertAlmostEqual(log, expected)
for bad in -(1L << 10000), -2L, 0L:
self.assertRaises(ValueError, math.log, bad)
self.assertRaises(ValueError, math.log10, bad)
def _parse_code(code):
parsed_code = []
while len(code):
next_token, code = CAM._get_next_token_new(code)
parsed_code.append(next_token)
if next_token == u'?' or next_token == 'Y':
arg, code = get_term_in_brackets(code)
parsed_code.append(CAM._parse_code(arg))
elif next_token == '\'':
arg = int(UnicodeHack(re.search(CAM.nums_re, code).group()))
parsed_code.append([arg])
length = int(log10(abs(arg))) + 1 if arg != 0 else 1
code = code[length if arg >= 0 else length + 1:]
elif next_token == 'br':
args, code = get_term_in_brackets(code, remove_brackets=False)
arg1, arg2 = parse_args_in_brackets(args)
parsed_code.append([CAM._parse_code(arg1), CAM._parse_code(arg2)])
return parsed_code[::-1]
def round_sig( val, sig ) :
if ( val is None ) :
return None
elif ( val == 0. ) :
return 0.
else :
return round( val,
sig - int( floor( log10( abs( val ) ) ) ) - 1 )
################################################################################
## DEFINE THE FUNCTION FOR COMPUTING UNIT VECTOR
################################################################################
# Define the function for computing unit vector
def ansi_density(color, density_standard):
"""
Calculates density for the given SpectralColor using the spectral weighting
function provided. For example, ANSI_STATUS_T_RED. These may be found in
:py:mod:`colormath.density_standards`.
:param SpectralColor color: The SpectralColor object to calculate density for.
:param numpy.ndarray std_array: NumPy array of filter of choice
from :py:mod:`colormath.density_standards`.
:rtype: float
:returns: The density value for the given color and density standard.
"""
# Load the spec_XXXnm attributes into a Numpy array.
sample = color.get_numpy_array()
# Matrix multiplication
intermediate = sample * density_standard
# Sum the products.
numerator = intermediate.sum()
# This is the denominator in the density equation.
sum_of_standard_wavelengths = density_standard.sum()
# This is the top level of the density formula.
return -1.0 * log10(numerator / sum_of_standard_wavelengths)
def getMapLines(dmin, dmax, nlines):
drange = dmax-dmin
if drange > 4:
near = 1
else:
if drange >= 0.5:
near = 0.25
else:
near = 0.125
inc = roundToNearest(drange/nlines, near)
if inc == 0:
# make the increment the closest power of 10
near = np.power(10, round(math.log10(drange)))
inc = ceilToNearest(drange/nlines, near)
newdmin = floorToNearest(dmin, near)
newdmax = ceilToNearest(dmax, near)
else:
newdmin = ceilToNearest(dmin, near)
newdmax = floorToNearest(dmax, near)
darray = np.arange(newdmin, newdmax+inc, inc)
if darray[-1] > dmax:
darray = darray[0:-1]
return darray
def show_threads():
"""
Log the name, ident and daemon flag of all alive threads in DEBUG level
"""
if logger.isEnabledFor(logging.DEBUG):
all_threads = threading.enumerate()
max_name = reduce(max, map(len, [t.name for t in all_threads]))
max_ident = reduce(max, map(int, map(math.ceil, map(math.log10, [t.ident for t in all_threads if t.ident is not None]))))
msg = ['Name' + ' '*(max_name-2) + 'Ident' + ' '*(max_ident-3) + 'Daemon',
'='*max_name + ' ' + '=' * max_ident + ' ======']
fmt = '%{0}.{0}s %{1}d %d'.format(max_name, max_ident)
for t in threading.enumerate():
msg.append(fmt % (t.name, t.ident, t.daemon))
logger.debug("Threads currently alive on process %d:\n%s", os.getpid(), '\n'.join(msg))
def test_logs(self):
LOG10E = math.log10(math.e)
for exp in list(range(10)) + [100, 1000, 10000]:
value = 10 ** exp
log10 = math.log10(value)
self.assertAlmostEqual(log10, exp)
# log10(value) == exp, so log(value) == log10(value)/log10(e) ==
# exp/LOG10E
expected = exp / LOG10E
log = math.log(value)
self.assertAlmostEqual(log, expected)
for bad in -(1 << 10000), -2, 0:
self.assertRaises(ValueError, math.log, bad)
self.assertRaises(ValueError, math.log10, bad)
def calculateWordsIDF(texts):
all_documents_count = len(texts);
idf_data = dict()
for text in texts:
for word, frequency in text.word_frequency.items():
word_doc_freq = 0.0;
for doc in texts:
if(isSentencesContainsWord(doc.register_pass_centences, word)):
word_doc_freq = word_doc_freq + 1.0
continue
pre_idx = (0.0 + all_documents_count)/word_doc_freq
inverse_document_frequency = math.log10(pre_idx)
idf_data[word] = inverse_document_frequency
return idf_data
# ????????? TF*IDF ??? ??????? ????? ??????? ?????? ? ?????????? ? text.words_tf_idf[word]
def generate_R_scripts():
r_file = open(outdir + "/r_script.r","w")
if len(feature_list)==0:
r_file.close()
else :
cmd = "output_corr_matrix <- read.delim(\"" + outdir + "/output_corr_matrix.txt\")\n"
cmd = cmd + "data = output_corr_matrix\n"
cmd = cmd + "d3 <- as.dist((1 - data[,-1]))\n"
cmd = cmd + "clust3 <- hclust(d3, method = \"average\")\n"
if len(feature_list) < 5:
cmd = cmd + "pdf(\"" +outdir+ "/" + pdf_tag + ".pdf\", width=10, height=7)\n"
else:
cmd = cmd + "pdf(\"" +outdir+ "/" + pdf_tag + ".pdf\", width="+str(math.log10(len(feature_list))*10) +", height=7)\n"
cmd = cmd + "op = par(bg = \"gray85\")\n"
cmd = cmd + "par(plt=c(0.05, 0.95, 0.2, 0.9))\n"
cmd = cmd + "plot(clust3, lwd = 2, lty = 1,cex=0.8, xlab=\"Samples\", sub = \"\", ylab=\"Distance (1-Pearson correlation)\",hang = -1, axes = FALSE)\n"
cmd = cmd + "axis(side = 2, at = seq(0, 1, 0.2), labels = FALSE, lwd = 2)\n"
cmd = cmd + "mtext(seq(0, 1, 0.2), side = 2, at = seq(0, 1, 0.2), line = 1, las = 2)\n"
cmd = cmd + "dev.off()\n"
r_file.write(cmd)
r_file.close()
def generate_R_scripts():
r_file = open(outdir + "/r_script.r","w")
if len(feature_list)==0:
r_file.close()
else :
cmd = "output_corr_matrix <- read.delim(\"" + outdir + "/output_corr_matrix.txt\")\n"
cmd = cmd + "data = output_corr_matrix\n"
cmd = cmd + "d3 <- as.dist((1 - data[,-1]))\n"
cmd = cmd + "clust3 <- hclust(d3, method = \"average\")\n"
if len(feature_list) < 5:
cmd = cmd + "pdf(\"" +outdir+ "/" + pdf_tag + ".pdf\", width=10, height=7)\n"
else:
cmd = cmd + "pdf(\"" +outdir+ "/" + pdf_tag + ".pdf\", width="+str(math.log10(len(feature_list))*10) +", height=7)\n"
cmd = cmd + "op = par(bg = \"gray85\")\n"
cmd = cmd + "par(plt=c(0.05, 0.95, 0.2, 0.9))\n"
cmd = cmd + "plot(clust3, lwd = 2, lty = 1,cex=0.8, xlab=\"Samples\", sub = \"\", ylab=\"Distance (1-Pearson correlation)\",hang = -1, axes = FALSE)\n"
cmd = cmd + "axis(side = 2, at = seq(0, 1, 0.2), labels = FALSE, lwd = 2)\n"
cmd = cmd + "mtext(seq(0, 1, 0.2), side = 2, at = seq(0, 1, 0.2), line = 1, las = 2)\n"
cmd = cmd + "dev.off()\n"
r_file.write(cmd)
r_file.close()
def predict(testSet,PP,PN,positive_probabilities,negative_probabilities,unseen_pos_prob,unseen_neg_prob):
predicted_class = []
for review in testSet:
negative_probab = math.log10(PN)
positive_probab = math.log10(PP)
review_words = word_tokenize(review)
for w in review_words:
if w in negative_probabilities:
negative_probab = negative_probab + math.log10(negative_probabilities[w])
else:
negative_probab = negative_probab + math.log10(unseen_neg_prob)
if w in positive_probabilities:
positive_probab = positive_probab + math.log10(positive_probabilities[w])
else:
positive_probab = positive_probab + math.log10(unseen_pos_prob)
if(negative_probab > positive_probab):
result = '-'
else:
result = '+'
predicted_class.append(result)
return predicted_class
def format_message(self, current, total):
"""Creates message to be written on console"""
if total:
ratio = float(current) / total
filled_bricks = int((ratio + 0.05) * self.progress_num_bricks)
num_digits = int(math.log10(total))
else:
ratio = 1.0
filled_bricks = self.progress_num_bricks
num_digits = 1
last_step = total == current
if last_step:
eta = datetime.timedelta(0)
elif ratio and self.start_datetime:
total_seconds_ = total_seconds(
datetime.datetime.now() - self.start_datetime
)
eta = datetime.timedelta(
seconds=total_seconds_ / ratio - total_seconds_
)
else:
eta = '?'
screw = " " if last_step else next(self.screw_cycle)
return self.line_template.format(
bricks=self.progress_brick * filled_bricks,
num_bricks=self.progress_num_bricks,
ratio=ratio,
current=current,
total=total,
num_digits=num_digits,
eta=eta,
screw=screw
)
def log2(x):
"""Base 2 logarithm.
>>> log2(1024)
10.0
"""
return math.log10(x) / math.log10(2)
def compute_scale(
min_, max_, logarithmic, order_min,
min_scale, max_scale):
"""Compute an optimal scale between min and max"""
if min_ == 0 and max_ == 0:
return [0]
if max_ - min_ == 0:
return [min_]
if logarithmic:
log_scale = compute_logarithmic_scale(
min_, max_, min_scale, max_scale)
if log_scale:
return log_scale
# else we fallback to normal scalling
order = round(log10(max(abs(min_), abs(max_)))) - 1
if order_min is not None and order < order_min:
order = order_min
else:
while ((max_ - min_) / (10 ** order) < min_scale and
(order_min is None or order > order_min)):
order -= 1
step = float(10 ** order)
while (max_ - min_) / step > max_scale:
step *= 2.
positions = []
position = round_to_scale(min_, step)
while position < (max_ + step):
rounded = round_to_scale(position, step)
if min_ <= rounded <= max_:
if rounded not in positions:
positions.append(rounded)
position += step
if len(positions) < 2:
return [min_, max_]
return positions
def dot(self, serie, r_max):
"""Draw a dot line"""
serie_node = self.svg.serie(serie)
view_values = list(map(self.view, serie.points))
for i, value in safe_enumerate(serie.values):
x, y = view_values[i]
if self.logarithmic:
log10min = log10(self._min) - 1
log10max = log10(self._max or 1)
if value != 0:
size = r_max * (
(log10(abs(value)) - log10min) /
(log10max - log10min)
)
else:
size = 0
else:
size = r_max * (abs(value) / (self._max or 1))
metadata = serie.metadata.get(i)
dots = decorate(
self.svg,
self.svg.node(serie_node['plot'], class_="dots"),
metadata)
alter(self.svg.node(
dots, 'circle',
cx=x, cy=y, r=size,
class_='dot reactive tooltip-trigger' + (
' negative' if value < 0 else '')), metadata)
val = self._format(serie, i)
self._tooltip_data(
dots, val, x, y, 'centered',
self._get_x_label(i))
self._static_value(serie_node, val, x, y, metadata)
def __init__(self, width, height, box):
"""Create the view with a width an height and a box bounds"""
super(PolarLogView, self).__init__(width, height, box)
if not hasattr(box, '_rmin') or not hasattr(box, '_rmax'):
raise Exception(
'Box must be set with set_polar_box for polar charts')
self.log10_rmax = log10(self.box._rmax)
self.log10_rmin = log10(self.box._rmin)
if self.log10_rmin == self.log10_rmax:
self.log10_rmax = self.log10_rmin + 1
def __init__(self, width, height, box, aperture=pi / 3):
"""Create the view with a width an height and a box bounds"""
super(PolarThetaLogView, self).__init__(width, height, box)
self.aperture = aperture
if not hasattr(box, '_tmin') or not hasattr(box, '_tmax'):
raise Exception(
'Box must be set with set_polar_box for polar charts')
self.log10_tmax = log10(self.box._tmax) if self.box._tmax > 0 else 0
self.log10_tmin = log10(self.box._tmin) if self.box._tmin > 0 else 0
if self.log10_tmin == self.log10_tmax:
self.log10_tmax = self.log10_tmin + 1
def __call__(self, rhotheta):
"""Project rho and theta"""
if None in rhotheta:
return None, None
rho, theta = rhotheta
# Center case
if theta == 0:
return super(PolarThetaLogView, self).__call__((0, 0))
theta = self.box._tmin + (self.box._tmax - self.box._tmin) * (
log10(theta) - self.log10_tmin) / (
self.log10_tmax - self.log10_tmin)
start = 3 * pi / 2 + self.aperture / 2
theta = start + (2 * pi - self.aperture) * (
theta - self.box._tmin) / (
self.box._tmax - self.box._tmin)
return super(PolarThetaLogView, self).__call__(
(rho * cos(theta), rho * sin(theta)))