How to use the astropy.units function in astropy

To help you get started, weā€™ve selected a few astropy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github nanograv / PINT / tests / test_parfile_writing.py View on Github external
if isinstance(par.value, numbers.Number):
                ov = par.value
                if isinstance(par, mp.MJDParameter):
                    continue
                else:
                    par.value = ov * 0.8
        self.res = Residuals(
            self.toasB1855, self.modelB1855, use_weighted_mean=False
        ).time_resids.to(u.s)
        f = open(self.out_parfile, "w")
        f.write(self.modelB1855.as_parfile())
        f.close()
        read_model = mb.get_model(self.out_parfile)
        read_res = Residuals(
            self.toasB1855, read_model, use_weighted_mean=False
        ).time_resids.to(u.s)
        assert np.all(
            np.abs(read_res.value - self.res.value) < 1e-15
        ), "Output parfile did not produce same residuals."
        for pp in self.modelB1855.params:
            par_ori = getattr(self.modelB1855, pp)
            par_read = getattr(read_model, pp)
            if par_ori.uncertainty_value is not None:
                unc_diff = par_ori.uncertainty_value - par_read.uncertainty_value
                assert np.abs(unc_diff) < 1e-15, (
                    pp
                    + "uncertainty does not keep the precision. at"
                    + str(np.abs(unc_diff))
                )
github nanograv / PINT / tests / test_model_wave.py View on Github external
def test_vela(self):
        print("Test RMS of a VELA ephemeris with WAVE parameters.")
        rs = pint.residuals.Residuals(self.t, self.m).time_resids
        rms = rs.to(u.us).std()
        emsg = "RMS of " + str(rms.value) + " is too big."
        assert rms < 350.0 * u.us, emsg
github mkelley / mskpy / mskpy / modeling.py View on Github external
def __init__(self, scale, unit=u.Unit('W/(m2 um)'), param_dim=1):
        from scipy.interpolate import interp1d
        import astropy.units as u
        from .calib import _e490_sm

        self._scale = Parameter(name='scale', val=scale, mclass=self,
                                param_dim=param_dim)
        self.unit = unit

        ParametricModel.__init__(self, self.param_names, n_inputs=1,
                                 n_outputs=1, param_dim=param_dim)
        self.linear = True

        self._wave, self._flux = np.loadtxt(_e490_sm).T
        self._wave *= u.um
        self._flux *= u.W / u.m**2 / u.um
        if self._flux.unit != self.unit:
            self._flux = self._flux.to(self.unit,
                                       u.spectral_density(self._wave))
        self.solar_interp = interp1d(self._wave.value, self._flux.value)
github gbrammer / grizli / grizli / utils.py View on Github external
targname : str
        Target name like jHHMMSS[+-]DDMMSS.
    
    """
    import astropy.coordinates 
    import astropy.units as u
    import re
    
    if header is not None:
        if 'CRVAL1' in header:
            ra, dec = header['CRVAL1'], header['CRVAL2']
        else:
            if 'RA_TARG' in header:
                ra, dec = header['RA_TARG'], header['DEC_TARG']
    
    coo = astropy.coordinates.SkyCoord(ra=ra*u.deg, dec=dec*u.deg)
    
    cstr = re.split('[hmsd.]', coo.to_string('hmsdms', precision=2))
    targname = ('j{0}{1}'.format(''.join(cstr[0:3]), ''.join(cstr[4:7])))
    targname = targname.replace(' ', '')
    
    return targname
github KeplerGO / lightkurve / lightkurve / seismology / deltanu_estimators.py View on Github external
Parameters
    ----------
    numax : float
        An estimated numax value of the mode envelope in the periodogram. If
        not given units it is assumed to be in units of the periodogram
        frequency attribute.

    Returns
    -------
    deltanu : `.SeismologyQuantity`
        The average large frequency spacing of the seismic oscillation modes.
        In units of the periodogram frequency attribute.
    """
    # Run some checks on the passed in numaxs
    # Ensure input numax is in the correct units
    numax = u.Quantity(numax, periodogram.frequency.unit)
    fs = np.median(np.diff(periodogram.frequency.value))
    if numax.value < fs:
        raise ValueError("The input numax can not be lower than"
                         " a single frequency bin.")
    if numax.value > np.nanmax(periodogram.frequency.value):
        raise ValueError("The input numax can not be higher than"
                         "the highest frequency value in the periodogram.")

    # Calculate deltanu using the method by Stello et al. 2009
    # Make sure that this relation only ever happens in microhertz space
    deltanu_emp = u.Quantity((0.294 * u.Quantity(numax, u.microhertz).value ** 0.772)*u.microhertz,
                        periodogram.frequency.unit).value

    window_width = 2*int(np.floor(utils.get_fwhm(periodogram, numax.value)))
    aacf = utils.autocorrelate(periodogram, numax=numax.value, window_width=window_width)
    acf = (np.abs(aacf**2)/np.abs(aacf[0]**2)) / (3/(2*len(aacf)))
