pyphot package

Contents

pyphot package#

Pyphot - set of tools to compute synthetic photometry in a simple way, suitable for integration in larger projects.

This package is mostly organized around 2 main classes:

  • Filter that handles filter definitions and manipulations.

  • Library that handles a collection of filters in a few formats. This library class is derived into - an ASCII file reader Ascii_Library, - and a single HDF file reader HDF_Library.

In addition,

Subpackages#

Submodules#

pyphot.config module#

set_units_backend(backend)[source]#

Set the units backend to use throughout pyphot.

Parameters:

backend (str) – The name of the units backend to use.

:param see pyphot.unit_adapters:

set_vega_flavor(flavor)[source]#

Set the vega flavor to use throughout pyphot.

Parameters:

flavor (str) – The name of the vega flavor to use.

:param see pyphot.vega:

pyphot.constants module#

A module containing fundamental constants used in photometry calculations.

This module provides access to fundamental constants used in photometry calculations while ensuring consistency with the units defined in the config module. (not all unit packages provide these constants)

constants = Constants()#

Constants used in photometry calculations.

This class provides access to fundamental constants used in photometry calculations while ensuring consistency with the units defined in the config module.

pyphot.helpers module#

deprecated(message)[source]#

Deprecated warning decorator

progress_enumerate(it, *args, **kwargs)[source]#

Enumerate over a sequence with progression if requested

Parameter#

show_progress: bool

set to show progress

pyphot.legacy module#

Defines legacy aliases

UnitAsciiLibrary#

alias of Ascii_Library

UnitFilter#

alias of Filter

UnitHDFLibrary#

alias of HDF_Library

UnitLibrary#

alias of Library

pyphot.libraries module#

Collections of Filters

class Ascii_Library[source]#

Bases: Library

Interface one or multiple directory or many files as a filter Library

>>> lib = Ascii_Library(['ground', 'hst', 'myfilter.csv'])

Construct the library

add_filters(filter_object, fmt='%.6f', **kwargs)[source]#

Add a filter to the library permanently

Parameters:

filter_object (Filter object) – filter to add

get_library_content()[source]#

get the content of the library

Return type:

List[str]

load_all_filters(*, interp=True, lamb=None)[source]#

load all filters from the library

Parameters:
  • interp (bool) – reinterpolate the filters over given lambda points

  • lamb (ndarray[float, ndim=1]) – desired wavelength definition of the filter

Returns:

filters – list of filter objects

Return type:

list[filter]

load_filters(names, *, interp=True, lamb=None)[source]#

load a limited set of filters

Parameters:
  • names (list[str]) – normalized names according to filtersLib

  • interp (bool) – reinterpolate the filters over given lambda points

  • lamb (ndarray[float, ndim=1]) – desired wavelength definition of the filter

  • filterLib (path) – path to the filter library hd5 file

Returns:

filters – list of filter objects

Return type:

list[filter]

class HDF_Library[source]#

Bases: Library

Library for storage based on HDF files

__init__(source=None, mode='r')[source]#
Parameters:
  • source (str | None)

  • mode (Literal['r', 'w', 'a', 'r+'])

add_filter(f, **kwargs)[source]#

Add a filter to the library permanently

Parameters:

f (Filter object) – filter to add

get_library_content()[source]#

get the content of the library

Return type:

List[str]

hdf: File | None#

Source file stream of the library

load_all_filters(*, interp=True, lamb=None)[source]#

load all filters from the library

Parameters:
  • interp (bool) – reinterpolate the filters over given lambda points

  • lamb (ndarray[float, ndim=1]) – desired wavelength definition of the filter

Returns:

filters – list of filter objects

Return type:

list[filter]

load_filters(names, *, interp=True, lamb=None)[source]#

load a limited set of filters

Parameters:
  • names (list[str]) – normalized names according to filtersLib

  • interp (bool) – reinterpolate the filters over given lambda points

  • lamb (ndarray[float, ndim=1]) – desired wavelength definition of the filter

  • filterLib (path) – path to the filter library hd5 file

Returns:

filters – list of filter objects

Return type:

list[filter]

mode: Literal['r', 'w', 'a', 'r+'] = 'r'#

Mode of the library (file). It can be one of the following:

  • ‘r’: Read-only; no data can be modified.

  • ‘w’: Write; a new file is created (an existing file with the same name would be deleted).

  • ‘a’: Append; an existing file is opened for reading and writing, and if the file does not exist it is created.

  • ‘r+’: It is similar to ‘a’, but the file must already exist.

class Library[source]#

Bases: object

Common grounds for filter libraries

Construct the library

__init__(source=None, *args, **kwargs)[source]#

Construct the library

Parameters:

source (str | None)

