Reference/API

pysynphot.binning

Utilities related to wavelength bin calculations.

pysynphot.binning.calculate_bin_centers(edges)

Calculate the centers of wavelengths bins given their edges.

Parameters:edges (array_like) – Sequence of bin edges. Must be 1D and have at least two values.
Returns:centers – Array of bin centers. Will be 1D and have one less value than edges.
Return type:ndarray
pysynphot.binning.calculate_bin_edges(centers)

Calculate the edges of wavelength bins given the centers.

The algorithm calculates bin edges as the midpoints between bin centers and treats the first and last bins as symmetric about their centers.

Parameters:centers (array_like) – Sequence of bin centers. Must be 1D and have at least two values.
Returns:edges – Array of bin edges. Will be 1D and have one more value than centers.
Return type:ndarray
pysynphot.binning.calculate_bin_widths(edges)

Calculate the widths of wavelengths bins given their edges.

Parameters:edges (array_like) – Sequence of bin edges. Must be 1D and have at least two values.
Returns:widths – Array of bin widths. Will be 1D and have one less value than edges.
Return type:ndarray

pysynphot.Cache

This module is a container for IO-intensive items that should be read in only once, and then re-used from memory.

This includes the reddening laws (pysynphot.locations.RedLaws) and some indices for the catalog model atlases (pysynphot.Cache.CATALOG_CACHE).

pysynphot.Cache.reset_catalog_cache()

Empty the CATALOG_CACHE global variable.

pysynphot.catalog

This module is useful for working with catalog spectra such as Castelli-Kurucz Atlas, Kurucz Atlas, and Phoenix Models.

Spectra are constructed from basis spectra which are indexed for various combinations of effective temperature (T_{\textnormal{eff}}), metallicity (Z), and log surface gravity (\log g). The user may specify any combination of T_{\textnormal{eff}}, Z, and \log g so long as each parameter is within the range for that parameter defined by the catalog.

For example, the Castelli-Kurucz Atlas catalog contains spectra for effective temperatures between 3500 and 50000 K. In this case, no spectrum can be constructed for T_{\textnormal{eff}} of 50001 K or 3499 K. The range of parameters available may vary from catalog to catalog.

More information on catalogs can be found in Appendix A: Catalogs and Spectral Atlases.

Inheritance diagram of pysynphot.catalog.Icat
class pysynphot.catalog.Icat(catdir, Teff, metallicity, log_g)

Bases: pysynphot.spectrum.TabularSourceSpectrum

This class constructs a model from the grid available in catalogs. Specifically, they are Castelli-Kurucz Atlas, Kurucz Atlas, and Phoenix Models.

Each grid contains a master file named “catalog.fits”, as defined by pysynphot.locations.CAT_TEMPLATE. The basis spectra are located at pysynphot.locations.KUR_TEMPLATE. You may inspect the data files in CRDS to see how they are formatted.

Parameters:
  • catdir ({'ck04models', 'k93models', 'phoenix'}) – Name of directory holding the catalogs.
  • Teff (float) – Effective temperature of model, in Kelvin.
  • metallicity (float) – Metallicity of model.
  • log_g (float) – Log surface gravity of model.
name

str – Short description of the spectrum.

parameter_names

list of str – Names for model parameters. This is used for error reporting.

warnings

dict – To store warnings.

isAnalytic

bool – This is always False.

waveunits, fluxunits

Units – Catalog units for wavelength and flux.

wave, flux

array_like – Wavelength set and associated flux in catalog units.

Raises:pysynphot.exceptions.ParameterOutOfBounds – Given parameter value is out of bounds.

Examples

>>> spec = S.Icat('k93models', 6440, 0, 4.3)

pysynphot.exceptions

Custom exceptions for pysynphot to raise.

Inheritance diagram of pysynphot.exceptions
class pysynphot.exceptions.PysynphotError(msg)

Bases: Exception

Parent class for pysynphot exceptions.

Parameters:msg (str) – Error message.
class pysynphot.exceptions.TableFormatError(msg, rows=None)

Bases: pysynphot.exceptions.PysynphotError

Exception to do with table access.

Parameters:
  • msg (str) – Error message.
  • rows (list) – Rows with wrong values.
class pysynphot.exceptions.DuplicateWavelength(msg, rows=None)

Bases: pysynphot.exceptions.TableFormatError

Exception for duplicate wavelength values in table.

class pysynphot.exceptions.ZeroWavelength(msg, rows=None)

Bases: pysynphot.exceptions.TableFormatError

Exception for wavelength values containing zero.

class pysynphot.exceptions.UnsortedWavelength(msg, rows=None)

Bases: pysynphot.exceptions.TableFormatError

Exception for wavelength values not in ascending or descending order.

class pysynphot.exceptions.BadRow(msg, rows=None)

Bases: pysynphot.exceptions.TableFormatError

Exception for invalid row in table.

class pysynphot.exceptions.OverlapError(msg)

Bases: pysynphot.exceptions.PysynphotError

Exception to do with overlap checking.

class pysynphot.exceptions.PartialOverlap(msg)

Bases: pysynphot.exceptions.OverlapError

Exception for partial overlap between two spectra.

class pysynphot.exceptions.DisjointError(msg)

Bases: pysynphot.exceptions.OverlapError

Exception for no overlap between two spectra.

class pysynphot.exceptions.GraphtabError(msg)

Bases: pysynphot.exceptions.PysynphotError

Exception to do with graph table traversal.

class pysynphot.exceptions.UnusedKeyword(msg)

Bases: pysynphot.exceptions.GraphtabError

Exception for unused keyword in graph table lookup.

class pysynphot.exceptions.IncompleteObsmode(msg)

Bases: pysynphot.exceptions.GraphtabError

Exception for incomplete observation mode in graph table lookup.

class pysynphot.exceptions.AmbiguousObsmode(msg)

Bases: pysynphot.exceptions.GraphtabError

Exception for ambiguous observation mode in graph table lookup.

class pysynphot.exceptions.UndefinedBinset(msg)

Bases: pysynphot.exceptions.PysynphotError

Exception for undefined binset in bandpass or observation.

class pysynphot.exceptions.ExtrapolationNotAllowed(msg)

Bases: pysynphot.exceptions.PysynphotError

Exception for invalid extrapolation.

class pysynphot.exceptions.ParameterOutOfBounds(msg)

Bases: pysynphot.exceptions.PysynphotError

Exception for invalid parameter value in a catalog.

class pysynphot.exceptions.IncompatibleSources(msg)

Bases: pysynphot.exceptions.PysynphotError

Exception for operation on two incompatible spectra types.

pysynphot.extinction

This module handles deprecated extinction models for backward compatibility with IRAF STSDAS SYNPHOT.

Inheritance diagram of pysynphot.extinction.DeprecatedExtinction
class pysynphot.extinction.DeprecatedExtinction(extval, redlaw)

Bases: pysynphot.spectrum.SpectralElement

This class handles deprecated extinction models from IRAF STSDAS SYNPHOT like a spectral element.

Parameters:
  • extval (float) – Extinction in magnitude.
  • redlaw ({'gal1', 'smc', 'lmc', 'xgal'}) – Reddening law (Gal1, Smc, Lmc, or Xgal).
name

str – Name of the extinction law.

citation

str – The publication where this curve was obtained from.

isAnalytic

bool – This is always False.

warnings

dict – To store warnings

binset

None – This is reserved to be used by ObsModeBandpass.

waveunits

Units – This is set to Angstrom at initialization.

wave, throughput

array_like – Wavelength set in waveunits and associated unitless extinction.

Examples

>>> extinction = S.Extinction(0.3, 'gal1')
class pysynphot.extinction.Gal1(extval)

Deprecated Milky Way extinction curve (Seaton 1979).

Parameters:extval (float) – Value of E(B-V) in magnitudes.
name

str – Name of the extinction law.

citation

str – The publication where this curve was obtained from.

transparencytable

array_like – This is the same as \textnormal{THRU} defined in reddening().

class pysynphot.extinction.Smc(extval)

Deprecated SMC extinction curve (Prevot et al. 1984).

Parameters:extval (float) – Value of E(B-V) in magnitudes.
name

str – Name of the extinction law.

citation

str – The publication where this curve was obtained from.

transparencytable

array_like – This is the same as \textnormal{THRU} defined in reddening().

class pysynphot.extinction.Lmc(extval)

Deprecated LMC extinction curve (Howarth 1983).

Parameters:extval (float) – Value of E(B-V) in magnitudes.
name

str – Name of the extinction law.

citation

str – The publication where this curve was obtained from.

transparencytable

array_like – This is the same as \textnormal{THRU} defined in reddening().

class pysynphot.extinction.Xgal(extval)

Deprecated Extra-galactic extinction curve (Calzetti et al. 1994).

Parameters:extval (float) – Value of E(B-V) in magnitudes.
name

str – Name of the extinction law.

citation

str – The publication where this curve was obtained from.

transparencytable

array_like – This is the same as \textnormal{THRU} defined in reddening().

pysynphot.locations

This module handles locations of data files.

Global Variables

  • pysynphot.locations.rootdir - Root directory for CDBS/CRDS data files. By default, it is extracted from your PYSYN_CDBS environment variable.
  • pysynphot.locations.specdir - Data directory for data files distributed with this software.
  • pysynphot.locations.CAT_TEMPLATE and pysynphot.locations.KUR_TEMPLATE - String templates used for Icat to select spectra from catalogs.
  • pysynphot.locations.VegaFile - Vega spectrum to use for vegamag calculations.
  • pysynphot.locations.EXTDIR - Directory containing extinction curves.
  • pysynphot.locations.RedLaws - Dictionary mapping reddening laws to data files or cached instances (see Cache).
  • pysynphot.locations.wavecat - Data file for wavetable.
  • pysynphot.locations.CONVERTDICT - Dictionary mapping IRAF-style directory shortcuts to actual paths.
pysynphot.locations.get_data_filename(filename)

Map filename to its actual path.

Parameters:filename (str) – Filename to search.
Returns:path – Full path to the file in data directory.
Return type:str
pysynphot.locations.get_latest_file(template, raise_error=False, err_msg='')

Find the filename that appears last in sorted order based on given template.

Parameters:
  • template (str) – Search template in the form of path/pattern where pattern is acceptable by fnmatch.
  • raise_error (bool, optional) – Raise an error when no files found. Otherwise, will issue warning only.
  • err_msg (str) – Alternate message for when no files found. If not given, generic message is used.
Returns:

filename – Latest filename.

Return type:

str

Raises:

IOError – No files found.

pysynphot.locations.irafconvert(iraffilename)

Convert the IRAF file name to its Unix equivalent.

Input can be in directory$file or $directory/file format. If '$' is not found in the input string, it is returned as-is.

Parameters:iraffilename (str) – Filename in IRAF format.
Returns:unixfilename – Filename in Unix format.
Return type:str
Raises:AttributeError – Input is not a string.

pysynphot.obsbandpass

This module handle bandpass of observation modes.

pysynphot.obsbandpass.ObsBandpass(obstring, graphtable=None, comptable=None, component_dict={})

Generate a bandpass object from observation mode.

If the bandpass consists of multiple throughput files (e.g., “acs,hrc,f555w”), then ObsModeBandpass is returned. Otherwise, if it consists of a single throughput file (e.g., “johnson,v”), then TabularSpectralElement is returned.

See Observation Mode and Appendix B: OBSMODE Keywords for more details.

Parameters:
  • obstring (str) – Observation mode.
  • comptable, component_dict (graphtable,) – See ObservationMode.
Returns:

bp

Return type:

TabularSpectralElement or ObsModeBandpass

Examples

>>> bp1 = S.ObsBandpass('acs,hrc,f555w')
>>> bp2 = S.ObsBandpass('johnson,v')
Inheritance diagram of pysynphot.obsbandpass.ObsModeBandpass
class pysynphot.obsbandpass.ObsModeBandpass(ob)

Bases: pysynphot.spectrum.CompositeSpectralElement

Bandpass instantiated from an obsmode string. Also see Observation Mode, Appendix B: OBSMODE Keywords, and Appendix C: TMG, TMC, and TMT Files.

Parameters:ob (str) – Observation mode.
obsmode, name

Same as input ob.

component1, component2

CompositeSpectralElement or SpectralElement – Components and sub-components that belong to the observation mode.

isAnalytic

bool – This is always False.

warnings

dict – To store warnings, which are inherited from all inputs. If they have the same warning keyword, the one from most recently read component is used.

primary_area

float – See Area for how this is set.

binset

array_like – This is set with bandWave(), as described in Reference Data.

waveunits