github radio-astro-tools / spectral-cube / spectral_cube / dask_spectral_cube.py View on Github external
if unit == 'self':
            unit = self.unit

        out = function(self, *args, **kwargs)

        axis = kwargs.get('axis')

        if isinstance(out, da.Array):
            out = self._compute(out)

        if axis is None:

            # return is scalar
            if unit is not None:
                return u.Quantity(out, unit=unit)
            else:
                return out

        elif projection and axis is not None and self._naxes_dropped(axis) in (1, 2):

            meta = {'collapse_axis': axis}
            meta.update(self._meta)

            if hasattr(axis, '__len__') and len(axis) == 2:
                # if operation is over two spatial dims
                if set(axis) == set((1, 2)):
                    new_wcs = self._wcs.sub([wcs.WCSSUB_SPECTRAL])
                    header = self._nowcs_header
                    if hasattr(self, '_beam') and self._beam is not None:
                        bmarg = {'beam': self.beam}
                    elif hasattr(self, '_beams') and self._beams is not None:
github astropy / astropy / astropy / visualization / wcsaxes / formatter_locator.py View on Github external
def base_spacing(self):

        if self._decimal:

            spacing = self._unit / (10. ** self._precision)

        else:

            if self._fields == 1:
                spacing = 1. * u.degree
            elif self._fields == 2:
                spacing = 1. * u.arcmin
            elif self._fields == 3:
                if self._precision == 0:
                    spacing = 1. * u.arcsec
                else:
                    spacing = u.arcsec / (10. ** self._precision)

        if self._unit is u.hourangle:
            spacing *= 15

        return spacing
github Jammy2211 / PyAutoLens / autolens / data / ccd.py View on Github external
def simulate_as_gaussian_via_alma_fits_header_parameters(cls, shape, pixel_scale, y_stddev, x_stddev, theta,
                                                             centre=(0.0, 0.0)):

        x_stddev = x_stddev * (units.deg).to(units.arcsec) / (2.0 * np.sqrt(2.0 * np.log(2.0)))
        y_stddev = y_stddev * (units.deg).to(units.arcsec) / (2.0 * np.sqrt(2.0 * np.log(2.0)))

        axis_ratio = x_stddev / y_stddev

        gaussian = EllipticalGaussian(centre=centre, axis_ratio=axis_ratio, phi=90.0-theta, intensity=1.0, sigma=y_stddev)

        grid_1d = grid_util.regular_grid_1d_masked_from_mask_pixel_scales_and_origin(mask=np.full(shape, False),
                                                                                     pixel_scales=(pixel_scale, pixel_scale))
        gaussian_1d = gaussian.intensities_from_grid(grid=grid_1d)
        gaussian_2d = mapping_util.map_unmasked_1d_array_to_2d_array_from_array_1d_and_shape(array_1d=gaussian_1d,
                                                                                             shape=shape)
        return PSF(array=gaussian_2d, pixel_scale=pixel_scale, renormalize=True)
github astropy / astropy / astropy / coordinates / builtin_frames / gcrs.py View on Github external
Can only be passed in as a keyword argument.
    """

    frame_specific_representation_info = {
        'spherical': [RepresentationMapping('lon', 'ra'),
                      RepresentationMapping('lat', 'dec')]
    }
    frame_specific_representation_info['unitspherical'] = \
        frame_specific_representation_info['spherical']

    default_representation = SphericalRepresentation

    equinox = TimeFrameAttribute(default=EQUINOX_J2000)
    obstime = TimeFrameAttribute(default=DEFAULT_OBSTIME)
    obsgeoloc = QuantityFrameAttribute(default=0, unit=u.m, shape=(3,))
    obsgeovel = QuantityFrameAttribute(default=0, unit=u.m/u.s, shape=(3,))
github mkelley / mskpy / mskpy / polarimetry.py View on Github external
self.sig_I = sig_I
        self.sig_QI = sig_QI
        self.sig_UI = sig_UI

        self.p_eff = p_eff
        self.sig_p_eff = sig_p_eff

        self.QI_inst = QI_inst
        self.UI_inst = UI_inst
        
        self.p_eff_correct = p_eff_correct
        self.rc_correct = rc_correct
        self.inst_correct = inst_correct

        self.rotated = False
        self.dtheta = Angle(0.0 * u.deg)
        self.sig_dtheta = Angle(0.0 * u.deg)