BASTA utility functions

Utility functions for the distance calculation and parallax fitting

utils_distances.EDSD(libitem, index)[source]

Exponentially decreasing space density prior Define characteristic length scale k in kpc

utils_distances.compute_absmag(m, dist, A)[source]

Use distance moduli to compute the absolute magnitudes from distances, apparent magnitudes m, and absorption A.

Parameters:
  • m (float) – Apparent magnitude

  • dist (float) – Distances in parsec

  • A (float) – Absorption

Returns:

M (float) – Absolute magnitude

utils_distances.compute_distlikelihoods(r, plxobs, plxobs_err, L=None, outfilename='', debug=False)[source]

Compute the likelihood as the product between a gaussian of the parallax and the exponentially decreasing volume density prior. For the unnormalised posterior, see Eq. 18 in Bailer-Jones 2015. This also works for nonpositive parallaxes.

utils_distances.distance_from_mag(m, M, A)[source]

Compute distance from magnitudes.

Parameters:
  • m (float) – Apparent magnitude

  • M (float) – Absolute magnitude

  • A (float) – Absorption

Returns:

d (float) – distance in parsec

utils_distances.loggaussian(x, mu, sigma)[source]

Compute the log of a gaussian.

Parameters:
  • x (array-like) – Data

  • mu (float) – The mean of x

  • sigma (float) – Standard deviation of x

Returns:

loggaussian (array) – The gaussian data

General mix of utility functions

class utils_general.Logger(outfilename)[source]

Class used to redefine stdout to terminal and an output file.

Parameters:

outfilename (str) – Absolute path to an output file

utils_general.add_out(hout, out, par, x, xm, xp, uncert)[source]

Add entries in out list, according to the wanted uncertainty.

Parameters:
  • hout (list) – Names in header

  • out (list) – Parameter values

  • par (str) – Parameter name

  • x (float) – Centroid value

  • xm (float) – Lower bound uncertainty, or symmetric uncertainty

  • xp (float, None) – Upper bound uncertainty if not symmetric uncertainty (None for symmetric)

  • uncert (str) – Type of reported uncertainty, “quantiles” or “std”

Returns:

  • hout (list) – Header list with added names

  • out (list) – Parameter list with added entries

utils_general.compare_output_to_input(starid, inputparams, hout, out, hout_dist, out_dist, uncert='qunatiles', sigmacut=1)[source]

This function compares the outputted value of all fitting parameters to the input that was fitted.

If one or more fitting parameters deviates more than ‘sigmacut’ number of the effective symmetric uncertainty away from their input parameter, a warning is printed and ‘starid’ is appended to the .warn-file.

Parameters:
  • starid (str) – Unique identifier of current target.

  • inputparms (dict) – Dict containing input from xml-file.

  • hout (list) – List of column headers for output

  • out (list) – List of output values for the columns given in hout.

  • uncert (str) – Type of reported uncertainty to use for comparison.

  • sigmacut (float, optional) – Number of standard deviation used for determining when to issue a warning.

Returns:

comparewarn (bool) – Flag to determine whether or not a warning was raised.

utils_general.get_parameter_values(parameter, Grid, selectedmodels, noofind)[source]

Get parameter values from grid

Parameters:
  • parameter (str) – Grid, hdf5 object

  • selectedmodels – models to return

  • noofind – number of parameter values

Returns:

x_all (array) – parameter values

utils_general.h5py_to_array(xs)[source]

Copy vector/dataset from an HDF5 file to a NumPy array

Parameters:

xs (h5py_dataset) – The input dataset read by h5py from an HDF5 object

Returns:

res (array_like) – Copy of the dataset as NumPy array

utils_general.inflog(x)[source]

np.log(x), but where x=0 returns -inf without a warning

utils_general.list_metallicities(Grid, defaultpath, inputparams, limits)[source]

Get a list of metallicities in the grid that we loop over

Parameters:
  • Grid (hdf5 object) – The already loaded grid, containing the tracks/isochrones.

  • defaultpath (str) – Path in Grid

  • inputparams (dict) – Dictionary of all controls and input.

  • limits (dict) – Dict of flat priors used in run.

Returns:

metal (list) – List of possible metalliticies that should be looped over in bastamain.

