コード例 #1
0
ファイル: activewpdata.py プロジェクト: eman89/bluesky
    def Reached(self, qdr, dist, flyby):
        # Calculate distance before waypoint where to start the turn
        # Turn radius:      R = V2 tan phi / g
        # Distance to turn: wpturn = R * tan (1/2 delhdg) but max 4 times radius
        # using default bank angle per flight phase
        turnrad = bs.traf.tas * bs.traf.tas /     \
                      np.maximum(bs.traf.eps, np.tan(bs.traf.bank) * g0 * nm)  # [nm]

        next_qdr = np.where(self.next_qdr < -900., qdr, self.next_qdr)

        # Avoid circling
#        away = np.abs(degto180(bs.traf.trk - next_qdr)+180.)>90.
#        away     = np.abs(degto180(bs.traf.trk - next_qdr))>90.
        away     = np.abs(degto180(bs.traf.trk%360. - qdr%360.))>90.
        incircle = dist<turnrad*1.01
        circling = away*incircle


        # distance to turn initialisation point [nm]
        self.turndist = flyby*np.minimum(100., np.abs(turnrad *
            np.tan(np.radians(0.5 * np.abs(degto180(qdr%360. - next_qdr%360.))))))


        # Check whether shift based dist [nm] is required, set closer than WP turn distanc
        return np.where(bs.traf.swlnav * ((dist < self.turndist)+circling))[0]
コード例 #2
0
    def reconstruct(self, t, x, y, z, core_x, core_y):
        """Reconstruct angles for many detections

        :param t: arrival times in the detectors in ns.
        :param x,y,z: positions of the detectors in m.
        :param core_x,core_y: core position at z = 0 in m.
        :return: theta as derived by Montanus2014,
                 phi as derived by Montanus2014.

        """
        if not logic_checks(t, x, y, z):
            return nan, nan

        regress2d = RegressionAlgorithm()
        theta, phi = regress2d.reconstruct_common(t, x, y)

        dtheta = 1.
        iteration = 0
        while dtheta > 0.001:
            iteration += 1
            if iteration > self.MAX_ITERATIONS:
                return nan, nan
            nxnz = tan(theta) * cos(phi)
            nynz = tan(theta) * sin(phi)
            nz = cos(theta)
            x_proj = [xi - zi * nxnz for xi, zi in zip(x, z)]
            y_proj = [yi - zi * nynz for yi, zi in zip(y, z)]
            t_proj = [ti + zi / (c * nz) -
                      self.time_delay(xpi, ypi, core_x, core_y, theta, phi)
                      for ti, xpi, ypi, zi in zip(t, x_proj, y_proj, z)]
            theta_prev = theta
            theta, phi = regress2d.reconstruct_common(t_proj, x_proj, y_proj)
            dtheta = abs(theta - theta_prev)

        return theta, phi
コード例 #3
0
ファイル: gmf.py プロジェクト: me-manu/gmf
    def r_log_spiral(self,phi):
	"""
	return distance from center for angle phi of logarithmic spiral

	Parameters
	----------
	phi: scalar or np.array with polar angle values

	Returns
	-------
	r(phi) = rx * exp(b * phi) as np.array

	Notes
	-----
	see http://en.wikipedia.org/wiki/Logarithmic_spiral
	"""
	if np.isscalar(phi):
	    phi = np.array([phi])
	ones = np.ones(phi.shape[0])

	# self.rx.shape = 8
	# phi.shape = p
	# then result is given as (8,p)-dim array, each row stands for one rx

	result = np.tensordot(self.rx , np.exp((phi - 3.*pi*ones) / np.tan(pi/2. - self.idisk)),axes = 0)
	result = np.vstack((result, np.tensordot(self.rx , np.exp((phi - pi*ones) / np.tan(pi/2. - self.idisk)),axes = 0) ))
	result = np.vstack((result, np.tensordot(self.rx , np.exp((phi + pi*ones) / np.tan(pi/2. - self.idisk)),axes = 0) ))
	return np.vstack((result, np.tensordot(self.rx , np.exp((phi + 3.*pi*ones) / np.tan(pi/2. - self.idisk)),axes = 0) ))
コード例 #4
0
ファイル: utils.py プロジェクト: jaabell/pySW4
def latlon2xy(lat, lon, origin=(37.0, -118.0), az=0, km2deg=111.3195):
    """Project cartesian x,y coordinates to geographical lat,lon.

    Parameters
    -----------
    lat and lon : 2darrays in decimal degrees.

    origin : tuple or list, optional, default: lat=37.0 lon=-118.0
            lat,lon coordinates of the south-west corner of the x,y grid

    az : float or int, optional, default: 0 degrees
            rotation of the grid aroud the vertical (z-axis),
            see the SW4 User Guide for more information.

    km2deg : float, optional, default: 111.3195 km
            how many km to a degree.

    Returns
    --------
    x and y 2darrays."""

    az = np.radians(az)
    x = km2deg * (
        ((lat - origin[0]) +
         (lon - origin[1]) * np.cos(np.radians(lat)) * np.tan(az)) /
        (np.cos(az) * (1 + np.tan(az)**2)))
    y = (km2deg * ((lon - origin[1]) * np.cos(np.radians(lat))) /
         np.cos(az)) - x * np.tan(az)

    return x, y
コード例 #5
0
ファイル: activewpdata.py プロジェクト: isabelmetz/bluesky
    def Reached(self, qdr, dist, flyby):
        # Calculate distance before waypoint where to start the turn
        # Turn radius:      R = V2 tan phi / g
        # Distance to turn: wpturn = R * tan (1/2 delhdg) but max 4 times radius
        # using default bank angle per flight phase
        turnrad = bs.traf.tas * bs.traf.tas /     \
                      (np.maximum(bs.traf.eps, np.tan(bs.traf.bank)) * g0)  \
                       # Turn radius in meters!

        next_qdr = np.where(self.next_qdr < -900., qdr, self.next_qdr)

        # Avoid circling by checking for flying away
        away     = np.abs(degto180(bs.traf.trk%360. - qdr%360.)) > 90. # difference large than 90

        # Ratio between distance close enough to switch to next wp when flying away
        # When within pro1 nm and flying away: switch also
        proxfact = 1.01 # Turnradius scales this contant , factor => [turnrad]
        incircle = dist<turnrad*proxfact
        circling = away*incircle # [True/False] passed wp,used for flyover as well


        # distance to turn initialisation point [m]
        self.turndist = flyby*np.abs(turnrad *
            np.tan(np.radians(0.5 * np.abs(degto180(qdr%360. - next_qdr%360.)))))


        # Check whether shift based dist is required, set closer than WP turn distance
        swreached = np.where(bs.traf.swlnav * ((dist < self.turndist)+circling))[0]

        # Return True/1.0 for a/c where we have reached waypoint
        return swreached
コード例 #6
0
 def xzCrossingTime(self):
   """
     Calculate times of crossing the xz-plane.
     
     This method calculates the times at which
     the xz-plane is crossed by the orbit. This
     is equivalent to finding the times where
     y=0.
     
     Returns
     -------
     Time 1 : float
         First crossing time defined as having POSITIVE
         x position.
     Time 2 : float
         Second crossing time defined as having NEGATIVE
         x position.
   """
   f = -self._w - arctan(tan(self._Omega)/cos(self._i))
   E = 2.*arctan(sqrt((1-self.e)/(1.+self.e)) * tan(f/2.))
   t1 = (E - self.e*sin(E))/self._n + self.tau
   p1 = self.xyzPos(t1)
   f += pi
   E = 2.*arctan(sqrt((1-self.e)/(1.+self.e)) * tan(f/2.))
   t2 = (E - self.e*sin(E))/self._n + self.tau
   
   t1 -= self._per * numpy.floor(t1/self._per)
   t2 -= self._per * numpy.floor(t2/self._per)
   
   if p1[0] >= 0.0:
     # y position of p1 is > 0
     return (t1, t2)
   else:
     return (t2, t1)
コード例 #7
0
def calculate_fracture_step_sizes(start_yx, ang):
    """
    Calculate the sizes of steps dx and dy to be used when "drawing" the
    fracture onto the grid.

    Parameters
    ----------
    start_yx : tuple of int
        Starting grid coordinates
    ang : float
        Fracture angle relative to horizontal (radians)

    Returns
    -------
    (dy, dx) : tuple of float
        Step sizes in y and x directions. One will always be unity, and the
        other will always be <1.
    """
    starty, startx = start_yx
    if startx==0:  # frac starts on left side
        dx = 1
        dy = tan(ang)
    else:  # frac starts on bottom side
        dy = 1
        dx = -tan(ang-pi/2)

    return (dy, dx)
コード例 #8
0
def _prepare_input_epr_mur(w,epb,mub,ange,angm,sigmadc,tau):
    epr = _np.zeros((len(epb),len(w)),dtype=complex)
    mur = _np.zeros((len(epb),len(w)),dtype=complex)
    for j in range(len(epb)):
        epr[j,:] = epb[j]*(1-1j*_np.sign(w)*_np.tan(ange[j])) + sigmadc[j]/(1+1j*w*tau[j])/(1j*w*_ep0)
        mur[j,:] = mub[j]*(1-1j*_np.sign(w)*_np.tan(angm[j]))
    return epr, mur
コード例 #9
0
ファイル: skymapper.py プロジェクト: rainwoodman/skymapper
    def __init__(self, ra_0, dec_0, dec_1, dec_2):
        """Lambert Conformal conic projection.

        LCC is a conic projection with an origin along the lines connecting
        the poles. It preserves angles, but is not equal-area,
        perspective or equistant.

        Its preferred use of for areas with predominant east-west extent
        at higher latitudes.

        As a conic projection, it depends on two standard parallels, i.e.
        intersections of the cone with the sphere. To minimize scale variations,
        these standard parallels should be chosen as small as possible while
        spanning the range in declinations of the data.

        For details, see Snyder (1987, section 15).

        Args:
            ra_0: RA that maps onto x = 0
            dec_0: Dec that maps onto y = 0
            dec_1: lower standard parallel
            dec_2: upper standard parallel (must not be -dec_1)
        """
        ConicProjection.__init__(self, ra_0, dec_0, dec_1, dec_2)
        # Snyder 1987, eq. 14-1, 14-2 and 15-1 to 15-3.
        self.dec_max = 89.99

        dec_1 *= self.deg2rad
        dec_2 *= self.deg2rad
        self.n = np.log(np.cos(dec_1)/np.cos(dec_2)) / \
        (np.log(np.tan(np.pi/4 + dec_2/2)/np.tan(np.pi/4 + dec_1/2)))
        self.F = np.cos(dec_1)*(np.tan(np.pi/4 + dec_1/2)**self.n)/self.n
        self.rho_0 = self._rho(dec_0)
コード例 #10
0
ファイル: conjugates.py プロジェクト: ki113r4bbi7/rayopt
 def map_object(self, yo, a):
     p = self.projection
     n = yo.shape[0]
     if p == "rectilinear":
         y = yo*np.tan(a)
         u = np.hstack((y, np.ones((n, 1))))
         u /= np.sqrt(np.square(u).sum(-1))[:, None]
     elif p == "stereographic":
         y = yo*(2*np.tan(a/2))
         r = np.square(y).sum(-1)[:, None]/4
         u = np.hstack((y, 1 - r))/(r + 1)
     elif p == "equisolid":
         y = yo*(2*np.sin(a/2))
         r = np.square(y).sum(-1)[:, None]
         u = np.hstack((y*np.sqrt(1 - r/4), 1 - r/2))
     elif p == "orthographic":
         y = yo*np.sin(a)
         r = np.square(y).sum(-1)[:, None]
         u = np.hstack((y, np.sqrt(1 - r)[:, None]))
     elif p == "equidistant":
         y = yo*a
         b = np.square(y).sum(-1) > (np.pi/2)**2
         y = np.sin(y)
         z = np.sqrt(np.square(y).sum(-1))
         z = np.where(b, -z, z)[:, None]
         u = np.hstack((y, z))
     return u
コード例 #11
0
ファイル: single_color_vision.py プロジェクト: iaq3/gatlin
	def project(self, p, radius, width, height) :
		#print p
		#print width
		#print height
		#print "radius"
		#print radius

		xFOV = 63.38
		yFOV = 48.25
		cx = width /2
		cy = height /2
		fx = cx / np.tan((xFOV/2) * np.pi / 180)
		fy = cy / np.tan((yFOV/2) * np.pi / 180)
		
		toball = np.zeros(3)
		toball[0] = (p[0] - cx) / fx
		toball[1] = -(p[1] - cy) / fy
		toball[2] = 1
		toball = toball / np.linalg.norm(toball) #normalize so we can then multiply by distance
		distance = self.pixel_radius / radius
		toball = toball * distance

		pose = Pose()
		pose.position = Point(toball[0], toball[1], toball[2])
		pose.orientation = Quaternion(0,0,0,1)
		#print "FOUND ORANGE BALL!!!!"
		#print toball
		return pose
コード例 #12
0
ファイル: features.py プロジェクト: looooo/FCGear
    def profile(self, m, r, r0, t_c, t_i, alpha_w, y0, y1, y2):
        r_ew = m * t_i / 2

        # 1: modifizierter Waelzkreisdurchmesser:
        r_e = r / r0 * r_ew

        # 2: modifizierter Schraegungswinkel:
        alpha = np.arccos(r0 / r * np.cos(alpha_w))

        # 3: winkel phi bei senkrechter stellung eines zahns:
        phi = np.pi / t_i / 2 + (alpha - alpha_w) + (np.tan(alpha_w) - np.tan(alpha))

        # 4: Position des Eingriffspunktes:
        x_c = r_e * np.sin(phi)
        dy = -r_e * np.cos(phi) + r_ew

        # 5: oberer Punkt:
        b = y1 - dy
        a = np.tan(alpha) * b
        x1 = a + x_c

        # 6: unterer Punkt
        d = y2 + dy
        c = np.tan(alpha) * d
        x2 = x_c - c

        r *= np.cos(phi)
        pts = [
            [-x1, r, y0],
            [-x2, r, y0 - y1 - y2],
            [x2, r, y0 - y1 - y2],
            [x1, r, y0]
        ]
        pts.append(pts[0])
        return pts
コード例 #13
0
def build_planar_surface(geometry):
    """
    Builds the planar rupture surface from the openquake.nrmllib.models
    instance
    """
    # Read geometry from wkt
    geom = wkt.loads(geometry.wkt)
    top_left = Point(geom.xy[0][0],
                     geom.xy[1][0],
                     geometry.upper_seismo_depth)
    top_right = Point(geom.xy[0][1],
                      geom.xy[1][1],
                      geometry.upper_seismo_depth)
    strike = top_left.azimuth(top_right)
    dip_dir = (strike + 90.) % 360.
    depth_diff = geometry.lower_seismo_depth - geometry.upper_seismo_depth
    bottom_right = top_right.point_at(
        depth_diff / np.tan(geometry.dip * (np.pi / 180.)),
        depth_diff,
        dip_dir)
    bottom_left = top_left.point_at(
        depth_diff / np.tan(geometry.dip * (np.pi / 180.)),
        depth_diff,
        dip_dir)
    return PlanarSurface(1.0,
                         strike,
                         geometry.dip,
                         top_left,
                         top_right,
                         bottom_right,
                         bottom_left)
コード例 #14
0
ファイル: navpy.py プロジェクト: AuraUAS/aura-core
def omega2rates(phi,theta,input_unit='rad',output_type='ndarray'):
    """
    This function is used to create the transformation matrix to get
    phi_dot, the_dot and psi_dot from given pqr (body rate).
    Input:
    e: Euler Angle in the format of [phi the psi];
    Output:
    R: Transformation matrix, numpy array 3x3
    Programmer:    Adhika Lie
    Created:    	 May 13, 2011
    Last Modified: May 13, 2011
    """
    R = np.zeros((3,3))
    if(input_unit=='deg'):
        phi = np.deg2rad(phi)
        theta = np.deg2rad(theta)
    
    R[0,0] = 1.0
    R[0,1] = np.sin(phi)*np.tan(theta)
    R[0,2] = np.cos(phi)*np.tan(theta)
    
    R[1,0] = 0.0
    R[1,1] = np.cos(phi)
    R[1,2] = -np.sin(phi)
    
    R[2,0] = 0.0
    R[2,1] = np.sin(phi)/np.cos(theta)
    R[2,2] = np.cos(phi)/np.cos(theta)
    
    if(output_type=='matrix'):
        R = np.matrix(R)
    
    return R
コード例 #15
0
ファイル: features.py プロジェクト: looooo/FCGear
 def execute(self, fp):
     fp.rack.m = fp.module.Value
     fp.rack.z = fp.teeth
     fp.rack.pressure_angle = fp.pressure_angle.Value * np.pi / 180.
     fp.rack.thickness = fp.thickness.Value
     fp.rack.beta = fp.beta.Value * np.pi / 180.
     fp.rack.head = fp.head
     fp.rack._update()
     pts = fp.rack.points()
     pol = Wire(makePolygon(list(map(fcvec, pts))))
     if fp.beta.Value == 0:
         face = Face(Wire(pol))
         fp.Shape = face.extrude(fcvec([0., 0., fp.height.Value]))
     elif fp.double_helix:
         beta = fp.beta.Value * np.pi / 180.
         pol2 = Part.Wire(pol)
         pol2.translate(fcvec([0., np.tan(beta) * fp.height.Value / 2, fp.height.Value / 2]))
         pol3 = Part.Wire(pol)
         pol3.translate(fcvec([0., 0., fp.height.Value]))
         fp.Shape = makeLoft([pol, pol2, pol3], True, True)
     else:
         beta = fp.beta.Value * np.pi / 180.
         pol2 = Part.Wire(pol)
         pol2.translate(fcvec([0., np.tan(beta) * fp.height.Value, fp.height.Value]))
         fp.Shape = makeLoft([pol, pol2], True)
コード例 #16
0
ファイル: simplectrl.py プロジェクト: joschu/surgical
def makeArch(thread, center, mainax, up, elev):
    p_start = center - mainax
    p_end = center + mainax        
    v_start = normr(mainax + normr(up)*norm(mainax)*tan(elev))
    v_end = normr(mainax - normr(up)*norm(mainax)*tan(elev))
    
    print "p_start,p_end",p_start,p_end
    
    while True:
        xyz = thread.getXYZ()
        s0 = xyz.T[0]
        e0 = xyz.T[-1]
        
    
    while True:
        xyz = thread.getXYZ()
        s0,s1,e1,e0 = xyz.T[[0,1,-2,-1]]
        print "s0,e0",s0,e0
        print "ang_start",angBetween(v_start,s1-s0)
        print "ang_end",angBetween(v_end,e0-e1)
        if almostEq(s0,p_start) and almostEq(e0,p_end) and\
           almostEq(v_start,s1-s0) and almostEq(v_end,e0-e1): break
        else:
            t_start = trunc(p_end - s0,.5)
            t_end = trunc(p_start - e0,.5)
            #print t_start,t_end
            ang1 = trunc(angBetween(v_start,s1-s0),.05)
            ang2 = trunc(angBetween(v_end,e0-e1),.05)
            cons = moveEndCons(thread,t_start,t_end,"towards",(v_start,ang1),(v_end,ang2))
            #cons = thread.getConstraints()
            #cons = r_[cons[0:3]+t_start,cons[3:6],cons[6:9]+t_end,cons[9:12]]
            yield cons            
コード例 #17
0
ファイル: res.py プロジェクト: pkienzle/sansresolution
def nominal_q(sx, sy, az_in, el_in, az_out, el_out, dz):
    nx, ny = sx + dz * tan(az_in), sy + dz * tan(el_in)
    nd = sqrt( (nx-sx)**2 + (ny-sy)**2 + dz**2 )
    #plt.subplot(131); plot(nx/5,ny/5,'G: direct flight beam center')

    px, py = sx + dz * tan(az_out), sy + dz * tan(el_out)
    pd = sqrt( (px-sx)**2 + (py-sy)**2 + dz**2 )
    #plt.subplot(122); plot(px/5,py/5,'G: direct flight scattered beam')

    if 0:
        # Correction to move px,py into the q normal plane.  This is
        # insignificant for small angle scattering.
        nx_hat, ny_hat, nz_hat = (nx-sx)/nd, (ny-sy)/nd, dz/nd
        px_hat, py_hat, pz_hat = (px-sx)/pd, (py-sy)/pd, dz/pd
        d = nd / (px_hat*nx_hat + py_hat*ny_hat + pz_hat*nz_hat)
        px, py = sx + px_hat*d, sy + py_hat*d
    #plt.subplot(122); plot((px)/5,(py)/5,'G: scattered beam on q normal plane')

    # Note: px,py is the location of the scattered neutron relative to the
    # beam center without gravity in detector coordinates, not the qx,qy vector
    # in inverse coordinates.  This allows us to compute the scattered angle at 
    # the sample, returning theta and phi.
    qd = sqrt((px-nx)**2 + (py-ny)**2)
    theta, phi = arctan2(qd, nd)/2, arctan2(py-ny, px-nx)

    return theta, phi
コード例 #18
0
ファイル: wcsutil.py プロジェクト: erykoff/esutil
    def sph2image(self, longitude, latitude):
        """
        Must be a tangent plane projection
        """

        longitude,latitude = self.Rotate(longitude, latitude)
        longitude *= d2r
        latitude  *= d2r

        x = numpy.zeros_like(longitude)
        y = numpy.zeros_like(longitude)

        if isscalar(longitude):
            if latitude > 0.0:
                rdiv= r2d/numpy.tan(latitude)
                x =  rdiv*numpy.sin(longitude)
                y = -rdiv*numpy.cos(longitude)
        else:
            w, = numpy.where(latitude > 0.0)
            if w.size > 0:
                rdiv= r2d/numpy.tan(latitude[w])
                x[w] =  rdiv*numpy.sin(longitude[w])
                y[w] = -rdiv*numpy.cos(longitude[w])

        return x,y
コード例 #19
0
    def _make_source(self, mfd, aspect_ratio, fault_trace, dip):
        sf = super(ComplexFaultSourceRupEnclPolyTestCase, self)._make_source(
            mfd, aspect_ratio, fault_trace, dip
        )
        # create an equivalent top and bottom edges
        vdist_top = sf.upper_seismogenic_depth
        vdist_bottom = sf.lower_seismogenic_depth

        hdist_top = vdist_top / numpy.tan(numpy.radians(dip))
        hdist_bottom = vdist_bottom / numpy.tan(numpy.radians(dip))

        strike = fault_trace[0].azimuth(fault_trace[-1])
        azimuth = (strike + 90.0) % 360

        top_edge = []
        bottom_edge = []
        for point in fault_trace.points:
            top_edge.append(point.point_at(hdist_top, vdist_top, azimuth))
            bottom_edge.append(point.point_at(hdist_bottom, vdist_bottom,
                                              azimuth))
        edges = [Line(top_edge), Line(bottom_edge)]

        return ComplexFaultSource(
            sf.source_id, sf.name, sf.tectonic_region_type,
            sf.mfd, sf.rupture_mesh_spacing,
            sf.magnitude_scaling_relationship, sf.rupture_aspect_ratio,
            edges, sf.rake
        )
コード例 #20
0
ファイル: abb_batch.py プロジェクト: kennexrazon/FilterDev
def accel_to_lin_xz_xy(seg_len,xa,ya,za):

    x=seg_len/np.sqrt(1+(np.tan(np.arctan(za/(np.sqrt(xa**2+ya**2))))**2+(np.tan(np.arctan(ya/(np.sqrt(xa**2+za**2))))**2)))
    xz=x*(za/(np.sqrt(xa**2+ya**2)))
    xy=x*(ya/(np.sqrt(xa**2+za**2)))
    
    return np.round(xz,4),np.round(xy,4)
コード例 #21
0
ファイル: kepler.py プロジェクト: xagriff/vallado
def kep_eqtnP(del_t, p, mu=Earth.mu):
    """Parabolic solution to Kepler's Equation (Algorithm 3)
    
    A trigonometric approach to solving Kepler's Equation for 
    parabolic orbits. For reference, see Algorithm 3 in Vallado (Fourth 
    Edition), Section 2.2 (pg 69).
    
    Parameters
    ----------
    del_t: double
        Change in time
    p: double
        Semi-parameter
    mu: double, optional, default = Earth.mu
        Gravitational parameter; defaults to Earth
        
    Returns
    -------
    B: double
        Parabolic Anomaly (radians)
    """
    
    p3 = p**3
    n_p = 2.0*np.sqrt(mu/p3)
    s = 0.5*np.arctan(2.0/(3.0*n_p*del_t))
    w = np.arctan((np.tan(s))**(1/3.0))
    B = 2.0/np.tan(2.0*w)
    return B
コード例 #22
0
def simulator_alpha(theta, N=100):
    """
    function that samples form the alpha stable distribution
    theta is np.array([alpha, beta, gamma, delta])
    """
    # unpack values
    #	theta = theta.astype(object)
    alpha = theta[0,:]
    beta =  theta[1,:]
    gamma =  theta[2,:]
    delta =  theta[3,:]
    # add random seed
    random_seed = random.randrange(10**9)
    np.random.seed(seed=random_seed)
    # generate w and u for simulating
    #	pdb.set_trace()
    w = nr.exponential(size=N)
    u = nr.uniform(low=-np.pi/2., high=np.pi/2., size=N)
    #	w = w.astype(float)
    #	u = u.astype(float)
    S_a_b = (1.+ beta**2. * np.tan(np.pi*alpha/2.)**2. )**(1/(2.*alpha))
    B_a_b = 1./alpha * np.arctan(beta*np.tan(np.pi*alpha*0.5))
    if alpha == 1.:
        y_bar = 2./np.pi * ((np.pi/2. + beta*u)*np.tan(u)-beta*np.log(np.pi/2. * w *np.cos(u ) / (np.pi/2. + beta*u)   ) )
    else:
        y_bar = S_a_b * ((np.sin(alpha)*(u + B_a_b ) ) / np.cos(u)**(1./alpha)  ) * (np.cos(u-alpha*(u+ B_a_b ))/w) **((1-alpha)/alpha )

    return S1_summary_statistic_alpha(y_bar*gamma+delta, theta)
コード例 #23
0
def fundamental_geometry_plot_data(par):
    '''Returns the coordinates for line end points of the bicycle fundamental
    geometry.

    Parameters
    ----------
    par : dictionary
        Benchmark bicycle parameters.

    Returns
    -------
    x : ndarray
    z : ndarray

    '''
    d1 = np.cos(par['lam']) * (par['c'] + par['w'] -
                par['rR'] * np.tan(par['lam']))
    d3 = -np.cos(par['lam']) * (par['c'] - par['rF'] *
                np.tan(par['lam']))
    x = np.zeros(4, dtype=object)
    z = np.zeros(4, dtype=object)
    x[0] = 0.
    x[1] = d1 * np.cos(par['lam'])
    x[2] = par['w'] - d3 * np.cos(par['lam'])
    x[3] = par['w']
    z[0] = -par['rR']
    z[1] = -par['rR'] - d1 * np.sin(par['lam'])
    z[2] = -par['rF'] + d3 * np.sin(par['lam'])
    z[3] = -par['rF']

    return x, z
コード例 #24
0
ファイル: Tools.py プロジェクト: maldun/MyMesh
def compute_voroni_area_of_triangle(w1,w2,l1,l2):
    """
    computes the part of the triangle for the Voroni area
    descriped in [1]

            x_i
          +
          |\
          | \
          |  \
        l1|   \l2
          |    \
          |     \
          |w1  w2\
          +-------+
        x_j  l3  x_{j+1}

    """
    # Check if triangle is obtuse in x_i
    if w1+w2 < pi/2.0:
        # Then get Area(T)/2
        return norm(cross(l1,l2))/4.0
    
    if w1 > pi/2.0 or w2 > pi/2:
        # Then get Area(T)/4
        return norm(cross(l1,l2))/8.0
            

    #Else use formula on page 9 in [1]
    return ((1/tan(w1))*inner(l2,l2) + (1/tan(w2))*inner(l1,l1))/8.0
    def draw(self, output="plot.png", label=None):
        """ draw the wave structure """

        print(self.left_pos, self.contact_pos, self.right_pos)

        # each wave has a point on the origin.  The maximum height we
        # want to draw to is self.dx -- we'll do the center and right
        x1 = self.x0 + self.dx * np.tan(np.radians(self.left_pos))
        xc = self.x0 + self.dx * np.tan(np.radians(self.contact_pos))
        x3 = self.x0 + self.dx * np.tan(np.radians(self.right_pos))

        # draw the waves
        if self.left_type == "shock":
            plt.plot([self.x0, x1], [0, self.dx], color="C0", lw=3)
        else:
            for n in range(5):
                x1 = self.x0 + self.dx * np.tan(np.radians(self.left_pos - 2*n))
                plt.plot([self.x0, x1], [0, self.dx], color="C0", lw=1)

        plt.plot([self.x0, xc], [0, self.dx], color="C1")

        if self.right_type == "shock":
            plt.plot([self.x0, x3], [0, self.dx], color="C0", lw=3)
        else:
            for n in range(5):
                x3 = self.x0 + self.dx * np.tan(np.radians(self.right_pos + 2*n))
                plt.plot([self.x0, x3], [0, self.dx], color="C0", lw=1)
