def score_match(query_rep, text, length_penalty, dictionary=None, debug=False):
if text == "":
return 0
if not dictionary:
words = text.lower().split(' ')
else:
words = [w for w in dictionary.tokenize(text.lower())]
score = 0
rw = query_rep['words']
used = {}
for w in words:
if w in rw and w not in used:
score += rw[w]
if debug:
print("match: " + w)
used[w] = True
norm = math.sqrt(len(used))
score = score / math.pow(norm * query_rep['norm'], length_penalty)
return score
python类pow()的实例源码
def get_num_samples(self, idx):
"""
Number of samples needed to estimate the population variance within the tolerance limit
Sample variance is normally distributed http://stats.stackexchange.com/a/105338/71884
(see warning below).
Var(s^2) /approx 1/n * (\mu_4 - \sigma^4)
Adjust n as per the tolerance needed to estimate the sample variance
warning: does not work for some distributions like bernoulli - https://stats.stackexchange.com/a/104911
use the min_samples for explicitly controlling the number of samples to be drawn
"""
if self.min_samples:
return self.min_samples
min_samples = 1000
tol = 10.0
required_precision = self.prec / tol
if not self.scipy_dist:
return min_samples
args, kwargs = self.scipy_arg_fn(**self.get_dist_params(idx, wrap_tensor=False))
try:
fourth_moment = np.max(self.scipy_dist.moment(4, *args, **kwargs))
var = np.max(self.scipy_dist.var(*args, **kwargs))
min_computed_samples = int(math.ceil((fourth_moment - math.pow(var, 2)) / required_precision))
except (AttributeError, ValueError):
return min_samples
return max(min_samples, min_computed_samples)
def get_tolerance(zoom_level):
# pixels squared factor
tolerance_square_pixels = 7
# default Google/Bing map tile scales
metres_per_pixel = 156543.03390625 / math.pow(2.0, float(zoom_level + 1))
# the tolerance (metres) for vector simplification using the VW algorithm
square_metres_per_pixel = math.pow(metres_per_pixel, 2.0)
# tolerance to use
tolerance = square_metres_per_pixel * tolerance_square_pixels
return tolerance
# maximum number of decimal places for boundary coordinates - improves display performance
def quadraticFactorisation(N=4):
(p,q,pn) = primeFactorisation(N) #??N??????
for ptr0 in range(len(q)): #??????????????
if (q[ptr0] % 2): q[ptr0] += 1
if len(p): #?????????????
if p[0] == 2: p.append(3); q.append(2) #??2??????3^2
else: p.append(2); q.append(2) #??????????2^2
x = y = 1
slc = len(p) / 2 #??
for ptr1 in range(slc): #?????x
x *= int(math.pow(p[ptr1],q[ptr1]))
for ptr2 in range(slc,len(p)): #?????y
y *= int(math.pow(p[ptr2],q[ptr2]))
if (x % 2): x *= 4 #?x?????????4??2^2?
if (y % 2): y *= 4 #?y?????????4??2^2?
return solve(x,y) #?????a?b
#????? | ??????????????????
def get_price_for_trade(prediction, trade):
"""Returns the price of a trade for a prediction."""
if trade.contract == 'CONTRACT_ONE':
old_quantity = prediction.contract_one
old_quantity_other = prediction.contract_two
else:
old_quantity = prediction.contract_two
old_quantity_other = prediction.contract_one
if trade.direction == 'BUY':
new_quantity = old_quantity + trade.quantity
else:
new_quantity = old_quantity - trade.quantity
price = (prediction.liquidity * math.log(
math.pow(math.e, (new_quantity / prediction.liquidity)) +
math.pow(math.e, (old_quantity_other / prediction.liquidity)))) - (
prediction.liquidity * math.log(
math.pow(math.e, (old_quantity / prediction.liquidity)) +
math.pow(math.e, (old_quantity_other / prediction.liquidity))))
return price
def advance(self, dt, padding):
bodies = self.bodies
def calc_vel(i):
b1 = bodies[i]
for b2 in bodies:
d_pos = b1.pos.sub(b2.pos)
distance = d_pos.length() + padding
mag = dt / math.pow(distance, 3)
b1.vel = b1.vel.sub(d_pos.scale(b2.mass).scale(mag))
gpumap(calc_vel, self.indices)
def update(body):
body.pos = body.pos.add(body.vel.scale(dt))
gpumap(update, bodies)
def advance(self, dt, padding):
bodies = self.bodies
def calc_vel(i):
b1 = bodies[i]
for b2 in bodies:
d_pos = b1.pos.sub(b2.pos)
distance = d_pos.length() + padding
mag = dt / math.pow(distance, 3)
b1.vel = b1.vel.sub(d_pos.scale(b2.mass).scale(mag))
list(map(calc_vel, self.indices))
def update(body):
body.pos = body.pos.add(body.vel.scale(dt))
list(map(update, bodies))
def E_MurnV(V,a0,a1,a2,a3):
"""
This function implements the Murnaghan EOS (in a form which is best for fitting).
Returns the energy at the volume *V* using the coefficients *a0,a1,a2,a3*
from the equation:
.. math::
E = a_0 - (a_2*a_1)/(a_3-1.0) V a_2/a_3 ( a_1/V^{a_3})/(a_3-1.0) +1.0 )
"""
res=np.zeros(len(V))
for i in range(0,len(V)):
res[i]=a0 - a2*a1/(a3-1.0) + V[i]*a2/a3*( pow(a1/V[i],a3)/(a3-1.0)+1.0 )
return res
# Other functions
def c_qv2(T,omega):
x = omega * kb1 / T
expx = math.exp(-x) # exponential term
x2 = math.pow(x,2)
return x2*K_BOLTZMANN_RY*expx/math.pow(expx-1.0,2)
################################################################################
#
# This function computes the thermal expansions alpha using the Gruneisein
# parameters
# more comments to be added
# First with min0, freq and grun T-independent
#
# More ibrav types to be implemented
def _get_max_sigma(self, R):
"""Calculate maximum sigma of scanner RAS coordinates
Parameters
----------
R : 2D array, with shape [n_voxel, n_dim]
The coordinate matrix of fMRI data from one subject
Returns
-------
max_sigma : float
The maximum sigma of scanner coordinates.
"""
max_sigma = 2.0 * math.pow(np.nanmax(np.std(R, axis=0)), 2)
return max_sigma
def get_epsilon_k(self):
'''
Get $\epsilon_k$ according to the exploration schedule
'''
trial = self.env.count_trials - 2 # ?
if self.decayfun == 'tpower':
# e = a^t, where 0 < z < 1
# self.f_epsilon = math.pow(0.9675, trial) # for 100 trials
self.f_epsilon = math.pow(0.9333, trial) # for 50 trials
elif self.decayfun == 'trig':
# e = cos(at), where 0 < z < 1
# self.f_epsilon = math.cos(0.0168 * trial) # for 100 trials
self.f_epsilon = math.cos(0.03457 * trial) # for 50 trials
else:
# self.f_epsilon = max(0., 1. - (1./45. * trial)) # for 50 trials
self.f_epsilon = max(0., 1. - (1./95. * trial)) # for 100 trials
return self.f_epsilon
def getlearningrate(epoch, opt):
# update lr
lr = opt.LR
if opt.lrPolicy == "multistep":
if epoch + 1.0 > opt.nEpochs * opt.ratio[1]: # 0.6 or 0.8
lr = opt.LR * 0.01
elif epoch + 1.0 > opt.nEpochs * opt.ratio[0]: # 0.4 or 0.6
lr = opt.LR * 0.1
elif opt.lrPolicy == "linear":
k = (0.001-opt.LR)/math.ceil(opt.nEpochs/2.0)
lr = k*math.ceil((epoch+1)/opt.step)+opt.LR
elif opt.lrPolicy == "exp":
power = math.floor((epoch+1)/opt.step)
lr = lr*math.pow(opt.gamma, power)
elif opt.lrPolicy == "fixed":
lr = opt.LR
else:
assert False, "invalid lr policy"
return lr
def get_inputs_values(self, enemes, input_size=4):
inputs = []
for i in range(input_size):
inputs.append(0.0)
inputs[0] = (self.x * 1.0 / SCREEN_SIZE[0])
index = 1
for eneme in enemes:
inputs[index] = eneme.x * 1.0 / SCREEN_SIZE[0]
index += 1
inputs[index] = eneme.y * 1.0 / SCREEN_SIZE[1]
index += 1
# if len(enemes) > 0:
# distance = math.sqrt(math.pow(enemes[0].x + enemes[0].width/2 - self.x + self.width/2, 2) + math.pow(enemes[0].y + enemes[0].height/2 - self.y + self.height/2, 2));
if len(enemes) > 0 and self.x < enemes[0].x:
inputs[index] = -1.0
index += 1
else:
inputs[index] = 1.0
return inputs
def hex_to_rgb(value, alpha=True):
"""Convets a Hex code to a Blender RGB Value"""
gamma = 2.2
value = value.lstrip('#')
lv = len(value)
fin = list(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))
r = pow(fin[0] / 255, gamma)
g = pow(fin[1] / 255, gamma)
b = pow(fin[2] / 255, gamma)
fin.clear()
fin.append(r)
fin.append(g)
fin.append(b)
if alpha == True:
fin.append(1.0)
return tuple(fin)
def rgb_to_hex(rgb):
"""Converts Blender RGB Value to Hex code"""
gamma = 1/2.2
fin = list(rgb)
r = fin[0]*255
g = fin[1]*255
b = fin[2]*255
r = int(255*pow(r / 255, gamma))
g = int(255*pow(g / 255, gamma))
b = int(255*pow(b / 255, gamma))
fin.clear()
fin.append(r)
fin.append(g)
fin.append(b)
fin = tuple(fin)
return '#%02x%02x%02x' % fin
def convertSize(size):
if (size == 0):
return '0 Bytes'
size_name = ("Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
i = int(math.floor(math.log(size,1024)))
p = math.pow(1024,i)
s = round(size/p,2)
return '{} {}'.format(s,size_name[i])
#http://stackoverflow.com/questions/1392413/calculating-a-directory-size-using-python
def convertSize(size):
if (size == 0):
return '0 Bytes'
size_name = ("Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
i = int(math.floor(math.log(size,1024)))
p = math.pow(1024,i)
s = round(size/p,2)
return '{} {}'.format(s,size_name[i])
def weibull(t1, t2, lam, k):
return 1 - exp(pow(t1 / lam,k) - pow(t2 / lam, k))
def calc_stem_radius(self, stem):
"""Calculate radius of this stem as defined in paper"""
if stem.depth == 0: # trunk
result = stem.length * self.param.ratio * self.param.radius_mod[0]
else: # other
result = self.param.radius_mod[stem.depth] * stem.parent.radius * pow((
stem.length / stem.parent.length), self.param.ratio_power)
result = max(0.005, result)
result = min(stem.radius_limit, result)
return result
def shape_ratio(self, shape, ratio):
"""Calculate shape ratio as defined in paper"""
if shape == 1: # spherical
result = 0.2 + 0.8 * sin(pi * ratio)
elif shape == 2: # hemispherical
result = 0.2 + 0.8 * sin(0.5 * pi * ratio)
elif shape == 3: # cylindrical
result = 1.0
elif shape == 4: # tapered cylindrical
result = 0.5 + 0.5 * ratio
elif shape == 5: # flame
if ratio <= 0.7:
result = ratio / 0.7
else:
result = (1.0 - ratio) / 0.3
elif shape == 6: # inverse conical
result = 1.0 - 0.8 * ratio
elif shape == 7: # tend flame
if ratio <= 0.7:
result = 0.5 + 0.5 * ratio / 0.7
else:
result = 0.5 + 0.5 * (1.0 - ratio) / 0.3
elif shape == 8: # envelope
if ratio < 0 or ratio > 1:
result = 0.0
elif ratio < 1 - self.param.prune_width_peak:
result = pow(ratio / (1 - self.param.prune_width_peak),
self.param.prune_power_high)
else:
result = pow((1 - ratio) / (1 - self.param.prune_width_peak),
self.param.prune_power_low)
else: # conical (0)
result = 0.2 + 0.8 * ratio
return result