Example #1
0
    def rechne(self):
        q = self.q.value()
        T = self.vext.value()*1000.+self.term.value()*(float(self.mout.value())/self.min.value()+q)*1.e6*(self.t.value()/100.+1.)
        a = self.a.value()/1000.
        xi = 30000.*q/T/a**2
        chi = math.sqrt(2.*self.mout.value()*T)/q*math.sqrt(1.660538921e-27 / 1.602176565e-19)

        for  i in range(0,4):
            self.percent[i].setValue(ky[i]/xi*100.)
            self.ast[i].setValue((kx[i]-ky[i])/xi*100.)
            
        if (self.GIC.isChecked()): radius[2] = 1.545
        if (self.TOF.isChecked()): radius[2] = 1.545*30./20.
        if (self.SIG.isChecked()): radius[2] = 1.545*30./(-15.)
        if (self.AFD.isChecked()): radius[2] = -1.545
        
        for i in range(1,4):
            feld = chi/radius[i]
            self.mfeld[i].setValue(feld)
            self.mstrom[i].setValue(self.magnetstrom(i,feld))
        feld = math.sqrt(2.*self.min.value()*self.vext.value()*1000.)*math.sqrt(1.660538921e-27 / 1.602176565e-19)/radius[0]
        self.mfeld[0].setValue(feld)
        self.mstrom[0].setValue(self.magnetstrom(0,feld))
        
        self.espannung[0].setValue(self.vext.value()*.05325/.469)
        self.espannung[1].setValue(T/q*.032/2.816/1000.)
Example #2
0
def simplesnr(f,h,i=None,years=1,noisemodel=None,includewd=None):
    if i == None:
        h0 = h * math.sqrt(16.0/5.0)    # rms average over inclinations
    else:
        h0 = h * math.sqrt((1 + math.cos(i)**2)**2 + (2*math.cos(i))**2)        
    
    return h0 * math.sqrt(years * 365.25*24*3600) / math.sqrt(lisanoise(f,noisemodel,includewd))
Example #3
0
    def legIK(self, X, Y, Z, resolution):
        """ Compute leg servo positions. """
        ans = [0,0,0,0]    # (coxa, femur, tibia)
       
        try:
            # first, make this a 2DOF problem... by solving coxa
            ans[0] = radToServo(atan2(X,Y), resolution)
            trueX = int(sqrt(sq(X)+sq(Y))) - self.L_COXA
            im = int(sqrt(sq(trueX)+sq(Z)))  # length of imaginary leg
            
            # get femur angle above horizon...
            q1 = -atan2(Z,trueX)
            d1 = sq(self.L_FEMUR)-sq(self.L_TIBIA)+sq(im)
            d2 = 2*self.L_FEMUR*im
            q2 = acos(d1/float(d2))
            ans[1] = radToServo(q1+q2, resolution)  
        
            # and tibia angle from femur...
            d1 = sq(self.L_FEMUR)-sq(im)+sq(self.L_TIBIA)
            d2 = 2*self.L_TIBIA*self.L_FEMUR;
            ans[2] = radToServo(acos(d1/float(d2))-1.57, resolution)
        except:
            if self.debug:
                "LegIK FAILED"
            return [1024,1024,1024,0]

        if self.debug:
            print "LegIK:",ans
        return ans
Example #4
0
def sieve(start=start,stop=stop):
  '''
  Given a set of positive integers, remove all integer products of known
  primes, since they are thus not prime.  When p is less than sqrt(stop) + 1,
  then all the remaining integers the current range of integers are prime.
  Recurse until the range containing p_target is processed and return that
  prime.
  start: starting integer
  stop:  ending integer
  '''
  integers = [i for i in xrange(start,stop)]
  if len(primes) == 0:                  # base case
    p = start                           # initial working prime
  else:
    for p in primes:                    # first check primes we know
      if p < int(sqrt(stop) + 1):
        remove_factors(p,integers)
    p = integers[0]                     # first integer left is now prime
  while p < int(sqrt(stop) + 1):        # then sift through the new primes
    remove_factors(p,integers)          # remove all factors of p from integers
    p = integers[integers.index(p) + 1] # next integer in integers is now prime
  primes.extend(integers)               # all remaining integers are primes
  if len(primes) < target:              # need to look for more primes
    sieve(stop,2*stop)                  # look at the next range of integers
  else:                                 # found p_target
    print('The %dst prime is %d' % (target,primes[target + 1]))
def standardMC_european_option(K, T, R, V, S0, N, option_type, path_num=10000):
    dt = T / N
    sigma = V
    drift = math.exp((R - 0.5 * sigma * sigma) * dt)
    sigma_sqrt = sigma * math.sqrt(dt)
    exp_RT = math.exp(-R * T)
    european_payoff = []
    for i in xrange(path_num):
        former = S0
        for j in xrange(int(N)):
            former = former * drift * math.exp(sigma_sqrt * numpy.random.normal(0, 1))
        european_option = former

        if option_type == 1.0:
            european_payoff_call = exp_RT * max(european_option - K, 0)
            european_payoff.append(european_payoff_call)
        elif option_type == 2.0:
            european_payoff_put = exp_RT * max(K - european_option, 0)
            european_payoff.append(european_payoff_put)

    # Standard Monte Carlo
    p_mean = numpy.mean(european_payoff)
    p_std = numpy.std(european_payoff)
    p_confmc = (p_mean - 1.96 * p_std / math.sqrt(path_num), p_mean + 1.96 * p_std / math.sqrt(path_num))
    return p_mean, p_std, p_confmc
Example #6
0
def parmeq(G0, G, GB, w0, Dw):
    beta = math.tan(Dw/2) * math.sqrt(abs(GB**2 - G0**2)) / math.sqrt(abs(G**2 - GB**2))
    #global aeq,beq
    beq = [(G0 + G*beta), -2*G0*math.cos(w0), (G0 - G*beta)]
    beq=   np.array(beq) / (1+beta)
    aeq = np.array([1, -2*math.cos(w0)/(1+beta), (1-beta)/(1+beta)])
    return beq,aeq
Example #7
0
def MoveOffLand(particle, fieldset, time, dt):
    onland = fieldset.LandMask[0, particle.lon, particle.lat, particle.depth]
    if onland == 1:
        oldlon = particle.lon - particle.Ax - particle.Dx - particle.Cx - particle.Vx
        oldlat = particle.lat - particle.Ay - particle.Dy - particle.Cy - particle.Vy
        lat_convert = 1 / 1000. / 1.852 / 60.
        lon_convert = to_lat / math.cos(oldlat*math.pi/180)
        Kfield_new = fieldset.K[time, oldlon, oldlat, particle.depth]
        r_var_new = 1/3.
        Dx_component = math.sqrt(2 * Kfield_new * dt / r_var_new) * lon_convert
        Dy_component = math.sqrt(2 * Kfield_new * dt / r_var_new) * lat_convert
        count = 0
        particle.In_Loop = 0
        while onland > 0:
            #return ErrorCode.ErrorOutOfBounds
            #print("particle on land at %s|%s" % (particle.lon, particle.lat))
            particle.lon -= particle.Dx
            particle.lat -= particle.Dy
            Rx_new = random.uniform(-1., 1.)
            Ry_new = random.uniform(-1., 1.)
            particle.Dx = Dx_component * Rx_new
            particle.Dy = Dy_component * Ry_new
            particle.lon += particle.Dx
            particle.lat += particle.Dy
            onland = fieldset.LandMask[0, particle.lon, particle.lat, particle.depth]
            #print("attempting move to %s|%s" % (particle.lon, particle.lat))
            #print("onland now = %s" % onland)
            count += 1
            particle.In_Loop += 1
            if count > 100:
                particle.lon -= particle.Ax + (particle.Dx + particle.Cx + particle.Vx)# * to_lon
                particle.lat -= particle.Ay + (particle.Dy + particle.Cy + particle.Vy)# * to_lat
                particle.Ax = particle.Ay = particle.Dx = particle.Dy = particle.Cx = particle.Cy = particle.Vx = particle.Vy = 0.0
                onland = 0
Example #8
0
 def _beta_analysis1(stream=None):
     """private function called by beta_analysis()"""
     if stream is None:
         stream=sys.stdout
     q2 = []
     for i in range(1,17):
         q_copy=copy.copy(self)
         q_copy.beta=2**(i/4.0)
         q_copy.dim=250
         q_copy.grain=0.02
         q_copy.recompute()
         q2.append(q_copy)
     na = num.array # shorthand
     t2    = na([q2i.mean() for q2i in q2])
     p2    = na([q2i.pdf_at(t2i) for q2i,t2i in zip(q2,t2)])
     sd2   = na([q2i.sd() for q2i in q2])
     beta2 = na([q2i.beta for q2i in q2])
     i=num.argsort(p2)[-1]
     t=t2[i]
     sd=q2[i].sd()
     p=num.sum(p2)
     betaMean=num.sum(p2*beta2)/p
     betaSd=math.sqrt(num.sum(p2*beta2**2)/p-(num.sum(p2*beta2)/p)**2)
     iBetaMean=num.sum(p2/beta2)/p
     iBetaSd=math.sqrt(num.sum(p2/beta2**2)/p-(num.sum(p2/beta2)/p)**2)
     stream.write('%5.2f	%5.2f	%4.1f	%4.1f	%6.3f\n'%(t,sd,1/iBetaMean,betaSd,self.gamma))
