Example #1
0
    def test_radians(self):

        q1 = np.deg2rad(180. * u.degree)
        assert_allclose(q1.value, np.pi)
        assert q1.unit == u.radian

        q2 = np.radians(180. * u.degree)
        assert_allclose(q2.value, np.pi)
        assert q2.unit == u.radian

        # the following doesn't make much sense in terms of the name of the
        # routine, but we check it gives the correct result.
        q3 = np.deg2rad(3. * u.radian)
        assert_allclose(q3.value, 3.)
        assert q3.unit == u.radian

        q4 = np.radians(3. * u.radian)
        assert_allclose(q4.value, 3.)
        assert q4.unit == u.radian

        with pytest.raises(TypeError):
            np.deg2rad(3. * u.m)

        with pytest.raises(TypeError):
            np.radians(3. * u.m)
Example #2
0
def key_callback(window, key, scancode, action, mods):
   global gCamAng
   if action==glfw.PRESS or action==glfw.REPEAT:
      if key==glfw.KEY_1:
         gCamAng += np.radians(-10)
      elif key==glfw.KEY_3:
         gCamAng += np.radians(10)
    def get_synthetic_data_dict(self):
        data_dict = {}
        data_dict['x'] = np.linspace(-70, 470, 200)
        data_dict['y'] = np.linspace(10, 340, 100)
        data_dict['z'] = np.array([-0, -3, -10, -25, -100])
        # Make a horizontal slice
        xg, yg = np.meshgrid(data_dict['x'], data_dict['y'])
        slice1 = np.ma.array(np.cos(np.radians(xg)) +
                             np.sin(np.radians(yg)))
        # Add some holes
        slice1[0:40, 50:60] = np.nan
        slice1[40:60, 100:120] = np.nan
        slice1[20:22, 30:32] = np.nan
        slice1 = np.ma.masked_invalid(slice1)

        # Make another horizontal slice ("below") with more holes
        slice2 = slice1*1.1
        slice2[70:80, 20:28] = np.nan
        
        # Add a 2D and a 3D variable to dictionary
        data_dict['var2d'] = slice1
        data_dict['var3d'] = np.ma.array([slice1, slice2, 1.2*slice1,
                                          1*3*slice1, 10*slice1])
        data_dict['time'] = datetime.now()

        # Generate some points
        x = np.linspace(data_dict['x'].min(), data_dict['x'].max(), 100)
        y = np.linspace(data_dict['y'].min(), data_dict['y'].max(), 100)
        z = np.linspace(data_dict['z'].min(), data_dict['z'].max(), 100)

        return data_dict, x, y, z
Example #4
0
def great_circle(**kwargs):
    """
        Named arguments:
        distance  = distance to travel, or numpy array of distances
        azimuth   = angle, in DEGREES of HEADING from NORTH, or numpy array of azimuths
        latitude  = latitude, in DECIMAL DEGREES, or numpy array of latitudes
        longitude = longitude, in DECIMAL DEGREES, or numpy array of longitudes
        rmajor    = radius of earth's major axis. default=6378137.0 (WGS84)
        rminor    = radius of earth's minor axis. default=6356752.3142 (WGS84)

        Returns a dictionary with:
        'latitude' in decimal degrees
        'longitude' in decimal degrees
        'reverse_azimuth' in decimal degrees

    """

    distance  = kwargs.pop('distance')
    azimuth   = np.radians(kwargs.pop('azimuth'))
    latitude  = np.radians(kwargs.pop('latitude'))
    longitude = np.radians(kwargs.pop('longitude'))
    rmajor    = kwargs.pop('rmajor', 6378137.0)
    rminor    = kwargs.pop('rminor', 6356752.3142)
    f         = (rmajor - rminor) / rmajor

    vector_pt = np.vectorize(vinc_pt)
    lat_result, lon_result, angle_result = vector_pt(f, rmajor,
                                                     latitude,
                                                     longitude,
                                                     azimuth,
                                                     distance)
    return {'latitude': np.degrees(lat_result),
            'longitude': np.degrees(lon_result),
            'reverse_azimuth': np.degrees(angle_result)}
    def testNativeLonLatVector(self):
        """
        Test that nativeLonLatFromRaDec works in a vectorized way; we do this
        by performing a bunch of tansformations passing in ra and dec as numpy arrays
        and then comparing them to results computed in an element-wise way
        """

        obs = ObservationMetaData(pointingRA=123.0, pointingDec=43.0, mjd=53467.2)

        raPoint = 145.0
        decPoint = -35.0

        nSamples = 100
        np.random.seed(42)
        raList = np.random.random_sample(nSamples)*360.0
        decList = np.random.random_sample(nSamples)*180.0 - 90.0

        lonList, latList = nativeLonLatFromRaDec(raList, decList, obs)

        for rr, dd, lon, lat in zip(raList, decList, lonList, latList):
            lonControl, latControl = nativeLonLatFromRaDec(rr, dd, obs)
            distance = arcsecFromRadians(haversine(np.radians(lon), np.radians(lat),
                                                   np.radians(lonControl), np.radians(latControl)))

            self.assertLess(distance, 0.0001)
Example #6
0
def spherical_to_cartesian(lons, lats, depths):
    """
    Return the position vectors (in Cartesian coordinates) of list of spherical
    coordinates.

    For equations see: http://mathworld.wolfram.com/SphericalCoordinates.html.

    Parameters are components of spherical coordinates in a form of scalars,
    lists or numpy arrays. ``depths`` can be ``None`` in which case it's
    considered zero for all points.

    :returns:
        ``numpy.array`` of 3d vectors representing points' coordinates in
        Cartesian space. The array has the same shape as parameter arrays.
        In particular it means that if ``lons`` and ``lats`` are scalars,
        the result is a single 3d vector. Vector of length ``1`` represents
        distance of 1 km.

    See also :func:`cartesian_to_spherical`.
    """
    phi = numpy.radians(lons)
    theta = numpy.radians(lats)
    if depths is None:
        rr = EARTH_RADIUS
    else:
        rr = EARTH_RADIUS - numpy.array(depths)
    cos_theta_r = rr * numpy.cos(theta)
    xx = cos_theta_r * numpy.cos(phi)
    yy = cos_theta_r * numpy.sin(phi)
    zz = rr * numpy.sin(theta)
    vectors = numpy.array([xx.transpose(), yy.transpose(), zz.transpose()]) \
                   .transpose()
    return vectors
Example #7
0
    def from_parameters(a, b, c, alpha, beta, gamma):
        """
        Create a Lattice using unit cell lengths and angles (in degrees).

        Args:
            a (float): *a* lattice parameter.
            b (float): *b* lattice parameter.
            c (float): *c* lattice parameter.
            alpha (float): *alpha* angle in degrees.
            beta (float): *beta* angle in degrees.
            gamma (float): *gamma* angle in degrees.

        Returns:
            Lattice with the specified lattice parameters.
        """

        alpha_r = radians(alpha)
        beta_r = radians(beta)
        gamma_r = radians(gamma)
        val = (np.cos(alpha_r) * np.cos(beta_r) - np.cos(gamma_r))\
            / (np.sin(alpha_r) * np.sin(beta_r))
        #Sometimes rounding errors result in values slightly > 1.
        val = val if abs(val) <= 1 else val / abs(val)
        gamma_star = np.arccos(val)
        vector_a = [a * np.sin(beta_r), 0.0, a * np.cos(beta_r)]
        vector_b = [-b * np.sin(alpha_r) * np.cos(gamma_star),
                    b * np.sin(alpha_r) * np.sin(gamma_star),
                    b * np.cos(alpha_r)]
        vector_c = [0.0, 0.0, float(c)]
        return Lattice([vector_a, vector_b, vector_c])
Example #8
0
    def __init__(self, fname):

# Assuming basic format, with sky motion including PA
# 00243              [H= 9.94]
# Date       UT      R.A. (J2000) Decl.    Delta     r     El.    Ph.   V      Sky Motion       Uncertainty info
#            h m s                                                            "/min    P.A.    3-sig/" P.A.
# 2017 09 10 000000 12 43 00.8 -05 24 35   3.810   2.927   24.8   8.3  15.8    0.96    113.1       N/A   N/A / Map / Offsets
#....
        data = numpy.loadtxt(fname, dtype={
            'names': ('year', 'month', 'day', 'hms', 'ra_h', 'ra_m', 'ra_s', 'dec_d', 'dec_m', 'dec_s', 'delta', 'r', 'el', 'ph', 'V', 'sky', 'PA', 'uncerr'),
            'formats': ('i4', 'i2', 'i2', 'S6', 'i2', 'i2', 'f4', 'i2', 'i2', 'i2', 'f4', 'f4', 'f4', 'f4', 'f4', 'f4', 'f4', 'S20')
        })

        self.data = numpy.array(
            [(
                numpy.datetime64('{0}-{1:>02}-{2:>02}T{3}:{4}:{5}.00'.format(year, month, day, hms[:2].decode('u8'), hms[2:4].decode('u8'), hms[4:6].decode('u8'))),
                ra_h + ra_m / 60.0 + ra_s / 3600.0,
                dec_d + dec_m / 60.0 + dec_s / 3600.0,
                sky * numpy.sin(numpy.radians(PA)),
                sky * numpy.cos(numpy.radians(PA)),
                V
            ) for year, month, day, hms, ra_h, ra_m, ra_s, dec_d, dec_m, dec_s, delta, r, el, ph, V, sky, PA, uncerr in data],
            dtype=[
                ('date', 'datetime64[ms]'),
                ('ra', 'f4'),
                ('dec', 'f4'),
                ('ra_motion', 'f4'),
                ('dec_motion', 'f4'),
                ('V', 'f4')
            ]
        )
Example #9
0
    def __init__(self, end_effector_length):
        # create joint limit dicts
        self.joint_lim_dict = {}
        self.joint_lim_dict["right_arm"] = {
            "max": np.radians([120.00, 122.15, 77.5, 144.0, 122.0, 45.0, 45.0]),
            "min": np.radians([-47.61, -20.0, -77.5, 0.0, -80.0, -45.0, -45.0]),
        }

        self.joint_lim_dict["left_arm"] = {
            "max": np.radians([120.00, 20.0, 77.5, 144.0, 80.0, 45.0, 45.0]),
            "min": np.radians([-47.61, -122.15, -77.5, 0.0, -122.0, -45.0, -45.0]),
        }

        end_effector_length += 0.0135 + 0.04318  # add wrist linkange and FT sensor lengths
        self.setup_kdl_mekabot(end_effector_length)
        q_guess_pkl_l = (
            os.environ["HOME"]
            + "/svn/gt-ros-pkg/hrl/hrl_arm_control/hrl_cody_arms/src/hrl_cody_arms/q_guess_left_dict.pkl"
        )
        q_guess_pkl_r = (
            os.environ["HOME"]
            + "/svn/gt-ros-pkg/hrl/hrl_arm_control/hrl_cody_arms/src/hrl_cody_arms/q_guess_right_dict.pkl"
        )

        self.q_guess_dict_left = ut.load_pickle(q_guess_pkl_l)
        self.q_guess_dict_right = ut.load_pickle(q_guess_pkl_r)
Example #10
0
def j2000tob1950(ra, dec):
    """
    Convert J2000 to B1950 coordinates.

    This routine was derived by taking the inverse of the b1950toj2000 routine
    """

    # Convert to radians
    ra = np.radians(ra)
    dec = np.radians(dec)

    # Convert RA, Dec to rectangular coordinates
    x = np.cos(ra) * np.cos(dec)
    y = np.sin(ra) * np.cos(dec)
    z = np.sin(dec)

    # Apply the precession matrix
    x2 = P2[0, 0] * x + P2[1, 0] * y + P2[2, 0] * z
    y2 = P2[0, 1] * x + P2[1, 1] * y + P2[2, 1] * z
    z2 = P2[0, 2] * x + P2[1, 2] * y + P2[2, 2] * z

    # Convert the new rectangular coordinates back to RA, Dec
    ra = np.arctan2(y2, x2)
    dec = np.arcsin(z2)

    # Convert to degrees
    ra = np.degrees(ra)
    dec = np.degrees(dec)

    # Make sure ra is between 0. and 360.
    ra = np.mod(ra, 360.0)
    dec = np.mod(dec + 90.0, 180.0) - 90.0

    return ra, dec
Example #11
0
def b1950toj2000(ra, dec):
    """
    Convert B1950 to J2000 coordinates.

    This routine is based on the technique described at
    http://www.stargazing.net/kepler/b1950.html
    """

    # Convert to radians
    ra = np.radians(ra)
    dec = np.radians(dec)

    # Convert RA, Dec to rectangular coordinates
    x = np.cos(ra) * np.cos(dec)
    y = np.sin(ra) * np.cos(dec)
    z = np.sin(dec)

    # Apply the precession matrix
    x2 = P1[0, 0] * x + P1[1, 0] * y + P1[2, 0] * z
    y2 = P1[0, 1] * x + P1[1, 1] * y + P1[2, 1] * z
    z2 = P1[0, 2] * x + P1[1, 2] * y + P1[2, 2] * z

    # Convert the new rectangular coordinates back to RA, Dec
    ra = np.arctan2(y2, x2)
    dec = np.arcsin(z2)

    # Convert to degrees
    ra = np.degrees(ra)
    dec = np.degrees(dec)

    # Make sure ra is between 0. and 360.
    ra = np.mod(ra, 360.0)
    dec = np.mod(dec + 90.0, 180.0) - 90.0

    return ra, dec
Example #12
0
    def update(self):

        if not self.targetFrame:
            return

        r = self.properties.getProperty("Distance (m)")
        theta = np.radians(90 - self.properties.getProperty("Elevation (deg)"))
        phi = np.radians(180 - self.properties.getProperty("Azimuth (deg)"))

        x = r * np.cos(phi) * np.sin(theta)
        y = r * np.sin(phi) * np.sin(theta)
        z = r * np.cos(theta)

        c = self.camera
        targetToWorld = self.targetFrame.transform

        currentPosition = np.array(c.GetPosition())
        desiredPosition = np.array(targetToWorld.TransformPoint([x, y, z]))

        smoothTime = self.properties.getProperty("Smooth Time (s)")

        newPosition, self.currentVelocity = smoothDamp(
            currentPosition, desiredPosition, self.currentVelocity, smoothTime, maxSpeed=100, deltaTime=self.dt
        )

        trackerToWorld = transformUtils.getLookAtTransform(targetToWorld.GetPosition(), newPosition)

        c.SetFocalPoint(targetToWorld.GetPosition())
        c.SetPosition(trackerToWorld.GetPosition())
        self.view.render()
Example #13
0
    def xy2lonlat(self, x, y):
        """Calculate x,y in own projection from given lon,lat (scalars/arrays).
        """
        if self.projected is True:
            if self.proj.is_latlong():
                return x, y
            else:
                if 'ob_tran' in self.proj4:
                    logging.info('NB: Converting degrees to radians ' +
                                 'due to ob_tran srs')
                    x = np.radians(np.array(x))
                    y = np.radians(np.array(y))
                return self.proj(x, y, inverse=True)
        else:
            np.seterr(invalid='ignore')  # Disable warnings for nan-values
            y = np.atleast_1d(np.array(y))
            x = np.atleast_1d(np.array(x))

            # NB: mask coordinates outside domain
            x[x < self.xmin] = np.nan
            x[x > self.xmax] = np.nan
            y[y < self.ymin] = np.nan
            y[y < self.ymin] = np.nan

            lon = map_coordinates(self.lon, [y, x], order=1,
                                  cval=np.nan, mode='nearest')
            lat = map_coordinates(self.lat, [y, x], order=1,
                                  cval=np.nan, mode='nearest')
            return (lon, lat)
