Esempio n. 1
0
    def testSnrFuncs(self):
        """test for signal to noise ratio functions"""

        # trivial
        data_triv = sp.ones((3, 10))
        snr_triv_test = sp.ones(3)
        assert_equal(
            snr_peak(data_triv, 1.0),
            snr_triv_test)
        assert_equal(
            snr_power(data_triv, 1.0),
            snr_triv_test)
        assert_equal(
            snr_maha(data_triv, sp.eye(data_triv.shape[1])),
            snr_triv_test)

        # application
        data = sp.array([
            sp.sin(sp.linspace(0.0, 2 * sp.pi, 100)),
            sp.sin(sp.linspace(0.0, 2 * sp.pi, 100)) * 2,
            sp.sin(sp.linspace(0.0, 2 * sp.pi, 100)) * 5,
        ])
        assert_equal(
            snr_peak(data, 1.0),
            sp.absolute(data).max(axis=1))
        assert_equal(
            snr_power(data, 1.0),
            sp.sqrt((data * data).sum(axis=1) / data.shape[1]))
        assert_almost_equal(
            snr_maha(data, sp.eye(data.shape[1])),
            sp.sqrt((data * data).sum(axis=1) / data.shape[1]))
Esempio n. 2
0
File: gid.py Progetto: 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
Esempio n. 3
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'
Esempio n. 4
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]  
Esempio n. 5
0
def Spm2(k,dx):
    from scipy import sqrt,sin,exp
    im = sqrt(-1)
    Sp = exp(im*k*dx)*(1 - 0.5*(im*sin(im*k*dx)))
    Sm = (1 + 0.5*(im*sin(im*k*dx)))
    
    return Sp, Sm