Example #9
0
 def testStudentSampleMultiDimensional(self):
   with self.test_session():
     batch_size = 7
     df = constant_op.constant([[3., 7.]] * batch_size)
     mu = constant_op.constant([[3., -3.]] * batch_size)
     sigma = constant_op.constant([[math.sqrt(10.), math.sqrt(15.)]] *
                                  batch_size)
     df_v = [3., 7.]
     mu_v = [3., -3.]
     sigma_v = [np.sqrt(10.), np.sqrt(15.)]
     n = constant_op.constant(200000)
     student = student_t.StudentT(df=df, loc=mu, scale=sigma)
     samples = student.sample(n, seed=123456)
     sample_values = self.evaluate(samples)
     self.assertEqual(samples.get_shape(), (200000, batch_size, 2))
     self.assertAllClose(
         sample_values[:, 0, 0].mean(), mu_v[0], rtol=1e-2, atol=0)
     self.assertAllClose(
         sample_values[:, 0, 0].var(),
         sigma_v[0]**2 * df_v[0] / (df_v[0] - 2),
         rtol=1e-1,
         atol=0)
     self._checkKLApprox(df_v[0], mu_v[0], sigma_v[0], sample_values[:, 0, 0])
     self.assertAllClose(
         sample_values[:, 0, 1].mean(), mu_v[1], rtol=1e-2, atol=0)
     self.assertAllClose(
         sample_values[:, 0, 1].var(),
         sigma_v[1]**2 * df_v[1] / (df_v[1] - 2),
         rtol=1e-1,
         atol=0)
     self._checkKLApprox(df_v[0], mu_v[0], sigma_v[0], sample_values[:, 0, 1])
 def __init__(self,n_hidden,n_input,n_out,fnc = 'sigmoid',loss_fnc= softmax,batchsize = 10,epochs = 1,learning_rate = 0.1,reg = 0.0,momentum = 0.0):
             
     self.nn = {}
     self.nn['batchsize'] = batchsize
     self.nn['epochs'] = epochs
     self.nn['learning_rate'] = learning_rate
     self.nn['reg'] = reg
     self.nn['momentum'] = momentum
     self.nn['loss_fnc'] = loss_fnc
     self.nn['w1'] = np.random.randn(n_hidden*n_input).reshape(n_input,n_hidden)/math.sqrt(n_hidden*n_input)
     self.nn['b1'] = np.zeros(n_hidden).reshape(n_hidden)
     
     self.nn['w2'] = np.random.random(n_hidden*n_out).reshape(n_hidden,n_out)/math.sqrt(n_hidden*n_out)
     self.nn['b2'] = np.zeros(n_out).reshape(n_out)
     
     self.nn['dw1'] = np.zeros_like(self.nn['w1'])
     self.nn['db1'] = np.zeros_like(self.nn['b1'])
     
     self.nn['dw2'] = np.zeros_like(self.nn['w2'])
     self.nn['db2'] = np.zeros_like(self.nn['b2'])
     
     self.nn['p_dw1'] = self.nn['dw1']
     self.nn['p_db1'] = self.nn['db1']
     
     self.nn['p_dw2'] = self.nn['dw2']
     self.nn['p_db2'] = self.nn['db2']