Example #14
0
def fnc(ra, *args):
    """
    Function used in the minimisation problem.

    :param ra:
        Semi-axis of the ellipses used in the Yu et al.
    :returns:
        The absolute difference between the epicentral distance and the
        adjusted distance
    """
    #
    # epicentral distance
    repi = args[0]
    #
    # azimuth
    theta = args[1]
    #
    # magnitude
    mag = args[2]
    #
    # coefficients
    coeff = args[3]
    #
    # compute the difference between epicentral distances
    rb = rbf(ra, coeff, mag)
    t1 = ra**2 * (np.sin(np.radians(theta)))**2
    t2 = rb**2 * (np.cos(np.radians(theta)))**2
    xx = ra * rb / (t1+t2)**0.5
    return xx-repi
Example #15
0
 def draw_scater(self, sw_list):
     """
     Descript. : draws data collection item on the scatter
                 subwedge is represented as list:
                 collection_id, sw_id, first_image, num_images, 
                 osc_start, osc_full_range
     """
     self.axes.clear()
     col_count = 0
     for sw_index, sw in enumerate(sw_list):
         bars = self.axes.bar(
             np.radians(sw[4]), 1, width=np.radians(sw[5]), bottom=sw[0], color=Qt4_widget_colors.TASK_GROUP[sw[0]]
         )
         x_mid = bars[0].get_bbox().xmin + (bars[0].get_bbox().xmax - bars[0].get_bbox().xmin) / 2.0
         y_mid = bars[0].get_bbox().ymin + (bars[0].get_bbox().ymax - bars[0].get_bbox().ymin) / 2.0
         self.axes.text(
             x_mid,
             y_mid,
             "%d (%d:%d)" % (sw_index + 1, sw[0] + 1, sw[1] + 1),
             horizontalalignment="center",
             verticalalignment="center",
             weight="bold",
         )
         if sw[0] > col_count:
             col_count = sw[0]
     self.axes.set_yticks(np.arange(1, col_count + 2))
     self.fig.canvas.draw_idle()
Example #16
0
    def get_equation_of_time(self):
        """ calculates the equation of time in minutes """

        if not self.equation_of_time == None:
            return self.equation_of_time

        if self.oblique_corr == None:
            self.get_oblique_corr()

        if self.geomean_long == None:
            self.get_geomean_long()

        if self.geomean_anom == None:
            self.get_geomean_anom()

        if self.earth_eccent == None:
            self.get_earth_eccent()

        oc = radians(self.oblique_corr)
        gml = radians(self.geomean_long)
        gma = radians(self.geomean_anom)
        ec = self.earth_eccent

        vary = tan(oc / 2) ** 2

        self.equation_of_time = 4 * degrees(
            vary * sin(2 * gml)
            - 2 * ec * sin(gma)
            + 4 * ec * vary * sin(gma) * cos(2 * gml)
            - 0.5 * vary * vary * sin(4 * gml)
            - 1.25 * ec * ec * sin(2 * gma)
        )

        return self.equation_of_time
Example #17
0
    def _get_delta_tdb_tt(self, jd1=None, jd2=None):
        if not hasattr(self, '_delta_tdb_tt'):
            # If jd1 and jd2 are not provided (which is the case for property
            # attribute access) then require that the time scale is TT or TDB.
            # Otherwise the computations here are not correct.
            if jd1 is None or jd2 is None:
                if self.scale not in ('tt', 'tdb'):
                    raise ValueError('Accessing the delta_tdb_tt attribute '
                                     'is only possible for TT or TDB time '
                                     'scales')
                else:
                    jd1 = self._time.jd1
                    jd2 = self._time.jd2

            # First go from the current input time (which is either
            # TDB or TT) to an approximate UTC.  Since TT and TDB are
            # pretty close (few msec?), assume TT.
            njd1, njd2 = sofa_time.tt_tai(jd1, jd2)
            njd1, njd2 = sofa_time.tai_utc(njd1, njd2)
            # TODO: actually need to go to UT1 which needs DUT.
            ut = njd1 + njd2

            # Compute geodetic params needed for d_tdb_tt()
            phi = np.radians(self.lat)
            elon = np.radians(self.lon)
            xyz = sofa_time.iau_gd2gc(1, elon, phi, 0.0)
            u = np.sqrt(xyz[0] ** 2 + xyz[1] ** 2)
            v = xyz[2]

            self._delta_tdb_tt = sofa_time.d_tdb_tt(jd1, jd2, ut, elon, u, v)

        return self._delta_tdb_tt
Example #18
0
    def beam(self, feed, freq):
        """Beam for a particular feed.
        
        Parameters
        ----------
        feed : integer
            Index for the feed.
        freq : integer
            Index for the frequency.
        
        Returns
        -------
        beam : np.ndarray
            A Healpix map (of size self._nside) of the beam. Potentially
            complex.
        """

        if self._bc_freq != freq or self._bc_nside != self._nside:
            sigma = np.radians(self.fwhm) / (8.0*np.log(2.0))**0.5 / (self.frequencies[freq] / 150.0)

            pointing = np.array([np.pi / 2.0 - np.radians(self.pointing), self.zenith[1]])

            x2 = (1.0 - coord.sph_dot(self._angpos, pointing)**2) / (4*sigma**2)
            self._bc_map = np.exp(-x2)

            self._bc_freq = freq
            self._bc_nside = self._nside

        return self._bc_map
Example #19
0
def star(a,b,c,alpha,beta,gamma):
    "Calculate unit cell volume, reciprocal cell volume, reciprocal lattice parameters"
    alpha=np.radians(alpha)
    beta=np.radians(beta)
    gamma=np.radians(gamma)
    V=2*a*b*c*\
        np.sqrt(np.sin((alpha+beta+gamma)/2)*\
               np.sin((-alpha+beta+gamma)/2)*\
               np.sin((alpha-beta+gamma)/2)*\
               np.sin((alpha+beta-gamma)/2))
    Vstar=(2*np.pi)**3/V;
    astar=2*np.pi*b*c*np.sin(alpha)/V
    bstar=2*np.pi*a*c*np.sin(beta)/V
    cstar=2*np.pi*b*a*np.sin(gamma)/V
    alphastar=np.arccos((np.cos(beta)*np.cos(gamma)-\
                        np.cos(alpha))/ \
                       (np.sin(beta)*np.sin(gamma)))
    betastar= np.arccos((np.cos(alpha)*np.cos(gamma)-\
                        np.cos(beta))/ \
                       (np.sin(alpha)*np.sin(gamma)))
    gammastar=np.arccos((np.cos(alpha)*np.cos(beta)-\
                        np.cos(gamma))/ \
                       (np.sin(alpha)*np.sin(beta)))
    V=V
    alphastar=np.degrees(alphastar)
    betastar=np.degrees(betastar)
    gammastar=np.degrees(gammastar)
    return astar,bstar,cstar,alphastar,betastar,gammastar
Example #20
0
def readGC(file,standard_cosmology=True):

    ra,dec,zs,zp =[],[],[],[]
    dl = []
    with open(file,'r') as f:
        if standard_cosmology: omega = lal.CreateCosmologicalParameters(0.7,0.3,0.7,-1.0,0.0,0.0)
        for line in f:
            fields = line.split(None)
            if 0.0 < np.float(fields[40]) > 0.0 or np.float(fields[41]) > 0.0:
                if not(standard_cosmology):
                    h = np.random.uniform(0.5,1.0)
                    om = np.random.uniform(0.0,1.0)
                    ol = 1.0-om
                    omega = lal.CreateCosmologicalParameters(h,om,ol,-1.0,0.0,0.0)
                
                ra.append(np.float(fields[0]))
                dec.append(np.float(fields[1]))
                zs.append(np.float(fields[40]))
                zp.append(np.float(fields[41]))
                if not(np.isnan(zs[-1])):
                    dl.append(lal.LuminosityDistance(omega,zs[-1]))
                elif not(np.isnan(zp[-1])):
                    dl.append(lal.LuminosityDistance(omega,zp[-1]))
                else:
                    dl.append(-1)
        f.close()
    return np.column_stack((np.radians(np.array(ra)),np.radians(np.array(dec)),np.array(dl)))
    def test_samplePatchOnSphere(self):
        

        A = lambda theta_min, theta_max: np.sin(theta_max) - np.sin(theta_min)


        theta_c = np.radians(self.theta_c)
        delta = np.radians(self.delta)

        theta_min = theta_c - delta
        theta_max = theta_c + delta
        tvals = np.arange(theta_min, theta_max, 0.001) 
        tvalsShifted = np.zeros(len(tvals))
        tvalsShifted[:-1] = tvals[1:]

        area = A(tvals, tvalsShifted)
        
        binsize = np.unique(np.diff(tvals))
        assert binsize.size == 1
        normval = np.sum(area) * binsize[0]


        theta_samps = np.radians(self.dense_samples[1])
        binnedvals = np.histogram(theta_samps, bins=tvals[:-1], normed=True)[0]
        resids = area[:-2] / normval - binnedvals

        fiveSigma = np.sqrt(binnedvals) * 5.0
        assert all(resids < fiveSigma)
Example #22
0
def lb_to_azalt(gal_l, gal_b, lat, lon, unixtime=None):
    """
    Converts galactic coordiantes to az/alt coordinates. The input
    angles are expected to be in degrees.
    """
    # Convert degrees to radians
    gal_l = _np.radians(gal_l)
    gal_b = _np.radians(gal_b)

    # Location on unit sphere
    theta = _np.pi / 2 - gal_b
    phi   = gal_l
    x = _np.sin(theta) * _np.cos(phi)
    y = _np.sin(theta) * _np.sin(phi)
    z = _np.cos(theta)
    cartesian = _np.array([x, y, z])

    # Get the of-date ra/dec to convert to az/alt
    radec_cart = _np.dot(matrix_lb_radec(), cartesian)
    x, y, z = radec_cart
    r = _np.sqrt(x**2 + y**2 + z**2) # should be 1
    theta = _np.arccos(z / r)
    phi = _np.arctan2(y, x)
    ra = _np.degrees(phi)
    dec = _np.degrees(_np.pi / 2 - theta)
    if ra < 0:
        ra += 360.0
    ra, dec = get_radec_ofdate(ra, dec, unixtime)

    # Convert ra/dec to az/alt (in degrees)
    return radec_to_azalt(ra, dec, lat, lon, unixtime)
    def testGetRotTelPos(self):
        rotSkyList = np.random.random_sample(len(self.raList))*2.0*np.pi
        mjd=56789.3
        obsTemp = ObservationMetaData(mjd=mjd, site=Site(longitude=self.lon, latitude=self.lat, name='LSST'))

        rotTelRad = utils._getRotTelPos(self.raList, self.decList,
                                        obsTemp, rotSkyList)

        rotTelDeg = utils.getRotTelPos(np.degrees(self.raList),
                                       np.degrees(self.decList),
                                       obsTemp, np.degrees(rotSkyList))

        np.testing.assert_array_almost_equal(rotTelRad, np.radians(rotTelDeg), 10)

        rotTelRad = utils._getRotTelPos(self.raList, self.decList,
                                        obsTemp, rotSkyList[0])

        rotTelDeg = utils.getRotTelPos(np.degrees(self.raList),
                                       np.degrees(self.decList),
                                       obsTemp, np.degrees(rotSkyList[0]))

        np.testing.assert_array_almost_equal(rotTelRad, np.radians(rotTelDeg), 10)


        for ra, dec, rotSky in \
        zip(self.raList, self.decList, rotSkyList):

            obsTemp = ObservationMetaData(mjd=mjd, site=Site(longitude=self.lon, latitude=self.lat, name='LSST'))

            rotTelRad = utils._getRotTelPos(ra, dec, obsTemp, rotSky)

            rotTelDeg = utils.getRotTelPos(np.degrees(ra), np.degrees(dec),
                                           obsTemp, np.degrees(rotSky))

            self.assertAlmostEqual(rotTelRad, np.radians(rotTelDeg), 10)
Example #24
0
def fk4_e_terms(equinox):
    """
    Return the e-terms of aberation vector

    Parameters
    ----------
    equinox : Time object
        The equinox for which to compute the e-terms
    """

    from . import earth_orientation as earth

    # Constant of aberration at J2000
    k = 0.0056932

    # Eccentricity of the Earth's orbit
    e = earth.eccentricity(equinox.jd)
    e = np.radians(e)

    # Mean longitude of perigee of the solar orbit
    g = earth.mean_lon_of_perigee(equinox.jd)
    g = np.radians(g)

    # Obliquity of the ecliptic
    o = earth.obliquity(equinox.jd, algorithm=1980)
    o = np.radians(o)

    return e * k * np.sin(g), \
           -e * k * np.cos(g) * np.cos(o), \
           -e * k * np.cos(g) * np.sin(o)
Example #25
0
    def __init__(self, irf, alpha, min_fsig=0.0, redge="0.0/1.0"):

        self._irf = irf
        #        self._th68 = self._irf._psf.counts
        #        self._bkg_rate = (self._det.proton_wcounts_density +
        #                          self._det.electron_wcounts_density)/(50.0*Units.hr*
        #                                                               Units.deg2)

        self._loge_axis = Axis.create(np.log10(Units.gev) + 1.4, np.log10(Units.gev) + 3.6, 22)
        self._loge = self._loge_axis.center
        self._dloge = self._loge_axis.width

        rmin, rmax = [float(t) for t in redge.split("/")]

        self._psi_axis = Axis(np.linspace(np.radians(0.0), np.radians(1.0), 101))
        self._psi = self._psi_axis.center
        self._domega = np.pi * (np.power(self._psi_axis.edges[1:], 2) - np.power(self._psi_axis.edges[:-1], 2))

        self._aeff = self._irf.aeff(self._loge - Units.log10_mev)
        self._bkg_rate = irf.bkg(self._loge - Units.log10_mev) * self._dloge

        self._redge = [np.radians(rmin), np.radians(rmax)]
        self._msk = (self._psi > self._redge[0]) & (self._psi < self._redge[1])

        self._domega_sig = np.sum(self._domega[self._msk])
        self._domega_bkg = self._domega_sig / alpha

        self._min_fsig = min_fsig
        self._alpha = alpha
        self._alpha_bin = self._domega / self._domega_bkg