コード例 #26
0
ファイル: geometry_elements.py プロジェクト: danustc/Optics
def cone_to_plane(theta, a_max):
    '''
    convert the cone to plane
    '''
    h = 1./np.tan(a_max)
    sl = h*np.tan(theta)
    return sl
コード例 #27
0
 def publish(self, event):
     if self.imgmsg is None:
         return
     now = rospy.Time.now()
     # setup ros message and publish
     with self.lock:
         self.imgmsg.header.stamp = now
         self.imgmsg.header.frame_id = self.frame_id
     self.pub.publish(self.imgmsg)
     if self.publish_info:
         info = CameraInfo()
         info.header.stamp = now
         info.header.frame_id = self.frame_id
         info.width = self.imgmsg.width
         info.height = self.imgmsg.height
         if self.fovx is not None and self.fovy is not None:
             fx = self.imgmsg.width / 2.0 / \
                 np.tan(np.deg2rad(self.fovx / 2.0))
             fy = self.imgmsg.height / 2.0 / \
                 np.tan(np.deg2rad(self.fovy / 2.0))
             cx = self.imgmsg.width / 2.0
             cy = self.imgmsg.height / 2.0
             info.K = np.array([fx, 0, cx,
                                0, fy, cy,
                                0, 0, 1.0])
             info.P = np.array([fx, 0, cx, 0,
                                0, fy, cy, 0,
                                0, 0, 1, 0])
             info.R = [1, 0, 0, 0, 1, 0, 0, 0, 1]
         self.pub_info.publish(info)
コード例 #28
0
ファイル: insar.py プロジェクト: emolch/pyrocko
    def get_corner_coordinates(self):
        inc = self.inclination

        llLat, llLon = self.get_ll_anchor()
        urLat, urLon = self.get_ur_anchor()

        if self.orbital_node == 'Ascending':

            ulLat, ulLon = od.ne_to_latlon(
                self.lat_center, self.lon_center,
                self.track_length/2,
                -num.tan(inc*d2r) * self.width/2)
            lrLat, lrLon = od.ne_to_latlon(
                self.lat_center, self.lon_center,
                -self.track_length/2,
                num.tan(inc*d2r) * self.width/2)

        elif self.orbital_node == 'Descending':
            urLat, urLon = od.ne_to_latlon(
                self.lat_center, self.lon_center,
                self.track_length/2,
                num.tan(inc*d2r) * self.width/2)
            llLat, llLon = od.ne_to_latlon(
                self.lat_center, self.lon_center,
                -self.track_length/2,
                -num.tan(inc*d2r) * self.width/2)

        return ((llLat, llLon), (ulLat, ulLon),
                (urLat, urLon), (lrLat, lrLon))
コード例 #29
0
def get_distance_matrix(pan, fov, height, rows):
    """
        画像と同じ行数で一列の配列を返す。
        それぞれの行にはcameraからcenterまでの距離が入ってる。

        src: pan       -> カメラの傾き   [radian]
             fov       -> カメラの視野角 [radian]
             height    -> 地面からカメラまでの高さ [m]
             rows      -> 画像の縦方向のピクセル数 [pixel]

        dst: dis       -> 距離の真値
             dis_ratio -> dis[row] / dis[len(rows)]の値(画像中心からの距離の比)
    """

    # Convert radian -> degree
    pan = 1.0 * pan * np.pi / 180
    fov = 1.0 * fov * np.pi / 180
    dis = []
    dis_ratio = []

    for row in range(rows - 1, -1, -1):
        # dis.append( height * np.tan(1.*row*fov/rows + pan - 1.*fov/2))
        dis_ratio.append(np.tan(1.0 * row * fov / rows + pan - 1.0 * fov / 2) / np.tan(pan))

    return dis_ratio
コード例 #30
0
def KMatrixFun(N=0, O=0, h=12, day=173, iter=len(X)):
	KMatrix = KMatrixCrown = KMatrixHeight = np.zeros([iter, 2]) 
	KMatrixTot = np.zeros(iter)
	
	for i in xrange(iter):
		KMatrixCrown[i] = ([X[i], Y[i]]+np.dot(RM(np.radians(-(SolAziNBGW(h,day)-210)))/np.tan(SolElvNBGW(h,day)),[-CW[i]/200,HE[i]])-[N, O])/([X[i], Y[i]]+np.dot(RM(np.radians(-(SolAziNBGW(h,day)-210)))/np.tan(SolElvNBGW(h,day)),[-CW[i]/200,HE[i]-CH[i]])-[N, O])
		for j in xrange(2):
			if KMatrixCrown[i, j] <= 0:
				KMatrixCrown[i, j] = 0
			else:
				KMatrixCrown[i, j] = 1
	
		KMatrixHeight[i] = ([X[i], Y[i]]+np.dot(RM(np.radians(-(SolAziNBGW(h,day)-210)))/np.tan(SolElvNBGW(h,day)),[0,HE[i]])-[N, O])/([X[i], Y[i]]+np.dot(RM(np.radians(-(SolAziNBGW(h,day)-210)))/np.tan(SolElvNBGW(h,day)),[0,HE[i]-CH[i]])-[N, O])
		for j in xrange(2):
			if KMatrixHeight[i, j] <= 0:
				KMatrixHeight[i, j] = 0
			else:
				KMatrixHeight[i, j] = 1
			
		KMatrix[i] = KMatrixHeight[i]+KMatrixCrown[i]
		KMatrixTot[i] = KMatrix[i,0]+KMatrix[i,1]
		
	for i in xrange(iter):
		if KMatrixTot[i] <= 0:
			KMatrixTot[i] = 0
		else:
			KMatrixTot[i] = 1
	
	if (iter - KMatrixTot.sum()) <= 0:
		KMatrixTotTot = 1
	else:
		KMatrixTotTot = 0
	
	return KMatrixTotTot
コード例 #31
0
    def step(self):
        # Unpack the state and actions.
        # -----------------------------
        # Want to ignore the previous value of omegadd; it could only cause a
        # bug if we assign to it.

        (theta, thetad, omega, omegad, _, xf, yf, xb, yb, psi) = self.sensors
        (T, d) = self.actions

        # For recordkeeping.
        # ------------------
        if self._save_wheel_contact_trajectories:
            self.xfhist.append(xf)
            self.yfhist.append(yf)
            self.xbhist.append(xb)
            self.ybhist.append(yb)

        # Intermediate time-dependent quantities.
        # ---------------------------------------
        # Avoid divide-by-zero, just as Randlov did.
        if theta == 0:
            rf = 1e8
            rb = 1e8
            rCM = 1e8
        else:
            rf = self.L / np.abs(sin(theta))
            rb = self.L / np.abs(tan(theta))
            rCM = sqrt((self.L - self.c)**2 + self.L**2 / tan(theta)**2)

        phi = omega + np.arctan(d / self.h)

        # Equations of motion.
        # --------------------
        # Second derivative of angular acceleration:
        omegadd = 1 / self.Itot * (
            self.M * self.h * self.g * sin(phi) - cos(phi) *
            (self.Idc * self.sigmad * thetad + sign(theta) * self.v**2 *
             (self.Md * self.r *
              (1.0 / rf + 1.0 / rb) + self.M * self.h / rCM)))
        thetadd = (T - self.Idv * self.sigmad * omegad) / self.Idl

        # Integrate equations of motion using Euler's method.
        # ---------------------------------------------------
        # yt+1 = yt + yd * dt.
        # Must update omega based on PREVIOUS value of omegad.
        omegad += omegadd * self.time_step
        omega += omegad * self.time_step
        thetad += thetadd * self.time_step
        theta += thetad * self.time_step

        # Handlebars can't be turned more than 80 degrees.
        theta = np.clip(theta, -1.3963, 1.3963)

        # Wheel ('tyre') contact positions.
        # ---------------------------------

        # Front wheel contact position.
        front_temp = self.v * self.time_step / (2 * rf)
        # See Randlov's code.
        if front_temp > 1:
            front_temp = sign(psi + theta) * 0.5 * np.pi
        else:
            front_temp = sign(psi + theta) * arcsin(front_temp)
        xf += self.v * self.time_step * -sin(psi + theta + front_temp)
        yf += self.v * self.time_step * cos(psi + theta + front_temp)

        # Rear wheel.
        back_temp = self.v * self.time_step / (2 * rb)
        # See Randlov's code.
        if back_temp > 1:
            back_temp = np.sign(psi) * 0.5 * np.pi
        else:
            back_temp = np.sign(psi) * np.arcsin(back_temp)
        xb += self.v * self.time_step * -sin(psi + back_temp)
        yb += self.v * self.time_step * cos(psi + back_temp)

        # Preventing numerical drift.
        # ---------------------------
        # Copying what Randlov did.
        current_wheelbase = sqrt((xf - xb)**2 + (yf - yb)**2)
        if np.abs(current_wheelbase - self.L) > 0.01:
            relative_error = self.L / current_wheelbase - 1.0
            xb += (xb - xf) * relative_error
            yb += (yb - yf) * relative_error

        # Update heading, psi.
        # --------------------
        delta_y = yf - yb
        if (xf == xb) and delta_y < 0.0:
            psi = np.pi
        else:
            if delta_y > 0.0:
                psi = arctan((xb - xf) / delta_y)
            else:
                psi = sign(xb - xf) * 0.5 * np.pi - arctan(delta_y / (xb - xf))

        self.sensors = np.array(
            [theta, thetad, omega, omegad, omegadd, xf, yf, xb, yb, psi])
コード例 #32
0
ファイル: math_utils.py プロジェクト: jameslehoux/yt
def get_perspective_matrix(fovy, aspect, z_near, z_far):
    """
    Given a field of view in radians, an aspect ratio, and a near
    and far plane distance, this routine computes the transformation matrix
    corresponding to perspective projection using homogenous coordinates.

    Parameters
    ----------
    fovy : scalar
        The angle in degrees of the field of view.

    aspect : scalar
        The aspect ratio of width / height for the projection.

    z_near : scalar
        The distance of the near plane from the camera.

    z_far : scalar
        The distance of the far plane from the camera.

    Returns
    -------
    persp_matrix : ndarray
        A new 4x4 2D array. Represents a perspective transformation
        in homogeneous coordinates. Note that this matrix does not
        actually perform the projection. After multiplying a 4D
        vector of the form (x_0, y_0, z_0, 1.0), the point will be
        transformed to some (x_1, y_1, z_1, w). The final projection
        is applied by performing a divide by w, that is
        (x_1/w, y_1/w, z_1/w, w/w). The matrix uses a row-major
        ordering, rather than the column major ordering typically
        used by OpenGL.

    Notes
    -----
    The usage of 4D homogeneous coordinates is for OpenGL and GPU
    hardware that automatically performs the divide by w operation.
    See the following for more details about the OpenGL perspective matrices.

    https://www.tomdalling.com/blog/modern-opengl/explaining-homogenous-coordinates-and-projective-geometry/
    http://www.songho.ca/opengl/gl_projectionmatrix.html

    """

    tan_half_fovy = np.tan(np.radians(fovy) / 2)

    result = np.zeros((4, 4), dtype="float32", order="C")
    # result[0][0] = 1 / (aspect * tan_half_fovy)
    # result[1][1] = 1 / tan_half_fovy
    # result[2][2] = - (z_far + z_near) / (z_far - z_near)
    # result[3][2] = -1
    # result[2][3] = -(2 * z_far * z_near) / (z_far - z_near)

    f = z_far
    n = z_near

    t = tan_half_fovy * n
    b = -t * aspect
    r = t * aspect
    l = -t * aspect

    result[0][0] = (2 * n) / (r - l)
    result[2][0] = (r + l) / (r - l)
    result[1][1] = (2 * n) / (t - b)
    result[1][2] = (t + b) / (t - b)
    result[2][2] = -(f + n) / (f - n)
    result[2][3] = -2 * f * n / (f - n)
    result[3][2] = -1

    return result
コード例 #33
0
ファイル: utils.py プロジェクト: eleurent/IGNite
 def y_x(x):
     return coords[1] - earth_radius * np.log(np.tan(x / 2 + np.pi / 4))
コード例 #34
0
ファイル: jiangyan2.py プロジェクト: sihanfei/control
def model_motion_delta(v, delta, Phi, l):
    M = [np.cos(Phi), np.sin(Phi), np.divide(np.tan(delta), l)]
    status = np.multiply(M, v)  # dX, dY, dPhi
    return status
コード例 #35
0
def mesh_geodesic_distances(mesh, sources, m=1.0):
    Lc = trimesh_cotangent_laplacian_matrix(mesh)

    key_index = mesh.key_index()
    vertices = mesh.get_vertices_attributes('xyz')
    faces = [[key_index[key] for key in mesh.face_vertices(fkey)]
             for fkey in mesh.faces()]

    V = array(vertices)
    F = array(faces, dtype=int)

    # Laplacian matrix with symmetric cotangent weights

    # W = empty(0)
    # I = empty(0, dtype=int)
    # J = empty(0, dtype=int)

    # for i1, i2, i3 in [(0, 1, 2), (1, 2, 0), (2, 0, 1)]:
    #     v1 = F[:, i1]
    #     v2 = F[:, i2]
    #     v3 = F[:, i3]

    #     e1 = V[v2] - V[v1]
    #     e2 = V[v3] - V[v1]

    #     cotan = 0.5 * sum(e1 * e2, axis=1) / normrow(cross(e1, e2)).ravel()

    #     W = append(W, cotan)
    #     I = append(I, v2)
    #     J = append(J, v3)

    #     W = append(W, cotan)
    #     I = append(I, v3)
    #     J = append(J, v2)

    # Lc = csr_matrix((W, (I, J)), shape=(V.shape[0], V.shape[0]))
    # Lc = Lc - spdiags(Lc * ones(V.shape[0]), 0, V.shape[0], V.shape[0])

    # Step I
    # Heat *u* is allowed to diffuse for a brief period of time (t)

    e01 = V[F[:, 1]] - V[F[:, 0]]
    e12 = V[F[:, 2]] - V[F[:, 1]]
    e20 = V[F[:, 0]] - V[F[:, 2]]

    normal = cross(e01, e12)
    A2 = normrow(normal)

    A3 = A2.ravel() / 6

    VA = zeros(V.shape[0])
    for i in (0, 1, 2):
        b = bincount(F[:, i], A3)
        VA[:len(b)] += b
    VA = spdiags(VA, 0, V.shape[0], V.shape[0])

    h = mean([normrow(e01), normrow(e12), normrow(e20)])
    t = m * h**2

    u0 = zeros(V.shape[0])
    u0[sources] = 1.0

    A = VA - t * Lc

    print(A.sum(axis=1))

    u = splu((VA - t * Lc).tocsc()).solve(u0)
    # u = spsolve(VA - t * Lc, u0)

    # A = VA - t * Lc
    # b = u0
    # u = spsolve(A.transpose().dot(A), A.transpose().dot(b))

    unit = normal / A2

    unit_e01 = cross(unit, e01)
    unit_e12 = cross(unit, e12)
    unit_e20 = cross(unit, e20)

    grad_u = (unit_e01 * u[F[:, 2], None] + unit_e12 * u[F[:, 0], None] +
              unit_e20 * u[F[:, 1], None]) / A2

    X = -grad_u / normrow(grad_u)

    div_X = zeros(V.shape[0])

    for i1, i2, i3 in [(0, 1, 2), (1, 2, 0), (2, 0, 1)]:
        v1 = F[:, i1]
        v2 = F[:, i2]
        v3 = F[:, i3]

        e1 = V[v2] - V[v1]
        e2 = V[v3] - V[v1]
        e0 = V[v3] - V[v2]

        a = 1 / tan(arccos(sum(normalizerow(-e2) * normalizerow(-e0), axis=1)))
        b = 1 / tan(arccos(sum(normalizerow(-e1) * normalizerow(+e0), axis=1)))

        div_X += bincount(v1,
                          0.5 *
                          (a * sum(e1 * X, axis=1) + b * sum(e2 * X, axis=1)),
                          minlength=V.shape[0])

    print(Lc.sum(axis=1))

    phi = splu(Lc.tocsc()).solve(div_X)
    # phi = spsolve(Lc, div_X)

    # A = Lc
    # b = div_X
    # phi = spsolve(A.transpose().dot(A), A.transpose().dot(b))

    phi -= phi.min()

    return phi
