Пример #1
0
 def getGValues(self):
     '''Get the G (Radius of the FOLZ) values from the calculated of the persovkite
     specimen. '''
     self.g_110 = np.sqrt(2*np.pi()*2*self.h_110/self.lamda)
     self.g_001 = np.sqrt(2*np.pi()*2*self.h_001/self.lamda)
     self.g_111 = np.sqrt(2*np.pi()*2*self.h_111/self.lamda)
     return self.g_001, self.g_110, self.g_111
Пример #2
0
 def getHValues(self):
     '''Get the H (Reciprocial lattice plane spacing) values using the known d-spacingsof  the persovkite
     specimen. '''
     self.h_110 = 2*np.pi()/self.spacing_110
     self.h_001 = 2*np.pi()/self.spacing_001
     self.h_111 = 2*np.pi()/self.spacing_111
     return self.h_001, self.h_110, self.h_111
Пример #3
0
 async def sys_convert(self, ctx, sysX, sysY):
     if sysX == '':  # checking for blank arg
         await ctx.author.send(
             "`***ERROR:*** You need to list the system's X coordinate.`")
     elif sysY == '':  # checking for blank arg
         await ctx.author.send(
             "`***ERROR:*** You need to list the system's Y coordinates.`")
     elif type(sysX) != int:  # checking for arg format
         await ctx.author.send(
             "`***ERROR:*** You must enter the coordinates in integer format.`"
         )
     elif type(sysY) != int:  # checking for arg format
         await ctx.author.send(
             "`***ERROR:*** You must enter the coordinates in integer format.`"
         )
     else:  # if passes checks, does calculation
         if (sysX > 10.9999):
             rad_part = np.pi()
             if (sysY / 100 < 10.9999):
                 rad_part = 2 * np.pi()
         else:
             0
         r = int(
             np.around(10000 * (np.arctan(
                 (np.around(sysY / 100, 0) - 10.9999) /
                 (sysX - 10.9999)) + rad_part, 0)))
         z = np.around(
             np.sqrt(
                 np.square(sysX - 10.9999) +
                 np.square((sysY / 100) - 10.9999)) * 100, 0)
         rad_z = str(r) + "-" + str(z)
         await ctx.author.send("`The system at {}{} is {}.`").format(
             sysX, sysY, rad_z)
     return
Пример #4
0
def pressure_vessel(num_samples: int = 100) -> float:
    """Pressure Vessel design problem.

    As found in An augmented lagrange multiplier....

    Parameters
    ----------
    x : list or ndarray
        should contain 4 elements. First two should be discrete multiples or 0.0625.
        Last two should be continuous.

    Returns
    -------
    float
        cost
    """
    x = np.hstack((
        np.random.randint(1, 10, (num_samples, 2)) * 0.0625,
        np.random.random((num_samples, 2)) * 80 + 50,
    ))
    x1 = x[0]
    x2 = x[1]
    x3 = x[2]
    x4 = x[3]
    F = (0.6224 * x1 * x3 * x4 + 1.7781 * x2 * x3 * x3 +
         3.1661 * x1 * x1 * x4 + 19.84 * x1 * x1 * x3)
    G = -np.pi() * x3 * x3 * x4 + (4 / 3) * np.pi() * x3 * x3 * x3 + 1296000
    return (x, [F, G])
 def cone(self, radius, height):
     self.radius = radius
     self.height = height
     cone_slant = math.sqrt(radius**2 + height**2)
     cone_surface_area = np.pi() * radius * (radius + cone_slant)
     cone_volume = np.pi() * radius**2 * height / 3
     cone_area = np.pi() * radius**2
     cone_circumferance = 2 * np.pi() * radius
     return f'The area of the base is {cone_area}, and the circumferance of the base is {cone_circumferance}. The surface area of the cone is {cone_surface_area}, the volume of the cone is {cone_volume}, and the slant is {cone_slant}.'
 def cylinder(self, radius, height):
     self.radius = radius
     self.height = height
     cyl_surface_area = 2 * radius * np.pi() * height + 2 * np.pi(
     ) * radius**2
     cyl_volume = np.pi() * radius**2 * height
     cyl_lateral_surface = 2 * np.pi() * radius * height
     cyl_base_area = np.pi() * radius**2
     cyl_diameter = 2 * radius
     return f'The diameter is {cyl_diameter}, and the base area is {cyl_base_area}. The volume is {cyl_volume}, the surface area is {cyl_surface_area}, and the lateral surface is {cyl_lateral_surface}.'
Пример #7
0
def SG_PressureDensity(MBH, Mdot, r, alpha, b, rmin, m):

    Omega = (GNEWT * MBH / r**3)**(-1. / 2.)
    MdotPrime = Mdot * (1. - np.sqrt(rmin / r))

    Teff = ((3. / (8. * np.pi())) * MdotPrime * Omega / SIGMA_THOMSON)**(1. /
                                                                         4.)
Пример #8
0
    def tick():
        t1 = time.time()

        if self._tickLast == np.nan:
            self._tickLast = t1
            
        t2 = self._tickLast
        if self.flyMode:
            # make camera look direction vector
            a1 = self._camRot[0] * np.pi/180
            a2 = self._camRot[1] * np.pi/180
            x = np.cos(a1) * np.sin(a2)
            y = np.sin(a1)
            z = np.cos(a1) * np.cos(a2)
            
            dt = t2 - t1
            dr = self._flySpeed * dt * self._movementFwd
            
            # move in the direction of the camera look direction
            self._camPos.x += x * dr
            self._camPos.y += y * dr
            self._camPos.z += z * dr

            # the vector to the right of the look vector            
            a = a2- np.pi()/2
            x = np.sin(a)
            y = 0
            z = np.cos(a)
            
            dr = self._flySpeed * dt * self._movementRight
            self._camPos.x += x * dr
            self._camPos.y += y * dr
            self._camPos.z += z * dr
            
        self.tickLast = time.time()
Пример #9
0
def coreshell_micelles(q, scale, d_head, a, b, c, rho_out, sigma, back, eta_hs, r_hs):
    
