Esempio n. 1
0
    def test_alt_unit(self):

        layer = self.client.layers.add_table_layer(table=self.table)

        # Using a string
        layer.alt_unit = 'm'

        # Using a string of an imperial unit
        layer.alt_unit = 'inch'

        # Using an astropy unit
        layer.alt_unit = u.km

        # Using a unit that is equal but not identical to one of the accepted ones
        layer.alt_unit = u.def_unit('same_as_km', 1000 * u.m)

        # Using an invalid string
        with pytest.raises(ValueError) as exc:
            layer.alt_unit = 'banana'
        assert exc.value.args[0].strip().startswith(
            "'banana' did not parse as unit: At col 0, banana is not a valid unit."
        )

        # Using an unsupported unit
        with pytest.raises(ValueError) as exc:
            layer.alt_unit = u.kg
        assert exc.value.args[0].strip(
        ) == "alt_unit should be one of AU/Mpc/ft/inch/km/lyr/m/mi/pc"

        # Using a non-equal custom unit
        with pytest.raises(ValueError) as exc:
            layer.alt_unit = u.def_unit('same_as_half_km', 500 * u.m)
        assert exc.value.args[0].strip(
        ) == "alt_unit should be one of AU/Mpc/ft/inch/km/lyr/m/mi/pc"
Esempio n. 2
0
def setup_registered_units():
    """
    Function to setup predefined units.
    This should run once when the module
    is imported.
    """
    global FORMATTED_UNITS
    # Load up configurations from yaml file
    with open(DEFAULT_FLUX_UNITS_CONFIGS, 'r') as yamlfile:
        cfg = yaml.load(yamlfile)

    # Define and add new units to astropy
    for new_unit_key in cfg["new_units"]:
        new_unit = cfg["new_units"][new_unit_key]
        try:
            u.Unit(new_unit["name"])
        except ValueError:
            if "base" in new_unit:
                new_astropy_unit = u.def_unit(new_unit["name"],
                                              u.Unit(new_unit["base"]))
            else:
                new_astropy_unit = u.def_unit(new_unit["name"])
            register_new_unit(new_astropy_unit)

    new_physical_types = [[(u.Jy / u.degree**2), 'SFD_over_solid_angle'],
                          [(u.Jy / u.pix), 'SFD_over_pix']]

    for model_unit, name in new_physical_types:
        try:
            u.def_physical_type(model_unit, name)
        except ValueError:
            continue

    FORMATTED_UNITS = cfg["formatted_units"]
Esempio n. 3
0
    def test_lon_unit(self):

        layer = self.client.layers.add_table_layer(table=self.table)

        # Using a string
        layer.lon_unit = 'deg'

        # Using an astropy unit
        layer.lon_unit = u.hourangle

        # Using a unit that is equal but not identical to one of the accepted ones
        layer.lon_unit = u.def_unit('same_as_deg', 3600 * u.arcsec)

        # Using an invalid string
        with pytest.raises(ValueError) as exc:
            layer.lon_unit = 'banana'
        assert exc.value.args[0].strip().startswith(
            "'banana' did not parse as unit: At col 0, banana is not a valid unit."
        )

        # Using an unsupported unit
        with pytest.raises(ValueError) as exc:
            layer.lon_unit = u.kg
        assert exc.value.args[0].strip(
        ) == "lon_unit should be one of deg/h/hourangle"

        # Using a non-equal custom unit
        with pytest.raises(ValueError) as exc:
            layer.lon_unit = u.def_unit('same_as_arcmin', 60 * u.arcsec)
        assert exc.value.args[0].strip(
        ) == "lon_unit should be one of deg/h/hourangle"
Esempio n. 4
0
    def __init__(self, cubeviz_layout=None):
        self.cubeviz_layout = cubeviz_layout

        # Load up configurations from yaml file
        with open(DEFAULT_FLUX_UNITS_CONFIGS, 'r') as yamlfile:
            cfg = yaml.load(yamlfile)

        # Define and add new units to astropy
        for new_unit_key in cfg["new_units"]:
            new_unit = cfg["new_units"][new_unit_key]
            try:
                u.Unit(new_unit["name"])
            except ValueError:
                if "base" in new_unit:
                    new_astropy_unit = u.def_unit(new_unit["name"], u.Unit(new_unit["base"]))
                else:
                    new_astropy_unit = u.def_unit(new_unit["name"])
                self.register_new_unit(new_astropy_unit)

        self._define_new_physical_types()

        # Formatted units
        self.formatted_units = cfg["formatted_units"]

        self.data = None
        self.wcs = None
        self._components = {}
Esempio n. 5
0
    def set_units(self,
                  velocity_in_cm_per_s=1e5,
                  lenght_in_cm=3.085678e24,
                  mass_in_g=1.989e43):
        """Set gadget internal units

        Args:
            velocity_in_cm_per_s: unit velocity un cm/s
            lenght_in_cm: unit lenght in cm
            mass_in_g: unit mass in grams

        Note:
            Default values result in:
                - velocity units in km/s
                - lenght units in kpc/h
                - mass units in 1e10 * solMass/h
            Where H0 = 100 * h Km s^{-1} Mpc^{-1} is the Hubble constant
        """

        unit_velocity_in_cm_per_s = velocity_in_cm_per_s * u.cm / u.s
        unit_lenght_in_cm = lenght_in_cm * u.cm
        unit_mass_in_g = mass_in_g * u.gram

        h = self.h
        vel = u.def_unit("gadget_velocity",
                         unit_velocity_in_cm_per_s.to("km/s"))
        lenght = u.def_unit("gadget_lenght", unit_lenght_in_cm.to("kpc") / h)
        mass = u.def_unit("gadget_mass", unit_mass_in_g.to("solMass") / h)
        time = lenght / vel

        self.gadget_velocity = vel
        self.gadget_lenght = lenght
        self.gadget_mass = mass
        self.gadget_time = time
        self.gadget_sfr = mass / time
Esempio n. 6
0
    def __init__(self, _frequency, luminosity):

        # Check for correct inputs
        if not _frequency.shape[0] == luminosity.shape[0] + 1:
            raise ValueError(
                "shape of '_frequency' and 'luminosity' are not compatible"
                f": '{_frequency.shape[0]}' and '{luminosity.shape[0]}'"
            )
        self._frequency = _frequency.to("Hz", u.spectral())
        self.luminosity = luminosity.to("erg / s")

        l_nu_unit = u.def_unit("erg\ s^{-1}\ Hz^{-1}", u.Unit("erg/(s Hz)"))
        l_lambda_unit = u.def_unit(
            "erg\ s^{-1}\ \\AA^{-1}", u.Unit("erg/(s AA)")
        )

        self.frequency = self._frequency[:-1]
        self.delta_frequency = self._frequency[1] - self._frequency[0]
        self.wavelength = self.frequency.to("angstrom", u.spectral())

        self.luminosity_density_nu = (
            self.luminosity / self.delta_frequency
        ).to(l_nu_unit)
        self.luminosity_density_lambda = self.f_nu_to_f_lambda(
            self.luminosity_density_nu,
        ).to(l_lambda_unit)
def setup_registered_units():
    """
    Function to setup predefined units.
    This should run once when the module
    is imported.
    """
    global FORMATTED_UNITS
    # Load up configurations from yaml file
    with open(DEFAULT_FLUX_UNITS_CONFIGS, 'r') as yamlfile:
        cfg = yaml.load(yamlfile)

    # Define and add new units to astropy
    for new_unit_key in cfg["new_units"]:
        new_unit = cfg["new_units"][new_unit_key]
        try:
            u.Unit(new_unit["name"])
        except ValueError:
            if "base" in new_unit:
                new_astropy_unit = u.def_unit(new_unit["name"], u.Unit(new_unit["base"]))
            else:
                new_astropy_unit = u.def_unit(new_unit["name"])
            register_new_unit(new_astropy_unit)

    new_physical_types = [
        [(u.Jy / u.degree ** 2), 'SFD_over_solid_angle'],
        [(u.Jy / u.pix), 'SFD_over_pix']
    ]

    for model_unit, name in new_physical_types:
        try:
            u.def_physical_type(model_unit, name)
        except ValueError:
            continue

    FORMATTED_UNITS = cfg["formatted_units"]
