astromodels.core package

Submodules

astromodels.core.cpickle_compatibility_layer module

astromodels.core.memoization module

astromodels.core.memoization.memoize(method)[source]

A decorator for functions of sources which memoize the results of the last _CACHE_SIZE calls,

Parameters:

method – method to be memoized

Returns:

the decorated method

astromodels.core.memoization.use_astromodels_memoization(switch, cache_size=20)[source]

Activate/deactivate memoization temporarily

Parameters:
  • switch – True (memoization on) or False (memoization off)

  • cache_size – number of previous evaluation of functions to keep in memory. Default: 100

Returns:

astromodels.core.model module

exception astromodels.core.model.CannotWriteModel(directory, message)[source]

Bases: OSError

exception astromodels.core.model.InvalidInput[source]

Bases: ValueError

class astromodels.core.model.Model(*sources)[source]

Bases: Node

add_external_parameter(parameter: Parameter) None[source]

Add a parameter that comes from something other than a function, to the model.

Parameters:

parameter – a Parameter instance

Returns:

none

add_independent_variable(variable: IndependentVariable) None[source]

Add a global independent variable to this model, such as time.

Parameters:

variable – an IndependentVariable instance

Returns:

none

add_source(new_source: Union[PointSource, ExtendedSource, ParticleSource]) None[source]

Add the provided source to the model

Parameters:

new_source – the new source to be added (an instance of PointSource, ExtendedSource or ParticleSource)

Returns:

(none)

display(complete: bool = False) None[source]

Display information about the point source.

:param complete : if True, displays also information on fixed parameters :return: (none)

property extended_sources: Dict[str, ExtendedSource]

Returns the dictionary of all defined extended sources

Returns:

collections.OrderedDict()

property free_parameters: Dict[str, Parameter]

Get a dictionary with all the free parameters in this model

Returns:

dictionary of free parameters

get_extended_source_boundaries(id: int)[source]
get_extended_source_fluxes(id: int, j2000_ra: float, j2000_dec: float, energies: ndarray) ndarray[source]

Get the flux of the id-th extended sources at the given position at the given energies

Parameters:
  • id – id of the source

  • j2000_ra – R.A. where the flux is desired

  • j2000_dec – Dec. where the flux is desired

  • energies – energies at which the flux is desired

Returns:

flux array

get_extended_source_name(id: int) str[source]

Return the name of the n-th extended source

Parameters:

id – id of the source (integer)

Returns:

the name of the id-th source

get_number_of_extended_sources() int[source]

Return the number of extended sources

Returns:

number of extended sources

get_number_of_particle_sources() int[source]

Return the number of particle sources

Returns:

number of particle sources

get_number_of_point_sources() int[source]

Return the number of point sources

Returns:

number of point sources

get_particle_source_fluxes(id: int, energies: ndarray) ndarray[source]

Get the fluxes from the id-th point source

Parameters:
  • id – id of the source

  • energies – energies at which you need the flux

Returns:

fluxes

get_particle_source_name(id: int) str[source]
get_point_source_fluxes(id: int, energies: ndarray, tag=None, stokes=None) ndarray[source]

Get the fluxes from the id-th point source

Parameters:
  • id – id of the source

  • energies – energies at which you need the flux

  • tag – a tuple (integration variable, a, b) specifying the integration to perform. If this

parameter is specified then the returned value will be the average flux for the source computed as the integral between a and b over the integration variable divided by (b-a). The integration variable must be an independent variable contained in the model. If b is None, then instead of integrating the integration variable will be set to a and the model evaluated in a. :param stokes: can be I, Q, U, V :return: fluxes

get_point_source_name(id: int) str[source]
get_point_source_position(id) Tuple[float][source]

Get the point source position (R.A., Dec)

Parameters:

id – id of the source

Returns:

a tuple with R.A. and Dec.

get_total_flux(energies: ndarray) float[source]

Returns the total differential flux at the provided energies from all point sources

Returns:

property has_free_parameters: bool

Returns True or False depending on if any parameters are free

is_inside_any_extended_source(j2000_ra: float, j2000_dec: float) bool[source]

Link the value of the provided parameters through the provided function (identity is the default, i.e., parameter_1 = parameter_2).

Parameters:
  • parameter_1 – the first parameter;can be either a single parameter or a list of prarameters

  • parameter_2 – the second parameter

  • link_function – a function instance. If not provided, the identity function will be used by default.

Otherwise, this link will be set: parameter_1 = link_function(parameter_2) :return: (none)