Example #11
0
File: YAX.py Project: limmb/YAX
	def AzimuthalPointsSelected(self):
		xyinner = self.storedClickCoordinates[0]
		xyouter = self.storedClickCoordinates[1]
		xinner = xyinner[0]
		yinner = xyinner[1]
		xouter = xyouter[0]
		youter = xyouter[1]

		innerxDiff = xinner - self.parameters.centreX
		inneryDiff = yinner - self.parameters.centreY
		outerxDiff = xouter - self.parameters.centreX
		outeryDiff = youter - self.parameters.centreY
		innerCircleDistance = sqrt((innerxDiff * innerxDiff) + (inneryDiff * inneryDiff))
		outerCircleDistance = sqrt((outerxDiff * outerxDiff) + (outeryDiff * outeryDiff))
		innerOvalx1 = self.parameters.centreX - innerCircleDistance
		innerOvaly1 = self.parameters.centreY - innerCircleDistance
		innerOvalx2 = self.parameters.centreX + innerCircleDistance
		innerOvaly2 = self.parameters.centreY + innerCircleDistance
		outerOvalx1 = self.parameters.centreX - outerCircleDistance
		outerOvaly1 = self.parameters.centreY - outerCircleDistance
		outerOvalx2 = self.parameters.centreX + outerCircleDistance
		outerOvaly2 = self.parameters.centreY + outerCircleDistance

		Rad1 = sqrt(((xinner - self.parameters.centreX) * (xinner - self.parameters.centreX)) + ((yinner - self.parameters.centreY) * (yinner - self.parameters.centreY)))
		Rad2 = sqrt(((xouter - self.parameters.centreX) * (xouter - self.parameters.centreX)) + ((youter - self.parameters.centreY) * (youter - self.parameters.centreY)))
		self.parameters.outerCircleRadians = int(round(max(Rad1, Rad2)))
		self.parameters.innerCircleRadians = int(round(min(Rad1, Rad2)))

		self.AzimuthalIntegrationSetupWindow()
		self.clicksStoring = 2
		self.ResetMainImageFrame()
		self.mainImageCanvas.create_oval(innerOvalx1, innerOvaly1, innerOvalx2, innerOvaly2, width = 3, outline = "red")
		self.mainImageCanvas.create_oval(outerOvalx1, outerOvaly1, outerOvalx2, outerOvaly2, width = 3, outline = "red")
def relbreit(x,par):
   a = x[0]**2. - par[1]**2.
   b = par[1]*par[2]
   c = par[1]*math.sqrt(par[1]**2.+par[2]**2.)
   d = (2*math.sqrt(2)/math.pi)*(par[1]*par[2]*c)
   e = d/math.sqrt(par[1]**2.+c)
   return par[0]*e/(a**2. + b**2.)
def esfericaCoordenada(x, y, z):
    from math import atan, sqrt, pi
    r=sqrt(x**2+y**2+z**2)
    if z>0:
        phi=atan(sqrt(x**2+y**2)/z)
    elif z=0:
        phi= pi/2
Example #14
0
def avgQ(qx,qy,h):
	nx,ny = h.shape[0], h.shape[1]
	tx,ty = ida.tipcoord(h)
	ch=[]
	lp=0
	Q = np.zeros(tx)
	for x in range(tx):
		vec = h[x,:]
		ch.append([x for i in vec if i>2.0])
		if(np.size(ch[x])==ny):
			lp=x
	#ch = np.array(ch)
	for x in range(tx):
		for y in range(ny):
			if x <= lp:
				Q[x] += (math.sqrt((qx[x][y]**2.0+qy[x][y]**2.0)))/ny
				#Q[x] += p[x][y]/ny
			else:
				break
	for x in range(lp+1,tx):
		for y in range(ty-200,ty+200):
				if h[x][y] > 2.0:
					Q[x] += (math.sqrt((qx[x][y]**2.0+qy[x][y]**2.0)))#/np.size(ch[x])
				#	Q[x] += p[x][y]/np.size(ch[x])
	#plt.plot(Q)
	#plt.show()
	return Q
Example #15
0
def _bezierpolyrange(x0, x1, x2, x3):
    tc = [0, 1]

    a = x3 - 3*x2 + 3*x1 - x0
    b = 2*x0 - 4*x1 + 2*x2
    c = x1 - x0

    s = b*b - 4*a*c
    if s >= 0:
        if b >= 0:
            q = -0.5*(b+math.sqrt(s))
        else:
            q = -0.5*(b-math.sqrt(s))

        try:
            t = q*1.0/a
        except ZeroDivisionError:
            pass
        else:
            if 0 < t < 1:
                tc.append(t)

        try:
            t = c*1.0/q
        except ZeroDivisionError:
            pass
        else:
            if 0 < t < 1:
                tc.append(t)

    p = [(((a*t + 1.5*b)*t + 3*c)*t + x0) for t in tc]

    return min(*p), max(*p)
