Python astropy.units 模块,Unit() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用astropy.units.Unit()

项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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

# -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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

# -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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.
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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)

# -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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

    # -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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

    # -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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

    # -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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)

    # -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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)

    # -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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)

    # -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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")

    # -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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")

    # -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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)

    # -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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")

    # -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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)

# -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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

# -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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

# -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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

# -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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()

    # -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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

# -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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")

# -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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")

# -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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

# -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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

# -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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

# -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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

# -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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.
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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)

# -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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

    # -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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

    # -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def pixelscale(self):

        """
        This function ...
        :return:
        """

        result = utils.proj_plane_pixel_scales(self)

        # returns: A vector (ndarray) of projection plane increments corresponding to each pixel side (axis).
        # The units of the returned results are the same as the units of cdelt, crval, and cd for the celestial WCS
        # and can be obtained by inquiring the value of cunit property of the input WCS WCS object.

        x_pixelscale = result[0] * Unit("deg/pix")
        y_pixelscale = result[1] * Unit("deg/pix")

        # Return the pixel scale as an extent
        return Pixelscale(x_pixelscale, y_pixelscale)

    # -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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)

    # -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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)

    # -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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")

    # -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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)

    # -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def from_file(cls, path, skiprows=0):

        """
        This function ...
        :param path:
        :param skiprows:
        :return:
        """

        # Create a new SED
        sed = cls()

        wavelength_column, luminosity_column = np.loadtxt(path, dtype=float, unpack=True, skiprows=skiprows)
        sed.table = tables.new([wavelength_column, luminosity_column], ["Wavelength", "Luminosity"])
        sed.table["Wavelength"].unit = Unit("micron")
        sed.table["Luminosity"].unit = Unit("W/micron")

        # Return the SED
        return sed

    # -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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)

# -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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

# -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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

# -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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

# -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def setup(self, image):

        """
        This function ...
        :param image:
        :return:
        """

        # Call the setup function of the base class
        super(UnitConverter, self).setup()

        # Create a unit object
        self.target_unit = u.Unit(self.config.to_unit)

        # Set the image reference
        self.image = image

    # -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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

# -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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")

# -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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")

# -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def project_tilt_to_pa(tilt, inclination):

    """
    This function ...
    :param tilt:
    :param inclination:
    :return:
    """

    # Get the tilt angle and inclination in radians
    tilt_radian = tilt.to("radian").value
    i_radian = inclination.to("radian").value

    denominator = math.sqrt(math.sin(tilt_radian)**2 * math.sin(i_radian)**2 + math.cos(tilt_radian)**2)

    cos_pa = math.sin(tilt_radian) * math.sin(i_radian) / denominator
    sin_pa = math.cos(tilt_radian) / denominator

    pa_radian = math.atan2(sin_pa, cos_pa) * Unit("radian")

    return pa_radian.to("deg")

# -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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

# -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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

# -----------------------------------------------------------------
项目:specviz    作者:spacetelescope    | 项目源码 | 文件源码
def _make_quantity(data, unit):
    """
    Get a LogQuantity if the a LogUnit is used rather than a regular Quantity.

    Parameters
    ----------
    data: numpy.ndarray
        the data
    unit: ~astropy.unit.Unit or ~astropy.unit.LogUnit
        The data units

    Returns
    -------
    ~astropy.unit.Quantity or ~astropy.unit.LogQuantity
        depending on the unit type
    """
    if isinstance(unit, LogUnit):
        return LogQuantity(data, unit=unit)
    else:
        return Quantity(data, unit=unit)
项目:specviz    作者:spacetelescope    | 项目源码 | 文件源码
def _custom_unit_changed(self):

        if self.custom_units is None:
            return

        unit = self.custom_units.text()
        if unit == '':
            self.label_status.setText('')
        else:
            try:
                u.Unit(unit)
            except:
                self.label_status.setText('Invalid units')
                self.label_status.setStyleSheet('color: red')
            else:
                self.label_status.setText('Valid units')
                self.label_status.setStyleSheet('color: green')