index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
10,984 | burnman.classes.mineral_helpers | __init__ | null | def __init__(self):
self.current_rock = None
Material.__init__(self)
| (self) |
10,986 | burnman.classes.mineral_helpers | debug_print | null | def debug_print(self, indent=""):
print("%sHelperRockSwitcher" % (indent))
| (self, indent='') |
10,990 | burnman.classes.mineral_helpers | select_rock | null | def select_rock(self):
raise NotImplementedError("Need to implement select_rock() in derived class!")
| (self) |
10,991 | burnman.classes.mineral_helpers | set_method | null | def set_method(self, method):
raise NotImplementedError("Need to implement select_rock() in derived class!")
| (self, method) |
10,996 | burnman.classes.mineral_helpers | HelperSpinTransition |
Helper class that makes a mineral that switches between two materials
(for low and high spin) based on some transition pressure [Pa]
| class HelperSpinTransition(Composite):
"""
Helper class that makes a mineral that switches between two materials
(for low and high spin) based on some transition pressure [Pa]
"""
def __init__(self, transition_pressure, ls_mat, hs_mat):
"""
Takes a transition pressure, and two minerals. Use the
thermoelastic parameters for ls_mat below the transition
pressure, and the thermoelastic parameters for hs_mat
above the transition pressure
"""
Material.__init__(self)
self.transition_pressure = transition_pressure
self.ls_mat = ls_mat
self.hs_mat = hs_mat
Composite.__init__(self, [ls_mat, hs_mat])
def debug_print(self, indent=""):
print("%sHelperSpinTransition:" % indent)
self.ls_mat.debug_print(indent + " ")
self.hs_mat.debug_print(indent + " ")
def set_state(self, pressure, temperature):
if pressure >= self.transition_pressure:
Composite.set_fractions(self, [1.0, 0.0])
else:
Composite.set_fractions(self, [0.0, 1.0])
Composite.set_state(self, pressure, temperature)
| (transition_pressure, ls_mat, hs_mat) |
10,997 | burnman.classes.mineral_helpers | __init__ |
Takes a transition pressure, and two minerals. Use the
thermoelastic parameters for ls_mat below the transition
pressure, and the thermoelastic parameters for hs_mat
above the transition pressure
| def __init__(self, transition_pressure, ls_mat, hs_mat):
"""
Takes a transition pressure, and two minerals. Use the
thermoelastic parameters for ls_mat below the transition
pressure, and the thermoelastic parameters for hs_mat
above the transition pressure
"""
Material.__init__(self)
self.transition_pressure = transition_pressure
self.ls_mat = ls_mat
self.hs_mat = hs_mat
Composite.__init__(self, [ls_mat, hs_mat])
| (self, transition_pressure, ls_mat, hs_mat) |
11,003 | burnman.classes.mineral_helpers | debug_print | null | def debug_print(self, indent=""):
print("%sHelperSpinTransition:" % indent)
self.ls_mat.debug_print(indent + " ")
self.hs_mat.debug_print(indent + " ")
| (self, indent='') |
11,011 | burnman.classes.mineral_helpers | set_state | null | def set_state(self, pressure, temperature):
if pressure >= self.transition_pressure:
Composite.set_fractions(self, [1.0, 0.0])
else:
Composite.set_fractions(self, [0.0, 1.0])
Composite.set_state(self, pressure, temperature)
| (self, pressure, temperature) |
11,015 | burnman.classes.layer | Layer |
The base class for a planetary layer.
The user needs to set the following before properties can be computed:
- set_material(), which sets the material of the layer,
e.g. a mineral, solid_solution, or composite
- set_temperature_mode(), either predefine, or set to an adiabatic profile
- set_pressure_mode(), to set the self-consistent pressure
(with user-defined option the pressures can be overwritten).
To set the self-consistent pressure the pressure at the top and the
gravity at the bottom of the layer need to be set.
- make(), computes the self-consistent part of the layer and starts the
settings to compute properties within the layer
Note that the entire planet this layer sits in is not necessarily
self-consistent, as the pressure at the top of the layer is a
function of the density within the layer (through the gravity).
Entire planets can be computed self-consistently with the planet class.
Properties will be returned at the pre-defined radius array,
although the evaluate() function can take a newly defined depthlist
and values are interpolated between these (sufficient sampling of the layer
is needed for this to be accurate).
| class Layer(object):
"""
The base class for a planetary layer.
The user needs to set the following before properties can be computed:
- set_material(), which sets the material of the layer,
e.g. a mineral, solid_solution, or composite
- set_temperature_mode(), either predefine, or set to an adiabatic profile
- set_pressure_mode(), to set the self-consistent pressure
(with user-defined option the pressures can be overwritten).
To set the self-consistent pressure the pressure at the top and the
gravity at the bottom of the layer need to be set.
- make(), computes the self-consistent part of the layer and starts the
settings to compute properties within the layer
Note that the entire planet this layer sits in is not necessarily
self-consistent, as the pressure at the top of the layer is a
function of the density within the layer (through the gravity).
Entire planets can be computed self-consistently with the planet class.
Properties will be returned at the pre-defined radius array,
although the evaluate() function can take a newly defined depthlist
and values are interpolated between these (sufficient sampling of the layer
is needed for this to be accurate).
"""
def __init__(self, name=None, radii=None, verbose=False):
self.name = name
assert np.all(np.diff(radii) > 0)
self.radii = radii
self.outer_radius = max(self.radii)
self.inner_radius = min(self.radii)
self.thickness = self.outer_radius - self.inner_radius
self.n_slices = len(self.radii)
self.verbose = verbose
self._cached = {}
self._pressures = None
self._temperatures = None
self.sublayers = None
self.material = None
self.pressure_mode = "self-consistent"
self.temperature_mode = None
def __str__(self):
"""
Prints details of the layer
"""
writing = (
f"The {self.name} is made of {self.material.name}"
f" with {self.temperature_mode} temperatures and "
f"{self.pressure_mode} pressures\n"
)
return writing
def reset(self):
"""
Resets all cached material properties.
It is typically not required for the user to call this function.
"""
self._cached = {}
self._pressures = None
self._temperatures = None
self.sublayers = None
def set_material(self, material):
"""
Set the material of a Layer with a Material
"""
assert isinstance(material, Material)
self.material = material
self.reset()
def set_temperature_mode(
self, temperature_mode="adiabatic", temperatures=None, temperature_top=None
):
"""
Sets temperatures within the layer as user-defined values or as
a (potentially perturbed) adiabat.
:param temperature_mode: This can be set to 'user-defined', 'adiabatic',
or 'perturbed-adiabatic'. 'user-defined' fixes the temperature
with the profile input by the user. 'adiabatic' self-consistently
computes the adiabat when setting the state of the layer.
'perturbed-adiabatic' adds the user input array to the adiabat.
This allows the user to apply boundary layers (for example).
:type temperature_mode: string
:param temperatures: The desired fixed temperatures in [K].
Should have same length as defined radii in layer.
:type temperatures: array of float
:param temperature_top: Temperature at the top of the layer.
Used if the temperature mode is chosen to be 'adiabatic' or
'perturbed-adiabatic'. If 'perturbed-adiabatic' is chosen as the
temperature mode, temperature_top corresponds to the true temperature
at the top of the layer, and the reference isentrope at this radius
is defined to lie at a temperature of
temperature_top - temperatures[-1].
:type temperature_top: float
"""
self.reset()
assert (
temperature_mode == "user-defined"
or temperature_mode == "adiabatic"
or temperature_mode == "perturbed-adiabatic"
)
self.temperature_mode = temperature_mode
if (
temperature_mode == "user-defined"
or temperature_mode == "perturbed-adiabatic"
):
assert len(temperatures) == len(self.radii)
self.usertemperatures = temperatures
else:
self.usertemperatures = np.zeros_like(self.radii)
if temperature_mode == "adiabatic" or temperature_mode == "perturbed-adiabatic":
self.temperature_top = temperature_top
else:
self.temperature_top = None
def set_pressure_mode(
self,
pressure_mode="self-consistent",
pressures=None,
gravity_bottom=None,
pressure_top=None,
n_max_iterations=50,
max_delta=1.0e-5,
):
"""
Sets the pressure mode of the layer,
which can either be 'user-defined', or 'self-consistent'.
:param pressure_mode: This can be set to 'user-defined' or 'self-consistent'.
'user-defined' fixes the pressures with the profile input
by the user in the 'pressures' argument.
'self-consistent' forces Layer to calculate pressures
self-consistently. If this is selected, the user will need
to supply values for the gravity_bottom [m/s^2]
and pressure_top [Pa] arguments.
:type pressure_mode: string
:param pressures: Pressures [Pa] to set layer to
(if the 'user-defined' pressure_mode has been selected).
The array should be the same length as
the layers user-defined radii array.
:type pressures: array of floats
:param pressure_top: Pressure [Pa] at the top of the layer.
:type pressure_top: float
:param gravity_bottom: Gravity [m/s^2] at the bottom of the layer.
:type gravity_bottom: float
:param n_max_iterations: Maximum number of iterations to reach
self-consistent pressures.
:type n_max_iterations: integer
:param max_delta: Relative update to the highest pressure in the layer between
iterations to stop iterations.
:type max_delta: float
"""
self.reset()
assert pressure_mode == "user-defined" or pressure_mode == "self-consistent"
self.pressure_mode = pressure_mode
assert gravity_bottom is not None
self.gravity_bottom = gravity_bottom
if pressure_mode == "user-defined":
assert pressures is not None
assert len(pressures) == len(self.radii)
self.pressures = pressures
warnings.warn(
"By setting the pressures in Layer they "
"are unlikely to be self-consistent"
)
elif pressure_mode == "self-consistent":
self.pressure_top = pressure_top
self.n_max_iterations = n_max_iterations
self.max_delta = max_delta
else:
raise NotImplementedError(
f"pressure mode {pressure_mode} " "not recognised"
)
def make(self):
"""
This routine needs to be called before evaluating any properties.
If pressures and temperatures are not user-defined, they
are computed here. This method also initializes an array of copied
materials from which properties can be computed.
"""
self.reset()
if not hasattr(self, "material"):
raise AttributeError(
"You must set_material() for the layer " "before running make()."
)
if not hasattr(self, "temperature_mode"):
raise AttributeError(
"You must set_temperature_mode() for the "
"layer before running make()."
)
if not hasattr(self, "pressure_mode"):
raise AttributeError(
"You must set_pressure_mode() for the layer " "before running make()."
)
if self.pressure_mode == "user-defined":
self.temperatures = self._evaluate_temperature(
self.pressures, self.temperature_top
)
elif self.pressure_mode == "self-consistent":
new_press = (
self.pressure_top + (-self.radii + max(self.radii)) * 1.0e3
) # initial pressure curve guess
temperatures = self._evaluate_temperature(new_press, self.temperature_top)
# Make it self-consistent!!!
i = 0
while i < self.n_max_iterations:
i += 1
ref_press = new_press
new_grav, new_press = self._evaluate_eos(
new_press, temperatures, self.gravity_bottom, self.pressure_top
)
temperatures = self._evaluate_temperature(
new_press, self.temperature_top
)
rel_err = abs((max(ref_press) - max(new_press)) / max(new_press))
if self.verbose:
print(
f"Iteration {i:0d} maximum relative pressure error: "
f"{rel_err:.1f}"
)
if rel_err < self.max_delta:
break
self.pressures = new_press
self.temperatures = temperatures
else:
raise NotImplementedError("pressure mode not recognised")
self.sublayers = []
for r in range(len(self.radii)):
self.sublayers.append(self.material.copy())
self.sublayers[r].set_state(self.pressures[r], self.temperatures[r])
def evaluate(self, properties, radlist=None, radius_planet=None):
"""
Function that is used to evaluate properties
across the layer. If radlist is not defined, values are
returned at the internal radlist.
If asking for different radii than the internal radlist,
pressure and temperature values are interpolated and the
layer material evaluated at those pressures and
temperatures.
:param properties: List of properties to evaluate.
:type properties: list of strings
:param radlist: Radii to evaluate properties at. If left empty,
internal radii list is used.
:type radlist: array of floats
:param planet_radius: Planet outer radius. Used only to calculate depth.
:type planet_radius: float
:returns: 1D or 2D array of requested properties
(1D if only one property was requested)
:rtype: numpy.array
"""
if radlist is None:
values = np.empty([len(properties), len(self.radii)])
for i, prop in enumerate(properties):
if prop == "depth":
values[i] = radius_planet - self.radii
else:
try:
values[i] = getattr(self, prop)
except:
values[i] = np.array(
[
getattr(self.sublayers[i], prop)
for i in range(len(self.sublayers))
]
)
else:
func_p = interp1d(self.radii, self.pressures)
pressures = func_p(radlist)
func_t = interp1d(self.radii, self.temperatures)
temperatures = func_t(radlist)
values = np.empty([len(properties), len(radlist)])
for i, prop in enumerate(properties):
if prop == "depth":
values[i] = radius_planet - radlist
else:
try:
values[i] = self.material.evaluate(
[prop], pressures, temperatures
)
except:
func_prop = interp1d(self.radii, getattr(self, prop))
values[i] = func_prop(radlist)
if values.shape[0] == 1:
values = values[0]
return values
def _evaluate_temperature(self, pressures=None, temperature_top=None):
"""
Returns the temperatures of the layer for given pressures.
Used by make()
"""
if (
self.temperature_mode == "adiabatic"
or self.temperature_mode == "perturbed-adiabatic"
):
adiabat = geotherm.adiabatic(
pressures[::-1],
temperature_top - self.usertemperatures[-1],
self.material,
)[::-1]
else:
adiabat = np.zeros_like(self.radii)
return adiabat + self.usertemperatures
def _evaluate_eos(self, pressures, temperatures, gravity_bottom, pressure_top):
"""
Returns updated gravity and pressure
make() loops over this until consistency is achieved.
"""
[density] = self.material.evaluate(["density"], pressures, temperatures)
grav = self._compute_gravity(density, gravity_bottom)
press = self._compute_pressure(density, grav, pressure_top)
return grav, press
# Functions needed to compute self-consistent radii-pressures
def _compute_gravity(self, density, gravity_bottom):
"""
Computes the gravity of a layer
Used by _evaluate_eos()
"""
# Create a spline fit of density as a function of radius
rhofunc = UnivariateSpline(self.radii, density)
# Numerically integrate Poisson's equation
def poisson(p, x):
return 4.0 * np.pi * constants.G * rhofunc(x) * x * x
grav = np.ravel(
odeint(poisson, gravity_bottom * self.radii[0] * self.radii[0], self.radii)
)
if self.radii[0] == 0:
grav[0] = 0
grav[1:] = grav[1:] / self.radii[1:] / self.radii[1:]
else:
grav[:] = grav[:] / self.radii[:] / self.radii[:]
return grav
def _compute_pressure(self, density, gravity, pressure_top):
"""
Calculate the pressure profile based on density and gravity.
This integrates the equation for hydrostatic equilibrium P = rho g z.
Used by _evaluate_eos()
"""
# flip radius, density and gravity to increasing pressure
depthfromtop = -self.radii[::-1] + max(self.radii)
density = density[::-1]
gravity = gravity[::-1]
# Make a spline fit of density as a function of depth
rhofunc = UnivariateSpline(depthfromtop, density)
# Make a spline fit of gravity as a function of depth
gfunc = UnivariateSpline(depthfromtop, gravity)
# integrate the hydrostatic equation
pressure = np.ravel(
odeint((lambda p, x: gfunc(x) * rhofunc(x)), pressure_top, depthfromtop)
)
return pressure[::-1]
@property
def mass(self):
"""
Calculates the mass of the layer [kg]
"""
mass = 0.0
radii = self.radii
density = self.evaluate(["density"])
rhofunc = UnivariateSpline(radii, density)
mass = np.abs(
quad(lambda r: 4 * np.pi * rhofunc(r) * r * r, radii[0], radii[-1])[0]
)
return mass
@property
def moment_of_inertia(self):
"""
Returns the moment of inertia of the layer [kg m^2]
"""
moment = 0.0
radii = self.radii
density = self.evaluate(["density"])
rhofunc = UnivariateSpline(radii, density)
moment = np.abs(
quad(
lambda r: 8.0 / 3.0 * np.pi * rhofunc(r) * r * r * r * r,
radii[0],
radii[-1],
)[0]
)
return moment
@property
def gravity(self):
"""
Returns gravity profile of the layer [m s^(-2)]
"""
return self._compute_gravity(self.density, self.gravity_bottom)
@property
def bullen(self):
"""
Returns the Bullen parameter across the layer.
The Bullen parameter assess if compression as a function of pressure is
like homogeneous, adiabatic compression.
Bullen parameter =1 , homogeneous, adiabatic compression
Bullen parameter > 1 , more compressed with pressure,
e.g. across phase transitions Bullen parameter < 1,
less compressed with pressure, e.g. across a boundary layer.
"""
kappa = self.bulk_sound_velocity * self.bulk_sound_velocity * self.density
phi = self.bulk_sound_velocity * self.bulk_sound_velocity
try:
dkappadP = np.gradient(kappa, edge_order=2) / np.gradient(
self.pressures, edge_order=2
)
dphidr = (
np.gradient(phi, edge_order=2)
/ np.gradient(self.radii, edge_order=2)
/ self.gravity
)
except:
dkappadP = np.gradient(kappa) / np.gradient(self.pressures)
dphidr = np.gradient(phi) / np.gradient(self.radii) / self.gravity
bullen = dkappadP + dphidr
return bullen
@property
def brunt_vasala(self):
"""
Returns the brunt-vasala (or buoyancy) frequency, N, across the layer.
This frequency assess the stabilty of the layer:
N < 0, fluid will convect
N= 0, fluid is neutral
N > 0, fluid is stabily stratified.
"""
kappa = self.bulk_sound_velocity * self.bulk_sound_velocity * self.density
brunt_vasala = (
self.density * self.gravity * self.gravity * (self.bullen - 1.0) / kappa
)
return brunt_vasala
@property
def pressure(self):
"""
Returns current pressures across the layer that was set
with :func:`~burnman.Material.set_state`.
Aliased with :func:`~burnman.Material.P`.
:returns: Pressures in [Pa] at the predefined radii.
:rtype: numpy.array
"""
return self.pressures
@property
def temperature(self):
"""
Returns current temperature across the layer that was set with
:func:`~burnman.Material.set_state`.
- Aliased with :func:`~burnman.Material.T`.
:returns: Temperatures in [K] at the predefined radii.
:rtype: numpy.array
"""
return self.temperatures
@material_property
def molar_internal_energy(self):
"""
Returns the molar internal energies across the layer.
Notes
-----
- Needs to be implemented in derived classes.
- Aliased with :func:`~burnman.Material.energy`.
:returns: The internal energies in [J/mol] at the predefined radii.
:rtype: numpy.array
"""
return np.array(
[
self.sublayers[i].molar_internal_energy
for i in range(len(self.sublayers))
]
)
@material_property
def molar_gibbs(self):
"""
Returns the molar Gibbs free energies across the layer.
Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.gibbs`.
:returns: Gibbs energies in [J/mol] at the predefined radii.
:rtype: numpy.array
"""
return np.array(
[self.sublayers[i].molar_gibbs for i in range(len(self.sublayers))]
)
@material_property
def molar_helmholtz(self):
"""
Returns the molar Helmholtz free energies across the layer.
Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.helmholtz`.
:returns: Helmholtz energies in [J/mol] at the predefined radii.
:rtype: numpy.array
"""
return np.array(
[self.sublayers[i].molar_helmholtz for i in range(len(self.sublayers))]
)
@material_property
def molar_mass(self):
"""
Returns molar mass of the layer.
Needs to be implemented in derived classes.
:returns: Molar mass in [kg/mol].
:rtype: numpy.array
"""
return np.array(
[self.sublayers[i].molar_mass for i in range(len(self.sublayers))]
)
@material_property
def molar_volume(self):
"""
Returns molar volumes across the layer.
Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.V`.
:returns: Molar volumes in [m^3/mol] at the predefined radii.
:rtype: numpy.array
"""
return np.array(
[self.sublayers[i].molar_volume for i in range(len(self.sublayers))]
)
@material_property
def density(self):
"""
Returns the densities across this layer.
Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.rho`.
:returns: The densities of this material in [kg/m^3] at the predefined radii.
:rtype: numpy.array
"""
return np.array([self.sublayers[i].density for i in range(len(self.sublayers))])
@material_property
def molar_entropy(self):
"""
Returns molar entropies acroos the layer.
Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.S`.
:returns: Entropies in [J/K/mol] at the predefined radii.
:rtype: numpy.array
"""
return np.array(
[self.sublayers[i].molar_entropy for i in range(len(self.sublayers))]
)
@material_property
def molar_enthalpy(self):
"""
Returns molar enthalpies across the layer.
Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.H`.
:returns: Enthalpies in [J/mol] at the predefined radii.
:rtype: numpy.array
"""
return np.array(
[self.sublayers[i].molar_enthalpy for i in range(len(self.sublayers))]
)
@material_property
def isothermal_bulk_modulus(self):
"""
Returns isothermal bulk moduli across the layer.
Notes
-----
- Needs to be implemented in derived classes.
- Aliased with :func:`~burnman.Material.K_T`.
:returns: Bulk moduli in [Pa] at the predefined radii.
:rtype: numpy.array
"""
return np.array(
[
self.sublayers[i].isothermal_bulk_modulus
for i in range(len(self.sublayers))
]
)
@material_property
def adiabatic_bulk_modulus(self):
"""
Returns the adiabatic bulk moduli across the layer.
Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.K_S`.
:returns: Adiabatic bulk modulus in [Pa] at the predefined radii.
:rtype: numpy.array
"""
return np.array(
[
self.sublayers[i].adiabatic_bulk_modulus
for i in range(len(self.sublayers))
]
)
@material_property
def isothermal_compressibility(self):
"""
Returns isothermal compressibilities across the layer
(or inverse isothermal bulk moduli).
Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.beta_T`.
:returns: Isothermal compressibilities in [1/Pa] at the predefined radii.
:rtype: numpy.array
"""
return np.array(
[
self.sublayers[i].isothermal_compressibility
for i in range(len(self.sublayers))
]
)
@material_property
def adiabatic_compressibility(self):
"""
Returns adiabatic compressibilities across the layer
(or inverse adiabatic bulk moduli).
Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.beta_S`.
:returns: Adiabatic compressibilities in [1/Pa] at the predefined radii.
:rtype: numpy.array
"""
return np.array(
[
self.sublayers[i].adiabatic_compressibility
for i in range(len(self.sublayers))
]
)
@material_property
def shear_modulus(self):
"""
Returns shear moduli across the layer.
Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.beta_G`.
:returns: Shear moduli in [Pa] at the predefined radii.
:rtype: numpy.array
"""
return np.array(
[self.sublayers[i].shear_modulus for i in range(len(self.sublayers))]
)
@material_property
def p_wave_velocity(self):
"""
Returns P wave speeds across the layer.
Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.v_p`.
:returns: P wave speeds in [m/s] at the predefined radii.
:rtype: numpy.array
"""
return np.array(
[self.sublayers[i].p_wave_velocity for i in range(len(self.sublayers))]
)
@material_property
def bulk_sound_velocity(self):
"""
Returns bulk sound speeds across the layer.
Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.v_phi`.
:returns: Bulk sound velocities in [m/s] at the predefined radii.
:rtype: numpy.array
"""
return np.array(
[self.sublayers[i].bulk_sound_velocity for i in range(len(self.sublayers))]
)
@material_property
def shear_wave_velocity(self):
"""
Returns shear wave speeds across the layer.
Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.v_s`.
:returns: Shear wave speeds in [m/s] at the predefined radii.
:rtype: numpy.array
"""
return np.array(
[self.sublayers[i].shear_wave_velocity for i in range(len(self.sublayers))]
)
@material_property
def grueneisen_parameter(self):
"""
Returns the grueneisen parameters across the layer.
Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.gr`.
:returns: Grueneisen parameters [unitless] at the predefined radii.
:rtype: numpy.array
"""
return np.array(
[self.sublayers[i].grueneisen_parameter for i in range(len(self.sublayers))]
)
@material_property
def thermal_expansivity(self):
"""
Returns thermal expansion coefficients across the layer.
Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.alpha`.
:returns: Thermal expansivities in [1/K] at the predefined radii.
:rtype: numpy.array
"""
return np.array(
[self.sublayers[i].thermal_expansivity for i in range(len(self.sublayers))]
)
@material_property
def molar_heat_capacity_v(self):
"""
Returns molar heat capacity at constant volumes across the layer.
Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.C_v`.
:returns: Heat capacities in [J/K/mol] at the predefined radii.
:rtype: numpy.array
"""
return np.array(
[
self.sublayers[i].molar_heat_capacity_v
for i in range(len(self.sublayers))
]
)
@material_property
def molar_heat_capacity_p(self):
"""
Returns molar_heat capacity at constant pressures across the layer.
Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.C_p`.
:returns: Heat capacities in [J/K/mol] at the predefined radii.
:rtype: numpy.array
"""
return np.array(
[
self.sublayers[i].molar_heat_capacity_p
for i in range(len(self.sublayers))
]
)
# Aliased properties
@property
def P(self):
"""Alias for :func:`~burnman.Layer.pressure`"""
return self.pressure
@property
def T(self):
"""Alias for :func:`~burnman.Layer.temperature`"""
return self.temperature
@property
def energy(self):
"""Alias for :func:`~burnman.Layer.molar_internal_energy`"""
return self.molar_internal_energy
@property
def helmholtz(self):
"""Alias for :func:`~burnman.Layer.molar_helmholtz`"""
return self.molar_helmholtz
@property
def gibbs(self):
"""Alias for :func:`~burnman.Layer.molar_gibbs`"""
return self.molar_gibbs
@property
def V(self):
"""Alias for :func:`~burnman.Layer.molar_volume`"""
return self.molar_volume
@property
def rho(self):
"""Alias for :func:`~burnman.Layer.density`"""
return self.density
@property
def S(self):
"""Alias for :func:`~burnman.Layer.molar_entropy`"""
return self.molar_entropy
@property
def H(self):
"""Alias for :func:`~burnman.Layer.molar_enthalpy`"""
return self.molar_enthalpy
@property
def K_T(self):
"""Alias for :func:`~burnman.Layer.isothermal_bulk_modulus`"""
return self.isothermal_bulk_modulus
@property
def K_S(self):
"""Alias for :func:`~burnman.Layer.adiabatic_bulk_modulus`"""
return self.adiabatic_bulk_modulus
@property
def beta_T(self):
"""Alias for :func:`~burnman.Layer.isothermal_compressibility`"""
return self.isothermal_compressibility
@property
def beta_S(self):
"""Alias for :func:`~burnman.Layer.adiabatic_compressibility`"""
return self.adiabatic_compressibility
@property
def G(self):
"""Alias for :func:`~burnman.Layer.shear_modulus`"""
return self.shear_modulus
@property
def v_p(self):
"""Alias for :func:`~burnman.Layer.p_wave_velocity`"""
return self.p_wave_velocity
@property
def v_phi(self):
"""Alias for :func:`~burnman.Layer.bulk_sound_velocity`"""
return self.bulk_sound_velocity
@property
def v_s(self):
"""Alias for :func:`~burnman.Layer.shear_wave_velocity`"""
return self.shear_wave_velocity
@property
def gr(self):
"""Alias for :func:`~burnman.Layer.grueneisen_parameter`"""
return self.grueneisen_parameter
@property
def alpha(self):
"""Alias for :func:`~burnman.Layer.thermal_expansivity`"""
return self.thermal_expansivity
@property
def C_v(self):
"""Alias for :func:`~burnman.Material.molar_heat_capacity_v`"""
return self.molar_heat_capacity_v
@property
def C_p(self):
"""Alias for :func:`~burnman.Material.molar_heat_capacity_p`"""
return self.molar_heat_capacity_p
| (name=None, radii=None, verbose=False) |
11,016 | burnman.classes.layer | __init__ | null | def __init__(self, name=None, radii=None, verbose=False):
self.name = name
assert np.all(np.diff(radii) > 0)
self.radii = radii
self.outer_radius = max(self.radii)
self.inner_radius = min(self.radii)
self.thickness = self.outer_radius - self.inner_radius
self.n_slices = len(self.radii)
self.verbose = verbose
self._cached = {}
self._pressures = None
self._temperatures = None
self.sublayers = None
self.material = None
self.pressure_mode = "self-consistent"
self.temperature_mode = None
| (self, name=None, radii=None, verbose=False) |
11,017 | burnman.classes.layer | __str__ |
Prints details of the layer
| def __str__(self):
"""
Prints details of the layer
"""
writing = (
f"The {self.name} is made of {self.material.name}"
f" with {self.temperature_mode} temperatures and "
f"{self.pressure_mode} pressures\n"
)
return writing
| (self) |
11,018 | burnman.classes.layer | _compute_gravity |
Computes the gravity of a layer
Used by _evaluate_eos()
| def _compute_gravity(self, density, gravity_bottom):
"""
Computes the gravity of a layer
Used by _evaluate_eos()
"""
# Create a spline fit of density as a function of radius
rhofunc = UnivariateSpline(self.radii, density)
# Numerically integrate Poisson's equation
def poisson(p, x):
return 4.0 * np.pi * constants.G * rhofunc(x) * x * x
grav = np.ravel(
odeint(poisson, gravity_bottom * self.radii[0] * self.radii[0], self.radii)
)
if self.radii[0] == 0:
grav[0] = 0
grav[1:] = grav[1:] / self.radii[1:] / self.radii[1:]
else:
grav[:] = grav[:] / self.radii[:] / self.radii[:]
return grav
| (self, density, gravity_bottom) |
11,019 | burnman.classes.layer | _compute_pressure |
Calculate the pressure profile based on density and gravity.
This integrates the equation for hydrostatic equilibrium P = rho g z.
Used by _evaluate_eos()
| def _compute_pressure(self, density, gravity, pressure_top):
"""
Calculate the pressure profile based on density and gravity.
This integrates the equation for hydrostatic equilibrium P = rho g z.
Used by _evaluate_eos()
"""
# flip radius, density and gravity to increasing pressure
depthfromtop = -self.radii[::-1] + max(self.radii)
density = density[::-1]
gravity = gravity[::-1]
# Make a spline fit of density as a function of depth
rhofunc = UnivariateSpline(depthfromtop, density)
# Make a spline fit of gravity as a function of depth
gfunc = UnivariateSpline(depthfromtop, gravity)
# integrate the hydrostatic equation
pressure = np.ravel(
odeint((lambda p, x: gfunc(x) * rhofunc(x)), pressure_top, depthfromtop)
)
return pressure[::-1]
| (self, density, gravity, pressure_top) |
11,020 | burnman.classes.layer | _evaluate_eos |
Returns updated gravity and pressure
make() loops over this until consistency is achieved.
| def _evaluate_eos(self, pressures, temperatures, gravity_bottom, pressure_top):
"""
Returns updated gravity and pressure
make() loops over this until consistency is achieved.
"""
[density] = self.material.evaluate(["density"], pressures, temperatures)
grav = self._compute_gravity(density, gravity_bottom)
press = self._compute_pressure(density, grav, pressure_top)
return grav, press
| (self, pressures, temperatures, gravity_bottom, pressure_top) |
11,021 | burnman.classes.layer | _evaluate_temperature |
Returns the temperatures of the layer for given pressures.
Used by make()
| def _evaluate_temperature(self, pressures=None, temperature_top=None):
"""
Returns the temperatures of the layer for given pressures.
Used by make()
"""
if (
self.temperature_mode == "adiabatic"
or self.temperature_mode == "perturbed-adiabatic"
):
adiabat = geotherm.adiabatic(
pressures[::-1],
temperature_top - self.usertemperatures[-1],
self.material,
)[::-1]
else:
adiabat = np.zeros_like(self.radii)
return adiabat + self.usertemperatures
| (self, pressures=None, temperature_top=None) |
11,022 | burnman.classes.layer | evaluate |
Function that is used to evaluate properties
across the layer. If radlist is not defined, values are
returned at the internal radlist.
If asking for different radii than the internal radlist,
pressure and temperature values are interpolated and the
layer material evaluated at those pressures and
temperatures.
:param properties: List of properties to evaluate.
:type properties: list of strings
:param radlist: Radii to evaluate properties at. If left empty,
internal radii list is used.
:type radlist: array of floats
:param planet_radius: Planet outer radius. Used only to calculate depth.
:type planet_radius: float
:returns: 1D or 2D array of requested properties
(1D if only one property was requested)
:rtype: numpy.array
| def evaluate(self, properties, radlist=None, radius_planet=None):
"""
Function that is used to evaluate properties
across the layer. If radlist is not defined, values are
returned at the internal radlist.
If asking for different radii than the internal radlist,
pressure and temperature values are interpolated and the
layer material evaluated at those pressures and
temperatures.
:param properties: List of properties to evaluate.
:type properties: list of strings
:param radlist: Radii to evaluate properties at. If left empty,
internal radii list is used.
:type radlist: array of floats
:param planet_radius: Planet outer radius. Used only to calculate depth.
:type planet_radius: float
:returns: 1D or 2D array of requested properties
(1D if only one property was requested)
:rtype: numpy.array
"""
if radlist is None:
values = np.empty([len(properties), len(self.radii)])
for i, prop in enumerate(properties):
if prop == "depth":
values[i] = radius_planet - self.radii
else:
try:
values[i] = getattr(self, prop)
except:
values[i] = np.array(
[
getattr(self.sublayers[i], prop)
for i in range(len(self.sublayers))
]
)
else:
func_p = interp1d(self.radii, self.pressures)
pressures = func_p(radlist)
func_t = interp1d(self.radii, self.temperatures)
temperatures = func_t(radlist)
values = np.empty([len(properties), len(radlist)])
for i, prop in enumerate(properties):
if prop == "depth":
values[i] = radius_planet - radlist
else:
try:
values[i] = self.material.evaluate(
[prop], pressures, temperatures
)
except:
func_prop = interp1d(self.radii, getattr(self, prop))
values[i] = func_prop(radlist)
if values.shape[0] == 1:
values = values[0]
return values
| (self, properties, radlist=None, radius_planet=None) |
11,023 | burnman.classes.layer | make |
This routine needs to be called before evaluating any properties.
If pressures and temperatures are not user-defined, they
are computed here. This method also initializes an array of copied
materials from which properties can be computed.
| def make(self):
"""
This routine needs to be called before evaluating any properties.
If pressures and temperatures are not user-defined, they
are computed here. This method also initializes an array of copied
materials from which properties can be computed.
"""
self.reset()
if not hasattr(self, "material"):
raise AttributeError(
"You must set_material() for the layer " "before running make()."
)
if not hasattr(self, "temperature_mode"):
raise AttributeError(
"You must set_temperature_mode() for the "
"layer before running make()."
)
if not hasattr(self, "pressure_mode"):
raise AttributeError(
"You must set_pressure_mode() for the layer " "before running make()."
)
if self.pressure_mode == "user-defined":
self.temperatures = self._evaluate_temperature(
self.pressures, self.temperature_top
)
elif self.pressure_mode == "self-consistent":
new_press = (
self.pressure_top + (-self.radii + max(self.radii)) * 1.0e3
) # initial pressure curve guess
temperatures = self._evaluate_temperature(new_press, self.temperature_top)
# Make it self-consistent!!!
i = 0
while i < self.n_max_iterations:
i += 1
ref_press = new_press
new_grav, new_press = self._evaluate_eos(
new_press, temperatures, self.gravity_bottom, self.pressure_top
)
temperatures = self._evaluate_temperature(
new_press, self.temperature_top
)
rel_err = abs((max(ref_press) - max(new_press)) / max(new_press))
if self.verbose:
print(
f"Iteration {i:0d} maximum relative pressure error: "
f"{rel_err:.1f}"
)
if rel_err < self.max_delta:
break
self.pressures = new_press
self.temperatures = temperatures
else:
raise NotImplementedError("pressure mode not recognised")
self.sublayers = []
for r in range(len(self.radii)):
self.sublayers.append(self.material.copy())
self.sublayers[r].set_state(self.pressures[r], self.temperatures[r])
| (self) |
11,024 | burnman.classes.layer | reset |
Resets all cached material properties.
It is typically not required for the user to call this function.
| def reset(self):
"""
Resets all cached material properties.
It is typically not required for the user to call this function.
"""
self._cached = {}
self._pressures = None
self._temperatures = None
self.sublayers = None
| (self) |
11,025 | burnman.classes.layer | set_material |
Set the material of a Layer with a Material
| def set_material(self, material):
"""
Set the material of a Layer with a Material
"""
assert isinstance(material, Material)
self.material = material
self.reset()
| (self, material) |
11,026 | burnman.classes.layer | set_pressure_mode |
Sets the pressure mode of the layer,
which can either be 'user-defined', or 'self-consistent'.
:param pressure_mode: This can be set to 'user-defined' or 'self-consistent'.
'user-defined' fixes the pressures with the profile input
by the user in the 'pressures' argument.
'self-consistent' forces Layer to calculate pressures
self-consistently. If this is selected, the user will need
to supply values for the gravity_bottom [m/s^2]
and pressure_top [Pa] arguments.
:type pressure_mode: string
:param pressures: Pressures [Pa] to set layer to
(if the 'user-defined' pressure_mode has been selected).
The array should be the same length as
the layers user-defined radii array.
:type pressures: array of floats
:param pressure_top: Pressure [Pa] at the top of the layer.
:type pressure_top: float
:param gravity_bottom: Gravity [m/s^2] at the bottom of the layer.
:type gravity_bottom: float
:param n_max_iterations: Maximum number of iterations to reach
self-consistent pressures.
:type n_max_iterations: integer
:param max_delta: Relative update to the highest pressure in the layer between
iterations to stop iterations.
:type max_delta: float
| def set_pressure_mode(
self,
pressure_mode="self-consistent",
pressures=None,
gravity_bottom=None,
pressure_top=None,
n_max_iterations=50,
max_delta=1.0e-5,
):
"""
Sets the pressure mode of the layer,
which can either be 'user-defined', or 'self-consistent'.
:param pressure_mode: This can be set to 'user-defined' or 'self-consistent'.
'user-defined' fixes the pressures with the profile input
by the user in the 'pressures' argument.
'self-consistent' forces Layer to calculate pressures
self-consistently. If this is selected, the user will need
to supply values for the gravity_bottom [m/s^2]
and pressure_top [Pa] arguments.
:type pressure_mode: string
:param pressures: Pressures [Pa] to set layer to
(if the 'user-defined' pressure_mode has been selected).
The array should be the same length as
the layers user-defined radii array.
:type pressures: array of floats
:param pressure_top: Pressure [Pa] at the top of the layer.
:type pressure_top: float
:param gravity_bottom: Gravity [m/s^2] at the bottom of the layer.
:type gravity_bottom: float
:param n_max_iterations: Maximum number of iterations to reach
self-consistent pressures.
:type n_max_iterations: integer
:param max_delta: Relative update to the highest pressure in the layer between
iterations to stop iterations.
:type max_delta: float
"""
self.reset()
assert pressure_mode == "user-defined" or pressure_mode == "self-consistent"
self.pressure_mode = pressure_mode
assert gravity_bottom is not None
self.gravity_bottom = gravity_bottom
if pressure_mode == "user-defined":
assert pressures is not None
assert len(pressures) == len(self.radii)
self.pressures = pressures
warnings.warn(
"By setting the pressures in Layer they "
"are unlikely to be self-consistent"
)
elif pressure_mode == "self-consistent":
self.pressure_top = pressure_top
self.n_max_iterations = n_max_iterations
self.max_delta = max_delta
else:
raise NotImplementedError(
f"pressure mode {pressure_mode} " "not recognised"
)
| (self, pressure_mode='self-consistent', pressures=None, gravity_bottom=None, pressure_top=None, n_max_iterations=50, max_delta=1e-05) |
11,027 | burnman.classes.layer | set_temperature_mode |
Sets temperatures within the layer as user-defined values or as
a (potentially perturbed) adiabat.
:param temperature_mode: This can be set to 'user-defined', 'adiabatic',
or 'perturbed-adiabatic'. 'user-defined' fixes the temperature
with the profile input by the user. 'adiabatic' self-consistently
computes the adiabat when setting the state of the layer.
'perturbed-adiabatic' adds the user input array to the adiabat.
This allows the user to apply boundary layers (for example).
:type temperature_mode: string
:param temperatures: The desired fixed temperatures in [K].
Should have same length as defined radii in layer.
:type temperatures: array of float
:param temperature_top: Temperature at the top of the layer.
Used if the temperature mode is chosen to be 'adiabatic' or
'perturbed-adiabatic'. If 'perturbed-adiabatic' is chosen as the
temperature mode, temperature_top corresponds to the true temperature
at the top of the layer, and the reference isentrope at this radius
is defined to lie at a temperature of
temperature_top - temperatures[-1].
:type temperature_top: float
| def set_temperature_mode(
self, temperature_mode="adiabatic", temperatures=None, temperature_top=None
):
"""
Sets temperatures within the layer as user-defined values or as
a (potentially perturbed) adiabat.
:param temperature_mode: This can be set to 'user-defined', 'adiabatic',
or 'perturbed-adiabatic'. 'user-defined' fixes the temperature
with the profile input by the user. 'adiabatic' self-consistently
computes the adiabat when setting the state of the layer.
'perturbed-adiabatic' adds the user input array to the adiabat.
This allows the user to apply boundary layers (for example).
:type temperature_mode: string
:param temperatures: The desired fixed temperatures in [K].
Should have same length as defined radii in layer.
:type temperatures: array of float
:param temperature_top: Temperature at the top of the layer.
Used if the temperature mode is chosen to be 'adiabatic' or
'perturbed-adiabatic'. If 'perturbed-adiabatic' is chosen as the
temperature mode, temperature_top corresponds to the true temperature
at the top of the layer, and the reference isentrope at this radius
is defined to lie at a temperature of
temperature_top - temperatures[-1].
:type temperature_top: float
"""
self.reset()
assert (
temperature_mode == "user-defined"
or temperature_mode == "adiabatic"
or temperature_mode == "perturbed-adiabatic"
)
self.temperature_mode = temperature_mode
if (
temperature_mode == "user-defined"
or temperature_mode == "perturbed-adiabatic"
):
assert len(temperatures) == len(self.radii)
self.usertemperatures = temperatures
else:
self.usertemperatures = np.zeros_like(self.radii)
if temperature_mode == "adiabatic" or temperature_mode == "perturbed-adiabatic":
self.temperature_top = temperature_top
else:
self.temperature_top = None
| (self, temperature_mode='adiabatic', temperatures=None, temperature_top=None) |
11,028 | burnman.classes.material | Material |
Base class for all materials. The main functionality is unroll() which
returns a list of objects of type :class:`~burnman.Mineral` and their molar
fractions. This class is available as ``burnman.Material``.
The user needs to call set_method() (once in the beginning) and set_state()
before querying the material with unroll() or density().
| class Material(object):
"""
Base class for all materials. The main functionality is unroll() which
returns a list of objects of type :class:`~burnman.Mineral` and their molar
fractions. This class is available as ``burnman.Material``.
The user needs to call set_method() (once in the beginning) and set_state()
before querying the material with unroll() or density().
"""
def __init__(self):
self._pressure = None
self._temperature = None
if not hasattr(self, "name"):
# if a derived class decides to set .name before calling this
# constructor (I am looking at you, SLB_2011.py!), do not
# overwrite the name here.
self._name = self.__class__.__name__
self._cached = {}
@property
def name(self):
"""Human-readable name of this material.
By default this will return the name of the class, but it can be set
to an arbitrary string. Overriden in Mineral.
"""
return self._name
@name.setter
def name(self, value):
self._name = value
def set_method(self, method):
"""
Set the averaging method. See :doc:`averaging` for details.
.. note:: Needs to be implemented in derived classes.
"""
raise NotImplementedError("need to implement set_method() in derived class!")
def to_string(self):
"""
Returns a human-readable name of this material.
The default implementation will return the name of the class,
which is a reasonable default.
:returns: A human-readable name of the material.
:rtype: str
"""
return "'" + self.name + "'"
def debug_print(self, indent=""):
"""
Print a human-readable representation of this Material.
"""
raise NotImplementedError(
"Derived classes need to implement debug_print(). This is '"
+ self.__class__.__name__
+ "'"
)
def print_minerals_of_current_state(self):
"""
Print a human-readable representation of this Material at the current
P, T as a list of minerals.
This requires set_state() has been called before.
"""
(minerals, fractions) = self.unroll()
if len(minerals) == 1:
print(minerals[0].to_string())
else:
print("Material %s:" % self.to_string())
for mineral, fraction in zip(minerals, fractions):
print(" %g of phase %s" % (fraction, mineral.to_string()))
def set_state(self, pressure, temperature):
"""
Set the material to the given pressure and temperature.
:param pressure: The desired pressure in [Pa].
:type pressure: float
:param temperature: The desired temperature in [K].
:type temperature: float
"""
if not hasattr(self, "_pressure"):
raise Exception(
"Material.set_state() could not find class member _pressure. "
"Did you forget to call Material.__init__(self) in __init___?"
)
self.reset()
self._pressure = pressure
self._temperature = temperature
def set_state_with_volume(
self, volume, temperature, pressure_guesses=[0.0e9, 10.0e9]
):
"""
This function acts similarly to set_state, but takes volume and
temperature as input to find the pressure. In order to ensure
self-consistency, this function does not use any pressure functions
from the material classes, but instead finds the pressure using the
brentq root-finding method.
:param volume: The desired molar volume of the mineral [m^3].
:type volume: float
:param temperature: The desired temperature of the mineral [K].
:type temperature: float
:param pressure_guesses: A list of floats denoting the initial
low and high guesses for bracketing of the pressure [Pa].
These guesses should preferably bound the correct pressure,
but do not need to do so. More importantly,
they should not lie outside the valid region of
the equation of state. Defaults to [5.e9, 10.e9].
:type pressure_guesses: list
"""
def _delta_volume(pressure, volume, temperature):
# Try to set the state with this pressure,
# but if the pressure is too low most equations of state
# fail. In this case, treat the molar_volume as infinite
# and brentq will try a larger pressure.
try:
self.set_state(pressure, temperature)
return volume - self.molar_volume
except Exception:
return -np.inf
# we need to have a sign change in [a,b] to find a zero.
args = (volume, temperature)
try:
sol = bracket(_delta_volume, pressure_guesses[0], pressure_guesses[1], args)
except ValueError:
raise Exception(
"Cannot find a pressure, perhaps the volume or starting pressures "
"are outside the range of validity for the equation of state?"
)
pressure = brentq(_delta_volume, sol[0], sol[1], args=args)
self.set_state(pressure, temperature)
def reset(self):
"""
Resets all cached material properties.
It is typically not required for the user to call this function.
"""
self._cached = {}
def copy(self):
return deepcopy(self)
def unroll(self):
"""
Unroll this material into a list of :class:`burnman.Mineral` and their molar
fractions. All averaging schemes then operate on this list of minerals.
Note that the return value of this function may depend on the current
state (temperature, pressure).
.. note:: Needs to be implemented in derived classes.
:returns: A list of molar fractions which should sum to 1.0,
and a list of :class:`burnman.Mineral` objects
containing the minerals in the material.
:rtype: tuple
"""
raise NotImplementedError("need to implement unroll() in derived class!")
def evaluate(self, vars_list, pressures, temperatures):
"""
Returns an array of material properties requested through a list of strings
at given pressure and temperature conditions.
At the end it resets the set_state to the original values.
The user needs to call set_method() before.
:param vars_list: Variables to be returned for given conditions
:type vars_list: list of strings
:param pressures: ndlist or ndarray of float of pressures in [Pa].
:type pressures: :class:`numpy.array`, n-dimensional
:param temperatures: ndlist or ndarray of float of temperatures in [K].
:type temperatures: :class:`numpy.array`, n-dimensional
:returns: Array returning all variables at given pressure/temperature values.
output[i][j] is property vars_list[j] for temperatures[i] and pressures[i].
:rtype: :class:`numpy.array`, n-dimensional
"""
old_pressure = self.pressure
old_temperature = self.temperature
pressures = np.array(pressures)
temperatures = np.array(temperatures)
assert pressures.shape == temperatures.shape
output = np.empty((len(vars_list),) + pressures.shape)
for i, p in np.ndenumerate(pressures):
self.set_state(p, temperatures[i])
for j in range(len(vars_list)):
output[(j,) + i] = getattr(self, vars_list[j])
if old_pressure is None or old_temperature is None:
# do not set_state if old values were None. Just reset to None
# manually
self._pressure = self._temperature = None
self.reset()
else:
self.set_state(old_pressure, old_temperature)
return output
@property
def pressure(self):
"""
Returns current pressure that was set with :func:`~burnman.Material.set_state`.
.. note:: Aliased with :func:`~burnman.Material.P`.
:returns: Pressure in [Pa].
:rtype: float
"""
return self._pressure
@property
def temperature(self):
"""
Returns current temperature that was set with
:func:`~burnman.Material.set_state`.
.. note:: Aliased with :func:`~burnman.Material.T`.
:returns: Temperature in [K].
:rtype: float
"""
return self._temperature
@material_property
def molar_internal_energy(self):
"""
Returns the molar internal energy of the mineral.
.. note:: Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.energy`.
:returns: The internal energy in [J/mol].
:rtype: float
"""
raise NotImplementedError(
"need to implement molar_internal_energy() in derived class!"
)
@material_property
def molar_gibbs(self):
"""
Returns the molar Gibbs free energy of the mineral.
.. note:: Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.gibbs`.
:returns: Gibbs free energy in [J/mol].
:rtype: float
"""
raise NotImplementedError("need to implement molar_gibbs() in derived class!")
@material_property
def molar_helmholtz(self):
"""
Returns the molar Helmholtz free energy of the mineral.
.. note:: Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.helmholtz`.
:returns: Helmholtz free energy in [J/mol].
:rtype: float
"""
raise NotImplementedError(
"need to implement molar_helmholtz() in derived class!"
)
@material_property
def molar_mass(self):
"""
Returns molar mass of the mineral.
.. note:: Needs to be implemented in derived classes.
:returns: Molar mass in [kg/mol].
:rtype: float
"""
raise NotImplementedError("need to implement molar_mass() in derived class!")
@material_property
def molar_volume(self):
"""
Returns molar volume of the mineral.
.. note:: Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.V`.
:returns: Molar volume in [m^3/mol].
:rtype: float
"""
raise NotImplementedError("need to implement molar_volume() in derived class!")
@material_property
def density(self):
"""
Returns the density of this material.
.. note:: Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.rho`.
:returns: The density of this material in [kg/m^3].
:rtype: float
"""
raise NotImplementedError("need to implement density() in derived class!")
@material_property
def molar_entropy(self):
"""
Returns molar entropy of the mineral.
.. note:: Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.S`.
:returns: Entropy in [J/K/mol].
:rtype: float
"""
raise NotImplementedError("need to implement molar_entropy() in derived class!")
@material_property
def molar_enthalpy(self):
"""
Returns molar enthalpy of the mineral.
.. note:: Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.H`.
:returns: Enthalpy in [J/mol].
:rtype: float
"""
raise NotImplementedError(
"need to implement molar_enthalpy() in derived class!"
)
@material_property
def isothermal_bulk_modulus(self):
"""
Returns isothermal bulk modulus of the material.
.. note:: Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.K_T`.
:returns: Isothermal bulk modulus in [Pa].
:rtype: float
"""
raise NotImplementedError(
"need to implement isothermal_bulk_moduls() in derived class!"
)
@material_property
def adiabatic_bulk_modulus(self):
"""
Returns the adiabatic bulk modulus of the mineral.
.. note:: Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.K_S`.
:returns: Adiabatic bulk modulus in [Pa].
:rtype: float
"""
raise NotImplementedError(
"need to implement adiabatic_bulk_modulus() in derived class!"
)
@material_property
def isothermal_compressibility(self):
"""
Returns isothermal compressibility of the mineral
(or inverse isothermal bulk modulus).
.. note:: Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.beta_T`.
:returns: Isothermal compressibility in [1/Pa].
:rtype: float
"""
raise NotImplementedError(
"need to implement compressibility() in derived class!"
)
@material_property
def adiabatic_compressibility(self):
"""
Returns adiabatic compressibility of the mineral
(or inverse adiabatic bulk modulus).
.. note:: Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.beta_S`.
:returns: Adiabatic compressibility in [1/Pa].
:rtype: float
"""
raise NotImplementedError(
"need to implement compressibility() in derived class!"
)
@material_property
def shear_modulus(self):
"""
Returns shear modulus of the mineral.
.. note:: Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.beta_G`.
:returns: Shear modulus in [Pa].
:rtype: float
"""
raise NotImplementedError("need to implement shear_modulus() in derived class!")
@material_property
def p_wave_velocity(self):
"""
Returns P wave speed of the mineral.
.. note:: Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.v_p`.
:returns: P wave speed in [m/s].
:rtype: float
"""
raise NotImplementedError(
"need to implement p_wave_velocity() in derived class!"
)
@material_property
def bulk_sound_velocity(self):
"""
Returns bulk sound speed of the mineral.
.. note:: Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.v_phi`.
:returns: Bulk sound velocity in [m/s].
:rtype: float
"""
raise NotImplementedError(
"need to implement bulk_sound_velocity() in derived class!"
)
@material_property
def shear_wave_velocity(self):
"""
Returns shear wave speed of the mineral.
.. note:: Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.v_s`.
:returns: Shear wave speed in [m/s].
:rtype: float
"""
raise NotImplementedError(
"need to implement shear_wave_velocity() in derived class!"
)
@material_property
def grueneisen_parameter(self):
"""
Returns the grueneisen parameter of the mineral.
.. note:: Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.gr`.
:returns: Grueneisen parameter [unitless].
:rtype: float
"""
raise NotImplementedError(
"need to implement grueneisen_parameter() in derived class!"
)
@material_property
def thermal_expansivity(self):
"""
Returns thermal expansion coefficient of the mineral.
.. note:: Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.alpha`.
:returns: Thermal expansivity in [1/K].
:rtype: float
"""
raise NotImplementedError(
"need to implement thermal_expansivity() in derived class!"
)
@material_property
def molar_heat_capacity_v(self):
"""
Returns molar heat capacity at constant volume of the mineral.
.. note:: Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.C_v`.
:returns: Isochoric heat capacity in [J/K/mol].
:rtype: float
"""
raise NotImplementedError(
"need to implement molar_heat_capacity_v() in derived class!"
)
@material_property
def molar_heat_capacity_p(self):
"""
Returns molar heat capacity at constant pressure of the mineral.
.. note:: Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.C_p`.
:returns: Isobaric heat capacity in [J/K/mol].
:rtype: float
"""
raise NotImplementedError(
"need to implement molar_heat_capacity_p() in derived class!"
)
#
# Aliased properties
@property
def P(self):
"""Alias for :func:`~burnman.Material.pressure`"""
return self.pressure
@property
def T(self):
"""Alias for :func:`~burnman.Material.temperature`"""
return self.temperature
@property
def energy(self):
"""Alias for :func:`~burnman.Material.molar_internal_energy`"""
return self.molar_internal_energy
@property
def helmholtz(self):
"""Alias for :func:`~burnman.Material.molar_helmholtz`"""
return self.molar_helmholtz
@property
def gibbs(self):
"""Alias for :func:`~burnman.Material.molar_gibbs`"""
return self.molar_gibbs
@property
def V(self):
"""Alias for :func:`~burnman.Material.molar_volume`"""
return self.molar_volume
@property
def rho(self):
"""Alias for :func:`~burnman.Material.density`"""
return self.density
@property
def S(self):
"""Alias for :func:`~burnman.Material.molar_entropy`"""
return self.molar_entropy
@property
def H(self):
"""Alias for :func:`~burnman.Material.molar_enthalpy`"""
return self.molar_enthalpy
@property
def K_T(self):
"""Alias for :func:`~burnman.Material.isothermal_bulk_modulus`"""
return self.isothermal_bulk_modulus
@property
def K_S(self):
"""Alias for :func:`~burnman.Material.adiabatic_bulk_modulus`"""
return self.adiabatic_bulk_modulus
@property
def beta_T(self):
"""Alias for :func:`~burnman.Material.isothermal_compressibility`"""
return self.isothermal_compressibility
@property
def beta_S(self):
"""Alias for :func:`~burnman.Material.adiabatic_compressibility`"""
return self.adiabatic_compressibility
@property
def isothermal_bulk_modulus_reuss(self):
"""Alias for :func:`~burnman.Material.isothermal_bulk_modulus`"""
return self.isothermal_bulk_modulus
@property
def adiabatic_bulk_modulus_reuss(self):
"""Alias for :func:`~burnman.Material.adiabatic_bulk_modulus`"""
return self.adiabatic_bulk_modulus
@property
def isothermal_compressibility_reuss(self):
"""Alias for :func:`~burnman.Material.isothermal_compressibility`"""
return self.isothermal_compressibility
@property
def adiabatic_compressibility_reuss(self):
"""Alias for :func:`~burnman.Material.adiabatic_compressibility`"""
return self.adiabatic_compressibility
@property
def G(self):
"""Alias for :func:`~burnman.Material.shear_modulus`"""
return self.shear_modulus
@property
def v_p(self):
"""Alias for :func:`~burnman.Material.p_wave_velocity`"""
return self.p_wave_velocity
@property
def v_phi(self):
"""Alias for :func:`~burnman.Material.bulk_sound_velocity`"""
return self.bulk_sound_velocity
@property
def v_s(self):
"""Alias for :func:`~burnman.Material.shear_wave_velocity`"""
return self.shear_wave_velocity
@property
def gr(self):
"""Alias for :func:`~burnman.Material.grueneisen_parameter`"""
return self.grueneisen_parameter
@property
def alpha(self):
"""Alias for :func:`~burnman.Material.thermal_expansivity`"""
return self.thermal_expansivity
@property
def C_v(self):
"""Alias for :func:`~burnman.Material.molar_heat_capacity_v`"""
return self.molar_heat_capacity_v
@property
def C_p(self):
"""Alias for :func:`~burnman.Material.molar_heat_capacity_p`"""
return self.molar_heat_capacity_p
| () |
11,029 | burnman.classes.material | __init__ | null | def __init__(self):
self._pressure = None
self._temperature = None
if not hasattr(self, "name"):
# if a derived class decides to set .name before calling this
# constructor (I am looking at you, SLB_2011.py!), do not
# overwrite the name here.
self._name = self.__class__.__name__
self._cached = {}
| (self) |
11,040 | burnman.classes.polytope | MaterialPolytope |
A class that can be instantiated to create pycddlib polytope objects.
These objects can be interrogated to provide the vertices satisfying the
input constraints.
This class is available as :class:`burnman.polytope.MaterialPolytope`.
| class MaterialPolytope(object):
"""
A class that can be instantiated to create pycddlib polytope objects.
These objects can be interrogated to provide the vertices satisfying the
input constraints.
This class is available as :class:`burnman.polytope.MaterialPolytope`.
"""
def __init__(
self,
equalities,
inequalities,
number_type="fraction",
return_fractions=False,
independent_endmember_occupancies=None,
):
"""
Initialization function for the MaterialPolytope class.
Declares basis attributes of the class.
:param equalities: A numpy array containing all the
equalities defining the polytope. Each row should evaluate to 0.
:type equalities: numpy.array (2D)
:param inequalities: A numpy array containing all the inequalities
defining the polytope. Each row should evaluate to <= 0.
:type inequalities: numpy.array (2D)
:param number_type: Whether pycddlib should read the input arrays as
fractions or floats. Valid options are 'fraction' or 'float'.
:type number_type: str
:param return_fractions: Choose whether the generated polytope object
should return fractions or floats.
:type return_fractions: bool
:param independent_endmember_occupancies: If specified, this array provides
the independent endmember set against which the dependent endmembers
are defined.
:type independent_endmember_occupancies: numpy.array (2D) or None
"""
self.set_return_type(return_fractions)
self.equality_matrix = equalities[:, 1:]
self.equality_vector = -equalities[:, 0]
self.polytope_matrix = cdd.Matrix(
equalities, linear=True, number_type=number_type
)
self.polytope_matrix.rep_type = cdd.RepType.INEQUALITY
self.polytope_matrix.extend(inequalities, linear=False)
self.polytope = cdd.Polyhedron(self.polytope_matrix)
if independent_endmember_occupancies is not None:
self.independent_endmember_occupancies = independent_endmember_occupancies
def set_return_type(self, return_fractions=False):
"""
Sets the return_type for the polytope object. Also deletes the cached
endmember_occupancies property.
:param return_fractions: Choose whether the generated polytope object
should return fractions or floats.
:type return_fractions: bool
"""
try:
del self.__dict__["endmember_occupancies"]
except KeyError:
pass
self.return_fractions = return_fractions
@cached_property
def raw_vertices(self):
"""
Returns a list of the vertices of the polytope without any
postprocessing. See also endmember_occupancies.
"""
return self.polytope.get_generators()[:]
@cached_property
def limits(self):
"""
Return the limits of the polytope (the set of bounding inequalities).
"""
return np.array(self.polytope.get_inequalities(), dtype=float)
@cached_property
def n_endmembers(self):
"""
Return the number of endmembers
(the number of vertices of the polytope).
"""
return len(self.raw_vertices)
@cached_property
def endmember_occupancies(self):
"""
Return the endmember occupancies
(a processed list of all of the vertex locations).
"""
if self.return_fractions:
if self.polytope.number_type == "fraction":
v = np.array(
[[Fraction(value) for value in v] for v in self.raw_vertices]
)
else:
v = np.array(
[
[Rational(value).limit_denominator(1000000) for value in v]
for v in self.raw_vertices
]
)
else:
v = np.array([[float(value) for value in v] for v in self.raw_vertices])
if len(v.shape) == 1:
raise ValueError(
"The combined equality and positivity "
"constraints result in a null polytope."
)
return v[:, 1:] / v[:, 0, np.newaxis]
@cached_property
def independent_endmember_occupancies(self):
"""
Return an independent set of endmember occupancies
(a linearly-independent set of vertex locations)
"""
arr = self.endmember_occupancies
return arr[independent_row_indices(arr)]
@cached_property
def endmembers_as_independent_endmember_amounts(self):
"""
Return a list of all the endmembers as a linear sum of
the independent endmembers.
"""
ind = self.independent_endmember_occupancies
sol = (
np.linalg.lstsq(
np.array(ind.T).astype(float),
np.array(self.endmember_occupancies.T).astype(float),
rcond=0,
)[0]
.round(decimals=12)
.T
)
return sol
def _decompose_vertices_into_simplices(self, vertices):
"""
Decomposes a set of vertices into simplices by Delaunay triangulation.
"""
# Delaunay triangulation only works in dimensions > 1
# and we remove the nullspace (sum(fractions) = 1)
if len(vertices) > 2:
nulls = np.repeat(vertices[:, -1], vertices.shape[1]).reshape(
vertices.shape
)
tri = Delaunay((vertices - nulls)[:, :-1])
return tri.simplices
else:
return [[0, 1]]
@cached_property
def independent_endmember_polytope(self):
"""
Returns the polytope expressed in terms of proportions of the
independent endmembers. The polytope involves the first
n-1 independent endmembers. The last endmember proportion makes
the sum equal to one.
"""
arr = self.endmembers_as_independent_endmember_amounts
arr = np.hstack((np.ones((len(arr), 1)), arr[:, :-1]))
M = cdd.Matrix(arr, number_type="fraction")
M.rep_type = cdd.RepType.GENERATOR
return cdd.Polyhedron(M)
@cached_property
def independent_endmember_limits(self):
"""
Gets the limits of the polytope as a function of the independent
endmembers.
"""
return np.array(
self.independent_endmember_polytope.get_inequalities(), dtype=float
)
def subpolytope_from_independent_endmember_limits(self, limits):
"""
Returns a smaller polytope by applying additional limits to the amounts
of the independent endmembers.
"""
modified_limits = self.independent_endmember_polytope.get_inequalities().copy()
modified_limits.extend(limits, linear=False)
return cdd.Polyhedron(modified_limits)
def subpolytope_from_site_occupancy_limits(self, limits):
"""
Returns a smaller polytope by applying additional limits to the
individual site occupancies.
"""
modified_limits = self.polytope_matrix.copy()
modified_limits.extend(limits, linear=False)
return cdd.Polyhedron(modified_limits)
def grid(
self,
points_per_edge=2,
unique_sorted=True,
grid_type="independent endmember proportions",
limits=None,
):
"""
Create a grid of points which span the polytope.
:param points_per_edge: Number of points per edge of the polytope.
:type points_per_edge: int
:param unique_sorted: The gridding is done by splitting the polytope into
a set of simplices. This means that points will be duplicated along
vertices, faces etc. If unique_sorted is True, this function
will sort and make the points unique. This is an expensive
operation for large polytopes, and may not always be necessary.
:type unique_sorted: bool
:param grid_type: Whether to grid the polytope in terms of
independent endmember proportions or site occupancies.
Choices are 'independent endmember proportions' or 'site occupancies'
:type grid_type: str
:param limits: Additional inequalities restricting the
gridded area of the polytope.
:type limits: numpy.array (2D)
:returns: A list of points gridding the polytope.
:rtype: numpy.array (2D)
"""
if limits is None:
if grid_type == "independent endmember proportions":
f_occ = self.endmembers_as_independent_endmember_amounts / (
points_per_edge - 1
)
elif grid_type == "site occupancies":
f_occ = self.endmember_occupancies / (points_per_edge - 1)
else:
raise Exception(
"grid type not recognised. Should be one of "
"independent endmember proportions "
"or site occupancies"
)
simplices = self._decompose_vertices_into_simplices(
self.endmembers_as_independent_endmember_amounts
)
else:
if grid_type == "independent endmember proportions":
ppns = np.array(
self.subpolytope_from_independent_endmember_limits(
limits
).get_generators()[:]
)[:, 1:]
last_ppn = np.array([1.0 - sum(p) for p in ppns]).reshape(
(len(ppns), 1)
)
vertices_as_independent_endmember_proportions = np.hstack(
(ppns, last_ppn)
)
f_occ = vertices_as_independent_endmember_proportions / (
points_per_edge - 1
)
elif grid_type == "site occupancies":
occ = np.array(
self.subpolytope_from_site_occupancy_limits(
limits
).get_generators()[:]
)[:, 1:]
f_occ = occ / (points_per_edge - 1)
ind = self.independent_endmember_occupancies
vertices_as_independent_endmember_proportions = (
np.linalg.lstsq(
np.array(ind.T).astype(float),
np.array(occ.T).astype(float),
rcond=None,
)[0]
.round(decimals=12)
.T
)
else:
raise Exception(
"grid_type not recognised. "
"Should be one of "
"independent endmember proportions "
"or site occupancies"
)
simplices = self._decompose_vertices_into_simplices(
vertices_as_independent_endmember_proportions
)
n_ind = f_occ.shape[1]
n_simplices = len(simplices)
dim = len(simplices[0])
simplex_grid = SimplexGrid(dim, points_per_edge)
grid = simplex_grid.grid("array")
points_per_simplex = simplex_grid.n_points()
n_points = n_simplices * points_per_simplex
points = np.empty((n_points, n_ind))
idx = 0
for i in range(0, n_simplices):
points[idx : idx + points_per_simplex] = grid.dot(f_occ[simplices[i]])
idx += points_per_simplex
if unique_sorted:
points = np.unique(points, axis=0)
return points
| (equalities, inequalities, number_type='fraction', return_fractions=False, independent_endmember_occupancies=None) |
11,041 | burnman.classes.polytope | __init__ |
Initialization function for the MaterialPolytope class.
Declares basis attributes of the class.
:param equalities: A numpy array containing all the
equalities defining the polytope. Each row should evaluate to 0.
:type equalities: numpy.array (2D)
:param inequalities: A numpy array containing all the inequalities
defining the polytope. Each row should evaluate to <= 0.
:type inequalities: numpy.array (2D)
:param number_type: Whether pycddlib should read the input arrays as
fractions or floats. Valid options are 'fraction' or 'float'.
:type number_type: str
:param return_fractions: Choose whether the generated polytope object
should return fractions or floats.
:type return_fractions: bool
:param independent_endmember_occupancies: If specified, this array provides
the independent endmember set against which the dependent endmembers
are defined.
:type independent_endmember_occupancies: numpy.array (2D) or None
| def __init__(
self,
equalities,
inequalities,
number_type="fraction",
return_fractions=False,
independent_endmember_occupancies=None,
):
"""
Initialization function for the MaterialPolytope class.
Declares basis attributes of the class.
:param equalities: A numpy array containing all the
equalities defining the polytope. Each row should evaluate to 0.
:type equalities: numpy.array (2D)
:param inequalities: A numpy array containing all the inequalities
defining the polytope. Each row should evaluate to <= 0.
:type inequalities: numpy.array (2D)
:param number_type: Whether pycddlib should read the input arrays as
fractions or floats. Valid options are 'fraction' or 'float'.
:type number_type: str
:param return_fractions: Choose whether the generated polytope object
should return fractions or floats.
:type return_fractions: bool
:param independent_endmember_occupancies: If specified, this array provides
the independent endmember set against which the dependent endmembers
are defined.
:type independent_endmember_occupancies: numpy.array (2D) or None
"""
self.set_return_type(return_fractions)
self.equality_matrix = equalities[:, 1:]
self.equality_vector = -equalities[:, 0]
self.polytope_matrix = cdd.Matrix(
equalities, linear=True, number_type=number_type
)
self.polytope_matrix.rep_type = cdd.RepType.INEQUALITY
self.polytope_matrix.extend(inequalities, linear=False)
self.polytope = cdd.Polyhedron(self.polytope_matrix)
if independent_endmember_occupancies is not None:
self.independent_endmember_occupancies = independent_endmember_occupancies
| (self, equalities, inequalities, number_type='fraction', return_fractions=False, independent_endmember_occupancies=None) |
11,042 | burnman.classes.polytope | _decompose_vertices_into_simplices |
Decomposes a set of vertices into simplices by Delaunay triangulation.
| def _decompose_vertices_into_simplices(self, vertices):
"""
Decomposes a set of vertices into simplices by Delaunay triangulation.
"""
# Delaunay triangulation only works in dimensions > 1
# and we remove the nullspace (sum(fractions) = 1)
if len(vertices) > 2:
nulls = np.repeat(vertices[:, -1], vertices.shape[1]).reshape(
vertices.shape
)
tri = Delaunay((vertices - nulls)[:, :-1])
return tri.simplices
else:
return [[0, 1]]
| (self, vertices) |
11,043 | burnman.classes.polytope | grid |
Create a grid of points which span the polytope.
:param points_per_edge: Number of points per edge of the polytope.
:type points_per_edge: int
:param unique_sorted: The gridding is done by splitting the polytope into
a set of simplices. This means that points will be duplicated along
vertices, faces etc. If unique_sorted is True, this function
will sort and make the points unique. This is an expensive
operation for large polytopes, and may not always be necessary.
:type unique_sorted: bool
:param grid_type: Whether to grid the polytope in terms of
independent endmember proportions or site occupancies.
Choices are 'independent endmember proportions' or 'site occupancies'
:type grid_type: str
:param limits: Additional inequalities restricting the
gridded area of the polytope.
:type limits: numpy.array (2D)
:returns: A list of points gridding the polytope.
:rtype: numpy.array (2D)
| def grid(
self,
points_per_edge=2,
unique_sorted=True,
grid_type="independent endmember proportions",
limits=None,
):
"""
Create a grid of points which span the polytope.
:param points_per_edge: Number of points per edge of the polytope.
:type points_per_edge: int
:param unique_sorted: The gridding is done by splitting the polytope into
a set of simplices. This means that points will be duplicated along
vertices, faces etc. If unique_sorted is True, this function
will sort and make the points unique. This is an expensive
operation for large polytopes, and may not always be necessary.
:type unique_sorted: bool
:param grid_type: Whether to grid the polytope in terms of
independent endmember proportions or site occupancies.
Choices are 'independent endmember proportions' or 'site occupancies'
:type grid_type: str
:param limits: Additional inequalities restricting the
gridded area of the polytope.
:type limits: numpy.array (2D)
:returns: A list of points gridding the polytope.
:rtype: numpy.array (2D)
"""
if limits is None:
if grid_type == "independent endmember proportions":
f_occ = self.endmembers_as_independent_endmember_amounts / (
points_per_edge - 1
)
elif grid_type == "site occupancies":
f_occ = self.endmember_occupancies / (points_per_edge - 1)
else:
raise Exception(
"grid type not recognised. Should be one of "
"independent endmember proportions "
"or site occupancies"
)
simplices = self._decompose_vertices_into_simplices(
self.endmembers_as_independent_endmember_amounts
)
else:
if grid_type == "independent endmember proportions":
ppns = np.array(
self.subpolytope_from_independent_endmember_limits(
limits
).get_generators()[:]
)[:, 1:]
last_ppn = np.array([1.0 - sum(p) for p in ppns]).reshape(
(len(ppns), 1)
)
vertices_as_independent_endmember_proportions = np.hstack(
(ppns, last_ppn)
)
f_occ = vertices_as_independent_endmember_proportions / (
points_per_edge - 1
)
elif grid_type == "site occupancies":
occ = np.array(
self.subpolytope_from_site_occupancy_limits(
limits
).get_generators()[:]
)[:, 1:]
f_occ = occ / (points_per_edge - 1)
ind = self.independent_endmember_occupancies
vertices_as_independent_endmember_proportions = (
np.linalg.lstsq(
np.array(ind.T).astype(float),
np.array(occ.T).astype(float),
rcond=None,
)[0]
.round(decimals=12)
.T
)
else:
raise Exception(
"grid_type not recognised. "
"Should be one of "
"independent endmember proportions "
"or site occupancies"
)
simplices = self._decompose_vertices_into_simplices(
vertices_as_independent_endmember_proportions
)
n_ind = f_occ.shape[1]
n_simplices = len(simplices)
dim = len(simplices[0])
simplex_grid = SimplexGrid(dim, points_per_edge)
grid = simplex_grid.grid("array")
points_per_simplex = simplex_grid.n_points()
n_points = n_simplices * points_per_simplex
points = np.empty((n_points, n_ind))
idx = 0
for i in range(0, n_simplices):
points[idx : idx + points_per_simplex] = grid.dot(f_occ[simplices[i]])
idx += points_per_simplex
if unique_sorted:
points = np.unique(points, axis=0)
return points
| (self, points_per_edge=2, unique_sorted=True, grid_type='independent endmember proportions', limits=None) |
11,044 | burnman.classes.polytope | set_return_type |
Sets the return_type for the polytope object. Also deletes the cached
endmember_occupancies property.
:param return_fractions: Choose whether the generated polytope object
should return fractions or floats.
:type return_fractions: bool
| def set_return_type(self, return_fractions=False):
"""
Sets the return_type for the polytope object. Also deletes the cached
endmember_occupancies property.
:param return_fractions: Choose whether the generated polytope object
should return fractions or floats.
:type return_fractions: bool
"""
try:
del self.__dict__["endmember_occupancies"]
except KeyError:
pass
self.return_fractions = return_fractions
| (self, return_fractions=False) |
11,045 | burnman.classes.polytope | subpolytope_from_independent_endmember_limits |
Returns a smaller polytope by applying additional limits to the amounts
of the independent endmembers.
| def subpolytope_from_independent_endmember_limits(self, limits):
"""
Returns a smaller polytope by applying additional limits to the amounts
of the independent endmembers.
"""
modified_limits = self.independent_endmember_polytope.get_inequalities().copy()
modified_limits.extend(limits, linear=False)
return cdd.Polyhedron(modified_limits)
| (self, limits) |
11,046 | burnman.classes.polytope | subpolytope_from_site_occupancy_limits |
Returns a smaller polytope by applying additional limits to the
individual site occupancies.
| def subpolytope_from_site_occupancy_limits(self, limits):
"""
Returns a smaller polytope by applying additional limits to the
individual site occupancies.
"""
modified_limits = self.polytope_matrix.copy()
modified_limits.extend(limits, linear=False)
return cdd.Polyhedron(modified_limits)
| (self, limits) |
11,047 | burnman.classes.mineral | Mineral |
This is the base class for all minerals. States of the mineral
can only be queried after setting the pressure and temperature
using set_state(). The method for computing properties of
the material is set using set_method(). This is done during
initialisation if the param 'equation_of_state' has been defined.
The method can be overridden later by the user.
This class is available as ``burnman.Mineral``.
If deriving from this class, set the properties in self.params
to the desired values. For more complicated materials you
can overwrite set_state(), change the params and then call
set_state() from this class.
All the material parameters are expected to be in plain SI units. This
means that the elastic moduli should be in Pascals and NOT Gigapascals,
and the Debye temperature should be in K not C. Additionally, the
reference volume should be in m^3/(mol molecule) and not in unit cell
volume and 'n' should be the number of atoms per molecule. Frequently in
the literature the reference volume is given in Angstrom^3 per unit cell.
To convert this to m^3/(mol of molecule) you should multiply by 10^(-30) *
N_a / Z, where N_a is Avogadro's number and Z is the number of formula units per
unit cell. You can look up Z in many places, including www.mindat.org
| class Mineral(Material):
"""
This is the base class for all minerals. States of the mineral
can only be queried after setting the pressure and temperature
using set_state(). The method for computing properties of
the material is set using set_method(). This is done during
initialisation if the param 'equation_of_state' has been defined.
The method can be overridden later by the user.
This class is available as ``burnman.Mineral``.
If deriving from this class, set the properties in self.params
to the desired values. For more complicated materials you
can overwrite set_state(), change the params and then call
set_state() from this class.
All the material parameters are expected to be in plain SI units. This
means that the elastic moduli should be in Pascals and NOT Gigapascals,
and the Debye temperature should be in K not C. Additionally, the
reference volume should be in m^3/(mol molecule) and not in unit cell
volume and 'n' should be the number of atoms per molecule. Frequently in
the literature the reference volume is given in Angstrom^3 per unit cell.
To convert this to m^3/(mol of molecule) you should multiply by 10^(-30) *
N_a / Z, where N_a is Avogadro's number and Z is the number of formula units per
unit cell. You can look up Z in many places, including www.mindat.org
"""
def __init__(self, params=None, property_modifiers=None):
Material.__init__(self)
if params is not None:
self.params = params
elif "params" not in self.__dict__:
self.params = {}
if property_modifiers is not None:
self.property_modifiers = property_modifiers
elif "property_modifiers" not in self.__dict__:
self.property_modifiers = []
self.method = None
if "equation_of_state" in self.params:
self.set_method(self.params["equation_of_state"])
if "name" in self.params:
self.name = self.params["name"]
def set_method(self, equation_of_state):
"""
Set the equation of state to be used for this mineral.
Takes a string corresponding to any of the predefined
equations of state: 'bm2', 'bm3', 'mgd2', 'mgd3', 'slb2', 'slb3',
'mt', 'hp_tmt', or 'cork'. Alternatively, you can pass a user defined
class which derives from the equation_of_state base class.
After calling set_method(), any existing derived properties
(e.g., elastic parameters or thermodynamic potentials) will be out
of date, so set_state() will need to be called again.
"""
if equation_of_state is None:
self.method = None
return
new_method = eos.create(equation_of_state)
if self.method is not None and "equation_of_state" in self.params:
self.method = eos.create(self.params["equation_of_state"])
if type(new_method).__name__ == "instance":
raise Exception(
"Please derive your method from object (see python old style classes)"
)
if (
self.method is not None
and isinstance(new_method, type(self.method)) is False
):
# Warn user that they are changing the EoS
warnings.warn(
"Warning, you are changing the method to "
f"{new_method.__class__.__name__} even though the "
"material is designed to be used with the method "
f"{self.method.__class__.__name__}. "
"This does not overwrite any mineral attributes",
stacklevel=2,
)
self.reset()
self.method = new_method
# Validate the params object on the requested EOS.
try:
self.method.validate_parameters(self.params)
except Exception as e:
print(
f"Mineral {self.to_string()} failed to validate parameters "
f'with message: "{e.message}"'
)
raise
# Invalidate the cache upon resetting the method
self.reset()
def to_string(self):
"""
Returns the name of the mineral class
"""
return (
"'"
+ self.__class__.__module__.replace(".minlib_", ".")
+ "."
+ self.__class__.__name__
+ "'"
)
def debug_print(self, indent=""):
print("%s%s" % (indent, self.to_string()))
def unroll(self):
return ([self], [1.0])
@copy_documentation(Material.set_state)
def set_state(self, pressure, temperature):
Material.set_state(self, pressure, temperature)
self._property_modifiers = (
eos.property_modifiers.calculate_property_modifications(self)
)
if self.method is None:
raise AttributeError(
"no method set for mineral, or equation_of_state given in mineral.params"
)
"""
Properties from equations of state
We choose the P, T properties (e.g. Gibbs(P, T) rather than Helmholtz(V, T)),
as it allows us to more easily apply corrections to the free energy
"""
@material_property
@copy_documentation(Material.molar_gibbs)
def molar_gibbs(self):
return (
self.method.gibbs_free_energy(
self.pressure,
self.temperature,
self._molar_volume_unmodified,
self.params,
)
+ self._property_modifiers["G"]
)
@material_property
def _molar_volume_unmodified(self):
return self.method.volume(self.pressure, self.temperature, self.params)
@material_property
@copy_documentation(Material.molar_volume)
def molar_volume(self):
return self._molar_volume_unmodified + self._property_modifiers["dGdP"]
@material_property
@copy_documentation(Material.molar_entropy)
def molar_entropy(self):
return (
self.method.entropy(
self.pressure,
self.temperature,
self._molar_volume_unmodified,
self.params,
)
- self._property_modifiers["dGdT"]
)
@material_property
@copy_documentation(Material.isothermal_bulk_modulus)
def isothermal_bulk_modulus(self):
K_T_orig = self.method.isothermal_bulk_modulus(
self.pressure, self.temperature, self._molar_volume_unmodified, self.params
)
return self.molar_volume / (
(self._molar_volume_unmodified / K_T_orig)
- self._property_modifiers["d2GdP2"]
)
@material_property
@copy_documentation(Material.molar_heat_capacity_p)
def molar_heat_capacity_p(self):
return (
self.method.molar_heat_capacity_p(
self.pressure,
self.temperature,
self._molar_volume_unmodified,
self.params,
)
- self.temperature * self._property_modifiers["d2GdT2"]
)
@material_property
@copy_documentation(Material.thermal_expansivity)
def thermal_expansivity(self):
return (
(
self.method.thermal_expansivity(
self.pressure,
self.temperature,
self._molar_volume_unmodified,
self.params,
)
* self._molar_volume_unmodified
)
+ self._property_modifiers["d2GdPdT"]
) / self.molar_volume
@material_property
@copy_documentation(Material.shear_modulus)
def shear_modulus(self):
G = self.method.shear_modulus(
self.pressure, self.temperature, self._molar_volume_unmodified, self.params
)
if G < np.finfo("float").eps:
warnings.formatwarning = (
lambda msg, *a: "Warning from file '{0}', line {1}:\n{2}\n\n".format(
a[1], a[2], msg
)
)
warnings.warn(
"You are trying to calculate shear modulus for {0} when it is exactly zero. \n"
"If {0} is a liquid, then you can safely ignore this warning, but consider \n"
"calculating bulk modulus or bulk sound rather than Vp or Vs. \n"
"If {0} is not a liquid, then shear modulus calculations for the \n"
"underlying equation of state ({1}) have not been implemented, \n"
"and Vp and Vs estimates will be incorrect.".format(
self.name, self.method.__class__.__name__
),
stacklevel=1,
)
return G
"""
Properties from mineral parameters,
Legendre transformations
or Maxwell relations
"""
@material_property
def formula(self):
"""
Returns the chemical formula of the Mineral class
"""
if "formula" in self.params:
return self.params["formula"]
else:
raise ValueError(
"No formula parameter for mineral {0}.".format(self.to_string)
)
@material_property
@copy_documentation(Material.molar_mass)
def molar_mass(self):
if "molar_mass" in self.params:
return self.params["molar_mass"]
else:
raise ValueError(
"No molar_mass parameter for mineral {0}.".format(self.to_string)
)
@material_property
@copy_documentation(Material.density)
def density(self):
return self.molar_mass / self.molar_volume
@material_property
@copy_documentation(Material.molar_internal_energy)
def molar_internal_energy(self):
return (
self.molar_gibbs
- self.pressure * self.molar_volume
+ self.temperature * self.molar_entropy
)
@material_property
@copy_documentation(Material.molar_helmholtz)
def molar_helmholtz(self):
return self.molar_gibbs - self.pressure * self.molar_volume
@material_property
@copy_documentation(Material.molar_enthalpy)
def molar_enthalpy(self):
return self.molar_gibbs + self.temperature * self.molar_entropy
@material_property
@copy_documentation(Material.adiabatic_bulk_modulus)
def adiabatic_bulk_modulus(self):
if self.temperature < 1.0e-10:
return self.isothermal_bulk_modulus
else:
return (
self.isothermal_bulk_modulus
* self.molar_heat_capacity_p
/ self.molar_heat_capacity_v
)
@material_property
@copy_documentation(Material.isothermal_compressibility)
def isothermal_compressibility(self):
return 1.0 / self.isothermal_bulk_modulus
@material_property
@copy_documentation(Material.adiabatic_compressibility)
def adiabatic_compressibility(self):
return 1.0 / self.adiabatic_bulk_modulus
@material_property
@copy_documentation(Material.p_wave_velocity)
def p_wave_velocity(self):
return np.sqrt(
(self.adiabatic_bulk_modulus + 4.0 / 3.0 * self.shear_modulus)
/ self.density
)
@material_property
@copy_documentation(Material.bulk_sound_velocity)
def bulk_sound_velocity(self):
return np.sqrt(self.adiabatic_bulk_modulus / self.density)
@material_property
@copy_documentation(Material.shear_wave_velocity)
def shear_wave_velocity(self):
return np.sqrt(self.shear_modulus / self.density)
@material_property
@copy_documentation(Material.grueneisen_parameter)
def grueneisen_parameter(self):
eps = np.finfo("float").eps
if np.abs(self.molar_heat_capacity_v) > eps:
return (
self.thermal_expansivity
* self.isothermal_bulk_modulus
* self.molar_volume
/ self.molar_heat_capacity_v
)
elif (
(np.abs(self._property_modifiers["d2GdPdT"]) < eps)
and (np.abs(self._property_modifiers["d2GdP2"]) < eps)
and (np.abs(self._property_modifiers["dGdP"]) < eps)
and (np.abs(self._property_modifiers["d2GdT2"]) < eps)
):
return self.method.grueneisen_parameter(
self.pressure, self.temperature, self.molar_volume, self.params
)
else:
raise Exception(
"You are trying to calculate the grueneisen parameter at a temperature where the heat capacity is very low and where you have defined Gibbs property modifiers."
)
@material_property
@copy_documentation(Material.molar_heat_capacity_v)
def molar_heat_capacity_v(self):
return (
self.molar_heat_capacity_p
- self.molar_volume
* self.temperature
* self.thermal_expansivity
* self.thermal_expansivity
* self.isothermal_bulk_modulus
)
| (params=None, property_modifiers=None) |
11,048 | burnman.classes.mineral | __init__ | null | def __init__(self, params=None, property_modifiers=None):
Material.__init__(self)
if params is not None:
self.params = params
elif "params" not in self.__dict__:
self.params = {}
if property_modifiers is not None:
self.property_modifiers = property_modifiers
elif "property_modifiers" not in self.__dict__:
self.property_modifiers = []
self.method = None
if "equation_of_state" in self.params:
self.set_method(self.params["equation_of_state"])
if "name" in self.params:
self.name = self.params["name"]
| (self, params=None, property_modifiers=None) |
11,059 | burnman.classes.perplex | PerplexMaterial |
This is the base class for a PerpleX material. States of the material
can only be queried after setting the pressure and temperature
using set_state().
Instances of this class are initialised with
a 2D PerpleX tab file. This file should be in the standard format
(as output by werami), and should have columns with the following names:
'rho,kg/m3', 'alpha,1/K', 'beta,1/bar', 'Ks,bar', 'Gs,bar', 'v0,km/s',
'vp,km/s', 'vs,km/s', 's,J/K/kg', 'h,J/kg', 'cp,J/K/kg', 'V,J/bar/mol'.
The order of these names is not important.
Properties of the material are determined by linear interpolation from
the PerpleX grid. They are all returned in SI units on a molar basis,
even though the PerpleX tab file is not in these units.
This class is available as ``burnman.PerplexMaterial``.
| class PerplexMaterial(Material):
"""
This is the base class for a PerpleX material. States of the material
can only be queried after setting the pressure and temperature
using set_state().
Instances of this class are initialised with
a 2D PerpleX tab file. This file should be in the standard format
(as output by werami), and should have columns with the following names:
'rho,kg/m3', 'alpha,1/K', 'beta,1/bar', 'Ks,bar', 'Gs,bar', 'v0,km/s',
'vp,km/s', 'vs,km/s', 's,J/K/kg', 'h,J/kg', 'cp,J/K/kg', 'V,J/bar/mol'.
The order of these names is not important.
Properties of the material are determined by linear interpolation from
the PerpleX grid. They are all returned in SI units on a molar basis,
even though the PerpleX tab file is not in these units.
This class is available as ``burnman.PerplexMaterial``.
"""
def __init__(self, tab_file, name="Perple_X material"):
self.name = name
self.params = {"name": name}
(
self._property_interpolators,
self.params["molar_mass"],
self.bounds,
) = self._read_2D_perplex_file(tab_file)
Material.__init__(self)
def _read_2D_perplex_file(self, filename):
with open(filename, "r") as f:
datastream = f.read()
lines = [
line.strip().split() for line in datastream.split("\n") if line.strip()
]
if lines[2][0] != "2":
raise Exception("This is not a 2D PerpleX table")
bounds = [
(float(lines[4][0]), float(lines[5][0]), int(lines[6][0])),
(float(lines[8][0]), float(lines[9][0]), int(lines[10][0])),
]
if lines[3][0] == "P(bar)" and lines[7][0] == "T(K)":
Pmin, Pint, nP = bounds[0]
Tmin, Tint, nT = bounds[1]
elif lines[3][0] == "T(K)" and lines[7][0] == "P(bar)":
Pmin, Pint, nP = bounds[1]
Tmin, Tint, nT = bounds[0]
else:
raise Exception(
"This file does not have a recognised PerpleX structure.\n"
"Are the independent variables P(bar) and T(K)?"
)
Pmin = Pmin * 1.0e5 # bar to Pa
Pint = Pint * 1.0e5 # bar to Pa
Pmax = Pmin + Pint * (nP - 1.0)
Tmax = Tmin + Tint * (nT - 1.0)
pressures = np.linspace(Pmin, Pmax, nP)
temperatures = np.linspace(Tmin, Tmax, nT)
n_properties = int(lines[11][0])
property_list = lines[12]
# property_table[i][j][k] returns the kth property at the ith pressure and jth temperature
table = np.array(
[[float(string) for string in line] for line in lines[13 : 13 + nP * nT]]
)
if lines[3][0] == "P(bar)":
property_table = np.swapaxes(table.reshape(nT, nP, n_properties), 0, 1)
else:
property_table = table.reshape(nP, nT, n_properties)
ordered_property_list = [
"rho,kg/m3",
"alpha,1/K",
"beta,1/bar",
"Ks,bar",
"Gs,bar",
"v0,km/s",
"vp,km/s",
"vs,km/s",
"s,J/K/kg",
"h,J/kg",
"cp,J/K/kg",
"V,J/bar/mol",
]
p_indices = [
i
for i, p in enumerate(property_list)
for ordered_p in ordered_property_list
if p == ordered_p
]
properties = {}
for i, p_idx in enumerate(p_indices):
# Fill in NaNs as long as they aren't in the corners of the P-T grid
a = np.array(property_table[:, :, [p_idx]][:, :, 0])
x, y = np.indices(a.shape)
a[np.isnan(a)] = griddata(
(x[~np.isnan(a)], y[~np.isnan(a)]), # points we know
a[~np.isnan(a)], # values we know
(x[np.isnan(a)], y[np.isnan(a)]),
)
# Fill any remaining NaNs with zeros
properties[ordered_property_list[i]] = np.nan_to_num(a, 0.0)
densities = properties["rho,kg/m3"]
volumes = 1.0e-5 * properties["V,J/bar/mol"]
molar_masses = densities * volumes
molar_mass = np.mean(molar_masses)
property_interpolators = {
"rho": RegularGridInterpolator(
(pressures, temperatures), densities, bounds_error=True
),
"alpha": RegularGridInterpolator(
(pressures, temperatures), properties["alpha,1/K"], bounds_error=True
),
"K_T": RegularGridInterpolator(
(pressures, temperatures),
1.0e5 / properties["beta,1/bar"],
bounds_error=True,
),
"K_S": RegularGridInterpolator(
(pressures, temperatures),
1.0e5 * properties["Ks,bar"],
bounds_error=True,
),
"G_S": RegularGridInterpolator(
(pressures, temperatures),
1.0e5 * properties["Gs,bar"],
bounds_error=True,
),
"bulk_sound_velocity": RegularGridInterpolator(
(pressures, temperatures),
1.0e3 * properties["v0,km/s"],
bounds_error=True,
),
"p_wave_velocity": RegularGridInterpolator(
(pressures, temperatures),
1.0e3 * properties["vp,km/s"],
bounds_error=True,
),
"s_wave_velocity": RegularGridInterpolator(
(pressures, temperatures),
1.0e3 * properties["vs,km/s"],
bounds_error=True,
),
"S": RegularGridInterpolator(
(pressures, temperatures),
properties["s,J/K/kg"] * molar_masses,
bounds_error=True,
),
"H": RegularGridInterpolator(
(pressures, temperatures),
properties["h,J/kg"] * molar_masses,
bounds_error=True,
),
"C_p": RegularGridInterpolator(
(pressures, temperatures),
properties["cp,J/K/kg"] * molar_masses,
bounds_error=True,
),
"V": RegularGridInterpolator(
(pressures, temperatures), volumes, bounds_error=True
),
}
bounds = [[Pmin, Pmax], [Tmin, Tmax]]
return property_interpolators, molar_mass, bounds
@copy_documentation(Material.set_state)
def set_state(self, pressure, temperature):
if not np.logical_and(
np.all(self.bounds[0][0] <= pressure), np.all(pressure <= self.bounds[0][1])
):
raise ValueError(
"The set_state pressure ({0:.4f}) is outside the bounds of this rock ({1:.4f}-{2:.4f} GPa)".format(
pressure, self.bounds[0][0] / 1.0e9, self.bounds[0][1] / 1.0e9
)
)
if not np.logical_and(
np.all(self.bounds[1][0] <= temperature),
np.all(temperature <= self.bounds[1][1]),
):
raise ValueError(
"The set_state temperature ({0:.1f}) is outside the bounds of this rock ({1:.1f}-{2:.1f} K)".format(
temperature, self.bounds[1][0], self.bounds[1][1]
)
)
Material.set_state(self, pressure, temperature)
"""
Properties by linear interpolation of Perple_X output
"""
@material_property
@copy_documentation(Material.molar_volume)
def molar_volume(self):
return self._property_interpolators["V"]([self.pressure, self.temperature])[0]
@material_property
@copy_documentation(Material.molar_enthalpy)
def molar_enthalpy(self):
return self._property_interpolators["H"]([self.pressure, self.temperature])[0]
@material_property
@copy_documentation(Material.molar_entropy)
def molar_entropy(self):
return self._property_interpolators["S"]([self.pressure, self.temperature])[0]
@material_property
@copy_documentation(Material.isothermal_bulk_modulus)
def isothermal_bulk_modulus(self):
return self._property_interpolators["K_T"]([self.pressure, self.temperature])[0]
@material_property
@copy_documentation(Material.adiabatic_bulk_modulus)
def adiabatic_bulk_modulus(self):
return self._property_interpolators["K_S"]([self.pressure, self.temperature])[0]
@material_property
@copy_documentation(Material.molar_heat_capacity_p)
def molar_heat_capacity_p(self):
return self._property_interpolators["C_p"]([self.pressure, self.temperature])[0]
@material_property
@copy_documentation(Material.thermal_expansivity)
def thermal_expansivity(self):
return self._property_interpolators["alpha"]([self.pressure, self.temperature])[
0
]
@material_property
@copy_documentation(Material.shear_modulus)
def shear_modulus(self):
return self._property_interpolators["G_S"]([self.pressure, self.temperature])[0]
@material_property
@copy_documentation(Material.p_wave_velocity)
def p_wave_velocity(self):
return self._property_interpolators["p_wave_velocity"](
[self.pressure, self.temperature]
)[0]
@material_property
@copy_documentation(Material.bulk_sound_velocity)
def bulk_sound_velocity(self):
return self._property_interpolators["bulk_sound_velocity"](
[self.pressure, self.temperature]
)[0]
@material_property
@copy_documentation(Material.shear_wave_velocity)
def shear_wave_velocity(self):
return self._property_interpolators["s_wave_velocity"](
[self.pressure, self.temperature]
)[0]
"""
Properties from mineral parameters,
Legendre transformations
or Maxwell relations
"""
@material_property
@copy_documentation(Material.molar_gibbs)
def molar_gibbs(self):
return self.molar_enthalpy - self.temperature * self.molar_entropy
@material_property
@copy_documentation(Material.molar_mass)
def molar_mass(self):
if "molar_mass" in self.params:
return self.params["molar_mass"]
else:
raise ValueError(
"No molar_mass parameter for mineral " + self.to_string + "."
)
@material_property
@copy_documentation(Material.density)
def density(self):
return self._property_interpolators["rho"]([self.pressure, self.temperature])[0]
@material_property
@copy_documentation(Material.molar_internal_energy)
def molar_internal_energy(self):
return (
self.molar_gibbs
- self.pressure * self.molar_volume
+ self.temperature * self.molar_entropy
)
@material_property
@copy_documentation(Material.molar_helmholtz)
def molar_helmholtz(self):
return self.molar_gibbs - self.pressure * self.molar_volume
@material_property
@copy_documentation(Material.isothermal_compressibility)
def isothermal_compressibility(self):
return 1.0 / self.isothermal_bulk_modulus
@material_property
@copy_documentation(Material.adiabatic_compressibility)
def adiabatic_compressibility(self):
return 1.0 / self.adiabatic_bulk_modulus
@material_property
@copy_documentation(Material.molar_heat_capacity_v)
def molar_heat_capacity_v(self):
return (
self.molar_heat_capacity_p
- self.molar_volume
* self.temperature
* self.thermal_expansivity
* self.thermal_expansivity
* self.isothermal_bulk_modulus
)
@material_property
@copy_documentation(Material.grueneisen_parameter)
def grueneisen_parameter(self):
return (
self.thermal_expansivity
* self.molar_volume
* self.adiabatic_bulk_modulus
/ self.molar_heat_capacity_p
)
| (tab_file, name='Perple_X material') |
11,060 | burnman.classes.perplex | __init__ | null | def __init__(self, tab_file, name="Perple_X material"):
self.name = name
self.params = {"name": name}
(
self._property_interpolators,
self.params["molar_mass"],
self.bounds,
) = self._read_2D_perplex_file(tab_file)
Material.__init__(self)
| (self, tab_file, name='Perple_X material') |
11,061 | burnman.classes.perplex | _read_2D_perplex_file | null | def _read_2D_perplex_file(self, filename):
with open(filename, "r") as f:
datastream = f.read()
lines = [
line.strip().split() for line in datastream.split("\n") if line.strip()
]
if lines[2][0] != "2":
raise Exception("This is not a 2D PerpleX table")
bounds = [
(float(lines[4][0]), float(lines[5][0]), int(lines[6][0])),
(float(lines[8][0]), float(lines[9][0]), int(lines[10][0])),
]
if lines[3][0] == "P(bar)" and lines[7][0] == "T(K)":
Pmin, Pint, nP = bounds[0]
Tmin, Tint, nT = bounds[1]
elif lines[3][0] == "T(K)" and lines[7][0] == "P(bar)":
Pmin, Pint, nP = bounds[1]
Tmin, Tint, nT = bounds[0]
else:
raise Exception(
"This file does not have a recognised PerpleX structure.\n"
"Are the independent variables P(bar) and T(K)?"
)
Pmin = Pmin * 1.0e5 # bar to Pa
Pint = Pint * 1.0e5 # bar to Pa
Pmax = Pmin + Pint * (nP - 1.0)
Tmax = Tmin + Tint * (nT - 1.0)
pressures = np.linspace(Pmin, Pmax, nP)
temperatures = np.linspace(Tmin, Tmax, nT)
n_properties = int(lines[11][0])
property_list = lines[12]
# property_table[i][j][k] returns the kth property at the ith pressure and jth temperature
table = np.array(
[[float(string) for string in line] for line in lines[13 : 13 + nP * nT]]
)
if lines[3][0] == "P(bar)":
property_table = np.swapaxes(table.reshape(nT, nP, n_properties), 0, 1)
else:
property_table = table.reshape(nP, nT, n_properties)
ordered_property_list = [
"rho,kg/m3",
"alpha,1/K",
"beta,1/bar",
"Ks,bar",
"Gs,bar",
"v0,km/s",
"vp,km/s",
"vs,km/s",
"s,J/K/kg",
"h,J/kg",
"cp,J/K/kg",
"V,J/bar/mol",
]
p_indices = [
i
for i, p in enumerate(property_list)
for ordered_p in ordered_property_list
if p == ordered_p
]
properties = {}
for i, p_idx in enumerate(p_indices):
# Fill in NaNs as long as they aren't in the corners of the P-T grid
a = np.array(property_table[:, :, [p_idx]][:, :, 0])
x, y = np.indices(a.shape)
a[np.isnan(a)] = griddata(
(x[~np.isnan(a)], y[~np.isnan(a)]), # points we know
a[~np.isnan(a)], # values we know
(x[np.isnan(a)], y[np.isnan(a)]),
)
# Fill any remaining NaNs with zeros
properties[ordered_property_list[i]] = np.nan_to_num(a, 0.0)
densities = properties["rho,kg/m3"]
volumes = 1.0e-5 * properties["V,J/bar/mol"]
molar_masses = densities * volumes
molar_mass = np.mean(molar_masses)
property_interpolators = {
"rho": RegularGridInterpolator(
(pressures, temperatures), densities, bounds_error=True
),
"alpha": RegularGridInterpolator(
(pressures, temperatures), properties["alpha,1/K"], bounds_error=True
),
"K_T": RegularGridInterpolator(
(pressures, temperatures),
1.0e5 / properties["beta,1/bar"],
bounds_error=True,
),
"K_S": RegularGridInterpolator(
(pressures, temperatures),
1.0e5 * properties["Ks,bar"],
bounds_error=True,
),
"G_S": RegularGridInterpolator(
(pressures, temperatures),
1.0e5 * properties["Gs,bar"],
bounds_error=True,
),
"bulk_sound_velocity": RegularGridInterpolator(
(pressures, temperatures),
1.0e3 * properties["v0,km/s"],
bounds_error=True,
),
"p_wave_velocity": RegularGridInterpolator(
(pressures, temperatures),
1.0e3 * properties["vp,km/s"],
bounds_error=True,
),
"s_wave_velocity": RegularGridInterpolator(
(pressures, temperatures),
1.0e3 * properties["vs,km/s"],
bounds_error=True,
),
"S": RegularGridInterpolator(
(pressures, temperatures),
properties["s,J/K/kg"] * molar_masses,
bounds_error=True,
),
"H": RegularGridInterpolator(
(pressures, temperatures),
properties["h,J/kg"] * molar_masses,
bounds_error=True,
),
"C_p": RegularGridInterpolator(
(pressures, temperatures),
properties["cp,J/K/kg"] * molar_masses,
bounds_error=True,
),
"V": RegularGridInterpolator(
(pressures, temperatures), volumes, bounds_error=True
),
}
bounds = [[Pmin, Pmax], [Tmin, Tmax]]
return property_interpolators, molar_mass, bounds
| (self, filename) |
11,072 | burnman.classes.planet | Planet |
A class to build (self-consistent) Planets made out of Layers
(:class:`burnman.Layer`). By default the planet is set to be self-consistent
(with zero pressure at the surface and zero gravity at the center),
but this can be overwritte using the set_pressure_mode().
Pressure_modes defined in the individual layers will be ignored.
If temperature modes are already set for each of the layers, when the
planet is initialized, the planet will be built immediately.
| class Planet(object):
"""
A class to build (self-consistent) Planets made out of Layers
(:class:`burnman.Layer`). By default the planet is set to be self-consistent
(with zero pressure at the surface and zero gravity at the center),
but this can be overwritte using the set_pressure_mode().
Pressure_modes defined in the individual layers will be ignored.
If temperature modes are already set for each of the layers, when the
planet is initialized, the planet will be built immediately.
"""
def __init__(
self, name, layers, n_max_iterations=50, max_delta=1.0e-5, verbose=False
):
"""
:param name: Name of planet.
:type name: str
:param layers: Layers to build the planet out of
(layers are sorted within the planet).
:type layers: list of :class:`burnman.Layer`
:param n_max_iterations: Maximum number of iterations to reach
self-consistent planet.
:type n_max_iterations: int
:param max_delta: Relative update to the center pressure of the planet between
iterations to stop iterations.
:type max_delta: float
"""
# sort layers
self.layers = sorted(layers, key=lambda x: x.inner_radius)
# assert layers attach to one another
if len(self.layers) > 1:
for i in range(1, len(self.layers)):
assert self.layers[i].inner_radius == self.layers[i - 1].outer_radius
self.name = name
self.radii = self.evaluate(["radii"])
self.n_slices = len(self.radii)
self.radius_planet = max(self.radii)
self.volume = 4.0 / 3.0 * np.pi * np.power(self.radius_planet, 3.0)
for layer in self.layers:
layer.n_start = np.where(self.radii == layer.inner_radius)[0][-1]
layer.n_end = np.where(self.radii == layer.outer_radius)[0][0] + 1
self._cached = {}
self.verbose = verbose
self.set_pressure_mode(n_max_iterations=n_max_iterations, max_delta=max_delta)
def __iter__(self):
"""
Planet object will iterate over Layers.
"""
return list(self.layers).__iter__()
def __str__(self):
"""
Prints details of the planet
"""
writing = "{0} consists of {1} layers:\n".format(self.name, len(self.layers))
for layer in self:
writing = writing + layer.__str__()
return writing
def reset(self):
"""
Resets all cached material properties.
It is typically not required for the user to call this function.
"""
self._cached = {}
def get_layer(self, name):
"""
Returns a layer with a given name
:param name: Given name of a layer
:type name: str
:returns: Layer with the given name.
:rtype: :class:`burnman.Layer`
"""
for layer in self.layers:
if layer.name == name:
return layer
raise LookupError()
def get_layer_by_radius(self, radius):
"""
Returns a layer in which this radius lies
:param radius: Radius at which to evaluate the layer.
:type radius: float
:returns: Layer in which the radius lies.
:rtype: :class:`burnman.Layer`
"""
for layer in self.layers:
if layer.outer_radius >= radius:
return layer
raise LookupError()
def evaluate(self, properties, radlist=None):
"""
Function that is generally used to evaluate properties
of the different layers and stitch them together.
If asking for different radii than the internal radlist,
pressure and temperature values are interpolated and the
layer material evaluated at those pressures and
temperatures.
:param properties: List of properties to evaluate
:type properties: list of strings
:param radlist: Radii to evaluate properties at. If left empty,
internal radius lists are used.
:type radlist: array of floats
:returns: 1D or 2D array of requested properties
(1D if only one property was requested)
:rtype: numpy.array
"""
if radlist is None:
values = np.empty(
[len(properties), np.sum([len(layer.radii) for layer in self.layers])]
)
for i, prop in enumerate(properties):
if prop == "depth":
values[i] = np.array(
[
self.radius_planet - r
for layer in self.layers
for r in layer.radii
]
)
else:
j = 0
for layer in self.layers:
vals = getattr(layer, prop)
values[i, j : j + len(vals)] = vals
j += len(vals)
else:
values = np.empty([len(properties), len(radlist)])
l_idx = [
i
for i, layer in enumerate(self.layers)
for r in radlist
if r >= layer.inner_radius and r <= layer.outer_radius
]
for j, r in enumerate(radlist):
values[:, j] = (
self.layers[l_idx[j]]
.evaluate(properties, [r], self.radius_planet)
.T[0]
)
if values.shape[0] == 1:
values = values[0]
return values
def set_pressure_mode(
self,
pressure_mode="self-consistent",
pressures=None,
pressure_top=0.0,
gravity_bottom=0.0,
n_max_iterations=50,
max_delta=1.0e-5,
):
"""
Sets the pressure mode of the planet by user-defined values are in a
self-consistent fashion.
pressure_mode is 'user-defined' or 'self-consistent'.
The default for the planet is self-consistent, with zero pressure at
the surface and zero pressure at the center.
:param pressure_mode: This can be set to 'user-defined' or 'self-consistent'.
:type pressure_mode: str
:param pressures: Pressures (Pa) to set layer to ('user-defined').
This should be the same length as defined radius array for the layer.
:type pressures: array of floats
:param pressure_top: Pressure (Pa) at the top of the layer.
:type pressure_top: float
:param gravity_bottom: Gravity (m/s^2) at the bottom the layer
:type gravity_bottom: float
:param n_max_iterations: Maximum number of iterations to reach
self-consistent pressures.
:type n_max_iterations: int
"""
self.reset()
assert pressure_mode == "user-defined" or pressure_mode == "self-consistent"
self.pressure_mode = pressure_mode
self.gravity_bottom = gravity_bottom
if pressure_mode == "user-defined":
assert len(pressures) == len(self.radii)
self._pressures = pressures
warnings.warn(
"User-defined pressures mean that the planet is "
"unlikely to be self-consistent"
)
if pressure_mode == "self-consistent":
self.pressure_top = pressure_top
self.n_max_iterations = n_max_iterations
self.max_delta = max_delta
def make(self):
"""
This routine needs to be called before evaluating any properties.
If pressures and temperatures are self-consistent, they
are computed across the planet here. Also initializes an array of materials
in each Layer to compute properties from.
"""
self.reset()
for layer in self.layers:
assert layer.temperature_mode is not None
if self.pressure_mode == "user-defined":
self._temperatures = self._evaluate_temperature(self._pressures)
if self.pressure_mode == "self-consistent":
new_press = (
self.pressure_top + (-self.radii + max(self.radii)) * 1.0e3
) # initial pressure curve guess
temperatures = self._evaluate_temperature(new_press)
# Make it self-consistent!!!
i = 0
while i < self.n_max_iterations:
i += 1
ref_press = new_press
new_grav, new_press = self._evaluate_eos(
new_press, temperatures, self.gravity_bottom, self.pressure_top
)
temperatures = self._evaluate_temperature(new_press)
rel_err = abs((max(ref_press) - max(new_press)) / max(new_press))
if self.verbose:
print(
f"Iteration {i:0d} maximum relative pressure error: "
f"{rel_err:.1e}"
)
if rel_err < self.max_delta:
break
self.pressures = new_press
self.temperatures = temperatures
self._gravity = new_grav
for layer in self.layers:
layer.sublayers = []
layer.pressures = self.pressures[layer.n_start : layer.n_end]
layer.temperatures = self.temperatures[layer.n_start : layer.n_end]
layer.gravity_bottom = self._gravity[layer.n_start - 1]
layer.pressure_mode = "set-in-planet"
for i in range(len(layer.radii)):
layer.sublayers.append(layer.material.copy())
layer.sublayers[i].set_state(layer.pressures[i], layer.temperatures[i])
def _evaluate_eos(self, pressures, temperatures, gravity_bottom, pressure_top):
"""
Used to update the pressure profile in set_state()
"""
density = self._evaluate_density(pressures, temperatures)
grav = self._compute_gravity(density, gravity_bottom)
press = self._compute_pressure(density, grav, pressure_top)
return grav, press
def _evaluate_density(self, pressures, temperatures):
"""
Used to update the density profile in _evaluate_eos()
"""
density = []
for layer in self.layers:
density.append(
layer.material.evaluate(
["density"],
pressures[layer.n_start : layer.n_end],
temperatures[layer.n_start : layer.n_end],
)
)
return np.squeeze(np.hstack(density))
def _evaluate_temperature(self, pressures):
"""
Returns the temperatures of different layers for given pressures.
Used by set_state()
"""
temps = []
temperature_top = None
for layer in self.layers[::-1]:
if temperature_top is None or layer.temperature_top is not None:
temperature_top = layer.temperature_top
temps.extend(
layer._evaluate_temperature(
(pressures[layer.n_start : layer.n_end]), temperature_top
)[::-1]
)
temperature_top = temps[-1]
return np.hstack(np.squeeze(temps))[::-1]
def _compute_gravity(self, density, gravity_bottom):
"""
Calculate the gravity of the planet, based on a density profile.
This integrates Poisson's equation in radius, under the assumption
that the planet is laterally homogeneous.
Used to update the gravity profile in _evaluate_eos()
"""
start_gravity = gravity_bottom
grav = []
for layer in self.layers:
grav.extend(
layer._compute_gravity(
density[layer.n_start : layer.n_end], start_gravity
)
)
start_gravity = grav[-1]
return np.array(grav)
def _compute_pressure(self, density, gravity, pressure_top):
"""
Calculate the pressure profile based on density and gravity.
This integrates the equation for hydrostatic equilibrium P = rho g z.
Used to update the pressure profile in _evaluate_eos()
"""
start_pressure = pressure_top
press = []
for layer in self.layers[::-1]:
press.extend(
layer._compute_pressure(
density[layer.n_start : layer.n_end],
gravity[layer.n_start : layer.n_end],
start_pressure,
)[::-1]
)
start_pressure = press[-1]
return np.array(press)[::-1]
@property
def mass(self):
"""
calculates the mass of the entire planet [kg]
"""
return np.sum([layer.mass for layer in self.layers])
@property
def average_density(self):
"""
calculates the average density of the entire planet [kg/m^3]
"""
return self.mass / self.volume
@property
def moment_of_inertia(self):
"""
#Returns the moment of inertia of the planet [kg m^2]
"""
return np.sum([layer.moment_of_inertia for layer in self.layers])
@property
def moment_of_inertia_factor(self):
"""
#Returns the moment of inertia of the planet [kg m^2]
"""
moment_factor = (
self.moment_of_inertia / self.mass / self.radius_planet / self.radius_planet
)
return moment_factor
@property
def depth(self):
"""
Returns depth of the layer [m]
"""
return self.evaluate(["depth"])
@property
def gravity(self):
"""
Returns gravity of the layer [m s^(-2)]
"""
return self.evaluate(["gravity"])
@property
def bullen(self):
"""
Returns the Bullen parameter
"""
return self.evaluate(["bullen"])
@property
def brunt_vasala(self):
return self.evaluate(["brunt_vasala"])
@property
def pressure(self):
"""
Returns current pressure that was set with
:func:`~burnman.Material.set_state`.
Aliased with :func:`~burnman.Material.P`.
:returns: Pressure in [Pa].
:rtype: array of floats
"""
return self.pressures
@property
def temperature(self):
"""
Returns current temperature that was set with
:func:`~burnman.Material.set_state`.
Aliased with :func:`~burnman.Material.T`.
:returns: Temperature in [K].
:rtype: array of floats
"""
return self.temperatures
@material_property
def molar_internal_energy(self):
"""
Returns the molar internal energy of the planet.
Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.energy`.
:returns: The internal energy in [J/mol].
:rtype: array of floats
"""
return self.evaluate(["molar_internal_energy"])
@material_property
def molar_gibbs(self):
"""
Returns the molar Gibbs free energy of the planet.
Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.gibbs`.
:returns: Gibbs energy in [J/mol].
:rtype: array of floats
"""
return self.evaluate(["molar_gibbs"])
@material_property
def molar_helmholtz(self):
"""
Returns the molar Helmholtz free energy of the planet.
Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.helmholtz`.
:returns: Helmholtz energy in [J/mol].
:rtype: array of floats
"""
return self.evaluate(["molar_helmholtz"])
@material_property
def molar_mass(self):
"""
Returns molar mass of the planet.
Needs to be implemented in derived classes.
:returns: Molar mass in [kg/mol].
:rtype: array of floats
"""
return self.evaluate(["molar_mass"])
@material_property
def molar_volume(self):
"""
Returns molar volume of the planet.
Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.V`.
:returns: Molar volume in [m^3/mol].
:rtype: array of floats
"""
return self.evaluate(["molar_volume"])
@material_property
def density(self):
"""
Returns the density of this planet.
Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.rho`.
:returns: The density of this material in [kg/m^3].
:rtype: array of floats
"""
return self.evaluate(["density"])
@material_property
def molar_entropy(self):
"""
Returns molar entropy of the planet.
Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.S`.
:returns: Entropy in [J/K/mol].
:rtype: array of floats
"""
return self.evaluate(["molar_entropy"])
@material_property
def molar_enthalpy(self):
"""
Returns molar enthalpy of the planet.
Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.H`.
:returns: Enthalpy in [J/mol].
:rtype: array of floats
"""
return self.evaluate(["molar_enthalpy"])
@material_property
def isothermal_bulk_modulus(self):
"""
Returns isothermal bulk modulus of the planet.
Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.K_T`.
:returns: Isothermal bulk modulus in [Pa].
:rtype: array of floats
"""
return self.evaluate(["isothermal_bulk_modulus"])
@material_property
def adiabatic_bulk_modulus(self):
"""
Returns the adiabatic bulk modulus of the planet.
Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.K_S`.
:returns: Adiabatic bulk modulus in [Pa].
:rtype: array of floats
"""
return self.evaluate(["adiabatic_bulk_modulus"])
@material_property
def isothermal_compressibility(self):
"""
Returns isothermal compressibility of the planet
(or inverse isothermal bulk modulus).
Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.beta_T`.
:returns: Isothermal compressibility in [1/Pa].
:rtype: array of floats
"""
return self.evaluate(["istothermal_compressibility"])
@material_property
def adiabatic_compressibility(self):
"""
Returns adiabatic compressibility of the planet
(or inverse adiabatic bulk modulus).
Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.beta_S`.
:returns: Adiabatic compressibility in [1/Pa].
:rtype: array of floats
"""
return self.evaluate(["adiabatic_compressibility"])
@material_property
def shear_modulus(self):
"""
Returns shear modulus of the planet.
Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.beta_G`.
:returns: Shear modulus in [Pa].
:rtype: array of floats
"""
return self.evaluate(["shear_modulus"])
@material_property
def p_wave_velocity(self):
"""
Returns P wave speed of the planet.
Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.v_p`.
:returns: P wave speed in [m/s].
:rtype: array of floats
"""
return self.evaluate(["p_wave_velocity"])
@material_property
def bulk_sound_velocity(self):
"""
Returns bulk sound speed of the planet.
Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.v_phi`.
:returns: Bulk sound velocity in [m/s].
:rtype: array of floats
"""
return self.evaluate(["bulk_sound_velocity"])
@material_property
def shear_wave_velocity(self):
"""
Returns shear wave speed of the planet.
Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.v_s`.
:returns: Shear wave speed in [m/s].
:rtype: array of floats
"""
return self.evaluate(["shear_wave_velocity"])
@material_property
def grueneisen_parameter(self):
"""
Returns the grueneisen parameter of the planet.
Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.gr`.
:returns: Grueneisen parameters [unitless].
:rtype: array of floats
"""
return self.evaluate(["grueneisen_parameter"])
@material_property
def thermal_expansivity(self):
"""
Returns thermal expansion coefficient of the planet.
Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.alpha`.
:returns: Thermal expansivity in [1/K].
:rtype: array of floats
"""
return self.evaluate(["thermal_expansivity"])
@material_property
def molar_heat_capacity_v(self):
"""
Returns molar heat capacity at constant volume of the planet.
Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.C_v`.
:returns: Isochoric heat capacity in [J/K/mol].
:rtype: array of floats
"""
return self.evaluate(["molar_heat_capacity_v"])
@material_property
def molar_heat_capacity_p(self):
"""
Returns molar heat capacity at constant pressure of the planet.
Needs to be implemented in derived classes.
Aliased with :func:`~burnman.Material.C_p`.
:returns: Isobaric heat capacity in [J/K/mol].
:rtype: array of floats
"""
return self.evaluate(["molar_heat_capacity_p"])
#
# Aliased properties
@property
def P(self):
"""Alias for :func:`~burnman.Material.pressure`"""
return self.pressure
@property
def T(self):
"""Alias for :func:`~burnman.Material.temperature`"""
return self.temperature
@property
def energy(self):
"""Alias for :func:`~burnman.Material.molar_internal_energy`"""
return self.molar_internal_energy
@property
def helmholtz(self):
"""Alias for :func:`~burnman.Material.molar_helmholtz`"""
return self.molar_helmholtz
@property
def gibbs(self):
"""Alias for :func:`~burnman.Material.molar_gibbs`"""
return self.molar_gibbs
@property
def V(self):
"""Alias for :func:`~burnman.Material.molar_volume`"""
return self.molar_volume
@property
def rho(self):
"""Alias for :func:`~burnman.Material.density`"""
return self.density
@property
def S(self):
"""Alias for :func:`~burnman.Material.molar_entropy`"""
return self.molar_entropy
@property
def H(self):
"""Alias for :func:`~burnman.Material.molar_enthalpy`"""
return self.molar_enthalpy
@property
def K_T(self):
"""Alias for :func:`~burnman.Material.isothermal_bulk_modulus`"""
return self.isothermal_bulk_modulus
@property
def K_S(self):
"""Alias for :func:`~burnman.Material.adiabatic_bulk_modulus`"""
return self.adiabatic_bulk_modulus
@property
def beta_T(self):
"""Alias for :func:`~burnman.Material.isothermal_compressibility`"""
return self.isothermal_compressibility
@property
def beta_S(self):
"""Alias for :func:`~burnman.Material.adiabatic_compressibility`"""
return self.adiabatic_compressibility
@property
def G(self):
"""Alias for :func:`~burnman.Material.shear_modulus`"""
return self.shear_modulus
@property
def v_p(self):
"""Alias for :func:`~burnman.Material.p_wave_velocity`"""
return self.p_wave_velocity
@property
def v_phi(self):
"""Alias for :func:`~burnman.Material.bulk_sound_velocity`"""
return self.bulk_sound_velocity
@property
def v_s(self):
"""Alias for :func:`~burnman.Material.shear_wave_velocity`"""
return self.shear_wave_velocity
@property
def gr(self):
"""Alias for :func:`~burnman.Material.grueneisen_parameter`"""
return self.grueneisen_parameter
@property
def alpha(self):
"""Alias for :func:`~burnman.Material.thermal_expansivity`"""
return self.thermal_expansivity
@property
def C_v(self):
"""Alias for :func:`~burnman.Material.molar_heat_capacity_v`"""
return self.molar_heat_capacity_v
@property
def C_p(self):
"""Alias for :func:`~burnman.Material.molar_heat_capacity_p`"""
return self.molar_heat_capacity_p
| (name, layers, n_max_iterations=50, max_delta=1e-05, verbose=False) |
11,073 | burnman.classes.planet | __init__ |
:param name: Name of planet.
:type name: str
:param layers: Layers to build the planet out of
(layers are sorted within the planet).
:type layers: list of :class:`burnman.Layer`
:param n_max_iterations: Maximum number of iterations to reach
self-consistent planet.
:type n_max_iterations: int
:param max_delta: Relative update to the center pressure of the planet between
iterations to stop iterations.
:type max_delta: float
| def __init__(
self, name, layers, n_max_iterations=50, max_delta=1.0e-5, verbose=False
):
"""
:param name: Name of planet.
:type name: str
:param layers: Layers to build the planet out of
(layers are sorted within the planet).
:type layers: list of :class:`burnman.Layer`
:param n_max_iterations: Maximum number of iterations to reach
self-consistent planet.
:type n_max_iterations: int
:param max_delta: Relative update to the center pressure of the planet between
iterations to stop iterations.
:type max_delta: float
"""
# sort layers
self.layers = sorted(layers, key=lambda x: x.inner_radius)
# assert layers attach to one another
if len(self.layers) > 1:
for i in range(1, len(self.layers)):
assert self.layers[i].inner_radius == self.layers[i - 1].outer_radius
self.name = name
self.radii = self.evaluate(["radii"])
self.n_slices = len(self.radii)
self.radius_planet = max(self.radii)
self.volume = 4.0 / 3.0 * np.pi * np.power(self.radius_planet, 3.0)
for layer in self.layers:
layer.n_start = np.where(self.radii == layer.inner_radius)[0][-1]
layer.n_end = np.where(self.radii == layer.outer_radius)[0][0] + 1
self._cached = {}
self.verbose = verbose
self.set_pressure_mode(n_max_iterations=n_max_iterations, max_delta=max_delta)
| (self, name, layers, n_max_iterations=50, max_delta=1e-05, verbose=False) |
11,074 | burnman.classes.planet | __iter__ |
Planet object will iterate over Layers.
| def __iter__(self):
"""
Planet object will iterate over Layers.
"""
return list(self.layers).__iter__()
| (self) |
11,075 | burnman.classes.planet | __str__ |
Prints details of the planet
| def __str__(self):
"""
Prints details of the planet
"""
writing = "{0} consists of {1} layers:\n".format(self.name, len(self.layers))
for layer in self:
writing = writing + layer.__str__()
return writing
| (self) |
11,076 | burnman.classes.planet | _compute_gravity |
Calculate the gravity of the planet, based on a density profile.
This integrates Poisson's equation in radius, under the assumption
that the planet is laterally homogeneous.
Used to update the gravity profile in _evaluate_eos()
| def _compute_gravity(self, density, gravity_bottom):
"""
Calculate the gravity of the planet, based on a density profile.
This integrates Poisson's equation in radius, under the assumption
that the planet is laterally homogeneous.
Used to update the gravity profile in _evaluate_eos()
"""
start_gravity = gravity_bottom
grav = []
for layer in self.layers:
grav.extend(
layer._compute_gravity(
density[layer.n_start : layer.n_end], start_gravity
)
)
start_gravity = grav[-1]
return np.array(grav)
| (self, density, gravity_bottom) |
11,077 | burnman.classes.planet | _compute_pressure |
Calculate the pressure profile based on density and gravity.
This integrates the equation for hydrostatic equilibrium P = rho g z.
Used to update the pressure profile in _evaluate_eos()
| def _compute_pressure(self, density, gravity, pressure_top):
"""
Calculate the pressure profile based on density and gravity.
This integrates the equation for hydrostatic equilibrium P = rho g z.
Used to update the pressure profile in _evaluate_eos()
"""
start_pressure = pressure_top
press = []
for layer in self.layers[::-1]:
press.extend(
layer._compute_pressure(
density[layer.n_start : layer.n_end],
gravity[layer.n_start : layer.n_end],
start_pressure,
)[::-1]
)
start_pressure = press[-1]
return np.array(press)[::-1]
| (self, density, gravity, pressure_top) |
11,078 | burnman.classes.planet | _evaluate_density |
Used to update the density profile in _evaluate_eos()
| def _evaluate_density(self, pressures, temperatures):
"""
Used to update the density profile in _evaluate_eos()
"""
density = []
for layer in self.layers:
density.append(
layer.material.evaluate(
["density"],
pressures[layer.n_start : layer.n_end],
temperatures[layer.n_start : layer.n_end],
)
)
return np.squeeze(np.hstack(density))
| (self, pressures, temperatures) |
11,079 | burnman.classes.planet | _evaluate_eos |
Used to update the pressure profile in set_state()
| def _evaluate_eos(self, pressures, temperatures, gravity_bottom, pressure_top):
"""
Used to update the pressure profile in set_state()
"""
density = self._evaluate_density(pressures, temperatures)
grav = self._compute_gravity(density, gravity_bottom)
press = self._compute_pressure(density, grav, pressure_top)
return grav, press
| (self, pressures, temperatures, gravity_bottom, pressure_top) |
11,080 | burnman.classes.planet | _evaluate_temperature |
Returns the temperatures of different layers for given pressures.
Used by set_state()
| def _evaluate_temperature(self, pressures):
"""
Returns the temperatures of different layers for given pressures.
Used by set_state()
"""
temps = []
temperature_top = None
for layer in self.layers[::-1]:
if temperature_top is None or layer.temperature_top is not None:
temperature_top = layer.temperature_top
temps.extend(
layer._evaluate_temperature(
(pressures[layer.n_start : layer.n_end]), temperature_top
)[::-1]
)
temperature_top = temps[-1]
return np.hstack(np.squeeze(temps))[::-1]
| (self, pressures) |
11,081 | burnman.classes.planet | evaluate |
Function that is generally used to evaluate properties
of the different layers and stitch them together.
If asking for different radii than the internal radlist,
pressure and temperature values are interpolated and the
layer material evaluated at those pressures and
temperatures.
:param properties: List of properties to evaluate
:type properties: list of strings
:param radlist: Radii to evaluate properties at. If left empty,
internal radius lists are used.
:type radlist: array of floats
:returns: 1D or 2D array of requested properties
(1D if only one property was requested)
:rtype: numpy.array
| def evaluate(self, properties, radlist=None):
"""
Function that is generally used to evaluate properties
of the different layers and stitch them together.
If asking for different radii than the internal radlist,
pressure and temperature values are interpolated and the
layer material evaluated at those pressures and
temperatures.
:param properties: List of properties to evaluate
:type properties: list of strings
:param radlist: Radii to evaluate properties at. If left empty,
internal radius lists are used.
:type radlist: array of floats
:returns: 1D or 2D array of requested properties
(1D if only one property was requested)
:rtype: numpy.array
"""
if radlist is None:
values = np.empty(
[len(properties), np.sum([len(layer.radii) for layer in self.layers])]
)
for i, prop in enumerate(properties):
if prop == "depth":
values[i] = np.array(
[
self.radius_planet - r
for layer in self.layers
for r in layer.radii
]
)
else:
j = 0
for layer in self.layers:
vals = getattr(layer, prop)
values[i, j : j + len(vals)] = vals
j += len(vals)
else:
values = np.empty([len(properties), len(radlist)])
l_idx = [
i
for i, layer in enumerate(self.layers)
for r in radlist
if r >= layer.inner_radius and r <= layer.outer_radius
]
for j, r in enumerate(radlist):
values[:, j] = (
self.layers[l_idx[j]]
.evaluate(properties, [r], self.radius_planet)
.T[0]
)
if values.shape[0] == 1:
values = values[0]
return values
| (self, properties, radlist=None) |
11,082 | burnman.classes.planet | get_layer |
Returns a layer with a given name
:param name: Given name of a layer
:type name: str
:returns: Layer with the given name.
:rtype: :class:`burnman.Layer`
| def get_layer(self, name):
"""
Returns a layer with a given name
:param name: Given name of a layer
:type name: str
:returns: Layer with the given name.
:rtype: :class:`burnman.Layer`
"""
for layer in self.layers:
if layer.name == name:
return layer
raise LookupError()
| (self, name) |
11,083 | burnman.classes.planet | get_layer_by_radius |
Returns a layer in which this radius lies
:param radius: Radius at which to evaluate the layer.
:type radius: float
:returns: Layer in which the radius lies.
:rtype: :class:`burnman.Layer`
| def get_layer_by_radius(self, radius):
"""
Returns a layer in which this radius lies
:param radius: Radius at which to evaluate the layer.
:type radius: float
:returns: Layer in which the radius lies.
:rtype: :class:`burnman.Layer`
"""
for layer in self.layers:
if layer.outer_radius >= radius:
return layer
raise LookupError()
| (self, radius) |
11,084 | burnman.classes.planet | make |
This routine needs to be called before evaluating any properties.
If pressures and temperatures are self-consistent, they
are computed across the planet here. Also initializes an array of materials
in each Layer to compute properties from.
| def make(self):
"""
This routine needs to be called before evaluating any properties.
If pressures and temperatures are self-consistent, they
are computed across the planet here. Also initializes an array of materials
in each Layer to compute properties from.
"""
self.reset()
for layer in self.layers:
assert layer.temperature_mode is not None
if self.pressure_mode == "user-defined":
self._temperatures = self._evaluate_temperature(self._pressures)
if self.pressure_mode == "self-consistent":
new_press = (
self.pressure_top + (-self.radii + max(self.radii)) * 1.0e3
) # initial pressure curve guess
temperatures = self._evaluate_temperature(new_press)
# Make it self-consistent!!!
i = 0
while i < self.n_max_iterations:
i += 1
ref_press = new_press
new_grav, new_press = self._evaluate_eos(
new_press, temperatures, self.gravity_bottom, self.pressure_top
)
temperatures = self._evaluate_temperature(new_press)
rel_err = abs((max(ref_press) - max(new_press)) / max(new_press))
if self.verbose:
print(
f"Iteration {i:0d} maximum relative pressure error: "
f"{rel_err:.1e}"
)
if rel_err < self.max_delta:
break
self.pressures = new_press
self.temperatures = temperatures
self._gravity = new_grav
for layer in self.layers:
layer.sublayers = []
layer.pressures = self.pressures[layer.n_start : layer.n_end]
layer.temperatures = self.temperatures[layer.n_start : layer.n_end]
layer.gravity_bottom = self._gravity[layer.n_start - 1]
layer.pressure_mode = "set-in-planet"
for i in range(len(layer.radii)):
layer.sublayers.append(layer.material.copy())
layer.sublayers[i].set_state(layer.pressures[i], layer.temperatures[i])
| (self) |
11,085 | burnman.classes.planet | reset |
Resets all cached material properties.
It is typically not required for the user to call this function.
| def reset(self):
"""
Resets all cached material properties.
It is typically not required for the user to call this function.
"""
self._cached = {}
| (self) |
11,086 | burnman.classes.planet | set_pressure_mode |
Sets the pressure mode of the planet by user-defined values are in a
self-consistent fashion.
pressure_mode is 'user-defined' or 'self-consistent'.
The default for the planet is self-consistent, with zero pressure at
the surface and zero pressure at the center.
:param pressure_mode: This can be set to 'user-defined' or 'self-consistent'.
:type pressure_mode: str
:param pressures: Pressures (Pa) to set layer to ('user-defined').
This should be the same length as defined radius array for the layer.
:type pressures: array of floats
:param pressure_top: Pressure (Pa) at the top of the layer.
:type pressure_top: float
:param gravity_bottom: Gravity (m/s^2) at the bottom the layer
:type gravity_bottom: float
:param n_max_iterations: Maximum number of iterations to reach
self-consistent pressures.
:type n_max_iterations: int
| def set_pressure_mode(
self,
pressure_mode="self-consistent",
pressures=None,
pressure_top=0.0,
gravity_bottom=0.0,
n_max_iterations=50,
max_delta=1.0e-5,
):
"""
Sets the pressure mode of the planet by user-defined values are in a
self-consistent fashion.
pressure_mode is 'user-defined' or 'self-consistent'.
The default for the planet is self-consistent, with zero pressure at
the surface and zero pressure at the center.
:param pressure_mode: This can be set to 'user-defined' or 'self-consistent'.
:type pressure_mode: str
:param pressures: Pressures (Pa) to set layer to ('user-defined').
This should be the same length as defined radius array for the layer.
:type pressures: array of floats
:param pressure_top: Pressure (Pa) at the top of the layer.
:type pressure_top: float
:param gravity_bottom: Gravity (m/s^2) at the bottom the layer
:type gravity_bottom: float
:param n_max_iterations: Maximum number of iterations to reach
self-consistent pressures.
:type n_max_iterations: int
"""
self.reset()
assert pressure_mode == "user-defined" or pressure_mode == "self-consistent"
self.pressure_mode = pressure_mode
self.gravity_bottom = gravity_bottom
if pressure_mode == "user-defined":
assert len(pressures) == len(self.radii)
self._pressures = pressures
warnings.warn(
"User-defined pressures mean that the planet is "
"unlikely to be self-consistent"
)
if pressure_mode == "self-consistent":
self.pressure_top = pressure_top
self.n_max_iterations = n_max_iterations
self.max_delta = max_delta
| (self, pressure_mode='self-consistent', pressures=None, pressure_top=0.0, gravity_bottom=0.0, n_max_iterations=50, max_delta=1e-05) |
11,087 | burnman.classes.solution | Solution |
This is the base class for all solutions.
Site occupancies, endmember activities and the constant
and pressure and temperature dependencies of the excess
properties can be queried after using set_composition().
States of the solution can only be queried after setting
the pressure, temperature and composition using set_state().
This class is available as :class:`burnman.Solution`.
It uses an instance of :class:`burnman.SolutionModel` to
calculate interaction terms between endmembers.
All the solution parameters are expected to be in SI units. This
means that the interaction parameters should be in J/mol, with the T
and P derivatives in J/K/mol and m^3/mol.
The parameters are relevant to all solution models. Please
see the documentation for individual models for details about
other parameters.
:param name: Name of the solution.
:type name: string
:param solution_model: The SolutionModel object defining the properties
of the solution.
:type solution_model: :class:`burnman.SolutionModel`
:param molar_fractions: The molar fractions of each endmember in the solution.
Can be reset using the set_composition() method.
:type molar_fractions: numpy.array
| class Solution(Mineral):
"""
This is the base class for all solutions.
Site occupancies, endmember activities and the constant
and pressure and temperature dependencies of the excess
properties can be queried after using set_composition().
States of the solution can only be queried after setting
the pressure, temperature and composition using set_state().
This class is available as :class:`burnman.Solution`.
It uses an instance of :class:`burnman.SolutionModel` to
calculate interaction terms between endmembers.
All the solution parameters are expected to be in SI units. This
means that the interaction parameters should be in J/mol, with the T
and P derivatives in J/K/mol and m^3/mol.
The parameters are relevant to all solution models. Please
see the documentation for individual models for details about
other parameters.
:param name: Name of the solution.
:type name: string
:param solution_model: The SolutionModel object defining the properties
of the solution.
:type solution_model: :class:`burnman.SolutionModel`
:param molar_fractions: The molar fractions of each endmember in the solution.
Can be reset using the set_composition() method.
:type molar_fractions: numpy.array
"""
def __init__(self, name=None, solution_model=None, molar_fractions=None):
"""
Set up matrices to speed up calculations for when P, T, X is defined.
"""
Mineral.__init__(self)
# Solution needs a method attribute to call Mineral.set_state().
# Note that set_method() below will not change self.method
self.method = "SolutionMethod"
if name is not None:
self.name = name
if solution_model is not None:
self.solution_model = solution_model
# Equation of state
for i in range(self.n_endmembers):
self.solution_model.endmembers[i][0].set_method(
self.solution_model.endmembers[i][0].params["equation_of_state"]
)
# Molar fractions
if molar_fractions is not None:
self.set_composition(molar_fractions)
@cached_property
def endmembers(self):
return self.solution_model.endmembers
def set_composition(self, molar_fractions):
"""
Set the composition for this solution.
Resets cached properties.
:param molar_fractions: Molar abundance for each endmember, needs to sum to one.
:type molar_fractions: list of float
"""
assert len(self.solution_model.endmembers) == len(molar_fractions)
if type(self.solution_model) != MechanicalSolution:
assert sum(molar_fractions) > 0.9999
assert sum(molar_fractions) < 1.0001
if type(self.solution_model) == PolynomialSolution:
self.solution_model.set_composition(molar_fractions)
self.reset()
self.molar_fractions = np.array(molar_fractions)
def set_method(self, method):
for i in range(self.n_endmembers):
self.solution_model.endmembers[i][0].set_method(method)
# note: do not set self.method here!
self.reset()
def set_state(self, pressure, temperature):
if type(self.solution_model) == PolynomialSolution:
self.solution_model.set_state(pressure, temperature)
Mineral.set_state(self, pressure, temperature)
for i in range(self.n_endmembers):
self.solution_model.endmembers[i][0].set_state(pressure, temperature)
@material_property
def formula(self):
"""
Returns molar chemical formula of the solution.
:rtype: Counter
"""
return sum_formulae(self.endmember_formulae, self.molar_fractions)
@material_property
def site_occupancies(self):
"""
:returns: The fractional occupancies of species on each site.
:rtype: list of OrderedDicts
"""
occs = np.einsum(
"ij, i", self.solution_model.endmember_occupancies, self.molar_fractions
)
site_occs = []
k = 0
for i in range(self.solution_model.n_sites):
site_occs.append(OrderedDict())
for j in range(len(self.solution_model.sites[i])):
site_occs[-1][self.solution_model.sites[i][j]] = occs[k]
k += 1
return site_occs
def site_formula(self, precision=2):
"""
Returns the molar chemical formula of the solution with site occupancies.
For example, [Mg0.4Fe0.6]2SiO4.
:param precision: Precision with which to print the site occupancies
:type precision: int
:returns: Molar chemical formula of the solution with site occupancies
:rtype: str
"""
split_empty = self.solution_model.empty_formula.split("[")
formula = split_empty[0]
for i, site_occs in enumerate(self.site_occupancies):
formula += "["
for species, occ in site_occs.items():
formula += f"{species}{occ:0.{precision}f}"
formula += split_empty[i + 1]
return formula
@material_property
def activities(self):
"""
Returns a list of endmember activities [unitless].
"""
return self.solution_model.activities(
self.pressure, self.temperature, self.molar_fractions
)
@material_property
def activity_coefficients(self):
"""
Returns a list of endmember activity coefficients
(gamma = activity / ideal activity) [unitless].
"""
return self.solution_model.activity_coefficients(
self.pressure, self.temperature, self.molar_fractions
)
@material_property
def molar_internal_energy(self):
"""
Returns molar internal energy of the mineral [J/mol].
Aliased with self.energy
"""
return self.molar_helmholtz + self.temperature * self.molar_entropy
@material_property
def excess_partial_gibbs(self):
"""
Returns excess partial molar gibbs free energy [J/mol].
Property specific to solutions.
"""
return self.solution_model.excess_partial_gibbs_free_energies(
self.pressure, self.temperature, self.molar_fractions
)
@material_property
def excess_partial_volumes(self):
"""
Returns excess partial volumes [m^3].
Property specific to solutions.
"""
return self.solution_model.excess_partial_volumes(
self.pressure, self.temperature, self.molar_fractions
)
@material_property
def excess_partial_entropies(self):
"""
Returns excess partial entropies [J/K].
Property specific to solutions.
"""
return self.solution_model.excess_partial_entropies(
self.pressure, self.temperature, self.molar_fractions
)
@material_property
def partial_gibbs(self):
"""
Returns endmember partial molar gibbs free energy [J/mol].
Property specific to solutions.
"""
return (
np.array(
[
self.solution_model.endmembers[i][0].gibbs
for i in range(self.n_endmembers)
]
)
+ self.excess_partial_gibbs
)
@material_property
def partial_volumes(self):
"""
Returns endmember partial volumes [m^3].
Property specific to solutions.
"""
return (
np.array(
[
self.solution_model.endmembers[i][0].molar_volume
for i in range(self.n_endmembers)
]
)
+ self.excess_partial_volumes
)
@material_property
def partial_entropies(self):
"""
Returns endmember partial entropies [J/K].
Property specific to solutions.
"""
return (
np.array(
[
self.solution_model.endmembers[i][0].molar_entropy
for i in range(self.n_endmembers)
]
)
+ self.excess_partial_entropies
)
@material_property
def excess_gibbs(self):
"""
Returns molar excess gibbs free energy [J/mol].
Property specific to solutions.
"""
return self.solution_model.excess_gibbs_free_energy(
self.pressure, self.temperature, self.molar_fractions
)
@material_property
def gibbs_hessian(self):
"""
Returns an array containing the second compositional derivative
of the Gibbs free energy [J]. Property specific to solutions.
"""
return self.solution_model.gibbs_hessian(
self.pressure, self.temperature, self.molar_fractions
)
@material_property
def entropy_hessian(self):
"""
Returns an array containing the second compositional derivative
of the entropy [J/K]. Property specific to solutions.
"""
return self.solution_model.entropy_hessian(
self.pressure, self.temperature, self.molar_fractions
)
@material_property
def volume_hessian(self):
"""
Returns an array containing the second compositional derivative
of the volume [m^3]. Property specific to solutions.
"""
return self.solution_model.volume_hessian(
self.pressure, self.temperature, self.molar_fractions
)
@material_property
def molar_gibbs(self):
"""
Returns molar Gibbs free energy of the solution [J/mol].
Aliased with self.gibbs.
"""
return (
sum(
[
self.solution_model.endmembers[i][0].gibbs * self.molar_fractions[i]
for i in range(self.n_endmembers)
]
)
+ self.excess_gibbs
)
@material_property
def molar_helmholtz(self):
"""
Returns molar Helmholtz free energy of the solution [J/mol].
Aliased with self.helmholtz.
"""
return self.molar_gibbs - self.pressure * self.molar_volume
@material_property
def molar_mass(self):
"""
Returns molar mass of the solution [kg/mol].
"""
return sum(
[
self.solution_model.endmembers[i][0].molar_mass
* self.molar_fractions[i]
for i in range(self.n_endmembers)
]
)
@material_property
def excess_volume(self):
"""
Returns excess molar volume of the solution [m^3/mol].
Specific property for solutions.
"""
return self.solution_model.excess_volume(
self.pressure, self.temperature, self.molar_fractions
)
@material_property
def molar_volume(self):
"""
Returns molar volume of the solution [m^3/mol].
Aliased with self.V.
"""
return (
sum(
[
self.solution_model.endmembers[i][0].molar_volume
* self.molar_fractions[i]
for i in range(self.n_endmembers)
]
)
+ self.excess_volume
)
@material_property
def density(self):
"""
Returns density of the solution [kg/m^3].
Aliased with self.rho.
"""
return self.molar_mass / self.molar_volume
@material_property
def excess_entropy(self):
"""
Returns excess molar entropy [J/K/mol].
Property specific to solutions.
"""
return self.solution_model.excess_entropy(
self.pressure, self.temperature, self.molar_fractions
)
@material_property
def molar_entropy(self):
"""
Returns molar entropy of the solution [J/K/mol].
Aliased with self.S.
"""
return (
sum(
[
self.solution_model.endmembers[i][0].S * self.molar_fractions[i]
for i in range(self.n_endmembers)
]
)
+ self.excess_entropy
)
@material_property
def excess_enthalpy(self):
"""
Returns excess molar enthalpy [J/mol].
Property specific to solutions.
"""
return self.solution_model.excess_enthalpy(
self.pressure, self.temperature, self.molar_fractions
)
@material_property
def molar_enthalpy(self):
"""
Returns molar enthalpy of the solution [J/mol].
Aliased with self.H.
"""
return (
sum(
[
self.solution_model.endmembers[i][0].H * self.molar_fractions[i]
for i in range(self.n_endmembers)
]
)
+ self.excess_enthalpy
)
@material_property
def isothermal_bulk_modulus(self):
"""
Returns isothermal bulk modulus of the solution [Pa].
Aliased with self.K_T.
"""
return (
self.V
* 1.0
/ (
sum(
[
self.solution_model.endmembers[i][0].V
/ (self.solution_model.endmembers[i][0].K_T)
* self.molar_fractions[i]
for i in range(self.n_endmembers)
]
)
+ self.solution_model.VoverKT_excess()
)
)
@material_property
def adiabatic_bulk_modulus(self):
"""
Returns adiabatic bulk modulus of the solution [Pa].
Aliased with self.K_S.
"""
if self.temperature < 1e-10:
return self.isothermal_bulk_modulus
else:
return (
self.isothermal_bulk_modulus
* self.molar_heat_capacity_p
/ self.molar_heat_capacity_v
)
@material_property
def isothermal_compressibility(self):
"""
Returns isothermal compressibility of the solution.
(or inverse isothermal bulk modulus) [1/Pa].
Aliased with self.K_T.
"""
return 1.0 / self.isothermal_bulk_modulus
@material_property
def adiabatic_compressibility(self):
"""
Returns adiabatic compressibility of the solution.
(or inverse adiabatic bulk modulus) [1/Pa].
Aliased with self.K_S.
"""
return 1.0 / self.adiabatic_bulk_modulus
@material_property
def shear_modulus(self):
"""
Returns shear modulus of the solution [Pa].
Aliased with self.G.
"""
G_list = np.fromiter(
(e[0].G for e in self.solution_model.endmembers),
dtype=float,
count=self.n_endmembers,
)
return reuss_average_function(self.molar_fractions, G_list)
@material_property
def p_wave_velocity(self):
"""
Returns P wave speed of the solution [m/s].
Aliased with self.v_p.
"""
return np.sqrt(
(self.adiabatic_bulk_modulus + 4.0 / 3.0 * self.shear_modulus)
/ self.density
)
@material_property
def bulk_sound_velocity(self):
"""
Returns bulk sound speed of the solution [m/s].
Aliased with self.v_phi.
"""
return np.sqrt(self.adiabatic_bulk_modulus / self.density)
@material_property
def shear_wave_velocity(self):
"""
Returns shear wave speed of the solution [m/s].
Aliased with self.v_s.
"""
return np.sqrt(self.shear_modulus / self.density)
@material_property
def grueneisen_parameter(self):
"""
Returns grueneisen parameter of the solution [unitless].
Aliased with self.gr.
"""
if self.temperature < 1e-10:
return float("nan")
else:
return (
self.thermal_expansivity
* self.isothermal_bulk_modulus
* self.molar_volume
/ self.molar_heat_capacity_v
)
@material_property
def thermal_expansivity(self):
"""
Returns thermal expansion coefficient (alpha)
of the solution [1/K].
Aliased with self.alpha.
"""
return (1.0 / self.V) * (
sum(
[
self.solution_model.endmembers[i][0].alpha
* self.solution_model.endmembers[i][0].V
* self.molar_fractions[i]
for i in range(self.n_endmembers)
]
)
+ self.solution_model.alphaV_excess()
)
@material_property
def molar_heat_capacity_v(self):
"""
Returns molar heat capacity at constant volume of the
solution [J/K/mol].
Aliased with self.C_v.
"""
return (
self.molar_heat_capacity_p
- self.molar_volume
* self.temperature
* self.thermal_expansivity
* self.thermal_expansivity
* self.isothermal_bulk_modulus
)
@material_property
def molar_heat_capacity_p(self):
"""
Returns molar heat capacity at constant pressure
of the solution [J/K/mol].
Aliased with self.C_p.
"""
return (
sum(
[
self.solution_model.endmembers[i][0].molar_heat_capacity_p
* self.molar_fractions[i]
for i in range(self.n_endmembers)
]
)
+ self.solution_model.Cp_excess()
)
@cached_property
def stoichiometric_matrix(self):
"""
A sympy Matrix where each element M[i,j] corresponds
to the number of atoms of element[j] in endmember[i].
"""
def f(i, j):
e = self.elements[j]
if e in self.endmember_formulae[i]:
return nsimplify(self.endmember_formulae[i][e])
else:
return 0
return Matrix(len(self.endmember_formulae), len(self.elements), f)
@cached_property
def stoichiometric_array(self):
"""
An array where each element arr[i,j] corresponds
to the number of atoms of element[j] in endmember[i].
"""
return np.array(self.stoichiometric_matrix)
@cached_property
def reaction_basis(self):
"""
An array where each element arr[i,j] corresponds
to the number of moles of endmember[j] involved in reaction[i].
"""
reaction_basis = np.array(
[v[:] for v in self.stoichiometric_matrix.T.nullspace()]
)
if len(reaction_basis) == 0:
reaction_basis = np.empty((0, len(self.endmember_names)))
return reaction_basis
@cached_property
def n_reactions(self):
"""
The number of reactions in reaction_basis.
"""
return len(self.reaction_basis[:, 0])
@cached_property
def independent_element_indices(self):
"""
A list of an independent set of element indices. If the amounts of
these elements are known (element_amounts),
the amounts of the other elements can be inferred by
-compositional_null_basis[independent_element_indices].dot(element_amounts).
"""
return sorted(independent_row_indices(self.stoichiometric_matrix.T))
@cached_property
def dependent_element_indices(self):
"""
The element indices not included in the independent list.
"""
return [
i
for i in range(len(self.elements))
if i not in self.independent_element_indices
]
@cached_property
def compositional_null_basis(self):
"""
An array N such that N.b = 0 for all bulk compositions that can
be produced with a linear sum of the endmembers in the solution.
"""
null_basis = np.array([v[:] for v in self.stoichiometric_matrix.nullspace()])
M = null_basis[:, self.dependent_element_indices]
assert (M.shape[0] == M.shape[1]) and (M == np.eye(M.shape[0])).all()
return null_basis
@cached_property
def endmember_formulae(self):
"""
A list of formulae for all the endmember in the solution.
"""
return [mbr[0].params["formula"] for mbr in self.solution_model.endmembers]
@cached_property
def endmember_names(self):
"""
A list of names for all the endmember in the solution.
"""
return [mbr[0].name for mbr in self.solution_model.endmembers]
@cached_property
def n_endmembers(self):
"""
The number of endmembers in the solution.
"""
return len(self.solution_model.endmembers)
@cached_property
def elements(self):
"""
A list of the elements which could be contained in the solution,
returned in the IUPAC element order.
"""
keys = []
for f in self.endmember_formulae:
keys.extend(f.keys())
return sort_element_list_to_IUPAC_order(set(keys))
| (name=None, solution_model=None, molar_fractions=None) |
11,088 | burnman.classes.solution | __init__ |
Set up matrices to speed up calculations for when P, T, X is defined.
| def __init__(self, name=None, solution_model=None, molar_fractions=None):
"""
Set up matrices to speed up calculations for when P, T, X is defined.
"""
Mineral.__init__(self)
# Solution needs a method attribute to call Mineral.set_state().
# Note that set_method() below will not change self.method
self.method = "SolutionMethod"
if name is not None:
self.name = name
if solution_model is not None:
self.solution_model = solution_model
# Equation of state
for i in range(self.n_endmembers):
self.solution_model.endmembers[i][0].set_method(
self.solution_model.endmembers[i][0].params["equation_of_state"]
)
# Molar fractions
if molar_fractions is not None:
self.set_composition(molar_fractions)
| (self, name=None, solution_model=None, molar_fractions=None) |
11,094 | burnman.classes.solution | set_composition |
Set the composition for this solution.
Resets cached properties.
:param molar_fractions: Molar abundance for each endmember, needs to sum to one.
:type molar_fractions: list of float
| def set_composition(self, molar_fractions):
"""
Set the composition for this solution.
Resets cached properties.
:param molar_fractions: Molar abundance for each endmember, needs to sum to one.
:type molar_fractions: list of float
"""
assert len(self.solution_model.endmembers) == len(molar_fractions)
if type(self.solution_model) != MechanicalSolution:
assert sum(molar_fractions) > 0.9999
assert sum(molar_fractions) < 1.0001
if type(self.solution_model) == PolynomialSolution:
self.solution_model.set_composition(molar_fractions)
self.reset()
self.molar_fractions = np.array(molar_fractions)
| (self, molar_fractions) |
11,096 | burnman.classes.solution | set_state | null | def set_state(self, pressure, temperature):
if type(self.solution_model) == PolynomialSolution:
self.solution_model.set_state(pressure, temperature)
Mineral.set_state(self, pressure, temperature)
for i in range(self.n_endmembers):
self.solution_model.endmembers[i][0].set_state(pressure, temperature)
| (self, pressure, temperature) |
11,098 | burnman.classes.solution | site_formula |
Returns the molar chemical formula of the solution with site occupancies.
For example, [Mg0.4Fe0.6]2SiO4.
:param precision: Precision with which to print the site occupancies
:type precision: int
:returns: Molar chemical formula of the solution with site occupancies
:rtype: str
| def site_formula(self, precision=2):
"""
Returns the molar chemical formula of the solution with site occupancies.
For example, [Mg0.4Fe0.6]2SiO4.
:param precision: Precision with which to print the site occupancies
:type precision: int
:returns: Molar chemical formula of the solution with site occupancies
:rtype: str
"""
split_empty = self.solution_model.empty_formula.split("[")
formula = split_empty[0]
for i, site_occs in enumerate(self.site_occupancies):
formula += "["
for species, occ in site_occs.items():
formula += f"{species}{occ:0.{precision}f}"
formula += split_empty[i + 1]
return formula
| (self, precision=2) |
11,116 | burnman.tools.partitioning | calculate_nakajima_fp_pv_partition_coefficient |
Calculate the partitioning of iron between periclase and bridgmanite as given
by Nakajima et al., 2012.
:param pressure: Equilibrium pressure [Pa]
:type pressure: float
:param temperature: Equilibrium temperature [K]
:type temperature: float
:param bulk_composition_mol: Bulk composition [mol].
Only Mg, Fe, and Si are assumed to explicitly affect the partitioning
with Al playing an implicit role.
:type bulk_composition_mol: dict
:param initial_distribution_coefficient: The distribution coefficient (Kd_0)
at 25 GPa and 0 K.
:type initial_distribution_coefficient: float
:returns: The proportion of Fe in ferropericlase and perovskite, respectively
:rtype: tuple
| def calculate_nakajima_fp_pv_partition_coefficient(
pressure, temperature, bulk_composition_mol, initial_distribution_coefficient
):
"""
Calculate the partitioning of iron between periclase and bridgmanite as given
by Nakajima et al., 2012.
:param pressure: Equilibrium pressure [Pa]
:type pressure: float
:param temperature: Equilibrium temperature [K]
:type temperature: float
:param bulk_composition_mol: Bulk composition [mol].
Only Mg, Fe, and Si are assumed to explicitly affect the partitioning
with Al playing an implicit role.
:type bulk_composition_mol: dict
:param initial_distribution_coefficient: The distribution coefficient (Kd_0)
at 25 GPa and 0 K.
:type initial_distribution_coefficient: float
:returns: The proportion of Fe in ferropericlase and perovskite, respectively
:rtype: tuple
"""
norm = bulk_composition_mol["Mg"] + bulk_composition_mol["Fe"]
f_FeO = bulk_composition_mol["Fe"] / norm
f_SiO2 = bulk_composition_mol["Si"] / norm
Kd_0 = initial_distribution_coefficient
delV = 2.0e-7 # in m^3/mol, average taken from Nakajima et al 2012, JGR
# eq 5 Nakajima et al 2012, JGR. Solved for ln(K(P,T,X))
rs = ((25.0e9 - pressure) * delV / (constants.gas_constant * temperature)) + np.log(
Kd_0
)
# The exchange coefficent at P and T. K(P,T,X) in eq 5 Nakajima et al 2012
K = np.exp(rs)
# Solving equation 6 in Nakajima et al., 2012 for X_Fe_fp and X_Fe_pv
# Solved using the definition of the distribution coefficient
# to define X_Fe_fp as a function of X_Fe_pv
num_to_sqrt = (-4.0 * f_FeO * (K - 1.0) * K * f_SiO2) + (
pow(1.0 + (f_FeO * (K - 1)) + ((K - 1.0) * f_SiO2), 2.0)
)
X_Fe_pv = (
-1.0 + f_FeO - (f_FeO * K) + f_SiO2 - (f_SiO2 * K) + np.sqrt(num_to_sqrt)
) / (2.0 * f_SiO2 * (1.0 - K))
X_Fe_fp = X_Fe_pv / (((1.0 - X_Fe_pv) * K) + X_Fe_pv)
return (X_Fe_fp, X_Fe_pv)
| (pressure, temperature, bulk_composition_mol, initial_distribution_coefficient) |
11,118 | burnman.utils.unitcell | cell_parameters_to_vectors |
Converts cell parameters to unit cell vectors.
:param cell_parameters: An array containing the three lengths of the
unit cell vectors [m], and the three angles [degrees].
The first angle (:math:`\alpha`) corresponds to the angle between the
second and the third cell vectors, the second (:math:`\beta`) to the
angle between the first and third cell vectors, and the third
(:math:`\gamma`) to the angle between the first and second vectors.
:type cell_parameters: numpy.array (1D)
:returns: The three vectors defining the parallelopiped cell [m].
This function assumes that the first cell vector is colinear with the
x-axis, and the second is perpendicular to the z-axis, and the third is
defined in a right-handed sense.
:rtype: numpy.array (2D)
| def cell_parameters_to_vectors(cell_parameters):
"""
Converts cell parameters to unit cell vectors.
:param cell_parameters: An array containing the three lengths of the
unit cell vectors [m], and the three angles [degrees].
The first angle (:math:`\\alpha`) corresponds to the angle between the
second and the third cell vectors, the second (:math:`\\beta`) to the
angle between the first and third cell vectors, and the third
(:math:`\\gamma`) to the angle between the first and second vectors.
:type cell_parameters: numpy.array (1D)
:returns: The three vectors defining the parallelopiped cell [m].
This function assumes that the first cell vector is colinear with the
x-axis, and the second is perpendicular to the z-axis, and the third is
defined in a right-handed sense.
:rtype: numpy.array (2D)
"""
a, b, c, alpha_deg, beta_deg, gamma_deg = cell_parameters
alpha = np.radians(alpha_deg)
beta = np.radians(beta_deg)
gamma = np.radians(gamma_deg)
n2 = (np.cos(alpha) - np.cos(gamma) * np.cos(beta)) / np.sin(gamma)
M = np.array(
[
[a, 0, 0],
[b * np.cos(gamma), b * np.sin(gamma), 0],
[c * np.cos(beta), c * n2, c * np.sqrt(np.sin(beta) ** 2 - n2**2)],
]
)
return M
| (cell_parameters) |
11,119 | burnman.utils.unitcell | cell_vectors_to_parameters |
Converts unit cell vectors to cell parameters.
:param M: The three vectors defining the parallelopiped cell [m].
This function assumes that the first cell vector is colinear with the
x-axis, the second is perpendicular to the z-axis, and the third is
defined in a right-handed sense.
:type M: numpy.array (2D)
:returns: An array containing the three lengths of the unit cell vectors [m],
and the three angles [degrees].
The first angle (:math:`\alpha`) corresponds to the angle between the
second and the third cell vectors, the second (:math:`\beta`) to the
angle between the first and third cell vectors, and the third
(:math:`\gamma`) to the angle between the first and second vectors.
:rtype: numpy.array (1D)
| def cell_vectors_to_parameters(M):
"""
Converts unit cell vectors to cell parameters.
:param M: The three vectors defining the parallelopiped cell [m].
This function assumes that the first cell vector is colinear with the
x-axis, the second is perpendicular to the z-axis, and the third is
defined in a right-handed sense.
:type M: numpy.array (2D)
:returns: An array containing the three lengths of the unit cell vectors [m],
and the three angles [degrees].
The first angle (:math:`\\alpha`) corresponds to the angle between the
second and the third cell vectors, the second (:math:`\\beta`) to the
angle between the first and third cell vectors, and the third
(:math:`\\gamma`) to the angle between the first and second vectors.
:rtype: numpy.array (1D)
"""
assert M[0, 1] == 0
assert M[0, 2] == 0
assert M[1, 2] == 0
a = M[0, 0]
b = np.sqrt(np.power(M[1, 0], 2.0) + np.power(M[1, 1], 2.0))
c = np.sqrt(
np.power(M[2, 0], 2.0) + np.power(M[2, 1], 2.0) + np.power(M[2, 2], 2.0)
)
gamma = np.arccos(M[1, 0] / b)
beta = np.arccos(M[2, 0] / c)
alpha = np.arccos(M[2, 1] / c * np.sin(gamma) + np.cos(gamma) * np.cos(beta))
gamma_deg = np.degrees(gamma)
beta_deg = np.degrees(beta)
alpha_deg = np.degrees(alpha)
return np.array([a, b, c, alpha_deg, beta_deg, gamma_deg])
| (M) |
11,125 | burnman.tools.equilibration | equilibrate |
A function that finds the thermodynamic equilibrium state of an
assemblage subject to given equality constraints by solving a set of
nonlinear equations related to the chemical potentials and
other state variables of the system.
The user chooses an assemblage (e.g. olivine, garnet and orthopyroxene)
and :math:`2+n_c` equality constraints, where :math:`n_c` is the number of
bulk compositional degrees of freedom. The equilibrate function attempts to
find the remaining unknowns that satisfy those constraints.
There are a number of equality constraints implemented in burnman. These are
given as a list of lists. Each constraint should have the form:
[<constraint type>, <constraint>], where
<constraint type> is one of 'P', 'T', 'S', 'V', 'X', 'PT_ellipse',
'phase_fraction', or 'phase_composition'. The format of the
<constraint> object depends on the constraint type:
- P: float or numpy.array of
pressures [Pa]
- T: float or numpy.array of
temperatures [K]
- S: float or numpy.array of
entropies [J/K]
- V: float or numpy.array of
volumes [m:math:`^3`]
- PT_ellipse: list of two floats or numpy.arrays, where the equality
satifies the equation norm(([P, T] - arr[0])/arr[1]) = 1
- phase_fraction: tuple with the form (<phase> <fraction(s)>),
where <phase> is one of the phase objects in the assemblage
and <fraction(s)> is a float or numpy.array corresponding
to the desired phase fractions.
- phase_composition: tuple with the form (<phase> <constraint>),
where <phase> is one of the phase objects in the assemblage
and <constraint> has the form (site_names, n, d, v),
where :math:`(nx)/(dx) = v`, n and d are constant vectors of
site coefficients, and v is a float or numpy.array. For example,
a constraint of the form ([Mg_A, Fe_A], [1., 0.], [1., 1.], [0.5])
would correspond to equal amounts Mg and Fe on the A site
(Mg_A / (Mg_A + Fe_A) = 0.5).
- X: list of a numpy.array and a float or numpy.array,
where the equality satisfies the linear equation arr[0] x = arr[1].
The first numpy.array is fixed, and the second is to be looped over
by the equilibrate function.
This is a generic compositional equality constraint.
:param composition: The bulk composition that the assemblage must satisfy.
:type composition: dict
:param assemblage: The assemblage to be equilibrated.
:type assemblage: :class:`burnman.Composite`
:param equality_constraints: The list of equality constraints. See above
for valid formats.
:type equality_constraints: list of list
:param free_compositional_vectors: A list of dictionaries containing
the compositional freedom of the solution. For example, if the list
contains the vector {'Mg': 1., 'Fe': -1}, that implies that the bulk
composition is equal to composition + :math:`a` (n_Mg - n_Fe),
where the value of :math:`a` is to be determined by the solve.
Vector given in atomic (molar) units of elements.
:type free_compositional_vectors: list of dict
:param tol: The tolerance for the nonlinear solver.
:type tol: float
:param store_iterates: Whether to store the parameter values for
each iteration in each solution object.
:type store_iterates: bool
:param store_assemblage: Whether to store a copy of the assemblage
object in each solution object.
:type store_assemblage: bool
:param max_iterations: The maximum number of iterations for the
nonlinear solver.
:type max_iterations: int
:param verbose: Whether to print output updating the user on the status of
equilibration.
:type verbose: bool
:returns: Solver solution object (or a list, or a 2D list of solution objects)
created by :func:`burnman.optimize.nonlinear_solvers.damped_newton_solve`,
and a namedtuple object created by
:func:`burnman.tools.equilibration.get_equilibration_parameters`. See
documentation of these functions for the return types. If store_assemblage
is True, each solution object also has an attribute called `assemblage`,
which contains a copy of the input assemblage with the equilibrated
properties. So, for a 2D grid of solution objects, one could call either
sols[0][1].x[0] or sols[0][1].assemblage.pressure to get the pressure.
:rtype: tuple
| def equilibrate(
composition,
assemblage,
equality_constraints,
free_compositional_vectors=[],
tol=1.0e-3,
store_iterates=False,
store_assemblage=True,
max_iterations=100.0,
verbose=False,
):
"""
A function that finds the thermodynamic equilibrium state of an
assemblage subject to given equality constraints by solving a set of
nonlinear equations related to the chemical potentials and
other state variables of the system.
The user chooses an assemblage (e.g. olivine, garnet and orthopyroxene)
and :math:`2+n_c` equality constraints, where :math:`n_c` is the number of
bulk compositional degrees of freedom. The equilibrate function attempts to
find the remaining unknowns that satisfy those constraints.
There are a number of equality constraints implemented in burnman. These are
given as a list of lists. Each constraint should have the form:
[<constraint type>, <constraint>], where
<constraint type> is one of 'P', 'T', 'S', 'V', 'X', 'PT_ellipse',
'phase_fraction', or 'phase_composition'. The format of the
<constraint> object depends on the constraint type:
- P: float or numpy.array of
pressures [Pa]
- T: float or numpy.array of
temperatures [K]
- S: float or numpy.array of
entropies [J/K]
- V: float or numpy.array of
volumes [m:math:`^3`]
- PT_ellipse: list of two floats or numpy.arrays, where the equality
satifies the equation norm(([P, T] - arr[0])/arr[1]) = 1
- phase_fraction: tuple with the form (<phase> <fraction(s)>),
where <phase> is one of the phase objects in the assemblage
and <fraction(s)> is a float or numpy.array corresponding
to the desired phase fractions.
- phase_composition: tuple with the form (<phase> <constraint>),
where <phase> is one of the phase objects in the assemblage
and <constraint> has the form (site_names, n, d, v),
where :math:`(nx)/(dx) = v`, n and d are constant vectors of
site coefficients, and v is a float or numpy.array. For example,
a constraint of the form ([Mg_A, Fe_A], [1., 0.], [1., 1.], [0.5])
would correspond to equal amounts Mg and Fe on the A site
(Mg_A / (Mg_A + Fe_A) = 0.5).
- X: list of a numpy.array and a float or numpy.array,
where the equality satisfies the linear equation arr[0] x = arr[1].
The first numpy.array is fixed, and the second is to be looped over
by the equilibrate function.
This is a generic compositional equality constraint.
:param composition: The bulk composition that the assemblage must satisfy.
:type composition: dict
:param assemblage: The assemblage to be equilibrated.
:type assemblage: :class:`burnman.Composite`
:param equality_constraints: The list of equality constraints. See above
for valid formats.
:type equality_constraints: list of list
:param free_compositional_vectors: A list of dictionaries containing
the compositional freedom of the solution. For example, if the list
contains the vector {'Mg': 1., 'Fe': -1}, that implies that the bulk
composition is equal to composition + :math:`a` (n_Mg - n_Fe),
where the value of :math:`a` is to be determined by the solve.
Vector given in atomic (molar) units of elements.
:type free_compositional_vectors: list of dict
:param tol: The tolerance for the nonlinear solver.
:type tol: float
:param store_iterates: Whether to store the parameter values for
each iteration in each solution object.
:type store_iterates: bool
:param store_assemblage: Whether to store a copy of the assemblage
object in each solution object.
:type store_assemblage: bool
:param max_iterations: The maximum number of iterations for the
nonlinear solver.
:type max_iterations: int
:param verbose: Whether to print output updating the user on the status of
equilibration.
:type verbose: bool
:returns: Solver solution object (or a list, or a 2D list of solution objects)
created by :func:`burnman.optimize.nonlinear_solvers.damped_newton_solve`,
and a namedtuple object created by
:func:`burnman.tools.equilibration.get_equilibration_parameters`. See
documentation of these functions for the return types. If store_assemblage
is True, each solution object also has an attribute called `assemblage`,
which contains a copy of the input assemblage with the equilibrated
properties. So, for a 2D grid of solution objects, one could call either
sols[0][1].x[0] or sols[0][1].assemblage.pressure to get the pressure.
:rtype: tuple
"""
for ph in assemblage.phases:
if isinstance(ph, Solution) and not hasattr(ph, "molar_fractions"):
raise Exception(
f"set_composition for solution {ph} before running equilibrate."
)
if assemblage.molar_fractions is None:
n_phases = len(assemblage.phases)
f = 1.0 / float(n_phases)
assemblage.set_fractions([f for i in range(n_phases)])
assemblage.n_moles = sum(composition.values()) / sum(assemblage.formula.values())
n_equality_constraints = len(equality_constraints)
n_free_compositional_vectors = len(free_compositional_vectors)
if n_equality_constraints != n_free_compositional_vectors + 2:
raise Exception(
"The number of equality constraints "
f"(currently {n_equality_constraints}) "
"must be two more than the number of "
"free_compositional vectors "
f"(currently {n_free_compositional_vectors})."
)
for v in free_compositional_vectors:
if np.abs(sum(v.values())) > 1.0e-12:
raise Exception(
"The amounts of each free_compositional_vector" "must sum to zero"
)
# Make parameter tuple
prm = get_equilibration_parameters(
assemblage, composition, free_compositional_vectors
)
# Check equality constraints have the correct structure
# Convert into the format readable by the function and jacobian functions
eq_constraint_lists = process_eq_constraints(equality_constraints, assemblage, prm)
# Set up solves
nc = [len(eq_constraint_list) for eq_constraint_list in eq_constraint_lists]
# Find the initial state (could be none here)
initial_state = [assemblage.pressure, assemblage.temperature]
# Reset initial state if equality constraints
# are related to pressure or temperature
for i in range(n_equality_constraints):
if eq_constraint_lists[i][0][0] == "P":
initial_state[0] = eq_constraint_lists[i][0][1]
elif eq_constraint_lists[i][0][0] == "T":
initial_state[1] = eq_constraint_lists[i][0][1]
elif eq_constraint_lists[i][0][0] == "PT_ellipse":
initial_state = eq_constraint_lists[i][0][1][1]
if initial_state[0] is None:
initial_state[0] = 5.0e9
if initial_state[1] is None:
initial_state[1] = 1200.0
assemblage.set_state(*initial_state)
parameters = get_parameters(assemblage, n_free_compositional_vectors)
# Solve the system of equations, loop over input parameters
sol_array = np.empty(shape=tuple(nc), dtype="object")
# Loop over problems
problems = list(product(*[list(range(nc[i])) for i in range(len(nc))]))
n_problems = len(problems)
for i_problem, i_c in enumerate(problems):
if verbose:
string = "Processing solution"
for i in range(len(i_c)):
string += " {0}/{1}".format(i_c[i] + 1, nc[i])
print(string + ":")
equality_constraints = [eq_constraint_lists[i][i_c[i]] for i in range(len(nc))]
# Set the initial fractions and compositions
# of the phases in the assemblage:
sol = damped_newton_solve(
F=lambda x: F(
x,
assemblage,
equality_constraints,
prm.reduced_composition_vector,
prm.reduced_free_composition_vectors,
),
J=lambda x: jacobian(
x,
assemblage,
equality_constraints,
prm.reduced_free_composition_vectors,
),
lambda_bounds=lambda dx, x: lambda_bounds(
dx, x, assemblage.endmembers_per_phase
),
guess=parameters,
linear_constraints=(prm.constraint_matrix, prm.constraint_vector),
tol=tol,
store_iterates=store_iterates,
max_iterations=max_iterations,
)
if sol.success and len(assemblage.reaction_affinities) > 0.0:
maxres = np.max(np.abs(assemblage.reaction_affinities)) + 1.0e-5
assemblage.equilibrium_tolerance = maxres
if store_assemblage:
sol.assemblage = assemblage.copy()
if sol.success and len(assemblage.reaction_affinities) > 0.0:
sol.assemblage.equilibrium_tolerance = maxres
if verbose:
print(sol.text)
sol_array[i_c] = sol
# Next, we use the solution values and Jacobian
# to provide a starting guess for the next problem.
# First, we find the equality constraints for the next problem
if i_problem < n_problems - 1:
next_i_c = problems[i_problem + 1]
next_equality_constraints = [
eq_constraint_lists[i][next_i_c[i]] for i in range(len(nc))
]
# We use the nearest solutions as potential starting points
# to make the next guess
prev_sols = []
for i in range(len(nc)):
if next_i_c[i] != 0:
prev_i_c = np.copy(next_i_c)
prev_i_c[i] -= 1
prev_sols.append(sol_array[tuple(prev_i_c)])
updated_params = False
for s in prev_sols:
if s.success and not updated_params:
# next guess based on a Newton step
# using the old solution vector and Jacobian
# with the new constraints.
dF = F(
s.x,
assemblage,
next_equality_constraints,
prm.reduced_composition_vector,
prm.reduced_free_composition_vectors,
)
luJ = lu_factor(s.J)
new_parameters = s.x + lu_solve(luJ, -dF)
c = (
prm.constraint_matrix.dot(new_parameters)
+ prm.constraint_vector
)
if all(c <= 0.0): # accept new guess
parameters = new_parameters
else: # use the parameters from this step
parameters = s.x
exhausted_phases = [
assemblage.phases[phase_idx].name
for phase_idx, v in enumerate(
new_parameters[prm.phase_amount_indices]
)
if v < 0.0
]
if len(exhausted_phases) > 0 and verbose:
print(
"A phase might be exhausted before the "
f"next step: {exhausted_phases}"
)
updated_params = True
# Finally, make dimensions of sol_array equal the input dimensions
if np.product(sol_array.shape) > 1:
sol_array = np.squeeze(sol_array)
else:
sol_array = sol_array.flatten()[0]
return sol_array, prm
| (composition, assemblage, equality_constraints, free_compositional_vectors=[], tol=0.001, store_iterates=False, store_assemblage=True, max_iterations=100.0, verbose=False) |
11,129 | burnman.classes.material | material_property |
Decorator @material_property to be used for cached properties of materials.
To be used on function in Material or derived classes that should be exposed
as read-only properties that are cached. The function Material.reset() will
reset the cached values.
Internally, the values are stored in a dictionary member called _cached, which
is emptied by .reset().
| def material_property(func):
"""
Decorator @material_property to be used for cached properties of materials.
To be used on function in Material or derived classes that should be exposed
as read-only properties that are cached. The function Material.reset() will
reset the cached values.
Internally, the values are stored in a dictionary member called _cached, which
is emptied by .reset().
"""
class mat_obj:
def __init__(self, func):
self.func = func
self.varname = self.func.__name__
def get(self, obj):
if not hasattr(obj, "_cached"):
raise Exception(
"The material_property decorator could not find "
"class member _cached. "
"Did you forget to call Material.__init__(self) in __init___?"
)
cache_array = getattr(obj, "_cached")
if self.varname not in cache_array:
cache_array[self.varname] = self.func(obj)
return cache_array[self.varname]
return property(mat_obj(func).get, doc=func.__doc__)
| (func) |
11,137 | smtpapi | SMTPAPIHeader | null | class SMTPAPIHeader(object):
def __init__(self):
self.data = {}
def add_to(self, to):
if 'to' not in self.data:
self.data['to'] = []
if type(to) is list:
self.data['to'] += to
else:
self.data['to'].append(to)
def set_tos(self, tos):
self.data['to'] = tos
def add_substitution(self, key, value):
if 'sub' not in self.data:
self.data['sub'] = {}
if key not in self.data['sub']:
self.data['sub'][key] = []
self.data['sub'][key].append(value)
def set_substitutions(self, subs):
self.data['sub'] = subs
def _add_key_value(self, index, key, value):
if index not in self.data:
self.data[index] = {}
self.data[index][key] = value
def _add_key(self, index, key):
if index not in self.data:
self.data[index] = []
self.data[index].append(key)
def add_unique_arg(self, key, value):
self._add_key_value('unique_args', key, value)
def set_unique_args(self, value):
self.data['unique_args'] = value
def add_category(self, category):
self._add_key('category', category)
def set_categories(self, category):
self.data['category'] = category
def add_section(self, key, section):
self._add_key_value('section', key, section)
def set_sections(self, value):
self.data['section'] = value
def add_send_each_at(self, time):
self._add_key('send_each_at', time)
def set_send_each_at(self, time):
self.data['send_each_at'] = time
def set_send_at(self, time):
self.data['send_at'] = time
def add_filter(self, app, setting, val):
if 'filters' not in self.data:
self.data['filters'] = {}
if app not in self.data['filters']:
self.data['filters'][app] = {}
if 'settings' not in self.data['filters'][app]:
self.data['filters'][app]['settings'] = {}
self.data['filters'][app]['settings'][setting] = val
def set_asm_group_id(self, value):
if not bool(value):
self.data['asm_group_id'] = {}
else:
self.data['asm_group_id'] = value
def set_ip_pool(self, value):
if bool(value):
self.data['ip_pool'] = value
else:
self.data['ip_pool'] = {}
def json_string(self):
result = {}
for key in self.data.keys():
if self.data[key] != [] and self.data[key] != {}:
result[key] = self.data[key]
return json.dumps(result, cls=_CustomJSONEncoder)
| () |
11,138 | smtpapi | __init__ | null | def __init__(self):
self.data = {}
| (self) |
11,139 | smtpapi | _add_key | null | def _add_key(self, index, key):
if index not in self.data:
self.data[index] = []
self.data[index].append(key)
| (self, index, key) |
11,140 | smtpapi | _add_key_value | null | def _add_key_value(self, index, key, value):
if index not in self.data:
self.data[index] = {}
self.data[index][key] = value
| (self, index, key, value) |
11,141 | smtpapi | add_category | null | def add_category(self, category):
self._add_key('category', category)
| (self, category) |
11,142 | smtpapi | add_filter | null | def add_filter(self, app, setting, val):
if 'filters' not in self.data:
self.data['filters'] = {}
if app not in self.data['filters']:
self.data['filters'][app] = {}
if 'settings' not in self.data['filters'][app]:
self.data['filters'][app]['settings'] = {}
self.data['filters'][app]['settings'][setting] = val
| (self, app, setting, val) |
11,143 | smtpapi | add_section | null | def add_section(self, key, section):
self._add_key_value('section', key, section)
| (self, key, section) |
11,144 | smtpapi | add_send_each_at | null | def add_send_each_at(self, time):
self._add_key('send_each_at', time)
| (self, time) |
11,145 | smtpapi | add_substitution | null | def add_substitution(self, key, value):
if 'sub' not in self.data:
self.data['sub'] = {}
if key not in self.data['sub']:
self.data['sub'][key] = []
self.data['sub'][key].append(value)
| (self, key, value) |
11,146 | smtpapi | add_to | null | def add_to(self, to):
if 'to' not in self.data:
self.data['to'] = []
if type(to) is list:
self.data['to'] += to
else:
self.data['to'].append(to)
| (self, to) |
11,147 | smtpapi | add_unique_arg | null | def add_unique_arg(self, key, value):
self._add_key_value('unique_args', key, value)
| (self, key, value) |
11,148 | smtpapi | json_string | null | def json_string(self):
result = {}
for key in self.data.keys():
if self.data[key] != [] and self.data[key] != {}:
result[key] = self.data[key]
return json.dumps(result, cls=_CustomJSONEncoder)
| (self) |
11,149 | smtpapi | set_asm_group_id | null | def set_asm_group_id(self, value):
if not bool(value):
self.data['asm_group_id'] = {}
else:
self.data['asm_group_id'] = value
| (self, value) |
11,150 | smtpapi | set_categories | null | def set_categories(self, category):
self.data['category'] = category
| (self, category) |
11,151 | smtpapi | set_ip_pool | null | def set_ip_pool(self, value):
if bool(value):
self.data['ip_pool'] = value
else:
self.data['ip_pool'] = {}
| (self, value) |
11,152 | smtpapi | set_sections | null | def set_sections(self, value):
self.data['section'] = value
| (self, value) |
11,153 | smtpapi | set_send_at | null | def set_send_at(self, time):
self.data['send_at'] = time
| (self, time) |
11,154 | smtpapi | set_send_each_at | null | def set_send_each_at(self, time):
self.data['send_each_at'] = time
| (self, time) |
11,155 | smtpapi | set_substitutions | null | def set_substitutions(self, subs):
self.data['sub'] = subs
| (self, subs) |
11,156 | smtpapi | set_tos | null | def set_tos(self, tos):
self.data['to'] = tos
| (self, tos) |
11,157 | smtpapi | set_unique_args | null | def set_unique_args(self, value):
self.data['unique_args'] = value
| (self, value) |
11,158 | smtpapi | _CustomJSONEncoder | null | class _CustomJSONEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.Decimal):
return float(o)
# Provide a fallback to the default encoder if we haven't implemented
# special support for the object's class
return super(_CustomJSONEncoder, self).default(o)
| (*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None) |
11,159 | json.encoder | __init__ | Constructor for JSONEncoder, with sensible defaults.
If skipkeys is false, then it is a TypeError to attempt
encoding of keys that are not str, int, float or None. If
skipkeys is True, such items are simply skipped.
If ensure_ascii is true, the output is guaranteed to be str
objects with all incoming non-ASCII characters escaped. If
ensure_ascii is false, the output can contain non-ASCII characters.
If check_circular is true, then lists, dicts, and custom encoded
objects will be checked for circular references during encoding to
prevent an infinite recursion (which would cause an RecursionError).
Otherwise, no such check takes place.
If allow_nan is true, then NaN, Infinity, and -Infinity will be
encoded as such. This behavior is not JSON specification compliant,
but is consistent with most JavaScript based encoders and decoders.
Otherwise, it will be a ValueError to encode such floats.
If sort_keys is true, then the output of dictionaries will be
sorted by key; this is useful for regression tests to ensure
that JSON serializations can be compared on a day-to-day basis.
If indent is a non-negative integer, then JSON array
elements and object members will be pretty-printed with that
indent level. An indent level of 0 will only insert newlines.
None is the most compact representation.
If specified, separators should be an (item_separator, key_separator)
tuple. The default is (', ', ': ') if *indent* is ``None`` and
(',', ': ') otherwise. To get the most compact JSON representation,
you should specify (',', ':') to eliminate whitespace.
If specified, default is a function that gets called for objects
that can't otherwise be serialized. It should return a JSON encodable
version of the object or raise a ``TypeError``.
| def __init__(self, *, skipkeys=False, ensure_ascii=True,
check_circular=True, allow_nan=True, sort_keys=False,
indent=None, separators=None, default=None):
"""Constructor for JSONEncoder, with sensible defaults.
If skipkeys is false, then it is a TypeError to attempt
encoding of keys that are not str, int, float or None. If
skipkeys is True, such items are simply skipped.
If ensure_ascii is true, the output is guaranteed to be str
objects with all incoming non-ASCII characters escaped. If
ensure_ascii is false, the output can contain non-ASCII characters.
If check_circular is true, then lists, dicts, and custom encoded
objects will be checked for circular references during encoding to
prevent an infinite recursion (which would cause an RecursionError).
Otherwise, no such check takes place.
If allow_nan is true, then NaN, Infinity, and -Infinity will be
encoded as such. This behavior is not JSON specification compliant,
but is consistent with most JavaScript based encoders and decoders.
Otherwise, it will be a ValueError to encode such floats.
If sort_keys is true, then the output of dictionaries will be
sorted by key; this is useful for regression tests to ensure
that JSON serializations can be compared on a day-to-day basis.
If indent is a non-negative integer, then JSON array
elements and object members will be pretty-printed with that
indent level. An indent level of 0 will only insert newlines.
None is the most compact representation.
If specified, separators should be an (item_separator, key_separator)
tuple. The default is (', ', ': ') if *indent* is ``None`` and
(',', ': ') otherwise. To get the most compact JSON representation,
you should specify (',', ':') to eliminate whitespace.
If specified, default is a function that gets called for objects
that can't otherwise be serialized. It should return a JSON encodable
version of the object or raise a ``TypeError``.
"""
self.skipkeys = skipkeys
self.ensure_ascii = ensure_ascii
self.check_circular = check_circular
self.allow_nan = allow_nan
self.sort_keys = sort_keys
self.indent = indent
if separators is not None:
self.item_separator, self.key_separator = separators
elif indent is not None:
self.item_separator = ','
if default is not None:
self.default = default
| (self, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None) |
11,160 | smtpapi | default | null | def default(self, o):
if isinstance(o, decimal.Decimal):
return float(o)
# Provide a fallback to the default encoder if we haven't implemented
# special support for the object's class
return super(_CustomJSONEncoder, self).default(o)
| (self, o) |
11,161 | json.encoder | encode | Return a JSON string representation of a Python data structure.
>>> from json.encoder import JSONEncoder
>>> JSONEncoder().encode({"foo": ["bar", "baz"]})
'{"foo": ["bar", "baz"]}'
| def encode(self, o):
"""Return a JSON string representation of a Python data structure.
>>> from json.encoder import JSONEncoder
>>> JSONEncoder().encode({"foo": ["bar", "baz"]})
'{"foo": ["bar", "baz"]}'
"""
# This is for extremely simple cases and benchmarks.
if isinstance(o, str):
if self.ensure_ascii:
return encode_basestring_ascii(o)
else:
return encode_basestring(o)
# This doesn't pass the iterator directly to ''.join() because the
# exceptions aren't as detailed. The list call should be roughly
# equivalent to the PySequence_Fast that ''.join() would do.
chunks = self.iterencode(o, _one_shot=True)
if not isinstance(chunks, (list, tuple)):
chunks = list(chunks)
return ''.join(chunks)
| (self, o) |
11,162 | json.encoder | iterencode | Encode the given object and yield each string
representation as available.
For example::
for chunk in JSONEncoder().iterencode(bigobject):
mysocket.write(chunk)
| def iterencode(self, o, _one_shot=False):
"""Encode the given object and yield each string
representation as available.
For example::
for chunk in JSONEncoder().iterencode(bigobject):
mysocket.write(chunk)
"""
if self.check_circular:
markers = {}
else:
markers = None
if self.ensure_ascii:
_encoder = encode_basestring_ascii
else:
_encoder = encode_basestring
def floatstr(o, allow_nan=self.allow_nan,
_repr=float.__repr__, _inf=INFINITY, _neginf=-INFINITY):
# Check for specials. Note that this type of test is processor
# and/or platform-specific, so do tests which don't depend on the
# internals.
if o != o:
text = 'NaN'
elif o == _inf:
text = 'Infinity'
elif o == _neginf:
text = '-Infinity'
else:
return _repr(o)
if not allow_nan:
raise ValueError(
"Out of range float values are not JSON compliant: " +
repr(o))
return text
if (_one_shot and c_make_encoder is not None
and self.indent is None):
_iterencode = c_make_encoder(
markers, self.default, _encoder, self.indent,
self.key_separator, self.item_separator, self.sort_keys,
self.skipkeys, self.allow_nan)
else:
_iterencode = _make_iterencode(
markers, self.default, _encoder, self.indent, floatstr,
self.key_separator, self.item_separator, self.sort_keys,
self.skipkeys, _one_shot)
return _iterencode(o, 0)
| (self, o, _one_shot=False) |
11,233 | ffmpeg_editlist | atomic_write | Atomically write into the given fname.
Returns a NamedTemporaryFile that will be moved (atomically,
os.replace). Use [returnvalue].name to access the file's name.
| def main(argv=sys.argv[1:]):
parser = argparse.ArgumentParser()
parser.add_argument('editlist')
parser.add_argument('input', type=Path,
help="Input file or directory of files.")
parser.add_argument('--output', '-o', default='.', type=Path,
help='Output directory')
parser.add_argument('--srt', action='store_true',
help='Also convert subtitles')
parser.add_argument('--limit', '-l', action='append',
help='Limit to only outputs matching this pattern. There is no wildcarding. This option can be given multiple times.')
parser.add_argument('--check', '-c', action='store_true',
help="Don't encode or generate output files, just check consistency of the YAML file. This *will* override the .info.txt output file.")
parser.add_argument('--force', '-f', action='store_true',
help='Overwrite existing output files without prompting')
parser.add_argument('--verbose', '-v', action='store_true',
help='Verbose (put ffmpeg in normal mode, otherwise ffmpeg is quiet.)')
parser.add_argument('--reencode', action='store_true',
help='Re-encode all segments of the video. See --preset and --crf to adjust parameters.'
'This is needed when you start a snipet in the middle of a video, since the video decoding '
'can only begin at a key frame. '
'Default false.')
parser.add_argument('--crf', default=20, type=int,
help='x264 crf (preceived quality) to use for re-encoding, lower is higher quality. '
'Reasonable options are 20 (extremely good) to 30 (lower quality) (the absolute range 1 - 51); '
'higher numbers take less time to encode.'
'Default is 20, which should be good enough for any purpose.')
parser.add_argument('--preset', default='veryslow',
help='x264 preset to use for re-encoding, basically the encoding speed. '
'Changing this affects how much time it will take to compress to get the --crf quality target '
'you request; slower=better compression by using more expensive codec features. '
'Example options you might use include veryslow, slow, medium, fast, and ultrafast. '
'Default is veryslow, use ultrafast for fast testing.')
parser.add_argument('--threads', type=int,
help='Number of encoding threads. Default: unset, autodetect')
parser.add_argument('--wait', action='store_true',
help='Wait after each encoding (don\'t clean up the temporary directory right away')
parser.add_argument('--list', action='store_true',
help="Don't do anything, just list all outputs that would be processed (and nothing else)")
args = parser.parse_args(argv)
if args.threads:
FFMPEG_VIDEO_ENCODE.extend(['-threads', str(args.threads)])
FFMPEG_VIDEO_ENCODE.extend(['-preset', args.preset])
FFMPEG_VIDEO_ENCODE.extend(['-crf', str(args.crf)])
if args.srt:
import srt
all_inputs = set()
# Open the input file. Parse out of markdown if it is markdown:
data = open(args.editlist).read()
if '```' in data:
matches = re.findall(r'`{3,}[^\n]*\n(.*?)\n`{3,}', data, re.MULTILINE|re.DOTALL)
#print(matches)
data = '\n'.join([m for m in matches])
#print(data)
data = yaml.safe_load(data)
PWD = Path(os.getcwd())
LOGLEVEL = 31
if args.verbose:
LOGLEVEL = 40
workshop_title = None
workshop_description = None
options_ffmpeg_global = [ ]
#
# For each output file
#
input0 = args.input
for segment in data:
#print(segment)
tmp_outputs = [ ]
TOC = [ ]
segment_list = [ ]
cumulative_time = 0
filters = [ ]
covers = [ ]
options_ffmpeg_output = [ ]
subtitles = [ ]
with tempfile.TemporaryDirectory() as tmpdir:
# Find input
if 'input' in segment:
input0 = segment['input']
if 'workshop_description' in segment:
workshop_description = segment['workshop_description'].strip()
if 'workshop_title' in segment:
workshop_title = segment['workshop_title']
if 'crop' in segment:
# -filter:v "crop=w:h:x:y" - x:y is top-left corner
options_ffmpeg_output.extend(generate_crop(**segment['crop']))
if 'output' not in segment:
continue
allow_reencode = segment.get('reencode', True)
# Exclude non-matching files if '--limit' specified.
if args.limit and not any(limit_match in segment['output'] for limit_match in args.limit):
continue
if args.list:
print(segment['output'])
continue
input1 = input0
editlist = segment.get('editlist', segment.get('time'))
if editlist is None:
continue
#
# For each segment in the output
#
options_ffmpeg_segment = [ ]
segment_type = 'video'
segment_number = 0
for i, command in enumerate(editlist):
# Is this a command to cover a part of the video?
if isinstance(command, dict) and 'cover' in command:
cover = command['cover']
covers.append((segment_number, seconds(cover['begin'])))
filters.append(generate_cover(**cover))
continue
# Input command: change input files
elif isinstance(command, dict) and 'input' in command:
input1 = command['input']
# Handle png images
if 'duration' in command:
start = 0
stop = seconds(command['duration'])
segment_type = 'image'
segment_number += 1
else:
continue
# Start command: start a segment
elif isinstance(command, dict) and 'start' in command:
segment_number += 1
start = command['start']
continue
elif isinstance(command, dict) and 'begin' in command:
segment_number += 1
start = command['begin']
continue
# End command: process this segment and all queued commands
elif isinstance(command, dict) and 'stop' in command:
stop = command['stop']
# Continue below to process this segment
elif isinstance(command, dict) and 'end' in command:
stop = command['end']
# Continue below to process this segment
# Is this a TOC entry?
# If it's a dict, it is a table of contents entry that will be
# mapped to the correct time in the procesed video.
# This is a TOC entry
elif isinstance(command, dict):
( (time, title), ) = list(command.items())
if time == '-':
time = start
if title in {'stop', 'start', 'begin', 'end', 'cover', 'input'}:
LOG.error("ERROR: Suspicious TOC entry name, aborting encoding: %s", title)
sys.exit(1)
#print(start, title)
#print('TOC', start, title, segment)
TOC.append((segment_number, seconds(time), title))
continue
# The end of our time segment (from 'start' to 'stop'). Do the
# actual processing of this segment now.
else:
# time can be string with comma or list
time = command
if isinstance(time, str):
time = time.split(',')
if len(time) == 2:
start, stop = time
elif len(time) == 3:
input1, start, stop = time
start = str(start).strip()
stop = str(stop).strip()
# Print status
LOG.info("\n\nBeginning %s (line %d)", segment.get('title') if 'title' in segment else '[no title]', i)
# Find input file
if not os.path.exists(input1):
input1 = args.input / input1
input1 = os.path.expanduser(input1)
all_inputs.add(input1)
segment_list.append([segment_number, seconds(start), cumulative_time])
segment_list.append([segment_number, seconds(stop), None])
start_cumulative = cumulative_time
cumulative_time += seconds(stop) - seconds(start)
# filters
if filters:
filters = ['-vf', ','.join(filters)]
# Encode for video, image, etc?
if segment_type == 'video':
encoding_args = ['-i', input1,
'-ss', start, '-to', stop,
*(FFMPEG_VIDEO_ENCODE if (args.reencode and allow_reencode) or filters else FFMPEG_VIDEO_COPY),
*FFMPEG_AUDIO_COPY,
]
if seconds(start) > seconds(stop):
raise RuntimeError(f"start is greater than stop time ({start} > {stop} time in {segment.get('title')}")
elif segment_type == 'image':
# https://trac.ffmpeg.org/wiki/Slideshow
encoding_args = ['-loop', '1',
'-i', input1,
'-t', str(command['duration']),
'-vf', f'fps={FFMPEG_FRAMERATE},format=yuv420p',
'-c:v', 'libx264', ]#'-r', str(FFMPEG_FRAMERATE)]
else:
raise RuntimeError(f"unknown segment_type: {segment_type}")
# Do encoding
tmp_out = str(Path(tmpdir)/('tmpout-%02d.mkv'%i))
tmp_outputs.append(tmp_out)
cmd = ['ffmpeg', '-loglevel', str(LOGLEVEL),
*encoding_args,
*options_ffmpeg_output,
*options_ffmpeg_segment,
*filters,
tmp_out,
]
LOG.info(shell_join(cmd))
if not args.check:
subprocess.check_call(cmd)
# Subtitles?
if args.srt:
sub_file = os.path.splitext(input1)[0] + '.srt'
start_dt = timedelta(seconds=seconds(start))
end_dt = timedelta(seconds=seconds(stop))
start_cumulative_dt = timedelta(seconds=start_cumulative)
duration_segment_dt = end_dt-start_dt
for sub in srt.parse(open(sub_file).read()):
if sub.end < start_dt: continue
if sub.start > end_dt: continue
sub = copy.copy(sub)
sub.start = sub.start - start_dt + start_cumulative_dt
sub.end = sub.end - start_dt + start_cumulative_dt
sub.start = max(sub.start, start_cumulative_dt)
sub.end = min(sub.end, start_cumulative_dt + duration_segment_dt)
subtitles.append(sub)
# Reset for the next round
filters = [ ]
options_ffmpeg_segment = [ ]
segment_type = 'video'
# Create the playlist of inputs
playlist = Path(tmpdir) / 'playlist.txt'
with open(playlist, 'w') as playlist_f:
for file_ in tmp_outputs:
playlist_f.write('file '+str(file_)+'\n')
LOG.debug("Playlist:")
LOG.debug(open(playlist).read())
# Re-encode
output = args.output / segment['output']
ensure_filedir_exists(output)
if output in all_inputs:
raise RuntimeError("Output is the same as an input file, aborting.")
tmpdir_out = str(Path(tmpdir)/('final-'+segment['output'].replace('/', '%2F')))
cmd = ['ffmpeg', '-loglevel', str(LOGLEVEL),
#*itertools.chain.from_iterable(('-i', x) for x in tmp_outputs),
#'-i', 'concat:'+'|'.join(tmp_outputs),
'-safe', '0', '-f', 'concat', '-i', playlist,
'-fflags', '+igndts',
'-c', 'copy',
*(['-y'] if args.force else []),
tmpdir_out,
]
LOG.info(shell_join(cmd))
if not args.check:
subprocess.check_call(cmd)
# We need another copy, since ffmpeg detects output based on filename. Yet for atomicness, we need a temporary filename for the temp part
if not args.check:
with atomic_write(output) as tmp_output:
shutil.move(tmpdir_out, tmp_output)
# Subtitles
if args.srt:
srt_output = os.path.splitext(output)[0] + '.srt'
open(srt_output, 'w').write(srt.compose(subtitles))
# Print table of contents
import pprint
LOG.debug(pprint.pformat(segment_list))
LOG.debug(pprint.pformat(TOC))
video_description = [ ]
if segment.get('title'):
title = segment['title']
if workshop_title is not None:
title = title + ' - ' + workshop_title
video_description.extend([title.strip()])
if segment.get('description'):
video_description.extend([segment['description'].strip().replace('\n', '\n\n')])
# Print out the table of contents
#video_description.append('\n')
toc = [ ]
for seg_n, time, name in TOC:
LOG.debug("TOC entry %s %s", time, name)
new_time = map_time(seg_n, segment_list, time)
print(humantime(new_time), name)
toc.append(f"{humantime(new_time)} {name}")
if toc:
video_description.append('\n'.join(toc))
if workshop_description:
video_description.append('-----')
video_description.append(workshop_description.replace('\n', '\n\n').strip())
if video_description:
with atomic_write(os.path.splitext(str(output))[0]+'.info.txt', 'w') as toc_file:
open(toc_file, 'w').write('\n\n'.join(video_description))
# Print out covered segments (for verification purposes)
for seg_n, time in covers:
new_time = map_time(seg_n, segment_list, time)
LOG.info("Check cover at %s", humantime(new_time))
if args.wait:
input('press return to continue> ')
| (fname, mode='w+b') |
11,237 | ffmpeg_editlist | ensure_filedir_exists | Ensure a a directory exists, that can hold the file given as argument | def ensure_filedir_exists(filename):
"""Ensure a a directory exists, that can hold the file given as argument"""
dirname = os.path.dirname(filename)
if dirname == '':
return
if not os.path.isdir(dirname):
os.makedirs(dirname)
| (filename) |
11,238 | ffmpeg_editlist | generate_cover | null | def generate_cover(begin, end, w=10000, h=10000, x=0, y=0):
begin = seconds(begin)
end = seconds(end)
return FFMPEG_COVER.format(**locals())
| (begin, end, w=10000, h=10000, x=0, y=0) |
11,239 | ffmpeg_editlist | generate_crop | null | def generate_crop(w, h, x, y):
return ['-filter:v', f"crop={w}:{h}:{x}:{y}"]
| (w, h, x, y) |
11,240 | ffmpeg_editlist | humantime | null | def humantime(x):
hou = x // 3600
min = (x % 3600) // 60
sec = x % 60
if hou:
return "%d:%02d:%02d"%(hou, min, floor(sec))
return "%02d:%02d"%(min, floor(sec))
| (x) |
11,241 | ffmpeg_editlist | is_time | null | def is_time(x):
m = re.match(r'((\d{1,2}:)?\d{1,2}:)?\d{1,2}(\.\d*)?$', x)
return bool(m)
| (x) |
11,244 | ffmpeg_editlist | main | null | def main(argv=sys.argv[1:]):
parser = argparse.ArgumentParser()
parser.add_argument('editlist')
parser.add_argument('input', type=Path,
help="Input file or directory of files.")
parser.add_argument('--output', '-o', default='.', type=Path,
help='Output directory')
parser.add_argument('--srt', action='store_true',
help='Also convert subtitles')
parser.add_argument('--limit', '-l', action='append',
help='Limit to only outputs matching this pattern. There is no wildcarding. This option can be given multiple times.')
parser.add_argument('--check', '-c', action='store_true',
help="Don't encode or generate output files, just check consistency of the YAML file. This *will* override the .info.txt output file.")
parser.add_argument('--force', '-f', action='store_true',
help='Overwrite existing output files without prompting')
parser.add_argument('--verbose', '-v', action='store_true',
help='Verbose (put ffmpeg in normal mode, otherwise ffmpeg is quiet.)')
parser.add_argument('--reencode', action='store_true',
help='Re-encode all segments of the video. See --preset and --crf to adjust parameters.'
'This is needed when you start a snipet in the middle of a video, since the video decoding '
'can only begin at a key frame. '
'Default false.')
parser.add_argument('--crf', default=20, type=int,
help='x264 crf (preceived quality) to use for re-encoding, lower is higher quality. '
'Reasonable options are 20 (extremely good) to 30 (lower quality) (the absolute range 1 - 51); '
'higher numbers take less time to encode.'
'Default is 20, which should be good enough for any purpose.')
parser.add_argument('--preset', default='veryslow',
help='x264 preset to use for re-encoding, basically the encoding speed. '
'Changing this affects how much time it will take to compress to get the --crf quality target '
'you request; slower=better compression by using more expensive codec features. '
'Example options you might use include veryslow, slow, medium, fast, and ultrafast. '
'Default is veryslow, use ultrafast for fast testing.')
parser.add_argument('--threads', type=int,
help='Number of encoding threads. Default: unset, autodetect')
parser.add_argument('--wait', action='store_true',
help='Wait after each encoding (don\'t clean up the temporary directory right away')
parser.add_argument('--list', action='store_true',
help="Don't do anything, just list all outputs that would be processed (and nothing else)")
args = parser.parse_args(argv)
if args.threads:
FFMPEG_VIDEO_ENCODE.extend(['-threads', str(args.threads)])
FFMPEG_VIDEO_ENCODE.extend(['-preset', args.preset])
FFMPEG_VIDEO_ENCODE.extend(['-crf', str(args.crf)])
if args.srt:
import srt
all_inputs = set()
# Open the input file. Parse out of markdown if it is markdown:
data = open(args.editlist).read()
if '```' in data:
matches = re.findall(r'`{3,}[^\n]*\n(.*?)\n`{3,}', data, re.MULTILINE|re.DOTALL)
#print(matches)
data = '\n'.join([m for m in matches])
#print(data)
data = yaml.safe_load(data)
PWD = Path(os.getcwd())
LOGLEVEL = 31
if args.verbose:
LOGLEVEL = 40
workshop_title = None
workshop_description = None
options_ffmpeg_global = [ ]
#
# For each output file
#
input0 = args.input
for segment in data:
#print(segment)
tmp_outputs = [ ]
TOC = [ ]
segment_list = [ ]
cumulative_time = 0
filters = [ ]
covers = [ ]
options_ffmpeg_output = [ ]
subtitles = [ ]
with tempfile.TemporaryDirectory() as tmpdir:
# Find input
if 'input' in segment:
input0 = segment['input']
if 'workshop_description' in segment:
workshop_description = segment['workshop_description'].strip()
if 'workshop_title' in segment:
workshop_title = segment['workshop_title']
if 'crop' in segment:
# -filter:v "crop=w:h:x:y" - x:y is top-left corner
options_ffmpeg_output.extend(generate_crop(**segment['crop']))
if 'output' not in segment:
continue
allow_reencode = segment.get('reencode', True)
# Exclude non-matching files if '--limit' specified.
if args.limit and not any(limit_match in segment['output'] for limit_match in args.limit):
continue
if args.list:
print(segment['output'])
continue
input1 = input0
editlist = segment.get('editlist', segment.get('time'))
if editlist is None:
continue
#
# For each segment in the output
#
options_ffmpeg_segment = [ ]
segment_type = 'video'
segment_number = 0
for i, command in enumerate(editlist):
# Is this a command to cover a part of the video?
if isinstance(command, dict) and 'cover' in command:
cover = command['cover']
covers.append((segment_number, seconds(cover['begin'])))
filters.append(generate_cover(**cover))
continue
# Input command: change input files
elif isinstance(command, dict) and 'input' in command:
input1 = command['input']
# Handle png images
if 'duration' in command:
start = 0
stop = seconds(command['duration'])
segment_type = 'image'
segment_number += 1
else:
continue
# Start command: start a segment
elif isinstance(command, dict) and 'start' in command:
segment_number += 1
start = command['start']
continue
elif isinstance(command, dict) and 'begin' in command:
segment_number += 1
start = command['begin']
continue
# End command: process this segment and all queued commands
elif isinstance(command, dict) and 'stop' in command:
stop = command['stop']
# Continue below to process this segment
elif isinstance(command, dict) and 'end' in command:
stop = command['end']
# Continue below to process this segment
# Is this a TOC entry?
# If it's a dict, it is a table of contents entry that will be
# mapped to the correct time in the procesed video.
# This is a TOC entry
elif isinstance(command, dict):
( (time, title), ) = list(command.items())
if time == '-':
time = start
if title in {'stop', 'start', 'begin', 'end', 'cover', 'input'}:
LOG.error("ERROR: Suspicious TOC entry name, aborting encoding: %s", title)
sys.exit(1)
#print(start, title)
#print('TOC', start, title, segment)
TOC.append((segment_number, seconds(time), title))
continue
# The end of our time segment (from 'start' to 'stop'). Do the
# actual processing of this segment now.
else:
# time can be string with comma or list
time = command
if isinstance(time, str):
time = time.split(',')
if len(time) == 2:
start, stop = time
elif len(time) == 3:
input1, start, stop = time
start = str(start).strip()
stop = str(stop).strip()
# Print status
LOG.info("\n\nBeginning %s (line %d)", segment.get('title') if 'title' in segment else '[no title]', i)
# Find input file
if not os.path.exists(input1):
input1 = args.input / input1
input1 = os.path.expanduser(input1)
all_inputs.add(input1)
segment_list.append([segment_number, seconds(start), cumulative_time])
segment_list.append([segment_number, seconds(stop), None])
start_cumulative = cumulative_time
cumulative_time += seconds(stop) - seconds(start)
# filters
if filters:
filters = ['-vf', ','.join(filters)]
# Encode for video, image, etc?
if segment_type == 'video':
encoding_args = ['-i', input1,
'-ss', start, '-to', stop,
*(FFMPEG_VIDEO_ENCODE if (args.reencode and allow_reencode) or filters else FFMPEG_VIDEO_COPY),
*FFMPEG_AUDIO_COPY,
]
if seconds(start) > seconds(stop):
raise RuntimeError(f"start is greater than stop time ({start} > {stop} time in {segment.get('title')}")
elif segment_type == 'image':
# https://trac.ffmpeg.org/wiki/Slideshow
encoding_args = ['-loop', '1',
'-i', input1,
'-t', str(command['duration']),
'-vf', f'fps={FFMPEG_FRAMERATE},format=yuv420p',
'-c:v', 'libx264', ]#'-r', str(FFMPEG_FRAMERATE)]
else:
raise RuntimeError(f"unknown segment_type: {segment_type}")
# Do encoding
tmp_out = str(Path(tmpdir)/('tmpout-%02d.mkv'%i))
tmp_outputs.append(tmp_out)
cmd = ['ffmpeg', '-loglevel', str(LOGLEVEL),
*encoding_args,
*options_ffmpeg_output,
*options_ffmpeg_segment,
*filters,
tmp_out,
]
LOG.info(shell_join(cmd))
if not args.check:
subprocess.check_call(cmd)
# Subtitles?
if args.srt:
sub_file = os.path.splitext(input1)[0] + '.srt'
start_dt = timedelta(seconds=seconds(start))
end_dt = timedelta(seconds=seconds(stop))
start_cumulative_dt = timedelta(seconds=start_cumulative)
duration_segment_dt = end_dt-start_dt
for sub in srt.parse(open(sub_file).read()):
if sub.end < start_dt: continue
if sub.start > end_dt: continue
sub = copy.copy(sub)
sub.start = sub.start - start_dt + start_cumulative_dt
sub.end = sub.end - start_dt + start_cumulative_dt
sub.start = max(sub.start, start_cumulative_dt)
sub.end = min(sub.end, start_cumulative_dt + duration_segment_dt)
subtitles.append(sub)
# Reset for the next round
filters = [ ]
options_ffmpeg_segment = [ ]
segment_type = 'video'
# Create the playlist of inputs
playlist = Path(tmpdir) / 'playlist.txt'
with open(playlist, 'w') as playlist_f:
for file_ in tmp_outputs:
playlist_f.write('file '+str(file_)+'\n')
LOG.debug("Playlist:")
LOG.debug(open(playlist).read())
# Re-encode
output = args.output / segment['output']
ensure_filedir_exists(output)
if output in all_inputs:
raise RuntimeError("Output is the same as an input file, aborting.")
tmpdir_out = str(Path(tmpdir)/('final-'+segment['output'].replace('/', '%2F')))
cmd = ['ffmpeg', '-loglevel', str(LOGLEVEL),
#*itertools.chain.from_iterable(('-i', x) for x in tmp_outputs),
#'-i', 'concat:'+'|'.join(tmp_outputs),
'-safe', '0', '-f', 'concat', '-i', playlist,
'-fflags', '+igndts',
'-c', 'copy',
*(['-y'] if args.force else []),
tmpdir_out,
]
LOG.info(shell_join(cmd))
if not args.check:
subprocess.check_call(cmd)
# We need another copy, since ffmpeg detects output based on filename. Yet for atomicness, we need a temporary filename for the temp part
if not args.check:
with atomic_write(output) as tmp_output:
shutil.move(tmpdir_out, tmp_output)
# Subtitles
if args.srt:
srt_output = os.path.splitext(output)[0] + '.srt'
open(srt_output, 'w').write(srt.compose(subtitles))
# Print table of contents
import pprint
LOG.debug(pprint.pformat(segment_list))
LOG.debug(pprint.pformat(TOC))
video_description = [ ]
if segment.get('title'):
title = segment['title']
if workshop_title is not None:
title = title + ' - ' + workshop_title
video_description.extend([title.strip()])
if segment.get('description'):
video_description.extend([segment['description'].strip().replace('\n', '\n\n')])
# Print out the table of contents
#video_description.append('\n')
toc = [ ]
for seg_n, time, name in TOC:
LOG.debug("TOC entry %s %s", time, name)
new_time = map_time(seg_n, segment_list, time)
print(humantime(new_time), name)
toc.append(f"{humantime(new_time)} {name}")
if toc:
video_description.append('\n'.join(toc))
if workshop_description:
video_description.append('-----')
video_description.append(workshop_description.replace('\n', '\n\n').strip())
if video_description:
with atomic_write(os.path.splitext(str(output))[0]+'.info.txt', 'w') as toc_file:
open(toc_file, 'w').write('\n\n'.join(video_description))
# Print out covered segments (for verification purposes)
for seg_n, time in covers:
new_time = map_time(seg_n, segment_list, time)
LOG.info("Check cover at %s", humantime(new_time))
if args.wait:
input('press return to continue> ')
| (argv=['--package', 'ffmpeg-editlist', '--s3_bucket', '/data']) |
11,245 | ffmpeg_editlist | map_time | Map a time from source time to output time
| def map_time(seg_n, lookup_table, time):
"""Map a time from source time to output time
"""
time_lookup_vals = [(x[0], x[1]) for x in lookup_table]
i = bisect.bisect_right(time_lookup_vals, (seg_n, time))
#print(f"lookup of {seg_n},{time} found at i={i}")
if lookup_table[i-1][1] is None:
#LOG.error("%s", lookup_table)
#LOG.error("%s", time)
LOG.error("Bad time lookup (type 1) for %s(=%ss)", humantime(time), time)
sys.exit(1)
if lookup_table[i-1][2] is None:
#LOG.error("%s", lookup_table)
#LOG.error("%s", time)
LOG.error("Bad time lookup (type 2) for %s(=%ss)", humantime(time), time)
sys.exit(1)
return time - lookup_table[i-1][1] + lookup_table[i-1][2]
| (seg_n, lookup_table, time) |
11,248 | ffmpeg_editlist | seconds | Convert HH:MM:SS.SS or S to seconds | def seconds(x):
"""Convert HH:MM:SS.SS or S to seconds"""
if isinstance(x, (int, float)):
return x
x = x.split(':')
sec = float(x[-1])
if len(x) >= 2:
sec += float(x[-2]) * 60
if len(x) >= 3:
sec += float(x[-3]) * 3600
return sec
| (x) |
11,249 | ffmpeg_editlist | shell_join | null | def shell_join(x):
return ' '.join(shlex.quote(str(_)) for _ in x)
| (x) |
11,255 | ffmpeg_editlist | test_humantime | null | def test_humantime():
assert humantime(30) == "00:30"
assert humantime(90) == "01:30"
assert humantime(150) == "02:30"
assert humantime(3690) == "1:01:30"
assert humantime(3690.5) == "1:01:30"
assert humantime(7350) == "2:02:30"
assert humantime(43950) == "12:12:30"
| () |
11,256 | ffmpeg_editlist | test_is_time | null | def test_is_time():
assert is_time('10')
assert is_time('10.')
assert is_time('10:10.5')
assert is_time('10:10:10.5')
assert not is_time('1e5')
assert not is_time('string')
assert not is_time('.5')
assert not is_time('Exercise: aoeu')
| () |
11,257 | ffmpeg_editlist | test_seconds | null | def test_seconds():
assert seconds(30) == 30
assert seconds(30.5) == 30.5
assert seconds('30') == 30
assert seconds('1:30') == 90
assert seconds('1:1:30') == 3690
assert seconds('1:1:30.5') == 3690.5
| () |
11,260 | rarfile | AES_CBC_Decrypt | Decrypt API | class AES_CBC_Decrypt:
"""Decrypt API"""
def __init__(self, key, iv):
if _have_crypto == 2:
self.decrypt = AES.new(key, AES.MODE_CBC, iv).decrypt
else:
ciph = Cipher(algorithms.AES(key), modes.CBC(iv), default_backend())
self.decrypt = ciph.decryptor().update
| (key, iv) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.