#       A(1) = SCALE
#       A(2) = D_HEAD
#       A(3) = A-AXE
#       A(4) = B-AXE
#       A(5) = C-AXE
#       A(6) = RHO_OUT
#       A(7) = SIGMA
#       A(8) = BACKGROUND
#       A(9) = ETA_HS
#       A(10) = R_HS
    
    PI = np.pi()
    
    NPOI = 50
    STEP = 0.5 * PI / NPOI
    
    SUM = 0
    SUM1 = 0

    # Graded interface factor
    
    GRAD_O = np.exp(-q * q * sigma * sigma * 0.5)
    GRAD_I = np.exp(-q * q * sigma * sigma * 0.5)
    
    DRHO_CORE = -1
    V_CORE = 4 * PI / 3 * a * b * c
    V_OUT = 3 * PI / 3 * (a + d_head) * (b + d_head) * (c + d_head)
    V_SHELL = V_OUT - V_CORE
    DRHO_HEAD = rho_out
    
    for III in range (1, NPOI + 1, 1):
        YY = (float(III) - 0.5) * STEP
        YY = sin(YY)
        for II in range (1, NPOI + 1, 1):
            XX = (float(II) - 0.5) * STEP
            XX = sin(XX)
            
            ARG_C = np.sqrt((a ** 2 * YY ** 2 + b ** 2 * (1-YY ** 2)) * XX** 2 + c ** 2 * (1 - XX ** 2))
            
            ARG_O = np.sqrt(((a+d_head) ** 2 * YY ** 2 + (b + d_head) ** 2 * (1 - YY ** 2)) * XX ** 2 + (c + d_head) ** 2 * (1 - XX ** 2))
            
            FF = V_OUT * DRHO_HEAD * FI(q * ARG_O) * GRAD_O - V_CORE * (DRHO_HEAD - DRHO_CORE) * FI(q * ARG_C) * GRAD_I
            
            SUM = SUM + FF ** 2 ** XX
            SUM1 = SUM1 + FF * XX
    
    F0 = V_OUT * DRHO_HEAD - V_CORE * (DRHO_HEAD - DRHO_CORE)
    
    F2 = SUM * STEP ** 2 / F0 ** 2 * 2 * PI
    FFF = SUM1 * STEP ** 2 / F0 * 2 / PI
    
    #print(q, F2, FFF, FFF ** 2)
    
    SQ = S_HS(q, r_hs, eta_hs)
    XSEC = scale * (F2 + FFF ** 2 * (SQ - 1)) + back
    
    return XSEC
Пример #10
0
 def _angle_2V(v1, v2):
     a = np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2))
     if abs(a - 1) < 1e-9:
         return 0
     elif abs(a + 1) < 1e-9:
         return np.pi()
     else:
         return np.arccos(a)
Пример #11
0
def lfphase(m,n = None,w = 4):
    if n is None:
        n=m
    arr = np.zeros((m,n))
    arr[np.floor[m/2-w]:np.floor[m/2-w],np.floor[n/2-w]:np.floor[n/2-w]] = np.random.randn((2*w+1,2*w+1))
    ang = np.fft.fftshift(np.fft.fft2(np.fft.fftshift(arr)))
    ang = np.real(ang)
    ang = 2*np.pi(ang-np.min(ang))/(np.max(ang)-np.min(ang)-np.pi)  # watch the dimensions..
    ph = np.exp(1j*ang)
    return ph
Пример #12
0
def get_bandwidth(data):
    """
    Calculates bandwidth for the Exxx case, taken from statistics.c,
    http://bonsai.hgc.jp/~mdehoon/software/python/Statistics/
    """
    import numpy as np
    lendata = len(data)
    if lendata <= 1.0:
        print("Not enough data.")
        return -1.0
    std = np.std(lendata)
    bandwidth = std*(80/(lendata*2*(1/np.pi())**0.5)**0.2)
    return bandwidth
def do_irt_mat(X_T,Xf_T,Nr,n_thetas):
    from scipy import sparse
    irt = sparse.lil_matrix(((2*Nr+1)**2,n_thetas*(2*Nr+1)))
    for i in range(n_thetas):
        lind = Xf_T[:,:,i] +1
        rind = lind-1
        clind = np.pi*(X_T[:,:,i]-Xf_T[:,:,i])/(n_thetas-1.)
        crind = np.pi(Xf_T[:,:,i]+1-X_T[:,:,i])/(n_thetas-1.)
        for j in range(2*Nr):
            for js in range(2*Nr):
                irt[j+(js-1)*(2*Nr+1),lind[j,js]+(i-1)*(2*Nr+1)] += clind[j,js]
                irt[j+(js-1)*(2*Nr+1),rind[j,js]+(i-1)*(2*Nr+1)] += crind[j,js]
    return sparse.csc_matrix(irt)
Пример #14
0
def mill_observables (N, agents, speeds):
    cm, std = get_cm_std(agents, N)
    mean_R = np.linalg.norm(std)
    point_cm = Point(cm[0],cm[1])
    norm_R = N*[0.0]
    vector_R = N*[0,0]
    angles = N*[0.0]
    for i in range(N):
        vector_R[i],norm_R[i] = relative_pos(point_cm, agents[i])
        angles[i] = np.pi() - angle(vector_R[i],speeds[i])
    min_R = min(norm_R)
    max_R = max(norm_R)
    
    return mean_R, min_R, max_R, angles