Example #16
0
  def testStudentLogPDFMultidimensional(self):
    with self.test_session():
      batch_size = 6
      df = constant_op.constant([[1.5, 7.2]] * batch_size)
      mu = constant_op.constant([[3., -3.]] * batch_size)
      sigma = constant_op.constant([[-math.sqrt(10.), math.sqrt(15.)]] *
                                   batch_size)
      df_v = np.array([1.5, 7.2])
      mu_v = np.array([3., -3.])
      sigma_v = np.array([np.sqrt(10.), np.sqrt(15.)])
      t = np.array([[-2.5, 2.5, 4., 0., -1., 2.]], dtype=np.float32).T
      student = student_t.StudentT(df, loc=mu, scale=sigma)
      log_pdf = student.log_prob(t)
      log_pdf_values = self.evaluate(log_pdf)
      self.assertEqual(log_pdf.get_shape(), (6, 2))
      pdf = student.prob(t)
      pdf_values = self.evaluate(pdf)
      self.assertEqual(pdf.get_shape(), (6, 2))

      if not stats:
        return
      expected_log_pdf = stats.t.logpdf(t, df_v, loc=mu_v, scale=sigma_v)
      expected_pdf = stats.t.pdf(t, df_v, loc=mu_v, scale=sigma_v)
      self.assertAllClose(expected_log_pdf, log_pdf_values)
      self.assertAllClose(np.log(expected_pdf), log_pdf_values)
      self.assertAllClose(expected_pdf, pdf_values)
      self.assertAllClose(np.exp(expected_log_pdf), pdf_values)
def relIsoMethod(histogramForEstimation, function='expo',
                   fitRange=(0.3, 1.6), signalRegion=(0., 0.1)):
    
    histogramForEstimation = histogramForEstimation.Clone('tmp')
    
    #investigate them
    binWidthOfOriginalHistoram = 0.01
    rebinOfOriginalHistogram = 10

    estimate = 0
    relativeErrorSquared = 0
    histogramForEstimation.Rebin(rebinOfOriginalHistogram)

    fit = None
    fit = performFit(histogramForEstimation, function, fitRange)
    if fit:
        estimate = fit.Integral(signalRegion[0], signalRegion[1]) / (binWidthOfOriginalHistoram * rebinOfOriginalHistogram)
        for parErr in range(0, fit.GetNumberFreeParameters()):
            par = fit.GetParameter(parErr)
            err = fit.GetParError(parErr)
            if not par == 0:
                relativeErrorSquared += (err / par) ** 2
                
    result = {'estimate': estimate,
              'absoluteError':sqrt(relativeErrorSquared) * estimate,
              'relativeError':sqrt(relativeErrorSquared),
              'fit':fit}
    return result
Example #18
0
def average_data(data):
    """
    Find mean and std. deviation of data returned by ``simulate``.
    """
    numnodes = data['nodes']
    its = data['its']
    its_mean = numpy.average(its)
    its_std = math.sqrt(numpy.var(its))
    dead = data['dead']
    dead_mean = 100.0*numpy.average(dead)/numnodes
    dead_std = 100.0*math.sqrt(numpy.var(dead))/numnodes
    immune = data['immune']
    immune_mean = 100.0*numpy.average(immune)/numnodes
    immune_std = 100.0*math.sqrt(numpy.var(immune))/numnodes
    max_contam = data['max_contam']
    max_contam_mean = 100.0*numpy.average(max_contam)/numnodes
    max_contam_std = 100.0*math.sqrt(numpy.var(max_contam))/numnodes
    normal = data['normal']
    normal_mean = 100.0*numpy.average(normal)/numnodes
    normal_std = 100.0*math.sqrt(numpy.var(normal))/numnodes
    return {'its': (its_mean, its_std),
            'nodes': numnodes,
            'dead': (dead_mean, dead_std),
            'immune': (immune_mean, immune_std),
            'max_contam': (max_contam_mean, max_contam_std),
            'normal': (normal_mean, normal_std)}