コード例 #36
0
def Calculate_Surface_Velocity(h, n, beta):

    a = 0.67
    b = np.tan(beta)**0.5 / n
    return b * h**a
コード例 #37
0
    def _get_new_base_nodes(self, rock_state):
        """
        Return an array (or scalar) of states for the newly uplifted bottom
        inner row.
        
        Examples
        --------
        >>> from landlab import HexModelGrid
        >>> from landlab.ca.hex_cts import HexCTS
        >>> from landlab.ca.celllab_cts import Transition
        >>> mg = HexModelGrid(5, 5, 1.0, orientation='vertical', shape='rect')
        >>> nsd = {}  # node state dict
        >>> for i in range(10):
        ...     nsd[i] = i
        >>> xnlist = []
        >>> xnlist.append(Transition((0,0,0), (1,1,0), 1.0, 'frogging'))
        >>> nsg = mg.add_zeros('node', 'node_state_grid')
        >>> ca = HexCTS(mg, nsd, xnlist, nsg)

        >>> lu = LatticeUplifter(opt_block_layer=True)
        >>> lu._get_new_base_nodes(rock_state=7)
        array([9, 9, 9])
        >>> lu.uplift_interior_nodes(ca, current_time=0.0, rock_state=7)
        >>> lu.node_state[:5]
        array([0, 9, 0, 9, 9])
        >>> lu = LatticeUplifter(opt_block_layer=True, block_layer_thickness=2,
        ... block_layer_dip_angle=90.0, layer_left_x=1.0)
        >>> lu._get_new_base_nodes(rock_state=7)
        array([9, 7, 9])
        >>> lu.uplift_interior_nodes(ca, current_time=0.0, rock_state=7)
        >>> lu.node_state[:5]
        array([0, 9, 0, 7, 9])
        >>> lu = LatticeUplifter(opt_block_layer=True, block_layer_thickness=1,
        ... block_layer_dip_angle=45.0, y0_top=-1.0)
        >>> lu._get_new_base_nodes(rock_state=7)
        array([9, 7, 9])
        >>> lu.uplift_interior_nodes(ca, current_time=0.0, rock_state=7)
        >>> lu.node_state[:5]
        array([0, 9, 0, 7, 9])
        """

        new_base_nodes = zeros(len(self.inner_base_row_nodes), dtype=int)

        if self.block_layer_dip_angle == 0.0:  # horizontal
            
            if self.cum_uplift < self.block_layer_thickness:
                new_base_nodes[:] = self.block_ID
            else:
                new_base_nodes[:] = rock_state

        elif self.block_layer_dip_angle == 90.0:  # vertical

            layer_right_x = self.layer_left_x + self.block_layer_thickness
            inside_layer = where(logical_and(
                    self.grid.x_of_node[self.inner_base_row_nodes] >= self.layer_left_x,
                    self.grid.x_of_node[self.inner_base_row_nodes] <= layer_right_x))[0]
            new_base_nodes[:] = rock_state
            new_base_nodes[inside_layer] = self.block_ID
        
        else:
            
            x = self.grid.x_of_node[self.inner_base_row_nodes]
            y = self.grid.y_of_node[self.inner_base_row_nodes]
            m = tan(pi * self.block_layer_dip_angle / 180.0)
            y_top = m * x + self.y0_top
            y_bottom = y_top - (self.block_layer_thickness 
                                / cos(pi * self.block_layer_dip_angle / 180.0))
            inside_layer = where(logical_and(y >= y_bottom, y <= y_top))
            new_base_nodes[:] = rock_state
            new_base_nodes[inside_layer] = self.block_ID
        
        return new_base_nodes
コード例 #38
0
ファイル: pyscript.py プロジェクト: heh15/Arp240
for thisFile in os.listdir(outfolder+'maps/'): 
	if 'local_0mom.fits' in thisFile: files_mod0.append(thisFile) 
	if 'local_1mom.fits' in thisFile: files_mod1.append(thisFile) 
	if 'local_2mom.fits' in thisFile: files_mod2.append(thisFile) 

norm0 = ImageNormalize(vmin=interval.get_limits(mom0)[0],vmax=interval.get_limits(mom0)[1], stretch=LinearStretch()) 
norm1 = ImageNormalize(vmin=interval.get_limits(mom1)[0],vmax=interval.get_limits(mom1)[1], stretch=LinearStretch()) 
norm2 = ImageNormalize(vmin=interval.get_limits(mom2)[0],vmax=interval.get_limits(mom2)[1], stretch=LinearStretch()) 
norm = [norm0, norm1, norm2] 
cmaps = [matplotlib.cm.jet,matplotlib.cm.jet,matplotlib.cm.jet] 
barlab = ['Intensity ('+bunit+')', 'V$_\mathrm{LOS}$ (km/s)', '$\sigma$ (km/s)'] 
titles = ['DATA', 'MODEL'] 
mapname = ['INTENSITY', 'VELOCITY', 'DISPERSION'] 

x = np.arange(0,xmax-xmin,0.1) 
y = np.tan(np.radians(phi-90))*(x-xcen)+ycen 
ext = [0,xmax-xmin,0, ymax-ymin] 

for k in range (len(files_mod0)): 
	mom0_mod = fits.open(outfolder+'/maps/'+files_mod0[k])[0].data[ymin:ymax+1,xmin:xmax+1] 
	mom1_mod = fits.open(outfolder+'/maps/'+files_mod1[k])[0].data[ymin:ymax+1,xmin:xmax+1] 
	mom2_mod = fits.open(outfolder+'/maps/'+files_mod2[k])[0].data[ymin:ymax+1,xmin:xmax+1] 
	to_plot = [[mom0,mom1,mom2],[mom0_mod,mom1_mod,mom2_mod]] 

	fig=plt.figure(figsize=(11.69,8.27), dpi=150) 
	fig_ratio = 11.69/8.27 
	nrows, ncols = 3, 2 
	x_len, y_len = 0.2, 0.2 
	x_sep, y_sep = 0.00,0.02 
	ax, ax_cb, bottom_corner = [], [], [0.1,0.7] 
	for i in range (nrows): 
コード例 #39
0
    s.enableFastPSFMode(True)
    s.enableRaytracing(False)
    s.enableIrradianceMode(False)
    s.enablePathTracing(False)

s.createBRDF('sun', 'sun.brdf', {})
s.createShape('sun', 'sphere.shp', {'radius': sun_radius})
s.createBody('sun', 'sun', 'sun', [])
s.setSunPower(8 * ua * ua * pi * 5.2 * 5.2 * vec4(1, 1, 1, 1))

s.createBRDF('hapke', 'hapke.brdf', {})
s.createMesh('asteroid', 'itokawa_f3145728.obj', 1e3)
s.setObjectElementBRDF('asteroid', 'asteroid', 'hapke')

s.setCameraFOVDeg(fov,
                  np.arctan(np.tan(fov / 360 * pi) * N[1] / N[0]) * 360 / pi)
s.setImageSize(N[0], N[1])


def gen_image(alpha, beta):
    Rcam = np.eye(3)
    s.setObjectPosition('camera', vec3(0, 0, 0))
    s.setObjectAttitude('camera', MatToQuat(Rcam))
    s.setObjectPosition('sun', pos_sun)
    s.setObjectPosition('asteroid', pos_target)
    R_ast = np.eye(3)
    R_ast = QuatToMat(quat(vec3(1, 0, 0), pi / 2)) @ R_ast
    R_ast = QuatToMat(quat(vec3(0, 1, 0), -pi / 2)) @ R_ast
    R_ast = QuatToMat(quat(vec3(0, 1, 0), -pi / 8)) @ R_ast
    R_ast = QuatToMat(quat(vec3(0, 0, 1), pi / 4)) @ R_ast
    R_ast = QuatToMat(quat(vec3(1, 0, 0), -pi / 3)) @ R_ast
コード例 #40
0
grasp_dataset = np.empty((0, 3))

grasp_path = "Data/plt_bigwhiteplate/box_pos"
g_key = '.pkl'
for g_dir_name, g_sub_dirs, g_files in sorted(os.walk(grasp_path)):
    for gf in sorted(g_files):
        if g_key == gf[-len(g_key):]:
            with open(os.path.join(g_dir_name, gf), 'rb') as f:
                ff = pickle.load(f, encoding='latin1')
bx = ff[0]
by = ff[1]
bz = ff[2]

dgx = ((gx - cy) - (bx - cy))
dgy = ((gy + cx) - (by + cx))
dgz = np.sqrt(dgx**2 + dgy**2) * np.tan(math.pi - gt)
n = np.sqrt(dgx**2 + dgy**2 + dgz**2)
#dgz = math.sqrt((gx-cy)**2+(gy+cx)**2) * tan(math.pi-gt)
#soa = np.array([[0, 0, 0.02, 0.05, 0.03, 0],
#                [0, 0, 0.3, 0.01, 0.03, 0]])
soa = np.array([[(gx - cy)[:9], (gy + cx)[:9],
                 (cz - gz)[:9], (-dgx / n / 50)[:9], (-dgy / n / 50)[:9],
                 (-dgz / n / 50)[:9]]])
soal = np.array([[(gx - cy)[9], (gy + cx)[9], (cz - gz)[9], -(dgx / n / 50)[9],
                  -(dgy / n / 50)[9], -(dgz / n / 50)[9]]])
#soal = soa
X, Y, Z, U, V, W = list(zip(*soa))[:][:][:]
Xl, Yl, Zl, Ul, Vl, Wl = list(zip(*soal))[:][:][:]

#グラフの枠を作っていく
fig = plt.figure()
コード例 #41
0
    def set_points_by_ends(self, start, end, buff=0, path_arc=0):
        # Find the right tip length and thickness
        vect = end - start
        length = max(np.linalg.norm(vect), 1e-8)
        thickness = self.thickness
        w_ratio = self.max_width_to_length_ratio / (thickness / length)
        if w_ratio < 1:
            thickness *= w_ratio

        tip_width = self.tip_width_ratio * thickness
        tip_length = tip_width / (2 * np.tan(self.tip_angle / 2))
        t_ratio = self.max_tip_length_to_length_ratio / (tip_length / length)
        if t_ratio < 1:
            tip_length *= t_ratio
            tip_width *= t_ratio

        # Find points for the stem
        if path_arc == 0:
            points1 = (length - tip_length) * np.array(
                [RIGHT, 0.5 * RIGHT, ORIGIN])
            points1 += thickness * UP / 2
            points2 = points1[::-1] + thickness * DOWN
        else:
            # Solve for radius so that the tip-to-tail length matches |end - start|
            a = 2 * (1 - np.cos(path_arc))
            b = -2 * tip_length * np.sin(path_arc)
            c = tip_length**2 - length**2
            R = (-b + np.sqrt(b**2 - 4 * a * c)) / (2 * a)

            # Find arc points
            points1 = OpenGLArc.create_quadratic_bezier_points(path_arc)
            points2 = np.array(points1[::-1])
            points1 *= R + thickness / 2
            points2 *= R - thickness / 2
            if path_arc < 0:
                tip_length *= -1
            rot_T = rotation_matrix_transpose(PI / 2 - path_arc, OUT)
            for points in points1, points2:
                points[:] = np.dot(points, rot_T)
                points += R * DOWN

        self.set_points(points1)
        # Tip
        self.add_line_to(tip_width * UP / 2)
        self.add_line_to(tip_length * LEFT)
        self.tip_index = len(self.points) - 1
        self.add_line_to(tip_width * DOWN / 2)
        self.add_line_to(points2[0])
        # Close it out
        self.append_points(points2)
        self.add_line_to(points1[0])

        if length > 0:
            # Final correction
            super().scale(length / self.get_length())

        self.rotate(angle_of_vector(vect) - self.get_angle())
        self.rotate(
            PI / 2 - np.arccos(normalize(vect)[2]),
            axis=rotate_vector(self.get_unit_vector(), -PI / 2),
        )
        self.shift(start - self.get_start())
        self.refresh_triangulation()
コード例 #42
0
def theta_to_eta(theta):
    try:
        eta = -np.log(np.tan(theta / 2.))
    except:
        eta = -np.log(np.tan((theta + np.pi) / 2.))
    return eta