Units – User unit inherited from inputs, where all inputs are required to have the same unit or an exception will be raised.

throughputunits

None – This is only to inform user that throughput is unitless.

wave, throughput

array_like – Wavelength set in user unit and associated unitless throughput.

Raises:
  • NotImplementedError – Inputs have different wavelength units.
  • TypeError – Both input spectra must be bandpasses.
  • pysynphot.exceptions.IncompatibleSources – Input spectra have different telescope areas defined.
pixel_range(waverange, waveunits=None, round='round')

Returns the number of wavelength bins within waverange.

Note

This calls pixel_range() with self.binset as the first argument.

Parameters:
  • round (waverange,) – See pixel_range().
  • waveunits (str, optional) – The units of the wavelengths given in waverange. If None (default), the wavelengths are assumed to be in the units of self.waveunits.
Returns:

num – Number of wavelength bins within waverange.

Return type:

int or float

Raises:

pysynphot.exceptions.UndefinedBinset – If self.binset is None.

showfiles()

Same as pysynphot.observationmode.BaseObservationMode.showfiles().

thermback()

Calculate thermal background count rate for self.obsmode.

Calculation uses ThermalSpectrum() to extract thermal component source spectrum in photlam per square arcsec. Then this spectrum is integrated and multiplied by detector pixel scale and telescope collecting area to produce a count rate in count/s/pix. This unit is non-standard but used widely by STScI Exposure Time Calculator.

Note

Similar to IRAF STSDAS SYNPHOT thermback task.

Returns:ans – Thermal background count rate.
Return type:float
Raises:NotImplementedError – Bandpass has no thermal information in graph table.
wave_range(cenwave, npix, waveunits=None, round='round')

Get the wavelength range covered by the given number of pixels centered on the given wavelength.

Note

This calls wave_range() with self.binset as the first argument.

Parameters:
  • npix, round (cenwave,) – See wave_range().
  • waveunits (str, optional) – Wavelength units of cenwave and the returned wavelength range. If None (default), the wavelengths are assumed to be in the units of self.waveunits.
Returns:

waverange – The range of wavelengths spanned by npix centered on cenwave.

Return type:

tuple of floats

Raises:

pysynphot.exceptions.UndefinedBinset – If self.binset is None.

pysynphot.obsbandpass.pixel_range(bins, waverange, round='round')

Returns the number of wavelength bins within waverange.

Parameters:
  • bins (ndarray) – Wavelengths of pixel centers. Must be in the same units as waverange.
  • waverange (array_like) – A sequence containing the wavelength range of interest. Only the first and last elements are used. Assumed to be in increasing order. Must be in the same units as bins.
  • round ({‘round’, ‘min’, ‘max’, None}, optional) –

    How to deal with pixels at the edges of the wavelength range. All of the options, except None, will return an integer number of pixels. Defaults to 'round'.

    • 'round' - Wavelength ends that fall in the middle of a pixel are counted if more than half of the pixel is within waverange. Ends that fall in the center of a pixel are rounded up to the nearest pixel edge.
    • 'min' - Only pixels wholly within waverange are counted.
    • 'max' - End pixels that are within waverange by any margin are counted.
    • None - The exact number of encompassed pixels, including fractional pixels, is returned.
Returns:

num – Number of wavelength bins within waverange.

Return type:

int or float

Raises:
pysynphot.obsbandpass.wave_range(bins, cenwave, npix, round='round')

Get the wavelength range covered by the given number of pixels centered on the given wavelength.

Parameters:
  • bins (ndarray) – Wavelengths of pixel centers. Must be in the same units as cenwave.
  • cenwave (float) – Central wavelength of range. Must be in the same units as bins.
  • npix (int) – Number of pixels in range, centered on cenwave.
  • round ({‘round’, ‘min’, ‘max’, None}, optional) –

    How to deal with pixels at the edges of the wavelength range. All of the options, except None, will return wavelength ends that correpsonds to pixel edges. Defaults to 'round'.

    • 'round' - A wavelength range is returned such that the ends are pixel edges and the range spans exactly npix pixels. Ends that fall in the center of bins are rounded up to the nearest pixel edge.
    • 'min' - The returned wavelength range is shrunk so that it includes an integer number of pixels and the ends fall on pixel edges. May not span exactly npix pixels.
    • 'max' - The returned wavelength range is expanded so that it includes an integer number of pixels and the ends fall on pixel edges. May not span exactly npix pixels.
    • None - An exact wavelength range is returned. The wavelength ends returned may not correspond to pixel edges, but will cover exactly npix pixels.
Returns:

waverange – The range of wavelengths spanned by npix centered on cenwave.

Return type:

tuple of floats

Raises:
  • ValueError – If round is not an allowed value.
  • pysynphot.exceptions.OverlapError – If cenwave is not within bins, or the returned waverange would exceed the limits of bins.

pysynphot.observationmode

This module handles observation modes that are defined in graph tables.

Global Variables

  • pysynphot.observationmode.rootdir - Same as pysynphot.locations.rootdir.
  • pysynphot.observationmode.datadir - Same as pysynphot.locations.specdir.
  • pysynphot.observationmode.wavecat - Same as pysynphot.locations.wavecat.
  • pysynphot.observationmode.CLEAR - String to represent a clear filter in an observation mode, i.e., ‘clear’.
Inheritance diagram of pysynphot.observationmode.ObservationMode
class pysynphot.observationmode.BaseObservationMode(obsmode, method='HSTGraphTable', graphtable=None)

Class that handles the graph table, common to both optical and thermal observation modes. Also see Appendix C: TMG, TMC, and TMT Files.

Parameters:
  • obsmode (str) – Observation mode.
  • method ({'HSTGraphTable'}) – Not used.
  • graphtable (str or None) – Graph table name. If None, it is taken from refs.
pardict

dict – Stores parameterized keywords and their values. For example, aper#0.1 would result in {'aper':0.1}.

modes

list of str – Individual keywords that make up the observation mode. This includes parameterized ones.

gtname

str – Graph table name.

compnames, thcompnames

list of str – Optical and thermal component names based on keyword look-ups. The look-up is done using GetComponentsFromGT().

primary_area

float – See Area for how this is set.

components, pixscale

None – Reserved to be used by sub-classes.

binset

str – Filename containing the optimal wavelength set, or a string defining it.

GetFileNames()

Return throughput files of this observation mode.

Returns:throughput_filenames
Return type:list
bandWave()

Return the binned wavelength set most appropriate for the observation mode, as defined by pysynphot.locations.wavecat. Also see Reference Data.

Returns:bandwave
Return type:array_like
showfiles()

Like GetFileNames() but print the filenames instead. 'clear' components are not printed.

Note

Similar to IRAF STSDAS SYNPHOT showfiles task.

class pysynphot.observationmode.ObservationMode(obsmode, method='HSTGraphTable', graphtable=None, comptable=None, component_dict={})

Bases: pysynphot.observationmode.BaseObservationMode

Class to handle optical observation mode.

Parameters:
  • method, graphtable (obsmode,) – See BaseObservationMode.
  • comptable (str or None) – Component table name. If None, it is taken from refs.
  • component_dict (dict) – Maps component filename to corresponding component object.
pardict

dict – Stores parameterized keywords and their values. For example, aper#0.1 would result in {'aper':0.1}.

modes

list of str – Individual keywords that make up the observation mode. This includes parameterized ones.

gtname, ctname

str – Graph and component table names.

compnames, thcompnames

list of str – Optical and thermal component names based on keyword look-ups. The look-up is done using GetComponentsFromGT().

primary_area

float – See Area for how this is set.

components

list – List of component objects. Each object has throughput_name (str), throughput (SpectralElement), and waveunits (Units) attributes.

pixscale

number or None – Detector pixel scale, if applicable.

binset

str – Filename containing the optimal wavelength set, or a string defining it.

Raises:IndexError – Component look-up failed.
ThermalSpectrum()

Calculate thermal spectrum.

Returns:sp – Thermal spectrum in photlam.
Return type:CompositeSourceSpectrum
Raises:IndexError – Calculation failed.
Throughput()

Combined throughput from multiplying all the components together.

Returns:throughput – Combined throughput.
Return type:TabularSpectralElement or None

pysynphot.observation

This module handles an observation and related calculations.

Inheritance diagram of pysynphot.observation.Observation
class pysynphot.observation.Observation(spec, band, binset=None, force=None)

Bases: pysynphot.spectrum.CompositeSourceSpectrum

Class to handle an observation. An observation is the end point of a chain of spectral manipulation.

Most ObsBandpass objects have a built-in binset that is optimized for use with the specified observing mode (also see Wavelength Table). Specifying the binset here would override the built-in one.

Parameters:
spectrum

Same as input spec.

bandpass

Same as input band.

binset

Same as input binset.

component1, component2

SourceSpectrum or SpectralElement – Components and sub-components that belong to the observation.

operation

str – This is always “multiply”.

name

str – Short description of the observation.

warnings

dict – To store warnings, which are inherited from all inputs. If they have the same warning keyword, the one from most recently read component is used.

isAnalytic

bool – Flag to indicate whether this is an analytic spectrum. This is only True if both inputs are analytic.

primary_area

number or NoneArea of the telescope. This is inherited from either of the inputs, if available (not None). If inputs have different values, an exception is raised.

waveunits, fluxunits

Units – User units inherited from source spectrum.

wave, flux

array_like – Wavelength set and associated flux in user units. This is the native dataset.

binwave, binflux

array_like – Binned dataset.

Raises:pysynphot.exceptions.IncompatibleSources – Input spectra have different telescope areas defined.
as_spectrum(binned=True)

Reduce the observation to a simple spectrum object.

An observation is a complex object with some restrictions on its capabilities. At times, it would be useful to work with the simulated observation as a simple object that is easier to manipulate and takes up less memory.

Parameters:binned (bool) – If True (default), export binned dataset. Otherwise, native.
Returns:result – Observation dataset as a simple spectrum object.
Return type:ArraySourceSpectrum
countrate(binned=True, range=None, force=False)

Calculate effective stimulus in count/s. Also see Count Rate and Effective Stimulus.

Note

This is the calculation performed when the ETC invokes countrate.

Parameters:
  • binned (bool) – If True (default), use binned data. Otherwise, use native data.
  • range (tuple or None) –

    If not None, it must be a sequence with two floating-point elements specifying the wavelength range (inclusive) in the unit of self.waveunits in the form of (low, high); This is the range over which the integration will be performed. If the specified range does not exactly match a value in the wavelength set:

    • If binned=True, the bin containing the range value will be used. This assumes self.binwave contains bin centers.
    • If binned=False, native dataset will be interpolated to the specified values. (Not Implemented.)
  • force (bool) – If False (default), partially overlapping ranges will raise an exception. If True, a partial overlap will return the calculated value instead. Disjoint ranges raise an exception regardless.
Returns:

ans – Count rate.

Return type:

float

Raises:
efflam(binned=True)

Calculate effective wavelength of the observation. Calculation is done in the flux unit of flam.

Note

Similar to IRAF STSDAS SYNPHOT efflphot task.

Parameters:binned (bool) – Use binned dataset for calculations. Otherwise, use native dataset.
Returns:ans – Effective wavelength.
Return type:float
effstim(fluxunits='photlam')

Compute effective stimulus.

Calculations are done in given flux unit, and wavelengths in Angstrom. Native dataset is used.

Parameters:fluxunits (str) – Flux unit.
Returns:ans – Effective stimulus.
Return type:float
Raises:ValueError – Invalid integrated flux.
initbinflux()

Calculate binned flux and edges.

Flux is computed by integrating the spectrum on the specified binned wavelength set, using information from the natural wavelength set.

Native wave/flux arrays should be considered samples of a continuous function, but not their binned counterparts. Thus, it makes sense to interpolate (wave, flux) but not (binwave, binflux).

Note

Assumes that the wavelength values in the binned wavelength set are the centers of the bins.

Uses pysynphot.pysynphot_utils.calcbinflux() C-extension, if available, for binned flux calculation.

initbinset(binset=None)

Set self.binwave.

By default, wavelength values for binning are inherited from bandpass. If the bandpass has no binning information, then source spectrum wavelengths are used. However, if user provides values, then those are used without question.

Parameters:binset (array_like or None) – Wavelength values to be used for binning when converting to counts.
pivot(binned=True)

Calculate pivot wavelength of the observation.

Note

This is the calculation performed when ETC invokes calcphot.

Parameters:binned (bool) – Use binned dataset for calculations. Otherwise, use native dataset.
Returns:ans – Pivot wavelength.
Return type:float
pixel_range(waverange, waveunits=None, round='round')

Calculate the number of wavelength bins within given wavelength range.

