ch_util.fluxcat

Catalog the measured flux densities of astronomical sources

This module contains tools for cataloging astronomical sources and predicting their flux density at radio frequencies based on previous measurements.

Functions

format_source_name(input_name)

Standardise the name of a source.

get_epoch(date)

Return the epoch for a date.

json_numpy_obj_hook(dct)

Decodes a previously encoded numpy ndarray with proper shape and dtype.

varname(name)

Create a python variable name from name.

Classes

CurvedPowerLaw([freq_pivot, nparam])

Class to fit a spectrum to a polynomial in log-log space, given by

FitSpectrum([param, param_cov, stats])

A base class for modeling and fitting spectra.

FluxCatalog(name[, ra, dec, ...])

Class for cataloging astronomical sources and predicting their flux density at radio frequencies based on spectral fits to previous measurements.

MetaFluxCatalog

Metaclass for FluxCatalog.

NumpyEncoder(*[, skipkeys, ensure_ascii, ...])

Constructor for JSONEncoder, with sensible defaults.

class ch_util.fluxcat.CurvedPowerLaw(freq_pivot=600.0, nparam=2, *args, **kwargs)[source]

Bases: FitSpectrum

Class to fit a spectrum to a polynomial in log-log space, given by

\[\ln{S} = a_{0} + a_{1} \ln{\nu'} + a_{2} \ln{\nu'}^2 + a_{3} \ln{\nu'}^3 + \dots \]

where \(S\) is the flux density, \(\nu'\) is the (normalized) frequency, and \(a_{i}\) are the fit parameters.

Parameters:
  • nparam (int) – Number of parameters. This sets the order of the polynomial. Default is 2 (powerlaw).

  • freq_pivot (float) – The pivot frequency \(\nu' = \nu / freq_pivot\). Default is FREQ_NOMINAL.

Instantiates a CurvedPowerLaw object

class ch_util.fluxcat.FitSpectrum(param=None, param_cov=None, stats=None)[source]

Bases: object

A base class for modeling and fitting spectra. Any spectral model used by FluxCatalog should be derived from this class.

The fit method should be used to populate the param, param_cov, and stats attributes. The predict and uncertainty methods can then be used to obtain the flux density and uncertainty at arbitrary frequencies.

param

Best-fit parameters.

Type:

np.ndarray[nparam, ]

param_cov

Covariance of the fit parameters.

Type:

np.ndarray[nparam, nparam]

stats

Dictionary that contains statistics related to the fit. Must include ‘chisq’ and ‘ndof’.

Type:

dict

Abstract Methods
----------------
Any subclass of FitSpectrum must define these methods

fit _get_x _fit_func _deriv_fit_func

Instantiates a FitSpectrum object.

predict(freq)[source]

Predicts the flux density at a particular frequency.

uncertainty(freq, alpha=0.32)[source]

Predicts the uncertainty on the flux density at a particular frequency.

class ch_util.fluxcat.FluxCatalog(name, ra=None, dec=None, alternate_names=[], model='CurvedPowerLaw', model_kwargs=None, stats=None, param=None, param_cov=None, measurements=None, overwrite=0)[source]

Bases: object

Class for cataloging astronomical sources and predicting their flux density at radio frequencies based on spectral fits to previous measurements.

Class methods act upon and provide access to the catalog of all sources. Instance methods act upon and provide access to individual sources. All instances are stored in an internal class dictionary.

fields

List of attributes that are read-from and written-to the JSON catalog files.

Type:

list

model_lookup

Dictionary that provides access to the various models that can be fit to the spectrum. These models should be subclasses of FitSpectrum.

Type:

dict

Instantiates a FluxCatalog object for an astronomical source.

Parameters:
  • name (string) – Name of the source. The convention for the source name is to use the MAIN_ID in the SIMBAD database in all uppercase letters with spaces replaced by underscores.

  • ra (float) – Right Ascension in degrees.

  • dec (float) – Declination in degrees.

  • alternate_names (list of strings) – Alternate names for the source. Ideally should include all alternate names present in the SIMBAD database using the naming convention specified above.

  • model (string) – Name of FitSpectrum subclass.

  • model_kwargs (dict) – Dictionary containing keywords required by the model.

  • stats (dict) – Dictionary containing statistics from model fit.

  • param (list, length nparam) – Best-fit parameters.

  • param_cov (2D-list, size nparam x nparam) – Estimate of covariance of fit parameters.

  • measurements (2D-list, size nmeas x 7) – List of measurements of the form: [freq, flux, eflux, flag, catalog, epoch, citation]. Should use the add_measurement method to populate this list.

  • overwrite (int between 0 and 2) – Action to take in the event that this source is already in the catalog: - 0 - Return the existing entry. - 1 - Add the measurements to the existing entry. - 2 - Overwrite the existing entry. Default is 0.

add_measurement(freq, flux, eflux, flag=True, catalog=None, epoch=None, citation=None)[source]

Add entries to the list of measurements. Each argument/keyword can be a list of items with length equal to ‘len(flux)’, or alternatively a single item in which case the same value is used for all measurements.

Parameters:
  • freq (float, list of floats) – Frequency in MHz.

  • flux (float, list of floats) – Flux density in Jansky.

  • eflux (float, list of floats) – Uncertainty on flux density in Jansky.

  • flag (bool, list of bool) – If True, use this measurement in model fit. Default is True.

  • catalog (string or None, list of strings or Nones) – Name of the catalog from which this measurement originates. Default is None.

  • epoch (float or None, list of floats or Nones) – Year when this measurement was taken. Default is None.

  • citation (string or None, list of strings or Nones) – Citation where this measurement can be found (e.g., ‘Baars et al. (1977)’). Default is None.

classmethod available_collections()[source]

Search the local directory for potential collections that can be loaded.

Returns:

collections – List containing a tuple for each collection. The tuple contains the filename of the collection (str) and the sources it contains (list of str).

Return type:

list of (str, [str, …])

property catalog

Catalog from which each measurement originates.

property citation

Citation where more information on each measurement can be found.

classmethod delete(source_name)[source]

Deletes a source from the catalog.

Parameters:

source_name (str) – Name of the astronomical source.

classmethod dump(filename)[source]

Dumps the contents of the catalog to a file.

Parameters:

filename (str) – Valid path name. Should have .json or .pickle extension.

property eflux

Error on the flux measurements in Jansky.

property epoch

Year that each measurement occured.

fit_model()[source]

Fit the measurements stored in the ‘measurements’ attribute with the spectral model specified in the ‘model’ attribute. This populates the ‘param’, ‘param_cov’, and ‘stats’ attributes.

property flag

Boolean flag indicating what measurements are used in the spectral fit.

property flux

Flux measurements in Jansky.

property freq

Frequency of measurements in MHz.

classmethod from_dict(name, flux_body_dict)[source]

Instantiates a FluxCatalog object for an astronomical source from a dictionary of kwargs. Used when loading sources from a JSON catalog file.

Parameters:
  • name (str) – Name of the astronomical source.

  • flux_body_dict (dict) – Dictionary containing some or all of the keyword arguments listed in the __init__ function for this class.

Returns:

obj – Object that can be used to predict the flux of this source, plot flux measurements, etc.

Return type:

FluxCatalog instance

classmethod get(key)[source]

Searches the catalog for a source. First checks against the ‘name’ of each entry, then checks against the ‘alternate_names’ of each entry.

Parameters:

key (str) – Name of the astronomical source.

Returns:

obj – Object that can be used to predict the flux of this source, plot flux measurements, etc.

Return type:

FluxCatalog instance

classmethod iter()[source]

Iterates through the sources in the catalog.

Returns:

it – Provides the name of each source in the catalog in the order specified by the ‘sort’ class method.

Return type:

iterator

classmethod iteritems()[source]

Iterates through the sources in the catalog.

Returns:

it – Provides (name, object) for each source in the catalog in the order specified by the ‘sort’ class method.

Return type:

iterator

classmethod keys()[source]

Alias for sort.

Returns:

names – List of source names in correct order.

Return type:

list of str

classmethod len()[source]

Number of sources in the catalog.

Returns:

N

Return type:

int

classmethod load(filename, overwrite=0, set_globals=False, verbose=False)[source]

Load the contents of a file into the catalog.

Parameters:
  • filename (str) – Valid path name. Should have .json or .pickle extension.

  • overwrite (int between 0 and 2) – Action to take in the event that this source is already in the catalog: - 0 - Return the existing entry. - 1 - Add any measurements to the existing entry. - 2 - Overwrite the existing entry. Default is 0.

  • set_globals (bool) – If True, this creates a variable in the global space for each source in the file. Default is False.

  • verbose (bool) – If True, print some basic info about the contents of the file as it is loaded. Default is False.

classmethod load_dict(collection_dict, collection_name, overwrite=0, set_globals=False, verbose=False)[source]

Load the contents of a dict into the catalog.

Parameters:
  • collection_dict (dict) – keys are source names, values are the sources

  • collection_name (str) – Name of the collection

  • overwrite (int between 0 and 2) – Action to take in the event that this source is already in the catalog: - 0 - Return the existing entry. - 1 - Add any measurements to the existing entry. - 2 - Overwrite the existing entry. Default is 0.

  • set_globals (bool) – If True, this creates a variable in the global space for each source in the file. Default is False.

  • verbose (bool) – If True, print some basic info about the contents of the file as it is loaded. Default is False.

classmethod loaded_collections()[source]

Return the collections that have been loaded.

Returns:

collections – List containing a tuple for each collection. The tuple contains the filename of the collection (str) and the sources it contains (list of str).

Return type:

list of (str, [str, …])

plot(legend=True, catalog=True, residuals=False)[source]

Plot the measurements, best-fit model, and confidence interval.

Parameters:
  • legend (bool) – Show legend. Default is True.

  • catalog (bool) – If True, then label and color code the measurements according to their catalog. If False, then label and color code the measurements according to their citation. Default is True.

  • residuals (bool) – Plot the residuals instead of the measurements and best-fit model. Default is False.

predict_flux(freq, epoch=None)[source]

Predict the flux density of the source at a particular frequency and epoch.

Parameters:
  • freq (float, np.array of floats) – Frequency in MHz.

  • epoch (float, np.array of floats) – Year. Defaults to current year.

Returns:

flux – Flux density in Jansky.

Return type:

float, np.array of floats

predict_uncertainty(freq, epoch=None)[source]

Calculate the uncertainty in the estimate of the flux density of the source at a particular frequency and epoch.

Parameters:
  • freq (float, np.array of floats) – Frequency in MHz.

  • epoch (float, np.array of floats) – Year. Defaults to current year.

Returns:

flux_uncertainty – Uncertainty on the flux density in Jansky.

Return type:

float, np.array of floats

classmethod print_available_collections(verbose=False)[source]

Print information about the available collections.

Parameters:

verbose (bool) – If True, then print all source names in addition to the names of the files and number of sources. Default is False.

classmethod print_loaded_collections(verbose=False)[source]

Print information about the collection that have been loaded.

Parameters:

verbose (bool) – If True, then print all source names in addition to the names of the files and number of sources. Default is False.

print_measurements()[source]

Print all measurements.

classmethod reversed()[source]

Iterates through the sources in the catalog in reverse order.

Returns:

it – Provides the name of each source in the catalog in the reverse order as that specified by the ‘sort’ class method.

Return type:

iterator

property skyfield

Skyfield star representation skyfield.starlib.Star for the source.

classmethod sort()[source]

Sorts the entries in the catalog by their flux density at FREQ_NOMINAL in descending order.

Returns:

names – List of source names in correct order.

Return type:

list of str

classmethod string()[source]

Print basic information about the sources in the catalog.

to_dict()[source]

Returns an ordered dictionary containing attributes for this instance object. Used to dump the information stored in the instance object to a file.

Returns:

flux_body_dict – Dictionary containing all attributes listed in the ‘fields’ class attribute.

Return type:

dict

class ch_util.fluxcat.MetaFluxCatalog[source]

Bases: type

Metaclass for FluxCatalog. Defines magic methods for the class that can act on and provide access to the catalog of all astronomical sources.

class ch_util.fluxcat.NumpyEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Bases: JSONEncoder

Constructor for JSONEncoder, with sensible defaults.

If skipkeys is false, then it is a TypeError to attempt encoding of keys that are not str, int, float or None. If skipkeys is True, such items are simply skipped.

If ensure_ascii is true, the output is guaranteed to be str objects with all incoming non-ASCII characters escaped. If ensure_ascii is false, the output can contain non-ASCII characters.

If check_circular is true, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an RecursionError). Otherwise, no such check takes place.

If allow_nan is true, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats.

If sort_keys is true, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis.

If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation.

If specified, separators should be an (item_separator, key_separator) tuple. The default is (’, ‘, ‘: ‘) if indent is None and (‘,’, ‘: ‘) otherwise. To get the most compact JSON representation, you should specify (‘,’, ‘:’) to eliminate whitespace.

If specified, default is a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError.

default(obj)[source]

If input object is an ndarray it will be converted into a dict holding dtype, shape and the data, base64 encoded.

ch_util.fluxcat.format_source_name(input_name)[source]

Standardise the name of a source.

Parameters:
  • input_name (str) – The name to format

  • Returns

  • formatted_name (str) – The name after formatting.

ch_util.fluxcat.get_epoch(date)[source]

Return the epoch for a date.

Parameters:

date (datetime.datetime) – Date to calculate epoch

Returns:

epoch – The fractional-year epoch

Return type:

float

ch_util.fluxcat.json_numpy_obj_hook(dct)[source]

Decodes a previously encoded numpy ndarray with proper shape and dtype.

Parameters:

dct – (dict) json encoded ndarray

Returns:

(ndarray) if input was an encoded ndarray

ch_util.fluxcat.varname(name)[source]

Create a python variable name from name.

The variable name replaces spaces in name with underscores and adds a leading underscore if name starts with a digit.

Parameters:

name (str) – The name to create a variable name for

Returns:

varname – The python variable name.

Return type:

str