Example #19
0
def LagrangianDiffusion(particle, fieldset, time, dt):
    if particle.active == 1:
        to_lat = 1 / 1000. / 1.852 / 60.
        to_lon = to_lat / math.cos(particle.lat*math.pi/180)
        r_var = 1/3.
        #Rx = np.random.uniform(-1., 1.)
        #Ry = np.random.uniform(-1., 1.)
        Rx = random.uniform(-1., 1.)
        Ry = random.uniform(-1., 1.)
        #dK  = RK4(fieldset.dK_dx, fieldset.dK_dy, particle.lon, particle.lat, time, dt)
        dKdx, dKdy = (fieldset.dK_dx[time, particle.lon, particle.lat, particle.depth], fieldset.dK_dy[time, particle.lon, particle.lat, particle.depth])
        #half_dx = 0.5 * dKdx * dt * to_lon
        #half_dy = 0.5 * dKdy * dt * to_lat
        #print(particle.lon + half_dx)
        #print(particle.lat + half_dy)
        #K = RK4(fieldset.K, fieldset.K, particle.lon + half_dx, particle.lat + half_dy, time, dt)
        Kfield = fieldset.K[time, particle.lon, particle.lat, particle.depth]
        Rx_component = Rx * math.sqrt(2 * Kfield * dt / r_var) * to_lon
        Ry_component = Ry * math.sqrt(2 * Kfield * dt / r_var) * to_lat
        CorrectionX = dKdx * dt * to_lon
        CorrectionY = dKdy * dt * to_lat
        #print(Rx_component)
        #print(Ry_component)
        Dx = Rx_component
        Dy = Ry_component
        Cx = CorrectionX
        Cy = CorrectionY
Example #20
0
 def __init__(self, shape, degree):
     quadrature.Quadrature.__init__(self)
     if shape == "line":
         if degree <= 1:
             self._quadrature_data = [
                 quadrature.QPData(Point(0.0, index=0), 2.0)
             ]
         elif degree <= 3:
             self._quadrature_data = [
                 quadrature.QPData(Point(-sqrt(1/3), index=0), 1.0),
                 quadrature.QPData(Point(sqrt(1/3), index=1), 1.0)
             ]
         elif degree <= 5:
             self._quadrature_data = [
                 quadrature.QPData(Point(-sqrt(3/5), index=0),
                                   5/9),
                 quadrature.QPData(Point(0.0, index=1),
                                   8/9),
                 quadrature.QPData(Point(sqrt(3/5), index=2),
                                   5/9)
             ]
         else:
             raise Exception("Gauss quadrature not implemented for degree \"{0:d}\"".format(degree))
     else:
         raise Exception("Gauss quadrature not implemented for shape \"{0:s}\"".format(shape))
Example #21
0
def InAnscombeTrans(imdata, opt = 'exact'):
    """ The Inverse Anscombe Transform function.

    Parameters
    ----------
    imdata: numpy array
        The input image array
    opt: str
        The options for inverse transform. Default set as 'asymptotic'.
    """

    imdata = np.float32(imdata)
    if opt == 'algebra':
        z = imdata*imdata/4 - 3/8
        
    if opt == 'asymptotic':
        z = imdata*imdata/4 - 1/8

    if opt == 'exact':
        z = imdata*imdata/4 + math.sqrt(3/2)/imdata/4 - 11/8/(imdata*imdata) + \
            5/8*math.sqrt(3/2)/(imdata*imdata*imdata) - 1/8
        z = np.maximum(z, np.zeros(imdata.shape, dtype=np.float32))

    if opt == 'MMSE':
        print 'sth'
        
    return np.uint16(z)   
Example #22
0
def generate(data):
    m = random.choice([3, 1.4, 1.6, 1.8])
    h = random.choice([4, 12, 14, 16])
    d = 1.5*h
    g = 9.8 
    v0xmin = d*math.sqrt(g/(2*h))
    v0x = round(random.choice([4, v0xmin*1.4, v0xmin*1.6, v0xmin*1.8]), 3)

    data["params"]["m"] = m
    data["params"]["h"] = h
    data["params"]["d"] = d
    data["params"]["v0x"] = v0x

    t = d/v0x

    data["params"]["t_c"] = round(t, 3)
    data["params"]["t_x1"] = round(math.sqrt(2*h/g), 3)
    data["params"]["t_x2"] = round(v0x*2/g, 3)

    v0y = 0.5*g*t - h/t

    data["params"]["vy_c"] = round(v0y, 2)
    data["params"]["vy_x1"] = round(-math.sqrt((g*t)**2 + v0x**2/2), 2)
    data["params"]["vy_x2"] = round( -0.5*g*t - h/2, 2)
    data["params"]["vy_x3"] = round(-math.sqrt(v0x**2 + v0y**2), 2)
    data["params"]["vy_x4"] = 0
Example #23
0
def cosine_sim(util, id1, id2, th=3):
    num = 0
        
    # get items util[id1] and util[id2] share in common
    shared = set(util[id1].keys()).intersection(util[id2].keys())

    # optimization to not compute similarity between items
    # that don't meet threshold
    if len(shared) < th:
        return (0.0, len(shared))
    firstmag = 0 
    secondmag = 0
    # calculate dot product and magnitudes of shared items
    for item in shared:
        num += util[id1][item] * util[id2][item]
        firstmag += util[id1][item]**2
        secondmag += util[id2][item]**2

    # prevent denom == 0
    firstmag = 1 if firstmag == 0 else firstmag
    secondmag = 1 if secondmag == 0 else secondmag
    # calculate magnitude of shared items in util[id2]
    denom = math.sqrt(firstmag) * math.sqrt(secondmag)

    return ((num/denom+1)/2, len(shared))
