Ejemplo n.º 1
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
Ejemplo n.º 2
0
    def __calc_laplacian(self):
        numDims                 = self.polygons.shape[0];
        numPoints               = self.points.shape[1];
        numPolygons             = self.polygons.shape[1];

        sparseMatrix            = csr_matrix((numPoints, numPoints));

        for i in range(0, numDims):
            i1                  = (i + 0)%3;
            i2                  = (i + 1)%3;
            i3                  = (i + 2)%3;

            distP2P1            = self.points[:, self.polygons[i2, :]] - self.points[:, self.polygons[i1, :]];
            distP3P1            = self.points[:, self.polygons[i3, :]] - self.points[:, self.polygons[i1, :]];

            distP2P1            = distP2P1 / repmat(sqrt((distP2P1**2).sum(0)), 3, 1);
            distP3P1            = distP3P1 / repmat(sqrt((distP3P1**2).sum(0)), 3, 1);

            angles              = arccos((distP2P1 * distP3P1).sum(0));

            iterData1           = csr_matrix((1/tan(angles), 
                                                    (self.polygons[i2,:], 
                                                     self.polygons[i3,:])), 
                                                    shape=(numPoints, numPoints));

            iterData2           = csr_matrix((1/tan(angles), (self.polygons[i3,:], self.polygons[i2,:])), shape=(numPoints, numPoints));

            sparseMatrix        = sparseMatrix + iterData1 + iterData2;

        diagonal                = sparseMatrix.sum(0);
        diagonalSparse          = spdiags(diagonal, 0, numPoints, numPoints);
        self.__laplacian        = diagonalSparse - sparseMatrix;
Ejemplo n.º 3
0
 def azimuth(self, date):
     dec = self.declination(date)
     ha = self.hour_angle(date)
     az = sp.arcsin(sp.cos(dec) * sp.sin(ha) / sp.cos(self.elevation(date)))
     if (sp.cos(ha) >= (sp.tan(dec) / sp.tan(self.lat))):
         return az
     else:
         return (sp.pi - az)
Ejemplo n.º 4
0
def Kaklamanos_Rrup_prime(Rx, widths, dips, depths_to_top):
    """
    Calculation for the in-plane rupture distance based on 3 zones
    (Fig. 4 Kaklamanos et al. (2011)


    ~-----------Zone A--------->|<--Zone B-->|<--Zone C--~
    ____________________________|____________|____________
          ^     |              /            /   #####   ^
          |     |             /            /           /
          |     |            /            /   Ground _/
          |     |           /            /    Surface
          |     |          /            /
          |     |         /            /
          |     |        /            /
        depth   |       /            /
          |     |      /            /
          |     |     /            /
          |     |    /            /
          |     |   /            /
          |     |  /            /
          |     | /            /
       ___._____|/____        /
                / dip        /
               / #          /
              /   #        /
             /^    #      /
               \    #    /
             width   #  / 90 degrees
                 \    #/
                  \   /
                   . /
                    /
    """

    d = dips * pi / 180  # define dips in terms of radians
    Ztor = depths_to_top
    W = widths

    Rrup_p = zeros(Rx.shape)

    # Zone A
    Rrup_p = where(Rx < Ztor * tan(d),
                   sqrt(Rx ** 2 + Ztor ** 2),
                   Rrup_p)

    # Zone B
    Rrup_p = where((Rx >= Ztor * tan(d)) & (Rx <= Ztor * tan(d) + W * sec(d)),
                   Rx * sin(d) + Ztor * cos(d),
                   Rrup_p)

    # Zone C
    Rrup_p = where(Rx > Ztor * tan(d) + W * sec(d),
                   sqrt((Rx - W * cos(d)) ** 2 + (Ztor + W * sin(d)) ** 2),
                   Rrup_p)

    return Rrup_p
Ejemplo n.º 5
0
def det(origin, ang1=120., ang2=150., offset=1e-3, angle=(0., 0., 0.)):

    norm = TRIPPy.Vecx((0., 0., 1.))
    meri = TRIPPy.Vecx((0., 1., 0.))
    area = [
        2 * offset * scipy.tan(ang1 * scipy.pi / 360.),
        2 * offset * scipy.tan(ang2 * scipy.pi / 360.)
    ]
    return TRIPPy.surface.Rect((0., 0., -offset), origin, area, angle=angle)
Ejemplo n.º 6
0
    def pixelate(self, sagi, meri):
        """ convert surface into number of rectangular surfaces"""
        ins = old_div(float((sagi - 1)), sagi)
        inm = old_div(float((meri - 1)), meri)
        stemp = old_div(self.norm.s, sagi)
        mtemp = old_div(self.meri.s, meri)

        z, theta = scipy.meshgrid(
            scipy.linspace(-self.norm.s * ins, self.norm.s * ins, sagi),
            scipy.linspace(-self.meri.s * inm, self.meri.s * inm, meri))

        vecin = geometry.Vecr(
            (self.sagi.s * scipy.ones(theta.shape),
             theta + old_div(scipy.pi, 2),
             scipy.zeros(theta.shape)))  #this produces an artificial
        # meri vector, which is in the 'y_hat' direction in the space of the cylinder
        # This is a definite patch over the larger problem, where norm is not normal
        # to the cylinder surface, but is instead the axis of rotation.  This was
        # done to match the Vecr input, which works better with norm in the z direction

        pt1 = geometry.Point(
            geometry.Vecr((self.sagi.s * scipy.ones(theta.shape), theta, z)),
            self)

        pt1.redefine(self._origin)

        vecin = vecin.split()

        x_hat = self + pt1  #creates a vector which includes all the centers of the subsurface

        out = []
        #this for loop makes me cringe super hard
        for i in range(meri):
            try:
                temp = []
                for j in range(sagi):
                    inp = self.rot(vecin[i][j])
                    temp += [
                        Rect(geometry.Vecx(x_hat.x()[:, i, j]),
                             self._origin,
                             [2 * stemp, 2 * scipy.tan(mtemp) * self.sagi.s],
                             vec=[inp, self.sagi.copy()],
                             flag=self.flag)
                    ]
                out += [temp]
            except IndexError:
                inp = self.rot(vecin[i])
                out += [
                    Rect(geometry.Vecx(x_hat.x()[:, i]),
                         self._origin,
                         [2 * stemp, 2 * scipy.tan(mtemp) * self.sagi.s],
                         vec=[inp, self.sagi.copy()],
                         flag=self.flag)
                ]

        return out
Ejemplo n.º 7
0
    def pixelate(self, sagi, meri):
        """ convert surface into number of rectangular surfaces"""
        ins = float((sagi - 1))/sagi
        inm = float((meri - 1))/meri
        stemp = self.norm.s/sagi
        mtemp = self.meri.s/meri

        z,theta = scipy.meshgrid(scipy.linspace(-self.norm.s*ins,
                                                self.norm.s*ins,
                                                sagi),
                                 scipy.linspace(-self.meri.s*inm,
                                                self.meri.s*inm,
                                                meri))

        vecin = geometry.Vecr((self.sagi.s*scipy.ones(theta.shape),
                               theta+scipy.pi/2,
                               scipy.zeros(theta.shape))) #this produces an artificial
        # meri vector, which is in the 'y_hat' direction in the space of the cylinder
        # This is a definite patch over the larger problem, where norm is not normal
        # to the cylinder surface, but is instead the axis of rotation.  This was
        # done to match the Vecr input, which works better with norm in the z direction
               
        pt1 = geometry.Point(geometry.Vecr((self.sagi.s*scipy.ones(theta.shape),
                                            theta,
                                            z)),
                             self)

        pt1.redefine(self._origin)
                
        vecin = vecin.split()

        x_hat = self + pt1 #creates a vector which includes all the centers of the subsurface

        out = []
        #this for loop makes me cringe super hard
        for i in xrange(meri):
            try:
                temp = []
                for j in xrange(sagi):
                    inp = self.rot(vecin[i][j])
                    temp += [Rect(geometry.Vecx(x_hat.x()[:,i,j]),
                                  self._origin,
                                  [2*stemp,2*scipy.tan(mtemp)*self.sagi.s],
                                  vec=[inp, self.sagi.copy()],
                                  flag=self.flag)]
                out += [temp]
            except IndexError:
                inp = self.rot(vecin[i])
                out += [Rect(geometry.Vecx(x_hat.x()[:,i]),
                             self._origin,
                             [2*stemp,2*scipy.tan(mtemp)*self.sagi.s],
                             vec=[inp, self.sagi.copy()],
                             flag=self.flag)]


        return out