add_filter(f)[source]#

add a filter to the library

Parameters:

f (Filter)

property content: List[str]#

Get the content list

find(name, case_sensitive=True)[source]#

Search for a filter in the library

Parameters:

name (str)

Return type:

List[str]

classmethod from_ascii(filename, **kwargs)[source]#

Read in an ASCII library

Return type:

Ascii_Library

classmethod from_hd5(filename, **kwargs)[source]#
Return type:

HDF_Library

get_library_content()[source]#

get the content of the library

Return type:

List[str]

load_all_filters(*, interp=True, lamb=None)[source]#

load all filters from the library

Parameters:
  • interp (bool) – reinterpolate the filters over given lambda points

  • lamb (ndarray[float, ndim=1]) – desired wavelength definition of the filter

Returns:

filters – list of filter objects

Return type:

list[filter]

source: str | None#

Source of the library

to_csv(directory='./', progress=True, **kwargs)[source]#

Export each filter into a csv file with its own name

Parameters:
  • directory (str) – directory to write into

  • progress (bool) – show progress if set

to_hdf(fname='filters.hd5', progress=True, **kwargs)[source]#

Export each filter into a csv file with its own name

Parameters:
  • directory (str) – directory to write into

  • progress (bool) – show progress if set

get_library(fname=None, **kwargs)[source]#

Finds the appropriate class to load the library

Parameters:

fname (str | None)

pyphot.licks module#

This module provides function to compute spectral indices

The Lick system of spectral line indices is one of the most commonly used methods of determining ages and metallicities of unresolved (integrated light) stellar populations.

The calibration of the Lick / IDS system is complicated because the original Lick spectra were not flux calibrated, so there are usually systematic effects due to differences in continuum shape. Proper calibration involves observing many of the original Lick/IDS standard stars and deriving offsets to the standard system.

In Vazdekis et al. (2010), they propose a new Line Index System, hereafter LIS, with three new spectral resolutions at which to measure the Lick indices. Note that this new system should not be restricted to the Lick set of indices in a flux calibrated system. In fact, LIS can be used for any index in the literature (e.g., for the Rose (1984) indices), including newly defined indices (e.g., Cervantes & Vazdekis 2009).

Indices are defined through LickIndex

The LIS system is defined for 3 different spectral resolutions which are best suited for the following astrophysical cases:

  • LIS-5.0AA: globular clusters

  • LIS-8.4AA: low and intermediate-mass galaxies

  • LIS-14.0AA: massive galaxies

reduce_resolution() adapts the resolution of the spectra to match the lick definitions.

Conversions to transform the data from the Lick/IDS system to LIS can be found in Johansson, Thomas & Maraston (2010), which provides a discussion of indices and the information content of them.

A collection of many common indices is available in the internal library pyphot.config.__default_lick_lib__ licks.dat and accessible through LickLibrary.

See also

Extention to Lick indices contains a lot more information and literature references about the Lick/IDS system.

class LickDefinition[source]#

Bases: object

Definition of a Lick Index

expecting ‘blue’, ‘red’, ‘band’, and ‘unit’ definitions - blue and red are used to continuum normalize the spectra - band covers the index itself. - index_unit gives the index measurement type as either magnitude (mag) or equivalent width (ew)

Consistency is checked such that all fields are set with consistent units (priority to band field) wavelength_unit is also associated

Build a LickDefinition from values

Parameters:
  • band (QuantityType or tuple of float) – Bandpass of the lick

  • blue (QuantityType or tuple of float) – Blue limit of the lick

  • red (QuantityType or tuple of float) – Red limit of the lick

  • index_unit (Literal["mag", "ew"], optional) – Unit of the index, by default “mag”

  • wavelength_unit (Optional[str], optional) – Unit of the wavelength, by default None

Returns:

The LickDefinition object

Return type:

LickDefinition

__init__(*, band, blue, red, index_unit='mag', wavelength_unit=None)[source]#

Build a LickDefinition from values

Parameters:
  • band (QuantityType or tuple of float) – Bandpass of the lick

  • blue (QuantityType or tuple of float) – Blue limit of the lick

  • red (QuantityType or tuple of float) – Red limit of the lick

  • index_unit (Literal["mag", "ew"], optional) – Unit of the index, by default “mag”

  • wavelength_unit (Optional[str], optional) – Unit of the wavelength, by default None

Returns:

The LickDefinition object

Return type:

LickDefinition