property linked_functions: List[_LinkedFunctionContainer]

return a list of containers for the linked functions

property linked_parameters: Dict[str, Parameter]

Get a dictionary with all parameters in this model in a linked status. A parameter is in a linked status if it is linked to another parameter (i.e. it is forced to have the same value of the other parameter), or if it is linked with another parameter or an independent variable through a law.

Returns:

dictionary of linked parameters

property parameters: Dict[str, Parameter]

Return a dictionary with all parameters

Returns:

dictionary of parameters

property particle_sources: Dict[str, ParticleSource]

Returns the dictionary of all defined particle sources

Returns:

collections.OrderedDict()

property point_sources: Dict[str, PointSource]

Returns the dictionary of all defined point sources

Returns:

collections.OrderedDict()

property properties: Dict[str, Parameter]

Return a dictionary with all parameters

Returns:

dictionary of parameters

remove_external_parameter(parameter_name: str) None[source]

Remove an external parameter which was added with add_external_parameter

Parameters:

variable_name – name of parameter to remove

Returns:

remove_independent_variable(variable_name: str) None[source]

Remove an independent variable which was added with add_independent_variable

Parameters:

variable_name – name of variable to remove

Returns:

remove_source(source_name: str) None[source]

Returns a new model with the provided source removed from the current model. Any parameters linked to the source to be removed are automatically unlinked.

Parameters:

source_name – the name of the source to be removed

Returns:

a new Model instance without the source

save(output_file, overwrite=False)[source]

Save the model to disk

set_free_parameters(values: Iterable[float]) None[source]

Set the free parameters in the model to the provided values.

NOTE: of course, order matters

Parameters:

values – a list of new values

Returns:

None

property sources: Dict[str, Union[PointSource, ExtendedSource, ParticleSource]]

Returns a dictionary containing all defined sources (of any kind)

Returns:

collections.OrderedDict()

to_dict_with_types()[source]

Sets free one or more parameters which have been linked previously

Parameters:

parameter – the parameter to be set free, can also be a list of parameters

Returns:

(none)

Unlink all parameters of the current model that are linked to a parameter of a given source. To be called before removing a source from the model.

Parameters:
  • source_name – the name of the source to which to remove all links

  • warn – If True, prints a warning if any parameters were unlinked.

exception astromodels.core.model.ModelFileExists[source]

Bases: OSError

exception astromodels.core.model.ModelInternalError[source]

Bases: ValueError

astromodels.core.model_parser module

class astromodels.core.model_parser.IndependentVariableParser(name, definition)[source]

Bases: object

get_variable()[source]
exception astromodels.core.model_parser.ModelIOError[source]

Bases: OSError

class astromodels.core.model_parser.ModelParser(model_file=None, model_dict=None)[source]

Bases: object

get_model()[source]
exception astromodels.core.model_parser.ModelSyntaxError[source]

Bases: RuntimeError

exception astromodels.core.model_parser.ModelYAMLError[source]

Bases: YAMLError

class astromodels.core.model_parser.ParameterParser(name, definition)[source]

Bases: object

get_variable()[source]
class astromodels.core.model_parser.ShapeParser(source_name)[source]

Bases: object

property external_functions
property extra_setups
parse(component_name, function_name, parameters_definition, is_spatial=False)[source]
class astromodels.core.model_parser.SourceParser(source_name, source_definition)[source]

Bases: object

property external_functions: List[Dict[str, str]]
property extra_setups
get_source()[source]
astromodels.core.model_parser.clone_model(model_instance)[source]

Returns a copy of the given model with all objects cloned. This is equivalent to saving the model to a file and reload it, but it doesn’t require writing or reading to/from disk. The original model is not touched.

Parameters:

model – model to be cloned

Returns:

a cloned copy of the given model

astromodels.core.model_parser.load_model(filename)[source]

Load a model from a file.

Parameters:

filename – the name of the file containing the model

Returns:

an instance of a Model

astromodels.core.model_parser.model_unpickler(state)[source]

astromodels.core.my_yaml module

astromodels.core.my_yaml.dict_constructor(loader, node)[source]
astromodels.core.my_yaml.dict_representer(dumper, data)[source]

astromodels.core.node_type module

class astromodels.core.node_type.NewNodeUnpickler[source]

Bases: object

class astromodels.core.node_type.NodeBase(_name: str, _parent: Optional[Type[ForwardRef('NodeBase')]] = None, _children: Dict[str, Type[ForwardRef('NodeBase')]] = <factory>, _path: Optional[str] = '')[source]