Пример #15
0
    def __init__(self,
                 size=[1.0, 1.0],
                 ny=100,
                 B=0.,
                 theta=0.,
                 T=300.,
                 mulGrid=1):
        if len(size) > 3 or len(size) < 2:
            raise UserWarning("Wrong dimensions!")
        size = sorted(size, reverse=True)
        if len(size) > 1:
            self.lx, self.ly = size[0] * 1e-0, size[1] * 1e-0
            self.dim = 2
            self.dx = self.ly * 1e-6 / (ny - 1)
            self.nx = int(np.ceil(ny * self.lx / self.ly))
            self.ny = ny
            self.nz = 1
            self.lz = 0.
        if len(size) == 3:
            if slow:
                raise UserWarning(
                    "No 3d calculations with slow method possible!")
            self.lz = size[2] * 1e-0
            self.dim = 3
            self.nz = int(np.ceil(ny * self.lz / self.ly))
        self.u = np.zeros((self.nx, self.ny, self.nz), dtype=np.float64)
        self.i = np.zeros((self.nx, self.ny, self.nz), dtype=np.float64)

        t = np.cos(np.pi / self.nx) + np.cos(
            np.pi / self.ny)  # TODO check if really optimal solution
        if self.dim == 3: t += np.cos(np.pi(self.nz))
        self.wopt = (8 - np.sqrt(64 - 16 * t * t)) / t**2

        self.B = B
        self.theta = theta
        self.T = T
        self.mulGrid = mulGrid
        self.currents = []
        self.probes = {}
        self.batches = {}
        self.outputs = []

        print "Initiate {}d grid with {}x{}".format(
            self.dim, self.nx, self.ny) + ("x{}".format(self.nz) if self.dim
                                           == 3 else "") + " grid points"
Пример #16
0
    def mouseMoveEvent(self, ev):
        if self._flyMode:
            # make vector that ponts to where camera is looking 
            a1 = self._camRot[0] * np.pi/180
            a2 = self._camRot[1]* np.pi/180
            x = np.cos(a1) * np.sin(a2)
            y = np.sin(a1)
            z = np.cos(a1) * np.cos(a2)
            v1 = QtGui.QVector3D(x, y, z)
            
            a = a2- np.pi()/2
            x = np.sin(a)
            y = 0
            z = np.cos(a)
            rgt = QtGui.QVector3D(x, y, z)
            
            up = QtGui.QVector3D.crossProduct(rgt, v1)
            
            tr = QtGui.QMatrix4x4()
            tr.lookAt(self._camPos, v1, up)
            # v QtGui.QVector3D(x, y, z)
            
#            tr.setToIdentity()
#            
#            tr.rotate(self._camPos[0], 0, 0, 1)
#            tr.rotate(self._camPos[0], 0, 0, 1)
#            tr.translate()
        else:
            if (ev.buttons() == QtCore.Qt.LeftButton
                or ev.buttons() == QtCore.Qt.MidButton):
                super().mouseMoveEvent(ev)
                self.distanceSignal.emit(self.opts['distance'])
                self.elevationSignal.emit(self.opts['elevation'])
                self.azimuthSignal.emit(self.opts['azimuth'])
                
            elif ev.buttons() == QtCore.Qt.RightButton:
                diff = ev.pos() - self.mousePos
                self.mousePos = ev.pos()
                if not self.drawROI:
                    delta = (diff.x()+diff.y())*1
                    self.nearClip += delta
                    self.nearClip = max(0.01, self.nearClip)
                    self.setProjection()
                    self.nearClipSignal.emit(self.nearClip)
        self.update()
Пример #17
0
def r_parallel(snapshot,
               topology,
               groups,
               image_molecules=False,
               mass_weighted=False):
    import openpathsampling
    import numpy

    traj = openpathsampling.engines.Trajectory([snapshot
                                                ]).to_mdtraj(topology=topology)
    group_definitions = [numpy.asarray(gf) for gf in groups]

    atom_masses = numpy.array([aa.element.mass for aa in topology.atoms])
    if mass_weighted:
        masses_in_groups = [
            atom_masses[aa_in_rr] for aa_in_rr in group_definitions
        ]
    else:
        masses_in_groups = [
            np.ones_like(aa_in_rr) for aa_in_rr in group_definitions
        ]

    traj_copy = traj[:]
    com = []
    if image_molecules:
        traj_copy = traj_copy.image_molecules()
    for aas, mms in zip(group_definitions, masses_in_groups):
        com.append(numpy.average(traj_copy.xyz[:, aas, ], axis=1, weights=mms))

    v1 = com[2] - com[0]
    v2 = com[1] - com[0]
    cosine = numpy.inner(v1,
                         v2) / (numpy.linalg.norm(v1) * numpy.linalg.norm(v2))
    if (cosine >= 1):
        angle = 0
    elif (cosine <= -1):
        angle = numpy.pi()
    else:
        angle = numpy.arccos(cosine)

    return numpy.cos(angle) * numpy.linalg.norm(v1)
    def gauss_pdf(self, X, M, S):
        if M.shape[1] == 1:
            DX = X - np.tile(M, X.shape[1])
            E = 0.5 * np.sum(DX * (np.dot(linalg.inv(S), DX)), axis=0)
            E = E + 0.5 * M.shape[0] * np.log(2 * np.pi) + 0.5 * np.log(
                linalg.det(S))
            P = np.exp(-E)
        elif X.shape[1] == 1:
            DX = np.tile(X, M.shape[1]) - M
            E = 0.5 * np.sum(DX * (np.dot(linalg.inv(S), DX)), axis=0)
            E = E + 0.5 * M.shape[0] * np.log(2 * np.pi) + 0.5 * np.log(
                linalg.det(S))
            P = np.exp(-E)
        else:
            DX - X - M
            E = 0.5 * np.dot(DX.T, np.dot(linalg.inv(S), DX))
            E = E + 0.5 * M.shape[0] * np.log(2 * np.pi()) + 0.5 * np.log(
                linalg.det(S))
            P = np.exp(-E)

        return (P[0], E[0])