Note

This calls pysynphot.obsbandpass.pixel_range() with self.binwave as the first argument.

Parameters:
  • round (waverange,) – See pysynphot.obsbandpass.pixel_range().
  • waveunits (str, optional) – The unit of the wavelength range. If None (default), the wavelengths are assumed to be in the units of self.waveunits.
Returns:

num – Number of wavelength bins within waverange.

Return type:

int or float

Raises:

pysynphot.exceptions.UndefinedBinset – No binned dataset.

sample(swave, binned=True, fluxunits='counts')

Sample the observation at the given wavelength. Also see Sampling.

Parameters:
  • swave (float) – Wavelength to sample.
  • binned (bool) – Sample binned dataset (no interpolation). Otherwise, native (perform interpolation).
  • fluxunits ({'counts'}) – Only the unit of counts is supported for now.
Returns:

ans – Sampled flux in given unit.

Return type:

float

Raises:
  • NotImplementedError – Flux unit is not supported or non-scalar wavelength is given.
  • ValueError – Given wavelength out of range.
validate_overlap(force)

Validate that spectrum and bandpass overlap. Warnings are stored in self.warnings.

Parameters:force ({‘extrap’, ‘taper’, None}) – If None, it is required that the spectrum and bandpass fully overlap. Partial overlap is allowed if this is set to 'extrap' or 'taper'. See validate_overlap().
wave_range(cenwave, npix, waveunits=None, round='round')

Calculate the wavelength range covered by the given number of pixels, centered on the given wavelength.

Note

This calls pysynphot.obsbandpass.wave_range() with self.binwave as the first argument.

Parameters:
  • npix, round (cenwave,) – See pysynphot.obsbandpass.wave_range().
  • waveunits (str, optional) – Wavelength unit of the given and the returned wavelength values. If None (default), the wavelengths are assumed to be in the unit of self.waveunits.
Returns:

waverange – The range of wavelengths spanned by npix centered on cenwave.

Return type:

tuple of floats

Raises:

pysynphot.exceptions.UndefinedBinset – No binned dataset.

writefits(fname, clobber=True, trimzero=True, binned=True, hkeys=None)

Like pysynphot.spectrum.SourceSpectrum.writefits() but with binned=True as default.

pysynphot.observation.check_overlap(a, b)

Check for wavelength overlap between two spectra.

Parameters:b (a,) – Typically a source spectrum, spectral element, observation, or bandpass from observation mode.
Returns:result – Full, partial, or no overlap.
Return type:{‘full’, ‘partial’, ‘none’}
Raises:AttributeError – Given spectrum does not have flux or throughput.
pysynphot.observation.validate_overlap(comp1, comp2, force)

Validate the overlap between the wavelength sets of the two given components.

Parameters:
  • comp2 (comp1,) – Source spectrum and bandpass of an observation.
  • force ({‘extrap’, ‘taper’, None}) – If not None, the components may be adjusted by extrapolation or tapering.
Returns:

  • comp1, comp2 – Same as inputs. However, comp1 might be tapered if that option is selected.
  • warnings (dict) – Maps warning keyword to its description.

Raises:

pysynphot.planck

This module handles Planck’s law of blackbody radiation.

Global Variables

  • pysynphot.planck.H - Planck’s constant in CGS units.
  • pysynphot.planck.HS - Planck’s constant in SI units.
  • pysynphot.planck.C - Speed of light in SI units.
  • pysynphot.planck.K - Boltzmann constant in SI units.

These are used in calculations to prevent floating point overflow, as defined in IRAF STSDAS SYNPHOT bbfunc task:

  • pysynphot.planck.LOWER
  • pysynphot.planck.UPPER

These are constants used in llam_SI():

  • pysynphot.planck.C1 - Power \times unit area per steradian.
  • pysynphot.planck.C2

This is used in bb_photlam_arcsec():

  • pysynphot.planck.F - Factor for conversion from \textnormal{m}^{2} \; \textnormal{sr}^{-1} \; \textnormal{m}^{-1} to \textnormal{cm}^{2} \; \textnormal{arcsec}^{-2} \; \AA^{-1}.
pysynphot.planck.bb_photlam_arcsec(wave, temperature)

Evaluate Planck’s law in photlam per square arcsec.

Note

Uses llam_SI() for calculation, and then converts SI units back to CGS.

Parameters:
  • wave (array_like) – Wavelength values in Angstrom.
  • temperature (float) – Blackbody temperature in Kelvin.
Returns:

result – Blackbody radiation in photlam per square arcsec.

Return type:

array_like

pysynphot.planck.bbfunc(wave, temperature)

Evaluate Planck’s law in photlam (per steradian).

Note

Adapted from IRAF STSDAS SYNPHOT bbfunc task.

Parameters:
  • wave (array_like) – Wavelength values in Angstrom.
  • temperature (float) – Blackbody temperature in Kelvin.
Returns:

result – Blackbody radiation in photlam per steradian.

Return type:

array_like

pysynphot.planck.llam_SI(wave, temperature)

Like bbfunc() but in SI units.

Note

Adapted from SSP code by Dr. Anand Sivaramakrishnan in IRAF STSDAS SYNPHOT.

Parameters:
  • wave (array_like) – Wavelength values in meters.
  • temperature (float) – Blackbody temperature in Kelvin.
Returns:

result – Blackbody radiation in SI units.

Return type:

array_like

pysynphot.reddening

This module handles reddening laws and extinction calculations.

pysynphot.reddening.print_red_laws()

Print available extinction laws to screen.

Available extinction laws are extracted from pysynphot.locations.EXTDIR. The printed names may be used with Extinction() to retrieve available reddening laws.

Examples

>>> S.reddening.print_red_laws()
name       reference
--------   --------------------------------------------------------------
None        Cardelli, Clayton, & Mathis (1989, ApJ, 345, 245) R_V = 3.10.
gal3        Cardelli, Clayton, & Mathis (1989, ApJ, 345, 245) R_V = 3.10.
lmc30dor    Gordon et al. (2003, ApJ, 594, 279) R_V = 2.76.
lmcavg      Gordon et al. (2003, ApJ, 594, 279) R_V = 3.41.
mwavg       Cardelli, Clayton, & Mathis (1989, ApJ, 345, 245) R_V = 3.10.
mwdense     Cardelli, Clayton, & Mathis (1989, ApJ, 345, 245) R_V = 5.00.
mwrv21      Cardelli, Clayton, & Mathis (1989, ApJ, 345, 245) R_V = 2.1.
mwrv4       Cardelli, Clayton, & Mathis (1989, ApJ, 345, 245) R_V = 4.0.
smcbar      Gordon et al. (2003, ApJ, 594, 279) R_V=2.74.
xgalsb      Calzetti et al. (2000. ApJ, 533, 682)
pysynphot.reddening.Extinction(extval, name=None)

Generate extinction curve to be used with spectra.

By default, reddening() is used to generate the extinction curve. If a deprecated reddening law is given, then DeprecatedExtinction is used instead.

Note

Reddening laws are cached in pysynphot.Cache.RedLaws for better performance. Repeated calls to the same reddening law here returns the cached result.

Parameters:
  • extval (float) – Value of E(B-V) in magnitudes.
  • name (str or None) – Name of reddening law (see print_red_laws()). If None (default), the average Milky Way extinction ('mwavg') will be used.
Returns:

ext – Extinction curve.

Return type:

ArraySpectralElement or DeprecatedExtinction

Raises:

ValueError – Invalid reddening law.

Examples

>>> ext = S.Extinction(0.3, 'mwavg')
Inheritance diagram of pysynphot.reddening.RedLaw
class pysynphot.reddening.CustomRedLaw(wave=None, waveunits='InverseMicrons', Avscaled=None, name='Unknown Reddening Law', litref=None)

Class to handle reddening law.

Parameters:
  • wave (array_like) – Wavelength values.
  • waveunits (str) – Wavelength unit, as accepted by Units. By default, it is \mu m^{-1}.
  • Avscaled (array_like) – Values of A(V)/E(B-V).
  • name (str) – Short description of the reddening law.
  • litref (str) – Literature reference of the reddening law.
wave, waveunits, name, litref

Same as inputs.

obscuration

Same as input Avscaled.

reddening(extval)

Compute the reddening for the given extinction.

A(V) = R(V) \; \times \; E(B-V)

\textnormal{THRU} = 10^{-0.4 \; A(V)}

Note

self.litref is passed into ans.citation.

Parameters:extval (float) – Value of E(B-V) in magnitudes.
Returns:ans – Extinction curve to apply to a source spectrum.
Return type:ArraySpectralElement
class pysynphot.reddening.RedLaw(filename)

Bases: pysynphot.reddening.CustomRedLaw

CustomRedLaw from a FITS file.

Table must be in EXT 1 and contains the following columns:

  1. WAVELENGTH
  2. Av/E(B-V)

Wavelength unit is extracted from TUNIT1 keyword in EXT 1 header. The primary header (EXT 0) must have SHORTNM and LITREF keywords.

Parameters:filename (str) – FITS table filename.
wave

array_like – Wavelength values from the WAVELENGTH column in EXT 1.

waveunits

str – Value of TUNIT1 in EXT 1 header.

name

str – Value of SHORTNM in EXT 0 header.

litref

str – Value of LITREF in EXT 0 header.

obscuration

Values from the Av/E(B-V) column in EXT 1.

pysynphot.refs

This module handles constants and look-up tables used in calculations.

Global Variables

  • pysynphot.refs._default_waveset - Default wavelength set to use if no instrument-specific values found.
  • pysynphot.refs._default_waveset_str - Description of the default wavelength set above.
  • pysynphot.refs.PRIMARY_AREA - Telescope collecting area, i.e., the primary mirror, in \textnormal{cm}^{2}. The value for HST is 45238.93416.

These are used in observationmode to look up throughput files for a given bandpass:

  • pysynphot.refs.GRAPHTABLE
  • pysynphot.refs.GRAPHDICT
  • pysynphot.refs.COMPTABLE
  • pysynphot.refs.COMPDICT
  • pysynphot.refs.THERMTABLE
  • pysynphot.refs.THERMDICT
pysynphot.refs.getref()

Current default values for graph and component tables, primary area, and wavelength set.

Note

Also see setref().

Returns:ans – Mapping of parameter names to their current values.
Return type:dict
pysynphot.refs.showref()

Like getref() but print results to screen instead of returning a dictionary.

pysynphot.refs.setref(graphtable=None, comptable=None, thermtable=None, area=None, waveset=None)

Set default graph and component tables, primary area, and wavelength set.

This is similar to setting refdata in IRAF STSDAS SYNPHOT. If all parameters set to None, they are reverted to software default. If any of the parameters are not None, they are set to desired values while the rest (if any) remain at current setting.

Parameters:
  • comptable, thermtable (graphtable,) – Graph, component, and thermal table names, respectively, for observationmode throughput look-up. Do not use “*” wildcard.
  • area (float or None) – Telescope collecting area, i.e., the primary mirror, in \textnormal{cm}^{2}.
  • waveset (tuple or None) –
    Parameters for set_default_waveset() as follow:
    • (minwave, maxwave, num) - This assumes log scale.
    • (minwave, maxwave, num, 'log')
    • (minwave, maxwave, num, 'linear')
Raises:

ValueError – Invalid waveset parameters.

pysynphot.refs.set_default_waveset(minwave=500, maxwave=26000, num=10000, delta=None, log=True)

Set the default wavelength set, pysynphot.refs._default_waveset.

Parameters:
  • maxwave (minwave,) – The start (inclusive) and end (exclusive) points of the wavelength set. Values should be given in linear space regardless of log.
  • num (int, optional) – The number of elements in the wavelength set. Only used if delta=None.
  • delta (float, optional) – Delta between values in the wavelength set. If log=True, this defines wavelegth spacing in log space.
  • log (bool, optional) – Determines whether the wavelength set is evenly spaced in log or linear space.

pysynphot.renorm

This module handles normalization of source spectrum flux.

pysynphot.renorm.DefineStdSpectraForUnits()

Define StdSpectrum attribute for all the supported Flux Units.

This is automatically done on module import. The attribute stores the source spectrum necessary for normalization in the corresponding flux unit.

For photlam, photnu, flam, fnu, Jy, and mJy, the spectrum is flat in the respective units with flux value of 1.

For counts and obmag, it is flat in the unit of counts with flux value of 1 / N, where N is the size of default wavelength set (see refs).

For abmag and stmag, it is flat in the respective units with flux value of 0 mag. That is equivalent to 3.63 \times 10^{-20} fnu and 3.63 \times 10^{-9} flam, respectively.