Esempio n. 8
0
def generateSpecialUnits(qMass, qR, gR):
    linearRg = (qMass.to('kg') * const.G / const.c / const.c).to('m')
    angleRg = linearRg / cosmo.angular_diameter_distance(qR)
    rgUnit = u.def_unit('r_g', angleRg.value * u.rad)
    thetaE = 4 * const.G * u.Quantity(0.5, 'solMass').to('kg') * _scaleFactor(
        qR, gR) / const.c / const.c
    thetaEUnit = u.def_unit('theta_E', math.sqrt(thetaE.value) * u.rad)
    return [thetaEUnit, rgUnit]
Esempio n. 9
0
	def __init__(self,fp=None,pool=None,length_unit=1.0*kpc,mass_unit=1.0e10*Msun,velocity_unit=1.0*km/s,header_kwargs=dict()):

		self.pool = pool

		self._length_unit = length_unit.to(cm).value
		self._mass_unit = mass_unit.to(g).value
		self._velocity_unit = velocity_unit.to(cm/s).value

		if fp is not None:
		
			self.fp = fp

			#Load the header
			self._header = self.getHeader(**header_kwargs)
			
			#Check that header has been loaded correctly
			self._check_header()

			#Hubble parameter
			h = self._header["h"]

			#Define the Mpc/h, and kpc/h units for convenience
			if h>0.0:
				
				self.kpc_over_h = def_unit("kpc/h",kpc/self._header["h"])
				self.Mpc_over_h = def_unit("Mpc/h",Mpc/self._header["h"])

				#Scale box to kpc/h
				self._header["box_size"] *= self.kpc_over_h
				#Convert to Mpc/h
				self._header["box_size"] = self._header["box_size"].to(self.Mpc_over_h)

				#Read in the comoving distance
				if "comoving_distance" in self._header:
					self._header["comoving_distance"] = (self._header["comoving_distance"] / 1.0e3) * self.Mpc_over_h

			else:
				self._header["box_size"] *= kpc
				logging.debug("Warning! Hubble parameter h is zero!!")

			#Scale masses to correct units
			if h>0.0:
				self._header["masses"] *= (self._mass_unit / self._header["h"])
				self._header["masses"] = (self._header["masses"]*g).to(Msun) 

			#Scale Hubble parameter to correct units
			self._header["H0"] = self._header["h"] * 100 * km / (s*Mpc)

			#Update the dictionary with the number of particles per side
			self._header["num_particles_total_side"] = int(np.round(self._header["num_particles_total"]**(1/3)))

			#Once all the info is available, add a wCDM instance as attribute to facilitate the cosmological calculations
			if h>0.0:
				self.cosmology = w0waCDM(H0=self._header["H0"],Om0=self._header["Om0"],Ode0=self._header["Ode0"],w0=self._header["w0"],wa=self._header["wa"])

			#Set particle number limits that this instance will handle
			self.setLimits()
Esempio n. 10
0
 def test_load_w_quantity(self):
     try:
         from astropy import units as u
         from pvl.decoder import OmniDecoder
         pvl_file = 'tests/data/pds3/units1.lbl'
         km_upper = u.def_unit('KM', u.km)
         m_upper = u.def_unit('M', u.m)
         u.add_enabled_units([km_upper, m_upper])
         label = pvl.load(pvl_file,
                          decoder=OmniDecoder(quantity_cls=u.Quantity))
         self.assertEqual(label['FLOAT_UNIT'], u.Quantity(0.414, 'KM'))
     except ImportError:
         pass
Esempio n. 11
0
 def setup_bases(self):
     """Set the standard, non-dimensional bases"""
     temperature_unit = u.def_unit("Box-delta-T", np.abs(self.deltaT))
     length_unit = u.def_unit("Box-D", self.depth)
     viscosity_unit = u.def_unit("kappa", self.primary_viscosity)
     time_unit = length_unit**2 / viscosity_unit
     self.add_bases("nondimensional", set([temperature_unit, length_unit, viscosity_unit, time_unit]))
     
     temperature_unit = self.deltaT.unit
     length_unit = self.depth.unit
     time_unit = type(self).Time.unit
     viscosity_unit = length_unit**2 / time_unit
     self.add_bases("standard", set([temperature_unit, length_unit, time_unit, viscosity_unit]))
Esempio n. 12
0
def test_represents():
    assert u.m.represents is u.m
    assert u.km.represents.scale == 1000.
    assert u.km.represents.bases == [u.m]
    assert u.Ry.scale == 1.0 and u.Ry.bases == [u.Ry]
    assert_allclose(u.Ry.represents.scale, 13.605692518464949)
    assert u.Ry.represents.bases == [u.eV]
    bla = u.def_unit('bla', namespace=locals())
    assert bla.represents is bla
    blabla = u.def_unit('blabla', 10 * u.hr, namespace=locals())
    assert blabla.represents.scale == 10.
    assert blabla.represents.bases == [u.hr]
    assert blabla.decompose().scale == 10 * 3600
    assert blabla.decompose().bases == [u.s]
Esempio n. 13
0
def test_represents():
    assert u.m.represents is u.m
    assert u.km.represents.scale == 1000.
    assert u.km.represents.bases == [u.m]
    assert u.Ry.scale == 1.0 and u.Ry.bases == [u.Ry]
    assert_allclose(u.Ry.represents.scale, 13.605692518464949)
    assert u.Ry.represents.bases == [u.eV]
    bla = u.def_unit('bla', namespace=locals())
    assert bla.represents is bla
    blabla = u.def_unit('blabla', 10 * u.hr, namespace=locals())
    assert blabla.represents.scale == 10.
    assert blabla.represents.bases == [u.hr]
    assert blabla.decompose().scale == 10 * 3600
    assert blabla.decompose().bases == [u.s]
Esempio n. 14
0
    def __init__(self, scdata, inputs, params=None, dphi=1*u.deg, **kwargs):
        """Initializes the LOSResult and runs the model if necessary"""
        if params is None:
            params = {'quantity': 'radiance'}
        else:
            pass

        scdata.set_frame('Model')
        super().__init__(inputs, params)
        
        # Basic information
        self.species = scdata.species
        self.query = scdata.query
        self.type = 'LineOfSight'
        self.dphi = dphi.to(u.rad).value
        self._oedge = np.min([self.inputs.options.outeredge*2, 100])

        self.fitted = self.inputs.options.fitted
        nspec = len(scdata)
        self.radiance = pd.Series(np.zeros(nspec), index=scdata.data.index)
        self.radiance_unit = u.def_unit('kR', 1e3*u.R)
        self.sourcemap = None
        self.modelfiles = None
        
        self.goodness_of_fit = None
        self.mask = None
        self.masking = kwargs.get('masking', None)
        self.fit_method = kwargs.get('fit_method', None)
        self.label = kwargs.get('label', 'LOSResult')

        if self.fitted:
            self.unfit_outid = None
            self.unfit_outputfiles = None
        else:
            pass