コード例 #43
0
ファイル: ClaessBL_N.py プロジェクト: wholden/xrt
def align_beamline(beamLine,
                   hDiv=1.5e-3,
                   vDiv=2.5e-4,
                   nameVCMstripe='Rh',
                   pitch=None,
                   nameDCMcrystal='Si111',
                   bragg=None,
                   energy=9000.,
                   fixedExit=20.,
                   nameDiagnFoil='top-edge',
                   nameVFMcylinder='Rh',
                   heightVFM=None):

    beamLine.feMovableMaskLT.set_divergence(beamLine.sources[0],
                                            [-hDiv / 2, vDiv / 2])
    beamLine.feMovableMaskRB.set_divergence(beamLine.sources[0],
                                            [hDiv / 2, -vDiv / 2])
    print('for {0:.2f}h x {1:.2f}v mrad^2 divergence:'.format(
        hDiv * 1e3, vDiv * 1e3))
    print('full feMovableMaskLT.opening = [{0[0]:.3f}, {0[1]:.3f}]'.format(
        beamLine.feMovableMaskLT.opening))
    print('full feMovableMaskRB.opening = [{0[0]:.3f}, {0[1]:.3f}]'.format(
        beamLine.feMovableMaskRB.opening))
    print('half feMovableMaskLT.opening = [{0[0]:.3f}, {0[1]:.3f}]'.format(
        [op / 2 for op in beamLine.feMovableMaskLT.opening]))
    print('half feMovableMaskRB.opening = [{0[0]:.3f}, {0[1]:.3f}]'.format(
        [op / 2 for op in beamLine.feMovableMaskRB.opening]))

    beamLine.vfm.select_surface(nameVFMcylinder)
    p = raycing.distance_xy(beamLine.vfm.center, beamLine.sources[0].center)
    if pitch is None:
        sinPitch = beamLine.vfm.r * 1.5 / p
        pitch = float(np.arcsin(sinPitch))
    else:
        sinPitch = np.sin(pitch)
    beamLine.vfm.R = p / sinPitch

    beamLine.vcm.select_surface(nameVCMstripe)
    beamLine.vcm.pitch = pitch
    beamLine.vcm.set_jacks()
    p = raycing.distance_xy(beamLine.vcm.center, beamLine.sources[0].center)
    beamLine.vcm.R = 2. * p / sinPitch
    beamLine.vcm.get_orientation()
    print('VCM.p = {0:.1f}'.format(p))
    print('VCM.pitch = {0:.6f} mrad'.format(beamLine.vcm.pitch * 1e3))
    print('VCM.roll = {0:.6f} mrad'.format(beamLine.vcm.roll * 1e3))
    print('VCM.yaw = {0:.6f} mrad'.format(beamLine.vcm.yaw * 1e3))
    print('VCM.z = {0:.3f}'.format(beamLine.vcm.center[2]))
    print('VCM.R = {0:.0f}'.format(beamLine.vcm.R))
    print('VCM.dx = {0:.3f}'.format(beamLine.vcm.dx))
    print('VCM.jack1.zCalib = {0:.3f}'.format(beamLine.vcm.jack1Calib))
    print('VCM.jack2.zCalib = {0:.3f}'.format(beamLine.vcm.jack2Calib))
    print('VCM.jack3.zCalib = {0:.3f}'.format(beamLine.vcm.jack3Calib))
    print('VCM.tx1 = {0:.3f}'.format(beamLine.vcm.tx1[0]))
    print('VCM.tx2 = {0:.3f}'.format(beamLine.vcm.tx2[0]))

    p = raycing.distance_xy(beamLine.fsm2.center, beamLine.vcm.center)
    fsm2height = beamLine.height + p * np.tan(2 * pitch)

    beamLine.dcm.select_surface(nameDCMcrystal)
    p = raycing.distance_xy(beamLine.dcm.center, beamLine.vcm.center)
    beamLine.dcm.center[2] = beamLine.height + p * np.tan(2 * pitch)
    beamLine.dcm.set_jacks()
    aCrystal = beamLine.dcm.material[beamLine.dcm.surface.index(
        nameDCMcrystal)]
    dSpacing = aCrystal.d
    print('DCM.crystal = {0}'.format(nameDCMcrystal))
    print('DCM.dSpacing = {0:.6f} angsrom'.format(dSpacing))
    if bragg is None:
        theta = float(np.arcsin(rm.ch / (2 * dSpacing * energy)))
        bragg = theta + 2 * pitch
    else:
        theta = bragg - 2 * pitch
        energy = rm.ch / (2 * dSpacing * np.sin(theta))
    print('DCM.energy = {0:.3f} eV'.format(energy))
    print('DCM.bragg = {0:.6f} deg'.format(np.degrees(bragg)))
    print('DCM.realThetaAngle = DCM.bragg - 2*VCM.pitch = {0:.6f} deg'.format(
        np.degrees(theta)))
    beamLine.dcm.energy = energy
    beamLine.dcm.bragg = bragg
    p = raycing.distance_xy(beamLine.vfm.center, beamLine.vcm.center)
    if heightVFM is not None:
        fixedExit = (heightVFM - beamLine.height -
                     p * np.tan(2 * pitch)) * np.cos(2 * pitch)
    else:
        heightVFM = fixedExit / np.cos(2 * pitch) + \
            beamLine.height + p * np.tan(2 * pitch) + 0.5

    beamLine.heightVFM = heightVFM
    beamLine.dcm.fixedExit = fixedExit
    beamLine.dcm.cryst2perpTransl = \
        beamLine.dcm.fixedExit/2./np.cos(beamLine.dcm.bragg)
    beamLine.dcm.get_orientation()
    print('DCM.pitch = {0:.6f} mrad'.format(beamLine.dcm.pitch * 1e3))
    print('DCM.roll = {0:.6f} mrad'.format(beamLine.dcm.roll * 1e3))
    print('DCM.yaw = {0:.6f} mrad'.format(beamLine.dcm.yaw * 1e3))
    print('DCM.z = {0:.3f}'.format(beamLine.dcm.center[2]))
    print('DCM.fixedExit = {0:.3f}'.format(fixedExit))
    print('DCM.cryst2perpTransl = {0:.3f}'.format(
        beamLine.dcm.cryst2perpTransl))
    print('DCM.dx = {0:.3f}'.format(beamLine.dcm.dx))
    print('DCM.jack1.zCalib = {0:.3f}'.format(beamLine.dcm.jack1Calib))
    print('DCM.jack2.zCalib = {0:.3f}'.format(beamLine.dcm.jack2Calib))
    print('DCM.jack3.zCalib = {0:.3f}'.format(beamLine.dcm.jack3Calib))

    p = raycing.distance_xy(beamLine.vfm.center, beamLine.fsm3.center)
    fsm3height = heightVFM - p * np.tan(2 * pitch)

    p = raycing.distance_xy(
        beamLine.vfm.center,
        (beamLine.xbpm4foils.center[0], beamLine.xbpm4foils.center[1]))
    heightXBPM4 = heightVFM - p * np.tan(2 * pitch)
    beamLine.xbpm4foils.select_aperture(nameDiagnFoil, heightXBPM4)
    print('beamLine.xbpm4foils.zActuator = {0:.3f}'.format(
        beamLine.xbpm4foils.zActuator))

    beamLine.vfm.pitch = -pitch
    beamLine.vfm.center[2] = heightVFM - beamLine.vfm.hCylinder
    beamLine.vfm.set_jacks()
    #    beamLine.vfm.yaw = 50e-6
    beamLine.vfm.set_x_stages()
    beamLine.vfm.get_orientation()
    print('VFM.pitch = {0:.6f} mrad'.format(beamLine.vfm.pitch * 1e3))
    print('VFM.roll = {0:.6f} mrad'.format(beamLine.vfm.roll * 1e3))
    print('VFM.yaw = {0:.6f} mrad'.format(beamLine.vfm.yaw * 1e3))
    print('VFM.z = {0:.3f}'.format(beamLine.vfm.center[2]))
    print('VFM.R = {0:.0f}'.format(beamLine.vfm.R))
    print('VFM.r = {0:.3f}'.format(beamLine.vfm.r))
    print('VFM.dx = {0:.3f}'.format(beamLine.vfm.dx))
    print('VFM.jack1.zCalib = {0:.3f}'.format(beamLine.vfm.jack1Calib))
    print('VFM.jack2.zCalib = {0:.3f}'.format(beamLine.vfm.jack2Calib))
    print('VFM.jack3.zCalib = {0:.3f}'.format(beamLine.vfm.jack3Calib))
    print('VFM.tx1 = {0:.3f}'.format(beamLine.vfm.tx1[0]))
    print('VFM.tx2 = {0:.3f}'.format(beamLine.vfm.tx2[0]))

    beamLine.eh100To40Flange.center[2] = heightVFM
    print('eh100To40Flange.center[2] = {0:.3f}'.format(
        beamLine.eh100To40Flange.center[2]))

    beamLine.slitEH.opening[2] += heightVFM - beamLine.height
    beamLine.slitEH.opening[3] += heightVFM - beamLine.height
    beamLine.slitEH.set_optical_limits()

    print('fsm1.z = {0:.3f}'.format(beamLine.height))
    print('fsm2.z = {0:.3f}'.format(fsm2height))
    print('fsm3.z = {0:.3f}'.format(fsm3height))
    print('fsm4.z = {0:.3f}'.format(heightVFM))
コード例 #44
0
    def create_grid(self):
        """
        Domain is unit square. One fracture, centered on (0.5, 0.5), tilted 
        according to self.angle.

        """

        angle = self.angle

        corners = np.array([[0, 1, 1, 0], [0, 0, 1, 1], [0, 0, 0, 0]])

        # The fracture points always have x coordinates 0.2 and 0.8
        # The y-coordinates are set so that the fracture forms the prescribed angle with
        # the x-axis
        frac_pt = np.array(
            [[0.2, 0.8],
             [0.5 - 0.3 * np.tan(angle), 0.5 + 0.3 * np.tan(angle)], [0, 0]])

        nodes = np.hstack((corners, frac_pt))

        rows = np.array([
            [0, 1],
            [1, 5],
            [5, 0],
            [1, 2],
            [2, 5],
            [2, 4],
            [2, 3],
            [3, 0],
            [3, 4],
            [4, 0],
            [4, 5],
            [4, 5],
        ]).ravel()
        cols = np.vstack((np.arange(12), np.arange(12))).ravel("F")
        data = np.ones_like(rows)

        fn_2d = sps.coo_matrix((data, (rows, cols)), shape=(6, 12)).tocsc()
        rows = np.array([[0, 1, 2], [1, 3, 4], [4, 5, 10], [5, 6, 8],
                         [7, 8, 9], [2, 11, 9]]).ravel()
        cols = np.tile(np.arange(6), (3, 1)).ravel("F")
        data = np.array(
            [-1, -1, -1, 1, -1, -1, 1, -1, -1, -1, 1, -1, 1, 1, -1, 1, 1, 1])
        cf_2d = sps.coo_matrix((data, (rows, cols)), shape=(12, 6)).tocsc()

        g_2d = pp.Grid(2, nodes, fn_2d, cf_2d, "mock_2d_grid")
        g_2d.compute_geometry()

        fn_1d = sps.csc_matrix(np.array([[1, 0], [0, 1]]))
        cf_1d = sps.csc_matrix(np.array([[-1], [1]]))

        g_1d = pp.Grid(1, frac_pt, fn_1d, cf_1d, "mock_1d_grid")
        g_1d.compute_geometry()

        gb = pp.GridBucket()
        gb.add_nodes([g_2d, g_1d])

        # Construct mortar grid
        side_grids = {
            mortar_grid.LEFT_SIDE: g_1d.copy(),
            mortar_grid.RIGHT_SIDE: g_1d.copy(),
        }

        data = np.array([1, 1])
        row = np.array([0, 0])
        col = np.array([10, 11])
        face_cells_mortar = sps.coo_matrix(
            (data, (row, col)),
            shape=(g_1d.num_cells, g_2d.num_faces)).tocsc()

        mg = pp.MortarGrid(1, side_grids, face_cells_mortar)

        edge = (g_2d, g_1d)
        gb.add_edge(edge, face_cells_mortar)
        d = gb.edge_props(edge)

        d["mortar_grid"] = mg

        self.gb = gb
        self.Nd = 2

        self.g1 = g_1d
        self.g2 = g_2d
        self.edge = edge
        self.mg = mg
コード例 #45
0
    def _preprocess(self, data):
        preprocessed_data = {}
        filesDatas = []
        for k, v in data.items():
            for file_name, file_content in v.items():
                df = pd.read_csv(file_content)

                unique_clutter_index = [
                    2, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17, 18
                ]
                user_cols = [
                    'X', 'Y', 'Altitude', 'Building Height', 'Clutter Index'
                ]

                # add_norm
                df['hb'] = df['Height'] + df['Cell Altitude'] - df['Altitude']
                df['d'] = ((df['Cell X'] - df['X'])**2 +
                           (df['Cell Y'] - df['Y'])**2)**(1 / 2) * 0.001
                df['lgd'] = np.log10(df['d'] + 1)
                df['hv'] = df['hb'] - df['d'] * np.tan(
                    (df['Electrical Downtilt'] + df['Mechanical Downtilt']) *
                    np.pi / 180)
                df['len'] = df['d'] / np.cos(
                    (df['Electrical Downtilt'] + df['Mechanical Downtilt']) *
                    np.pi / 180)
                df['lghb'] = np.log10(df['hb'] + 1)

                # add angle
                df['theta'] = np.arccos(
                    (np.sin(df['Azimuth'] * np.pi / 180) *
                     (df['Y'] - df['Cell Y']) +
                     np.cos(df['Azimuth'] * np.pi / 180) *
                     (df['X'] - df['Cell X'])) / (np.sqrt(
                         np.sin(df['Azimuth'] * np.pi / 180)**2 +
                         np.cos(df['Azimuth'] * np.pi / 180)**2) * np.sqrt(
                             (df['X'] - df['Cell X'])**2 +
                             (df['Y'] - df['Cell Y'])**2))) / np.pi * 180

                # add_count
                for col in user_cols:
                    df[col + '_count'] = df[col].map(df[col].value_counts())

                # add_density
                df['n'] = len(df)
                df['area'] = (
                    (df['X'].quantile(0.97) - df['X'].quantile(0.03)) *
                    (df['Y'].quantile(0.97) - df['Y'].quantile(0.03)))
                df['density'] = df['n'] / df['area']

                # add_index
                cell_clutter_dummy = pd.get_dummies(pd.Categorical(
                    df['Cell Clutter Index'], categories=unique_clutter_index),
                                                    prefix='CellClutterIndex')
                clutter_dummy = pd.get_dummies(pd.Categorical(
                    df['Clutter Index'], categories=unique_clutter_index),
                                               prefix='ClutterIndex')
                df = (df.merge(cell_clutter_dummy,
                               left_index=True,
                               right_index=True).merge(clutter_dummy,
                                                       left_index=True,
                                                       right_index=True))

                x_cols = [
                    col for col in df.columns if col not in [
                        'Cell Index', 'Cell Clutter Index', 'Clutter Index',
                        'RSRP'
                    ]
                ]
                df = df.fillna(df.mean())
                input_data = df[x_cols].values
                filesDatas.append(input_data)
        filesDatas = np.concatenate(filesDatas, axis=0)

        preprocessed_data['myInput'] = filesDatas.astype(np.float32)
        print('myInput.shape', filesDatas.shape)
        return preprocessed_data