For vegamag, it is simply Vega.

pysynphot.renorm.StdRenorm(spectrum, band, RNval, RNunitstring, force=False)

This is used by SourceSpectrum for renormalization.

Parameters:
Returns:

newsp – Renormalized spectrum.

Return type:

CompositeSourceSpectrum

pysynphot.spark

SPARK 0.6.1 is obtained from John Aycock (1998-2000). It is the underlying engine used by pysynphot.spparser.

pysynphot.spectrum

This module contains the basis for all spectra classes, including source spectra and bandpasses.

It also pre-loads the built-in Vega spectrum to pysynphot.spectrum.Vega.

Inheritance diagram of pysynphot.spectrum
class pysynphot.spectrum.Integrator

Integrator engine, which is the base class for SourceSpectrum and SpectralElement.

trapezoidIntegration(x, y)

Perform trapezoid integration.

Parameters:
  • x (array_like) – Wavelength set.
  • y (array_like) – Integrand. For example, throughput or throughput multiplied by wavelength.
Returns:

sum – Integrated sum.

Return type:

float

validate_fluxtable()

Check for non-negative fluxes. If found, the negative flux values are set to zero, and a warning is printed to screen. This check is not done if flux unit is a magnitude because negative magnitude values are legal.

validate_wavetable()

Enforce monotonic, ascending wavelength array with no zero or negative values.

Raises:
class pysynphot.spectrum.SourceSpectrum

Bases: pysynphot.spectrum.Integrator

This is the base class for all source spectra.

addmag(magval)

Add a scalar magnitude to existing flux values.

\textnormal{flux}_{\textnormal{new}} = 10^{-0.4 \; \textnormal{magval}} \; \textnormal{flux}

Parameters:magval (number) – Magnitude value.
Returns:sp – New source spectrum with adjusted flux values.
Return type:CompositeSourceSpectrum
Raises:TypeError – Magnitude value is not a scalar number.
convert(targetunits)

Set new user unit, for either wavelength or flux.

This effectively converts the spectrum wavelength or flux to given unit. Note that actual data are always kept in internal units (Angstrom and photlam), and only converted to user units by getArrays() during actual computation. User units are stored in self.waveunits and self.fluxunits.

Parameters:targetunits (str) – New unit name, as accepted by Units.
flux

Flux property.

getArrays()

Return wavelength and flux arrays in user units.

Returns:
  • wave (array_like) – Wavelength array in self.waveunits.
  • flux (array_like) – Flux array in self.fluxunits. When necessary, self.primary_area is used for unit conversion.
integrate(fluxunits='photlam')

Integrate the flux in given unit.

Integration is done using trapezoidIntegration() with x=wave and y=flux, where flux has been convert to given unit first.

\textnormal{result} = \int F_{\lambda} d\lambda

Parameters:fluxunits (str) – Flux unit to integrate in.
Returns:result – Integrated sum.
Return type:float
redshift(z)

Apply redshift to the spectrum.

Redshifted spectrum is never analytic even if the input spectrum is. Output units are always Angstrom and PHOTLAM regardless of user units.

Parameters:z (number) – Redshift value.
Returns:copy – Redshifted spectrum.
Return type:ArraySourceSpectrum
renorm(RNval, RNUnits, band, force=False)

Renormalize the spectrum to the specified value, unit, and bandpass.

This wraps StdRenorm() for convenience. Basically, the spectrum is multiplied by a numeric factor so that the total integrated flux will be the given value in the given unit in the given bandpass.

When force=False, if spectrum is not fully defined within the given bandpass, but the overlap is at least 99%, a warning is printed to screen and self.warnings['PartialRenorm'] is set to True.

Parameters:
  • RNval (number) – Flux value for renormalization.
  • RNUnits (str) – Unit name, as accepted by Units, for RNval.
  • band (SpectralElement) – Bandpass that RNval is based on.
  • force (bool) – Force renormalization regardless of overlap status with given bandpass. If True, overlap check is skipped. Default is False.
Returns:

newsp – Renormalized spectrum.

Return type:

CompositeSourceSpectrum

Raises:
sample(wave, interp=True)

Sample the spectrum at given wavelength(s).

This method has two behaviors:

  • When interp=True, wavelength(s) must be provided as a Numpy array. Interpolation is done in internal units (Angstrom and photlam).
  • When interp=False, wavelength must be a scalar number. The flux that corresponds to the closest matching wavelength value is returned. This option should only be used for sampling binned data in Observation.
Parameters:
  • wave (number or array_like) – Wavelength(s) to sample, given in user unit.
  • interp (bool) – Allow flux interpolation. Default is True.
Returns:

ans – Sampled flux in user unit.

Return type:

number or array_like

Raises:

NotImplementedError – Non-scalar wavelength set provided when interpolation is not allowed.

validate_units()

Ensure that wavelenth and flux units belong to the correct classes.

Raises:TypeError – Wavelength unit is not WaveUnits or flux unit is not FluxUnits.
wave

Wavelength property.

writefits(filename, clobber=True, trimzero=True, binned=False, precision=None, hkeys=None)

Write the spectrum to a FITS table.

Primary header in EXT 0. FILENAME, ORIGIN, and any extra keyword(s) from hkeys will also be added.

Table header and data are in EXT 1. The table has 2 columns, i.e., WAVELENGTH and FLUX. Data are stored in user units. Its header also will have these additional keywords:

  • EXPR - Description of the spectrum.
  • TDISP1 and TDISP2 - Columns display format, always “G15.7”.
  • GRFTABLE and CMPTABLE - Graph and component table names to use with associated observation mode. These are only added if applicable.

If data is already double-precision but user explicitly set output precision to single, pysynphot.spectrum.syn_epsilon defines the allowed minimum wavelength separation. This limit (3.2 \times 10^{-4}) was taken from IRAF STSDAS SYNPHOT FAQ. Values equal or smaller than this limit are considered as the same, and duplicates are ignored, resulting in data loss. In the way that this comparison is coded, when such precision clash happens, even when no duplicates are detected, the last row is always omitted (also data loss). Therefore, it is not recommended for user to force single-precision when the data is in double-precision.

Parameters:
  • filename (str) – Output filename.
  • clobber (bool) – Overwrite existing file. Default is True.
  • trimzero (bool) – Trim off duplicate rows with flux values of zero from both ends of the spectrum. This keeps one row of zero-flux at each end, if it exists; However, it does not add a zero-flux row if it does not. Default is True.
  • binned (bool) – Write self.binwave and self.binflux (binned) dataset, instead of self.wave and self.flux (native). Using this option when object does not have binned data will cause an exception to be raised. Default is False.
  • precision ({‘s’, ‘d’, None}) – Write data out in single ('s') or double ('d') precision. Default is None, which will enforce native precision from self.flux.
  • hkeys (dict) – Additional keyword(s) to be added to primary FITS header, in the format of {keyword:(value,comment)}.
class pysynphot.spectrum.TabularSourceSpectrum(filename=None, fluxname=None, keepneg=False)

Bases: pysynphot.spectrum.SourceSpectrum

Base class for ArraySourceSpectrum and FileSourceSpectrum.

Parameters:
  • filename (str or None) – File with spectral data (can be ASCII or FITS). If not None, data will be loaded from file at initialization.
  • fluxname (str or None) – Column name containing flux data. This is only used if filename is given and is of FITS format.
  • keepneg (bool) – Keep negative flux values instead of setting them to zero with a warning. Default is False.
filename, name

Same as input.

warnings

dict – To store warnings.

isAnalytic

bool – This is always False.

waveunits, fluxunits

Units – User units for wavelength and flux.

wave, flux

array_like – Wavelength set and associated flux in user units.

GetWaveSet()

Return the wavelength set for the spectrum.

Returns:waveset – Wavelength set (a copy of the internal wavelength table).
Return type:array_like
resample(resampledWaveTab)

Resample the spectrum for the given wavelength set.

Given wavelength array must be monotonically increasing or decreasing. Flux interpolation is done using numpy.interp().

Parameters:resampledWaveTab (array_like) – Wavelength set for resampling.
Returns:resampled – Resampled spectrum.
Return type:ArraySourceSpectrum
taper()

Taper the spectrum by adding zero flux to each end. This is similar to SpectralElement.taper().

There is no check to see if the spectrum is already tapered. Hence, calling this on a tapered spectrum will result in multiple zero-flux entries at both ends.

The wavelengths to use for the new first and last points are calculated by using the same ratio as for the two interior points used at each end.

Returns:OutSpec – Tapered spectrum.
Return type:TabularSourceSpectrum
class pysynphot.spectrum.ArraySourceSpectrum(wave=None, flux=None, waveunits='angstrom', fluxunits='photlam', name='UnnamedArraySpectrum', keepneg=False)

Bases: pysynphot.spectrum.TabularSourceSpectrum

Class to handle source spectrum from arrays.

Parameters:
  • flux (wave,) – Wavelength and flux arrays.
  • fluxunits (waveunits,) – Wavelength and flux units, as accepted by Units. Defaults are Angstrom and photlam.
  • name (str) – Description of the spectrum. Default is “UnnamedArraySpectrum”.
  • keepneg (bool) – Keep negative flux values instead of setting them to zero with a warning. Default is False.
name

Same as input.

warnings

dict – To store warnings.

isAnalytic

bool – This is always False.

waveunits, fluxunits

Units – User units for wavelength and flux.

wave, flux

array_like – Wavelength set and associated flux in user units.

Raises:ValueError – Mismatched wavelength and flux arrays.
class pysynphot.spectrum.FileSourceSpectrum(filename, fluxname=None, keepneg=False)

Bases: pysynphot.spectrum.TabularSourceSpectrum

Class to handle source spectrum loaded from ASCII or FITS table. Also see File I/O.

Parameters:
  • filename (str) – File with spectral data (can be ASCII or FITS).
  • fluxname (str or None) – Column name containing flux data. This is only used if the given file is in FITS format.
  • keepneg (bool) – Keep negative flux values instead of setting them to zero with a warning. Default is False.
name

str – Resolved filename; i.e., IRAF-style directory name is expanded to actual path name.

fheader

dict – For FITS file, this contains headers from both extensions 0 and 1. If the extensions have the same keyword, the one from the latter is used.

warnings

dict – To store warnings.

isAnalytic

bool – This is always False.

waveunits, fluxunits

Units – User units for wavelength and flux.

wave, flux

array_like – Wavelength set and associated flux in user units.

class pysynphot.spectrum.AnalyticSpectrum(waveunits='angstrom', fluxunits='photlam')

Bases: pysynphot.spectrum.SourceSpectrum

Base class for analytic source spectrum. This includes BlackBody, FlatSpectrum, GaussianSource, and Powerlaw.

Parameters:fluxunits (waveunits,) – Wavelength and flux units, as accepted by Units. Defaults are Angstrom and photlam.
warnings

dict – To store warnings.

isAnalytic

bool – This is always True.

waveunits, fluxunits

Units – User units for wavelength and flux.

wave, flux

array_like – Wavelength set and associated flux in user units.

GetWaveSet()

Return the wavelength set for the spectrum.

Returns:waveset – Wavelength set (a copy of the default wavelength table).
Return type:array_like
class pysynphot.spectrum.GaussianSource(flux, center, fwhm, waveunits='angstrom', fluxunits='flam')

Bases: pysynphot.spectrum.AnalyticSpectrum

Class to handle a Gaussian source.

Parameters:
  • flux (float) – Total flux under the Gaussian curve, in given flux unit.
  • center (float) – Central wavelength of the Gaussian curve, in given wavelength unit.
  • fwhm (float) – FWHM of the Gaussian curve, in given wavelength unit.
  • fluxunits (waveunits,) – Wavelength and flux units, as accepted by Units. Defaults are Angstrom and flam.
total_flux

Same as input flux.

center, fwhm

Same as inputs.

sigma, factor

float – These are \sigma and A as defined in Gaussian Emission.

name

str – Description of the spectrum.

warnings

dict – To store warnings.

isAnalytic

bool – This is always True.

waveunits, fluxunits

Units – User units for wavelength and flux.

wave, flux

array_like – Wavelength set and associated flux in user units.

GetWaveSet()

Return the wavelength set that optimally samples the Gaussian curve. It has 101 values, as defined below:

x_{\textnormal{first,last}} = x_{0} \; \pm \; 5 \; \sigma

\delta x = 0.1 \; \sigma

Returns:waveset – Wavelength set in internal unit.
Return type:array_like
class pysynphot.spectrum.FlatSpectrum(fluxdensity, waveunits='angstrom', fluxunits='photlam')

Bases: pysynphot.spectrum.AnalyticSpectrum

