def __init__(self, physical_unit=None, function_unit=None): if physical_unit is None: self._physical_unit = dimensionless_unscaled else: self._physical_unit = Unit(physical_unit) if (not isinstance(self._physical_unit, UnitBase) or self._physical_unit.is_equivalent( self._default_function_unit)): raise ValueError("Unit {0} is not a physical unit.".format( self._physical_unit)) if function_unit is None: self._function_unit = self._default_function_unit else: # any function unit should be equivalent to subclass default function_unit = Unit( getattr(function_unit, 'function_unit', function_unit)) if function_unit.is_equivalent(self._default_function_unit): self._function_unit = function_unit else: raise ValueError( "Cannot initialize '{0}' instance with " "function unit '{1}', as it is not " "equivalent to default function unit '{2}'.".format( self.__class__.__name__, function_unit, self._default_function_unit))
def verify_unit(quantity, unit): """Verify unit of passed quantity and return it. Parameters: quantity: :py:class:`~astropy.units.Quantity` to be verified. Bare numbers are valid if the unit is dimensionless. unit: Equivalent unit, or string parsable by :py:class:`astropy.units.Unit` Raises: ValueError: Units are not equivalent. Returns: ``quantity`` unchanged. Bare numbers will be converted to a dimensionless :py:class:`~astropy.units.Quantity`. Example: .. code-block:: python def __init__(self, a): self.a = verify_unit(a, astropy.units.m) """ if not isinstance(unit, UnitBase): unit = Unit(unit) q = quantity * u.one if unit.is_equivalent(q.unit): return q else: raise ValueError("Unit '{}' not equivalent to quantity '{}'.".format(unit, quantity))
def __init__(self, physical_unit=None, function_unit=None): if physical_unit is None: self._physical_unit = dimensionless_unscaled else: self._physical_unit = Unit(physical_unit) if (not isinstance(self._physical_unit, UnitBase) or self._physical_unit.is_equivalent( self._default_function_unit)): raise ValueError("Unit {0} is not a physical unit." .format(self._physical_unit)) if function_unit is None: self._function_unit = self._default_function_unit else: # any function unit should be equivalent to subclass default function_unit = Unit(getattr(function_unit, 'function_unit', function_unit)) if function_unit.is_equivalent(self._default_function_unit): self._function_unit = function_unit else: raise ValueError("Cannot initialize '{0}' instance with " "function unit '{1}', as it is not " "equivalent to default function unit '{2}'." .format(self.__class__.__name__, function_unit, self._default_function_unit))
def verify_unit(quantity, unit): """Verify unit of passed quantity and return it. Parameters: quantity: :py:class:`~astropy.units.Quantity` to be verified. Bare numbers are valid if the unit is dimensionless. unit: Equivalent unit, or string parsable by :py:class:`astropy.units.Unit` Raises: ValueError: Units are not equivalent. Returns: ``quantity`` unchanged. Bare numbers will be converted to a dimensionless :py:class:`~astropy.units.Quantity`. Example: .. code-block:: python def __init__(self, a): self.a = verify_unit(a, astropy.units.m) """ if not isinstance(unit, UnitBase): unit = Unit(unit) q = quantity * u.one if unit.is_equivalent(q.unit): return q else: raise ValueError("Unit '{}' not equivalent to quantity '{}'.".format( unit, quantity))
def verify_unit(quantity, unit): """Verify unit of passed quantity and return it. Parameters: quantity: Quantity to be verified. unit: Equivalent unit, or string parsable by :py:class:`astropy.units.Unit` Raises: ValueError: Units are not equivalent. Returns: quantity parameter, unchanged. Example: .. code-block:: python def __init__(self, a): self.a = verify_unit(a, astropy.units.m) :type quantity: :py:class:`astropy.units.Quantity` :type unit: :py:class:`astropy.units.UnitBase` """ if not isinstance(unit, Unit): unit = Unit(unit) if unit.is_equivalent((quantity * u.one).unit): return quantity else: raise ValueError( "Unit '{}' not equivalent to quantity '{}'.".format(unit, quantity))
def ingest_filter_set(path: str, instrument: str, instrument_response: bool = False, atmosphere: bool = False, source: str = None, wavelength_unit: units.Unit = None, percentage: bool = False, lambda_name='LAMBDA', quiet: bool = False): """ :param path: :param instrument: :param instrument_response: Filter curve includes instrument response :param atmosphere: Filter curve includes atmospheric transmission :param source: :param wavelength_unit: :param percentage: :param lambda_name: :param quiet: :return: """ if not wavelength_unit.is_equivalent(units.Angstrom): raise units.UnitTypeError( f"Wavelength units must be of type length, not {wavelength_unit}") type_str = "_filter" if instrument_response: type_str += "_instrument" if atmosphere: type_str += "_atmosphere" data = QTable.read(path, format='ascii') data.sort("col1") wavelengths = data["col1"] * wavelength_unit wavelengths = wavelengths.to("Angstrom") for f in data.colnames: if f != lambda_name: params = filter_params(f=f, instrument=instrument, quiet=quiet) transmissions = data[f] if params is None: params = new_filter_params(quiet=quiet) params['name'] = f if source is not None: params[f'source{type_str}'] = source if percentage: transmissions /= 100 params[f'wavelengths{type_str}'] = wavelengths params[f'transmissions{type_str}'] = transmissions save_params(file=param_dir + f'filters/{instrument}-{f}', dictionary=params, quiet=quiet) refresh_params_filters(quiet=quiet)
def validate(self, p_str, p_int): try: unit = Unit(p_str) if unit.is_equivalent(self._layer.dispersion_unit, equivalencies=spectral()): return (QValidator.Acceptable, p_str, p_int) else: return (QValidator.Intermediate, p_str, p_int) except ValueError as e: return (QValidator.Intermediate, p_str, p_int) return (QValidator.Invalid, p_str, p_int)
class FunctionUnitBase(metaclass=ABCMeta): """Abstract base class for function units. Function units are functions containing a physical unit, such as dB(mW). Most of the arithmetic operations on function units are defined in this base class. While instantiation is defined, this class should not be used directly. Rather, subclasses should be used that override the abstract properties `_default_function_unit` and `_quantity_class`, and the abstract methods `from_physical`, and `to_physical`. Parameters ---------- physical_unit : `~astropy.units.Unit` or `string` Unit that is encapsulated within the function unit. If not given, dimensionless. function_unit : `~astropy.units.Unit` or `string` By default, the same as the function unit set by the subclass. """ # ↓↓↓ the following four need to be set by subclasses # Make this a property so we can ensure subclasses define it. @property @abstractmethod def _default_function_unit(self): """Default function unit corresponding to the function. This property should be overridden by subclasses, with, e.g., `~astropy.unit.MagUnit` returning `~astropy.unit.mag`. """ # This has to be a property because the function quantity will not be # known at unit definition time, as it gets defined after. @property @abstractmethod def _quantity_class(self): """Function quantity class corresponding to this function unit. This property should be overridden by subclasses, with, e.g., `~astropy.unit.MagUnit` returning `~astropy.unit.Magnitude`. """ @abstractmethod def from_physical(self, x): """Transformation from value in physical to value in function units. This method should be overridden by subclasses. It is used to provide automatic transformations using an equivalency. """ @abstractmethod def to_physical(self, x): """Transformation from value in function to value in physical units. This method should be overridden by subclasses. It is used to provide automatic transformations using an equivalency. """ # ↑↑↑ the above four need to be set by subclasses # have priority over arrays, regular units, and regular quantities __array_priority__ = 30000 def __init__(self, physical_unit=None, function_unit=None): if physical_unit is None: self._physical_unit = dimensionless_unscaled else: self._physical_unit = Unit(physical_unit) if (not isinstance(self._physical_unit, UnitBase) or self._physical_unit.is_equivalent( self._default_function_unit)): raise ValueError("Unit {0} is not a physical unit.".format( self._physical_unit)) if function_unit is None: self._function_unit = self._default_function_unit else: # any function unit should be equivalent to subclass default function_unit = Unit( getattr(function_unit, 'function_unit', function_unit)) if function_unit.is_equivalent(self._default_function_unit): self._function_unit = function_unit else: raise ValueError( "Cannot initialize '{0}' instance with " "function unit '{1}', as it is not " "equivalent to default function unit '{2}'.".format( self.__class__.__name__, function_unit, self._default_function_unit)) def _copy(self, physical_unit=None): """Copy oneself, possibly with a different physical unit.""" if physical_unit is None: physical_unit = self.physical_unit return self.__class__(physical_unit, self.function_unit) @property def physical_unit(self): return self._physical_unit @property def function_unit(self): return self._function_unit @property def equivalencies(self): """List of equivalencies between function and physical units. Uses the `from_physical` and `to_physical` methods. """ return [(self, self.physical_unit, self.to_physical, self.from_physical)] # ↓↓↓ properties/methods required to behave like a unit def decompose(self, bases=set()): """Copy the current unit with the physical unit decomposed. For details, see `~astropy.units.UnitBase.decompose`. """ return self._copy(self.physical_unit.decompose(bases)) @property def si(self): """Copy the current function unit with the physical unit in SI.""" return self._copy(self.physical_unit.si) @property def cgs(self): """Copy the current function unit with the physical unit in CGS.""" return self._copy(self.physical_unit.cgs) def _get_physical_type_id(self): """Get physical type corresponding to physical unit.""" return self.physical_unit._get_physical_type_id() @property def physical_type(self): """Return the physical type of the physical unit (e.g., 'length').""" return self.physical_unit.physical_type def is_equivalent(self, other, equivalencies=[]): """ Returns `True` if this unit is equivalent to ``other``. Parameters ---------- other : unit object or string or tuple The unit to convert to. If a tuple of units is specified, this method returns true if the unit matches any of those in the tuple. equivalencies : list of equivalence pairs, optional A list of equivalence pairs to try if the units are not directly convertible. See :ref:`unit_equivalencies`. This list is in addition to the built-in equivalencies between the function unit and the physical one, as well as possible global defaults set by, e.g., `~astropy.units.set_enabled_equivalencies`. Use `None` to turn off any global equivalencies. Returns ------- bool """ if isinstance(other, tuple): return any( self.is_equivalent(u, equivalencies=equivalencies) for u in other) other_physical_unit = getattr( other, 'physical_unit', (dimensionless_unscaled if self.function_unit.is_equivalent(other) else other)) return self.physical_unit.is_equivalent(other_physical_unit, equivalencies) def to(self, other, value=1., equivalencies=[]): """ Return the converted values in the specified unit. Parameters ---------- other : `~astropy.units.Unit` object, `~astropy.units.function.FunctionUnitBase` object or string The unit to convert to. value : scalar int or float, or sequence convertible to array, optional Value(s) in the current unit to be converted to the specified unit. If not provided, defaults to 1.0. equivalencies : list of equivalence pairs, optional A list of equivalence pairs to try if the units are not directly convertible. See :ref:`unit_equivalencies`. This list is in meant to treat only equivalencies between different physical units; the build-in equivalency between the function unit and the physical one is automatically taken into account. Returns ------- values : scalar or array Converted value(s). Input value sequences are returned as numpy arrays. Raises ------ UnitsError If units are inconsistent. """ # conversion to one's own physical unit should be fastest if other is self.physical_unit: return self.to_physical(value) other_function_unit = getattr(other, 'function_unit', other) if self.function_unit.is_equivalent(other_function_unit): # when other is an equivalent function unit: # first convert physical units to other's physical units other_physical_unit = getattr(other, 'physical_unit', dimensionless_unscaled) if self.physical_unit != other_physical_unit: value_other_physical = self.physical_unit.to( other_physical_unit, self.to_physical(value), equivalencies) # make function unit again, in own system value = self.from_physical(value_other_physical) # convert possible difference in function unit (e.g., dex->dB) return self.function_unit.to(other_function_unit, value) else: try: # when other is not a function unit return self.physical_unit.to(other, self.to_physical(value), equivalencies) except UnitConversionError as e: if self.function_unit == Unit('mag'): # One can get to raw magnitudes via math that strips the dimensions off. # Include extra information in the exception to remind users of this. msg = "Did you perhaps subtract magnitudes so the unit got lost?" e.args += (msg, ) raise e else: raise def is_unity(self): return False def __eq__(self, other): return (self.physical_unit == getattr(other, 'physical_unit', dimensionless_unscaled) and self.function_unit == getattr(other, 'function_unit', other)) def __ne__(self, other): return not self.__eq__(other) def __mul__(self, other): if isinstance(other, (str, UnitBase, FunctionUnitBase)): if self.physical_unit == dimensionless_unscaled: # If dimensionless, drop back to normal unit and retry. return self.function_unit * other else: raise UnitsError("Cannot multiply a function unit " "with a physical dimension with any unit.") else: # Anything not like a unit, try initialising as a function quantity. try: return self._quantity_class(other, unit=self) except Exception: return NotImplemented def __rmul__(self, other): return self.__mul__(other) def __div__(self, other): if isinstance(other, (str, UnitBase, FunctionUnitBase)): if self.physical_unit == dimensionless_unscaled: # If dimensionless, drop back to normal unit and retry. return self.function_unit / other else: raise UnitsError("Cannot divide a function unit " "with a physical dimension by any unit.") else: # Anything not like a unit, try initialising as a function quantity. try: return self._quantity_class(1. / other, unit=self) except Exception: return NotImplemented def __rdiv__(self, other): if isinstance(other, (str, UnitBase, FunctionUnitBase)): if self.physical_unit == dimensionless_unscaled: # If dimensionless, drop back to normal unit and retry. return other / self.function_unit else: raise UnitsError("Cannot divide a function unit " "with a physical dimension into any unit") else: # Don't know what to do with anything not like a unit. return NotImplemented __truediv__ = __div__ __rtruediv__ = __rdiv__ def __pow__(self, power): if power == 0: return dimensionless_unscaled elif power == 1: return self._copy() if self.physical_unit == dimensionless_unscaled: return self.function_unit**power raise UnitsError("Cannot raise a function unit " "with a physical dimension to any power but 0 or 1.") def __pos__(self): return self._copy() def to_string(self, format='generic'): """ Output the unit in the given format as a string. The physical unit is appended, within parentheses, to the function unit, as in "dB(mW)", with both units set using the given format Parameters ---------- format : `astropy.units.format.Base` instance or str The name of a format or a formatter object. If not provided, defaults to the generic format. """ if format not in ('generic', 'unscaled', 'latex'): raise ValueError("Function units cannot be written in {0} format. " "Only 'generic', 'unscaled' and 'latex' are " "supported.".format(format)) self_str = self.function_unit.to_string(format) pu_str = self.physical_unit.to_string(format) if pu_str == '': pu_str = '1' if format == 'latex': self_str += r'$\mathrm{{\left( {0} \right)}}$'.format( pu_str[1:-1]) # need to strip leading and trailing "$" else: self_str += '({0})'.format(pu_str) return self_str def __str__(self): """Return string representation for unit.""" self_str = str(self.function_unit) pu_str = str(self.physical_unit) if pu_str: self_str += '({0})'.format(pu_str) return self_str def __repr__(self): # By default, try to give a representation using `Unit(<string>)`, # with string such that parsing it would give the correct FunctionUnit. if callable(self.function_unit): return 'Unit("{0}")'.format(self.to_string()) else: return '{0}("{1}"{2})'.format( self.__class__.__name__, self.physical_unit, "" if self.function_unit is self._default_function_unit else ', unit="{0}"'.format(self.function_unit)) def _repr_latex_(self): """ Generate latex representation of unit name. This is used by the IPython notebook to print a unit with a nice layout. Returns ------- Latex string """ return self.to_string('latex') def __hash__(self): return hash((self.function_unit, self.physical_unit))
def to(self, unit, equivalencies=[], doppler_rest=None, doppler_convention=None): """ Return a new `~astropy.coordinates.SpectralQuantity` object with the specified unit. By default, the ``spectral`` equivalency will be enabled, as well as one of the Doppler equivalencies if converting to/from velocities. Parameters ---------- unit : unit-like An object that represents the unit to convert to. Must be an `~astropy.units.UnitBase` object or a string parseable by the `~astropy.units` package, and should be a spectral unit. equivalencies : list of `~astropy.units.equivalencies.Equivalency`, optional A list of equivalence pairs to try if the units are not directly convertible (along with spectral). See :ref:`astropy:unit_equivalencies`. If not provided or ``[]``, spectral equivalencies will be used. If `None`, no equivalencies will be applied at all, not even any set globally or within a context. doppler_rest : `~astropy.units.Quantity` ['speed'], optional The rest value used when converting to/from velocities. This will also be set at an attribute on the output `~astropy.coordinates.SpectralQuantity`. doppler_convention : {'relativistic', 'optical', 'radio'}, optional The Doppler convention used when converting to/from velocities. This will also be set at an attribute on the output `~astropy.coordinates.SpectralQuantity`. Returns ------- `SpectralQuantity` New spectral coordinate object with data converted to the new unit. """ # Make sure units can be passed as strings unit = Unit(unit) # If equivalencies is explicitly set to None, we should just use the # default Quantity.to with equivalencies also set to None if equivalencies is None: result = super().to(unit, equivalencies=None) result = result.view(self.__class__) result.__array_finalize__(self) return result # FIXME: need to consider case where doppler equivalency is passed in # equivalencies list, or is u.spectral equivalency is already passed if doppler_rest is None: doppler_rest = self._doppler_rest if doppler_convention is None: doppler_convention = self._doppler_convention elif doppler_convention not in DOPPLER_CONVENTIONS: raise ValueError( f"doppler_convention should be one of {'/'.join(sorted(DOPPLER_CONVENTIONS))}" ) if self.unit.is_equivalent(KMS) and unit.is_equivalent(KMS): # Special case: if the current and final units are both velocity, # and either the rest value or the convention are different, we # need to convert back to frequency temporarily. if doppler_convention is not None and self._doppler_convention is None: raise ValueError("Original doppler_convention not set") if doppler_rest is not None and self._doppler_rest is None: raise ValueError("Original doppler_rest not set") if doppler_rest is None and doppler_convention is None: result = super().to(unit, equivalencies=equivalencies) result = result.view(self.__class__) result.__array_finalize__(self) return result elif (doppler_rest is None) is not (doppler_convention is None): raise ValueError("Either both or neither doppler_rest and " "doppler_convention should be defined for " "velocity conversions") vel_equiv1 = DOPPLER_CONVENTIONS[self._doppler_convention]( self._doppler_rest) freq = super().to(si.Hz, equivalencies=equivalencies + vel_equiv1) vel_equiv2 = DOPPLER_CONVENTIONS[doppler_convention](doppler_rest) result = freq.to(unit, equivalencies=equivalencies + vel_equiv2) else: additional_equivalencies = eq.spectral() if self.unit.is_equivalent(KMS) or unit.is_equivalent(KMS): if doppler_convention is None: raise ValueError( "doppler_convention not set, cannot convert to/from velocities" ) if doppler_rest is None: raise ValueError( "doppler_rest not set, cannot convert to/from velocities" ) additional_equivalencies = additional_equivalencies + DOPPLER_CONVENTIONS[ doppler_convention](doppler_rest) result = super().to(unit, equivalencies=equivalencies + additional_equivalencies) # Since we have to explicitly specify when we want to keep this as a # SpectralQuantity, we need to convert it back from a Quantity to # a SpectralQuantity here. Note that we don't use __array_finalize__ # here since we might need to set the output doppler convention and # rest based on the parameters passed to 'to' result = result.view(self.__class__) result.__array_finalize__(self) result._doppler_convention = doppler_convention result._doppler_rest = doppler_rest return result
class FunctionUnitBase(metaclass=ABCMeta): """Abstract base class for function units. Function units are functions containing a physical unit, such as dB(mW). Most of the arithmetic operations on function units are defined in this base class. While instantiation is defined, this class should not be used directly. Rather, subclasses should be used that override the abstract properties `_default_function_unit` and `_quantity_class`, and the abstract methods `from_physical`, and `to_physical`. Parameters ---------- physical_unit : `~astropy.units.Unit` or `string` Unit that is encapsulated within the function unit. If not given, dimensionless. function_unit : `~astropy.units.Unit` or `string` By default, the same as the function unit set by the subclass. """ # ↓↓↓ the following four need to be set by subclasses # Make this a property so we can ensure subclasses define it. @property @abstractmethod def _default_function_unit(self): """Default function unit corresponding to the function. This property should be overridden by subclasses, with, e.g., `~astropy.unit.MagUnit` returning `~astropy.unit.mag`. """ # This has to be a property because the function quantity will not be # known at unit definition time, as it gets defined after. @property @abstractmethod def _quantity_class(self): """Function quantity class corresponding to this function unit. This property should be overridden by subclasses, with, e.g., `~astropy.unit.MagUnit` returning `~astropy.unit.Magnitude`. """ @abstractmethod def from_physical(self, x): """Transformation from value in physical to value in function units. This method should be overridden by subclasses. It is used to provide automatic transformations using an equivalency. """ @abstractmethod def to_physical(self, x): """Transformation from value in function to value in physical units. This method should be overridden by subclasses. It is used to provide automatic transformations using an equivalency. """ # ↑↑↑ the above four need to be set by subclasses # have priority over arrays, regular units, and regular quantities __array_priority__ = 30000 def __init__(self, physical_unit=None, function_unit=None): if physical_unit is None: self._physical_unit = dimensionless_unscaled else: self._physical_unit = Unit(physical_unit) if (not isinstance(self._physical_unit, UnitBase) or self._physical_unit.is_equivalent( self._default_function_unit)): raise ValueError("Unit {0} is not a physical unit." .format(self._physical_unit)) if function_unit is None: self._function_unit = self._default_function_unit else: # any function unit should be equivalent to subclass default function_unit = Unit(getattr(function_unit, 'function_unit', function_unit)) if function_unit.is_equivalent(self._default_function_unit): self._function_unit = function_unit else: raise ValueError("Cannot initialize '{0}' instance with " "function unit '{1}', as it is not " "equivalent to default function unit '{2}'." .format(self.__class__.__name__, function_unit, self._default_function_unit)) def _copy(self, physical_unit=None): """Copy oneself, possibly with a different physical unit.""" if physical_unit is None: physical_unit = self.physical_unit return self.__class__(physical_unit, self.function_unit) @property def physical_unit(self): return self._physical_unit @property def function_unit(self): return self._function_unit @property def equivalencies(self): """List of equivalencies between function and physical units. Uses the `from_physical` and `to_physical` methods. """ return [(self, self.physical_unit, self.to_physical, self.from_physical)] # ↓↓↓ properties/methods required to behave like a unit def decompose(self, bases=set()): """Copy the current unit with the physical unit decomposed. For details, see `~astropy.units.UnitBase.decompose`. """ return self._copy(self.physical_unit.decompose(bases)) @property def si(self): """Copy the current function unit with the physical unit in SI.""" return self._copy(self.physical_unit.si) @property def cgs(self): """Copy the current function unit with the physical unit in CGS.""" return self._copy(self.physical_unit.cgs) def _get_physical_type_id(self): """Get physical type corresponding to physical unit.""" return self.physical_unit._get_physical_type_id() @property def physical_type(self): """Return the physical type of the physical unit (e.g., 'length').""" return self.physical_unit.physical_type def is_equivalent(self, other, equivalencies=[]): """ Returns `True` if this unit is equivalent to ``other``. Parameters ---------- other : unit object or string or tuple The unit to convert to. If a tuple of units is specified, this method returns true if the unit matches any of those in the tuple. equivalencies : list of equivalence pairs, optional A list of equivalence pairs to try if the units are not directly convertible. See :ref:`unit_equivalencies`. This list is in addition to the built-in equivalencies between the function unit and the physical one, as well as possible global defaults set by, e.g., `~astropy.units.set_enabled_equivalencies`. Use `None` to turn off any global equivalencies. Returns ------- bool """ if isinstance(other, tuple): return any(self.is_equivalent(u, equivalencies=equivalencies) for u in other) other_physical_unit = getattr(other, 'physical_unit', ( dimensionless_unscaled if self.function_unit.is_equivalent(other) else other)) return self.physical_unit.is_equivalent(other_physical_unit, equivalencies) def to(self, other, value=1., equivalencies=[]): """ Return the converted values in the specified unit. Parameters ---------- other : `~astropy.units.Unit` object, `~astropy.units.function.FunctionUnitBase` object or string The unit to convert to. value : scalar int or float, or sequence convertible to array, optional Value(s) in the current unit to be converted to the specified unit. If not provided, defaults to 1.0. equivalencies : list of equivalence pairs, optional A list of equivalence pairs to try if the units are not directly convertible. See :ref:`unit_equivalencies`. This list is in meant to treat only equivalencies between different physical units; the build-in equivalency between the function unit and the physical one is automatically taken into account. Returns ------- values : scalar or array Converted value(s). Input value sequences are returned as numpy arrays. Raises ------ UnitsError If units are inconsistent. """ # conversion to one's own physical unit should be fastest if other is self.physical_unit: return self.to_physical(value) other_function_unit = getattr(other, 'function_unit', other) if self.function_unit.is_equivalent(other_function_unit): # when other is an equivalent function unit: # first convert physical units to other's physical units other_physical_unit = getattr(other, 'physical_unit', dimensionless_unscaled) if self.physical_unit != other_physical_unit: value_other_physical = self.physical_unit.to( other_physical_unit, self.to_physical(value), equivalencies) # make function unit again, in own system value = self.from_physical(value_other_physical) # convert possible difference in function unit (e.g., dex->dB) return self.function_unit.to(other_function_unit, value) else: # when other is not a function unit return self.physical_unit.to(other, self.to_physical(value), equivalencies) def is_unity(self): return False def __eq__(self, other): return (self.physical_unit == getattr(other, 'physical_unit', dimensionless_unscaled) and self.function_unit == getattr(other, 'function_unit', other)) def __ne__(self, other): return not self.__eq__(other) def __mul__(self, other): if isinstance(other, (str, UnitBase, FunctionUnitBase)): if self.physical_unit == dimensionless_unscaled: # If dimensionless, drop back to normal unit and retry. return self.function_unit * other else: raise UnitsError("Cannot multiply a function unit " "with a physical dimension with any unit.") else: # Anything not like a unit, try initialising as a function quantity. try: return self._quantity_class(other, unit=self) except Exception: return NotImplemented def __rmul__(self, other): return self.__mul__(other) def __div__(self, other): if isinstance(other, (str, UnitBase, FunctionUnitBase)): if self.physical_unit == dimensionless_unscaled: # If dimensionless, drop back to normal unit and retry. return self.function_unit / other else: raise UnitsError("Cannot divide a function unit " "with a physical dimension by any unit.") else: # Anything not like a unit, try initialising as a function quantity. try: return self._quantity_class(1./other, unit=self) except Exception: return NotImplemented def __rdiv__(self, other): if isinstance(other, (str, UnitBase, FunctionUnitBase)): if self.physical_unit == dimensionless_unscaled: # If dimensionless, drop back to normal unit and retry. return other / self.function_unit else: raise UnitsError("Cannot divide a function unit " "with a physical dimension into any unit") else: # Don't know what to do with anything not like a unit. return NotImplemented __truediv__ = __div__ __rtruediv__ = __rdiv__ def __pow__(self, power): if power == 0: return dimensionless_unscaled elif power == 1: return self._copy() if self.physical_unit == dimensionless_unscaled: return self.function_unit ** power raise UnitsError("Cannot raise a function unit " "with a physical dimension to any power but 0 or 1.") def __pos__(self): return self._copy() def to_string(self, format='generic'): """ Output the unit in the given format as a string. The physical unit is appended, within parentheses, to the function unit, as in "dB(mW)", with both units set using the given format Parameters ---------- format : `astropy.units.format.Base` instance or str The name of a format or a formatter object. If not provided, defaults to the generic format. """ if format not in ('generic', 'unscaled', 'latex'): raise ValueError("Function units cannot be written in {0} format. " "Only 'generic', 'unscaled' and 'latex' are " "supported.".format(format)) self_str = self.function_unit.to_string(format) pu_str = self.physical_unit.to_string(format) if pu_str == '': pu_str = '1' if format == 'latex': self_str += r'$\mathrm{{\left( {0} \right)}}$'.format( pu_str[1:-1]) # need to strip leading and trailing "$" else: self_str += '({0})'.format(pu_str) return self_str def __str__(self): """Return string representation for unit.""" self_str = str(self.function_unit) pu_str = str(self.physical_unit) if pu_str: self_str += '({0})'.format(pu_str) return self_str def __repr__(self): # By default, try to give a representation using `Unit(<string>)`, # with string such that parsing it would give the correct FunctionUnit. if callable(self.function_unit): return 'Unit("{0}")'.format(self.to_string()) else: return '{0}("{1}"{2})'.format( self.__class__.__name__, self.physical_unit, "" if self.function_unit is self._default_function_unit else ', unit="{0}"'.format(self.function_unit)) def _repr_latex_(self): """ Generate latex representation of unit name. This is used by the IPython notebook to print a unit with a nice layout. Returns ------- Latex string """ return self.to_string('latex') def __hash__(self): return hash((self.function_unit, self.physical_unit))
def ingest_filter_transmission(path: str, fil_name: str, instrument: str, instrument_response: bool = False, atmosphere: bool = False, lambda_eff: units.Quantity = None, fwhm: float = None, source: str = None, wavelength_unit: units.Unit = units.Angstrom, percentage: bool = False, quiet: bool = False): """ :param path: :param fil_name: :param instrument: :param instrument_response: Filter curve includes instrument response :param atmosphere: Filter curve includes atmospheric transmission :param lambda_eff: :param fwhm: :param source: :param wavelength_unit: :param percentage: :param quiet: :return: """ if not wavelength_unit.is_equivalent(units.Angstrom): raise units.UnitTypeError( f"Wavelength units must be of type length, not {wavelength_unit}") type_str = "_filter" if instrument_response: type_str += "_instrument" if atmosphere: type_str += "_atmosphere" params = filter_params(f=fil_name, instrument=instrument, quiet=quiet) if params is None: params = new_filter_params(quiet=quiet) params['name'] = fil_name params['instrument'] = instrument if lambda_eff is not None: lambda_eff = u.check_quantity(lambda_eff, unit=units.Angstrom, convert=True) params['lambda_eff'] = lambda_eff # TODO: If None, measure? if fwhm is not None: params['fwhm'] = fwhm # TODO: If None, measure? if source is not None: params[f'source{type_str}'] = source tbl = QTable.read(path, format="ascii") tbl["col1"].name = "wavelength" tbl["wavelength"] *= wavelength_unit tbl["wavelength"] = tbl["wavelength"].to("Angstrom") tbl["col2"].name = "transmission" if percentage: tbl["transmission"] /= 100 tbl.sort("wavelength") params[f'wavelengths{type_str}'] = tbl["wavelength"].value.tolist() params[f'transmissions{type_str}'] = tbl["transmission"].value.tolist() save_params(file=os.path.join(param_dir, 'filters', f'{instrument}-{fil_name}'), dictionary=params, quiet=quiet)