def _rfact(l, m): pi4 = 4 * pi if m == 0: return msqrt((2*l + 1)/pi4) elif m < 0: return -msqrt(2*(2*l + 1)/pi4 * fact(l-m)/fact(l+m)) * (-1) ** m return msqrt(2*(2*l + 1)/pi4 * fact(l-m)/fact(l+m))
def calculate_solutions(self): self.C = 3 * self.b**2 - 8 * self.a * self.c self.D = 2 * self.b**3 - 8 * self.a * self.b * self.c + 16 * self.a * self.a * self.d self.E = -3 * self.b ** 4 + 16 * self.a * self.b ** 2 * self.c - 64 * self.a ** 2 * self.b * self.d +\ 256 * self.a ** 3 * self.e self.X = self.C**2 + 3 * self.E self.Y = -self.C**3 + 9 * self.C * self.E + 27 * self.D**2 if self.X > 0: self.W += [ sqrt((self.C + sqrt(self.X) * cos(acos(self.Y / sqrt(self.X**3)) / 3)) / 3), sqrt((self.C + sqrt(self.X) * cos(acos(self.Y / sqrt(self.X**3)) / 3 - 2 * pi / 3)) / 3), sqrt( (self.C + sqrt(self.X) * cos(acos(self.Y / sqrt(self.X**3)) / 3 - 4 * pi / 3)) / 3) ] if self.Y * self.Y >= self.X * self.X * self.X: self.W += [ sqrt((2 * self.C + cubic_root(self.Y + msqrt(self.Y**2 - self.X**3)) + cubic_root(self.Y - msqrt(self.Y**2 - self.X**3))) / 6) ] self.W = sorted(self.W, key=abs) self.Z = self.W[-1]
def angle(self, n1, n2, n3, unit='radian'): """compute angle n1-n2-n3. Provide real atom numbers""" r1 = array(self.atoms[n1 - 1].pos()) r2 = array(self.atoms[n2 - 1].pos()) r3 = array(self.atoms[n3 - 1].pos()) P1 = r1 - r2 P2 = r3 - r2 P1n = msqrt(sum(P1 * P1)) P2n = msqrt(sum(P2 * P2)) angle = macos(sum(P1 * P2) / (P1n * P2n)) conv = 180. / mPi if unit == 'deg': angle *= conv return angle
def angle(self,n1,n2,n3,unit='radian'): """compute angle n1-n2-n3. Provide real atom numbers""" r1 = array(self.atoms[n1-1].pos()) r2 = array(self.atoms[n2-1].pos()) r3 = array(self.atoms[n3-1].pos()) P1 = r1-r2 P2 = r3-r2 P1n= msqrt(sum(P1*P1)) P2n= msqrt(sum(P2*P2)) angle = macos(sum(P1*P2)/(P1n*P2n)) conv = 180./mPi if unit=='deg': angle*=conv return angle
def distance(p0, p1, doRound=False): # Calculate the distance between two points d = msqrt((p0.x - p1.x) ** 2 + (p0.y - p1.y) ** 2) if doRound: return int(round(d)) else: return d
def fusionLR(p): z = defaultdict(lambda: 0) for ((x, _), a) in p.items(): z[x] += abs(a)**2 for (x, a) in z.items(): z[x] = msqrt(a) return z
def cps(mat_1, mat_2): """ Find rotation and translation difference between two transformations. Arguments: *mat_1,mat_2* Transformation matrices. Returns: The translation and rotation differences """ mat1 = matrix(mat_1) mat2 = matrix(mat_2) # mat to euler (angular distance not accurate!) #t1,p1,s1 = _rotmat_to_euler(mat1) #t2,p2,s2 = _rotmat_to_euler(mat2) #ang_magnitude = msqrt(mpow(t2-t1,2)+mpow(p2-p1,2)+mpow(s2-s1,2)) matR1 = matrix([mat_1[0][:-1], mat_1[1][:-1], mat_1[2][:-1]]) matR2 = matrix([mat_2[0][:-1], mat_2[1][:-1], mat_2[2][:-1]]) matR = matR2 * matR1.transpose() ang_magnitude, xV, yV, zV = _rotmat_to_axisangle(matR) ang_magnitude = ang_magnitude * (180.0 / pi) shift = msqrt( mpow(mat2[0, 3] - mat1[0, 3], 2) + mpow(mat2[1, 3] - mat1[1, 3], 2) + mpow(mat2[2, 3] - mat1[2, 3], 2)) #print (mpow(mat2[0,3]-mat1[0,3],2)+mpow(mat2[1,3]-mat1[1,3],2)+mpow(mat2[2,3]-mat1[2,3],2)), ang_magnitude #acps_score = (pi/360)*(mpow(mat2[0,3]-mat1[0,3],2)+mpow(mat2[1,3]-mat1[1,3],2)+mpow(mat2[2,3]-mat1[2,3],2))*abs(ang_magnitude) return shift, ang_magnitude
def mesh(startx, starty, endx, endy, side=None, area=None): """ Compute a mesh grid :param startx: :param starty: :param endx: :param endy: :param side: :param area: :return: """ if not side: side = msqrt(area) startx = startx - side/2 starty = starty - side/2 endx = endx + side/2 endy = endy + side/2 origx = startx polygons = [] while starty < endy: startx = origx while startx < endx: poly = [ (startx, starty), (startx, starty + side), (startx + side, starty + side), (startx + side, starty)] polygons.append(Polygon(poly)) startx += side starty += side return polygons
def hyperopt_loss_function(results: DataFrame, trade_count: int, min_date: datetime, max_date: datetime, config: Dict, processed: Dict[str, DataFrame], backtest_stats: Dict[str, Any], *args, **kwargs) -> float: """ Objective function, returns smaller number for more optimal results. Uses Calmar Ratio calculation. """ total_profit = backtest_stats["profit_total"] days_period = (max_date - min_date).days # adding slippage of 0.1% per trade total_profit = total_profit - 0.0005 expected_returns_mean = total_profit.sum() / days_period * 100 # calculate max drawdown try: _, _, _, high_val, low_val = calculate_max_drawdown( results, value_col="profit_abs") max_drawdown = (high_val - low_val) / high_val except ValueError: max_drawdown = 0 if max_drawdown != 0: calmar_ratio = expected_returns_mean / max_drawdown * msqrt(365) else: # Define high (negative) calmar ratio to be clear that this is NOT optimal. calmar_ratio = -20.0 # print(expected_returns_mean, max_drawdown, calmar_ratio) return -calmar_ratio
def sqNear0(lf): assert(lf>=0) d=int(mlog(lf,10)) r0=10**((d)//2) fl=lf*10**(2*10)//r0**2 fl=msqrt(fl) r1=r0*int(fl*10**10)//10**20 return(r1)
def toSphere(self): """ Create a sphere which is surely encompassing the *full* shape """ from .ellipsoid import Sphere # Retrieve spheres A = self.A.toSphere() Ar = A.radius Ac = A.center B = self.B.toSphere() Br = B.radius Bc = B.center # Calculate the distance between the spheres dist = fnorm(Ac - Bc) # If one is fully enclosed in the other, we can simply neglect the other if dist + Ar <= Br: # A is fully enclosed in B (or they are the same) return A elif dist + Br <= Ar: # B is fully enclosed in A (or they are the same) return B elif dist <= (Ar + Br): # We can reduce the sphere drastically because only the overlapping region is important # i_r defines the intersection radius, search for Sphere-Sphere Intersection dx = (dist**2 - Br**2 + Ar**2) / (2 * dist) if dx > dist: # the intersection is placed after the radius of B # And in this case B is smaller (otherwise dx < 0) return B elif dx < 0: return A i_r = msqrt(4 * (dist * Ar)**2 - (dist**2 - Br**2 + Ar**2)**2) / (2 * dist) # Now we simply need to find the dx point along the vector Bc - Ac # Then we can easily calculate the point from A center = Bc - Ac center = Ac + center / fnorm(center) * dx A = i_r B = i_r else: # In this case there is actually no overlap. So perhaps we should # create an infinitisemal sphere such that no point will ever be found # Or we should return a new Shape which *always* return False for indices etc. center = (Ac + Bc) * 0.5 # Currently we simply use a very small sphere and put it in the middle between # the spheres # This should at least speed up comparisons A = 0.001 B = 0.001 return Sphere(max(A, B), center)
def is_close_phy(self, coor1, coor2, max_dist=15): self.etc.log("Calculating proximity(PHY)") try: dX = coor1[0] - coor2[0] dY = coor1[1] - coor2[1] dist = msqrt(mpow(dX, 2) + mpow(dY, 2)) return (dist < max_dist) except Exception as e: self.etc.log(e)
def bond(self, n1, n2, unit='bohr'): """compute bond length between atoms n1 and n2. Provide real atom numbers""" r1 = array(self.atoms[n1 - 1].pos()) r2 = array(self.atoms[n2 - 1].pos()) bond = msqrt(sum((r1 - r2)**2)) conv = 0.5291772086 if unit.lower().startswith('a'): bond *= conv return bond
def bond(self,n1,n2,unit='bohr'): """compute bond length between atoms n1 and n2. Provide real atom numbers""" r1 = array(self.atoms[n1-1].pos()) r2 = array(self.atoms[n2-1].pos()) bond = msqrt(sum((r1-r2)**2)) conv = 0.5291772086 if unit.lower().startswith('a'): bond*=conv return bond
def honeycomb(startx, starty, endx, endy, radius=None, area=None): """ Parameters ---------- startx starty endx endy radius area Returns ------- """ if not radius: radius = msqrt(area / (2*msqrt(3))) return (Polygon(poly) for poly in honeycomb_nb(startx, starty, endx, endy, radius))
def fusionLR(p): z = defaultdict(float) for (c, a) in p.items(): x1 = c[0] d1 = c[1] x2 = c[2] d2 = c[3] z[x1] += abs(a)**2 z[x2] += abs(a)**2 for (x, a) in z.items(): z[x] = msqrt(a) return z
def ldist(z, q0=None, lambda0=None): term1 = (1. + z) ** 2 term2 = 1. + 2. * (q0 + lambda0) * z term3 = z * (2. + z) * lambda0 denom = (term1 * term2 - term3) if denom>0: out = 1. / msqrt(denom) # since the function is used with scalar arguments # I use math.sqrt instead of numpy.sqrt for # performance reasons else: out = 0. return out
def sqrt_dd(x, y): if x == 0.0: return (0.0, 0.0) r = msqrt(x) u = r * 134217729.0 s2 = u - (u - r) f2 = r - s2 s = r * r f = ((s2 * s2 - s) + 2.0 * s2 * f2) + f2 * f2 e = (x - s - f + y) * 0.5 / r r0 = r + e e = e - (r0 - r) return r0, e
def weight_std(values, weights): """ Return weighted standard deviation Use math.sqrt rather than numpy.sqrt for speed :param values: :param weights: :return: """ try: average = np.average(values, weights=weights) except ZeroDivisionError: return None variance = np.average((values - average)**2, weights=weights) return msqrt(variance)
def build_vocab(self, sentences, threshold=0): """ Build vocabulary from a sequence of sentences (can be a once-only generator stream). Each sentence must be a list of utf8 strings. """ logger.info("collecting all words and their counts") sentence_no, vocab = -1, {} total_words = 0 for sentence_no, sentence in enumerate(sentences): if sentence_no % 10000 == 0: logger.info("PROGRESS: at sentence #%i, processed %i words and %i unique words" % (sentence_no, total_words, len(vocab))) for word in sentence: total_words += 1 try: vocab[word].count += 1 except KeyError: vocab[word] = Vocab(count=1) logger.info("collected %i unique words from a corpus of %i words and %i sentences" % (len(vocab), total_words, sentence_no + 1)) # assign a unique index to each word self.vocab, self.index2word = {}, [] for word, v in vocab.iteritems(): if v.count >= self.min_count: v.index = len(self.vocab) self.index2word.append(word) self.vocab[word] = v logger.info("total of %i unique words after removing those with count < %s" % (len(self.vocab), self.min_count)) # add probabilities for subsampling (if threshold > 0) if threshold > 0: total_words = float(sum(v.count for v in self.vocab.itervalues())) for word in self.vocab: # formula from paper #self.vocab[word].prob = max(0.,1.-msqrt(threshold*total_words/self.vocab[word].count)) # formula from code self.vocab[word].prob = (msqrt(self.vocab[word].count / (threshold * total_words)) + 1.) * (threshold * total_words) / self.vocab[word].count else: # if prob is 0, word wont get discarded for word in self.vocab: self.vocab[word].prob = 0. # add info about each word's Huffman encoding if TRAINING == 'hsoftm': self.create_binary_tree() # build the table for drawing random words (for negative sampling) else: self.make_table() self.reset_weights()
def dihedral(self, n1, n2, n3, n4, unit='radian'): """compute dihedral angle n1-n2-n3-n4. Provide real atom numbers. The dihedral evaluated by this code gave opposite signs as compared with MOLDEN for a test NMA molecule""" r1 = array(self.atoms[n1 - 1].pos()) r2 = array(self.atoms[n2 - 1].pos()) r3 = array(self.atoms[n3 - 1].pos()) r4 = array(self.atoms[n4 - 1].pos()) P1 = r2 - r1 P2 = r3 - r2 P3 = r4 - r3 N1 = cross(P1, P2) N2 = cross(P2, P3) N1 /= msqrt(sum(N1 * N1)) N2 /= msqrt(sum(N2 * N2)) #angle = macos(mabs(sum(N1*N2))) P2 /= msqrt(sum(P2 * P2)) M1 = cross(N1, P2) x = sum(N1 * N2) y = sum(M1 * N2) angle = arctan2(y, x) conv = 180. / mPi if unit == 'deg': angle *= conv return angle
def dihedral(self,n1,n2,n3,n4,unit='radian'): """compute dihedral angle n1-n2-n3-n4. Provide real atom numbers. The dihedral evaluated by this code gave opposite signs as compared with MOLDEN for a test NMA molecule""" r1 = array(self.atoms[n1-1].pos()) r2 = array(self.atoms[n2-1].pos()) r3 = array(self.atoms[n3-1].pos()) r4 = array(self.atoms[n4-1].pos()) P1 = r2-r1 P2 = r3-r2 P3 = r4-r3 N1 = cross(P1,P2) N2 = cross(P2,P3) N1/= msqrt(sum(N1*N1)) N2/= msqrt(sum(N2*N2)) #angle = macos(mabs(sum(N1*N2))) P2/= msqrt(sum(P2*P2)) M1 = cross(N1,P2) x = sum(N1*N2) y = sum(M1*N2) angle = arctan2(y,x) conv = 180./mPi if unit=='deg': angle*=conv return angle
def my_errornorm(u, u_hp, m_norm): """ Compute the m-norm th seminorm of u-u_hp. Combines the implementations of norm and errornorm from FEniCS. No sanity checks for types, etc. """ # compute the error by interpolating both u and u_hp onto higher order DG # space mesh = u_hp.function_space().mesh() order = u_hp.ufl_element().degree() + 3 if u.ufl_element().degree() < order: print "Increase order in the expresion!" exit() DG = FunctionSpace(mesh, 'DG', order) u = interpolate(u, DG) u_hp = interpolate(u_hp, DG) # Compute the difference e = Function(DG) e.assign(u) e.vector().axpy(-1.0, u_hp.vector()) if m_norm == 0: norm = assemble(inner(e, e)*dx,\ form_compiler_parameters={"representation" : "quadrature"}) elif m_norm == 1: norm = assemble(inner(grad(e), grad(e))*dx,\ form_compiler_parameters={"representation" : "quadrature"}) elif m_norm == 2: norm = assemble(inner(div(grad(e)), div(grad(e)))*dx,\ form_compiler_parameters={"representation" : "quadrature"}) else: raise ValueError("Only H_m norms, m=0, 1, 2 are suported.") if norm < 0: print "Warning. Round off problems?", norm norm = -1 # this is a flag indicator else: norm = msqrt(norm) return norm
def lookAtNearestFood(self, individu): ''' finds the nearest food and return the vector pointing at it Input: individu - int - id of the object to link it to the window Output: lookAtNearestFood - python list - coordinates x and y of the nearest food ''' coordPredator = self.f.canv.coords(individu) coordsFood = [self.f.canv.coords(el) for el in self.foodList] dist = [msqrt((el[0] - coordPredator[0])**2 + (el[1] - coordPredator[1])**2) for el in coordsFood] ion = dist.index(min(dist)) xCenterFood = coordsFood[ion][2] - (coordsFood[ion][2] - coordsFood[ion][0])/2 yCenterFood = coordsFood[ion][3] - (coordsFood[ion][3] - coordsFood[ion][1])/2 xCenterPred = coordPredator[2] - (coordPredator[2] - coordPredator[0])/2 yCenterPred = coordPredator[3] - (coordPredator[3] - coordPredator[1])/2 lookAtNearestFood = [xCenterFood - xCenterPred, yCenterFood - yCenterPred] return lookAtNearestFood
def sqrt(sqr): rt = msqrt(sqr) if int(rt) == rt: return int(rt) else: return 0
def sqNear1(lf): le=int(mlog(lf,10)//2)*2 if le <100: return(int(msqrt(lf))) a=lf//10**(le-100) return(int(msqrt(a))*10**((le-100)//2))
def normD(p): s = 0 for (_, a) in p.items(): s += abs(a)**2 return msqrt(s)
def sqrt(x): return int(msqrt(x))
u = TrialFunction(V) v = TestFunction(V) bc = DirichletBC(V, Constant(0), DomainBoundary()) A, _ = assemble_system(inner(grad(u), grad(v))*dx, Constant(0)*v*dx, bc) M, _ = assemble_system(u*v*dx, Constant(0)*v*dx, bc) e, l = octave.eig(A.array(), M.array()) e = matrix(e) l = matrix(l) u = interpolate(Expression("sin(k*pi*x[0])", k=1), V) U = matrix(u.vector().array()) # norm from assemble aL2 = sqrt(assemble(u**2*dx)) aH10 = sqrt(assemble(inner(grad(u), grad(u))*dx)) M = matrix(M.array()) # cast M so that numpy can work with it eL2, eH10 = 0, 0 for k in range(V.dim()): F = matrix(e[:, k]) # select k-th eigenvector lmbda = l[k, k] # select k-th eigenvalue eL2 += npdot(npdot(U, M), F)**2 eH10 += lmbda*(npdot(npdot(U, M), F))**2 eL2 = msqrt(eL2); eH10 = msqrt(eH10) diffL2 = abs(eL2 - aL2); diffH10 = abs(eH10 - aH10) print "L2 assemble %g, eigenvalues %g, diff %g" % (aL2, eL2, diffL2) print "H10 assemble %g, eigenvalues %g, diff %g" % (aH10, eH10, diffH10)
def pair_distance(i1, i2): return msqrt((i1[0] - i2[0])**2 + (i1[1] - i2[1])**2)
def do_calculations(self, cluster, rel_size_unc=0.0): self.asec_per_kpc = cosmo.arcsec_per_kpc_proper(cluster.z) self.a = (self.a_asec / self.asec_per_kpc).to(u.kpc) self.b = (self.b_asec / self.asec_per_kpc).to(u.kpc) self.ellip = self.a / self.b self.Vmax = ((4 * pi / 3) * (self.a * self.a * self.b)).to(u.cm**3) self.Vmin = ((4 * pi / 3) * (self.a * self.b * self.b)).to(u.cm**3) self.volume = np.sqrt(self.Vmax * self.Vmin) # geometric mean -- (ab)^(3/2) self.area = (pi * self.a * self.b).to(u.cm**2) # Volume uncertainties, take the max of: # 1) Geometric effects, or # 2) Propagated from axis ratios assuming a certain value self.volume_p_frac = max( msqrt(self.ellip) - 1, 3 * rel_size_unc / msqrt(2)) self.volume_m_frac = max(1 - 1 / msqrt(self.ellip), 3 * rel_size_unc / msqrt(2)) self.volume_p = self.volume * self.volume_p_frac self.volume_m = self.volume * self.volume_m_frac R = cluster.centroid.separation(self.coords) self.R = (R / self.asec_per_kpc).to(u.kpc) p = cluster.interpolate("pressure", self.R, xkey="R_kpc", return_error=True) p = np.array(p) * u.erg / u.cm**3 p, p_p, p_m = p self.cavity_pressure = p self.cavity_pressure_p = p_p self.cavity_pressure_m = p_m ne = cluster.interpolate("density", self.R, xkey="R_kpc") / u.cm**3 kT = cluster.interpolate("kT", self.R, xkey="R_kpc", return_error=True) kT = np.array(kT) * u.keV kT, kT_p, kT_m = kT T = kT.to(u.K, equivalencies=u.temperature_energy()) self.pV = p * self.volume self.pV_p = self.pV * msqrt((p_p / p)**2 + (self.volume_p_frac)**2) self.pV_m = self.pV * msqrt((p_m / p)**2 + (self.volume_m_frac)**2) self.enthalpy = 4 * self.pV self.enthalpy_p = 4 * self.pV_p self.enthalpy_m = 4 * self.pV_m self.sound_speed = np.sqrt(5 * k_B * T / (3 * 0.62 * u.M_p)).to(u.km / u.s) self.sound_crossing_time = (self.R / self.sound_speed).to(1e8 * u.yr) self.sound_crossing_time_p = self.sound_crossing_time * 0.5 * (kT_p / kT) self.sound_crossing_time_m = self.sound_crossing_time * 0.5 * (kT_m / kT) try: g = cluster.potential.g(self.R) g_interp = cluster.interpolate("g", self.R, xkey="R_kpc", return_error=True) _, g_p, g_m = np.array(g_interp) * g.unit self.buoyancy_time = (self.R * np.sqrt(0.75 * self.area / (2 * g * self.volume))).to( 1e8 * u.yr) self.buoyancy_time_p = self.buoyancy_time * msqrt( (0.5 * g_p / g)**2 + 1 / 8 * rel_size_unc**2) self.buoyancy_time_m = self.buoyancy_time * msqrt( (0.5 * g_m / g)**2 + 1 / 8 * rel_size_unc**2) age_type = "buoyancy_time" except AttributeError: age_type = "sound_crossing_time" self.age = getattr(self, age_type) self.age_p = getattr(self, f"{age_type}_p") self.age_m = getattr(self, f"{age_type}_m") self.Pcav = (self.enthalpy / self.age).to(u.erg / u.s) self.Pcav_p = self.Pcav * msqrt((self.pV_p / self.pV)**2 + (self.age_p / self.age)**2) self.Pcav_m = self.Pcav * msqrt((self.pV_m / self.pV)**2 + (self.age_m / self.age)**2) self.Mdisp = (1.0 + 1 / 1.2) * (ne * self.volume * 0.62 * u.M_p).to( u.Msun) self.Mdisp_p = self.Mdisp * self.volume_p_frac self.Mdisp_m = self.Mdisp * self.volume_m_frac self.Macc = (self.enthalpy / (0.1 * c * c)).to(u.Msun) self.Macc_p = self.Macc * self.enthalpy_p / self.enthalpy self.Macc_m = self.Macc * self.enthalpy_m / self.enthalpy self.Mdot_acc = (self.Pcav / (0.1 * c * c)).to(u.Msun / u.yr) self.Mdot_acc_p = self.Mdot_acc * self.Pcav_p / self.Pcav self.Mdot_acc_m = self.Mdot_acc * self.Pcav_m / self.Pcav
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: Pieter Huycke email: [email protected] GitHub: phuycke """ #%% from cmath import sqrt as csqrt from math import sqrt as msqrt abc = str(input('Values for a,b and c (space separated)?\n')) a, b, c = map(int, abc.split(' ')) if (b**2 - 4 * a * c) < 0: complex_root = csqrt((b**2 - 4 * a * c) + 0j) quad1, quad2 = -b + complex_root / 2 * a, -b - complex_root / 2 * a print('The roots are imaginary:\n{0}\n{1}'.format(quad1, quad2)) else: if msqrt(b**2 - 4 * a * c) == 0: print('There is only one solution:\n{}'.format(-b)) else: quad1, quad2 = -b + msqrt(b**2 - 4 * a * c) / 2 * a, -b - msqrt( b**2 - 4 * a * c) / 2 * a print('There are two solutions:\n{0}\n{1}'.format(quad1, quad2))
from math import sqrt as msqrt from random import random def sqrt(x, eps): l = 0. r = max(1, float(x)) while r - l > eps: m = (l + r) / 2 if m ** 2 < x: l = m else: r = m return (l + r) / 2 eps = 1e-8 while True: x = random() * 100 y1 = msqrt(x) y2 = sqrt(x, eps) if abs(y1 - y2) > eps: print(f'fail: {x:.9f}') exit(0) else: print('OK')
from mods.extmod import sqrt, summ from math import sqrt as msqrt print("custmod:", __name__) print(sqrt(10)) print(msqrt(16)) print(summ(5))