Example #26
0
def get_fringe(qubic,horns, SOURCE_POWER=1., SOURCE_THETA=np.radians(0), SOURCE_PHI=np.radians(45),
               NU=150e9,DELTANU_NU=0.25,npts=512,display=True,background=True):
    horn_i=horns[0]
    horn_j=horns[1]
    all_open=~qubic.horn.removed
    all_open_i=all_open.copy()
    all_open_i[horn_i[0],horn_i[1]] = False
    all_open_j=all_open.copy()
    all_open_j[horn_j[0],horn_j[1]] = False
    all_open_ij=all_open.copy()
    all_open_ij[horn_i[0],horn_i[1]] = False
    all_open_ij[horn_j[0],horn_j[1]] = False

    Sall,Nall=get_fpimage(qubic,SOURCE_POWER=SOURCE_POWER,SOURCE_THETA=SOURCE_THETA, SOURCE_PHI=SOURCE_PHI,
                          NU=NU,DELTANU_NU=DELTANU_NU,npts=npts,display=display,HORN_OPEN=all_open,
                          background=background)
    S_i,N_i=get_fpimage(qubic,SOURCE_POWER=SOURCE_POWER,SOURCE_THETA=SOURCE_THETA, SOURCE_PHI=SOURCE_PHI,
                          NU=NU,DELTANU_NU=DELTANU_NU,npts=npts,display=display,HORN_OPEN=all_open_i,
                          background=background)
    S_j,N_j=get_fpimage(qubic,SOURCE_POWER=SOURCE_POWER,SOURCE_THETA=SOURCE_THETA, SOURCE_PHI=SOURCE_PHI,
                          NU=NU,DELTANU_NU=DELTANU_NU,npts=npts,display=display,HORN_OPEN=all_open_j,
                          background=background)
    S_ij,N_ij=get_fpimage(qubic,SOURCE_POWER=SOURCE_POWER,SOURCE_THETA=SOURCE_THETA, SOURCE_PHI=SOURCE_PHI,
                          NU=NU,DELTANU_NU=DELTANU_NU,npts=npts,display=display,HORN_OPEN=all_open_ij,
                          background=background)

    saturated = (Sall == 0) | (S_i == 0) | (S_j == 0) | (S_ij == 0)
    Sout=Sall+S_ij-S_i-S_j
    Nout=np.sqrt(Nall**2+N_ij**2+N_i**2+N_j**2)
    Sout[saturated]=0
    Nout[saturated]=0
    return Sout,Nout,[Sall,S_i,S_j,S_ij]
Example #27
0
 def convert_arc(en):
     angles = [np.radians(en.data['50']), np.radians(en.data['51'])]
     C = [en.data['10'], en.data['20']] #, en.data['30']]
     R = en.data['40']
     points = angles_to_threepoint(angles, C[0:2], R).tolist()   
     entities.append(Arc(len(vertices) + np.arange(3), closed=False))
     vertices.extend(points)
    def testObservedFromICRS(self):
        obs = ObservationMetaData(pointingRA=35.0, pointingDec=-45.0,
                                  mjd=43572.0)
        for pmRaList in [self.pm_raList, None]:
            for pmDecList in [self.pm_decList, None]:
                for pxList in [self.pxList, None]:
                    for vRadList in [self.v_radList, None]:
                        for includeRefraction in [True, False]:


                            raRad, decRad = utils._observedFromICRS(self.raList, self.decList,
                                                                         pm_ra=pmRaList, pm_dec=pmDecList,
                                                                         parallax=pxList, v_rad=vRadList,
                                                                         obs_metadata=obs, epoch=2000.0,
                                                                         includeRefraction=includeRefraction)

                            raDeg, decDeg = utils.observedFromICRS(np.degrees(self.raList), np.degrees(self.decList),
                                                                         pm_ra=utils.arcsecFromRadians(pmRaList),
                                                                         pm_dec=utils.arcsecFromRadians(pmDecList),
                                                                         parallax=utils.arcsecFromRadians(pxList),
                                                                         v_rad=vRadList,
                                                                         obs_metadata=obs, epoch=2000.0,
                                                                     includeRefraction=includeRefraction)



                            dRa = utils.arcsecFromRadians(raRad-np.radians(raDeg))
                            np.testing.assert_array_almost_equal(dRa, np.zeros(self.nStars), 9)

                            dDec = utils.arcsecFromRadians(decRad-np.radians(decDeg))
                            np.testing.assert_array_almost_equal(dDec, np.zeros(self.nStars), 9)
Example #29
0
def clock_image(time):

    # Create new image
    display = Image.new('RGBA', display_size, color=0)

    # Draw graphics
    draw = ImageDraw.Draw(display)

    # Add hour markers
    for angle in range(0, 360, 30):
        theta = np.radians(angle)
        points = radial_line(centre, theta, r1, r2, w)
        draw.polygon(points, fill=colors[0])

    # Add minute and hour hands
    h1_angle = np.radians(time.minute*360/60)
    h2_angle = np.radians((time.hour*360 + time.minute*6)/12)

    points = radial_line(centre, h1_angle, -w, r3, w)
    draw.polygon(points, fill=colors[1])

    points = radial_line(centre, h2_angle, -w, r4, w+2)
    draw.polygon(points, fill=colors[1])

    return display
Example #30
0
def azalt_to_lb(az, alt, lat, lon, unixtime=None):
    """
    Converts az/alt coordiantes to galactic coordinates. All inputs are
    expected to be in degrees.
    """
    # Get the of-date ra/dec
    ra, dec = azalt_to_radec(az, alt, lat, lon, unixtime)

    # Convert of-date ra/dec to J2000
    ra, dec = get_radec_j2000(ra, dec, unixtime)

    # Convert degrees to radians
    ra  = _np.radians(ra)
    dec = _np.radians(dec)

    # Location on unit sphere
    theta = _np.pi / 2 - dec
    phi   = ra
    x = _np.sin(theta) * _np.cos(phi)
    y = _np.sin(theta) * _np.sin(phi)
    z = _np.cos(theta)
    cartesian = _np.array([x, y, z])

    # Perform the final matrix multilication to get l/b
    lb_cart = _np.dot(matrix_radec_lb(), cartesian)
    x, y, z = lb_cart
    r = _np.sqrt(x**2 + y**2 + z**2) # should be 1
    theta = _np.arccos(z / r)
    phi = _np.arctan2(y, x)
    gal_l = _np.degrees(phi)
    gal_b = _np.degrees(_np.pi / 2 - theta)
    if gal_l < 0:
        gal_l += 360.0

    return (gal_l, gal_b)
Example #31
0
    def configure(self):
        self.addSegment("Pelvis",
                        0,
                        enums.SegmentSide.Central,
                        calibration_markers=["SACR", "midASIS"],
                        tracking_markers=["LASI", "RASI", "LPSI", "RPSI"])
        self.addSegment("Left Thigh",
                        1,
                        enums.SegmentSide.Left,
                        calibration_markers=["LKNE", "LKNM"],
                        tracking_markers=["LTHI1", "LTHI2", "LTHI3", "LTHI4"])
        self.addSegment("Right Thigh",
                        4,
                        enums.SegmentSide.Right,
                        calibration_markers=["RKNE", "RKNM"],
                        tracking_markers=["RTHI1", "RTHI2", "RTHI3", "RTHI4"])
        self.addSegment("Left Shank",
                        2,
                        enums.SegmentSide.Left,
                        calibration_markers=["LANK", "LMED"],
                        tracking_markers=["LTIB1", "LTIB2", "LTIB3", "LTIB4"])
        self.addSegment("Right Shank",
                        5,
                        enums.SegmentSide.Right,
                        calibration_markers=["RANK", "RMED"],
                        tracking_markers=["RTIB1", "RTIB2", "RTIB3", "RTIB4"])
        self.addSegment("Left Foot",
                        3,
                        enums.SegmentSide.Left,
                        calibration_markers=["LMET"],
                        tracking_markers=["LHEE", "LFMH", "LSMH", "LVMH"])
        self.addSegment("Right Foot",
                        6,
                        enums.SegmentSide.Right,
                        calibration_markers=["RMET"],
                        tracking_markers=["RHEE", "RFMH", "RSMH", "RVMH"])

        self.addJoint("LHip", "Pelvis", "Left Thigh", "YXZ")
        self.addJoint("LKnee", "Left Thigh", "Left Shank", "YXZ")
        self.addJoint("LAnkle", "Left Shank", "Left Foot", "YXZ")

        self.addJoint("RHip", "Pelvis", "Right Thigh", "YXZ")
        self.addJoint("RKnee", "Right Thigh", "Right Shank", "YXZ")
        self.addJoint("RAnkle", "Right Shank", "Right Foot", "YXZ")

        self.setClinicalDescriptor("LHip", enums.DataType.Angle, [0, 1, 2],
                                   [-1.0, -1.0, -1.0], [0.0, 0.0, 0.0])
        self.setClinicalDescriptor("LKnee", enums.DataType.Angle, [0, 1, 2],
                                   [+1.0, -1.0, -1.0], [0.0, 0.0, 0.0])
        self.setClinicalDescriptor("LAnkle", enums.DataType.Angle, [0, 2, 1],
                                   [-1.0, -1.0, -1.0],
                                   [np.radians(90), 0.0, 0.0])
        self.setClinicalDescriptor("RHip", enums.DataType.Angle, [0, 1, 2],
                                   [-1.0, +1.0, +1.0], [0.0, 0.0, 0.0])
        self.setClinicalDescriptor("RKnee", enums.DataType.Angle, [0, 1, 2],
                                   [+1.0, +1.0, +1.0], [0.0, 0.0, 0.0])
        self.setClinicalDescriptor("RAnkle", enums.DataType.Angle, [0, 2, 1],
                                   [-1.0, +1.0, +1.0],
                                   [np.radians(90), 0.0, 0.0])

        self.setClinicalDescriptor("Pelvis", enums.DataType.Angle, [0, 1, 2],
                                   [1.0, 1.0, -1.0], [0.0, 0.0, 0.0])
        self.setClinicalDescriptor("Left Foot", enums.DataType.Angle,
                                   [0, 2, 1], [1.0, 1.0, -1.0],
                                   [0.0, 0.0, 0.0])
        self.setClinicalDescriptor("Right Foot", enums.DataType.Angle,
                                   [0, 2, 1], [1.0, -1.0, 1.0],
                                   [0.0, 0.0, 0.0])
Example #32
0
    def Eby_straight(self, ownship, intruder, conf, qdr, dist, tcpa, tLOS, idx1, idx2):
        ''' 
            Resolution: Eby method assuming aircraft move straight forward,
            solving algebraically, only horizontally.
        '''
        # from degrees to radians
        qdr  = np.radians(qdr)
        # relative position vector
        d    = np.array([np.sin(qdr) * dist, \
                         np.cos(qdr) * dist, \
                         intruder.alt[idx2] - ownship.alt[idx1]])

        # find track in radians
        t1 = np.radians(ownship.trk[idx1])
        t2 = np.radians(intruder.trk[idx2])

        # write velocities as vectors and find relative velocity vector
        v1 = np.array([np.sin(t1) * ownship.tas[idx1], np.cos(t1) * ownship.tas[idx1], ownship.vs[idx1]])
        v2 = np.array([np.sin(t2) * intruder.tas[idx2], np.cos(t2) * intruder.tas[idx2], intruder.vs[idx2]])
        v = np.array(v2 - v1)
        # bear in mind: the definition of vr (relative velocity) is opposite to
        # the velocity vector in the LOS_nominal method, this just has consequences
        # for the derivation of tstar following Eby method, not more
        """
        intrusion vector:
        i(t)=self.hsep-d(t)
        d(t)=sqrt((d[0]+v[0]*t)**2+(d[1]+v[1]*t)**2)
        find max(i(t)/t)
        -write the equation out
        -take derivative, set to zero
        -simplify, take square of everything so the sqrt disappears (creates two solutions)
        -write to the form a*t**2 + b*t + c = 0
        -Solve using the quadratic formula
        """
        # These terms are used to construct a,b,c of the quadratic formula
        R2 = (conf.rpz * self.resofach) ** 2 # in meters
        d2 = np.dot(d, d) # distance vector length squared
        v2 = np.dot(v, v) # velocity vector length squared
        dv = np.dot(d, v) # dot product of distance and velocity

        # Solving the quadratic formula
        a = R2 * v2 - dv **2
        b = 2 * dv * (R2 - d2)
        c = R2 * d2 - d2 ** 2
        discrim = b ** 2 - 4 * a * c

        if discrim < 0: # if the discriminant is negative, we're done as taking the square root will result in an error
            discrim = 0
        time1 = (-b + np.sqrt(discrim)) / (2 * a)
        time2 = (-b - np.sqrt(discrim)) / (2 * a)

        #time when the size of the conflict is largest relative to time to solve
        tstar = min(abs(time1), abs(time2))

        #find drel and absolute distance at tstar
        drelstar = d + v * tstar
        dstarabs = np.linalg.norm(drelstar)
        #exception: if the two aircraft are on exact collision course
        #(passing eachother within 10 meter), change drelstar
        exactcourse = 10 #10 meter
        dif = exactcourse - dstarabs
        if dif > 0:
            vperp = np.array([-v[1], v[0], 0]) #rotate velocity 90 degrees in horizontal plane
            drelstar += dif * vperp / np.linalg.norm(vperp) #normalize to 10 m and add to drelstar
            dstarabs = np.linalg.norm(drelstar)

        #intrusion at tstar
        i = (conf.rpz * self.resofach) - dstarabs

        #desired change in the plane's speed vector:
        dv = i * drelstar / (dstarabs * tstar)
        return dv
 def lift(self, x, v):
     cl = self.rocket.get_cl_alpha()
     ref_area = np.pi / 4 * (self.rocket.static_params['Diameter'] ** 2)
     return 0.5 * self.rho([x]) * (v ** 2) * ref_area * cl * np.sin(np.radians(self.aoa))
Example #34
0
def transAngle(theta,n1,n2):
    return np.degrees(np.arcsin((n1/n2)*np.sin(np.radians(theta))))
Example #35
0
def reflCoefS(theta,n1,n2):
    num = n1*np.cos(np.radians(theta)) - n2*np.sqrt(1-((n1/n2)*np.sin(np.radians(theta)))**2)
    den = n1*np.cos(np.radians(theta)) + n2*np.sqrt(1-((n1/n2)*np.sin(np.radians(theta)))**2)

    ret = (num/den)**2
    return ret
Example #36
0
    alpha = y[6]

    dydt = np.zeros_like(y)
    dydt[:3] = np.cross(jhat, s1) - alpha * np.cross(s2, s1)
    dydt[3:6] = np.cross(jhat, s2) - alpha * np.cross(s1, s2)
    dydt[6] = eps * alpha
    return dydt


def H(s1s, s2s, alpha):
    return (-ts_dot_hat(s1s + s2s, np.array([0, 0, 1])) +
            alpha * ts_dot(s1s, s2s))


if __name__ == '__main__':
    I1 = np.radians(10)
    I2 = np.radians(20)
    y0 = [0, np.sin(I1), np.cos(I1), 0, np.sin(I2), np.cos(I2), 0.1]
    ret = solve_ivp(dydt_fixedj, (0, 1e2),
                    y0,
                    method='DOP853',
                    atol=1e-9,
                    rtol=1e-9,
                    args=[0.03])
    fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2,
                                                 2,
                                                 figsize=(8, 8),
                                                 sharex=True)
    s1s = np.reshape(ret.y[:3, :], (3, len(ret.t)))
    s2s = np.reshape(ret.y[3:6, :], (3, len(ret.t)))
    alpha = ret.y[6]