Esempio n. 15
0
    def _get_unit(cls, t):
        # match as normal
        try:
            return cls._parse_unit(t.value)
        except ValueError as exc:
            name = t.value
            sname = name[:-1] if name.endswith('s') else ''

            # parse alternative units from the error message
            match = cls.re_closest_unit.search(str(exc))
            try:  # split 'A, B, or C' -> ['A', 'B', 'C']
                alts = cls.re_closest_unit_delim.split(match.groups()[0])[::2]
            except AttributeError:
                alts = []
            alts = list(set(alts))

            # match uppercase to titled (e.g. MPC -> Mpc)
            if name.title() in alts:
                alt = name.title()
            # match titled unit to lower-case (e.g. Amp -> amp)
            elif name.lower() in alts:
                alt = name.lower()
            # match plural to singular (e.g. meters -> meter)
            elif sname in alts:
                alt = sname
            elif sname.lower() in alts:
                alt = sname.lower()
            else:
                warnings.warn('{0} Mathematical operations using this unit '
                              'should work, but conversions to other units '
                              'will not.'.format(str(exc).rstrip(' ')),
                              category=units.UnitsWarning)
                return units.def_unit(name, doc='Unrecognized unit')
            return cls._parse_unit(alt)
Esempio n. 16
0
def get_y_units(y_data, filename, header):
    """finds flux/reflectance units
       inputs: y_data, spectrum file
       outputs: scaled flux with Units
    """
    y_factor = 1
    if 'BUNIT' in header:
        try:
            y_units = u.Unit(header['BUNIT'])
        except ValueError:
            print("Could not parse flux units from header.")

    elif "ctiostan" in filename and '.dat' in filename:  # from ESO aaareadme.ctio
        y_units = u.erg / (u.cm**2) / u.s / u.AA
        y_factor = 10**16

    elif .001 < np.median(y_data) < 10:  # Probably Normalized
        y_units = u.def_unit("Normalized_Reflectance",
                             u.dimensionless_unscaled)

    elif '_2df_ex.fits' in filename:  # from FLOYDS
        y_factor = 10**20
        y_units = u.erg / (u.cm**2) / u.s / u.AA

    else:
        print("Could not parse flux units from file. Assuming erg/cm^2/s/A")
        y_units = u.erg / (u.cm**2) / u.s / u.AA

    yyy = np.array(y_data)
    flux = ((yyy / y_factor) * y_units)
    return flux
Esempio n. 17
0
def astro_dist(mass):
    """
    Function for turning distance into astronomical perspective.
    """
    value = (G.value * mass) / (c.value ** 2)
    astro_dist = u.def_unit("astro-m(GM/c2)", u.m / value)
    return astro_dist
Esempio n. 18
0
def astro_sec(mass):
    """
    Function for turning time into astronomical perspective.
    """
    value = (G.value * mass) / (c.value ** 3)
    astro_sec = u.def_unit("astro-sec(GM/c3)", u.s / value)
    return astro_sec
Esempio n. 19
0
    def test_with_custom_units_qtable(self, tmpdir):
        # Test only for QTable - for Table's Column, new units are dropped
        # (as is checked in test_write_drop_nonstandard_units).
        filename = str(tmpdir.join('test_with_units.fits'))
        unit = u.def_unit('bandpass_sol_lum')
        t = QTable()
        t['l'] = np.ones(5) * unit
        with pytest.warns(AstropyUserWarning) as w:
            t.write(filename, overwrite=True)
        assert len(w) == 1
        assert 'bandpass_sol_lum' in str(w[0].message)
        # Just reading back, the data is fine but the unit is not recognized.
        with pytest.warns(u.UnitsWarning,
                          match="'bandpass_sol_lum' did not parse") as w:
            t2 = QTable.read(filename)
        assert len(w) == 1
        assert isinstance(t2['l'].unit, u.UnrecognizedUnit)
        assert str(t2['l'].unit) == 'bandpass_sol_lum'
        assert np.all(t2['l'].value == t['l'].value)

        # But if we enable the unit, it should be recognized.
        with u.add_enabled_units(unit):
            t3 = QTable.read(filename)
            assert t3['l'].unit is unit
            assert equal_data(t3, t)

            # Regression check for #8897; write used to fail when a custom
            # unit was enabled.
            with pytest.warns(AstropyUserWarning):
                t3.write(filename, overwrite=True)
Esempio n. 20
0
    def test_auto_lon_unit(self):

        self.table['longitude'] = [1, 4, 5] * u.hour
        self.table['longitude2'] = [1, 4, 5] * u.def_unit(
            'same_as_deg', 3600 * u.arcsec)
        self.table['flux'].unit = u.kg

        layer = self.client.layers.add_table_layer(table=self.table)

        assert layer.lon_att == 'ra'
        assert layer.lon_unit is u.deg

        layer.lon_att = 'longitude'
        assert layer.lon_unit is u.hour

        layer.lon_att = 'longitude2'
        assert layer.lon_unit is u.deg

        expected_warning = (
            'Column flux has units of kg but this is not a '
            'valid unit of longitude - set the unit directly with '
            'lon_unit')

        with pytest.warns(UserWarning, match=expected_warning):
            layer.lon_att = 'flux'
Esempio n. 21
0
    def __init__(self, coords):
        valid_coords = ['KRTP', 'KSM', 'KSO', 'RTN']
        if coords not in valid_coords:
            raise ValueError('coords must be one of {}'.format(valid_coords))
        self.coords = coords

        Rs = u.def_unit('saturnRad', 60268 * u.km)
        if (coords == 'KRTP'):
            self.units = OrderedDict([('Bx', u.nT), ('By', u.nT), ('Bz', u.nT),
                                      ('X', Rs), ('|B|', u.nT),
                                      ('Y', u.deg),
                                      ('Z', u.deg),
                                      ('Local hour', u.dimensionless_unscaled),
                                      ('n points', u.dimensionless_unscaled)])
        if (coords == 'RTN'):
            self.units = OrderedDict([('Bx', u.nT), ('By', u.nT), ('Bz', u.nT),
                                      ('X', u.AU), ('Y', u.AU), ('Z', u.AU),
                                      ('|B|', u.nT),
                                      ('Local hour', u.dimensionless_unscaled),
                                      ('n points', u.dimensionless_unscaled)])
        if (coords == 'KSM' or coords == 'KSO'):
            self.units = OrderedDict([('Bx', u.nT), ('By', u.nT), ('Bz', u.nT),
                                      ('X', Rs), ('Y', Rs), ('Z', Rs),
                                      ('|B|', u.nT),
                                      ('Local hour', u.dimensionless_unscaled),
                                      ('n points', u.dimensionless_unscaled)])
Esempio n. 22
0
def test_read_cdf_empty_variable():
    # This tests that:
    # - A CDF file with an empty column can be read
    # - Unknown unit handling works as expected
    result = sunpy.net.Fido.search(a.Time('2020-01-01', '2020-01-02'),
                                   a.cdaweb.Dataset('AC_H6_SWI'))
    filename = Fido.fetch(result[0, 0])

    # Temporarily reset sunpy.io.cdf registry of known unit conversions
    import sunpy.io.cdf as sunpy_cdf
    known_units = sunpy_cdf._known_units
    sunpy_cdf._known_units = {}

    with pytest.warns(SunpyUserWarning, match='Assigning dimensionless units'):
        ts = sunpy.timeseries.TimeSeries(filename)

    assert ts.quantity('nH').unit == u.dimensionless_unscaled

    # Put back known unit registry, and check that units are recognised
    sunpy_cdf._known_units = known_units
    ts = sunpy.timeseries.TimeSeries(filename)
    assert ts.quantity('nH').unit == u.cm**-3

    # Reset again to check that registring units via. astropy works too
    sunpy_cdf._known_units = {}
    u.add_enabled_units([u.def_unit('#/cm^3', represents=u.cm**-3)])
    ts = sunpy.timeseries.TimeSeries(filename)
    assert ts.quantity('nH').unit == u.cm**-3

    sunpy_cdf._known_units = known_units