Bases: object

property is_leaf: bool

is this a a leaf of the tree

property is_root: bool

is this the root of the tree

property name: str
property path: str
plot_tree() Tree[source]

this plots the tree to the screen

astromodels.core.parameter module

exception astromodels.core.parameter.CannotConvertValueToNewUnits[source]

Bases: RuntimeError

exception astromodels.core.parameter.CannotUnderstandUnit[source]

Bases: RuntimeError

class astromodels.core.parameter.IndependentVariable(name, value, unit, min_value=None, max_value=None, desc=None)[source]

Bases: ParameterBase

An independent variable like time or energy.

exception astromodels.core.parameter.IndependentVariableCannotBeLinked[source]

Bases: RuntimeError

exception astromodels.core.parameter.NotCallableOrErrorInCall[source]

Bases: RuntimeError

class astromodels.core.parameter.Parameter(name: Optional[str] = None, value: Optional[float] = None, min_value: Optional[float] = None, max_value: Optional[float] = None, delta: Optional[float] = None, desc: Optional[str] = None, free: bool = True, unit='', prior=None, is_normalization: bool = False, transformation: Optional[ParameterTransformation] = None)[source]

Bases: ParameterBase

Implements a numerical parameter. Optionally the parameter can vary according to an auxiliary law (see below).

Parameters:
  • name – Name for the parameter

  • value – Initial value

  • min_value – minimum allowed value for the parameter (default: None)

  • max_value – maximum allowed value for the parameter (default: None)

  • delta – initial step used by some fitting engines (default: 0.1 * value)

  • desc – description of parameter (default: ‘’)

  • free – whether the parameter is free or not (default: True)

  • unit – the parameter units (default: dimensionless)

  • prior – the parameter’s prior (default: None)

  • is_normalization – True or False, wether the parameter is a normalization or not (default: False)

  • transformation – a transformation to be used between external value (the value the user interacts with) and the value the fitting/sampling engine interacts with (internal value). It is an instance of a class implementing a forward(external_value) and a backward(internal_value) method returning respectively the transformation of the external value in the internal value and viceversa. This is useful because for example the logarithm of a parameter with a large range of possible values (say from 1e-12 to 1e20) is handled much better by fitting engines than the raw value. The log transformation indeed makes the gradient much easier to compute.

add_auxiliary_variable(variable, law) None[source]

TODO describe function

Parameters:
  • variable

  • law

Returns:

property auxiliary_variable: Tuple

Returns a tuple with the auxiliary variable and the law

Returns:

tuple (variable, law)

property delta

Gets or sets the delta for the parameter

property fix

‘p.fix = True’ or ‘p.fix = False’.

Type:

Gets or sets whether the parameter is fixed or not. Use booleans, like

property free

‘p.free = True’ or ‘p.free = False’.

Type:

Gets or sets whether the parameter is free or not. Use booleans, like

get_randomized_value(variance=0.1)[source]
property has_auxiliary_variable: bool

Returns whether the parameter is linked to an auxiliary variable

has_prior()[source]

Check whether the current parameter has a defined prior

Returns:

True or False

property is_normalization: bool
property prior

Gets or sets the current prior for this parameter. The prior must be a callable function accepting the current value of the parameter as input and returning the probability density as output. Set to None to remove prior.

remove_auxiliary_variable()[source]

Remove an existing auxiliary variable

Returns:

set_uninformative_prior(prior_class)[source]

Sets the prior for the parameter to a uniform prior between the current minimum and maximum, or a log-uniform prior between the current minimum and maximum.

NOTE: if the current minimum and maximum are not defined, the default bounds for the prior class will be used.

:param prior_class : the class to be used as prior (either Log_uniform_prior or Uniform_prior, or a class which provide a lower_bound and an upper_bound properties) :return: (none)

to_dict(minimal=False)[source]

Returns the representation for serialization

class astromodels.core.parameter.ParameterBase(name: str, value: float, min_value: Optional[float] = None, max_value: Optional[float] = None, desc: Optional[str] = None, unit: Unit = Unit(dimensionless), transformation: Optional[ParameterTransformation] = None)[source]

Bases: Node

Parameters:
  • name – name for parameter

  • value – initial value

  • min_value – minimum

  • max_value – maximum

  • desc – description

  • unit – units (string or astropy.Unit)

  • transformation – a class which implements a .forward and a .backward method to transform forth and back from face value (the value exposed to the user) to the internal value (the value exposed to the fitting engine)

