Skip to content

Commit

Permalink
Merge pull request #24 from ibaris/units
Browse files Browse the repository at this point in the history
Add frequency conversion method
  • Loading branch information
ibaris committed Apr 19, 2019
2 parents 97ffda0 + f1d6c51 commit dc740b5
Show file tree
Hide file tree
Showing 4 changed files with 98 additions and 43 deletions.
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
numpy
sympy
scipy
numpy
2 changes: 1 addition & 1 deletion rspy/__version__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"""
Created on 31.12.2019 by Ismail Baris
"""
version_info = (0, 0, 2)
version_info = (0, 0, 3)
__version__ = '.'.join(map(str, version_info))
114 changes: 91 additions & 23 deletions rspy/units/ancillary.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

import numpy as np

import rspy.constants as const
from rspy.auxiliary import Operator, UnitError
from rspy.bin.bin_units import sym_convert_to
from rspy.units.auxiliary import (Frequency, Length, Energy, Power, Time, Temperature, Mass, Current, Other,
Expand Down Expand Up @@ -71,6 +72,9 @@ def __init__(self):

self.__setup_units()

# --------------------------------------------------------------------------------------------------------
# Magic Methods
# --------------------------------------------------------------------------------------------------------
def __getattr__(self, name):
try:
return self[name]
Expand All @@ -91,25 +95,9 @@ def __repr__(self):
def __dir__(self):
return list(self.keys())

def __setup_units(self):
"""
Setup Unit class with all available units and dimensions.
Returns
-------
None
"""
for item in self.units.keys():
dimension = self.units[item].dimension.name

if dim_isnone(self.units[item]) or dim_isone(self.units[item]) or dim_iszero(self.units[item]):
self.__unit_dict['other'][str(item)] = self.units[item]
else:
self.__unit_dict[str(dimension)][str(item)] = self.units[item]

for item in self.__unit_dict.keys():
self[item] = self.__unit_dict[item]

# --------------------------------------------------------------------------------------------------------
# Callable Methods
# --------------------------------------------------------------------------------------------------------
@staticmethod
def unit_isnone(unit):
"""
Expand Down Expand Up @@ -267,8 +255,7 @@ def get_unit(unit):
else:
raise UnitError("{} is not a valid unit.".format(str(unit)))

@staticmethod
def convert_to(value, unit, to_unit):
def convert_to(self, value, unit, to_unit):

if isinstance(unit, str):
unit = Units.str2unit(unit)
Expand All @@ -293,7 +280,6 @@ def convert_to(value, unit, to_unit):

elif hasattr(to_unit, 'dimension') and hasattr(unit, 'dimension'):
if to_unit.dimension == unit.dimension:

# Convert tempretures
if unit.dimension == Units.dimensions['temperature']:

Expand All @@ -318,7 +304,7 @@ def convert_to(value, unit, to_unit):
if to_unit == Units.temperature.celsius:
value = (value - 32) / unit.scale_factor
if to_unit == Units.temperature.kelvin:
value = (value + 459.67) * 5./9.
value = (value + 459.67) * 5. / 9.

else:
scaled_value = value * Units[str(to_unit.dimension.name)][str(unit)].scale_factor
Expand All @@ -327,6 +313,12 @@ def convert_to(value, unit, to_unit):

return np.atleast_1d(np.asarray(value, dtype=np.double))

if unit.dimension == Units.dimensions['length'] and to_unit.dimension == Units.dimensions['frequency']:
return np.atleast_1d(self.__convert_wavelength(value, unit, to_unit))

if unit.dimension == Units.dimensions['frequency'] and to_unit.dimension == Units.dimensions['length']:
return np.atleast_1d(self.__convert_frequency(value, unit, to_unit))

if isinstance(value, np.ndarray):
shape = value.shape
expr = value.astype(np.double).flatten() * unit
Expand All @@ -341,5 +333,81 @@ def convert_to(value, unit, to_unit):

return sym_convert_to(expr, to_unit).base

# --------------------------------------------------------------------------------------------------------
# Private Methods
# --------------------------------------------------------------------------------------------------------
def __convert_wavelength(self, wavelength, unit='cm', output='GHz'):
"""
Convert wavelengths in frequencies.
Parameters
----------
wavelength : int, float, np.ndarray, object
Wavelength as int, float, numpy.ndarray or as a respy.units.quantity.Quantity object.
unit : str, object
Unit of the wavelength (default is 'cm'). See respy.units.Units.length.keys() for available units.
This is optional if the input is an respy.units.quantity.Quantity object.
output : str, object
Unit of entered frequency (default is 'GHz'). See respy.units.Units.frequency.keys() for available units.
Returns
-------
frequency: float, np.ndarray or respy.units.quantity.Quantity
"""
unit = Units.get_unit(unit)
output = Units.get_unit(output)

c = Units.convert_to(const.c, 'm / s', unit / Units.time.s)
f = c / wavelength

return Units.convert_to(f, 'Hz', output)

def __convert_frequency(self, frequency, unit='GHz', output='cm'):
"""
Convert frequencies in wavelength.
Parameters
----------
frequency : int, float, np.ndarray, object
Frequency as int, float, numpy.ndarray or as a respy.units.quantity.Quantity object.
unit : str, object
Unit of entered frequency (default is 'GHz'). See respy.units.Units.frequency.keys() for available units.
This is optional if the input is an respy.units.quantity.Quantity object.
output : str, object
Unit of the wavelength (default is 'cm'). See respy.units.Units.length.keys() for available units.
Returns
-------
Wavelength: float, np.ndarray or respy.units.quantity.Quantity
"""
unit = Units.get_unit(unit)
output = Units.get_unit(output)

frequency = Units.convert_to(frequency, unit, '1 / s')

w = const.c / frequency

return Units.convert_to(w, 'm', output)

def __setup_units(self):
"""
Setup Unit class with all available units and dimensions.
Returns
-------
None
"""
for item in self.units.keys():
dimension = self.units[item].dimension.name

if dim_isnone(self.units[item]) or dim_isone(self.units[item]) or dim_iszero(self.units[item]):
self.__unit_dict['other'][str(item)] = self.units[item]
else:
self.__unit_dict[str(dimension)][str(item)] = self.units[item]

for item in self.__unit_dict.keys():
self[item] = self.__unit_dict[item]


Units = Units()
23 changes: 5 additions & 18 deletions rspy/waves/waves.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@
import numpy as np

import rspy.constants as const
from rspy.units import Units
from rspy.auxiliary import UnitError
from rspy.ancillary import align_all
from rspy.auxiliary import UnitError
from rspy.units.ancillary import Units

__all__ = ['Waves']

Expand Down Expand Up @@ -270,15 +270,9 @@ def compute_frequency(wavelength, unit='cm', output='GHz'):
Returns
-------
frequency: float, np.ndarray or respy.units.quantity.Quantity
"""
unit = Units.get_unit(unit)
output = Units.get_unit(output)

c = Units.convert_to(const.c, 'm / s', unit / Units.time.s)
f = c / wavelength

return Units.convert_to(f, 'Hz', output)
return Units.convert_to(wavelength, unit, output)

@staticmethod
def compute_wavelength(frequency, unit='GHz', output='cm'):
Expand All @@ -299,14 +293,7 @@ def compute_wavelength(frequency, unit='GHz', output='cm'):
-------
Wavelength: float, np.ndarray or respy.units.quantity.Quantity
"""
unit = Units.get_unit(unit)
output = Units.get_unit(output)

frequency = Units.convert_to(frequency, unit, '1 / s')

w = const.c / frequency

return Units.convert_to(w, 'm', output)
return Units.convert_to(frequency, unit, output)

@staticmethod
def compute_wavenumber(frequency, unit='GHz', output='cm'):
Expand All @@ -327,4 +314,4 @@ def compute_wavenumber(frequency, unit='GHz', output='cm'):
-------
wavenumber: float, np.ndarray or respy.units.quantity.Quantity
"""
return 2 * const.pi / Waves.compute_wavelength(frequency, unit=unit, output=output)
return 2 * const.pi / Units.convert_to(frequency, unit, output)

0 comments on commit dc740b5

Please sign in to comment.