Theory codes

Synopsis:

Theory is a base class for theory codes and likelihoods.

Both likelihoods and theories calculate something. Likelihoods are distinguished because they calculate a log likelihood. Both theory codes and likelihoods can calculate other things, and they may have complex dependencies between them: e.g. the likelihood depends on observable A that is computed by theory code B than in turn requires calculation of input calculation by code C.

This module contains the base class for all of these calculation components. It handles caching of results, so that calculations do not need to be redone when the parameters on which a component directly (or indirectly) depends have not changed.

Subclasses generally provide the Theory.get_requirements(), Theory.calculate() and initialization methods as required. The Theory.must_provide() method is used to tell a code which requirements are actually needed by other components, and may return a dictionary of additional conditional requirements based on those passed.

The Theory.calculate() method saves all needed results in the state dictionary (which is cached and reused as needed). Subclasses define get_X or get_result(X) methods to return the actual result of the calculation for X for the current cache state. The Theory.get_param() method returns the value of a derived parameter for the current state.

For details and examples of how to handle multiple theory codes with complex dependencies see Creating theory classes and dependencies.

Theory class

class theory.Theory(info=mappingproxy({}), name=None, timing=None, packages_path=None, initialize=True, standalone=True)

Bases: CobayaComponent

Base class theory that can calculate something.

get_requirements()

Get a dictionary of requirements (or a list of requirement name, option tuples) that are always needed (e.g. must be calculated by another component or provided as input parameters).

Return type:

Union[Dict[str, Any], Sequence[str], Sequence[Tuple[str, Dict[str, Any]]]]

Returns:

dictionary or list of tuples of requirement names and options (or iterable of requirement names if no optional parameters are needed)

must_provide(**requirements)

Function called by Cobaya with the actual products that this component needs to compute (i.e. the things this component can provide that are actually used by other components). The function can return conditional requirements that this component needs from other components in order to compute those things.

The requirements argument is a requirement name with any optional parameters. This function may be called more than once with different requirements.

Return type:

Union[None, Dict[str, Any], Sequence[str], Sequence[Tuple[str, Dict[str, Any]]]]

Returns:

optional dictionary (or list of requirement name, option tuples) of conditional requirements for the ones requested.

calculate(state, want_derived=True, **params_values_dict)

Do the actual calculation and store results in state dict

Parameters:
  • state – dictionary to store results

  • want_derived – whether to set state[‘derived’] derived parameters

  • params_values_dict – parameter values

Returns:

None or True if success, False for fail

initialize_with_params()

Additional initialization after requirements called and input_params and output_params have been assigned (but provider and assigned requirements not yet set).

initialize_with_provider(provider)

Final initialization after parameters, provider and assigned requirements set. The provider is used to get the requirements of this theory using provider.get_X() and provider.get_param(‘Y’).

Parameters:

provider (Provider) – the theory.Provider instance that should be used by this component to get computed requirements

get_param(p)

Interface function for likelihoods and other theory components to get derived parameters.

Return type:

float

get_result(result_name, **kwargs)

Interface function for likelihood and other theory components to get quantities calculated by this component. By default assumes the quantity is just directly saved into the current state (i.e. returns state[result_name]).

Parameters:
  • result_name – name of quantity

  • kwargs – options specific to X or this component

Returns:

result

get_can_provide_methods()

Get a dictionary of quantities X that can be retrieved using get_X methods.

Returns:

dictionary of the form {X: get_X method}

get_can_provide()

Get a list of names of quantities that can be retrieved using the general get_result(X) method.

Return type:

Iterable[str]

Returns:

iterable of quantity names

get_can_provide_params()

Get a list of derived parameters that this component can calculate. The default implementation returns the result based on the params attribute set via the .yaml file or class params (with derived:True for derived parameters).

Return type:

Iterable[str]

Returns:

iterable of parameter names

get_can_support_params()

Get a list of parameters supported by this component, can be used to support parameters that don’t explicitly appear in the .yaml or class params attribute or are otherwise explicitly supported (e.g. via requirements)

Return type:

Iterable[str]

Returns:

iterable of names of parameters

get_allow_agnostic()

Whether it is allowed to pass all unassigned input parameters to this component (True) or whether parameters must be explicitly specified (False).

Returns:

True or False

property input_params_extra

Parameters required from other components, to be passed as input parameters.

set_cache_size(n)

Set how many states to cache

check_cache_and_compute(params_values_dict, dependency_params=None, want_derived=False, cached=True)