Пример #19
0
def twobodyephem(X0, t):
    #TWOBODYEPHEM Produce two-body ephemeris table from time and state
    #Using two-body point force, propagate from initial state through given
    #time to produce ephemeris.
    #INPUTS:
    #   X0 - Given state in inertial frame at time t. [meters, meters/seconds]
    #   t  - State will be predicted for each point. [seconds]

    mu = 3.9860044e+14
    #m^3/s^2 Earth gravitational parameter
    we = 2 * np.pi() / 86164
    #rad/sec Earth average rotational rate
    re = 6378137
    #meters, spherical Earth radius
    ag = 0
    #Greenwich angle
    [oe, T, rp, ra, f0] = rv2oe(X0, mu)

    a = oe[1]  #semimajor axis, meters
    e = oe[2]  #eccentricity
    i = oe[3]  #inclination, radians
    Si = np.sin(i)
    Ci = np.cos(i)
    raan = oe[4]  #%ascending node, rad
    Sraan = np.sin(raan)
    Craan = np.cos(raan)
    w = oe[5]  #aop, radians
    Sw = np.sin(w)
    Cw = np.cos(w)
    M0 = oe[6]  #mean anomaly, radians
    Sm0 = np.sin(M0)
    Cm0 = np.cos(M0)

    n = np.sqrt(mu / a**3)  #mean motion
    for i in range(0, np.size(t)):
        Et = keplerseqn(e, n, t[i], M0)
        Mt = Et - (e * np.sin(Et))
        ft = np.arccos((np.cos(Et) - e) / (1 - (e * np.cos(Et))))
        oe[6] = Mt
        Xt[:, i] = oe2rv(oe, ft)
Пример #20
0
def ft_sh_phase_screen(r0, N, delta, L0, l0):
    D = N*delta
    phz_hi = ft_phase_screen(r0, N, delta, L0, l0)
    x,y = np.meshgrid(np.arange(-N/2,N/2)*delta,np.arange(-N/2,N/2)*delta)
    phz_lo = np.zeros(np.size(phz_hi), np.size(phz_hi))
    for p in range(1,3):
        del_f = 1/(3**p*D)
        fx = np.arange(-1,1)*del_f
        fx,fy = np.meshgrid(fx,fx)
        f,th = cart2pol(fx,fy)
        fm = 5.92/10/(2*np.pi)
        f0 = 1/L0
        PSD_phi = 0.023*r0**(-5/3)*np.exp(-(f/fm)**2)/(f**2+f0**2)*(11/6)
        PSD_phi[1,1] = 0
        cn = (np.random.randn(3,3) + 1j*np.random.randn(3,3)).*np.sqrt(PSD_phi) * del_f
        SH = np.zeros(N,N)
        for ii in range(0,9):
            SH = SH + cn(ii)*np.exp(1j*2*np.pi(fx(ii)*x+fy(ii)*y))

        phz_lo = phz_lo + SH
    phz_lo = np.real(phz_lo) - np.mean(np.real(phz_lo))
    return phz_lo, phz_hi
Пример #21
0
    def get_k(self, kmin=1e-3):
        """Get the sampled wavelengths for a spherically symmetric fourier transform
        generated with trapezoidal integration.

        Parameters
        ----------
        kmin : float, optional
            The smallest wavelength to sample.

        Returns
        -------
        k : array of float
            Wavelengths to sample.

        Notes
        -----
        As this function will be used in the hnc solvers, it should be noted that
        setting kmin to be too small can lead to singularity issues."""
        k = np.zeros(self.rbar.shape)
        k[0] = kmin
        dk = np.pi(self.rbar[-1] - self.rbar[0])
        for i in range(1, k.shape[0]):
            k[i] = k[i - 1] + dk
        return k
Пример #22
0
    inplace=True,
    downcast="infer",
)
print(coords_df)

theta = np.arctan2(
    coords_df["headY"][args.frame_number] -
    coords_df["thoraxY"][args.frame_number],
    coords_df["headX"][args.frame_number] -
    coords_df["thoraxX"][args.frame_number],
)
print(f"\nCurrent frame theta: {theta}")

angular_resolution = 100
thetas_to_check = np.linspace(theta,
                              theta + 2 * np.pi(),
                              num=angular_resolution,
                              endpoint=False)
cross_cor = np.zeros((max_shift, angular_resolution))

angular_index = -1
for current_theta in thetas_to_check:
    angular_index += 1
    # Convert coordinates
    cX_array = coords_df["cX"].to_numpy()
    cY_array = coords_df["cY"].to_numpy()

    cX_array = cX_array * np.cos(theta)  # Forward-facing
    cY_array = cY_array * np.cos(theta)  # Side-facing

    max_shift = 1000
Пример #23
0
 def coherence(self):
     return np.sin(2 * np.pi(self.value - self.value.mean()) +
                   np.pi / 2).mean()
Пример #24
0
def reflectance ( file, Temp='None' ):
    from netCDF4 import Dataset
    import numpy as np
    import matplotlib.pyplot as plt
    from mpl_toolkits.basemap import Basemap
    import datetime
    plt.close("all")
    #VIS DEFS
    mVIS=0.6118208
    kVIS=0.001160
    X0=29.0
    C=1.255  # For FEB2013
    tz=-4  #For Manaus
    RadVISUnits='Radiance  [W/(m2 sr um)]'
    RefVISUnits='Reflectance'
    #IR DEFS
    m2=227.3889
    m3=38.8383
    m4=5.2285
    m6=5.5297
    bb2=68.2167
    bb3=29.1287
    bb4=15.6854
    bb6=16.5892
    RadIRUnits='Radiance  [mW/(m2 sr cm-1)]'
    TUnits='Brightness Temperature  [K]'
    C1=1.191066e-5   #  mW/(m2 sr cm-4)
    C2=1.438833      #  K/(cm-1)
    n2=2561.7421
    n3=1522.5182
    n4=937.23449
    n6=749.82589
    a2=-1.4755462
    a3=-4.1556932
    a4=-0.52227011
    a6=-0.16089410
    b2=1.0028656
    b3=1.0142082
    b4=1.0023802
    b6=1.0006896
    g2=-5.8203946e-7
    g3=-8.0255086e-6
    g4=-2.0798856e-6
    g6=-3.9853774e-7
    band=file.split('.')[4]
    procmode='IR'
    if band == 'BAND_01':
        procmode = 'VIS'
        #if time < 09 UTC, do not process night time in Manaus - TBD
    print 'Reading: ', file
    print 'Mode: ', procmode
    fh = Dataset(file, mode='r')
    lons = fh.variables['lon'][:]
    lats = fh.variables['lat'][:]
    datas = fh.variables['data'][:]
    fh.close()
    
    fn=file.split('/')
    fn=fn[len(fn)-1][:-3]+'-'+type+'.png'
    year=fn.split('.')[1]
    julian=fn.split('.')[2]
    hhmm=fn.split('.')[3]
    h=datetime.datetime(int(year), 1, 1) + datetime.timedelta(int(julian) - 1)    
     
    # Get some parameters for the Geostationary map projection    
    f=plt.figure(facecolor='Black')
    f.set_size_inches(7,6,forward='True')
    ax = f.add_axes([0,0,1,1])
    m = Basemap(resolution='h',projection='geos', lon_0=-75,lat_0=0, llcrnrlat=-5.98,llcrnrlon=-63.0,urcrnrlon=-57.0,urcrnrlat=0.0)
    lon, lat = lons, lats
    xi, yi = m(lon, lat)
    
    
    
    
    #Convert 16bit to 10bit
    Raw=datas/32.
    RawUnits='Counts'
    
    # Data processing for VIS channel
    if procmode == 'VIS':
        date=datetime.date(h.year,h.month,h.day)
        time=datetime.time(int(hhmm[:-4]),int(hhmm[2:-2]),int(hhmm[4:]))
        RefPre=kVIS*(Raw-X0)
        RefVIS=RefPre * C
        SZA, SED = sunzen(date, time, tz, lat, lon)
        RefVIS=RefVIS*(SED*SED/np.cos(np.deg2rad(SZA)))
        cs = RefVIS
            
    # Data processing for IR
    if procmode == 'IR':
        RadIR=(Raw - bb2)/m2
        Emission = Planck(Temperature=Temp,wavelength=3.90)
        RefIR = (RadIR - Emission)/((t0 * F0 * mu0 / np.pi())- Emission)
        cs = RefIR
    
    return, cs