Esempio n. 23
0
	def __init__(self,cosmoModel=cosmology.WMAP9):

		assert isinstance(cosmoModel,cosmology.FLRW),"cosmoModel should be a valid astropy cosmology instance!"
		self.cosmoModel = cosmoModel

		#Define also the Mpc/h units for convenience
		self.Mpc_over_h = def_unit("Mpc/h",Mpc/self.cosmoModel.h)
Esempio n. 24
0
def aspcapStar_loader(file_obj, **kwargs):
    """
    Loader for APOGEE aspcapStar files.

    Parameters
    ----------
    file_obj: str or file-like
        FITS file name or object (provided from name by Astropy I/O Registry).

    Returns
    -------
    data: Spectrum1D
        The spectrum that is represented by the data in this table.
    """

    with read_fileobj_or_hdulist(file_obj, **kwargs) as hdulist:
        header = hdulist[0].header
        meta = {'header': header}
        wcs = WCS(hdulist[1].header)

        data = hdulist[1].data  # spectrum in the first extension
        unit = def_unit('arbitrary units')

        uncertainty = StdDevUncertainty(hdulist[2].data)

    # dispersion from the WCS but convert out of logspace
    dispersion = 10**wcs.all_pix2world(np.arange(data.shape[0]), 0)[0]
    dispersion_unit = Unit('Angstrom')

    return Spectrum1D(data=data * unit,
                      uncertainty=uncertainty,
                      spectral_axis=dispersion * dispersion_unit,
                      meta=meta,
                      wcs=wcs)
Esempio n. 25
0
def get_y_units(y_data, filename, y_error=[]):
    """finds flux/reflectance units
       inputs: y_data, spectrum file
       outputs: scaled flux with Units
    """
    y_factor = 1
    if "ctiostan" in filename and '.dat' in filename:  # from ESO aaareadme.ctio
        y_units = u.erg/(u.cm**2)/u.s/u.AA
        y_factor = 10**16

    elif .001 < np.median(y_data) < 10:  # Probably Normalized
        y_units = u.def_unit("Normalized_Reflectance", u.dimensionless_unscaled)

    elif '_2df_ex.fits' in filename:  # from FLOYDS
        y_factor = 10**20
        y_units = u.erg/(u.cm**2)/u.s/u.AA

    else:
        logger.warning("Could not parse flux units from file. Assuming erg/cm^2/s/A")
        y_units = u.erg/(u.cm**2)/u.s/u.AA

    yyy = np.array(y_data)
    err = np.array(y_error)
    flux = ((yyy / y_factor) * y_units)
    error = ((err / y_factor) * y_units)
    return flux, error
Esempio n. 26
0
def cdf_dict(unit_string):
    """
    Method to obtain the unit denoted by the strings inside the CDF files in
    the UNIT attribute.
    """
    ionic_charge = u.def_unit('Charged State', 1.6021766 * (10**-19) * u.C)

    units = OrderedDict([('ratio', u.dimensionless_unscaled),
                         ('Unitless', u.dimensionless_unscaled),
                         ('unitless', u.dimensionless_unscaled),
                         ('Spacecraft', u.dimensionless_unscaled),
                         ('microW m^-2', u.mW * u.m**-2), ('years', u.yr),
                         ('days', u.d), ('#/cc', u.cm**-3),
                         ('#/cm^3', u.cm**-3), ('cm^{-3}', u.cm**-3),
                         ('particles cm^-3', u.cm**-3),
                         ('n/cc (from moments)', u.cm**-3),
                         ('n/cc (from fits)', u.cm**-3),
                         ('km/sec (from fits)', u.km / u.s),
                         ('km/sec (from moments)', u.km / u.s),
                         ('ionic charge', u.electron),
                         ('earth radii', u.earthRad), ('Re', u.earthRad),
                         ('Degrees', u.deg), ('degrees', u.deg),
                         ('deg (from fits)', u.deg),
                         ('deg (from moments)', u.deg),
                         ('#/{cc*(cm/s)^3}', (u.cm**3 * (u.cm / u.s)**3)**-1),
                         ('sec', u.s), ('seconds', u.s), ('nT GSE', u.nT),
                         ('nT GSM', u.nT), ('nT DSL', u.nT), ('nT SSL', u.nT),
                         ('msec', u.ms), ('ionic charge', ionic_charge)])
    try:
        return units[unit_string]
    except KeyError:
        return None
Esempio n. 27
0
def mkwvl(quantity, base=u.um):
    """Generate a new Wavelength unit.

    Parameters
    ----------
    quantity : `float` or `astropy.units.unit`
        number of (base) for the wavelength, e.g. quantity=632.8 with base=u.nm for HeNe.
        if an astropy unit, simply returned by this function
    base : `astropy.units.Unit`
        base unit, e.g. um or nm

    Returns
    -------
    `astropy.units.Unit`
        new Unit for appropriate wavelength

    """
    if quantity is None:
        return quantity
    elif not isinstance(quantity, u.Unit):
        return u.def_unit(['wave', 'wavelength'],
                          quantity * base,
                          format={
                              'latex': r'\lambda',
                              'unicode': 'λ'
                          })
    else:
        return quantity
Esempio n. 28
0
    def test_auto_alt_unit(self):

        self.table['altitude'] = [1, 4, 5] * u.au
        self.table['altitude2'] = [1, 4, 5] * u.def_unit(
            'same_as_km', 1000 * u.m)
        self.table['flux'].unit = u.kg

        layer = self.client.layers.add_table_layer(table=self.table)

        assert layer.alt_att == ''
        assert layer.alt_unit is None

        layer.alt_att = 'altitude'
        assert layer.alt_unit is u.au

        layer.alt_att = 'altitude2'
        assert layer.alt_unit is u.km

        expected_warning = (
            'Column flux has units of kg but this is not a '
            'valid unit of altitude - set the unit directly with '
            'alt_unit')

        with pytest.warns(UserWarning, match=expected_warning):
            layer.alt_att = 'flux'
Esempio n. 29
0
	def setHeaderInfo(self,Om0=0.26,Ode0=0.74,w0=-1.0,wa=0.0,h=0.72,redshift=100.0,box_size=15.0*u.Mpc/0.72,flag_cooling=0,flag_sfr=0,flag_feedback=0,flag_stellarage=0,flag_metals=0,flag_entropy_instead_u=0,masses=np.array([0,1.03e10,0,0,0,0])*u.Msun,num_particles_file_of_type=None,npartTotalHighWord=np.zeros(6,dtype=np.uint32)):

		"""
		Sets the header info in the snapshot to write

		"""

		if num_particles_file_of_type is None:
			num_particles_file_of_type = np.array([0,1,0,0,0,0],dtype=np.int32) * self.positions.shape[0]

		assert num_particles_file_of_type.sum()==self.positions.shape[0],"The total number of particles must match!!"
		assert box_size.unit.physical_type=="length"
		assert masses.unit.physical_type=="mass"

		#Create the header
		self._header = Gadget2Header()
		
		#Fill in
		self._header["Om0"] = Om0
		self._header["Ode0"] = Ode0
		self._header["w0"] = w0
		self._header["wa"] = wa
		self._header["h"] = h
		self._header["H0"] = 100.0*h*u.km/(u.s*u.Mpc)
		self._header["redshift"] = redshift
		self._header["scale_factor"] = 1.0 / (1.0 + redshift)
		self._header["box_size"] = box_size
		self._header["flag_cooling"] = flag_cooling
		self._header["flag_sfr"] = flag_sfr
		self._header["flag_feedback"] = flag_feedback
		self._header["flag_stellarage"] = flag_stellarage
		self._header["flag_metals"] = flag_metals
		self._header["flag_entropy_instead_u"] = flag_entropy_instead_u
		self._header["masses"] = masses
		self._header["num_particles_file_of_type"] = num_particles_file_of_type
		self._header["num_particles_file"] = num_particles_file_of_type.sum()
		self._header["num_particles_total_of_type"] = num_particles_file_of_type
		self._header["num_particles_total"] = num_particles_file_of_type.sum()
		self._header["npartTotalHighWord"] = npartTotalHighWord

		#Define the kpc/h and Mpc/h units for convenience
		self.kpc_over_h = u.def_unit("kpc/h",u.kpc/self._header["h"])
		self.Mpc_over_h = u.def_unit("Mpc/h",u.Mpc/self._header["h"])

		#Compute the comoving distance according to the model
		cosmo = w0waCDM(H0=100.0*h,Om0=Om0,Ode0=Ode0,w0=w0,wa=wa)
		self._header["comoving_distance"] = cosmo.comoving_distance(redshift).to(self.Mpc_over_h)