band: astropy_adapter.ap_Quantity | pint_adapter.pint_Quantity | ezunits_adapter.ez_Quantity = <dataclasses._MISSING_TYPE object>#
blue: astropy_adapter.ap_Quantity | pint_adapter.pint_Quantity | ezunits_adapter.ez_Quantity = <dataclasses._MISSING_TYPE object>#
index_unit: Literal['mag', 'ew'] = 'mag'#
red: astropy_adapter.ap_Quantity | pint_adapter.pint_Quantity | ezunits_adapter.ez_Quantity = <dataclasses._MISSING_TYPE object>#
wavelength_unit: str | None = None#
class LickIndex[source]#

Bases: object

Define a Lick Index similarily to a Filter object

Constructor

Parameters:
  • name (str) – name of the index

  • lick (dict or LickDefinition) – expecting ‘blue’, ‘red’, ‘band’, and ‘unit’ definitions blue and red are used to continuum normalize the spectra band covers the index itself. unit gives the index measurement units, either magnitudes (mag) or equivalent width (ew)

  • unit (str) – wavelength unit of the intervals if not provided in the lick definition

__init__(name, lick, unit='AA')[source]#

Constructor

Parameters:
  • name (str) – name of the index

  • lick (dict or LickDefinition) – expecting ‘blue’, ‘red’, ‘band’, and ‘unit’ definitions blue and red are used to continuum normalize the spectra band covers the index itself. unit gives the index measurement units, either magnitudes (mag) or equivalent width (ew)

  • unit (str) – wavelength unit of the intervals if not provided in the lick definition

property band: astropy_adapter.ap_Quantity | pint_adapter.pint_Quantity | ezunits_adapter.ez_Quantity#

Unitwise band definition

property blue: astropy_adapter.ap_Quantity | pint_adapter.pint_Quantity | ezunits_adapter.ez_Quantity#

Unitwise band definition

classmethod continuum_normalized_region_around_line(wi, fi, blue, red, band=None, degree=1)[source]#

cut out and normalize flux around a line

Parameters:
  • wi (ndarray (nw, )) – array of wavelengths in AA

  • fi (ndarray (N, nw)) – array of flux values for different spectra in the series

  • blue (tuple(2)) – selection for blue continuum estimate

  • red (tuple(2)) – selection for red continuum estimate

  • band (tuple(2), optional) – select region in this band only. default is band = (min(blue), max(red))

  • degree (int) – degree of the polynomial fit to the continuum

Returns:

  • wnew (ndarray (nw1, )) – wavelength of the selection in AA

  • f (ndarray (N, len(wnew))) – normalized flux in the selection region

Example

# indice of CaII
# wavelength are always supposed in AA
w, f = region_around_line(
    wavelength, flux, [3925, 3930],[3938, 3945]]
    )
get(wave, flux, **kwargs)[source]#

compute spectral index after continuum subtraction

Important

Decorated function get() with default units.

Parameters Units:

  • wave : AA

  • flux : flam

Parameters:
  • w (ndarray (nw, )) – array of wavelengths in AA

  • flux (ndarray (N, nw)) – array of flux values for different spectra in the series

  • degree (int (default 1)) – degree of the polynomial fit to the continuum

  • nocheck (bool) – set to silently pass on spectral domain mismatch. otherwise raises an error when index is not covered

  • wave (astropy_adapter.ap_Quantity | pint_adapter.pint_Quantity | ezunits_adapter.ez_Quantity)

Returns:

ew – equivalent width or magnitude array

Return type:

ndarray (N,)

Raises:

ValueError – when the spectral coverage wave does not cover the index range:

property index_unit: Literal['mag', 'ew']#

Index definition type

info()[source]#

display information about the current Index

name: str#

Name of the index

property red: astropy_adapter.ap_Quantity | pint_adapter.pint_Quantity | ezunits_adapter.ez_Quantity#

Unitwise band definition

to_dict()[source]#

return a dictionary of the current index

Return type:

dict

property wavelength_unit: str#

Wavelength unit of the intervals

class LickLibrary[source]#

Bases: object

Collection of Lick indices

See also

This library behaves like the photometric one pyphot.libraries.Library

Initialize the LickLibrary object.

Parameters:
  • fname (str, optional) – ascii file containing the indices’ definitions

  • comment (str, optional) – character indicating comment in the file

__init__(fname=None, comment='#')[source]#

Initialize the LickLibrary object.

Parameters:
  • fname (str, optional) – ascii file containing the indices’ definitions

  • comment (str, optional) – character indicating comment in the file

property content: List[str]#

Get the content of the library

property description: List[str]#

any comment in the input file

find(name, case_sensitive=True)[source]#

Find indices in the library

Parameters:
  • name (str) – Name of the filter to find

  • case_sensitive (bool, optional) – Whether to perform a case-sensitive search, by default True

Returns:

List of indices that match the given name

Return type:

List[str]

get_library_content()[source]#
Return type:

List[str]

source: str#

Source of the library