Class to handle a flat source spectrum.

Parameters:
  • fluxdensity (float) – The constant flux value in the given flux unit.
  • fluxunits (waveunits,) – Wavelength and flux units, as accepted by Units. Defaults are Angstrom and photlam.
name

str – Description of the spectrum.

warnings

dict – To store warnings.

isAnalytic

bool – This is always True.

waveunits, fluxunits

Units – User units for wavelength and flux.

wave, flux

array_like – Wavelength set and associated flux in user units.

redshift(z)

Apply redshift to the flat spectrum.

Unlike SourceSpectrum.redshift(), the redshifted spectrum remains an analytic flat source.

Parameters:z (number) – Redshift value.
Returns:ans
Return type:FlatSpectrum
class pysynphot.spectrum.Powerlaw(refwave, index, waveunits='angstrom', fluxunits='photlam')

Bases: pysynphot.spectrum.AnalyticSpectrum

Class to handle a power-law source spectrum.

Parameters:
  • refwave (number) – Reference wavelength in the given unit.
  • index (number) – Power-law index.
  • fluxunits (waveunits,) – Wavelength and flux units, as accepted by Units. Defaults are Angstrom and photlam.
name

str – Description of the spectrum.

warnings

dict – To store warnings.

isAnalytic

bool – This is always True.

waveunits, fluxunits

Units – User units for wavelength and flux.

wave, flux

array_like – Wavelength set and associated flux in user units.

class pysynphot.spectrum.BlackBody(temperature)

Bases: pysynphot.spectrum.AnalyticSpectrum

Class to handle a blackbody source.

Flux is evaluated with bbfunc() and normalized with pysynphot.spectrum.RENORM, which is:

\textnormal{RENORM} = \pi \; (\frac{R_{\odot}}{1 \; \textnormal{kpc}})^{2}

Parameters:temperature (number) – Blackbody temperature in Kelvin.
temperature

Same as input.

name

str – Description of the spectrum.

warnings

dict – To store warnings.

isAnalytic

bool – This is always True.

waveunits, fluxunits

Units – User units for wavelength and flux.

wave, flux

array_like – Wavelength set and associated flux in user units.

class pysynphot.spectrum.CompositeSourceSpectrum(source1, source2, operation)

Bases: pysynphot.spectrum.SourceSpectrum

Class to handle composite spectrum involving source spectra.

Parameters:
  • source2 (source1,) – One or both of the inputs must be source spectrum.
  • operation ({'add', 'multiply'}) – Math operation to perform.
component1, component2

Same as input source1 and source2.

operation

Same as input.

name

str – Short description of the spectrum.

warnings

dict – To store warnings, which are inherited from both input sources. If inputs have the same warning keyword, the one from source2 is used.

isAnalytic

bool – Flag to indicate whether this is an analytic spectrum. This is only True if both inputs are analytic.

primary_area

number or NoneArea of the telescope. This is inherited from either of the inputs, if available (not None). If inputs have different values, an exception is raised.

waveunits, fluxunits

Units – User units inherited from source1 (if available) or source2 (if not).

wave, flux

array_like – Wavelength set and associated flux in user units.

Raises:pysynphot.exceptions.IncompatibleSources – Input spectra have different telescope areas defined.
GetWaveSet()

Obtain the wavelength set for the composite spectrum. This is done by using MergeWaveSets() to form a union of wavelength sets from its components.

Returns:waveset – Composite wavelength set.
Return type:array_like
complist()

Return a list of all components and sub-components. This is for use with __iter__().

tabulate()

Return a simplified version of the spectrum.

Composite spectrum can be overly complicated when it has too many components and sub-components. This method copies the following into a simple (tabulated) source spectrum:

  • Name
  • Wavelength array and unit
  • Flux array and unit
Returns:sp – Tabulated source spectrum.
Return type:ArraySourceSpectrum
class pysynphot.spectrum.SpectralElement

Bases: pysynphot.spectrum.Integrator

This is the base class for all bandpasses and spectral elements (e.g., filter and detector response curves).

binset

None – This is reserved to be used by ObsModeBandpass.

GetThroughput()

Obtain throughput for the spectrum.

Returns:throughput – Throughput values.
Return type:array_like
GetWaveSet()

Obtain the wavelength set for the spectrum.

Returns:wave – Wavelength set in internal unit.
Return type:array_like
avgwave()

Calculate Bandpass Average Wavelength.

Returns:ans – Average wavelength.
Return type:float
check_overlap(other)

Check overlap with another spectrum. Also see Overlap Checks.

This checks whether the wavelength set of the given spectrum is defined everywhere within self. Wavelength values where throughput is zero are excluded from the check. Typical use case is for checking whether a source spectrum is fully defined over the range of a bandpass. This check is asymmetric in the sense that if self is fully defined within the given spectrum, but not the other way around, it will still only return “partial”. If the given spectrum is analytic, the result is always “full”.

Example of full overlap:

|---------- other ----------|
   |------ self ------|

Examples of partial overlap:

|---------- self ----------|
   |------ other ------|

|---- other ----|
   |---- self ----|

|---- self ----|
   |---- other ----|

Examples of no overlap:

|---- self ----|  |---- other ----|

|---- other ----|  |---- self ----|
Parameters:other (SourceSpectrum or SpectralElement) – The other spectrum.
Returns:ans – Overlap status.
Return type:{‘full’, ‘partial’, ‘none’}
check_sig(other)

Check overlap insignificance with another spectrum. Also see Overlap Checks.

Note

Only use when check_overlap() returns “partial”.

Parameters:other (SourceSpectrum or SpectralElement) – The other spectrum.
Returns:ansTrue means the lack of overlap is insignificant (i.e., okay to proceed).
Return type:bool
convert(targetunits)

Set new user unit, for wavelength only.

This effectively converts the spectrum wavelength to given unit. Note that actual data are always kept in internal unit (Angstrom), and only converted to user unit by GetWaveSet() during actual computation. User unit is stored in self.waveunits. Throughput is unitless and cannot be converted.

Parameters:targetunits (str) – New unit name, as accepted by Units.
efficiency()

Calculate Bandpass Dimensionless Efficiency.

Returns:ans – Bandpass dimensionless efficiency.
Return type:float
equivwidth()

Calculate Bandpass Equivalent Width. This basically just calls integrate().

Returns:ans – Bandpass equivalent width.
Return type:float
integrate(wave=None)

Integrate the throughput over the specified wavelength set. If no wavelength set is specified, the built-in one is used.

Integration is done using trapezoidIntegration() with x=wave and y=throughput. Also see Bandpass Equivalent Width.

Parameters:wave (array_like or None) – Wavelength set for integration.
Returns:ans – Integrated sum.
Return type:float
photbw(floor=0)

Calculate Bandpass RMS Band Width (SYNPHOT).

Note

For backward-compatibility with IRAF STSDAS SYNPHOT only.

Parameters:floor (float) – Same as rmswidth().
Returns:ans – RMS band width (deprecated).
Return type:float
pivot(binned=False)

Calculate Pivot Wavelength.

Parameters:binned (bool) – This is reserved for use by Observation. If True, binned wavelength set is used. Default is False.
Returns:ans – Pivot wavelength.
Return type:float
Raises:AttributeError – Binned wavelength set requested but not found.
rectwidth()

Calculate Bandpass Rectangular Width.

Returns:ans – Bandpass rectangular width.
Return type:float
resample(resampledWaveTab)

Resample the spectrum for the given wavelength set.

Given wavelength array must be monotonically increasing or decreasing. Throughput interpolation is done using numpy.interp().

Parameters:resampledWaveTab (array_like) – Wavelength set for resampling.
Returns:resampled – Resampled spectrum.
Return type:ArraySpectralElement
rmswidth(floor=0)

Calculate Bandpass RMS Band Width (Koornneef).

Parameters:floor (float) – Throughput values equal or below this threshold are not included in the calculation. By default (0), all points are included.
Returns:ans – RMS band width.
Return type:float
sample(wave)

Sample the spectrum.

This uses resample() to do the actual computation.

Parameters:wave (number or array_like) – Wavelength set for sampling, given in user unit.
Returns:throughput – Sampled throughput.
Return type:number or array_like
taper()

Taper the spectrum by adding zero throughput to each end. This is similar to TabularSourceSpectrum.taper().

There is no check to see if the spectrum is already tapered. Hence, calling this on a tapered spectrum will result in multiple zero-throughput entries at both ends.

The wavelengths to use for the new first and last points are calculated by using the same ratio as for the two interior points used at each end.

Returns:OutElement – Tapered spectrum.
Return type:TabularSpectralElement
throughput

Throughput property.

unit_response()

Calculate Bandpass Unit Response.

Warning

Result is correct only if self.waveunits is in Angstrom.

Returns:ans – Bandpass unit response.
Return type:float
validate_units()

Ensure that wavelenth unit belongs to the correct class. There is no check for throughput because it is unitless.

Raises:TypeError – Wavelength unit is not WaveUnits.
wave

Wavelength property.

writefits(filename, clobber=True, trimzero=True, precision=None, hkeys=None)

Write the spectrum to a FITS table.

Primary header in EXT 0. FILENAME, ORIGIN, and any extra keyword(s) from hkeys will also be added.

Table header and data are in EXT 1. The table has 2 columns, i.e., WAVELENGTH and THROUGHPUT. Wavelength data are stored in user unit. Its header also will have these additional keywords:

  • EXPR - Description of the spectrum.
  • TDISP1 and TDISP2 - Columns display format, always “G15.7”.
  • GRFTABLE and CMPTABLE - Graph and component table names to use with associated observation mode. These are only added if applicable.

If data is already double-precision but user explicitly set output precision to single, pysynphot.spectrum.syn_epsilon defines the allowed minimum wavelength separation. This limit (3.2 \times 10^{-4}) was taken from IRAF STSDAS SYNPHOT FAQ. Values equal or smaller than this limit are considered as the same, and duplicates are ignored, resulting in data loss. In the way that this comparison is coded, when such precision clash happens, even when no duplicates are detected, the last row is always omitted (also data loss). Therefore, it is not recommended for user to force single-precision when the data is in double-precision.

Parameters:
  • filename (str) – Output filename.
  • clobber (bool) – Overwrite existing file. Default is True.
  • trimzero (bool) – Trim off duplicate rows with flux values of zero from both ends of the spectrum. This keeps one row of zero-flux at each end, if it exists; However, it does not add a zero-flux row if it does not. Default is True.
  • precision ({‘s’, ‘d’, None}) – Write data out in single ('s') or double ('d') precision. Default is None, which will enforce native precision from self.throughput.
  • hkeys (dict) – Additional keyword(s) to be added to primary FITS header, in the format of {keyword:(value,comment)}.
class pysynphot.spectrum.TabularSpectralElement(fileName=None, thrucol='throughput')

Bases: pysynphot.spectrum.SpectralElement

Base class for ArraySpectralElement and FileSpectralElement.

Parameters:
  • fileName (str or None) – File with spectral data (can be ASCII or FITS). If not None, data will be loaded from file at initialization.
  • thrucol (str) – Column name containing throughput data. Default is “throughput” (case-insensitive). This is only used if filename is given and is of FITS format.
name

Same as input fileName.

warnings

dict – To store warnings.

isAnalytic

bool – This is always False.

binset

None – This is reserved to be used by ObsModeBandpass.

waveunits

Units – User unit for wavelength.

throughputunits

{‘none’, None} – This is only to inform user that throughput is unitless.

wave, throughput

array_like – Wavelength set in user unit and associated unitless throughput.

class pysynphot.spectrum.ArraySpectralElement(wave=None, throughput=None, waveunits='angstrom', name='UnnamedArrayBandpass')

Bases: pysynphot.spectrum.TabularSpectralElement

Class to handle bandpass from arrays.

Parameters:
  • throughput (wave,) – Wavelength and throughput arrays.
  • waveunits (str) – Wavelength unit, as accepted by Units. Default is Angstrom.
  • name (str) – Description of the spectrum. Default is “UnnamedArrayBandpass”.
name

Same as input.

warnings

dict – To store warnings.

isAnalytic

bool – This is always False.

binset

None – This is reserved to be used by ObsModeBandpass.

waveunits

Units – User unit for wavelength.

wave, throughput

array_like – Wavelength set in user unit and associated unitless throughput.

Raises:ValueError – Mismatched wavelength and throughput arrays.
class pysynphot.spectrum.FileSpectralElement(filename, thrucol=None)

Bases: pysynphot.spectrum.TabularSpectralElement

Class to handle bandpass loaded from ASCII or FITS table. Also see File I/O.