add_callback(callback) None[source]

Add a callback to the list of functions which are called immediately after the value of the parameter is changed. The callback must be a function accepting the current parameter as input. The return value of the callback is ignored. More than one callback can be specified. In that case, the callbacks will be called in the same order they have been entered.

property as_quantity: Quantity

Return the current value with its units (as an astropy.Quantity instance)

Returns:

an instance of astropy.Quantity)

property bounds: Tuple[float]

Gets or sets the boundaries (minimum and maximum) for this parameter

property description: Optional[str]

Return a description of this parameter

Returns:

a string cointaining a description of the meaning of this parameter

duplicate() Parameter[source]

Returns an exact copy of the current parameter

empty_callbacks() None[source]

Remove all callbacks for this parameter

get_callbacks()[source]

Returns the list of callbacks currently defined

Returns:

property has_auxiliary_variable: bool
has_transformation() bool[source]
in_unit_of(unit, as_quantity=False) Quantity[source]

Return the current value transformed to the new units

Parameters:
  • unit – either an astropy.Unit instance, or a string which can be converted to an astropy.Unit instance, like “1 / (erg cm**2 s)”

  • as_quantity – if True, the method return an astropy.Quantity, if False just a floating point number. Default is False

Returns:

either a floating point or a astropy.Quantity depending on the value of “as_quantity”

internal_to_external_delta(internal_value, internal_delta)[source]

Transform an interval from the internal to the external reference (through the transformation). It is useful if you have for example a confidence interval in internal reference and you want to transform it to the external reference

Parameters:
  • interval_value – value in internal reference

  • internal_delta – delta in internal reference

Returns:

value and delta in external reference

property max_value: float

Gets or sets the maximum allowed value for the parameter

property min_value

Gets or sets the minimum allowed value for the parameter

remove_maximum() None[source]

Remove the maximum from this parameter (i.e., it becomes boundless in the positive direction)

remove_minimum() None[source]

Remove the minimum from this parameter (i.e., it becomes boundless in the negative direction)

remove_transformation() None[source]

remove any transform on the parameter

useful in bayesian fits where we do not care about transformations but want speed

Returns:

restore_transformation() None[source]

restore the original transformation if it had been removed

Returns:

property static_name: str

Returns a name which will never change, even if the name of the parameter does (for example in composite functions)

:return : the static name :type : str

to_dict(minimal=False) Dict[str, Any][source]

Returns the representation for serialization

property transformation: Optional[ParameterTransformation]
property unit

Gets or sets the unit for the parameter

property value: float

Get and sets the current value for the parameter, with or without units

exception astromodels.core.parameter.ParameterMustHaveBounds[source]

Bases: RuntimeError

exception astromodels.core.parameter.SettingOutOfBounds[source]

Bases: RuntimeError

exception astromodels.core.parameter.WarningUnitsAreSlow[source]

Bases: Warning

astromodels.core.parameter.accept_quantity(input_type=<class 'float'>, allow_none=False)[source]

A class-method decorator which allow a given method (typically the set_value method) to receive both a astropy.Quantity or a simple float, but to be coded like it’s always receiving a pure float in the right units. This is to give a way to avoid the huge bottleneck that are astropy.units

Parameters:

input_type – the expected type for the input (float, int)

:param allow_none : whether to allow or not the passage of None as argument (default: False) :return: a decorator for the particular type

astromodels.core.parameter.turn_off_parameter_transforms() None[source]

deactivate parameter transforms temporarily :return: None

astromodels.core.parameter_transformation module

class astromodels.core.parameter_transformation.LogarithmicTransformation[source]

Bases: ParameterTransformation

backward(internal_value)[source]
forward(external_value, vector=False)[source]
class astromodels.core.parameter_transformation.ParameterTransformation(is_positive=False)[source]

Bases: object

backward(internal_value)[source]
forward(external_value)[source]
property is_positive
astromodels.core.parameter_transformation.get_transformation(transformation_name)[source]

Returns an instance of a transformation by name

Parameters:

transformation_name

Returns:

instance of transformation with provided name

astromodels.core.polarization module

class astromodels.core.polarization.LinearParameter(name, value)[source]

Bases: Node

class astromodels.core.polarization.LinearPolarization(degree, angle)[source]

Bases: Polarization

class astromodels.core.polarization.Polarization(polarization_type='linear')[source]

Bases: Node

class astromodels.core.polarization.StokesParameter(name, value)[source]

Bases: Node

