Example #1
0
def qnwcheb1(n, a, b):
    """ Univariate Gauss-Chebyshev quadrature nodes and weights

    Parameters
    -----------
    n : int
        number of nodes
    a : float
        left endpoint
    b : float
        right endpoint

    Returns
    ---------
    x : array, shape (n,)
        nodes
    x : array, shape (n,)
        weights

    Notes
    ---------
    
    Port of the qnwcheb1 function in the compecon matlab toolbox.
    """
    x = ((b + a) / 2 - (b - a) / 2
         * sp.cos(sp.pi / n * sp.arange(0.5, n + 0.5, 1)))
    w2 =  sp.r_[1, -2. / (sp.r_[1:(n - 1):2] * sp.r_[3:(n + 1):2])]
    w1 = (sp.cos(sp.pi / n * sp.mat((sp.r_[0:n] + 0.5)).T *
                 sp.mat((sp.r_[0:n:2]))).A)
    w0 = (b - a) / n
    w = w0 * sp.dot(w1, w2)
    return x, w
    def f(self, x):
        B1 = 0.5 * sin(x[0]) - 2*cos(x[0]) + sin(x[1]) -1.5*cos(x[1])
        B2 = 1.5 * sin(x[0]) - cos(x[0]) + 2*sin(x[1]) -0.5*cos(x[1])

        f1 = 1 + (self._A1-B1)**2 + (self._A2-B2)**2
        f2 = (x[0]+3)**2 + (x[1]+1)**2
        return -array([f1, f2])
Example #3
0
def xyzfield(gcoefs, hcoefs, phi, theta, rparam=1.0, order=13):
    # no usar esta función, es peor en rendimiento
    x, y, z = 0, 0, 0

    legendre, dlegendre = scipy.special.lpmn(order + 1, order + 1, scipy.cos(theta))

    for l in range(1, order + 1):
        for m in range(0, l + 1):
            deltax = (
                rparam ** (l + 2)
                * (gcoefs[m, l] * scipy.cos(m * phi) + hcoefs[m, l] * scipy.sin(m * phi))
                * dlegendre[m, l]
                * (-scipy.sin(theta))
            )
            deltay = (
                rparam ** (l + 2)
                * (gcoefs[m, l] * scipy.sin(m * phi) - hcoefs[m, l] * scipy.cos(m * phi))
                * m
                * legendre[m, l]
                / (scipy.sin(theta))
            )
            deltaz = (
                rparam ** (l + 2)
                * (l + 1)
                * (gcoefs[m, l] * scipy.cos(m * phi) + hcoefs[m, l] * scipy.sin(m * phi))
                * legendre[m, l]
            )

            x += deltax
            y += deltay
            z += deltaz

    return (x, y, z)
Example #4
0
    def GetReward(self, x):
        # r: the returned reward.
        # f: true if the car reached the goal, otherwise f is false
        y_acrobot = [0, 0, 0]

        theta1 = x[0]
        theta2 = x[1]
        y_acrobot[1] = y_acrobot[0] - cos(theta1)
        y_acrobot[2] = y_acrobot[1] - cos(theta2)
        #print y_acrobot
        #goal
        goal = y_acrobot[0] + self.target
        if self.easy_rewards:
            r = y_acrobot[2]
        else:
            #r = -0.01
            r = 0
        f = 0

        if  y_acrobot[2] >= goal:
            if self.easy_rewards:
                r = 10 * y_acrobot[2]
            else:
                r = 1
            f = 1

        if self.steps >= self.maxSteps:
            f = 5
            #r = -1

        return r, f
def test_time_integration():

    dt = 0.01
    tmax = 1

    def check_time_integration(res, y0, exact):
        ts, ys = time_integrate(res, y0, dt, tmax)

        exacts = [exact(t) for t in ts]

        print(ts, ys, exacts)

        utils.assert_list_almost_equal(ys, exacts, 1e-3)

    tests = [
        (lambda t, y, dy: y - dy, 1.0, lambda t: array(exp(t))),
        (lambda t, y, dy: y + dy, 1.0, lambda t: array(exp(-t))),
        (
            lambda t, y, dy: array([-0.1 * sin(t), y[1]]) - dy,
            array([0.1 * cos(0.0), exp(0.0)]),
            lambda t: array([0.1 * cos(t), exp(t)]),
        ),
    ]

    for r, y0, exact in tests:
        yield check_time_integration, r, y0, exact
Example #6
0
def radec_to_lb_single(ra,dec,T,degree=False):
    """
    NAME:
       radec_to_lb_single
    PURPOSE:
       transform from equatorial coordinates to Galactic coordinates for a single pair of ra,dec
    INPUT:
       ra - right ascension
       dec - declination
       T - epoch dependent transformation matrix (dictionary)
       degree - (Bool) if True, ra and dec are given in degree and l and b will be as well
    OUTPUT:
       l,b
    HISTORY:
       2009-11-12 - Written - Bovy (NYU)
    """
    T=T['T']
    if degree:
        thisra= ra/180.*sc.pi
        thisdec= dec/180.*sc.pi
    else:
        thisra= ra
        thisdec= dec
    XYZ=sc.array([sc.cos(thisdec)*sc.cos(thisra),sc.cos(thisdec)*sc.sin(thisra),sc.sin(thisdec)])
    galXYZ= sc.dot(T,XYZ)
    b= m.asin(galXYZ[2])
    l= m.atan(galXYZ[1]/galXYZ[0])
    if galXYZ[0]/sc.cos(b) < 0.:
        l+= sc.pi
    if l < 0.:
        l+= 2.*sc.pi
    if degree:
        return (l/sc.pi*180.,b/sc.pi*180.)
    else:
        return (l,b)
def evaluateSphericalVariation (phi,theta,cntPhi,cntTheta):
  global conf,cons
  success = False

  alpha0     =sp.zeros([dim['alpha']],complex)
  alpha0[conf['id0']]=sp.cos(phi)*sp.sin(theta)+0j
  alpha0[conf['id1']]=sp.sin(phi)*sp.sin(theta)+0j
  alpha0[conf['id2']]=sp.cos(theta)+0j

#  if (sp.absolute(alpha0[conf['id0']]) <= 1e-10): 
#    alpha0[conf['id0']]=0.0+0j
#  if (sp.absolute(alpha0[conf['id1']]) <= 1e-10): 
#    alpha0[conf['id1']]=0.0+0j
#  if (sp.absolute(alpha0[conf['id2']]) <= 1e-10): 
#    alpha0[conf['id2']]=0.0+0j
#  
  # normalize coefficients for alpha -> defines net-power
  alpha0[:]=alpha0[:]/sp.linalg.norm(alpha0[:])*cons['alpha_norm']
  __,res   = MemoryPulseFunctional.evaluateFunctional(alpha0,1.0+0j)
 
  myRes    = sp.zeros([conf['entries']+3])
  myRes[0] = alpha0[conf['id0']].real
  myRes[1] = alpha0[conf['id1']].real
  myRes[2] = alpha0[conf['id2']].real
  myRes[3:]= res
 
  print "### spherical map: phi/pi={0:5.3f}, theta/pi={1:5.3f}, fun={2:f}".format(phi/sp.pi,theta/sp.pi,myRes[conf['funval']])

  myRes[conf['funval']] = min(conf['cutoff'],res[conf['funval']])

  return myRes,cntPhi,cntTheta
def lat_lon_2_vertex(lat,lon):
	"""
	A routine to return the location of a detector's vertex in 3D
	Cartesean Coordinates given the latitude and longitude of the
	detector. This routine approximates teh Earth as a sphere.
	"""
	return (metric.R_earth*cos(lon)*cos(lat), metric.R_earth*sin(lon)*cos(lat), metric.R_earth*sin(lat))
Example #9
0
    def form_point_set(self, histo, point_set):
        (slices, numbins) = histo.shape
        phases = numpy.arange(numbins)
        phases = phases * (360. / numbins)
        phases += phases[1] / 2.
        phi_step = phases[0]
        
        for time in xrange(slices):
            z = float(time)
            for bin in xrange(numbins):
                r = histo[time,bin]
                theta = phi_step * (bin+1)
                theta *= (scipy.pi / 180.)
                x = r*scipy.cos(theta)
                y = r*scipy.sin(theta)
                point_set.InsertNextPoint(x, y, z)

            for bin in xrange(numbins):
                curbin = bin
                lastbin = bin-1
                if lastbin < 0:
                    lastbin = numbins-1

                r = (histo[time,bin] -  histo[time,lastbin]) / 2.
                theta = curbin * 360. / numbins
                x = r*scipy.cos(theta)
                y = r*scipy.sin(theta)
                point_set.InsertNextPoint(x, y, z)
Example #10
0
def binary_ephem(P, T, e, a, i, O_node, o_peri, t):
   # Grados a radianes
   d2rad = pi/180.
   rad2d = 180./pi
   i = i*d2rad
   O_node = (O_node*d2rad)%(2*pi)
   o_peri = (o_peri*d2rad)%(2*pi)
 
   # Anomalia media
   M = ((2.0*pi)/P)*(t - T)  # radianes
    
   if M >2*pi: M = M - 2*pi 
   M=M%(2*pi)

   # Anomalia excentrica (1ra aproximacion)
   E0 = M  + e*sin(M) + (e**2/M) * sin(2.0*M)

   for itera in range(15):
      M0 = E0 - e*sin(E0)
      E0 = E0 + (M-M0)/(1-e*cos(E0))

   true_anom = 2.0*arctan(sqrt((1+e)/(1-e))*tan(E0/2.0))
 
   #radius = (a*(1-e**2))/(1+e*cos(true_anom))
   radius = a*(1-e*cos(E0))

   theta = arctan( tan(true_anom + o_peri)*cos(i) ) + O_node
   rho = radius * (cos(true_anom + o_peri)/cos(theta - O_node))
   
   # revuelve rho ("), theta (grad), Anomalia excentrica (grad), Anomalia verdadera (grad)
   return rho, (theta*rad2d)%360. #, E0*rad2d, M*rad2d, true_anom*rad2d
Example #11
0
 def rotate(self, angle, mask=None):
     """Rotate the grids (arena centered)
     
     Grids to be rotated can be optionally specified by bool/index array
     *mask*, otherwise population is rotated. Specified *angle* can be a
     scalar value to be applied to the population or a population- or
     mask-sized array depending on whether *mask* is specified.
     """
     rot2D = lambda psi: [[cos(psi), sin(psi)], [-sin(psi),  cos(psi)]]
     if mask is not None and type(mask) is np.ndarray:
         if mask.dtype.kind == 'b':
             mask = mask.nonzero()[0]
         if type(angle) is np.ndarray and angle.size == mask.size:
             for i,ix in enumerate(mask):
                 self._phi[ix] = np.dot(self._phi[ix], rot2D(angle[i]))
         elif type(angle) in (int, float, np.float64):
             angle = float(angle)
             self._phi[mask] = np.dot(self._phi[mask], rot2D(angle))
         else:
             raise TypeError, 'angle must be mask-sized array or float'
         self._psi[mask] = np.fmod(self._psi[mask]+angle, 2*pi)
     elif mask is None:
         if type(angle) is np.ndarray and angle.size == self.num_maps:
             for i in xrange(self.num_maps):
                 self._phi[i] = np.dot(self._phi[i], rot2D(angle[i]))
         elif type(angle) in (int, float, np.float64):
             angle = float(angle)
             self._phi = np.dot(self._phi, rot2D(angle))
         else:
             raise TypeError, 'angle must be num_maps array or float'
         self._psi = np.fmod(self._psi+angle, 2*pi)
     else:
         raise TypeError, 'mask must be bool/index array'
Example #12
0
File: gid.py Project: isaxs/pynx
 def __init__(self,alphai,eparall,eperp,nrj):
   """
       Incident wave above a surface.
       Coordinates:
         - z is perpendicular to the surface, >0 going UP (different from H Dosch's convention)
         - x is the projection of the wavevector on the surface
         - y is parallel to the surface
       
       alphai: incident angle, with respect to the surface
       eparallel: component of the electric field parallel to the incident plane (vertical plane)
       eperp: component of the electric field perpendicular to the incident plane (along y)
       nrj: values of the energy of the incident wave, in eV
       
       alphai *or* nrj can be arrays, but not together
   """
   self.alphai=alphai
   self.eparall=eparall
   self.eperp=eperp
   self.ex=scipy.sin(alphai)*eparall
   self.ey=eperp
   self.ez=scipy.cos(alphai)*eparall
   self.kx= 2*pi/W2E(nrj)*scipy.cos(alphai)
   self.ky= 2*pi/W2E(nrj)*0
   self.kz=-2*pi/W2E(nrj)*scipy.sin(alphai)
   self.nrj=nrj