reduce_resolution(wi, fi, fwhm0=0.55, sigma_floor=0.2, warn=True)[source]#

Adapt the resolution of the spectra to match the lick definitions

Lick definitions have different resolution elements as function of wavelength. These definition are hard-coded in this function

Parameters:
  • wi (ndarray (n, ) with or without units) – wavelength definition

  • fi (ndarray (nspec, n) or (n, ) with or without units) – spectra to convert

  • fwhm0 (float or QuantityType) – initial broadening in the spectra fi

  • sigma_floor (float or QuantityType) – minimal dispersion to consider

  • warn (bool) – Warn for unit assumptions

Returns:

flux_red – reduced spectra

Return type:

ndarray (nspec, n) or (n, )

pyphot.pbar module#

Simple progressbar#

This package implement a unique progress bar class that can be used to decorate an iterator, a function or even standalone.

The format of the meter is flexible and can display along with the progress meter, the running time, an eta, and the rate of the iterations.

An example is::

description [———-] k/n 10% [time: 00:00:00, eta: 00:00:00, 2.7 iters/sec]

class Pbar[source]#

Bases: object

make a progress string in a shape of:

[----------] k/n  10% [time: 00:00:00, eta: 00:00:00, 2.7 iters/sec]
time#

if set, add the runtime information

Type:

bool, optional (default: True)

eta#

if set, add an estimated time to completion

Type:

bool, optional (default: True)

rate#

if set, add the rate information

Type:

bool, optional (default: True)

length#

number of characters showing the progress meter itself if None, the meter will adapt to the buffer width

TODO: make it variable with the buffer length

Type:

int, optional (default: None)

keep#

If not set, deletes its traces from screen after completion

Type:

bool, optional (default: True)

file#

the buffer to write into

Type:

buffer

mininterval#

minimum time in seconds between two updates of the meter

Type:

float (default: 0.5)

miniters#

minimum iteration number between two updates of the meter

Type:

int, optional (default: 1)

units#

unit of the iteration

Type:

str, optional (default: ‘iters’)

__init__(maxval=None, desc=None, time=True, eta=True, rate=True, length=None, file=None, keep=True, mininterval=0.5, miniters=1, units='iters', **kwargs)[source]#
build_str_meter(n, total, elapsed)[source]#

make a progress string in a shape of:

[----------] k/n  10% [time: 00:00:00, eta: 00:00:00, 2.7 iters/sec]
Parameters:
  • n (int) – number of finished iterations

  • total (int) – total number of iterations, or None

  • elapsed (int) – number of seconds passed since start

Returns:

txt – string representing the meter

Return type:

str

decorator(func)[source]#

Provide a function decorator allowing for counting calls and rates

static format_interval(t)[source]#

make a human readable time interval decomposed into days, hours, minutes and seconds

Parameters:

t (int) – interval in seconds

Returns:

txt – string representing the interval (format: <days>d <hrs>:<min>:<sec>)

Return type:

str

handle_resize(signum, frame)[source]#
iterover(iterable, total=None)[source]#

Get an iterable object, and return an iterator which acts exactly like the iterable, but prints a progress meter and updates it every time a value is requested.

Parameters:
  • iterable (generator or iterable object) – object to iter over.

  • total (int, optional) – the number of iterations is assumed to be the length of the iterator. But sometimes the iterable has no associated length or its length is not the actual number of future iterations. In this case, total can be set to define the number of iterations.

Returns:

gen – pass the values from the initial iterator

Return type:

generator

print_status(s)[source]#

print a status s on the last file line and clean the rest of the line

Parameters:

s (str) – message to write

update(n, desc=None, total=None)[source]#

Kept for backward compatibility and the decorator feature

Parameters:
  • n (int) – force iteration number n

  • desc (str) – update description string

  • total (int) – update the total number of iterations

pyphot.phot module#

Photometric package#

This module defines the Filter class.

Note

integrations are done using trapezoid() Why not Simpsons? Simpsons principle is to take sequence of 3 points to make a quadratic interpolation. Which in the end, when filters have sharp edges, the error due to this “interpolation” are extremely large in comparison to the uncertainties induced by trapeze integration.

class Filter[source]#

Bases: object

Evolution of Filter that makes sure the input spectra and output fluxes have units to avoid mis-interpretation.

Note

the usual (non SI) units of flux definitions:

  • flam = erg/s/cm**2/AA

  • fnu = erg/s/cm**2/Hz

  • photflam = photon/s/cm**2/AA

  • photnu = photon/s/cm**2/Hz

Define a filter by its name, wavelength and transmission The type of detector (energy or photon counter) can be specified for adapting calculations. (default: photon)

Constructor