Пример #25
0
elif e_norm < 1:
    print("a. It is an elliptical orbit")
    print("e is " + str(e_norm))
elif e_norm == 1:
    print("a. It is a parabolic orbit")
    print("e is " + str(e_norm))
elif e_norm > 1:
    print("a. It is a hyperbolic orbit")
    print("e is " + str(e_norm))

# b
h_norm = lg.norm(h)
k = (h_norm**2) / (r_0_norm * MU) - 1
theta_0 = np.arccos(k / e_norm)  # anomaly at initial condition
if np.dot(r_0, v_0) < 0:
    theta_0 = 2 * np.pi() - theta_0
print("b. Anomaly at t_0 is " + str(theta_0))
E_0 = 2 * math.atan2(
    np.sqrt(1 - e_norm) * np.tan(theta_0 / 2), np.sqrt((1 + e_norm)))
print("Eccentric Anomaly at t_0 is: " + str(E_0))
M_E_0 = E_0 - e_norm * np.sin(E_0)
print("Mean Anomaly at t_0 is: " + str(M_E_0))

# c
a = (r_0_norm * (1 + e_norm * np.cos(theta_0))) / (1 - e_norm * e_norm)
n = np.sqrt(MU / a**3)
t_p = -M_E_0 / n
print("c. t_p is: " + str(t_p))

# d
t = np.linspace(0, 40000, 81)
Пример #26
0
v[0:N] = q[0] / a[0]
Q[0] = q
Y[0] = y
A[0] = a
V[0] = v

#Seccion 3
t = 0
k = 0
while t < Tfin:
    k += 1
    dt = NC * dx / V[k]
    t += dt
    if t <= 150 * 60:
        Q[k + 1,
          0] = 250 + 750 / (np.pi() * (1 - np.cos(np.pi() * t / (60 * 75))))
    else:
        Q[k + 1, 0] = 250

    y = NRalpha(Q[k + 1, 1], B, ss, n, Co, S)
    A[k + 1, 1] = y[0]
    Y[k + 1, 1] = y[1]
    V[k + 1, 1] = Q[k + 1, 1] / A[k + 1, 1]

    for i in range(N - 1):
        Q[k + 1, i + 1] = Q[k + 1, i] - dt / dx * (A[k + 1, i] - A[k, i])

        z = NRalpha(Q[k + 1, i + 1], B, ss, n, Co, S)
        A[k + 1, i + 1] = z[0]
        Y[k + 1, i + 1] = z[1]
        V[k + 1, i + 1] = Q[k + 1, i + 1] / A[k + 1, i + 1]
Пример #27
0
def ir_stick_spectrum_compute(omega,eigenvalues,Iir1modeAbs):
    q = []
    for i in range(0,len(Iir1modeAbs)):
        q.append((Iir1modeAbs[i]*Gamma_IR_Sticks/np.pi())/((omega - eigenvalues[i]-Omega_offset_IR)**2+Gamma_IR_Sticks**2))
    IR_Stick_Spectrum_Omega = sum(q)
    return IR_Stick_Spectrum_Omega
Пример #28
0
import numpy as np
import numpy.linalg as lg

MU = 1  # DU^3/TU^2

r = [-1.2, 1.5, 0]
v = [0, 0, .922]
h = np.cross(r, v)
print("The momentum vector is: " + str(h) + "DU^2/TU")
v_norm = lg.norm(v)
r_norm = lg.norm(r)
eps = (v_norm * v_norm) / 2 - MU / r_norm
print("Total Energy is: " + str(eps))
e = np.cross(v, h) / MU - np.divide(r, r_norm)
print("Eccentricity vector is: " + str(e))
e_norm = lg.norm(e)
h_norm = lg.norm(h)
k = (h_norm * h_norm) / r_norm - 1
theta = np.arccos(k / e_norm)
if np.dot(r, v) < 0:
    theta = 2 * np.pi() - theta
print("Anomaly is: " + str(theta))
print("The magnitude of the eccentricity is: " + str(e_norm))
a = (r_norm * (1 + e_norm * np.cos(theta))) / (1 - e_norm * e_norm)
print("Semi-major axis length: " + str(a))
r_p = a * (1 - e_norm)
print("Periapsis length: " + str(r_p))
r_a = a * (1 + e_norm)
print("Apoapsis length: " + str(r_a))
Пример #29
0
    X = np.concatenate((x, y))
    X += amplitude * np.random.randn(2, X, shape[1])
    return X.T