Example #37
0
def direct_optimization(N, dt, path_state, Ux, path_idx, ds):
    print('check')
    print(path_state)
    s0 = path_state[0]
    s_dot0 = path_state[1]
    e0 = path_state[2]
    e_dot0 = path_state[3]
    dpsi0 = path_state[4]
    dpsi_dot0 = path_state[5]

    est_idx = Ux * N * dt / ds
    split_idx = est_idx / N
    K = np.rint(split_idx * np.arange(0, N))
    K_dot = np.zeros(N)
    for idx in range(1, N):
        K_dot[idx] = K[idx] - K[idx - 1]

    delta = cp.Variable((N, 1))
    s = cp.Variable((N, 1))
    s_dot = cp.Variable((N, 1))
    e = cp.Variable((N, 1))
    e_dot = cp.Variable((N, 1))
    dpsi = cp.Variable((N, 1))
    dpsi_dot = cp.Variable((N, 1))

    f0 = -s[-1]
    objective = cp.Minimize(f0)
    #subject to x_i+1 = x_i + hAx_i + hBu_i + hC
    constraints = [
        s[0] == s0, e[0] == e0, dpsi[0] == dpsi0, dpsi_dot[0] == dpsi_dot0,
        e_dot[0] == e_dot0, s_dot[0] == Ux
    ]
    constraints += [delta[0] <= np.radians(25), delta[0] >= np.radians(-25)]
    for idx in range(1, N):
        constraints += [s[idx] == s[idx - 1] + s_dot[idx - 1] * dt]
        constraints += [s_dot[idx] == Ux]
        constraints += [e[idx] == e[idx - 1] + e_dot[idx - 1] * dt]
        constraints += [
            e_dot[idx] == e_dot[idx - 1] + dt *
            (-(Ca_f + Ca_r) / (m * Ux) * e_dot[idx - 1] +
             (Ca_f + Ca_r) / m * dpsi[idx - 1] + (b * Ca_r - a * Ca_f) /
             (m * Ux) * dpsi_dot[idx - 1]) + dt * (Ca_f / m) * delta[idx - 1] +
            dt * (-K[idx - 1] * (Ux**2 - (b * Ca_r - a * Ca_f) / m))
        ]
        constraints += [dpsi[idx] == dpsi[idx - 1] + dpsi_dot[idx - 1] * dt]
        constraints += [
            dpsi_dot[idx] == dpsi_dot[idx - 1] + dt *
            ((b * Ca_r - a * Ca_f) / (Iz * Ux) * e_dot[idx - 1] +
             (a * Ca_f - b * Ca_r) / Iz * dpsi[idx - 1] -
             (a**2 * Ca_f + b**2 * Ca_r) / (Iz * Ux) * dpsi_dot[idx - 1]) +
            dt * a * Ca_f / Iz * delta[idx - 1] + dt *
            (-K[idx - 1] *
             (a**2 * Ca_f + b**2 * Ca_r) / Iz - K_dot[idx - 1] * Ux)
        ]
        constraints += [
            delta[idx] <= np.radians(25), delta[idx] >= np.radians(-25)
        ]
        constraints += [
            e[idx] <= TRACK_WIDTH / 2.0, e[idx] >= -TRACK_WIDTH / 2.0
        ]

    prob = cp.Problem(objective, constraints)
    result = prob.solve()

    return -delta.value[0][0]
Example #38
0
 def setbanklim(self,idx,bankangle=None):
     if bankangle:
         self.bank[idx] = np.radians(bankangle) # [rad]
         return True
     else:
         return True,"Banklimit of "+self.id[idx]+" is "+str(int(np.degrees(self.bank[idx])))+" deg"
Example #39
0
        # fitting error
        fit_err = get_fitting_error(mesh, ih26m_joint_regressor, cam_params,
                                    joints, hand_type, capture_idx, frame_idx,
                                    cam_idx)
        print('Fitting error: ' + str(fit_err) + ' mm')

        # save mesh to obj files
        save_obj(
            mesh, mano_layer[hand_type].faces,
            osp.join(save_path,
                     img_path.split('/')[-1][:-4] + '_' + hand_type + '.obj'))

        # mesh
        mesh = mesh / 1000  # milimeter to meter
        mesh = trimesh.Trimesh(mesh, mano_layer[hand_type].faces)
        rot = trimesh.transformations.rotation_matrix(np.radians(180),
                                                      [1, 0, 0])
        mesh.apply_transform(rot)
        material = pyrender.MetallicRoughnessMaterial(
            metallicFactor=0.0,
            alphaMode='OPAQUE',
            baseColorFactor=(1.0, 1.0, 0.9, 1.0))
        mesh = pyrender.Mesh.from_trimesh(mesh,
                                          material=material,
                                          smooth=False)
        scene = pyrender.Scene(ambient_light=(0.3, 0.3, 0.3))
        scene.add(mesh, 'mesh')

        # add camera intrinsics
        focal = np.array(cam_param['focal'][cam_idx],
                         dtype=np.float32).reshape(2)
def parametric_adjustment(first_directional_angle: float,
                          last_directional_angle: float,
                          angles: list,
                          horizontal_layings: list,
                          first_point: list,
                          last_point: list,
                          left_angle=True):
    # Вычисление значений приближенных координат пунктов полигонометрического хода
    angles_array = np.array(angles)
    horizontal_layings_array = np.array(horizontal_layings)
    if left_angle:
        directional_angles = list()
        directional_angles.append(first_directional_angle + angles_array[0] -
                                  180)
        for i in range(len(angles_array) - 2):
            dir_angle = directional_angles[i] + angles_array[i + 1] - 180
            if dir_angle > 360:
                directional_angles.append(dir_angle - 360)
            elif dir_angle < 0:
                directional_angles.append(dir_angle + 360)
            else:
                directional_angles.append(dir_angle)
    else:
        directional_angles = list()
        directional_angles.append(first_directional_angle - angles_array[0] +
                                  180)
        for i in range(len(angles_array) - 2):
            directional_angles.append(directional_angles[i] -
                                      angles_array[i + 1] + 180)
    directional_angles_array = np.array(directional_angles)
    delta_x_array = horizontal_layings_array * np.cos(
        np.radians(directional_angles_array))
    delta_y_array = horizontal_layings_array * np.sin(
        np.radians(directional_angles_array))
    x_coordinates = list()
    x_coordinates.append(round(first_point[0] + delta_x_array[0], 3))
    for i in range(len(delta_x_array) - 2):
        x_coordinates.append(x_coordinates[i] + delta_x_array[i + 1])
    y_coordinates = list()
    y_coordinates.append(round(first_point[1] + delta_y_array[0], 3))
    for i in range(len(delta_y_array) - 2):
        y_coordinates.append(y_coordinates[i] + delta_y_array[i + 1])

    # По полученным приближенным значениям кооодинат вычисляются теоретические углы и длины линий
    # Теоретические значения горизонтальных углов
    theoretical_angles = list()
    theoretical_angles.append(
        ogz_points(first_point[0], first_point[1], x_coordinates[0],
                   y_coordinates[0]) - first_directional_angle + 180 - 360)
    theoretical_angles.append(
        degrees(
            atan2(y_coordinates[1] - y_coordinates[0], x_coordinates[1] -
                  x_coordinates[0])) - degrees(
                      atan2(first_point[1] - y_coordinates[0], first_point[0] -
                            x_coordinates[0])) + 360)
    for i in range(len(angles_array) - 4):
        angle = degrees(
            atan2(y_coordinates[i + 2] - y_coordinates[i + 1],
                  x_coordinates[i + 2] - x_coordinates[i + 1])) - degrees(
                      atan2(y_coordinates[i] - y_coordinates[i + 1],
                            x_coordinates[i] - x_coordinates[i + 1]))
        if angle < 0:
            theoretical_angles.append(angle + 360)
        elif angle > 360:
            theoretical_angles.append(angle - 360)
        else:
            theoretical_angles.append(angle)

    theoretical_angles.append(
        true_angle(
            degrees(
                atan2(last_point[1] - y_coordinates[-1], last_point[0] -
                      x_coordinates[-1])) - degrees(
                          atan2(y_coordinates[-2] -
                                y_coordinates[-1], x_coordinates[-2] -
                                x_coordinates[-1])) + 360))
    theoretical_angles.append(
        true_angle(last_directional_angle -
                   ogz_points(x_coordinates[-1], y_coordinates[-1],
                              last_point[0], last_point[1]) + 180 - 360))
    # Теоретические значения горизонтальных проложений
    theoretical_layings = list()
    theoretical_layings.append(
        sqrt((x_coordinates[0] - first_point[0])**2 +
             (y_coordinates[0] - first_point[1])**2))
    for i in range(len(horizontal_layings_array) - 2):
        theoretical_layings.append(
            sqrt((x_coordinates[i + 1] - x_coordinates[i])**2 +
                 (y_coordinates[i + 1] - y_coordinates[i])**2))
    theoretical_layings.append(
        sqrt((last_point[0] - x_coordinates[-1])**2 +
             (last_point[1] - y_coordinates[-1])**2))
    # Составление матрицы свободных членов L
    v_angles = (np.array(theoretical_angles) - np.array(angles)) * 3600
    v_layings = (np.array(theoretical_layings) -
                 np.array(horizontal_layings)) * 100
    l_matrix = np.concatenate(
        (v_angles,
         v_layings))  # Поменял знак, так как перенос на другую сторону
    # Составлание матрицы коэффициентов А для углов
    a_matrix_angles = list()
    for i in range(len(v_angles)):
        row = list()
        for j in range(len(x_coordinates) * 2):
            row.append(0)
        a_matrix_angles.append(row)
    # Коэффициенты для поправок в углы
    # Коэффиценты для первого угла
    kxj = -(sin(radians(directional_angles[0])) *
            (206265 / (horizontal_layings[0] * 100)))
    kyj = (cos(radians(directional_angles[0])) *
           (206265 / (horizontal_layings[0] * 100)))
    a_matrix_angles[0][0] = kxj
    a_matrix_angles[0][1] = kyj
    # Теперь цикл для всех углов до последнего
    for i in range(len(v_angles) - 2):
        if directional_angles[i] < 180:
            dir_angle_ik = directional_angles[i] + 180
        else:
            dir_angle_ik = directional_angles[i] - 180
        kxk = (sin(radians(dir_angle_ik)) * (206265 /
                                             (horizontal_layings[i] * 100)))
        kyk = -(cos(radians(dir_angle_ik)) * (206265 /
                                              (horizontal_layings[i] * 100)))
        kxi = (sin(radians(directional_angles[i + 1])) *
               (206265 / (horizontal_layings[i + 1] * 100))) - (
                   sin(radians(dir_angle_ik)) *
                   (206265 / (horizontal_layings[0] * 100)))
        kyi = -(cos(radians(directional_angles[i + 1])) *
                (206265 / (horizontal_layings[i + 1] * 100))) + (
                    cos(radians(dir_angle_ik)) *
                    (206265 / (horizontal_layings[0] * 100)))
        kxj = -(sin(radians(directional_angles[i + 1])) *
                (206265 / (horizontal_layings[i + 1] * 100)))
        kyj = (cos(radians(directional_angles[i + 1])) *
               (206265 / (horizontal_layings[i + 1] * 100)))
        # Заполение матрицы
        if i == 0:
            a_matrix_angles[1][0] = kxi
            a_matrix_angles[1][1] = kyi
            a_matrix_angles[1][2] = kxj
            a_matrix_angles[1][3] = kyj
            point = 0  # Для перехода точек через две координаты
        elif i == (len(v_angles) - 3):
            a_matrix_angles[i + 1][point] = kxk
            a_matrix_angles[i + 1][point + 1] = kyk
            a_matrix_angles[i + 1][point + 2] = kxi
            a_matrix_angles[i + 1][point + 3] = kyi
        else:
            a_matrix_angles[i + 1][point] = kxk
            a_matrix_angles[i + 1][point + 1] = kyk
            a_matrix_angles[i + 1][point + 2] = kxi
            a_matrix_angles[i + 1][point + 3] = kyi
            a_matrix_angles[i + 1][point + 4] = kxj
            a_matrix_angles[i + 1][point + 5] = kyj
            point += 2
    # Коэффиценты последнего угла
    if directional_angles[-1] < 180:
        dir_angle_ik = directional_angles[-1] + 180
    else:
        dir_angle_ik = directional_angles[-1] - 180
    kxk = (sin(radians(dir_angle_ik)) * (206265 /
                                         (horizontal_layings[-1] * 100)))
    kyk = -(cos(radians(dir_angle_ik)) * (206265 /
                                          (horizontal_layings[-1] * 100)))
    a_matrix_angles[-1][-2] = kxk
    a_matrix_angles[-1][-1] = kyk
    # Составление матрицы А для проложений
    a_matrix_layings = list()
    for i in range(len(v_layings)):
        row = list()
        for j in range(len(x_coordinates) * 2):
            row.append(0)
        a_matrix_layings.append(row)
    # Коэфициенты для поправок в стороны
    # Коэфициенты для первой стороны
    kxj = (cos(radians(directional_angles[0])))
    kyj = (sin(radians(directional_angles[0])))
    a_matrix_layings[0][0] = kxj
    a_matrix_layings[0][1] = kyj
    # Теперь цикл для всех сторон до последнего
    for i in range(len(v_layings) - 2):
        kxi = -(cos(radians(directional_angles[i + 1])))
        kyi = -(sin(radians(directional_angles[i + 1])))
        kxj = cos(radians(directional_angles[i + 1]))
        kyj = sin(radians(directional_angles[i + 1]))
        # Заполение матрицы
        if i == 0:
            point = 0  # Для перехода точек через две координаты
        a_matrix_layings[i + 1][point] = kxi
        a_matrix_layings[i + 1][point + 1] = kyi
        a_matrix_layings[i + 1][point + 2] = kxj
        a_matrix_layings[i + 1][point + 3] = kyj
        point += 2
    # Коэффициенты последей стороны
    kxi = -(cos(radians(directional_angles[-1])))
    kyi = -(sin(radians(directional_angles[-1])))
    a_matrix_layings[-1][-2] = kxi
    a_matrix_layings[-1][-1] = kyi
    # Построение матрицы общей матрицы А из матрицы коэф углои и матрицы коэф сторон
    a_matrix_angles_array = np.array(a_matrix_angles)
    a_matrix_layings_array = np.array(a_matrix_layings)
    a_matrix_array = np.concatenate(
        (a_matrix_angles_array, a_matrix_layings_array))
    # Составление матрицы весов
    p_matrix = list()
    for i in range(len(l_matrix)):
        row = list()
        for j in range(len(l_matrix)):
            row.append(0)
        p_matrix.append(row)
    # Угловые веса
    for i in range(len(v_angles)):
        p_matrix[i][i] = 1
    # Линейные веса
    for i in range(len(v_angles), len(l_matrix)):
        p_matrix[i][i] = 5**2 / 0.3**2
    p_matrix_array = np.array(p_matrix)
    # Составление матрицы нормальных уравнений RA
    a_matrix_tr_array = np.transpose(a_matrix_array)
    r_koeff = np.dot(a_matrix_tr_array, p_matrix_array)
    ra = np.dot(r_koeff, a_matrix_array)
    rl = -np.dot(r_koeff, l_matrix)
    # Решение матричноего уравнения поправки в координаты
    v_coordinates = np.linalg.solve(ra, rl)
    # Нахождение поправок в измерения
    v_measurement = np.dot(a_matrix_array, v_coordinates) + l_matrix
    # контроль
    control = np.dot(np.dot(a_matrix_tr_array, p_matrix_array), v_measurement)
    pvv = np.dot(np.dot(np.transpose(v_measurement), p_matrix_array),
                 v_measurement)
    pvl = np.dot(np.dot(np.transpose(v_measurement), p_matrix_array), l_matrix)
    # Вычисление уравненных коодинат
    v_coordinates = list(v_coordinates)
    v_x = list()
    for i in range(0, len(v_coordinates), 2):
        v_x.append(v_coordinates[i])
    v_y = list()
    for i in range(1, len(v_coordinates), 2):
        v_y.append(v_coordinates[i])
    v_x = np.array(v_x)
    v_y = np.array(v_y)
    x_coordinates = np.array(x_coordinates)
    y_coordinates = np.array(y_coordinates)
    x_corrected = x_coordinates + v_x / 100
    y_corrected = y_coordinates + v_y / 100
    table = pd.DataFrame()
    table['x'] = x_corrected
    table['y'] = y_corrected
    # Оценка точности
    mu = sqrt(pvv / 3)
    mb = mu
    ms = mu * sqrt(1 / (10**2 / 2**2))
    k = np.linalg.inv(ra) * mu**2
    q = list()
    for i in range(len(v_coordinates)):
        q.append(sqrt(k[i][i]))
    mt = list()
    for i in range(0, len(q), 2):
        mt.append(sqrt(q[i]**2 + q[i + 1]**2))
    return mt