Parameters:
  • wavelength (ndarray | QuantityType) – wavelength sequence defining the filter transmission curve

  • transmit (ndarray) – transmission curve of the filter

  • name (str) – name of the filter

  • dtype (str) – detector type, either “photon” or “energy” counter

  • unit (str) – wavelength units

  • vega (str) – Vega flavor to use for calculations, default is ‘default’ (see pyphot.vega.Vega for details)

property AB_zero_Jy: astropy_adapter.ap_Quantity | pint_adapter.pint_Quantity | ezunits_adapter.ez_Quantity#

AB flux zero point in Jansky (Jy)

\[{f_{Jy}} = \frac{10^5}{10^{-8}c} {\lambda_p^2} {f_\lambda}\]
property AB_zero_flux: astropy_adapter.ap_Quantity | pint_adapter.pint_Quantity | ezunits_adapter.ez_Quantity#

AB flux zero point in erg/s/cm2/AA

property AB_zero_mag: float#

AB magnitude zero point

\[\begin{split}\begin{align} \mathrm{ABmag} &= -2.5 \log_{10}(f_{\nu}) - 48.60 \\ &= -2.5 \log_{10}(f_{\lambda}) - 2.5 \log_{10}(\lambda_{pivot}^2 / c) - 48.60 \\ &= -2.5 \log_{10}(f_{\lambda}) - zpts \end{align}\end{split}\]
property ST_zero_Jy: astropy_adapter.ap_Quantity | pint_adapter.pint_Quantity | ezunits_adapter.ez_Quantity#

ST flux zero point in Jansky (Jy)

property ST_zero_flux: astropy_adapter.ap_Quantity | pint_adapter.pint_Quantity | ezunits_adapter.ez_Quantity#

ST flux zero point in erg/s/cm2/AA

property ST_zero_mag: float#

ST magnitude zero point STmag = -2.5 * log10(f_lamb) -21.1

property Vega_zero_Jy#

Vega flux zero point in Jansky (Jy)

property Vega_zero_flux#

Vega flux zero point in flam (erg/s/cm2/AA)

property Vega_zero_mag#

vega magnitude zero point

\[\begin{split}\begin{align} \mathrm{mag} &= -2.5 \log_{10}(f_\lambda / f_\mathrm{Vega}) \\ &= -2.5 \log_{10}(f_\lambda) - \mathrm{zeropoint} \end{align}\end{split}\]
property Vega_zero_photons: astropy_adapter.ap_Quantity | pint_adapter.pint_Quantity | ezunits_adapter.ez_Quantity#

Vega number of photons per wavelength unit

__init__(wavelength, transmit, *, name='', dtype='photon', unit=None, vega=None)[source]#

Constructor

Parameters:
  • wavelength (ndarray | QuantityType) – wavelength sequence defining the filter transmission curve

  • transmit (ndarray) – transmission curve of the filter

  • name (str) – name of the filter

  • dtype (str) – detector type, either “photon” or “energy” counter

  • unit (str) – wavelength units

  • vega (str) – Vega flavor to use for calculations, default is ‘default’ (see pyphot.vega.Vega for details)

applyTo(slamb, sflux)#

Apply filter transmission to a spectrum (with reinterpolation of the filter)

Parameters:
  • slamb (ndarray) – spectrum wavelength definition domain

  • sflux (ndarray) – associated flux

Returns:

flux – new spectrum values accounting for the filter

Return type:

float

apply_transmission(slamb, sflux)[source]#

Apply filter transmission to a spectrum (with reinterpolation of the filter)

Parameters:
  • slamb (ndarray) – spectrum wavelength definition domain

  • sflux (ndarray) – associated flux

Returns:

flux – new spectrum values accounting for the filter

Return type:

float

property cl: astropy_adapter.ap_Quantity | pint_adapter.pint_Quantity | ezunits_adapter.ez_Quantity#

Unitwise Central wavelength

\[\lambda_{cl} = \frac{\int \lambda T(\lambda) d\lambda}{\int T(\lambda) d\lambda}\]
dtype: Literal['photon', 'energy']#

Type of detector (photon or energy)

classmethod from_ascii(fname, *, dtype='csv', **kwargs)[source]#

Load a Filter from an ASCII file

Parameters:
  • fname (str) – path to the ASCII file

  • dtype (str, optional) – type of the ASCII file (e.g. ‘csv’)

  • kwargs (dict, optional) – additional keyword arguments to pass to the ASCII reader or to the Filter constructor

Returns:

filter – Filter object loaded from the ASCII file

Return type:

Filter

property fwhm: astropy_adapter.ap_Quantity | pint_adapter.pint_Quantity | ezunits_adapter.ez_Quantity#

the difference between the two wavelengths for which filter transmission is half maximum

