Python astropy.units.UnitConversionError() Examples
The following are 18
code examples of astropy.units.UnitConversionError().
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: periodogram.py From lightkurve with MIT License | 6 votes |
def __init__(self, frequency, power, nyquist=None, label=None, targetid=None, default_view='frequency', meta={}): # Input validation if not isinstance(frequency, u.quantity.Quantity): raise ValueError('frequency must be an `astropy.units.Quantity` object.') if not isinstance(power, u.quantity.Quantity): raise ValueError('power must be an `astropy.units.Quantity` object.') # Frequency must have frequency units try: frequency.to(u.Hz) except u.UnitConversionError: raise ValueError('Frequency must be in units of 1/time.') # Frequency and power must have sensible shapes if frequency.shape[0] <= 1: raise ValueError('frequency and power must have a length greater than 1.') if frequency.shape != power.shape: raise ValueError('frequency and power must have the same length.') self.frequency = frequency self.power = power self.nyquist = nyquist self.label = label self.targetid = targetid self.default_view = self._validate_view(default_view) self.meta = meta
Example #2
Source File: test_parameter.py From astromodels with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_set_units(): p = Parameter('test_parameter',1.0, unit=u.keV) p.value = 3.0 * u.MeV assert p.value == 3000.0 with pytest.raises(u.UnitConversionError): p.value = 3.0 * u.cm with pytest.raises(CannotConvertValueToNewUnits): p.unit = u.cm with pytest.raises(CannotConvertValueToNewUnits): p.unit = u.dimensionless_unscaled p.unit = u.MeV assert p.unit == u.MeV p.display()
Example #3
Source File: fitted_point_sources.py From threeML with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _determine_quantity(self): # scroll thru conversions until one works for k, v in self._flux_lookup.items(): try: self._flux_unit.to(v) self._flux_type = k except (u.UnitConversionError): continue if self._flux_type is None: raise InvalidUnitError( "The flux_unit provided is not a valid flux quantity" )
Example #4
Source File: nduncertainty.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def unit(self, value): """ The unit should be set to a value consistent with the parent NDData unit and the uncertainty type. """ if value is not None: # Check the hidden attribute below, not the property. The property # raises an exception if there is no parent_nddata. if self._parent_nddata is not None: parent_unit = self.parent_nddata.unit try: # Check for consistency with the unit of the parent_nddata self._data_unit_to_uncertainty_unit(parent_unit).to(value) except UnitConversionError: raise UnitConversionError("Unit {} is incompatible " "with unit {} of parent " "nddata".format(value, parent_unit)) self._unit = Unit(value) else: self._unit = value
Example #5
Source File: core.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _validate_inputs(self, t, y, dy): # Validate shapes of inputs if dy is None: t, y = np.broadcast_arrays(t, y, subok=True) else: t, y, dy = np.broadcast_arrays(t, y, dy, subok=True) if t.ndim != 1: raise ValueError("Inputs (t, y, dy) must be 1-dimensional") # validate units of inputs if any is a Quantity if any(has_units(arr) for arr in (t, y, dy)): t, y = map(units.Quantity, (t, y)) if dy is not None: dy = units.Quantity(dy) try: dy = units.Quantity(dy, unit=y.unit) except units.UnitConversionError: raise ValueError("Units of dy not equivalent " "to units of y") return t, y, dy
Example #6
Source File: test_quantities.py From ctapipe with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_all_to_value(): """test all_to_value""" x_m = np.arange(5) * u.m y_mm = np.arange(5) * 1000 * u.mm z_km = np.arange(5) * 1e-3 * u.km nono_deg = np.arange(5) * 1000 * u.deg # one argument x = all_to_value(x_m, unit=u.m) assert (x == np.arange(5)).all() # two arguments x, y = all_to_value(x_m, y_mm, unit=u.m) assert (x == np.arange(5)).all() assert (y == np.arange(5)).all() # three x, y, z = all_to_value(x_m, y_mm, z_km, unit=u.m) assert (x == np.arange(5)).all() assert (y == np.arange(5)).all() assert (z == np.arange(5)).all() # cannot be converted with pytest.raises(u.UnitConversionError): all_to_value(x_m, nono_deg, unit=x_m.unit)
Example #7
Source File: test_bls.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_input_units(data): t, y, dy, params = data t_unit = u.day y_unit = u.mag with pytest.raises(u.UnitConversionError): BoxLeastSquares(t * t_unit, y * y_unit, dy * u.one) with pytest.raises(u.UnitConversionError): BoxLeastSquares(t * t_unit, y * u.one, dy * y_unit) with pytest.raises(u.UnitConversionError): BoxLeastSquares(t * t_unit, y, dy * y_unit) model = BoxLeastSquares(t*t_unit, y * u.one, dy) assert model.dy.unit == model.y.unit model = BoxLeastSquares(t*t_unit, y * y_unit, dy) assert model.dy.unit == model.y.unit model = BoxLeastSquares(t*t_unit, y*y_unit) assert model.dy is None
Example #8
Source File: test_units.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_incompatible_units(): # NOTE: minversion check does not work properly for matplotlib dev. try: # https://github.com/matplotlib/matplotlib/pull/13005 from matplotlib.units import ConversionError except ImportError: err_type = u.UnitConversionError else: err_type = ConversionError plt.figure() with quantity_support(): plt.plot([1, 2, 3] * u.m) with pytest.raises(err_type): plt.plot([105, 210, 315] * u.kg)
Example #9
Source File: test_nduncertainty.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_assigning_uncertainty_with_bad_unit_to_parent_fails(NDClass, UncertClass): # Does assigning an uncertainty with a non-matching unit to an NDData # with a unit work? ndd = NDClass([1, 1], unit=u.adu) # Set the unit to something inconsistent with ndd's unit v = UncertClass([1, 1], unit=u.second) with pytest.raises(u.UnitConversionError): ndd.uncertainty = v
Example #10
Source File: test_logarithmic.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_magnitude_conversion_fails_message(self): """Check that "dimensionless" magnitude units include a message in their exception text suggesting a possible cause of the problem. """ with pytest.raises(u.UnitConversionError) as excinfo: (10*u.ABmag - 2*u.ABmag).to(u.nJy) assert "Did you perhaps subtract magnitudes so the unit got lost?" in str(excinfo.value)
Example #11
Source File: core.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _validate_t(self, t): t = np.asanyarray(t) if has_units(self._trel): t = units.Quantity(t) try: t = units.Quantity(t, unit=self._trel.unit) except units.UnitConversionError: raise ValueError("Units of t not equivalent to " "units of input self.t") return t
Example #12
Source File: test_bls.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_period_units(data): t, y, dy, params = data t_unit = u.day y_unit = u.mag model = BoxLeastSquares(t * t_unit, y * y_unit, dy) p = model.autoperiod(params["duration"]) assert p.unit == t_unit p = model.autoperiod(params["duration"] * 24 * u.hour) assert p.unit == t_unit with pytest.raises(u.UnitConversionError): model.autoperiod(params["duration"] * u.mag) p = model.autoperiod(params["duration"], minimum_period=0.5) assert p.unit == t_unit with pytest.raises(u.UnitConversionError): p = model.autoperiod(params["duration"], minimum_period=0.5*u.mag) p = model.autoperiod(params["duration"], maximum_period=0.5) assert p.unit == t_unit with pytest.raises(u.UnitConversionError): p = model.autoperiod(params["duration"], maximum_period=0.5*u.mag) p = model.autoperiod(params["duration"], minimum_period=0.5, maximum_period=1.5) p2 = model.autoperiod(params["duration"], maximum_period=0.5, minimum_period=1.5) assert_quantity_allclose(p, p2)
Example #13
Source File: test_console.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_bad_human_file_size(size): assert pytest.raises(u.UnitConversionError, console.human_file_size, size)
Example #14
Source File: test_nduncertainty.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_changing_unit_to_value_inconsistent_with_parent_fails(NDClass, UncertClass): ndd1 = NDClass(1, unit='adu') v = UncertClass(1) # Sets the uncertainty unit to whatever makes sense with this data. ndd1.uncertainty = v with pytest.raises(u.UnitConversionError): # Nothing special about 15 except no one would ever use that unit v.unit = ndd1.unit ** 15
Example #15
Source File: nduncertainty.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def parent_nddata(self, value): if value is not None and not isinstance(value, weakref.ref): # Save a weak reference on the uncertainty that points to this # instance of NDData. Direct references should NOT be used: # https://github.com/astropy/astropy/pull/4799#discussion_r61236832 value = weakref.ref(value) # Set _parent_nddata here and access below with the property because value # is a weakref self._parent_nddata = value # set uncertainty unit to that of the parent if it was not already set, unless initializing # with empty parent (Value=None) if value is not None: parent_unit = self.parent_nddata.unit if self.unit is None: if parent_unit is None: self.unit = None else: # Set the uncertainty's unit to the appropriate value self.unit = self._data_unit_to_uncertainty_unit(parent_unit) else: # Check that units of uncertainty are compatible with those of # the parent. If they are, no need to change units of the # uncertainty or the data. If they are not, let the user know. unit_from_data = self._data_unit_to_uncertainty_unit(parent_unit) try: unit_from_data.to(self.unit) except UnitConversionError: raise UnitConversionError("Unit {} of uncertainty " "incompatible with unit {} of " "data".format(self.unit, parent_unit))
Example #16
Source File: parameter.py From astromodels with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _set_unit(self, input_unit): # This will fail if the input is not valid new_unit = self._safe_assign_unit(input_unit) # Now transform the current _value in the new unit, unless the current unit is dimensionless, in which # case there is no transformation to make # (self._unit is the OLD unit here) if self._unit != u.dimensionless_unscaled: # This will fail if the new unit is not compatible with the old one try: self.value = self.as_quantity.to(new_unit).value except u.UnitConversionError: if new_unit == u.dimensionless_unscaled: new_unit_name = '(dimensionless)' else: new_unit_name = new_unit raise CannotConvertValueToNewUnits("Cannot convert the value %s from %s to the " "new units %s" % (self.value, self._unit, new_unit_name)) else: # This is possibly the first time the unit is set pass # Finally store the new unit self._unit = new_unit
Example #17
Source File: core.py From Carnets with BSD 3-Clause "New" or "Revised" License | 4 votes |
def _get_time_fmt(self, val, val2, format, scale, precision, in_subfmt, out_subfmt): """ Given the supplied val, val2, format and scale try to instantiate the corresponding TimeFormat class to convert the input values into the internal jd1 and jd2. If format is `None` and the input is a string-type or object array then guess available formats and stop when one matches. """ if (format is None and (val.dtype.kind in ('S', 'U', 'O', 'M') or val.dtype.names)): # Input is a string, object, datetime, or a table-like ndarray # (structured array, recarray). These input types can be # uniquely identified by the format classes. formats = [(name, cls) for name, cls in self.FORMATS.items() if issubclass(cls, TimeUnique)] # AstropyTime is a pseudo-format that isn't in the TIME_FORMATS registry, # but try to guess it at the end. formats.append(('astropy_time', TimeAstropyTime)) elif not (isinstance(format, str) and format.lower() in self.FORMATS): if format is None: raise ValueError("No time format was given, and the input is " "not unique") else: raise ValueError("Format {!r} is not one of the allowed " "formats {}".format(format, sorted(self.FORMATS))) else: formats = [(format, self.FORMATS[format])] assert formats problems = {} for name, cls in formats: try: return cls(val, val2, scale, precision, in_subfmt, out_subfmt) except UnitConversionError: raise except (ValueError, TypeError) as err: # If ``format`` specified then there is only one possibility, so raise # immediately and include the upstream exception message to make it # easier for user to see what is wrong. if len(formats)==1: raise ValueError( f'Input values did not match the format class {format}:' + os.linesep + f'{err.__class__.__name__}: {err}' ) from err else: problems[name] = err else: raise ValueError(f'Input values did not match any of the formats ' f'where the format keyword is optional: ' f'{problems}') from problems[formats[0][0]]
Example #18
Source File: container.py From ctapipe with BSD 3-Clause "New" or "Revised" License | 4 votes |
def validate(self, value): """ check that a given value is appropriate for this Field Parameters ---------- value: Any the value to test Raises ------ FieldValidationError: if the value is not valid """ if self.allow_none and value is None: return errorstr = f"the value '{value}' ({type(value)}) is invalid: " if self.unit is not None: if not isinstance(value, Quantity): raise FieldValidationError( f"{errorstr} Should have units of {self.unit}" ) from None try: value.to(self.unit) except UnitConversionError as err: raise FieldValidationError(f"{errorstr}: {err}") # strip off the units now, so we can test the rest without units value = value.value if self.ndim is not None: # should be a numpy array if not isinstance(value, np.ndarray): raise FieldValidationError(f"{errorstr} Should be an ndarray") if value.ndim != self.ndim: raise FieldValidationError( f"{errorstr} Should have dimensionality {self.ndim}" ) if value.dtype != self.dtype: raise FieldValidationError( f"{errorstr} Has dtype " f"{value.dtype}, should have dtype" f" {self.dtype}" ) else: # not a numpy array if self.dtype is not None: if not isinstance(value, self.dtype.type): raise FieldValidationError( f"{errorstr} Should have numpy dtype {self.dtype}" )