def estimateBIsochrone(R,z,pot=None):
    """
    NAME:
       estimateBIsochrone
    PURPOSE:
       Estimate a good value for the scale of the isochrone potential by matching the slope of the rotation curve
    INPUT:
       R,z = coordinates (if these are arrays, the median estimated delta is returned, i.e., if this is an orbit)
       pot= Potential instance or list thereof
    OUTPUT:
       b if 1 R,Z given
       bmin,bmedian,bmax if multiple R given       
    HISTORY:
       2013-09-12 - Written - Bovy (IAS)
    """
    if pot is None: #pragma: no cover
        raise IOError("pot= needs to be set to a Potential instance or list thereof")
    if isinstance(R,nu.ndarray):
        bs= nu.array([estimateBIsochrone(R[ii],z[ii],pot=pot) for ii in range(len(R))])
        return (nu.amin(bs[True-nu.isnan(bs)]),
                nu.median(bs[True-nu.isnan(bs)]),
                nu.amax(bs[True-nu.isnan(bs)]))
    else:
        r2= R**2.+z**2
        r= math.sqrt(r2)
        dlvcdlr= dvcircdR(pot,r)/vcirc(pot,r)*r
        try:
            b= optimize.brentq(lambda x: dlvcdlr-(x/math.sqrt(r2+x**2.)-0.5*r2/(r2+x**2.)),
                               0.01,100.)
        except: #pragma: no cover
            b= nu.nan
        return b
Example #25
0
def cal_delta_X10811(X):
    #X为条纹位置数组
    #计算δx 
    global DELTA_X,UA_10DELTA_X,UB_10DELTA_X,U_10DELTA_X,U_DELTA_X
    sum=0
    for x in range(len(X)/2):
        sum+=X[x+len(X)/2]-X[x]
        delta_x=sum/(len(X)/2)**2
    #大写常量作为格式化后要打印在tex文件里的数
    DELTA_X = ToScience(delta_x)
    #计算不确定度
    sum=0 
    for x in range(len(X)/2):
        sum+=(10*(X[x+len(X)/2]-X[x])-10*delta_x)**2
    ua_10delta_x=math.sqrt(sum/(len(X)*(len(X)-1)))
    ub_10delta_x=0.01/(2*math.sqrt(3))
    u_delta_x=math.sqrt(ua_10delta_x**2+ub_10delta_x**2)/1000
    
    UA_10DELTA_X = ToScience(ua_10delta_x)

    UB_10DELTA_X = ToScience(ub_10delta_x)

    u_10delta_x = math.sqrt(ua_10delta_x**2+ub_10delta_x**2)
    U_10DELTA_X = ToScience(u_10delta_x)

    u_delta_x= u_10delta_x /10
    U_DELTA_X = ToScience(u_delta_x)
    #delta_x为条纹间距
    #u_delta_x为δx的不确定度
    return delta_x,u_delta_x
def test_vec_to_sym_matrix():
    # Check error if unsuitable size
    vec = np.ones(31)
    assert_raises_regex(ValueError, 'Vector of unsuitable shape',
                        vec_to_sym_matrix, vec)

    # Check error if given diagonal shape incompatible with vec
    vec = np.ones(3)
    diagonal = np.zeros(4)
    assert_raises_regex(ValueError, 'incompatible with vector',
                        vec_to_sym_matrix, vec, diagonal)

    # Check output value is correct
    vec = np.ones(6, )
    sym = np.array([[sqrt(2), 1., 1.], [1., sqrt(2), 1.],
                    [1., 1., sqrt(2)]])
    assert_array_almost_equal(vec_to_sym_matrix(vec), sym)

    # Check output value is correct with seperate diagonal
    vec = np.ones(3, )
    diagonal = np.ones(3)
    assert_array_almost_equal(vec_to_sym_matrix(vec, diagonal=diagonal), sym)

    # Check vec_to_sym_matrix is the inverse function of sym_matrix_to_vec
    # when diagonal is included
    assert_array_almost_equal(vec_to_sym_matrix(sym_matrix_to_vec(sym)), sym)

    # when diagonal is discarded
    vec = sym_matrix_to_vec(sym, discard_diagonal=True)
    diagonal = np.diagonal(sym) / sqrt(2)
    assert_array_almost_equal(vec_to_sym_matrix(vec, diagonal=diagonal), sym)