コード例 #46
0
 def get_slope(self):
     return np.tan(self.get_angle())
コード例 #47
0
ファイル: calc.py プロジェクト: qed11/thernalDiff

def get_intersect(result, exp, i):
    #get interseciton of our values to the graph
    lol = abs(exp[i] - result)
    #print(np.amin(five_min))
    #print("min val",np.amin(lol))
    index = np.where(lol == np.amin(lol))
    return index[0][0]


if __name__ == '__main__':
    data = read('thernalDiff5\phaseDiff.txt')
    phi = data / times * 2 * np.pi * -1
    print("phi is", phi)
    ratio = np.tan(phi)  #tan(phi)
    print(ratio)

    a = np.linspace(0, 3, 100000)
    result = fnc.bei(a) / fnc.ber(a)  #the bernoulli equations

    plt.plot(a, result)
    plt.ylim(-10, 10)
    index = []

    for i in range(len(ratio)):
        index.append(get_intersect(result, ratio, i))  #get interseciton

    x = a[index]
    print('x vals', x)
    #get x value
コード例 #48
0
ファイル: demo3.py プロジェクト: xcbdjazk/PY3
import numpy as np

arr = np.array([[5, 2, 3, 4], [2, 3, 4, 5]])

arr1 = np.array([0, 1, 2, 3])
# 做下面的内容必须长度,类型一致,才能进行运算
print(arr + arr1)
print(arr - arr1)

print(arr**2)

print(np.sin(arr))
print(np.cos(arr))
print(np.tan(arr))

print(arr < 2)
print(arr == 2)
# 矩阵乘法
print(np.dot(arr, arr1))

arr2 = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
print(arr2.dot(arr))
print(arr.dot(arr2))
コード例 #49
0
def getD8big_noBLI_subs():
    """
        returns substitution dic for a 777esque D8
        """

    sweep = 32.583  # [deg]
    VTsweep = 28.  #[deg]
    HTsweep = 33.  #[deg]
    M4a = .1025
    fan = 1.7
    lpc = 4.69
    hpc = 5.25

    #Min cruise mach number
    Mcruisemin = 0.84

    substitutions = {
        'N_{land}': 6.,
        'p_s': 81. * units('cm'),
        '\\theta_{db}': 0.366,
        'n_{eng}': 2.,
        'n_{vt}': 2.,
        'n_{aisle}': 2.,
        'W_{avg. pass}': 180. * units('lbf'),
        'W_{carry on}': 15. * units('lbf'),
        'W_{checked}': 40. * units('lbf'),
        'W_{fix}': 3000. * units('lbf'),
        'w_{aisle}': 0.51 * units('m'),
        'w_{seat}': 0.5 * units('m'),
        'w_{sys}': 0.1 * units('m'),
        'r_E': 1.,  # [TAS]
        'p_{\\lambda_{vt}}': 1.6,
        '\\lambda_{cone}': 0.3,  # [TAS]
        '\\rho_{cone}': 2700.,  #*units('kg/m^3'),  # [TAS]
        '\\rho_{bend}': 2700.,  #*units('kg/m^3'),  # [TAS]
        '\\rho_{floor}': 2700.,  #*units('kg/m^3'),  # [TAS]
        '\\rho_{skin}': 2700.,  #*units('kg/m^3'),  # [TAS]
        '\\sigma_{floor}': 30000. / 0.000145,  # [TAS] [Al]
        '\\sigma_{skin}': 15000. / 0.000145,  # [TAS] [Al]
        '\\sigma_{bend}': 30000. / 0.000145,  # [TAS] [Al]
        '\\tau_{floor}': 30000. / 0.000145,  # [TAS] [Al]
        'W\'\'_{floor}': 60.,  # [TAS]
        'W\'\'_{insul}': 22.,  # [TAS]
        'W\'_{window}': 145. * 3. * units('N/m'),  # [TAS]
        'V_{mn}': 133.76 * units('m/s'),
        'V_{ne}': 143.92 * units('m/s'),

        #BLI drag reduction factor
        'D_{reduct}': 1,

        # TASOPT Fuselage substitutions
        'l_{nose}': 29. * units('ft') *
        1.75,  #1.75 is estimated length increase factor from D8.2
        'f_{L_{total/wing}}': 1.179,

        # Fuselage subs
        'f_{seat}': 0.1,
        'W\'_{seat}': 1.,  # Seat weight determined by weight fraction instead
        'W_{cargo}':
        0.1 * units('N'),  # Cargo weight determined by W_{avg. pass_{total}}
        'W_{avg. pass_{total}}': 230. * units('lbf'),
        'f_{string}': 0.35,
        'h_{floor}': 5 * units('in'),
        ##                'R_{fuse}': 1.715*units('m'),
        ##                '\\Delta R_{fuse}': 0.43*units('m'),
        ##                'w_{db}': 0.93*units('m'),
        '\\Delta P_{over}': 8.382 * units('psi'),
        'SPR': 12.,

        # Power system and landing gear subs
        'f_{hpesys}': 0.01,  # [TAS]
        'f_{lgmain}': 0.04,  # [TAS]
        'f_{lgnose}': 0.01,  # [TAS]
        'f_{pylon}': 0.10,

        # Fractional weights
        'f_{fadd}': 0.2,  # [TAS]
        'f_{frame}': 0.25,  # [Philippe]
        'f_{lugg,1}': 0.4,  # [Philippe]
        'f_{lugg,2}': 0.4,  # [Philippe]
        'f_{padd}': 0.35,  # [TAS]
        'f_{hpesys}': 0.01,  # [TAS]
        'f_{lgmain}': 0.03,  # [TAS]
        'f_{lgnose}': 0.0075,  # [TAS]

        # Wing substitutions
        ##                'AR':15.749,
        ##                'b_{max}': 200.0 * 0.3048*units('m'),
        'C_{L_{w,max}}': 2.25 / (cos(sweep)**2),  # [TAS]
        '\\tan(\\Lambda)': tan(sweep * pi / 180.),
        '\\cos(\\Lambda)': cos(sweep * pi / 180.),
        '\\eta': 0.97,
        '\\rho_0': 1.225 * units('kg/m^3'),
        '\\rho_{fuel}': 817. * units('kg/m^3'),  # Kerosene [TASOPT]
        '\\tau_{max_w}': 0.15,
        'f_{wingfuel}': .5,
        'TipReduct': 1.0,

        # Wing fractional weights
        'FuelFrac': 0.9,
        'f_{flap}': 0.2,
        'f_{slat}': 0.0001,
        'f_{aileron}': 0.04,
        'f_{lete}': 0.1,
        'f_{ribs}': 0.15,
        'f_{spoiler}': 0.02,
        'f_{watt}': 0.03,

        # VT substitutions
        'A_{vt}': 2.2,
        'C_{D_{wm}}': 0.5,  # [2]
        'C_{L_{vt,max}}': 2.6,  # [TAS]
        'V_1': 70. * units('m/s'),
        '\\rho_{TO}': 1.225 * units('kg/m^3'),
        '\\tan(\\Lambda_{vt})': tan(VTsweep * pi / 180),
        'c_{l_{vt,EO}}': 0.5,  # [TAS]
        'e_{vt}': 0.8,
        # 'y_{eng}': 4.83*units('m'), # [3]
        'V_{land}': 72. * units('m/s'),
        '\\dot{r}_{req}': 0.00001,  # 10 deg/s/s yaw rate acceleration
        'N_{spar}': 1.,
        'f_{VT}': 0.4,
        '\\cos(\\Lambda_{vt})^3': cos(VTsweep * pi / 180.)**3,
        'c_{d_{fv}}': 0.0060,
        'c_{d_{pv}}': 0.0035,
        'V_{vt_{min}}': 0.03,

        # HT substitutions
        '\\alpha_{ht,max}': 2.5,
        'C_{L_{ht,max}}': 2.0,  # [TAS]
        'SM_{min}': 0.05,
        '\\Delta x_{CG}': 11.97 * units('ft'),
        'x_{CG_{min}}': 117.31 * units('ft'),
        'C_{L_{ht,fCG}}': 0.85,
        'f_{ht}': 0.3,
        '\\cos(\\Lambda_{ht})^3': cos(HTsweep * pi / 180.)**3,
        'c_{d_{fh}}': 0.0060,
        'c_{d_{ph}}': 0.0035,
        ##                'AR_{ht}': 12.,
        '\\lambda_{ht}': 0.3,
        '\\tan(\\Lambda_{ht})':
        tan(HTsweep * pi / 180.),  # tangent of HT sweep
        '\\lambda_{vt}': 0.3,

        #engine system subs
        'f_{pylon}': 0.12,
        'f_{eadd}': 0.1,

        # Cabin air substitutions in AircraftP

        #set the fuel reserve fraction
        'f_{fuel_{res}}': .05,

        # Minimum Cruise Mach Number
        'M_{min}': Mcruisemin,

        #new engine params
        '\pi_{tn}': .995,
        '\\pi_{b}': .94,
        '\\pi_{d}': .995,
        '\\pi_{fn}': .985,
        'T_{ref}': 288.15,
        'P_{ref}': 101.325,
        '\\eta_{HPshaft}': .978,
        '\\eta_{LPshaft}': .99,
        '\\eta_{B}': .985,
        '\\pi_{f_D}': fan,
        '\\pi_{hc_D}': hpc,
        '\\pi_{lc_D}': lpc,

        ##                '\\alpha_{OD}': 8.62,
        ##                '\\alpha_{max}': 8.62,     #place holder value not active during analysis
        'hold_{4a}': 1 + .5 * (1.313 - 1) * M4a**2,
        'r_{uc}': .01,
        '\\alpha_c': .156,
        'T_{t_f}': 435,
        'M_{takeoff}': .9539,
        'G_{f}': 1,
        'h_{f}': 43.003,
        'C_{p_{t1}}': 1257.3,
        'C_{p_{t2}}': 1158.35,
        'C_{p_{c}}': 1278.5,
        'HTR_{f_{SUB}}': 1 - .3**2,
        'HTR_{lpc_{SUB}}': 1 - 0.6**2,

        # engine system subs
        'r_{S_{nacelle}}': 12.,
        # nacelle drag calc parameter
        'r_{v_{nacelle}}': 1.02,
        'T_{t_{4.1_{max}}}': 1860. * units('K'),
    }

    return substitutions
コード例 #50
0
ファイル: sankey.py プロジェクト: MrKolt01/pythonLab
    def __init__(self, ax=None, scale=1.0, unit='', format='%G', gap=0.25,
                 radius=0.1, shoulder=0.03, offset=0.15, head_angle=100,
                 margin=0.4, tolerance=1e-6, **kwargs):
        """
        Create a new Sankey instance.

        The optional arguments listed below are applied to all subdiagrams so
        that there is consistent alignment and formatting.

        In order to draw a complex Sankey diagram, create an instance of
        :class:`Sankey` by calling it without any kwargs::

            sankey = Sankey()

        Then add simple Sankey sub-diagrams::

            sankey.add() # 1
            sankey.add() # 2
            #...
            sankey.add() # n

        Finally, create the full diagram::

            sankey.finish()

        Or, instead, simply daisy-chain those calls::

            Sankey().add().add...  .add().finish()

        Other Parameters
        ----------------
        ax : `~.axes.Axes`
            Axes onto which the data should be plotted.  If *ax* isn't
            provided, new Axes will be created.
        scale : float
            Scaling factor for the flows.  *scale* sizes the width of the paths
            in order to maintain proper layout.  The same scale is applied to
            all subdiagrams.  The value should be chosen such that the product
            of the scale and the sum of the inputs is approximately 1.0 (and
            the product of the scale and the sum of the outputs is
            approximately -1.0).
        unit : str
            The physical unit associated with the flow quantities.  If *unit*
            is None, then none of the quantities are labeled.
        format : str or callable
            A Python number formatting string or callable used to label the
            flows with their quantities (i.e., a number times a unit, where the
            unit is given). If a format string is given, the label will be
            ``format % quantity``. If a callable is given, it will be called
            with ``quantity`` as an argument.
        gap : float
            Space between paths that break in/break away to/from the top or
            bottom.
        radius : float
            Inner radius of the vertical paths.
        shoulder : float
            Size of the shoulders of output arrows.
        offset : float
            Text offset (from the dip or tip of the arrow).
        head_angle : float
            Angle, in degrees, of the arrow heads (and negative of the angle of
            the tails).
        margin : float
            Minimum space between Sankey outlines and the edge of the plot
            area.
        tolerance : float
            Acceptable maximum of the magnitude of the sum of flows.  The
            magnitude of the sum of connected flows cannot be greater than
            *tolerance*.
        **kwargs
            Any additional keyword arguments will be passed to :meth:`add`,
            which will create the first subdiagram.

        See Also
        --------
        Sankey.add
        Sankey.finish

        Examples
        --------
        .. plot:: gallery/specialty_plots/sankey_basics.py
        """
        # Check the arguments.
        if gap < 0:
            raise ValueError(
                "'gap' is negative, which is not allowed because it would "
                "cause the paths to overlap")
        if radius > gap:
            raise ValueError(
                "'radius' is greater than 'gap', which is not allowed because "
                "it would cause the paths to overlap")
        if head_angle < 0:
            raise ValueError(
                "'head_angle' is negative, which is not allowed because it "
                "would cause inputs to look like outputs and vice versa")
        if tolerance < 0:
            raise ValueError(
                "'tolerance' is negative, but it must be a magnitude")

        # Create axes if necessary.
        if ax is None:
            import matplotlib.pyplot as plt
            fig = plt.figure()
            ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[])

        self.diagrams = []

        # Store the inputs.
        self.ax = ax
        self.unit = unit
        self.format = format
        self.scale = scale
        self.gap = gap
        self.radius = radius
        self.shoulder = shoulder
        self.offset = offset
        self.margin = margin
        self.pitch = np.tan(np.pi * (1 - head_angle / 180.0) / 2.0)
        self.tolerance = tolerance

        # Initialize the vertices of tight box around the diagram(s).
        self.extent = np.array((np.inf, -np.inf, np.inf, -np.inf))

        # If there are any kwargs, create the first subdiagram.
        if len(kwargs):
            self.add(**kwargs)