Ejemplo n.º 8
0
def fov_vectors(fov_h, fov_v):
    h_diff = scipy.tan(fov_h / 2.0)
    v_diff = scipy.tan(fov_v / 2.0)

    return [
        scipy.array([1, h_diff, v_diff]),
        scipy.array([1, h_diff, -v_diff]),
        scipy.array([1, -h_diff, v_diff]),
        scipy.array([1, -h_diff, -v_diff]),
    ]
Ejemplo n.º 9
0
def fov_vectors(fov_h, fov_v):
    h_diff = scipy.tan(fov_h / 2.0)
    v_diff = scipy.tan(fov_v / 2.0)

    return [
        scipy.array([1, h_diff, v_diff]),
        scipy.array([1, h_diff, -v_diff]),
        scipy.array([1, -h_diff, v_diff]),
        scipy.array([1, -h_diff, -v_diff])
    ]
        def f(_lamba):
            # mi1 = sqrt(self.delta[0] / self.delta[1]) * _lamba
            # mi2 = sqrt(self.delta[0] / self.delta[2]) * _lamba

            mi1, mi2 = self._calc_mi(_lamba)

            result = -tan(_lamba) - (
                self.Delta1 * tan(mi1) + self.Delta2 * tan(mi2)) / (
                    1.0 - (self.Delta2 / self.Delta1) * tan(mi1) * tan(mi2))
            return result
Ejemplo n.º 11
0
def Kaklamanos_Rrup_prime(Rx, widths, dips, depths_to_top):
    """
    Calculation for the in-plane rupture distance based on 3 zones
    (Fig. 4 Kaklamanos et al. (2011)


    ~-----------Zone A--------->|<--Zone B-->|<--Zone C--~
    ____________________________|____________|____________
          ^     |              /            /   #####   ^
          |     |             /            /           /
          |     |            /            /   Ground _/
          |     |           /            /    Surface
          |     |          /            /
          |     |         /            /
          |     |        /            /
        depth   |       /            /
          |     |      /            /
          |     |     /            /
          |     |    /            /
          |     |   /            /
          |     |  /            /
          |     | /            /
       ___._____|/____        /
                / dip        /
               / #          /
              /   #        /
             /^    #      /
               \    #    /
             width   #  / 90 degrees
                 \    #/
                  \   /
                   . /
                    /
    """

    d = dips * pi / 180  # define dips in terms of radians
    Ztor = depths_to_top
    W = widths

    Rrup_p = zeros(Rx.shape)

    # Zone A
    Rrup_p = where(Rx < Ztor * tan(d), sqrt(Rx**2 + Ztor**2), Rrup_p)

    # Zone B
    Rrup_p = where((Rx >= Ztor * tan(d)) & (Rx <= Ztor * tan(d) + W * sec(d)),
                   Rx * sin(d) + Ztor * cos(d), Rrup_p)

    # Zone C
    Rrup_p = where(Rx > Ztor * tan(d) + W * sec(d),
                   sqrt((Rx - W * cos(d))**2 + (Ztor + W * sin(d))**2), Rrup_p)

    return Rrup_p
def draw_hough_line(array, theta, r, value=1):
    """Replaces all the pixels in ``array`` that fall under a Hough line with parameters ``(theta, r) with ``value``."""
    h, w = array.shape    
    
    x_bounds = [r/sp.cos(theta) - (h - 1)*sp.tan(theta), r/sp.cos(theta)]
    x_min = max(min(x_bounds), 0)
    x_max = min(max(x_bounds), w - 1)
    
    xs = sp.array([x_min, x_max])
    ys = -xs/sp.tan(theta) + r/sp.sin(theta)
  
    line_indices = skimage.draw.line(int(ys[0]), int(x_min), int(ys[1]), int(x_max))
    array[line_indices] = value
def draw_hough_line(array, theta, r, value=1):
    """Replaces all the pixels in ``array`` that fall under a Hough line with parameters ``(theta, r) with ``value``."""
    h, w = array.shape

    x_bounds = [r / sp.cos(theta) - (h - 1) * sp.tan(theta), r / sp.cos(theta)]
    x_min = max(min(x_bounds), 0)
    x_max = min(max(x_bounds), w - 1)

    xs = sp.array([x_min, x_max])
    ys = -xs / sp.tan(theta) + r / sp.sin(theta)

    line_indices = skimage.draw.line(int(ys[0]), int(x_min), int(ys[1]),
                                     int(x_max))
    array[line_indices] = value
Ejemplo n.º 14
0
def HybOffDiagFiniteW(GammaL,GammaR,Delta,P,W,iw):
	''' off-diagonal part of the finite-bandwidth sc lead hybridization 
	PhiS angle keeps the hybridization real '''
	Phi = P*sp.pi
	PhiS = sp.arctan((GammaL-GammaR)/(GammaL+GammaR+1e-12)*sp.tan(Phi/2.0))
	return Delta*sp.exp(1.0j*PhiS)*\
	(GammaL*sp.exp(-1.0j*Phi/2.0)+GammaR*sp.exp(1.0j*Phi/2.0))*IntFiniteBW(Delta,W,iw)
Ejemplo n.º 15
0
	def select(self, alpha=None, beta=None):
		"""Roullet wheel selection"""
		scores = [c.score for c in self.chromossomes]

		if beta is not None:
			if beta > max(scores):
				raise ValueError("Negative score increase beta?")
			for i in xrange(len(scores)):
				scores[i] -= beta

		if alpha is not None:
			start = max(scores) - tan(alpha) * len(scores)
			if start < 0:
				raise ValueError("Negative score decrease alpha?")
			for i in xrange(len(scores)):
				scores[i] = start + alpha * i

		n_scores = scores / sum(scores)

		number = random.random()

		acc = 0
		for idx, value in enumerate(n_scores):
			acc += value
			if acc > number:
				return self.chromossomes[idx]