..note::

This calculation is not exact but rounded to the nearest passband data points

getFlux(slamb, sflux, axis=-1)#

Get integrated flux through the filter

Important

Decorated function get_flux() with default units.

Parameters Units:

  • slamb : AA

  • sflux : flam

Return Units

  • output: erg*s**-1*cm**-2*AA**-1

Parameters:
  • slamb (Union[npt.NDArray[np.floating], QuantityType]) – spectrum wavelength definition domain

  • sflux (Union[npt.NDArray[np.floating], QuantityType]) – associated flux or array of many fluxes

  • axis (int, optional) – axis along which to integrate the flux

Returns:

flux – Energy of the spectrum within the filter

Return type:

float

get_Nphotons(slamb, sflux, axis=-1)[source]#

Get integrated number of photons through the filter

Important

Decorated function get_Nphotons() with default units.

Parameters Units:

  • slamb : AA

  • sflux : flam

Return Units

  • output: photon*s**-1*cm**-2*AA**-1

equivalent to self.get_flux(…) * leff / h / c

Parameters:
  • slamb (Union[npt.NDArray[np.floating], QuantityType]) – spectrum wavelength definition domain

  • sflux (Union[npt.NDArray[np.floating], QuantityType]) – associated flux or array of many fluxes

  • axis (int, optional) – axis along which to integrate the flux

Returns:

Nphotons – Integrated number of photons through the filter in photons / cm^2 / s / A

Return type:

QuantityType

get_flux(slamb, sflux, axis=-1)[source]#

Get integrated flux through the filter

Important

Decorated function get_flux() with default units.

Parameters Units:

  • slamb : AA

  • sflux : flam

Return Units

  • output: erg*s**-1*cm**-2*AA**-1

Parameters:
  • slamb (Union[npt.NDArray[np.floating], QuantityType]) – spectrum wavelength definition domain

  • sflux (Union[npt.NDArray[np.floating], QuantityType]) – associated flux or array of many fluxes

  • axis (int, optional) – axis along which to integrate the flux

Returns:

flux – Energy of the spectrum within the filter

Return type:

float

info(show_zeropoints=True)[source]#

print information about the current filter

Parameters:

show_zeropoints (bool)

property leff: astropy_adapter.ap_Quantity | pint_adapter.pint_Quantity | ezunits_adapter.ez_Quantity#

Unitwise Effective wavelength leff = int (lamb * T * Vega dlamb) / int(T * Vega dlamb)

property lmax: astropy_adapter.ap_Quantity | pint_adapter.pint_Quantity | ezunits_adapter.ez_Quantity#

Calculated as the last value with a transmission at least 1% of maximum transmission

property lmin: astropy_adapter.ap_Quantity | pint_adapter.pint_Quantity | ezunits_adapter.ez_Quantity#

Calculate das the first value with a transmission at least 1% of maximum transmission

property lphot: astropy_adapter.ap_Quantity | pint_adapter.pint_Quantity | ezunits_adapter.ez_Quantity#

Photon distribution based effective wavelength. Defined as

\[lphot = \int \lambda^2 T \cdot Vega(\lambda) d\lambda / \int \lambda T \cdot Vega(\lambda) d\lambda\]

which we calculate as

lphot = get_flux(lamb * vega) / get_flux(vega)

property lpivot: astropy_adapter.ap_Quantity | pint_adapter.pint_Quantity | ezunits_adapter.ez_Quantity#

Unitwise wavelength definition

the calculation depends on the type (dtype) of the filter.

for photon filters:

\[\lambda_{pivot}^2 = \frac{\int \lambda T(\lambda) d\lambda}{\int T(\lambda) d\lambda / \lambda}\]

for energy filters:

\[\lambda_{pivot}^2 = \frac{\int T(\lambda) d\lambda}{\int T(\lambda) d\lambda / \lambda^2}\]
classmethod make_integration_filter(lmin, lmax, name='', dtype='photon', unit=None, **kwargs)[source]#

Generate an heavyside filter between lmin and lmax

Parameters:
  • lmin (float or QuantityType) – Minimum wavelength of the filter

  • lmax (float or QuantityType) – Maximum wavelength of the filter

  • name (str, optional) – Name of the filter

  • dtype (Literal["photon", "energy"], optional) – Type of the filter

  • unit (Optional[str], optional) – Unit of the filter

  • **kwargs – Additional keyword arguments

Returns:

filter – Filter object

Return type:

Filter

name: str#

Name of the filter

norm: float#

Normalization factor

reinterp(lamb)[source]#

reinterpolate filter onto a different wavelength definition

Parameters:

