Python astropy.units.UnitsError() Examples
The following are 30
code examples of astropy.units.UnitsError().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
astropy.units
, or try the search function
.
Example #1
Source File: test_representation_arithmetic.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_add_sub(self, representation): in_rep = self.cartesian.represent_as(representation) r1 = in_rep + in_rep assert isinstance(r1, representation) expected = 2. * in_rep for component in in_rep.components: assert_quantity_allclose(getattr(r1, component), getattr(expected, component)) with pytest.raises(TypeError): 10.*u.m + in_rep with pytest.raises(u.UnitsError): in_rep + (in_rep / u.s) r2 = in_rep - in_rep assert isinstance(r2, representation) assert np.all(representation_equal( r2.to_cartesian(), CartesianRepresentation(0.*u.m, 0.*u.m, 0.*u.m))) r3 = in_rep - in_rep / 2. assert isinstance(r3, representation) expected = in_rep / 2. assert_representation_allclose(r3, expected)
Example #2
Source File: test_quantity_non_ufuncs.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_insert(self): # Unit of inserted values is not ignored. q = np.arange(12.).reshape(6, 2) * u.m out = np.insert(q, (3, 5), [50., 25.] * u.cm) assert isinstance(out, u.Quantity) assert out.unit == q.unit expected = np.insert(q.value, (3, 5), [0.5, 0.25]) << q.unit assert np.all(out == expected) # 0 can have any unit. out2 = np.insert(q, (3, 5), 0) expected2 = np.insert(q.value, (3, 5), 0) << q.unit assert np.all(out2 == expected2) a = np.arange(3.) result = np.insert(a, (2,), 50. * u.percent) assert isinstance(result, u.Quantity) assert result.unit == u.dimensionless_unscaled expected = np.insert(a, (2,), 0.5) * u.dimensionless_unscaled assert np.all(result == expected) with pytest.raises(TypeError): np.insert(q, 3 * u.cm, 50. * u.cm) with pytest.raises(u.UnitsError): np.insert(q, (3, 5), 0. * u.s)
Example #3
Source File: test_quantity_non_ufuncs.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_putmask(self): q = np.arange(3.) * u.m mask = [True, False, True] values = [50, 0, 150] * u.cm np.putmask(q, mask, values) assert q.unit == u.m expected = [50, 100, 150] * u.cm assert np.all(q == expected) with pytest.raises(u.UnitsError): np.putmask(q, mask, values.value) with pytest.raises(u.UnitsError): np.putmask(q.value, mask, values) a = np.arange(3.) values = [50, 0, 150] * u.percent np.putmask(a, mask, values) expected = np.array([0.5, 1., 1.5]) assert np.all(a == expected)
Example #4
Source File: function.py From astromodels with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _call_with_units(self, x, y): # Gather the current parameters' values with units values = list(map(attrgetter("as_quantity"), self._get_children())) try: results = self.evaluate(x, y, *values) except u.UnitsError: # pragma: no cover raise u.UnitsError("Looks like you didn't provide all the units, or you provided the wrong ones, when " "calling function %s" % self.name) else: return results
Example #5
Source File: test_quantity.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_quantity_comparison(self): assert u.Quantity(1100, unit=u.meter) > u.Quantity(1, unit=u.kilometer) assert u.Quantity(900, unit=u.meter) < u.Quantity(1, unit=u.kilometer) with pytest.raises(u.UnitsError): assert u.Quantity(1100, unit=u.meter) > u.Quantity(1, unit=u.second) with pytest.raises(u.UnitsError): assert u.Quantity(1100, unit=u.meter) < u.Quantity(1, unit=u.second) assert u.Quantity(1100, unit=u.meter) >= u.Quantity(1, unit=u.kilometer) assert u.Quantity(1000, unit=u.meter) >= u.Quantity(1, unit=u.kilometer) assert u.Quantity(900, unit=u.meter) <= u.Quantity(1, unit=u.kilometer) assert u.Quantity(1000, unit=u.meter) <= u.Quantity(1, unit=u.kilometer) with pytest.raises(u.UnitsError): assert u.Quantity( 1100, unit=u.meter) >= u.Quantity(1, unit=u.second) with pytest.raises(u.UnitsError): assert u.Quantity(1100, unit=u.meter) <= u.Quantity(1, unit=u.second) assert u.Quantity(1200, unit=u.meter) != u.Quantity(1, unit=u.kilometer)
Example #6
Source File: function.py From astromodels with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _call_with_units(self, x, y, z): # Gather the current parameters' values with units values = list(map(attrgetter("as_quantity"), self._get_children())) try: results = self.evaluate(x, y, z, *values) except u.UnitsError: # pragma: no cover raise u.UnitsError("Looks like you didn't provide all the units, or you provided the wrong ones, when " "calling function %s" % self.name) else: return results
Example #7
Source File: formatter_locator.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def __init__(self, values=None, number=None, spacing=None, format=None, unit=None, decimal=None, format_unit=None, show_decimal_unit=True): if unit is None: unit = u.degree if format_unit is None: format_unit = unit if format_unit not in (u.degree, u.hourangle, u.hour): if decimal is False: raise UnitsError("Units should be degrees or hours when using non-decimal (sexagesimal) mode") self._decimal = decimal self._sep = None self.show_decimal_unit = show_decimal_unit super().__init__(values=values, number=number, spacing=spacing, format=format, unit=unit, format_unit=format_unit)
Example #8
Source File: icrs_cirs_transforms.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def hcrs_to_icrs(hcrs_coo, icrs_frame): # this is just an origin translation so without a distance it cannot go ahead if isinstance(hcrs_coo.data, UnitSphericalRepresentation): raise u.UnitsError(_NEED_ORIGIN_HINT.format(hcrs_coo.__class__.__name__)) if hcrs_coo.data.differentials: from astropy.coordinates.solar_system import get_body_barycentric_posvel bary_sun_pos, bary_sun_vel = get_body_barycentric_posvel('sun', hcrs_coo.obstime) bary_sun_vel = bary_sun_vel.represent_as(CartesianDifferential) bary_sun_pos = bary_sun_pos.with_differentials(bary_sun_vel) else: from astropy.coordinates.solar_system import get_body_barycentric bary_sun_pos = get_body_barycentric('sun', hcrs_coo.obstime) bary_sun_vel = None return None, bary_sun_pos
Example #9
Source File: icrs_cirs_transforms.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def icrs_to_hcrs(icrs_coo, hcrs_frame): # this is just an origin translation so without a distance it cannot go ahead if isinstance(icrs_coo.data, UnitSphericalRepresentation): raise u.UnitsError(_NEED_ORIGIN_HINT.format(icrs_coo.__class__.__name__)) if icrs_coo.data.differentials: from astropy.coordinates.solar_system import get_body_barycentric_posvel bary_sun_pos, bary_sun_vel = get_body_barycentric_posvel('sun', hcrs_frame.obstime) bary_sun_pos = -bary_sun_pos bary_sun_vel = -bary_sun_vel.represent_as(CartesianDifferential) bary_sun_pos = bary_sun_pos.with_differentials(bary_sun_vel) else: from astropy.coordinates.solar_system import get_body_barycentric bary_sun_pos = -get_body_barycentric('sun', hcrs_frame.obstime) bary_sun_vel = None return None, bary_sun_pos
Example #10
Source File: angle_utilities.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def parse(self, angle, unit, debug=False): try: found_angle, found_unit = self._parser.parse( angle, lexer=self._lexer, debug=debug) except ValueError as e: if str(e): raise ValueError("{} in angle {!r}".format( str(e), angle)) else: raise ValueError( f"Syntax error parsing angle {angle!r}") if unit is None and found_unit is None: raise u.UnitsError("No unit specified") return found_angle, found_unit
Example #11
Source File: test_representation_arithmetic.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_add_sub_cartesian(self): c1 = self.cartesian + self.cartesian assert isinstance(c1, CartesianRepresentation) assert c1.x.dtype.kind == 'f' assert np.all(representation_equal(c1, 2. * self.cartesian)) with pytest.raises(TypeError): self.cartesian + 10.*u.m with pytest.raises(u.UnitsError): self.cartesian + (self.cartesian / u.s) c2 = self.cartesian - self.cartesian assert isinstance(c2, CartesianRepresentation) assert np.all(representation_equal( c2, CartesianRepresentation(0.*u.m, 0.*u.m, 0.*u.m))) c3 = self.cartesian - self.cartesian / 2. assert isinstance(c3, CartesianRepresentation) assert np.all(representation_equal(c3, self.cartesian / 2.))
Example #12
Source File: test_representation_arithmetic.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_add_sub_unit_spherical(self): s1 = self.unit_spherical + self.unit_spherical assert isinstance(s1, SphericalRepresentation) expected = 2. * self.unit_spherical for component in s1.components: assert_quantity_allclose(getattr(s1, component), getattr(expected, component)) with pytest.raises(TypeError): 10.*u.m - self.unit_spherical with pytest.raises(u.UnitsError): self.unit_spherical + (self.unit_spherical / u.s) s2 = self.unit_spherical - self.unit_spherical / 2. assert isinstance(s2, SphericalRepresentation) expected = self.unit_spherical / 2. for component in s2.components: assert_quantity_allclose(getattr(s2, component), getattr(expected, component))
Example #13
Source File: test_sky_coord.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_units(): sc = SkyCoord(1, 2, 3, unit='m', representation_type='cartesian') # All get meters assert sc.x.unit is u.m assert sc.y.unit is u.m assert sc.z.unit is u.m sc = SkyCoord(1, 2*u.km, 3, unit='m', representation_type='cartesian') # All get u.m assert sc.x.unit is u.m assert sc.y.unit is u.m assert sc.z.unit is u.m sc = SkyCoord(1, 2, 3, unit=u.m, representation_type='cartesian') # All get u.m assert sc.x.unit is u.m assert sc.y.unit is u.m assert sc.z.unit is u.m sc = SkyCoord(1, 2, 3, unit='m, km, pc', representation_type='cartesian') assert_quantities_allclose(sc, (1*u.m, 2*u.km, 3*u.pc), ('x', 'y', 'z')) with pytest.raises(u.UnitsError) as err: SkyCoord(1, 2, 3, unit=(u.m, u.m), representation_type='cartesian') assert 'should have matching physical types' in str(err.value) SkyCoord(1, 2, 3, unit=(u.m, u.km, u.pc), representation_type='cartesian') assert_quantities_allclose(sc, (1*u.m, 2*u.km, 3*u.pc), ('x', 'y', 'z'))
Example #14
Source File: test_quantities_evaluation.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_evaluate_with_quantities_and_equivalencies(): """ We now make sure that equivalencies are correctly taken into account """ g = Gaussian1D(1 * u.Jy, 10 * u.nm, 2 * u.nm) # We aren't setting the equivalencies, so this won't work with pytest.raises(UnitsError) as exc: g(30 * u.PHz) assert exc.value.args[0] == ("Gaussian1D: Units of input 'x', PHz (frequency), could " "not be converted to required input units of " "nm (length)") # But it should now work if we pass equivalencies when evaluating assert_quantity_allclose(g(30 * u.PHz, equivalencies={'x': u.spectral()}), g(9.993081933333332 * u.nm))
Example #15
Source File: test_quantity_interaction.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_quantity_output_errors(self): dt = TimeDelta(250., format='sec') with pytest.raises(u.UnitsError): dt.to(u.m) with pytest.raises(u.UnitsError): dt.to_value(u.m) with pytest.raises(u.UnitsError): dt.to_value(unit=u.m) with pytest.raises(ValueError, match=("not one of the known formats.*" "failed to parse as a unit")): dt.to_value('parrot') with pytest.raises(TypeError): dt.to_value('sec', unit=u.s) with pytest.raises(TypeError): # TODO: would be nice to make this work! dt.to_value(u.s, subfmt='str')
Example #16
Source File: test_quantities_parameters.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_parameter_lose_units(): """ Check that parameters that have been set to a quantity that are then set to a value with no units raise an exception. We do this because setting a parameter to a value with no units is ambiguous if units were set before: if a paramter is 1 * u.Jy and the parameter is then set to 4, does this mean 2 without units, or 2 * u.Jy? """ g = Gaussian1D(1 * u.Jy, 3, 0.1) with pytest.raises(UnitsError) as exc: g.amplitude = 2 assert exc.value.args[0] == ("The 'amplitude' parameter should be given as " "a Quantity because it was originally " "initialized as a Quantity")
Example #17
Source File: test_quantity.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_insert(): """ Test Quantity.insert method. This does not test the full capabilities of the underlying np.insert, but hits the key functionality for Quantity. """ q = [1, 2] * u.m # Insert a compatible float with different units q2 = q.insert(0, 1 * u.km) assert np.all(q2.value == [1000, 1, 2]) assert q2.unit is u.m assert q2.dtype.kind == 'f' if minversion(np, '1.8.0'): q2 = q.insert(1, [1, 2] * u.km) assert np.all(q2.value == [1, 1000, 2000, 2]) assert q2.unit is u.m # Cannot convert 1.5 * u.s to m with pytest.raises(u.UnitsError): q.insert(1, 1.5 * u.s) # Tests with multi-dim quantity q = [[1, 2], [3, 4]] * u.m q2 = q.insert(1, [10, 20] * u.m, axis=0) assert np.all(q2.value == [[1, 2], [10, 20], [3, 4]]) q2 = q.insert(1, [10, 20] * u.m, axis=1) assert np.all(q2.value == [[1, 10, 2], [3, 20, 4]]) q2 = q.insert(1, 10 * u.m, axis=1) assert np.all(q2.value == [[1, 10, 2], [3, 10, 4]])
Example #18
Source File: functional_models.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _parameter_units_for_data_units(self, inputs_unit, outputs_unit): # Note that here we need to make sure that x and y are in the same # units otherwise this can lead to issues since rotation is not well # defined. if inputs_unit['x'] != inputs_unit['y']: raise UnitsError("Units of 'x' and 'y' inputs should match") return {'x_0': inputs_unit['x'], 'y_0': inputs_unit['x'], 'R_0': inputs_unit['x'], 'amplitude': outputs_unit['z']}
Example #19
Source File: functional_models.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _parameter_units_for_data_units(self, inputs_unit, outputs_unit): # Note that here we need to make sure that x and y are in the same # units otherwise this can lead to issues since rotation is not well # defined. if inputs_unit['x'] != inputs_unit['y']: raise UnitsError("Units of 'x' and 'y' inputs should match") return {'x_0': inputs_unit['x'], 'y_0': inputs_unit['x'], 'a': inputs_unit['x'], 'b': inputs_unit['x'], 'theta': u.rad, 'amplitude': outputs_unit['z']}
Example #20
Source File: test_quantities_evaluation.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_compound_input_units_equivalencies(): """ Test setting input_units_equivalencies on one of the models. """ s1 = Shift(10 * u.deg) s1.input_units_equivalencies = {'x': u.pixel_scale(0.5 * u.deg / u.pix)} s2 = Shift(10 * u.deg) sp = Shift(10 * u.pix) cs = s1 | s2 out = cs(10 * u.pix) assert_quantity_allclose(out, 25 * u.deg) cs = sp | s1 out = cs(10 * u.pix) assert_quantity_allclose(out, 20 * u.deg) cs = s1 & s2 cs = cs.rename('TestModel') out = cs(20 * u.pix, 10 * u.deg) assert_quantity_allclose(out, 20 * u.deg) with pytest.raises(UnitsError) as exc: out = cs(20 * u.pix, 10 * u.pix) assert exc.value.args[0] == "Shift: Units of input 'x', pix (unknown), could not be converted to required input units of deg (angle)"
Example #21
Source File: test_quantities_evaluation.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_compound_incompatible_units_fail(): """ Test incompatible model units in chain. """ s1 = Shift(10 * u.pix) s2 = Shift(10 * u.deg) cs = s1 | s2 with pytest.raises(UnitsError): cs(10 * u.pix)
Example #22
Source File: test_quantities_evaluation.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_compound_input_units_fail(): """ Test incompatible units to first model in chain. """ s1 = Shift(10 * u.deg) s2 = Shift(10 * u.deg) cs = s1 | s2 with pytest.raises(UnitsError): cs(10 * u.pix)
Example #23
Source File: test_quantities_evaluation.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_input_units_equivalencies(self): self.model._input_units = {'x': u.micron} with pytest.raises(UnitsError) as exc: self.model(3 * u.PHz, 3) assert exc.value.args[0] == ("MyTestModel: Units of input 'x', PHz (frequency), could " "not be converted to required input units of " "micron (length)") self.model.input_units_equivalencies = {'x': u.spectral()} assert_quantity_allclose(self.model(3 * u.PHz, 3), 3 * (3 * u.PHz).to(u.micron, equivalencies=u.spectral()))
Example #24
Source File: test_quantities_evaluation.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_input_units_allow_dimensionless(self): self.model._input_units = {'x': u.deg} self.model._input_units_allow_dimensionless = True assert_quantity_allclose(self.model(3 * u.deg, 4), 12 * u.deg) assert_quantity_allclose(self.model(4 * u.rad, 2), 8 * u.rad) with pytest.raises(UnitsError) as exc: self.model(4 * u.s, 3) assert exc.value.args[0] == ("MyTestModel: Units of input 'x', s (time), could not be " "converted to required input units of deg (angle)") assert_quantity_allclose(self.model(3, 3), 9)
Example #25
Source File: test_quantity_non_ufuncs.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_product(self): with pytest.raises(u.UnitsError): np.product(self.q)
Example #26
Source File: test_quantities_evaluation.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_evaluate_with_quantities(): """ Test evaluation of a single model with Quantity parameters that do not explicitly require units. """ # We create two models here - one with quantities, and one without. The one # without is used to create the reference values for comparison. g = Gaussian1D(1, 1, 0.1) gq = Gaussian1D(1 * u.J, 1 * u.m, 0.1 * u.m) # We first check that calling the Gaussian with quantities returns the # expected result assert_quantity_allclose(gq(1 * u.m), g(1) * u.J) # Units have to be specified for the Gaussian with quantities - if not, an # error is raised with pytest.raises(UnitsError) as exc: gq(1) assert exc.value.args[0] == ("Gaussian1D: Units of input 'x', (dimensionless), could not be " "converted to required input units of m (length)") # However, zero is a special case assert_quantity_allclose(gq(0), g(0) * u.J) # We can also evaluate models with equivalent units assert_allclose(gq(0.0005 * u.km).value, g(0.5)) # But not with incompatible units with pytest.raises(UnitsError) as exc: gq(3 * u.s) assert exc.value.args[0] == ("Gaussian1D: Units of input 'x', s (time), could not be " "converted to required input units of m (length)") # We also can't evaluate the model without quantities with a quantity with pytest.raises(UnitsError) as exc: g(3 * u.m) # TODO: determine what error message should be here # assert exc.value.args[0] == ("Units of input 'x', m (length), could not be " # "converted to required dimensionless input")
Example #27
Source File: test_quantities_fitting.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_fitting_incompatible_units(): """ Raise an error if the data and model have incompatible units """ g_init = models.Gaussian1D(amplitude=1. * u.Jy, mean=3 * u.m, stddev=2 * u.cm) fit_g = fitting.LevMarLSQFitter() with pytest.raises(UnitsError) as exc: fit_g(g_init, [1, 2, 3] * u.Hz, [4, 5, 6] * u.Jy) assert exc.value.args[0] == ("'Hz' (frequency) and 'm' (length) are not convertible")
Example #28
Source File: test_quantities_fitting.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_fitting_missing_data_units(): """ Raise an error if the model has units but the data doesn't """ class UnorderedGaussian1D(models.Gaussian1D): # Parameters are ordered differently here from Gaussian1D # to ensure the order does not break functionality. def _parameter_units_for_data_units(self, inputs_unit, outputs_unit): return {'amplitude': outputs_unit['y'], 'mean': inputs_unit['x'], 'stddev': inputs_unit['x']} g_init = UnorderedGaussian1D(amplitude=1. * u.mJy, mean=3 * u.cm, stddev=2 * u.mm) fit_g = fitting.LevMarLSQFitter() # We define flux unit so that conversion fails at wavelength unit. # This is because the order of parameter unit conversion seems to # follow the order defined in _parameter_units_for_data_units method. with pytest.raises(UnitsError) as exc: fit_g(g_init, [1, 2, 3], [4, 5, 6] * (u.erg / (u.s * u.cm * u.cm * u.Hz))) assert exc.value.args[0] == ("'cm' (length) and '' (dimensionless) are " "not convertible") with pytest.raises(UnitsError) as exc: fit_g(g_init, [1, 2, 3] * u.m, [4, 5, 6]) assert exc.value.args[0] == ("'mJy' (spectral flux density) and '' " "(dimensionless) are not convertible")
Example #29
Source File: test_quantity_non_ufuncs.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_cumprod(self): with pytest.raises(u.UnitsError): np.cumprod(self.q)
Example #30
Source File: functional_models.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _parameter_units_for_data_units(self, inputs_unit, outputs_unit): # Note that here we need to make sure that x and y are in the same # units otherwise this can lead to issues since rotation is not well # defined. if inputs_unit['x'] != inputs_unit['y']: raise UnitsError("Units of 'x' and 'y' inputs should match") return {'x_0': inputs_unit['x'], 'y_0': inputs_unit['x'], 'sigma': inputs_unit['x'], 'amplitude': outputs_unit['z']}