Example #41
0
def _rotation(degree):
    """Generate the rotation matrix."""
    theta = np.radians(degree)
    rot = np.array(((np.cos(theta), -np.sin(theta)), (np.sin(theta), np.cos(theta))))
    return rot
Example #42
0
    def create(self, n=1, actype="B744", acalt=None, acspd=None, dest=None,
                aclat=None, aclon=None, achdg=None, acid=None):
        """ Create multiple random aircraft in a specified area """
        area = bs.scr.getviewbounds()
        if acid is None:
            idtmp = chr(randint(65, 90)) + chr(randint(65, 90)) + '{:>05}'
            acid = [idtmp.format(i) for i in range(n)]

        elif isinstance(acid, str):
            # Check if not already exist
            if self.id.count(acid.upper()) > 0:
                return False, acid + " already exists."  # already exists do nothing
            acid = [acid]
        else:
            # TODO: for a list of a/c, check each callsign
            pass

        super(Traffic, self).create(n)

        # Increase number of aircraft
        self.ntraf += n

        if aclat is None:
            aclat = np.random.rand(n) * (area[1] - area[0]) + area[0]
        elif isinstance(aclat, (float, int)):
            aclat = np.array(n * [aclat])

        if aclon is None:
            aclon = np.random.rand(n) * (area[3] - area[2]) + area[2]
        elif isinstance(aclon, (float, int)):
            aclon = np.array(n * [aclon])

        # Limit longitude to [-180.0, 180.0]
        if n == 1:
            aclon = aclon - 360 if aclon > 180 else \
                    aclon + 360 if aclon < -180.0 else aclon
        else:
            aclon[aclon > 180.0] -= 360.0
            aclon[aclon < -180.0] += 360.0

        if achdg is None:

            achdg = np.random.randint(1, 360, n)
        elif isinstance(achdg, (float, int)):
            achdg = np.array(n * [achdg])

        if acalt is None:
            acalt = np.random.randint(2000, 39000, n) * ft
        elif isinstance(acalt, (float, int)):
            acalt = np.array(n * [acalt])

        if acspd is None:
            acspd = np.random.randint(250, 450, n) * kts
        elif isinstance(acspd,(float, int)):
            acspd = np.array(n * [acspd])

        actype = n * [actype] if isinstance(actype, str) else actype
        dest = n * [dest] if isinstance(dest, str) else dest

        # SAVEIC: save cre command when filled in
        # Special provision in case SAVEIC is on: then save individual CRE commands
        # Names of aircraft (acid) need to be recorded for saved future commands
        # And positions need to be the same in case of *MCRE"
        for i in range(n):
            bs.stack.savecmd(" ".join([ "CRE", acid[i], actype[i],
                                        str(aclat[i]), str(aclon[i]), str(int(round(achdg[i]))),
                                        str(int(round(acalt[i]/ft))),
                                        str(int(round(acspd[i]/kts)))]))

        # Aircraft Info
        self.id[-n:]   = acid
        self.type[-n:] = actype

        # Positions
        self.lat[-n:]  = aclat
        self.lon[-n:]  = aclon
        self.alt[-n:]  = acalt

        self.hdg[-n:]  = achdg
        self.trk[-n:]  = achdg

        # Velocities
        self.tas[-n:], self.cas[-n:], self.M[-n:] = vcasormach(acspd, acalt)
        self.gs[-n:]      = self.tas[-n:]
        hdgrad = np.radians(achdg)
        self.gsnorth[-n:] = self.tas[-n:] * np.cos(hdgrad)
        self.gseast[-n:] = self.tas[-n:] * np.sin(hdgrad)

        # Atmosphere
        self.p[-n:], self.rho[-n:], self.Temp[-n:] = vatmos(acalt)

        # Wind
        if self.wind.winddim > 0:
            applywind         = self.alt[-n:]> 50.*ft
            self.windnorth[-n:], self.windeast[-n:]  = self.wind.getdata(self.lat[-n:], self.lon[-n:], self.alt[-n:])
            self.gsnorth[-n:] = self.gsnorth[-n:] + self.windnorth[-n:]*applywind
            self.gseast[-n:]  = self.gseast[-n:]  + self.windeast[-n:]*applywind
            self.trk[-n:]     = np.logical_not(applywind)*achdg + \
                                applywind*np.degrees(np.arctan2(self.gseast[-n:], self.gsnorth[-n:]))
            self.gs[-n:]      = np.sqrt(self.gsnorth[-n:]**2 + self.gseast[-n:]**2)
        else:
            self.windnorth[-n:] = 0.0
            self.windeast[-n:]  = 0.0

        # Traffic performance data
        #(temporarily default values)
        self.apvsdef[-n:] = 1500. * fpm   # default vertical speed of autopilot
        self.aphi[-n:]    = 0.            # bank angle output of autopilot (optional)
        self.ax[-n:]      = kts           # absolute value of longitudinal accelleration
        self.bank[-n:]    = np.radians(25.)

        # Traffic autopilot settings
        self.selspd[-n:] = self.cas[-n:]
        self.aptas[-n:]  = self.tas[-n:]
        self.selalt[-n:] = self.alt[-n:]

        # Display information on label
        self.label[-n:] = n*[['', '', '', 0]]

        # Miscallaneous
        self.coslat[-n:] = np.cos(np.radians(aclat))  # Cosine of latitude for flat-earth aproximations
        self.eps[-n:] = 0.01

        # Finally call create for child TrafficArrays. This only needs to be done
        # manually in Traffic.
        self.create_children(n)
Example #43
0
 def _xytoll_merc(self, xs, ys, lambda_0, m, rad_earth):
     lon = np.degrees(np.radians(lambda_0) + xs / (m * rad_earth))
     lat = -np.degrees(2 * np.arctan(np.exp(ys /
                                            (m * rad_earth))) - np.pi / 2)
     return lat, lon
Example #44
0
    def compute_position_log(self,
                             td=None,
                             method='mc',
                             update_deviation=True):
        """
        Args:
            deviation (ndarray): A deviation survey with rows like MD, INC, AZI
            td (Number): The TD of the well, if not the end of the deviation
                survey you're passing.
            method (str):
                'aa': average angle
                'bt': balanced tangential
                'mc': minimum curvature
            update_deviation: This function makes some adjustments to the dev-
                iation survey, to account for the surface and TD. If you do not
                want to change the stored deviation survey, set to False.

        Returns:
            ndarray. A position log with rows like X-offset, Y-offset, Z-offset
        """
        deviation = np.copy(self.deviation)

        # Adjust to TD.
        if td is not None:
            last_row = np.copy(deviation[-1, :])
            last_row[0] = td
            deviation = np.vstack([deviation, last_row])

        # Adjust to surface if necessary.
        if deviation[0, 0] > 0:
            deviation = np.vstack([np.array([0, 0, 0]), deviation])

        last = deviation[:-1]
        this = deviation[1:]

        diff = this[:, 0] - last[:, 0]

        Ia, Aa = np.radians(last[:, 1]), np.radians(last[:, 2])
        Ib, Ab = np.radians(this[:, 1]), np.radians(this[:, 2])

        if method == 'aa':
            Iavg = (Ia + Ib) / 2
            Aavg = (Aa + Ab) / 2
            delta_N = diff * np.sin(Iavg) * np.cos(Aavg)
            delta_E = diff * np.sin(Iavg) * np.sin(Aavg)
            delta_V = diff * np.cos(Iavg)
        elif method in ('bt', 'mc'):
            delta_N = 0.5 * diff * np.sin(Ia) * np.cos(Aa)
            delta_N += 0.5 * diff * np.sin(Ib) * np.cos(Ab)
            delta_E = 0.5 * diff * np.sin(Ia) * np.sin(Aa)
            delta_E += 0.5 * diff * np.sin(Ib) * np.sin(Ab)
            delta_V = 0.5 * diff * np.cos(Ia)
            delta_V += 0.5 * diff * np.cos(Ib)
        else:
            raise Exception("Method must be one of 'aa', 'bt', 'mc'")

        if method == 'mc':
            _x = np.sin(Ib) * (1 - np.cos(Ab - Aa))
            dogleg = np.arccos(np.cos(Ib - Ia) - np.sin(Ia) * _x)
            dogleg[dogleg == 0] = 1e-9
            rf = 2 / dogleg * np.tan(dogleg / 2)  # ratio factor
            rf[np.isnan(rf)] = 1  # Adjust for NaN.
            delta_N *= rf
            delta_E *= rf
            delta_V *= rf

        # Prepare the output array.
        result = np.zeros_like(deviation, dtype=np.float)

        # Stack the results, add the surface.
        _offsets = np.squeeze(np.dstack([delta_N, delta_E, delta_V]))
        _offsets = np.vstack([np.array([0, 0, 0]), _offsets])
        result += _offsets.cumsum(axis=0)

        if update_deviation:
            self.deviation = deviation

        self.position = result

        return
Example #45
0
    def load_data(self):

        print("************* setting-up data structure")

        # the data array is the full set of measurements

        self.data = np.zeros(
            (self.npts, self.pmodes, self.amodes, self.padpix, self.padpix))
        self.data_energy = np.zeros((self.npts, self.pmodes, self.amodes))

        print("************* loading data")

        # ... load data into data array ... #
        # ... don't need to calculate the jones matrices for the polarisers ... #
        # ... they will be included in the amp and phase of the probes ... #

        for i in range(self.pmodes):
            for j in range(self.amodes):

                print("polarisation mode: {}|analyser mode: {}".format(i, j))

                kk = (i * self.pmodes) + j

                self.subdir = "scan_%02d/grid_00_00/" % np.int(
                    self.vpie_config[kk, 0])

                self.theta_p[i] = self.vpie_config[kk, 1]
                self.theta_a[j] = self.vpie_config[kk, 2]

                for k in np.arange(self.npts):

                    self.procdir = ("processed_r" + str(self.rebpix) + "_p" +
                                    str(self.padpix) + "/npy_files/")

                    filename = "position_%04d_int.npy" % k

                    self.full_filename = (self.scan_path + self.subdir +
                                          self.procdir + filename)

                    self.data[k, i, j, self.spx:self.epx,
                              self.spx:self.epx] = np.sqrt(
                                  np.load(self.full_filename))

                    self.data_energy[k, i, j] = np.sum(
                        self.data[k, i, j, self.spx:self.epx,
                                  self.spx:self.epx]**2)

                    self.data[k, i, j] = np.fft.fftshift(self.data[k, i, j])

        # ... transform angles from degrees to radians
        self.theta_p = np.radians(self.theta_p)
        self.theta_a = np.radians(self.theta_a)
        print(self.theta_a)
        print(tjheta)
        self.stheta_p = np.sin(self.theta_p)
        self.ctheta_p = np.cos(self.theta_p)

        self.stheta_a = np.sin(self.theta_a)
        self.ctheta_a = np.cos(self.theta_a)

        # for a given position on the sample, the detector estimate will depend the polariser and analyser settings

        # thus we need to declare psi_det_est to have pmodes*amodes slices

        # ... load the sample positions text file
        spec_data = sp.loadtxt(
            self.scan_path + ("scan_%02d" % np.int(self.vpie_config[0, 0])) +
            "/grid_00_00/final_smarpod_positions.txt",
            delimiter=",",
        )

        # ... and create a new set of position arrays in pixel units
        pos_x = spec_data[:, 0] / self.dx4
        pos_y = spec_data[:, 1] / self.dx4

        self.ix = np.round(pos_x)
        self.iy = np.round(pos_y)

        # this is important ... the probe is always in the middle of the smaller array ... the rx and ry tell the algorithm where to put the top corner of the cutout (sample) array so you're cutting out the right part

        self.rx = self.sammid - self.padmid
        self.ry = self.sammid - self.padmid

        self.fft_denom = 1.0 / self.padpix
Example #46
0
 def CAD_ANGLE(self):
     return np.radians(360 - self.ANGLE)
Example #47
0
def _orientation(yaw):
    return np.float32([np.cos(np.radians(yaw)), np.sin(np.radians(yaw))])
Example #48
0
 def _get_sigma(self, phi_0, lats, south_hemis=False):
     sign = -1 if south_hemis else 1
     sigma = (1. + np.sin(np.radians(sign * phi_0))) / (
         1. + np.sin(np.radians(sign * lats)))
     return sigma
Example #49
0
import numpy as np

from ss_generator import geometry
from . import basic

D_MEAN = 3.81
D_STD = 0.02
THETA_MEAN = np.radians(91.8)
THETA_STD = np.radians(3.35)
TAU_MEAN = np.radians(49.5)
TAU_STD = np.radians(7.1)


def theta_tau_to_rotation_matrix(theta, tau):
    '''Get the rotation matrix corresponding to the
    bond angle theta and dihedral tau.
    '''
    return np.dot(
        geometry.rotation_matrix_from_axis_and_angle(np.array([0, 1, 0]), tau),
        geometry.rotation_matrix_from_axis_and_angle(np.array([0, 0, 1]),
                                                     theta - np.pi))


def axis_to_theta_tau(axis):
    '''Get the bond angle theta and dihedral tau,
    from a rotation axis.
    '''
    theta = 2 * np.arctan(-axis[1] / axis[0])
    tau = 2 * np.arctan(axis[0] / axis[2])

    return theta, tau