Example #13
0
def ned2ecef(lat, lon, alt, n, e, d):
    X0, Y0, Z0 = coord.geodetic2ecef(lat, lon, alt)
    lat, lon = radians(lat), radians(lon)
    
    pitch = math.pi/2 + lat
    yaw = -lon 
    
    my = mat('[%f %f %f; %f %f %f; %f %f %f]' %
        (cos(pitch), 0, -sin(pitch),
         0,1,0,
         sin(pitch), 0, cos(pitch)))
    
    mz = mat('[%f %f %f; %f %f %f; %f %f %f]' %
        (cos(yaw), sin(yaw),0,
         -sin(yaw),cos(yaw),0,
         0,0,1))
    
    mr = mat('[%f %f %f; %f %f %f; %f %f %f]' %
        (-cos(lon)*sin(lat), -sin(lon), -cos(lat) * cos(lon), 
         -sin(lat)*sin(lon), cos(lon), -sin(lon)*cos(lat),
         cos(lat), 0, -sin(lat)))
    
    geo = mat('[%f; %f; %f]' % (X0, Y0, Z0))
    ned = mat('[%f; %f; %f]' % (n, e, d))
    res = mr*ned + geo
    return res[0], res[1], res[2]  
Example #14
0
    def get_bl(self,ra=None,dec=None):
        """
        http://scienceworld.wolfram.com/astronomy/GalacticCoordinates.html
        """
        if ra==None: ra=self.get_column("RA")
        if dec==None: dec=self.get_column("DEC")
        if type(ra)==float: 
            ral=scipy.zeros(1)
            ral[0]=ra
            ra=ral
        if type(dec)==float: 
            decl=scipy.zeros(1)
            decl[0]=dec
            dec=decl

        c62=math.cos(62.6*D2R)
        s62=math.sin(62.6*D2R)
        
        b=scipy.sin(dec*D2R)*c62
        b-=scipy.cos(dec*D2R)*scipy.sin((ra-282.25)*D2R)*s62
        b=scipy.arcsin(b)*R2D
        
        cosb=scipy.cos(b*D2R)
        #l minus 33 degrees
        lm33=(scipy.cos(dec*D2R)/cosb)*scipy.cos((ra-282.25))
        l=scipy.arccos(lm33)*R2D+33.0
        return b,l
Example #15
0
 def __init__(self,id,matName,orientation,source=0.0):
     self.id = id
     self.matName = matName
     self.orientation = orientation
     self.source = source
     self.T = array([[cos(orientation),-sin(orientation)],
                     [sin(orientation), cos(orientation)]])
 def setUp(self):
     # Make a positive definite noise matrix, clean map, and dirty_map.
     self.nra = 10
     self.ndec = 5
     self.nf = 20
     self.shape = (self.nf, self.nra, self.ndec)
     self.size = self.nra * self.ndec * self.nf
     # Clean map.
     clean_map = sp.empty(self.shape, dtype=float)
     clean_map = al.make_vect(clean_map, axis_names=('freq', 'ra', 'dec'))
     clean_map[...] = sp.sin(sp.arange(self.nf))[:,None,None]
     clean_map *= sp.cos(sp.arange(self.nra))[:,None]
     clean_map *= sp.cos(sp.arange(self.ndec))
     # Noise inverse matrix.
     noise_inv = sp.empty(self.shape * 2, dtype=float)
     noise_inv = al.make_mat(noise_inv, axis_names=('freq', 'ra', 'dec')*2,
                             row_axes=(0, 1, 2), col_axes=(3, 4, 5))
     rand_mat = rand.randn(*((self.size,) * 2))
     information_factor = 1.e6  # K**-2
     rand_mat = sp.dot(rand_mat, rand_mat.transpose()) * information_factor
     noise_inv.flat[...] = rand_mat.flat
     # Dirty map.
     dirty_map = al.partial_dot(noise_inv, clean_map)
     # Store in self.
     self.clean_map = clean_map
     self.noise_inv = noise_inv
     self.dirty_map = dirty_map
 def sky_ra_dec(self, ra, dec):
     ra_dec_shape = (ra * dec).shape
     sl = (slice(None),) + (None,) * (ra * dec).ndim
     time_stream = sp.zeros((self.nf,) + ra_dec_shape)
     time_stream += sp.sin(ra*0.9 + 3.0)*sp.cos(dec*1.3 + 2.0) # The sky map.
     time_stream *= sp.cos(sp.arange(self.nf, dtype=float) + 5.0)[sl] + 1.2
     return time_stream
Example #18
0
def rect_to_cyl_vec(vx,vy,vz,X,Y,Z,cyl=False):
    """
    NAME:
       rect_to_cyl_vec
    PURPOSE:
       transform vectors from rectangular to cylindrical coordinates vectors
    INPUT:
       vx - 
       vy - 
       vz - 
       X - X
       Y - Y
       Z - Z
       cyl - if True, X,Y,Z are already cylindrical
    OUTPUT:
       vR,vT,vz
    HISTORY:
       2010-09-24 - Written - Bovy (NYU)
    """
    if not cyl:
        R,phi,Z= rect_to_cyl(X,Y,Z)
    else:
        phi= Y
    vr=+vx*sc.cos(phi)+vy*sc.sin(phi)
    vt= -vx*sc.sin(phi)+vy*sc.cos(phi)
    return (vr,vt,vz)
Example #19
0
def radec_to_lb(ra,dec,degree=False,epoch=2000.0):
    """
    NAME:
       radec_to_lb
    PURPOSE:
       transform from equatorial coordinates to Galactic coordinates
    INPUT:
       ra - right ascension
       dec - declination
       degree - (Bool) if True, ra and dec are given in degree and l and b will be as well
       epoch - epoch of ra,dec (right now only 2000.0 and 1950.0 are supported)
    OUTPUT:
       l,b
       For vector inputs [:,2]
    HISTORY:
       2009-11-12 - Written - Bovy (NYU)
       2014-06-14 - Re-written w/ numpy functions for speed and w/ decorators for beauty - Bovy (IAS)
    """
    import math as m
    import numpy as nu
    import scipy as sc
    #First calculate the transformation matrix T
    theta,dec_ngp,ra_ngp= get_epoch_angles(epoch)
    T= sc.dot(sc.array([[sc.cos(theta),sc.sin(theta),0.],[sc.sin(theta),-sc.cos(theta),0.],[0.,0.,1.]]),sc.dot(sc.array([[-sc.sin(dec_ngp),0.,sc.cos(dec_ngp)],[0.,1.,0.],[sc.cos(dec_ngp),0.,sc.sin(dec_ngp)]]),sc.array([[sc.cos(ra_ngp),sc.sin(ra_ngp),0.],[-sc.sin(ra_ngp),sc.cos(ra_ngp),0.],[0.,0.,1.]])))
    #Whether to use degrees and scalar input is handled by decorators
    XYZ= nu.array([nu.cos(dec)*nu.cos(ra),
                   nu.cos(dec)*nu.sin(ra),
                   nu.sin(dec)])
    galXYZ= nu.dot(T,XYZ)
    b= nu.arcsin(galXYZ[2])
    l= nu.arctan2(galXYZ[1]/sc.cos(b),galXYZ[0]/sc.cos(b))
    l[l<0.]+= 2.*nu.pi
    out= nu.array([l,b])
    return out.T
Example #20
0
    def getObservation(self):
        obs = array(impl.getObs())
        if self.verbose:
            print(('obs', obs))
        obs.resize(self.outdim)
        if self.extraObservations:
            cartpos = obs[-1]
            if self.markov:
                angle1 = obs[1]
            else:
                angle1 = obs[0]
            obs[-1 + self.extraRandoms] = 0.1 * cos(angle1) + cartpos
            obs[-2 + self.extraRandoms] = 0.1 * sin(angle1) + cartpos
            if self.numPoles == 2:
                if self.markov:
                    angle2 = obs[3]
                else:
                    angle2 = obs[1]
                obs[-3 + self.extraRandoms] = 0.05 * cos(angle2) + cartpos
                obs[-4 + self.extraRandoms] = 0.05 * sin(angle2) + cartpos

        if self.extraRandoms > 0:
            obs[-self.extraRandoms:] = randn(self.extraRandoms)

        if self.verbose:
            print(('obs', obs))
        return obs
Example #21
0
def _genBFEdgeZero(plasma, zeros, rcent, zcent):
    """ this will absolutely need to be rewritten"""

    theta = scipy.linspace(-scipy.pi,scipy.pi,zeros)
    cent = geometry.Point(geometry.Vecr([rcent,0,zcent]),plasma)
    zerobeam = []
    outline = []
    for i in xrange(len(plasma.norm.s)-1):
        outline += [geometry.Vecx([plasma.sagi.s[i],
                                   0,
                                   plasma.norm.s[i]])-cent]
        
    for i in xrange(zeros):
        temp2 = geometry.Vecr([scipy.cos(theta[i]),
                               0,
                               scipy.sin(theta[i])])
        s = 0
        for j in outline:
            temp4 = j*temp2
            if temp4 > s:
                s = temp4

        temp2.s = s
        zerobeam += [Ray(geometry.Point(cent+temp2,
                                        plasma),
                         geometry.Vecr([scipy.sin(theta[i]),
                                        0,
                                        -scipy.cos(theta[i])]))]

    return zerobeam
    def residuals(self, p,errors, f,freq_val):
        theta = self.theta
#        Isrc = 19.6*pow((750.0/freq_val[f]),0.495)*2 
#        Isrc = 19.6*pow((750.0/freq_val[f]),0.495)*(2.28315426-0.000484307905*freq_val[f]) # Added linear fit for Jansky to Kelvin conversion.
#        Isrc = 19.74748409*pow((750.0/freq_val[f]),0.49899785)*(2.28315426-0.000484307905*freq_val[f]) # My fit solution for 3C286
        Isrc = 25.15445092*pow((750.0/freq_val[f]),0.75578842)*(2.28315426-0.000484307905*freq_val[f]) # My fit solution for  3C48
#        Isrc = 4.56303633*pow((750.0/freq_val[f]),0.59237327)*(2.28315426-0.000484307905*freq_val[f]) # My fit solution for 3C67
        PAsrc = 33.0*sp.pi/180.0 # for 3C286, doesn't matter for unpolarized. 
#        Psrc = 0.07 #for 3C286 
        Psrc = 0 #for #3C48,3C67 
        Qsrc = Isrc*Psrc*sp.cos(2*PAsrc) 
        Usrc = Isrc*Psrc*sp.sin(2*PAsrc) 
        Vsrc = 0
        XXsrc0 = Isrc-Qsrc
        YYsrc0 = Isrc+Qsrc
#        XXsrc = (0.5*(1+sp.cos(2*theta[i]))*XXsrc0-sp.sin(2*theta[i])*Usrc+0.5*(1-sp.cos(2*theta[i]))*YYsrc0)
#        YYsrc = (0.5*(1-sp.cos(2*theta[i]))*XXsrc0+sp.sin(2*theta[i])*Usrc+0.5*(1+sp.cos(2*theta[i]))*YYsrc0)
        source = sp.zeros(4*self.file_num)
        for i in range(0,len(source),4):
            source[i] = (0.5*(1+sp.cos(2*theta[i]))*XXsrc0-sp.sin(2*theta[i])*Usrc+0.5*(1-sp.cos(2*theta[i]))*YYsrc0)
            source[i+1] = 0
            source[i+2] = 0
            source[i+3] = (0.5*(1-sp.cos(2*theta[i]))*XXsrc0+sp.sin(2*theta[i])*Usrc+0.5*(1+sp.cos(2*theta[i]))*YYsrc0)
        err = (source-self.peval(p,f))/errors
        return err
Example #23
0
 def f(self, x):
     res = 0
     for i in range(self.xdim):
         Ai = sum(self.A[i] * sin(self.alphas) + self.B[i] * cos(self.alphas))
         Bix = sum(self.A[i] * sin(x) + self.B[i] * cos(x))
         res += (Ai - Bix) ** 2
     return res
Example #24
0
 def InitJackArrays(self,freq,samples):
   """Initialize Jack Arrays"""
   self.iIa = sp.zeros(samples).astype(sp.float32)
   self.iQa = sp.zeros(samples).astype(sp.float32)      
   
   self.oIa = sp.zeros(samples, dtype=sp.float32 )
   self.oQa = sp.zeros(samples, dtype=sp.float32 )
   
   ## 100 frames warmup
   sf = 0
   ef = self.rtframes2sync
   samples = sp.pi + (2*sp.pi*freq*(self.dt * sp.r_[sf:ef]))
   self.oIa[sf:ef] = self.amp * sp.cos(samples)
   self.oQa[sf:ef] = self.amp * sp.sin(samples)
   
   # For IQ balancing
   #self.oIa[sf:ef] = sp.cos(samples) - (sp.sin(samples)*(1+self.oalpha)*sp.sin(self.ophi))
   #self.oQa[sf:ef] = sp.sin(samples)*(1+self.oalpha)*sp.cos(self.ophi)
   
   ## 180 phase change 
   sf = ef
   ef = ef + self.sync2fft + self.fftn + self.fft2end
   samples = (2*sp.pi*freq*(self.dt * sp.r_[sf:ef]))
   self.oIa[sf:ef] = self.amp * sp.cos(samples) 
   self.oQa[sf:ef] = self.amp * sp.sin(samples)   
 def test_correlate(self) :
     Data = self.blocks[0]
     Data.calc_freq()
     map = self.map
     gain = 3.45
     const = 2.14
     # Set all data = gain*(cos(time_ind)).
     Data.data[:,:,:,:] = gain*sp.cos(sp.arange(1,11)
                                 [:,sp.newaxis,sp.newaxis,sp.newaxis])
     # Explicitly set time mean to something known.
     Data.data -= ma.mean(Data.data, 0)
     Data.data += gain*const*Data.freq/800.0e6
     # Now the Map.
     map[:,:,:] = 0.0
     # Set 10 pixels to match cos part of data.
     map[:, range(10), range(10)] = (
                 sp.cos(sp.arange(1,11)[None, :]))
     map[:, range(10), range(10)] -= ma.mean(
         map[:, range(10), range(10)], 1)[:, None]
     # Give Map a mean to test things out. Should really have no effect.
     map[...] += 0.352*map.get_axis('freq')[:, None, None]/800.0e6
     # Rig the pointing to point to those 10 pixels.
     def rigged_pointing() :
         Data.ra = map.get_axis('ra')[range(10)]
         Data.dec = map.get_axis('dec')[range(10)]
     Data.calc_pointing = rigged_pointing
     solved_gains = smd.sub_map(Data, map, correlate=True)
     # Now data should be just be gain*const*f, within machine precision.
     Data.data /= gain*Data.freq/800.0e6
     self.assertTrue(sp.allclose(Data.data[:,:,:,:], const))
     self.assertTrue(sp.allclose(solved_gains, gain))