lamb (QuantityType | npt.NDArray[np.floating]) – Wavelength to reinterpolate onto If no unit is provided, the filter’s wavelength unit is assumed.

Returns:

Filter reinterpolated onto the new wavelength definition

Return type:

Filter

set_dtype(dtype)[source]#

Set the detector type (photon or energy)

Parameters:

dtype (Literal['photon', 'energy'])

set_vega_flavor(vega, reset=True)[source]#

Set the Vega flavor to use for calculations.

Parameters:
  • vega (str | None)

  • reset (bool)

set_wavelength_unit(unit)[source]#

Set the wavelength units

Parameters:

unit (str | None)

to_Table(**kwargs)[source]#

Export filter to a SimpleTable object

Parameters:
  • fname (str) – filename

  • parameters (Uses SimpleTable)

Return type:

DataFrame

to_dict()[source]#

Return a dictionary of the filter

Return type:

dict

transmit: ndarray[tuple[Any, ...], dtype[floating]]#

Transmission/throughput curve

property wavelength: astropy_adapter.ap_Quantity | pint_adapter.pint_Quantity | ezunits_adapter.ez_Quantity#

Unitwise wavelength definition

wavelength_unit: str#

Wavelength unit

property width: astropy_adapter.ap_Quantity | pint_adapter.pint_Quantity | ezunits_adapter.ez_Quantity#

Effective width Equivalent to the horizontal size of a rectangle with height equal to maximum transmission and with the same area that the one covered by the filter transmission curve.

\[W = \int_{\lambda_{min}}^{\lambda_{max}} T(\lambda) d\lambda / \max(T)\]
write_to(fname, **kwargs)[source]#

Export filter to a file

Parameters:
  • fname (str) – filename

  • parameters (Uses SimpleTable.write)

pyphot.sun module#

Handle the Sun Spectrum

class Sun[source]#

Bases: object

Class that handles the Sun’s spectrum and references.

Observed solar spectrum comes from: ftp://ftp.stsci.edu/cdbs/current_calspec/sun_reference_stis_001.fits

and theoretical spectrum comes from: ftp://ftp.stsci.edu/cdbs/grid/k93models/standards/sun_kurucz93.fits

The theoretical spectrum is scaled to match the observed spectrum from 1.5 - 2.5 microns, and then it is used where the observed spectrum ends. The theoretical model of the Sun from Kurucz’93 atlas using the following parameters when the Sun is at 1 au.

log(Z)

Teff

log_g

V_{Johnson}

+0.0

+5777

+4.44

-26.75

Constructor

__init__(*, source=None, distance=None, flavor='theoretical')[source]#

Constructor

Parameters:
  • source (str | None)

  • distance (astropy_adapter.ap_Quantity | pint_adapter.pint_Quantity | ezunits_adapter.ez_Quantity | None)

  • flavor (Literal['observed', 'theoretical'])

property data: DataFrame#

Return the data extracted from the source

distance: astropy_adapter.ap_Quantity | pint_adapter.pint_Quantity | ezunits_adapter.ez_Quantity#

Distance to the instance of the Sun

distance_conversion: float#

Conversion factor to convert distance to the default_distance (usually au)

flavor: Literal['observed', 'theoretical'] | None#

Flavor of the Sun spectrum

property flux: astropy_adapter.ap_Quantity | pint_adapter.pint_Quantity | ezunits_adapter.ez_Quantity#
units: Tuple[str, str] | None#

Units of the data (wavelength, flux)

property wavelength: astropy_adapter.ap_Quantity | pint_adapter.pint_Quantity | ezunits_adapter.ez_Quantity#

pyphot.svo module#

Link to the SVO filter profile service

See also their website http://svo2.cab.inta-csic.es/theory/fps/

Important

If your research benefits from the use of the SVO Filter Profile Service, include the following acknowledgement in your publication:

