signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
@property<EOL><INDENT>def as_quantity(self):<DEDENT> | return self.value * self._unit<EOL> | Return the current value with its units (as an astropy.Quantity instance)
:return: an instance of astropy.Quantity) | f13304:c7:m7 |
def in_unit_of(self, unit, as_quantity=False): | new_unit = u.Unit(unit)<EOL>new_quantity = self.as_quantity.to(new_unit)<EOL>if as_quantity:<EOL><INDENT>return new_quantity<EOL><DEDENT>else:<EOL><INDENT>return new_quantity.value<EOL><DEDENT> | Return the current value transformed to the new units
:param unit: either an astropy.Unit instance, or a string which can be converted to an astropy.Unit
instance, like "1 / (erg cm**2 s)"
:param as_quantity: if True, the method return an astropy.Quantity, if False just a floating point number.
Default is False
:return: either a floating point or a astropy.Quantity depending on the value of "as_quantity" | f13304:c7:m8 |
def internal_to_external_delta(self, internal_value, internal_delta): | external_value = self.transformation.backward(internal_value)<EOL>bound_internal = internal_value + internal_delta<EOL>bound_external = self.transformation.backward(bound_internal)<EOL>external_delta = bound_external - external_value<EOL>return external_value, external_delta<EOL> | 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
:param interval_value: value in internal reference
:param internal_delta: delta in internal reference
:return: value and delta in external reference | f13304:c7:m12 |
def _get_value(self): | <EOL>if self._aux_variable:<EOL><INDENT>return self._aux_variable['<STR_LIT>'](self._aux_variable['<STR_LIT>'].value)<EOL><DEDENT>if self._transformation is None:<EOL><INDENT>return self._internal_value<EOL><DEDENT>else:<EOL><INDENT>return self._transformation.backward(self._internal_value)<EOL><DEDENT> | Return current parameter value | f13304:c7:m13 |
@accept_quantity(float, allow_none=False) <EOL><INDENT>def _set_value(self, new_value):<DEDENT> | if self.min_value is not None and new_value < self.min_value:<EOL><INDENT>raise SettingOutOfBounds(<EOL>"<STR_LIT>".format(<EOL>self.name, new_value, self.min_value))<EOL><DEDENT>if self.max_value is not None and new_value > self.max_value:<EOL><INDENT>raise SettingOutOfBounds(<EOL>"<STR_LIT>".format(<EOL>self.name, new_value, self.max_value))<EOL><DEDENT>if self.has_auxiliary_variable():<EOL><INDENT>with warnings.catch_warnings():<EOL><INDENT>warnings.simplefilter("<STR_LIT>", RuntimeWarning)<EOL>warnings.warn("<STR_LIT>"<EOL>"<STR_LIT>", RuntimeWarning)<EOL><DEDENT><DEDENT>if self._transformation is None:<EOL><INDENT>new_internal_value = new_value<EOL><DEDENT>else:<EOL><INDENT>new_internal_value = self._transformation.forward(new_value)<EOL><DEDENT>if new_internal_value != self._internal_value:<EOL><INDENT>self._internal_value = new_internal_value<EOL>for callback in self._callbacks:<EOL><INDENT>try:<EOL><INDENT>callback(self)<EOL><DEDENT>except:<EOL><INDENT>raise NotCallableOrErrorInCall("<STR_LIT>" % self.name)<EOL><DEDENT><DEDENT><DEDENT> | Sets the current value of the parameter, ensuring that it is within the allowed range. | f13304:c7:m14 |
def _get_internal_value(self): | <EOL>assert len(self._aux_variable)==<NUM_LIT:0>, "<STR_LIT>""<STR_LIT>"<EOL>return self._internal_value<EOL> | This is supposed to be only used by fitting engines at the beginning to get the starting value for free
parameters. From then on, only the _set_internal_value should be used
:return: the internal value | f13304:c7:m15 |
def _set_internal_value(self, new_internal_value): | if new_internal_value != self._internal_value:<EOL><INDENT>self._internal_value = new_internal_value<EOL>for callback in self._callbacks:<EOL><INDENT>callback(self)<EOL><DEDENT><DEDENT> | This is supposed to be only used by fitting engines
:param new_internal_value: new value in internal representation
:return: none | f13304:c7:m16 |
def _get_min_value(self): | return self._external_min_value<EOL> | Return current minimum allowed value | f13304:c7:m17 |
@accept_quantity(float, allow_none=True)<EOL><INDENT>def _set_min_value(self, min_value):<DEDENT> | <EOL>if self._transformation is not None:<EOL><INDENT>if min_value is not None:<EOL><INDENT>try:<EOL><INDENT>_ = self._transformation.forward(min_value)<EOL><DEDENT>except FloatingPointError:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" % (min_value,<EOL>type(self._transformation),<EOL>self.path))<EOL><DEDENT><DEDENT><DEDENT>self._external_min_value = min_value<EOL>if self._external_min_value is not None and self.value < self._external_min_value:<EOL><INDENT>warnings.warn("<STR_LIT>"<EOL>"<STR_LIT>" % (self.name, self.value, self._external_min_value),<EOL>exceptions.RuntimeWarning)<EOL>self.value = self._external_min_value<EOL><DEDENT> | Sets current minimum allowed value | f13304:c7:m18 |
def remove_minimum(self): | self._external_min_value = None<EOL> | Remove the minimum from this parameter (i.e., it becomes boundless in the negative direction) | f13304:c7:m19 |
def _get_internal_min_value(self): | if self.min_value is None:<EOL><INDENT>return None<EOL><DEDENT>else:<EOL><INDENT>if self._transformation is None:<EOL><INDENT>return self._external_min_value<EOL><DEDENT>else:<EOL><INDENT>return self._transformation.forward(self._external_min_value)<EOL><DEDENT><DEDENT> | This is supposed to be only used by fitting engines to get the minimum value in internal representation.
It is supposed to be called only once before doing the minimization/sampling, to set the range of the parameter
:return: minimum value in internal representation (or None if there is no minimum) | f13304:c7:m21 |
def _get_max_value(self): | return self._external_max_value<EOL> | Return current maximum allowed value | f13304:c7:m22 |
@accept_quantity(float, allow_none=True)<EOL><INDENT>def _set_max_value(self, max_value):<DEDENT> | self._external_max_value = max_value<EOL>if self._external_max_value is not None and self.value > self._external_max_value:<EOL><INDENT>warnings.warn("<STR_LIT>"<EOL>"<STR_LIT>" % (self.name, self.value, self._external_max_value),<EOL>exceptions.RuntimeWarning)<EOL>self.value = self._external_max_value<EOL><DEDENT> | Sets current maximum allowed value | f13304:c7:m23 |
def remove_maximum(self): | self._external_max_value = None<EOL> | Remove the maximum from this parameter (i.e., it becomes boundless in the positive direction) | f13304:c7:m24 |
def _get_internal_max_value(self): | if self.max_value is None:<EOL><INDENT>return None<EOL><DEDENT>else:<EOL><INDENT>if self._transformation is None:<EOL><INDENT>return self._external_max_value<EOL><DEDENT>else:<EOL><INDENT>return self._transformation.forward(self._external_max_value)<EOL><DEDENT><DEDENT> | This is supposed to be only used by fitting engines to get the maximum value in internal representation.
It is supposed to be called only once before doing the minimization/sampling, to set the range of the parameter
:return: maximum value in internal representation (or None if there is no minimum) | f13304:c7:m26 |
def _set_bounds(self, bounds): | <EOL>min_value, max_value = bounds<EOL>self.min_value = None<EOL>self.max_value = None<EOL>self.min_value = min_value<EOL>self.max_value = max_value<EOL> | Sets the boundaries for this parameter to min_value and max_value | f13304:c7:m27 |
def _get_bounds(self): | return self.min_value, self.max_value<EOL> | Returns the current boundaries for the parameter | f13304:c7:m28 |
def add_callback(self, callback): | self._callbacks.append(callback)<EOL> | 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. | f13304:c7:m29 |
def get_callbacks(self): | return self._callbacks<EOL> | Returns the list of callbacks currently defined
:return: | f13304:c7:m30 |
def empty_callbacks(self): | self._callbacks = []<EOL> | Remove all callbacks for this parameter | f13304:c7:m31 |
def duplicate(self): | <EOL>new_parameter = copy.deepcopy(self)<EOL>return new_parameter<EOL> | Returns an exact copy of the current parameter | f13304:c7:m32 |
def to_dict(self, minimal=False): | data = collections.OrderedDict()<EOL>if minimal:<EOL><INDENT>data['<STR_LIT:value>'] = self._to_python_type(self.value)<EOL><DEDENT>else:<EOL><INDENT>data['<STR_LIT:value>'] = self._to_python_type(self.value)<EOL>data['<STR_LIT>'] = str(self.description)<EOL>data['<STR_LIT>'] = self._to_python_type(self.min_value)<EOL>data['<STR_LIT>'] = self._to_python_type(self.max_value)<EOL>data['<STR_LIT>'] = self.unit.to_string(format='<STR_LIT>')<EOL><DEDENT>return data<EOL> | Returns the representation for serialization | f13304:c7:m33 |
@staticmethod<EOL><INDENT>def _to_python_type(variable):<DEDENT> | <EOL>try:<EOL><INDENT>return variable.item()<EOL><DEDENT>except AttributeError:<EOL><INDENT>return variable<EOL><DEDENT> | Returns the value in the variable handling also np.array of one element
:param variable: input variable
:return: the value of the variable having a python type (int, float, ...) | f13304:c7:m34 |
@accept_quantity(float, allow_none=False)<EOL><INDENT>def _set_delta(self, delta):<DEDENT> | self._delta = delta<EOL> | Sets the current delta for the parameter. The delta is used as initial step by some fitting engines | f13304:c8:m3 |
def _get_internal_delta(self): | if self._transformation is None:<EOL><INDENT>return self._delta<EOL><DEDENT>else:<EOL><INDENT>delta_int = None<EOL>for i in range(<NUM_LIT:2>):<EOL><INDENT>low_bound_ext = self.value - self.delta<EOL>if low_bound_ext > self.min_value:<EOL><INDENT>low_bound_int = self._transformation.forward(low_bound_ext)<EOL>delta_int = abs(low_bound_int - self._get_internal_value())<EOL>break<EOL><DEDENT>else:<EOL><INDENT>hi_bound_ext = self.value + self._delta<EOL>if hi_bound_ext < self.max_value:<EOL><INDENT>hi_bound_int = self._transformation.forward(hi_bound_ext)<EOL>delta_int = abs(hi_bound_int - self._get_internal_value())<EOL>break<EOL><DEDENT>else:<EOL><INDENT>self.delta = abs(self.value - self.min_value) / <NUM_LIT><EOL>if self.delta == <NUM_LIT:0>:<EOL><INDENT>self.delta = abs(self.value - self.max_value) / <NUM_LIT><EOL><DEDENT>continue<EOL><DEDENT><DEDENT><DEDENT>assert delta_int is not None, "<STR_LIT>"<EOL>return delta_int<EOL><DEDENT> | This is only supposed to be used by fitting/sampling engine, to get the initial step in internal representation
:return: initial delta in internal representation | f13304:c8:m4 |
def _set_prior(self, prior): | if prior is None:<EOL><INDENT>self._prior = None<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>_ = prior(self.value)<EOL><DEDENT>except:<EOL><INDENT>raise NotCallableOrErrorInCall("<STR_LIT>" +<EOL>"<STR_LIT>")<EOL><DEDENT>try:<EOL><INDENT>prior.set_units(self.unit, u.dimensionless_unscaled)<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise NotCallableOrErrorInCall("<STR_LIT>")<EOL><DEDENT>self._prior = prior<EOL><DEDENT> | Set prior for this parameter. The prior must be a function accepting the current value of the parameter
as input and giving the probability density as output. | f13304:c8:m6 |
def has_prior(self): | return self._prior is not None<EOL> | Check whether the current parameter has a defined prior
:return: True or False | f13304:c8:m7 |
def set_uninformative_prior(self, prior_class): | prior_instance = prior_class()<EOL>if self.min_value is None:<EOL><INDENT>raise ParameterMustHaveBounds("<STR_LIT>"<EOL>"<STR_LIT>" % self.path)<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>prior_instance.lower_bound = self.min_value<EOL><DEDENT>except SettingOutOfBounds:<EOL><INDENT>raise SettingOutOfBounds("<STR_LIT>" % (self.min_value,<EOL>prior_instance.name))<EOL><DEDENT><DEDENT>if self.max_value is None:<EOL><INDENT>raise ParameterMustHaveBounds("<STR_LIT>"<EOL>"<STR_LIT>" % self.path)<EOL><DEDENT>else: <EOL><INDENT>try:<EOL><INDENT>prior_instance.upper_bound = self.max_value<EOL><DEDENT>except SettingOutOfBounds:<EOL><INDENT>raise SettingOutOfBounds("<STR_LIT>" % (self.max_value,<EOL>prior_instance.name))<EOL><DEDENT><DEDENT>assert np.isfinite(prior_instance.upper_bound.value),"<STR_LIT>" % self.name<EOL>assert np.isfinite(prior_instance.lower_bound.value),"<STR_LIT>" % self.name<EOL>self._set_prior(prior_instance)<EOL> | 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) | f13304:c8:m8 |
def remove_auxiliary_variable(self): | if not self.has_auxiliary_variable():<EOL><INDENT>warnings.warn("<STR_LIT>", RuntimeWarning)<EOL><DEDENT>else:<EOL><INDENT>self._remove_child(self._aux_variable['<STR_LIT>'].name)<EOL>self._aux_variable = {}<EOL>self.free = self._old_free<EOL><DEDENT> | Remove an existing auxiliary variable
:return: | f13304:c8:m14 |
def has_auxiliary_variable(self): | if self._aux_variable:<EOL><INDENT>return True<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT> | Returns whether the parameter is linked to an auxiliary variable | f13304:c8:m15 |
@property<EOL><INDENT>def auxiliary_variable(self):<DEDENT> | return self._aux_variable['<STR_LIT>'], self._aux_variable['<STR_LIT>']<EOL> | Returns a tuple with the auxiliary variable and the law
:return: tuple (variable, law) | f13304:c8:m16 |
def to_dict(self, minimal=False): | data = super(Parameter, self).to_dict()<EOL>data['<STR_LIT>'] = self._is_normalization<EOL>if minimal:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>if self.has_auxiliary_variable():<EOL><INDENT>data['<STR_LIT:value>'] = '<STR_LIT>' % self._aux_variable['<STR_LIT>']._get_path()<EOL>aux_variable_law_data = collections.OrderedDict()<EOL>aux_variable_law_data[ self._aux_variable['<STR_LIT>'].name ] = self._aux_variable['<STR_LIT>'].to_dict()<EOL>data['<STR_LIT>'] = aux_variable_law_data<EOL><DEDENT>data['<STR_LIT>'] = self._to_python_type(self._delta)<EOL>data['<STR_LIT>'] = self.free<EOL>if self.has_prior():<EOL><INDENT>data['<STR_LIT>'] = {self.prior.name: self.prior.to_dict()}<EOL><DEDENT><DEDENT>return data<EOL> | Returns the representation for serialization | f13304:c8:m18 |
def xspec_abund(command_string=None): | if command_string is None:<EOL><INDENT>return _xspec.get_xsabund()<EOL><DEDENT>else:<EOL><INDENT>_xspec.set_xsabund(command_string)<EOL><DEDENT> | Change/Report the solar abundance table in use. See XSpec manual for help:
http://heasarc.nasa.gov/xanadu/xspec/manual/XSabund.html
:param command_string : the command string. If None, returns the current settings, otherwise set to the provided
settings
:return: Either none or the current setting | f13305:m0 |
def xspec_cosmo(H0=None,q0=None,lambda_0=None): | current_settings = _xspec.get_xscosmo()<EOL>if (H0 is None) and (q0 is None) and (lambda_0 is None):<EOL><INDENT>return current_settings<EOL><DEDENT>else:<EOL><INDENT>user_inputs = [H0, q0, lambda_0]<EOL>for i, current_setting in enumerate(current_settings):<EOL><INDENT>if user_inputs[i] is None:<EOL><INDENT>user_inputs[i] = current_setting<EOL><DEDENT><DEDENT>_xspec.set_xscosmo(*user_inputs)<EOL><DEDENT> | Define the Cosmology in use within the XSpec models. See Xspec manual for help:
http://heasarc.nasa.gov/xanadu/xspec/manual/XScosmo.html
All parameters can be modified or just a single parameter
:param H0: the hubble constant
:param q0:
:param lambda_0:
:return: Either none or the current setting (H_0, q_0, lambda_0) | f13305:m1 |
def xspec_xsect(command_string=None): | if command_string is None:<EOL><INDENT>return _xspec.get_xsxsect()<EOL><DEDENT>else:<EOL><INDENT>_xspec.set_xsxsect(command_string)<EOL><DEDENT> | Change/Report the photoionization cross sections in use for XSpec models. See Xspec manual for help:
http://heasarc.nasa.gov/xanadu/xspec/manual/XSxsect.html
:param command_string : the command string. If None, returns the current settings, otherwise set to the provided
settings
:return: Either none or the current setting | f13305:m2 |
def find_model_dat(): | <EOL>headas_env = os.environ.get("<STR_LIT>")<EOL>assert headas_env is not None, ("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>headas_env = os.path.expandvars(os.path.expanduser(headas_env))<EOL>assert os.path.exists(headas_env), "<STR_LIT>" % (headas_env)<EOL>inferred_path = os.path.dirname(headas_env)<EOL>final_path = os.path.join(inferred_path, '<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL>assert os.path.exists(final_path), "<STR_LIT>" % (final_path)<EOL>return os.path.abspath(final_path)<EOL> | Find the file containing the definition of all the models in Xspec
(model.dat) and return its path | f13307:m0 |
def get_models(model_dat_path): | <EOL>with open(model_dat_path) as f:<EOL><INDENT>model_dat = f.read()<EOL><DEDENT>if "<STR_LIT:\n>" in model_dat:<EOL><INDENT>model_dat = model_dat.replace("<STR_LIT:\r>", "<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>model_dat = model_dat.replace("<STR_LIT:\r>", "<STR_LIT:\n>")<EOL><DEDENT>lines = model_dat.split("<STR_LIT:\n>")<EOL>model_definitions = collections.OrderedDict()<EOL>for line in lines:<EOL><INDENT>match = re.match('''<STR_LIT>''', line)<EOL>if match is not None:<EOL><INDENT>tokens = line.split()<EOL>if len(tokens) == <NUM_LIT:7>:<EOL><INDENT>(model_name, n_parameters,<EOL>min_energy, max_energy,<EOL>library_function,<EOL>model_type,<EOL>flag) = line.split()<EOL><DEDENT>else:<EOL><INDENT>(model_name, n_parameters,<EOL>min_energy, max_energy,<EOL>library_function,<EOL>model_type,<EOL>flag,<EOL>flag_2) = line.split()<EOL><DEDENT>this_model = collections.OrderedDict()<EOL>this_model['<STR_LIT:description>'] = '<STR_LIT>''<STR_LIT>' % model_name<EOL>this_model['<STR_LIT>'] = collections.OrderedDict()<EOL>model_definitions[(model_name, library_function, model_type)] = this_model<EOL><DEDENT>else:<EOL><INDENT>if len(line.split()) == <NUM_LIT:0>:<EOL><INDENT>continue<EOL><DEDENT>free = True<EOL>if line[<NUM_LIT:0>] == '<STR_LIT:$>':<EOL><INDENT>free = False<EOL>tokens = line.split()<EOL>if len(tokens) == <NUM_LIT:2>:<EOL><INDENT>par_name = tokens[<NUM_LIT:0>][<NUM_LIT:1>:]<EOL>default_value = tokens[<NUM_LIT:1>]<EOL>par_unit = "<STR_LIT>"<EOL>hard_minimum, soft_minimum, soft_maximum, hard_maximum = (<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT>, <NUM_LIT>)<EOL><DEDENT>elif len(tokens) == <NUM_LIT:3>:<EOL><INDENT>par_name = tokens[<NUM_LIT:0>][<NUM_LIT:1>:]<EOL>default_value = tokens[<NUM_LIT:2>]<EOL>par_unit = "<STR_LIT>"<EOL>hard_minimum, soft_minimum, soft_maximum, hard_maximum = (<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT>, <NUM_LIT>)<EOL><DEDENT>else:<EOL><INDENT>match = re.match('<STR_LIT>', line[<NUM_LIT:1>:])<EOL>par_name, par_unit, par_spec = match.groups()<EOL>tokens = par_spec.split()<EOL>if len(tokens) == <NUM_LIT:1>:<EOL><INDENT>default_value = tokens[<NUM_LIT:0>]<EOL>par_unit = "<STR_LIT>"<EOL>hard_minimum, soft_minimum, soft_maximum, hard_maximum = (<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT>, <NUM_LIT>)<EOL><DEDENT>else:<EOL><INDENT>par_unit = "<STR_LIT>"<EOL>(default_value,<EOL>hard_minimum, soft_minimum,<EOL>soft_maximum, hard_maximum,<EOL>delta) = par_spec.split()<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>match = re.match('<STR_LIT>', line)<EOL>if match is None:<EOL><INDENT>raise RuntimeError("<STR_LIT>" % line)<EOL><DEDENT>par_name, par_unit, par_spec = match.groups()<EOL>if par_name[<NUM_LIT:0>] == '<STR_LIT:*>':<EOL><INDENT>par_name = par_name[<NUM_LIT:1>:]<EOL>free = False<EOL>tokens = par_spec.split()<EOL>if len(tokens) == <NUM_LIT:1>:<EOL><INDENT>default_value = tokens[<NUM_LIT:0>]<EOL>(hard_minimum, soft_minimum,<EOL>soft_maximum, hard_maximum,<EOL>delta) = (None, None, None, None, <NUM_LIT:0.1>)<EOL><DEDENT>else:<EOL><INDENT>(default_value,<EOL>hard_minimum, soft_minimum,<EOL>soft_maximum, hard_maximum,<EOL>delta) = par_spec.split()<EOL>delta = abs(float(delta))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>(default_value,<EOL>hard_minimum, soft_minimum,<EOL>soft_maximum, hard_maximum,<EOL>delta) = par_spec.split()<EOL>delta = float(delta)<EOL>if delta <= <NUM_LIT:0>:<EOL><INDENT>free = False<EOL>delta = abs(delta)<EOL><DEDENT><DEDENT><DEDENT>par_name = re.sub('<STR_LIT>', '<STR_LIT:_>', par_name)<EOL>par_name = re.sub('<STR_LIT:<>', '<STR_LIT>', par_name)<EOL>par_name = re.sub('<STR_LIT:>>', '<STR_LIT>', par_name)<EOL>par_name = re.sub('<STR_LIT:/>', '<STR_LIT>', par_name)<EOL>par_name = re.sub('<STR_LIT>', '<STR_LIT>', par_name)<EOL>par_name = re.sub('<STR_LIT>', '<STR_LIT>', par_name)<EOL>par_name = re.sub('<STR_LIT>', '<STR_LIT>', par_name)<EOL>par_name = re.sub('<STR_LIT:@>', '<STR_LIT>', par_name)<EOL>par_name = par_name.lower()<EOL>par_name = par_name.replace('<STR_LIT:">', '<STR_LIT>')<EOL>if par_name == "<STR_LIT:z>":<EOL><INDENT>par_name = "<STR_LIT>"<EOL><DEDENT>if par_name in illegal_variable_names:<EOL><INDENT>par_name = "<STR_LIT>" % par_name<EOL><DEDENT>if par_unit:<EOL><INDENT>par_unit = par_unit.replace("<STR_LIT>",'<STR_LIT>')<EOL><DEDENT>if par_unit == "<STR_LIT>":<EOL><INDENT>par_unit = "<STR_LIT>"<EOL><DEDENT>elif par_unit == "<STR_LIT>":<EOL><INDENT>par_unit = "<STR_LIT>"<EOL><DEDENT>elif par_unit == "<STR_LIT>":<EOL><INDENT>par_unit = "<STR_LIT>"<EOL><DEDENT>elif par_unit == "<STR_LIT:z>" and par_name.lower() == "<STR_LIT>":<EOL><INDENT>par_unit = "<STR_LIT>"<EOL><DEDENT>try:<EOL><INDENT>_ = u.Unit(par_unit)<EOL><DEDENT>except ValueError:<EOL><INDENT>par_unit = '<STR_LIT>'<EOL><DEDENT>if re.match('<STR_LIT>', par_name) is None:<EOL><INDENT>raise ValueError("<STR_LIT>" % (par_name))<EOL><DEDENT>this_model['<STR_LIT>'][par_name] = {'<STR_LIT>': float(default_value),<EOL>'<STR_LIT>': '<STR_LIT>'<EOL>'<STR_LIT>',<EOL>'<STR_LIT>': hard_minimum,<EOL>'<STR_LIT>': hard_maximum,<EOL>'<STR_LIT>': float(delta),<EOL>'<STR_LIT>': par_unit,<EOL>'<STR_LIT>': free}<EOL><DEDENT><DEDENT>return model_definitions<EOL> | Parse the model.dat file from Xspec and returns a dictionary containing the definition of all the models
:param model_dat_path: the path to the model.dat file
:return: dictionary containing the definition of all XSpec models | f13307:m1 |
def dict_to_table(dictionary, list_of_keys=None): | <EOL>table = Table()<EOL>if len(dictionary) > <NUM_LIT:0>:<EOL><INDENT>table['<STR_LIT:name>'] = dictionary.keys()<EOL>prototype = dictionary.values()[<NUM_LIT:0>]<EOL>column_names = prototype.keys()<EOL>if list_of_keys is not None:<EOL><INDENT>column_names = filter(lambda key: key in list_of_keys, column_names)<EOL><DEDENT>for column_name in column_names:<EOL><INDENT>table[column_name] = map(lambda x: x[column_name], dictionary.values())<EOL><DEDENT><DEDENT>return table<EOL> | Return a table representing the dictionary.
:param dictionary: the dictionary to represent
:param list_of_keys: optionally, only the keys in this list will be inserted in the table
:return: a Table instance | f13308:m0 |
def _base_repr_(self, html=False, show_name=True, **kwargs): | table_id = '<STR_LIT>'.format(id=id(self))<EOL>data_lines, outs = self.formatter._pformat_table(self,<EOL>tableid=table_id, html=html, max_width=(-<NUM_LIT:1> if html else None),<EOL>show_name=show_name, show_unit=None, show_dtype=False)<EOL>out = '<STR_LIT:\n>'.join(data_lines)<EOL>return out<EOL> | Override the method in the astropy.Table class
to avoid displaying the description, and the format
of the columns | f13308:c0:m0 |
def long_path_formatter(line, max_width=pd.get_option('<STR_LIT>')): | if len(line) > max_width:<EOL><INDENT>tokens = line.split("<STR_LIT:.>")<EOL>trial1 = "<STR_LIT>" % (tokens[<NUM_LIT:0>], tokens[-<NUM_LIT:1>])<EOL>if len(trial1) > max_width:<EOL><INDENT>return "<STR_LIT>" %(tokens[-<NUM_LIT:1>][-<NUM_LIT:1>:-(max_width-<NUM_LIT:3>)])<EOL><DEDENT>else:<EOL><INDENT>return trial1<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return line<EOL><DEDENT> | If a path is longer than max_width, it substitute it with the first and last element,
joined by "...". For example 'this.is.a.long.path.which.we.want.to.shorten' becomes
'this...shorten'
:param line:
:param max_width:
:return: | f13309:m0 |
def dict_to_list(dictionary, html=False): | if html:<EOL><INDENT>return _process_html(dictionary)<EOL><DEDENT>else:<EOL><INDENT>return _process_text(dictionary)<EOL><DEDENT> | Convert a dictionary into a unordered list.
:param dictionary: a dictionary
:param html: whether to output HTML or simple text (True or False)
:return: the list | f13311:m2 |
def _get_data_file_path(data_file): | try:<EOL><INDENT>file_path = pkg_resources.resource_filename("<STR_LIT>", '<STR_LIT>' % data_file)<EOL><DEDENT>except KeyError:<EOL><INDENT>raise IOError("<STR_LIT>"<EOL>"<STR_LIT>" % (data_file))<EOL><DEDENT>else:<EOL><INDENT>return os.path.abspath(file_path)<EOL><DEDENT> | Returns the absolute path to the required data files.
:param data_file: relative path to the data file, relative to the astromodels/data path.
So to get the path to data/dark_matter/gammamc_dif.dat you need to use data_file="dark_matter/gammamc_dif.dat"
:return: absolute path of the data file | f13312:m0 |
def is_valid_variable_name(string_to_check): | try:<EOL><INDENT>parse('<STR_LIT>'.format(string_to_check))<EOL>return True<EOL><DEDENT>except (SyntaxError, ValueError, TypeError):<EOL><INDENT>return False<EOL><DEDENT> | Returns whether the provided name is a valid variable name in Python
:param string_to_check: the string to be checked
:return: True or False | f13313:m0 |
def angular_distance_fast(ra1, dec1, ra2, dec2): | lon1 = np.deg2rad(ra1)<EOL>lat1 = np.deg2rad(dec1)<EOL>lon2 = np.deg2rad(ra2)<EOL>lat2 = np.deg2rad(dec2)<EOL>dlon = lon2 - lon1<EOL>dlat = lat2 - lat1<EOL>a = np.sin(dlat/<NUM_LIT>)**<NUM_LIT:2> + np.cos(lat1) * np.cos(lat2) * np.sin(dlon /<NUM_LIT>)**<NUM_LIT:2><EOL>c = <NUM_LIT:2> * np.arcsin(np.sqrt(a))<EOL>return np.rad2deg(c)<EOL> | Compute angular distance using the Haversine formula. Use this one when you know you will never ask for points at
their antipodes. If this is not the case, use the angular_distance function which is slower, but works also for
antipodes.
:param lon1:
:param lat1:
:param lon2:
:param lat2:
:return: | f13314:m0 |
def angular_distance(ra1, dec1, ra2, dec2): | <EOL>lon1 = np.deg2rad(ra1)<EOL>lat1 = np.deg2rad(dec1)<EOL>lon2 = np.deg2rad(ra2)<EOL>lat2 = np.deg2rad(dec2)<EOL>sdlon = np.sin(lon2 - lon1)<EOL>cdlon = np.cos(lon2 - lon1)<EOL>slat1 = np.sin(lat1)<EOL>slat2 = np.sin(lat2)<EOL>clat1 = np.cos(lat1)<EOL>clat2 = np.cos(lat2)<EOL>num1 = clat2 * sdlon<EOL>num2 = clat1 * slat2 - slat1 * clat2 * cdlon<EOL>denominator = slat1 * slat2 + clat1 * clat2 * cdlon<EOL>return np.rad2deg(np.arctan2(np.sqrt(num1 ** <NUM_LIT:2> + num2 ** <NUM_LIT:2>), denominator))<EOL> | Returns the angular distance between two points, two sets of points, or a set of points and one point.
:param ra1: array or float, longitude of first point(s)
:param dec1: array or float, latitude of first point(s)
:param ra2: array or float, longitude of second point(s)
:param dec2: array or float, latitude of second point(s)
:return: angular distance(s) in degrees | f13314:m1 |
def spherical_angle( ra0, dec0, ra1, dec1, ra2, dec2 ): | a = np.deg2rad( angular_distance(ra0, dec0, ra1, dec1))<EOL>b = np.deg2rad( angular_distance(ra0, dec0, ra2, dec2))<EOL>c = np.deg2rad( angular_distance(ra2, dec2, ra1, dec1))<EOL>numerator = np.atleast_1d( np.cos(c) - np.cos(a) * np.cos(b) )<EOL>denominator = np.atleast_1d( np.sin(a)*np.sin(b) )<EOL>return np.where( denominator == <NUM_LIT:0> , np.zeros( len(denominator)), np.rad2deg( np.arccos( numerator/denominator)) )<EOL> | Returns the spherical angle distance between two sets of great circles defined by (ra0, dec0), (ra1, dec1) and (ra0, dec0), (ra2, dec2)
:param ra0: array or float, longitude of intersection point(s)
:param dec0: array or float, latitude of intersection point(s)
:param ra1: array or float, longitude of first point(s)
:param dec1: array or float, latitude of first point(s)
:param ra2: array or float, longitude of second point(s)
:param dec2: array or float, latitude of second point(s)
:return: spherical angle in degrees | f13314:m2 |
def vincenty(lon0, lat0, a1, s): | lon0 = np.deg2rad(lon0)<EOL>lat0 = np.deg2rad(lat0)<EOL>a1 = np.deg2rad(a1)<EOL>s = np.deg2rad(s)<EOL>sina = np.cos(lat0) * np.sin(a1)<EOL>num1 = np.sin(lat0)*np.cos(s) + np.cos(lat0)*np.sin(s)*np.cos(a1)<EOL>den1 = np.sqrt(sina**<NUM_LIT:2> + (np.sin(lat0)*np.sin(s) - np.cos(lat0)*np.cos(a1))**<NUM_LIT:2>)<EOL>lat = np.rad2deg(np.arctan2(num1, den1))<EOL>num2 = np.sin(s)*np.sin(a1)<EOL>den2 = np.cos(lat0)*np.cos(s) - np.sin(lat0)*np.sin(s)*np.cos(a1)<EOL>L = np.arctan2(num2, den2)<EOL>lon = np.rad2deg(lon0 + L)<EOL>return lon, lat<EOL> | Returns the coordinates of a new point that is a given angular distance s away from a starting point (lon0, lat0) at bearing (angle from north) a1), to within a given precision
Note that this calculation is a simplified version of the full vincenty problem, which solves for the coordinates on the surface on an arbitrary ellipsoid. Here we only care about the surface of a sphere.
Note: All parameters are assumed to be given in DEGREES
:param lon0: float, longitude of starting point
:param lat0: float, latitude of starting point
:param a1: float, bearing to second point, i.e. angle between due north and line connecting 2 points
:param s: float, angular distance between the two points
:return: coordinates of second point in degrees | f13317:m0 |
def set_frame(self, new_frame): | assert isinstance(new_frame, BaseCoordinateFrame)<EOL>self._frame = new_frame<EOL> | Set a new frame for the coordinates (the default is ICRS J2000)
:param new_frame: a coordinate frame from astropy
:return: (none) | f13319:c0:m1 |
def get_total_spatial_integral(self, z=None): | dL= self.l_max.value-self.l_min.value if self.l_max.value > self.l_min.value else <NUM_LIT> + self.l_max.value - self.l_max.value<EOL>integral = np.sqrt( <NUM_LIT:2>*np.pi ) * self.sigma_b.value * self.K.value * dL <EOL>if isinstance( z, u.Quantity):<EOL><INDENT>z = z.value<EOL><DEDENT>return integral * np.power( <NUM_LIT> / np.pi, -<NUM_LIT:2> ) * np.ones_like( z )<EOL> | Returns the total integral (for 2D functions) or the integral over the spatial components (for 3D functions).
needs to be implemented in subclasses.
:return: an array of values of the integral (same dimension as z). | f13319:c0:m5 |
def get_total_spatial_integral(self, z=None): | if isinstance( z, u.Quantity):<EOL><INDENT>z = z.value<EOL><DEDENT>return np.ones_like( z )<EOL> | Returns the total integral (for 2D functions) or the integral over the spatial components (for 3D functions).
needs to be implemented in subclasses.
:return: an array of values of the integral (same dimension as z). | f13319:c1:m3 |
def get_total_spatial_integral(self, z=None): | if isinstance( z, u.Quantity):<EOL><INDENT>z = z.value<EOL><DEDENT>return np.ones_like( z )<EOL> | Returns the total integral (for 2D functions) or the integral over the spatial components (for 3D functions).
needs to be implemented in subclasses.
:return: an array of values of the integral (same dimension as z). | f13319:c2:m3 |
def get_total_spatial_integral(self, z=None): | if isinstance( z, u.Quantity):<EOL><INDENT>z = z.value<EOL><DEDENT>return np.ones_like( z )<EOL> | Returns the total integral (for 2D functions) or the integral over the spatial components (for 3D functions).
needs to be implemented in subclasses.
:return: an array of values of the integral (same dimension as z). | f13319:c3:m3 |
def get_total_spatial_integral(self, z=None): | if isinstance( z, u.Quantity):<EOL><INDENT>z = z.value<EOL><DEDENT>return np.ones_like( z )<EOL> | Returns the total integral (for 2D functions) or the integral over the spatial components (for 3D functions).
needs to be implemented in subclasses.
:return: an array of values of the integral (same dimension as z). | f13319:c4:m4 |
def set_frame(self, new_frame): | assert new_frame.lower() in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>' ]<EOL>self._frame = new_frame<EOL> | Set a new frame for the coordinates (the default is ICRS J2000)
:param new_frame: a coordinate frame from astropy
:return: (none) | f13319:c5:m4 |
def get_total_spatial_integral(self, z=None): | if isinstance( z, u.Quantity):<EOL><INDENT>z = z.value<EOL><DEDENT>return np.multiply(self.K.value,np.ones_like( z ) )<EOL> | Returns the total integral (for 2D functions) or the integral over the spatial components (for 3D functions).
needs to be implemented in subclasses.
:return: an array of values of the integral (same dimension as z). | f13319:c5:m7 |
def get_total_spatial_integral(self, z=None): | if isinstance( z, u.Quantity):<EOL><INDENT>z = z.value<EOL><DEDENT>return np.ones_like( z )<EOL> | Returns the total integral (for 2D functions) or the integral over the spatial components (for 3D functions).
needs to be implemented in subclasses.
:return: an array of values of the integral (same dimension as z). | f13319:c6:m3 |
def from_unit_cube(self, x): | mu = self.mu.value<EOL>sigma = self.sigma.value<EOL>sqrt_two = <NUM_LIT><EOL>if x < <NUM_LIT> or (<NUM_LIT:1> - x) < <NUM_LIT>:<EOL><INDENT>res = -<NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>res = mu + sigma * sqrt_two * erfcinv(<NUM_LIT:2> * (<NUM_LIT:1> - x))<EOL><DEDENT>return res<EOL> | Used by multinest
:param x: 0 < x < 1
:param lower_bound:
:param upper_bound:
:return: | f13320:c0:m3 |
def from_unit_cube(self, x): | x0 = self.x0.value<EOL>gamma = self.gamma.value<EOL>half_pi = <NUM_LIT><EOL>res = np.tan(np.pi * x - half_pi) * gamma + x0<EOL>return res<EOL> | Used by multinest
:param x: 0 < x < 1
:param lower_bound:
:param upper_bound:
:return: | f13320:c2:m3 |
def from_unit_cube(self, x): | cosdec_min = np.cos(deg2rad*(<NUM_LIT> + self.lower_bound.value))<EOL>cosdec_max = np.cos(deg2rad*(<NUM_LIT> + self.upper_bound.value))<EOL>v = x * (cosdec_max - cosdec_min)<EOL>v += cosdec_min<EOL>v = np.clip(v, -<NUM_LIT:1.0>, <NUM_LIT:1.0>)<EOL>dec = np.arccos(v)<EOL>dec = rad2deg * dec<EOL>dec -= <NUM_LIT><EOL>return dec<EOL> | Used by multinest
:param x: 0 < x < 1
:param lower_bound:
:param upper_bound:
:return: | f13320:c3:m4 |
def from_unit_cube(self, x): | mu = self.mu.value<EOL>sigma = self.sigma.value<EOL>sqrt_two = <NUM_LIT><EOL>if x < <NUM_LIT> or (<NUM_LIT:1> - x) < <NUM_LIT>:<EOL><INDENT>res = -<NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>res = mu + sigma * sqrt_two * erfcinv(<NUM_LIT:2> * (<NUM_LIT:1> - x))<EOL><DEDENT>return np.exp(res)<EOL> | Used by multinest
:param x: 0 < x < 1
:param lower_bound:
:param upper_bound:
:return: | f13320:c4:m3 |
def from_unit_cube(self, x): | lower_bound = self.lower_bound.value<EOL>upper_bound = self.upper_bound.value<EOL>low = lower_bound<EOL>spread = float(upper_bound - lower_bound)<EOL>par = x * spread + low<EOL>return par<EOL> | Used by multinest
:param x: 0 < x < 1
:param lower_bound:
:param upper_bound:
:return: | f13320:c5:m3 |
def from_unit_cube(self, x): | low = math.log10(self.lower_bound.value)<EOL>up = math.log10(self.upper_bound.value)<EOL>spread = up - low<EOL>par = <NUM_LIT:10> ** (x * spread + low)<EOL>return par<EOL> | Used by multinest
:param x: 0 < x < 1
:param lower_bound:
:param upper_bound:
:return: | f13320:c6:m3 |
def _custom_init_(self, model_name, other_name=None,log_interp = True): | <EOL>data_dir_path = get_user_data_path()<EOL>filename_sanitized = os.path.abspath(os.path.join(data_dir_path, '<STR_LIT>' % model_name))<EOL>if not os.path.exists(filename_sanitized):<EOL><INDENT>raise MissingDataFile("<STR_LIT>"<EOL>"<STR_LIT>" % (filename_sanitized))<EOL><DEDENT>self._data_file = filename_sanitized<EOL>with HDFStore(filename_sanitized) as store:<EOL><INDENT>self._data_frame = store['<STR_LIT>']<EOL>self._parameters_grids = collections.OrderedDict()<EOL>processed_parameters = <NUM_LIT:0><EOL>for key in store.keys():<EOL><INDENT>match = re.search('<STR_LIT>', key)<EOL>if match is None:<EOL><INDENT>continue<EOL><DEDENT>else:<EOL><INDENT>tokens = match.groups()<EOL>this_parameter_number = int(tokens[<NUM_LIT:0>])<EOL>this_parameter_name = str(tokens[<NUM_LIT:1>])<EOL>assert this_parameter_number == processed_parameters, "<STR_LIT>"<EOL>self._parameters_grids[this_parameter_name] = store[key]<EOL>processed_parameters += <NUM_LIT:1><EOL><DEDENT><DEDENT>self._energies = store['<STR_LIT>']<EOL>metadata = store.get_storer('<STR_LIT>').attrs.metadata<EOL>description = metadata['<STR_LIT:description>']<EOL>name = metadata['<STR_LIT:name>']<EOL>self._interpolation_degree = metadata['<STR_LIT>']<EOL>self._spline_smoothing_factor = metadata['<STR_LIT>']<EOL><DEDENT>function_definition = collections.OrderedDict()<EOL>function_definition['<STR_LIT:description>'] = description<EOL>function_definition['<STR_LIT>'] = '<STR_LIT>'<EOL>parameters = collections.OrderedDict()<EOL>parameters['<STR_LIT>'] = Parameter('<STR_LIT>', <NUM_LIT:1.0>)<EOL>parameters['<STR_LIT>'] = Parameter('<STR_LIT>', <NUM_LIT:1.0>)<EOL>for parameter_name in self._parameters_grids.keys():<EOL><INDENT>grid = self._parameters_grids[parameter_name]<EOL>parameters[parameter_name] = Parameter(parameter_name, grid.median(),<EOL>min_value=grid.min(),<EOL>max_value=grid.max())<EOL><DEDENT>if other_name is None:<EOL><INDENT>super(TemplateModel, self).__init__(name, function_definition, parameters)<EOL><DEDENT>else:<EOL><INDENT>super(TemplateModel, self).__init__(other_name, function_definition, parameters)<EOL><DEDENT>self._prepare_interpolators(log_interp)<EOL> | Custom initialization for this model
:param model_name: the name of the model, corresponding to the root of the .h5 file in the data directory
:param other_name: (optional) the name to be used as name of the model when used in astromodels. If None
(default), use the same name as model_name
:return: none | f13321:c5:m0 |
def get_function(function_name, composite_function_expression=None): | <EOL>if composite_function_expression is not None:<EOL><INDENT>return _parse_function_expression(composite_function_expression)<EOL><DEDENT>else:<EOL><INDENT>if function_name in _known_functions:<EOL><INDENT>return _known_functions[function_name]()<EOL><DEDENT>else:<EOL><INDENT>from astromodels.functions.template_model import TemplateModel, MissingDataFile<EOL>try:<EOL><INDENT>instance = TemplateModel(function_name)<EOL><DEDENT>except MissingDataFile:<EOL><INDENT>raise UnknownFunction("<STR_LIT>" %<EOL>(function_name, "<STR_LIT:U+002C>".join(list(_known_functions.keys()))))<EOL><DEDENT>else:<EOL><INDENT>return instance<EOL><DEDENT><DEDENT><DEDENT> | Returns the function "name", which must be among the known functions or a composite function.
:param function_name: the name of the function (use 'composite' if the function is a composite function)
:param composite_function_expression: composite function specification such as
((((powerlaw{1} + (sin{2} * 3)) + (sin{2} * 25)) - (powerlaw{1} * 16)) + (sin{2} ** 3.0))
:return: the an instance of the requested class | f13322:m4 |
def get_function_class(function_name): | if function_name in _known_functions:<EOL><INDENT>return _known_functions[function_name]<EOL><DEDENT>else:<EOL><INDENT>raise UnknownFunction("<STR_LIT>" %<EOL>(function_name, "<STR_LIT:U+002C>".join(list(_known_functions.keys()))))<EOL><DEDENT> | Return the type for the requested function
:param function_name: the function to return
:return: the type for that function (i.e., this is a class, not an instance) | f13322:m5 |
def _parse_function_expression(function_specification): | <EOL>unique_functions = set(re.findall(r'<STR_LIT>',function_specification))<EOL>instances = {}<EOL>for (unique_function, number) in unique_functions:<EOL><INDENT>complete_function_specification = "<STR_LIT>" % (unique_function, number)<EOL>if unique_function in _known_functions:<EOL><INDENT>function_class = _known_functions[unique_function]<EOL>if issubclass(function_class, Function):<EOL><INDENT>instance = function_class()<EOL>instances[complete_function_specification] = instance<EOL><DEDENT>else:<EOL><INDENT>raise FunctionDefinitionError("<STR_LIT>"<EOL>% unique_function )<EOL><DEDENT><DEDENT>else:<EOL><INDENT>import astromodels.functions.template_model<EOL>try:<EOL><INDENT>instance = astromodels.functions.template_model.TemplateModel(unique_function)<EOL><DEDENT>except astromodels.functions.template_model.MissingDataFile:<EOL><INDENT>raise UnknownFunction("<STR_LIT>"<EOL>"<STR_LIT>" % (unique_function, function_specification))<EOL><DEDENT>else:<EOL><INDENT>instances[complete_function_specification] = instance<EOL><DEDENT><DEDENT><DEDENT>if len(instances)==<NUM_LIT:0>:<EOL><INDENT>raise DesignViolation("<STR_LIT>")<EOL><DEDENT>string_for_literal_eval = function_specification<EOL>for function_expression in list(instances.keys()):<EOL><INDENT>string_for_literal_eval = string_for_literal_eval.replace(function_expression, '<STR_LIT>')<EOL><DEDENT>for operator in list(_operations.keys()):<EOL><INDENT>string_for_literal_eval = string_for_literal_eval.replace(operator,'<STR_LIT>')<EOL><DEDENT>if re.match('''<STR_LIT>''', string_for_literal_eval):<EOL><INDENT>raise DesignViolation("<STR_LIT>")<EOL><DEDENT>string_for_literal_eval = "<STR_LIT:U+002C>".join(string_for_literal_eval.split())<EOL>try:<EOL><INDENT>ast.literal_eval(string_for_literal_eval)<EOL><DEDENT>except (ValueError, SyntaxError):<EOL><INDENT>raise DesignViolation("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>sanitized_function_specification = function_specification<EOL>for function_expression in list(instances.keys()):<EOL><INDENT>sanitized_function_specification = sanitized_function_specification.replace(function_expression,<EOL>'<STR_LIT>' %<EOL>function_expression)<EOL><DEDENT>composite_function = eval(sanitized_function_specification, {}, {'<STR_LIT>': instances})<EOL>return composite_function<EOL><DEDENT> | Parse a complex function expression like:
((((powerlaw{1} + (sin{2} * 3)) + (sin{2} * 25)) - (powerlaw{1} * 16)) + (sin{2} ** 3.0))
and return a composite function instance
:param function_specification:
:return: a composite function instance | f13322:m7 |
@staticmethod<EOL><INDENT>def check_calling_sequence(name, function_name, function, possible_variables):<DEDENT> | <EOL>try:<EOL><INDENT>calling_sequence = inspect.getargspec(function.input_object).args<EOL><DEDENT>except AttributeError:<EOL><INDENT>calling_sequence = inspect.getargspec(function).args<EOL><DEDENT>assert calling_sequence[<NUM_LIT:0>] == '<STR_LIT>', "<STR_LIT>""<STR_LIT>" % name<EOL>variables = [var for var in calling_sequence if var in possible_variables]<EOL>assert len(variables) > <NUM_LIT:0>, "<STR_LIT>""<STR_LIT>" % (name, '<STR_LIT:U+002C>'.join(possible_variables), "<STR_LIT:U+002C>".join(variables))<EOL>if variables != possible_variables[:len(variables)]:<EOL><INDENT>raise AssertionError("<STR_LIT>"<EOL>% ("<STR_LIT:U+002C>".join(variables), function_name, name, possible_variables[:len(variables)]))<EOL><DEDENT>other_parameters = [var for var in calling_sequence if var not in variables and var != '<STR_LIT>']<EOL>return variables, other_parameters<EOL> | Check the calling sequence for the function looking for the variables specified.
One or more of the variables can be in the calling sequence. Note that the
order of the variables will be enforced.
It will also enforce that the first parameter in the calling sequence is called 'self'.
:param function: the function to check
:param possible_variables: a list of variables to check, The order is important, and will be enforced
:return: a tuple containing the list of found variables, and the name of the other parameters in the calling
sequence | f13322:c10:m3 |
@property<EOL><INDENT>def n_dim(self):<DEDENT> | return type(self)._n_dim<EOL> | :return: number of dimensions for this function (1, 2 or 3) | f13322:c11:m1 |
@property<EOL><INDENT>def free_parameters(self):<DEDENT> | free_parameters = collections.OrderedDict([(k,v) for k, v in self.parameters.items() if v.free])<EOL>return free_parameters<EOL> | Returns a dictionary of free parameters for this function
:return: dictionary of free parameters | f13322:c11:m2 |
@staticmethod<EOL><INDENT>def _generate_uuid():<DEDENT> | return uuid.UUID(bytes=os.urandom(<NUM_LIT:16>), version=<NUM_LIT:4>)<EOL> | Generate a unique identifier for this function.
:return: the UUID | f13322:c11:m3 |
def has_fixed_units(self): | return not (self._fixed_units is None)<EOL> | Returns True if this function cannot change units, which is the case only for very specific functions (like
models from foreign libraries like Xspec)
:return: True or False | f13322:c11:m4 |
@property<EOL><INDENT>def is_prior(self):<DEDENT> | return self._is_prior<EOL> | Returns False by default and must be overrided in the prior functions.
:return: True or False | f13322:c11:m5 |
@property<EOL><INDENT>def fixed_units(self):<DEDENT> | return self._fixed_units<EOL> | Returns the fixed units if has_fixed_units is True (see has_fixed_units)
:return: None, or a tuple (x_unit, y_unit) | f13322:c11:m6 |
@property<EOL><INDENT>def description(self):<DEDENT> | return self._function_definition['<STR_LIT:description>']<EOL> | Returns a description for this function | f13322:c11:m7 |
@property<EOL><INDENT>def parameters(self):<DEDENT> | return self._parameters<EOL> | Returns a dictionary of parameters | f13322:c11:m8 |
@property<EOL><INDENT>def latex(self):<DEDENT> | return self._function_definition['<STR_LIT>']<EOL> | Returns the LaTEX formula for this function | f13322:c11:m9 |
def of(self, another_function): | return CompositeFunction('<STR_LIT>', self, another_function)<EOL> | Compose this function with another as in this_function(another_function(x))
:param another_function: another function to compose with the current one
:return: a composite function instance | f13322:c11:m10 |
@property<EOL><INDENT>def uuid(self):<DEDENT> | return self._uuid<EOL> | Returns the ID of the current function. The ID is used by the CompositeFunction class to keep track of the
unique instances of each function. It should not be used by the user for any specific purpose.
:return: (none) | f13322:c11:m22 |
def duplicate(self): | <EOL>function_copy = copy.deepcopy(self)<EOL>return function_copy<EOL> | Create a copy of the current function with all the parameters equal to the current value
:return: a new copy of the function | f13322:c11:m23 |
def get_boundaries(self): | raise NotImplementedError("<STR_LIT>")<EOL> | Returns the boundaries of this function. By default there is no boundary, but subclasses can
override this.
:return: a tuple of tuples containing the boundaries for each coordinate (ra_min, ra_max), (dec_min, dec_max) | f13322:c11:m24 |
def evaluate_at(self, *args, **parameter_specification): | <EOL>for parameter in parameter_specification:<EOL><INDENT>self._get_child(parameter).value = parameter_specification[parameter]<EOL><DEDENT>return self(*args)<EOL> | Evaluate the function at the given x(,y,z) for the provided parameters, explicitly provided as part of the
parameter_specification keywords.
:param *args:
:param **parameter_specification:
:return: | f13322:c11:m27 |
def get_total_spatial_integral(self, z): | raise NotImplementedError("<STR_LIT>")<EOL> | Returns the total integral (for 2D functions) or the integral over the spatial components (for 3D functions).
needs to be implemented in subclasses.
:return: an array of values of the integral (same dimension as z). | f13322:c11:m28 |
@property<EOL><INDENT>def x_unit(self):<DEDENT> | return self._x_unit<EOL> | The unit of the independent variable
:return: a astropy.Unit instance | f13322:c12:m4 |
@property<EOL><INDENT>def y_unit(self):<DEDENT> | return self._y_unit<EOL> | The unit of the dependent variable
:return: a astropy.Unit instance | f13322:c12:m5 |
def get_boundaries(self): | raise DesignViolation("<STR_LIT>")<EOL> | Returns the boundaries of this function. By default there is no boundary, but subclasses can
override this.
:return: a tuple of tuples containing the boundaries for each coordinate (ra_min, ra_max), (dec_min, dec_max) | f13322:c12:m9 |
@property<EOL><INDENT>def functions(self):<DEDENT> | return self._functions<EOL> | A list containing the function used to build this composite function | f13322:c15:m5 |
def get_total_spatial_integral(self, z=None): | if isinstance( z, u.Quantity):<EOL><INDENT>z = z.value<EOL><DEDENT>return np.ones_like( z )<EOL> | Returns the total integral (for 2D functions) or the integral over the spatial components (for 3D functions).
needs to be implemented in subclasses.
:return: an array of values of the integral (same dimension as z). | f13323:c0:m3 |
def get_total_spatial_integral(self, z=None): | if isinstance( z, u.Quantity):<EOL><INDENT>z = z.value<EOL><DEDENT>return np.ones_like( z )<EOL> | Returns the total integral (for 2D functions) or the integral over the spatial components (for 3D functions).
needs to be implemented in subclasses.
:return: an array of values of the integral (same dimension as z). | f13323:c1:m3 |
def get_total_spatial_integral(self, z=None): | if isinstance( z, u.Quantity):<EOL><INDENT>z = z.value<EOL><DEDENT>return np.ones_like( z )<EOL> | Returns the total integral (for 2D functions) or the integral over the spatial components (for 3D functions).
needs to be implemented in subclasses.
:return: an array of values of the integral (same dimension as z). | f13323:c2:m3 |
@property<EOL><INDENT>def peak_energy(self):<DEDENT> | <EOL>return self.piv.value * pow(<NUM_LIT:10>, ((<NUM_LIT:2> + self.alpha.value) * np.log(<NUM_LIT:10>)) / (<NUM_LIT:2> * self.beta.value))<EOL> | Returns the peak energy in the nuFnu spectrum
:return: peak energy in keV | f13324:c23:m2 |
def sanitize_lib_name(library_path): | lib_name = os.path.basename(library_path)<EOL>tokens = re.findall("<STR_LIT>", lib_name)<EOL>if not tokens:<EOL><INDENT>raise RuntimeError('<STR_LIT>'%(lib_name,library_path))<EOL><DEDENT>return tokens[<NUM_LIT:0>][<NUM_LIT:0>]<EOL> | Get a fully-qualified library name, like /usr/lib/libgfortran.so.3.0, and returns the lib name needed to be
passed to the linker in the -l option (for example gfortran)
:param library_path:
:return: | f13332:m0 |
def find_library(library_root, additional_places=None): | <EOL>first_guess = ctypes.util.find_library(library_root)<EOL>if first_guess is not None:<EOL><INDENT>if sys.platform.lower().find("<STR_LIT>") >= <NUM_LIT:0>:<EOL><INDENT>return sanitize_lib_name(first_guess), None<EOL><DEDENT>elif sys.platform.lower().find("<STR_LIT>") >= <NUM_LIT:0>:<EOL><INDENT>return sanitize_lib_name(first_guess), os.path.dirname(first_guess)<EOL><DEDENT>else:<EOL><INDENT>raise NotImplementedError("<STR_LIT>" % sys.platform)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if sys.platform.lower().find("<STR_LIT>") >= <NUM_LIT:0>:<EOL><INDENT>possible_locations = os.environ.get("<STR_LIT>", "<STR_LIT>").split("<STR_LIT::>")<EOL><DEDENT>elif sys.platform.lower().find("<STR_LIT>") >= <NUM_LIT:0>:<EOL><INDENT>possible_locations = os.environ.get("<STR_LIT>", "<STR_LIT>").split("<STR_LIT::>")<EOL><DEDENT>else:<EOL><INDENT>raise NotImplementedError("<STR_LIT>" % sys.platform)<EOL><DEDENT>if additional_places is not None:<EOL><INDENT>possible_locations.extend(additional_places)<EOL><DEDENT>library_name = None<EOL>library_dir = None<EOL>for search_path in possible_locations:<EOL><INDENT>if search_path == "<STR_LIT>":<EOL><INDENT>continue<EOL><DEDENT>results = glob.glob(os.path.join(search_path, "<STR_LIT>" % library_root))<EOL>if len(results) >= <NUM_LIT:1>:<EOL><INDENT>for result in results:<EOL><INDENT>if re.match("<STR_LIT>" % library_root, os.path.basename(result)) is None:<EOL><INDENT>continue<EOL><DEDENT>else:<EOL><INDENT>library_name = result<EOL>library_dir = search_path<EOL>break<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>continue<EOL><DEDENT>if library_name is not None:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if library_name is None:<EOL><INDENT>return None, None<EOL><DEDENT>else:<EOL><INDENT>return sanitize_lib_name(library_name), library_dir<EOL><DEDENT><DEDENT> | Returns the name of the library without extension
:param library_root: root of the library to search, for example "cfitsio_" will match libcfitsio_1.2.3.4.so
:return: the name of the library found (NOTE: this is *not* the path), and a directory path if the library is not
in the system paths (and None otherwise). The name of libcfitsio_1.2.3.4.so will be cfitsio_1.2.3.4, in other words,
it will be what is needed to be passed to the linker during a c/c++ compilation, in the -l option | f13332:m1 |
def register(self, event_name): | def registrar(func):<EOL><INDENT>self.callbacks[event_name].append(func)<EOL>return func<EOL><DEDENT>return registrar<EOL> | Decorator,
Registers the decorated function as a callback for the `event_name`
given.
:param event_name: The name of the event to register for.
Example:
>>> callbacks = Callbacks()
>>> @callbacks.register("my_event")
... def hello():
... print("Hello world")
...
>>> # Which then can be called
>>> callbacks.call("my_event")
Hello world | f13336:c0:m1 |
def send(self, event_name, *args, **kwargs): | for callback in self.callbacks[event_name]:<EOL><INDENT>callback(*args, **kwargs)<EOL><DEDENT> | Method,
Calls all callbacks registered for `event_name`. The arguments given
are passed to each callback.
:param event_name: The event name to call the callbacks for.
:param args: The positional arguments passed to the callbacks.
:param kwargs: The keyword arguments passed to the callbacks.
Example:
>>> callbacks = Callbacks()
>>> @callbacks.register("my_event")
... def hello(your_name):
... print("Hello %s, how are you today." % your_name)
...
>>> callbacks.call("my_event", "Wessie")
Hello Wessie, how are you today. | f13336:c0:m2 |
def filter(filter_creator): | filter_func = [None]<EOL>def function_getter(function):<EOL><INDENT>if isinstance(function, Filter):<EOL><INDENT>function.add_filter(filter)<EOL>return function<EOL><DEDENT>else:<EOL><INDENT>return Filter(<EOL>filter=filter_func[<NUM_LIT:0>],<EOL>callback=function,<EOL>)<EOL><DEDENT><DEDENT>def filter_decorator(*args, **kwargs):<EOL><INDENT>filter_function = filter_creator(*args, **kwargs)<EOL>filter_func[<NUM_LIT:0>] = filter_function<EOL>return function_getter<EOL><DEDENT>return filter_decorator<EOL> | Creates a decorator that can be used as a filter.
.. warning::
This is currently not compatible with most other decorators, if
you are using a decorator that isn't part of `hurler` you should
take caution. | f13337:m0 |
def filter_simple(filter): | def function_getter(function):<EOL><INDENT>if isinstance(function, Filter):<EOL><INDENT>function.add_filter(filter)<EOL>return function<EOL><DEDENT>else:<EOL><INDENT>return Filter(<EOL>filter=filter,<EOL>callback=function,<EOL>)<EOL><DEDENT><DEDENT>return function_getter<EOL> | A simpler version of :func:`filter`. This instead assumes the decorated
function is already a valid filter function, and uses it directly. | f13337:m1 |
def check_filter(self, args, kwargs): | for f in self._filters:<EOL><INDENT>if not f(*args, **kwargs):<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<EOL> | Calls all filters in the :attr:`_filters` list and if all of them
return :const:`True` will return :const:`True`. If any of the filters
return :const:`False` will return :const:`True` instead.
This method is equal to the following snippet:
`all(f(*args, **kwargs) for f in self.filters)` | f13337:c0:m1 |
def add_filter(self, filter): | self._filters.append(filter)<EOL> | Adds a filter to the list of filters to be called. | f13337:c0:m2 |
@filter<EOL>def dice_result(equal=None, higher_than=None, lower_than=None): | if not equal is None:<EOL><INDENT>return (lambda result: result == equal)<EOL><DEDENT>if not higher_than is None:<EOL><INDENT>return (lambda result: result > higher_than)<EOL><DEDENT>if not lower_than is None:<EOL><INDENT>return (lambda result: result < lower_than)<EOL><DEDENT>raise ValueError("<STR_LIT>")<EOL> | A simple filter that checks if the given result is higher, lower than or
equal to the passed value. It only supports one at a time though. | f13339:m0 |
@callback_register.register("<STR_LIT>")<EOL>def roll_dice(amount_of_dice=<NUM_LIT:1>, faces=<NUM_LIT:6>): | for _ in range(amount_of_dice):<EOL><INDENT>result = random.choice(range(<NUM_LIT:1>, faces + <NUM_LIT:1>))<EOL>callback_register.send("<STR_LIT>", result)<EOL><DEDENT> | A simple callback that rolls a dice and calls all callbacks
registered for the event `dice_result` with each result found.
:param amount_of_dice: The amount of dices to roll.
:param faces: The amount of faces each dice has. | f13339:m2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.