How to use the astropy.units.Unit function in astropy

To help you get started, weā€™ve selected a few astropy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github radio-astro-tools / pvextractor / pvextractor / utils / wcs_utils.py View on Github external
def get_spectral_scale(wcs):

    # Code adapted from APLpy

    wcs = wcs.sub([WCSSUB_SPECTRAL])
    cdelt = np.matrix(wcs.wcs.get_cdelt())
    pc = np.matrix(wcs.wcs.get_pc())
    scale = np.array(cdelt * pc)

    return abs(scale[0,0]) * u.Unit(wcs.wcs.cunit[0])
github vaexio / vaex / packages / vaex-core / vaex / file / other.py View on Github external
def _try_unit(unit):
	try:
		unit = astropy.units.Unit(str(unit))
		if not isinstance(unit, astropy.units.UnrecognizedUnit):
			return unit
	except:
		#logger.exception("could not parse unit: %r", unit)
		pass
	try:
		unit_mangle = re.match(".*\[(.*)\]", str(unit)).groups()[0]
		unit = astropy.units.Unit(unit_mangle)
	except:
		pass#logger.exception("could not parse unit: %r", unit)
	if isinstance(unit, six.string_types):
		return None
	elif isinstance(unit, astropy.units.UnrecognizedUnit):
		return None
	else:
		return unit