コード例 #51
0
    def __execute_basket_weaving(self):
        ###
        # Basket-Weaving (Emerson & Grave 1988)
        ###
        casalog.post('Apply Basket-Weaving')

        # CAS-5410 Use private tools inside task scripts
        ia = gentools(['ia'])[0]

        # initial setup
        outimage = ia.newimagefromimage(infile=self.infiles[0],
                                        outfile=self.outfile,
                                        overwrite=self.overwrite)
        imshape_out = outimage.shape()
        ndim_out = len(imshape_out)
        coordsys = outimage.coordsys()
        axis_types = coordsys.axiscoordinatetypes()
        # direction axis should always exist
        try:
            direction_axis0 = axis_types.index('Direction')
            direction_axis1 = axis_types[direction_axis0 + 1:].index(
                'Direction') + direction_axis0 + 1
        except IndexError:
            raise RuntimeError('Direction axes don\'t exist.')
        nx = imshape_out[direction_axis0]
        ny = imshape_out[direction_axis1]
        tmp = []
        nfile = len(self.infiles)
        for i in xrange(nfile):
            tmp.append(numpy.zeros(imshape_out, dtype=float))
        maskedpixel = numpy.array(tmp)
        del tmp

        # direction
        dirs = []
        if len(self.direction) == nfile:
            dirs = self.direction
        else:
            casalog.post('direction information is extrapolated.')
            for i in range(nfile):
                dirs.append(self.direction[i % len(self.direction)])

        # maskwidth
        masks = []
        if isinstance(self.maskwidth, int) or isinstance(
                self.maskwidth, float):
            for i in range(nfile):
                masks.append(self.maskwidth)
        elif isinstance(self.maskwidth,
                        list):  #  and nfile != len(self.maskwidth):
            for i in range(nfile):
                masks.append(self.maskwidth[i % len(self.maskwidth)])
        for i in range(len(masks)):
            masks[i] = 0.01 * masks[i]

        # mask
        for i in range(nfile):
            self.realimage = create_4d_image(self.infiles[i],
                                             self.tmprealname[i])
            self.imagimage = self.realimage.subimage(
                outfile=self.tmpimagname[i])

            # replace masked pixels with 0.0
            if not self.realimage.getchunk(getmask=True).all():
                casalog.post(
                    "Replacing masked pixels with 0.0 in %d-th image" % (i))
                self.realimage.replacemaskedpixels(0.0)
            self.realimage.close()
            self.imagimage.close()

        # Below working images are all 4D regardless of dimension of input images
        # image shape for temporary images (always 4D)
        ia.open(self.tmprealname[0])
        imshape = ia.shape()
        ndim = len(imshape)
        ia.close()

        if len(self.thresh) == 0:
            casalog.post('Use whole region')
        else:
            for i in range(nfile):
                self.realimage = ia.newimage(self.tmprealname[i])
                for iaxis2 in range(imshape[2]):
                    for iaxis3 in range(imshape[3]):
                        pixmsk = self.realimage.getchunk(
                            [0, 0, iaxis2, iaxis3],
                            [nx - 1, ny - 1, iaxis2, iaxis3])
                        for ix in range(pixmsk.shape[0]):
                            for iy in range(pixmsk.shape[1]):
                                if self.thresh[0] == self.nolimit:
                                    if pixmsk[ix][iy] > self.thresh[1]:
                                        maskedpixel[i][ix][iy][iaxis2][
                                            iaxis3] = pixmsk[ix][iy]
                                        pixmsk[ix][iy] = 0.0
                                elif self.thresh[1] == self.nolimit:
                                    if pixmsk[ix][iy] < self.thresh[0]:
                                        maskedpixel[i][ix][iy][iaxis2][
                                            iaxis3] = pixmsk[ix][iy]
                                        pixmsk[ix][iy] = 0.0
                                else:
                                    if pixmsk[ix][iy] < self.thresh[
                                            0] or pixmsk[ix][iy] > self.thresh[
                                                1]:
                                        maskedpixel[i][ix][iy][iaxis2][
                                            iaxis3] = pixmsk[ix][iy]
                                        pixmsk[ix][iy] = 0.0
                        self.realimage.putchunk(pixmsk, [0, 0, iaxis2, iaxis3])
                self.realimage.close()
        maskedvalue = None
        if any(maskedpixel.flatten() != 0.0):
            maskedvalue = maskedpixel.mean(axis=0)
        del maskedpixel

        # set weight factor
        weights = numpy.ones(shape=(nfile, nx, ny), dtype=float)
        eps = 1.0e-5
        dtor = numpy.pi / 180.0
        for i in range(nfile):
            scan_direction = ''
            if abs(numpy.sin(
                    dirs[i] * dtor)) < eps:  # direction is around 0 deg
                maskw = 0.5 * nx * masks[i]
                scan_direction = 'horizontal'
            elif abs(numpy.cos(
                    dirs[i] * dtor)) < eps:  # direction is around 90 deg
                maskw = 0.5 * ny * masks[i]
                scan_direction = 'vertical'
            else:
                maskw = 0.5 * numpy.sqrt(nx * ny) * masks[i]
            for ix in range(nx):
                halfwx = (nx - 1) / 2
                for iy in range(ny):
                    halfwy = (ny - 1) / 2
                    if scan_direction == 'horizontal':
                        #dd = abs(float(ix) - 0.5*(nx-1))
                        dd = abs(float(ix) - halfwx)  # for CAS-9434
                    elif scan_direction == 'vertical':
                        #dd = abs(float(iy) - 0.5*(ny-1))
                        dd = abs(float(iy) - halfwy)  # for CAS-9434
                    else:
                        tand = numpy.tan((dirs[i] - 90.0) * dtor)
                        #dd = abs((float(ix) - 0.5*(nx-1)) * tand - (float(iy) - 0.5*(ny-1)))
                        dd = abs((float(ix) - halfwx) * tand -
                                 (float(iy) - halfwy))  # for CAS-9434
                        dd = dd / numpy.sqrt(1.0 + tand * tand)
                    if dd < maskw:
                        cosd = numpy.cos(0.5 * numpy.pi * dd / maskw)
                        weights[i][ix][iy] = 1.0 - cosd * cosd
                    if weights[i][ix][iy] == 0.0:
                        weights[i][ix][iy] += eps * 0.01
            """
            if abs(numpy.sin(dirs[i]*dtor)) < eps:
                # direction is around 0 deg
                maskw = 0.5 * nx * masks[i] 
                for ix in range(nx):
                    for iy in range(ny):
                        dd = abs( float(ix) - 0.5 * (nx-1) )
                        if dd < maskw:
                            cosd = numpy.cos(0.5*numpy.pi*dd/maskw)
                            weights[i][ix][iy] = 1.0 - cosd * cosd
                        if weights[i][ix][iy] == 0.0:
                            weights[i][ix][iy] += eps*0.01
            elif abs(numpy.cos(dirs[i]*dtor)) < eps:
                # direction is around 90 deg
                maskw = 0.5 * ny * masks[i]
                for ix in range(nx):
                    for iy in range(ny):
                        dd = abs( float(iy) - 0.5 * (ny-1) )
                        if dd < maskw:
                            cosd = numpy.cos(0.5*numpy.pi*dd/maskw)
                            weights[i][ix][iy] = 1.0 - cosd * cosd
                        if weights[i][ix][iy] == 0.0:
                            weights[i][ix][iy] += eps*0.01
            else:
                maskw = 0.5 * numpy.sqrt( nx * ny ) * masks[i]
                for ix in range(nx):
                    for iy in range(ny):
                        tand = numpy.tan((dirs[i]-90.0)*dtor)
                        dd = abs( ix * tand - iy - 0.5 * (nx-1) * tand + 0.5 * (ny-1) )
                        dd = dd / numpy.sqrt( 1.0 + tand * tand )
                        if dd < maskw:
                            cosd = numpy.cos(0.5*numpy.pi*dd/maskw)
                            weights[i][ix][iy] = 1.0 - cosd * cosd
                        if weights[i][ix][iy] == 0.0:
                            weights[i][ix][iy] += eps*0.01 
            """
            # shift
            xshift = -((ny - 1) / 2)
            yshift = -((nx - 1) / 2)
            for ix in range(xshift, 0, 1):
                tmp = weights[i, :, 0].copy()
                weights[i, :, 0:ny - 1] = weights[i, :, 1:ny].copy()
                weights[i, :, ny - 1] = tmp
            for iy in range(yshift, 0, 1):
                tmp = weights[i, 0:1].copy()
                weights[i, 0:nx - 1] = weights[i, 1:nx].copy()
                weights[i, nx - 1:nx] = tmp

        # FFT
        for i in range(nfile):
            self.realimage = ia.newimage(self.tmprealname[i])
            self.imagimage = ia.newimage(self.tmpimagname[i])
            for iaxis2 in range(imshape[2]):
                for iaxis3 in range(imshape[3]):
                    pixval = self.realimage.getchunk(
                        [0, 0, iaxis2, iaxis3],
                        [nx - 1, ny - 1, iaxis2, iaxis3])
                    pixval = pixval.reshape((nx, ny))
                    pixfft = npfft.fft2(pixval)
                    pixfft = pixfft.reshape((nx, ny, 1, 1))
                    self.realimage.putchunk(pixfft.real,
                                            [0, 0, iaxis2, iaxis3])
                    self.imagimage.putchunk(pixfft.imag,
                                            [0, 0, iaxis2, iaxis3])
                    del pixval, pixfft
            self.realimage.close()
            self.imagimage.close()

        # weighted mean
        for ichan in range(imshape[2]):
            for iaxis3 in range(imshape[3]):
                pixout = numpy.zeros(shape=(nx, ny), dtype=complex)
                denom = numpy.zeros(shape=(nx, ny), dtype=float)
                for i in range(nfile):
                    self.realimage = ia.newimage(self.tmprealname[i])
                    self.imagimage = ia.newimage(self.tmpimagname[i])
                    pixval = self.realimage.getchunk( [0,0,ichan,iaxis3], [nx-1,ny-1,ichan,iaxis3] ) \
                        + self.imagimage.getchunk( [0,0,ichan,iaxis3], [nx-1,ny-1,ichan,iaxis3] ) * 1.0j
                    pixval = pixval.reshape((nx, ny))
                    pixout = pixout + pixval * weights[i]
                    denom = denom + weights[i]
                    self.realimage.close()
                    self.imagimage.close()
                pixout = pixout / denom
                pixout = pixout.reshape((nx, ny, 1, 1))
                self.realimage = ia.newimage(self.tmprealname[0])
                self.imagimage = ia.newimage(self.tmpimagname[0])
                self.realimage.putchunk(pixout.real, [0, 0, ichan, iaxis3])
                self.imagimage.putchunk(pixout.imag, [0, 0, ichan, iaxis3])
                self.realimage.close()
                self.imagimage.close()

        # inverse FFT
        self.realimage = ia.newimage(self.tmprealname[0])
        self.imagimage = ia.newimage(self.tmpimagname[0])
        for ichan in range(imshape[2]):
            for iaxis3 in range(imshape[3]):
                pixval = self.realimage.getchunk( [0,0,ichan,iaxis3], [nx-1,ny-1,ichan,iaxis3] ) \
                    + self.imagimage.getchunk( [0,0,ichan,iaxis3], [nx-1,ny-1,ichan,iaxis3] ) * 1.0j
                pixval = pixval.reshape((nx, ny))
                pixifft = npfft.ifft2(pixval)
                pixifft = pixifft.reshape((nx, ny, 1, 1))
                self.realimage.putchunk(pixifft.real,
                                        blc=[0, 0, ichan, iaxis3])
                del pixval, pixifft
        if maskedvalue is not None:
            self.realimage.putchunk(self.realimage.getchunk() + maskedvalue)

        # put result into outimage
        chunk = self.realimage.getchunk()
        outimage.putchunk(chunk.reshape(imshape_out))
        # handling of output image mask
        maskstr = ""
        for name in self.infiles:
            if len(maskstr) > 0: maskstr += " || "
            maskstr += ("mask('%s')" % (name))
        outimage.calcmask(maskstr, name="basketweaving", asdefault=True)

        self.realimage.close()
        self.imagimage.close()
        outimage.close()
コード例 #52
0
def extract_and_publish_contours(self):
    if OPENCV_VERSION == 2:
        contours, hierarchy = cv2.findContours(self.threshed,
                                               cv2.RETR_EXTERNAL,
                                               cv2.CHAIN_APPROX_NONE)
    elif OPENCV_VERSION == 3:
        image, contours, hierarchy = cv2.findContours(self.threshed,
                                                      cv2.RETR_EXTERNAL,
                                                      cv2.CHAIN_APPROX_NONE)
    # http://docs.opencv.org/trunk/doc/py_tutorials/py_imgproc/py_contours/py_contour_features/py_contour_features.html

    try:
        header = Header(stamp=self.framestamp, frame_id=str(self.framenumber))
    except:
        header = Header(stamp=None, frame_id=str(self.framenumber))
        print 'could not get framestamp, run tracker_nobuffer instead'

    contour_info = []
    coords_and_area = set()
    for contour in contours:
        # Large objects are approximated by an ellipse
        # TODO break fitting into func and make recursive?
        if len(contour) >= 5:
            x, y, ecc, area, angle = fit_ellipse_to_contour(self, contour)
            coords_and_area.add((x, y, area))

            # if object is too large, split it in two, this helps with colliding objects, but is not 100% correct
            if area > self.params['max_expected_area']:
                slope = np.tan(angle)
                intercept = y - slope * x
                c1 = []
                c2 = []
                for point in contour:
                    point = point.reshape(2)
                    if is_point_below_line(point, slope, intercept):
                        c1.append([point])
                    else:
                        c2.append([point])
                c1 = np.array(c1)
                c2 = np.array(c2)

                if len(c1) >= 5:
                    x, y, ecc, area, angle = fit_ellipse_to_contour(
                        self, np.array(c1))
                    if area < self.params['max_size'] and area > self.params[
                            'min_size']:
                        data = add_data_to_contour_info(
                            x, y, ecc, area, angle, self.dtCamera, header)
                        contour_info.append(data)

                if len(c2) >= 5:
                    x, y, ecc, area, angle = fit_ellipse_to_contour(
                        self, np.array(c2))
                    if area < self.params['max_size'] and area > self.params[
                            'min_size']:
                        data = add_data_to_contour_info(x, y, ecc , area, angle, \
                            self.dtCamera, header)
                        contour_info.append(data)
            else:
                if area < self.params['max_size'] and area > self.params[
                        'min_size']:
                    data = add_data_to_contour_info(x, y, ecc, area, angle,
                                                    self.dtCamera, header)
                    contour_info.append(data)

        # Small ones just get a point
        else:
            area = 0

    # publish the contours
    self.pubContours.publish(Contourlist(header=header, contours=contour_info))
    return coords_and_area