def get_rose(t, noise_amplitude=0.02):
    k = 5
    r = np.cos(k * t) + 0.25
    x = r * np.cos(t)
    y = r * np.sin(t)
    return add_noise(x, y, noise_amplitude)


def get_hypotrochoid(t, noise_amplitude=0):
    a, b, h = 10.0, 2.0, 4.0
    x = (a - b) * np.cos(t) + h * np.cos((a - b) / b * t)
    y = (a - b) * np.sin(t) + h * np.sin((a - b) / b * t)
    return add_noise(x, y, 0)


if __name__ == '__main__':
    n_samples = 500
    np.random.seed(2)
    t = 2.5 * np.pi(1 + 2 * np.random.rand(1, n_samples))
    x = get_spiral(t)
    connectivity = None
    perform_clustering(x, connectivity, 'No Connectivity')
    connectivity = kneighbors_graph(x, 10, include_self=False)
    perform_clustering(x, connectivity, 'KNN Connectivity')
    plt.show()
Пример #30
0
 def area_to_width(total, max_width):
     return np.sqrt(total / np.pi())
Пример #31
0
import numpy as np

#coverage calculation:
#assume the earth is a sphere (approximation)
#AltitudeFromCentre is distance from object being tracked to centre of earth
#unitary. Just add constants and stir for coverage satisfaction
val = input(
    'enter altitude in earth radii (note, earth radius here is normalised)')
Altitude = float(val)
EarthRadius = 1
AltitudeFromCentre = Altitude + EarthRadius

#theta: angle between vector:centre to object and vector: object to coverage limit
thetaA = np.arcsin(EarthRadius / AltitudeFromCentre)

#DistToLimit: distance to coverage limit from the object (symmetrical through theta in spherical approximation)
DistToLimit = EarthRadius / np.tan(theta)

#PolarAxisToSurface: distance between z axis and a point lying on the coverage limit
PolarAxisToSurface = DistToLimit * np.sin(theta)

#DistToAltitude: distance from the origin of PolarAxisToSurface and the object
DistToAltitude = np.sqrt((PolarAxisToSurface**2) + (DistToLimit**2))

#coverage: the coverage radius that defines the area of coverage (line of sight)
coverage = 2 * np.pi() * theta / 360

print('distance to ')
Пример #32
0
def rv2oe(rv, mu):
    #RV2OE Convert from position and velocity to orbital elements
    #Given a known gravitational parameter for a planet, an artificial satellit
    #e initial state is provided in a nonrotating coordinate system.

    rholder = rv[0:3]
    vholder = rv[3:6]
    del rv
    rv = np.vstack((rholder, vholder))

    #magnitudes
    rmag = np.linalg.norm(rholder)  #m
    vmag = np.linalg.norm(vholder)  #m/s

    #specific angular momentum
    h = np.cross(rholder, vholder)  #m^2/s
    hmag = np.linalg.norm(h)
    #inclination
    i = np.arccos(h[2] / hmag)  #rad
    #raan
    hxy = np.sqrt(h[0]**2 + h[1]**2)
    sinraan = h[0] / hxy
    cosraan = -h[1] / hxy
    raan = np.arctan2(sinraan, cosraan)

    #specific energy per unit mass
    energy = ((vmag**2) / 2) - (mu / rmag)

    #semimajor axis
    a = -mu / (2 * energy)

    #eccentricity
    e = np.sqrt(1 + ((2 * energy * hmag**2) / mu**2))
    evec = np.cross(vholder, (h / mu)) - rholder / rmag

    #semiminor axis
    b = a * np.sqrt(1 - e**2)

    #semi-latus rectum
    p = a * (1 - e**2)

    #true anomaly
    if np.dot(rholder, vholder) < 0:
        f = (2 * np.pi() - np.arccos(np.dot(evec, rholder) / (e * rmag)))
    else:
        f = np.arccos(np.dot(evec, rholder) / (e * rmag))

    #perifocus
    sinwf = rholder[2] / (rmag * np.sin(i))
    coswf = ((rholder[0] / rmag) * np.cos(raan)) + (
        (rholder[1] / rmag) * sin(raan))
    wf = np.arctan2(sinwf, coswf)
    w = wf - f

    #eccentric anomaly
    cosE0 = ((rmag / a) * np.cos(f)) + e
    sinE0 = ((rmag / b) * np.sin(f))
    E0 = np.arctan2(sinE0, cosE0)

    #Mean Anomaly
    M0 = E0 - e * np.sin(E0)

    #Period
    T = 2 * np.pi() * np.sqrt(a**3 / mu)
    rp = a * (1 - e)
    ra = a * (1 + e)

    oe = np.array([a, e, i, raan, w, M0])
    return oe, T, rp, ra, f
