def sameCoords(self,point,absolute=True,tol=1e-12): if absolute: return (point.get_x()==self._x and point.get_y()==self._y) else: xequiv=math.abs((self.get_x()/point.get_x())-1.)<tol yequiv=math.abs((self.get_y()/point.get_y())-1.)<tol return xequiv and yequiv
def findR(self, Vtarget, theta, phi): """ This function finds the radius at which the zero velocity potential equals targetV in the direction (theta, phi). The radius is given as a fraction of a. NOTE: This function only works if the target potential is less than the potential at the Roche lobe. """ if( Vtarget > systemparams.VL1 ): print("Attempted to find a point outside the Roche lobe in findR).") epsilonr = 1.0e-7 * systemparams.a r = 0.8 * systemparams.rL1 for i in range(100): if i ==100: print("Too many iterations in findR.") Vplus = self.V( r + epsilonr, theta, phi) Vminus = self.V( r - epsilonr, theta, phi) Vzero = self.V( r, theta, phi) slope = (Vplus - Vminus) / (2.0 * epsilonr) if slope == 0.0: slope = 100.0 * Vzero / systemparams.a deltar = (Vtarget - Vzero) / slope if( math.abs(deltar) > (0.05 * r) ): deltar = (0.05 * r) * (deltar / math.abs(deltar)) r = r + deltar if( r >= systemparams.rL1 ): r = systemparams.rL1 x = math.abs( (Vtarget - self.V(r, theta, phi)) / Vtarget ) if( x <= 1.0e-6 ): break return r
def heuristicMD(self, node): """ Heuristic function being used. Calculates the manhattan distance between node and end. @param node. The current node being searched @returns Integer. The manhattan distance. """ return abs(node.x - self.endNode.x) + abs(node.y - self.endNode.y)
def getCoord(self,position): x,y = position dx,dy = self.position dist = sqrt( abs(x - dx)**2 + abs(y - dy)**2 ) if dist%int(dist) > 0: dist = int(dist) + 1 self.currentStep = dist
def r8_aint ( x ): #****************************************************************************80 # ## R8_AINT truncates an R8 argument to an integer. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 24 July 2014 # # Author: # # John Burkardt. # # Parameters: # # Input, real X, the argument. # # Output, real VALUE, the truncated version of X. # from math import abs from math import floor if ( x < 0.0 ): value = - floor ( abs ( x ) ) else: value = floor ( abs ( x ) ) return value
def geo2tm( dsttype, in_pt, out_pt ) : transform(GEO, dsttype, in_pt) delta_lon = in_pt.getX() - m_arLonCenter[dsttype] sin_phi = math.sin(in_pt.getY()) cos_phi = math.cos(in_pt.getY()) if (m_Ind[dsttype] != 0) : b = cos_phi * math.sin(delta_lon) if ((math.abs(math.abs(b) - 1.0)) < EPSLN) : pass #Log.d("infinite error") #System.out.println("infinite error") else : b = 0 x = 0.5 * m_arMajor[dsttype] * m_arScaleFactor[dsttype] * math.log((1.0 + b) / (1.0 - b)) con = math.acos(cos_phi * math.cos(delta_lon) / math.sqrt(1.0 - b * b)) if (in_pt.getY() < 0) : con = con * -1 y = m_arMajor[dsttype] * m_arScaleFactor[dsttype] * (con - m_arLatCenter[dsttype]) al = cos_phi * delta_lon als = al * al c = m_Esp[dsttype] * cos_phi * cos_phi tq = math.tan(in_pt.getY()) t = tq * tq con = 1.0 - m_Es[dsttype] * sin_phi * sin_phi n = m_arMajor[dsttype] / math.sqrt(con) ml = m_arMajor[dsttype] * mlfn(e0fn(m_Es[dsttype]), e1fn(m_Es[dsttype]), e2fn(m_Es[dsttype]), e3fn(m_Es[dsttype]), in_pt.getY()) out_pt.setX( m_arScaleFactor[dsttype] * n * al * (1.0 + als / 6.0 * (1.0 - t + c + als / 20.0 * (5.0 - 18.0 * t + t * t + 72.0 * c - 58.0 * m_Esp[dsttype]))) + m_arFalseEasting[dsttype] ) out_pt.setY( m_arScaleFactor[dsttype] * (ml - dst_m[dsttype] + n * tq * (als * (0.5 + als / 24.0 * (5.0 - t + 9.0 * c + 4.0 * c * c + als / 30.0 * (61.0 - 58.0 * t + t * t + 600.0 * c - 330.0 * m_Esp[dsttype]))))) + m_arFalseNorthing[dsttype] )
def estimate(self, xOther, yOther): goalx = xOther - self.x goaly = xOther - self.y # Manhattan distance d = math.abs(goalx) + math.abs(goaly) return (d)
def getDistance(self, l1, l2): dx = math.abs(l1.x - l2.x) dy = math.abs(l1.y - l2.y) if dx > self.map_width / 2: dx = self.map_width - dx if dy > self.map_height / 2: dy = self.map_height - dy return math.sqrt((dx*dx) + (dy*dy))
def SpreadValueAcrossAllComponents(self, val): temp = val/3 for i in range(len(self.components)): if (self.components[i] < 0): self.components[i] -= abs(temp) else: self.components[i] += abs(temp)
def getDistance(self, l1, l2): dx = math.abs(l1.x - l2.x) dy = math.abs(l1.y - l2.y) if dx > self.width / 2: dx = self.width - dx if dy > self.height / 2: dy = self.height - dy return dx + dy
def parse_hole_coordinates(hole_vertices): hole_vertices.gsub!(/[\[\],]/, ' ') hole_vertices = hole_vertices.split(" ").to_a hole_vertices.map! { |e| e.to_i } x = math.abs(hole_vertices[0] - hole_vertices[2]) y = math.abs(hole_vertices[1] - hole_vertices[3]) return x, y
def horizontal_update_ball(self, ball_pos): """ Update horizontal ball position """ global speed_factor updated_ball_pos = ball_pos if (updated_ball_pos[0] <= self.PAD_WIDTH + self.BALL_RADIUS): # The ball is at the left edge. # For bouncing: Change direction of movement, before update self.global_ball_vel[0]= - self.global_ball_vel[0] # Calculation without making use of geometric distance formula: # Does the ball hit the paddle? # # If at the moment where the ball touches the gutter, # and if the vertical distance is as big as or bigger as the # "sum of ball radius and half of the paddle", # the ball would not touch the paddle when passing by... # if (math.abs(updated_ball_pos[1]-self.paddle1_pos) >= (self.HALF_PAD_HEIGHT+self.BALL_RADIUS)): self.score2 += 1 self.ball_init(True) else: # Requirement 11 "To moderately increase the difficulty of your game, # increase the velocity of the ball by 10% each time # it strikes a paddle" self.speed_factor *= 1.1 else: if (updated_ball_pos[0] >= self.WIDTH - self.PAD_WIDTH - self.BALL_RADIUS): # The ball is at the right edge. # For bouncing: Change direction of movement, before update self.global_ball_vel[0]= - self.global_ball_vel[0] # Calculation without making use of geometric distance formula: # Does the ball hit the paddle? # # If at the moment where the ball touches the gutter, # and if the vertical distance is as big as or bigger as the # "sum of ball radius and half of the paddle", # the ball would not touch the paddle when passing by... # if (math.abs(updated_ball_pos[1]-self.paddle2_pos) >= (self.HALF_PAD_HEIGHT+self.BALL_RADIUS)): self.score1 += 1 self.ball_init(False) else: # Requirement 11 "To moderately increase the difficulty of your game, # increase the velocity of the ball by 10% each time # it strikes a paddle" self.speed_factor *= 1.1 else: # Ball is not too much right or left # Just update horizontal position pass # update anyhow # by this the ball gets out of the limits, # so that out-of-limits is not detected with next cycle # and we must not check the direction of the ball velocity updated_ball_pos[0] +=self.global_ball_vel[0] return updated_ball_pos
def Execute(COMMON, XOUT, PAR, WRK, DOF): x1 = DOF[1]+PAR[1] y1 = DOF[2]+PAR[2] x2 = DOF[4]+PAR[3] y2 = DOF[5]+PAR[4] x3 = DOF[7]+PAR[5] y3 = DOF[8]+PAR[6] x4 = DOF[10]+PAR[7] y4 = DOF[11]+PAR[8] d = (x2-x1)*(y4-y3)-(x4-x3)*(y2-y1) d1= (x3-x1)*(y4-y3)-(x4-x3)*(y3-y1) d2 = (x2-x1)*(y3-y1)-(x3-x1)*(y2-y1) if (math.abs(d)<1e-8): XOUT[1] =0.0 XOUT[2] =0.0 XOUT[3] =0.0 res = return_result(COMMON, XOUT, WRK) return res t1 = d1/d t2 = d2/d #check! f1 = (x2-x1)*t1+(x4-x3)*t2- (x3-x1) f2 = (y2-y1)*t1+(y4-y3)*t2- (y3-y1) if (math.abs(f1)>1e-8 | math.abs(f2)>1e-5): print 'Wrong linear system calculation' if (t1>0.0): r1 = t1-1.0 else: r1 = - t1 if (t2>0.0): r2 = t2-1.0 else: r2 = - t2 r = r1 + r2 if (r1<WRK[1]): WRK[1] = r1 if (r2<WRK[2]): WRK[2] = r2 XOUT[1] =r XOUT[2] =r1 XOUT[3] =r2 res = return_result(COMMON, XOUT, WRK) return res
def pmv_hoppe_iso( t, rh, wind, mtrad, iclo): eta = 0.01; # Mechanical efficiency age = 35.0; # Age mbody = 75.0; # Weigth in kg ht = 1.75; # Heigth in m tcl = 30.005 MAX_LOOP = 200 MAX_LOOP_HALF = MAX_LOOP / 2 tcl_eps = 0.05 eps = 0.97 sigm = 5.67e-8 adu = 0.203 * math.pow(mbody, 0.425) * math.pow(ht, 0.725) metbf = 3.19 * math.pow(mbody, (3.0/4.0)) * (1.0 + 0.004* (30.0- age)+0.018 * ((ht * 100.0/ math.pow(mbody, (1.0/3.0))) - 42.1)) metbm = 3.45 * math.pow(mbody, (3.0/4.0)) * (1.0 + 0.004* (30.0- age)+0.010 * ((ht * 100.0/ math.pow(mbody, (1.0/3.0))) - 43.4)) vpa = (rh / 100) * 6.105 * math.pow(2.718281828, ( 17.27*t / ( 237.7 + t ) )) fcl = 1.0 + iclo * 0.15 metb = metabolism(t) metf = metbf + metb metm = metbm + metb metb = (metf+metm)/2.0 h = metb * (1.0 - eta) aef = 0.71 * fcl * adu p1 = 35.7 - 0.032 * (metb / (adu * 1.16))* (1 - eta) tcl1 = tcl for x in range(0, MAX_LOOP_HALF): if x < MAX_LOOP_HALF: hc = 12.06 * math.sqrtf(wind) abhc = 0.0 else: hc = 2.38 * math.pow(fabsf(tcl1 - t), 4.0) abhc = 0.6 * fabsf(math.pow((tcl1 - t), -0.75)) tcl2 = p1 - 0.155 * iclo * (3.94 * 0.00000001* fcl *(math.pow((tcl1 + 273.2),4.0)- math.pow((mtrad+ 273.2), 4.0))+fcl * hc* (tcl1 - t)) diff = math.abs(tcl1 - tcl2) if diff < tcl_eps: break abtcl = -0.155 * iclo * (4.0 * 3.94* 0.00000001* fcl *math.pow((tcl1+ 273.2),3.0) + fcl * hc- fcl *(tcl1 - t)* abhc)- 1.0 tcl1 = tcl1 - (tcl2 - tcl1) / abtcl difhc = (12.06 * math.sqrt(wind)) - (2.38 * (math.pow(math.abs(t - tcl1), 0.25))) if difhc > 0.0 and i == MAX_LOOP_HALF: break tsk = 35.7 - (0.028 * h / adu) esw = 0.42 * adu * (h / adu - 58.08) if esw < 0.0: esw= 0.0 rsum = aef * eps * sigm * (math.pow((tcl1 + 273.2), 4.0) - math.pow((mtrad + 273.2),4.0)) csum = adu * fcl * hc * (tcl1 - t) erel = 0.0023 * metb * (44.0 - 0.75 * vpa) eres = 0.0014 * metb * (34.0 - t) ed = 0.406 * adu * (1.92 * tsk - 25.3- 0.75 * vpa) load = (h - ed - erel - eres - esw - rsum - csum) / adu ts = (0.303 * math.expf(-0.036 * (metb / adu)) + 0.028) pmv= ts * load return pmv
def update_center_and_radius(self): n = len(self.members.keys()) if ( n == 0 ): return R = 6371 c_x = 0 c_y = 0 c_z = 0 center = {} for user_id in self.members: location = self.members[user_id]["location"] latitude = math.radians(location["lat"]) longitude = math.radians(location["long"]) x = math.cos(latitude) * math.cos(longitude) * R y = math.cos(latitude) * math.sin(longitude) * R z = math.sin(latitude) * R c_x += x c_y += y c_z += z c_x /= n c_y /= n c_z /= n if ( ( math.fabs(c_x) < math.pow(10, -9) ) and ( math.abs(c_y) < math.pow(10, -9) ) and ( math.abs(c_z) < math.pow(10, -9) ) ): center["lat"] = 40.866667 center["long"] = 34.566667 else: hyp = math.sqrt(math.pow(c_x, 2) + math.pow(c_y, 2)) center["lat"] = math.degrees(math.atan2(c_z, hyp)) center["long"] = math.degrees(math.atan2(c_y, c_x)) self.center = center radius = ChatRoom.MIN_RADIUS for user_id in self.members: location = self.members[user_id]["location"] distance = ChatRoom.distance(center, location) if ( distance > radius ): radius = distance + (ChatRoom.MIN_RADIUS / 3) self.radius = radius ChatRoom.assign_tags(self, None)
def SpreadValueAcrossComponents(self, indices, val): temp = val/(len(indices)) if (len(indices) > len(self.components)): print("Too many indices provided for vector") return for i in range(len(indices)): if (self.components[indices[i]] < 0): self.components[indices[i]] -= abs(temp) else: self.components[indices[i]] += abs(temp)
def advTestingMove(): _, t = self.tracker.cap.read() width = t.shape[0:2] while(True): tags = self.tracker.getTag() next = min(tags, key = lambda x:(math.abs(x)-width/2.0) while(math.abs(next)<=self.tracker.r): self.mover.bot.go(10, 0) past = next tags = self.tracker.getTag() next = min(tags, key = lambda x:(math.abs(x)-width/2.0) if(math.abs(past) <=self.tracker.r and math.abs(next) >=width/6.0): ##check if the next value is way off. ##This is a sign that we are almost at our target tag, and just lost sight of it self.mover.bot.go(10, 0) time.sleep(5) ##Turn until facing a tag else: while(math.abs(next) >=self.tracker.r): self.mover.bot.go(0, 5*math.abs(next)/next) past = next tags = self.tracker.getTag() next = min(tags, key = lambda x:(math.abs(x)-width/2.0)
def laplace_crossover(random, mom, dad, args): a = args.setdefault('laplace_a', 1) b = args.setdefault('laplace_b', 0) bro = copy.copy(dad) sis = copy.copy(mom) for i, (m, d) in enumerate(zip(mom, dad)): u = random.random() if random.random() <= 0.5: beta = a - b * math.log(u) else: beta = a + b * math.log(u) bro[i] = m + beta * math.abs(m - d) sis[i] = d + beta * math.abs(m - d) return [bro, sis]
def getMag(halfSpectrum): from math import sqrt, abs rPart = halfSpectrum[0] iPart = halfSpectrum[1] length = len(rPart) data = [0] * (length + 1) for i in xrange(1, length): data[i] = sqrt(rPart[i] * rPart[i] + iPart[i] * iPart[i]) data[0] = abs(rPart[0]) * 2 data[length] = abs(iPart[0]) * 2
def getTurnOffset(offsets, velX, velY, sprint): turn = offsets.turnInPlace if velX > 0: if sprint: turn = turn + math.abs(velX) * (offsets.turnSprint - offsets.turnInPlace) else: turn = turn + math.abs(velX) * (offsets.turnFwd - offsets.turnInPlace) else: turn = turn + math.abs(velX) * (offsets.turnBack - offsets.turnInPlace) if velY > 0: turn = turn + math.abs(velY) * (offsets.turnLeft - offsets.turnInPlace) else: turn = turn + math.abs(velY) * (offsets.turnRight - offsets.turnInPlace) return turn
def steerRobotOnBridge(self, centerOfGap, robotCenter): '''Physically stears the robot by writing the correct velocity and turning commands to it. Stearing is done through portional control with the difference between the center of the largest gap in the image and the center of the image. INPUT: Integer representing center of the largest gap found by the robot OUTPUT: Integer representing center of the image, used to determine how far off center the robot is EFFECT: The robot turns and moves forward. Turning is porportional to how far awway from the center of the image the largest gap is. ''' K = .06 #PID constant portion = math.abs(centerOfGap - robotCenter) turnAmount = K * portion speed=Vector3(float(xspeed),0.0,0.0) #uses if statements because without having the current heading, simple subtraction isn't that robust' if centerOfGap < robotCenter: #Gap is to the left of the robot's center #turn left angular=Vector3(0.0,0.0,math.fabs(float(turnAmount))) elif centerOfGap > robotCenter: angular=Vector3(0.0,0.0,math.fabs(float(-1*turnAmount))) else: angular=Vector3(0.0,0.0,0.0) pub.publish(speed, angular) #print 'lft turn ', lft_trn_amt #Construct publish data: return Twist(speed,angular)
def mountains2(L): peaks=0 for i in range(len(L)-1): dif = math.abs(L[i]-L[i]+1) if dif>=30: peaks=peaks+1 return peaks >= 3
def histogram_data(data, nbins=10, histrange=(0,10), edges=None, weights=None): """ Histogram a 1-d Array, integral normalized Histogram is integral normalized. A stdev is outputted as sqrt(N)/norm where N is the total counts of each bin and norm is the normalization factor the whole histogram is divided by. Must specify range and number of bins Or a list of edges to histogram inside Weights is optional and is assumed equal weighting if None """ if weights is None: weights = np.ones(np.shape(data)[0]) if edges is None: hist, edges, slices = stats.binned_statistic(data, weights, statistic="sum", histrange=[histrange], bins=nbins) else: hist, edges, slices = stats.binned_statistic(data, weights, statistic="sum", edges=edges) normalization = math.abs(integrate_simple(hist, edges)) stdev = np.sqrt(hist) / normalization hist = hist / normalization bincenters = 0.5*(edges[1:] + edges[:-1]) return hist, stdev, bincenters, edges, slices
def detwin_miller_array(miller_obs, twin_law, twin_fraction): # for the moment, ignore incompleten twin pairs please cb_op = sgtbx.change_of_basis_op( twin_law ) twin_related_miller = miller_obs.change_basis( cb_op ).set_observation_type( miller_obs ) set1, set2 = miller_obs.common_sets( twin_related_miller )\ .set_observation_type(miller_obs ) assert miller_obs.observation_type() is not None assert miller_obs.sigmas() is not None if set1.is_xray_amplitude_array(): set1 = set1.f_as_f_sq() set2 = set1.f_as_f_sq() detwinned_f = flex.double() detwinned_sigma = flex.double() if set1.is_xray_intensity_array(): if set2.is_xray_intensity_array(): for i1,s1,i2,s2 in zip( set1.data(), set1.sigmas(), set2.data(), set2.sigmas() ): tmp_detwinner = detwin(i1,s1,i2,s2) # we do some double work here actually ni1 = tmp_detwinner.xm ns1 = math.sqrt( math.abs(self.vcv[0]) ) detwinned_f.append( ni1 ) detwinned_s.append( ns1 ) set1 = set1.f_sq_as_f() new_f = set1.customized_copy
def rune_kutta_fehlberg(f, a, b, alpha, TOL = 1e-08, hmax, hmin): t = a w = alpha h = hmax yield t, w, h FLAG = True while FLAG: K1 = h * f(t, w) K2 = h * f(t + 0.25 * h, w + 0.25 * K1) K3 = h * f(t + 0.375 * h, w + 0.09375 * K1 + 0.28125 * K2) K4 = h * f(t + 12 * h / 13, w[i-1] + 1932 * K1/2197 - 7200 * K2 / 2197 + 7296 * K3 / 2197) K5 = h * f(t + h, w + 439 * K1 / 216 - 8 * K2 + 3680 * K3 / 513 - 845 * K4 / 4104) K6 = h * f(t + 0.5 * h, w - 8 * K1 / 27 + 2 * K2 - 3544 * K3 / 2565 +1859 * K4 / 4104 - 11 * K5 / 40) R = math.abs(K1 / 360 - 128 * K3 / 4275 - 2197 * K4 / 75240 + K5 / 50 + 2 * K6 / 55) / h if R <= TOL: t = t + h w = w + 25 * K1 / 216 + 1408 * K3 / 2565 + 2197 * K4 / 4104 - K5 / 5 yield t ,w , h delta = 0.84 * math.pow(TOL / R, 0.25) if delta <= 0.1: h = 0.1 * h elif delta >= 4: h = 4 * h else: h = delta * h if h > hmax: h = hmax if t >= b: FLAG = False elif t + h > b: h = b - t elif h < hmin: FLAG = False raise ValueError('minimum h exceeded')
def isCompatableWith(self, other, tol=1e-6): S = self.S * other.S E1 = self.__restrictedTo(S) E2 = other.__restrictedTo(S) for _p_ in E1.keys(): if M.abs(E1[_p_] - E2[_p_]) > tol: return False return True
def findDrawingPointsAdded(self, curveIndex, t0, t1, pointList, insertionIndex): left = self.calculateBezerPoint(curveIndex, t0) right = self.calculateBezerPoint(curveIndex, t1) if (left - right).sqrMagnitude() < self.minimum_sqr_distance: return 0 tMid = (t0 - t1) / 2 mid = self.calculateBezerPoint(curveIndex, tMid) leftDirection = (left - mid).normalize() rightDirection = (right - mid).normalize() if (leftDirection.dot(rightDirection) > self.divison_threshold or math.abs(tMid - 0.5) < 0.0001): pointsAddedCount = 0 pointsAddedCount += self.findDrawingPointsAdded(curveIndex, t0, tMid, pointList, insertionIndex) pointList.append(insertionIndex + pointsAddedCount, mid) pointsAddedCount += 1 pointsAddedCount += self.findDrawingPointsAdded(curveIndex, tMid, t1, pointList, insertionIndex + pointsAddedCount) return pointsAddedCount return 0
def RtoEuler(R): #given a 3x3 rotaiton matrix #gives you the angles that make up the rotation matrix #in a 1x3 matrix if math.abs(R[2,0])!=1: theta1=-1*math.asin(R[2,0]) theta2=math.pi-theta1 cos1=math.cos(theta1) cos2=math.cos(theta2) zai1=math.atan2(R[2,1]/cos1,R[2,2]/cos1) zai2=math.atan2(R[2,1]/cos2,R[2,2]/cos2) phi1=math.atan2(R[1,0]/cos1,R[0,0]/cos1) phi2=math.atan2(R[1,0]/cos2,R[0,0]/cos2) euler=np.array([[theta1,zai1,phi1], [theta2,zai2,phi2]]) else: phi=0 if R[2,0]==-1: theta=math.pi/2 zai= math.atan2(R[0,1],R[0,2]) else: theta=-1*math.pi/2 zai= math.atan2(-1*R[0,1],-1*R[0,2]) euler=np.array([theta,zai,phi]) return euler
def Broyden(F, x, N, TOL = 1e-05): J = Jacobi(F) j = np.matrix([[],[]]) j.reshape((len(F),len(F))) for i in range(0, len(F)): for j in range(0, len(F)): j[i][j] = J[i][j](x) A0 = j v = np.array([]) v.reshape((len(F))) for i in range(0, len(F)): v[i] = F[i](x) A = np.linalg.inv(A0) s = -A * v X = x X = X + s k = 2 while k <= N: w = v for i in range(0, len(F)): v[i] = F[i](X) y = v - w z = -A * y p = -s.T * z u = s.T * A A = A + (s + z) * u / p s = -A * v X = X + s if max([math.abs(i) for i in s]) < TOL: return x k = k + 1 raise ValueError('Maximum number of iterations exceeded')
def calculateDistanceProbability(self, distanceAmplitudePairs): # the pressure of sound is reduced linearly by the distance # http://en.wikipedia.org/wiki/Sound_pressure#Distance_law # distance law: p ~ 1/r # op (original pressure) / d (distance) = sp (pressure at sensor) # => op1 / d1 = sp1 & op2 / d2 = sp2 [divide both equations] # => op1 / d1 * d2 / op2 = sp1 / sp2 [op1 = op2, as it's same audio signal] # => d2 / d1 = sp1 / sp2 # => 0 = sp1 / sp2 - d2 / d1 # if the the position is not correct, we need an error term # => e = sp1 / sp2 - d2 / d1 # => we want to normalize the error term between 0..1, where 1 represents no error # => exp(-|e|) = exp(-| sp1/sp2 - d2/d1 |) sumOfProbs = 0. numOfProbs = 0 for sensorA, seonsorB in itertools.combinations(distanceAmplitudePairs, repeat=2): d1, sp1 = sensorA d2, sp2 = seonsorB prob = math.exp(-math.abs( sp1/sp2 - d2/d1 )) numOfProbs = numOfProbs + 1 sumOfProbs = sumOfProbs + prob return sumOfProbs / numOfProbs
def compute_h0_eigenvalues_sneg(u, g): Lambda = get_lambda('param') z = get_z() scale = (1 + Lambda**-1) / 2.0 * Lambda**(1.0 - z) u, g = scale_u_gamma(u, g) g = mt.abs(g) eigs = np.empty(22) eigs[0] = u eigs[1] = 0.5 * (u - (u**2 + 8 * g)**0.5) eigs[2] = 0.5 * (3 * u - (u**2 + 8 * g)**0.5) eigs[3] = 0.5 * (u + (u**2 + 8 * g)**0.5) eigs[4] = 0.5 * (3 * u + (u**2 + 8 * g)**0.5) eig5 = -1/6*(u**2 + 8*g)*(-1j*ct.sqrt(3) + 1)/(u**3 - (u**2 - 4*g)*u - 6*g*u \ + 1/3*ct.sqrt(-1/3*u**6 - 8*g*u**4 - 28*g**2*u**2 - 512/3*g**3))**(1/3) \ - 1/2*(u**3 - (u**2 - 4*g)*u - 6*g*u + 1/3*ct.sqrt(-1/3*u**6 - 8*g*u**4 \ - 28*g**2*u**2 - 512/3*g**3))**(1/3)*(1j*mt.sqrt(3) + 1) + u eigs[5] = eig5.real eig6 = -1/6*(u**2 + 8*g)*(1j*ct.sqrt(3) + 1)/(u**3 - (u**2 - 4*g)*u - 6*g*u + \ 1/3*ct.sqrt(-1/3*u**6 - 8*g*u**4 - 28*g**2*u**2 - 512/3*g**3))**(1/3) - \ 1/2*(u**3 - (u**2 - 4*g)*u - 6*g*u + 1/3*ct.sqrt(-1/3*u**6 - 8*g*u**4 - \ 28*g**2*u**2 - 512/3*g**3))**(1/3)*(-1j*ct.sqrt(3) + 1) + u eigs[6] = eig6.real eig7 = u + 1/3*(u**2 + 8*g)/(u**3 - (u**2 - 4*g)*u - 6*g*u + 1/3*ct.sqrt(-1/3*u**6 - \ 8*g*u**4 - 28*g**2*u**2 - 512/3*g**3))**(1/3) + (u**3 - (u**2 - 4*g)*u - 6*g*u \ + 1/3*ct.sqrt(-1/3*u**6 - 8*g*u**4 - 28*g**2*u**2 - 512/3*g**3))**(1/3) eigs[7] = eig7.real eigs[8] = 0 eigs[9] = 2 * u eigs[10] = 0.5 * (3 * u - (u**2 + 8 * g)**0.5) eigs[11] = 0.5 * (3 * u + (u**2 + 8 * g)**0.5) eig12 = -1/6*(u**2 + 8*g)*(-1j*mt.sqrt(3) + 1)/(u**3 - (u**2 - 4*g)*u - \ 2*g*u + 1/3*ct.sqrt(-1/3*u**6 - 8*g*u**4 - 28*g**2*u**2 - \ 512/3*g**3))**(1/3) - 1/2*(u**3 - (u**2 - 4*g)*u - 2*g*u + \ 1/3*ct.sqrt(-1/3*u**6 - 8*g*u**4 - 28*g**2*u**2 - 512/3*g**3))**(1/3)*(1j*ct.sqrt(3) + 1) + u eigs[12] = eig12.real eig13 = -1/6*(u**2 + 8*g)*(1j*mt.sqrt(3) + 1)/(u**3 - (u**2 - 4*g)*u - 2*g*u + \ 1/3*ct.sqrt(-1/3*u**6 - 8*g*u**4 - 28*g**2*u**2 - 512/3*g**3))**(1/3) - \ 1/2*(u**3 - (u**2 - 4*g)*u - 2*g*u + 1/3*ct.sqrt(-1/3*u**6 - 8*g*u**4 - \ 28*g**2*u**2 - 512/3*g**3))**(1/3)*(-1j*mt.sqrt(3) + 1) + u eigs[13] = eig13.real eig14 = u + 1/3*(u**2 + 8*g)/(u**3 - (u**2 - 4*g)*u - 2*g*u + 1/3*ct.sqrt(-1/3*u**6 \ - 8*g*u**4 - 28*g**2*u**2 - 512/3*g**3))**(1/3) + (u**3 - (u**2 - 4*g)*u - \ 2*g*u + 1/3*ct.sqrt(-1/3*u**6 - 8*g*u**4 - 28*g**2*u**2 - 512/3*g**3))**(1/3) eigs[14] = eig14.real eigs[15] = u eigs[16] = 0.5 * (u - (u**2 + 8 * g)**0.5) eigs[17] = 0.5 * (u + (u**2 + 8 * g)**0.5) eigs[18] = u eigs[19] = 0.5 * (3 * u - (u**2 + 8 * g)**0.5) eigs[20] = 0.5 * (3 * u + (u**2 + 8 * g)**0.5) eigs[21] = 2 * u return (eigs - eigs.min()) * scale
def GetNewCollectionName(dbName, MaxIndex): db = client[dbName] collectionName = db.list_collection_names(session=None) NewCollectionName = [] EmailBody = [] for i in collectionName: flag = 0 price = [] number = [] OneBody = [] for index in range(1, MaxIndex + 1): collection = db[i] query = {"Index": index} result = collection.find(query, {"_id": 0, "Index": 0}) for x in result: price.append(x["Price"]) number.append(x["Number"]) ##构建构建内容 包括名称价格等信息 if MaxIndex > 5: Email = str(i) + "\n" EmailPric = "Price:" + "-".join(price) + "\n" EmailNumber = "Number" + "-".join(number) + "\n" Email = Email + EmailPric + EmailNumber OneBody.append(Email) ###取数量均值 allNumber = 0 for x in range(0, len(number)): allNumber = allNumber + number[x] avg = allNumber / len(number) if avg < 20: continue #当数据量小于5时候不做修改 只有数量小于20的才会进行修改 if MaxIndex <= 5: NewCollectionName.append(i) continue proPrice = 0 backPrice = 0 proNumber = 0 backNumber = 0 avgPrice = 0 avgNumber = 0 for x in range(0, len(price)): if x == 0: proPrice = price[x] proNumber = number[x] elif x == 1: backPrice = price[x] backNumber = number[x] avgPrice = avgPrice + math.fabs(proPrice - backPrice) / float(proPrice) avgNumber = avgNumber + math.abs(proNumber - backNumber) # if proPrice >= backPrice : ##降价 # diffPrice = proPrice - backPrice # avgPrice = avgPrice + diffPrice/float(proPrice) # else : #涨价 # diffPrice = backPrice - proPrice # avgPrice = avgPrice + diffPrice/float(proPrice) # if proNumber >= backNumber: # diffNumber = proNumber - backNumber # avgNumber = avgNumber + diffNumber # else : # diffNumber = backNumber - proNumber # avgNumber = else: proPrice = backPrice backPrice = price[x] proNumber = backNumber backNumber = number[x] avgPrice = avgPrice + math.fabs(proPrice - backPrice) / float(proPrice) avgNumber = avgNumber + math.abs(proNumber - backNumber) # if proPrice >= backPrice : ##降价 # diffPrice = proPrice - backPrice # avgPrice = avgPrice + diffPrice/float(proPrice) # else : #涨价 # diffPrice = backPrice - proPrice # avgPrice = avgPrice + diffPrice/float(proPrice) avgNumber = avgNumber / float(len(number) - 1) avgPrice = avgPrice / float(len(price) - 1) #数量和价格平均波动大于5% if (avgNumber >= 0.05 and avgPrice >= 0.05): flag = 1 if flag == 1: NewCollectionName.append(i) if MaxIndex > 5: sendemail.SendToMe("监控目录", "\n".join(EmailBody)) return NewCollectionName
d.bottom() - d.top()]) faces_size = len(faces) array_of_faces.append(faces) array_of_faces_labeling.append([0 for x in range(faces_size)]) happened = 0 distance = 0 k_best = 0 l_best = 0 border = 0 current_label = 0 #### FOR EACH FACE OF THE CURRENT FRAME for i in range(faces_size): print "**NEW_FACE**" happened = 0 distance = abs(height) + abs(width) k_best = 0 l_best = 0 roi = frame[faces[i][1]:faces[i][1] + faces[i][3], faces[i][0]:faces[i][0] + faces[i][2]] ##### Is the current face potentially a criminal ? In which case is_criminal >=1 cv2.imwrite("face.png", roi) feats = extract_feature(net, ["face.png"], 'prob', 1) feats = feats[0] #preprocess("face.png") is_criminal = 0 for z in range(0, len(features_criminal)): if cosine_similarity(feats, features_criminal[z]) > 0.2: is_criminal += 1
def set_motor(self, motor, speed): current = math.round(self.s) while current != speed: sign = (speed - current) / math.abs(speed - current) motor.ChangeDutyCycle(current + (1 * sign)) sleep(0.01)
def draw_line( x0, y0, z0, x1, y1, z1, screen, zbuffer, color ): #swap points if going right -> left if x0 > x1: x0,y0,z0,x1,y1,z1 = x1,y1,z1,x0,y0,z0 x = x0 y = y0 A = 2 * (y1 - y0) B = -2 * (x1 - x0) wide = False tall = False if ( abs(x1-x0) >= abs(y1 - y0) ): #octants 1/8 wide = True loop_start = x loop_end = x1 dx_east = dx_northeast = 1 dy_east = 0 d_east = A if ( A > 0 ): #octant 1 d = A + B/2 dy_northeast = 1 d_northeast = A + B else: #octant 8 d = A - B/2 dy_northeast = -1 d_northeast = A - B else: #octants 2/7 tall = True dx_east = 0 dx_northeast = 1 if ( A > 0 ): #octant 2 d = A/2 + B dy_east = dy_northeast = 1 d_northeast = A + B d_east = B loop_start = y loop_end = y1 else: #octant 7 d = A/2 - B dy_east = dy_northeast = -1 d_northeast = A - B d_east = -1 * B loop_start = y1 loop_end = y z = z0 if x1!=x0 and ((y1-y0)/(x1-x0))>-1 and ((y1-y0)/(x1-x0))<1: dz = (z1-z0)/(x1-x0) elif y1!=y0: dz = (z1-z0)/math.abs(y1-y0) while ( loop_start < loop_end ): plot( screen, zbuffer, color, x, y, z ) z += dz if ( (wide and ((A > 0 and d > 0) or (A < 0 and d < 0))) or (tall and ((A > 0 and d < 0) or (A < 0 and d > 0 )))): x+= dx_northeast y+= dy_northeast d+= d_northeast else: x+= dx_east y+= dy_east d+= d_east loop_start+= 1
def calc_heuristic_maldis(n1, n2): w = 1.0 # weight of heuristic dx = w * math.abs(n1.x - n2.x) dy = w * math.abs(n1.y - n2.y) return dx + dy
def hit(self, other): if math.abs(self.x - other.x) < 5 and math.abs(self.y - other.y) < 5: return True return False
def get_distance(x,y): return math.abs(x[0]-y[0])+math.abs(x[1]-y[1])
def intersect_mline(): plot,orientation = current_position() x,__ = plot if x >= 0 and 90 < orientation <= 270: if 90 < orientation <= 180: temp = 180 - orientation elif 180 < orientation <= 270: temp = 270 - orientation elif x < 0 and (0 <= orientation <= 90 or 270 < orientation <= 360): if 0 <= orientation <= 90: temp = orientation elif 270 < orientation <= 360: temp = 360 - orientation else: #not oriented towards mline return BIGNUM dist = math.abs(x) / math.cos(math.radians(temp)) * 100 #convert m to cm #if at the mline if dist < 10: n = 0 if 0 <= orientation <= 180: if orientation < 90: temp = 180 - orientation elif 180 < orientation <= 360: if orientation <= 270: turn('right',orientation+90) temp = 90 n = 1 else: turn('left',(360-orientation)+90) temp = 90 n = 2 c_servo(temp) distance = dream_team_us_dist() goal_dist = distance_to_goal() #if you can see the goal unobstructed, go for it if distance >= goal_dist: enc = (goal_dist/CRCM) * 18. if 0 <= orientation <= 90: turn('left', 90-orientation) elif 90 < orientation <= 180: turn('right', orientation-90) enc_tgt(1,1, int(math.ceil(enc))) fwd() while read_enc_status() != 0: time.sleep(.2) stop() print "Goal Reached!" raise SystemExit elif distance <= OBS_DIST: #return to previous orientation if n == 1: turn('left', orientation+90) elif n == 2: turn('right', (360-orientation)+90) return BIGNUM #if we are going to travel along the mline with a future obstacle else: pos,orient = mov_table[-1] x,y = pos if 0 <= orient <= 90: turn = 90 - orient turn('left', turn) elif 90 < orient <= 270: turn = orient - 90 turn('right', turn) my_fwd(15) insert_mov_plot((x,y+0.15), 90) runner() #number of encoders to the closest mline point on current orientation return (dist/CRCM)*18.
def compute_distance(self, p:Point): numerator = math.abs(self.a * p.x + self.b * p.y + self.c) denominator = math.sqrt(self.a ** 2 + self.b**2) return numerator / denominator
def distance(self, angle): phi = math.abs(angle.angle - self.angle) % 360 distance = 360 - phi if phi > 180 else phi return distance
exit() print("\n\nResultado: " + str(resultado)) elif opcao == 2: num1 = int(raw_input("Informe um numero:\n")) operacao = int( raw_input( "Selecione uma operacao:\n 1 - Ceil\n 2 - Floor\n 3 - Sqrt\n 4 - Abs\n" )) if operacao == 1: resultado = math.ceil(num1) elif operacao == 2: resultado = math.floor(num1) elif operacao == 3: resultado = resultado = math.sqrt(num1) elif operacao == 4: resultado = math.abs(num1) else: print("Opcao invalida!") exit() print("\n\nResultado: " + str(resultado)) elif opcao == 3: exit() else: print("Opcao invalida!") exit()
def get_area(self): return math.abs((self.azimuth_in + AzimuthDMS(180) - self.azimuth_out).to_radians() * self.radius)
x = int(imu0.ypr[2]) y = int(imu0.ypr[1]) if x >= 60: x = 60 if x <= -60: x = -60 if y >= 60: y = 60 if y <= -60: y = -60 label0.setText("%s" % x) label4.setText("%s" % y) # 计算出速度 speed_max = max(abs(x), abs(y)) - stop_limit speed = int(abs(speed_max // 10)) pos = 0 # 赋初始值 # 停止 if abs(x) <= stop_limit and abs(y) <= stop_limit: pos = 0 # 前进 if x < -stop_limit and -stop_limit < y < stop_limit: pos = 1 # 后退 if x > stop_limit and -stop_limit < y < stop_limit: pos = 2
def get_sum_of_squared_residuals(self): ss_residuals = 0 for x, y in zip(self.training_x, self.training_y): ss_residuals += math.abs(y - self.f(x))**2 g.debug.prn(self, 'SS Residuals gotten.') return ss_residuals
def len_ABS( P_coord ): #print ( P_coord ) return math.max( math.abs( P_coord[0]), math.abs( P_coord[1]),math.abs( P_coord[2]) )
def __nonzero__(self): """Return 'truthiness' value of the vector.""" return math.abs( math.sqrt(self.x * self.x + self.y * self.y + self.z * self.z)) >= 0.000000001
def flux_altitude_attenuation(flux, latitude): # Taking into account constant altitude ~ 11 km koef = 0.0226 * math.abs(latitude)
def area_of_triangle(p1, p2, p3): return math.abs(p1.x * (p2.y - p3.y) + p2.x * (p3.y - p1.y) + p3.x * (p1.y - p2.y)) / 2.0
# Print text print("this is a demo") # User input userinput = input("type some input: ") # If/else if (userinput == ""): print("you typed nothing") else: print("you typed '" + userinput + "'") # For print("numbers from 1 to 9") for x in range(1,10): print("- " + x) # Arithmetic a = 1 b = 1 sum = a + b diff = a - b absdiff = math.abs(diff) product = a * b sqrtproduct = math.sqrt(product) quotient = a / b exponent = a ** b modulo = a %% b
def absolute_error(n_distinct: int, threshold: int) -> int: return abs(n_distinct - threshold)
def isCarStable(self, na, nva, fva): f = 2.5 return (math.abs(na) < .025*f) and (math.abs(nva) < .0125*f) and (math.abs(fva) < .0125*f)
def display_network(A, opt_normalize=True, opt_graycolor=True, cols=-1, opt_colmajor=False): A = np.asarray(A) m = A.mean() B = A - m A = B # #Colormap # s = A.shape() L = s[0] #Row M = s[1] #column sz = math.sqrt(L) buf = 1 if cols == -1: if (math.floor(math.sqrt(M))**2) != M: n = math.ceil(math.sqrt(M)) while M % n != 0 and n < 1.2 * math.sqrt(M): n = n + 1 m = math.ceil(M / n) else: n = math.sqrt(M) m = n else: n = cols m = math.ceil(M / n) array = -1 * np.ones((buf + m * (sz + buf), buf + n * (sz + buf))) if opt_graycolor == False: array = 0.1 * array if opt_colmajor == False: k = 1 for i in range(1, m + 1): for j in range(1, n + 1): if k > M: continue clim = math.max(math.abs(A[:, k])) #Check this line if opt_normalize: array[np.ix_( buf + (i - 1) * (sz + buf) + range(1, sz + 1) - 1, buf + (j - 1) * (sz + buf) + range(1, sz + 1) - 1)] = np.reshape(A[:, k], (sz, sz)) / clim else: xx = A array[np.ix_( buf + (i - 1) * (sz + buf) + range(1, sz + 1), buf + (j - 1) * (sz + buf) + range(1, sz + 1) - 1)] = np.reshape( A[:, k], (sz, sz)) / abs(xx.flat[abs(xx).argmax()]) k = k + 1 else: k = 1 for j in range(1, n): for i in range(1, m): if k > M: continue clim = math.max(math.abs(A[:, k])) #Check this line if opt_normalize: array[np.ix_( buf + (i - 1) * (sz + buf) + range(1, sz + 1) - 1, buf + (j - 1) * (sz + buf) + range(1, sz + 1) - 1)] = np.reshape(A[:, k], (sz, sz)) / clim else: array[np.ix_( buf + (i - 1) * (sz + buf) + range(1, sz + 1), buf + (j - 1) * (sz + buf) + range(1, sz + 1) - 1)] = np.reshape(A[:, k], (sz, sz)) k = k + 1 fig, ax = plt.subplots() ax.plot(array) ax.axis('off') f = plt.figure(1) return f, array
import math print("Введите c ") c = float(input()) print("Введите d ") x = float(input()) res = int(math.abs(math.sin**3) * (math.abs(c * x**3)))
def jayBinner(numDeps, tauRos, temp, planckBin, grayLevel): """// method jayBolom computes bolometric angle-averaged mean intensity, J // This is a Lambda operation, ie. the Schwartzschild equation""" #// For bolometric J on a Gray Tau scale in LTE: #// J(Tau) = 1/2 * Sigma_Tau=0^Infty { E_1(|t-Tau|)*Planck_Bol(Tau) } logE = math.log10(math.e) #// for debug output #double E1 #//E_1(x) #//Set up local optical depth scale: tauBin = [ [ 0.0 for i in range(numDeps) ] for j in range(2) ] #double deltaTauRos tauBin[0][0] = tauRos[0][0] * grayLevel #// Is this a good idea?? tauBin[1][0] = math.log(tauBin[0][0]) for iTau in range(1, numDeps): deltaTauRos = tauRos[0][iTau] - tauRos[0][iTau - 1] #//grayLevel *is*, by definition, the ratio kappa_Bin/kappaRos that we need here! tauBin[0][iTau] = tauBin[0][iTau - 1] + grayLevel * deltaTauRos; tauBin[1][iTau] = math.log(tauBin[0][iTau]); #double logInteg, integ, integ1, integ2, logInteg1, logInteg2, meanInteg, logMeanInteg, term, logTerm; #double deltaTau, logDeltaTau; //accumulator accum = 0.0 #//accumulator jayBin = [0.0 for i in range(numDeps)] #// if E_1(t-Tau) evaluated at Tau=bottom of atmosphere, then just set Jay=B at that Tau - we're deep enough to be thermalized #// and we don't want to let lambda operation implicitly include depths below bottom of model where B=0 implicitly tiny = 1.0e-14 #//tuned to around maxTauDIff at Tau_Ros ~ 3 #double maxTauDiff; #//stipulate the {|t-Tau|} grid at which E_1(x)B will be evaluated - necessary to sample the #// sharply peaked integrand properly #// ** CAUTION: minLog10TmTau and maxLog10TmTau are tau offsets from the centre of J integration, #// NOT the optical depth scale of the atmosphere! #//stipulate the {|t-Tau|} grid at which E_1(x)B will be evaluated - necessary to sample the #// sharply peaked integrand properly fineFac = 3.0 #// integrate E1 on a grid fineFac x finer in logTau space E1Range = 36.0 #// number of master tauBin intervals within which to integrate J numInteg = E1Range * fineFac deltaLogTauE1 = (tauBin[1][numDeps - 1] - tauBin[1][0]) / numDeps deltaLogTauE1 = deltaLogTauE1 / fineFac #double thisTau1, logThisTau1, thisTau2, logThisTau2, logE1, deltaTauE1, logThisPlanck, iFloat; #//Prepare 1D vectors for Interpol.interpol: logTauBin = [0.0 for i in range(numDeps)] logPlanck = [0.0 for i in range(numDeps)] #//System.out.println("logTauBin logB"); for k in range(numDeps): logTauBin[k] = tauBin[1][k] logPlanck[k] = math.log(planckBin[0][k]) #//System.out.format("%12.8f %12.8f%n", logE*logTauBin[k], logE*logPlanck[k]); #//Outer loop over Taus where Jay(Tau) being computed: #// Start from top and work down to around tau=1 - below that assume we're thermalized with J=B #//System.out.println("For logTauRos = " + logE*tauRos[1][40] + ": thisTau E1xB E1 B"); #//System.out.println("tauRos[1][iTau] Math.log(planckBin[iTau]) jayBin[1][iTau]"); for iTau in range(numDeps): #//System.out.println("jayBinner: iTau: " + iTau + " tauRos[0] " + tauRos[0][iTau] + " tauRos[1] " + logE * tauRos[1][iTau]); jayBin[iTau] = planckBin[0][iTau] #//default initialization J_bin = B_bin if (tauRos[0][iTau] < 66.67): #//System.out.println("tauRos[0] < limit condition passed"); #// initial test - don't let E_1(x) factor in integrand run off bottom of atmosphere #// - we have no emissivity down there and J will drop below B again, like at surface! maxTauDiff = math.abs(tauBin[0][numDeps - 1] - tauBin[0][iTau]) #//System.out.println("tauBin[0][numDeps - 1]: " + tauBin[0][numDeps - 1] + " tauBin[0][iTau] " + tauBin[0][iTau] + " maxTauDiff " + maxTauDiff); #//System.out.println("maxTauDiff= " + maxTauDiff + " expOne(maxTauDiff)= " + expOne(maxTauDiff)); if (expOne(maxTauDiff) < tiny): #//System.out.println("maxTauDiff < tiny condition passed, expOne(maxTauDiff): " + expOne(maxTauDiff)); #// We're above thermalization depth: J may not = B: #//Inner loop over depths contributing to each Jay(iTau): #// work outward from t=Tau (ie. i=iTau) piece-wise accum = 0.0; #// conribution from depths above Tau: #//initial integrand: #// start at i=1 instead of i=0 - cuts out troublesome central cusp of E_1(x) - but now we underestimate J! logThisTau1 = tauBin[1][iTau] - deltaLogTauE1 thisTau1 = math.exp(logThisTau1) deltaTauE1 = tauBin[0][iTau] - thisTau1 E1 = expOne(deltaTauE1) logE1 = math.log(E1) logThisPlanck = ToolBox.interpol(logTauBin, logPlanck, logThisTau1) logInteg1 = logE1 + logThisPlanck integ1 = Math.exp(logInteg1); for i in range(2, numInteg-1): iFloat = float(i) #// Evaluate E_1(x) and log(E_1(x)) one and for all here #//System.out.format("%02d %12.8f %12.8f%n", j, tmTau[j], E1); #// LTE bolometric source function is Bolometric Planck function #// Extended trapezoidal rule for non-uniform abscissae - this is an exponential integrand! #// We cannot evaluate E_1(x) at x=0 - singular: logThisTau2 = tauBin[1][iTau] - iFloat * deltaLogTauE1 thisTau2 = math.exp(logThisTau2) #//if (i == numInteg - 2) { #// System.out.println("i " + i + " logThisTau1 " + logE * logThisTau1 + " logThisTau2 " + logE * logThisTau2); #//} #// Make sure we're still in the atmosphere! if (logThisTau2 > tauBin[1][0]): #//if (i == numInteg - 2) { #// System.out.println("thisTau2 > tauBin[0][0] condition passed"); #//} #//if (iTau == 37) { #// System.out.println("i " + i + " logThisTau1 " + logE * logThisTau1 + " logThisTau2 " + logE * logThisTau2); #//} deltaTauE1 = tauBin[0][iTau] - thisTau2 E1 = expOne(deltaTauE1) logE1 = math.log(E1) #// interpolate log(B(log(Tau)) to the integration abscissa logThisPlanck = ToolBox.interpol(logTauBin, logPlanck, logThisTau2) logInteg2 = logE1 + logThisPlanck integ2 = math.exp(logInteg2) logDeltaTau = math.log(thisTau1 - thisTau2) #// logDeltaTau *NOT* the same as deltaLogTau!! meanInteg = 0.5 * (integ1 + integ2) #//Trapezoid rule logMeanInteg = math.log(meanInteg) #//if (iTau == 40) { #// System.out.format("%15.8f %15.8f %15.8f %15.8f%n", logE*Math.log(thisTau1), logE*logMeanInteg, logE*logE1, logE*logThisPlanck); #//} logTerm = logMeanInteg + logDeltaTau term = math.exp(logTerm) accum = accum + term integ1 = integ2 thisTau1 = thisTau2 #//if (iTau == 41){ #// System.out.println("term " + term + " accum " + accum); #//} #} // thisTau > 0 #} // i ("t") loop, above iTau jayBin[iTau] = 0.5 * accum #//store what we have. #//test jayBin[iTau] = 0.5 * planckBin[0][iTau]; // fake upper half with isotropic result #//test jayBin[iTau] = jayBin[iTau] + 0.5 * planckBin[0][iTau]; // test upper atmosphere part of J integration by fixing lower part with isotropic result #// conribution from depths below Tau: #// include iTau itself so we don't miss the area under the central peak of E_1(x) - the expOne function #// will protect itself from the x=0 singularity using variable 'tiny' accum = 0.0 #//initial integrand: #// start at i=1 instead of i=0 - cuts out troublesome central cusp of E_1(x) - but now we underestimate J! logThisTau1 = tauBin[1][iTau] + deltaLogTauE1 thisTau1 = math.exp(logThisTau1) deltaTauE1 = thisTau1 - tauBin[0][iTau] E1 = expOne(deltaTauE1) logE1 = math.log(E1) logThisPlanck = ToolBox.interpol(logTauBin, logPlanck, logThisTau1) logInteg1 = logE1 + logThisPlanck integ1 = math.exp(logInteg1) for i in range(2, numInteg - 1): iFloat = float(i) logThisTau2 = tauBin[1][iTau] + iFloat * deltaLogTauE1 thisTau2 = math.exp(logThisTau2) #// We cannot evaluate E_1(x) at x=0 - singular: #// Extended trapezoidal rule for non-uniform abscissae - the is an exponential integrand! #// make sure we're still in the atmosphere! if (logThisTau2 < tauBin[1][numDeps - 1]): deltaTauE1 = thisTau2 - tauBin[0][iTau] E1 = expOne(deltaTauE1) logE1 = math.log(E1) logThisPlanck = ToolBox.interpol(logTauBin, logPlanck, logThisTau2) logInteg2 = logE1 + logThisPlanck integ2 = math.exp(logInteg2) logDeltaTau = math.log(thisTau2 - thisTau1) #// logDeltaTau *NOT* the same as deltaLogTau!! meanInteg = 0.5 * (integ1 + integ2) #//Trapezoid rule logMeanInteg = math.log(meanInteg) #//if (iTau == 40) { #// System.out.format("%15.8f %15.8f %15.8f %15.8f%n", logE*Math.log(thisTau1), logE*logMeanInteg, logE*logE1, logE*logThisPlanck); #//} #// LTE bolometric source function is Bolometric Plnack function logTerm = logMeanInteg + logDeltaTau term = math.exp(logTerm) accum = accum + term integ1 = integ2 thisTau1 = thisTau2 #}// if thisTau < tauBin[0][numDeps-1] #} #// i ("t") loop, below iTau jayBin[iTau] = jayBin[iTau] + 0.5 * accum #} //if branch for E_1(x) safely dwindling away before reaching bottom of atmosphere #} #// if branch for above thermalization depth of Tau=10? #//System.out.format("%12.8f %12.8f %12.8f%n", #// logE * tauRos[1][iTau], Math.log10(planckBin[iTau]), Math.log10(jayBin[iTau])); #} //iTau loop return jayBin
def mgTCorr(numDeps, teff, tauRos, temp, rho, kappa): #// updated temperature structure newTemp = [ [ 0.0 for i in range(numDeps) ] for j in range(2) ] #//Teff boundary between early and late-type stars: isCool = 6500.0 #//Set up multi-gray opacity: #// lambda break-points and gray levels: #// No. multi-gray bins = num lambda breakpoints +1 #//double[] grayLams = {30.0, 1.0e6}; //nm //test #//double[] grayLevel = {1.0}; //test #// *** Late type stars, Teff < 9500 K (???): #// minLambda = 30.0 #//nm maxLambda = 1.0e6 #//nm maxNumBins = 11 grayLams = [0.0 for i in range(maxNumBins + 1)] grayLevel = [0.0 for i in range(maxNumBins)] epsilon = [0.0 for i in range(maxNumBins)] #//initialize everything first: for iB in range(maxNumBins): grayLams[iB] = maxLambda grayLevel[iB] = 1.0 epsilon[iB] = 0.99 grayLams[maxNumBins] = maxLambda #//Set final wavelength grayLevelsEpsilons = grayLevEps(maxNumBins, minLambda, maxLambda, teff, isCool) #//Find actual number of multi-gray bins: numBins = 0 #//initialization for i in range(maxNumBins): if (grayLevelsEpsilons[0][i] < maxLambda): numBins+=1 #//Add one more for final lambda: #//numBins++; #//System.out.println("numBins: " + numBins); """/* if (teff < isCool) { #// physically based wavelength break-points and gray levels for Sun from Rutten Fig. 8.6 #// H I Balmer and Lyman jumps for lambda <=3640 A, H^- b-f opacity hump in visible & hole at 1.6 microns, increasing f-f beyond that double[] lamSet = {minLambda, 91.1, 158.5, 364.0, 794.3, 1600.0, 3.0e3, 1.0e4, 3.3e4, 1.0e5, 3.3e5, maxLambda}; //nm double[] levelSet = {1000.0, 100.0, 5.0, 1.0, 0.3, 1.0, 3.0, 10.0, 30.0, 100.0, 1000.0}; #//photon *thermal* destruction and creation probability (as opposed to scattering) #//WARNING: THese cannot be set exactly = 1.0 or a Math.log() will blow up!! double[] epsilonSet = {0.50, 0.50, 0.50, 0.50, 0.50, 0.9, 0.99, 0.99, 0.99, 0.99, 0.99}; int numBins = levelSet.length; for (int iB = 0; iB < numBins; iB++) { grayLams[iB] = lamSet[iB] * 1.0e-7; grayLevel[iB] = levelSet[iB]; epsilon[iB] = epsilonSet[iB]; } grayLams[numBins] = lamSet[numBins] * 1.0e-7; //Get final wavelength } else { #// *** Early type stars, Teff > 9500 K (???) #// It's all about H I b-f (??) What about Thomson scattering (gray)? #// Lyman, Balmer, Paschen, Brackett jumps #//What about He I features? double[] lamSet = {minLambda, 91.1, 364.0, 820.4, 1458.0, maxLambda}; //nm double[] levelSet = {100.0, 10.0, 2.0, 1.0, 1.0}; //??? double[] epsilonSet = {0.5, 0.6, 0.7, 0.8, 0.5}; int numBins = levelSet.length; for (int iB = 0; iB < numBins; iB++) { grayLams[iB] = lamSet[iB] * 1.0e-7;; grayLevel[iB] = levelSet[iB]; epsilon[iB] = epsilonSet[iB]; } grayLams[numBins] = lamSet[numBins] * 1.0e-7; //Get final wavelength } #//Find out how many bins we really have: #int numBins = 0; //initialize #for (int iB = 0; iB < maxNumBins; iB++) { if (grayLams[iB] < maxLambda) { numBins++; #} } */""" for iB in range(numBins): grayLams[iB] = grayLevelsEpsilons[0][iB] grayLevel[iB] = grayLevelsEpsilons[1][iB] epsilon[iB] = grayLevelsEpsilons[2][iB]; grayLams[numBins] = grayLevelsEpsilons[0][numBins] #//Get final wavelength #//Set overall gray-level - how emissive and absorptive the gas is overall #// a necessary "fudge" because our kappa values are arbitrary rather than "in situ" graySet = 1.0 #//double tcDamp = 0.5; // damp the temperature corrections, Delta T, by this *multiplicative* factor tcDamp = 1.0 #// no damping - Lambda iteration is slow rather than oscillatory logE = math.log10(math.E) #// for debug output #//double[][] planckBol = MulGrayTCorr.planckBin(numDeps, temp, lamStart, lamStop); planckBol = [0.0 for i in range(numDeps)] #//just for reference - not really needed - ?? jayBol = [0.0 for i in range(numDeps)] #//just for reference - not really needed - ?? dBdTBol = [0.0 for i in range(numDeps)] #//just for reference - not really needed - ?? cool = [0.0 for i in range(numDeps)] #// cooling term in Stromgren equation heat = [0.0 for i in range(numDeps)] #// heating term in Stromgren equation corrDenom = [0.0 for i in range(numDeps)] #//denominator in 1st order temp correction #//double[] accumB = new double[numDeps]; //accumulator #//CAUTION: planckBin[2][]: Row 0 is bin-integrated B_lambda; row 1 is bin integrated dB/dT_lambda planckBin = [ [ 0.0 for i in range(numDeps) ] for j in range(2) ] jayBin = [0.0 for i in range(numDeps)] dBdTBin = [0.0 for i in range(numDeps)] #//double logCool, logHeat, logCorrDenom, logCoolTherm, logCoolScat; #// initialize accumulators & set overell gray kappa level: for iTau in range(numDeps): planckBol[iTau] = 0.0 #//just for reference - not really needed - ?? jayBol[iTau] = 0.0 #//just for reference - not really needed - ?? dBdTBol[iTau] = 0.0 #//just for reference - not really needed - ?? cool[iTau] = 0.0 heat[iTau] = 0.0 corrDenom[iTau] = 0.0 kappa[1][iTau] = kappa[1][iTau] + math.log(graySet) kappa[0][iTau] = math.exp(kappa[1][iTau]) for iB in range(numBins): #//System.out.println("iB: " + iB + " grayLams[iB] " + grayLams[iB]); planckBin = planckBinner(numDeps, temp, grayLams[iB], grayLams[iB + 1]) #// We are lambda-operating on a wavelength integrated B_lambda for each multi-gray bin jayBin = jayBinner(numDeps, tauRos, temp, planckBin, grayLevel[iB]) #//System.out.println("tauRos[1][iTau] planckBin[0] planckBin[1] jayBin"); for iTau in range(numDeps): #//System.out.format("%12.8f %12.8f %12.8f %12.8f%n", #// logE * tauRos[1][iTau], logE * Math.log(planckBin[0][iTau]), logE * Math.log(planckBin[1][iTau]), logE * Math.log(jayBin[iTau])); #//CAUTION: planckBin[2][]: Row 0 is bin-integrated B_lambda; row 1 is bin integrated dB/dT_lambda #//Net LTE volume cooling rate deltaE = Integ_lam=0^infnty(4*pi*kappa*rho*B_lam)dlam - Integ_lam=0^infnty(4*pi*kappa*rho*J_lam)dlam #// where Jlam = LambdaO[B_lam] - Rutten Eq. 7.32, 7.33 #// CAUTION: the 4pi and rho factors cancel out when diving B-J term by dB/dT term planckBol[iTau] = planckBol[iTau] + planckBin[0][iTau] #//just for reference - not really needed - ?? #//logCool = Math.log(grayLevel[iB]) + kappa[1][iTau] + Math.log(planckBin[0][iTau]) #//no scatering #//cool[iTau] = cool[iTau] + Math.exp(logCool); //no scattering logCoolTherm = math.log(grayLevel[iB]) + math.log(epsilon[iB]) + kappa[1][iTau] + math.log(planckBin[0][iTau]) logCoolScat = math.log(grayLevel[iB]) + math.log((1.0 - epsilon[iB])) + kappa[1][iTau] + math.log(jayBin[iTau]) cool[iTau] = cool[iTau] + math.exp(logCoolTherm) + math.exp(logCoolScat) jayBol[iTau] = jayBol[iTau] + jayBin[iTau] #//just for reference - not really needed - ?? logHeat = math.log(grayLevel[iB]) + kappa[1][iTau] + math.log(jayBin[iTau]) heat[iTau] = heat[iTau] + math.exp(logHeat) dBdTBol[iTau] = dBdTBol[iTau] + planckBin[1][iTau] #//just for reference - not really needed - ?? logCorrDenom = math.log(grayLevel[iB]) + kappa[1][iTau] + math.log(planckBin[1][iTau]) corrDenom[iTau] = corrDenom[iTau] + math.exp(logCorrDenom) #// if (iTau == 10){ #// System.out.format("iB: %02d %12.8f %12.8f %12.8f %12.8f%n", iB, logE*Math.log(planckBin[0][iTau]), logE*Math.log(cool[iTau]), logE*Math.log(heat[iTau]), logE*Math.log(corrDenom[iTau])); #//} #} // iTau loop #} //iB loop #// System.out.println("i tauRos[1][iTau] planckBol[0] planckBol[1] jayBol cool heat corrDenom"); #// for (int iTau = 0; iTau < numDeps; iTau++) { #//System.out.format("%02d %12.8f %12.8f %12.8f %12.8f %12.8f %12.8f %12.8f%n", iTau, #// logE * tauRos[1][iTau], logE * Math.log(planckBol[iTau]), logE * Math.log(dBdTBol[iTau]), logE * Math.log(jayBol[iTau]), #// logE * Math.log(cool[iTau]), logE * Math.log(heat[iTau]), logE * Math.log(corrDenom[iTau])); #// } #double logRatio, ratio, deltaTemp, logDeltaTemp; sign = 1.0 #//initialize for positive JminusB #//System.out.println("tauRos[1][iTau] deltaTemp[iTau]"); for iTau in range(numDeps): #// Compute a 1st order T correction: Compute J-B so that DeltaT < 0 if J < B: #// avoid direct subtraction of two large almost equal numbers, J & B: """/* //Gray method: double JminusB logRatio = Math.log(planckBol[iTau]) - Math.log(jayBol[iTau]); ratio = Math.exp(logRatio); JminusB = jayBol[iTau] * (1.0 - ratio); if (JminusB < 0.0) { sign = -1.0; } #// DeltaB/DeltaT ~ dB/dT & dB/dT = (4/pi)sigma*T^3 logDeltaTemp = Math.log(Math.abs(JminusB)) + Math.log(Math.PI) - Math.log(4.0) - Useful.logSigma() - 3.0 * temp[1][iTau]; deltaTemp[iTau] = sign * Math.exp(logDeltaTemp) * tcDamp; #//System.out.format("%12.8f %12.8f%n", tauRos[1][iTau], deltaTemp[iTau]); sign = 1.0; //reset sign */""" #//Multi-Gray method: #double deltaE; #//double logHeatNorm, heatNorm, logCoolNorm, deltaENorm; #////Normalize numbers by dividing heat and cool terms each by common denominator derivative term first: #//logHeatNorm = Math.log(heat[iTau]) - Math.log(corrDenom[iTau]); #//heatNorm = Math.exp(logHeatNorm); #//logCoolNorm = Math.log(cool[iTau]) - Math.log(corrDenom[iTau]); logRatio = math.log(cool[iTau]) - math.log(heat[iTau]) #//logRatio = logCoolNorm - logHeatNorm ratio = math.exp(logRatio) deltaE = heat[iTau] * (1.0 - ratio) #//deltaENorm = heatNorm * (1.0 - ratio) if (deltaE < 0.0): sign = -1.0 #//CHEAT: Try a Tau-dependent deltaE damping here - things are flaky at tdepth where t(Tau) steepens deltaE = deltaE * math.exp(1.0 * (tauRos[0][0] - tauRos[0][iTau])) #// DeltaE/DeltaT ~ dB/dT_Bol logDeltaTemp = math.log(math.abs(deltaE)) - math.log(corrDenom[iTau]) deltaTemp = sign * math.exp(logDeltaTemp) * tcDamp #//deltaTemp = sign * deltaENorm * tcDamp; newTemp[0][iTau] = temp[0][iTau] + deltaTemp; newTemp[1][iTau] = math.log(newTemp[0][iTau]); #} //iTau loop return newTemp
def jolaProfileQ(omega0, logf, vibConst, jolaPoints, alphQ, numDeps, temp): """//JOLA profile for Q (Delta J = 0) branch //Equation 24 from Zeidler & Koestler""" nm2cm = 1.0e-7 numPoints = len(jolaPoints) #// derivative of rotational-line oscillator strength with respect to frequency dfBydw = [[0.0 for i in range(numDeps)] for j in range(numPoints)] fvv = math.exp(logf) logHcBbyK = Useful.logH() + Useful.logC() + math.log(vibConst[0]) \ - Useful.logK() Bsum = vibConst[1] + vibConst[0] Bdiff = vibConst[1] - vibConst[0] #double mQ; #// related to J, for R & P branches, respectively #//value of m is closely related to rotational quantum number J, #//Near band origin, frequency, w, range should correspond to -1 <= m <= 1 - ???: #// double wMin = Useful.c / (1.0e-7*lambda[1]); //first frequency omega #// double wMax = Useful.c / (1.0e-7*lambda[0]); //last frequency omega #// double deltaW = 0.02; #double w, logW, mQFctr, mHelp; #double denom, mQTerm, wMinusw0OverBDiff; #double help1, logHcBbyKt, hcBbyKt; #//Outer loop over frequency omega #//for (int iW = -1; iW <= 1; iW++){ #for (int iW = numPoints-1; iW >= 0; iW--){ for iW in range(numPoints - 1, 0, -1): #//dW = (double) iW; #//w = wMin + (dW*deltaW); #//logW = Useful.logC() - Math.log(1.0e-7*jolaPoints[iW]); //if w is freq in Hz logW = 0.0 - math.log( nm2cm * jolaPoints[iW]) #//if w is waveno in cm^-1 w = math.exp(logW) #//I have no idea if this is right... wMinusw0OverBDiff = (w - omega0) / Bdiff mHelp = 0.25 + math.abs(wMinusw0OverBDiff) mHelp = math.sqrt(mHelp) #//Eq. 17 mQ = -0.5 + mHelp mQFctr = (mQ * mQ - mQ) denom = math.abs(Bdiff) for iD in range(numDeps): if (wMinusw0OverBDiff > 0): logHcBbyKt = logHcBbyK - temp[1][iD] hcBbyKt = math.exp(logHcBbyKt) help1 = -1.0 * hcBbyKt * mQFctr mQTerm = math.exp(help1) / denom #//Can this be used like a differential cross-section (once converted to sigma)? #//System.out.println("alphQ " + alphQ + " fvv " + " logHcBbyKt " + logHcBbyKt + " mQTerm " + mQTerm); dfBydw[iW][iD] = alphQ * fvv * hcBbyKt * mQTerm #// Eq. 24 else: dfBydw[iW][iD] = 0.0 #//if (iD%10 == 1){ #//System.out.println("Q iD " + iD + " iW " + iW + " dfBydw " + dfBydw[iW][iD]); #//} #//iD - depth loop #} //iW - frequency loop return dfBydw
def lansvd(A, m = A.shape[0], n = A.shape[1], K = math.min(math.min(m, n), 6), SIGMA='L', OPTS=[]): #LANSVD Compute a few singular values and singular vectors. # LANSVD computes singular triplets (u,v,sigma) such that # A*u = sigma*v and A'*v = sigma*u. Only a few singular values # and singular vectors are computed using the Lanczos # bidiagonalization algorithm with partial reorthogonalization (BPRO). # # S = LANSVD(A) # S = LANSVD('Afun','Atransfun',M,N) # # The first input argument is either a matrix or a # string containing the name of an M-file which applies a linear # operator to the columns of a given matrix. In the latter case, # the second input must be the name of an M-file which applies the # transpose of the same operator to the columns of a given matrix, # and the third and fourth arguments must be M and N, the dimensions # of the problem. # # [U,S,V] = LANSVD(A,K,'L',...) computes the K largest singular values. # # [U,S,V] = LANSVD(A,K,'S',...) computes the K smallest singular values. # # The full calling sequence is # # [U,S,V] = LANSVD(A,K,SIGMA,OPTIONS) # [U,S,V] = LANSVD('Afun','Atransfun',M,N,K,SIGMA,OPTIONS) # # where K is the number of singular values desired and # SIGMA is 'L' or 'S'. # # The OPTIONS structure specifies certain parameters in the algorithm. # Field name Parameter Default # # OPTIONS.tol Convergence tolerance 16*eps # OPTIONS.lanmax Dimension of the Lanczos basis. # OPTIONS.p0 Starting vector for the Lanczos rand(n,1)-0.5 # iteration. # OPTIONS.delta Level of orthogonality among the sqrt(eps/K) # Lanczos vectors. # OPTIONS.eta Level of orthogonality after 10*eps^(3/4) # reorthogonalization. # OPTIONS.cgs reorthogonalization method used 0 # '0' : iterated modified Gram-Schmidt # '1' : iterated classical Gram-Schmidt # OPTIONS.elr If equal to 1 then extended local 1 # reorthogonalization is enforced. # # See also LANBPRO, SVDS, SVD # References: # R.M. Larsen, Ph.D. Thesis, Aarhus University, 1998. # # B. N. Parlett, ``The Symmetric Eigenvalue Problem'', # Prentice-Hall, Englewood Cliffs, NJ, 1980. # # H. D. Simon, ``The Lanczos algorithm with partial reorthogonalization'', # Math. Comp. 42 (1984), no. 165, 115--142. # Rasmus Munk Larsen, DAIMI, 1998 # Python Implementation: Matt Dioso, Seattle University Department of Electrical and Computer Engineering 2018 # NOTE: Purposely omitting the Atrans option. don't think it applies in Python implementation # ref: https://github.com/areslp/matlab/blob/master/PROPACK/lansvd.m ##################### Parse and check input arguments. ###################### if not isinstance(A, str): if not np.isreal(A): print("[lansvd] A must be real") return if m < 0 or n < 0 or K < 0: print("[lansvd] m, n, and K must be positive integers") return if math.min(n, m) < 1 or K < 1: U = np.eye(m, K) S = np.zeroes(K, K) V = np.eye(n, K) bnd = np.zeroes(K, 1) return U, S, V else if math.min(n, m) == 1 and K > 0: U, S, V = np.linalg.svd(A) #translated from [U,S,V] = svd(full(A)) bnd = 0 return U, S, V if isinstance(A, num): if np.count_nonzero(A) == 0: U = np.eye(m, K) S = np.zeroes(K, K) V = np.eye(n, K) bnd = np.zeros(K, 1) return U, S, V lanmax = math.min(m, n) tol = 16 * np.spacing(1) p = np.random.rand(m, 1) - 0.5 c = list(opts.keys()) for i in range(0, len(c)): if "p0" in c: p = opts.get("p0") p = p[:] if "tol" in c: tol = opts.get("tol") if "lanmax" in c: lanmax = opts.get("lanmax") tol = math.max(tol, np.spacing(1)) lanmax = math.min(lanmax, math.min(m, n)) if p.shape(0) != m: print("[lansvd] p0 must be a vector of length m") return lanmax = math.min(lanmax, math.min(m, n)) if K > lanmax: print("[lansvd] K must satisfy K <= LANMAX <= MIN(M, N)") if SIGMA == 'S': if isinstance(A, str): print("[lansvd] Shift-and-invert works only when the atrix A is given explicitly") else: if scipy.sparse.issparse(A): pmmd = scipy.sparse.linalg.splu(A, 'COLAMD') AA = A[:,pmmd] #CHECK THIS else: AA = A #ALSO CHECK THIS if m>=n: if scipy.sparse.issparse(AA): AR = scipy.linalg.qr(AA) ARt = AR.conj().transpose() p = ARt / (AA.conj().transpose().dot(p)) else: AQ, AR = scipy.linalg.qr(AA) ARt = AR.conj().transpose() p = AQ.conj.transpose().dot(p) else: print("Sorry, shift-and-invert for m<n not implemented yet") AR = scipy.linalg.qr(AA.conj().transpose()) ARt = AR.conj().transpose() condR = np.linalg.cond(AR) if condR > 1/np.spacing(1): print("[lansvd] A is rank deficient or too ill-conditioned to do shift-and-invert") return ksave = K neig = 0 nrestart = -1 j = math.min(k+math.max(8, K) + 1, lanmax) U = [] V = [] B = [] anorm = [] work = np.zeros(2, 2) while neig < K: if not isinstance(A, str): U, B, V, p, ierr, w = lanbpro(A, j, p, opts, U, B, V, anorm) #IMPLEMENT LANBPRO work = work +w if ierr < 0: j = -ierr resnrm = np.linalg.norm(p) S, bot = bdsqr(np,diag(B), [np.diag(B, -1); resnrm]) #IMPLEMENT BDSQR anorm = S[0] bnd = resnrm * math.abs(bot) bnd = refinebounds(S**2, bnd, n*np.spacing(1)*anorm) i = 0 neig = 0 while i <= math.min(j, k): if (bnd[i] <= tol*math.abs(S[i])): neig = neig + 1 i = i + 1 else: i = math.min(j, k) + 1 if ierr < 0: if j < k: print("[lansvd] Warning: Invariant subspace of dimension %d found", j-1) j = j - 1 break if j >= lanmax: if j >= math.min(m,n): neig = ksave break if neig < ksave: print("[lansvd] Warning maximum dimension of Krylob subspace exceeded prior to convergence") break else: j = math.max(1.5*j, j+10) if neig > 0: j = j+math.min(100, math.max(2, 0.5*(K-neig)*j/(neig+1))) else: j=math.max(1.5*j, j+10) j = math.ceil(math.min(j+1, lanmax)) nrestart = nrestart + 1 K = math.min(ksave, j) j=B.shape[1] P, S, Q = np.linalg.svd([B;np.zeros(1, j-1)]) S = np.diag(S) if Q.shape[1] != K: Q = Q[:, 0:K] P = P[:, 0:K] if resnrm != 0: U = U.dot(P[0:j, :]) + (p/resnrm).dot(P[j+1, :]) else: U = U.dot(P[0:j, :]) V = V.dot(Q) for i in range(0, K): nq = np.linalg.norm(V[:, i]) if np.isfinite(nq) and nq != 0 and nq != 1: V[:,i] = U[:, i]/nq nq = np.linalg.norm(U[:, i]) if np.isfinite(nq) and nq != 0 and nq != 1: U[:, i] = U[:, i]/nq S = S[0:K] bnd = bnd[0:K] if sigma == 'S': S= np.sort(-1/S) S = -S bnd = bnd[S.size] if scipy.sparse.issparse(AA): U = AA.dot(AR/U[:,p]) V[pmmd,:] = V[:,p] else: U = AQ[:, 1:math.min(m,n)].dot(U[:, p]) V = V[:,p] return U, S, V, bnd, j
def prA(): k = 3 log_laur = lambda t: log1p( abs(Laurent(k, exp(2 * math.pi * cmath.sqrt(-1) * t)))) integrand = integrate.quad(log_laur, 0, 1) print exp(integrand)
def ekf_localization(estimated_state_mean, estimated_state_covariance, z, u): """ Jacobian of Motion Model __motion model__ x_{t+1} = x_t - v/w*sin(yaw_t) + v/w*sin(yaw_t + w*dt) y_{t+1} = y_t + v/w*cos(yaw_t) - v/w*cos(yaw_t + w*dt) yaw_{t+1} = yaw_t + w*dt --- __partial derivatives__ dx/dyaw = - v/w*cos(yaw_t) + v/w*cos(yaw_t + w*dt) dy/dyaw = -v/w*sin(yaw_t) + v/w*sin(yaw_t + w*dt) dy/dv = dt*sin(yaw) dx/dt = 1 dy/dt = 1 dyaw/dt = 1 """ yaw = estimated_state_mean[2, 0] v = u[0, 0] w = u[1, 0] G = np.array([ [ 1.0, 0.0, -v / w * math.cos(yaw) + v / w * math.cos(yaw + w * delta_t) ], [ 0.0, 1.0, -v / w * math.sin(yaw) + v / w * math.sin(yaw + w * delta_t) ], [0.0, 0.0, 1.0], ]) """ Jacobian of Gaussian Noise in Motion Model __noise__ N(0,R_t) __derivative of non-linear motion function with respect to control inputs__ dx/dv = (-sin(yaw_t) + sin(yaw_t + w*dt)) / w dx/dw = v *(sin(yaw_t) - sin(yaw_t +w*dt))/w^2 + v*cos(yaw_t+w*dt)*dt/w dy/dv = (cos(yaw_t) - cos(yaw_t +w*dt))/w dy/dw = - v *(cos(yaw_t) - cos(yaw_t + w*dt)) /w^2 + v*sin(yaw_t+w*dt)*dt/w dyaw/dv = 0 dyaw/dw = dt """ V = np.array([[(-math.sin(yaw) + math.sin(yaw + w * delta_t)) / w, v * (math.sin(yaw) - math.sin(yaw + w * delta_t)) / (w**2) + v * math.cos(yaw + w * delta_t) * delta_t / w], [(math.cos(yaw) - math.cos(yaw + w * delta_t)) / w, -v * (math.cos(yaw) - math.cos(yaw + w * delta_t)) / (w**2) + v * math.sin(yaw + w * delta_t) * delta_t / w], [0, delta_t]]) """ Covariance of the additional motion noise N(0,R_t) in control space. """ M = np.array([(a1 * math.abs(v) + a2 * math.abs(w))**2, 0], [0, (a3 * math.abs(v) + a4 * math.abs(w))**2]) # Predict pred_state_covariance = G @ estimated_state_covariance @ G.T + V @ M @ V.T pred_state_mean = motion_model(estimated_state_mean, u) # Correction """ Measurement noise on landmarks """ Q = np.array([[std_range**2, 0, 0], [0, std_yaw**2, 0], [0, 0, std_signature**2]]) H = jacobian_observation(pred_state_mean) zPred = H @ pred_state_mean y = z - zPred S = H @ pred_state_covariance @ H.T + R K = pred_state_covariance @ H.T @ np.linalg.inv(S) estimated_state_mean = pred_state_mean + K @ y estimated_state_covariance = (np.eye(len(estimated_state_mean)) - K @ H) @ pred_state_covariance return estimated_state_mean, estimated_state_covariance