Esempio n. 6
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
Esempio n. 7
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)
Esempio n. 8
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)
Esempio n. 9
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)
    """
    #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.]])))
    transform={}
    transform['T']= T
    if sc.array(ra).shape == ():
        return radec_to_lb_single(ra,dec,transform,degree)
    else:
        function= sc.frompyfunc(radec_to_lb_single,4,2)
        return sc.array(function(ra,dec,transform,degree),dtype=sc.float64).T
Esempio n. 10
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
Esempio n. 11
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
Esempio n. 12
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
Esempio n. 13
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 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
Esempio n. 15
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)
Esempio n. 16
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
Esempio n. 17
0
def f_Refl_Thin_Film_fit(Data):
    strain = Data[0]
    DW = Data[1]

    dat = Data[2]
    wl = dat[0]
    N = dat[2]

    phi = dat[3]
    t_l = dat[4]
    thB_S = dat[6]
    G = dat[7]
    F0 = dat[8]
    FH = dat[9]
    FmH = dat[10]
    th = dat[19]

    thB = thB_S - strain * tan(thB_S)  # angle de Bragg dans chaque lamelle

    eta = 0
    res = 0

    n = 1
    while (n <= N):
        g0 = sin(thB[n] - phi)  # gamma 0
        gH = -sin(thB[n] + phi)  # gamma H
        b = g0 / gH
        T = pi * G * ((FH[n]*FmH[n])**0.5) * t_l * DW[n] / (wl * (abs(g0*gH)**0.5))
        eta = (-b*(th-thB[n])*sin(2*thB_S) - 0.5*G*F0[n]*(1-b)) / ((abs(b)**0.5) * G * DW[n] * (FH[n]*FmH[n])**0.5)
        S1 = (res - eta + (eta*eta-1)**0.5)*exp(-1j*T*(eta*eta-1)**0.5)
        S2 = (res - eta - (eta*eta-1)**0.5)*exp(1j*T*(eta*eta-1)**0.5)
        res = (eta + ((eta*eta-1)**0.5) * ((S1+S2)/(S1-S2)))
        n += 1
    return res
Esempio n. 18
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
Esempio n. 19
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
Esempio n. 20
0
def distance_fn(p1, l1, p2, l2, units='m'):
    """
    Simplified Vincenty formula.
    Returns distance between coordinates.
    """

    assert (units in ['km', 'm', 'nm']), 'Units must be km, m, or nm'

    if units == 'km':
        
        r = 6372.7974775959065
        
    elif units == 'm':
        
        r = 6372.7974775959065 * 0.621371
        
    elif units == 'nm':
        
        r = 6372.7974775959065 * 0.539957

#    compute Vincenty formula

    l = abs(l1 - l2)
    num = scipy.sqrt(((scipy.cos(p2) * scipy.sin(l)) ** 2) +\
        (((scipy.cos(p1) * scipy.sin(p2)) - (scipy.sin(p1) * scipy.cos(p2) * scipy.cos(l))) ** 2))
    den = scipy.sin(p1) * scipy.sin(p2) + scipy.cos(p1) * scipy.cos(p2) * scipy.cos(l)
    theta = scipy.arctan(num / den)
    distance = abs(int(round(r * theta)))

    return distance
Esempio n. 21
0
File: wcs.py Progetto: MCTwo/CodeCDF
def pix2sky(header,x,y):
	hdr_info = parse_header(header)
	x0 = x-hdr_info[1][0]+1.	# Plus 1 python->image
	y0 = y-hdr_info[1][1]+1.
	x0 = x0.astype(scipy.float64)
	y0 = y0.astype(scipy.float64)
	x = hdr_info[2][0,0]*x0 + hdr_info[2][0,1]*y0
	y = hdr_info[2][1,0]*x0 + hdr_info[2][1,1]*y0
	if hdr_info[3]=="DEC":
		a = x.copy()
		x = y.copy()
		y = a.copy()
		ra0 = hdr_info[0][1]
		dec0 = hdr_info[0][0]/raddeg
	else:
		ra0 = hdr_info[0][0]
		dec0 = hdr_info[0][1]/raddeg
	if hdr_info[5]=="TAN":
		r_theta = scipy.sqrt(x*x+y*y)/raddeg
		theta = arctan(1./r_theta)
		phi = arctan2(x,-1.*y)
	elif hdr_info[5]=="SIN":
		r_theta = scipy.sqrt(x*x+y*y)/raddeg
		theta = arccos(r_theta)
		phi = artan2(x,-1.*y)
	ra = ra0 + raddeg*arctan2(-1.*cos(theta)*sin(phi-pi),
				   sin(theta)*cos(dec0)-cos(theta)*sin(dec0)*cos(phi-pi))
	dec = raddeg*arcsin(sin(theta)*sin(dec0)+cos(theta)*cos(dec0)*cos(phi-pi))

	return ra,dec
Esempio n. 22
0
    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])
Esempio n. 23
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)
Esempio n. 24
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)
Esempio n. 25
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)]])
Esempio n. 26
0
def calc_max_width_in_slab(out_of_dip, slab_width, max_width):
    """Calculate the max width of a rupture within a slab in kms; given
    the slab width, and the out of dip angle.  the returned max width values
    are compared to the calculated width and the fault width, and then
    the mimium value of the 3 is used as the rupture width.

    out_of_dip     out of dip angle in Degrees
    slab_width     width of slab in kms
    max_width      width of the fault

    Returns the max width of ruptures within a slab in kms.
    """
    max_width_in_slab = zeros(len(out_of_dip))

    i = where(out_of_dip >= 180)
    out_of_dip[i] = out_of_dip[i] - 180

    i = where(out_of_dip <= 1)
    max_width_in_slab[i] = max_width

    j = where(((out_of_dip < 90) & (out_of_dip > 1)))
    max_width_in_slab[j] = slab_width / (sin(radians(out_of_dip[j])))

    k = where(out_of_dip == 90)
    max_width_in_slab[k] = slab_width

    k = where((out_of_dip > 90) & (out_of_dip < 179))
    max_width_in_slab[k] = slab_width / (sin(radians(180 - out_of_dip[k])))

    i = where(out_of_dip >= 179)
    max_width_in_slab[i] = max_width

    return max_width_in_slab
Esempio n. 27
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
Esempio n. 28
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)
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
Esempio n. 30
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
Esempio n. 31
0
    def solve(self, wls):
        """Anisotropic solver.

        INPUT
        wls = wavelengths to scan (any asarray-able object).

        OUTPUT
        self.DEO1, self.DEE1, self.DEO3, self.DEE3 = power reflected
        and transmitted.
        """

        self.wls = S.atleast_1d(wls)

        LAMBDA = self.LAMBDA
        n = self.n
        multilayer = self.multilayer
        alpha = self.alpha
        delta = self.delta
        psi = self.psi
        phi = self.phi

        nlayers = len(multilayer)
        i = S.arange(-n, n + 1)
        nood = 2 * n + 1
        hmax = nood - 1

        DEO1 = S.zeros((nood, self.wls.size))
        DEO3 = S.zeros_like(DEO1)
        DEE1 = S.zeros_like(DEO1)
        DEE3 = S.zeros_like(DEO1)

        c1 = S.array([1.0, 0.0, 0.0])
        c3 = S.array([1.0, 0.0, 0.0])
        # grating on the xy plane
        K = 2 * pi / LAMBDA * S.array([S.sin(phi), 0.0, S.cos(phi)], dtype=complex)
        dirk1 = S.array(
            [S.sin(alpha) * S.cos(delta), S.sin(alpha) * S.sin(delta), S.cos(alpha)]
        )

        # D polarization vector
        u = S.array(
            [
                S.cos(psi) * S.cos(alpha) * S.cos(delta) - S.sin(psi) * S.sin(delta),
                S.cos(psi) * S.cos(alpha) * S.sin(delta) + S.sin(psi) * S.cos(delta),
                -S.cos(psi) * S.sin(alpha),
            ]
        )

        kO1i = S.zeros((3, i.size), dtype=complex)
        kE1i = S.zeros_like(kO1i)
        kO3i = S.zeros_like(kO1i)
        kE3i = S.zeros_like(kO1i)

        Mp = S.zeros((4 * nood, 4 * nood, nlayers), dtype=complex)
        M = S.zeros((4 * nood, 4 * nood, nlayers), dtype=complex)

        dlt = (i == 0).astype(int)

        for iwl, wl in enumerate(self.wls):

            nO1 = nE1 = multilayer[0].mat.n(wl).item()
            nO3 = nE3 = multilayer[-1].mat.n(wl).item()

            # wavevectors
            k = 2 * pi / wl

            eps1 = S.diag(S.asarray([nE1, nO1, nO1]) ** 2)
            eps3 = S.diag(S.asarray([nE3, nO3, nO3]) ** 2)

            # ordinary wave
            abskO1 = k * nO1
            # abskO3 = k * nO3
            # extraordinary wave
            # abskE1 = k * nO1 *nE1 / S.sqrt(nO1**2 + (nE1**2 - nO1**2) * S.dot(-c1, dirk1)**2)
            # abskE3 = k * nO3 *nE3 / S.sqrt(nO3**2 + (nE3**2 - nO3**2) * S.dot(-c3, dirk1)**2)

            k1 = abskO1 * dirk1

            kO1i[0, :] = k1[0] - i * K[0]
            kO1i[1, :] = k1[1] * S.ones_like(i)
            kO1i[2, :] = -dispersion_relation_ordinary(kO1i[0, :], kO1i[1, :], k, nO1)

            kE1i[0, :] = kO1i[0, :]
            kE1i[1, :] = kO1i[1, :]
            kE1i[2, :] = -dispersion_relation_extraordinary(
                kE1i[0, :], kE1i[1, :], k, nO1, nE1, c1
            )

            kO3i[0, :] = kO1i[0, :]
            kO3i[1, :] = kO1i[1, :]
            kO3i[2, :] = dispersion_relation_ordinary(kO3i[0, :], kO3i[1, :], k, nO3)

            kE3i[0, :] = kO1i[0, :]
            kE3i[1, :] = kO1i[1, :]
            kE3i[2, :] = dispersion_relation_extraordinary(
                kE3i[0, :], kE3i[1, :], k, nO3, nE3, c3
            )

            # k2i = S.r_[[k1[0] - i * K[0]], [k1[1] - i * K[1]], [k1[2] - i * K[2]]]
            k2i = S.r_[[k1[0] - i * K[0]], [k1[1] - i * K[1]], [-i * K[2]]]

            # aliases for constant wavevectors
            kx = kO1i[0, :]  # o kE1i(1,;), tanto e' lo stesso
            ky = k1[1]

            # matrices
            I = S.eye(nood, dtype=complex)
            ZERO = S.zeros((nood, nood), dtype=complex)
            Kx = S.diag(kx / k)
            Ky = ky / k * I
            Kz = S.diag(k2i[2, :] / k)
            KO1z = S.diag(kO1i[2, :] / k)
            KE1z = S.diag(kE1i[2, :] / k)
            KO3z = S.diag(kO3i[2, :] / k)
            KE3z = S.diag(kE3i[2, :] / k)

            ARO = Kx * eps1[0, 0] + Ky * eps1[1, 0] + KO1z * eps1[2, 0]
            BRO = Kx * eps1[0, 1] + Ky * eps1[1, 1] + KO1z * eps1[2, 1]
            CRO_1 = inv(Kx * eps1[0, 2] + Ky * eps1[1, 2] + KO1z * eps1[2, 2])

            ARE = Kx * eps1[0, 0] + Ky * eps1[1, 0] + KE1z * eps1[2, 0]
            BRE = Kx * eps1[0, 1] + Ky * eps1[1, 1] + KE1z * eps1[2, 1]
            CRE_1 = inv(Kx * eps1[0, 2] + Ky * eps1[1, 2] + KE1z * eps1[2, 2])

            ATO = Kx * eps3[0, 0] + Ky * eps3[1, 0] + KO3z * eps3[2, 0]
            BTO = Kx * eps3[0, 1] + Ky * eps3[1, 1] + KO3z * eps3[2, 1]
            CTO_1 = inv(Kx * eps3[0, 2] + Ky * eps3[1, 2] + KO3z * eps3[2, 2])

            ATE = Kx * eps3[0, 0] + Ky * eps3[1, 0] + KE3z * eps3[2, 0]
            BTE = Kx * eps3[0, 1] + Ky * eps3[1, 1] + KE3z * eps3[2, 1]
            CTE_1 = inv(Kx * eps3[0, 2] + Ky * eps3[1, 2] + KE3z * eps3[2, 2])

            DRE = c1[1] * KE1z - c1[2] * Ky
            ERE = c1[2] * Kx - c1[0] * KE1z
            FRE = c1[0] * Ky - c1[1] * Kx

            DTE = c3[1] * KE3z - c3[2] * Ky
            ETE = c3[2] * Kx - c3[0] * KE3z
            FTE = c3[0] * Ky - c3[1] * Kx

            b = S.r_[
                u[0] * dlt,
                u[1] * dlt,
                (k1[1] / k * u[2] - k1[2] / k * u[1]) * dlt,
                (k1[2] / k * u[0] - k1[0] / k * u[2]) * dlt,
            ]
            Ky_CRO_1 = ky / k * CRO_1
            Ky_CRE_1 = ky / k * CRE_1
            Kx_CRO_1 = kx[:, S.newaxis] / k * CRO_1
            Kx_CRE_1 = kx[:, S.newaxis] / k * CRE_1
            MR31 = -S.dot(Ky_CRO_1, ARO)
            MR32 = -S.dot(Ky_CRO_1, BRO) - KO1z
            MR33 = -S.dot(Ky_CRE_1, ARE)
            MR34 = -S.dot(Ky_CRE_1, BRE) - KE1z
            MR41 = S.dot(Kx_CRO_1, ARO) + KO1z
            MR42 = S.dot(Kx_CRO_1, BRO)
            MR43 = S.dot(Kx_CRE_1, ARE) + KE1z
            MR44 = S.dot(Kx_CRE_1, BRE)
            MR = S.asarray(
                S.bmat(
                    [
                        [I, ZERO, I, ZERO],
                        [ZERO, I, ZERO, I],
                        [MR31, MR32, MR33, MR34],
                        [MR41, MR42, MR43, MR44],
                    ]
                )
            )

            Ky_CTO_1 = ky / k * CTO_1
            Ky_CTE_1 = ky / k * CTE_1
            Kx_CTO_1 = kx[:, S.newaxis] / k * CTO_1
            Kx_CTE_1 = kx[:, S.newaxis] / k * CTE_1
            MT31 = -S.dot(Ky_CTO_1, ATO)
            MT32 = -S.dot(Ky_CTO_1, BTO) - KO3z
            MT33 = -S.dot(Ky_CTE_1, ATE)
            MT34 = -S.dot(Ky_CTE_1, BTE) - KE3z
            MT41 = S.dot(Kx_CTO_1, ATO) + KO3z
            MT42 = S.dot(Kx_CTO_1, BTO)
            MT43 = S.dot(Kx_CTE_1, ATE) + KE3z
            MT44 = S.dot(Kx_CTE_1, BTE)
            MT = S.asarray(
                S.bmat(
                    [
                        [I, ZERO, I, ZERO],
                        [ZERO, I, ZERO, I],
                        [MT31, MT32, MT33, MT34],
                        [MT41, MT42, MT43, MT44],
                    ]
                )
            )

            Mp.fill(0.0)
            M.fill(0.0)

            for nlayer in range(nlayers - 2, 0, -1):  # internal layers

                layer = multilayer[nlayer]
                thickness = layer.thickness

                EPS2, EPS21 = layer.getEPSFourierCoeffs(wl, n, anisotropic=True)

                # Exx = S.squeeze(EPS2[0, 0, :])
                # Exx = toeplitz(S.flipud(Exx[0:hmax + 1]), Exx[hmax:])
                Exy = S.squeeze(EPS2[0, 1, :])
                Exy = toeplitz(S.flipud(Exy[0 : hmax + 1]), Exy[hmax:])
                Exz = S.squeeze(EPS2[0, 2, :])
                Exz = toeplitz(S.flipud(Exz[0 : hmax + 1]), Exz[hmax:])

                Eyx = S.squeeze(EPS2[1, 0, :])
                Eyx = toeplitz(S.flipud(Eyx[0 : hmax + 1]), Eyx[hmax:])
                Eyy = S.squeeze(EPS2[1, 1, :])
                Eyy = toeplitz(S.flipud(Eyy[0 : hmax + 1]), Eyy[hmax:])
                Eyz = S.squeeze(EPS2[1, 2, :])
                Eyz = toeplitz(S.flipud(Eyz[0 : hmax + 1]), Eyz[hmax:])

                Ezx = S.squeeze(EPS2[2, 0, :])
                Ezx = toeplitz(S.flipud(Ezx[0 : hmax + 1]), Ezx[hmax:])
                Ezy = S.squeeze(EPS2[2, 1, :])
                Ezy = toeplitz(S.flipud(Ezy[0 : hmax + 1]), Ezy[hmax:])
                Ezz = S.squeeze(EPS2[2, 2, :])
                Ezz = toeplitz(S.flipud(Ezz[0 : hmax + 1]), Ezz[hmax:])

                Exx_1 = S.squeeze(EPS21[0, 0, :])
                Exx_1 = toeplitz(S.flipud(Exx_1[0 : hmax + 1]), Exx_1[hmax:])
                Exx_1_1 = inv(Exx_1)

                # lalanne
                Ezz_1 = inv(Ezz)
                Ky_Ezz_1 = ky / k * Ezz_1
                Kx_Ezz_1 = kx[:, S.newaxis] / k * Ezz_1
                Exz_Ezz_1 = S.dot(Exz, Ezz_1)
                Eyz_Ezz_1 = S.dot(Eyz, Ezz_1)
                H11 = 1j * S.dot(Ky_Ezz_1, Ezy)
                H12 = 1j * S.dot(Ky_Ezz_1, Ezx)
                H13 = S.dot(Ky_Ezz_1, Kx)
                H14 = I - S.dot(Ky_Ezz_1, Ky)
                H21 = 1j * S.dot(Kx_Ezz_1, Ezy)
                H22 = 1j * S.dot(Kx_Ezz_1, Ezx)
                H23 = S.dot(Kx_Ezz_1, Kx) - I
                H24 = -S.dot(Kx_Ezz_1, Ky)
                H31 = S.dot(Kx, Ky) + Exy - S.dot(Exz_Ezz_1, Ezy)
                H32 = Exx_1_1 - S.dot(Ky, Ky) - S.dot(Exz_Ezz_1, Ezx)
                H33 = 1j * S.dot(Exz_Ezz_1, Kx)
                H34 = -1j * S.dot(Exz_Ezz_1, Ky)
                H41 = S.dot(Kx, Kx) - Eyy + S.dot(Eyz_Ezz_1, Ezy)
                H42 = -S.dot(Kx, Ky) - Eyx + S.dot(Eyz_Ezz_1, Ezx)
                H43 = -1j * S.dot(Eyz_Ezz_1, Kx)
                H44 = 1j * S.dot(Eyz_Ezz_1, Ky)
                H = 1j * S.diag(S.repeat(S.diag(Kz), 4)) + S.asarray(
                    S.bmat(
                        [
                            [H11, H12, H13, H14],
                            [H21, H22, H23, H24],
                            [H31, H32, H33, H34],
                            [H41, H42, H43, H44],
                        ]
                    )
                )

                q, W = eig(H)
                W1, W2, W3, W4 = S.split(W, 4)

                #
                # boundary conditions
                #
                # x = [R T]
                # R = [ROx ROy REx REy]
                # T = [TOx TOy TEx TEy]
                # b + MR.R = M1p.c
                # M1.c = M2p.c
                # ...
                # ML.c = MT.T
                # therefore: b + MR.R = (M1p.M1^-1.M2p.M2^-1. ...).MT.T
                # missing equations from (46)..(49) in glytsis_rigorous
                # [b] = [-MR Mtot.MT] [R]
                # [0]   [...........] [T]

                z = S.zeros_like(q)
                z[S.where(q.real > 0)] = -thickness
                D = S.exp(k * q * z)
                Sy0 = W1 * D[S.newaxis, :]
                Sx0 = W2 * D[S.newaxis, :]
                Uy0 = W3 * D[S.newaxis, :]
                Ux0 = W4 * D[S.newaxis, :]

                z = thickness * S.ones_like(q)
                z[S.where(q.real > 0)] = 0
                D = S.exp(k * q * z)
                D1 = S.exp(-1j * k2i[2, :] * thickness)
                Syd = D1[:, S.newaxis] * W1 * D[S.newaxis, :]
                Sxd = D1[:, S.newaxis] * W2 * D[S.newaxis, :]
                Uyd = D1[:, S.newaxis] * W3 * D[S.newaxis, :]
                Uxd = D1[:, S.newaxis] * W4 * D[S.newaxis, :]

                Mp[:, :, nlayer] = S.r_[Sx0, Sy0, -1j * Ux0, -1j * Uy0]
                M[:, :, nlayer] = S.r_[Sxd, Syd, -1j * Uxd, -1j * Uyd]

            Mtot = S.eye(4 * nood, dtype=complex)
            for nlayer in range(1, nlayers - 1):
                Mtot = S.dot(S.dot(Mtot, Mp[:, :, nlayer]), inv(M[:, :, nlayer]))

            BC_b = S.r_[b, S.zeros_like(b)]
            BC_A1 = S.c_[-MR, S.dot(Mtot, MT)]
            BC_A2 = S.asarray(
                S.bmat(
                    [
                        [
                            (c1[0] * I - c1[2] * S.dot(CRO_1, ARO)),
                            (c1[1] * I - c1[2] * S.dot(CRO_1, BRO)),
                            ZERO,
                            ZERO,
                            ZERO,
                            ZERO,
                            ZERO,
                            ZERO,
                        ],
                        [
                            ZERO,
                            ZERO,
                            (DRE - S.dot(S.dot(FRE, CRE_1), ARE)),
                            (ERE - S.dot(S.dot(FRE, CRE_1), BRE)),
                            ZERO,
                            ZERO,
                            ZERO,
                            ZERO,
                        ],
                        [
                            ZERO,
                            ZERO,
                            ZERO,
                            ZERO,
                            (c3[0] * I - c3[2] * S.dot(CTO_1, ATO)),
                            (c3[1] * I - c3[2] * S.dot(CTO_1, BTO)),
                            ZERO,
                            ZERO,
                        ],
                        [
                            ZERO,
                            ZERO,
                            ZERO,
                            ZERO,
                            ZERO,
                            ZERO,
                            (DTE - S.dot(S.dot(FTE, CTE_1), ATE)),
                            (ETE - S.dot(S.dot(FTE, CTE_1), BTE)),
                        ],
                    ]
                )
            )

            BC_A = S.r_[BC_A1, BC_A2]

            x = linsolve(BC_A, BC_b)

            ROx, ROy, REx, REy, TOx, TOy, TEx, TEy = S.split(x, 8)

            ROz = -S.dot(CRO_1, (S.dot(ARO, ROx) + S.dot(BRO, ROy)))
            REz = -S.dot(CRE_1, (S.dot(ARE, REx) + S.dot(BRE, REy)))
            TOz = -S.dot(CTO_1, (S.dot(ATO, TOx) + S.dot(BTO, TOy)))
            TEz = -S.dot(CTE_1, (S.dot(ATE, TEx) + S.dot(BTE, TEy)))

            denom = (k1[2] - S.dot(u, k1) * u[2]).real
            DEO1[:, iwl] = (
                -(
                    (S.absolute(ROx) ** 2 + S.absolute(ROy) ** 2 + S.absolute(ROz) ** 2)
                    * S.conj(kO1i[2, :])
                    - (ROx * kO1i[0, :] + ROy * kO1i[1, :] + ROz * kO1i[2, :])
                    * S.conj(ROz)
                ).real
                / denom
            )
            DEE1[:, iwl] = (
                -(
                    (S.absolute(REx) ** 2 + S.absolute(REy) ** 2 + S.absolute(REz) ** 2)
                    * S.conj(kE1i[2, :])
                    - (REx * kE1i[0, :] + REy * kE1i[1, :] + REz * kE1i[2, :])
                    * S.conj(REz)
                ).real
                / denom
            )
            DEO3[:, iwl] = (
                (S.absolute(TOx) ** 2 + S.absolute(TOy) ** 2 + S.absolute(TOz) ** 2)
                * S.conj(kO3i[2, :])
                - (TOx * kO3i[0, :] + TOy * kO3i[1, :] + TOz * kO3i[2, :]) * S.conj(TOz)
            ).real / denom
            DEE3[:, iwl] = (
                (S.absolute(TEx) ** 2 + S.absolute(TEy) ** 2 + S.absolute(TEz) ** 2)
                * S.conj(kE3i[2, :])
                - (TEx * kE3i[0, :] + TEy * kE3i[1, :] + TEz * kE3i[2, :]) * S.conj(TEz)
            ).real / denom

        # save the results
        self.DEO1 = DEO1
        self.DEE1 = DEE1
        self.DEO3 = DEO3
        self.DEE3 = DEE3

        return self
Esempio n. 32
0
    def solve(self, wls):
        """Isotropic solver.

        INPUT
        wls = wavelengths to scan (any asarray-able object).

        OUTPUT
        self.DE1, self.DE3 = power reflected and transmitted.

        NOTE
        see:
        Moharam, "Formulation for stable and efficient implementation
        of the rigorous coupled-wave analysis of binary gratings",
        JOSA A, 12(5), 1995
        Lalanne, "Highly improved convergence of the coupled-wave
        method for TM polarization", JOSA A, 13(4), 1996
        Moharam, "Stable implementation of the rigorous coupled-wave
        analysis for surface-relief gratings: enhanced trasmittance
        matrix approach", JOSA A, 12(5), 1995
        """

        self.wls = S.atleast_1d(wls)

        LAMBDA = self.LAMBDA
        n = self.n
        multilayer = self.multilayer
        alpha = self.alpha
        delta = self.delta
        psi = self.psi
        phi = self.phi

        nlayers = len(multilayer)
        i = S.arange(-n, n + 1)
        nood = 2 * n + 1
        hmax = nood - 1

        # grating vector (on the xz plane)
        # grating on the xy plane
        K = 2 * pi / LAMBDA * S.array([S.sin(phi), 0.0, S.cos(phi)], dtype=complex)

        DE1 = S.zeros((nood, self.wls.size))
        DE3 = S.zeros_like(DE1)

        dirk1 = S.array(
            [S.sin(alpha) * S.cos(delta), S.sin(alpha) * S.sin(delta), S.cos(alpha)]
        )

        # usefull matrices
        I = S.eye(i.size)
        I2 = S.eye(i.size * 2)
        ZERO = S.zeros_like(I)

        X = S.zeros((2 * nood, 2 * nood, nlayers), dtype=complex)
        MTp1 = S.zeros((2 * nood, 2 * nood, nlayers), dtype=complex)
        MTp2 = S.zeros_like(MTp1)

        EPS2 = S.zeros(2 * hmax + 1, dtype=complex)
        EPS21 = S.zeros_like(EPS2)

        dlt = (i == 0).astype(int)

        for iwl, wl in enumerate(self.wls):

            # free space wavevector
            k = 2 * pi / wl

            n1 = multilayer[0].mat.n(wl).item()
            n3 = multilayer[-1].mat.n(wl).item()

            # incident plane wave wavevector
            k1 = k * n1 * dirk1

            # all the other wavevectors
            tmp_x = k1[0] - i * K[0]
            tmp_y = k1[1] * S.ones_like(i)
            tmp_z = dispersion_relation_ordinary(tmp_x, tmp_y, k, n1)
            k1i = S.r_[[tmp_x], [tmp_y], [tmp_z]]

            # k2i = S.r_[[k1[0] - i*K[0]], [k1[1] - i * K[1]], [-i * K[2]]]

            tmp_z = dispersion_relation_ordinary(tmp_x, tmp_y, k, n3)
            k3i = S.r_[[k1i[0, :]], [k1i[1, :]], [tmp_z]]

            # aliases for constant wavevectors
            kx = k1i[0, :]
            ky = k1[1]

            # angles of reflection
            # phi_i = S.arctan2(ky,kx)
            phi_i = S.arctan2(ky, kx.real)  # OKKIO

            Kx = S.diag(kx / k)
            Ky = ky / k * I
            Z1 = S.diag(k1i[2, :] / (k * n1 ** 2))
            Y1 = S.diag(k1i[2, :] / k)
            Z3 = S.diag(k3i[2, :] / (k * n3 ** 2))
            Y3 = S.diag(k3i[2, :] / k)
            # Fc = S.diag(S.cos(phi_i))
            fc = S.cos(phi_i)
            # Fs = S.diag(S.sin(phi_i))
            fs = S.sin(phi_i)

            MR = S.asarray(
                S.bmat([[I, ZERO], [-1j * Y1, ZERO], [ZERO, I], [ZERO, -1j * Z1]])
            )

            MT = S.asarray(
                S.bmat([[I, ZERO], [1j * Y3, ZERO], [ZERO, I], [ZERO, 1j * Z3]])
            )

            # internal layers (grating or layer)
            X.fill(0.0)
            MTp1.fill(0.0)
            MTp2.fill(0.0)
            for nlayer in range(nlayers - 2, 0, -1):  # internal layers

                layer = multilayer[nlayer]
                d = layer.thickness

                EPS2, EPS21 = layer.getEPSFourierCoeffs(wl, n, anisotropic=False)

                E = toeplitz(EPS2[hmax::-1], EPS2[hmax:])
                E1 = toeplitz(EPS21[hmax::-1], EPS21[hmax:])
                E11 = inv(E1)
                # B = S.dot(Kx, linsolve(E,Kx)) - I
                B = kx[:, S.newaxis] / k * linsolve(E, Kx) - I
                # A = S.dot(Kx, Kx) - E
                A = S.diag((kx / k) ** 2) - E

                # Note: solution bug alfredo
                # randomizzo Kx un po' a caso finche' cond(A) e' piccolo (<1e10)
                # soluzione sporca... :-(
                # per certi kx, l'operatore di helmholtz ha 2 autovalori nulli e A, B
                # non sono invertibili --> cambio leggermente i kx... ma dovrei invece
                # trattare separatamente (analiticamente) questi casi
                if cond(A) > 1e10:
                    warning("BAD CONDITIONING: randomization of kx")
                    while cond(A) > 1e10:
                        Kx = Kx * (1 + 1e-9 * S.rand())
                        B = kx[:, S.newaxis] / k * linsolve(E, Kx) - I
                        A = S.diag((kx / k) ** 2) - E

                if S.absolute(K[2] / k) > 1e-10:

                    raise ValueError(
                        "First Order Helmholtz Operator not implemented, yet!"
                    )

                elif ky == 0 or S.allclose(S.diag(Ky / ky * k), 1):

                    # lalanne
                    # H_U_reduced = S.dot(Ky, Ky) + A
                    H_U_reduced = (ky / k) ** 2 * I + A
                    # H_S_reduced = S.dot(Ky, Ky) + S.dot(Kx, linsolve(E, S.dot(Kx, E11))) - E11
                    H_S_reduced = (
                        (ky / k) ** 2 * I
                        + kx[:, S.newaxis] / k * linsolve(E, kx[:, S.newaxis] / k * E11)
                        - E11
                    )

                    q1, W1 = eig(H_U_reduced)
                    q1 = S.sqrt(q1)
                    q2, W2 = eig(H_S_reduced)
                    q2 = S.sqrt(q2)

                    # boundary conditions

                    # V11 = S.dot(linsolve(A, W1), S.diag(q1))
                    V11 = linsolve(A, W1) * q1[S.newaxis, :]
                    V12 = (ky / k) * S.dot(linsolve(A, Kx), W2)
                    V21 = (ky / k) * S.dot(linsolve(B, Kx), linsolve(E, W1))
                    # V22 = S.dot(linsolve(B, W2), S.diag(q2))
                    V22 = linsolve(B, W2) * q2[S.newaxis, :]

                    # Vss = S.dot(Fc, V11)
                    Vss = fc[:, S.newaxis] * V11
                    # Wss = S.dot(Fc, W1)  + S.dot(Fs, V21)
                    Wss = fc[:, S.newaxis] * W1 + fs[:, S.newaxis] * V21
                    # Vsp = S.dot(Fc, V12) - S.dot(Fs, W2)
                    Vsp = fc[:, S.newaxis] * V12 - fs[:, S.newaxis] * W2
                    # Wsp = S.dot(Fs, V22)
                    Wsp = fs[:, S.newaxis] * V22
                    # Wpp = S.dot(Fc, V22)
                    Wpp = fc[:, S.newaxis] * V22
                    # Vpp = S.dot(Fc, W2)  + S.dot(Fs, V12)
                    Vpp = fc[:, S.newaxis] * W2 + fs[:, S.newaxis] * V12
                    # Wps = S.dot(Fc, V21) - S.dot(Fs, W1)
                    Wps = fc[:, S.newaxis] * V21 - fs[:, S.newaxis] * W1
                    # Vps = S.dot(Fs, V11)
                    Vps = fs[:, S.newaxis] * V11

                    Mc2bar = S.asarray(
                        S.bmat(
                            [
                                [Vss, Vsp, Vss, Vsp],
                                [Wss, Wsp, -Wss, -Wsp],
                                [Wps, Wpp, -Wps, -Wpp],
                                [Vps, Vpp, Vps, Vpp],
                            ]
                        )
                    )

                    x = S.r_[S.exp(-k * q1 * d), S.exp(-k * q2 * d)]

                    # Mc1 = S.dot(Mc2bar, S.diag(S.r_[S.ones_like(x), x]))
                    xx = S.r_[S.ones_like(x), x]
                    Mc1 = Mc2bar * xx[S.newaxis, :]

                    X[:, :, nlayer] = S.diag(x)

                    MTp = linsolve(Mc2bar, MT)
                    MTp1[:, :, nlayer] = MTp[0 : 2 * nood, :]
                    MTp2 = MTp[2 * nood :, :]

                    MT = S.dot(
                        Mc1,
                        S.r_[
                            I2,
                            S.dot(MTp2, linsolve(MTp1[:, :, nlayer], X[:, :, nlayer])),
                        ],
                    )

                else:

                    ValueError("Second Order Helmholtz Operator not implemented, yet!")

            # M = S.asarray(S.bmat([-MR, MT]))
            M = S.c_[-MR, MT]
            b = S.r_[
                S.sin(psi) * dlt,
                1j * S.sin(psi) * n1 * S.cos(alpha) * dlt,
                -1j * S.cos(psi) * n1 * dlt,
                S.cos(psi) * S.cos(alpha) * dlt,
            ]

            x = linsolve(M, b)
            R, T = S.split(x, 2)
            Rs, Rp = S.split(R, 2)
            for ii in range(1, nlayers - 1):
                T = S.dot(linsolve(MTp1[:, :, ii], X[:, :, ii]), T)
            Ts, Tp = S.split(T, 2)

            DE1[:, iwl] = (k1i[2, :] / (k1[2])).real * S.absolute(Rs) ** 2 + (
                k1i[2, :] / (k1[2] * n1 ** 2)
            ).real * S.absolute(Rp) ** 2
            DE3[:, iwl] = (k3i[2, :] / (k1[2])).real * S.absolute(Ts) ** 2 + (
                k3i[2, :] / (k1[2] * n3 ** 2)
            ).real * S.absolute(Tp) ** 2

        # save the results
        self.DE1 = DE1
        self.DE3 = DE3

        return self
Esempio n. 33
0
def FF(x):  # подсчёт значения функции f(x) через сумму ряда в точке x
    S = a0 / 2
    for i in range(1, k):
        S += AK[i] * sp.cos(i * x) + BK[i] * sp.sin(i * x)
    return S
Esempio n. 34
0
import os
import sys

example = 'example_1d_cubic'
title = 'Sine Wave using two 1D Cubic Lagrange Element'
testdatadir = 'data'
docimagedir = os.path.join('..', 'doc', 'images')

# sphinx tag start
import scipy
import morphic

x = scipy.linspace(0, 2 * scipy.pi, 7)
y = scipy.sin(x)
X = scipy.array([x, y]).T

mesh = morphic.Mesh()
for i, xn in enumerate(X):
    mesh.add_stdnode(i + 1, xn)

mesh.add_element(1, ['L3'], [1, 2, 3, 4])
mesh.add_element(2, ['L3'], [4, 5, 6, 7])
# sphinx tag end

if len(sys.argv) > 1:
    action = sys.argv[1]

    from matplotlib import pyplot
    import pickle

    Xn = mesh.get_nodes()
Esempio n. 35
0
def generate_base_points(num_points, domain_size, prob=None):
    r"""
    Generates a set of base points for passing into the DelaunayVoronoiDual
    class.  The points can be distributed in spherical, cylindrical, or
    rectilinear patterns.

    Parameters
    ----------
    num_points : scalar
        The number of base points that lie within the domain.  Note that the
        actual number of points returned will be larger, with the extra points
        lying outside the domain.

    domain_size : list or array
        Controls the size and shape of the domain, as follows:

        **sphere** : If a single value is received, its treated as the radius
        [r] of a sphere centered on [0, 0, 0].

        **cylinder** : If a two-element list is received it's treated as the
        radius and height of a cylinder [r, z] positioned at [0, 0, 0] and
        extending in the positive z-direction.

        **rectangle** : If a three element list is received, it's treated
        as the outer corner of rectangle [x, y, z] whose opposite corner lies
        at [0, 0, 0].

    prob : 3D array, optional
        A 3D array that contains fractional (0-1) values indicating the
        liklihood that a point in that region should be kept.  If not specified
        an array containing 1's in the shape of a sphere, cylinder, or cube is
        generated, depnending on the give ``domain_size`` with zeros outside.
        When specifying a custom probabiliy map is it recommended to also set
        values outside the given domain to zero.  If not, then the correct
        shape will still be returned, but with too few points in it.

    Notes
    -----
    This method places the given number of points within the specified domain,
    then reflects these points across each domain boundary.  This results in
    smooth flat faces at the boundaries once these excess pores are trimmed.

    The reflection approach tends to create larger pores near the surfaces, so
    it might be necessary to use the ``prob`` argument to specify a slightly
    higher density of points near the surfaces.

    For rough faces, it is necessary to define a larger than desired domain
    then trim to the desired size.  This will discard the reflected points
    plus some of the original points.

    Examples
    --------
    The following generates a spherical array with higher values near the core.
    It uses a distance transform to create a sphere of radius 10, then a
    second distance transform to create larger values in the center away from
    the sphere surface.  These distance values could be further skewed by
    applying a power, with values higher than 1 resulting in higher values in
    the core, and fractional values smoothinging them out a bit.

    >>> import OpenPNM as op
    >>> import scipy as sp
    >>> import scipy.ndimage as spim
    >>> im = sp.ones([21, 21, 21], dtype=int)
    >>> im[10, 10, 10] = 0
    >>> im = spim.distance_transform_edt(im) <= 20  # Create sphere of 1's
    >>> prob = spim.distance_transform_edt(im)
    >>> prob = prob / sp.amax(prob)  # Normalize between 0 and 1
    >>> pts = op.Network.tools.generate_base_points(num_points=50,
    ...                                             domain_size=[2],
    ...                                             prob=prob)
    >>> net = op.Network.DelaunayVoronoiDual(points=pts, domain_size=[2])
    """
    def _try_points(num_points, prob):
        prob = _sp.array(prob)/_sp.amax(prob)  # Ensure prob is normalized
        base_pts = []
        N = 0
        while N < num_points:
            pt = _sp.random.rand(3)  # Generate a point
            # Test whether to keep it or not
            [indx, indy, indz] = _sp.floor(pt*_sp.shape(prob)).astype(int)
            if _sp.random.rand(1) <= prob[indx][indy][indz]:
                base_pts.append(pt)
                N += 1
        base_pts = _sp.array(base_pts)
        return base_pts
    if len(domain_size) == 1:  # Spherical
        domain_size = _sp.array(domain_size)
        if prob is None:
            prob = _sp.ones([41, 41, 41])
            prob[20, 20, 20] = 0
            prob = _spim.distance_transform_bf(prob) <= 20
        base_pts = _try_points(num_points, prob)
        # Convert to spherical coordinates
        [X, Y, Z] = _sp.array(base_pts - [0.5, 0.5, 0.5]).T  # Center at origin
        r = 2*_sp.sqrt(X**2 + Y**2 + Z**2)*domain_size[0]
        theta = 2*_sp.arctan(Y/X)
        phi = 2*_sp.arctan(_sp.sqrt(X**2 + Y**2)/Z)
        # Trim points outside the domain (from improper prob images)
        inds = r <= domain_size[0]
        [r, theta, phi] = [r[inds], theta[inds], phi[inds]]
        # Reflect base points across perimeter
        new_r = 2*domain_size - r
        r = _sp.hstack([r, new_r])
        theta = _sp.hstack([theta, theta])
        phi = _sp.hstack([phi, phi])
        # Convert to Cartesean coordinates
        X = r*_sp.cos(theta)*_sp.sin(phi)
        Y = r*_sp.sin(theta)*_sp.sin(phi)
        Z = r*_sp.cos(phi)
        base_pts = _sp.vstack([X, Y, Z]).T
    elif len(domain_size) == 2:  # Cylindrical
        domain_size = _sp.array(domain_size)
        if prob is None:
            prob = _sp.ones([41, 41, 41])
            prob[20, 20, :] = 0
            prob = _spim.distance_transform_bf(prob) <= 20
        base_pts = _try_points(num_points, prob)
        # Convert to cylindrical coordinates
        [X, Y, Z] = _sp.array(base_pts - [0.5, 0.5, 0]).T  # Center on z-axis
        r = 2*_sp.sqrt(X**2 + Y**2)*domain_size[0]
        theta = 2*_sp.arctan(Y/X)
        z = Z*domain_size[1]
        # Trim points outside the domain (from improper prob images)
        inds = r <= domain_size[0]
        [r, theta, z] = [r[inds], theta[inds], z[inds]]
        inds = ~((z > domain_size[1]) + (z < 0))
        [r, theta, z] = [r[inds], theta[inds], z[inds]]
        # Reflect base points about faces and perimeter
        new_r = 2*domain_size[0] - r
        r = _sp.hstack([r, new_r])
        theta = _sp.hstack([theta, theta])
        z = _sp.hstack([z, z])
        r = _sp.hstack([r, r, r])
        theta = _sp.hstack([theta, theta, theta])
        z = _sp.hstack([z, -z, 2-z])
        # Convert to Cartesean coordinates
        X = r*_sp.cos(theta)
        Y = r*_sp.sin(theta)
        Z = z
        base_pts = _sp.vstack([X, Y, Z]).T
    elif len(domain_size) == 3:  # Rectilinear
        domain_size = _sp.array(domain_size)
        Nx, Ny, Nz = domain_size
        if prob is None:
            prob = _sp.ones([10, 10, 10], dtype=float)
        base_pts = _try_points(num_points, prob)
        base_pts = base_pts*domain_size
        # Reflect base points about all 6 faces
        orig_pts = base_pts
        base_pts = _sp.vstack((base_pts, [-1, 1, 1]*orig_pts +
                                         [2.0*Nx, 0, 0]))
        base_pts = _sp.vstack((base_pts, [1, -1, 1]*orig_pts +
                                         [0, 2.0*Ny, 0]))
        base_pts = _sp.vstack((base_pts, [1, 1, -1]*orig_pts +
                                         [0, 0, 2.0*Nz]))
        base_pts = _sp.vstack((base_pts, [-1, 1, 1]*orig_pts))
        base_pts = _sp.vstack((base_pts, [1, -1, 1]*orig_pts))
        base_pts = _sp.vstack((base_pts, [1, 1, -1]*orig_pts))
    return base_pts
Esempio n. 36
0
    N = 8
    array = buildAntennaArray(num_elements=N,
                              ref_element=1,
                              seperation=wavelength / 2)

    plt.axis([-2, 2, -2, 2])
    plt.ion()
    plt.show()

    for angle in range(-89, 89, 1):
        plt.clf()
        plt.axis([-2, 2, -2, 2])
        plt.plot(array, sp.zeros(N, dtype=sp.double), 'or')

        pd = calculatePhaseDelay(array, (angle * sp.pi / 180), wavelength)
        aoa = calculateAOA(array, pd, wavelength)
        #print aoa

        for i in range(N):
            mag = 1
            ang = aoa[i]
            x = array[i]
            y = 0
            # remember, 0 degrees should be boresight
            plt.plot([x, mag * sp.cos((90 - ang) * sp.pi / 180) + x],
                     [y, mag * sp.sin((90 - ang) * sp.pi / 180) + y], 'r')

        plt.draw()
        plt.pause(0.001)
        #raw_input("paused...")
Esempio n. 37
0
def g(wind_angle, num_iterations=num_iterations):

    # wind_angle = 7*np.pi/4
    wind_mag = 1.2

    #Loop through pickle files for that parameter value and merge counts
    for i in range(num_iterations):
        # file_name = 'trap_arrival_by_wind_live_coarse_dt'
        # file_name = 'trap_time_course_by_wind'
        # file_name = 'trap_arrival_by_wind_fit_gauss'
        file_name = 'trap_arrival_by_wind_adjusted_fit_gauss'
        file_name = file_name + '_wind_mag_' + str(
            wind_mag)  #+'_wind_angle_'+str(wind_angle)[0:4]+'_iter_'+str(i)

        # file_name = file_name +'_wind_mag_'+str(wind_mag)+'_wind_angle_'+str(wind_angle)[0:4]+'_iter_'+str(i)
        # file_name = file_name +'_wind_mag_'+str(wind_mag)

        output_file = file_name + '.pkl'

        with open(output_file, 'r') as f:
            (_, swarm) = pickle.load(f)
            # swarm = pickle.load(f)

        if i == 0:
            sim_trap_counts_cumul = np.zeros(swarm.num_traps)

        sim_trap_counts_cumul += swarm.get_trap_counts()

    # print(sim_trap_counts_cumul)
    #Trap arrival plot

    #Set 0s to 1 for plotting purposes
    sim_trap_counts_cumul /= num_iterations
    sim_trap_counts_cumul[sim_trap_counts_cumul == 0] = .5
    trap_locs = (2 * scipy.pi / swarm.num_traps) * scipy.array(
        swarm.list_all_traps())
    radius_scale = 0.3
    plot_size = 1.5
    fig = plt.figure(200 + int(10 * wind_mag))
    ax = plt.subplot(aspect=1)
    trap_locs_2d = [(scipy.cos(trap_loc), scipy.sin(trap_loc))
                    for trap_loc in trap_locs]
    patches = [
        plt.Circle(center, size) for center, size in zip(
            trap_locs_2d, radius_scale * sim_trap_counts_cumul /
            max(sim_trap_counts_cumul))
    ]
    biggest_trap_loc = trap_locs_2d[np.where(
        sim_trap_counts_cumul == max(sim_trap_counts_cumul))[0][0]]
    coll = matplotlib.collections.PatchCollection(patches,
                                                  facecolors='blue',
                                                  edgecolors='blue')
    ax.add_collection(coll)
    ax.set_ylim([-plot_size, plot_size])
    ax.set_xlim([-plot_size, plot_size])
    ax.set_xticks([])
    ax.set_xticklabels('')
    ax.set_yticks([])
    ax.set_yticklabels('')
    #Label max trap count
    ax.text(biggest_trap_loc[0],
            biggest_trap_loc[1],
            str(max(sim_trap_counts_cumul)),
            horizontalalignment='center',
            verticalalignment='center',
            fontsize=18,
            color='white')
    #Wind arrow
    plt.arrow(
        0.5,
        0.5,
        0.1 * scipy.cos(wind_angle),
        0.1 * scipy.sin(wind_angle),
        transform=ax.transAxes,
        color='b',
        width=0.001,
        head_width=0.03,
        head_length=0.05,
    )
    # ax.text(0.55, 0.5,'Wind',transform=ax.transAxes,color='b')
    ax.text(0,
            1.5,
            'N',
            horizontalalignment='center',
            verticalalignment='center',
            fontsize=25)
    ax.text(0,
            -1.5,
            'S',
            horizontalalignment='center',
            verticalalignment='center',
            fontsize=25)
    ax.text(1.5,
            0,
            'E',
            horizontalalignment='center',
            verticalalignment='center',
            fontsize=25)
    ax.text(-1.5,
            0,
            'W',
            horizontalalignment='center',
            verticalalignment='center',
            fontsize=25)
    # plt.title('Simulated')
    fig.patch.set_facecolor('white')
    plt.axis('off')
    ax.text(0,
            1.7,
            'Trap Counts' + ' (Wind Mag: ' + str(wind_mag)[0:3] + ')',
            horizontalalignment='center',
            verticalalignment='center',
            fontsize=20)

    # file_name = 'trap_arrival_by_wind_live_coarse_dt'
    file_name = 'trap_arrival_by_wind_adjusted_fit_gauss'

    png_file_name = file_name + '_wind_mag_' + str(
        wind_mag) + '_wind_angle_' + str(wind_angle)[0:4]

    plt.savefig(png_file_name + '.png', format='png')
Esempio n. 38
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 paralell 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.
Esempio n. 39
0
def f(x, y):
    return 3.0 * scipy.sin(x * y + 1e-4) / (x * y + 1e-4)
Esempio n. 40
0
def calculatePhaseDelay(array, angle, wavelength):
    phasedelay = 2 * sp.pi * array * sp.sin(angle) / wavelength
    phasedelay = abs(phasedelay) % (2 * sp.pi) * phasedelay / abs(
        phasedelay
    )  # this adds realism, you'd never be able to detect the overall phasedelays beyond the -pi to pi range
    return phasedelay
Esempio n. 41
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]]))
import matplotlib.pyplot as plt
from matplotlib import rc
rc('text', usetex=True)
################################# USER SETTINGS ###################################

"""
Diffeq params
"""
lmd1 = 1.0
lmd2 = 2.0
xa = 0.0
xg = 1.0
xb = 2.0
ua = 1.0
ub = 3.0
f1 = lambda x: sc.sin(x)
f2 = lambda x: sc.cos(3*x)
globres = 1000 #Resoltion of global discretisations
dnres1 = 5 # Resolution of the dir/neu alg discretisations
dnres2 = 7
"""
Discretisation params
"""
dirDisc = "FEM" # FDM,FEM,FVM
neuDisc = "FVM" # FDM,FEM,FVM


#############################  PROGRAM ##############################

def Ldense(x):
    return sc.expm1(3*x)/(sc.exp(3)-1)
    def __init__(self):
        """ Constructor or the initializer """
        QMainWindow.__init__(self)

        # Set some default attributes of the window
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setWindowTitle("Reflection and Refraction")

        # define the main widget as self
        self.main_widget = QWidget(self)

        # Add the label widgets and sliders
        # Refractive Index - Object Side
        self.loRIOne = QVBoxLayout()
        self.lblRIOne = QLabel("Refractive Index: n1", self)
        self.sldRIOne = QSlider(Qt.Horizontal)
        self.sldRIOne.setMinimum(100)
        self.sldRIOne.setMaximum(200)
        self.sldRIOne.setValue(100)
        self.sldRIOne.setTickPosition(QSlider.TicksBelow)
        self.sldRIOne.setTickInterval(10)
        self.edtRIOne = QLineEdit(self)
        self.edtRIOne.setMaxLength(5)
        self.loRIOne.addWidget(self.lblRIOne)
        self.loRIOne.addSpacing(3)
        self.loRIOne.addWidget(self.sldRIOne)
        self.loRIOne.addSpacing(3)
        self.loRIOne.addWidget(self.edtRIOne)

        # Refractive Index - Object Side
        self.loRITwo = QVBoxLayout()
        self.lblRITwo = QLabel("Refractive Index: n2", self)
        self.sldRITwo = QSlider(Qt.Horizontal)
        self.sldRITwo.setMinimum(100)
        self.sldRITwo.setMaximum(200)
        self.sldRITwo.setValue(152)
        self.sldRITwo.setTickPosition(QSlider.TicksBelow)
        self.sldRITwo.setTickInterval(10)
        self.edtRITwo = QLineEdit(self)
        self.edtRITwo.setMaxLength(5)
        self.loRITwo.addWidget(self.lblRITwo)
        self.loRITwo.addSpacing(3)
        self.loRITwo.addWidget(self.sldRITwo)
        self.loRITwo.addSpacing(3)
        self.loRITwo.addWidget(self.edtRITwo)

        # Angle of incidence
        self.loIncAng = QVBoxLayout()
        self.lblIncAng = QLabel("Angle of Incidence", self)
        self.sldIncAng = QSlider(Qt.Horizontal)
        self.sldIncAng.setMinimum(0)
        self.sldIncAng.setMaximum(90)
        self.sldIncAng.setValue(30)
        self.sldIncAng.setTickPosition(QSlider.TicksBelow)
        self.sldIncAng.setTickInterval(10)
        self.edtIncAng = QLineEdit(self)
        self.edtIncAng.setMaxLength(2)
        self.loIncAng.addWidget(self.lblIncAng)
        self.loIncAng.addSpacing(3)
        self.loIncAng.addWidget(self.sldIncAng)
        self.loIncAng.addSpacing(3)
        self.loIncAng.addWidget(self.edtIncAng)

        # Angle of refraction
        self.loRefrAng = QHBoxLayout()
        self.lblRefrAng = QLabel("Angle of Refraction", self)
        self.edtRefrAng = QLineEdit(self)
        self.loRefrAng.addWidget(self.lblRefrAng)
        self.loRefrAng.addSpacing(3)
        self.loRefrAng.addWidget(self.edtRefrAng)
        refrAng = 180.0 / pi * arcsin(1.0 * sin(pi / 180.0 * 30) / 1.52)
        self.edtRefrAng.setText(str('%5.3f' % (refrAng)))

        # Waves Param Layout
        self.loRayParams = QHBoxLayout()
        self.loRayParams.addLayout(self.loRIOne)
        self.loRayParams.addStretch()
        self.loRayParams.addLayout(self.loRITwo)
        self.loRayParams.addStretch()
        self.loRayParams.addLayout(self.loIncAng)

        # Get the values from the sliders
        nOne = self.sldRIOne.value() / 100
        nTwo = self.sldRITwo.value() / 100
        incAng = self.sldIncAng.value()
        self.edtRIOne.setText(str(nOne))
        self.edtRITwo.setText(str(nTwo))
        self.edtIncAng.setText(str(incAng))

        # Create an instance of the FigureCanvas
        self.loCanvas = MplCanvas(self.main_widget,
                                  width=5,
                                  height=4,
                                  nOne=nOne,
                                  nTwo=nTwo,
                                  incAng=incAng)

        # Set the focus to the main_widget and set it to be central widget
        self.main_widget.setFocus()
        self.setCentralWidget(self.main_widget)

        # Populate the master layout
        self.loMaster = QVBoxLayout(self.main_widget)
        self.loMaster.addLayout(self.loRayParams)
        self.loMaster.addWidget(self.loCanvas)
        self.loMaster.addLayout(self.loRefrAng)

        # Connect slots
        self.sldRIOne.valueChanged.connect(self.OnRIOneChanged)
        self.sldRITwo.valueChanged.connect(self.OnRITwoChanged)
        self.sldIncAng.valueChanged.connect(self.OnIncAngChanged)
        self.edtRIOne.editingFinished.connect(self.OnEdtRIOneChanged)
        self.edtRITwo.editingFinished.connect(self.OnEdtRITwoChanged)
        self.edtIncAng.editingFinished.connect(self.OnEdtIncAngChanged)
    def drawPlot(self, nOne, nTwo, incAng):
        self.ax.clear()
        # Angle of reflection
        reflAng = incAng
        # Angle of refraction
        refrAng = 180.0 / pi * arcsin(nOne * sin(pi / 180.0 * incAng) / nTwo)

        # The canvas
        x = linspace(-3.0, 3.0, 1024)
        y = linspace(-3.0, 3.0, 1024)
        X, Y = meshgrid(x, y)
        y = sin(2 * pi * x / (nOne / 1000) + nTwo)

        # Draw the boundary between the two media
        bdy = mlines.Line2D([0, 0], [-3, 3], color='k')
        self.ax.add_line(bdy)

        # Draw the normal
        nml = mlines.Line2D([-2, 2], [0, 0], ls='dashed', color='k')
        self.ax.add_line(nml)

        # Draw the incident and reflected ray
        lIncRay = lRefrRay = lReflRay = 2.8
        xIncRay = -lIncRay * cos(pi / 180.0 * incAng)
        yIncRay = -lIncRay * sin(pi / 180.0 * incAng)
        xReflRay = xIncRay
        yReflRay = -yIncRay
        incRay = mlines.Line2D([xIncRay, 0], [yIncRay, 0], color='k')
        self.ax.add_line(incRay)

        # Draw the arrow at the middle of the ray
        self.ax.arrow(xIncRay / 2,
                      yIncRay / 2,
                      0.05,
                      0.05 * tan(pi / 180.0 * incAng),
                      length_includes_head=True,
                      head_width=0.1,
                      color='k',
                      shape='full')
        reflRay = mlines.Line2D([xReflRay, 0], [yReflRay, 0], color='k')
        self.ax.add_line(reflRay)

        # Draw the arrow at the middle of the ray
        self.ax.arrow(xReflRay / 2,
                      yReflRay / 2,
                      -0.05,
                      0.05 * tan(pi / 180.0 * reflAng),
                      length_includes_head=True,
                      head_width=0.1,
                      color='k',
                      shape='full')

        # Draw the refracted ray
        if not isinstance(refrAng, complex):
            xRefrRay = lRefrRay * cos(pi / 180.0 * refrAng)
            yRefrRay = lRefrRay * sin(pi / 180.0 * refrAng)
            refrRay = mlines.Line2D([0, xRefrRay], [0, yRefrRay], color='k')
            self.ax.add_line(refrRay)

            # Draw the arrow at the middle of the ray
            self.ax.arrow(xRefrRay / 2,
                          yRefrRay / 2,
                          0.05,
                          0.05 * tan(pi / 180.0 * refrAng),
                          length_includes_head=True,
                          head_width=0.1,
                          color='k',
                          shape='full')

        # Set the axes properties
        self.ax.set_ylim(-3, 3)
        self.ax.set_xlim(-3, 3)
        self.ax.set_xticklabels([])
        self.ax.set_yticklabels([])
        self.ax.text(-2.5, 2.5, 'Medium 1')
        self.ax.text(1.0, 2.5, 'Medium 2')

        # Draw the axes
        self.draw()
Esempio n. 45
0
import scipy as sp
import matplotlib.pylab as plt

t = sp.arange(0, 10, 1 / 100)
plt.plot(t, sp.sin(1.7 * 2 * sp.pi * t) + sp.sin(1.9 * 2 * sp.pi * t))
plt.show()
Esempio n. 46
0
def get_E_crit(N):
    return - 2 * abs(sp.sin(sp.pi * (2 * sp.arange(N) + 1) / (2 * (2 * N + 1)))).sum()
Esempio n. 47
0
def Heat_1D(c, L, t, T1, T2, fun=lambda x: 100):
    """
    This function gives the solution to the 1D heat equation:
        du(x,t)/dt = c^2 d^2(u(x,t))/dx^2
    Evaluated at multiple times and positions.
    The function only considers members with no internal heat sources. The bar is
    assumed to be homogeneous, made of a single material.
    
    This function's resolution is not very fine, it you want better resolution use
    single_heat as it will be evaluated at a single position and time.
    
    Inputs:
        c: the diffusivity, k/(s*rho)
       
        L: the length of the member
        
        t: the time of interest
        
        T1: boundary condition: u(0,t) = T1
        
        T2: boundary condition: u(L,t) = T2
        
        fun: boundary condition: u(x,0) = f(x) 
        
            fun defaults to 100, this means that the bar is at a uniform temperature of 100 when
            you start observing the system.
    """

    if L <= 10:
        point = int(10 * L)
    else:
        point = 100

    if t <= 60:
        times = int(5 * t)
    else:
        times = 350

    T = sp.linspace(0, t, times)  # the time increments needed
    X = sp.linspace(0, L, point)  # the points on the bar
    N1 = 10  #these are different upperbounds to the series solution to be used as comparison
    N2 = 30
    N3 = 80
    Sol1 = [
    ]  # in the end these will each contain a list for every time value of the solution at the different points on the bar
    Sol2 = []
    Sol3 = []

    for ts in T:  #this loops through the different time increments
        s1 = [
            T1
        ]  #the ends are defined by the boundary conditions so this saves needless calculations
        s2 = [T1]
        s3 = [T1]
        for x in X[
                1:-1]:  # this loops through the defined positions on the bar
            sn1 = [
            ]  #this is list that contains the values of the solution at each n up to N1
            sn2 = [
            ]  #this is list that contains the values of the solution at each n up to N2
            sn3 = [
            ]  #this is list that contains the values of the solution at each n up to N3

            for n in range(1, N1 +
                           1):  # these itterate the n values within the series
                lam1 = c * n * pi / L

                u1_1 = (
                    T2 - T1
                ) * x / L + T1  #this is steady state, time independent solution.

                b1_n = integrate.quad(b_n, 0, L, args=(
                    L,
                    T1,
                    T2,
                    n,
                    fun,
                ))[0]  #this finds the fourier coefficient

                u1_2 = b1_n * sp.exp(-lam1**2 * ts) * sp.sin(
                    n * pi * x / L)  #this is the time dependent solution

                u1 = u1_1 + u1_2
                sn1.append(
                    u1)  # i think if i had been a little more clever and
                #had a bit more time i could have made a subfunction so i would
                #not be doing the same calculation 3 times. Use an appropriate bound conditions on for loop as well

            for n in range(1, N2 +
                           1):  # these itterate the n values within the series
                lam2 = c * n * pi / L

                u2_1 = (
                    T2 - T1
                ) * x / L + T1  #this is steady state, time independent solution.

                b2_n = integrate.quad(b_n, 0, L, args=(
                    L,
                    T1,
                    T2,
                    n,
                    fun,
                ))[0]  #this finds the fourier coefficient

                u2_2 = b2_n * sp.exp(-lam2**2 * ts) * sp.sin(
                    n * pi * x / L)  #this is the time dependent solution

                u2 = u2_1 + u2_2
                sn2.append(u2)

            for n in range(1, N3 +
                           1):  # these itterate the n values within the series
                lam3 = c * n * pi / L

                u3_1 = (
                    T2 - T1
                ) * x / L + T1  #this is steady state, time independent solution.

                b3_n = integrate.quad(b_n, 0, L, args=(
                    L,
                    T1,
                    T2,
                    n,
                    fun,
                ))[0]  #this finds the fourier coefficient

                u3_2 = b3_n * sp.exp(-lam3**2 * ts) * sp.sin(
                    n * pi * x / L)  #this is the time dependent solution

                u3 = u3_1 + u3_2
                sn3.append(u3)

            sol1 = sumr(
                sn1
            )  #this sums up all the values within the list of the solution evaluated at different n's getting the numerical answer at the position
            sol2 = sumr(sn2)
            sol3 = sumr(sn3)

            s1.append(sol1)
            s2.append(sol2)
            s3.append(sol3)
            if x == X[-2]:
                s1.append(
                    T2
                )  #the ends are defined by the boundary conditions so this saves needless calculations
                s2.append(T2)
                s3.append(T2)
        Sol1.append(s1)
        Sol2.append(s2)
        Sol3.append(s3)

    return Sol1, Sol2, Sol3, X, T
Esempio n. 48
0
def somefunc1(x):  # function of a scalar argument
    if x < 0:
        r = 0
    else:
        r = scipy.sin(x)
    return r
Esempio n. 49
0
#     print freq_limit
m_total = sp.zeros((4, 4, freq_limit), float)
m_tot = sp.zeros((freq_limit, 17), float)
for i in range(0, freq_limit):
    #Note that this version is based on the combined matrix I derived corrected for linear feed:
    dG = mp[i, 1]
    al = mp[i, 2] * sp.pi / 180
    ps = mp[i, 3] * sp.pi / 180
    ph = mp[i, 4] * sp.pi / 180
    ep = mp[i, 5]
    ch = mp[i, 6] * sp.pi / 180
    flux = mp[i, 7]
    be = mp[i, 8] * sp.pi / 180

    m_total[0, 0, i] = flux
    m_total[0, 1, i] = flux * (0.5 * dG * sp.cos(2 * al) - 2 * ep * sp.sin(
        2 * al) * sp.cos(ph - ch)) * sp.cos(be) - flux * (
            0.5 * dG * sp.sin(2 * al) * sp.cos(ch) + 2 * ep *
            (sp.cos(al) * sp.cos(al) * sp.sin(ph) -
             sp.sin(al) * sp.sin(al) * sp.cos(ph - 2 * ch))) * sp.sin(be)
    m_total[0, 2, i] = flux * (0.5 * dG * sp.cos(2 * al) - 2 * ep * sp.sin(
        2 * al) * sp.cos(ph - ch)) * sp.sin(be) + flux * (
            0.5 * dG * sp.sin(2 * al) * sp.cos(ch) + 2 * ep *
            (sp.cos(al) * sp.cos(al) * sp.sin(ph) -
             sp.sin(al) * sp.sin(al) * sp.cos(ph - 2 * ch))) * sp.cos(be)
    m_total[0, 3,
            i] = 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_total[1, 0, i] = flux * 0.5 * dG
    m_total[1, 1, i] = flux * sp.cos(2 * al) * sp.cos(be) - flux * sp.sin(
        2 * al) * sp.cos(ch) * sp.sin(be)
Esempio n. 50
0
def single_heat(c, L, x, t, T1, T2, fun=lambda x: 100):
    """
    This function gives the solution to the 1D heat equation:
        du(x,t)/dt = c^2 d^2(u(x,t))/dx^2
    Evaluated at a single time, t, and position, x.
    The function only considers members with no internal heat sources. The bar is
    assumed to be homogeneous, made of a single material.
    
    Inputs:
        c: the diffusivity, k/(s*rho)
       
        L: the length of the member
        
        x: the position of interest
        
        t: the time of interest
        
        T1: boundary condition: u(0,t) = T1
        
        T2: boundary condition: u(L,t) = T2
        
        fun: boundary condition: u(x,0) = f(x) 
        
            fun defaults to 100, this means that the bar is at a uniform temperature of 100 when
            you start observing the system.
    """

    N = 115
    sn = []  #this list will contain the solution at each itteration, n
    if x == 0:
        sol = T1

    elif x == L:
        sol = T2

    else:
        for n in range(1,
                       N + 1):  # these itterate the n values within the series
            lam1 = c * n * pi / L

            u1_1 = (
                T2 - T1
            ) * x / L + T1  #this is steady state, time independent solution.

            b1_n = integrate.quad(b_n, 0, L, args=(
                L,
                T1,
                T2,
                n,
                fun,
            ))[0]  #this finds the fourier coefficient

            u1_2 = b1_n * sp.exp(-lam1**2 * t) * sp.sin(
                n * pi * x / L)  #this is the time dependent solution

            u1 = u1_1 + u1_2
            sn.append(u1)

        sol = sumr(
            sn
        )  #this sums up all the solutions at the values n getting the solution at x,t

    return sol, x, t
Esempio n. 51
0
"""
import matplotlib.pyplot as plt
import scipy as sp
#CADA FIGURE ES UNA VENTANA
#FIGURA 1---------
plt.figure(1)
ejeX = sp.linspace(1,10,100)
y = sp.cos(ejeX)
plt.title('Figura 1')
plt.xlabel('eje x')
plt.ylabel('Mi función coseno')
plt.plot(ejeX, y, 'bo')
#FIGURA 2---------
plt.figure(2)
ejeX2 = sp.linspace(10, 50, 20)
g = sp.sin(ejeX2)
plt.xlabel('eje x')
plt.ylabel('Mi función seno')
plt.title('Figura 2')
plt.plot(ejeX2, g, 'r--')