Example #26
0
def cyl_to_rect_vec(vr,vt,vz,phi):
    """
    NAME:

       cyl_to_rect_vec

    PURPOSE:

       transform vectors from cylindrical to rectangular coordinate vectors

    INPUT:

       vr - radial velocity

       vt - tangential velocity

       vz - vertical velocity

       phi - azimuth

    OUTPUT:

       vx,vy,vz

    HISTORY:

       2011-02-24 - Written - Bovy (NYU)

    """
    vx= vr*sc.cos(phi)-vt*sc.sin(phi)
    vy= vr*sc.sin(phi)+vt*sc.cos(phi)
    return (vx,vy,vz)
Example #27
0
def lla2ecef(lla: Sequence[float], cst: ConstantsFile, lla_as_degrees: bool=False) -> Tuple[float, float, float]:
    """
    converts LLA (Latitude, Longitude, Altitude) coordinates
    to ECEF (Earth-Centre, Earth-First) XYZ coordinates.
    """

    lat, lon, alt = lla
    if lla_as_degrees:
        lat = radians(lat)
        lon = radians(lon)

    a = cst.semi_major_axis
    b = cst.semi_minor_axis
    # calc. ellipsoid flatness
    f = (a - b) / a
    # calc. eccentricity
    e = sqrt(f * (2 - f))

    # Calculate length of the normal to the ellipsoid
    N = a / sqrt(1 - (e * sin(lat)) ** 2)
    # Calculate ecef coordinates
    x = (N + alt) * cos(lat) * cos(lon)
    y = (N + alt) * cos(lat) * sin(lon)
    z = (N * (1 - e ** 2) + alt) * sin(lat)
    # Return the ecef coordinates
    return x, y, z
Example #28
0
def CalcXY2GPSParam_2p(x1,x2,g1,g2,K=[0,0]):
	# Kx = dLng/dx; Ky = dlat/dy;
	# In China:
	# Kx = (133.4-1.2*lat)*1e3
	# Ky = (110.2+0.002*lat)*1e3

	X1 = array(x1)
	Y1 = array(g1)
	X2 = array(x2)
	Y2 = array(g2)
	detX = X2-X1
	detY = Y2-Y1
	lat = Y1[1]
	if K[0] == 0:
		Kx = (133.4-1.2*lat)*1e3
		Ky = (110.2+0.002*lat)*1e3
		K = array([Kx,Ky])
	else:
		Kx = K[0]
		Ky = K[1]
	detKY = detY*K

	alpha =  myArctan(detX[0],detX[1]) - myArctan(detKY[0],detKY[1])
	A = array([[sp.cos(alpha),sp.sin(alpha)],[-sp.sin(alpha),sp.cos(alpha)]])
	X01 = X1 - dot(linalg.inv(A),Y1*K) 
	X02 = X2 - dot(linalg.inv(A),Y2*K)
	X0 = (X01+X02) /2

	return A,X0,K
Example #29
0
def elaz2radec_lst(el, az, lst, lat = 38.43312) :
    """DO NOT USE THIS ROUTINE FOR ANTHING THAT NEEDS TO BE RIGHT.  IT DOES NOT
    CORRECT FOR PRECESSION.

    Calculates the Ra and Dec from elavation, aximuth, LST and Latitude.

    This function is vectorized with numpy so should be fast.  Standart numpy
    broadcasting should also work.

    All angles in degrees, lst in seconds. Latitude defaults to GBT.
    """

    # Convert everything to radians.
    el = sp.radians(el)
    az = sp.radians(az)
    lst = sp.array(lst, dtype = float)*2*sp.pi/86400
    lat = sp.radians(lat)
    # Calculate dec.
    dec = sp.arcsin(sp.sin(el)*sp.sin(lat) +
                    sp.cos(el)*sp.cos(lat)*sp.cos(az))
    # Calculate the hour angle
    ha = sp.arccos((sp.sin(el) - sp.sin(lat)*sp.sin(dec)) /
                   (sp.cos(lat)*sp.cos(dec)))
    ra = sp.degrees(lst - ha) % 360

    return ra, sp.degrees(dec)
Example #30
0
def sparse_orth(d):
    """ Constructs a sparse orthogonal matrix.
    
    The method is described in:
    Gi-Sang Cheon et al., Constructions for the sparsest orthogonal matrices,
    Bull. Korean Math. Soc 36 (1999) No.1 pp.199-129
    """
    from scipy.sparse import eye
    from scipy import r_, pi, sin, cos

    if d % 2 == 0:
        seq = r_[0:d:2, 1:d - 1:2]
    else:
        seq = r_[0:d - 1:2, 1:d:2]
    Q = eye(d, d).tocsc()
    for i in seq:
        theta = random() * 2 * pi
        flip = (random() - 0.5) > 0;
        Qi = eye(d, d).tocsc()
        Qi[i, i] = cos(theta)
        Qi[(i + 1), i] = sin(theta)
        if flip > 0:
            Qi[i, (i + 1)] = -sin(theta)
            Qi[(i + 1), (i + 1)] = cos(theta)
        else:
            Qi[i, (i + 1)] = sin(theta)
            Qi[(i + 1), (i + 1)] = -cos(theta)
        Q = Q * Qi;
    return Q
Example #31
0
def trig_func(y, t):
    ydot = scipy.zeros(1, scipy.float_)
    ydot[0] = scipy.cos(t)
    return ydot
Example #32
0
def req_noise(xyzsource, d_inch, P_h, T, B, RPM, h, r, CG, PWL_req):

    SPL_req = PWL_to_SPL(PWL_req, r)
    print(SPL_req)
    SPLlst = list()

    R_ft = 0.0833333333 * d_inch / 2
    m = 1
    gamma, R, Temp = 1.4, 287, isa(h)[1]
    M_t = V_r(RPM, d_inch, 1) * 0.3048 / np.sqrt(gamma * R * Temp)
    V_07 = V_r(RPM, d_inch, 0.7)

    #Assumption blade area
    A_b = 2 / B * 1 / 12
    thetalst = list()

    for theta in np.arange(0, 360 + 1, 1):

        x = r * np.sin(theta)
        y = r * np.cos(theta)
        thetalst.append(theta)

        xyzobserver = [x, y, 0]
        S, theta = position(xyzsource, xyzobserver)

        p_rn = list()
        p_v = list()

        for S, theta in zip(S, theta):
            #ORDERED ROTATIONAL NOISE PRESSURE AT OBSERVER
            rotationp = p_m(m, S, R_ft, P_h, T, B, M_t, theta)
            p_rn.append(rotationp)
            #VORTEX NOISE AT OBSERVER
            vortexSPL = SPL_vortex(A_b, V_07)
            vortexSPL_obs = SPL_to_PWL_dist(vortexSPL, 300, S_obs=S)
            vortexp = SPL_to_p(vortexSPL_obs)
            p_v.append(vortexp)

        p_sum = sum(p_rn + p_v)

        SPL = p_to_SPL(p_sum)
        SPLlst.append(SPL)

    return max(SPLlst), thetalst, SPLlst


#BUTTERFLY PLOT
#plst=list()
#thetalst=list()
#for theta in np.arange(0,2*np.pi*1.026,0.05):
#    p=p_m(1,3,0.645833333075,1.36,12.521858094085683,3, 0.75, theta)
#    if p>0:
#        thetalst.append(theta)
#        plst.append(p)
#    else:
#        thetalst.append(theta)
#        plst.append(-p)
#
#plt.plot(thetalst,plst)
#plt.polar(thetalst,plst)
#plt.show()
#plt.ylabel('p')
#plt.xlabel('theta')
Example #33
0
def gettrack_roms(jdmat_m, lon_v, lat_v, u, v, startdate, numdays, daystep, la,
                  lo):  # tracks particle at surface
    # calculate the points near la,lo
    distance, index_location = nearxy(lon_v, lat_v, lo, la)
    ####### get index of startdate in jdmat_m#####
    jdmat_m_num = []  # this is the date in the form of a number
    jdmat_m_list, jdmat = [], []
    # convert array to list
    for jdmat_m_i in jdmat_m:
        jdmat_m_list.append(jdmat_m_i)
    for i in jdmat_m_list:  # convert time to number
        jdmat_m_num.append(i)
    dts = date2num(dt.datetime(2001, 1, 1, 0, 0, 0))
    jdmat_m = [i + dts for i in jdmat_m]
    index_startdate = int(
        round(np.interp(startdate, jdmat_m,
                        range(len(jdmat_m)))))  #get the index of startdate
    print "index_startdate = ", index_startdate, " inside getreack_roms  "
    print "the start u's location", index_location
    u1 = float(u[index_startdate][index_location])
    v1 = float(v[index_startdate][index_location])
    if u1 == -999.0:  # case of no good data
        u1 = 0
        v1 = 0

    nsteps = scipy.floor(min(numdays, jdmat_m_num[-1]) / daystep)
    print "nsteps =", nsteps

    uu, vv, lon_k, lat_k, time = [], [], [], [], []
    uu.append(u1)
    vv.append(v1)
    lat_k.append(la)
    lon_k.append(lo)
    time.append(startdate)

    for i in range(1, int(nsteps)):
        # first, estimate the particle move to its new position using velocity of previous time steps
        lat1 = lat_k[i - 1] + float(
            vv[i - 1] * daystep * 24 * 3600) / 1000 / 1.8535 / 60
        lon1 = lon_k[i - 1] + float(
            uu[i - 1] * daystep * 24 * 3600) / 1000 / 1.8535 / 60 * (
                scipy.cos(float(lat_k[i - 1])) / 180 * np.pi)
        # find the closest model time for the new timestep
        jdmat_m_num_i = time[i - 1] + daystep
        time.append(jdmat_m_num_i)
        if jdmat_m_num_i > max(jdmat_m_num):
            print "This time is not available in the model"
        index_startdate = int(
            round(
                np.interp(jdmat_m_num_i, jdmat_m_num,
                          range(len(jdmat_m_num)))))

        #find the point's index of near lat1,lon1
        index_location = nearxy(lon_v, lat_v, lon1, lat1)[1]

        ui = u[index_startdate][index_location]
        vi = v[index_startdate][index_location]

        vv.append(vi)
        uu.append(ui)
        # estimate the particle move from its new position using velocity of previous time steps
        lat_k.append(
            float(lat1 + lat_k[i - 1] +
                  float(vv[i] * daystep * 24 * 3600) / 1000 / 1.8535 / 60) / 2)
        lon_k.append(
            float(lon1 + lon_k[i - 1] +
                  float(uu[i] * daystep * 24 * 3600) / 1000 / 1.8535 / 60 *
                  scipy.cos(float(lat_k[i]) / 180 * np.pi)) / 2)

    return lat_k, lon_k, time