github Stargrazer82301 / CAAPR / CAAPR_AstroMagic / PTS / pts / modeling / fitting / initialization.py View on Github external
"""

        # Inform the user
        log.info("Configuring the bulge component ...")

        # Like M31
        bulge_template = "BruzualCharlot"
        bulge_age = 12
        #bulge_metallicity = 0.02
        bulge_metallicity = 0.03

        # Get the flux density of the bulge
        fluxdensity = self.parameters.bulge.fluxdensity # In Jy

        # Convert the flux density into a spectral luminosity
        luminosity = fluxdensity_to_luminosity(fluxdensity, self.i1.pivotwavelength() * Unit("micron"), self.parameters.distance)

        # Get the spectral luminosity in solar units
        #luminosity = luminosity.to(self.sun_i1).value

        # Set the parameters of the bulge
        self.ski.set_stellar_component_geometry("Evolved stellar bulge", self.bulge)
        self.ski.set_stellar_component_sed("Evolved stellar bulge", bulge_template, bulge_age, bulge_metallicity) # SED
        #self.ski.set_stellar_component_luminosity("Evolved stellar bulge", luminosity, self.i1) # normalization by band
        self.ski.set_stellar_component_luminosity("Evolved stellar bulge", luminosity, self.i1.centerwavelength() * Unit("micron"))
github threeML / threeML / threeML / io / model_plot.py View on Github external
def _plot_component_mle(self, x_unit='keV', y_unit='erg/(cm2 keV s)', sources_to_plot=[], summed=False, x_min=10.,
                            x_max=1E4, num_ene=300, legend=True, fit_cmap=None, contour_cmap=None,
                            contour_alpha=0.6, lw=1., ls='-',
                            **kwargs):

        self._analysis.restore_best_fit()

        x_unit = u.Unit(x_unit)
        y_unit = u.Unit(y_unit)

        if fit_cmap is None:
            fit_cmap = plt.get_cmap(threeML_config['model plot']['fit cmap'])

        if contour_cmap is None:
            contour_cmap = plt.get_cmap(threeML_config['model plot']['contour cmap'])

        # Initialize plotting arrays
        y_values = []
        x_values = np.logspace(np.log10(x_min), np.log10(x_max), num_ene)

        if self._convert_to_frequency:

            # we are going to plot in frequency, but
            # the functions take energy.
github Stargrazer82301 / CAAPR / CAAPR_AstroMagic / PTS / pts / modeling / decomposition / decomposition.py View on Github external
parameter = key[:-1]

                value = table[key][index]

                if parameter == "PA":
                    value = Angle(value + 90., "deg")
                    if quadrant(value) == 2: value = value - Angle(180., "deg")
                    elif quadrant(value) == 3: value = value + Angle(180., "deg")

                    if value.to("deg").value > 180.: value = value - Angle(360., "deg")
                    elif value.to("deg").value < -180.: value = value + Angle(360., "deg")
                elif parameter == "mag":
                    parameter = "fluxdensity"
                    value = unitconversion.ab_to_jansky(value) * Unit("Jy")
                elif parameter == "mu0": value = value * Unit("mag/arcsec2")
                elif parameter == "hr":
                    value = value * Unit("arcsec")
                    value = (self.parameters.distance * value).to("pc", equivalencies=dimensionless_angles())
                elif parameter == "hz":
                    value = value * Unit("arcsec")
                    value = (self.parameters.distance * value).to("pc", equivalencies=dimensionless_angles())

                component_parameters[parameter] = value

            if functionname == "sersic":

                re = table["Re"][index] * Unit("arcsec")
                component_parameters["Re"] = (self.parameters.distance * re).to("pc", equivalencies=dimensionless_angles())
                component_parameters["n"] = table["n"][index]

            elif functionname == "ferrer2":
github gammapy / gammapy / gammapy / maps / counts_spectrum.py View on Github external
def __init__(self, energy_lo, energy_hi, data=None, unit="", region=None, wcs=None):
        e_edges = edges_from_lo_hi(energy_lo, energy_hi)
        self.energy = MapAxis.from_edges(e_edges, interp="log", name="energy")

        if data is None:
            data = np.zeros(self.energy.nbin)

        self.data = np.array(data)
        if not self.energy.nbin == self.data.size:
            raise ValueError("Incompatible data and energy axis size.")

        self.unit = u.Unit(unit)
        self.region = region
        self.wcs = wcs
github astropy / astropy / astropy / coordinates / sky_coordinate.py View on Github external
if 'unit' not in kwargs:
        units = [None, None, None]

    else:
        units = kwargs.pop('unit')

        if isinstance(units, six.string_types):
            units = [x.strip() for x in units.split(',')]
            # Allow for input like unit='deg' or unit='m'
            if len(units) == 1:
                units = [units[0], units[0], units[0]]
        elif isinstance(units, (Unit, IrreducibleUnit)):
            units = [units, units, units]

        try:
            units = [(Unit(x) if x else None) for x in units]
            units.extend(None for x in range(3 - len(units)))
            if len(units) > 3:
                raise ValueError()
        except:
            raise ValueError('Unit keyword must have one to three unit values as '
                             'tuple or comma-separated string')

    return units
github pyspeckit / pyspeckit / pyspeckit / spectrum / units.py View on Github external
    @classmethod
    def validate_unit(self, unit, bad_unit_response='raise'):
        try:
            if unit is None or unit == 'unknown':
                unit = u.dimensionless_unscaled
            if unit == 'angstroms': unit = 'angstrom'
            unit = u.Unit(unit)
        except ValueError:
            if bad_unit_response == "pixel":
                unit = "unknown"
            elif bad_unit_response == "raise":
                raise ValueError('Unit %s not recognized.' % unit)
            else:
                raise ValueError('Unit %s not recognized. Invalid bad_unit_response, valid options: [%s/%s]' 
                                % (unit, "raise", "pixel"))
        return unit
github astropy / photutils / photutils / extern / wcs_utils.py View on Github external
cls = SkyCoord

    if _has_distortion(wcs) and wcs.naxis != 2:
        raise ValueError("Can only handle WCS with distortions for 2-dimensional WCS")

    # Keep only the celestial part of the axes, also re-orders lon/lat
    wcs = wcs.sub([WCSSUB_CELESTIAL])

    if wcs.naxis != 2:
        raise ValueError("WCS should contain celestial component")

    # Check which frame the WCS uses
    frame = wcs_to_celestial_frame(wcs)

    # Check what unit the WCS gives
    lon_unit = u.Unit(wcs.wcs.cunit[0])
    lat_unit = u.Unit(wcs.wcs.cunit[1])

    # Convert pixel coordinates to celestial coordinates
    if mode == 'all':
        lon, lat = wcs.all_pix2world(xp, yp, origin)
    elif mode == 'wcs':
        lon, lat = wcs.wcs_pix2world(xp, yp, origin)
    else:
        raise ValueError("mode should be either 'all' or 'wcs'")

    # Add units to longitude/latitude
    lon = lon * lon_unit
    lat = lat * lat_unit

    # Create a SkyCoord-like object
    data = UnitSphericalRepresentation(lon=lon, lat=lat)
github astropy / astroquery / astroquery / lcogt / core.py View on Github external
def _parse_dimension(dim):
    if (isinstance(dim, u.Quantity) and
            dim.unit in u.deg.find_equivalent_units()):
        if dim.unit not in ['arcsec', 'arcmin', 'deg']:
            dim = dim.to(u.degree)
    # otherwise must be an Angle or be specified in hours...
    else:
        try:
            new_dim = coord.Angle(dim)
            dim = u.Quantity(new_dim.degree, u.Unit('degree'))
        except (u.UnitsError, coord.errors.UnitsError, AttributeError):
            raise u.UnitsError("Dimension not in proper units")
    return dim