#FIGURA 3
plt.figure(3)
with plt.style.context(('dark_background')):
    plt.plot(ejeX2, g, 'r-o')


plt.show()


Esempio n. 52
0
def run(hps=None):
    defaults = PaperDefaults()

    #David's globals
    _DECODER_TYPE = None  #'circular_vote'
    _DEFAULT_KW97_TILTEFFECT_DEGPERPIX = .45  # <OToole77>
    _DEFAULT_TILTEFFECT_SIZE = 101  #101
    _DEFAULT_KW97_TILTEFFECT_CSIZE = iround(3.6 /
                                            _DEFAULT_KW97_TILTEFFECT_DEGPERPIX)
    _DEFAULT_KW97_TILTEFFECT_NSIZE = iround(5.4 /
                                            _DEFAULT_KW97_TILTEFFECT_DEGPERPIX)
    _DEFAULT_KW97_TILTEFFECT_FSIZE = iround(10.7 /
                                            _DEFAULT_KW97_TILTEFFECT_DEGPERPIX)
    _DEFAULT_TILTEFFECT_CVAL = .5
    _DEFAULT_TILTEFFECT_SVALS = np.linspace(0.0, 0.5, 10)
    _DEFAULT_KW97_TILTEFFECT_SCALE = 1.25
    _DEFAULT_TILTEFFECT_NPOINTS = 25  #100
    _DEFAULT_TILTEFFECT_CIRCULAR = True
    _DEFAULT_TILTEFFECT_DECODER_TYPE = 'circular_vote'
    csvfiles = [
        os.path.join(defaults._DATADIR, 'KW97_GH.csv'),
        os.path.join(defaults._DATADIR, 'KW97_JHK.csv'),
        os.path.join(defaults._DATADIR, 'KW97_LL.csv'),
        os.path.join(defaults._DATADIR, 'KW97_SJL.csv'),
    ]

    # experiment parameters
    m = (lambda x: sp.sin(sp.pi * x)) if _DEFAULT_TILTEFFECT_CIRCULAR else (
        lambda x: x)
    cpt = (_DEFAULT_TILTEFFECT_SIZE // 2, _DEFAULT_TILTEFFECT_SIZE // 2)
    spt = (_DEFAULT_TILTEFFECT_SIZE // 2,
           _DEFAULT_TILTEFFECT_SIZE // 2 + _DEFAULT_KW97_TILTEFFECT_CSIZE)
    dt_in = _DEFAULT_TILTEFFECT_CVAL - _DEFAULT_TILTEFFECT_SVALS
    dtmin = dt_in.min()
    dtmax = dt_in.max()

    # simulate populations
    im = sp.array([[
        stim.get_center_nfsurrounds(size=_DEFAULT_TILTEFFECT_SIZE,
                                    csize=_DEFAULT_KW97_TILTEFFECT_CSIZE,
                                    nsize=_DEFAULT_KW97_TILTEFFECT_NSIZE,
                                    fsize=_DEFAULT_KW97_TILTEFFECT_FSIZE,
                                    cval=_DEFAULT_TILTEFFECT_CVAL,
                                    nval=sp.nan,
                                    fval=sval,
                                    bgval=sp.nan)
    ] for sval in _DEFAULT_TILTEFFECT_SVALS])

    # get shifts for model for both papers, and from digitized data
    sortidx = sp.argsort(dt_in)  # re-order in increasing angular differences

    # O'Toole and Wenderoth (1977)
    n_subjects = len(csvfiles)
    ds_kw97_paper_x = sp.zeros((n_subjects, 9))
    ds_kw97_paper_y = sp.zeros((n_subjects, 9))

    for sidx, csv in enumerate(csvfiles):
        ds_kw97_paper_x[sidx], ds_kw97_paper_y[sidx] = \
            sp.genfromtxt(csv, delimiter=',').T
    dt_model = (_DEFAULT_TILTEFFECT_CVAL -
                _DEFAULT_TILTEFFECT_SVALS)[sortidx] * 360

    ds_kw97_paper_x = (ds_kw97_paper_x + 360.) % 360. - 45.
    ds_kw97_paper_y = 45. - ds_kw97_paper_y

    for sidx in range(n_subjects):
        ds_kw97_paper_x[sidx] = ds_kw97_paper_x[sidx][sp.argsort(
            ds_kw97_paper_x[sidx])]

    extra_vars = {}
    extra_vars['scale'] = _DEFAULT_KW97_TILTEFFECT_SCALE
    extra_vars['decoder'] = _DEFAULT_TILTEFFECT_DECODER_TYPE
    extra_vars['npoints'] = _DEFAULT_TILTEFFECT_NPOINTS
    extra_vars['npoints'] = _DEFAULT_TILTEFFECT_NPOINTS
    extra_vars['cval'] = _DEFAULT_TILTEFFECT_CVAL
    extra_vars['sortidx'] = sortidx
    extra_vars['cpt'] = cpt
    extra_vars['spt'] = spt
    extra_vars['sval'] = sval
    extra_vars['kind'] = 'circular'
    extra_vars['figure_name'] = 'f3b'
    extra_vars['return_var'] = 'O'

    adjusted_gt = signal.resample(np.mean(ds_kw97_paper_y, axis=0), 10)
    defaults = adjust_parameters(defaults, hps)
    optimize_model(im, adjusted_gt, extra_vars, defaults)
Esempio n. 53
0
def f(r, t):
    theta = r[0]
    omega = r[1]
    ftheta = omega
    fomega = -(g / l) * sin(theta)
    return array([ftheta, fomega], float)
Esempio n. 54
0
    def fit(
        self,
        raw_data=None,
        n_slices=None,
        n_scans=None,
        timing=None,
    ):
        """Fits an STC transform that can be later used (using the
        transform(..) method) to re-slice compatible data.

        Each row of the fitter transform is precisely the filter by
        which the signal will be convolved to introduce the phase
        shift in the corresponding slice. It is constructed explicitly
        in the Fourier domain. In the time domain, it can be described
        via the Whittaker-Shannon formula (sinc interpolation).

        Parameters
        ----------
        raw_data: 4D array of shape (n_rows, n_colomns, n_slices,
        n_scans) (optional, default None)
            raw data to fit the transform on. If this is specified, then
            n_slices and n_scans parameters should not be specified.

        n_slices: int (optional, default None)
            number of slices in each 3D volume. If the raw_data parameter
            is specified then this parameter should not be specified

        n_scans: int (optional, default None)
            number of 3D volumes. If the raw_data parameter
            is specified then this parameter should not be specified

        timing: list or tuple of length 2 (optional, default None)
            additional information for sequence timing
            timing[0] = time between slices
            timing[1] = time between last slices and next volume

        Returns
        -------
        self: fitted STC object

        Raises
        ------
        ValueError, in case parameters are insane

        """

        # set basic meta params
        if not raw_data is None:
            raw_data = self._sanitize_raw_data(
                raw_data,
                fitting=True,
            )
            self.n_slices = raw_data.shape[2]
            self.n_scans = raw_data.shape[-1]

            self.raw_data = raw_data
        else:
            if n_slices is None:
                raise ValueError(
                    "raw_data parameter not specified. You need to"
                    " specify a value for n_slices!")
            else:
                self.n_slices = n_slices
            if n_scans is None:
                raise ValueError(
                    "raw_data parameter not specified. You need to"
                    " specify a value for n_scans!")
            else:
                self.n_scans = n_scans

        # fix slice indices consistently with slice order
        self.slice_indices = get_slice_indices(self.n_slices,
                                               slice_order=self.slice_order,
                                               return_final=True,
                                               interleaved=self.interleaved)

        # fix ref slice index, to be consistent with the slice order
        self.ref_slice = self.slice_indices[self.ref_slice]

        # timing info (slice_TR is the time of acquisition of a single slice,
        # as a fractional multiple of the TR)
        if not timing is None:
            TR = (self.n_slices - 1) * timing[0] + timing[1]
            slice_TR = timing[0] / TR
            assert 0 <= slice_TR < 1
            self._log("Your TR is %s" % TR)
        else:
            # TR normalized to 1 (
            slice_TR = 1. / self.n_slices

        # least power of 2 not less than n_scans
        N = 2**int(np.floor(np.log2(self.n_scans)) + 1)

        # this will hold phase shifter of each slice k
        self.kernel_ = np.ndarray(
            (self.n_slices, N),
            dtype=np.complex,  # beware, default dtype is float!
        )

        # loop over slices (z axis)
        for z in range(self.n_slices):
            self._log(("STC: Estimating phase-shift transform for slice "
                       "%i/%i...") % (z + 1, self.n_slices))

            # compute time delta for shifting this slice w.r.t. the reference
            shift_amount = (self.slice_indices[z] - self.ref_slice) * slice_TR

            # phi represents a range of phases up to the Nyquist
            # frequency
            phi = np.ndarray(N)
            phi[0] = 0.
            for f in range(int(N / 2)):
                phi[f + 1] = -1. * shift_amount * 2 * np.pi * (f + 1) / N

            # check if signal length is odd or even -- impacts how phases
            # (phi) are reflected across Nyquist frequency
            offset = N % 2

            # mirror phi about the center
            phi[int(1 + N / 2 - offset):] = -phi[int(N / 2 + offset - 1):0:-1]

            # map phi to frequency domain: phi -> complex
            # point z = exp(i * phi) on unit circle
            self.kernel_[z] = scipy.cos(phi) + scipy.sqrt(-1) * scipy.sin(phi)

        self._log("Done.")

        # return fitted object
        return self
Esempio n. 55
0
def f(wind_angle, i):

    random_state = np.random.RandomState(i)

    wind_mag = 1.2

    file_name = 'trap_arrival_by_wind_live_coarse_dt'
    file_name = file_name + '_wind_mag_' + str(
        wind_mag) + '_wind_angle_' + str(wind_angle)[0:4] + '_iter_' + str(i)
    output_file = file_name + '.pkl'

    dt = 0.25
    plume_dt = 0.25
    frame_rate = 20
    times_real_time = 20  # seconds of simulation / sec in video
    capture_interval = int(scipy.ceil(times_real_time * (1. / frame_rate) /
                                      dt))

    simulation_time = 50. * 60.  #seconds
    release_delay = 30. * 60  #/(wind_mag)

    t_start = 0.0
    t = 0. - release_delay

    wind_param = {
        'speed': wind_mag,
        'angle': wind_angle,
        'evolving': False,
        'wind_dt': None,
        'dt': dt
    }
    wind_field_noiseless = wind_models.WindField(param=wind_param)

    #traps
    number_sources = 8
    radius_sources = 1000.0
    trap_radius = 0.5
    location_list, strength_list = utility.create_circle_of_sources(
        number_sources, radius_sources, None)
    trap_param = {
        'source_locations': location_list,
        'source_strengths': strength_list,
        'epsilon': 0.01,
        'trap_radius': trap_radius,
        'source_radius': radius_sources
    }

    traps = trap_models.TrapModel(trap_param)

    #Wind and plume objects

    #Odor arena
    xlim = (-1500., 1500.)
    ylim = (-1500., 1500.)
    sim_region = models.Rectangle(xlim[0], ylim[0], xlim[1], ylim[1])
    wind_region = models.Rectangle(xlim[0] * 1.2, ylim[0] * 1.2, xlim[1] * 1.2,
                                   ylim[1] * 1.2)

    source_pos = scipy.array(
        [scipy.array(tup) for tup in traps.param['source_locations']]).T

    #wind model setup
    diff_eq = False
    constant_wind_angle = wind_angle
    aspect_ratio = (xlim[1] - xlim[0]) / (ylim[1] - ylim[0])
    noise_gain = 3.
    noise_damp = 0.071
    noise_bandwidth = 0.71
    wind_grid_density = 200
    Kx = Ky = 10000  #highest value observed to not cause explosion: 10000
    wind_field = models.WindModel(wind_region,
                                  int(wind_grid_density * aspect_ratio),
                                  wind_grid_density,
                                  noise_gain=noise_gain,
                                  noise_damp=noise_damp,
                                  noise_bandwidth=noise_bandwidth,
                                  Kx=Kx,
                                  Ky=Ky,
                                  noise_rand=random_state,
                                  diff_eq=diff_eq,
                                  angle=constant_wind_angle,
                                  mag=wind_mag)

    # Set up plume model
    centre_rel_diff_scale = 2.
    # puff_release_rate = 0.001
    puff_release_rate = 10
    puff_spread_rate = 0.005
    puff_init_rad = 0.01
    max_num_puffs = int(2e5)
    # max_num_puffs=100

    plume_model = models.PlumeModel(
        sim_region,
        source_pos,
        wind_field,
        simulation_time + release_delay,
        plume_dt,
        plume_cutoff_radius=1500,
        centre_rel_diff_scale=centre_rel_diff_scale,
        puff_release_rate=puff_release_rate,
        puff_init_rad=puff_init_rad,
        puff_spread_rate=puff_spread_rate,
        max_num_puffs=max_num_puffs,
        prng=random_state)

    puff_mol_amount = 1.

    #Setup fly swarm
    wind_slippage = (0., 1.)
    swarm_size = 2000
    use_empirical_release_data = False

    #Grab wind info to determine heading mean
    wind_x, wind_y = wind_mag * scipy.cos(wind_angle), wind_mag * scipy.sin(
        wind_angle)

    beta = 1.
    release_times = scipy.random.exponential(beta, (swarm_size, ))
    kappa = 2.

    heading_data = None

    swarm_param = {
        'swarm_size':
        swarm_size,
        'heading_data':
        heading_data,
        'initial_heading':
        scipy.radians(scipy.random.uniform(0.0, 360.0, (swarm_size, ))),
        'x_start_position':
        scipy.zeros(swarm_size),
        'y_start_position':
        scipy.zeros(swarm_size),
        'flight_speed':
        scipy.full((swarm_size, ), 1.5),
        'release_time':
        release_times,
        'release_delay':
        release_delay,
        'cast_interval': [1, 3],
        'wind_slippage':
        wind_slippage,
        'odor_thresholds': {
            'lower': 0.0005,
            'upper': 0.05
        },
        'schmitt_trigger':
        False,
        'low_pass_filter_length':
        3,  #seconds
        'dt_plot':
        capture_interval * dt,
        't_stop':
        3000.,
        'cast_timeout':
        20,
        'airspeed_saturation':
        True
    }

    swarm = swarm_models.BasicSwarmOfFlies(wind_field_noiseless,
                                           traps,
                                           param=swarm_param,
                                           start_type='fh',
                                           track_plume_bouts=False,
                                           track_arena_exits=False)

    # xmin,xmax,ymin,ymax = -1000,1000,-1000,1000

    #Conc array gen to be used for the flies
    sim_region_tuple = plume_model.sim_region.as_tuple()

    #for the plume distance cutoff version, make sure this is at least 2x radius
    box_min, box_max = -3000., 3000.

    r_sq_max = 20
    epsilon = 0.00001
    N = 1e6

    array_gen_flies = processors.ConcentrationValueFastCalculator(
        box_min, box_max, r_sq_max, epsilon, puff_mol_amount, N)

    while t < simulation_time:
        for k in range(capture_interval):
            #update flies
            print('t: {0:1.2f}'.format(t))
            #update the swarm
            for j in range(int(dt / plume_dt)):
                wind_field.update(plume_dt)
                plume_model.update(plume_dt, verbose=True)
            if t > 0.:
                swarm.update(t,
                             dt,
                             wind_field_noiseless,
                             array_gen_flies,
                             traps,
                             plumes=plume_model,
                             pre_stored=False)
            t += dt

    with open(output_file, 'w') as f:
        pickle.dump((wind_field_noiseless, swarm), f)
 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])