Ejemplo n.º 16
0
def f_Refl_Thick_Film():
    a = P4Rm()

    wl = a.AllDataDict['wavelength']
    t = a.AllDataDict['damaged_depth']
    N = a.AllDataDict['number_slices']
    t_film = a.AllDataDict['film_thick']

    G = a.ParamDict['G']
    thB_S = a.ParamDict['thB_S']
    resol = a.ParamDict['resol']
    phi = a.ConstDict['phi']
    t_l = a.ParamDict['t_l']
    z = a.ParamDict['z']
    FH = a.ParamDict['FH']
    FmH = a.ParamDict['FmH']
    F0 = a.ParamDict['F0']
    sp = a.ParamDict['sp']
    dwp = a.ParamDict['dwp']
    th = a.ParamDict['th']
    spline_DW = a.splinenumber[1]
    spline_strain = a.splinenumber[0]
    param = a.ParamDict['par']
    delta_t = t_film - t

    strain = f_strain(z, param[:len(sp):], t, spline_strain)
    DW = f_DW(z, param[len(sp):len(sp) + len(dwp):], t, spline_DW)
    thB = thB_S - strain * tan(thB_S)  # angle de Bragg dans chaque lamelle

    eta = 0
    res = 0

    g0 = sin(thB[0] - phi)  # gamma 0
    gH = -sin(thB[0] + phi)  # gamma H
    b = g0 / gH
    T = pi * G * ((FH[0] * FmH[0])**0.5) * delta_t / (wl * (abs(g0 * gH)**0.5))
    eta = (-b * (th - thB[0]) * sin(2 * thB_S) - 0.5 * G * F0[0] *
           (1 - b)) / ((abs(b)**0.5) * G * (FH[0] * FmH[0])**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
    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 convolve(abs(res)**2, resol, mode='same')
Ejemplo n.º 17
0
def RV_model(THETA, time, kplanets):
    modelo = 0.0
    #sp.seterr(all=='raise')
    if kplanets == 0:
        return 0.0
    for i in range(kplanets):
        P, As, Ac, S, C = THETA[5 * i:5 * (i + 1)]
        #P, As, Ac, ecc, w = THETA[5*i:5*(i+1)]
        A = As**2 + Ac**2
        ecc = S**2 + C**2

        phase = sp.arccos(Ac / (A**0.5))
        w = sp.arccos(C / (ecc**0.5))  # longitude of periastron

        ### test
        if S < 0:
            w = 2 * sp.pi - sp.arccos(C / (ecc**0.5))
        if As < 0:
            phase = 2 * sp.pi - sp.arccos(Ac / (A**0.5))

        ###
        #  sp.seterr(all='raise') # DEL
        per = sp.exp(P)
        freq = 2. * sp.pi / per
        M = freq * time + phase  # mean anomaly
        E = sp.array([MarkleyKESolver().getE(m, ecc)
                      for m in M])  # eccentric anomaly
        f = (sp.arctan(
            ((1. + ecc)**0.5 / (1. - ecc)**0.5) * sp.tan(E / 2.)) * 2.
             )  # true anomaly
        modelo += A * (sp.cos(f + w) + ecc * sp.cos(w))
    return modelo
Ejemplo n.º 18
0
def pos2Ray(pos, tokamak, angle=None, eps=1e-6):
    r"""Take in GENIE pos vectors and convert it into TRIPPy rays
    
    Args:
        pos: 4 element tuple or 4x scipy-array
            Each pos is assembled into points of (R1,Z1,RT,phi)

        tokamak: 
            Tokamak object in which the pos vectors are defined.
            
    Returns:
        Ray: Ray object or typle of ray objects.
        
    """

    r1 = scipy.array(pos[0])
    z1 = scipy.array(pos[1])
    rt = scipy.array(pos[2])
    phi = scipy.array(pos[3])

    zt = z1 - scipy.tan(phi)*scipy.sqrt(r1**2 - rt**2)
    angle2  = scipy.arccos(rt/r1)

    if angle is None:
        angle = scipy.zeros(r1.shape)

    pt1 = geometry.Point((r1,angle,z1),tokamak)
    pt2 = geometry.Point((rt,angle+angle2,zt),tokamak)

    output = Ray(pt1,pt2)
    output.norm.s[-1] = eps
    tokamak.trace(output)
    return output
Ejemplo n.º 19
0
def Jensen_Wake_Model(x):
    nTurbs = (len(x) - 2) / 2
    xHAWT = x[0:nTurbs]
    yHAWT = x[nTurbs:nTurbs * 2]
    zTall = x[len(x) - 2]
    zShort = x[len(x) - 1]

    nTall = nTurbs / 2
    zHAWT = np.zeros(nTurbs)
    zHAWT[0:nTall] = zTall
    zHAWT[nTall:nTurbs] = zShort
    theta = 0.1
    alpha = sp.tan(theta)
    rho = 1.1716
    a = 1. / 3.
    Cp = 4. * a * (1 - a) ** 2.
    # nTurbines = len(xin)/2.
    r_0 = np.ones(nTurbs) * 63.2
    U_velocity = 8.
    U_direction = pi / 3.5
    "Make the graphic for the turbines and wakes"
    jensen_plot(x, y, r_0, alpha, U_direction_radians)

    "Calculate power from each turbine"
    return jensen_power(xHAWT, yHAWT, zHAWT, r_0, alpha, a, U_velocity, rho, Cp, U_direction)
Ejemplo n.º 20
0
def cotan_alpha_beta_angle(triangles, vertices):
    # cotan of all angle = (tan(a))^-1
    ctn_ab_angles = scipy.tan(edge_alpha_angle(triangles, vertices))
    ctn_ab_angles.data **= -1
    # matrix = cot(a) + cot(b) = cot(a_ij) + cot(b_ji)
    ctn_ab_angles = ctn_ab_angles + ctn_ab_angles.T
    return ctn_ab_angles
Ejemplo n.º 21
0
 def __init__(self, yaml):
     self._tf_listener = tf.TransformListener()
     self._grid = SearchGrid(10, 10, 2.0, 2.0)
     camera = yaml.sensors[0].camera
     self._fov_h = camera.horizontal_fov
     self._fov_v = 2.0 * scipy.arctan(scipy.tan(self._fov_h / 2.0) * (camera.image_height / camera.image_width))
     self._fov_vectors = fov_vectors(self._fov_h, self._fov_v)
Ejemplo n.º 22
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
Ejemplo n.º 23
0
def Jensen_Wake_Model(x):
    nTurbs = (len(x) - 2) / 2
    xHAWT = x[0:nTurbs]
    yHAWT = x[nTurbs:nTurbs * 2]
    zTall = x[len(x) - 2]
    zShort = x[len(x) - 1]

    nTall = nTurbs / 2
    zHAWT = np.zeros(nTurbs)
    zHAWT[0:nTall] = zTall
    zHAWT[nTall:nTurbs] = zShort
    theta = 0.1
    alpha = sp.tan(theta)
    rho = 1.1716
    a = 1. / 3.
    Cp = 4. * a * (1 - a)**2.
    # nTurbines = len(xin)/2.
    r_0 = np.ones(nTurbs) * 63.2
    U_velocity = 8.
    U_direction = pi / 3.5
    "Make the graphic for the turbines and wakes"
    jensen_plot(x, y, r_0, alpha, U_direction_radians)

    "Calculate power from each turbine"
    return jensen_power(xHAWT, yHAWT, zHAWT, r_0, alpha, a, U_velocity, rho,
                        Cp, U_direction)
Ejemplo n.º 24
0
def cotan_alpha_beta_angle(triangles, vertices):
    # cotan of all angle = (tan(a))^-1
    ctn_ab_angles = scipy.tan(edge_alpha_angle(triangles, vertices))
    ctn_ab_angles.data **= -1
    # matrix = cot(a) + cot(b) = cot(a_ij) + cot(b_ji)
    ctn_ab_angles = ctn_ab_angles + ctn_ab_angles.T
    return ctn_ab_angles
Ejemplo n.º 25
0
    def integrand(z):
        """
        Determine the integrand for calculating the apparent elevation angle.
        :param z: The altitude (km).
        :return: The integrand.
        """

        # Effective radius of the Earth (km)
        re = 6378.137

        # Standard values
        a = 0.000315
        b = 0.1361

        # Refractive index and derivative as a function of altitude
        n_z = 1. + a * exp(-b * z)
        np_z = -(a * b * exp(-b * z))

        # Refractive index at the given height
        n_h = 1. + a * exp(-b * height)

        tan_phi = tan(
            arccos(((re + height) * n_h) / ((re + z) * n_z) *
                   cos(radians(theta_true))))

        return np_z / (n_z * tan_phi)
Ejemplo n.º 26
0
def pos2Ray(pos, tokamak, angle=None, eps=1e-6):
    r"""Take in GENIE pos vectors and convert it into TRIPPy rays
    
    Args:
        pos: 4 element tuple or 4x scipy-array
            Each pos is assembled into points of (R1,Z1,RT,phi)

        tokamak: 
            Tokamak object in which the pos vectors are defined.
            
    Returns:
        Ray: Ray object or typle of ray objects.
        
    """

    r1 = scipy.array(pos[0])
    z1 = scipy.array(pos[1])
    rt = scipy.array(pos[2])
    phi = scipy.array(pos[3])

    zt = z1 - scipy.tan(phi) * scipy.sqrt(r1**2 - rt**2)
    angle2 = scipy.arccos(old_div(rt, r1))

    if angle is None:
        angle = scipy.zeros(r1.shape)

    pt1 = geometry.Point((r1, angle, z1), tokamak)
    pt2 = geometry.Point((rt, angle + angle2, zt), tokamak)

    output = Ray(pt1, pt2)
    output.norm.s[-1] = eps
    tokamak.trace(output)
    return output
Ejemplo n.º 27
0
def cotangentWeightsLaplacianMatrix(polydata, points=None, polygons=None):
    """Calculates the laplacian matrix from the cotangent weights of the mesh.

    Return:
        laplacianMatrix (scipy.sparse.csr.csr_matrix): laplacian matrix.

    Args:
        polydata (vtkPolyData): vtkPolyData object with information of the mesh
        points (numpy.ndarray): information of the coordinates of each vertex
        polygons (numpy.ndarray): information on the identifiers of every point in every triangle of the mesh
    """

    if points is None:
        points = vtkPointsToNumpy(polydata)

    if polygons is None:
        polygons = vtkCellsToNumpy(polydata)

    numPoints = polydata.GetNumberOfPoints()
    numPolygons = polydata.GetNumberOfPolys()
    numDims = polydata.GetPoints().GetData().GetNumberOfComponents()
    laplacianMatrix = csr_matrix((numPoints, numPoints))

    for i in range(0, numDims):
        i1 = (i + 0) % 3
        i2 = (i + 1) % 3
        i3 = (i + 2) % 3

        vectP2P1 = (points[:, polygons[i2, :]] - points[:, polygons[i1, :]])
        vectP3P1 = (points[:, polygons[i3, :]] - points[:, polygons[i1, :]])

        vectP2P1 = vectP2P1 / repmat(sqrt((vectP2P1**2).sum(0)), numDims, 1)
        vectP3P1 = vectP3P1 / repmat(sqrt((vectP3P1**2).sum(0)), numDims, 1)

        angles = arccos((vectP2P1 * vectP3P1).sum(0))

        iterData1 = csr_matrix(
            (1 / tan(angles), (polygons[i2, :], polygons[i3, :])),
            shape=(numPoints, numPoints))

        iterData2 = csr_matrix(
            (1 / tan(angles), (polygons[i3, :], polygons[i2, :])),
            shape=(numPoints, numPoints))

        laplacianMatrix = laplacianMatrix + iterData1 + iterData2

    return laplacianMatrix
Ejemplo n.º 28
0
def D_integrand(th):
    """Initial D field is calculated by integrating D_integrand w.r.t.
    theta. Assumes the input is between theta0 and theta1.
    Note that this function operates on vectorized input."""
    from scipy import sin, exp, tan
    f = 2.0 * Omega * sin(th)
    u_zon = (80.0 / e_n) * exp(1.0 / ((th - theta_0) * (th - theta_1)))
    return u_zon * (f + tan(th) * u_zon / R)
Ejemplo n.º 29
0
def mini_RV_model(params, time):
    P, A, phase, ecc, w = params
    freq = 2. * sp.pi / P
    M = freq * time + phase
    E = sp.array([MarkleyKESolver().getE(m, ecc) for m in M])
    f = (sp.arctan(((1. + ecc)**0.5 / (1. - ecc)**0.5) * sp.tan(E / 2.)) * 2.)
    modelo = A * (sp.cos(f + w) + ecc * sp.cos(w))
    return modelo
Ejemplo n.º 30
0
 def __init__(self, yaml):
     self._tf_listener = tf.TransformListener()
     self._grid = SearchGrid(10, 10, 2.0, 2.0)
     camera = yaml.sensors[0].camera
     self._fov_h = camera.horizontal_fov
     self._fov_v = 2.0 * scipy.arctan(
         scipy.tan(self._fov_h / 2.0) *
         (camera.image_height / camera.image_width))
     self._fov_vectors = fov_vectors(self._fov_h, self._fov_v)
Ejemplo n.º 31
0
def f_Refl_Thick_Film_and_Substrate_fit(Data):
    strain = Data[0]
    DW = Data[1]

    dat = Data[2]
    wl = dat[0]
    t = dat[1]
    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]

    b_Sub = dat[11]
    thB_Sub = dat[12]
    G_Sub = dat[13]
    F0_Sub = dat[14]
    FH_Sub = dat[15]
    FmH_Sub = dat[16]

    t_film = dat[17]
    dw_film = dat[18]
    th = dat[19]
    delta_t = t_film - t

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

    temp1 = -b_Sub*(th-thB_Sub)*sin(2*thB_Sub) - (0.5*G_Sub*F0_Sub[0]*(1-b_Sub))
    temp2 = (abs(b_Sub)**0.5) * G_Sub * (FH_Sub[0]*FmH_Sub[0])**0.5
    eta = temp1/temp2
    res = (eta - signe(eta.real)*((eta*eta - 1)**0.5))

    g0 = sin(thB[0] - phi)  # gamma 0
    gH = -sin(thB[0] + phi)  # gamma H
    b = g0 / gH
    T = pi * G * ((FH[0]*FmH[0])**0.5) * delta_t * dw_film / (wl * (abs(g0*gH)**0.5))
    eta = (-b*(th-thB[0])*sin(2*thB_S) - 0.5*G*F0[0]*(1-b)) / ((abs(b)**0.5) * G  * dw_film * (FH[0]*FmH[0])**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
    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] * dw_film / (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] * dw_film * (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
Ejemplo n.º 32
0
    def __LaplacianMatrix(self):
        numDims                     = self.polygonData.shape[0];
        numPoints                   = self.pointData.shape[1];
        numPolygons                 = self.polygonData.shape[1];
        boundary                    = self.boundary;
        boundaryConstrain           = scipy.zeros((2,numPoints));

        sparseMatrix                = scipy.sparse.csr_matrix((numPoints, numPoints));

        for i in range(0, numDims):
            i1                      = (i + 0)%3;
            i2                      = (i + 1)%3;
            i3                      = (i + 2)%3;

            distP2P1                = self.pointData[:, self.polygonData[i2, :]]                \
                                      - self.pointData[:, self.polygonData[i1, :]];
            distP3P1                = self.pointData[:, self.polygonData[i3, :]]                \
                                      - self.pointData[:, self.polygonData[i1, :]];

            distP2P1                = distP2P1 / numpy.matlib.repmat(scipy.sqrt((distP2P1**2).sum(0)), 3, 1);
            distP3P1                = distP3P1 / numpy.matlib.repmat(scipy.sqrt((distP3P1**2).sum(0)), 3, 1);

            angles                  = scipy.arccos((distP2P1 * distP3P1).sum(0));

            iterData1               = scipy.sparse.csr_matrix((1/scipy.tan(angles),         \
                                                              (self.polygonData[i2,:],      \
                                                              self.polygonData[i3,:])),     \
                                                              shape=(numPoints,            \
                                                                     numPoints));

            iterData2               = scipy.sparse.csr_matrix((1/scipy.tan(angles),     \
                                                              (self.polygonData[i3,:],  \
                                                              self.polygonData[i2,:])), \
                                                              shape=(numPoints,        \
                                                                     numPoints));

            sparseMatrix            = sparseMatrix + iterData1 + iterData2;

        diagonal                    = sparseMatrix.sum(0);
        diagonalSparse              = scipy.sparse.spdiags(diagonal, 0, \
                                                           numPoints,  \
                                                           numPoints);
        self.laplacianMatrix        = diagonalSparse - sparseMatrix;
Ejemplo n.º 33
0
    def __calc_laplacian(self):
        """ """

        print("TO-DO: DOCUMENTATION")

        numPoints = self.polydata.GetNumberOfPoints()
        numPolygons = self.polydata.GetNumberOfPolys()
        numDims = self.polydata.GetPoints().GetData().GetNumberOfComponents()
        sparseMatrix = csr_matrix((numPoints, numPoints))

        for i in range(0, numDims):
            i1 = (i + 0) % 3
            i2 = (i + 1) % 3
            i3 = (i + 2) % 3

            vectP2P1 = (self.points[:, self.polygons[i2, :]] -
                        self.points[:, self.polygons[i1, :]])
            vectP3P1 = (self.points[:, self.polygons[i3, :]] -
                        self.points[:, self.polygons[i1, :]])

            vectP2P1 = vectP2P1 / repmat(sqrt(
                (vectP2P1**2).sum(0)), numDims, 1)
            vectP3P1 = vectP3P1 / repmat(sqrt(
                (vectP3P1**2).sum(0)), numDims, 1)

            angles = arccos((vectP2P1 * vectP3P1).sum(0))

            iterData1 = csr_matrix(
                (1 / tan(angles),
                 (self.polygons[i2, :], self.polygons[i3, :])),
                shape=(numPoints, numPoints))

            iterData2 = csr_matrix(
                (1 / tan(angles),
                 (self.polygons[i3, :], self.polygons[i2, :])),
                shape=(numPoints, numPoints))

            sparseMatrix = sparseMatrix + iterData1 + iterData2

        # diagonal            = sparseMatrix.sum(0)
        # diagonalSparse      = spdiags(diagonal, 0, numPoints, numPoints)
        # self.__laplacian    = diagonalSparse - sparseMatrix
        self.__laplacian = sparseMatrix
Ejemplo n.º 34
0
    def __LaplacianMatrix(self):
        numDims = self.__polygonData.shape[0]
        numPoints = self.__pointData.shape[1]
        numPolygons = self.__polygonData.shape[1]
        boundary = self.__boundary
        boundaryConstrain = scipy.zeros((2, numPoints))

        sparseMatrix = scipy.sparse.csr_matrix((numPoints, numPoints))

        for i in range(0, numDims):
            i1 = (i + 0) % 3
            i2 = (i + 1) % 3
            i3 = (i + 2) % 3

            distP2P1 = self.__pointData[:, self.__polygonData[
                i2, :]] - self.__pointData[:, self.__polygonData[i1, :]]
            distP3P1 = self.__pointData[:, self.__polygonData[
                i3, :]] - self.__pointData[:, self.__polygonData[i1, :]]

            distP2P1 = distP2P1 / numpy.matlib.repmat(
                scipy.sqrt((distP2P1**2).sum(0)), 3, 1)
            distP3P1 = distP3P1 / numpy.matlib.repmat(
                scipy.sqrt((distP3P1**2).sum(0)), 3, 1)

            angles = scipy.arccos((distP2P1 * distP3P1).sum(0))

            iterData1 = scipy.sparse.csr_matrix(
                (1 / scipy.tan(angles),
                 (self.__polygonData[i2, :], self.__polygonData[i3, :])),
                shape=(numPoints, numPoints))

            iterData2 = scipy.sparse.csr_matrix(
                (1 / scipy.tan(angles),
                 (self.__polygonData[i3, :], self.__polygonData[i2, :])),
                shape=(numPoints, numPoints))

            sparseMatrix = sparseMatrix + iterData1 + iterData2

        diagonal = sparseMatrix.sum(0)
        diagonalSparse = scipy.sparse.spdiags(diagonal, 0, numPoints,
                                              numPoints)
        self.__laplacianMatrix = diagonalSparse - sparseMatrix
Ejemplo n.º 35
0
def propagateRay(initCoords,theta,w,h):
  '''
  From a starting point with a given direction, determine how far a ray travels before encountering a side wall of the resonator.
  Returns the distance traveled, the coordinates of the intersection point at the boundary, and a number 0-3 indicating which wall
  was struck [right,top,left,bottom]
  '''
  
  cornerTheta = getCornerAngles(initCoords,w,h)
  
  # slope of line through dipole point
  m = tan(theta)
  
  xo = initCoords[0]
  yo = initCoords[1]
  
  horizIntersect = lambda y: 1/m*(y-yo)+xo  #returns x
  vertIntersect  = lambda x:   m*(x-xo)+yo  #returns y
  
  side = -1
  
  # Top
  if   theta >= cornerTheta[0] and theta < cornerTheta[1]:
    y = h/2.
    x = horizIntersect(y)
    side = 1

  # Left
  elif theta >= cornerTheta[1] and theta < cornerTheta[2]:
    x = -w/2.
    y = vertIntersect(x)
    side = 2
    
  # Bottom
  elif theta >= cornerTheta[2] and theta < cornerTheta[3]:
    y = -h/2.
    x = horizIntersect(y)
    side = 3

  # Right
  elif (theta >= cornerTheta[3] and theta <= 2*pi) or (theta < cornerTheta[0] and theta >= 0):
    x = w/2.
    y = vertIntersect(x)
    side = 0
    
  else:
    print 'Invalid Theta.'
    print theta*180/pi
    print cornerTheta*180/pi
    exit()
    
  d = sqrt((x-xo)**2 + (y-yo)**2)
  finalCoords = newCoords((xo,yo),d,theta)
  
  return d,finalCoords,side
Ejemplo n.º 36
0
def f_Refl_Thick_Film():
    a = P4Rm()

    wl = a.AllDataDict['wavelength']
    t = a.AllDataDict['damaged_depth']
    N = a.AllDataDict['number_slices']
    t_film = a.AllDataDict['film_thick']

    G = a.ParamDict['G']
    thB_S = a.ParamDict['thB_S']
    resol = a.ParamDict['resol']
    phi = a.ConstDict['phi']
    t_l = a.ParamDict['t_l']
    z = a.ParamDict['z']
    FH = a.ParamDict['FH']
    FmH = a.ParamDict['FmH']
    F0 = a.ParamDict['F0']
    sp = a.ParamDict['sp']
    dwp = a.ParamDict['dwp']
    th = a.ParamDict['th']
    spline_DW = a.splinenumber[1]
    spline_strain = a.splinenumber[0]
    param = a.ParamDict['par']
    delta_t = t_film - t

    strain = f_strain(z, param[:len(sp):], t, spline_strain)
    DW = f_DW(z, param[len(sp):len(sp)+len(dwp):], t, spline_DW)
    thB = thB_S - strain * tan(thB_S)  # angle de Bragg dans chaque lamelle

    eta = 0
    res = 0

    g0 = sin(thB[0] - phi)  # gamma 0
    gH = -sin(thB[0] + phi)  # gamma H
    b = g0 / gH
    T = pi * G * ((FH[0]*FmH[0])**0.5) * delta_t / (wl * (abs(g0*gH)**0.5))
    eta = (-b*(th-thB[0])*sin(2*thB_S) - 0.5*G*F0[0]*(1-b)) / ((abs(b)**0.5) * G  * (FH[0]*FmH[0])**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
    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 convolve(abs(res)**2, resol, mode='same')
Ejemplo n.º 37
0
def f_Refl_Thick_Film_fit(Data):
    strain = Data[0]
    DW = Data[1]

    dat = Data[2]
    wl = dat[0]
    t = dat[1]
    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]
    t_film = dat[17]
    th = dat[19]
    delta_t = t_film - t

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

    eta = 0
    res = 0

    g0 = sin(thB[0] - phi)  # gamma 0
    gH = -sin(thB[0] + phi)  # gamma H
    b = g0 / gH
    T = pi * G * ((FH[0] * FmH[0])**0.5) * delta_t / (wl * (abs(g0 * gH)**0.5))
    eta = (-b * (th - thB[0]) * sin(2 * thB_S) - 0.5 * G * F0[0] *
           (1 - b)) / ((abs(b)**0.5) * G * (FH[0] * FmH[0])**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
    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
Ejemplo n.º 38
0
def multivariateCauchy(mu, sigma, onlyDiagonal=True):
    """ Generates a sample according to a given multivariate Cauchy distribution. """
    if not onlyDiagonal:
        u, s, d = svd(sigma)
        coeffs = sqrt(s)
    else:
        coeffs = diag(sigma)
    r = rand(len(mu))
    res = coeffs * tan(pi * (r - 0.5))
    if not onlyDiagonal:
        res = dot(d, dot(res, u))
    return res + mu
Ejemplo n.º 39
0
def k_teta_DC(mean_incl, elevations=[9.23,10.81,26.57,31.08,47.41,52.62,69.16,90]):
    #computes extinction coefficient from mean inclination
    # equations from SIRASCA. Calculations for each elevation angle (p210-211 crop stucture and light microclimate)
    # default elevation for turtle 46 directions 
    #elevations (beam, degre)-> 90 = vertical ; 0=horizontal
    #mean_incl (feuille, degre) -> 90 = vertical ; 0=horizontal
    nh=len(elevations)
    xinc = radians(mean_incl)
    lst_xk=[]
    for ih in elevations:
        hh = radians(ih)
        if (hh >=xinc):
            xk = cos(xinc)
        else:
            xmm = -tan(hh)/tan(xinc)
            #print xmm
            xmm = arccos(xmm)
            xk = cos(xinc)*(2*(xmm - tan(xmm))/pi - 1.)

        lst_xk.append(xk)
    return lst_xk
Ejemplo n.º 40
0
def multivariateCauchy(mu, sigma, onlyDiagonal=True):
    """ Generates a sample according to a given multivariate Cauchy distribution. """
    if not onlyDiagonal:
        u, s, d = svd(sigma)
        coeffs = sqrt(s)
    else:
        coeffs = diag(sigma)
    r = rand(len(mu))
    res = coeffs * tan(pi * (r - 0.5))
    if not onlyDiagonal:
        res = dot(d, dot(res, u))
    return res + mu
def show_hough_lines(im, angles, dists):
    """Displays a set of Hough lines on top of an image"""
    fig, ax = show_image(im)
    for angle, dist in zip(angles, dists):
        xs = sp.array([0, im.shape[1]])
        ys = -xs / sp.tan(angle) + dist / sp.sin(angle)

        ax.plot(xs, ys, 'r')

    ax.set_xlim(0, im.shape[1])
    ax.set_ylim(im.shape[0], 0)

    return fig, ax
def show_hough_lines(im, angles, dists):
    """Displays a set of Hough lines on top of an image"""
    fig, ax = show_image(im)
    for angle, dist in zip(angles, dists):
        xs = sp.array([0, im.shape[1]])
        ys = -xs/sp.tan(angle) + dist/sp.sin(angle)
    
        ax.plot(xs, ys, 'r')
    
    ax.set_xlim(0, im.shape[1])
    ax.set_ylim(im.shape[0], 0)
    
    return fig, ax   
Ejemplo n.º 43
0
def Jensen_Wake_Model(xHAWT, yHAWT, zHAWT, params):
    theta = 0.1
    alpha = sp.tan(theta)
    rho = 1.1716
    a = 1. / 3.
    Cp = 4.*a*(1-a)**2.
    # nTurbines = len(xin)/2.
    r_0, U_velocity = params
    "Make the graphic for the turbines and wakes"
    # jensen_plot(x, y, r_0, alpha, U_direction_radians)

    "Calculate power from each turbine"
    return jensen_power(xHAWT, yHAWT, zHAWT, r_0, alpha, a, U_velocity, rho, Cp)
Ejemplo n.º 44
0
def radar_cross_section(frequency, nose_radius, base_radius, length,
                        incident_angle):
    """
    Calculate the radar cross section of a frustum.
    :param frequency: The operating frequency (Hz).
    :param nose_radius: The radius of the nose (m).
    :param base_radius: The radius of the base (m).
    :param length: The length (m).
    :param incident_angle: The incident angle (rad).
    :return: The radar cross section of the frustum (m^2).
    """
    # Wavelength
    wavelength = c / frequency

    # Wavenumber
    k = 2.0 * pi / wavelength

    # Calculate the half cone angle
    half_cone_angle = arctan((base_radius - nose_radius) / length)

    # Calculate the heights
    z2 = base_radius * tan(half_cone_angle)
    z1 = nose_radius * tan(half_cone_angle)

    # Calculate the RCS
    if abs(incident_angle - (0.5 * pi + half_cone_angle)) < 1e-12:
        # Specular
        rcs = 8.0 / 9.0 * pi * (z2 ** 1.5 - z1 ** 1.5) ** 2 * sin(half_cone_angle) / \
              (wavelength * cos(half_cone_angle) ** 4)
    elif incident_angle < 1e-3:
        rcs = wavelength**2 * (k * base_radius)**4 / (4.0 * pi)
    elif pi - incident_angle < 1e-3:
        rcs = wavelength**2 * (k * nose_radius)**4 / (4.0 * pi)
    else:
        rcs = wavelength * base_radius / (8.0 * pi * sin(incident_angle)) * (
            tan(incident_angle - half_cone_angle))**2

    return rcs
Ejemplo n.º 45
0
    def calculateCentroids(self, zern):
        """
            Calcualates the locations of the centroids under the given 
            Zernike coefficients
        """
        self.wavefront.setZern(zern)
        dx = 10.0   # Microns
        dy = 10.0   # Microns
        centroids = []
        intensities = []
        DCx, DCy = self.pupil.getDecenter()  # Decenter of Pupil
        for c in self.lenslet.coordinates:
            # Calculates the partial derivatives
            zxp = self.wavefront.calcWaveFront(c[0]+DCx+dx, c[1]+DCy)
            zxm = self.wavefront.calcWaveFront(c[0]+DCx-dx, c[1]+DCy)
            zyp = self.wavefront.calcWaveFront(c[0]+DCx, c[1]+DCy+dy)
            zym = self.wavefront.calcWaveFront(c[0]+DCx, c[1]+DCy-dy)
            delx = (zxp - zxm)/(2)
            dely = (zyp - zym)/(2)

            # Computes the normal vector to the surface
            normalx = -delx*dy
            normaly = -dely*dx
            normalz = dx*dy

            #Calculates the shift in microns on the detector
            theta_x = scipy.arctan2(normalx, normalz)
            theta_y = scipy.arctan2(normaly, normalz)
            shift_x = scipy.tan(theta_x)*self.lenslet.fl
            shift_y = scipy.tan(theta_y)*self.lenslet.fl
            centroids.append([c[0]+shift_x, c[1]+shift_y])

            intensities.append(self.pupil.calculateApertureIllumination(
                               c[0]-self.lenslet.spacing/2.0, 
                               c[1]-self.lenslet.spacing/2.0,
                               self.lenslet.spacing))

        return numpy.array(centroids), numpy.array(intensities)
Ejemplo n.º 46
0
def Jensen_Wake_Model(xHAWT, yHAWT, zHAWT, params):
    theta = 0.1
    alpha = sp.tan(theta)
    rho = 1.1716
    a = 1. / 3.
    Cp = 4. * a * (1 - a)**2.
    # nTurbines = len(xin)/2.
    r_0, U_velocity = params
    "Make the graphic for the turbines and wakes"
    # jensen_plot(x, y, r_0, alpha, U_direction_radians)

    "Calculate power from each turbine"
    return jensen_power(xHAWT, yHAWT, zHAWT, r_0, alpha, a, U_velocity, rho,
                        Cp)
Ejemplo n.º 47
0
def edge_voronoi_area(triangles, vertices):
    vv_l2_sqr_map = edge_sqr_length(triangles, vertices)

    alpha = edge_alpha_angle(triangles, vertices)
    gamma = edge_gamma_angle(triangles, vertices)

    cot_alpha = scipy.tan(alpha)
    cot_alpha.data **= -1
    inv_sin2_alpha = scipy.sin(alpha)
    inv_sin2_alpha.data **= -2

    w_angle = scipy.sin(2.0 * gamma).multiply(inv_sin2_alpha) / 2.0
    vv_area = vv_l2_sqr_map.multiply(cot_alpha + w_angle) / 8.0
    return vv_area
Ejemplo n.º 48
0
    def __LaplacianMatrix(self):
        numDims = self.__polygonData.shape[0]
        numPoints = self.__pointData.shape[1]
        numPolygons = self.__polygonData.shape[1]

        sparseMatrix = csr_matrix((numPoints, numPoints))

        for i in range(0, numDims):
            i1 = (i + 0) % 3
            i2 = (i + 1) % 3
            i3 = (i + 2) % 3

            distP2P1 = self.__pointData[:, self.__polygonData[
                i2, :]] - self.__pointData[:, self.__polygonData[i1, :]]
            distP3P1 = self.__pointData[:, self.__polygonData[
                i3, :]] - self.__pointData[:, self.__polygonData[i1, :]]

            distP2P1 = distP2P1 / repmat(sqrt((distP2P1**2).sum(0)), 3, 1)
            distP3P1 = distP3P1 / repmat(sqrt((distP3P1**2).sum(0)), 3, 1)

            angles = arccos((distP2P1 * distP3P1).sum(0))

            iterData1 = csr_matrix(
                (1 / tan(angles),
                 (self.__polygonData[i2, :], self.__polygonData[i3, :])),
                shape=(numPoints, numPoints))

            iterData2 = csr_matrix(
                (1 / tan(angles),
                 (self.__polygonData[i3, :], self.__polygonData[i2, :])),
                shape=(numPoints, numPoints))

            sparseMatrix = sparseMatrix + iterData1 + iterData2

        diagonal = sparseMatrix.sum(0)
        diagonalSparse = spdiags(diagonal, 0, numPoints, numPoints)
        self.__laplacianMatrix = diagonalSparse - sparseMatrix
Ejemplo n.º 49
0
def edge_voronoi_area(triangles, vertices):
    from trimeshpy.math.angle import edge_alpha_angle, edge_gamma_angle
    vv_l2_sqr_map = edge_sqr_length(triangles, vertices)

    alpha = edge_alpha_angle(triangles, vertices)
    gamma = edge_gamma_angle(triangles, vertices)

    cot_alpha = scipy.tan(alpha)
    cot_alpha.data **= -1
    inv_sin2_alpha = scipy.sin(alpha)
    inv_sin2_alpha.data **= -2

    w_angle = scipy.sin(2.0 * gamma).multiply(inv_sin2_alpha) / 2.0
    vv_area = vv_l2_sqr_map.multiply(cot_alpha + w_angle) / 8.0
    return vv_area
Ejemplo n.º 50
0
Archivo: wcs.py Proyecto: MCTwo/CodeCDF
def sky2pix(header,ra,dec):
	hdr_info = parse_header(header)
	if scipy.isscalar(ra):
		ra /= raddeg
		dec /= raddeg
	else:
		ra = ra.astype(scipy.float64)/raddeg
		dec = dec.astype(scipy.float64)/raddeg
	if hdr_info[3]=="DEC":
		ra0 = hdr_info[0][1]/raddeg
		dec0 = hdr_info[0][0]/raddeg
	else:
		ra0 = hdr_info[0][0]/raddeg
		dec0 = hdr_info[0][1]/raddeg

	phi = pi + arctan2(-1*cos(dec)*sin(ra-ra0),sin(dec)*cos(dec0)-cos(dec)*sin(dec0)*cos(ra-ra0))
	argtheta = sin(dec)*sin(dec0)+cos(dec)*cos(dec0)*cos(ra-ra0)
	if scipy.isscalar(argtheta):
		theta = arcsin(argtheta)
	else:
		argtheta[argtheta>1.] = 1.
		theta = arcsin(argtheta)

	if hdr_info[5]=="TAN":
		r_theta = raddeg/tan(theta)
		x = r_theta*sin(phi)
		y = -1.*r_theta*cos(phi)
	elif hdr_info[5]=="SIN":
		r_theta = raddeg*cos(theta)
		x = r_theta*sin(phi)
		y = -1.*r_theta*cos(phi)
	if hdr_info[3]=="DEC":
		a = x.copy()
		x = y.copy()
		y = a.copy()
	inv = linalg.inv(hdr_info[2])
	x0 = inv[0,0]*x + inv[0,1]*y
	y0 = inv[1,0]*x + inv[1,1]*y

	x = x0+hdr_info[1][0]-1
	y = y0+hdr_info[1][1]-1

	return x,y
Ejemplo n.º 51
0
# -*- coding: utf-8 -*-
# Herramientas para computación científica
# Lección 1
# SciPy: Introducción

import scipy


x = 0
print(scipy.sin(x))
print(scipy.cos(x))
print(scipy.tan(x))

print(scipy.exp(2 + x))
print(scipy.log(2 + x))

print(type(scipy.inf))

print(scipy.pi)
print(scipy.e)
Ejemplo n.º 52
0
def model(A, P, w, phase, ecc, jitt, offset, time):
    freq = 2. * sp.pi / P
    M = freq * time + phase
    E = sp.array([ks.getE(m, ecc) for m in M])
    f = (sp.arctan(sp.sqrt((1. + ecc) / (1. - ecc)) * sp.tan(E / 2.)) * 2)
    return A * (sp.cos(f + w) + ecc * sp.cos(w)) + offset
Ejemplo n.º 53
0
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 15 12:42:52 2015

@author: Chris

"""

import scipy as sc
import matplotlib.pyplot as plt

x = sc.arange(0, 5*sc.pi, 0.1);
y = sc.sin(x)
plt.plot(x, y)

z = sc.cos(x)
plt.plot(x, z)

a = sc.tan(x)

plt.plot(x,a)

plt.axis([0,5*sc.pi,-1,1])
Ejemplo n.º 54
0
def sun_NR(doy=scipy.array([]),\
           lat=float):
    '''
    Function to calculate the maximum sunshine duration [h] and incoming
    radiation [MJ/day] at the top of the atmosphere from day of year and
    latitude.
    
    Parameters:
     - doy: (array of) day of year.
     - lat: latitude in decimal degrees, negative for southern hemisphere.

    Returns:
    - N: (float, array) maximum sunshine hours [h].
    - Rext: (float, array) extraterrestrial radiation [J day-1].

    Notes
    -----
    Only valid for latitudes between 0 and 67 degrees (i.e. tropics
    and temperate zone).

    References
    ----------

    R.G. Allen, L.S. Pereira, D. Raes and M. Smith (1998). Crop
    Evaporation - Guidelines for computing crop water requirements,
    FAO - Food and Agriculture Organization of the United Nations.
    Irrigation and drainage paper 56, Chapter 3. Rome, Italy.
    (http://www.fao.org/docrep/x0490e/x0490e07.htm)
    
    Examples
    --------
    
        >>> sun_NR(50,60)
        (9.1631820597268163, 9346987.824773483)
        >>> days = [100,200,300]
        >>> latitude = 52.
        >>> sun_NR(days,latitude)
        (array([ 13.31552077,  15.87073276,   9.54607624]), array([ 29354803.66244921,  39422316.42084264,  12619144.54566777]))

    '''
    
    # Test input array/value
    doy,lat = _arraytest(doy,lat)
    
    # Set solar constant [W/m2]
    S = 1367.0 # [W/m2]
    # Print warning if latitude is above 67 degrees
    if abs(lat) > 67.:
        print('WARNING: Latitude outside range of application (0-67 degrees).\n)')
    # Convert latitude [degrees] to radians
    latrad = lat * math.pi / 180.0
    # calculate solar declination dt [radians]
    dt = 0.409 * scipy.sin(2 * math.pi / 365 * doy - 1.39)
    # calculate sunset hour angle [radians]
    ws = scipy.arccos(-scipy.tan(latrad) * scipy.tan(dt))
    # Calculate sunshine duration N [h]
    N = 24 / math.pi * ws
    # Calculate day angle j [radians]
    j = 2 * math.pi / 365.25 * doy
    # Calculate relative distance to sun
    dr = 1.0 + 0.03344 * scipy.cos(j - 0.048869)
    # Calculate Rext
    Rext = S * 86400 / math.pi * dr * (ws * scipy.sin(latrad) * scipy.sin(dt)\
           + scipy.sin(ws) * scipy.cos(latrad) * scipy.cos(dt))
    return N, Rext
Ejemplo n.º 55
0
if __name__== "__main__":
    
    app = QtGui.QApplication(sys.argv)
    
    win_plot = nihms.QtGui.QWidget()
    uiplot = nihms.Ui_Form()
    uiplot.setupUi(win_plot)
    start()
    uiplot.lcdNumber.display(heartrate)
    uiplot.lcdNumber_2.display(spo2)
  
    
    n=1000
    x=numpy.arange(n)
    y=scipy.tan(2*3.14*x)
    
    uiplot.pushButton_2.clicked.connect(lambda: timer.setInterval(5))
    uiplot.pushButton.clicked.connect(lambda: timer.setInterval(10000))
    uiplot.pushButton_3.clicked.connect(sms())
    
    
    
    c=Qwt.QwtPlotCurve()
    c.attach(uiplot.plot)
    
    timer = QtCore.QTimer()
    timer.start(5.0)
    win_plot.connect(timer, QtCore.SIGNAL('timeout()'),plot)
     
    win_plot.show()
Ejemplo n.º 56
0
def det(origin,ang1=120.,ang2=150.,offset=1e-3,angle=(0.,0.,0.)):
    
    norm = TRIPPy.Vecx((0.,0.,1.))
    meri = TRIPPy.Vecx((0.,1.,0.))
    area = [2*offset*scipy.tan(ang1*scipy.pi/360.),2*offset*scipy.tan(ang2*scipy.pi/360.)]
    return TRIPPy.surface.Rect((0.,0.,-offset), origin, area, angle=angle)
Ejemplo n.º 57
0
    def gz (self):
        """Calcula a função Gz"""

        bm = self.dic['km']-self.dic['kb']
        
        return (self.dic['gm'] + bm*0.5*sp.tan(self.pos[3])**2)*sp.sin(self.pos[3])/self.dic['lpp']
Ejemplo n.º 58
0
    "Define Variables"
    x = np.array([0, 0, 0, 500, 500, 500, 1000, 1000, 1000])  # x coordinates of the turbines
    y = np.array([0, 500, 1000, 0, 500, 1000, 0, 500, 1000])  # y coordinates of the turbines
    z = np.array([150, 150, 150, 250, 250, 250, 350, 500, 350]) #hub height of each turbine
    # r_0 = np.array([40, 40, 40, 50, 50, 50, 60, 75, 60])
    # r_0 = np.ones(len(x))*20
    zTall = 150
    zShort = 50
    xin = np.hstack([x, y, zTall, zShort])
    nTurbs = (len(xin) - 2) / 2
    "0 degrees is coming from due North. +90 degrees means the wind is coming from due East, -90 from due West"
    U_direction = -90.
    r_0 = np.ones(nTurbs) * 63.2
    U_direction_radians = (U_direction + 90) * pi / 180.
    theta = 0.1
    alpha = sp.tan(theta)
    # print U_direction_radians

    # x_r, y_r = rotate(x, y, U_direction_radians)

    # Jensen_Wake_Model(overlap, loss, jensen_power, jensen_plot, x, y, r_0, alpha, U_direction_radians)
    # xin = np.hstack([x, y])
    print Jensen_Wake_Model(xin)
    # ax = Axes3D(plt.gcf())
    # for i in range(len(x)):
    #     ax.scatter(x[i], y[i], z[i], c = 'r', s=pi*r_0[i]**2, marker='.')
    #     fillstyles = ('none')
    #     #plt.axis(U_direction_radians)
    #     xtemp = (x[i], x[i])
    #     ytemp = (y[i], y[i])
    #     ztemp = (0, z[i]-r_0[i])
import os 
import sys

#Z = lambda x: sp.cos(x[0]-0.02) + sp.cos(x[1]+0.01) 
Z = lambda x: (x[0]) + (x[1])
InternalAngle = sp.deg2rad(80);
 
quad_x = sp.array([10.0, 11.0, 11+sp.cos(InternalAngle), 10+sp.cos(InternalAngle) ])
quad_y = sp.array([10.0, 10.0, 10+sp.sin(InternalAngle), 10+sp.sin(InternalAngle) ])
quad_z = Z([quad_x, quad_y])

x_samples = sp.zeros((100,100))
y_samples = sp.zeros((100,100))
for i in range(100):
    y_samples[:,i]= sp.linspace(10,10+sp.sin(InternalAngle),100)
    x_lim = 10+(y_samples[i,0]-10)/sp.tan(InternalAngle)
    x_samples[i,:] = sp.linspace(x_lim,1+x_lim,100)
    
#The correct values 
z_samples = Z([x_samples, y_samples])
#The SciPy values
interp_points_x = sp.copy(x_samples).reshape((100*100))
interp_points_y = sp.copy(y_samples).reshape((100*100))
interp_points   = sp.column_stack((interp_points_x,interp_points_y))
scipy_interp = sp.interpolate.griddata(sp.column_stack((quad_x,quad_y)),\
quad_z,interp_points,\
            method='linear') 
scipy_interp = scipy_interp.reshape((100,100))
scipy_error  = (scipy_interp - z_samples)/z_samples
#The SU2 values
SU2_Z  = SU2_interp.interp2d(quad_x,quad_y,quad_z)
Ejemplo n.º 60
0
Archivo: dist.py Proyecto: proggy/tb
 def __call__(self, *args, **kwargs):
     if self.isdist:
         return scipy.tan(self.dist(*args, **kwargs))
     else:
         return scipy.tan(self.dist)