class astromodels.core.polarization.StokesPolarization(I=None, Q=None, U=None, V=None)[source]

Bases: Polarization

astromodels.core.property module

class astromodels.core.property.FunctionProperty(name: str, desc: str, value: Optional[str] = None, allowed_values: Optional[List[Any]] = None, defer: bool = False, eval_func: Optional[str] = None)[source]

Bases: PropertyBase

class astromodels.core.property.PropertyBase(name: str, desc: str, value: Optional[str] = None, allowed_values: Optional[List[str]] = None, defer: bool = False, eval_func: Optional[str] = None)[source]

Bases: Node

property description: Optional[str]

Return a description of this parameter

Returns:

a string cointaining a description of the meaning of this parameter

duplicate() FunctionProperty[source]

Returns an exact copy of the current property

property is_deferred: bool
to_dict(minimal=False) Dict[str, Any][source]

Returns the representation for serialization

property value: Any

Get and sets the current value for the property

exception astromodels.core.property.SettingUnknownValue[source]

Bases: RuntimeError

astromodels.core.serialization module

astromodels.core.sky_direction module

exception astromodels.core.sky_direction.IllegalCoordinateValue[source]

Bases: ValueError

class astromodels.core.sky_direction.SkyDirection(ra=None, dec=None, l=None, b=None, equinox='J2000')[source]

Bases: Node

This is essentially a wrapper around astropy.coordinates.SkyCoord with a possibility for being serialized and deserialized with YAML.

property equinox

Returns the equinox for the coordinates.

Returns:

fix()[source]

Fix the parameters with the coordinates (either ra,dec or l,b depending on how the class has been instanced)

free()[source]

Free the parameters with the coordinates (either ra,dec or l,b depending on how the class has been instanced)

classmethod from_dict(data)[source]
get_b()[source]

Get Galactic latitude (b) corresponding to the current position

Returns:

Latitude

get_dec()[source]

Get Dec. corresponding to the current position (ICRS, J2000)

Returns:

Declination

get_l()[source]

Get Galactic Longitude (l) corresponding to the current position

Returns:

Galactic Longitude

get_ra()[source]

Get R.A. corresponding to the current position (ICRS, J2000)

Returns:

Right Ascension

property parameters

Get the dictionary of parameters (either ra,dec or l,b)

Returns:

dictionary of parameters

property sky_coord

Return an instance of astropy.coordinates.SkyCoord which can be used to make all transformations supported by it

Returns:

astropy.coordinates.SkyCoord

to_dict(minimal=False)[source]
exception astromodels.core.sky_direction.WrongCoordinatePair[source]

Bases: ValueError

exception astromodels.core.sky_direction.WrongCoordinateSystem[source]

Bases: ValueError

astromodels.core.spectral_component module

class astromodels.core.spectral_component.SpectralComponent(name, shape, polarization=None)[source]

Bases: Node

property shape

A generic name for the spectral shape.

Returns:

the spectral shape instance

astromodels.core.thread_safe_unit_format module

class astromodels.core.thread_safe_unit_format.ThreadSafe(*args, **kwargs)[source]

Bases: Base

name = 'threadsafe'
classmethod parse(s)[source]

Convert a string to a unit object.

classmethod to_string(unit)[source]

Convert a unit to its string representation.

Implementation for ~astropy.units.UnitBase.to_string.

Parameters:
  • unit (|Unit|) – The unit to convert.

  • fraction ({False|True|’inline’|’multiline’}, optional) – Options are as follows:

    • False : display unit bases with negative powers as they are (e.g., km s-1);

    • ‘inline’ or True : use a single-line fraction (e.g., km / s);

    • ‘multiline’ : use a multiline fraction (available for the latex, console and unicode formats only; e.g., $\mathrm{\frac{km}{s}}$).

Raises:

ValueError – If fraction is not recognized.

astromodels.core.tree module

exception astromodels.core.tree.DuplicatedNode[source]

Bases: Exception

class astromodels.core.tree.Node(name: str)[source]

Bases: NodeBase

display()[source]

Display information about the point source.

Returns:

(none)

to_dict(minimal: bool = False) Dict[str, Any][source]
exception astromodels.core.tree.NonExistingAttribute[source]

Bases: RuntimeWarning

exception astromodels.core.tree.ProtectedAttribute[source]

Bases: RuntimeError

astromodels.core.units module

exception astromodels.core.units.UnitMismatch[source]

Bases: Exception

exception astromodels.core.units.UnknownUnit[source]

Bases: Exception

Module contents