Esempio n. 57
0
def rotation_matrix(angle):
    A = scipy.array([[scipy.cos(angle), -scipy.sin(angle)],
                     [scipy.sin(angle), scipy.cos(angle)]])
    return A
Esempio n. 58
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
Esempio n. 59
0
def base(model, state_vec, noise_diff_coeffs, turn_rate):
    """ Base test for n-dimensional ConstantAcceleration Transition Models """

    # Create an ConstantTurn model object
    model = model
    model_obj = model(noise_diff_coeffs=noise_diff_coeffs, turn_rate=turn_rate)

    # State related variables
    state_vec = state_vec
    old_timestamp = datetime.datetime.now()
    timediff = 1  # 1sec
    new_timestamp = old_timestamp + datetime.timedelta(seconds=timediff)
    time_interval = new_timestamp - old_timestamp

    # Model-related components
    noise_diff_coeffs = noise_diff_coeffs  # m/s^3
    turn_rate = turn_rate
    turn_ratedt = turn_rate * timediff
    F = sp.array([[
        1,
        sp.sin(turn_ratedt) / turn_rate, 0,
        -(1 - sp.cos(turn_ratedt)) / turn_rate
    ], [0, sp.cos(turn_ratedt), 0, -sp.sin(turn_ratedt)],
                  [
                      0, (1 - sp.cos(turn_ratedt)) / turn_rate, 1,
                      sp.sin(turn_ratedt) / turn_rate
                  ], [0, sp.sin(turn_ratedt), 0,
                      sp.cos(turn_ratedt)]])

    qx = noise_diff_coeffs[0]
    qy = noise_diff_coeffs[1]
    Q = sp.array([[
        sp.power(qx, 2) * sp.power(timediff, 3) / 3,
        sp.power(qx, 2) * sp.power(timediff, 2) / 2, 0, 0
    ],
                  [
                      sp.power(qx, 2) * sp.power(timediff, 2) / 2,
                      sp.power(qx, 2) * timediff, 0, 0
                  ],
                  [
                      0, 0,
                      sp.power(qy, 2) * sp.power(timediff, 3) / 3,
                      sp.power(qy, 2) * sp.power(timediff, 2) / 2
                  ],
                  [
                      0, 0,
                      sp.power(qy, 2) * sp.power(timediff, 2) / 2,
                      sp.power(qy, 2) * timediff
                  ]])

    # Ensure ```model_obj.transfer_function(time_interval)``` returns F
    assert sp.array_equal(
        F,
        model_obj.matrix(timestamp=new_timestamp, time_interval=time_interval))

    # Ensure ```model_obj.covar(time_interval)``` returns Q
    assert sp.array_equal(
        Q, model_obj.covar(timestamp=new_timestamp,
                           time_interval=time_interval))

    # Propagate a state vector through the model
    # (without noise)
    new_state_vec_wo_noise = model_obj.function(state_vec,
                                                noise=0,
                                                timestamp=new_timestamp,
                                                time_interval=time_interval)

    assert sp.array_equal(new_state_vec_wo_noise, F @ state_vec)

    # Evaluate the likelihood of the predicted state, given the prior
    # (without noise)
    prob = model_obj.pdf(new_state_vec_wo_noise,
                         state_vec,
                         timestamp=new_timestamp,
                         time_interval=time_interval)
    assert approx(prob) == multivariate_normal.pdf(new_state_vec_wo_noise.T,
                                                   mean=sp.array(
                                                       F @ state_vec).ravel(),
                                                   cov=Q)

    # Propagate a state vector throughout the model
    # (with internal noise)
    new_state_vec_w_inoise = model_obj.function(state_vec,
                                                timestamp=new_timestamp,
                                                time_interval=time_interval)
    assert not sp.array_equal(new_state_vec_w_inoise, F @ state_vec)

    # Evaluate the likelihood of the predicted state, given the prior
    # (with noise)
    prob = model_obj.pdf(new_state_vec_w_inoise,
                         state_vec,
                         timestamp=new_timestamp,
                         time_interval=time_interval)
    assert approx(prob) == multivariate_normal.pdf(new_state_vec_w_inoise.T,
                                                   mean=sp.array(
                                                       F @ state_vec).ravel(),
                                                   cov=Q)

    # Propagate a state vector through the model
    # (with external noise)
    noise = model_obj.rvs(timestamp=new_timestamp, time_interval=time_interval)
    new_state_vec_w_enoise = model_obj.function(state_vec,
                                                timestamp=new_timestamp,
                                                time_interval=time_interval,
                                                noise=noise)
    assert sp.array_equal(new_state_vec_w_enoise, F @ state_vec + noise)

    # Evaluate the likelihood of the predicted state, given the prior
    # (with noise)
    prob = model_obj.pdf(new_state_vec_w_enoise,
                         state_vec,
                         timestamp=new_timestamp,
                         time_interval=time_interval)
    assert approx(prob) == multivariate_normal.pdf(new_state_vec_w_enoise.T,
                                                   mean=sp.array(
                                                       F @ state_vec).ravel(),
                                                   cov=Q)