utils_general.printparam(param, xmed, xstdm, xstdp, uncert='quantiles', centroid='median')[source]

Pretty-print of output parameter to log and console.

Parameters:
  • param (str) – Name of parameter

  • xmed (float) – Centroid value (median or mean)

  • xstdm (float) – Lower bound uncertainty, or symmetric unceartainty

  • xstdp (float) – Upper bound uncertainty, if not symmetric. Unused if uncert is std.

  • uncert (str, optional) – Type of reported uncertainty, “quantiles” or “std”

  • centroid (str, optional) – Type of reported uncertainty, “median” or “mean”

Returns:

None

utils_general.prt_center(text, llen)[source]

Prints a centered line

Parameters:
  • text (str) – The text string to print

  • llen (int) – Length of the line

Returns:

None

utils_general.unique_unsort(params)[source]

As we want to check for unique elements to not copy elements, but retain the order they were given in, we have to do this, until numpy implements an ‘unsort’ key to numpy.unique…

Parameters:

params (list) – List of parameters

Returns:

params (list) – List of unique params, retaining order

Auxiliary functions for frequency analysis

utils_seismic.calculate_epsilon(n, l, f, dnu)[source]

Calculates epsilon by fitting that and dnu to the White et al. 2012, equation (1)

Parameters:
  • n (array) – Radial order of the modes

  • l (array) – Angular degree of the modes

  • f (array) – Frequency of the modes

  • dnu (float or None) – The large frequency parameter. If none is provided, a dnu will be estimated from a fit to l=0 modes.

Returns:

epsilon (float) – epsilon parameter

utils_seismic.check_epsilon_of_freqs(freqs, starid, dnu, quiet=False)[source]

Calculates the offset epsilon of the frequencies, to check if the radial order has been labeled correctly. Value range of epsilon from White et al. 2012

Parameters:
  • freqs (dict) – Dictionary of frequencies and their modes, as read in read_fre

  • starid (str) – Unique identifier of star, for printing with the alert

  • dnu (float or None) – The large frequency parameter.

  • quiet (bool, optional) – Toggle to silence the output (useful for running batches)

Returns:

ncor (float) – Correction to the ordering of modes.

utils_seismic.compute_cov_from_mc(nr, osckey, osc, fittype, args, nrealisations=10000)[source]

Compute covariance matrix (and its inverse) using Monte Carlo realisations.

Parameters:
  • nr (int) – Size of covariance matrix

  • osckey (array) – Harmonic degrees, radial orders and radial orders of frequencies.

  • osc (array) – Frequencies and their error, following the structure of obs.

  • fittype (str) – Which sequence to determine, see constants.freqtypes.rtypes and constants.freqtypes.epsdiff for possible sequences.

  • args (dict) – Set of arguments to pass on to the function that computes the fitting sequences, i.e. freq_fit.compute_ratioseqs and freq_fit.compute_epsilondiffseqs.

  • nrealisations (int) – Number of realisations of the sampling for the computation of the covariance matrix.

utils_seismic.extend_modjoin(joinkey, join, modkey, mod)[source]

Re-determines modkey and mod for an extended range of model frequencies. Needed for constructing ratios that are interpolated at observed frequencies, to avoid extrapolation. For each degree l it finds a mode n lower and higher, and appends these.

Parameters:
  • joinkey (array) – Joined frequency identification keys of observations and model.

  • join (array) – Joined frequencies of observations and model.

  • modkey (array) – All frequency identification keys of the model.

  • mod (array) – All frequencies of the model.

Returns:

  • key (array) – The extended array of frequency identification keys.

  • osc (array) – The extended array of frequencies.

utils_seismic.get_givenl(l, osc, osckey)[source]

Returns frequencies, radial orders, and inertias or uncertainties of a given angular degree l.

Parameters:
  • l (int) – Angular degree between l=0 and l=2

  • osc (array) – An array containing the individual frequencies in [0,:] and the inertias/uncertainties in [1, :]. This can also be a joined array between observations and model modes as long as the sorting corresponds to the sorting in osckey.

  • osckey (array) – An array containing the n and l of the values in osc. They are ordered in the same way.

Returns:

  • osckey_givenl (array) – An array containing the n and l of the values in osc for the input l.

  • osc_givenl (array) – An array containing the individual frequencies, inertias for the input l.

utils_seismic.prepare_obs(inputparams, verbose=False, debug=False)[source]

Prepare frequencies and ratios for fitting

Parameters:
  • inputparams (dict) – Inputparameters for BASTA

  • verbose (bool, optional) – Flag that if True adds extra text to the log (for developers).

  • debug (bool, optional) – Activate additional output for debugging (for developers)

Returns:

  • obskey (array) – Array containing the angular degrees and radial orders of obs

  • obs (array) – Array containing the modes in the observed data

  • numax (float) – numax as found in inputparams.

  • dnufrac (float) – The allowed fraction of the large frequency separation that defines when the l=0 mode in the model is close enough to the lowest l=0 mode in the observed set that the model can be considered.

  • fcor (strgs) – Type of surface correction (see :func:’freq_fit.py’).

  • obsfreqdata (dict) – Requested frequency-dependent data such as glitches, ratios, and epsilon difference. It also contains the covariance matrix and its inverse of the individual frequency modes. The keys correspond to the science case, e.g. r01a, `glitch, or e012. Inside each case, you find the data (data), the covariance matrix (cov), and its inverse (covinv).

  • obsfreqmeta (dict) – The requested information about which frequency products to fit or plot, unpacked for easier access later.

  • obsintervals (array) – Array containing the endpoints of the intervals used in the frequency fitting routine in :func:’freq_fit.calc_join’. As it is the same in all iterations for the observed frequencies, this is computed in util.prepare_obs once and given as an argument in order to save time and memory.

utils_seismic.scale_by_inertia(osckey, osc)[source]

This function outputs the scaled sizes of the modes scaled inversly by the normalized inertia of the mode.

Parameters:
  • osckey (array) – Mode identification of the modes

  • osc (array) – Frequencies and either inertia in the case of modelled modes or uncertainties in the case of observed modes.

Returns:

s (list) – List containing 3 array, one per angular degree l. The arrays contain the sizes of the modes scaled by inertia.

utils_seismic.solar_scaling(Grid, inputparams, diffusion=None)[source]

Transform quantities to solar units based on the assumed solar values. Grids use solar units for numax and for dnu’s based on scaling relations. The input values (given in microHz) are converted into solar units to match the grid.

Secondly, if a solar model is found in the grid, scale input dnu’s according to the value of this model. This scaling will be reversed before outputting results and making plots.

Parameters:
  • Grid (hdf5 object) – The already loaded grid, containing the tracks/isochrones.

  • inputparams (tuple) – Tuple of strings with the variables to be fitted.

  • diffusion (None or int, optional) – Selection of solar model with/without diffusion for e.g. the BaSTI isochrones. None signals grids with only one available solar model. For isochrones (with odea), a value of 0 signals no diffusion; 1 is diffusion.

Returns:

inputparams (tuple) – Modified version of inputparams with the added scaled values.

utils_seismic.transform_obj_array(objarr)[source]

Transform a two-column nested array with dtype=object into a corresponding 2D array with a dtype matching the indivial columns.

Useful for reading frequency information from the BASTA HDF5 files stored in variable sized arrays.

Utilities for handling of XML files

utils_xml.ascii_to_xml(asciifile, outputfile, uncert='quantiles')[source]

Converts ascii output to XML output

Parameters:
  • asciifile (str) – Absolute path to ascii file

  • outputfile (str) – Absolute path to the output XML file

Returns:

pretty_xml (file) – Formatted XML file stored in the outputfile

utils_xml.create_xmltag(main, params, paramvals, fitparams, distparams, freqparams, missingval, intpollim)[source]

Creates tags for xml input files

Parameters:
  • main (str) – Name of tag added to the xml file.

  • params (str) – Name of the parameters in the asciifile defined in create_xml()

  • paramvals (int or float or str) – Values of the parameters read from the asciifile in create_xml()

  • fitparams (str) – Names of parameters to be fitted in the Bayesian analysis

  • distparams (str) – Additional parameters for the distance calculation

  • freqparams (str) – Additional parameters for the frequency calculation

  • missingval (int or float or str) – Value used to replace missing values in the ascii file

  • intpollim (list) – List of parameters that require values from the stars to set limits in interpolation.

Returns:

main (str) – Name of the tag added to the xml file