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
def from_json(cls, js): try: z_s = js['source']['redshift'] z_l = js['lens']['redshift'] mass = Jsonable.decode_quantity(js['source']['mass']) special_units = Parameters.special_units(z_s, z_l, mass) with u.add_enabled_units(special_units): gal = Lens.from_json(js['lens']) src = Quasar.from_json(js['source']) rays = Vec2D.from_json(js['ray_count']) sg = MassFunction.from_json(js['star_generator']) pcnts = js['percent_stars'] spln = Region.from_json(js['source_plane']) center = Vec2D.from_json(js['image_center']) return cls(src, gal, pcnts, center, rays, spln, sg) except KeyError as e: print(e) params = Parameters.from_json(js) with u.add_enabled_units([params.quasar.r_g, params.theta_E]): sg = MassFunction.from_json(js['star_generator']) pcnts = js['percent_stars'] spln = Region.from_json(js['source_plane']) rays = params.ray_region.resolution center = params.ray_region.center return cls(params.quasar, params.lens, pcnts, center, rays, spln, sg)
def test_pickling(): p = pickle.dumps(u.m) other = pickle.loads(p) assert other is u.m new_unit = u.IrreducibleUnit(['foo'], format={'baz': 'bar'}) # This is local, so the unit should not be registered. assert 'foo' not in u.get_current_unit_registry().registry # Test pickling of this unregistered unit. p = pickle.dumps(new_unit) new_unit_copy = pickle.loads(p) assert new_unit_copy.names == ['foo'] assert new_unit_copy.get_format_name('baz') == 'bar' # It should still not be registered. assert 'foo' not in u.get_current_unit_registry().registry # Now try the same with a registered unit. with u.add_enabled_units([new_unit]): p = pickle.dumps(new_unit) assert 'foo' in u.get_current_unit_registry().registry # Check that a registered unit can be loaded and that it gets re-enabled. with u.add_enabled_units([]): assert 'foo' not in u.get_current_unit_registry().registry new_unit_copy = pickle.loads(p) assert new_unit_copy.names == ['foo'] assert new_unit_copy.get_format_name('baz') == 'bar' assert 'foo' in u.get_current_unit_registry().registry # And just to be sure, that it gets removed outside of the context. assert 'foo' not in u.get_current_unit_registry().registry
def register_new_unit(new_unit): """ Add new unit to astropy.units :param new_unit: astropy unit """ u.add_enabled_units(new_unit) if FLUX_UNIT_REGISTRY.is_compatible(new_unit): FLUX_UNIT_REGISTRY.add_unit(new_unit) if new_unit.decompose() == u.pix.decompose() or \ 'solid angle' in new_unit.physical_type: AREA_UNIT_REGISTRY.add_unit(new_unit)
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
def register_new_unit(new_unit): """ Add new unit to astropy.units :param new_unit: astropy unit """ global AREA_UNIT_REGISTRY, FLUX_UNIT_REGISTRY u.add_enabled_units(new_unit) if FLUX_UNIT_REGISTRY.is_compatible(new_unit): FLUX_UNIT_REGISTRY.add_unit(new_unit) if new_unit.decompose() == u.pix.decompose() or \ 'solid angle' in new_unit.physical_type.lower(): AREA_UNIT_REGISTRY.add_unit(new_unit)
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
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_
def read_json(filename, **kwargs): """Read JSON. Parameters ---------- filename : str **kwargs Keyword arguments into :meth:`~astropy.cosmology.Cosmology.from_format` Returns ------- `~astropy.cosmology.Cosmology` instance """ # read if isinstance(filename, (str, bytes, os.PathLike)): with open(filename) as file: data = file.read() else: # file-like : this also handles errors in dumping data = filename.read() mapping = json.loads(data) # parse json mappable to dict # deserialize Quantity with u.add_enabled_units(cu.redshift): for k, v in mapping.items(): if isinstance(v, dict) and "value" in v and "unit" in v: mapping[k] = u.Quantity(v["value"], v["unit"]) for k, v in mapping.get("meta", {}).items(): # also the metadata if isinstance(v, dict) and "value" in v and "unit" in v: mapping["meta"][k] = u.Quantity(v["value"], v["unit"]) return Cosmology.from_format(mapping, format="mapping", **kwargs)
def test_equivalent_units2(): units = set(u.Hz.find_equivalent_units(u.spectral())) match = set( [u.AU, u.Angstrom, u.Hz, u.J, u.Ry, u.cm, u.eV, u.erg, u.lyr, u.m, u.micron, u.pc, u.solRad, u.Bq, u.Ci, u.k, u.earthRad, u.jupiterRad]) assert units == match from astropy.units import imperial with u.add_enabled_units(imperial): units = set(u.Hz.find_equivalent_units(u.spectral())) match = set( [u.AU, u.Angstrom, imperial.BTU, u.Hz, u.J, u.Ry, imperial.cal, u.cm, u.eV, u.erg, imperial.ft, imperial.fur, imperial.inch, imperial.kcal, u.lyr, u.m, imperial.mi, imperial.mil, u.micron, u.pc, u.solRad, imperial.yd, u.Bq, u.Ci, imperial.nmi, u.k, u.earthRad, u.jupiterRad]) assert units == match units = set(u.Hz.find_equivalent_units(u.spectral())) match = set( [u.AU, u.Angstrom, u.Hz, u.J, u.Ry, u.cm, u.eV, u.erg, u.lyr, u.m, u.micron, u.pc, u.solRad, u.Bq, u.Ci, u.k, u.earthRad, u.jupiterRad]) assert units == match
def from_yaml(yml, *, cosmology=None): """Load `~astropy.cosmology.Cosmology` from :mod:`yaml` object. Parameters ---------- yml : str :mod:`yaml` representation of |Cosmology| object cosmology : str, `~astropy.cosmology.Cosmology` class, or None (optional, keyword-only) The expected cosmology class (or string name thereof). This argument is is only checked for correctness if not `None`. Returns ------- `~astropy.cosmology.Cosmology` subclass instance Raises ------ TypeError If the |Cosmology| object loaded from ``yml`` is not an instance of the ``cosmology`` (and ``cosmology`` is not `None`). """ with u.add_enabled_units(cu): cosmo = load(yml) # Check argument `cosmology`, if not None # This kwarg is required for compatibility with |Cosmology.from_format| if isinstance(cosmology, str): cosmology = _COSMOLOGY_CLASSES[cosmology] if cosmology is not None and not isinstance(cosmo, cosmology): raise TypeError(f"cosmology {cosmo} is not an {cosmology} instance.") return cosmo
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)
def show_curve(self, index, x_axis_unit='uas'): with u.add_enabled_units(self.model.parameters.specialUnits): controller = self._masterController curve = self._trial.lightcurves[index] curveParams = self._trial.parameters.getExtras( 'batch_lightcurve').bounding_box self._masterController.runner.plotFromLightCurve( controller, curve, x_axis_unit, curveParams)
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
def test_pickle_instance(self, cosmo, pickle_protocol): """Test instances can pickle and unpickle.""" # pickle and unpickle f = pickle.dumps(cosmo, protocol=pickle_protocol) with u.add_enabled_units(cu): unpickled = pickle.loads(f) assert unpickled == cosmo assert unpickled.meta == cosmo.meta
def test_custom_unit(c): s = dump(c) with pytest.warns(u.UnitsWarning, match=f"'{c!s}' did not parse") as w: cy = load(s) assert len(w) == 1 assert isinstance(cy, u.UnrecognizedUnit) assert str(cy) == str(c) with u.add_enabled_units(c): cy2 = load(s) assert cy2 is c
def from_json(cls, js: 'Dict') -> 'Parameters': z_s = js['source']['redshift'] z_l = js['lens']['redshift'] mass = Jsonable.decode_quantity(js['source']['mass']) te = Parameters.static_theta_E(z_s, z_l) rg = Quasar.static_r_g(mass, z_s) with u.add_enabled_units([te, rg]): gal = Lens.from_json(js['lens']) src = Quasar.from_json(js['source']) rays = PixelRegion.from_json(js['ray_region']) return cls(src, gal, rays)
def enable(): """Enable `sbpy` units in the top-level `~astropy.units` namespace. Allows the use in `~astropy.units.UnitBase.find_equivalent_units` and `~astropy.units.UnitBase.compose`. May be used with the ``with`` statement to enable them temporarily. """ import inspect return u.add_enabled_units(inspect.getmodule(enable))
def test_equivalent_units(): from astropy.units import imperial with u.add_enabled_units(imperial): units = u.g.find_equivalent_units() units_set = set(units) match = set( [u.M_e, u.M_p, u.g, u.kg, u.solMass, u.t, u.u, u.M_earth, u.M_jup, imperial.oz, imperial.lb, imperial.st, imperial.ton, imperial.slug]) assert units_set == match r = repr(units) assert r.count('\n') == len(units) + 2
def get_object(self,*args,**kwargs): from mirage.parameters import Parameters, MicrolensingParameters, Quasar, Lens from mirage.util import Vec2D, PolarVec, PixelRegion, zero_vector from mirage.calculator import getMassFunction #First, pull out everyhing a micro and macro object needs. #Pull out values for special units first try: lRedshift = self.lRedshiftInput.value() qRedshift = self.qRedshiftInput.value() qMass = self.qMassInput.value()*u.solMass vDispersion = self.vDispersionInput.value()*u.km/u.s r_g, theta_E, xi = Parameters.special_units(qRedshift,lRedshift,qMass) einstein_radius = Parameters.static_einstein_radius(vDispersion,qRedshift,lRedshift) with u.add_enabled_units([r_g,theta_E,einstein_radius]): #Now I can continue to pull out values and not have a unit problem. ellipR, ellipTheta = self.ellipRInput.value(), self.ellipThetaInput.value() shearR, shearTheta = self.shearRInput.value(), self.shearThetaInput.value() qRadius = self.qRadiusInput.value()*UserInputWidget.unitFromString( self.qRadiusUnit.currentText(),r_g,theta_E) rayRegionLength = self.rootRayInput.value() shear = PolarVec(shearR,shearTheta) ellip = PolarVec(ellipR, ellipTheta) lens = Lens(lRedshift, vDispersion, shear, ellip) quasar = Quasar(qRedshift, qRadius, qMass) rayRegion = PixelRegion(zero_vector('arcsec'), Vec2D(1.4,1.4,einstein_radius), Vec2D(rayRegionLength,rayRegionLength)) macro_parameters = Parameters(quasar,lens,rayRegion) if self.enableMicrolensing.isChecked(): x,y = [float(v) for v in self.imgLocInput.text()[1:-1].split(",")] imgLocation = Vec2D(x,y,'arcsec') minorAxis = self.sPlaneDimInput.value()*UserInputWidget.unitFromString( self.sPlaneDimUnit.currentText(),r_g,theta_E) mass_fn = None mass_fn_seed = self.imfSeedInput.value() if self.imfInput.currentText() == "Custom": mass_fn = ParametersWidget._mk_mass_fn(self.imfPowersInput.text(), self.imfStepsInput.text(), self.imfAgingInput.text()) else: mass_fn = self.imfInput.currentText() star_generator = getMassFunction(mass_fn_seed,mass_fn) micro_params = macro_parameters.to_microParams(self.pcntStarsInput.value(), imgLocation, minorAxis, star_generator) return micro_params else: return macro_parameters except: UserInputWidget.warn_user("Error constructing the Parameters object. Please validate input and try again.")
def from_yaml(yml): """Load `~astropy.cosmology.Cosmology` from :mod:`yaml` object. Parameters ---------- yml : str :mod:`yaml` representation of |Cosmology| object Returns ------- `~astropy.cosmology.Cosmology` subclass instance """ with u.add_enabled_units(cu): return load(yml)
def test_yaml_constructor(): """Test :func:`~astropy.cosmology.io.yaml.yaml_constructor`.""" # test function `constructor` constructor = yaml_constructor(FlatLambdaCDM) assert callable(constructor) # it's too hard to manually construct a node, so we only test dump/load # this is also a good round-trip test yml = dump(Planck18) with u.add_enabled_units(cu): # needed for redshift units cosmo = load(yml) assert isinstance(cosmo, FlatLambdaCDM) assert cosmo == Planck18 assert cosmo.meta == Planck18.meta
def test_custom_unit(c): s = dump(c) with catch_warnings() as w: cy = load(s) assert len(w) == 1 assert f"'{c!s}' did not parse" in str(w[0].message) assert isinstance(cy, u.UnrecognizedUnit) assert str(cy) == str(c) with u.add_enabled_units(c): with catch_warnings() as w2: cy2 = load(s) assert len(w2) == 0 assert cy2 is c
def read_ecsv(filename, index=None, *, move_to_meta=False, cosmology=None, **kwargs): """Read a `~astropy.cosmology.Cosmology` from an ECSV file. Parameters ---------- filename : path-like or file-like From where to read the Cosmology. index : int, str, or None, optional Needed to select the row in tables with multiple rows. ``index`` can be an integer for the row number or, if the table is indexed by a column, the value of that column. If the table is not indexed and ``index`` is a string, the "name" column is used as the indexing column. move_to_meta : bool (optional, keyword-only) Whether to move keyword arguments that are not in the Cosmology class' signature to the Cosmology's metadata. This will only be applied if the Cosmology does NOT have a keyword-only argument (e.g. ``**kwargs``). Arguments moved to the metadata will be merged with existing metadata, preferring specified metadata in the case of a merge conflict (e.g. for ``Cosmology(meta={'key':10}, key=42)``, the ``Cosmology.meta`` will be ``{'key': 10}``). cosmology : str, `~astropy.cosmology.Cosmology` class, or None (optional, keyword-only) The cosmology class (or string name thereof) to use when constructing the cosmology instance. The class also provides default parameter values, filling in any non-mandatory arguments missing in 'table'. **kwargs Passed to :attr:`astropy.table.QTable.read` Returns ------- `~astropy.cosmology.Cosmology` subclass instance """ kwargs["format"] = "ascii.ecsv" with u.add_enabled_units(cu): table = QTable.read(filename, **kwargs) # build cosmology from table return from_table(table, index=index, move_to_meta=move_to_meta, cosmology=cosmology)
def __call__(self, *args, **kwargs): from astropy.cosmology.core import Cosmology # so subclasses can override, also pass the class as a kwarg. # allows for `FlatLambdaCDM.read` and # `Cosmology.read(..., cosmology=FlatLambdaCDM)` if self._cls is not Cosmology: kwargs.setdefault("cosmology", self._cls) # set, if not present # check that it is the correct cosmology, can be wrong if user # passes in e.g. `w0wzCDM.read(..., cosmology=FlatLambdaCDM)` valid = (self._cls, self._cls.__qualname__) if kwargs["cosmology"] not in valid: raise ValueError( "keyword argument `cosmology` must be either the class " f"{valid[0]} or its qualified name '{valid[1]}'") with add_enabled_units(cu): cosmo = self.registry.read(self._cls, *args, **kwargs) return cosmo
def test_pickle_builtin_realizations(name, pickle_protocol): """ Test in-built realizations can pickle and unpickle. Also a regression test for #12008. """ # get class instance original = getattr(cosmology, name) # pickle and unpickle f = pickle.dumps(original, protocol=pickle_protocol) with u.add_enabled_units(cu): unpickled = pickle.loads(f) assert unpickled == original assert unpickled.meta == original.meta # if the units are not enabled, it isn't equal because redshift units # are not equal. This is a weird, known issue. unpickled = pickle.loads(f) assert unpickled == original assert unpickled.meta != original.meta
def _bindFieldsHelper(self, parameters): """Sets the User interface's various input fields with the data in the passed-in parameters object.""" if parameters.stars != []: self._tmpStars = (parameters.galaxy.percentStars, parameters.galaxy.stars) else: self._tmpStars = None with u.add_enabled_units(parameters.specialUnits): qV = parameters.quasar.velocity.to('rad').unitless( ) * parameters.quasar.angDiamDist.to('km').value qP = parameters.quasar.position.to( self.qPositionLabel.text()).unitless() oqP = parameters.quasar.observedPosition.to( self.qPositionLabel.text()).unitless() gP = parameters.galaxy.position.to('arcsec').unitless() # self.qVelocity.setText(qV.asString) self.qPosition.setText(qP.asString) self.observedPosLabel.setText(oqP.asString) self.gCenter.setText(gP.asString) self.qRadius.setText( str( parameters.quasar.radius.to( self.qRadiusUnitOption.currentText()).value)) self.qRedshift.setText(str(parameters.quasar.redshift)) self.gRedshift.setText(str(parameters.galaxy.redshift)) self.gVelDispersion.setText( str(parameters.galaxy.velocityDispersion.value)) self.gNumStars.setText( str(int(parameters.galaxy.percentStars * 100))) self.gShearMag.setText(str(parameters.galaxy.shearMag)) self.gShearAngle.setText( str(parameters.galaxy.shearAngle.to('degree').value)) self.scaleInput.setText( str( parameters.dTheta.to( self.scaleUnitOption.currentText()).value * parameters.canvasDim)) self.dimensionInput.setText(str(parameters.canvasDim)) self.quasarBHMassEntry.setText( str(parameters.quasar.mass.to('solMass').value))
def test_round_trip_user_defined_unit(table_cls, tmpdir): """Ensure that we can read-back enabled user-defined units.""" from astropy.utils.compat.context import nullcontext # Test adapted from #8897, where it was noted that this works # but was not tested. filename = str(tmpdir.join('test.ecsv')) unit = u.def_unit('bandpass_sol_lum') t = table_cls() t['l'] = np.arange(5) * unit t.write(filename) # without the unit enabled, get UnrecognizedUnit if table_cls is QTable: ctx = pytest.warns(u.UnitsWarning, match=r"'bandpass_sol_lum' did not parse .*") else: ctx = nullcontext() # Note: The read might also generate ResourceWarning, in addition to UnitsWarning with ctx: t2 = table_cls.read(filename) assert isinstance(t2['l'].unit, u.UnrecognizedUnit) assert str(t2['l'].unit) == 'bandpass_sol_lum' if table_cls is QTable: assert np.all(t2['l'].value == t['l'].value) else: assert np.all(t2['l'] == t['l']) # But with it enabled, it works. with u.add_enabled_units(unit): t3 = table_cls.read(filename) assert t3['l'].unit is unit assert np.all(t3['l'] == t['l']) # Just to be sure, aloso try writing with unit enabled. filename2 = str(tmpdir.join('test2.ecsv')) t3.write(filename2) t4 = table_cls.read(filename) assert t4['l'].unit is unit assert np.all(t4['l'] == t['l'])
def test_round_trip_user_defined_unit(table_cls, tmpdir): """Ensure that we can read-back enabled user-defined units.""" # Test adapted from #8897, where it was noted that this works # but was not tested. filename = str(tmpdir.join('test.ecsv')) unit = u.def_unit('bandpass_sol_lum') t = table_cls() t['l'] = np.arange(5) * unit t.write(filename) # without the unit enabled, get UnrecognizedUnit with catch_warnings(u.UnitsWarning) as w: t2 = table_cls.read(filename) assert isinstance(t2['l'].unit, u.UnrecognizedUnit) assert str(t2['l'].unit) == 'bandpass_sol_lum' if table_cls is QTable: assert len(w) == 1 assert f"'{unit!s}' did not parse" in str(w[0].message) assert np.all(t2['l'].value == t['l'].value) else: assert len(w) == 0 assert np.all(t2['l'] == t['l']) # But with it enabled, it works. with u.add_enabled_units(unit): with catch_warnings(u.UnitsWarning) as w: t3 = table_cls.read(filename) assert len(w) == 0 assert t3['l'].unit is unit assert np.all(t3['l'] == t['l']) # Just to be sure, aloso try writing with unit enabled. filename2 = str(tmpdir.join('test2.ecsv')) t3.write(filename2) with catch_warnings(u.UnitsWarning) as w: t4 = table_cls.read(filename) assert len(w) == 0 assert t4['l'].unit is unit assert np.all(t4['l'] == t['l'])
def decode(self, js): gd = GalaxyJSONDecoder() qd = QuasarJSONDecoder() qDecode = QuantityJSONDecoder() qmass = qDecode.decode(js['quasar']['mass']) with u.add_enabled_units([ Parameters.calculateAvgMassEinsteinRadius( js['galaxy']['redshift'], js['quasar']['redshift']), Parameters.calculateGravRad(qmass, js['quasar']['redshift']) ]): galaxy = gd.decode(js['galaxy']) quasar = qd.decode(js['quasar']) canvasDim = int(js['canvasDim']) # print(canvasDim) dTheta = qDecode.decode(js['dTheta']) # print(str(dTheta)+str("DTHETA HERE")) parameters = Parameters(galaxy, quasar, dTheta, canvasDim) if 'rawMagnification' in js: parameters.setRawMag(js['rawMagnification']) if js['extraParameters']: decoder = ExperimentParamsJSONDecoder() extras = decoder.decode(js['extraParameters']) parameters.extras = extras return parameters
def test_pickle_does_not_keep_memoized_hash(unit): """ Tests private attribute since the problem with _hash being pickled and restored only appeared if the unpickling was done in another session, for which the hash no longer was valid, and it is difficult to mimic separate sessions in a simple test. See gh-11872. """ unit_hash = hash(unit) assert unit._hash is not None unit_copy = pickle.loads(pickle.dumps(unit)) # unit is not registered so we get a copy. assert unit_copy is not unit assert unit_copy._hash is None assert hash(unit_copy) == unit_hash with u.add_enabled_units([unit]): # unit is registered, so we get a reference. unit_ref = pickle.loads(pickle.dumps(unit)) if isinstance(unit, u.IrreducibleUnit): assert unit_ref is unit else: assert unit_ref is not unit # pickle.load used to override the hash, although in this case # it would be the same anyway, so not clear this tests much. assert hash(unit) == unit_hash
def test_flatten_impossible(): myunit = u.def_unit("FOOBAR_Two") with u.add_enabled_units(myunit), pytest.raises(ValueError): myunit.to_string('fits')
""" Module for analyzing GPS and pressure data from the SIP """ from __future__ import division, absolute_import, print_function import os import pickle import gzip import numpy as np import astropy.units as u from astropy.units import cds u.add_enabled_units([cds.mbar]) from astropy.coordinates import Latitude, Longitude from ..telemetry import parser_generator __all__ = ['GPSData'] DIR = os.path.join(__file__, "..") class GPSData(object): """Class for analyzing GPS and pressure data from the SIP Parameters ---------- telemetry_file : str The name of the telemetry file to analyze. If None is specified, a save file must be specified.
# 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)
from .config import DefaultConfig from .custom_exceptions import DataConfigurationError, EngineInputError from .pandeia_warnings import normalization_warning_messages as warning_messages from .utils import get_key_list, get_dict_from_keys, recursive_subclasses, merge_data from .instrument_factory import InstrumentFactory from .constants import pandeia_waveunits, pandeia_fluxunits from . import io_utils as io from . import config as cf default_refdata_directory = cf.default_refdata_directory # we use the plural of 'microns' everywhere, but astropy doesn't recognize it. configure it here... MICRONS = u.def_unit("microns", u.um, format={'generic': 'microns', 'console': 'microns'}) u.add_enabled_units([MICRONS]) class Normalization(DefaultConfig): """ Class for handling configuration and application of spectrum normalization Attributes ---------- type: string Type of normalization to perform norm_fluxunit: string Unit for fluxes used in normalization norm_waveunit: string Unit for wavelength used for reference wavelength, 'norm_wave'
# 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')), ])
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'}) # Register with astropy units u.add_enabled_units([PHOTLAM, PHOTNU, FLAM, FNU, OBMAG, VEGAMAG]) # --------------- # # Flux conversion # # --------------- # # Replace with https://github.com/astropy/astropy/pull/5012 def spectral_density_mag(wav): """Flux equivalencies between PHOTLAM and ABMAG/STMAG. Parameters ---------- wav : `~astropy.units.quantity.Quantity` Quantity associated with values being converted (e.g., wavelength or frequency).
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']
def test_register(): foo = u.def_unit("foo", u.m ** 3, namespace=locals()) assert 'foo' in locals() with u.add_enabled_units(foo): assert 'foo' in u.get_current_unit_registry().registry assert 'foo' not in u.get_current_unit_registry().registry
import pandas as pd import matplotlib.pyplot as plt import astropy import astropy.units as u from astropy.table import Table, Column from sunpy import config from sunpy.time import TimeRange from sunpy.timeseries import TimeSeriesMetaData from sunpy.util.metadata import MetaDict from sunpy.util.exceptions import SunpyUserWarning # define and register a new unit, needed for RHESSI det = u.def_unit('detector') u.add_enabled_units([det]) TIME_FORMAT = config.get("general", "time_format") class GenericTimeSeries: """ A generic time series object. Parameters ---------- data : `~pandas.DataFrame` A pandas DataFrame representing one or more fields as a function of time. meta : `~sunpy.timeseries.metadata.TimeSeriesMetaData`, optional The metadata giving details about the time series data/instrument.
# 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 on top of imgLoader init, set self.survey = 'hsc',
except ValueError as exc: if (parse_strict == 'raise' or 'did not parse as unit' not in str(exc)): raise # try again using out own lenient parser GWpyFormat.warn = parse_strict != 'silent' return units.Unit(name, parse_strict='silent', format=format) finally: GWpyFormat.warn = True # -- custom units ------------------------------------------------------------- # pylint: disable=no-member,invalid-name # enable imperial units units.add_enabled_units(units.imperial) # -- custom units settings # the following happens in two sets # 1) alternative names for standard units where SI prefices will not # be used # 2) new units or alternative names for standard units where SI prefices # _will_ be used # # for developers: when adding a new custom unit, please remember to add it # to the list of tested units in `test_detector.py` # 1) alternative names registry = units.get_current_unit_registry().registry for unit, aliases in [ (units.Unit('ct'), ('counts',)),