Takes a dictionary of parameter values and computes the products needed by the likelihood, or uses the cached value if that exists for these parameters. If want_derived, the derived parameters are saved in the computed state (retrieved using current_derived).

params_values_dict can be safely modified and stored.

get_provider()

Return object containing get_X, get_param, get_result methods to get computed results. This defaults to self, but can change to delegate provision to another object

Returns:

object instance

get_helper_theories()

Return dictionary of optional names and helper Theory instances that should be used in conjunction with this component. The helpers can be created here as only called once, and before any other use of helpers.

Return type:

Dict[str, Theory]

Returns:

dictionary of names and Theory instances

get_attr_list_with_helpers(attr)

Get combined list of self.attr and helper.attr for all helper theories

Parameters:

attr – attr name

Returns:

combined list

close(*args)

Finalizes the class, if something needs to be cleaned up.

classmethod compare_versions(version_a, version_b, equal=True)

Checks whether version_a is equal or higher than version_b.

For strictly higher, pass equal=False (default: True).

Returns:

bool

classmethod get_associated_file_content(ext, file_root=None)

Return the content of the associated file, if it exists.

This function handles extracting package files when they may be inside a zipped package and thus not directly accessible.

Return type:

Optional[str]

Returns:

The content of the file as a string, if it exists and can be read. None otherwise.

classmethod get_bibtex()

Get the content of .bibtex file for this component. If no specific bibtex from this class, it will return the result from an inherited class if that provides bibtex.

Return type:

Optional[str]

classmethod get_class_options(input_options=mappingproxy({}))

Returns dictionary of names and values for class variables that can also be input and output in yaml files, by default it takes all the (non-inherited and non-private) attributes of the class excluding known specials.

Could be overridden using input_options to dynamically generate defaults, e.g. a set of input parameters generated depending on the input_options.

Parameters:

input_options – optional dictionary of input parameters

Return type:

Dict[str, Any]

Returns:

dict of names and values

classmethod get_class_path()

Get the file path for the class.

Return type:

str

classmethod get_defaults(return_yaml=False, yaml_expand_defaults=True, input_options=mappingproxy({}))

Return defaults for this component_or_class, with syntax:

option: value
[...]

params:
  [...]  # if required

prior:
  [...]  # if required

If keyword return_yaml is set to True, it returns literally that, whereas if False (default), it returns the corresponding Python dict.

Note that in external components installed as zip_safe=True packages files cannot be accessed directly. In this case using !default .yaml includes currently does not work.

Also note that if you return a dictionary it may be modified (return a deep copy if you want to keep it).

if yaml_expand_defaults then !default: file includes will be expanded

input_options may be a dictionary of input options, e.g. in case default params are dynamically dependent on an input variable

get_desc()

Returns a short description of the class. By default, returns the class’ docstring.

You can redefine this method to dynamically generate the description based on the class initialisation info (see e.g. the source code of MCMC’s class method _get_desc()).

classmethod get_file_base_name()

Gets the string used as the name for .yaml, .bib files, typically the class name or an un-CamelCased class name

Return type:

str

classmethod get_kind()

Return, as a string, the kind of this component.

get_name()

Get the name. This is usually set by the name used in the input .yaml, but otherwise defaults to the fully-qualified class name.

Return type:

str

Returns:

name string

classmethod get_qualified_class_name()

Get the distinct shortest reference name for the class of the form module.ClassName or module.submodule.ClassName etc. For Cobaya components the name is relative to subpackage for the relevant kind of class (e.g. Likelihood names are relative to cobaya.likelihoods).

For external classes it loads the shortest fully qualified name of the form package.ClassName or package.module.ClassName or package.subpackage.module.ClassName, etc.

Return type:

str

classmethod get_text_file_content(file_name)

Return the content of a file in the directory of the module, if it exists.

Return type:

Optional[str]

get_version()

Get version information for this component.

Return type:

Union[None, str, Dict[str, Any]]

Returns:

string or dict of values or None

classmethod get_yaml_file()

Gets the file name of the .yaml file for this component if it exists on file (otherwise None).

Return type:

Optional[str]

has_version()

Whether to track version information for this component

initialize()

Initializes the class (called from __init__, before other initializations).

set_instance_defaults()

Can use this to define any default instance attributes before setting to the input dictionary (from inputs or defaults)

validate_info(k, value, annotations)

Does any validation on parameter k read from an input dictionary or yaml file, before setting the corresponding class attribute. You could enforce consistency with annotations here, but does not by default.

Parameters:
  • k (str) – name of parameter

  • value (Any) – value

  • annotations (dict) – resolved inherited dictionary of attributes for this class