Esempio n. 60
0
def elevDeriv(val_mat, direction_mat, inc):

    import scipy
    import scipy.linalg
    import math

    cell_angles = scipy.flipud(
        scipy.array([[3 * math.pi / 4, math.pi / 2, math.pi / 4],
                     [math.pi, scipy.nan, 0],
                     [-3 * math.pi / 4, -1 * math.pi / 2, -1 * math.pi / 4]]))
    cell_incs = scipy.array([[(inc**2 + inc**2)**0.5, inc,
                              (inc**2 + inc**2)**0.5], [inc, scipy.nan, inc],
                             [(inc**2 + inc**2)**0.5, inc,
                              (inc**2 + inc**2)**0.5]])
    angle = direction_mat[1, 1]

    cell_cosines_f = scipy.cos(angle - cell_angles)
    cell_cosines_b = scipy.cos(angle - cell_angles)
    cell_sines_f = scipy.sin(angle - cell_angles)
    cell_sines_b = scipy.sin(angle - cell_angles)

    cell_cosines_f[cell_cosines_f < 0.00001] = scipy.nan
    cell_cosines_f = cell_cosines_f**2
    cell_cosines_f = cell_cosines_f / sum(
        cell_cosines_f[~scipy.isnan(cell_cosines_f)])
    cell_cosines_b[cell_cosines_b > -0.00001] = scipy.nan
    cell_cosines_b = cell_cosines_b**2
    cell_cosines_b = cell_cosines_b / sum(
        cell_cosines_b[~scipy.isnan(cell_cosines_b)])
    cell_sines_f[cell_sines_f < 0.00001] = scipy.nan
    cell_sines_f = cell_sines_f**2
    cell_sines_f = cell_sines_f / sum(cell_sines_f[~scipy.isnan(cell_sines_f)])
    cell_sines_b[cell_sines_b > -0.00001] = scipy.nan
    cell_sines_b = cell_sines_b**2
    cell_sines_b = cell_sines_b / sum(cell_sines_b[~scipy.isnan(cell_sines_b)])

    temp = val_mat * cell_cosines_f
    h_x_f = sum(temp[~scipy.isnan(temp)])

    temp = val_mat * cell_cosines_b
    h_x_b = sum(temp[~scipy.isnan(temp)])

    temp = val_mat * cell_sines_f
    h_y_f = sum(temp[~scipy.isnan(temp)])

    temp = val_mat * cell_sines_b
    h_y_b = sum(temp[~scipy.isnan(temp)])

    h_x = scipy.array([h_x_b, val_mat[1, 1], h_x_f])
    h_y = scipy.array([h_y_b, val_mat[1, 1], h_y_f])

    xs = scipy.array([-1 * int(inc), 0, int(inc)])
    A = scipy.vstack([xs, scipy.ones(len(xs))]).T

    #	print("A: " + str(A));
    #	print("h_x_b: " + str(h_x_b));
    #	print("val_mat[1,1]: " + str(val_mat[1,1]));
    #	print("h_x_f: " + str(h_x_f));

    dh_dx, intercept = scipy.linalg.lstsq(A, h_x)[0]
    dh_dy, intercept = scipy.linalg.lstsq(A, h_y)[0]

    return dh_dx, dh_dy