Esempio n. 30
0
    def setup_bases(self):
        """Set the standard, non-dimensional bases"""
        temperature_unit = u.def_unit("Box-delta-T", np.abs(self.deltaT))
        length_unit = u.def_unit("Box-D", self.depth)
        viscosity_unit = u.def_unit("kappa", self.primary_viscosity)
        time_unit = length_unit**2 / viscosity_unit
        self.add_bases(
            "nondimensional",
            set([temperature_unit, length_unit, viscosity_unit, time_unit]))

        temperature_unit = self.deltaT.unit
        length_unit = self.depth.unit
        time_unit = type(self).Time.unit
        viscosity_unit = length_unit**2 / time_unit
        self.add_bases(
            "standard",
            set([temperature_unit, length_unit, time_unit, viscosity_unit]))
Esempio n. 31
0
 def static_theta_E(z_s, z_l):
     dS = Cosmic.cosmology.angular_diameter_distance(z_s)
     dL = Cosmic.cosmology.angular_diameter_distance(z_l)
     dLS = Cosmic.cosmology.angular_diameter_distance_z1z2(z_l, z_s)
     Msun = 1 * u.solMass
     tmp = (4 * const.G * Msun / const.c / const.c) * (dL * dLS / dS)
     ret = (tmp**0.5 / dL).to('').value
     return u.def_unit('theta_E', ret * u.rad)
Esempio n. 32
0
    def _generate_unit_names():

        from astropy import units as u
        names = {}
        deprecated_names = set()

        bases = [
            'A', 'C', 'cd', 'eV', 'F', 'g', 'H', 'Hz', 'J',
            'Jy', 'K', 'lm', 'lx', 'm', 'mol', 'N', 'ohm', 'Pa',
            'pc', 'rad', 's', 'S', 'sr', 'T', 'V', 'W', 'Wb'
        ]
        deprecated_bases = []
        prefixes = [
            'y', 'z', 'a', 'f', 'p', 'n', 'u', 'm', 'c', 'd',
            '', 'da', 'h', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'
        ]

        for base in bases + deprecated_bases:
            for prefix in prefixes:
                key = prefix + base
                if keyword.iskeyword(key):
                    continue
                names[key] = getattr(u, key)
        for base in deprecated_bases:
            for prefix in prefixes:
                deprecated_names.add(prefix + base)

        simple_units = [
            'angstrom', 'arcmin', 'arcsec', 'AU', 'barn', 'bin',
            'byte', 'chan', 'count', 'day', 'deg', 'erg', 'G',
            'h', 'lyr', 'mag', 'min', 'photon', 'pixel',
            'voxel', 'yr'
        ]
        for unit in simple_units:
            names[unit] = getattr(u, unit)

        # Create a separate, disconnected unit for the special case of
        # Crab and mCrab, since OGIP doesn't define their quantities.
        Crab = u.def_unit(['Crab'], prefixes=False, doc='Crab (X-ray flux)')
        mCrab = u.Unit(10 ** -3 * Crab)
        names['Crab'] = Crab
        names['mCrab'] = mCrab

        deprecated_units = ['Crab', 'mCrab']
        for unit in deprecated_units:
            deprecated_names.add(unit)

        # Define the function names, so we can parse them, even though
        # we can't use any of them (other than sqrt) meaningfully for
        # now.
        functions = [
            'log', 'ln', 'exp', 'sqrt', 'sin', 'cos', 'tan', 'asin',
            'acos', 'atan', 'sinh', 'cosh', 'tanh'
        ]
        for name in functions:
            names[name] = name

        return names, deprecated_names, functions
Esempio n. 33
0
    def _generate_unit_names():

        from astropy import units as u
        names = {}
        deprecated_names = set()

        bases = [
            'A', 'C', 'cd', 'eV', 'F', 'g', 'H', 'Hz', 'J',
            'Jy', 'K', 'lm', 'lx', 'm', 'mol', 'N', 'ohm', 'Pa',
            'pc', 'rad', 's', 'S', 'sr', 'T', 'V', 'W', 'Wb'
        ]
        deprecated_bases = []
        prefixes = [
            'y', 'z', 'a', 'f', 'p', 'n', 'u', 'm', 'c', 'd',
            '', 'da', 'h', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'
        ]

        for base in bases + deprecated_bases:
            for prefix in prefixes:
                key = prefix + base
                if keyword.iskeyword(key):
                    continue
                names[key] = getattr(u, key)
        for base in deprecated_bases:
            for prefix in prefixes:
                deprecated_names.add(prefix + base)

        simple_units = [
            'angstrom', 'arcmin', 'arcsec', 'AU', 'barn', 'bin',
            'byte', 'chan', 'count', 'day', 'deg', 'erg', 'G',
            'h', 'lyr', 'mag', 'min', 'photon', 'pixel',
            'voxel', 'yr'
        ]
        for unit in simple_units:
            names[unit] = getattr(u, unit)

        # Create a separate, disconnected unit for the special case of
        # Crab and mCrab, since OGIP doesn't define their quantities.
        Crab = u.def_unit(['Crab'], prefixes=False, doc='Crab (X-ray flux)')
        mCrab = u.Unit(10 ** -3 * Crab)
        names['Crab'] = Crab
        names['mCrab'] = mCrab

        deprecated_units = ['Crab', 'mCrab']
        for unit in deprecated_units:
            deprecated_names.add(unit)

        # Define the function names, so we can parse them, even though
        # we can't use any of them (other than sqrt) meaningfully for
        # now.
        functions = [
            'log', 'ln', 'exp', 'sqrt', 'sin', 'cos', 'tan', 'asin',
            'acos', 'atan', 'sinh', 'cosh', 'tanh'
        ]
        for name in functions:
            names[name] = name

        return names, deprecated_names, functions
Esempio n. 34
0
    def t_UNIT(self, t):
        r'<[\w*^\-/]+>'
        import astropy.units as u

        # most astropy units are lower-case versions of the PDS3 units
        unit = t.value[1:-1].lower()

        # but not all
        if unit in self.unit_translate:
            unit = self.unit_translate[unit]

        _degC = u.def_unit('degC', u.deg_C)
        _degc = u.def_unit('degc', _degC)
        _w = u.def_unit('w', u.W)
        u.add_enabled_units([_degC,_degc,_w])

        t.value = u.Unit(unit)
        return t