コード例 #53
0
while row_d<=12:
    alpha=data[row_d,1]
    row_p=0
    while row_p<=1475429: #depends on the number of patches
        x=int(patch[row_p,2]-1)
        y=int(patch[row_p,3]-1)
        z1=int(patch[row_p,4])
        z=int(zz[z1])
        nx=patch[row_p,6]
        ny=patch[row_p,7]
        nz=patch[row_p,8]
        if alpha>0 and alpha<90:
            if nx==-1 or ny==1 or nz==1:
                x2=x-1
                while x2>=0:
                    y2=int(y+(x-x2)/(np.tan(np.deg2rad(90-alpha))))
                    if x2>=0 and x2<=1199 and y2<=799 and y2>=0:       #depends on the limit of domain
                        h2=a[x2,y2]
                    if x2<0 or x2>1199 or y2<0 or y2>799:
                        h2=0
                    eletangle1=np.degrees(np.arctan((h2-z)/np.sqrt(((x2-x)*10)**2+((y2-y)*10)**2)))
                    if eletangle1>=data[row_d,2]:
                        break
                    x2-=1
                if x2==-1:
                    print "{:>2}{:>5}{:>10}{:>2}{:>2}".format(int(data[row_d,0]),101,int(patch[row_p,1]),1,1)
                else:
                    print "{:>2}{:>5}{:>10}{:>2}{:>2}".format(int(data[row_d,0]),101,int(patch[row_p,1]),0,0)
            if nx==1 or ny==-1:
                print "{:>2}{:>5}{:>10}{:>2}{:>2}".format(int(data[row_d,0]),101,int(patch[row_p,1]),0,0)
        if alpha>270 and alpha<360:
コード例 #54
0
def tdl(x):
    y = 8./x
    return np.tan(x) - np.sqrt(y*y-1.0)
コード例 #55
0
def t(x):
    ''' tangent of angle in radians'''
    return np.tan(x)
コード例 #56
0
ファイル: TestNet1.py プロジェクト: iamcurrent/Net
def getMix1():
    res = []
    t = np.linspace(0, 10, 640)
    s1 = np.sin(2 * np.pi * 450 * t)
    s2 = np.cos(2 * np.pi * 400 * t)
    noise = np.tan(2 * np.pi * 400 * t)
    mix = 0.2 * s1 + 0.8 * s2
    res.append(mix)
    res.append(s1)
    res.append(s2)
    mix = np.reshape(mix, (1, len(mix)))
    s1 = np.reshape(s1, (1, len(s1)))
    s2 = np.reshape(s2, (1, len(s2)))
    x = []
    y1 = []
    y2 = []

    scope = []
    angle = []

    sco1 = []
    sco2 = []

    ang1 = []
    ang2 = []

    ##构造数据集
    for i in range(0, len(mix[0]) - timestep, int(timestep / 2)):
        sp = mix[0, i:i + timestep]
        spfft = np.fft.fft(sp)
        A = np.abs(spfft)
        ang = 180 * np.angle(spfft) / np.pi
        scope.append(np.reshape(A, (1, len(A))))
        angle.append(np.reshape(ang, (1, len(ang))))

        ss1 = s1[0, i:i + timestep]
        s1fft = np.fft.fft(ss1)
        A = np.abs(s1fft)
        ang = 180 * np.angle(s1fft) / np.pi
        sco1.append(np.reshape(A, (1, len(A))))
        ang1.append(np.reshape(ang, (1, len(ang))))

        ss2 = s2[0, i:i + timestep]
        s2fft = np.fft.fft(ss2)
        A = np.abs(s2fft)
        ang = 180 * np.angle(s2fft) / np.pi

        sco2.append(np.reshape(A, (1, len(A))))
        ang2.append(np.reshape(ang, (1, len(ang))))

    c = len(scope)
    s = sc.fit_transform(scope[0])
    d1 = []
    d2 = []
    d3 = []
    d4 = []
    d5 = []
    d6 = []
    for i in range(c):
        d1.append(sc.transform(scope[i]))
        d2.append(sc.transform(angle[i]))
        d3.append(sc.transform(sco1[i]))
        d4.append(sc.transform(sco2[i]))
        d5.append(sc.transform(ang1[i]))
        d6.append(sc.transform(ang2[i]))
    x_train1 = np.reshape(d1, (c, timestep, 1))
    x_train2 = np.reshape(d2, (c, timestep, 1))
    y_train1 = np.reshape(d3, (c, timestep, 1))
    y_train2 = np.reshape(d4, (c, timestep, 1))
    y_train3 = np.reshape(d5, (c, timestep, 1))
    y_train4 = np.reshape(d6, (c, timestep, 1))
    return (x_train1, x_train2), (y_train1, y_train2, y_train3, y_train4), res
コード例 #57
0
ファイル: SPM.py プロジェクト: liulimin90/pySPM
 def get_shadow_mask(self, angle, BIN=None, pb=False):
     if BIN is not None:
         BIN = BIN * 1.0
     slope = np.tan(np.radians(angle))
     neg = False
     if slope < 0:
         neg = True
         slope = -slope
         topo = np.fliplr(self.pixels)
         if BIN is not None:
             BIN = np.fliplr(BIN)
     else:
         topo = self.pixels
     x = np.linspace(0, self.size['real']['x'], self.pixels.shape[1])
     if self.size['real']['unit'] == 'um':
         x *= 1e-6
     elif self.size['real']['unit'] == 'nm':
         x *= 1e-9
     mask = np.zeros(self.pixels.shape)
     AFM_bin_shadow = np.zeros(self.pixels.shape)
     Y = range(self.pixels.shape[0])
     if pb:
         Y = tqdm(Y)
     for yi in Y:
         for xi in range(self.pixels.shape[1]):
             cut = self.pixels.shape[1] - 2
             y_ray = slope * (x - x[xi]) + topo[yi, xi]
             while cut > xi and y_ray[cut] > topo[yi, cut]:
                 cut -= 1
             if xi == cut:
                 if BIN is not None:
                     AFM_bin_shadow[yi, xi] = BIN[yi, xi]
                 continue
             # Cut has been found
             if BIN is not None:
                 x1 = x[cut]
                 x2 = x[cut + 1]
                 y1 = topo[yi, cut]
                 y2 = topo[yi, cut + 1]
                 x0 = x[xi]
                 y0 = topo[yi, xi]
                 if y2 == y1:
                     x_cut = (y1 + slope * x0 - y0) / slope
                     y_cut = y1
                 else:
                     numerator = x1 / (x2 - x1) + (y0 - slope * x0 -
                                                   y1) / (y2 - y1)
                     denominator = 1 / (x2 - x1) - slope / (y2 - y1)
                     x_cut = numerator / denominator
                     y_cut = slope * (x_cut - x0) + y0
                 if x_cut >= x1 and x_cut <= x2:
                     y1 = BIN[yi, cut]
                     y2 = BIN[yi, cut + 1]
                     yint = (((y2 - y1) / (x2 - x1)) * (x_cut - x1)) + y1
                 else:
                     yint = BIN[yi, xi]
                 AFM_bin_shadow[yi, xi] = yint
             mask[yi, xi] = 1
     if neg:
         mask = np.fliplr(mask)
         AFM_bin_shadow = np.fliplr(AFM_bin_shadow)
     if BIN is not None:
         return (mask, AFM_bin_shadow)
     return mask
コード例 #58
0
    def update(self):

        # diam - diamond thickness
        # ds - seat thickness
        # r1 - small radius
        # r2 - large radius
        # tilt - tilting angle of DAC
        dtor = np.pi / 180.0

        diam = self._diamond_thickness
        ds = self._seat_thickness
        r1 = self._small_cbn_seat_radius
        r2 = self._large_cbn_seat_radius
        tilt = -self._tilt * dtor
        tilt_rotation = self._tilt_rotation * dtor + np.pi / 2
        center_offset_angle = self._center_offset_angle * dtor

        two_theta = self._tth_array * dtor
        azi = self._azi_array * dtor

        # calculate radius of the cone for each pixel specific to a center_offset and rotation angle
        if self._center_offset != 0:
            beta = azi - np.arcsin(self._center_offset * np.sin(
                (np.pi -
                 (azi + center_offset_angle))) / r1) + center_offset_angle
            r1 = np.sqrt(r1**2 + self._center_offset**2 -
                         2 * r1 * self._center_offset * np.cos(beta))
            r2 = np.sqrt(r2**2 + self._center_offset**2 -
                         2 * r2 * self._center_offset * np.cos(beta))

        # defining rotation matrices for the diamond anvil cell
        Rx = np.matrix([[1, 0, 0],
                        [0, np.cos(tilt_rotation), -np.sin(tilt_rotation)],
                        [0, np.sin(tilt_rotation),
                         np.cos(tilt_rotation)]])

        Ry = np.matrix([[np.cos(tilt), 0, np.sin(tilt)], [0, 1, 0],
                        [-np.sin(tilt), 0, np.cos(tilt)]])

        dac_vector = np.array(Rx * Ry * np.matrix([1, 0, 0]).T)

        # calculating a diffraction vector for each pixel
        diffraction_vec = np.array([
            np.cos(two_theta),
            np.cos(azi) * np.sin(two_theta),
            np.sin(azi) * np.sin(two_theta)
        ])

        # angle between diffraction vector and diamond anvil cell vector based on dot product:
        tt = np.arccos(dot_product(dac_vector, diffraction_vec) / \
                       (vector_len(dac_vector) * vector_len(diffraction_vec)))

        # calculate path through diamond its absorption
        path_diamond = diam / np.cos(tt)
        abs_diamond = np.exp(-path_diamond / self._diamond_abs_length)

        # define the different regions for the absorption in the seat
        # region 2 is partial absorption (in the cone) and region 3 is complete absorbtion
        ts1 = np.arctan(r1 / diam)
        ts2 = np.arctan(r2 / (diam + ds))
        tseat = np.arctan((r2 - r1) / ds)

        region2 = np.logical_and(tt > ts1, tt < ts2)
        region3 = tt >= ts2

        # calculate the paths through each region
        path_seat = np.zeros(tt.shape)
        if self._center_offset != 0:
            deltar = diam * np.tan(tt[region2]) - r1[region2]
            alpha = np.pi / 2. - tseat[region2]
            gamma = np.pi - (alpha + tt[region2] + np.pi / 2)
        else:
            deltar = diam * np.tan(tt[region2]) - r1
            alpha = np.pi / 2. - tseat
            gamma = np.pi - (alpha + tt[region2] + np.pi / 2)

        path_seat[region2] = deltar * np.sin(alpha) / np.sin(gamma)
        path_seat[region3] = ds / np.cos(tt[region3])

        abs_seat = np.exp(-path_seat / self._seat_abs_length)

        # combine both, diamond and seat absorption correction
        self._data = abs_diamond * abs_seat
コード例 #59
0
ファイル: bicycle.py プロジェクト: Kanghyun-Kim/jupyrobo
 def bicycle_rear_axle(self, state, v, gamma):
     #state : x, y, theta
     x, y, theta = state
     delta = np.array([v*np.cos(theta), v*np.sin(theta), v/self.L*np.tan(gamma)])
     next_state = state + delta  * self.dt
     return next_state
コード例 #60
0
ファイル: sim_hardware.py プロジェクト: nad-dch/sotodlib
def sim_telescope_detectors(hw, tele, tube_slots=None):
    """Generate detector properties for a telescope.

    Given a Hardware model, generate all detector properties for the specified
    telescope and optionally a subset of optics tube slots (for the LAT).

    Args:
        hw (Hardware): The hardware object to use.
        tele (str): The telescope name.
        tube_slots (list, optional): The optional list of tube slots to include.

    Returns:
        (OrderedDict): The properties of all selected detectors.

    """
    zaxis = np.array([0, 0, 1], dtype=np.float64)
    thirty = np.pi / 6.0
    # The properties of this telescope
    teleprops = hw.data["telescopes"][tele]
    platescale = teleprops["platescale"]
    fwhm = teleprops["fwhm"]

    # The tubes
    alltubes = teleprops["tube_slots"]
    ntube = len(alltubes)
    if tube_slots is None:
        tube_slots = alltubes
    else:
        for t in tube_slots:
            if t not in alltubes:
                raise RuntimeError("Invalid tube_slot '{}' for telescope '{}'"
                                   .format(t, tele))

    alldets = OrderedDict()
    if ntube == 1:
        # This is a SAT.  We have one tube at the center.
        tubeprops = hw.data["tube_slots"][tube_slots[0]]
        waferspace = tubeprops["waferspace"]

        shift = waferspace * platescale * np.pi / 180.0
        wcenters = [
            np.array([0.0, 0.0, 0.0]),
            np.array([shift * np.cos(thirty), shift * np.sin(thirty), 0.0]),
            np.array([0.0, shift, 0.0]),
            np.array([-shift * np.cos(thirty), shift * np.sin(thirty), 0.0]),
            np.array([-shift * np.cos(thirty), -shift * np.sin(thirty), 0.0]),
            np.array([0.0, -shift, 0.0]),
            np.array([shift * np.cos(thirty), -shift * np.sin(thirty), 0.0])
        ]
        centers = ang_to_quat(wcenters)

        windx = 0
        for wafer_slot in tubeprops["wafer_slots"]:
            dets = sim_wafer_detectors(hw, wafer_slot, platescale, fwhm,
                                       center=centers[windx])
            alldets.update(dets)
            windx += 1
    else:
        # This is the LAT.  Compute the tube centers.
        # Rotate each tube by 90 degrees, so that it is pointed "down".
        tubespace = teleprops["tubespace"]
        tuberot = 90.0 * np.ones(19, dtype=np.float64)
        tcenters = hex_layout(19, 4 * (tubespace * platescale), rotate=tuberot)

        tindx = 0
        for tube_slot in tube_slots:
            tubeprops = hw.data["tube_slots"][tube_slot]
            waferspace = tubeprops["waferspace"]
            location = tubeprops["location"]

            wradius = 0.5 * (waferspace * platescale * np.pi / 180.0)
            wcenters = [
                np.array([np.tan(thirty) * wradius, wradius, 0.0]),
                np.array([-wradius / np.cos(thirty), 0.0, 0.0]),
                np.array([np.tan(thirty) * wradius, -wradius, 0.0])
            ]
            qwcenters = ang_to_quat(wcenters)
            centers = list()
            for qwc in qwcenters:
                centers.append(qa.mult(tcenters[location], qwc))

            windx = 0
            for wafer_slot in tubeprops["wafer_slots"]:
                dets = sim_wafer_detectors(hw, wafer_slot, platescale, fwhm,
                                           center=centers[windx])
                alldets.update(dets)
                windx += 1
            tindx += 1
    return alldets