def spectral_factor_hz_to_micron(wavelength):
"""
This function ...
:param wavelength:
:return:
"""
wavelength_unit = "micron"
frequency_unit = "Hz"
# Convert string units to Unit objects
if isinstance(wavelength_unit, basestring): wavelength_unit = Unit(wavelength_unit)
if isinstance(frequency_unit, basestring): frequency_unit = Unit(frequency_unit)
conversion_factor_unit = wavelength_unit / frequency_unit
# Calculate the conversion factor
factor = (wavelength ** 2 / speed_of_light).to(conversion_factor_unit).value
return 1. / factor
# -----------------------------------------------------------------
python类Unit()的实例源码
def spectral_factor_hz_to_meter(wavelength):
"""
This function ...
:return:
"""
wavelength_unit = "m"
frequency_unit = "Hz"
# Convert string units to Unit objects
if isinstance(wavelength_unit, basestring): wavelength_unit = Unit(wavelength_unit)
if isinstance(frequency_unit, basestring): frequency_unit = Unit(frequency_unit)
conversion_factor_unit = wavelength_unit / frequency_unit
# Calculate the conversion factor
factor = (wavelength ** 2 / speed_of_light).to(conversion_factor_unit).value
return 1./factor
# -----------------------------------------------------------------
def get_quantity(self, element, name, default_unit=None):
# Import Astropy here to avoid import errors for this module for users without an Astropy installation
from astropy.units import Unit
splitted = element.get(name).split()
value = float(splitted[0])
try:
unit = splitted[1]
except IndexError:
unit = default_unit
# Create a quantity object
if unit is not None: value = value * Unit(unit)
return value
# -----------------------------------------------------------------
## This function sets the value of a certain parameter of the specified tree element from an Astropy quantity.
def set_quantity(self, element, name, value, default_unit=None):
# Import Astropy here to avoid import errors for this module for users without an Astropy installation
from astropy.units import Unit
try:
# If this works, assume it is a Quantity (or Angle)
unit = value.unit
# Works for Angles as well (str(angle) gives something that is not 'value + unit'
to_string = str(value.to(value.unit).value) + " " + str(unit)
except AttributeError:
if default_unit is not None:
to_string = str(value) + " " + str(Unit(default_unit))
else:
to_string = str(value) # dimensionless quantity
# Set the value in the tree element
element.set(name, to_string)
# -----------------------------------------------------------------
def get_cutout_range_for_galaxy(self, galaxy_name):
"""
This function ...
:param galaxy_name:
:return:
"""
# Find the index of the galaxy in the LEDA - WISE table
index = tables.find_index(self.leda_wise_table, galaxy_name)
# Get the RA and DEC
ra = self.leda_wise_table["ra2000"][index] * Unit("deg")
dec = self.leda_wise_table["de2000"][index] * Unit("deg")
# Get the D25
d25_arcmin = self.leda_wise_table["d25"][index]
if d25_arcmin < 6: width = .5 * Unit("deg")
else: width = 1. * Unit("deg")
# Return the RA, DEC and width (all in degrees)
return ra, dec, width
# -----------------------------------------------------------------
def unit(self, unit):
"""
This function ...
:param unit:
:return:
"""
# Convert string units to Astropy unit objects
if isinstance(unit, basestring): unit = Unit(unit)
# Loop over all frames
for frame_name in self.frames:
# Inform the user
log.debug("Setting the unit of the " + frame_name + " frame to " + str(unit) + " ...")
# Set the unit for this frame
self.frames[frame_name].unit = unit
# -----------------------------------------------------------------
def fwhms(self):
"""
This function ...
:return:
"""
# Initialize a list to contain the fwhm of the fitted stars
fwhms = []
# Loop over all stars
for star in self.stars:
# If the star contains a model, add the fwhm of that model to the list
if star.has_model:
fwhm_pix = star.fwhm * Unit("pix")
fwhm_arcsec = fwhm_pix * self.frame.average_pixelscale.to("arcsec/pix")
fwhms.append(fwhm_arcsec)
# Return the list
return fwhms
# -----------------------------------------------------------------
def length(self):
"""
This function ...
:return:
"""
dec_start = self.start.dec.to("deg").value
dec_end = self.end.dec.to("deg").value
dec_center = 0.5 * (dec_start + dec_end)
ra_start = self.start.ra.to("deg").value
ra_end = self.end.ra.to("deg").value
# Calculate the actual RA and DEC distance in degrees
ra_distance = abs(coordinates.ra_distance(dec_center, ra_start, ra_end))
dec_distance = abs(dec_end - dec_start)
ra_span = ra_distance * Unit("deg")
dec_span = dec_distance * Unit("deg")
return math.sqrt(ra_span**2 + dec_span**2)
# -----------------------------------------------------------------
def from_pixel(cls, circle, wcs):
"""
This function ...
:param circle:
:param wcs:
:return:
"""
center = SkyCoordinate.from_pixel(circle.center, wcs)
# Get the pixelscale
radius = circle.radius * Unit("pix") * wcs.average_pixelscale
# Create a new SkyCircle
return cls(center, radius, meta=circle.meta)
# -----------------------------------------------------------------
def from_pixel(cls, rectangle, wcs):
"""
This function ...
:param rectangle:
:param wcs:
:return:
"""
center = SkyCoordinate.from_pixel(rectangle.center, wcs)
# Get the pixelscale
radius = rectangle.radius * Unit("pix") * wcs.average_pixelscale
# Create a new SkyRectangle
return cls(center, radius, rectangle.angle, meta=rectangle.meta)
# -----------------------------------------------------------------
def __init__(self, wavelengths=None, transmissions=None):
"""
This function ...
:param wavelengths:
:param transmissions:
:return:
"""
# Column names
names = ["Wavelength", "Transmission"]
# Create the table
if wavelengths is None or transmissions is None: self.table = Table(names=names, dtype=('f8', 'f8'))
else: self.table = tables.new([wavelengths, transmissions], names)
# Set column units
self.table["Wavelength"].unit = Unit("micron")
# -----------------------------------------------------------------
def __init__(self, wavelengths=None, attenuations=None):
"""
This function ...
:param wavelengths:
:param attenuations:
:return:
"""
# Column names
names = ["Wavelength", "Attenuation"]
# Create the table
if wavelengths is None or attenuations is None: self.table = Table(names=names, dtype=('f8', 'f8'))
else: self.table = tables.new([wavelengths, attenuations], names)
# Set column units
self.table["Wavelength"].unit = Unit("micron")
# -----------------------------------------------------------------
def luminosity_for_filter(self, filter, unit="W/micron"):
"""
This function ...
:param filter:
:param unit:
:return:
"""
# Convole the Sun SED over the filter transmission curve
luminosity = filter.convolve(self.sed.wavelengths(unit="micron", asarray=True), self.sed.luminosities(unit="W/micron", asarray=True)) # also in W/micron
luminosity = luminosity * Unit("W/micron")
# Return the luminosity
return luminosity.to(unit)
# -----------------------------------------------------------------
def __init__(self):
"""
This function ...
:return:
"""
# Attributes
self.table = Table(names=["Observatory", "Instrument", "Band", "Wavelength", "Flux", "Error-", "Error+"],
dtype=('S10', 'S10', 'S10', 'f8', 'f8', 'f8', 'f8'))
self.table["Wavelength"].unit = Unit("micron")
self.table["Flux"].unit = Unit("Jy")
self.table["Error-"].unit = Unit("Jy")
self.table["Error+"].unit = Unit("Jy")
# -----------------------------------------------------------------
def luminosity_for_filter(self, filter, unit="W/micron"):
"""
This function ...
:param filter:
:param unit:
:return:
"""
#luminosity = filter.integrate(self.sed["Wavelength"], self.sed["Luminosity"])
luminosity = filter.convolve(self.sed.wavelengths(unit="micron", asarray=True), self.sed.luminosities(unit="W/micron", asarray=True)) # also in W/micron
luminosity = luminosity * Unit("W/micron")
# Return the luminosity in the desired unit
return luminosity.to(unit)
# -----------------------------------------------------------------
def get_quantity(entry, default_unit=None):
"""
This function ...
:param entry:
:param default_unit:
:return:
"""
splitted = entry.split()
value = float(splitted[0])
try: unit = splitted[1]
except IndexError: unit = default_unit
# Create a quantity object and return it
if unit is not None: value = value * Unit(unit)
return value
# -----------------------------------------------------------------
def get_quantity(entry, default_unit=None):
"""
This function ...
:param entry:
:param default_unit:
:return:
"""
splitted = entry.split()
value = float(splitted[0])
try: unit = splitted[1]
except IndexError: unit = default_unit
# Create a quantity object and return it
if unit is not None: value = value * Unit(unit)
return value
# -----------------------------------------------------------------
def spectral_factor(wavelength, wavelength_unit, frequency_unit):
"""
This function ...
:param wavelength:
:param wavelength_unit:
:param frequency_unit:
:return:
"""
# Convert string units to Unit objects
if isinstance(wavelength_unit, basestring): wavelength_unit = u.Unit(wavelength_unit)
if isinstance(frequency_unit, basestring): frequency_unit = u.Unit(frequency_unit)
conversion_factor_unit = wavelength_unit / frequency_unit
# Calculate the conversion factor
return (wavelength**2 / speed_of_light).to(conversion_factor_unit).value
# -----------------------------------------------------------------
def convert_sdss(self):
"""
This function ...
:return:
"""
# Unit = nanomaggies
# 1 nanomaggie = 3.613e-6 Jy
# Conversion from nanomaggies to Jy (per pixel2)
self.conversion_factor *= 3.613e-6
# Conversion from Jy per pixel2 to the target unit (MJy / sr)
self.convert_from_jy()
# -----------------------------------------------------------------
def get_quantity(entry, default_unit=None):
"""
This function ...
:param entry:
:param default_unit:
:return:
"""
splitted = entry.split()
value = float(splitted[0])
try: unit = splitted[1]
except IndexError: unit = default_unit
# Create a quantity object and return it
if unit is not None: value = value * Unit(unit)
return value
# -----------------------------------------------------------------
def project_azimuth_to_pa(azimuth, inclination):
"""
This function ...
:param azimuth:
:param inclination:
"""
# Get the azimuth angle and inclination in radians
azimuth_radian = azimuth.to("radian").value
i_radian = inclination.to("radian").value
denominator = math.sqrt(math.cos(azimuth_radian)**2 * math.cos(i_radian)**2 + math.sin(azimuth_radian)**2)
cos_pa = math.cos(azimuth_radian) * math.cos(i_radian) / denominator
sin_pa = math.sin(azimuth_radian) / denominator
pa_radian = math.atan2(sin_pa, cos_pa) * Unit("radian")
return pa_radian.to("deg")
# -----------------------------------------------------------------
def deproject_pa_to_azimuth(pa, inclination):
"""
This function ...
:param pa:
:param inclination:
:return:
"""
# Get the PA and inclination in radians
pa_radian = pa.to("radian").value
i_radian = inclination.to("radian").value
denominator = math.sqrt(math.cos(pa_radian)**2 + math.sin(pa_radian)**2 * math.cos(i_radian)**2)
cos_azimuth = math.cos(pa_radian) / denominator
sin_azimuth = math.sin(pa_radian) * math.cos(inclination) / denominator
azimuth_radian = math.atan2(sin_azimuth, cos_azimuth) * Unit("radian")
return azimuth_radian.to("deg")
# -----------------------------------------------------------------
def spectral_factor_hz_to_micron(wavelength):
"""
This function ...
:param wavelength:
:return:
"""
wavelength_unit = "micron"
frequency_unit = "Hz"
# Convert string units to Unit objects
if isinstance(wavelength_unit, basestring): wavelength_unit = Unit(wavelength_unit)
if isinstance(frequency_unit, basestring): frequency_unit = Unit(frequency_unit)
conversion_factor_unit = wavelength_unit / frequency_unit
# Calculate the conversion factor
factor = (wavelength ** 2 / speed_of_light).to(conversion_factor_unit).value
return 1. / factor
# -----------------------------------------------------------------
def fluxdensity_to_luminosity(fluxdensity, wavelength, distance):
"""
This function ...
:param fluxdensity:
:param wavelength:
:param distance:
:return:
"""
luminosity = (fluxdensity * 4. * math.pi * distance ** 2.).to("W/Hz")
# 3 ways:
#luminosity_ = luminosity.to("W/micron", equivalencies=spectral_density(wavelength)) # does not work
luminosity_ = (speed_of_light * luminosity / wavelength**2).to("W/micron")
luminosity = luminosity.to("W/Hz").value * spectral_factor_hz_to_micron(wavelength) * Unit("W/micron")
#print(luminosity_, luminosity) # is OK!
return luminosity
# -----------------------------------------------------------------
def spectral_factor_hz_to_meter(wavelength):
"""
This function ...
:return:
"""
wavelength_unit = "m"
frequency_unit = "Hz"
# Convert string units to Unit objects
if isinstance(wavelength_unit, basestring): wavelength_unit = Unit(wavelength_unit)
if isinstance(frequency_unit, basestring): frequency_unit = Unit(frequency_unit)
conversion_factor_unit = wavelength_unit / frequency_unit
# Calculate the conversion factor
factor = (wavelength ** 2 / speed_of_light).to(conversion_factor_unit).value
return 1./factor
# -----------------------------------------------------------------
def get_quantity(entry, default_unit=None):
"""
This function ...
:param entry:
:param default_unit:
:return:
"""
splitted = entry.split()
value = float(splitted[0])
try: unit = splitted[1]
except IndexError: unit = default_unit
# Create a quantity object and return it
if unit is not None: value = value * Unit(unit)
return value
# -----------------------------------------------------------------
def get_quantity(self, element, name, default_unit=None):
# Import Astropy here to avoid import errors for this module for users without an Astropy installation
from astropy.units import Unit
splitted = element.get(name).split()
value = float(splitted[0])
try:
unit = splitted[1]
except IndexError:
unit = default_unit
# Create a quantity object
if unit is not None: value = value * Unit(unit)
return value
# -----------------------------------------------------------------
## This function sets the value of a certain parameter of the specified tree element from an Astropy quantity.
def set_quantity(self, element, name, value, default_unit=None):
# Import Astropy here to avoid import errors for this module for users without an Astropy installation
from astropy.units import Unit
try:
# If this works, assume it is a Quantity (or Angle)
unit = value.unit
# Works for Angles as well (str(angle) gives something that is not 'value + unit'
to_string = str(value.to(value.unit).value) + " " + str(unit)
except AttributeError:
if default_unit is not None:
to_string = str(value) + " " + str(Unit(default_unit))
else:
to_string = str(value) # dimensionless quantity
# Set the value in the tree element
element.set(name, to_string)
# -----------------------------------------------------------------
def get_quantity(self, element, name, default_unit=None):
# Import Astropy here to avoid import errors for this module for users without an Astropy installation
from astropy.units import Unit
prop = element.get(name)
if prop.startswith("[") and prop.endswith("]"): prop = prop[1:-1].split(":")[1]
splitted = prop.split()
value = float(splitted[0])
try: unit = splitted[1]
except IndexError: unit = default_unit
# Create a quantity object
if unit is not None: value = value * Unit(unit)
return value
# -----------------------------------------------------------------
# Overwrite the default implementation in SkiFile to incorporate labeled properties
def unit(self, unit):
"""
This function ...
:param unit:
:return:
"""
# Convert string units to Astropy unit objects
if isinstance(unit, basestring): unit = Unit(unit)
# Loop over all frames
for frame_name in self.frames:
# Inform the user
log.debug("Setting the unit of the " + frame_name + " frame to " + str(unit) + " ...")
# Set the unit for this frame
self.frames[frame_name].unit = unit
# -----------------------------------------------------------------