Esempio n. 35
0
 def calculateAvgMassEinsteinRadius(gz, qz):
     avgMass = 0.247
     # avgMass = 0.20358470458734301
     dL = cosmo.angular_diameter_distance(gz).to('m')
     dS = cosmo.angular_diameter_distance(qz).to('m')
     dLS = cosmo.angular_diameter_distance_z1z2(gz, qz).to('m')
     thetaE = 4 * const.G * u.Quantity(
         avgMass, 'solMass').to('kg') * dLS / dL / dS / const.c / const.c
     thetaEUnit = u.def_unit('theta_E', math.sqrt(thetaE.value) * u.rad)
     return thetaEUnit
Esempio n. 36
0
 def setup_bases(self):
     """Setup the standard bases."""
     super(MagnetoSystem, self).setup_bases()
     magnetic_unit = u.def_unit("B0", self.B0)
     mass_unit = magnetic_unit * u.A * u.s**2
     self._bases["standard"][u.T.physical_type] = u.T
     self._bases["standard"][u.kg.physical_type] = u.kg
     self._bases["standard"][u.A.physical_type] = u.A
     self._bases["nondimensional"][magnetic_unit.physical_type] = magnetic_unit
     self._bases["nondimensional"][mass_unit.physical_type] = mass_unit
     self._bases["nondimensional"][u.A.physical_type] = u.A
    def _locally_defined_pixel_units():
        """
        list of defined spectral pixel units.
        :return: list of unit strings
        """
        units = ["pixel"]

        spaxel = u.def_unit('spaxel', u.astrophys.pix)
        u.add_enabled_units(spaxel)
        units.append('spaxel')

        return units
Esempio n. 38
0
 def load_units(self):
     """Load all unit definitions as defined in the [units] section
     """
     try:
         customunits = self.nditems('units')
     except configparser.NoSectionError:
         return []
     else:
         new_ = []
         for unit, b in customunits:
             if b.lower() == 'dimensionless':
                 b = ''
             new_.append(units.def_unit([unit], units.Unit(b)))
         units.add_enabled_units(new_)
         return new_
Esempio n. 39
0
    def _get_unit(cls, t):
        # match as normal
        try:
            return cls._parse_unit(t.value)
        except ValueError as exc:
            name = t.value
            sname = name[:-1] if name.endswith('s') else ''

            # parse alternative units from the error message
            match = cls.re_closest_unit.search(str(exc))
            try:  # split 'A, B, or C' -> ['A', 'B', 'C']
                alts = cls.re_closest_unit_delim.split(match.groups()[0])[::2]
            except AttributeError:
                alts = []
            alts = list(set(alts))

            # match uppercase to titled (e.g. MPC -> Mpc)
            if name.title() in alts:
                alt = name.title()
            # match titled unit to lower-case (e.g. Amp -> amp)
            elif name.lower() in alts:
                alt = name.lower()
            # match plural to singular (e.g. meters -> meter)
            elif sname in alts:
                alt = sname
            elif sname.lower() in alts:
                alt = sname.lower()
            else:
                if cls.warn:
                    warnings.warn(
                        '{0} Mathematical operations using this unit should '
                        'work, but conversions to other units will '
                        'not.'.format(str(exc).rstrip(' ')),
                        category=units.UnitsWarning)
                try:  # return previously created unit
                    return UNRECOGNIZED_UNITS[name]
                except KeyError:  # or create new one now
                    u = UNRECOGNIZED_UNITS[name] = units.def_unit(
                        name, doc='Unrecognized unit')
                    return u
            return cls._parse_unit(alt)
Esempio n. 40
0
def aspcapStar_loader(file_name, **kwargs):
    """
    Loader for APOGEE aspcapStar files.

    Parameters
    ----------
    file_name: str
        The path to the FITS file

    Returns
    -------
    data: Spectrum1D
        The spectrum that is represented by the data in this table.
    """
    name = os.path.basename(file_name.rstrip(os.sep)).rsplit('.', 1)[0]
    hdulist = fits.open(file_name, **kwargs)

    header = hdulist[0].header
    meta = {'header': header}
    wcs = WCS(hdulist[1].header)

    data = hdulist[1].data # spectrum in the first extension
    unit = def_unit('arbitrary units')

    uncertainty = StdDevUncertainty(hdulist[2].data)

    # dispersion from the WCS but convert out of logspace
    dispersion = 10**wcs.all_pix2world(np.arange(data.shape[0]), 0)[0]
    dispersion_unit = Unit('Angstrom')
    hdulist.close()

    return Spectrum1D(data=data * unit,
                      uncertainty=uncertainty,
                      dispersion=dispersion * dispersion_unit,
                      meta=meta,
                      wcs=wcs)
Esempio n. 41
0
"""

from .extern._version import get_versions
__version__ = get_versions()['version']
del get_versions

# Define a few important constants
import astropy.units as u
from astropy.units import si
import astropy.constants as c
import astropy.time as time
import numpy as np
from . import utils

# light-second unit
ls = u.def_unit('ls', c.c * 1.0 * u.s)

# DM unit (pc cm^-3)
dmu = u.def_unit('dmu', u.pc*u.cm**-3)

# define equivalency for astropy units
light_second_equivalency = [(ls, si.second, lambda x: x, lambda x: x)]
dimensionless_cycles = [(u.cycle, None)]
# hourangle_second unit
hourangle_second = u.def_unit('hourangle_second', u.hourangle/np.longdouble(3600.0))

# Following are from here:
# http://ssd.jpl.nasa.gov/?constants (grabbed on 30 Dec 2013)
GMsun = 1.32712440018e20 * u.m**3/u.s**2

# Solar mass in time units (sec)
Esempio n. 42
0
HC = H * C
SR_PER_ARCSEC2 = u.rad.to(u.arcsec) ** -2  # steradian per arcsec^2

# ------------- #
# synphot units #
# ------------- #

# Default unit of area covered by flux
AREA = u.cm * u.cm

# synphot unitless unit (using def_unit mess up arithmetic result unit string)
THROUGHPUT = u.dimensionless_unscaled

# synphot flux units
PHOTLAM = u.def_unit(
    'photlam', u.photon / (u.cm**2 * u.s * u.AA),
    format={'generic': 'PHOTLAM', 'console': 'PHOTLAM'})
PHOTNU = u.def_unit(
    'photnu', u.photon / (u.cm**2 * u.s * u.Hz),
    format={'generic': 'PHOTNU', 'console': 'PHOTNU'})
FLAM = u.def_unit(
    'flam', u.erg / (u.cm**2 * u.s * u.AA),
    format={'generic': 'FLAM', 'console': 'FLAM'})
FNU = u.def_unit(
    'fnu', u.erg / (u.cm**2 * u.s * u.Hz),
    format={'generic': 'FNU', 'console': 'FNU'})
OBMAG = u.def_unit(
    'obmag', u.mag, format={'generic': 'OBMAG', 'console': 'OBMAG'})
VEGAMAG = u.def_unit(
    'vegamag', u.mag, format={'generic': 'VEGAMAG', 'console': 'VEGAMAG'})
Esempio n. 43
0
# hscimgloader.py 
# ALS 2017/05/02

import numpy as np
import os
import requests
import astropy.units as u
from astropy.io import fits
import re

from ..loader import imgLoader
from ...filters import surveysetup
from ..get_credential import getCrendential
from . import hscurl

nanomaggy = u.def_unit('nanomaggy', 3.631e-6*u.Jy)
u.add_enabled_units([nanomaggy])
u.nanomaggy=nanomaggy


class hscimgLoader(imgLoader):

	def __init__(self, **kwargs):
		""" 
		hscimgLoader, child of imgLoader

		download stamps from HSC DAS Quarry
		download psf by either: 
			(iaa) call sumire to infer psf from calexp and download psf from sumire
			(online) download calexp from server and infer psf locally
Esempio n. 44
0
def test_flatten_to_known():
    myunit = u.def_unit("FOOBAR_One", u.erg / u.Hz)
    assert myunit.to_string('fits') == 'erg Hz-1'
    myunit2 = myunit * u.bit ** 3
    assert myunit2.to_string('fits') == 'bit3 erg Hz-1'