Parameters:
  • filename (str) – File with spectral data (can be ASCII or FITS).
  • thrucol (str or None) – Column name containing throughput data. This is only used if the given file is in FITS format.
name

str – Resolved filename; i.e., IRAF-style directory name is expanded to actual path name.

fheader

dict – For FITS file, this contains headers from both extensions 0 and 1. If the extensions have the same keyword, the one from the latter is used.

warnings

dict – To store warnings.

isAnalytic

bool – This is always False.

binset

None – This is reserved to be used by ObsModeBandpass.

waveunits

Units – User unit for wavelength.

wave, throughput

array_like – Wavelength set in user unit and associated unitless throughput.

class pysynphot.spectrum.InterpolatedSpectralElement(fileName, wavelength)

Bases: pysynphot.spectrum.SpectralElement

Class to handle parameterized keyword in an observation mode.

Parameters:
  • fileName (str) – Filename followed by a column name specification between square brackets. For example: “mythru_syn.fits[fr388n#]”
  • wavelength (number) – Desired value to interpolate to. This is not restricted to wavelength, but rather whatever parameter the file is parameterized for.
name

str – Expanded filename.

interpval

Same as input wavelength.

warnings

dict – To store warnings. When extrapolation is not allowed but a default throughput column is present and used, warnings['DefaultThroughput'] is set to True.

isAnalytic

bool – This is always False.

binset

None – This is reserved to be used by ObsModeBandpass.

waveunits

Units – User unit for wavelength.

throughputunits

‘none’ – This is only to inform user that throughput is unitless.

wave, throughput

array_like – Wavelength set in user unit and associated unitless throughput.

Raises:
class pysynphot.spectrum.UniformTransmission(value, waveunits='angstrom')

Bases: pysynphot.spectrum.SpectralElement

Class to handle a uniform bandpass.

Parameters:
  • value (number) – Constant throughput value for the bandpass.
  • waveunits (str) – Wavelength unit, as accepted by Units. Default is Angstrom.
value

Same as input.

name

str – Short description of the spectrum.

warnings

dict – To store warnings.

isAnalytic

bool – This is always True.

binset

None – This is reserved to be used by ObsModeBandpass.

waveunits

Units – User unit for wavelength.

wave, throughput

array_like – Wavelength set in user unit and associated unitless throughput.

GetWaveSet()

Obtain wavelength set for the spectrum.

Returns:waveset – Due to the nature of uniform transmission, this is always undefined.
Return type:None
wave

waveset for uniform transmission.

writefits(*args, **kwargs)

Write to file using default waveset.

class pysynphot.spectrum.Box(center, width, waveunits=None)

Bases: pysynphot.spectrum.SpectralElement

Class to handle a box-shaped bandpass.

Parameters:
  • width (center,) – Center and width of the box in the given wavelength unit.
  • waveunits (str or None) – Wavelength unit, as accepted by Units. If not given, assumed to be in Angstrom.
name

str – Description of the spectrum.

warnings

dict – To store warnings.

isAnalytic

bool – This is always False.

binset

None – This is reserved to be used by ObsModeBandpass.

waveunits

Units – User unit for wavelength.

wave, throughput

array_like – Wavelength set in user unit and associated unitless throughput.

resample(resampledWaveTab)

Resample the spectrum for the given wavelength set.

Given wavelength array must be monotonically increasing or decreasing.

Parameters:resampledWaveTab (array_like) – Wavelength set for resampling.
Returns:resampled – Resampled spectrum. This is no longer a real Box spectrum.
Return type:ArraySpectralElement
sample(wavelength)

Input wavelengths assumed to be in user unit.

class pysynphot.spectrum.ThermalSpectralElement(fileName)

Bases: pysynphot.spectrum.TabularSpectralElement

Class to handle spectral element with thermal properties read from a FITS table.

Note

This class does not know how to apply itself to an existing beam. Its emissivity is handled by ThermalSpectrum().

Parameters:fileName (str) – Filename of the thermal emissivity table.
name

Same as input fileName.

temperature

number – Default temperature in Kelvin from header.

beamFillFactor

number – Beam filling factor from header.

warnings

dict – To store warnings.

isAnalytic

bool – This is always False.

binset

None – This is reserved to be used by ObsModeBandpass.

waveunits

Units – User unit for wavelength.

throughputunits

‘none’ – This is only to inform user that throughput is unitless.

wave, throughput

array_like – Wavelength set in user unit and associated unitless emissivity.

class pysynphot.spectrum.CompositeSpectralElement(component1, component2)

Bases: pysynphot.spectrum.SpectralElement

Class to handle composite spectrum involving bandpasses.

Parameters:component2 (component1,) – Input bandpass.
component1, component2

Same as inputs.

name

str – Short description of the spectrum.

isAnalytic

bool – Flag to indicate whether this is an analytic spectrum. This is only True if both inputs are analytic.

warnings

dict – To store warnings, which are inherited from both input sources. If inputs have the same warning keyword, the one from component2 is used.

primary_area

number or NoneArea of the telescope. This is inherited from either of the inputs, if available (not None). If inputs have different values, an exception is raised.

binset

None – This is reserved to be used by ObsModeBandpass.

waveunits

Units – User unit inherited from inputs, where both inputs are required to have the same unit or an exception will be raised.

throughputunits

None – This is only to inform user that throughput is unitless.

wave, throughput

array_like – Wavelength set in user unit and associated unitless throughput.

Raises:
  • NotImplementedError – Inputs have different wavelength units.
  • TypeError – Both input spectra must be bandpasses.
  • pysynphot.exceptions.IncompatibleSources – Input spectra have different telescope areas defined.
GetWaveSet()

Obtain the wavelength set for the composite spectrum. This is done by using MergeWaveSets() to form a union of wavelength sets from its components.

Returns:waveset – Composite wavelength set.
Return type:array_like
complist()

Return a list of all components and sub-components.

pysynphot.spectrum.MergeWaveSets(waveset1, waveset2)

Return the union of the two wavelength sets.

The union is computed using numpy.union1d, unless one or both of them is None.

The merged result may sometimes contain numbers which are nearly equal but differ at levels as small as 1E-14. Having values this close together can cause problems due to effectively duplicate wavelength values. Therefore, wavelength values having differences smaller than or equal to pysynphot.spectrum.MERGETHRESH (defaults to 1E-12) are considered as the same.

Parameters:waveset2 (waveset1,) – Wavelength sets to combine.
Returns:MergedWaveSet – Merged wavelength set. It is None if both inputs are such.
Return type:array_like or None
pysynphot.spectrum.trimSpectrum(sp, minw, maxw)

Create a new spectrum with trimmed upper and lower ranges.

Parameters:
  • sp (SourceSpectrum) – Spectrum to trim.
  • maxw (minw,) – Lower and upper limits (inclusive) for the wavelength set in the trimmed spectrum.
Returns:

result – Trimmed spectrum.

Return type:

TabularSourceSpectrum

pysynphot.spparser

This module implements the Language Parser. It uses pysynphot.spark.

pysynphot.tables

This module handles graph and component tables. They are discussed in detail in Appendix C: TMG, TMC, and TMT Files.

class pysynphot.tables.GraphTable(GFile=None)

Class to handle a graph table.

Parameters:GFile (str) – Graph table filename.
keywords

array_like – Values from KEYWORD column in EXT 1, converted to lowercase.

innodes, outnodes, compnames, thcompnames

array_like – Values from INNODE, OUTNODE, COMPNAME, and THCOMPNAME columns in EXT 1.

primary_area

number – Value from PRIMAREA in EXT 0 header, if exists.

Raises:TypeError – No filename given.
GetComponentsFromGT(modes, innode)

Obtain components from graph table for the given observation mode keywords and starting node.

Note

This prints extra information to screen if pysynphot.tables.DEBUG is set to True.

Parameters:
  • modes (list of str) – List of individual keywords within the observation mode.
  • innode (int) – Starting node, usually 1.
Returns:

components, thcomponents – List of optical and thermal component names.

Return type:

list of str

Raises:
  • KeyError – No matches found for one of the keywords.
  • ValueError – Incomplete observation mode or unused keyword(s) detected.
class pysynphot.tables.CompTable(CFile=None)

Class to handle a component table.

Parameters:CFile (str) – Component table filename.
name

Same as input CFile.

compnames, filenames

array_like – Values from COMPNAME and FILENAME columns in EXT 1.

Raises:TypeError – No filename given.

pysynphot.units

This module handles wavelength and flux units. Constants used for unit conversion are also defined here.

pysynphot.units.Units(uname)

Generate a unit object.

Parameters:uname (str) – Wavelength or flux unit name.
Returns:unit – Unit object. None means unitless.
Return type:BaseUnit or None
Raises:ValueError – Unknown unit name.
Inheritance diagram of pysynphot.units
class pysynphot.units.BaseUnit(uname)

Base class for all units.

Parameters:uname (str) – Unit name.
name

Same as input uname.

Dispatch

dict or None – This is used by sub-classes for unit conversion by mapping target unit name to the relevant conversion method.

Convert(wave, flux, target_units)

Perform unit conversion.

Note

This is only applicable to some of the available flux conversions. All other sub-classes must re-implement this method.

Parameters:
  • flux (wave,) – Wavelength and flux values to be used for conversion.
  • target_units (str) – Unit to convert to.
Returns:

result – Converted values.

Return type:

number or array_like

Raises:

TypeError – Conversion to given unit is not allowed.

class pysynphot.units.WaveUnits

Bases: pysynphot.units.BaseUnit

Base unit for wavelength.

Since Angstrom is the internal unit used by pysynphot calculations, a wavelength unit can always convert to/from Angstrom. Conversion between two arbitrary units uses Angstrom as the intermediate unit.

name

None – To be set by sub-class of a specific wavelength unit.

Dispatch

dict – Defines conversion to Angstrom.

isFlux

bool – This is always False.

Convert(wave, target_units)

Perform unit conversion.

Parameters:
  • wave (number or array_like) – Wavelength values to be used for conversion.
  • target_units (str) – Unit to convert to.
Returns:

result – Converted values.

Return type:

number or array_like

Raises:

TypeError – Conversion to given unit is not allowed.

class pysynphot.units.Angstrom

Bases: pysynphot.units.WaveUnits

Class to handle Angstrom unit.

Since Angstrom is the internal wavelength unit, it can convert to all the other supported units.

name

str – This is always ‘angstrom’.

Dispatch

dict – Defines conversion to all supported wavelength units.

isFlux

bool – This is always False.

ToAngstrom(wave)

Convert to Angstrom.

Since there is no real conversion necessary, this returns a copy of input (if array) or just the input (if scalar). An input array is copied to avoid modifying the input in subsequent pysynphot processing.

Parameters:wave (number or array_like) – Wavelength values to be used for conversion.
Returns:result – Converted values.
Return type:number or array_like
ToCm(wave)

Convert to cm.

\textnormal{cm} = 10^{-8} \; \AA

Parameters:wave (number or array_like) – Wavelength values to be used for conversion.
Returns:result – Converted values.
Return type:number or array_like
ToHz(wave)

Convert to Hz.

\textnormal{Hz} = \frac{c}{\AA}

where c is as defined in Constants.

Parameters:wave (number or array_like) – Wavelength values to be used for conversion.
Returns:result – Converted values.
Return type:number or array_like
ToInverseMicron(wave)

Convert to inverse micron.

\mu \textnormal{m}^{-1} = 10^{4} \; \AA^{-1}

Parameters:wave (number or array_like) – Wavelength values to be used for conversion.
Returns:result – Converted values.
Return type:number or array_like
ToMeter(wave)

Convert to meter.

\textnormal{m} = 10^{-10} \; \AA

Parameters:wave (number or array_like) – Wavelength values to be used for conversion.
Returns:result – Converted values.
Return type:number or array_like
ToMicron(wave)

Convert to micron.

\mu \textnormal{m} = 10^{-4} \; \AA

Parameters:wave (number or array_like) – Wavelength values to be used for conversion.
Returns:result – Converted values.
Return type:number or array_like
ToMm(wave)

Convert to mm.

\textnormal{mm} = 10^{-7} \; \AA

Parameters:wave (number or array_like) – Wavelength values to be used for conversion.
Returns:result – Converted values.
Return type:number or array_like
ToNm(wave)

Convert to nm.

\textnormal{nm} = 10^{-1} \; \AA

Parameters:wave (number or array_like) – Wavelength values to be used for conversion.
Returns:result – Converted values.
Return type:number or array_like
class pysynphot.units.Hz

Bases: pysynphot.units.WaveUnits

Class to handle Hz unit.

name

str – This is always ‘hz’.

Dispatch

dict – Defines conversion to Angstrom.

isFlux

bool – This is always False.

ToAngstrom(wave)

Convert to Angstrom.

\AA = \frac{c}{\textnormal{Hz}}

where c is as defined in Constants.

Parameters:wave (number or array_like) – Wavelength values to be used for conversion.
Returns:result – Converted values.
Return type:number or array_like
class pysynphot.units.InverseMicron

Bases: pysynphot.units.WaveUnits

Class to handle inverse micron unit.

name

str – This is always ‘1/um’.

Dispatch

dict – Defines conversion to Angstrom.

isFlux

bool – This is always False.

ToAngstrom(wave)

Convert to Angstrom.

\AA = \frac{10^{4}}{\mu \textnormal{m}^{-1}}

Parameters:wave (number or array_like) – Wavelength values to be used for conversion.
Returns:result – Converted values.
Return type:number or array_like
class pysynphot.units._MetricWavelength

Bases: pysynphot.units.WaveUnits

Class to handle meter unit and its prefixes.

Note

Angstrom is not a sub-class of this because as an internal unit, it requires special handling.

name

None – To be set by sub-class of a specific wavelength unit.

Dispatch

dict – Defines conversion to Angstrom.

isFlux

bool – This is always False.

ToAngstrom(wave)

Convert to Angstrom.

Conversion is simply the input values multiplied by a factor specific to its sub-class.

Parameters:wave (number or array_like) – Wavelength values to be used for conversion.
Returns:result – Converted values.
Return type:number or array_like
class pysynphot.units.Nm

Bases: pysynphot.units._MetricWavelength

Class to handle nm unit.

name

str – This is always ‘nm’.

Dispatch

dict – Defines conversion to Angstrom.

isFlux

bool – This is always False.

factor

float – Conversion factor. This is always 10.

class pysynphot.units.Micron

Bases: pysynphot.units._MetricWavelength

Class to handle micron unit.

name

str – This is always ‘micron’.

Dispatch

dict – Defines conversion to Angstrom.

isFlux

bool – This is always False.

factor

float – Conversion factor. This is always 10^{4}.

class pysynphot.units.Mm

Bases: pysynphot.units._MetricWavelength

Class to handle mm unit.

name

str – This is always ‘mm’.

Dispatch

dict – Defines conversion to Angstrom.

isFlux

bool – This is always False.

factor

float – Conversion factor. This is always 10^{7}.

class pysynphot.units.Cm

Bases: pysynphot.units._MetricWavelength

Class to handle cm unit.

name

str – This is always ‘cm’.

Dispatch

dict – Defines conversion to Angstrom.

isFlux

bool – This is always False.

factor

float – Conversion factor. This is always 10^{8}.

class pysynphot.units.Meter

Bases: pysynphot.units._MetricWavelength

Class to handle meter unit.

name

str – This is always ‘m’.

Dispatch

dict – Defines conversion to Angstrom.

isFlux

bool – This is always False.

factor

float – Conversion factor. This is always 10^{10}.

class pysynphot.units.FluxUnits

Bases: pysynphot.units.BaseUnit

Base unit for flux.

Since photlam is the internal unit used by pysynphot calculations, a flux unit can always convert to/from photlam. Conversion between two arbitrary units uses photlam as the intermediate unit.

Note

To support source spectrum renormalization without introducing circular import, all supported flux units must have their StdSpectrum attributes defined separately in DefineStdSpectraForUnits().

name

None – To be set by sub-class of a specific flux unit.

Dispatch

dict – Defines conversion to photlam.

isFlux

bool – This is always True.

isMag

bool – This is True if this is a magnitude.

isDensity

bool – This is True except for counts and obmag.

nativewave

WaveUnits – Native wavelength unit associated with the flux unit. This is for informational purpose only.

Convert(wave, flux, target_units, area=None)

Perform unit conversion.

Parameters:
  • flux (wave,) – Wavelength and flux values to be used for conversion.
  • target_units (str) – Unit to convert to.
  • area (number or None) – Telescope area, if applicable. This is only needed for conversions involving counts or obmag.
Returns:

result – Converted values.

Return type:

number or array_like

Raises:

TypeError – Conversion to given unit is not allowed.

class pysynphot.units.Photlam

Bases: pysynphot.units.FluxUnits

Class to handle photlam unit.

Since photlam is the internal flux unit, it can convert to all the other supported units.

\textnormal{photlam} = \textnormal{photon} \; \textnormal{s}^{-1} \; \textnormal{cm}^{-2} \; \AA^{-1}

name

str – This is always ‘photlam’.

Dispatch

dict – Defines conversion to all supported flux units.

isFlux, isDensity

bool – This is always True.

isMag

bool – This is always False.

nativewave

WaveUnits – This is Angstrom by default. (Not used.)

ToABMag(wave, flux, **kwargs)

Convert to abmag.

\textnormal{AB}_{\nu} = -2.5 \; \log(h \lambda \; \textnormal{photlam}) - 48.6

where h is as defined in Constants.

Parameters:
  • flux (wave,) – Wavelength and flux values to be used for conversion.
  • kwargs (dict) – Extra keywords (not used).
Returns:

result – Converted values.

Return type:

number or array_like

ToCounts(wave, flux, area=None)

Convert to counts.

\textnormal{counts} = \delta \lambda \; \times \; \textnormal{area} \; \times  \; \textnormal{photlam}

where \delta \lambda represent bin widths derived from calculate_bin_edges() and calculate_bin_widths(), using the input wavelength values as bin centers.

Parameters:
  • flux (wave,) – Wavelength and flux values to be used for conversion.
  • area (number or None) – Telescope collecting area. If not given, default value from Reference Data is used.
Returns:

result – Converted values.

Return type:

number or array_like

ToFlam(wave, flux, **kwargs)

Convert to flam.

\textnormal{flam} = \frac{hc}{\lambda} \; \textnormal{photlam}

where h and c are as defined in Constants.

Parameters:
  • flux (wave,) – Wavelength and flux values to be used for conversion.
  • kwargs (dict) – Extra keywords (not used).
Returns:

result – Converted values.

Return type:

number or array_like

ToFnu(wave, flux, **kwargs)

Convert to fnu.

\textnormal{fnu} = h \lambda \; \textnormal{photlam}

where h is as defined in Constants.

Parameters:
  • flux (wave,) – Wavelength and flux values to be used for conversion.
  • kwargs (dict) – Extra keywords (not used).
Returns:

result – Converted values.

Return type:

number or array_like

ToJy(wave, flux, **kwargs)

Convert to Jy.

\textnormal{Jy} = 10^{23} h \lambda \; \textnormal{photlam}

where h is as defined in Constants.

Parameters:
  • flux (wave,) – Wavelength and flux values to be used for conversion.
  • kwargs (dict) – Extra keywords (not used).
Returns:

result – Converted values.

Return type:

number or array_like

ToOBMag(wave, flux, area=None)

Convert to obmag.

\textnormal{obmag} = -2.5 \; \log(\delta \lambda \; \times \; \textnormal{area} \; \times  \; \textnormal{photlam})

where \delta \lambda represent bin widths derived from calculate_bin_edges() and calculate_bin_widths(), using the input wavelength values as bin centers.

Parameters:
  • flux (wave,) – Wavelength and flux values to be used for conversion.
  • area (number or None) – Telescope collecting area. If not given, default value from Reference Data is used.
Returns:

result – Converted values.

Return type:

number or array_like

ToPhotlam(wave, flux, **kwargs)

Convert to photlam.

Since there is no real conversion necessary, this returns a copy of input flux (if array) or just the input (if scalar). An input array is copied to avoid modifying the input in subsequent pysynphot processing.

Parameters:
  • flux (wave,) – Wavelength (not used) and flux values to be used for conversion.
  • kwargs (dict) – Extra keywords (not used).
Returns:

result – Converted values.

Return type:

number or array_like

ToPhotnu(wave, flux, **kwargs)

Convert to photnu.

\textnormal{photnu} = \frac{\lambda^{2}}{c} \; \textnormal{photlam}

where c is as defined in Constants.

Parameters:
  • flux (wave,) – Wavelength and flux values to be used for conversion.
  • kwargs (dict) – Extra keywords (not used).
Returns:

result – Converted values.

Return type:

number or array_like

ToSTMag(wave, flux, **kwargs)

Convert to stmag.

\textnormal{ST}_{\lambda} = -2.5 \; \log(\frac{hc}{\lambda} \; \textnormal{photlam}) - 21.1

where h and c are as defined in Constants.

Parameters:
  • flux (wave,) – Wavelength and flux values to be used for conversion.
  • kwargs (dict) – Extra keywords (not used).
Returns:

result – Converted values.

Return type:

number or array_like

ToVegaMag(wave, flux, **kwargs)

Convert to vegamag.

\textnormal{vegamag} = -2.5 \; \log(\frac{\textnormal{photlam}}{f_{\textnormal{Vega}}})

where f_{\textnormal{Vega}} is the flux of Vega resampled at given wavelength values and converted to photlam.

Parameters:
  • flux (wave,) – Wavelength and flux values to be used for conversion.
  • kwargs (dict) – Extra keywords (not used).
Returns:

result – Converted values.

Return type:

number or array_like

TomJy(wave, flux, **kwargs)

Convert to mJy.

\textnormal{mJy} = 10^{26} h \lambda \; \textnormal{photlam}

where h is as defined in Constants.

Parameters:
  • flux (wave,) – Wavelength and flux values to be used for conversion.
  • kwargs (dict) – Extra keywords (not used).
Returns:

result – Converted values.

Return type:

number or array_like

TomuJy(wave, flux, **kwargs)

Convert to \mu \textnormal{Jy}.

\mu \textnormal{Jy} = 10^{29} h \lambda \; \textnormal{photlam}

where h is as defined in Constants.

Parameters:
  • flux (wave,) – Wavelength and flux values to be used for conversion.
  • kwargs (dict) – Extra keywords (not used).
Returns:

result – Converted values.

Return type:

number or array_like

TonJy(wave, flux, **kwargs)

Convert to nJy.

\textnormal{nJy} = 10^{32} h \lambda \; \textnormal{photlam}

where h is as defined in Constants.

Parameters:
  • flux (wave,) – Wavelength and flux values to be used for conversion.
  • kwargs (dict) – Extra keywords (not used).
Returns:

result – Converted values.

Return type:

number or array_like

class pysynphot.units.Flam

Bases: pysynphot.units.FluxUnits

Class to handle flam unit.

\textnormal{flam} = \textnormal{erg} \; \textnormal{s}^{-1} \; \textnormal{cm}^{-2} \; \AA^{-1}

name

str – This is always ‘flam’.

Dispatch

dict – Defines conversion to photlam.

isFlux, isDensity

bool – This is always True.

isMag

bool – This is always False.

nativewave

WaveUnits – This is Angstrom by default. (Not used.)

ToPhotlam(wave, flux, **kwargs)

Convert to photlam.

\textnormal{photlam} = \frac{\lambda}{hc} \; \textnormal{flam}

where h and c are as defined in Constants.

Parameters:
  • flux (wave,) – Wavelength and flux values to be used for conversion.
  • kwargs (dict) – Extra keywords (not used).
Returns:

result – Converted values.

Return type:

number or array_like

class pysynphot.units.Photnu

Bases: pysynphot.units.FluxUnits

Class to handle photnu unit.

\textnormal{photnu} = \textnormal{photon} \; \textnormal{s}^{-1} \; \textnormal{cm}^{-2} \; \textnormal{Hz}^{-1}

name

str – This is always ‘photnu’.

Dispatch

dict – Defines conversion to photlam.

isFlux, isDensity

bool – This is always True.

isMag

bool – This is always False.

nativewave

WaveUnits – This is Hz by default. (Not used.)

ToPhotlam(wave, flux, **kwargs)

Convert to photlam.

\textnormal{photlam} = \frac{c}{\lambda^{2}} \; \textnormal{photnu}

where c is as defined in Constants.

Parameters:
  • flux (wave,) – Wavelength and flux values to be used for conversion.
  • kwargs (dict) – Extra keywords (not used).
Returns:

result – Converted values.

Return type:

number or array_like

class pysynphot.units.Fnu

Bases: pysynphot.units.FluxUnits

Class to handle fnu unit.

\textnormal{fnu} = \textnormal{erg} \; \textnormal{s}^{-1} \textnormal{cm}^{-2} \textnormal{Hz}^{-1}

name

str – This is always ‘fnu’.

Dispatch

dict – Defines conversion to photlam.

isFlux, isDensity

bool – This is always True.

isMag

bool – This is always False.

nativewave

WaveUnits – This is Hz by default. (Not used.)

ToPhotlam(wave, flux, **kwargs)

Convert to photlam.

\textnormal{photlam} = \frac{1}{h \lambda} \; \textnormal{fnu}

where h is as defined in Constants.

Parameters:
  • flux (wave,) – Wavelength and flux values to be used for conversion.
  • kwargs (dict) – Extra keywords (not used).
Returns:

result – Converted values.

Return type:

number or array_like

class pysynphot.units.Jy

Bases: pysynphot.units.FluxUnits

Class to handle Jy unit.

\textnormal{Jy} = 10^{-23} \; \textnormal{erg} \; \textnormal{s}^{-1} \; \textnormal{cm}^{-2} \textnormal{Hz}^{-1}

name

str – This is always ‘jy’.

Dispatch

dict – Defines conversion to photlam.

isFlux, isDensity

bool – This is always True.

isMag

bool – This is always False.

nativewave

WaveUnits – This is Hz by default. (Not used.)

ToPhotlam(wave, flux, **kwargs)

Convert to photlam.

\textnormal{photlam} = \frac{10^{-23}}{h \lambda} \; \textnormal{Jy}

where h is as defined in Constants.

Parameters:
  • flux (wave,) – Wavelength and flux values to be used for conversion.
  • kwargs (dict) – Extra keywords (not used).
Returns:

result – Converted values.

Return type:

number or array_like

class pysynphot.units.mJy

Bases: pysynphot.units.FluxUnits

Class to handle mJy unit.

\textnormal{mJy} = 10^{-26} \; \textnormal{erg} \; \textnormal{s}^{-1} \; \textnormal{cm}^{-2} \textnormal{Hz}^{-1}

name

str – This is always ‘mjy’.

Dispatch

dict – Defines conversion to photlam.

isFlux, isDensity

bool – This is always True.

isMag

bool – This is always False.

nativewave

WaveUnits – This is Hz by default. (Not used.)

ToPhotlam(wave, flux, **kwargs)

Convert to photlam.

\textnormal{photlam} = \frac{10^{-26}}{h \lambda} \; \textnormal{mJy}

where h is as defined in Constants.

Parameters:
  • flux (wave,) – Wavelength and flux values to be used for conversion.
  • kwargs (dict) – Extra keywords (not used).
Returns:

result – Converted values.

Return type:

number or array_like

class pysynphot.units.muJy

Bases: pysynphot.units.FluxUnits

Class to handle \mu \textnormal{Jy} unit.

\mu \textnormal{Jy} = 10^{-29} \; \textnormal{erg} \; \textnormal{s}^{-1} \; \textnormal{cm}^{-2} \textnormal{Hz}^{-1}

name

str – This is always ‘mujy’.

Dispatch

dict – Defines conversion to photlam.

isFlux, isDensity

bool – This is always True.

isMag

bool – This is always False.

nativewave

WaveUnits – This is Hz by default. (Not used.)

ToPhotlam(wave, flux, **kwargs)

Convert to photlam.

\textnormal{photlam} = \frac{10^{-29}}{h \lambda} \; \mu \textnormal{Jy}

where h is as defined in Constants.

Parameters:
  • flux (wave,) – Wavelength and flux values to be used for conversion.
  • kwargs (dict) – Extra keywords (not used).
Returns:

result – Converted values.

Return type:

number or array_like

class pysynphot.units.nJy

Bases: pysynphot.units.FluxUnits

Class to handle nJy unit.

\textnormal{nJy} = 10^{-32} \; \textnormal{erg} \; \textnormal{s}^{-1} \; \textnormal{cm}^{-2} \textnormal{Hz}^{-1}

name

str – This is always ‘njy’.

Dispatch

dict – Defines conversion to photlam.

isFlux, isDensity

bool – This is always True.

isMag

bool – This is always False.

nativewave

WaveUnits – This is Hz by default. (Not used.)

ToPhotlam(wave, flux, **kwargs)

Convert to photlam.

\textnormal{photlam} = \frac{10^{-32}}{h \lambda} \; \textnormal{nJy}

where h is as defined in Constants.

Parameters:
  • flux (wave,) – Wavelength and flux values to be used for conversion.
  • kwargs (dict) – Extra keywords (not used).
Returns:

result – Converted values.

Return type:

number or array_like

class pysynphot.units.Counts

Bases: pysynphot.units.FluxUnits

Class to handle counts unit. See Counts and Magnitudes for more details.

name

str – This is always ‘counts’.

Dispatch

dict – Defines conversion to photlam.

isFlux

bool – This is always True.

isMag, isDensity

bool – This is always False.

nativewave

WaveUnits – This is Angstrom by default. (Not used.)

ToPhotlam(wave, flux, area=None)

Convert to photlam.

\textnormal{photlam} = \frac{\textnormal{counts}}{\delta \lambda \; \times \; \textnormal{area}}

where \delta \lambda represent bin widths derived from calculate_bin_edges() and calculate_bin_widths(), using the input wavelength values as bin centers.

Parameters:
  • flux (wave,) – Wavelength and flux values to be used for conversion.
  • area (number or None) – Telescope collecting area. If not given, default value from Reference Data is used.
Returns:

result – Converted values.

Return type:

number or array_like

class pysynphot.units.LogFluxUnits

Bases: pysynphot.units.FluxUnits

Base class for magnitude, which often requires special handling.

name, zeropoint

None – To be set by sub-class of a specific magnitude unit.

Dispatch

dict – Defines conversion to photlam.

isFlux, isMag

bool – This is always True.

isDensity

bool – This is True except for obmag.

nativewave

WaveUnits – Native wavelength unit associated with the flux unit. This is for informational purpose only.

linunit

None – Corresponding linear flux unit to be set by sub-class.

class pysynphot.units.ABMag

Bases: pysynphot.units.LogFluxUnits

Class to handle abmag unit. See Counts and Magnitudes for more details.

name

str – This is always ‘abmag’.

Dispatch

dict – Defines conversion to photlam.

isFlux, isMag, isDensity

bool – This is always True.

nativewave

WaveUnits – This is Angstrom by default. (Not used.)

linunit

FluxUnits – Corresponding linear flux unit is Fnu.

zeropoint

float – Its zero point is as defined by pysynphot.units.ABZERO.

ToPhotlam(wave, flux, **kwargs)

Convert to photlam.

m = -0.4 \; (\textnormal{AB}_{\nu} + 48.6)

\textnormal{photlam} = \frac{10^{m}}{h \lambda}

where h is as defined in Constants.

Parameters:
  • flux (wave,) – Wavelength and flux values to be used for conversion.
  • kwargs (dict) – Extra keywords (not used).
Returns:

result – Converted values.

Return type:

number or array_like

class pysynphot.units.STMag

Bases: pysynphot.units.LogFluxUnits

Class to handle stmag unit. See Counts and Magnitudes for more details.

name

str – This is always ‘stmag’.

Dispatch

dict – Defines conversion to photlam.

isFlux, isMag, isDensity

bool – This is always True.

nativewave

WaveUnits – This is Angstrom by default. (Not used.)

linunit

FluxUnits – Corresponding linear flux unit is Flam.

zeropoint

float – Its zero point is as defined by pysynphot.units.STZERO.

ToPhotlam(wave, flux, **kwargs)

Convert to photlam.

m = -0.4 \; (\textnormal{ST}_{\lambda} + 21.1)

\textnormal{photlam} = \frac{10^{m} \lambda}{hc}

where h and c are as defined in Constants.

Parameters:
  • flux (wave,) – Wavelength and flux values to be used for conversion.
  • kwargs (dict) – Extra keywords (not used).
Returns:

result – Converted values.

Return type:

number or array_like

class pysynphot.units.OBMag

Bases: pysynphot.units.LogFluxUnits

Class to handle obmag unit. See Counts and Magnitudes for more details.

name

str – This is always ‘obmag’.

Dispatch

dict – Defines conversion to photlam.

isFlux, isMag

bool – This is always True.

isDensity

bool – This is always False.

nativewave

WaveUnits – This is Angstrom by default. (Not used.)

linunit

FluxUnits – Corresponding linear flux unit is Counts.

zeropoint

float – This is always 0.

ToPhotlam(wave, flux, area=None)

Convert to photlam.

\textnormal{photlam} = \frac{10^{-0.4 \; \textnormal{obmag}}}{\delta \lambda \; \times \; \textnormal{area}}

where \delta \lambda represent bin widths derived from calculate_bin_edges() and calculate_bin_widths(), using the input wavelength values as bin centers.

Parameters:
  • flux (wave,) – Wavelength and flux values to be used for conversion.
  • area (number or None) – Telescope collecting area. If not given, default value from Reference Data is used.
Returns:

result – Converted values.

Return type:

number or array_like

class pysynphot.units.VegaMag

Bases: pysynphot.units.LogFluxUnits

Class to handle vegamag unit. See Counts and Magnitudes for more details.

name

str – This is always ‘vegamag’.

Dispatch

dict – Defines conversion to photlam.

isFlux, isMag, isDensity

bool – This is always True.

nativewave

WaveUnits – This is Angstrom by default. (Not used.)

linunit, zeropoint

None – This is not used.

vegaspec

SourceSpectrum – This is set to Vega.

ToPhotlam(wave, flux, **kwargs)

Convert to photlam.

\textnormal{photlam} = 10^{-0.4 \; \textnormal{vegamag}} \; f_{\textnormal{Vega}}

where f_{\textnormal{Vega}} is the flux of Vega resampled at given wavelength values and converted to photlam.

Parameters:
  • flux (wave,) – Wavelength and flux values to be used for conversion.
  • kwargs (dict) – Extra keywords (not used).
Returns:

result – Converted values.

Return type:

number or array_like

pysynphot.wavetable

This module handles selection of the appropriate wavelength table for a given observation mode. This is the same selection as used by ETC.

Its wavecat_file (see below) can contain a mix of the following:

  • Name of the ASCII file containing the wavelength values. The filename can contain IRAF-style path shortcut. The file must only contain one column, with a single wavelength value in Angstrom in each row. The file can also contain comment lines that begin with “#”, which will be skipped.

  • A string of comma-separated coefficients that describe how to construct the wavelength table in Angstrom, in the format of (c0,c1[,c2[,c3]]), where c2 and c3 are optional. They are used for the following computation. Basically, the wavelength table runs from c0 to c1, with constant \delta \lambda if c2 is undefined, or if c2 is given but not c3, or variable \delta \lambda if both c2 and c3 are given:

    c_{2} = \left \{
          \begin{array}{ll}
            c_{2} & : \textnormal{if given} \\
            (c_{1} - c_{0})/1999 & : \textnormal{else, where 1999 was taken from IRAF STSDAS SYNPHOT}
          \end{array}
        \right.

c_{3} = \left \{
          \begin{array}{ll}
            c_{3} & : \textnormal{if given} \\
            c_{2} & : \textnormal{else}
          \end{array}
        \right.

n = \textnormal{int}(\frac{2 \; (c_{1} - c_{0})}{c_{3} + c_{2}}) + 1

a = \frac{0.25 \; (c_{3}^{2} - c_{2}^{2})}{c_{1} - c_{0}}

\lambda_{i=0,n-1} = (a i + c_{2}) i + c_{0}

Example contents of a wavecat_file:

# OBSMODE           FILENAME_OR_COEFFS
stis,e140h,c1598    (1497.0,1699.0,0.0066,0.0075)
stis,g230l          (1568.0,3184.0,1.6)
stis,prism          synphot$data/prism.dat
stis,prism,c1200    synphot$data/prism.dat

Global Variables

  • pysynphot.wavetable.wavecat_file - This is the same as pysynphot.locations.wavecat. It is the data file used in this module.
  • pysynphot.wavetable.wavetable - This is a Wavetable object created using pysynphot.wavetable.wavecat_file.
class pysynphot.wavetable.Wavetable(fname)

Class to handle wavelength table.

__getitem__() is used to look up the wavelength table. It raises KeyError or ValueError if look-up fails. The look-up result is resolved into actual wavelength values by bandWave().

Parameters:fname (str) – Data file.
file

Same as input fname.

lookup

dict – Look-up table using obsmode string as key. This is used by default for direct match.

setlookup

dict – Same as lookup but the obsmode string is converted into a frozen set consisting of its components. This is used for partial look-up if there is no direct match.

Raises:ValueError – Failed to parse input file.

Examples

>>> wavetab = S.wavetable.Wavetable(S.wavetable.wavecat_file)
>>> wavetab['stis,g230l']
'(1568.0,3184.0,1.6)'
>>> wavetab['stis,prism']
'synphot$data/prism.dat'