Example #27
0
def test_executer():
    f = Feuille()
    o = f.objets
    f.executer("A = (1, 2)")
    f.executer("A.x += 1")
    assert(o.A.x == 2)
    f.executer("A' = 3, 4")
    f.executer("s = [A A']")
    f.executer("I = Milieu(s)")
    assertAlmostEqual(o.I.xy, (2.5, 3))
    f.executer("del")
    assert("I" not in o.noms)
    assert("A_prime" in o.noms)
    f.executer("del")
    f.executer("del")
    assert("A_prime" not in o.noms)
    f.executer("= (1, 2)")
    assert(o.M1.coordonnees == (1, 2))
    f.executer("txt0 = `Bonjour !`")
    f.executer(r"txt1 = `$P\`ere et m\`ere ont un accent grave.$`")
    f.executer("chaine_vide = ``")
    assert(o.txt0.texte == "Bonjour !")
    assert(o.txt1.texte == r"$P\`ere et m\`ere ont un accent grave.$")
    assert(o.chaine_vide.texte == "")
    f.executer("M = (5, 7)")
    f.executer("C = _")
    assert(o.C.x == 5)
    f.executer("=((i,sqrt(i)) for i in (3,4,5,6))")
    assert(o.M2.xy == (3, sqrt(3)))
    assert(o.M3.xy == (4, sqrt(4)))
    assert(o.M4.xy == (5, sqrt(5)))
    assert(o.M5.xy == (6, sqrt(6)))
 def reviseDistance(self, currentDistance, currentCount):
     if currentCount <= 0:
         return self.maxDistance
     newDistance = float(currentDistance) * math.sqrt(self.targetCount) / math.sqrt(currentCount)
     if newDistance > self.maxDistance:
         return self.maxDistance
     return newDistance
Example #29
0
 def gao(n):  
     m = int(math.sqrt(n))  
     if m * m == n:  
         return 0 
     ha = 1; ka = 0
     d = m  
     a = n  
     b = -m  
     c = 1
     hb = d; kb = 1
     if hb * hb - n * kb * kb == 1:
         return hb
     while True:  
         nc =  a - b * b  
         nc /= c  
         nd = int((math.sqrt(a) - b) / nc)  
         nb = -b - nd * nc
         c = nc; d = nd; b = nb;
         hc = d * hb + ha
         kc = d * kb + ka
         ha = hb
         ka = kb
         hb = hc
         kb = kc
         if hc * hc - n * kc * kc == 1:
             return hc
     return 0
Example #30
0
	def update(self, p1x, p1y, p2x, p2y, width, height, mat = 0):
		'''Update the quaterion with a new rotation position derived
		   from the first point (p1) and the second point (p2).  The
		   the mat parameter is not currently used.'''
		
		if p1x == p2x and p1y == p2y:
			self.quat = quaternion(1, 0, 0, 0)
		else:
			# First, figure out z-coordinates for projection of p1 and p2 to
			# deformed sphere
			p1x_u = self.scale*p1x/width - 1.0
			p1y_u = 1.0 - self.scale*p1y/height
			p2x_u = self.scale*p2x/width - 1.0
			p2y_u = 1.0 - self.scale*p2y/height

			P1 = (p1x_u,p1y_u,self.__track_project_to_sphere(p1x_u, p1y_u)) 
			P2 = (p2x_u,p2y_u,self.__track_project_to_sphere(p2x_u, p2y_u))

			a = [(P2[1]*P1[2]) - (P2[2]*P1[1]),
			     (P2[2]*P1[0]) - (P2[0]*P1[2]),
			     (P2[0]*P1[1]) - (P2[1]*P1[0])]
			
			# Figure out how much to rotate around that axis.
			d = map(lambda x, y: x - y, P1, P2)
			t = math.sqrt(d[0]**2 + d[1]**2 + d[2]**2) / (2.0 * self.size)

			# Avoid problems with out-of-control values...
			t = max(min(t, 1.0), -1.0)

			scale = t*math.sqrt(a[0]**2 + a[1]**2 + a[2]**2)
			q = map(lambda x, y: x*y, a, [scale]*3) + [math.sqrt(1.0-t**2)]
			self.quat = quaternion(q[0], q[1], q[2], q[3])