galapy.internal.utils
Functions
|
Converts an ASCII (e.g. Topcat-like) catalogue into a 2-levels dictionary. |
|
Function for filtering a list of strings (uses |
|
Function finding the indexes of array closer to the values in value. |
|
A function applying some function to a scalar or an ndarray. |
|
Find lower and upper limits in sample array containing given percent value around position. |
|
|
Generates a string with the minute the function is called |
|
|
Method for computing N-order polynomia. |
|
Returns a powerlaw with exponential cut-off of the form |
|
Very close to numpy.percentile, but supports weights. |
|
Recursive function for setting values in a nested dictionary. |
|
Function for shortening a string, splitting it in components. |
|
Trapezoid integration |
|
Generator yielding the items of a nested dictionary |
|
Generator yielding the keys of a nested dictionary |
Generator yielding the values of a nested dictionary |
Classes
|
- galapy.internal.utils.trap_int(xx, yy)
Trapezoid integration
- Parameters:
xx (array-like) – x-domain grid
yy (array-like) – y-domain grid
- Returns:
the integral along the whole x-domain
- Return type:
float
- galapy.internal.utils.find_nearest(array, value)
Function finding the indexes of array closer to the values in value.
- Parameters:
array (array-like)
value (array-like or scalar)
- Returns:
list of indexes of elements in array closer to values in value.
- Return type:
numpy-array
Warning
Uniqueness of elements in the returned array is not guaranteed.
- galapy.internal.utils.powerlaw_exp_cutoff(El, gamma, Ecut)
Returns a powerlaw with exponential cut-off of the form
\[y = E_\lambda^{-\gamma+3} e^{E_\lambda/E_\text{cut}}\]- Parameters:
El (scalar or array-like) – the x-values
gamma (scalar) – the spectral index
Ecut (scalar) – the cut-off x-scale
- Return type:
scalar or array-like
- galapy.internal.utils.poly_N(xx, coeff)
Method for computing N-order polynomia. The order of the polynomium is set by the length of the coeff list.
The method computes
\[y = \sum_0^N c_i * x^{N-i}\]- Parameters:
xx (scalar or array-like) – the x-values
coeff (list) – the values of the coefficients of the polynomium. The list must be ordered, with the first element corresponding to the coefficient multiplying the highest power of the x-variable and the last coefficient being the scalar coefficient
- Returns:
the y-values
- Return type:
scalar or array-like
- galapy.internal.utils.unwrap_keys(d)
Generator yielding the keys of a nested dictionary
- Parameters:
d (dictionary) – A nested dictionary (whathever object inheriting from ‘dict’ or collections.abc.MutableMapping or similar)
- Yields:
list of keys
Examples
>>> d = { 'a' : 1, 'b' : { 'c' : 2, 'd' : 3 } } >>> for i in unwrap_keys( d ) : print( i ) ['a'] ['b', 'c'] ['b', 'd']
- galapy.internal.utils.unwrap_values(d)
Generator yielding the values of a nested dictionary
- Parameters:
d (dictionary) – A nested dictionary (whathever object inheriting from ‘dict’ or collections.abc.MutableMapping or similar)
- Yields:
values
Examples
>>> d = { 'a' : 1, 'b' : { 'c' : 2, 'd' : 3 } } >>> for i in unwrap_values( d ) : print( i ) 1 2 3
- galapy.internal.utils.unwrap_items(d)
Generator yielding the items of a nested dictionary
- Parameters:
d (dictionary) – A nested dictionary (whathever object inheriting from ‘dict’ or collections.abc.MutableMapping or similar)
- Yields:
items – a 2d tuple in which the first element is the list of nested keys and the second is the associated value
Examples
>>> d = { 'a' : 1, 'b' : { 'c' : 2, 'd' : 3 } } >>> for i in unwrap_items( d ) : print( i ) (['a'], 1) (['b', 'c'], 2) (['b', 'd'], 3)
- galapy.internal.utils.set_nested(d, kl, v)
Recursive function for setting values in a nested dictionary.
- Parameters:
d (dictionary) – the i/o dictionary
kl (list) – a list of keywords to traverse the nested dictionary the first element is the highest position in the hierarchy of the nested dictionary
v (whatever) – the value to set at corresponding nested sequence of keywords
- Return type:
None
Examples
>>> d = {} >>> kl1 = ['first', 'second', 'third'] >>> kl2 = ['a', 'b', 'c'] >>> set_nested(d,kl1, 3.) >>> set_nested(d,kl2, True) >>> d {'first': {'second': {'third': 3.0}}, 'a': {'b': True}}
If we want to add a new key-value pair to an already existing level:
>>> kl3 = ['first', 'second', 'fourth'] >>> set_nested(d, kl3, 4.) >>> d {'first': {'second': {'third': 3.0, 'fourth': 4.0}},'a': {'b': True}}
- galapy.internal.utils.func_scalar_or_array(var, function, *args, **kwargs)
A function applying some function to a scalar or an ndarray.
- Parameters:
var (scalar or ndarray) – The argument of the function
function (callable) – A function taking a scalar as input
args (sequence) – A list or tuple of additional arguments to be passed to function
kwargs (dict) – A dictionary of additional keyword arguments to be passed to function
- Returns:
Depends on the shape of
var: (i) ifvaris a scalar it is the result offunction(var); (ii) ifvaris an ndarray it is the result ofarray([function(v) for v in var])- Return type:
scalar or ndarray
- galapy.internal.utils.quantile_weighted(values, quantiles, weights=None, values_sorted=False, old_style=False, axis=-1)
Very close to numpy.percentile, but supports weights. (partially stolen from stackoverflow: https://stackoverflow.com/questions/21844024/weighted-percentile-using-numpy)
- Parameters:
values (numpy.array) – with data
quantiles (array-like) – quantiles needed (NOTE: quantiles should be in [0, 1]!)
sample_weight (array-like) – same length as
valuesvalues_sorted (bool) – if True, then will avoid sorting of initial array
old_style (bool) – if True, will correct output to be consistent with numpy.percentile.
axis (int)
- Returns:
computed quantiles.
- Return type:
numpy.array
- galapy.internal.utils.get_credible_interval(samples, idcentre, percent=0.68, weights=None)
Find lower and upper limits in sample array containing given percent value around position.
It splits the samples in 2 half-intervals: [lower, samples[idcentre]) and [samples[idcentre], upper) that are set to contain 0.5*percent of all the weighted samples. If one of the two half-intervals does not have enough samples, it is considered un-defined. When this happens, the function consider it instead an upper/lower limit on the sampled parameter and returns instead (None, upper-limit) or (lower-limit, None).
- Parameters:
samples (ndarray or iterable) – the weighted samples over which to compute the estimator
idcentre (integer) – index in the samples iterable around which to compute the interval
percent (float) – probability enclosed by the interval
weights – (Optional, default = None) weights of the samples, if not None this must have the same size of the samples argument
- Returns:
lower, upper – [lower-, upper-) limits of the interval if the interval is defined. If it is not defined, the function will return either an upper limit or a lower limit, respectively.
- Return type:
scalar floats
- galapy.internal.utils.now_string()
Generates a string with the minute the function is called
- galapy.internal.utils.filter_strings(inlist, fields)
Function for filtering a list of strings (uses
fnmatch)- Parameters:
inlist (sequence of str) – A list of strings to filter
fields (str or sequence of str) – Either a single string or a sequence of strings. Also accepts wildcards (e.g.
which_params = 'sfh*'will show all the entries ininlistthat contain the sub-stringsfh).
- Return type:
str or sequence of str
- Raises:
ValueError –
- galapy.internal.utils.shorten_string(string, maxlength=10, splitchar='.')
Function for shortening a string, splitting it in components.
- Parameters:
string (str) – Input string
maxlength (int) – (default = 10) Maximum number of characters in the final string
splitchar (str) – (default = ‘.’) The character over which perform the splitting.
- Returns:
str
The shortened string with length <= maxlength+len(splitchar)
- galapy.internal.utils.cat_to_dict(infile, id_field='id', err_field='_err', meta_fields=[], skip_fields=[])
Converts an ASCII (e.g. Topcat-like) catalogue into a 2-levels dictionary. The 1st order dictionary contains a 2nd order dictionary for each entry in the catalogue. Each 2nd order dictionary contains data and meta-data about the named entry.
- Parameters:
infile (str) – Path to the ASCII file
id_field (str) – (Optional, default=’id’) header name of the field containing the sources’ ID
err_field (str) – (Optional, default=’_err’) the sub-string identifying fields containing error measurements
meta_fields (str or sequence of str) – (Optional, default empty list) which fields to consider meta-data Either a single string or a sequence of strings. Also accepts wildcards (e.g.
meta_fields = 'R*'will consider all the fields in header that start withRas meta-data).skip_fields (str or sequence of str) – (Optional, default empty list) which fields to skip Either a single string or a sequence of strings. Also accepts wildcards (e.g.
skip_fields = 'R*'will ignore all the fields in header that start withR).
- Return type:
dict