Esempio n. 45
0
def test_flatten_impossible():
    myunit = u.def_unit("FOOBAR_Two")
    with u.add_enabled_units(myunit), pytest.raises(ValueError):
        myunit.to_string('fits')
Esempio n. 46
0
from glue.lal import (Cache, CacheEntry)

from .array import *
from .array2d import *
from .series import *

# define custom time-series units
try:
    from astropy import (__version__ as astropyversion, units)
except ImportError:
    pass
else:
    from distutils.version import LooseVersion
    if LooseVersion(astropyversion) < LooseVersion('0.3'):
        units.def_unit(['counts'], represents=units.Unit('count'),
                       register=True)
        units.def_unit(['strain'], represents=units.dimensionless_unscaled,
                       register=True)
        units.def_unit(['coherence'], represents=units.dimensionless_unscaled,
                       register=True)
    else:
        units.add_enabled_units([
            units.def_unit(['counts'], units.Unit('count')),
            units.def_unit(['coherence'], units.dimensionless_unscaled),
            units.def_unit(['strain'], units.dimensionless_unscaled),
            ])

__all__ = ['Array', 'Array2D', 'Series', 'Cache', 'CacheEntry']

Esempio n. 47
0
import astropy.units as u
import astropy.constants as co


########################################################################
# Define new uv-coordinate units

lambdas = u.def_unit('lambdas', format={'format' : r'\lambda'})
klambdas = u.def_unit('kilolambdas', 1e3 * lambdas, format={'format' : r'k\lambda'})

# equivalency (from_unit, to_unit, forward, backward)
def lambdas_equivalencies(restunit):
    try:
        restfreq_hz = restunit.to(u.Hz, equivalencies=u.spectral())
    except (AttributeError):
        raise AttributeError('input \'restfreq\' should be a spectral unit.')
    eq = [
        (lambdas, u.s, lambda x: x/restfreq_hz, lambda x: x*restfreq_hz),
        (lambdas, u.m, lambda x: x/restfreq_hz * co.c.to(u.m/u.s).value, lambda x: x/co.c.to(u.m/u.s).value * restfreq_hz),
        (u.m, u.s, lambda x: x/co.c.to(u.m/u.s).value, lambda x: x*co.c.to(u.m/u.s).value),
        ]
    return eq


########################################################################


# BINNING
def uv_bin_vector(uvdist, re, im, wt, start='zero', binsize=10, nbins=50, weighted=False):
    """
Esempio n. 48
0
def make_table(header, section_lines):
    """
    From the seperated section lines and the header, clean up the data and
    convert to a QTable.
    """
    meta_data = get_meta_data(header)

    tables = []
    for i, lines in enumerate(section_lines):
        if lines:
            key = list(meta_data['id'].keys())[i]
            t1 = astropy.io.ascii.read(lines)

            if len(t1) == 0:
                col_data_types = {
                    # ID : <class 'str'>
                    'Nmbr': np.dtype('i4'),
                    'Location': np.dtype('U6'),
                    'Lo': np.dtype('i8'),
                    'Area': np.dtype('i8'),
                    'Z': np.dtype('U3'),
                    'LL': np.dtype('i8'),
                    'NN': np.dtype('i8'),
                    'MagType': np.dtype('S4'),
                    'Lat': np.dtype('i8')
                }
                for c in t1.itercols():
                    # Put data types of columns in empty table to correct types,
                    # or else vstack will fail.
                    c.dtype = col_data_types[c._name]
                t1.add_column(
                    Column(data=None, name="ID", dtype=('S2')), index=0)
            else:
                t1.add_column(Column(data=[key] * len(t1), name="ID"), index=0)

            tables.append(t1)

    out_table = vstack(tables)

    # Parse the Location column in Table 1
    if 'Location' in out_table.columns:
        col_lat, col_lon = parse_location(out_table['Location'])
        del out_table['Location']
        out_table.add_column(col_lat)
        out_table.add_column(col_lon)

    # Parse the Lat column in Table 3
    if 'Lat' in out_table.columns:
        parse_lat_col(out_table['Lat'], out_table['Latitude'])
        del out_table['Lat']

    # Give columns more sensible names
    out_table.rename_column("Nmbr", "Number")
    out_table.rename_column("NN", "Number of Sunspots")
    out_table.rename_column("Lo", "Carrington Longitude")
    out_table.rename_column("MagType", "Mag Type")
    out_table.rename_column("LL", "Longitudinal Extent")

    # Define a Solar Hemispere Unit
    a = {}
    u.def_unit(
        "SH",
        represents=(2 * np.pi * u.solRad**2),
        prefixes=True,
        namespace=a,
        doc="A solar hemisphere is the area of the visible solar disk.")

    # Set units on the table
    out_table['Carrington Longitude'].unit = u.deg
    out_table['Area'].unit = a['uSH']
    out_table['Longitudinal Extent'].unit = u.deg

    out_table.meta = meta_data

    # Number should be formatted in 10000 after 2002-06-15.
    if out_table.meta['issued'] > datetime.datetime(2002, 6, 15):
        out_table['Number'] += 10000

    return QTable(out_table)
Esempio n. 49
0
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GWpy.  If not, see <http://www.gnu.org/licenses/>.


"""Package to do gravitational wave astrophysics with python
"""

from astropy import table
try:
    from astropy.units.quantity import WARN_IMPLICIT_NUMERIC_CONVERSION
except ImportError:
    pass
else:
    WARN_IMPLICIT_NUMERIC_CONVERSION.set(False)

import warnings
warnings.filterwarnings("ignore", "Module (.*) was already import from")

# set metadata
from . import version
__author__ = "Duncan Macleod <*****@*****.**>"
__version__ = version.version

# register new unit at the top level
from astropy import units
units.def_unit(['counts'], represents=units.Unit('count'), register=True)
units.def_unit(['strain'], represents=units.Unit(''), register=True)
Esempio n. 50
0
      print 'No limits to cancel.'
  def __addwindow(self,limlo,limhi):
    if limhi < limlo:
      limlo,limhi = limhi,limlo
    self.windows.append([limlo,limhi])
  def __finalise(self):
    self.__addwindow(self.__limlo,self.__limhi)
    self.__ax.figure.canvas.mpl_disconnect(self.__buttonListener)
    self.__ax.figure.canvas.mpl_disconnect(self.__keyListener)
    plt.close(self.__ax.figure)

#---------------------
#New units definitions
#---------------------
#the units themselves
unit_t = u.def_unit('transmittance units',doc='Transmittance of radiation')
unit_transmittance = unit_t
unit_abs = u.def_unit('absorbance units',doc='Absorbance of radiation')
unit_absorbance = unit_abs
unit_od = u.def_unit('optical depth units',doc='Optical depth of radiation')
unit_opticaldepth = unit_od

#the equivalencies between the units
equivalencies_absorption = [
    (unit_t,unit_abs,lambda x:-np.log10(x),lambda x:10**-x),
    (unit_od,unit_abs,lambda x:x/np.log(10),lambda x:x*np.log(10)),
    (unit_od,unit_t,lambda x:10**(-x/np.log(10)),lambda x:-np.log10(x)*np.log(10))
    ]

#------------------------------------------------------
#Functions related to light scattering and transmission
Esempio n. 51
0
import astropy.units as u
import astropy.constants as ac
import astropy.coordinates.angles as ang
import matplotlib.pyplot as plt
from astropy import log
import time, copy

import collections

try:
    from collections import OrderedDict
except ImportError:
    from ordereddict import OrderedDict

# Make sure we have the minuteangle and secondangle units
u.minuteangle = u.def_unit('minuteangle', u.hourangle / 60)
u.secondangle = u.def_unit('secondangle', u.minuteangle / 60)
u.lts = u.def_unit(['lightsecond','ls','lts'], ac.c * u.s)

# In the case of a unitless interface, we need to make sure we provide the
# 'correct' tempo2-like units
map_units = {
             'F0': u.Hz,
             'F1': u.Hz/u.s,
             'F2': u.Hz/u.s**2, 
             'F3': u.Hz/u.s**3, 
             'F4': u.Hz/u.s**4, 
             'F5': u.Hz/u.s**5, 
             'F6': u.Hz/u.s**6, 
             'F7': u.Hz/u.s**7, 
             'F8': u.Hz/u.s**8, 
Esempio n. 52
0
# Top-level PINT __init__.py
"""
PINT Is Not TEMPO3!
"""
import os

# Define a few important constants
import astropy.units as u
import astropy.constants as c

# light-second unit
ls = u.def_unit('ls', c.c * 1.0 * u.s)

# Following are from here:
# http://ssd.jpl.nasa.gov/?constants (grabbed on 30 Dec 2013)
GMsun = 1.32712440018e20 * u.m**3/u.s**2

# Solar mass in time units (sec)
Tsun = (GMsun / c.c**3).to(u.s)

# Planet system(!) masses in time units
Tmercury = Tsun / 6023600.
Tvenus = Tsun / 408523.71
Tearth = Tsun / 328900.56 # Includes Moon!
Tmars = Tsun / 3098708.
Tjupiter = Tsun / 1047.3486
Tsaturn = Tsun / 3497.898
Turanus = Tsun / 22902.98
Tneptune = Tsun / 19412.24

# setup environment
Esempio n. 53
0
import math, shlex, subprocess, numpy
import astropy.constants as const
import astropy.units as u
from pint.utils import PosVel
from astropy import log
import os

from pinttestdata import testdir, datadir

log.setLevel('ERROR')
# for nice output info, set the following instead
#log.setLevel('INFO')

observatories = obsmod.read_observatories()

ls = u.def_unit('ls', const.c * 1.0 * u.s)

log.info("Reading TOAs into PINT")
ts = toa.get_TOAs(datadir + "/testtimes.tim",usepickle=False)
if log.level < 25:
    ts.print_summary()
ts.table.sort('index')

log.info("Calling TEMPO2")
#cmd = 'tempo2 -output general2 -f tests/testtimes.par tests/testtimes.tim -s "XXX {clock0} {clock1} {clock2} {clock3} {tt} {t2tb} {telSSB} {telVel} {Ttt}\n"'
cmd = 'tempo2 -output general2 -f ' + datadir+'/testtimes.par ' + datadir + \
      '/testtimes.tim -s "XXX {clock0} {clock1} {clock2} {clock3} {tt} {t2tb} {earth_ssb1} {earth_ssb2} {earth_ssb3} {earth_ssb4} {earth_ssb5} {earth_ssb6} {telEpos} {telEVel} {Ttt}\n"'
args = shlex.split(cmd)

tout = subprocess.check_output(args)
goodlines = [x for x in tout.split("\n") if x.startswith("XXX")]
Esempio n. 54
0
""" Module for spec widgets
"""
from __future__ import print_function, absolute_import, division, unicode_literals


import numpy as np
import pdb

from PyQt4 import QtGui
from PyQt4 import QtCore

from astropy.units import Quantity
from astropy import constants as const
from astropy import units as u
u.def_unit(['mAA', 'milliAngstrom'], 0.001 * u.AA, namespace=globals()) # mA

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

from astropy.modeling import models, fitting

from linetools.guis import utils as ltgu
from linetools.guis import line_widgets as ltgl
from linetools.spectra.xspectrum1d import XSpectrum1D
from ..spectralline import AbsLine
from ..analysis import voigt as ltv


class ExamineSpecWidget(QtGui.QWidget):
    """ Widget to plot a spectrum and interactively
        fiddle about.  Akin to XIDL/x_specplot.pro