def fit_tooth_data(data_fname, model_fname='equalsize_jul2015a.h5', **kwargs):


    print 'importing isotope data...'

    data_isomap, isomap_shape, isomap_data_x_ct = load_iso_data(data_fname)

    print 'loading tooth model ...'
    tooth_model = ToothModel(model_fname)

    fit_kwargs = kwargs.copy()

    # M1-M2 conversion parameters
    m2_m1_params = np.array([67.974, 0.003352, -25.414, 41., 21.820, .007889, 29.118, 35.]) # 'synch86', outlier, 100k
    #m2_m1_params = np.array([78.940, 0.003379, -49.708, 41., 21.820, .007889, 29.118, 35.]) # 'synch86', outliers, 100k
    m1_m2_params = np.array([21.820, .007889, 29.118, 35., 67.974, 0.003352, -25.414, 41.]) # 'synch86', outlier, 100k
    #m1_m2_params = np.array([21.820, .007889, 29.118, 35., 78.940, 0.003379, -49.708, 41.]) # 'synch86', outliers, 100k

    # Real climate data
    #month_d180 = np.array([-1.95, -1.92, -2.94, -3.44, -2.22, -1.10, -0.67, -1.71, -0.81, -1.47, -2.31, -3.19]) # Dar Es Salaam
    #month_d180 = np.array([-0.21, 0.30, -0.04, 0.25, -0.75, -0.19, -3.16, -4.53, -0.95, 0.29, -1.26, -1.73]) # Addis Ababa
    #month_d180 = np.array([-1.39, -0.35, -2.42, -3.25, -3.08, -1.44, -0.98, -1.88, -1.33, -3.10, -3.80, -1.63]) # Entebbe, Uganda
    #month_d180 = np.array([-6.31, -7.09, -4.87, -3.33, -1.83, -1.22, -1.08, -0.47, -0.17, -0.48, -2.92, -5.90]) # Harare, Zimbabwe
    #month_d180 = np.array([-2.98, -2.20, -4.74, -5.94, -2.64, -3.80, -0.25, -1.80, -1.25, -4.15, -5.80, -5.42]) # Kinshasa, DRC
    #month_d180 = np.array([-1.58, -1.54, -1.81, -3.08, -3.40, -3.69, -3.38, -3.78, -2.46, -2.19, -2.12, -1.79]) # Cape Town
    #month_d180 = np.array([-4.31, -3.50, -4.14, -4.68, -4.87, -5.11, -4.77, -4.80, -4.71, -4.50, -4.53, -4.77]) # Marion Island
    #month_d180 = np.array([0.00, -2.40, -1.75, -3.70, -3.90, -6.20, -7.75, -8.10, -6.25, -3.30, -4.75, -8.95, -2.10, -0.40, -4.55, -3.25, -5.75, -3.70, -8.60, -7.10, -8.50, -5.30, -4.55, -3.10, -2.75	-4.60, -2.00, -3.10, -5.25, -6.10]) # Hong Kong
    #month_d180 = np.array([-2.75, -5.35, -2.70, -1.60, -6.30, -7.25, -9.00, -8.10, -9.50, -5.30, -5.75, -4.00]) # Liuzhou
    #month_d180 = np.array([-5.30, -4.73, -7.44, -4.38, -4.39, -7.07, -9.76, -3.99, -3.95, -5.81, -8.98, -9.89, -8.62, -8.88, -8.25, -8.21, -9.74, -6.83, -6.69, -6.38, -10.33, -7.95, -5.72, -10.52, -10.74, -7.48, -9.30, -8.50, -12.66, -10.52, -10.82, -6.01, -8.34, -5.51, -7.03, -5.75, -8.14, -6.85, -4.82, -7.31, -8.79, -4.77, -6.14, -2.96, -2.31, -5.13, -9.31, -8.88, -9.22, -9.08, -7.51, -7.72, -10.29, -10.38, -9.69, -8.64, -10.66, -7.85, -6.94]) # Mulu, Borneo
    #week_d180 = np.array([-19.40, -19.4, -19.4, -19.4, -15.9, -15.9, -15.9, -23.1, -23.1, -23.1, -23.1, -23.1, -23.1, -23.1, -16.5, -16.5, -8.8, -8.8, -10.6, -10.6, -2.5, -9.3, -6.7, -8.2, -1.6, -6, -7, -4.4, -8.8, -6.5, -6.1, -6.1, -6.1, -0.6, 1.7, -4.5, -4.5, -4.5, -12.4, -12.4, -9.7, -12.2, -12.2, -12.2, -15.1, -15.1, -11, -11, -11, -30.5, -30.5, -30.5])  # North Platte Nebraska
    month_d180 = np.array([-18.50, -17.93, -12.16, -12.08, -6.88, -7.00, -7.49, -5.60, -8.87, -13.91, -14.20, -23.70]) # North Platte, Nebraska

    # Synthetic data testing
    daily_d18O_180 = 10.*np.sin((2*np.pi()/180.)*(np.arange(550.)))-11.
    daily_d18O_090 = 10.*np.sin((2*np.pi()/90.)*(np.arange(550.)))-11.
    daily_d18O_045 = 10.*np.sin((2*np.pi()/45.)*(np.arange(550.)))-11.

    # Conversion monthly precipitation isotope record into daily record
    year_iso_days = np.arange((24))*(730./(24.)) + 100.
    m1_iso_days = tooth_timing_convert(year_iso_days, *m2_m1_params)
    m1_iso_days -= (0. + m1_iso_days[0])
    w_iso_hist = np.ones(400)
    month_d180 = np.concatenate((month_d180, month_d180))
    month_d180 = np.concatenate((month_d180, month_d180))
    for k,d in enumerate(m1_iso_days):
        d = int(d)
        w_iso_hist[d:] = month_d180[k+11]

    water_spl, blood_spl, days_spl, i33_spl, i50_spl, i66_spl = spline_input_signal(1)
    water_spl = water_spl[50:]
    blood_spl = blood_spl[50:]
    days_spl = days_spl[50:]
    i33_spl = i33_spl[50:]
    i50_spl = i50_spl[50:]
    i66_spl = i66_spl[50:]

    m1_days_spl = tooth_timing_convert(days_spl, *m2_m1_params)

    water_spl_tmp = np.ones(days_spl.size)
    blood_spl_tmp = np.ones(days_spl.size)
    i33_spl_tmp = np.ones(days_spl.size)
    i50_spl_tmp = np.ones(days_spl.size)
    i66_spl_tmp = np.ones(days_spl.size)

    print i33_spl.size, i33_spl_tmp.size, water_spl_tmp.size, m1_days_spl.size


    for k,d in enumerate(m1_days_spl):
        d = int(d)
        water_spl_tmp[d:] = water_spl[k]
        blood_spl_tmp[d:] = blood_spl[k]
        i33_spl_tmp[d:] = i33_spl[k]
        i50_spl_tmp[d:] = i50_spl[k]
        i66_spl_tmp[d:] = i66_spl[k]

    water_spl = water_spl_tmp
    blood_spl = blood_spl_tmp
    i33_spl = i33_spl_tmp
    i50_spl = i50_spl_tmp
    i66_spl = i66_spl_tmp

    # Full model loading and isomap
    #fit_kwargs['tooth_model'] = tooth_model
    #model_isomap_full = water_hist_likelihood_fl(w_iso_hist, **fit_kwargs)
    #model_isomap_full = np.array(model_isomap_full)
    #mu_fl = np.median(model_isomap_full, axis=0)

    # Small tooth model generation
    tooth_model_sm = tooth_model.downsample_model((isomap_shape[0]+5, isomap_shape[1]+5), 1)

    # Set keyword arguments to be used in fitting procedure

    fit_kwargs['tooth_model'] = tooth_model_sm
    fit_kwargs['data_isomap'] = data_isomap
    fit_kwargs['isomap_shape'] = isomap_shape
    fit_kwargs['isomap_data_x_ct'] = isomap_data_x_ct

    # Generate blood d18O and tooth d18O isomap from drinking water history, with score compared to measured data
    score_sm_w, model_isomap_sm_w = water_hist_likelihood(water_spl, **fit_kwargs)
    score_i33, model_isomap_i33 = water_hist_likelihood(i33_spl, **fit_kwargs)
    score_i50, model_isomap_i50 = water_hist_likelihood(i50_spl, **fit_kwargs)
    score_i66, model_isomap_i66 = water_hist_likelihood(i66_spl, **fit_kwargs)
    mu_sm_w = np.median(model_isomap_sm_w, axis=2)
    sigma_sm_w = np.std(model_isomap_sm_w, axis=2)
    sigma_sm_w = np.sqrt(sigma_sm_w**2. + 0.15**2 + 0.05**2)
    #resid_img = (mu - data_isomap) / sigma

    # Generate tooth isomap from blood measurements
    forward_metabolic_kw = kwargs.get('metabolic_kw', {})
    forward_phosphate_eq_b_PO4 = PO4_dissoln_reprecip(3., 34.5, .3, blood_spl, **kwargs)
    forward_blood_model = gen_isomaps(isomap_shape, isomap_data_x_ct, tooth_model_sm, forward_phosphate_eq_b_PO4) # This takes the blood history from 962 scaled to the M1 without also downscaling the blood turnover

    plt.plot(m1_days_spl, water_spl, 'b', lw=2)
    plt.plot(m1_days_spl, blood_spl, 'r', lw=2)
    plt.plot(m1_days_spl, forward_phosphate_eq_b_PO4, 'g', lw=2)
    plt.show()

    m_mu_sm = np.ma.masked_array(mu_sm_w, np.isnan(mu_sm_w))
    mu_sm_r = np.mean(m_mu_sm, axis=1)
    small_sample = np.ones(int(mu_sm_r.size/2))
    for k,d in enumerate(small_sample):
        small_sample[k] = (mu_sm_r[(k*2)]+mu_sm_r[(k*2)+1])/2
    mu_sm_r = small_sample
    mu_sm_r.shape = (mu_sm_r.size, 1)
    print mu_sm_r.shape

    # Save generated isomap as CSV file
    #save_tooth = mu_sm.T
    #save_tooth[np.isnan(save_tooth)] = 0.
    #np.savetxt('m2_predicted_a_hist_half=3.csv', np.flipud(save_tooth), delimiter=',', fmt='%.2f')

    mu_sm_w[mu_sm_w==0.] = np.nan

    print score_sm_w
    textstr = '%.1f' % score_sm_w

    fig = plt.figure(figsize=(10,4), dpi=100)
    #ax1 = fig.add_subplot(3,1,1)
    #cimg1 = ax1.imshow(mu_fl.T, aspect='auto', interpolation='nearest', origin='lower', vmin=16., vmax=17., cmap='bwr')
    #cax1 = fig.colorbar(cimg1)

    ax1 = fig.add_subplot(6,1,1)
    ax1text = 'forward model from water data 100% ice'
    ax1.text(19, 3, ax1text, fontsize=8)
    cimg1 = ax1.imshow(mu_sm_w.T, aspect='equal', interpolation='nearest', origin='lower', vmin=9., vmax=15., cmap='bwr')
    cax1 = fig.colorbar(cimg1)

    ax2 = fig.add_subplot(6,1,2)
    ax2text = 'data'
    ax2.text(19, 3, ax2text, fontsize=8)
    cimg2 = ax2.imshow(data_isomap.T, aspect='equal', interpolation='nearest', origin='lower', vmin=9., vmax=15., cmap='bwr')
    cax2 = fig.colorbar(cimg2)

    ax3 = fig.add_subplot(6,1,3)
    ax3text = 'forward model from blood data'
    ax3.text(19, 3, ax3text, fontsize=8)
    cimg3 = ax3.imshow(np.mean(forward_blood_model, axis=2).T, aspect='equal', interpolation='nearest', origin='lower', vmin=9., vmax=15., cmap='bwr')
    cax3 = fig.colorbar(cimg3)

    ax4 = fig.add_subplot(6,1,4)
    ax4text = 'forward model 33% ice'
    ax4.text(19, 3, ax4text, fontsize=8)
    cimg4 = ax4.imshow(np.mean(model_isomap_i33, axis=2).T, aspect='equal', interpolation='nearest', origin='lower', vmin=9., vmax=15., cmap='bwr')
    cax4 = fig.colorbar(cimg4)

    ax5 = fig.add_subplot(6,1,5)
    ax5text = 'forward model 50% ice'
    ax5.text(19, 3, ax5text, fontsize=8)
    cimg5 = ax5.imshow(np.mean(model_isomap_i50, axis=2).T, aspect='equal', interpolation='nearest', origin='lower', vmin=9., vmax=15., cmap='bwr')
    cax5 = fig.colorbar(cimg5)

    ax6 = fig.add_subplot(6,1,6)
    ax6text = 'forward model 66% ice'
    ax6.text(19, 3, ax6text, fontsize=8)
    cimg6 = ax6.imshow(np.mean(model_isomap_i66, axis=2).T, aspect='equal', interpolation='nearest', origin='lower', vmin=9., vmax=15., cmap='bwr')
    cax6 = fig.colorbar(cimg6)

    t_save = time()
    fig.savefig('spline_water_snow_2015_11_14_18p6_w_ice_blood_w_PO4.svg'.format(t_save), dpi=300)
    plt.show()
    '''
Пример #34
0
def Nline(x):
    #Derivative of normal cumulative distribution function
    NDer = (1 / math.np.sqrt(2 * np.pi())) * np.exp(-(x ^ 2) / 2)
    return NDer