def HoG(img,
        See_graph=False,
        cell_per_blk=(3, 3),
        pix_per_cell=(5, 5),
        orientation=9):
    """
    The function for computing Histogram of oriented gradients. Takes 
    the following as keyword arguments:
    
    cell_per_blk:
     How may cells in a block ( cells in height, cells in width)

    pix_per_cell:
     The size of each cell: ( height, witdh )

    orientation:
     Binning the gradient into how many orientation bins
    """
    if img is None:
        print " pic read failed"
        return -1

    if img.ndim > 3:
        print " gray-scale process only for speed performance"
        return -1

    # gradient computation
    gradient_x = np.zeros(img.shape)
    gradient_y = np.zeros(img.shape)
    gradient_x[:, :-1] = np.diff(img, n=1, axis=1)
    gradient_y[:-1, :] = np.diff(img, n=1, axis=0)
    magnitude = sqrt(gradient_x**2 + gradient_y**2)
    ori = arctan2(gradient_y, (gradient_x + 1e-15)) * (180 / pi) + 90

    # Orientation Binning
    img_h, img_w = img.shape
    cx, cy = pix_per_cell
    bx, by = cell_per_blk
    ncell_x = int(np.floor(img_w // cx))
    ncell_y = int(np.floor(img_h // cy))
    ori_histogram = np.zeros((ncell_y, ncell_x, orientation))
    for i in range(0, orientation):
        temp1 = np.where(ori < 180 / orientation * (i + 1), ori, 0)
        temp1 = np.where(ori >= 180 / orientation * i, temp1, 0)
        temp2 = np.where(temp1 > 0, magnitude, 0)
        ori_histogram[:, :, i] = uniform_filter(temp2,
                                                size=(cy, cx))[cy / 2::cy,
                                                               cx / 2::cx]

    # display output if required
    if See_graph is True:
        from skimage import draw
        hog_image = np.zeros(img.shape, dtype=float)
        radius = min(cx, cy) // 2 - 1
        print "Drawing HOG output..."
        for x in range(ncell_x):
            for y in range(ncell_y):
                for o in range(orientation):
                    centre = tuple([y * cy + cy // 2, x * cx + cx // 2])
                    dx = radius * cos(float(o) / orientation * np.pi)
                    dy = radius * sin(float(o) / orientation * np.pi)
                    rr, cc = draw.line(int(centre[0] - dx),
                                       int(centre[1] - dy),
                                       int(centre[0] + dx),
                                       int(centre[1] + dy))
                    hog_image[rr, cc] += ori_histogram[y, x, o]

        cv2.imshow('HoG img', hog_image)
        cv2.waitKey(0)
        cv2.destroyAllWindows()

    # normalization
    n_blocksx = (ncell_x - bx) + 1
    n_blocksy = (ncell_y - by) + 1
    normalised_blocks = np.zeros((n_blocksy, n_blocksx, by, bx, orientation))
    for x in range(n_blocksx):
        for y in range(n_blocksy):
            block = ori_histogram[y:y + by, x:x + bx, :]
            eps = 1e-5
            normalised_blocks[y, x, :] = block / sqrt(block.sum()**2 + eps)

    return normalised_blocks
    def leastSquaresModel(self, tilt_series_list):
        phi, optical_axis, z0 = self.getCurrentParameters()
        if self.fixed_model == True:
            phi = self.phi0
            optical_axis = self.offset0
        parameters = [phi, optical_axis]
        args_list = []
        current_tilt_group = self.getCurrentTiltGroup()
        current_tilt_direction = current_tilt_group.is_plus_tilt
        current_tilt = current_tilt_group.tilts[-1]
        datalimit = self.fitdata
        if len(current_tilt_group) >= datalimit:
            previous_tilts = current_tilt_group.tilts[-datalimit:]
        else:
            previous_tilts = current_tilt_group.tilts[:]
        if self.fixed_model:
            # Accept accurate tilts only for fixed phi, offset fitting of z0
            tolerance = 0.01
        else:
            # With all three parameters free to change, use all tilt points to stablize the fiting
            # The result is more an average phi, offset.
            tolerance = 1.62
        tiltmin = min(previous_tilts) - tolerance
        tiltmax = max(previous_tilts) + tolerance
        for tilt_series in tilt_series_list:
            for tilt_group in tilt_series.tilt_groups:
                if len(tilt_group.tilts) == 0 or len(tilt_group.xs) != len(
                        tilt_group.tilts) or len(tilt_group.ys) != len(
                            tilt_group.tilts):
                    break
                # wrong direction tilt group should not be included in the fit
                elif tilt_group.is_plus_tilt is not current_tilt_direction:
                    continue
                parameters.extend([0])

                acceptableindices = self.acceptableindices(
                    tilt_group.tilts, tiltmin, tiltmax, datalimit)
                goodtilts = []
                goodxs = []
                goodys = []
                for i in acceptableindices:
                    goodtilts.append(tilt_group.tilts[i])
                    goodxs.append(tilt_group.xs[i])
                    goodys.append(tilt_group.ys[i])
                tilts = scipy.array(goodtilts)
                cos_tilts = scipy.cos(tilts)
                sin_tilts = scipy.sin(tilts)

                x0 = tilt_group.xs[0]
                y0 = tilt_group.ys[0]

                x = scipy.array(goodxs)
                y = scipy.array(goodys)

                args_list.append((cos_tilts, sin_tilts, x0, y0, x, y))

                # leastsq function gives improper parameters error if too many input data array are empty
                # This happens if 6 or more preceeding tilt series have much lower end tilt angle
                # than the current. We will ignore them.
                if cos_tilts.size < 1:
                    args_list.pop()
                    parameters.pop()

        args = (args_list, )
        kwargs = {
            'args': args,
            #'full_output': 1,
            #'ftol': 1e-12,
            #'xtol': 1e-12,
        }
        result = scipy.optimize.leastsq(self.residuals, parameters, **kwargs)
        try:
            x = list(result[0])
        except TypeError:
            x = [result[0]]
        return x
Example #36
0
 def Rotate2D(pts, cnt, ang=scipy.pi / 4):
     '''pts = {} Rotates points(nx2) about center cnt(2) by angle ang(1) in radian'''
     return scipy.dot(
         pts - cnt,
         ar([[scipy.cos(ang), scipy.sin(ang)],
             [-scipy.sin(ang), scipy.cos(ang)]])) + cnt
Example #37
0
def hog(image,
        orientations=9,
        pixels_per_cell=(8, 8),
        cells_per_block=(3, 3),
        visualise=False,
        normalise=False):
    """Extract Histogram of Oriented Gradients (HOG) for a given image.

    Compute a Histogram of Oriented Gradients (HOG) by
        1) (optional) global image normalisation
        2) computing the gradient image in x and y
        3) computing gradient histograms
        3) normalising across blocks
        4) flattening into a feature vector

    Parameters
    ----------
    image : (M, N) ndarray
        Input image (greyscale).
    orientations : int
        Number of orientation bins.
    pixels_per_cell : 2 tuple (int, int)
        Size (in pixels) of a cell.
    cells_per_block  : 2 tuple (int,int)
        Number of cells in each block.
    visualise : bool, optional
        Also return an image of the HOG.
    normalise : bool, optional
        Apply power law compression to normalise the image before
        processing.

    Returns
    -------
    newarr : ndarray
        HOG for the image as a 1D (flattened) array.
    hog_image : ndarray (if visualise=True)
        A visualisation of the HOG image.

    References
    ----------
    * http://en.wikipedia.org/wiki/Histogram_of_oriented_gradients

    * Dalal, N and Triggs, B, Histograms of Oriented Gradients for
      Human Detection, IEEE Computer Society Conference on Computer
      Vision and Pattern Recognition 2005 San Diego, CA, USA

    """
    image = np.atleast_2d(image)
    """
    The first stage applies an optional global image normalisation
    equalisation that is designed to reduce the influence of illumination
    effects. In practice we use gamma (power law) compression, either
    computing the square root or the log of each colour channel.
    Image texture strength is typically proportional to the local surface
    illumination so this compression helps to reduce the effects of local
    shadowing and illumination variations.
    """

    if image.ndim > 3:
        raise ValueError("Currently only supports grey-level images")

    if normalise:
        image = sqrt(image)
    """
    The second stage computes first order image gradients. These capture
    contour, silhouette and some texture information, while providing
    further resistance to illumination variations. The locally dominant
    colour channel is used, which provides colour invariance to a large
    extent. Variant methods may also include second order image derivatives,
    which act as primitive bar detectors - a useful feature for capturing,
    e.g. bar like structures in bicycles and limbs in humans.
    """

    gx = np.zeros(image.shape)
    gy = np.zeros(image.shape)
    gx[:, :-1] = np.diff(image, n=1, axis=1)
    gy[:-1, :] = np.diff(image, n=1, axis=0)
    """
    The third stage aims to produce an encoding that is sensitive to
    local image content while remaining resistant to small changes in
    pose or appearance. The adopted method pools gradient orientation
    information locally in the same way as the SIFT [Lowe 2004]
    feature. The image window is divided into small spatial regions,
    called "cells". For each cell we accumulate a local 1-D histogram
    of gradient or edge orientations over all the pixels in the
    cell. This combined cell-level 1-D histogram forms the basic
    "orientation histogram" representation. Each orientation histogram
    divides the gradient angle range into a fixed number of
    predetermined bins. The gradient magnitudes of the pixels in the
    cell are used to vote into the orientation histogram.
    """

    magnitude = sqrt(gx**2 + gy**2)
    orientation = arctan2(gy, (gx + 1e-15)) * (180 / pi) + 90

    sx, sy = image.shape
    cx, cy = pixels_per_cell
    bx, by = cells_per_block

    n_cellsx = int(np.floor(sx // cx))  # number of cells in x
    n_cellsy = int(np.floor(sy // cy))  # number of cells in y

    # compute orientations integral images
    orientation_histogram = np.zeros((n_cellsx, n_cellsy, orientations))
    for i in range(orientations):
        #create new integral image for this orientation
        # isolate orientations in this range

        temp_ori = np.where(orientation < 180 / orientations * (i + 1),
                            orientation, 0)
        temp_ori = np.where(orientation >= 180 / orientations * i, temp_ori, 0)
        # select magnitudes for those orientations
        cond2 = temp_ori > 0
        temp_mag = np.where(cond2, magnitude, 0)

        orientation_histogram[:, :,
                              i] = uniform_filter(temp_mag,
                                                  size=(cx, cy))[cx / 2::cx,
                                                                 cy / 2::cy].T

    # now for each cell, compute the histogram
    #orientation_histogram = np.zeros((n_cellsx, n_cellsy, orientations))

    radius = min(cx, cy) // 2 - 1
    hog_image = None
    if visualise:
        hog_image = np.zeros((sy, sx), dtype=float)

    if visualise:
        from skimage import draw

        for x in range(n_cellsx):
            for y in range(n_cellsy):
                for o in range(orientations):
                    centre = tuple([y * cy + cy // 2, x * cx + cx // 2])
                    dx = radius * cos(float(o) / orientations * np.pi)
                    dy = radius * sin(float(o) / orientations * np.pi)
                    rr, cc = draw.bresenham(centre[0] - dx, centre[1] - dy,
                                            centre[0] + dx, centre[1] + dy)
                    hog_image[rr, cc] += orientation_histogram[x, y, o]
    """
    The fourth stage computes normalisation, which takes local groups of
    cells and contrast normalises their overall responses before passing
    to next stage. Normalisation introduces better invariance to illumination,
    shadowing, and edge contrast. It is performed by accumulating a measure
    of local histogram "energy" over local groups of cells that we call
    "blocks". The result is used to normalise each cell in the block.
    Typically each individual cell is shared between several blocks, but
    its normalisations are block dependent and thus different. The cell
    thus appears several times in the final output vector with different
    normalisations. This may seem redundant but it improves the performance.
    We refer to the normalised block descriptors as Histogram of Oriented
    Gradient (HOG) descriptors.
    """

    n_blocksx = (n_cellsx - bx) + 1
    n_blocksy = (n_cellsy - by) + 1
    normalised_blocks = np.zeros((n_blocksx, n_blocksy, bx, by, orientations))

    for x in range(n_blocksx):
        for y in range(n_blocksy):
            block = orientation_histogram[x:x + bx, y:y + by, :]
            eps = 1e-5
            normalised_blocks[x, y, :] = block / sqrt(block.sum()**2 + eps)
    """
    The final step collects the HOG descriptors from all blocks of a dense
    overlapping grid of blocks covering the detection window into a combined
    feature vector for use in the window classifier.
    """

    if visualise:
        return normalised_blocks.ravel(), hog_image
    else:
        return normalised_blocks.ravel()
Example #38
0
def hof(flow, orientations=9, pixels_per_cell=(8, 8),
        cells_per_block=(3, 3), visualise=False, normalise=False, motion_threshold=1.):
    """Extract Histogram of Optical Flow (HOF) for a given image.
    Key difference between this and HOG is that flow is MxNx2 instead of MxN
    Compute a Histogram of Optical Flow (HOF) by
        1. (optional) global image normalisation
        2. computing the dense optical flow
        3. computing flow histograms
        4. normalising across blocks
        5. flattening into a feature vector
    Parameters
    ----------
    Flow : (M, N) ndarray
        Input image (x and y flow images).
    orientations : int
        Number of orientation bins.
    pixels_per_cell : 2 tuple (int, int)
        Size (in pixels) of a cell.
    cells_per_block  : 2 tuple (int,int)
        Number of cells in each block.
    visualise : bool, optional
        Also return an image of the hof.
    normalise : bool, optional
        Apply power law compression to normalise the image before
        processing.
    static_threshold : threshold for no motion
    Returns
    -------
    newarr : ndarray
        hof for the image as a 1D (flattened) array.
    hof_image : ndarray (if visualise=True)
        A visualisation of the hof image.
    References
    ----------
    * http://en.wikipedia.org/wiki/Histogram_of_oriented_gradients
    * Dalal, N and Triggs, B, Histograms of Oriented Gradients for
      Human Detection, IEEE Computer Society Conference on Computer
      Vision and Pattern Recognition 2005 San Diego, CA, USA
    """
    flow = np.atleast_2d(flow)

    """ 
    -1-
    The first stage applies an optional global image normalisation
    equalisation that is designed to reduce the influence of illumination
    effects. In practice we use gamma (power law) compression, either
    computing the square root or the log of each colour channel.
    Image texture strength is typically proportional to the local surface
    illumination so this compression helps to reduce the effects of local
    shadowing and illumination variations.
    """

    if flow.ndim < 3:
        raise ValueError("Requires dense flow in both directions")

    if normalise:
        flow = sqrt(flow)

    """ 
    -2-
    The second stage computes first order image gradients. These capture
    contour, silhouette and some texture information, while providing
    further resistance to illumination variations. The locally dominant
    colour channel is used, which provides colour invariance to a large
    extent. Variant methods may also include second order image derivatives,
    which act as primitive bar detectors - a useful feature for capturing,
    e.g. bar like structures in bicycles and limbs in humans.
    """

    if flow.dtype.kind == 'u':
        # convert uint image to float
        # to avoid problems with subtracting unsigned numbers in np.diff()
        flow = flow.astype('float')

    gx = np.zeros(flow.shape[:2])
    gy = np.zeros(flow.shape[:2])
    # gx[:, :-1] = np.diff(flow[:,:,1], n=1, axis=1)
    # gy[:-1, :] = np.diff(flow[:,:,0], n=1, axis=0)

    gx = flow[:, :, 1]
    gy = flow[:, :, 0]

    """ 
    -3-
    The third stage aims to produce an encoding that is sensitive to
    local image content while remaining resistant to small changes in
    pose or appearance. The adopted method pools gradient orientation
    information locally in the same way as the SIFT [Lowe 2004]
    feature. The image window is divided into small spatial regions,
    called "cells". For each cell we accumulate a local 1-D histogram
    of gradient or edge orientations over all the pixels in the
    cell. This combined cell-level 1-D histogram forms the basic
    "orientation histogram" representation. Each orientation histogram
    divides the gradient angle range into a fixed number of
    predetermined bins. The gradient magnitudes of the pixels in the
    cell are used to vote into the orientation histogram.
    """

    magnitude = sqrt(gx ** 2 + gy ** 2)
    orientation = arctan2(gy, gx) * (180 / pi) % 180

    sy, sx = flow.shape[:2]
    cx, cy = pixels_per_cell
    bx, by = cells_per_block

    n_cellsx = int(np.floor(sx // cx))  # number of cells in x
    n_cellsy = int(np.floor(sy // cy))  # number of cells in y

    # compute orientations integral images
    orientation_histogram = np.zeros((n_cellsy, n_cellsx, orientations))
    subsample = np.index_exp[int(cy / 2):cy * n_cellsy:cy, int(cx / 2):cx * n_cellsx:cx]
    for i in range(orientations - 1):
        # create new integral image for this orientation
        # isolate orientations in this range

        temp_ori = np.where(orientation < 180 / orientations * (i + 1),
                            orientation, -1)
        temp_ori = np.where(orientation >= 180 / orientations * i,
                            temp_ori, -1)
        # select magnitudes for those orientations
        cond2 = (temp_ori > -1) * (magnitude > motion_threshold)
        temp_mag = np.where(cond2, magnitude, 0)

        temp_filt = uniform_filter(temp_mag, size=(cy, cx))
        orientation_histogram[:, :, i] = temp_filt[subsample]

    ''' Calculate the no-motion bin '''
    temp_mag = np.where(magnitude <= motion_threshold, magnitude, 0)

    temp_filt = uniform_filter(temp_mag, size=(cy, cx))
    orientation_histogram[:, :, -1] = temp_filt[subsample]

    # now for each cell, compute the histogram
    hof_image = None

    if visualise:
        from skimage import draw

        radius = min(cx, cy) // 2 - 1
        hof_image = np.zeros((sy, sx), dtype=float)
        for x in range(n_cellsx):
            for y in range(n_cellsy):
                for o in range(orientations - 1):
                    centre = tuple([y * cy + cy // 2, x * cx + cx // 2])
                    dx = int(radius * cos(float(o) / orientations * np.pi))
                    dy = int(radius * sin(float(o) / orientations * np.pi))
                    rr, cc = draw.bresenham(centre[0] - dy, centre[1] - dx,
                                            centre[0] + dy, centre[1] + dx)
                    hof_image[rr, cc] += orientation_histogram[y, x, o]

    """
    The fourth stage computes normalisation, which takes local groups of
    cells and contrast normalises their overall responses before passing
    to next stage. Normalisation introduces better invariance to illumination,
    shadowing, and edge contrast. It is performed by accumulating a measure
    of local histogram "energy" over local groups of cells that we call
    "blocks". The result is used to normalise each cell in the block.
    Typically each individual cell is shared between several blocks, but
    its normalisations are block dependent and thus different. The cell
    thus appears several times in the final output vector with different
    normalisations. This may seem redundant but it improves the performance.
    We refer to the normalised block descriptors as Histogram of Oriented
    Gradient (hog) descriptors.
    """

    n_blocksx = (n_cellsx - bx) + 1
    n_blocksy = (n_cellsy - by) + 1
    normalised_blocks = np.zeros((n_blocksy, n_blocksx,
                                  by, bx, orientations))

    for x in range(n_blocksx):
        for y in range(n_blocksy):
            block = orientation_histogram[y:y + by, x:x + bx, :]
            eps = 1e-5
            normalised_blocks[y, x, :] = block / sqrt(block.sum() ** 2 + eps)

    """
    The final step collects the hof descriptors from all blocks of a dense
    overlapping grid of blocks covering the detection window into a combined
    feature vector for use in the window classifier.
    """

    if visualise:
        return normalised_blocks.ravel(), hof_image
    else:
        shape = normalised_blocks.shape
        return normalised_blocks.reshape(shape[0], shape[1], (shape[2]*shape[3]*shape[4]))
Example #39
0
                import numpy as np
                fig = plt.figure()
                ax = fig.gca(projection='3d')
                X = phis_far_field * pi / 180.
                Y = thetas_far_field * pi / 180.
                #X, Y = np.meshgrid(X, Y)
                #surf = ax.plot_surface(X, Y, sigma_theta+sigma_phi, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False)
                #ax.zaxis.set_major_locator(LinearLocator(10))
                #ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
                #fig.colorbar(surf, shrink=0.5, aspect=5)
                #plt.show()

                phis, thetas = np.meshgrid(X, Y)
                SIGMA = sigma_phi + sigma_theta
                SIGMA = SIGMA / amax(SIGMA)
                X = SIGMA * cos(phis) * sin(thetas)
                Y = SIGMA * sin(phis) * sin(thetas)
                Z = SIGMA * cos(thetas)
                surf = ax.plot_surface(X,
                                       Y,
                                       Z,
                                       rstride=1,
                                       cstride=1,
                                       cmap=cm.jet,
                                       linewidth=0.2)
                ax.zaxis.set_major_locator(LinearLocator(10))
                ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
                fig.colorbar(surf, shrink=0.5, aspect=5)
                ax.set_xlabel('X axis')
                ax.set_ylabel('Y axis')
                ax.set_zlabel('Z axis')
Example #40
0
def rotate_vecs(x, y, angle):
    xrot = x * scipy.cos(angle) - y * scipy.sin(angle)
    yrot = x * scipy.sin(angle) + y * scipy.cos(angle)
    return xrot, yrot
Example #41
0
def rotation_matrix(angle):
    A = scipy.array([[scipy.cos(angle), -scipy.sin(angle)],
                     [scipy.sin(angle), scipy.cos(angle)]])
    return A
Example #42
0
def radar_cross_section(frequency, theta, phi, An, Bn):
    """
    Calculate the radar cross section for a stratified sphere.
    :param frequency: The frequency of the incident wave (Hz).
    :param theta: The observation angle theta (rad).
    :param phi: The observation angle phi (rad).
    :param An: Scattering coefficient.
    :param Bn:Scattering coefficient.
    :return: The radar cross section for a stratified sphere.
    """
    # Wavelength
    wavelength = c / frequency

    # Wavenumber
    k = 2.0 * pi / wavelength

    st = abs(sin(theta))
    ct = cos(theta)

    # Associated Legendre Polynomial
    p_lm = zeros(len(An) + 1)
    p_lm[0] = -st
    p_lm[1] = -3.0 * st * ct

    s1 = 0
    s2 = 0

    p = p_lm[0]

    for i_mode in range(1, len(An) + 1):
        # Derivative of associated Legendre Polynomial
        if abs(ct) < 0.999999999:
            if i_mode == 1:
                dp = ct * p_lm[0] / sqrt(1.0 - ct**2)
            else:
                dp = (i_mode * ct * p_lm[i_mode - 1] -
                      (i_mode + 1.0) * p_lm[i_mode - 2]) / sqrt(1.0 - ct**2)

        if st > 1.0e-9:
            t1 = An[i_mode - 1] * p / st
            t2 = Bn[i_mode - 1] * p / st

        if ct > 0.999999999:
            val = 1j**(i_mode - 1) * (i_mode * (i_mode + 1.0) / 2.0) * (
                An[i_mode - 1] - 1j * Bn[i_mode - 1])
            s1 += val
            s2 += val
        elif ct < -0.999999999:
            val = (-1j)**(i_mode - 1) * (i_mode * (i_mode + 1.0) / 2.0) * (
                An[i_mode - 1] + 1j * Bn[i_mode - 1])
            s1 += val
            s2 -= val
        else:
            s1 += 1j**(i_mode + 1) * (t1 - 1j * Bn[i_mode - 1] * dp)
            s2 += 1j**(i_mode + 1) * (An[i_mode - 1] * dp - 1j * t2)

        # Recurrence relationship for nex Associated Legendre Polynomial
        if i_mode > 1:
            p_lm[i_mode] = (2.0 * i_mode +
                            1.0) * ct * p_lm[i_mode - 1] / i_mode - (
                                i_mode + 1.0) * p_lm[i_mode - 2] / i_mode

        p = p_lm[i_mode]

    rcs_th = s1 * cos(radians(phi)) * sqrt(4.0 * pi) / k
    rcs_ph = -s2 * sin(radians(phi)) * sqrt(4.0 * pi) / k

    return rcs_th, rcs_ph
    def predict(self, tilt):
        n_start_fit = 3
        tilt_series = self.getCurrentTiltSeries()
        tilt_group = self.getCurrentTiltGroup()
        current_tilt_direction = tilt_group.is_plus_tilt
        n_tilt_series = len(self.valid_tilt_series_list)
        n_tilt_groups = len(tilt_series)
        n_tilts = len(tilt_group)
        n = []
        gmaxtilt = []
        gmintilt = []
        for s in self.valid_tilt_series_list:
            for g in s.tilt_groups:
                if g.is_plus_tilt is not current_tilt_direction:
                    continue
                n.append(len(g))
                # old tilts may be aborted before start and therefore tilts=[]
                if len(g.tilts) > 0:
                    gmaxtilt.append(max(g.tilts))
                    gmintilt.append(min(g.tilts))
        maxtilt = max(gmaxtilt)
        mintilt = min(gmintilt)
        parameters = self.getCurrentParameters()
        if n_tilts < 1:
            raise RuntimeError
        elif n_tilts < 2:
            if len(self.tilt_series_list) != len(self.valid_tilt_series_list):
                print "%s out of %s tilt series are used in prediction" % (len(
                    self.valid_tilt_series_list), len(self.tilt_series_list))
            x, y = tilt_group.xs[-1], tilt_group.ys[-1]
            z = 0.0
        # calculate real z correction with current parameters
        elif n_tilts < n_start_fit:
            x, y = tilt_group.xs[-1], tilt_group.ys[-1]

            x0 = tilt_group.xs[0]
            y0 = tilt_group.ys[0]
            tilt0 = tilt_group.tilts[0]
            cos_tilts = scipy.cos(scipy.array([tilt0, tilt]))
            sin_tilts = scipy.sin(scipy.array([tilt0, tilt]))
            parameters = self.getCurrentParameters()
            args_list = [(cos_tilts, sin_tilts, x0, y0, None, None)]
            result = self.model(parameters, args_list)
            z0 = parameters[2]
            z = result[-1][-1][2] - z0
            x = result[-1][-1][0]
            y = result[-1][-1][1]

        else:
            if n_tilts != n_start_fit:
                self.forcemodel = False
            else:
                r2 = [0, 0]
                r2[0] = abs(
                    self._getCorrelationCoefficient(tilt_group.tilts[1:],
                                                    tilt_group.xs[1:]))
                r2[1] = abs(
                    self._getCorrelationCoefficient(tilt_group.tilts[1:],
                                                    tilt_group.ys[1:]))
                r2xy = abs(
                    self._getCorrelationCoefficient(tilt_group.xs[1:],
                                                    tilt_group.ys[1:]))
                if max(r2) > 0.95 and r2xy > 0.95 and not self.fixed_model:
                    self.forcemodel = True
                else:
                    self.forcemodel = False
            # x,y is only a smooth polynomial fit
            x, y = self.leastSquaresXY(tilt_group.tilts, tilt_group.xs,
                                       tilt_group.ys, tilt)
            #       tilt_group.addTilt(tilt, x, y)
            ## calculate optical axis tilt and offset
            if (abs(maxtilt) < math.radians(30)
                    and abs(mintilt) < math.radians(30)):
                ## optical axis offset fit is not reliable at small tilts
                orig_fixed_model = self.fixed_model
                self.fixed_model = True
                self.calculate()
                self.fixed_model = orig_fixed_model
            else:
                self.calculate()

        #       del tilt_group.tilts[-1]
        #       del tilt_group.xs[-1]
        #       del tilt_group.ys[-1]

            x0 = tilt_group.xs[0]
            y0 = tilt_group.ys[0]
            tilt0 = tilt_group.tilts[0]
            cos_tilts = scipy.cos(scipy.array([tilt0, tilt]))
            sin_tilts = scipy.sin(scipy.array([tilt0, tilt]))
            parameters = self.getCurrentParameters()
            args_list = [(cos_tilts, sin_tilts, x0, y0, None, None)]
            result = self.model(parameters, args_list)
            z0 = result[-1][0][2]
            z = result[-1][-1][2] - z0

        phi, offset = self.convertparams(self.parameters[0],
                                         self.parameters[1])
        result = {
            'x': float(x),
            'y': float(y),
            'z': float(z),
            'phi': float(phi),
            'optical axis': float(offset),
            'z0': float(self.parameters[-1]),
        }
        return result
Example #44
0
def number_of_muons_gradient(fita, sigma_s, sigma_o, k):
    # Function to integrate- return number of muons as a function of s I do not use it anymore
    return (k * (sigma_s * (1 + sp.cos(fita) * sp.cos(fita)) +
                 (sigma_o * sp.cos(fita))))
Example #45
0
import scipy as sp
import scipy.misc
import scipy.constants
from scipy import pi

if __name__ == "__main__" and __package__ is None:
    sys.path.append('..')
    __package__ = "doamusic"
import doamusic
from doamusic import music
from doamusic import _music
from doamusic import util

# 16 element unit circle in the y-z plane
antx = sp.arange(16)
circarray = sp.array([0 * antx, sp.cos(antx), sp.sin(antx)]).T

# 3 offset circles in planes parallel to y-z
front = circarray + [1, 0, 0]
back = circarray - [1, 0, 0]
triplecircarray = sp.concatenate((front, circarray, back))

# unit spacing grid (5x5)
gridarray = sp.array([(0, y, z)
                      for y, z in itertools.product(range(-3, 4), repeat=2)])

# unit spacing linear
linarray = sp.array([(0, y, 0) for y in range(10)])

# Arrays as constructed.
operating_frequency = 2.477e9
Example #46
0
    def _update_canvas(self):
        """
        Update the figure when the user changes an input value.
        :return:
        """
        seterr(divide='ignore')
        # Generate a sample signal to be used (later used matched filter output)
        number_of_samples = 1000
        i_noise = rnd.normal(0, 0.05, number_of_samples)
        q_noise = rnd.normal(0, 0.05, number_of_samples)

        noise_signal = sqrt(i_noise**2 + q_noise**2)

        # Create the time array
        t = linspace(0.0, 1.0, number_of_samples)

        # Create example signal for the CFAR process
        s1 = 0.4 * cos(2 * pi * 600 * t) + 1j * 0.4 * sin(2 * pi * 600 * t)
        s2 = 0.1 * cos(2 * pi * 150 * t) + 1j * 0.1 * sin(2 * pi * 150 * t)
        s3 = 0.2 * cos(2 * pi * 100 * t) + 1j * 0.2 * sin(2 * pi * 100 * t)

        # Sum for the example signal
        signal = abs(fftpack.fft(s1 + s2 + s3 + noise_signal))
        signal[0] = 0

        # Get the CFAR type from the form
        cfar_type = self.cfar_type.currentText()

        # Set up the key word args for the inputs
        kwargs = {
            'signal': signal,
            'guard_cells': int(self.guard_cells.text()),
            'reference_cells': int(self.reference_cells.text()),
            'bias': float(self.bias.text()),
            'cfar_type': cfar_type
        }

        # Calculate the CFAR threshold
        cfar_threshold = cfar(**kwargs)

        # Clear the axes for the updated plot
        self.axes1.clear()

        # Display the results
        self.axes1.plot(10.0 * log10(signal), '', label='Signal')
        self.axes1.plot(cfar_threshold, 'r--', label='CFAR Threshold')

        # Set the plot title and labels
        self.axes1.set_title('Constant False Alarm Rate', size=14)
        self.axes1.set_ylabel('Signal Strength (dB)', size=12)
        self.axes1.set_xlabel('Range (m)', size=12)
        self.axes1.set_ylim(-10, 30)

        # Set the tick label size
        self.axes1.tick_params(labelsize=12)

        # Set the legend
        self.axes1.legend(loc='upper right', prop={'size': 10})

        # Turn on the grid
        self.axes1.grid(linestyle=':', linewidth=0.5)

        # Update the canvas
        self.my_canvas.draw()
Example #47
0
def doTrial(cfg):

    # set up the target:
    targetangle_deg = cfg['tasks'][cfg['taskno']]['target'][cfg['trialno']]
    targetangle = (targetangle_deg / 180) * sp.pi
    targetpos = [
        sp.cos(targetangle) * cfg['targetdistance'],
        sp.sin(targetangle) * cfg['targetdistance']
    ]
    cfg['target'].pos = targetpos

    # hold home before reach:
    holdTime = 0.5

    # phase 0: do pre-reach aiming if required:
    doAim = cfg['tasks'][cfg['taskno']]['aiming'][cfg['trialno']]
    if doAim:

        cfg = doAiming(cfg)
        aim = cfg['aim']

    else:

        # if not required: set to correct value for data file:
        aim = sp.NaN

        # how long does one aiming trial take?
        holdTime = holdTime + 1.5

    # trials need to know whether or not there is a cursor
    showcursor = cfg['tasks'][cfg['taskno']]['cursor'][cfg['trialno']]

    # for trials with / without strategy, we should record that:
    usestrategy = cfg['tasks'][cfg['taskno']]['strategy'][cfg['trialno']]

    # set up rotation matrix for current rotation:
    rotation = cfg['tasks'][cfg['taskno']]['rotation'][cfg['trialno']]
    theta = (rotation / 180.) * sp.pi
    R = sp.array([[sp.cos(theta), -1 * sp.sin(theta)],
                  [sp.sin(theta), sp.cos(theta)]],
                 order='C')

    trialDone = False
    phase = 0

    # create lists to store data in:
    mouseX = []
    mouseY = []
    cursorX = []
    cursorY = []
    time_s = []

    while not (trialDone):

        [X, Y, T] = cfg['mouse'].getPos()

        cursorpos = list(R.dot(sp.array([[X], [Y]])).flatten())
        cfg['cursor'].pos = cursorpos
        cursorangle = sp.arctan2(cursorpos[1], cursorpos[0])

        mouseX.append(X)
        mouseY.append(Y)
        cursorX.append(cursorpos[0])
        cursorY.append(cursorpos[1])
        time_s.append(T)

        if (phase == 2):
            cfg['target'].draw()
            if showcursor:
                cfg['cursor'].draw()
                if (sp.sqrt(
                        sp.sum((sp.array(cursorpos) - sp.array(targetpos))**
                               2))) < cfg['radius']:
                    phase = 3
            else:
                #print('no-cursor, phase 2')
                idx = sp.argmin(abs(sp.array(time_s) + 0.250 - time_s[-1]))
                if (sp.sqrt(mouseX[-1]**2 + mouseY[-1]**2)) > (cfg['NSU'] *
                                                               .5):
                    distance = sp.sum(
                        sp.sqrt(
                            sp.diff(sp.array([mouseX[idx:]]))**2 +
                            sp.diff(sp.array([mouseY[idx:]]))**2))
                    if distance < (0.01 * cfg['NSU']):
                        phase = 3

        if (phase == 1):
            #cfg['home'].draw()
            cfg['cursor'].draw()
            if (time.time() > (phaseOneStart + holdTime)):
                # held the home position for long enough, going to phase 2:
                phase = 2
            if (sp.sqrt(sp.sum(sp.array(cursorpos)**2)) > cfg['radius']):
                # hold not maintained, restart phase 0:
                phase = 0

        if (phase == 0) or (phase == 3):
            cfg['home'].draw()
            if showcursor:
                cfg['cursor'].draw()
            else:
                #print('no-cursor, phase 1 or 3')
                if (sp.sqrt(sum([c**2 for c in cursorpos])) <
                    (0.15 * cfg['NSU'])):
                    cfg['cursor'].draw()
                else:
                    # put arrow in home position
                    grain = (2 * sp.pi) / 8
                    arrowangle = (((cursorangle -
                                    (grain / 2)) // grain) * grain) + grain
                    cfg['home_arrow'].ori = ((-1 * arrowangle) / sp.pi) * 180
                    cfg['home_arrow'].draw()
            #print([sp.sqrt(sp.sum(sp.array(cursorpos)**2)), (0.025 * cfg['NSU'])])
            if (sp.sqrt(sp.sum(sp.array(cursorpos)**2)) < cfg['radius']):
                if phase == 0:
                    phase = 1
                    phaseOneStart = time.time()
                if phase == 3:
                    trialDone = True

        #cfg['target'].draw()
        cfg['win'].flip()

        if cfg['keyboard'][key.ESCAPE]:
            sys.exit('escape key pressed')

    # make data frame and store as csv file...

    nsamples = len(time_s)

    task_idx = [cfg['taskno'] + 1] * nsamples
    trial_idx = [cfg['trialno'] + 1] * nsamples
    cutrial_no = [cfg['totrialno'] + 1] * nsamples
    targetangle_deg = [targetangle_deg] * nsamples
    targetx = [targetpos[0]] * nsamples
    targety = [targetpos[1]] * nsamples
    rotation_deg = [rotation] * nsamples
    doaiming_bool = [cfg['tasks'][cfg['taskno']]['aiming'][cfg['trialno']]
                     ] * nsamples
    showcursor_bool = [showcursor] * nsamples
    usestrategy_cat = [usestrategy] * nsamples

    cutime_ms = [int((t - cfg['expstart']) * 1000) for t in time_s]
    time_ms = [t - cutime_ms[0] for t in cutime_ms]

    aim_deg = [aim] * nsamples
    if sp.isnan(aim):
        aimdeviation_deg = aim_deg
        aimstart_deg = aim_deg
        aimtime_ms = aim_deg
    else:
        aimdeviation_deg = (aim - targetangle_deg[0]) % 360
        if aimdeviation_deg > 180:
            aimdeviation_deg = aimdeviation_deg - 360
        aimdeviation_deg = [aimdeviation_deg] * nsamples
        aimstart_deg = [
            targetangle_deg[0] +
            cfg['tasks'][cfg['taskno']]['aimoffset'][cfg['trialno']]
        ] * nsamples
        aimtime_ms = [cfg['aimtime_ms']] * nsamples

    # put all lists in dictionary:
    trialdata = {
        'task_idx': task_idx,
        'trial_idx': trial_idx,
        'cutrial_no': cutrial_no,
        'targetangle_deg': targetangle_deg,
        'targetx': targetx,
        'targety': targety,
        'rotation_deg': rotation_deg,
        'doaiming_bool': doaiming_bool,
        'aimstart_deg': aimstart_deg,
        'showcursor_bool': showcursor_bool,
        'usestrategy_cat': usestrategy_cat,
        'aim_deg': aim_deg,
        'aimdeviation_deg': aimdeviation_deg,
        'aimtime_ms': aimtime_ms,
        'cutime_ms': cutime_ms,
        'time_ms': time_ms,
        'mousex': mouseX,
        'mousey': mouseY,
        'cursorx': cursorX,
        'cursory': cursorY
    }
    # make dictionary into data frame:
    trialdata = pd.DataFrame(trialdata)

    # store data frame:
    filename = 'data/%s/p%03d/task%02d-trial%04d.csv' % (
        cfg['groupname'], cfg['ID'], cfg['taskno'] + 1, cfg['trialno'] + 1)
    trialdata.to_csv(filename, index=False, float_format='%0.5f')

    return (cfg)
    def peval(self, p, f):
        d = self.d
        dG = p[0]
        al = ((p[1] + 180) % 360 - 180) * sp.pi / 180
        ps = ((p[2] + 180) % 360 - 180) * sp.pi / 180
        ph = ((p[3] + 180) % 360 - 180) * sp.pi / 180
        ep = p[4]
        ch = ((p[5] + 180) % 360 - 180) * sp.pi / 180
        flux = p[
            6]  #This is a variable for accounting for the difference in flux.
        be = ((p[7] + 180) % 360 - 180) * sp.pi / 180
        theta = self.theta
        t = self.function
        m_tot = sp.zeros((4, 4), float)
        m_tot[0, 0] = flux
        m_IQ = flux * (0.5 * dG * sp.cos(2. * al) -
                       2. * ep * sp.cos(ph - ch) * sp.sin(2. * al))
        m_IU = flux * (0.5 * dG * sp.sin(2. * al) * sp.cos(ch) + 2 * ep *
                       (sp.cos(al) * sp.cos(al) * sp.cos(ph) -
                        sp.sin(al) * sp.sin(al) * sp.cos(ph - 2. * ch)))
        m_tot[0, 1] = m_IQ
        m_tot[0, 2] = m_IU
        m_tot[0,
              3] = flux * (0.5 * dG * sp.sin(2. * al) * sp.sin(ch) + 2 * ep *
                           (sp.cos(al) * sp.cos(al) * sp.sin(ph) +
                            sp.sin(al) * sp.sin(al) * sp.sin(ph - 2. * ch)))
        m_tot[1, 0] = flux * 0.5 * dG
        m_QQ = flux * sp.cos(2. * al)
        m_QU = flux * sp.sin(2 * al) * sp.cos(ch)
        m_tot[1, 1] = m_QQ
        m_tot[1, 2] = m_QU
        m_tot[1, 3] = flux * sp.sin(2. * al) * sp.sin(ch)
        m_tot[2, 0] = flux * 2 * ep * sp.cos(ph + ps)
        m_UQ = -flux * sp.sin(2 * al) * sp.cos(ps + ch)
        m_UU = flux * (sp.cos(al) * sp.cos(al) * sp.cos(ps) -
                       sp.sin(al) * sp.sin(al) * sp.cos(ps + 2. * ch))
        m_tot[2, 1] = m_UQ
        m_tot[2, 2] = m_UU
        m_tot[2, 3] = flux * (-sp.cos(al) * sp.cos(al) * sp.sin(ps) -
                              sp.sin(al) * sp.sin(al) * sp.sin(ps + 2. * ch))
        m_tot[3, 0] = flux * 2 * ep * sp.sin(ps + ph)
        m_VQ = -flux * sp.sin(2 * al) * sp.sin(ps + ch)
        m_VU = flux * (sp.sin(ps) * sp.cos(al) * sp.cos(al) -
                       sp.sin(al) * sp.sin(al) * sp.sin(ps + 2. * ch))
        m_tot[3, 1] = m_VQ
        m_tot[3, 2] = m_VU
        m_tot[3, 3] = flux * (sp.cos(al) * sp.cos(al) * sp.cos(ps) +
                              sp.sin(al) * sp.sin(al) * sp.cos(ps + 2. * ch))
        M_total = sp.mat(m_tot)
        M_total = M_total.I

        for i in range(0, len(t), 4):
            t[i] = M_total[0, 0] * d[i, f] + M_total[0, 1] * d[
                i + 1, f] + M_total[0, 2] * d[i + 2,
                                              f] + M_total[0, 3] * d[i + 3, f]
            t[i +
              1] = (M_total[1, 0] * sp.cos(2 * theta[i]) -
                    M_total[2, 0] * sp.sin(2 * theta[i])) * d[i, f] + (
                        M_total[1, 1] * sp.cos(2 * theta[i]) -
                        M_total[2, 1] * sp.sin(2 * theta[i])) * d[i + 1, f] + (
                            M_total[1, 2] * sp.cos(2 * theta[i]) -
                            M_total[2, 2] * sp.sin(2 * theta[i])
                        ) * d[i + 2, f] + (
                            M_total[1, 3] * sp.cos(2 * theta[i]) -
                            M_total[2, 3] * sp.sin(2 * theta[i])) * d[i + 3, f]
            t[i +
              2] = (M_total[1, 0] * sp.sin(2 * theta[i]) +
                    M_total[2, 0] * sp.cos(2 * theta[i])) * d[i, f] + (
                        M_total[1, 1] * sp.sin(2 * theta[i]) +
                        M_total[2, 1] * sp.cos(2 * theta[i])) * d[i + 1, f] + (
                            M_total[1, 2] * sp.sin(2 * theta[i]) +
                            M_total[2, 2] * sp.cos(2 * theta[i])
                        ) * d[i + 2, f] + (
                            M_total[1, 3] * sp.sin(2 * theta[i]) +
                            M_total[2, 3] * sp.cos(2 * theta[i])) * d[i + 3, f]
            t[i + 3] = M_total[3, 0] * d[i, f] + M_total[3, 1] * d[
                i + 1, f] + M_total[3, 2] * d[i + 2,
                                              f] + M_total[3, 3] * d[i + 3, f]
        return t
Example #49
0
        else:
            print "plotting only supported for indim=1 or indim=2."


if __name__ == '__main__':

    from pylab import figure, show

    # --- example on how to use the GP in 1 dimension
    ds = SupervisedDataSet(1, 1)
    gp = GaussianProcess(indim=1, start=-3, stop=3, step=0.05)
    figure()

    x = mgrid[-3:3:0.2]
    y = 0.1 * x**2 + x + 1
    z = sin(x) + 0.5 * cos(y)

    ds.addSample(-2.5, -1)
    ds.addSample(-1.0, 3)
    gp.mean = 0

    # new feature "autonoise" adds uncertainty to data depending on
    # it's distance to other points in the dataset. not tested much yet.
    # gp.autonoise = True

    gp.trainOnDataset(ds)
    gp.plotCurves(showSamples=True)

    # you can also test the gp on single points, but this deletes the
    # original testing grid. it can be restored with a call to _buildGrid()
    print gp.testOnArray(array([[0.4]]))
Example #50
0
def plot_circle(circ, color='k'):
    phi = sp.linspace(0, 2 * sp.pi, 100)
    xc, yc, r = circ
    x = r * sp.cos(phi) + xc
    y = r * sp.sin(phi) + yc
    pl.plot(x, y, color)
Example #51
0
def sec(x):
    return 1 / cos(x)  # 関数 sec を定義
Example #52
0
    # array([t, exp(t-t**2)])

    N = [2 * n for n in range(100)]
    stepsize = []
    mean_error = []
    result = []
    expected = []
    # TODO: возможно, стоит сделать тесты автоматизироваными?
    for n in N:
        stepsize.append((te - t0) / (n + 1))
        timeGrid = linspace(t0, te, n + 2)
        expected = [
            array([
                t, -exp(-t / 2) * sin(t * sqrt(3) / 2),
                exp(-t / 2) * ((-1 / 2) * sin(t * sqrt(3) / 2) +
                               (sqrt(3) / 2) * cos(t * sqrt(3) / 2))
            ]) for t in timeGrid
        ]
        method = Gauss(f, init, t0, te, n)
        method.solve()
        result = method.solution
        print(result)
        error = [
            norm(expected[i][1:] - result[i][1:]) for i in range(len(timeGrid))
        ]
        mean = np.mean(error)
        mean_error.append(mean)
        print(mean, error[1])
    result = array(result)
    expected = array(expected)
    X, Y = result[:, 1].flatten(), result[:, 2].flatten()
Example #53
0
# définition des paramètres du paquet d'onde inital
x0 = x[Nx/4]                 # position initiale du paquet
sigma = 2.e-10               # largeur du paquet en m
Lambda = 1.5e-10             # longeur d'onde de de Broglie l'électron (en m)
Ec = (h/Lambda)**2/(2*m_e*e) # énergie cinétique théorique de l'électron (en eV)

# définition des coefficients constants
a1 = -(hbar**2/(2*m_e*e*dx**2))

# initialisation des buffers de calcul aux conditions initiales
Psi_Real = zeros(Nx)
Psi_Imag = zeros(Nx)
Psi_Prob = zeros(Nx)

# calcul de la fonction d'onde initiale
Psi_Real = exp(-0.5*((x-x0)/sigma)**2)*cos(DeuxPi*(x-x0)/Lambda)
Psi_Imag = exp(-0.5*((x-x0)/sigma)**2)*sin(DeuxPi*(x-x0)/Lambda)
# normalisation du paquet d'onde
PsiPsiC = Psi_Real**2 + Psi_Imag**2
C = simps(PsiPsiC,x)
Psi_Real = Psi_Real/sqrt(C)
Psi_Imag = Psi_Imag/sqrt(C)
Psi_Prob = Psi_Real**2 + Psi_Imag**2
# calcul de l'énergie moyenne transportée par le paquet
En = zeros(Nx)
En[1:-1] = a1*(Psi_Real[1:-1] - 1j*Psi_Imag[1:-1]) \
           *(Psi_Real[2:] - 2*Psi_Real[1:-1] + Psi_Real[:-2] \
           + 1j*(Psi_Imag[2:] - 2*Psi_Imag[1:-1] + Psi_Imag[:-2]))                     
Ebarre = simps(En,x)
print "Energie theorique : " + str(Ec) + " eV"
print "Energie moyenne du paquet : " + str(Ebarre.real) + " eV"
Example #54
0
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D


def sec(x):
    return 1 / cos(x)  # 関数 sec を定義


u = linspace(0, 2 * pi, 20)  # メッシュ作成の変数方位角 θ 周り 0 から 2π,20 等分
v = linspace(0, 2 * pi, 20)  # メッシュ作成の変数方位角 φ 周り 0 から 2π,20 等分

epz = 3  # z 方向の誘電率の絶対値 (負の値)
epx = 5  # x 方向の誘電率 (正の値)
uu, vv = meshgrid(u, v)  # メッシュの作成

x = sqrt(epz) * sec(uu) * cos(vv)  # 屈折率楕円体の媒介変数表示 x 方向
y = sqrt(epz) * sec(uu) * sin(vv)  # 屈折率楕円体の媒介変数表示 y 方向
z = sqrt(epx) * tan(uu)  # 屈折率楕円体の媒介変数表示 z 方向

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_wireframe(x, y, z)  # ワイヤフレームのプロット
ax.set_xlabel('X')  # x 方向ラベル
ax.set_ylabel('Y')  # y 方向ラベル
ax.set_zlabel('Z')  # z 方向ラベル

ax.set_xlim3d(-20, 20)  # x 方向プロット範囲
ax.set_ylim3d(-20, 20)  # y 方向プロット範囲
ax.set_zlim3d(-30, 30)  # z 方向プロット範囲

plt.show()  # グラフの表示
Example #55
0
## Medium permittivity and permeability ##

EPSILON0 = 1  #8.854187817e-12
MU0 = 1  #4 * sp.pi * 1e-7
epsR = EPSILON0 * sp.ones((SIZE_R, SIZE_PHI))
muR = MU0 * sp.ones((SIZE_R, SIZE_PHI))

## Grid for plotting ##

grid = sp.mgrid[0:SIZE_R, 0:SIZE_PHI]

# Re-represent the grid values in cartesian coordinates
r = sp.array(grid[0], dtype=float)
r[0, :] = 0.000001
phi = 2 * grid[1]
gridx = r * sp.cos(sp.pi * phi / 180)
gridy = r * sp.sin(sp.pi * phi / 180)

## Coordinate-dependent scale factors ##

# We define the scale factors at *integral points*. Thus, the position of the
# scale factors does not coincide with *any* field point, because the fields
# are defined at points which are half-integral in at least one coordinate
h_r = sp.ones((SIZE_R, SIZE_PHI))
h_phi = r
h_z = sp.ones((SIZE_R, SIZE_PHI))

## Coefficients for update equations ##

# In this section, the notation cA_i_B_j is used to mean the coefficient of the
# j-component of B in the update equation for the i-component of A.
Example #56
0
def model_plot_track(depth, jdmat_m, lat_vel_1, lon_vel_1, u, v, lat_vel,
                     lon_vel, h_vel, siglay, startdate, numdays, daystep, x,
                     la, lo):
    fig = plt.figure(1)
    if len(depth) == 1:
        panels = len(startdate)
    if len(depth) != 1:
        panels = len(depth)
    for j in range(1, panels + 1):
        print int(str(panels) + str(2) + str(j))
        if panels == 1:
            ax = fig.add_subplot(111)
        else:
            ax = fig.add_subplot(int(str(2) + str(2) + str(j)))
        if j == 3:
            plt.xlabel('Longitude W')
        if j == 1:
            plt.ylabel('Latitude N')
        for k in range(len(la)):
            for m in range(len(lo)):
                (distance, index_location) = nearxy(lon_vel_1, lat_vel_1,
                                                    lo[m], la[k])
                (disth, index_location_h) = nearxy(lon_vel, lat_vel, lo[m],
                                                   la[k])

                depths = h_vel[index_location_h] * siglay[:, index_location_h]
                # make depths to be descending order
                new_depths = list(depths)
                new_depths.reverse()
                # depths range
                range_depths = range(len(depths))
                range_depths.reverse()
                if len(depth) == 1:
                    idz = 0
                else:
                    idz = int(
                        round(np.interp(depth[j - 1], new_depths,
                                        range_depths)))

                ####### get index of startdate in jdmat_m
                jdmat_m_num = []  # this is the data in the form of a number
                del_list, jdmat, del_index = [], [], []
                # convert array to list
                jdmat_m_list = [jdmat_m_i for jdmat_m_i in jdmat_m]

                # while seconds=60, can change the datetime to number, so delete
                for i in range(1, len(jdmat_m_list)):
                    if jdmat_m_list[i][17:19] == '60' or jdmat_m_list[
                            i - 1] == jdmat_m_list[i]:
                        del_list.append(jdmat_m_list[i])
                        del_index.append(i)  #get the index of deleted datetime
                jdmat = [val for val in jdmat_m_list if val not in del_list
                         ]  # delete the wrong value, jdmat just
                for i in jdmat:  # convert time to number
                    jdmat_m_num.append(
                        date2num(
                            dt.datetime.strptime(i, '%Y-%m-%dT%H:%M:%S.%f')))
                # get index of startdate in jdmat_m_num
                index_startdate_1 = int(
                    round(
                        np.interp(date2num(startdate[j - 1]), jdmat_m_num,
                                  range(len(jdmat_m_num)))))
                if del_index != []:
                    index_add = int(
                        np.ceil(
                            np.interp(index_startdate_1, del_index,
                                      range(len(del_index)))))
                    index_startdate = index_add + index_startdate_1
                else:
                    index_startdate = index_startdate_1
                # get u,v
                u1 = float(u[index_startdate, idz, index_location])
                v1 = float(v[index_startdate, idz, index_location])
                nsteps = scipy.floor(min(numdays, jdmat_m_num[-1]) / daystep)
                # get the velocity data at this first time & place
                lat_k = 'lat' + str(k)
                lon_k = 'lon' + str(k)
                uu, vv, lon_k, lat_k, time = [], [], [], [], []
                uu.append(u1)
                vv.append(v1)
                lat_k.append(la[k])
                lon_k.append(lo[m])
                time.append(date2num(startdate[j - 1]))

            for i in range(1, int(nsteps)):
                # first, estimate the particle move to its new position using velocity of previous time steps
                lat1 = lat_k[i - 1] + float(
                    vv[i - 1] * daystep * 24 * 3600) / 1000 / 1.8535 / 60
                lon1 = lon_k[i - 1] + float(
                    uu[i - 1] * daystep * 24 * 3600) / 1000 / 1.8535 / 60 * (
                        scipy.cos(float(lat_k[i - 1])) / 180 * np.pi)
                # find the closest model time for the new timestep
                jdmat_m_num_i = time[i - 1] + daystep
                time.append(jdmat_m_num_i)

                index_startdate_1 = int(
                    round(
                        np.interp(jdmat_m_num_i, jdmat_m_num,
                                  range(len(jdmat_m_num)))))
                if del_index != []:
                    index_add = int(
                        np.ceil(
                            np.interp(index_startdate_1, del_index,
                                      range(len(del_index)))))
                    index_startdate = index_add + index_startdate_1
                else:
                    index_startdate = index_startdate_1
                #find the point's index of near lat1,lon1
                index_location = nearxy(lon_vel_1, lat_vel_1, lon1, lat1)[1]
                ui = u[index_startdate, 1, index_location]
                vi = v[index_startdate, 1, index_location]
                vv.append(vi)
                uu.append(ui)
                # estimate the particle move from its new position using velocity of previous time steps
                lat_k.append(
                    float(lat1 + lat_k[i - 1] +
                          float(vv[i] * daystep * 24 * 3600) / 1000 / 1.8535 /
                          60) / 2)
                lon_k.append(
                    float(lon1 + lon_k[i - 1] +
                          float(uu[i] * daystep * 24 * 3600) / 1000 / 1.8535 /
                          60 * scipy.cos(float(lat_k[i]) / 180 * np.pi)) / 2)

            plt.plot(lon_k,
                     lat_k,
                     "-",
                     linewidth=1,
                     marker=".",
                     markerfacecolor='r')
            basemap([min(lat_k) - 2, max(lat_k) + 2],
                    [min(lon_k) - 2, max(lon_k) + 2])
            # make same size for the panels
            min_lat, max_lon, max_lat, min_lon = [], [], [], []
            min_lat.append(min(lat_k))
            max_lat.append(max(lat_k))
            min_lon.append(min(lon_k))
            max_lon.append(max(lon_k))

            text1 = ax.annotate(str(num2date(time[0]).month) + "-" +
                                str(num2date(time[0]).day),
                                xy=(lon_k[0], lat_k[0]),
                                xycoords='data',
                                xytext=(8, 10),
                                textcoords='offset points',
                                arrowprops=dict(arrowstyle="->"))
            text1.draggable()
            text1 = ax.annotate(str(num2date(time[-1]).month) + "-" +
                                str(num2date(time[-1]).day),
                                xy=(lon_k[-1], lat_k[-1]),
                                xycoords='data',
                                xytext=(8, 10),
                                textcoords='offset points',
                                arrowprops=dict(arrowstyle="->"))

        #set the numbers formatter
        majorFormatter = FormatStrFormatter('%.2f')
        ax.yaxis.set_major_formatter(majorFormatter)
        ax.xaxis.set_major_formatter(majorFormatter)
        if len(depth) == 1:
            plt.title(str(num2date(time[i - 1]).year))
        else:
            plt.title(
                str(num2date(time[i - 1]).year) + " year" + " depth: " +
                str(depth[j - 1]))

        ax.xaxis.set_label_coords(0.5, -0.005)  #set the position of the xlabel
        ax.yaxis.set_label_coords(-0.1, 0.5)
        plt.xlim([min(min_lon), max(max_lon)])
        plt.ylim([min(min_lat), max(max_lat)])
    plt.show()
Example #57
0
    def _update_canvas(self):
        """
        Update the figure when the user changes an input value
        :return:
        """
        # Get the parameters from the form
        frequency = float(self.frequency.text())
        number_of_elements = int(self.number_of_elements.text())
        scan_angle_theta = float(self.scan_angle_theta.text())
        scan_angle_phi = float(self.scan_angle_phi.text())
        radius = float(self.radius.text())

        # Set up the theta and phi arrays
        n = 360
        m = int(n / 8)
        theta, phi = meshgrid(linspace(0.0 * pi, 0.5 * pi, n),
                              linspace(0.0, 2.0 * pi, n))

        # Set up the args
        kwargs = {
            'number_of_elements': number_of_elements,
            'scan_angle_theta': radians(scan_angle_theta),
            'scan_angle_phi': radians(scan_angle_phi),
            'radius': radius,
            'frequency': frequency,
            'theta': theta,
            'phi': phi
        }

        # Get the array factor
        af = circular_uniform.array_factor(**kwargs)

        # Remove the color bar
        try:
            self.cbar.remove()
        except:
            # Initial plot
            pass

        # Clear the axes for the updated plot
        self.axes1.clear()

        # U-V coordinates for plotting the antenna pattern
        uu = sin(theta) * cos(phi)
        vv = sin(theta) * sin(phi)

        if self.plot_type.currentIndex() == 0:

            # Display the results
            im = self.axes1.pcolor(uu, vv, abs(af), cmap="jet")
            self.cbar = self.fig.colorbar(im,
                                          ax=self.axes1,
                                          orientation='vertical')
            self.cbar.set_label("Normalized Electric Field (V/m)", size=10)

            # Set the x- and y-axis labels
            self.axes1.set_xlabel("U (sines)", size=12)
            self.axes1.set_ylabel("V (sines)", size=12)

        elif self.plot_type.currentIndex() == 1:

            # Create the contour plot
            self.axes1.contour(uu,
                               vv,
                               abs(af),
                               20,
                               cmap="jet",
                               vmin=-0.2,
                               vmax=1.0)

            # Turn on the grid
            self.axes1.grid(linestyle=':', linewidth=0.5)

            # Set the x- and y-axis labels
            self.axes1.set_xlabel("U (sines)", size=12)
            self.axes1.set_ylabel("V (sines)", size=12)

        else:

            # Create the line plot
            self.axes1.plot(degrees(theta[0]),
                            20.0 * log10(abs(af[m])),
                            '',
                            label='E Plane')
            self.axes1.plot(degrees(theta[0]),
                            20.0 * log10(abs(af[0])),
                            '--',
                            label='H Plane')

            # Set the y axis limit
            self.axes1.set_ylim(-60, 5)

            # Set the x and y axis labels
            self.axes1.set_xlabel("Theta (degrees)", size=12)
            self.axes1.set_ylabel("Array Factor (dB)", size=12)

            # Turn on the grid
            self.axes1.grid(linestyle=':', linewidth=0.5)

            # Place the legend
            self.axes1.legend(loc='upper right', prop={'size': 10})

        # Set the plot title and labels
        self.axes1.set_title('Circular Array - Array Factor', size=14)

        # Set the tick label size
        self.axes1.tick_params(labelsize=12)

        # Update the canvas
        self.my_canvas.draw()
Example #58
0
dx = 0.1
t0 = 0.0
tmax = 500.0
dt = 0.1
x = arange(xmin, xmax, dx)
temps = arange(t0, tmax, dt)

# calcul d'une superposition de deux OPPH en milieu non dispersif
omega0 = 1000.0
domega = 1.0
k0 = 0.5
dk = 0.01
#mescourbes=[[2*Psi0*cos(domega*t - dk*xi)*cos(omega0*t - k0*xi) for xi in x] for t in temps]

# calcul d'un paquet d'ondes
mescourbes = [[
    2 * Psi0 * sinc(domega * t - dk * xi) * cos(omega0 * t - k0 * xi)
    for xi in x
] for t in temps]

# tracé de l'animation
fig = pyplot.figure()
ax = pyplot.axes(xlim=(0, xmax), ylim=(-1.0, 1.0))
courbe, = ax.plot(x, mescourbes[0])
line_ani = animation.FuncAnimation(fig,
                                   traceframe,
                                   100,
                                   interval=50,
                                   repeat=True)
pyplot.show()
Example #59
0
 def orbitPos(self, t):  #exact orbit position as f(t)
     x = self.orbitR * sp.cos(self.omega * t + self.theta)
     y = self.orbitR * sp.sin(self.omega * t + self.theta)
     return sp.array([x, y])
Example #60
0
def gettrack_FVCOM(depth, jdmat_m, lat_vel_1, lon_vel_1, u, v, lat_vel,
                   lon_vel, h_vel, siglay, startdate, numdays, daystep, la,
                   lo):
    """get the track for models"""

    # calculate the points near la,la
    (disth, index_location_h) = nearxy(lon_vel, lat_vel, lo, la)
    (distance, index_location) = nearxy(lon_vel_1, lat_vel_1, lo, la)
    # calculate all the depths
    depths = h_vel[index_location_h] * siglay[:, index_location_h]
    # make depths to be descending order
    new_depths = list(depths).reverse()
    # depths range
    range_depths = range(len(depths)).reverse()
    # calculate the index of depth in the depths
    idz = int(round(np.interp(depth, new_depths, range_depths)))
    print "the depth index is:", idz
    ####### get index of startdate in jdmat_m#####
    jdmat_m_num = []  # this is the data in the form of a number
    del_list, jdmat, del_index = [], [], []
    # convert array to list
    jdmat_m_list = [jdmat_m_i for jdmat_m_i in jdmat_m]
    # while seconds=60, can change the datetime to number, so delete

    for i in range(1, len(jdmat_m_list)):
        if jdmat_m_list[i][17:19] == '60' or jdmat_m_list[
                i - 1] == jdmat_m_list[i]:
            del_list.append(jdmat_m_list[i])
            del_index.append(i)  #get the index of deleted datetime
    jdmat = [val for val in jdmat_m_list
             if val not in del_list]  # delete the wrong value, jdmat just
    for i in jdmat:  # convert time to number
        jdmat_m_num.append(
            date2num(dt.datetime.strptime(i, '%Y-%m-%dT%H:%M:%S.%f')))

    index_startdate_1 = int(
        round(
            np.interp(date2num(startdate), jdmat_m_num,
                      range(len(jdmat_m_num)))))  #get the index of startdate
    print "the index of start date is:", index_startdate_1
    # calculate the delete index of time for u and v

    if del_index != []:
        index_add = int(
            np.ceil(
                np.interp(index_startdate_1, del_index,
                          range(len(del_index)))))
        index_startdate = index_add + index_startdate_1
    else:
        index_startdate = index_startdate_1

    # get u,v
    u1 = float(u[index_startdate, idz, index_location])
    v1 = float(v[index_startdate, idz, index_location])

    nsteps = scipy.floor(min(numdays, jdmat_m_num[-1]) / daystep)
    # get the velocity data at this first time & place
    lat_k = 'lat' + str(1)
    lon_k = 'lon' + str(1)
    uu, vv, lon_k, lat_k, time = [], [], [], [], []
    uu.append(u1)
    vv.append(v1)
    lat_k.append(la)
    lon_k.append(lo)
    time.append(date2num(startdate))
    delete_id = []

    for i in range(1, int(nsteps)):
        # first, estimate the particle move to its new position using velocity of previous time steps

        lat1 = lat_k[i - 1] + vv[i - 1] * daystep * 0.7769085
        lon1 = lon_k[i - 1] + uu[i - 1] * daystep * 0.7769085 * scipy.cos(
            lat_k[i - 1] / 180 * np.pi)
        # find the closest model time for the new timestep
        jdmat_m_num_i = time[i - 1] + daystep
        time.append(jdmat_m_num_i)

        index_startdate_1 = int(
            round(
                np.interp(jdmat_m_num_i, jdmat_m_num,
                          range(len(jdmat_m_num)))))
        if del_index != []:
            index_add = int(
                np.ceil(
                    np.interp(index_startdate_1, del_index,
                              range(len(del_index)))))
            index_startdate = index_add + index_startdate_1
        else:
            index_startdate = index_startdate_1
        #find the point's index of near lat1,lon1
        index_location = nearxy(lon_vel_1, lat_vel_1, lon1, lat1)[1]
        # calculate the model depth
        depth_model = getdepth(lat_k[i - 1], lon_k[i - 1])
        #get u and v
        ui = u[index_startdate, idz, index_location]
        vi = v[index_startdate, idz, index_location]
        vv.append(vi)
        uu.append(ui)
        # estimate the particle move from its new position using velocity of previous time steps

        lat_k.append((lat1 + lat_k[i - 1] + vv[i] * daystep * 0.7769085) / 2.)
        lon_k.append(
            (lon1 + lon_k[i - 1] +
             uu[i] * daystep * 0.7769085 * scipy.cos(lat_k[i] / 180 * np.pi)) /
            2.)

    if depth_model > 0:
        delete_id.append(i)
        #delete the depth is greater than 0
        delete_id.reverse()
        for i in delete_id:
            del lat_k[i]
            del lon_k[i]
            del time[i]
            del uu[i]
            del vv[i]
        if delete_id != []:
            del lat_k[-1]
            del lon_k[-1]
            del time[-1]
            del uu[-1]
            del vv[-1]
        return lat_k, lon_k, time, uu, vv