This research has made use of the SVO Filter Profile Service(http://svo2.cab.inta-csic.es/theory/fps/) supported from the Spanish MINECO through grant AYA2017-84089 and described in Rodrigo et al, (2012) and Rodrigo et al. (2020)

with references:

Example

>>> lst = "2MASS/2MASS.J 2MASS/2MASS.H 2MASS/2MASS.Ks HST/ACS_WFC.F475W HST/ACS_WFC.F814W".split()
    objects = [get_pyphot_filter(k) for k in lst]

Note

This module uses pyphot.io.votable to parse the SVO filter profile service response. (i.e. it does not depend on Astropy)

get_pyphot_filter(identifier)[source]#

Query the SVO filter profile service and return the filter object

Parameters:

identifier (str) – SVO identifier of the filter profile e.g., 2MASS/2MASS.Ks HST/ACS_WFC.F475W The identifier is the first column on the webpage of the facilities.

Returns:

filter – Filter object

Return type:

Filter

pyphot.typing module#

Module containing type aliases for pyphot.

pyphot.uncertain module#

Implements what could be a filter with uncertainties

This is not a complete implementation yet. It is basically a Monte-Carlo simulation of a filter with uncertainties.

class UncertainFilter[source]#

Bases: Filter

Implements what could be a filter with uncertainties

wavelength#

wavelength sequence defining the filter transmission curve

Type:

ndarray

mean#

mean passband transmission

Type:

Filter

samples#

samples from the uncertain passband transmission model

Type:

sequence(Filter)

name#

name of the passband

Type:

string

dtype#

detector type, either “photon” or “energy” counter

Type:

str

unit#

wavelength units

Type:

str

vega#

Vega flavor to use for calculations, default is ‘default’ (see pyphot.vega.Vega for details)

Type:

str

Constructor

__init__(wavelength, mean_transmit, sample_transmit, *, name='', dtype='photon', unit=None, vega=None)[source]#

Constructor

Parameters:
  • wavelength (ndarray[tuple[Any, ...], dtype[floating]] | astropy_adapter.ap_Quantity | pint_adapter.pint_Quantity | ezunits_adapter.ez_Quantity)

  • mean_transmit (ndarray[tuple[Any, ...], dtype[floating]])

  • sample_transmit (Sequence[ndarray[tuple[Any, ...], dtype[floating]]])

  • name (str)

  • dtype (Literal['photon', 'energy'])

  • unit (str | None)

  • vega (str | None)

dtype: Literal['photon', 'energy']#

Type of detector (photon or energy)

classmethod from_gp_model(model, xprime=None, n_samples=10, **kwargs)[source]#

Generate a filter object from a sklearn GP model

Parameters:
  • model (sklearn.gaussian_process.GaussianProcessRegressor) – model of the passband

  • xprime (ndarray) – wavelength to express the model in addition to the training points

  • n_samples (int) – number of samples to generate from the model.

  • kwargs (dict) – UncertainFilter keywords

Return type:

UncertainFilter

info(show_zeropoints=True)[source]#

display information about the current filter

model_: Any | None = None#
name: str#

Name of the filter

norm: float#

Normalization factor

reinterp(lamb)[source]#

reinterpolate filter onto a different wavelength definition

Parameters:

lamb (QuantityType | npt.NDArray[np.floating]) – Wavelength to reinterpolate onto If no unit is provided, the filter’s wavelength unit is assumed.

Returns:

Filter reinterpolated onto the new wavelength definition

Return type:

UncertainFilter

samples_: Sequence[Filter]#
transmit: ndarray[tuple[Any, ...], dtype[floating]]#

Transmission/throughput curve

property transmit_mean_and_samples#

Transmission curves

wavelength_unit: str#

Wavelength unit

pyphot.vega module#

Handle vega spec/mags/fluxes manipulations

Works with both ascii and hd5 files for back-compatibility

Vega.wavelength and Vega.flux have now units!

class Vega[source]#

Bases: object

Class that handles vega spectrum and references. This class know where to find the Vega synthetic spectrum in order to compute fluxes and magnitudes in given filters

An instance can be used as a context manager as:

>>> filters = ['HST_WFC3_F275W', 'HST_WFC3_F336W', 'HST_WFC3_F475W',                   'HST_WFC3_F814W', 'HST_WFC3_F110W', 'HST_WFC3_F160W']
    with Vega(flavor='stis_011') as v:
        vega_f, vega_mag, flamb = v.getSed(filters)
    print(vega_f, vega_mag, flamb)

See also

See the documentation Details on the internal Vega reference spectra for more information about the different flavors of Vega spectra and associated references.

Constructor

Parameters:
  • source (str, optional) – Source of the Vega spectrum. If not provided, the default flavor is used.

  • flavor (str, optional) – Flavor of the Vega spectrum. If not provided, the default flavor is used.

__init__(*, source=None, flavor='legacy')[source]#

Constructor

Parameters:
  • source (str, optional) – Source of the Vega spectrum. If not provided, the default flavor is used.

  • flavor (str, optional) – Flavor of the Vega spectrum. If not provided, the default flavor is used.

property data: DataFrame#
property flux: astropy_adapter.ap_Quantity | pint_adapter.pint_Quantity | ezunits_adapter.ez_Quantity#
units: Tuple[str, str] | None = None#

Units of the data (wavelength, flux)

property wavelength: astropy_adapter.ap_Quantity | pint_adapter.pint_Quantity | ezunits_adapter.ez_Quantity#

pyphot.version module#

Expose the version of pyphot the package metadata

>>> import pyphot
>>> pyphot.__VERSION__
'2.0.0'