Esempio n. 55
0
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GWpy.  If not, see <http://www.gnu.org/licenses/>.

"""This module registers a number of custom units used in GW astronomy.
"""

from .. import version
__author__ = "Duncan Macleod <*****@*****.**>"
__version__ = version.version

from astropy import units

# enable imperial units
units.add_enabled_units(units.imperial)

# -----------------------------------------------------------------------------
# instrumental units

units.add_enabled_units([
    units.def_unit(['counts'], represents=units.Unit('count')),
    units.def_unit(['undef'], doc='No unit has been defined for these data'),
    units.def_unit(['coherence'], represents=units.dimensionless_unscaled),
    units.def_unit(['strain'], represents=units.dimensionless_unscaled),
    units.def_unit(['Degrees_C'], represents=units.Unit('Celsius')),
    units.def_unit(['Degrees_F'], represents=units.Unit('Fahrenheit')),
])
Esempio n. 56
0
File: units.py Progetto: gwpy/gwsumm
# This file is part of GWSumm.
#
# GWSumm is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# GWSumm is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GWSumm.  If not, see <http://www.gnu.org/licenses/>.

"""Extra units for GW data processing
"""

__author__ = 'Duncan Macleod <*****@*****.**>'

from astropy import units
import gwpy.detector.units  # noqa: F401

_ns = {}  # collector for new units

# Virgo units
units.def_unit('state', namespace=_ns)

# -- register new units -----
units.add_enabled_units(_ns)
Esempio n. 57
0
import warnings
import numpy as np
from astropy import units as u
from astropy.utils import lazyproperty
from .utils import get_frame_rate


__all__ = ['u_sample', 'VLBIStreamBase', 'VLBIStreamReaderBase',
           'VLBIStreamWriterBase']

u_sample = u.def_unit('sample', doc='One sample from a data stream')


class VLBIStreamBase(object):
    """VLBI file wrapper, allowing access as a stream of data."""

    _frame_class = None

    def __init__(self, fh_raw, header0, nchan, bps, complex_data, thread_ids,
                 samples_per_frame, frames_per_second=None,
                 sample_rate=None):
        self.fh_raw = fh_raw
        self.header0 = header0
        self.nchan = nchan
        self.bps = bps
        self.complex_data = complex_data
        self.thread_ids = thread_ids
        self.nthread = nchan if thread_ids is None else len(thread_ids)
        self.samples_per_frame = samples_per_frame
        if frames_per_second is None:
            frames_per_second = sample_rate.to(u.Hz).value / samples_per_frame
Esempio n. 58
0
# 1) alternative names
registry = units.get_current_unit_registry().registry
for unit, aliases in [
        (units.Unit('ct'), ('counts',)),
        (units.Unit('Celsius'), ('Degrees_C', 'DegC')),
        (units.Unit('Fahrenheit'), ('Degrees_F', 'DegF')),
]:
    unit.names.extend(aliases)
    for alias in aliases:
        registry[alias] = unit

# 2) new units
_ns = {}

# LIGO-Lab standard for 'no unit defined'
units.def_unit(['NONE', 'undef'], namespace=_ns,
               doc='No unit has been defined for these data')

# other dimenionless units
units.def_unit('strain', represents=units.Unit(''), namespace=_ns)
units.def_unit('coherence', namespace=_ns)

# alias for 'second' but with prefices
units.def_unit((['sec'], ['sec']), represents=units.second, prefixes=True,
               namespace=_ns)

# alternative Pressure unit for LIGO UHV
units.def_unit((['torr'], ['torr']), represents=101325/760.*units.pascal,
               prefixes=True, namespace=_ns)

# pounds per square inch gauge
units.def_unit('psig', represents=units.imperial.psi, prefixes=True,