def ellipse(emittance, beta, alpha, gamma): phi = linspace(0, 2*const.pi, 1e3) a = sqrt(emittance/2*(beta+gamma+sqrt((beta+gamma)**2-4))) b = sqrt(emittance/2*(beta+gamma-sqrt((beta+gamma)**2-4))) if alpha > 0: PHI = acos(+sqrt((beta-b/a)*emittance/(a**2-b**2))) else: PHI = acos(-sqrt((beta-b/a)*emittance/(a**2-b**2))) pos = a*cos(phi)*cos(PHI)+b*sin(phi)*sin(PHI) mom = -a*cos(phi)*sin(PHI)+b*sin(phi)*cos(PHI) return pos, mom
def slerp(self, other, tVal): """Perform item-wise spherical linear interpolation at the given sample points Parameters ---------- other: Quaterion, QuaternionArray The other quaternions to slerp between tVal: float The percentages to compute for the slerp. For instance .25 would calculate the slerp at 25% all pairs Returns ------- QuaternnionArray: A quaternion array of interpolands """ other = arrayCompat(other) cosHalfAngle = np.einsum("...ij, ...ij -> ...i", self, other) # Handle floating point errors cosHalfAngle[abs(cosHalfAngle) >= 1.0] = 1.0 # Calculate the sin values halfAngle = np.acos(cosHalfAngle) sinHalfAngle = np.sqrt(1.0 - cosHalfAngle * cosHalfAngle) ratioA = np.sin((1 - tVal) * halfAngle) / sinHalfAngle ratioB = np.sin(tVal * halfAngle) / sinHalfAngle return (self * ratioA) + (other * ratioB)
def drawKochPyramid(self, level): angle = rad2deg(acos(1/3)) if (level == 0): glBegin(GL_TRIANGLES) self.basicTriangle() glEnd() else: glPushMatrix() glScalef(1.0/3, 1.0/3, 1.0/3) self.drawKochPyramid(level - 1) glTranslatef(1.0, 0, 0) self.drawKochPyramid(level - 1) glTranslatef(1.0, 0, 0) self.drawKochPyramid(level - 1) glTranslatef(-0.5, sqrt(3)/2.0, 0) self.drawKochPyramid(level - 1) self.innerPyra(level, angle) glTranslatef(-1,0, 0) self.drawKochPyramid(level - 1) self.innerPyra(level, angle) glTranslatef(0.5, sqrt(3)/2.0, 0) self.drawKochPyramid(level - 1) self.innerPyra(level, angle) glPopMatrix()
def get_phi_theta(vec): """ returns a tupel of the phi and theta angles of the given vector """ try: return (atan2(vec[1], vec[0]), acos(np.clip(vec[2] / length(vec), -1, 1))) * u.rad except ValueError: return (0, 0)
def point2unit_spherical(point): ub = dot(self.axinv, (point - self.origin)) u = zeros((self.DIM, )) u[0] = sqrt(ub[0] * ub[0] + ub[1] * ub[1] + ub[2] * ub[2]) u[1] = atan2(ub[1], ub[0]) * o2pi + .5 u[2] = acos(ub[2] / u[0]) * o2pi * 2.0 return u
def getlatlon(x,y,z): #radEarth = 6378145. #[m] rmag = np.sqrt(x**2+y**2+z**2) longitude = np.arctan2(y,x)*180./np.pi latitude = 90. - np.acos(z/rmag)*180./np.pi return (latitude,longitude)
def chessboard_binary_noise(hologram): """Dump power into a binary chessboard grating""" signs = np.zeros(hologram.shape, dtype=np.float) signs[0::2, 1::2] = 1 signs[1::2, 0::2] = 1 # signs is a chessboard grating return nearest(hologram) + signs * np.acos(normalised_amplitude(hologram))
def __init__( self, i, # input energy bin nphot, # number of photons geometry, verbose=False): self.verbose = verbose self.rad = numpy.zeros(nphot) self.phi = numpy.zeros(nphot) # initial left-right angle for position self.theta = numpy.zeros(nphot) # initial up-down angle for position self.alpha = rng.uniform( 0, 2 * pi, size=nphot ) # initial left-right direction for direction -- value does not matter due to symmetry #mu = numpy.linspace(-1, 1, nphot) # uniform distribution mu = rng.uniform(-1, 1, size=nphot) self.beta = acos(mu) # up-down angle for direction # self.beta = acos(numpy.linspace(-cone_in, cone_in, nphot)) # up-down angle for direction self.geometry = geometry energy_lo, energy_hi = bin2energy(i) e = (energy_lo + energy_hi) / 2. if self.verbose: print('PhotonBunch of size %d with energy %.2f keV' % (nphot, e)) #self.energy = e * numpy.ones(nphot) self.energy = rng.uniform(low=energy_lo, high=energy_hi, size=nphot) #bin = energy2bin(self.energy) #assert (bin == i).all(), (bin.min(), bin.max(), self.energy.min(), self.energy.max(), energy_lo, energy_hi, self.energy[bin!=i]) self.bin = i * numpy.ones(nphot, dtype=numpy.uint) self.stuck = self.rad != 0 # False
def incid(d, Rmin, rf, geoh): # interaction / impact costheta_max = d / np.sqrt(d**2 + (Rmin + rf)**2) follow0 = 1 while follow0: follow1 = 1 while follow1: xf = 2 * rf * random.random() - rf yf = 2 * rf * random.random() - rf if xf**2 + yf**2 <= rf**2: follow1 = 0 # x0 = xf y0 = yf theta1 = 1e-10 phi1 = 0 follow2 = 1 while follow2: follow3 = 1 if geoh[0] == "i": while follow3: theta1 = np.acos(1 - random.random() * (1 - costheta_max)) follow3 = 0 phi1 = 2 * np.pi * random.random() x0 = d * np.tan(theta1) * np.cos(phi1) + xf y0 = d * np.tan(theta1) * np.sin(phi1) + yf RA0 = np.sqrt(x0**2 + y0**2) if RA0 <= Rmin: follow2 = 0 follow0 = 0 else: follow2 = 0 z0 = 0 return theta1, phi1, x0, y0, z0
def angles_from_matrix(rot_matrix): if rot_matrix.shape == (2, 2): theta = np.atan2(rot_matrix[1, 0], rot_matrix[0, 0]) return theta, elif rot_matrix.shape == (3, 3): if rot_matrix[2, 2] == 1.: # cannot use last row and column theta = 0. # upper-left block is 2d rotation for phi + psi, so one needs # to be fixed psi = 0. phi = np.atan2(rot_matrix[1, 0], rot_matrix[0, 0]) if phi < 0: phi += 2 * np.pi # in [0, 2pi) else: phi = np.atan2(rot_matrix[0, 2], -rot_matrix[1, 2]) psi = np.atan2(rot_matrix[2, 0], rot_matrix[2, 1]) theta = np.acos(rot_matrix[2, 2]) if phi < 0. or psi < 0.: phi += np.pi psi += np.pi theta = -theta return phi, theta, psi else: raise ValueError('shape of `rot_matrix` must be (2, 2) or (3, 3), ' 'got {}'.format(rot_matrix.shape))
def point2unit_spherical(point): ub = dot(self.axinv,(point-self.origin)) u=zeros((self.DIM,)) u[0] = sqrt(ub[0]*ub[0]+ub[1]*ub[1]+ub[2]*ub[2]) u[1] = atan2(ub[1],ub[0])*o2pi+.5 u[2] = acos(ub[2]/u[0])*o2pi*2.0 return u
def develop(self): """ Develop the 3D shape into 2D """ return ## Every flat generatrice is 2 2D points flatgen = np.zeros((n_gen, 2, 2)) flatgen[0,0] = np.zeros(2) flatgen[0,1] = np.array([0, length(self.gen[0])]) ## 1st generatrice is already in same plane as 0st u1 = self.support[1] - self.support[0] c = cos(self.gen[1], u1) s = cos(self.gen[1], u1) d1 = np.array(length(u1)*s + length(u1)*c) flatgen[1,0] = flatgen[0,0] + d1 for i in np.range(1, n_gen): ## v is rotation axis v = self.gen[i] u1 = self.support[i] - self.support[i-1] u2 = self.support[i] + self.gen[i] - self.support[i-1] - self.gen[i-1] ## Pick the best triangle for reference plane c1 = np.cross(u1, v) c2 = np.cross(v, u2) if length(c1) > length(c2): u = u1 else: u = u2 ## Compute angle between gen and v c = cos(self.gen[i+1], v) alpha = np.acos(c) ## alpha is preserved in rotation, such as length of gen return self
def SunPositionLocalNoon(DoY, longitude, latitude): """ Original code provided by: Jose Luis Gomez-Dans https://gist.github.com/733741 Modified by: Gerardo Lopez-Saldana Calculates the position of the sun given a position at local solar noon. Basically, all you need to know is here: http://answers.google.com/answers/threadview/id/782886.html """ import time from numpy import sin from numpy import cos from numpy import degrees from numpy import radians from numpy import arccos as acos from numpy import deg2rad #from math import sin, cos, degrees, radians, acos #DoY = int ( time.strftime( "%j", time.strptime( date, "%Y-%m-%d" ) ) ) latitude = deg2rad(latitude) #longitude = deg2rad ( longitude ) # Calculate Local Solar Time LST n = numpy.round(DoY - 2451545 - 0.0009 - (longitude / 360.)) J = 2451545. + 0.0009 + (longitude / 360.) + n J = (J - JulianDay) * 60 #EoT M = (2 * numpy.pi * JulianDay) / 365.242 EoT = -7.655 * numpy.sin(M) + 9.873 * numpy.sin(2 * M + 3.588) TimeZone = 0 LST = (720 - 4 * longitude - EoT + TimeZone * 60) / 1440 longitude = deg2rad(longitude) #LST_hours = int(LST*24.0) #LST_mins = int((LST*24.0 - LST_hours) * 60.) #LST_secs = (((LST*24.0 - LST_hours) * 60.) - LST_mins) * 60. #print "LST:", str(LST_hours), str(LST_mins), str(LST_secs) #( hh, mm ) = hour.split(":") #h = float(hh) #h = h + float(mm)/60. # To emulate MODIS products, set fixed LST = 12.00 LST[:, :] = 12.0 ##Now we can calculate the Sun Zenith Angle (SZA): h = (12.0 - (LST)) / 12.0 * numpy.pi delta = -23.45 * (numpy.pi / 180.0) * cos(2 * numpy.pi / 365.0 * (DoY + 10)) SZA = degrees( acos(sin(latitude) * sin(delta) + cos(latitude) * cos(delta) * cos(h))) return (SZA, LST * 24)
def beta(self,m1,d,g=1.4,i=0): p=-(m1*m1+2.)/m1/m1-g*np.sin(d)*np.sin(d) q=(2.*m1*m1+1.)/ np.pow(m1,4.)+((g+1.)*(g+1.)/4.+ (g-1.)/m1/m1)*np.sin(d)*np.sin(d) r=-np.cos(d)*np.cos(d)/np.pow(m1,4.) a=(3.*q-p*p)/3. b=(2.*p*p*p-9.*p*q+27.*r)/27. test=b*b/4.+a*a*a/27. if (test>0.0): return -1.0 elif (test==0.0): x1=np.sqrt(-a/3.) x2=x1 x3=2.*x1 if(b>0.0): x1*=-1. x2*=-1. x3*=-1. if(test<0.0): phi=np.acos(np.sqrt(-27.*b*b/4./a/a/a)) x1=2.*np.sqrt(-a/3.)*np.cos(phi/3.) x2=2.*np.sqrt(-a/3.)*np.cos(phi/3.+np.pi*2./3.) x3=2.*np.sqrt(-a/3.)*np.cos(phi/3.+np.pi*4./3.) if(b>0.0): x1*=-1. x2*=-1. x3*=-1. s1=x1-p/3. s2=x2-p/3. s3=x3-p/3. if(s1<s2 and s1<s3): t1=s2 t2=s3 elif(s2<s1 and s2<s3): t1=s1 t2=s3 else: t1=s1 t2=s2 b1=np.asin(np.sqrt(t1)) b2=np.asin(np.sqrt(t2)) betas=b1 betaw=b2 if(b2>b1): betas=b2 betaw=b1 if(i==0): return betaw if(i==1): return betas
def angle_to(self, other): """computes the angle between two vectors cos theta = (n * m) / (n.length * m.length) """ arc = self.dot(other) / self.length / other.length if abs(arc - 1) <= 1e-6 or abs(arc + 1) <= 1e-6: arc = 1 return np.acos(arc)
def x_to_th(self, x): """Returns the angle on position for a given x coordinate""" if not x_in_workspace(): raise Arm_Exception('X not in Workspace') X_e = x[2] Y_e = x[1] Phi_e = x[0] Y_c = Y_e - l[2] * np.sin(Phi_e) X_c = X_e - l[2] * np.cos(Phi_e) alpha = np.atan2(Y_c, X_c) r = (X_c**2 + Y_c**2)**0.5 beta = np.acos((l[0]**2 + l[1]**2 - r**2) / (2 * l[0] * l[1])) gamma = np.acos((l[0]**2 + r**2 - l[1]**2) / (2 * l[0] * r)) th0 = alpha - gamma th1 = np.pi - beta th2 = Phi_e - th0 - th1 return np.array([th0, th1, th2])
def oneToS(self, x, y): if 'width' in self.params.keys(): d = self.params['width'] else: d = 1.0 return np.acos(1.0 - 2. * x / d) / np.pi
def oneToT(self, x, y): if 'height' in self.params.keys(): d = self.params['height'] else: d = 1.0 return np.acos(1.0 - 2. * y / d) / np.pi
def evaluate(self, xOrig): """ Calculates and returns RV curve according to current model parameters. .. note:: The units of the model RV curve are **stellar-radii per second**. Parameters ---------- xOrig : array The time stamps at which to calculate the model RV curve. Note that the orbit period and central transit time are used to convert time into "true anomaly". """ x = self.trueAnomaly(xOrig) Xp = self.Xp(x) Zp = self.Zp(x) rho = self.rho(Xp, Zp) etap = self.etap(Xp, Zp) zeta = self.zeta(etap) x0 = self.x0(etap) xc = self.xc(zeta, x0) # dphase is the phase difference between the primary transit and the time points # It is used to exclude the secondary transit from the calculations dphase = numpy.abs((xOrig-self["T0"])/self["P"]) dphase = numpy.minimum( dphase-numpy.floor(dphase), numpy.abs(dphase-numpy.floor(dphase)-1)) y = numpy.zeros(len(x)) indi = numpy.where(numpy.logical_and(rho < (1.0-self["gamma"]), dphase < 0.25))[0] y[indi] = Xp[indi]*self["Omega"]*sin(self["Is"])* self["gamma"]**2 * \ (1.0 - self["epsilon"]*(1.0 - self.W2(rho[indi]))) / \ (1.0 - self["gamma"]**2 - self["epsilon"]*(1./3. - self["gamma"]**2*(1.0-self.W1(rho[indi])))) indi = numpy.where(numpy.logical_and( \ numpy.logical_and(rho >= 1.-self["gamma"], rho < 1.0+self["gamma"]), dphase < 0.25))[0] z0 = self.z0(etap, indi) y[indi] = (Xp[indi]*self["Omega"]*sin(self["Is"])*( \ (1.0-self["epsilon"]) * (-z0[indi]*zeta[indi] + self["gamma"]**2*acos(zeta[indi]/self["gamma"])) + \ (self["epsilon"]/(1.0+etap[indi]))*self.W4(x0[indi], zeta[indi], xc[indi], etap[indi]))) / \ (pi*(1.-1.0/3.0*self["epsilon"]) - (1.0-self["epsilon"]) * (asin(z0[indi])-(1.+etap[indi])*z0[indi] + \ self["gamma"]**2*acos(zeta[indi]/self["gamma"])) - self["epsilon"]*self.W3(x0[indi], zeta[indi], xc[indi], etap[indi])) return y
def SunPositionLocalNoon ( DoY, longitude, latitude ): """ Original code provided by: Jose Luis Gomez-Dans https://gist.github.com/733741 Modified by: Gerardo Lopez-Saldana Calculates the position of the sun given a position at local solar noon. Basically, all you need to know is here: http://answers.google.com/answers/threadview/id/782886.html """ import time from numpy import sin from numpy import cos from numpy import degrees from numpy import radians from numpy import arccos as acos from numpy import deg2rad #from math import sin, cos, degrees, radians, acos #DoY = int ( time.strftime( "%j", time.strptime( date, "%Y-%m-%d" ) ) ) latitude = deg2rad ( latitude ) #longitude = deg2rad ( longitude ) # Calculate Local Solar Time LST n = numpy.round(DoY - 2451545 - 0.0009 - (longitude / 360.)) J = 2451545. + 0.0009 + (longitude / 360.) + n J = (J - JulianDay) * 60 #EoT M = (2*numpy.pi*JulianDay)/365.242 EoT = -7.655 * numpy.sin(M) + 9.873*numpy.sin(2*M + 3.588) TimeZone = 0 LST = (720-4*longitude-EoT+TimeZone*60)/1440 longitude = deg2rad ( longitude ) #LST_hours = int(LST*24.0) #LST_mins = int((LST*24.0 - LST_hours) * 60.) #LST_secs = (((LST*24.0 - LST_hours) * 60.) - LST_mins) * 60. #print "LST:", str(LST_hours), str(LST_mins), str(LST_secs) #( hh, mm ) = hour.split(":") #h = float(hh) #h = h + float(mm)/60. # To emulate MODIS products, set fixed LST = 12.00 LST[:,:] = 12.0 ##Now we can calculate the Sun Zenith Angle (SZA): h = (12.0 - (LST)) / 12.0 * numpy.pi delta = -23.45 * (numpy.pi/180.0) * cos (2 * numpy.pi/365.0 * (DoY+10)) SZA = degrees( acos(sin(latitude) * sin(delta) + cos(latitude) * cos(delta) * cos(h)) ) return (SZA, LST*24)
def arccos(x): """ A fast version of the periodic function arccosine(x), where x is in radians. """ if x < -1: x = -1 if x > 1: x = 1 return acos(x)
def kepel(r, v): mu = 3.986004415E+14 h = angular_momentum(r, v) n = node_vector(h) ev = eccentricity_vector(r, v, mu) E = specific_orbital_energy(r, v, mu) a = -mu / (2 * E) e = norm(ev) SMALL_NUMBER = 1E-15 # Inclination is the angle between the angular # momentum vector and its z component. i = acos(h.z / norm(h)) if abs(i - 0) < SMALL_NUMBER: # For non-inclined orbits, raan is undefined; # set to zero by convention raan = 0 if abs(e - 0) < SMALL_NUMBER: # For circular orbits, place periapsis # at ascending node by convention arg_pe = 0 else: # Argument of periapsis is the angle between # eccentricity vector and its x component. arg_pe = acos(ev.x / norm(ev)) else: # Right ascension of ascending node is the angle # between the node vector and its x component. raan = acos(n.x / norm(n)) if n.y < 0: raan = 2 * pi - raan # Argument of periapsis is angle between # node and eccentricity vectors. arg_pe = acos(dot(n, ev) / (norm(n) * norm(ev))) if abs(e - 0) < SMALL_NUMBER: if abs(i - 0) < SMALL_NUMBER: # True anomaly is angle between position # vector and its x component. f = acos(r.x / norm(r)) if v.x > 0: f = 2 * pi - f else: # True anomaly is angle between node # vector and position vector. f = acos(dot(n, r) / (norm(n) * norm(r))) if dot(n, v) > 0: f = 2 * pi - f else: if ev.z < 0: arg_pe = 2 * pi - arg_pe # True anomaly is angle between eccentricity # vector and position vector. f = acos(dot(ev, r) / (norm(ev) * norm(r))) if dot(r, v) < 0: f = 2 * pi - f KOE = np.array([a, e, i, raan, arg_pe, f]) return KOE
def acos(*args, **kw): arg0 = args[0] if isinstance(arg0, (int, float, long)): return _math.acos(*args,**kw) elif isinstance(arg0, complex): return _cmath.acos(*args,**kw) elif isinstance(arg0, _sympy.Basic): return _sympy.acos(*args,**kw) else: return _numpy.acos(*args,**kw)
def angle2vecs(vec1, vec2): """angle between two vectors""" # vector a * vector b = |a|*|b|* cos(angle between vector a and vector b) dot = np.dot(vec1, vec2) vec1_modulus = np.sqrt(np.multiply(vec1, vec1).sum()) vec2_modulus = np.sqrt(np.multiply(vec2, vec2).sum()) if (vec1_modulus * vec2_modulus) == 0: cos_angle = 1 else: cos_angle = dot / (vec1_modulus * vec2_modulus) return math.degrees(acos(cos_angle))
def xieta_from_radecl(inra, indecl, incenterra, incenterdecl, deg=True): '''This returns the image-plane projected xi-eta coords for inra, indecl. If deg = True, the input angles are assumed to be in degrees and the output is in degrees as well. A center RA and DEC are required. ''' if deg: ra = np.radians(inra) decl = np.radians(indecl) centerra = np.radians(incenterra) centerdecl = np.radians(incenterdecl) else: ra = inra decl = indecl centerra = incenterra centerdecl = incenterdecl cdecc = np.cos(centerdecl) sdecc = np.sin(centerdecl) crac = np.cos(centerra) srac = np.sin(centerra) uu = np.cos(decl) * np.cos(ra) vv = np.cos(decl) * np.sin(ra) ww = np.sin(decl) uun = uu * cdecc * crac + vv * cdecc * srac + ww * sdecc vvn = -uu * srac + vv * crac wwn = -uu * sdecc * crac - vv * sdecc * srac + ww * cdecc denom = vvn * vvn + wwn * wwn aunn = np.zeros_like(uun) aunn[uun >= 1.0] = 0.0 aunn[uun < 1.0] = np.acos(uun) xi, eta = np.zeros_like(aunn), np.zeros_like(aunn) xi[(aunn <= 0.0) | (denom <= 0.0)] = 0.0 eta[(aunn <= 0.0) | (denom <= 0.0)] = 0.0 sdenom = np.sqrt(denom) xi[(aunn > 0.0) | (denom > 0.0)] = aunn * vvn / sdenom eta[(aunn > 0.0) | (denom > 0.0)] = aunn * wwn / sdenom if deg: return np.degrees(xi), np.degrees(eta) else: return xi, eta
def calc_to_goal_cost(self, traj, goal): # calc to goal cost. It is 2D norm. goal_magnitude = np.sqrt(goal[0]**2 + goal[1]**2) traj_magnitude = np.sqrt(traj[-1, 0]**2 + traj[-1, 1]**2) dot_product = (goal[0] * traj[-1, 0]) + (goal[1] * traj[-1, 1]) error = dot_product / (goal_magnitude * traj_magnitude) error_angle = np.acos(error) cost = self.to_goal_cost_gain * error_angle return cost
def drawFaces(self, level): glPushMatrix() glRotatef(180, 0, 0, 1) # let these be the upper face of pyramid glRotatef(acos(1.0/3.0)*(180.0/pi), 1,0,0) # apply the dihedral angle self.drawKochPyramid(level - 1) glPopMatrix() glPushMatrix() glTranslate(-1,0,0) glRotatef(300, 0, 0, 1) # let these be the upper face of pyramid glRotatef(acos(1.0/3.0)*(180.0/pi), 1,0,0) # apply the dihedral angle self.drawKochPyramid(level - 1) glPopMatrix() glPushMatrix() glTranslate(-1/2.0, -sqrt(3)/2.0, 0) glRotatef(420, 0, 0, 1) # let these be the lower right face of pyramid glRotatef(acos(1.0/3.0)*(180.0/pi), 1,0,0) # apply the dihedral angle self.drawKochPyramid(level - 1) glPopMatrix()
def angle(v1,v2): """ calculates the angle between two vectors. v1 and v2 are numpy.array objects. returns a float containing the angle in radians. """ length_product = norm(v1)*norm(v2) if length_product == 0: raise AngleGeometryError(\ "Cannot calculate angle for vectors with length zero") angle = acos(scalar(v1,v2)/length_product) return angle
def finger_pose_callback(self, msg): self.finger_pose_list = msg a = list(self.finger_pose_list[0]) b = list(self.finger_pose_list[1]) c = [0, 0, 0] A = a - c B = a - b self.finger1_dist_ang = np.pi - np.acos( (A[0] * B[0] + A[1] * B[1] + A[2] * B[2]) / (sqrt(A[0] * A[0] + A[1] * A[1] + A[2] * A[2]) * sqrt(B[0] * B[0] + B[1] * B[1] + B[2] * B[2]))) a = list(self.finger_pose_list[2]) b = list(self.finger_pose_list[3]) c = [0, 0, 0] A = a - c B = a - b self.finger2_dist_ang = np.pi - np.acos( (A[0] * B[0] + A[1] * B[1] + A[2] * B[2]) / (sqrt(A[0] * A[0] + A[1] * A[1] + A[2] * A[2]) * sqrt(B[0] * B[0] + B[1] * B[1] + B[2] * B[2])))
def lp_proximal_mapping(val_norm, amount, p): ## helper function for vector version of soft thresholding for l1 (lp) minimization shrink_factor = np.zeros(val_norm.shape) if p == 1: ## soft thresholding nz = (val_norm > amount) shrink_factor[nz] = (val_norm[nz]-amount) / val_norm[nz] elif p == 1/2: # see eg "Computing the proximity operator of the lp norm..., Chen et al, IET Signal processing, 2016" nz = val_norm > 3/2*(val_norm)**(2/3) shrink_factor[nz] = (2/3*val_norm[nz]*(1+np.cos(2/3*np.acos(-3**(3/2)/4*amount*val_norm[nz]**(-3/2)))))/(val_norm[nz]) else: raise Exception('not implemented!') return shrink_factor
def solution_errors(solution, comparison): c = solution[1] solution = solution[0] wobj = comparison[:,:3] tool = comparison[:,3] tool_err = abs(tool - solution[:,3]) * 1000 wobj_err = abs(wobj - solution[:,:3]) wobjsol2, _ = fit_to_ori(solution[:,:3]) wobj_err22 = abs(wobj - wobjsol2) errors = { 'wobj': { 'norm': norm(wobj_err), 'x_ang': acos(wobj[:,0].dot(normalize(solution[:,0])))*180.0/pi, 'y_ang': acos(wobj[:,1].dot(normalize(solution[:,1])))*180.0/pi, 'n_ang': acos(wobj[:,2].dot(normalize(solution[:,2])))*180.0/pi, 'unit': 'deg' }, 'wobj22': { 'norm': norm(wobj_err22), 'x_ang': acos(wobj[:,0].dot(wobjsol2[:,0]))*180.0/pi, 'y_ang': acos(wobj[:,1].dot(wobjsol2[:,1]))*180.0/pi, 'n_ang': acos(wobj[:,2].dot(wobjsol2[:,2]))*180.0/pi, 'unit': 'deg' }, 'tool': { 'norm': norm(tool_err), 'x': tool_err[0], 'y': tool_err[1], 'z': tool_err[2], 'unit': 'mm' }, 'cond': c } return errors
def kcurv(cont, delta): COEF_MIN = 1.0 / (1.0 * delta) COEF_MAX = 1.0 * delta ret = [] d = 0 j = 0 i = 0 length = cv2.arcLength(cont, False) overlap = int(length) % delta k = (int(length) + overlap) / delta #pad contour with points from the head to be of size k*delta >= length cont = np.append(cont, cont[0:overlap+delta, ...], axis=0) #test_cont(cont) d_table = {(0, 1): 1.0, (1, 0): 1.0, (1, 1): sqrt(2)} ret.append([cont[0][0], 0]) while True: while d < delta and j < len(cont) - 1: dx = abs(cont[j][0][0] - cont[j+1][0][0]) dy = abs(cont[j][0][1] - cont[j+1][0][1]) d += d_table[(dx, dy)] j += 1 ret.append([cont[j][0], 0]) d = 0 i = j if j == len(cont) - 1: break #calculate k-curvature as angle between two adjacent segments l = len(ret) try: ret[0][1] = acos(cos_phi(ret[l-1], ret[0], ret[1])) for i in range(1, l-1): ret[i][1] = acos(cos_phi(ret[i-1], ret[i], ret[i+1])) ret[l-1][1] = acos(cos_phi(ret[l-2], ret[l-1], ret[0])) except Exception, e: print cos_phi(ret[l-1], ret[0], ret[1]) print cos_phi(ret[i-1], ret[i], ret[i+1]) print cos_phi(ret[l-2], ret[l-1], ret[0]) rospy.signal_shutdown('acos error') print e
def quaternion_to_axisangle(quat): data = quat._data sqr_length = sum(np.square(data[1:])) axis = np.zeros(3) if sqr_length > 0: angle = 2.0 * np.acos(data[0]) inv_length = 1.0 / np.sqrt(sqr_length) axis = inv_length * data[1:] else: angle = 0 axis[0] = 1 axis[1] = 0 axis[2] = 0 return axis, angle
def angle(v1, v2): """ computes the angle between two vectors assuming carthesian coordinates Parameters ---------- vec1 : numpy array vec2 : numpy array Returns ------- the angle between vec1 and vec2 as a dimensioned astropy quantity """ return acos(np.clip(v1.dot(v2) / (length(v1) * length(v2)), -1.0, 1.0))
def LSM(inliersList, param): J = np.empty((0, 3), float) # Jacobian matrix (mx3) F = np.empty((0, 1), float) # F matrix (mx1) P = np.empty((3, 1), float) # P matrix (3x1) X = param.reshape( (3, 1) ) # X=[a, b, c] # X의 초기값을 param 값으로 설정 # RANSAC에서 param을 np.array 형태로 받아옴 while True: # 현재의 X 추정값 (a,b,c 추정값)에 대해 J, F를 계산함 for i in inliersList: x = i[0] # x value로 변환 of i번째 inliersList y = i[1] # y value of i번째 inliersList a = X[0, 0] b = X[1, 0] c = X[2, 0] Ja = (a**2 - b * x) / (a**2 * np.sqrt(1 - x**2 / a**2) ) # f를 a로 편미분 Jb = -np.acos(x / a) J = np.append(J, np.array([[Ja, Jb, 1]]), axis=0) fi = a * np.sin(np.acos(x / a)) - b * np.acos(x / a) + c - y F = np.append(F, np.array([[fi]]), axis=0) # P 계산, X 업데이트 P = np.linalg.inv(J.T @ J) @ J.T @ F # @ : 행렬곱 bX = X # 업데이트 전 X X = X - P # X 업데이트 # 역행렬은 정방 행렬 (nxn)에서만 정의됨. J는 정방 행렬 될 수 없음. 따라서 역행렬이 존재하지 않음 # 종료 조건은 x 값의 변화가 거의 없을 때 if all(abs(X - bX) < 0.5): break return X # np.array X를 return
def ASBII(ATcur_P, ATxyz_P, ATxyz_K): """ | X | Astr. Azimuth , Zenith , Slope | Y | ---------------+-------> from P to K distance distance | Z |AT_P | (Apk) (Bpk) (Spk) | | | | | LAT | +--------------- | LON | | | H |AT_P | | X | | | Y | ---------------+ | Z |AT_K """ # given==================================================================== # ATcur_P ----> Cur.Coor. (LAT, LON, H)[3x1] of # ||| Station Point(P) on Avg. Terr. Coor. Sys. # ||| # ||----LAT ----> Astronomic latitude on Avg. Terr. # || Coor. Sys. # || # |-----LON ----> Astronomic longtitude on Avg. Terr. # | Coor. Sys. # | # ----- H ----> Orthometric height on Avg. Terr. # Coor. Sys. # ATxyz_P ----> Car.Coor. (X, Y, Z)[3x1] of # Station Point(P) on Avg. Terr. Coor. Sys. # ATxyz_K ----> Car.Coor. (X, Y, Z)[3x1] of # Obs. Point(K) on Avg. Terr. Coor. Sys. # # asked==================================================================== # Apk ----> Astronomic azimuth # Spk ----> Distance between sta. and obs. point # Bpk ----> Zenith distance # d = ATxyz_K - ATxyz_P Apk = atan( -d[0, 0] * sin(ATcur_P[1, 0].rad) + d[1, 0] * cos(ATcur_P[1, 0].rad), -d[0, 0] * sin(ATcur_P[0, 0].rad) * cos(ATcur_P[1, 0].rad) - d[1, 0] * sin(ATcur_P[0, 0].rad) * sin(ATcur_P[1, 0].rad) + d[2, 0] * cos(ATcur_P[0, 0].rad)) Spk = (d[0, 0]**2 + d[1, 0]**2 + d[2, 0]**2)**.5 Bpk = acos((d[0, 0] * cos(ATcur_P[0, 0].rad) * cos(ATcur_P[1, 0].rad) + d[1, 0] * cos(ATcur_P[0, 0].rad) * sin(ATcur_P[1, 0].rad) + d[2, 0] * sin(ATcur_P[0, 0].rad)) / Spk) return angle(Apk, "rad"), Spk, angle(Bpk, "rad")
def aitoff(lon, lat): """ Make Aitoff map projection. Take traditional longitude and latitude in radians and return a tuple (x, y). Notice that traditionally longitude is in [-pi:pi] from the meridian, and latitude is in [-pi/2:pi/2] from the equator. So, for example, if you would like to make a galactic map projection centered on the galactic center, before passing galactic longitude l to the function you should first do: l = l if l <= numpy.pi else l - 2 * numpy.pi Keyword arguments: lon -- Traditional longitude in radians, in range [-pi:pi] lat -- Traditional latitude in radians, in range [-pi/2:pi/2] """ def sinc(x): # a quick unnormalized sinc function, with discontinuity removed if not x: return 0 else: return numpy.sin(x) / x x = numpy.zeros_like(lon) y = numpy.zeros_like(lat) # check if the input values are in the range if lon > numpy.pi or lon < -numpy.pi or lat > numpy.pi / 2 or \ lat < -numpy.pi / 2: print('Aitoff: Input longitude and latitude out of range.\n') print(' lon: [-pi,pi]; lat: [-pi/2,pi/2].\n') return None # take care of the sigularity at (0, 0), otherwise division by zero may # happen if lon == 0 and lat == 0: return 0.0, 0.0 alpha = numpy.acos(numpy.cos(lat) * numpy.cos(lon / 2.0)) # the sinc function used here is the unnormalized sinc function x = 2.0 * numpy.cos(lat) * numpy.sin(lon / 2.0) / sinc(alpha) y = numpy.sin(lat) / sinc(alpha) return x, y
def angles(self, other): """Return the minimal angles between two quaternion rotations Parameters ---------- other: Quaternion, QuaternionArray The other quaterions to compare to Returns ------- np.ndarray: The calculated angles """ other = arrayCompat(other) return 2 * np.acos(np.einsum("...ij, ...ij -> ...i", self, other))
def generateAngle(self, nnew, emitted_energy, incident_energy): """ Use Moller approximation, or delegate calculation to rsoopic (return result from call to rsoopic function h2crosssections.generateAngle) """ if self.useMollerApproximation: theta = np.empty((nnew)) for i in range(nnew): costheta = emitted_energy[i] * (incident_energy[i] + 2. * self.emassEV) costheta /= incident_energy[i] * (emitted_energy[i] + 2. * self.emassEV) costheta = np.sqrt(costheta) theta[i] = np.acos(costheta) return theta else: return h2crosssections.generateAngle(nnew, emitted_energy, incident_energy)
def fold_P8p(data, costheta_k, costheta_l, phi): theta_k = np.acos(data[costheta_k]) theta_l = np.acos(data[costheta_l]) data[f'{costheta_k}_P8p'] = np.where(theta_l > 0.5 * pi, np.cos(pi - theta_k), data[costheta_k]) data[f'{phi}_P8p'] = np.where(data[phi] > 0.5 * pi, pi - data[phi], data[phi]) data[f'{phi}_P8p'] = np.where(data[f'{phi}_P8p'] < -0.5 * pi, -pi - data[f'{phi}_P8p'], data[f'{phi}_P8p']) data[f'{costheta_l}_P8p'] = np.where(theta_l > 0.5 * pi, np.cos(pi - theta_l), data[costheta_l]) return zfit.Data.from_pandas(data[f'{costheta_l}_P8p', f'{costheta_k}_P8p', f'{phi}_P8p'].copy().rename( index=str, columns={ f'{costheta_l}_P8p': costheta_l, f'{costheta_k}_P8p': costheta_k, f'{phi}_P8p': phi }))
def evaluate(self, xOrig): """ Calculates and returns RV curve according to current model parameters. .. note:: The units of the model RV curve are **stellar-radii per second**. Parameters ---------- xOrig : array The time stamps at which to calculate the model RV curve. Note that the orbit period and central transit time are used to convert time into "true anomaly". """ self._setkepellpars() # In coordinate system with observer in -z axis pos = self._ke.xyzPos(xOrig) # Use coordinate used by Ohta (looking into -y direction) Xp = -pos[::, 0] Zp = pos[::, 1] Yp = pos[::, 2] rho = RmcL.rho(self, Xp, Zp) etap = RmcL.etap(self, Xp, Zp) zeta = RmcL.zeta(self, etap) x0 = RmcL.x0(self, etap) xc = RmcL.xc(self, zeta, x0) # Planet in front of star y = np.zeros_like(xOrig) indi = np.where((Yp < 0) & (rho < (1.0 - self["gamma"])))[0] y[indi] = Xp[indi] * self["Omega"] * sin(self["Is"]) * self["gamma"]**2 * \ (1.0 - self["epsilon"] * (1.0 - RmcL.W2(self, rho[indi]))) / \ (1.0 - self["gamma"]**2 - self["epsilon"] * (1. / 3. - self["gamma"]**2 * (1.0 - RmcL.W1(self, rho[indi])))) indi = np.where((rho >= 1. - self["gamma"]) & (rho < 1.0 + self["gamma"]) & (Yp < 0))[0] z0 = RmcL.z0(self, etap, indi) y[indi] = (Xp[indi] * self["Omega"] * sin(self["Is"]) * ( (1.0 - self["epsilon"]) * (-z0[indi] * zeta[indi] + self["gamma"]**2 * acos(zeta[indi] / self["gamma"])) + (self["epsilon"] / (1.0 + etap[indi])) * RmcL.W4(self, x0[indi], zeta[indi], xc[indi], etap[indi]))) / \ (pi * (1. - 1.0 / 3.0 * self["epsilon"]) - (1.0 - self["epsilon"]) * (asin(z0[indi]) - (1. + etap[indi]) * z0[indi] + self["gamma"]**2 * acos(zeta[indi] / self["gamma"])) - \ self["epsilon"] * RmcL.W3(self, x0[indi], zeta[indi], xc[indi], etap[indi])) return y
def re_orient(self, draw_points): """rotates so that self angle and self velocity are parellel angle is dot product of self direction and self velocity""" if np.asarray(self.velocity).any() and \ np.asarray(self.direction).any() and \ self.fix_orientation: angle = np.acos( self._normalise(self.direction).dot( self._normalise(self.velocity))/( np.linalg.norm(self.direction) * \ np.linalg.norm(self.velocity))) rotation_matrix = self._rotate(angle) self.direction = self._normalise(np.copy(self.velocity)) return [rotation_matrix.dot(point) for point in draw_points] else: return draw_points
def aligned_cylindrical(grid_coords, voxel_size, origin, axis): cartesian = space(grid_coords, voxel_size, origin) # To get theta, we have to construct an 'up', i.e. theta = 0 direction. # We make this up = (0,1,0) - q * axis, with up.axis = 0. # I.e. it's a unit in the y-direction, moved along axis until we're perpendicular # to the axis. # Some straightforward maths gives q = axis_y, if axis is normalised. up = (0,1,0) - axis[1] * axis up /= np.sqrt(np.dot(up, up)) result = np.empty_like(cartesian) result[..., 2] = np.tensordot(cartesian, axis, axes=1) off_axis = cartesian - result[...,2:3] * axis result[..., 0] = (off_axis**2).sum(axis=-1) result[..., 1] = np.acos(np.tensordot(off_axis, up, axes=1) / result[..., 0]) return result
def angle(A,B): # this was really here just for developing the above function a = sqrt(A[0]**2 + A[1]**2) b = sqrt(B[0]**2 + B[1]**2) AdotB = sum( A * B ) T = AdotB / (a*b) Theta1 = np.acos( T ) AXB = A[0]*B[1] - B[0]*A[1] Theta2 = arcsin( AXB / (a*b) ) if Theta2 < 0: Theta = -Theta1 else: Theta = Theta1 return Theta
def solar_zenith(longitude=0,latitude=0, j2000_ott=None): """Zenith Angle, angle between sun and nadir""" if latitude > 90 or latitude < -90: raise ValueError("Latitude out of Bounds: {0}".format(latitude)) if j2000_ott is None: jday_tt = julian_tt() j2000_ott = j2000_offset_tt() ha = hourangle(longitude, j2000_ott) ls = Mars_Ls(j2000_ott) dec = solar_declination(ls)*np.pi/180 cosZ = np.sin(dec) * np.sin(latitude*np.pi/180) + \ np.cos(dec)*np.cos(latitude*np.pi/180.)*np.cos(ha) if use_numpy: Z = np.arccos(cosZ)*180./np.pi else: Z = np.acos(cosZ)*180./np.pi return Z
def rot2axis(rot): """ Converts a 3x3 rotation matrix to axis-angle representation @type rot: 3x3 numpy.ndarray with determinant = 1 @param rot: Rotation matrix @rtype: tuple @return: (e, theta) Axis-angle representation e - (3x1 numpy.ndarray) Rotation axis theta - (float) Angle of rotation in radians """ if not(type(rot) == np.ndarray and rot.shape == (3, 3) and \ np.allclose(np.linalg.det(rot), 1.0)): raise Exception("Invalid argument:\n" + str(rot) + \ "\n" + "Valid types: " + \ "3x3 numpy.array with determinant = 1") D, V = np.linalg.eig(rot) # Eigen decomposition of rotation matrix I1 = np.isclose(np.real(D), 1.) # Indices of eigenvalue with real part = 1 ind = np.argmax(np.sum(np.real(V[:, I1])**2, axis=0)) # Index with best eigenvector I2 = np.array([0, 1, 2]) I = I2[I1][ind] # Index with real part = 1 and best eigenvector u = V[:, I:I+1] # Axis unit vector v = nullspace(u.T) # Vectors perpendicular to u v = v[:, 0:1] # A vector perpendicular to u w = np.cross(u.T, v.T).T # A vector perpendicular to u and v p = min(max(np.asscalar(np.real(np.dot(np.dot(rot, v).T, v))), -1), 1) # Bounded projection of rot*v onto v theta = acos(p) # Angle of rotation acos((rot*v)'*v) sign = np.sign(np.real(np.dot(np.dot(rot, v).T, w))) # Sign of angle (rot*v)'*w if sign != 0: theta = np.asscalar(sign*wrap_to_pi(theta)) if np.all(u < 0): u = -1.*u theta = -1.*theta return (u, theta)
def main(): inFile, outFile, nFrames = getArgs(argv) # define a function that calculates interactions based on LJ potential with cut-offs # Start out with polymers that don't have vapor # thus: cos (theta) = - gamma_sl # Make the interactions function compare interactions between two lists # If the lists are identical, pass just one (use *args to handle this) NDIMS = 3 epsilon = 1 sigma = 1 r_cut = 1.75 cutOffEnergy = 4 * epsilon * ((sigma / r_cut) ** 12 - (sigma / r_cut) ** 6) U_LJ = lambda r: 4 * epsilon * ((sigma / r) ** 12 - (sigma / r) ** 12) - cutOffEnergy with open(outFile, "w") as otp: otp.write("# Youngs law calculation of theta and surface energy\n") with open(inFile, "r") as inp: # For each frame for n in range(nFrames): time, atoms = readFrame(inp) # filter out surface and polymer polymer = atoms[atoms[:, 0] == 1][:, 1:] surface = atoms[atoms[:, 0] == 2][:, 1:] box = makeBox(NDIMS, surface, polymer) # Calculate gamma_sl gamma_sl = interactions(U_LJ, r_cut, box, polymer, surface) # Calculate theta using Young's equation Youngs = lambda x: np.acos(-x) theta = Youngs(gamma_sl) with open(outFile, "a") as otp: np.savetxt(otp, [[time, gamma_sl, theta]], fmt="%d %.5f %.5f\n")
def angle_axis(matrix, unit=None): """ Computes the angle of rotation and the rotation axis for a given rotation matrix. Parameters ---------- matrix : array-like A 3 x 3 unitary rotation matrix. unit : UnitBase The output unit. If `None`, the output unit is degrees. Returns ------- angle : Angle The angle of rotation for this matrix. axis : array (length 3) The axis of rotation for this matrix. """ # TODO: This doesn't handle arrays of angles from numpy import sin, cos, acos, degrees, sqrt m = np.asmatrix(matrix) if m.shape != (3, 3): raise ValueError('matrix is not 3x3') angle = acos((m[0, 0] + m[1, 1] + m[2, 2] - 1) / 2) denom = sqrt(2 * ((m[2, 1] - m[1, 2]) + (m[0, 2] - m[2, 0]) + (m[1, 0] - m[0, 1]))) axis = np.array((m[2, 1] - m[1, 2], m[0, 2] - m[2, 0], m[1, 0] - m[0, 1])) / denom axis /= sqrt(np.sum(axis ** 2)) angle = Angle(angle, u.radian) if unit is None: unit = u.degree return angle.to(unit), axis
def points2domains_spherical(self,points,domains,points_outside): u = zeros((self.DIM,)) iu = zeros((self.DIM,),dtype=int) ndomains=-1 npoints,ndim = points.shape for p in xrange(npoints): ub = dot(self.axinv,(points[p]-self.origin)) u[0] = sqrt(ub[0]*ub[0]+ub[1]*ub[1]+ub[2]*ub[2]) u[1] = atan2(ub[1],ub[0])*o2pi+.5 u[2] = acos(ub[2]/u[0])*o2pi*2.0 if (u>self.umin).all() and (u<self.umax).all(): points_outside[p]=False iu=floor( (u-self.umin)*self.odu ) iu[0] = self.gmap[0][iu[0]] iu[1] = self.gmap[1][iu[1]] iu[2] = self.gmap[2][iu[2]] ndomains+=1 domains[ndomains,0] = p domains[ndomains,1] = dot(self.dm,iu) #end #end ndomains+=1 return ndomains
def xyGaussian(nside,sigx,sigy,moll=False): import healpy as hp import numpy as np import pylab as pl npix = 12l*nside**2 ipix = np.array( range(npix) ) sigx = sigx * np.pi/180. sigy = sigy * np.pi/180. theta, phi = hp.pixelfunc.pix2ang( nside, ipix ) theta = np.pi/2. - theta snd = np.array( phi > np.pi ) phi[snd] = phi[snd] - 2.*np.pi g = np.zeros( npix, dtype='float' ) g = np.exp( -0.5 * ( (theta/sigy)**2 + (phi/sigx)**2 ) ) if moll: hp.mollview(g, fig=1) pl.show() if sigx == sigy: vec0 = np.reshape( hp.pixelfunc.ang2vec( np.pi/2, 0. ), (3) ) vec = np.reshape( hp.pixelfunc.pix2vec( nside, ipix ), (npix,3) ) angdist = np.acos( np.dot(vec, vec0) ) ga = np.exp( -0.5*(angdist/sigx)**2 ) hp.mollview(ga, fig=2) pl.show() return g