Example #50
0
"""
from raytrace.splines import Extruded_bezier
from raytrace.beamstop import RectTarget
from raytrace.sources import RectRaySource
from raytrace.tracer import RayTraceModel
from raytrace.cmaterials import OpaqueMaterial, PECMaterial,DielectricMaterial
from raytrace.results import RayPaths
import numpy as np

#from raytrace.more_utils import transform_pts

import numpy as np

system_length = 100     #trough length

theta_p = np.radians(10)      #acceptance half angle (degrees becomes radians)
theta_n = np.radians(10)
len_exit_ap = 4.
exit_ap =[[-len_exit_ap/2.,0],[len_exit_ap/2,0]]
#start with an untilted parabola (directrix parallel to x axis), phi = 0 is -y
#in polar: r = 2a/(1+cos(phi))
#determine a, knowing that at phi = 90-theta+, r = width of entry aperature

lea = len_exit_ap
theta_D = np.pi/2. - theta_p
a = (lea*(1+np.cos(theta_D)))/2.

#next, determine the point where the other extreem ray from the orgin hits the parabola
#this is where phi = 180 - (theta+ + theta-)
#determine r there. call this point E
Example #51
0
vme.connect()
print("  done.")

# Make sure that, as we start, the robot is stopped.
vme.s()
vme.originate()
vme.o(270)

Ttot = 25       # Total period
subdiv = 24     # Number of sides of the N-gon (N = subdiv).
R = .75           # Radius of the circle intersecting the edges of the N-gon.

th = 360/subdiv			# Interior angle swept by a side of the N-gon.
phi = 90 - (180-th)/2   # Angle between the tangent at a corner and the cord connecting that
						#  corner to the adjacent corner.
th = np.radians(th)     # Convert to radians
phi = np.radians(phi)	#    "          "

ival = Ttot/subdiv      # time interval between corners.
speed = subdiv * 2*R*np.sin(th/2)/Ttot	# sibdiv * length of N-gon side.
xu = np.cos(phi)        # Get the unit vector along the cord connecting corners.
yu = np.sin(phi)

V = np.array( [xu, yu] ).reshape(2, 1)*speed # The velocity to get between the bottom corner and
                                             #  the next corner
# The rotation matrix to switch corners:
Rot = np.array([np.cos(th), -np.sin(th), np.sin(th), np.cos(th)]).reshape(2,2)

print(V)
print(Rot)
Example #52
0
def thread_backbone_for_helix(ca_list):
    '''Thread backbone atoms for a ca list of a helix using
    the method and parameters from the G. Grigoryan, W. F. DeGrado paper.
    Return a list of residue dictionaries.
    '''
    # Make the N termial residue

    residue_list = [{
        'ca':
        ca_list[0],
        'n':
        geometry.cartesian_coord_from_internal_coord(ca_list[2], ca_list[1],
                                                     ca_list[0], 1.45,
                                                     np.radians(95.0),
                                                     np.radians(65.0)),
        'c':
        geometry.cartesian_coord_from_internal_coord(ca_list[2], ca_list[1],
                                                     ca_list[0], 1.52,
                                                     np.radians(21.0),
                                                     np.radians(-79.0))
    }]

    # Make middle residues

    for i in range(1, len(ca_list) - 1):
        residue_list.append({
            'ca':
            ca_list[i],
            'n':
            geometry.cartesian_coord_from_internal_coord(
                ca_list[i - 1], ca_list[i + 1], ca_list[i], 1.45,
                np.radians(95.0), np.radians(14.0)),
            'c':
            geometry.cartesian_coord_from_internal_coord(
                ca_list[i + 1], ca_list[i - 1], ca_list[i], 1.52,
                np.radians(104.0), np.radians(16.0))
        })

    # Make the N terminal residue

    residue_list.append({
        'ca':
        ca_list[-1],
        'n':
        geometry.cartesian_coord_from_internal_coord(ca_list[-3], ca_list[-2],
                                                     ca_list[-1], 1.45,
                                                     np.radians(15.0),
                                                     np.radians(-56.0)),
        'c':
        geometry.cartesian_coord_from_internal_coord(ca_list[-3], ca_list[-2],
                                                     ca_list[-1], 1.52,
                                                     np.radians(104.0),
                                                     np.radians(67.0))
    })

    # Buil O atoms

    for i in range(1, len(ca_list)):
        residue_list[i - 1]['o'] = basic.get_o_for_peptide_bond(
            residue_list[i - 1]['c'], residue_list[i]['n'],
            residue_list[i]['ca'])

    return residue_list
    # get_injs needs the src list and signal spectrum
    inj_kw = dict (src=src, llh_src=llh_src, flux=flux, cut_n_sigma=cut_n_sigma, inj=inj)
    # trial.get_trial_runner loops over sub analyses and gives a single TrialRunner
    return trial.get_trial_runner (
        ana, get_llh, get_injs, llh_kw=llh_kw, inj_kw=inj_kw, mp_cpus=mp_cpus)

def get_sens(ana, ra, sindec, ext=np.radians(0), llh_ext=None, cut_n_sigma=None, sigsub=False, gamma=2, batch_size=500):
    src = cy.utils.Sources(ra=0, dec=np.arcsin(sindec),extension=ext)
    flux = hyp.PowerLawFlux(gamma)
    tr = get_tr(src=src, ana=ana, ext=ext, llh_ext=llh_ext, flux=flux, cut_n_sigma=cut_n_sigma, sigsub=sigsub)
    bg = cy.dists.Chi2TSD(tr.get_many_fits(1000))
    sens = tr.find_n_sig(bg.median(),0.9,batch_size=batch_size,max_batch_size=1000,tol=0.03, coverage=2)
    sens['flux'] = tr.to_E2dNdE(sens['n_sig'], E0=100, unit=1e3)
    return sens['flux']

def get_disc(ana, ra, sindec, ext=np.radians(0), llh_ext=None, cut_n_sigma=None, sigsub=False, gamma=2, batch_size=500):
    src = cy.utils.Sources(ra=0, dec=np.arcsin(sindec),extension=ext)
    flux = hyp.PowerLawFlux(gamma)
    tr = get_tr(src=src, ana=ana, ext=ext, llh_ext=llh_ext, flux=flux, cut_n_sigma=cut_n_sigma, sigsub=sigsub)
    bg = cy.dists.Chi2TSD(tr.get_many_fits(1000))
    sens = tr.find_n_sig(bg.isf_nsigma(5,fit=True),0.5,batch_size=batch_size,max_batch_size=1000,tol=0.03, coverage=2)
    sens['flux'] = tr.to_E2dNdE(sens['n_sig'], E0=100, unit=1e3)
    return sens['flux']

# llh_ext=None for extended source analysis on an extended source
# llh_ext=0 for point source analysis on an extended source

sindec_array = np.linspace(-0.98,0.98,50)
disc_1 = [get_disc(ana7,ra=0,sindec=d,ext=np.radians(1),llh_ext=None, cut_n_sigma=None, gamma=2, sigsub=False) for d in sindec_array]
np.save('/data/user/drysewyk/llh_sandbox/NumPyArrays/DiscoveryPotential/disc_1ext_llhextNone_cutnsigNone_gamma2_sigsubFalse_50bins.npy',disc_1)
Example #54
0
def omega2rates(pitch,
                roll,
                input_unit='rad',
                euler_angles_order='roll_pitch_yaw',
                output_type='ndarray'):
    """
    This function is used to create the transformation matrix to go from:
	    [p, q, r] --> [roll_rate, pitch_rate, yaw_rate]

    where pqr are xyz body rotation-rate measurements expressed in body frame.
    Yaw, pitch, and roll are the Euler angles.  We assume the Euler angles are
    3-2-1 (i.e Yaw -> Pitch -> Roll) transformations that go from navigation-
    frame to body-frame.

    Parameters
    ----------
    pitch : pitch angle, units of input_unit.
    roll  : roll angle , units of input_unit.
    input_unit : units for input angles {'rad', 'deg'}, optional
    euler_angles_order : {'roll_pitch_yaw', 'yaw_pitch_roll'}, optional
        Assumed order of Euler Angles attitude state vector (see ``Notes``).
    output_type : {'ndarray' or 'matrix'}, optional
        Numpy array (default) or matrix

    Returns
    -------
    R : transformation matrix, from xyz body-rate to Euler angle-rates
        numpy 'output_type' 3x3 (Note: default return variable is an ARRAY,
        not a matrix)

    Notes
    -----
    Since the returned transformation matrix is used to transform one vector
    to another, the assumed attitude variables order matters.
    The ``euler_angles_order`` parameter can be used to specify the assumed
    order.

    The difference is demonstrated by example:

        By default euler_angles_order='roll_pitch_yaw'
        R = omega2rates(pitch, roll)
        [ roll_rate]         [omega_x]
        [pitch_rate] = dot(R,[omega_y])
        [  yaw_rate]         [omega_z]

        Now assume our attitude state is [yaw, pitch, roll].T
        R = omega2rates(pitch, roll, euler_angles_order='yaw_pitch_roll')
        [ yaw_rate]          [omega_x]
        [pitch_rate] = dot(R,[omega_y])
        [ roll_rate]         [omega_z]

    References
    ----------
    [1] Equation 2.74, Aided Navigation: GPS with High Rate Sensors,
        Jay A. Farrel 2008

    [2] omega2rates.m function at:
    http://www.gnssapplications.org/downloads/chapter7/Chapter7_GNSS_INS_Functions.tar.gz
    """
    # Apply necessary unit transformations.
    if input_unit == 'rad':
        pitch_rad, roll_rad = pitch, roll
    elif input_unit == 'deg':
        pitch_rad, roll_rad = np.radians([pitch, roll])

    # Build transformation matrix.
    s_r, c_r = np.sin(roll_rad), np.cos(roll_rad)
    s_p, c_p = np.sin(pitch_rad), np.cos(pitch_rad)

    # Check for singularities (i.e. pitch near 90 degrees)
    singular_tol = 1e-2
    # flags anything between [90 +/- .5 deg]
    if abs(c_p) < singular_tol:
        print(
            'WARNING (omega2rates): Operating near pitch = 90 deg singularity.  NaN returned. '
        )
        return np.nan

    if euler_angles_order == 'roll_pitch_yaw':
        R = np.array([[1, s_r * s_p / c_p, c_r * s_p / c_p], [0, c_r, -s_r],
                      [0, s_r / c_p, c_r / c_p]],
                     dtype=float)
    elif euler_angles_order == 'yaw_pitch_roll':
        R = np.array([[0, s_r / c_p, c_r / c_p], [0, c_r, -s_r],
                      [1, s_r * s_p / c_p, c_r * s_p / c_p]],
                     dtype=float)

    if output_type == 'ndarray':
        pass
    elif output_type == 'matrix':
        R = np.matrix(R)
    else:
        print("WARNING (omega2rates): Unrecognized 'output_type' requested.")
        print("NaN is returned.")
        return np.nan

    return R
Example #55
0
def condon_errors(source, theta_n, psf=None):
    """
    Calculate the parameter errors for a fitted source
    using the description of Condon'97
    All parameters are assigned errors, assuming that all params were fit.
    If some params were held fixed then these errors are overestimated.

    Parameters
    ----------
    source : :class:`AegeanTools.models.SimpleSource`
        The source which was fit.

    theta_n : float
        A measure of the beam sampling. (See Condon'97).

    psf : :class:`AegeanTools.fits_image.Beam`
        The psf at the location of the source.

    Returns
    -------
    None

    """

    # indices for the calculation or rho
    alphas = {'amp': (3. / 2, 3. / 2),
              'major': (5. / 2, 1. / 2),
              'xo': (5. / 2, 1. / 2),
              'minor': (1. / 2, 5. / 2),
              'yo': (1. / 2, 5. / 2),
              'pa': (1. / 2, 5. / 2)}

    major = source.a / 3600.  # degrees
    minor = source.b / 3600.  # degrees
    phi = np.radians(source.pa)  # radians
    if psf is not None:
        beam = psf.get_beam(source.ra, source.dec)
        if beam is not None:
            theta_n = np.hypot(beam.a, beam.b)
            print(beam, theta_n)

    if theta_n is None:
        source.err_a = source.err_b = source.err_peak_flux = source.err_pa = source.err_int_flux = 0
        return

    smoothing = major * minor / (theta_n ** 2)
    factor1 = (1 + (major / theta_n))
    factor2 = (1 + (minor / theta_n))
    snr = source.peak_flux / source.local_rms
    # calculation of rho2 depends on the parameter being used so we lambda this into a function
    rho2 = lambda x: smoothing / 4 * factor1 ** alphas[x][0] * factor2 ** alphas[x][1] * snr ** 2

    source.err_peak_flux = source.peak_flux * np.sqrt(2 / rho2('amp'))
    source.err_a = major * np.sqrt(2 / rho2('major')) * 3600.  # arcsec
    source.err_b = minor * np.sqrt(2 / rho2('minor')) * 3600.  # arcsec

    err_xo2 = 2. / rho2('xo') * major ** 2 / (8 * np.log(2))  # Condon'97 eq 21
    err_yo2 = 2. / rho2('yo') * minor ** 2 / (8 * np.log(2))
    source.err_ra = np.sqrt(err_xo2 * np.sin(phi)**2 + err_yo2 * np.cos(phi)**2)
    source.err_dec = np.sqrt(err_xo2 * np.cos(phi)**2 + err_yo2 * np.sin(phi)**2)

    if (major == 0) or (minor == 0):
        source.err_pa = -1
    # if major/minor are very similar then we should not be able to figure out what pa is.
    elif abs(2 * (major-minor) / (major+minor)) < 0.01:
        source.err_pa = -1
    else:
        source.err_pa = np.degrees(np.sqrt(4 / rho2('pa')) * (major * minor / (major ** 2 - minor ** 2)))

    # integrated flux error
    err2 = (source.err_peak_flux / source.peak_flux) ** 2
    err2 += (theta_n ** 2 / (major * minor)) * ((source.err_a / source.a) ** 2 + (source.err_b / source.b) ** 2)
    source.err_int_flux = source.int_flux * np.sqrt(err2)
    return
Example #56
0
@author: Jacopo Carrani
"""

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib as mpl

dirFile = os.path.dirname(
    os.path.join('D:\\Final Year Project\\Figures', 'NicePlotProductivity.py'))
plt.style.use(os.path.join(dirFile, 'FYP_Figures.mplstyle'))

x = []
y = []
dist = 1
angles = np.radians(np.arange(0, 365, 5))
arr_centre = np.array([1.5, .5, 1.5]).reshape(1, 3)
arr = arr_centre[0, -1] * np.ones((3, 4))
arr[0, 0] = arr_centre[0, 0] - 0.045 * 3
arr[0, 1] = arr_centre[0, 0] - 0.015 * 3
arr[0, 2] = arr_centre[0, 0] + 0.015 * 3
arr[0, 3] = arr_centre[0, 0] + 0.045 * 3
arr[1, :] = arr_centre[0, 1]

for ang in range(0, 37):
    x.append(np.cos(angles[ang]) * dist + arr_centre[0, 0])
    y.append(np.sin(angles[ang]) * dist + arr_centre[0, 1])

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_aspect(1)
Example #57
0
def jacobian(pars, x, y):
    """
    Analytical calculation of the Jacobian for an elliptical gaussian
    Will work for a model that contains multiple Gaussians, and for which
    some components are not being fit (don't vary).

    Parameters
    ----------
    pars : lmfit.Model
        The model parameters
    x, y : list
        Locations at which the jacobian is being evaluated

    Returns
    -------
    j : 2d array
        The Jacobian.

    See Also
    --------
    :func:`AegeanTools.fitting.emp_jacobian`
    """

    matrix = []

    for i in range(pars['components'].value):
        prefix = "c{0}_".format(i)
        amp = pars[prefix + 'amp'].value
        xo = pars[prefix + 'xo'].value
        yo = pars[prefix + 'yo'].value
        sx = pars[prefix + 'sx'].value
        sy = pars[prefix + 'sy'].value
        theta = pars[prefix + 'theta'].value

        # The derivative with respect to component i doesn't depend on any other components
        # thus the model should not contain the other components
        model = elliptical_gaussian(x, y, amp, xo, yo, sx, sy, theta)

        # precompute for speed
        sint = np.sin(np.radians(theta))
        cost = np.cos(np.radians(theta))
        xxo = x - xo
        yyo = y - yo
        xcos, ycos = xxo * cost, yyo * cost
        xsin, ysin = xxo * sint, yyo * sint

        if pars[prefix + 'amp'].vary:
            dmds = model / amp
            matrix.append(dmds)

        if pars[prefix + 'xo'].vary:
            dmdxo = cost * (xcos + ysin) / sx ** 2 + sint * (xsin - ycos) / sy ** 2
            dmdxo *= model
            matrix.append(dmdxo)

        if pars[prefix + 'yo'].vary:
            dmdyo = sint * (xcos + ysin) / sx ** 2 - cost * (xsin - ycos) / sy ** 2
            dmdyo *= model
            matrix.append(dmdyo)

        if pars[prefix + 'sx'].vary:
            dmdsx = model / sx ** 3 * (xcos + ysin) ** 2
            matrix.append(dmdsx)

        if pars[prefix + 'sy'].vary:
            dmdsy = model / sy ** 3 * (xsin - ycos) ** 2
            matrix.append(dmdsy)

        if pars[prefix + 'theta'].vary:
            dmdtheta = model * (sy ** 2 - sx ** 2) * (xsin - ycos) * (xcos + ysin) / sx ** 2 / sy ** 2
            matrix.append(dmdtheta)

    return np.array(matrix)
Example #58
0
def errors(source, model, wcshelper):
    """
    Convert pixel based errors into sky coord errors

    Parameters
    ----------
    source : :class:`AegeanTools.models.SimpleSource`
        The source which was fit.

    model : lmfit.Parameters
        The model which was fit.

    wcshelper : :class:`AegeanTools.wcs_helpers.WCSHelper`
        WCS information.

    Returns
    -------
    source : :class:`AegeanTools.models.SimpleSource`
        The modified source obejct.

    """

    # if the source wasn't fit then all errors are -1
    if source.flags & (flags.NOTFIT | flags.FITERR):
        source.err_peak_flux = source.err_a = source.err_b = source.err_pa = -1
        source.err_ra = source.err_dec = source.err_int_flux = -1
        return source
    # copy the errors from the model
    prefix = "c{0}_".format(source.source)
    err_amp = model[prefix + 'amp'].stderr
    xo, yo = model[prefix + 'xo'].value, model[prefix + 'yo'].value
    err_xo = model[prefix + 'xo'].stderr
    err_yo = model[prefix + 'yo'].stderr

    sx, sy = model[prefix + 'sx'].value, model[prefix + 'sy'].value
    err_sx = model[prefix + 'sx'].stderr
    err_sy = model[prefix + 'sy'].stderr

    theta = model[prefix + 'theta'].value
    err_theta = model[prefix + 'theta'].stderr

    source.err_peak_flux = err_amp
    pix_errs = [err_xo, err_yo, err_sx, err_sy, err_theta]

    log.debug("Pix errs: {0}".format(pix_errs))

    ref = wcshelper.pix2sky([xo, yo])
    # check to see if the reference position has a valid WCS coordinate
    # It is possible for this to fail, even if the ra/dec conversion works elsewhere
    if not all(np.isfinite(ref)):
        source.flags |= flags.WCSERR
        source.err_peak_flux = source.err_a = source.err_b = source.err_pa = -1
        source.err_ra = source.err_dec = source.err_int_flux = -1
        return source

    # position errors
    if model[prefix + 'xo'].vary and model[prefix + 'yo'].vary \
            and all(np.isfinite([err_xo, err_yo])):
        offset = wcshelper.pix2sky([xo + err_xo, yo + err_yo])
        source.err_ra = gcd(ref[0], ref[1], offset[0], ref[1])
        source.err_dec = gcd(ref[0], ref[1], ref[0], offset[1])
    else:
        source.err_ra = source.err_dec = -1

    if model[prefix + 'theta'].vary and np.isfinite(err_theta):
        # pa error
        off1 = wcshelper.pix2sky([xo + sx * np.cos(np.radians(theta)), yo + sy * np.sin(np.radians(theta))])
        off2 = wcshelper.pix2sky(
            [xo + sx * np.cos(np.radians(theta + err_theta)), yo + sy * np.sin(np.radians(theta + err_theta))])
        source.err_pa = abs(bear(ref[0], ref[1], off1[0], off1[1]) - bear(ref[0], ref[1], off2[0], off2[1]))
    else:
        source.err_pa = -1

    if model[prefix + 'sx'].vary and model[prefix + 'sy'].vary \
            and all(np.isfinite([err_sx, err_sy])):
        # major axis error
        ref = wcshelper.pix2sky([xo + sx * np.cos(np.radians(theta)), yo + sy * np.sin(np.radians(theta))])
        offset = wcshelper.pix2sky(
            [xo + (sx + err_sx) * np.cos(np.radians(theta)), yo + sy * np.sin(np.radians(theta))])
        source.err_a = gcd(ref[0], ref[1], offset[0], offset[1]) * 3600

        # minor axis error
        ref = wcshelper.pix2sky([xo + sx * np.cos(np.radians(theta + 90)), yo + sy * np.sin(np.radians(theta + 90))])
        offset = wcshelper.pix2sky(
            [xo + sx * np.cos(np.radians(theta + 90)), yo + (sy + err_sy) * np.sin(np.radians(theta + 90))])
        source.err_b = gcd(ref[0], ref[1], offset[0], offset[1]) * 3600
    else:
        source.err_a = source.err_b = -1

    sqerr = 0
    sqerr += (source.err_peak_flux / source.peak_flux) ** 2 if source.err_peak_flux > 0 else 0
    sqerr += (source.err_a / source.a) ** 2 if source.err_a > 0 else 0
    sqerr += (source.err_b / source.b) ** 2 if source.err_b > 0 else 0
    if sqerr == 0:
        source.err_int_flux = -1
    else:
        source.err_int_flux = abs(source.int_flux * np.sqrt(sqerr))

    return source
Example #59
0
def new_errors(source, model, wcshelper):  # pragma: no cover
    """
    Convert pixel based errors into sky coord errors
    Uses covariance matrix for ra/dec errors
    and calculus approach to a/b/pa errors

    Parameters
    ----------
    source : :class:`AegeanTools.models.SimpleSource`
        The source which was fit.

    model : lmfit.Parameters
        The model which was fit.

    wcshelper : :class:`AegeanTools.wcs_helpers.WCSHelper`
        WCS information.

    Returns
    -------
    source : :class:`AegeanTools.models.SimpleSource`
        The modified source obejct.

    """

    # if the source wasn't fit then all errors are -1
    if source.flags & (flags.NOTFIT | flags.FITERR):
        source.err_peak_flux = source.err_a = source.err_b = source.err_pa = -1
        source.err_ra = source.err_dec = source.err_int_flux = -1
        return source
    # copy the errors/values from the model
    prefix = "c{0}_".format(source.source)
    err_amp = model[prefix + 'amp'].stderr
    xo, yo = model[prefix + 'xo'].value, model[prefix + 'yo'].value
    err_xo = model[prefix + 'xo'].stderr
    err_yo = model[prefix + 'yo'].stderr

    sx, sy = model[prefix + 'sx'].value, model[prefix + 'sy'].value
    err_sx = model[prefix + 'sx'].stderr
    err_sy = model[prefix + 'sy'].stderr

    theta = model[prefix + 'theta'].value
    err_theta = model[prefix + 'theta'].stderr

    # the peak flux error doesn't need to be converted, just copied
    source.err_peak_flux = err_amp

    pix_errs = [err_xo, err_yo, err_sx, err_sy, err_theta]

    # check for inf/nan errors -> these sources have poor fits.
    if not all(a is not None and np.isfinite(a) for a in pix_errs):
        source.flags |= flags.FITERR
        source.err_peak_flux = source.err_a = source.err_b = source.err_pa = -1
        source.err_ra = source.err_dec = source.err_int_flux = -1
        return source

    # calculate the reference coordinate
    ref = wcshelper.pix2sky([xo, yo])
    # check to see if the reference position has a valid WCS coordinate
    # It is possible for this to fail, even if the ra/dec conversion works elsewhere
    if not all(np.isfinite(ref)):
        source.flags |= flags.WCSERR
        source.err_peak_flux = source.err_a = source.err_b = source.err_pa = -1
        source.err_ra = source.err_dec = source.err_int_flux = -1
        return source

    # calculate position errors by transforming the error ellipse
    if model[prefix + 'xo'].vary and model[prefix + 'yo'].vary:
        # determine the error ellipse from the Jacobian
        mat = model.covar[1:3, 1:3]
        if not(np.all(np.isfinite(mat))):
            source.err_ra = source.err_dec = -1
        else:
            (a, b), e = np.linalg.eig(mat)
            pa = np.degrees(np.arctan2(*e[0]))
            # transform this ellipse into sky coordinates
            _, dec, major, minor, pa = wcshelper.pix2sky_ellipse([xo, yo], a, b, pa)

            # now determine the radius of the ellipse along the ra/dec directions.
            source.err_ra = major*minor / np.hypot(major*np.sin(np.radians(pa)), minor*np.cos(np.radians(pa)))
            source.err_dec = major*minor / np.hypot(major*np.cos(np.radians(pa)), minor*np.sin(np.radians(pa)))
    else:
        source.err_ra = source.err_dec = -1

    if model[prefix + 'theta'].vary:
        # pa error
        off1 = wcshelper.pix2sky([xo + sx * np.cos(np.radians(theta)), yo + sy * np.sin(np.radians(theta))])
        # offset by 1 degree
        off2 = wcshelper.pix2sky(
            [xo + sx * np.cos(np.radians(theta + 1)), yo + sy * np.sin(np.radians(theta + 1))])
        # scale the initial theta error by this amount
        source.err_pa = abs(bear(ref[0], ref[1], off1[0], off1[1]) - bear(ref[0], ref[1], off2[0], off2[1])) * err_theta
    else:
        source.err_pa = -1

    if model[prefix + 'sx'].vary and model[prefix + 'sy'].vary:
        # major axis error
        ref = wcshelper.pix2sky([xo + sx * np.cos(np.radians(theta)), yo + sy * np.sin(np.radians(theta))])
        # offset by 0.1 pixels
        offset = wcshelper.pix2sky(
            [xo + (sx + 0.1) * np.cos(np.radians(theta)), yo + sy * np.sin(np.radians(theta))])
        source.err_a = gcd(ref[0], ref[1], offset[0], offset[1])/0.1 * err_sx * 3600

        # minor axis error
        ref = wcshelper.pix2sky([xo + sx * np.cos(np.radians(theta + 90)), yo + sy * np.sin(np.radians(theta + 90))])
        # offset by 0.1 pixels
        offset = wcshelper.pix2sky(
            [xo + sx * np.cos(np.radians(theta + 90)), yo + (sy + 0.1) * np.sin(np.radians(theta + 90))])
        source.err_b = gcd(ref[0], ref[1], offset[0], offset[1])/0.1*err_sy * 3600
    else:
        source.err_a = source.err_b = -1

    sqerr = 0
    sqerr += (source.err_peak_flux / source.peak_flux) ** 2 if source.err_peak_flux > 0 else 0
    sqerr += (source.err_a / source.a) ** 2 if source.err_a > 0 else 0
    sqerr += (source.err_b / source.b) ** 2 if source.err_b > 0 else 0
    source.err_int_flux = abs(source.int_flux * np.sqrt(sqerr))

    return source
Example #60
0
def hessian(pars, x, y):
    """
    Create a hessian matrix corresponding to the source model 'pars'
    Only parameters that vary will contribute to the hessian.
    Thus there will be a total of nvar x nvar entries, each of which is a
    len(x) x len(y) array.

    Parameters
    ----------
    pars : lmfit.Parameters
        The model
    x, y : list
        locations at which to evaluate the Hessian

    Returns
    -------
    h : np.array
        Hessian. Shape will be (nvar, nvar, len(x), len(y))

    See Also
    --------
    :func:`AegeanTools.fitting.emp_hessian`
    """
    j = 0  # keeping track of the number of variable parameters
    # total number of variable parameters
    ntvar = np.sum([pars[k].vary for k in pars.keys() if k != 'components'])
    # construct an empty matrix of the correct size
    hmat = np.zeros((ntvar, ntvar, x.shape[0], x.shape[1]))
    npvar = 0

    for i in range(pars['components'].value):
        prefix = "c{0}_".format(i)
        amp = pars[prefix + 'amp'].value
        xo = pars[prefix + 'xo'].value
        yo = pars[prefix + 'yo'].value
        sx = pars[prefix + 'sx'].value
        sy = pars[prefix + 'sy'].value
        theta = pars[prefix + 'theta'].value

        amp_var = pars[prefix + 'amp'].vary
        xo_var = pars[prefix + 'xo'].vary
        yo_var = pars[prefix + 'yo'].vary
        sx_var = pars[prefix + 'sx'].vary
        sy_var = pars[prefix + 'sy'].vary
        theta_var = pars[prefix + 'theta'].vary

        # precomputed for speed
        model = elliptical_gaussian(x, y, amp, xo, yo, sx, sy, theta)
        sint = np.sin(np.radians(theta))
        sin2t = np.sin(np.radians(2*theta))
        cost = np.cos(np.radians(theta))
        cos2t = np.cos(np.radians(2*theta))
        sx2 = sx**2
        sy2 = sy**2
        xxo = x-xo
        yyo = y-yo
        xcos, ycos = xxo*cost, yyo*cost
        xsin, ysin = xxo*sint, yyo*sint

        if amp_var:
            k = npvar  # second round of keeping track of variable params
            # H(amp,amp)/G =  0
            hmat[j][k] = 0
            k += 1

            if xo_var:
                # H(amp,xo)/G =  1.0*(sx**2*((x - xo)*sin(t) + (-y + yo)*cos(t))*sin(t) + sy**2*((x - xo)*cos(t) + (y - yo)*sin(t))*cos(t))/(amp*sx**2*sy**2)
                hmat[j][k] = (xsin - ycos)*sint/sy2 + (xcos + ysin)*cost/sx2
                hmat[j][k] *= model
                k += 1

            if yo_var:
                # H(amp,yo)/G =  1.0*(-sx**2*((x - xo)*sin(t) + (-y + yo)*cos(t))*cos(t) + sy**2*((x - xo)*cos(t) + (y - yo)*sin(t))*sin(t))/(amp*sx**2*sy**2)
                hmat[j][k] = -(xsin - ycos)*cost/sy2 + (xcos + ysin)*sint/sx2
                hmat[j][k] *= model/amp
                k += 1

            if sx_var:
                # H(amp,sx)/G =  1.0*((x - xo)*cos(t) + (y - yo)*sin(t))**2/(amp*sx**3)
                hmat[j][k] = (xcos + ysin)**2
                hmat[j][k] *= model/(amp*sx**3)
                k += 1

            if sy_var:
                # H(amp,sy) =  1.0*((x - xo)*sin(t) + (-y + yo)*cos(t))**2/(amp*sy**3)
                hmat[j][k] = (xsin - ycos)**2
                hmat[j][k] *= model/(amp*sy**3)
                k += 1

            if theta_var:
                # H(amp,t) =  (-1.0*sx**2 + sy**2)*((x - xo)*sin(t) + (-y + yo)*cos(t))*((x - xo)*cos(t) + (y - yo)*sin(t))/(amp*sx**2*sy**2)
                hmat[j][k] = (xsin - ycos)*(xcos + ysin)
                hmat[j][k] *= sy2-sx2
                hmat[j][k] *= model/(amp*sx2*sy2)
                # k += 1
            j += 1

        if xo_var:
            k = npvar
            if amp_var:
                # H(xo,amp)/G = H(amp,xo)
                hmat[j][k] = hmat[k][j]
                k += 1

            # if xo_var:
            # H(xo,xo)/G =  1.0*(-sx**2*sy**2*(sx**2*sin(t)**2 + sy**2*cos(t)**2) + (sx**2*((x - xo)*sin(t) + (-y + yo)*cos(t))*sin(t) + sy**2*((x - xo)*cos(t) + (y - yo)*sin(t))*cos(t))**2)/(sx**4*sy**4)
            hmat[j][k] = -sx2*sy2*(sx2*sint**2 + sy2*cost**2)
            hmat[j][k] += (sx2*(xsin - ycos)*sint + sy2*(xcos + ysin)*cost)**2
            hmat[j][k] *= model/ (sx2**2*sy2**2)
            k += 1

            if yo_var:
                # H(xo,yo)/G =  1.0*(sx**2*sy**2*(sx**2 - sy**2)*sin(2*t)/2 - (sx**2*((x - xo)*sin(t) + (-y + yo)*cos(t))*sin(t) + sy**2*((x - xo)*cos(t) + (y - yo)*sin(t))*cos(t))*(sx**2*((x - xo)*sin(t) + (-y + yo)*cos(t))*cos(t) - sy**2*((x - xo)*cos(t) + (y - yo)*sin(t))*sin(t)))/(sx**4*sy**4)
                hmat[j][k] = sx2*sy2*(sx2 - sy2)*sin2t/2
                hmat[j][k] -= (sx2*(xsin - ycos)*sint + sy2*(xcos + ysin)*cost)*(sx2*(xsin -ycos)*cost - sy2*(xcos + ysin)*sint)
                hmat[j][k] *= model / (sx**4*sy**4)
                k += 1

            if sx_var:
                # H(xo,sx) =  ((x - xo)*cos(t) + (y - yo)*sin(t))*(-2.0*sx**2*sy**2*cos(t) + 1.0*((x - xo)*cos(t) + (y - yo)*sin(t))*(sx**2*((x - xo)*sin(t) + (-y + yo)*cos(t))*sin(t) + sy**2*((x - xo)*cos(t) + (y - yo)*sin(t))*cos(t)))/(sx**5*sy**2)
                hmat[j][k] = (xcos + ysin)
                hmat[j][k] *= -2*sx2*sy2*cost + (xcos + ysin)*(sx2*(xsin - ycos)*sint + sy2*(xcos + ysin)*cost)
                hmat[j][k] *= model / (sx**5*sy2)
                k += 1

            if sy_var:
                # H(xo,sy) =  ((x - xo)*sin(t) + (-y + yo)*cos(t))*(-2.0*sx**2*sy**2*sin(t) + 1.0*((x - xo)*sin(t) + (-y + yo)*cos(t))*(sx**2*((x - xo)*sin(t) + (-y + yo)*cos(t))*sin(t) + sy**2*((x - xo)*cos(t) + (y - yo)*sin(t))*cos(t)))/(sx2*sy**5)
                hmat[j][k] = (xsin - ycos)
                hmat[j][k] *= -2*sx2*sy2*sint + (xsin - ycos)*(sx2*(xsin - ycos)*sint + sy2*(xcos + ysin)*cost)
                hmat[j][k] *= model/(sx2*sy**5)
                k += 1

            if theta_var:
                # H(xo,t) =  1.0*(sx**2*sy**2*(sx**2 - sy**2)*(x*sin(2*t) - xo*sin(2*t) - y*cos(2*t) + yo*cos(2*t)) + (-sx**2 + 1.0*sy**2)*((x - xo)*sin(t) + (-y + yo)*cos(t))*((x - xo)*cos(t) + (y - yo)*sin(t))*(sx**2*((x - xo)*sin(t) + (-y + yo)*cos(t))*sin(t) + sy**2*((x - xo)*cos(t) + (y - yo)*sin(t))*cos(t)))/(sx**4*sy**4)
                # second part
                hmat[j][k] = (sy2-sx2)*(xsin - ycos)*(xcos + ysin)
                hmat[j][k] *= sx2*(xsin -ycos)*sint + sy2*(xcos + ysin)*cost
                # first part
                hmat[j][k] += sx2*sy2*(sx2 - sy2)*(xxo*sin2t -yyo*cos2t)
                hmat[j][k] *= model/(sx**4*sy**4)
                # k += 1
            j += 1

        if yo_var:
            k = npvar
            if amp_var:
                # H(yo,amp)/G = H(amp,yo)
                hmat[j][k] = hmat[0][2]
                k += 1

            if xo_var:
                # H(yo,xo)/G = H(xo,yo)/G
                hmat[j][k] =hmat[1][2]
                k += 1

            # if yo_var:
            # H(yo,yo)/G = 1.0*(-sx**2*sy**2*(sx**2*cos(t)**2 + sy**2*sin(t)**2) + (sx**2*((x - xo)*sin(t) + (-y + yo)*cos(t))*cos(t) - sy**2*((x - xo)*cos(t) + (y - yo)*sin(t))*sin(t))**2)/(sx**4*sy**4)
            hmat[j][k] = (sx2*(xsin - ycos)*cost - sy2*(xcos + ysin)*sint)**2 / (sx2**2*sy2**2)
            hmat[j][k] -= cost**2/sy2 + sint**2/sx2
            hmat[j][k] *= model
            k += 1

            if sx_var:
                # H(yo,sx)/G =  -((x - xo)*cos(t) + (y - yo)*sin(t))*(2.0*sx**2*sy**2*sin(t) + 1.0*((x - xo)*cos(t) + (y - yo)*sin(t))*(sx**2*((x - xo)*sin(t) - (y - yo)*cos(t))*cos(t) - sy**2*((x - xo)*cos(t) + (y - yo)*sin(t))*sin(t)))/(sx**5*sy**2)
                hmat[j][k] = -1*(xcos + ysin)
                hmat[j][k] *= 2*sx2*sy2*sint + (xcos + ysin)*(sx2*(xsin - ycos)*cost - sy2*(xcos + ysin)*sint)
                hmat[j][k] *= model/(sx**5*sy2)
                k += 1

            if sy_var:
                # H(yo,sy)/G =  ((x - xo)*sin(t) + (-y + yo)*cos(t))*(2.0*sx**2*sy**2*cos(t) - 1.0*((x - xo)*sin(t) + (-y + yo)*cos(t))*(sx**2*((x - xo)*sin(t) + (-y + yo)*cos(t))*cos(t) - sy**2*((x - xo)*cos(t) + (y - yo)*sin(t))*sin(t)))/(sx**2*sy**5)
                hmat[j][k] = (xsin -ycos)
                hmat[j][k] *= 2*sx2*sy2*cost - (xsin - ycos)*(sx2*(xsin - ycos)*cost - sy2*(xcos + ysin)*sint)
                hmat[j][k] *= model/(sx2*sy**5)
                k += 1

            if theta_var:
                # H(yo,t)/G =  1.0*(sx**2*sy**2*(sx**2*(-x*cos(2*t) + xo*cos(2*t) - y*sin(2*t) + yo*sin(2*t)) + sy**2*(x*cos(2*t) - xo*cos(2*t) + y*sin(2*t) - yo*sin(2*t))) + (1.0*sx**2 - sy**2)*((x - xo)*sin(t) + (-y + yo)*cos(t))*((x - xo)*cos(t) + (y - yo)*sin(t))*(sx**2*((x - xo)*sin(t) + (-y + yo)*cos(t))*cos(t) - sy**2*((x - xo)*cos(t) + (y - yo)*sin(t))*sin(t)))/(sx**4*sy**4)
                hmat[j][k] = (sx2 - sy2)*(xsin - ycos)*(xcos + ysin)
                hmat[j][k] *= (sx2*(xsin - ycos)*cost - sy2*(xcos + ysin)*sint)
                hmat[j][k] += sx2*sy2*(sx2-sy2)*(-x*cos2t + xo*cos2t - y*sin2t + yo*sin2t)
                hmat[j][k] *= model/(sx**4*sy**4)
                # k += 1
            j += 1

        if sx_var:
            k = npvar
            if amp_var:
                # H(sx,amp)/G = H(amp,sx)/G
                hmat[j][k] = hmat[k][j]
                k += 1

            if xo_var:
                # H(sx,xo)/G = H(xo,sx)/G
                hmat[j][k] = hmat[k][j]
                k += 1

            if yo_var:
                # H(sx,yo)/G = H(yo/sx)/G
                hmat[j][k] = hmat[k][j]
                k += 1

            # if sx_var:
            # H(sx,sx)/G =  (-3.0*sx**2 + 1.0*((x - xo)*cos(t) + (y - yo)*sin(t))**2)*((x - xo)*cos(t) + (y - yo)*sin(t))**2/sx**6
            hmat[j][k] = -3*sx2 + (xcos + ysin)**2
            hmat[j][k] *= (xcos + ysin)**2
            hmat[j][k] *= model/sx**6
            k += 1

            if sy_var:
                # H(sx,sy)/G =  1.0*((x - xo)*sin(t) + (-y + yo)*cos(t))**2*((x - xo)*cos(t) + (y - yo)*sin(t))**2/(sx**3*sy**3)
                hmat[j][k] = (xsin - ycos)**2 * (xcos + ysin)**2
                hmat[j][k] *= model/(sx**3*sy**3)
                k += 1

            if theta_var:
                # H(sx,t)/G =  (-2.0*sx**2*sy**2 + 1.0*(-sx**2 + sy**2)*((x - xo)*cos(t) + (y - yo)*sin(t))**2)*((x - xo)*sin(t) + (-y + yo)*cos(t))*((x - xo)*cos(t) + (y - yo)*sin(t))/(sx**5*sy**2)
                hmat[j][k] = -2*sx2*sy2 + (sy2 - sx2)*(xcos + ysin)**2
                hmat[j][k] *= (xsin -ycos)*(xcos + ysin)
                hmat[j][k] *= model/(sx**5*sy**2)
                # k += 1
            j += 1

        if sy_var:
            k = npvar
            if amp_var:
                # H(sy,amp)/G = H(amp,sy)/G
                hmat[j][k] = hmat[k][j]
                k += 1
            if xo_var:
                # H(sy,xo)/G = H(xo,sy)/G
                hmat[j][k] = hmat[k][j]
                k += 1
            if yo_var:
                # H(sy,yo)/G = H(yo/sy)/G
                hmat[j][k] = hmat[k][j]
                k += 1
            if sx_var:
                # H(sy,sx)/G = H(sx,sy)/G
                hmat[j][k] = hmat[k][j]
                k += 1

            # if sy_var:
            # H(sy,sy)/G =  (-3.0*sy**2 + 1.0*((x - xo)*sin(t) + (-y + yo)*cos(t))**2)*((x - xo)*sin(t) + (-y + yo)*cos(t))**2/sy**6
            hmat[j][k] = -3*sy2 + (xsin - ycos)**2
            hmat[j][k] *= (xsin - ycos)**2
            hmat[j][k] *= model/sy**6
            k += 1

            if theta_var:
                # H(sy,t)/G =  (2.0*sx**2*sy**2 + 1.0*(-sx**2 + sy**2)*((x - xo)*sin(t) + (-y + yo)*cos(t))**2)*((x - xo)*sin(t) + (-y + yo)*cos(t))*((x - xo)*cos(t) + (y - yo)*sin(t))/(sx**2*sy**5)
                hmat[j][k] = 2*sx2*sy2 + (sy2 - sx2)*(xsin - ycos)**2
                hmat[j][k] *= (xsin - ycos)*(xcos + ysin)
                hmat[j][k] *= model/(sx**2*sy**5)
                # k += 1
            j += 1

        if theta_var:
            k = npvar
            if amp_var:
                # H(t,amp)/G = H(amp,t)/G
                hmat[j][k] = hmat[k][j]
                k += 1
            if xo_var:
                # H(t,xo)/G = H(xo,t)/G
                hmat[j][k] = hmat[k][j]
                k += 1
            if yo_var:
                # H(t,yo)/G = H(yo/t)/G
                hmat[j][k] = hmat[k][j]
                k += 1
            if sx_var:
                # H(t,sx)/G = H(sx,t)/G
                hmat[j][k] = hmat[k][j]
                k += 1
            if sy_var:
                # H(t,sy)/G = H(sy,t)/G
                hmat[j][k] = hmat[k][j]
                k += 1
            # if theta_var:
            # H(t,t)/G =  (sx**2*sy**2*(sx**2*(((x - xo)*sin(t) + (-y + yo)*cos(t))**2 - 1.0*((x - xo)*cos(t) + (y - yo)*sin(t))**2) + sy**2*(-1.0*((x - xo)*sin(t) + (-y + yo)*cos(t))**2 + ((x - xo)*cos(t) + (y - yo)*sin(t))**2)) + (sx**2 - 1.0*sy**2)**2*((x - xo)*sin(t) + (-y + yo)*cos(t))**2*((x - xo)*cos(t) + (y - yo)*sin(t))**2)/(sx**4*sy**4)
            hmat[j][k] = sx2*sy2
            hmat[j][k] *= sx2*((xsin - ycos)**2 - (xcos + ysin)**2) + sy2*((xcos + ysin)**2 - (xsin - ycos)**2)
            hmat[j][k] += (sx2 - sy2)**2*(xsin - ycos)**2*(xcos + ysin)**2
            hmat[j][k] *= model/(sx**4*sy**4)
            # j += 1

        # save the number of variables for the next iteration
        # as we need to start our indexing at this number
        npvar = k
    return np.array(hmat)