Utilities¶
BurnMan has a number of low-level utilities to help achieve common goals.
Unit cell¶
- burnman.utils.unitcell.molar_volume_from_unit_cell_volume(unit_cell_v, z)[source]¶
Converts a unit cell volume from Angstroms^3 per unitcell, to m^3/mol.
- burnman.utils.unitcell.cell_parameters_to_vectors(cell_parameters, frame_convention)[source]¶
Converts cell parameters to unit cell vectors.
- Parameters:
cell_parameters (numpy.array (1D)) – An array containing the three lengths of the unit cell vectors [m], and the three angles [degrees]. The first angle (\(\alpha\)) corresponds to the angle between the second and the third cell vectors, the second (\(\beta\)) to the angle between the first and third cell vectors, and the third (\(\gamma\)) to the angle between the first and second vectors.
frame_convention (list of three integers) – A list (c) defining the reference frame convention. This function dictates that the c[0]th cell vector is colinear with the c[0]th axis, the c[1]th cell vector is perpendicular to the c[2]th axis, and the c[2]th cell vector is defined to give a right-handed coordinate system. In common crystallographic shorthand, x[c[0]] // a[c[0]], x[c[2]] // a[c[2]]^* (i.e. perpendicular to a[c[0]] and a[c[1]]).
- Returns:
The three vectors defining the parallelopiped cell [m].
- Return type:
numpy.array (2D)
- burnman.utils.unitcell.cell_vectors_to_parameters(vectors, frame_convention)[source]¶
Converts unit cell vectors to cell parameters.
- Parameters:
vectors (numpy.array (2D)) – The three vectors defining the parallelopiped cell [m].
frame_convention (list of three integers) – A list (c) defining the reference frame convention. This function dictates that the c[0]th cell vector is colinear with the c[0]th axis, the c[1]th cell vector is perpendicular to the c[2]th axis, and the c[2]th cell vector is defined to give a right-handed coordinate system. In common crystallographic shorthand, x[c[0]] // a[c[0]], x[c[2]] // a[c[2]]^* (i.e. perpendicular to a[c[0]] and a[c[1]]).
- Returns:
An array containing the three lengths of the unit cell vectors [m], and the three angles [degrees]. The first angle (\(\alpha\)) corresponds to the angle between the second and the third cell vectors, the second (\(\beta\)) to the angle between the first and third cell vectors, and the third (\(\gamma\)) to the angle between the first and second vectors.
- Return type:
numpy.array (1D)
Chemistry¶
- burnman.utils.chemistry.IUPAC_element_order = ['v', 'Og', 'Rn', 'Xe', 'Kr', 'Ar', 'Ne', 'He', 'Fr', 'Cs', 'Rb', 'K', 'Na', 'Li', 'Ra', 'Ba', 'Sr', 'Ca', 'Mg', 'Be', 'Lr', 'No', 'Md', 'Fm', 'Es', 'Cf', 'Bk', 'Cm', 'Am', 'Pu', 'Np', 'U', 'Pa', 'Th', 'Ac', 'Lu', 'Yb', 'Tm', 'Er', 'Ho', 'Dy', 'Tb', 'Gd', 'Eu', 'Sm', 'Pm', 'Nd', 'Pr', 'Ce', 'La', 'Y', 'Sc', 'Rf', 'Hf', 'Zr', 'Ti', 'Db', 'Ta', 'Nb', 'V', 'Sg', 'W', 'Mo', 'Cr', 'Bh', 'Re', 'Tc', 'Mn', 'Hs', 'Os', 'Ru', 'Fe', 'Mt', 'Ir', 'Rh', 'Co', 'Ds', 'Pt', 'Pd', 'Ni', 'Rg', 'Au', 'Ag', 'Cu', 'Cn', 'Hg', 'Cd', 'Zn', 'Nh', 'Tl', 'In', 'Ga', 'Al', 'B', 'Fl', 'Pb', 'Sn', 'Ge', 'Si', 'C', 'Mc', 'Bi', 'Sb', 'As', 'P', 'N', 'Lv', 'Po', 'Te', 'Se', 'S', 'O', 'H', 'Ts', 'At', 'I', 'Br', 'Cl', 'F']¶
IUPAC_element_order is a list of all the elements. Element order is based loosely on electronegativity, following the scheme suggested by IUPAC, except that H comes after the Group 16 elements, not before them.
- burnman.utils.chemistry.atomic_masses = {'Ag': 0.107868, 'Al': 0.0269815, 'Ar': 0.039948, 'As': 0.0749216, 'Au': 0.196967, 'B': 0.010811, 'Ba': 0.137327, 'Be': 0.00901218, 'Bi': 0.20898, 'Br': 0.079904, 'C': 0.0120107, 'Ca': 0.040078, 'Cd': 0.112411, 'Ce': 0.140116, 'Cl': 0.035453, 'Co': 0.0589332, 'Cr': 0.0519961, 'Cs': 0.132905, 'Cu': 0.063546, 'Dy': 0.1625, 'Er': 0.167259, 'Eu': 0.151964, 'F': 0.0189984, 'Fe': 0.055845, 'Ga': 0.069723, 'Gd': 0.15725, 'Ge': 0.07264, 'H': 0.00100794, 'He': 0.0040026, 'Hf': 0.17849, 'Hg': 0.20059, 'Ho': 0.16493, 'I': 0.126904, 'In': 0.114818, 'Ir': 0.192217, 'K': 0.0390983, 'Kr': 0.083798, 'La': 0.138905, 'Li': 0.006941, 'Lu': 0.174967, 'Mg': 0.024305, 'Mn': 0.054938, 'Mo': 0.09596, 'N': 0.0140067, 'Na': 0.0229898, 'Nb': 0.0929064, 'Nd': 0.144242, 'Ne': 0.0201797, 'Ni': 0.0586934, 'O': 0.0159994, 'Os': 0.19023, 'P': 0.0309738, 'Pa': 0.231036, 'Pb': 0.2072, 'Pd': 0.10642, 'Pr': 0.140908, 'Pt': 0.195084, 'Rb': 0.0854678, 'Re': 0.186207, 'Rh': 0.102905, 'Ru': 0.10107, 'S': 0.032065, 'Sb': 0.12176, 'Sc': 0.0449559, 'Se': 0.07896, 'Si': 0.0280855, 'Sm': 0.15036, 'Sn': 0.11871, 'Sr': 0.08762, 'Ta': 0.180948, 'Tb': 0.158925, 'Te': 0.1276, 'Th': 0.232038, 'Ti': 0.047867, 'Tl': 0.204383, 'Tm': 0.168934, 'U': 0.238029, 'V': 0.0509415, 'Vc': 0.0, 'W': 0.18384, 'Xe': 0.131293, 'Y': 0.0889058, 'Yb': 0.173054, 'Zn': 0.06538, 'Zr': 0.091224}¶
atomic_masses is a dictionary of atomic masses
- burnman.utils.chemistry.dictionarize_formula(formula)[source]¶
A function to read a chemical formula string and convert it into a dictionary
- burnman.utils.chemistry.sum_formulae(formulae, amounts=None)[source]¶
Adds together a set of formulae.
- burnman.utils.chemistry.formula_mass(formula)[source]¶
A function to take a chemical formula and compute the formula mass.
- burnman.utils.chemistry.convert_formula(formula, to_type='mass', normalize=False)[source]¶
Converts a chemical formula from one type (mass or molar) into the other. Renormalises amounts if normalize=True.
- burnman.utils.chemistry.process_solution_chemistry(solution_model)[source]¶
This function parses a class instance with a “site_formulae” attribute containing site information, e.g.
[ ‘[Mg]3[Al]2Si3O12’, ‘[Mg]3[Mg1/2Si1/2]2Si3O12’ ]
It outputs the bulk composition of each endmember (removing the site information), and also a set of variables and arrays which contain the site information. These are output in a format that can easily be used to calculate activities and gibbs free energies, given molar fractions of the phases and pressure and temperature where necessary.
- Parameters:
solution_model – Class must have a “site_formulae” attribute, containing a list of chemical formulae with site information
- Return type:
None
Note
Nothing is returned from this function, but the solution_model object gains the following attributes:
- empty_formula [string]
Abbreviated chemical formula with sites denoted by empty square brackets.
- general_formula [string]
General chemical formula with sites denoted by square brackets filled with a comma-separated list of species
- n_sites [integer]
Number of sites in the solution. Should be the same for all endmembers.
- sites [list of lists of strings]
A list of species for each site in the solution.
- site_names [list of strings]
A list of species_site pairs in the solution, where each distinct site is given by a unique uppercase letter e.g. [‘Mg_A’, ‘Fe_A’, ‘Al_A’, ‘Al_B’, ‘Si_B’].
- n_occupancies [integer]
Sum of the number of possible species on each of the sites in the solution. Example: A binary solution [[A][B],[B][C1/2D1/2]] would have n_occupancies = 5, with two possible species on Site 1 and three on Site 2.
- site_multiplicities [2D array of floats]
A 1D array for each endmember in the solution, containing the multiplicities of each site per formula unit. To simplify computations later, the multiplicities are repeated for each species on each site, so the shape of this attribute is (n_endmembers, n_site_species).
- endmember_occupancies [2d array of floats]
A 1D array for each endmember in the solution, containing the fraction of atoms of each species on each site.
- endmember_noccupancies [2d array of floats]
A 1D array for each endmember in the solution, containing the number of atoms of each species on each site per mole of endmember.
- burnman.utils.chemistry.site_occupancies_to_strings(site_species_names, site_multiplicities, endmember_occupancies)[source]¶
Converts a list of endmember site occupancies into a list of string representations of those occupancies.
- Parameters:
site_species_names (2D list of strings) – A list of list of strings, giving the names of the species which reside on each site. List of sites, each of which contains a list of the species occupying each site.
site_multiplicities (1D or 2D numpy array of floats) – List of floats giving the multiplicity of each site. If 2D, must have the same shape as endmember_occupancies. If 1D, must be either the same length as the number of sites, or the same length as site_species_names (with an implied repetition of the same number for each species on a given site).
endmember_occupancies (2D numpy array of floats) – A list of site-species occupancies for each endmember. The first dimension loops over the endmembers, and the second dimension loops over the site-species occupancies for that endmember. The total number and order of occupancies must be the same as the strings in site_species_names.
- Returns:
A list of strings in standard burnman format. For example, [Mg]3[Al]2 would correspond to the classic two-site pyrope garnet.
- Return type:
list of strings
- burnman.utils.chemistry.compositional_array(formulae)[source]¶
- Parameters:
formulae (list of dicts) – List of chemical formulae
- Returns:
Array of endmember formulae and a list of elements.
- Return type:
2D numpy.array of floats and a list of strs
- burnman.utils.chemistry.ordered_compositional_array(formulae, elements)[source]¶
- Parameters:
formulae (list of dicts) – List of chemical formulae
:param elements : List of elements :type elements: list of strings
- Returns:
Array of endmember formulae
- Return type:
2D array of floats
- burnman.utils.chemistry.formula_to_string(formula, use_fractions=True, significant_figures=2)[source]¶
- Parameters:
formula (dict or Counter) – Chemical formula
use_fractions (bool) – Whether or not to use fractions in the output string. If False, numbers are rounded to the number of significant figures given by the significant_figures parameter.
significant_figures (int) – Number of significant figures to use if use_fractions=False.
- Returns:
A formula string, with element order as given in the list IUPAC_element_order. If one or more keys in the dictionary are not one of the elements in the periodic table, then they are added at the end of the string.
- Return type:
- burnman.utils.chemistry.sort_element_list_to_IUPAC_order(element_list)[source]¶
:param element_list : List of elements. :type element_list: list
- Returns:
List of elements sorted into IUPAC order
- Return type:
- burnman.utils.chemistry.convert_fractions(composite, phase_fractions, input_type, output_type)[source]¶
Takes a composite with a set of user defined molar, volume or mass fractions (which do not have to be the fractions currently associated with the composite) and converts the fractions to molar, mass or volume.
Conversions to and from mass require a molar mass to be defined for all phases. Conversions to and from volume require set_state to have been called for the composite.
- Parameters:
composite (
Composite) – Composite for which fractions are to be defined.phase_fractions (list of floats) – List of input phase fractions (of type input_type).
input_type (str) – Input fraction type. One of ‘molar’, ‘mass’ or ‘volume’.
output_type (str) – Output fraction type. One of ‘molar’, ‘mass’ or ‘volume’.
- Returns:
List of output phase fractions (of type output_type)
- Return type:
list of floats
Anisotropy¶
- burnman.utils.anisotropy.voigt_index_to_ij(m)[source]¶
Returns the ij (or kl) indices of the stiffness tensor which correspond to those of the Voigt notation m (or n).
- burnman.utils.anisotropy.voigt_notation_to_stiffness_tensor(voigt_notation)[source]¶
Converts a stiffness tensor in Voigt notation (6x6 matrix) to the full fourth rank tensor (3x3x3x3 matrix).
- burnman.utils.anisotropy.contract_stresses(stresses)[source]¶
Takes a stress tensor in standard (3x3) form and returns the Voigt form (6). No factors are required to maintain the relationship with the corresponding stiffness and strain tensors (see contract_strains, which does require multiplicative factors).
- burnman.utils.anisotropy.expand_stresses(stresses)[source]¶
Takes a stress tensor in Voigt form (6) and returns the standard form (3x3). No factors are required to maintain the relationship with the corresponding stiffness and strain tensors (see contract_strains, which does require multiplicative factors).
- burnman.utils.anisotropy.contract_strains(strains)[source]¶
Takes a stress tensor in standard (3x3) form and returns the Voigt form (6). Note the factors which are required to maintain the relationship with the corresponding stiffness and strain tensors.
- burnman.utils.anisotropy.contract_compliances(compliances)[source]¶
Takes a compliance tensor in standard (3x3x3x3) form and returns the Voigt form (6x6). Note the compliance factors which are required to maintain the inverse relationship with the corresponding stiffness tensor.
Plotting¶
- class burnman.utils.plotting.Cell(x, y, h, polygon)[source]¶
Bases:
objectRepresents a square cell used during the polygon center search.
- burnman.utils.plotting.closest_point_on_segment(p, a, b)[source]¶
Return the closest point on segment ab to point p.
- Parameters:
p (np.array of shape (2,)) – the target point
a (np.array of shape (2,)) – the start point of the segment
b (np.array of shape (2,)) – the end point of the segment
- Returns:
closest point on segment ab
- Return type:
np.array of shape (2,)
- burnman.utils.plotting.closest_point_on_polygon(p, polygon)[source]¶
Find the closest point on a polygon to point p.
- Parameters:
p (np.array of shape (2,)) – the target point
polygon (np.array of shape (N, 2)) – the polygon vertices (assumed closed or will be treated as closed)
- Returns:
closest point on polygon
- Return type:
np.array of shape (2,)
- burnman.utils.plotting.visual_center_of_polygon(polygon_rings, precision=1.0, with_distance=False)[source]¶
Compute the pole of inaccessibility (visual center) of a polygon with the specified precision.
- Parameters:
- Returns:
The [x, y] coordinates of the center, and optionally the distance.
- Return type:
Mathematical¶
- burnman.utils.math.unit_normalize(a, order=2, axis=-1)[source]¶
Calculates the L2 normalized array of numpy array a of a given order and along a given axis.
- burnman.utils.math.linear_interpol(x, x1, x2, y1, y2)[source]¶
Linearly interpolate to point x, between the points (x1,y1), (x2,y2)
- burnman.utils.math.bracket(fn, x0, dx, args=(), ratio=1.618, maxiter=100)[source]¶
Given a function and a starting guess, find two inputs for the function that bracket a root.
- Parameters:
fn (function) – The function to bracket.
x0 (float) – The starting guess.
dx (float) – Small step for starting the search.
args (tuple) – Additional arguments to give to fn.
ratio (float) – The step size increases by this ratio every step in the search. Defaults to the golden ratio.
maxiter (int) – The maximum number of steps before giving up.
- Returns:
xa, xb, fa, fb. xa and xb are the inputs which bracket a root of fn. fa and fb are the values of the function at those points. If the bracket function takes more than maxiter steps, it raises a ValueError.
- Return type:
tuple of floats
- burnman.utils.math.smooth_array(array, grid_spacing, gaussian_rms_widths, truncate=4.0, mode='inverse_mirror')[source]¶
Creates a smoothed array by convolving it with a gaussian filter. Grid resolutions and gaussian RMS widths are required for each of the axes of the numpy array. The smoothing is truncated at a user-defined number of standard deviations. The edges of the array can be padded in a number of different ways given by the ‘mode’ parameter.
- Parameters:
array (numpy.ndarray) – The array to smooth.
grid_spacing (numpy.array of floats) – The spacing of points along each axis.
gaussian_rms_widths (numpy.array of floats) – The Gaussian RMS widths/standard deviations for the Gaussian convolution.
truncate (float) – The number of standard deviations at which to truncate the smoothing.
mode (str) – {‘reflect’, ‘constant’, ‘nearest’, ‘mirror’, ‘wrap’, ‘inverse_mirror’} The mode parameter determines how the array borders are handled either by scipy.ndimage.filters.gaussian_filter. Default is ‘inverse_mirror’, which uses
burnman.tools.math._pad_ndarray_inverse_mirror().
- Returns:
The smoothed array
- Return type:
numpy.ndarray
- burnman.utils.math.interp_smoothed_array_and_derivatives(array, x_values, y_values, x_stdev=0.0, y_stdev=0.0, truncate=4.0, mode='inverse_mirror', indexing='xy')[source]¶
Creates a smoothed array on a regular 2D grid. Smoothing is achieved using
burnman.tools.math.smooth_array(). Outputs scipy.interpolate.RegularGridInterpolator() interpolators which can be used to query the array, or its derivatives in the x- and y- directions.- Parameters:
array (numpy.array (2D)) – The array to smooth. Each element array[i][j] corresponds to the position x_values[i], y_values[j]
x_values (numpy.array (1D)) – The gridded x values over which to create the smoothed grid
y_values (numpy.array (1D)) – The gridded y_values over which to create the smoothed grid
x_stdev (float) – The standard deviation for the Gaussian filter along the x axis
y_stdev (float) – The standard deviation for the Gaussian filter along the y axis
truncate (float) – The number of standard deviations at which to truncate the smoothing.
mode (str) – {‘reflect’, ‘constant’, ‘nearest’, ‘mirror’, ‘wrap’, ‘inverse_mirror’} The mode parameter determines how the array borders are handled either by scipy.ndimage.filters.gaussian_filter. Default is ‘inverse_mirror’, which uses
burnman.tools.math._pad_ndarray_inverse_mirror().indexing (str) – {‘xy’, ‘ij’}, optional Cartesian (‘xy’, default) or matrix (‘ij’) indexing of output. See numpy.meshgrid for more details.
- Returns:
Three RegularGridInterpolator functors interpolation functions for the smoothed property and the first derivatives with respect to x and y.
- Return type:
- burnman.utils.math.l2_norm_profiles(depth, calc, obs)[source]¶
Computes the L2 norm for N profiles at a time (assumed to be linear between points).
- Parameters:
- Returns:
array of L2 norms of length N
- Return type:
array of floats
- burnman.utils.math.chisqr_profiles(calc, obs)[source]¶
Computes the chisqr factor for N profiles at a time. Assumes a 1% a priori uncertainty on the seismic model.
- burnman.utils.math.l2_norm_profile(x, funca, funcb)[source]¶
Computes the L2 norm of the difference between two 1D profiles, assuming linear interpolation between points.
This is equivalent to the square root of the integrated squared difference between the two functions over the given depth range. The integration is performed using the trapezoidal rule.
- Parameters:
x (array-like of float) – Array of depth values [m], must be 1D and monotonically increasing.
funca (array-like of float) – First profile (e.g., model or predicted values), must be same length as x.
funcb (array-like of float) – Second profile (e.g., observed or reference values), same shape as funca.
- Returns:
L2 norm (scalar)
- Return type:
- burnman.utils.math.chisqr_profile(calc, obs, uncertainties=0.01)[source]¶
Computes the \(\chi^2\) factor for a single profile, assuming a 1 % uncertainty on the reference (observed) values. This provides a normalized measure of the deviation between calculated and reference values.
The \(\chi^2\) factor is calculated as:
\[\chi^2 = \frac{1}{N} \sum_{i=1}^{N} \left( \frac{\text{calc}_i - \text{obs}_i}{0.01 \cdot \text{mean}(\text{obs})} \right)^2\]where \(N\) is the number of elements in the profile.
- burnman.utils.math.independent_row_indices(array)[source]¶
Returns the indices corresponding to an independent set of rows for a given array. The independent rows are determined from the pivots used during row reduction/Gaussian elimination.
- Parameters:
array (2D numpy.array of floats) – The input array.
- Returns:
The indices corresponding to a set of independent rows of the input array.
- Return type:
1D numpy array of integers
- burnman.utils.math.array_to_rational_matrix(array)[source]¶
Converts a numpy array into a sympy matrix filled with rationals
- burnman.utils.math.complete_basis(basis, flip_columns=True)[source]¶
Extends a partial basis (with fewer rows than columns) to a full basis by adding rows from the identity matrix that are linearly independent of the existing rows.
This is done by computing the reduced row echelon form (RREF) of the basis to identify pivot columns. Identity rows corresponding to non-pivot columns are added to complete the basis.
- Parameters:
basis (numpy.ndarray) – A 2D NumPy array representing a partial basis, with shape (n, m) where n < m.
flip_columns (bool, optional) – If True, the basis columns are flipped (reversed) before computing the RREF. This is helpful if the dependent columns are expected to appear later in the matrix. Default is True.
- Returns:
A completed basis as a NumPy array with shape (m, m), containing the original rows plus additional rows from the identity matrix.
- Return type:
numpy.ndarray
- burnman.utils.math.generate_complete_basis(incomplete_basis, array)[source]¶
Given a 2D array with independent rows and a second 2D array that spans a larger space, creates a complete basis for the combined array using all the rows of the first array, followed by any required rows of the second array. So, for example, if the first array is: [[1, 0, 0], [1, 1, 0]] and the second array is: [[1, 0, 0], [0, 1, 0], [0, 0, 1]], the complete basis will be: [[1, 0, 0], [1, 1, 0], [0, 0, 1]].
- Parameters:
incomplete_basis (2D numpy.array) – An array containing the basis to be completed.
array (2D numpy.array) – An array spanning the full space for which a basis is required.
- Returns:
An array containing the basis vectors spanning both of the input arrays.
- Return type:
2D numpy array
- burnman.utils.math.is_positive_definite(matrix)[source]¶
Checks if a matrix is positive definite
- Parameters:
matrix (2D numpy array) – Input matrix
- Returns:
Whether or not the matrix is positive definite
- Return type:
- burnman.utils.math.generalised_gammainc(a, x1, x2)[source]¶
An implementation of the generalised incomplete gamma function. Computed using the relationship with the regularised lower incomplete gamma function (scipy.special.gammainc). Uses the recurrence relation wherever a<0.
We could have used mpmath.gammainc(a, x1, x2) directly, but it is significantly slower than this implementation.
Row reductions and independent rows¶
Miscellaneous¶
- class burnman.utils.misc.OrderedCounter(iterable=None, /, **kwds)[source]¶
Bases:
Counter,OrderedDictCounter that remembers the order elements are first encountered
- clear() None. Remove all items from od.¶
- copy()¶
Return a shallow copy.
- elements()¶
Iterator over elements repeating each as many times as its count.
>>> c = Counter('ABCABC') >>> sorted(c.elements()) ['A', 'A', 'B', 'B', 'C', 'C']
# Knuth’s example for prime factors of 1836: 2**2 * 3**3 * 17**1 >>> import math >>> prime_factors = Counter({2: 2, 3: 3, 17: 1}) >>> math.prod(prime_factors.elements()) 1836
Note, if an element’s count has been set to zero or is a negative number, elements() will ignore it.
- classmethod fromkeys(iterable, v=None)¶
Create a new ordered dictionary with keys from iterable and values set to value.
- get(key, default=None, /)¶
Return the value for key if key is in the dictionary, else default.
- items() a set-like object providing a view on D's items¶
- keys() a set-like object providing a view on D's keys¶
- most_common(n=None)¶
List the n most common elements and their counts from the most common to the least. If n is None, then list all element counts.
>>> Counter('abracadabra').most_common(3) [('a', 5), ('b', 2), ('r', 2)]
- move_to_end(/, key, last=True)¶
Move an existing element to the end (or beginning if last is false).
Raise KeyError if the element does not exist.
- pop(/, key, default=<unrepresentable>)¶
If the key is not found, return the default if given; otherwise, raise a KeyError.
- popitem(/, last=True)¶
Remove and return a (key, value) pair from the dictionary.
Pairs are returned in LIFO order if last is true or FIFO order if false.
- setdefault(/, key, default=None)¶
Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
- subtract(iterable=None, /, **kwds)¶
Like dict.update() but subtracts counts instead of replacing them. Counts can be reduced below zero. Both the inputs and outputs are allowed to contain zero and negative counts.
Source can be an iterable, a dictionary, or another Counter instance.
>>> c = Counter('which') >>> c.subtract('witch') # subtract elements from another iterable >>> c.subtract(Counter('watch')) # subtract elements from another counter >>> c['h'] # 2 in which, minus 1 in witch, minus 1 in watch 0 >>> c['w'] # 1 in which, minus 1 in witch, minus 1 in watch -1
- total()¶
Sum of the counts
- update(iterable=None, /, **kwds)¶
Like dict.update() but add counts instead of replacing them.
Source can be an iterable, a dictionary, or another Counter instance.
>>> c = Counter('which') >>> c.update('witch') # add elements from another iterable >>> d = Counter('watch') >>> c.update(d) # add elements from another counter >>> c['h'] # four 'h' in which, witch, and watch 4
- values() an object providing a view on D's values¶
- burnman.utils.misc.copy_documentation(copy_from)[source]¶
Decorator @copy_documentation(another_function) will copy the documentation found in a different function (for example from a base class). The docstring applied to some function a() will be
(copied from BaseClass.some_function): <documentation from BaseClass.some_function> <optionally the documentation found in a()>
- burnman.utils.misc.merge_two_dicts(x, y)[source]¶
Given two dicts, merge them into a new dict as a shallow copy.
- burnman.utils.misc.pretty_string_values(popt, pcov, extra_decimal_places=0, combine_value_and_sigma=False)[source]¶
Takes a numpy array of parameters, the corresponding covariance matrix and a set of parameter names and returns the scaled variables and principal 1-s.d.uncertainties (np.sqrt(pcov[i][i])) and scaling factor as three separate lists of strings.
- Parameters:
- Returns:
values, uncertainties and the scaling factors
- Return type:
tuple of 3 lists
- burnman.utils.misc.pretty_print_values(popt, pcov, params, extra_decimal_places=0)[source]¶
Takes a numpy array of parameters, the corresponding covariance matrix and a set of parameter names and prints the scaled variables and principal 1-s.d.uncertainties (np.sqrt(pcov[i][i])) and scaling factor in an easy to read format.
- Parameters:
popt (numpy array) – Parameter values
pcov (2D numpy array) – Variance-covariance matrix
extra_decimal_places (int, optional) – extra precision for values, defaults to 0
- burnman.utils.misc.pretty_print_table(table, use_tabs=False)[source]¶
Takes a 2d table and prints it in a nice text based format. If use_tabs=True then only is used as a separator. This is useful for importing the data into other apps (Excel, …). The default is to pad the columns with spaces to make them look neat. The first column is left aligned, while the remainder is right aligned.
- burnman.utils.misc.attribute_function(m, attributes, powers=[], using_volume=False)[source]¶
Returns a callable function that evaluates a derived material property defined as a product of material attributes (optionally raised to given powers) at specified thermodynamic conditions.
The returned function is designed to be compatible with
burnman.optimize.nonlinear_fitting.confidence_prediction_bands(), which expects functions of the formf(x)where x contains composition and thermodynamic state variables.The expected order of arguments in x depends on the value of using_volume: - If
using_volume=False, the function expectsx = [X1, X2, ..., P, T, _]and the state of the material is set using set_state - Ifusing_volume=True, the function expectsx = [X1, X2, ..., V, T, _]and the state of the material is set using set_state_with_volumeThe function sets the state of the material using the appropriate method, evaluates the specified attributes, raises them to the corresponding powers, and returns the product.
- Parameters:
m (
burnman.Material) – The material instance whose attributes are evaluated.attributes (list of str) – List of material attributes to include in the product expression (e.g., [‘K_T’, ‘rho’]).
powers (list of float) – List of exponents to raise each corresponding attribute to. If empty, defaults to 1.0 for each attribute.
using_volume (bool) – If True, the input function defines the thermodynamic state using volume and temperature (V, T). If False, pressure and temperature (P, T) are used. This argument also determines the expected order of the final three elements in the input vector x.
- Returns:
A function
f(x)that evaluates the product of the specified attributes, each raised to the corresponding power, at the composition and thermodynamic conditions specified by x. The format of x is determined by using_volume, and is compatible with the x_array argument ofburnman.optimize.nonlinear_fitting.confidence_prediction_bands().- Return type:
function
- burnman.utils.misc.extract_lines_between_markers(file, start_string, end_string, inclusive=False)[source]¶
Extract lines from a file between two marker strings.
- Parameters:
file (str) – Path to the input text file.
start_string (str) – The marker string indicating where to start collecting lines.
end_string (str) – The marker string indicating where to stop collecting lines.
inclusive (bool, optional) – Whether to include the lines containing start_string and end_string, defaults to False.
- Returns:
A list of lines between the two markers.
- Return type: