_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q4800 | PDBParser.get_linkage | train | def get_linkage(self, line):
"""Get the linkage information from a LINK entry PDB line."""
conf1, id1, chain1, pos1 = line[16].strip(), line[17:20].strip(), line[21].strip(), int(line[22:26])
conf2, id2, chain2, pos2 = line[46].strip(), line[47:50].strip(), line[51].strip(), int(line[52:56]) | python | {
"resource": ""
} |
q4801 | LigandFinder.getpeptides | train | def getpeptides(self, chain):
"""If peptide ligand chains are defined via the command line options,
try to extract the underlying ligand formed by all residues in the
given chain without water
"""
all_from_chain = [o for o in pybel.ob.OBResidueIter(
self.proteincomplex.OBMol) if o.GetChain() == chain] # All residues from chain
| python | {
"resource": ""
} |
q4802 | LigandFinder.getligs | train | def getligs(self):
"""Get all ligands from a PDB file and prepare them for analysis.
Returns all non-empty ligands.
"""
if config.PEPTIDES == [] and config.INTRA is None:
# Extract small molecule ligands (default)
ligands = []
# Filter for ligands using lists
ligand_residues, self.lignames_all, self.water = self.filter_for_ligands()
all_res_dict = {(a.GetName(), a.GetChain(), a.GetNum()): a for a in ligand_residues}
self.lignames_kept = list(set([a.GetName() for a in ligand_residues]))
if not config.BREAKCOMPOSITE:
# Update register of covalent links with those between DNA/RNA subunits
self.covalent += nucleotide_linkage(all_res_dict)
# Find fragment linked by covalent bonds
res_kmers = self.identify_kmers(all_res_dict)
else:
res_kmers = [[a, ] for a in ligand_residues]
write_message("{} ligand kmer(s) detected for closer inspection.\n".format(len(res_kmers)), mtype='debug')
for kmer in res_kmers: # iterate over all ligands and extract molecules + information
if len(kmer) > config.MAX_COMPOSITE_LENGTH:
write_message("Ligand kmer(s) filtered out with a length of {} fragments ({} allowed).\n".format(
| python | {
"resource": ""
} |
q4803 | LigandFinder.is_het_residue | train | def is_het_residue(self, obres):
"""Given an OBResidue, determines if the residue is indeed a possible ligand
in the PDB file"""
if not obres.GetResidueProperty(0):
# If the residue is NOT amino (0)
# It can be amino_nucleo, coenzme, ion, nucleo, protein, purine, pyrimidine, solvent
# In these cases, it is a ligand candidate
return True
else:
# Here, the residue is classified as amino
# Amino acids can still be ligands, so we check for | python | {
"resource": ""
} |
q4804 | LigandFinder.filter_for_ligands | train | def filter_for_ligands(self):
"""Given an OpenBabel Molecule, get all ligands, their names, and water"""
candidates1 = [o for o in pybel.ob.OBResidueIter(
self.proteincomplex.OBMol) if not o.GetResidueProperty(9) and self.is_het_residue(o)]
if config.DNARECEPTOR: # If DNA is the receptor, don't consider DNA as a ligand
candidates1 = [res for res in candidates1 if res.GetName() not in config.DNA+config.RNA]
all_lignames = set([a.GetName() for a in candidates1])
water = [o for o in pybel.ob.OBResidueIter(self.proteincomplex.OBMol) if o.GetResidueProperty(9)]
# Filter out non-ligands
if not config.KEEPMOD: # Keep modified residues as ligands
candidates2 = [a for a in candidates1 if is_lig(a.GetName()) and a.GetName() not in self.modresidues]
else:
candidates2 = [a for a in candidates1 if is_lig(a.GetName())]
| python | {
"resource": ""
} |
q4805 | Mapper.id_to_atom | train | def id_to_atom(self, idx):
"""Returns the atom for a given original ligand ID.
To do this, the ID is mapped to the protein first and then the atom returned.
""" | python | {
"resource": ""
} |
q4806 | Mol.find_hba | train | def find_hba(self, all_atoms):
"""Find all possible hydrogen bond acceptors"""
data = namedtuple('hbondacceptor', 'a a_orig_atom a_orig_idx type')
a_set = []
for atom in filter(lambda at: at.OBAtom.IsHbondAcceptor(), all_atoms):
if atom.atomicnum not in [9, 17, 35, 53] and atom.idx not in self.altconf: # Exclude halogen atoms
| python | {
"resource": ""
} |
q4807 | Mol.find_rings | train | def find_rings(self, mol, all_atoms):
"""Find rings and return only aromatic.
Rings have to be sufficiently planar OR be detected by OpenBabel as aromatic."""
data = namedtuple('aromatic_ring', 'atoms orig_atoms atoms_orig_idx normal obj center type')
rings = []
aromatic_amino = ['TYR', 'TRP', 'HIS', 'PHE']
ring_candidates = mol.OBMol.GetSSSR()
write_message("Number of aromatic ring candidates: %i\n" % len(ring_candidates), mtype="debug")
# Check here first for ligand rings not being detected as aromatic by Babel and check for planarity
for ring in ring_candidates:
r_atoms = [a for a in all_atoms if ring.IsMember(a.OBAtom)]
if 4 < len(r_atoms) <= 6:
res = list(set([whichrestype(a) for a in r_atoms]))
if ring.IsAromatic() or res[0] in aromatic_amino or ring_is_planar(ring, r_atoms):
# Causes segfault with OpenBabel 2.3.2, so deactivated
# typ = ring.GetType() if not ring.GetType() == '' else 'unknown'
# Alternative typing
typ = '%s-membered' % len(r_atoms)
ring_atms = [r_atoms[a].coords for a in [0, 2, 4]] # Probe atoms for | python | {
"resource": ""
} |
q4808 | PLInteraction.find_unpaired_ligand | train | def find_unpaired_ligand(self):
"""Identify unpaired functional in groups in ligands, involving H-Bond donors, acceptors, halogen bond donors.
"""
unpaired_hba, unpaired_hbd, unpaired_hal = [], [], []
# Unpaired hydrogen bond acceptors/donors in ligand (not used for hydrogen bonds/water, salt bridges/mcomplex)
involved_atoms = [hbond.a.idx for hbond in self.hbonds_pdon] + [hbond.d.idx for hbond in self.hbonds_ldon]
[[involved_atoms.append(atom.idx) for atom in sb.negative.atoms] for sb in self.saltbridge_lneg]
[[involved_atoms.append(atom.idx) for atom in sb.positive.atoms] for sb in self.saltbridge_pneg]
[involved_atoms.append(wb.a.idx) for wb in self.water_bridges if wb.protisdon]
[involved_atoms.append(wb.d.idx) for wb in self.water_bridges if not wb.protisdon]
[involved_atoms.append(mcomplex.target.atom.idx) for mcomplex in self.metal_complexes
if mcomplex.location == 'ligand']
for atom in [hba.a for hba in self.ligand.get_hba()]:
| python | {
"resource": ""
} |
q4809 | PLInteraction.refine_hbonds_ldon | train | def refine_hbonds_ldon(self, all_hbonds, salt_lneg, salt_pneg):
"""Refine selection of hydrogen bonds. Do not allow groups which already form salt bridges to form H-Bonds."""
i_set = {}
for hbond in all_hbonds:
i_set[hbond] = False
for salt in salt_pneg:
protidx, ligidx = [at.idx for at in salt.negative.atoms], [at.idx for at in salt.positive.atoms]
if hbond.d.idx in ligidx and hbond.a.idx in protidx:
i_set[hbond] = True
for salt in salt_lneg:
protidx, ligidx = [at.idx for at in salt.positive.atoms], [at.idx for at in salt.negative.atoms]
if hbond.d.idx in ligidx and hbond.a.idx in protidx:
| python | {
"resource": ""
} |
q4810 | PLInteraction.refine_pi_cation_laro | train | def refine_pi_cation_laro(self, all_picat, stacks):
"""Just important for constellations with histidine involved. If the histidine ring is positioned in stacking
position to an aromatic ring in the ligand, there is in most cases stacking and pi-cation interaction reported
as histidine also carries a positive charge in the ring. For such cases, only report stacking.
"""
i_set = []
for picat in all_picat:
exclude = False
| python | {
"resource": ""
} |
q4811 | PLInteraction.refine_water_bridges | train | def refine_water_bridges(self, wbridges, hbonds_ldon, hbonds_pdon):
"""A donor atom already forming a hydrogen bond is not allowed to form a water bridge. Each water molecule
can only be donor for two water bridges, selecting the constellation with the omega angle closest to 110 deg."""
donor_atoms_hbonds = [hb.d.idx for hb in hbonds_ldon + hbonds_pdon]
wb_dict = {}
wb_dict2 = {}
omega = 110.0
# Just one hydrogen bond per donor atom
for wbridge in [wb for wb in wbridges if wb.d.idx not in donor_atoms_hbonds]:
if (wbridge.water.idx, wbridge.a.idx) not in wb_dict:
wb_dict[(wbridge.water.idx, wbridge.a.idx)] = wbridge
else:
if abs(omega - wb_dict[(wbridge.water.idx, wbridge.a.idx)].w_angle) < abs(omega - wbridge.w_angle):
wb_dict[(wbridge.water.idx, wbridge.a.idx)] = wbridge
for wb_tuple in wb_dict:
water, acceptor = wb_tuple
if water not in wb_dict2:
wb_dict2[water] = [(abs(omega - wb_dict[wb_tuple].w_angle), wb_dict[wb_tuple]), ]
elif | python | {
"resource": ""
} |
q4812 | BindingSite.find_charged | train | def find_charged(self, mol):
"""Looks for positive charges in arginine, histidine or lysine, for negative in aspartic and glutamic acid."""
data = namedtuple('pcharge', 'atoms atoms_orig_idx type center restype resnr reschain')
a_set = []
# Iterate through all residue, exclude those in chains defined as peptides
for res in [r for r in pybel.ob.OBResidueIter(mol.OBMol) if not r.GetChain() in config.PEPTIDES]:
if config.INTRA is not None:
if res.GetChain() != config.INTRA:
continue
a_contributing = []
a_contributing_orig_idx = []
if res.GetName() in ('ARG', 'HIS', 'LYS'): # Arginine, Histidine or Lysine have charged sidechains
for a in pybel.ob.OBResidueAtomIter(res):
if a.GetType().startswith('N') and res.GetAtomProperty(a, 8) \
and not self.Mapper.mapid(a.GetIdx(), mtype='protein') in self.altconf:
a_contributing.append(pybel.Atom(a))
a_contributing_orig_idx.append(self.Mapper.mapid(a.GetIdx(), mtype='protein'))
if not len(a_contributing) == 0:
a_set.append(data(atoms=a_contributing,
atoms_orig_idx=a_contributing_orig_idx,
type='positive',
center=centroid([ac.coords for ac in a_contributing]),
restype=res.GetName(),
resnr=res.GetNum(),
reschain=res.GetChain()))
| python | {
"resource": ""
} |
q4813 | Ligand.is_functional_group | train | def is_functional_group(self, atom, group):
"""Given a pybel atom, look up if it belongs to a function group"""
n_atoms = [a_neighbor.GetAtomicNum() for a_neighbor in pybel.ob.OBAtomAtomIter(atom.OBAtom)]
if group in ['quartamine', 'tertamine'] and atom.atomicnum == 7: # Nitrogen
# It's a nitrogen, so could be a protonated amine or quaternary ammonium
if '1' not in n_atoms and len(n_atoms) == 4:
return True if group == 'quartamine' else False # It's a quat. ammonium (N with 4 residues != H)
elif atom.OBAtom.GetHyb() == 3 and len(n_atoms) >= 3:
return True if group == 'tertamine' else False # It's sp3-hybridized, so could pick up an hydrogen
else:
return False
if group in ['sulfonium', 'sulfonicacid', 'sulfate'] and atom.atomicnum == 16: # Sulfur
if '1' not in n_atoms and len(n_atoms) == 3: # It's a sulfonium (S with 3 residues != H)
return True if group == 'sulfonium' else False
elif n_atoms.count(8) == 3: # It's a sulfonate or sulfonic acid
return True if group == 'sulfonicacid' else False
elif n_atoms.count(8) == 4: # It's a sulfate
return True if group == 'sulfate' else False
if group == 'phosphate' and atom.atomicnum == 15: # Phosphor
if set(n_atoms) == {8}: # It's a phosphate | python | {
"resource": ""
} |
q4814 | PDBComplex.extract_bs | train | def extract_bs(self, cutoff, ligcentroid, resis):
"""Return list of ids from residues belonging | python | {
"resource": ""
} |
q4815 | url_info | train | def url_info(request):
"""
Make MEDIA_URL and current HttpRequest object
available in template code.
"""
return {
'MEDIA_URL' : core_settings.MEDIA_URL,
'STATIC_URL': core_settings.STATIC_URL,
| python | {
"resource": ""
} |
q4816 | RelatedManager.collect_related | train | def collect_related(self, finder_funcs, obj, count, *args, **kwargs):
"""
Collects objects related to ``obj`` using a list of ``finder_funcs``.
Stops when required count is collected or the function list is
| python | {
"resource": ""
} |
q4817 | RelatedManager.get_related_for_object | train | def get_related_for_object(self, obj, count, finder=None, mods=[], only_from_same_site=True):
"""
Returns at most ``count`` publishable objects related to ``obj`` using
named related finder ``finder``.
If only specific type of publishable is prefered, use ``mods`` attribute
to list required classes.
Finally, use ``only_from_same_site`` if you don't want cross-site
| python | {
"resource": ""
} |
q4818 | ListingManager.get_listing | train | def get_listing(self, category=None, children=ListingHandler.NONE, count=10, offset=0, content_types=[], date_range=(), exclude=None, **kwargs):
"""
Get top objects for given category and potentionally also its child categories.
Params:
category - Category object to list objects for. None if any category will do
count - number of objects to output, defaults to 10
offset - starting with object number... 1-based
content_types - list of ContentTypes to list, if empty, object from all models are included
date_range - range for listing's publish_from field
**kwargs - rest of the parameter are passed to the queryset unchanged
"""
assert offset >= 0, "Offset must be a positive integer"
assert count >= 0, "Count must be a positive integer"
if not count:
return []
limit = offset + count
qset = self.get_listing_queryset(category, children, content_types, date_range, exclude, **kwargs)
# direct listings, we don't need to check for duplicates
if children == ListingHandler.NONE:
return qset[offset:limit]
seen = set()
out = []
| python | {
"resource": ""
} |
q4819 | do_author_listing | train | def do_author_listing(parser, token):
"""
Get N listing objects that were published by given author recently and optionally
omit a publishable object in results.
**Usage**::
{% author_listing <author> <limit> as <result> [omit <obj>] %}
**Parameters**::
================================== ================================================
Option Description
================================== ================================================
``author`` Author to load objects for.
``limit`` Maximum number of objects to store,
``result`` Store the resulting list in context under given
name.
================================== ================================================
**Examples**:: | python | {
"resource": ""
} |
q4820 | _Tb | train | def _Tb(P, S):
"""Procedure to calculate the boiling temperature of seawater
Parameters
----------
P : float
Pressure, [MPa]
S : float
Salinity, [kg/kg]
Returns
-------
Tb : float
Boiling temperature, [K]
References
----------
IAPWS, Advisory Note No. 5: Industrial Calculation of the Thermodynamic
Properties of Seawater, http://www.iapws.org/relguide/Advise5.html, Eq 7
"""
def f(T): | python | {
"resource": ""
} |
q4821 | _Tf | train | def _Tf(P, S):
"""Procedure to calculate the freezing temperature of seawater
Parameters
----------
P : float
Pressure, [MPa]
S : float
Salinity, [kg/kg]
Returns
-------
Tf : float
Freezing temperature, [K]
References
----------
IAPWS, Advisory Note No. 5: Industrial Calculation of the Thermodynamic
Properties of Seawater, http://www.iapws.org/relguide/Advise5.html, Eq 12
"""
| python | {
"resource": ""
} |
q4822 | _Triple | train | def _Triple(S):
"""Procedure to calculate the triple point pressure and temperature for
seawater
Parameters
----------
S : float
Salinity, [kg/kg]
Returns
-------
prop : dict
Dictionary with the triple point properties:
* Tt: Triple point temperature, [K]
* Pt: Triple point pressure, [MPa]
References
----------
IAPWS, Advisory Note No. 5: Industrial Calculation of the Thermodynamic
Properties of Seawater, http://www.iapws.org/relguide/Advise5.html, Eq 7
"""
def f(parr):
T, P = parr
pw = _Region1(T, P)
gw = pw["h"]-T*pw["s"] | python | {
"resource": ""
} |
q4823 | _OsmoticPressure | train | def _OsmoticPressure(T, P, S):
"""Procedure to calculate the osmotic pressure of seawater
Parameters
----------
T : float
Tmperature, [K]
P : float
Pressure, [MPa]
S : float
Salinity, [kg/kg]
Returns
-------
Posm : float
Osmotic pressure, [MPa]
References
----------
IAPWS, Advisory Note No. 5: Industrial Calculation of the Thermodynamic
Properties of Seawater, http://www.iapws.org/relguide/Advise5.html, Eq 15 | python | {
"resource": ""
} |
q4824 | _ThCond_SeaWater | train | def _ThCond_SeaWater(T, P, S):
"""Equation for the thermal conductivity of seawater
Parameters
----------
T : float
Temperature, [K]
P : float
Pressure, [MPa]
S : float
Salinity, [kg/kg]
Returns
-------
k : float
Thermal conductivity excess relative to that of the pure water, [W/mK]
Notes
------
Raise :class:`NotImplementedError` if input isn't in limit:
* 273.15 ≤ T ≤ 523.15
* 0 ≤ P ≤ 140
* 0 ≤ S ≤ 0.17
Examples
--------
>>> _ThCond_Seawater(293.15, 0.1, 0.035)
-0.00418604
References
----------
IAPWS, Guideline on the Thermal Conductivity of Seawater,
http://www.iapws.org/relguide/Seawater-ThCond.html
""" | python | {
"resource": ""
} |
q4825 | _solNa2SO4 | train | def _solNa2SO4(T, mH2SO4, mNaCl):
"""Equation for the solubility of sodium sulfate in aqueous mixtures of
sodium chloride and sulfuric acid
Parameters
----------
T : float
Temperature, [K]
mH2SO4 : float
Molality of sufuric acid, [mol/kg(water)]
mNaCl : float
Molality of sodium chloride, [mol/kg(water)]
Returns
-------
S : float
Molal solutility of sodium sulfate, [mol/kg(water)]
Notes
------
Raise :class:`NotImplementedError` if input isn't in limit:
* 523.15 ≤ T ≤ 623.15
* 0 ≤ mH2SO4 ≤ 0.75
* 0 ≤ mNaCl ≤ 2.25
Examples
--------
>>> _solNa2SO4(523.15, 0.25, 0.75)
2.68
| python | {
"resource": ""
} |
q4826 | _critNaCl | train | def _critNaCl(x):
"""Equation for the critical locus of aqueous solutions of sodium chloride
Parameters
----------
x : float
Mole fraction of NaCl, [-]
Returns
-------
prop : dict
A dictionary withe the properties:
* Tc: critical temperature, [K]
* Pc: critical pressure, [MPa]
* rhoc: critical density, [kg/m³]
Notes
------
Raise :class:`NotImplementedError` if input isn't in limit:
* 0 ≤ x ≤ 0.12
Examples
--------
>>> _critNaCl(0.1)
975.571016
References
----------
IAPWS, Revised Guideline on the Critical Locus of Aqueous Solutions of
Sodium Chloride, http://www.iapws.org/relguide/critnacl.html
"""
# Check input parameters
if x < 0 or x > 0.12:
raise NotImplementedError("Incoming out of bound")
T1 = Tc*(1 + 2.3e1*x - 3.3e2*x**1.5 - 1.8e3*x**2)
T2 = | python | {
"resource": ""
} |
q4827 | SeaWater._water | train | def _water(cls, T, P):
"""Get properties of pure water, Table4 pag 8"""
water = IAPWS95(P=P, T=T)
prop = {}
prop["g"] = water.h-T*water.s
prop["gt"] = -water.s
prop["gp"] = 1./water.rho
prop["gtt"] = -water.cp/T
prop["gtp"] = water.betas*water.cp/T
| python | {
"resource": ""
} |
q4828 | MEoS._saturation | train | def _saturation(self, T):
"""Saturation calculation for two phase search"""
rhoc = self._constants.get("rhoref", self.rhoc)
Tc = self._constants.get("Tref", self.Tc)
if T > Tc:
T = Tc
tau = Tc/T
rhoLo = self._Liquid_Density(T)
rhoGo = self._Vapor_Density(T)
def f(parr):
rhol, rhog = parr
deltaL = rhol/rhoc
deltaG = rhog/rhoc
phirL = _phir(tau, deltaL, self._constants)
phirG = _phir(tau, deltaG, self._constants)
phirdL = _phird(tau, deltaL, self._constants)
phirdG = _phird(tau, deltaG, self._constants)
Jl = deltaL*(1+deltaL*phirdL)
Jv = deltaG*(1+deltaG*phirdG)
| python | {
"resource": ""
} |
q4829 | MEoS._Helmholtz | train | def _Helmholtz(self, rho, T):
"""Calculated properties from helmholtz free energy and derivatives
Parameters
----------
rho : float
Density, [kg/m³]
T : float
Temperature, [K]
Returns
-------
prop : dict
Dictionary with calculated properties:
* fir: [-]
* fird: ∂fir/∂δ|τ
* firdd: ∂²fir/∂δ²|τ
* delta: Reducen density rho/rhoc, [-]
* P: Pressure, [kPa]
* h: Enthalpy, [kJ/kg]
* s: Entropy, [kJ/kgK]
* cv: Isochoric specific heat, [kJ/kgK]
* alfav: Thermal expansion coefficient, [1/K]
* betap: Isothermal compressibility, [1/kPa]
References
----------
IAPWS, Revised Release on the IAPWS Formulation 1995 for the
Thermodynamic Properties of Ordinary Water Substance for General and
Scientific Use, September 2016, Table | python | {
"resource": ""
} |
q4830 | MEoS._phi0 | train | def _phi0(self, tau, delta):
"""Ideal gas Helmholtz free energy and derivatives
Parameters
----------
tau : float
Inverse reduced temperature Tc/T, [-]
delta : float
Reduced density rho/rhoc, [-]
Returns
-------
prop : dictionary with ideal adimensional helmholtz energy and deriv
fio, [-]
fiot: ∂fio/∂τ|δ
fiod: ∂fio/∂δ|τ
fiott: ∂²fio/∂τ²|δ
fiodt: ∂²fio/∂τ∂δ
fiodd: ∂²fio/∂δ²|τ
References
----------
IAPWS, Revised Release on the IAPWS Formulation 1995 for the
Thermodynamic Properties of Ordinary Water Substance for General and
Scientific Use, September 2016, Table 4
http://www.iapws.org/relguide/IAPWS-95.html
"""
Fi0 = self.Fi0
fio = Fi0["ao_log"][0]*log(delta)+Fi0["ao_log"][1]*log(tau)
fiot = +Fi0["ao_log"][1]/tau
fiott = -Fi0["ao_log"][1]/tau**2
fiod = 1/delta
fiodd = -1/delta**2
fiodt = 0
for n, t in zip(Fi0["ao_pow"], Fi0["pow"]):
fio += n*tau**t
if t != 0:
| python | {
"resource": ""
} |
q4831 | MEoS._derivDimensional | train | def _derivDimensional(self, rho, T):
"""Calcule the dimensional form or Helmholtz free energy derivatives
Parameters
----------
rho : float
Density, [kg/m³]
T : float
Temperature, [K]
Returns
-------
prop : dict
Dictionary with residual helmholtz energy and derivatives:
* fir, [kJ/kg]
* firt: ∂fir/∂T|ρ, [kJ/kgK]
* fird: ∂fir/∂ρ|T, [kJ/m³kg²]
* firtt: ∂²fir/∂T²|ρ, [kJ/kgK²]
* firdt: ∂²fir/∂T∂ρ, [kJ/m³kg²K]
* firdd: ∂²fir/∂ρ²|T, [kJ/m⁶kg]
References
----------
IAPWS, Guideline on an Equation of State for Humid Air in Contact with
Seawater and Ice, Consistent with the IAPWS Formulation 2008 for the
Thermodynamic Properties of Seawater, Table 7,
http://www.iapws.org/relguide/SeaAir.html
"""
if not rho:
prop = {}
prop["fir"] = 0
prop["firt"] = 0
prop["fird"] = 0
prop["firtt"] = 0
prop["firdt"] = 0
prop["firdd"] = 0
| python | {
"resource": ""
} |
q4832 | MEoS._surface | train | def _surface(self, T):
"""Generic equation for the surface tension
Parameters
----------
T : float
Temperature, [K]
Returns
-------
σ : float
Surface tension, [N/m]
| python | {
"resource": ""
} |
q4833 | MEoS._Vapor_Pressure | train | def _Vapor_Pressure(cls, T):
"""Auxiliary equation for the vapour pressure
Parameters
----------
T : float
Temperature, [K]
Returns
-------
Pv : float
Vapour pressure, [Pa]
References
----------
IAPWS, Revised Supplementary Release on Saturation Properties of
Ordinary Water Substance | python | {
"resource": ""
} |
q4834 | MEoS._Liquid_Density | train | def _Liquid_Density(cls, T):
"""Auxiliary equation for the density of saturated liquid
Parameters
----------
T : float
Temperature, [K]
Returns
-------
rho : float
Saturated liquid density, [kg/m³]
References
----------
| python | {
"resource": ""
} |
q4835 | MEoS._Vapor_Density | train | def _Vapor_Density(cls, T):
"""Auxiliary equation for the density of saturated vapor
Parameters
----------
T : float
Temperature, [K]
Returns
-------
rho : float
Saturated vapor density, [kg/m³]
References
----------
| python | {
"resource": ""
} |
q4836 | _fugacity | train | def _fugacity(T, P, x):
"""Fugacity equation for humid air
Parameters
----------
T : float
Temperature, [K]
P : float
Pressure, [MPa]
x : float
Mole fraction of water-vapor, [-]
Returns
-------
fv : float
fugacity coefficient, [MPa]
Notes
------
Raise :class:`NotImplementedError` if input isn't in range of validity:
* 193 ≤ T ≤ 473
* 0 ≤ P ≤ 5
* 0 ≤ x ≤ 1
Really the xmax is the xsaturation but isn't implemented
Examples
--------
>>> _fugacity(300, 1, 0.1)
0.0884061686
References
----------
IAPWS, Guideline on a Virial Equation for the Fugacity of H2O in Humid Air,
http://www.iapws.org/relguide/VirialFugacity.html
"""
# Check input parameters
if T < 193 or T > 473 or P < 0 or P > 5 or | python | {
"resource": ""
} |
q4837 | MEoSBlend._bubbleP | train | def _bubbleP(cls, T):
"""Using ancillary equation return the pressure of bubble point"""
c = cls._blend["bubble"]
Tj = cls._blend["Tj"]
Pj = cls._blend["Pj"]
Tita = 1-T/Tj
suma = 0 | python | {
"resource": ""
} |
q4838 | HumidAir._eq | train | def _eq(self, T, P):
"""Procedure for calculate the composition in saturation state
Parameters
----------
T : float
Temperature [K]
P : float
Pressure [MPa]
Returns
-------
Asat : float
Saturation mass fraction of dry air in humid air [kg/kg]
"""
if T <= 273.16:
ice = _Ice(T, P)
gw = ice["g"]
else:
water = IAPWS95(T=T, P=P)
gw = water.g
def f(parr):
rho, a = parr
if a > 1:
| python | {
"resource": ""
} |
q4839 | HumidAir._prop | train | def _prop(self, T, rho, fav):
"""Thermodynamic properties of humid air
Parameters
----------
T : float
Temperature, [K]
rho : float
Density, [kg/m³]
fav : dict
dictionary with helmholtz energy and derivatives
Returns
-------
prop : dict
Dictionary with thermodynamic properties of humid air:
* P: Pressure, [MPa]
* s: Specific entropy, [kJ/kgK]
* cp: Specific isobaric heat capacity, [kJ/kgK]
* h: Specific enthalpy, [kJ/kg]
* g: Specific gibbs energy, [kJ/kg]
* alfav: Thermal expansion coefficient, [1/K]
* betas: Isentropic T-P coefficient, [K/MPa]
* xkappa: Isothermal compressibility, [1/MPa]
* ks: Isentropic compressibility, [1/MPa]
* w: Speed of sound, [m/s]
References
---------- | python | {
"resource": ""
} |
q4840 | HumidAir._coligative | train | def _coligative(self, rho, A, fav):
"""Miscelaneous properties of humid air
Parameters
----------
rho : float
Density, [kg/m³]
A : float
Mass fraction of dry air in humid air, [kg/kg]
fav : dict
dictionary with helmholtz energy and derivatives
Returns
-------
prop : dict
Dictionary with calculated properties:
* mu: Relative chemical potential, [kJ/kg]
* muw: Chemical potential of water, [kJ/kg]
* M: Molar mass of humid air, [g/mol]
* HR: Humidity ratio, [-]
* xa: Mole fraction of dry air, [-]
* xw: Mole fraction of water, [-]
References
----------
IAPWS, Guideline on an Equation of State for Humid Air in Contact with
Seawater and Ice, Consistent | python | {
"resource": ""
} |
q4841 | HumidAir._fav | train | def _fav(self, T, rho, A):
r"""Specific Helmholtz energy of humid air and derivatives
Parameters
----------
T : float
Temperature, [K]
rho : float
Density, [kg/m³]
A : float
Mass fraction of dry air in humid air, [kg/kg]
Returns
-------
prop : dict
Dictionary with helmholtz energy and derivatives:
* fir, [kJ/kg]
* fira: :math:`\left.\frac{\partial f_{av}}{\partial A}\right|_{T,\rho}`, [kJ/kg]
* firt: :math:`\left.\frac{\partial f_{av}}{\partial T}\right|_{A,\rho}`, [kJ/kgK]
* fird: :math:`\left.\frac{\partial f_{av}}{\partial \rho}\right|_{A,T}`, [kJ/m³kg²]
* firaa: :math:`\left.\frac{\partial^2 f_{av}}{\partial A^2}\right|_{T, \rho}`, [kJ/kg]
* firat: :math:`\left.\frac{\partial^2 f_{av}}{\partial A \partial T}\right|_{\rho}`, [kJ/kgK]
* firad: :math:`\left.\frac{\partial^2 f_{av}}{\partial A \partial \rho}\right|_T`, [kJ/m³kg²]
* firtt: :math:`\left.\frac{\partial^2 f_{av}}{\partial T^2}\right|_{A, \rho}`, [kJ/kgK²]
* firdt: :math:`\left.\frac{\partial^2 f_{av}}{\partial \rho \partial T}\right|_A`, [kJ/m³kg²K]
| python | {
"resource": ""
} |
q4842 | _Sublimation_Pressure | train | def _Sublimation_Pressure(T):
"""Sublimation Pressure correlation
Parameters
----------
T : float
Temperature, [K]
Returns
-------
P : float
Pressure at sublimation line, [MPa]
Notes
------
Raise :class:`NotImplementedError` if input isn't in limit:
* 50 ≤ T ≤ 273.16
Examples
--------
>>> _Sublimation_Pressure(230)
8.947352740189152e-06
References
----------
IAPWS, Revised Release on the Pressure along the Melting and Sublimation
Curves of Ordinary Water Substance, http://iapws.org/relguide/MeltSub.html.
"""
if 50 <= T <= 273.16:
Tita = T/Tt
| python | {
"resource": ""
} |
q4843 | _Melting_Pressure | train | def _Melting_Pressure(T, ice="Ih"):
"""Melting Pressure correlation
Parameters
----------
T : float
Temperature, [K]
ice: string
Type of ice: Ih, III, V, VI, VII.
Below 273.15 is a mandatory input, the ice Ih is the default value.
Above 273.15, the ice type is unnecesary.
Returns
-------
P : float
Pressure at sublimation line, [MPa]
Notes
------
Raise :class:`NotImplementedError` if input isn't in limit:
* 251.165 ≤ T ≤ 715
Examples
--------
>>> _Melting_Pressure(260)
8.947352740189152e-06
>>> _Melting_Pressure(254, "III")
268.6846466336108
References
----------
IAPWS, Revised Release on the Pressure along the Melting and Sublimation
Curves of Ordinary Water Substance, http://iapws.org/relguide/MeltSub.html.
"""
if ice == "Ih" and 251.165 <= T <= 273.16:
# Ice Ih
Tref = Tt
Pref = Pt
Tita = T/Tref
a = [0.119539337e7, 0.808183159e5, 0.33382686e4]
expo = [3., 0.2575e2, 0.10375e3]
suma = 1
for ai, expi in zip(a, expo):
suma += ai*(1-Tita**expi)
P = suma*Pref
elif | python | {
"resource": ""
} |
q4844 | _Tension | train | def _Tension(T):
"""Equation for the surface tension
Parameters
----------
T : float
Temperature, [K]
Returns
-------
σ : float
Surface tension, [N/m]
Notes
------
Raise :class:`NotImplementedError` if input isn't in limit:
* 248.15 ≤ T ≤ 647
* Estrapolate to -25ºC in supercooled | python | {
"resource": ""
} |
q4845 | _Dielectric | train | def _Dielectric(rho, T):
"""Equation for the Dielectric constant
Parameters
----------
rho : float
Density, [kg/m³]
T : float
Temperature, [K]
Returns
-------
epsilon : float
Dielectric constant, [-]
Notes
------
Raise :class:`NotImplementedError` if input isn't in limit:
* 238 ≤ T ≤ 1200
Examples
--------
>>> _Dielectric(999.242866, 298.15)
78.5907250
>>> _Dielectric(26.0569558, 873.15)
1.12620970
References
----------
IAPWS, Release on the Static Dielectric Constant of Ordinary Water
Substance for Temperatures from 238 K to 873 K and Pressures up to 1000
MPa, http://www.iapws.org/relguide/Dielec.html
"""
# Check input parameters
if T < 238 or T > 1200:
raise NotImplementedError("Incoming out of bound")
k = 1.380658e-23
Na = 6.0221367e23
alfa = 1.636e-40
epsilon0 = 8.854187817e-12
mu = 6.138e-30
d = rho/rhoc
Tr = Tc/T
I = [1, 1, 1, 2, 3, 3, 4, 5, 6, 7, 10, None]
J = [0.25, 1, 2.5, 1.5, 1.5, 2.5, 2, 2, 5, 0.5, 10, None]
n = | python | {
"resource": ""
} |
q4846 | _Refractive | train | def _Refractive(rho, T, l=0.5893):
"""Equation for the refractive index
Parameters
----------
rho : float
Density, [kg/m³]
T : float
Temperature, [K]
l : float, optional
Light Wavelength, [μm]
Returns
-------
n : float
Refractive index, [-]
Notes
------
Raise :class:`NotImplementedError` if input isn't in limit:
* 0 ≤ ρ ≤ 1060
* 261.15 ≤ T ≤ 773.15
* 0.2 ≤ λ ≤ 1.1
Examples
--------
>>> _Refractive(997.047435, 298.15, 0.2265)
1.39277824
>>> _Refractive(30.4758534, 773.15, 0.5893)
1.00949307
References
----------
IAPWS, Release on the Refractive Index of Ordinary Water Substance as a
Function of Wavelength, Temperature and Pressure,
http://www.iapws.org/relguide/rindex.pdf
"""
# Check input parameters
if | python | {
"resource": ""
} |
q4847 | _Kw | train | def _Kw(rho, T):
"""Equation for the ionization constant of ordinary water
Parameters
----------
rho : float
Density, [kg/m³]
T : float
Temperature, [K]
Returns
-------
pKw : float
Ionization constant in -log10(kw), [-]
Notes
------
Raise :class:`NotImplementedError` if input isn't in limit:
* 0 ≤ ρ ≤ 1250
* 273.15 ≤ T ≤ 1073.15
Examples
--------
>>> _Kw(1000, 300)
13.906565
References
----------
IAPWS, Release on the Ionization Constant of H2O,
http://www.iapws.org/relguide/Ionization.pdf
"""
# Check input parameters
if rho < 0 or rho > 1250 or T < 273.15 or T > 1073.15:
raise NotImplementedError("Incoming out of bound")
| python | {
"resource": ""
} |
q4848 | _D2O_Viscosity | train | def _D2O_Viscosity(rho, T):
"""Equation for the Viscosity of heavy water
Parameters
----------
rho : float
Density, [kg/m³]
T : float
Temperature, [K]
Returns
-------
μ : float
Viscosity, [Pa·s]
Examples
--------
>>> _D2O_Viscosity(998, 298.15)
0.0008897351001498108
>>> _D2O_Viscosity(600, 873.15)
7.743019522728247e-05
References
----------
IAPWS, Revised Release on Viscosity and Thermal Conductivity of Heavy
Water Substance, http://www.iapws.org/relguide/TransD2O-2007.pdf
"""
| python | {
"resource": ""
} |
q4849 | _D2O_ThCond | train | def _D2O_ThCond(rho, T):
"""Equation for the thermal conductivity of heavy water
Parameters
----------
rho : float
Density, [kg/m³]
T : float
Temperature, [K]
Returns
-------
k : float
Thermal conductivity, [W/mK]
Examples
--------
>>> _D2O_ThCond(998, 298.15)
0.6077128675880629
>>> _D2O_ThCond(0, 873.15)
0.07910346589648833
References
----------
IAPWS, Revised Release on Viscosity and Thermal Conductivity of Heavy
Water Substance, http://www.iapws.org/relguide/TransD2O-2007.pdf
"""
rhor = rho/358
Tr = T/643.847
tau = Tr/(abs(Tr-1.1)+1.1)
no = [1.0, 37.3223, 22.5485, 13.0465, 0.0, -2.60735]
Lo = sum([Li*Tr**i for i, Li in enumerate(no)])
nr = [483.656, -191.039, 73.0358, -7.57467]
| python | {
"resource": ""
} |
q4850 | _D2O_Sublimation_Pressure | train | def _D2O_Sublimation_Pressure(T):
"""Sublimation Pressure correlation for heavy water
Parameters
----------
T : float
Temperature, [K]
Returns
-------
P : float
Pressure at sublimation line, [MPa]
Notes
------
Raise :class:`NotImplementedError` if input isn't in limit:
* 210 ≤ T ≤ 276.969
Examples
--------
| python | {
"resource": ""
} |
q4851 | _D2O_Melting_Pressure | train | def _D2O_Melting_Pressure(T, ice="Ih"):
"""Melting Pressure correlation for heavy water
Parameters
----------
T : float
Temperature, [K]
ice: string
Type of ice: Ih, III, V, VI, VII.
Below 276.969 is a mandatory input, the ice Ih is the default value.
Above 276.969, the ice type is unnecesary.
Returns
-------
P : float
Pressure at melting line, [MPa]
Notes
------
Raise :class:`NotImplementedError` if input isn't in limit:
* 254.415 ≤ T ≤ 315
Examples
--------
>>> _D2O__Melting_Pressure(260)
8.947352740189152e-06
>>> _D2O__Melting_Pressure(254, "III")
268.6846466336108
References
----------
IAPWS, Revised Release on the Pressure along the Melting and Sublimation
Curves of Ordinary Water Substance, http://iapws.org/relguide/MeltSub.html.
"""
if ice == "Ih" and 254.415 <= T <= 276.969:
# Ice Ih, Eq 9
Tita = T/276.969
ai = [-0.30153e5, 0.692503e6]
ti = [5.5, 8.2]
suma = 1
for a, t in zip(ai, ti):
suma += a*(1-Tita**t) | python | {
"resource": ""
} |
q4852 | getphase | train | def getphase(Tc, Pc, T, P, x, region):
"""Return fluid phase string name
Parameters
----------
Tc : float
Critical temperature, [K]
Pc : float
Critical pressure, [MPa]
T : float
Temperature, [K]
P : float
Pressure, [MPa]
x : float
Quality, [-]
region: int
Region number, used only for IAPWS97 region definition
Returns
-------
phase : str
| python | {
"resource": ""
} |
q4853 | Region2_cp0 | train | def Region2_cp0(Tr, Pr):
"""Ideal properties for Region 2
Parameters
----------
Tr : float
Reduced temperature, [-]
Pr : float
Reduced pressure, [-]
Returns
-------
prop : array
Array with ideal Gibbs energy partial derivatives:
* g: Ideal Specific Gibbs energy [kJ/kg]
* gp: ∂g/∂P|T
* gpp: ∂²g/∂P²|T
* gt: ∂g/∂T|P
* gtt: ∂²g/∂T²|P
* gpt: ∂²g/∂T∂P
References
----------
IAPWS, Revised Release on the IAPWS Industrial Formulation 1997 for the
Thermodynamic Properties of Water and Steam August 2007,
http://www.iapws.org/relguide/IF97-Rev.html, Eq 16
"""
Jo = [0, 1, -5, -4, -3, -2, -1, 2, 3]
no = [-0.96927686500217E+01, 0.10086655968018E+02, -0.56087911283020E-02,
| python | {
"resource": ""
} |
q4854 | _Region4 | train | def _Region4(P, x):
"""Basic equation for region 4
Parameters
----------
P : float
Pressure, [MPa]
x : float
Vapor quality, [-]
Returns
-------
prop : dict
Dict with calculated properties. The available properties are:
* T: Saturated temperature, [K]
* P: Saturated pressure, [MPa]
* x: Vapor quality, [-]
* v: Specific volume, [m³/kg]
* h: Specific enthalpy, [kJ/kg]
* s: Specific entropy, [kJ/kgK]
| python | {
"resource": ""
} |
q4855 | _Bound_TP | train | def _Bound_TP(T, P):
"""Region definition for input T and P
Parameters
----------
T : float
Temperature, [K]
P : float
Pressure, [MPa]
Returns
-------
region : float
IAPWS-97 region code
References
----------
Wagner, W; Kretzschmar, H-J: International Steam Tables: Properties of
Water and Steam Based on the Industrial Formulation IAPWS-IF97; Springer,
2008; doi: 10.1007/978-3-540-74234-0. Fig. 2.3
"""
region = None
if 1073.15 < T <= 2273.15 and Pmin <= P <= 50:
region = 5
elif Pmin <= P <= Ps_623:
Tsat = _TSat_P(P)
| python | {
"resource": ""
} |
q4856 | _Bound_Ph | train | def _Bound_Ph(P, h):
"""Region definition for input P y h
Parameters
----------
P : float
Pressure, [MPa]
h : float
Specific enthalpy, [kJ/kg]
Returns
-------
region : float
IAPWS-97 region code
References
----------
Wagner, W; Kretzschmar, H-J: International Steam Tables: Properties of
Water and Steam Based on the Industrial Formulation IAPWS-IF97; Springer,
2008; doi: 10.1007/978-3-540-74234-0. Fig. 2.5
"""
region = None
if Pmin <= P <= Ps_623:
h14 = _Region1(_TSat_P(P), P)["h"]
h24 = _Region2(_TSat_P(P), P)["h"]
h25 = _Region2(1073.15, P)["h"]
hmin = _Region1(273.15, P)["h"]
hmax = _Region5(2273.15, P)["h"]
if hmin <= h <= h14:
region = 1
elif h14 < h < h24:
region | python | {
"resource": ""
} |
q4857 | _Bound_Ps | train | def _Bound_Ps(P, s):
"""Region definition for input P and s
Parameters
----------
P : float
Pressure, [MPa]
s : float
Specific entropy, [kJ/kgK]
Returns
-------
region : float
IAPWS-97 region code
References
----------
Wagner, W; Kretzschmar, H-J: International Steam Tables: Properties of
Water and Steam Based on the Industrial Formulation IAPWS-IF97; Springer,
2008; doi: 10.1007/978-3-540-74234-0. Fig. 2.9
"""
region = None
if Pmin <= P <= Ps_623:
smin = _Region1(273.15, P)["s"]
s14 = _Region1(_TSat_P(P), P)["s"]
s24 = _Region2(_TSat_P(P), P)["s"]
s25 = _Region2(1073.15, P)["s"]
smax = _Region5(2273.15, P)["s"]
if smin <= s <= s14:
region = 1
elif s14 < s < s24:
| python | {
"resource": ""
} |
q4858 | IAPWS97.calculable | train | def calculable(self):
"""Check if class is calculable by its kwargs"""
self._thermo = ""
if self.kwargs["T"] and self.kwargs["P"]:
self._thermo = "TP"
elif self.kwargs["P"] and self.kwargs["h"] is not None:
self._thermo = "Ph"
elif self.kwargs["P"] and self.kwargs["s"] is not None:
self._thermo = "Ps"
# TODO: Add other pairs definitions options
# elif self.kwargs["P"] and self.kwargs["v"]:
# self._thermo = "Pv"
# elif self.kwargs["T"] and self.kwargs["s"] is not None:
# | python | {
"resource": ""
} |
q4859 | Ttr | train | def Ttr(x):
"""Equation for the triple point of ammonia-water mixture
Parameters
----------
x : float
Mole fraction of ammonia in mixture, [mol/mol]
Returns
-------
Ttr : float
Triple point temperature, [K]
Notes
------
Raise :class:`NotImplementedError` if input isn't in limit:
* 0 ≤ x ≤ 1
References
----------
IAPWS, Guideline on the IAPWS | python | {
"resource": ""
} |
q4860 | H2ONH3._prop | train | def _prop(self, rho, T, x):
"""Thermodynamic properties of ammonia-water mixtures
Parameters
----------
T : float
Temperature [K]
rho : float
Density [kg/m³]
x : float
Mole fraction of ammonia in mixture [mol/mol]
Returns
-------
prop : dict
Dictionary with thermodynamic properties of ammonia-water mixtures:
* M: Mixture molecular mass, [g/mol]
* P: Pressure, [MPa]
* u: Specific internal energy, [kJ/kg]
* s: Specific entropy, [kJ/kgK]
* h: Specific enthalpy, [kJ/kg]
* a: Specific Helmholtz energy, [kJ/kg]
* g: Specific gibbs energy, [kJ/kg]
* cv: Specific isochoric heat capacity, [kJ/kgK]
* cp: Specific isobaric heat capacity, [kJ/kgK]
* w: Speed of sound, [m/s]
* fugH2O: Fugacity of water, [-]
* fugNH3: Fugacity of ammonia, [-]
References
----------
IAPWS, Guideline on the IAPWS Formulation 2001 for | python | {
"resource": ""
} |
q4861 | _preprocess_and_rename_grid_attrs | train | def _preprocess_and_rename_grid_attrs(func, grid_attrs=None, **kwargs):
"""Call a custom preprocessing method first then rename grid attrs.
This wrapper is needed to generate a single function to pass to the
``preprocesss`` of xr.open_mfdataset. It makes sure that the
user-specified preprocess function is called on the loaded Dataset before
aospy's is applied. An example for why this might be needed is output from
the WRF model; one needs to add a CF-compliant units attribute to the time
coordinate of all input files, because it is not present by default.
Parameters
----------
func : function
An arbitrary function to call before calling
``grid_attrs_to_aospy_names`` in ``_load_data_from_disk``. Must take
an xr.Dataset as an argument as well as ``**kwargs``.
grid_attrs : | python | {
"resource": ""
} |
q4862 | grid_attrs_to_aospy_names | train | def grid_attrs_to_aospy_names(data, grid_attrs=None):
"""Rename grid attributes to be consistent with aospy conventions.
Search all of the dataset's coords and dims looking for matches to known
grid attribute names; any that are found subsequently get renamed to the
aospy name as specified in ``aospy.internal_names.GRID_ATTRS``.
Also forces any renamed grid attribute that is saved as a dim without a
coord to have a coord, which facilitates subsequent slicing/subsetting.
This function does not compare to Model coordinates or add missing
coordinates from Model objects.
Parameters
----------
data : xr.Dataset
grid_attrs : dict (default None)
Overriding dictionary of grid attributes mapping aospy internal
names to names of grid attributes used in a particular model.
Returns
-------
xr.Dataset
Data returned with coordinates consistent with aospy
conventions
"""
if grid_attrs is None:
grid_attrs = {}
# Override GRID_ATTRS with entries in grid_attrs
attrs = GRID_ATTRS.copy()
for k, v in grid_attrs.items():
if k not in attrs:
| python | {
"resource": ""
} |
q4863 | set_grid_attrs_as_coords | train | def set_grid_attrs_as_coords(ds):
"""Set available grid attributes as coordinates in a given Dataset.
Grid attributes are assumed to have their internal aospy names. Grid
attributes are set as coordinates, such that they are carried by all
selected DataArrays with overlapping index dimensions.
Parameters
----------
ds : Dataset
Input data
| python | {
"resource": ""
} |
q4864 | _maybe_cast_to_float64 | train | def _maybe_cast_to_float64(da):
"""Cast DataArrays to np.float64 if they are of type np.float32.
Parameters
----------
da : xr.DataArray
Input DataArray
Returns
-------
DataArray
"""
if da.dtype == np.float32:
logging.warning('Datapoints were stored using the | python | {
"resource": ""
} |
q4865 | _sel_var | train | def _sel_var(ds, var, upcast_float32=True):
"""Select the specified variable by trying all possible alternative names.
Parameters
----------
ds : Dataset
Dataset possibly containing var
var : aospy.Var
Variable to find data for
upcast_float32 : bool (default True)
Whether to cast a float32 DataArray up to float64
Returns
-------
DataArray
Raises
------
KeyError
If the variable is not in the Dataset
"""
for name in var.names:
| python | {
"resource": ""
} |
q4866 | _prep_time_data | train | def _prep_time_data(ds):
"""Prepare time coordinate information in Dataset for use in aospy.
1. If the Dataset contains a time bounds coordinate, add attributes
representing the true beginning and end dates of the time interval used
to construct the Dataset
2. If the Dataset contains a time bounds coordinate, overwrite the time
coordinate values with the averages of the time bounds at each timestep
3. Decode the times into np.datetime64 objects for time indexing
Parameters
----------
ds : Dataset
Pre-processed Dataset with time coordinate renamed to
internal_names.TIME_STR
Returns
-------
Dataset
The processed Dataset
"""
ds = times.ensure_time_as_index(ds)
if TIME_BOUNDS_STR in ds:
ds = times.ensure_time_avg_has_cf_metadata(ds)
ds[TIME_STR] = times.average_time_bounds(ds)
else:
logging.warning("dt array not found. Assuming equally spaced "
"values in time, even though this may not be "
| python | {
"resource": ""
} |
q4867 | _load_data_from_disk | train | def _load_data_from_disk(file_set, preprocess_func=lambda ds: ds,
data_vars='minimal', coords='minimal',
grid_attrs=None, **kwargs):
"""Load a Dataset from a list or glob-string of files.
Datasets from files are concatenated along time,
and all grid attributes are renamed to their aospy internal names.
Parameters
----------
file_set : list or str
List of paths to files or glob-string
preprocess_func : function (optional)
Custom function to call before applying any aospy logic
to the loaded dataset
data_vars : str (default 'minimal')
Mode for concatenating data variables in call to ``xr.open_mfdataset``
coords : str (default 'minimal')
Mode for concatenating coordinate variables in call to
``xr.open_mfdataset``.
grid_attrs : dict
| python | {
"resource": ""
} |
q4868 | _setattr_default | train | def _setattr_default(obj, attr, value, default):
"""Set an attribute of an object to a value or default value."""
if value is None:
| python | {
"resource": ""
} |
q4869 | DataLoader.load_variable | train | def load_variable(self, var=None, start_date=None, end_date=None,
time_offset=None, grid_attrs=None, **DataAttrs):
"""Load a DataArray for requested variable and time range.
Automatically renames all grid attributes to match aospy conventions.
Parameters
----------
var : Var
aospy Var object
start_date : datetime.datetime
start date for interval
end_date : datetime.datetime
end date for interval
time_offset : dict
Option to add a time offset to the time coordinate to correct for
incorrect metadata.
grid_attrs : dict (optional)
Overriding dictionary of grid attributes mapping aospy internal
names to names of grid attributes used in a particular model.
**DataAttrs
Attributes needed to identify a unique set of files to load from
Returns
-------
da : DataArray
DataArray for the specified variable, date range, and interval in
"""
file_set = self._generate_file_set(var=var, start_date=start_date,
| python | {
"resource": ""
} |
q4870 | DataLoader._load_or_get_from_model | train | def _load_or_get_from_model(self, var, start_date=None, end_date=None,
time_offset=None, model=None, **DataAttrs):
"""Load a DataArray for the requested variable and time range
Supports both access of grid attributes either through the DataLoader
or through an optionally-provided Model object. Defaults to using
the version found in the DataLoader first.
"""
grid_attrs = None if model is None else model.grid_attrs
| python | {
"resource": ""
} |
q4871 | DataLoader.recursively_compute_variable | train | def recursively_compute_variable(self, var, start_date=None, end_date=None,
time_offset=None, model=None,
**DataAttrs):
"""Compute a variable recursively, loading data where needed.
An obvious requirement here is that the variable must eventually be
able to be expressed in terms of model-native quantities; otherwise the
recursion will never stop.
Parameters
----------
var : Var
aospy Var object
start_date : datetime.datetime
start date for interval
end_date : datetime.datetime
end date for interval
time_offset : dict
Option to add a time offset to the time coordinate to correct for
incorrect metadata.
model : Model
aospy Model object (optional)
**DataAttrs
Attributes needed to identify a unique set of files to load from
| python | {
"resource": ""
} |
q4872 | DataLoader._maybe_apply_time_shift | train | def _maybe_apply_time_shift(da, time_offset=None, **DataAttrs):
"""Apply specified time shift to DataArray"""
if time_offset is not None:
| python | {
"resource": ""
} |
q4873 | DictDataLoader._generate_file_set | train | def _generate_file_set(self, var=None, start_date=None, end_date=None,
domain=None, intvl_in=None, dtype_in_vert=None,
dtype_in_time=None, intvl_out=None):
"""Returns the file_set for the given interval in."""
try:
| python | {
"resource": ""
} |
q4874 | GFDLDataLoader._maybe_apply_time_shift | train | def _maybe_apply_time_shift(da, time_offset=None, **DataAttrs):
"""Correct off-by-one error in GFDL instantaneous model data.
Instantaneous data that is outputted by GFDL models is generally off by
one timestep. For example, a netCDF file that is supposed to
correspond to 6 hourly data for the month of January, will have its
last time value be in February.
"""
if time_offset is not None:
time = times.apply_time_offset(da[TIME_STR], **time_offset)
da[TIME_STR] = time
else:
| python | {
"resource": ""
} |
q4875 | Var.to_plot_units | train | def to_plot_units(self, data, dtype_vert=False):
"""Convert the given data to plotting units."""
if dtype_vert == 'vert_av' or not dtype_vert:
conv_factor = self.units.plot_units_conv
elif dtype_vert == ('vert_int'):
conv_factor = self.units.vert_int_plot_units_conv
| python | {
"resource": ""
} |
q4876 | Var.mask_unphysical | train | def mask_unphysical(self, data):
"""Mask data array where values are outside physically valid range."""
if not self.valid_range:
return data
else:
return | python | {
"resource": ""
} |
q4877 | to_radians | train | def to_radians(arr, is_delta=False):
"""Force data with units either degrees or radians to be radians."""
# Infer the units from embedded metadata, if it's there.
try:
units = arr.units
except AttributeError:
pass
else:
if units.lower().startswith('degrees'):
warn_msg = ("Conversion applied: degrees -> radians to array: "
"{}".format(arr))
logging.debug(warn_msg)
return np.deg2rad(arr)
# Otherwise, assume degrees if the values are sufficiently large. | python | {
"resource": ""
} |
q4878 | to_pascal | train | def to_pascal(arr, is_dp=False):
"""Force data with units either hPa or Pa to be in Pa."""
threshold = 400 if is_dp else 1200
if np.max(np.abs(arr)) < threshold:
warn_msg | python | {
"resource": ""
} |
q4879 | replace_coord | train | def replace_coord(arr, old_dim, new_dim, new_coord):
"""Replace a coordinate with new one; new and old must have same shape."""
| python | {
"resource": ""
} |
q4880 | to_pfull_from_phalf | train | def to_pfull_from_phalf(arr, pfull_coord):
"""Compute data at full pressure levels from values at half levels."""
phalf_top = arr.isel(**{internal_names.PHALF_STR: slice(1, None)})
phalf_top = replace_coord(phalf_top, internal_names.PHALF_STR,
internal_names.PFULL_STR, pfull_coord)
| python | {
"resource": ""
} |
q4881 | to_phalf_from_pfull | train | def to_phalf_from_pfull(arr, val_toa=0, val_sfc=0):
"""Compute data at half pressure levels from values at full levels.
Could be the pressure array itself, but it could also be any other data
| python | {
"resource": ""
} |
q4882 | pfull_from_ps | train | def pfull_from_ps(bk, pk, ps, pfull_coord):
"""Compute pressure at full levels from surface pressure."""
return | python | {
"resource": ""
} |
q4883 | d_deta_from_phalf | train | def d_deta_from_phalf(arr, pfull_coord):
"""Compute pressure level thickness from half level pressures."""
d_deta = arr.diff(dim=internal_names.PHALF_STR, n=1)
return replace_coord(d_deta, | python | {
"resource": ""
} |
q4884 | dp_from_ps | train | def dp_from_ps(bk, pk, ps, pfull_coord):
"""Compute pressure level thickness from surface pressure"""
return | python | {
"resource": ""
} |
q4885 | integrate | train | def integrate(arr, ddim, dim=False, is_pressure=False):
"""Integrate along the given dimension."""
if is_pressure:
dim | python | {
"resource": ""
} |
q4886 | get_dim_name | train | def get_dim_name(arr, names):
"""Determine if an object has an attribute name matching a given list."""
for name in names:
# TODO: raise warning/exception when multiple | python | {
"resource": ""
} |
q4887 | int_dp_g | train | def int_dp_g(arr, dp):
"""Mass weighted integral."""
return | python | {
"resource": ""
} |
q4888 | dp_from_p | train | def dp_from_p(p, ps, p_top=0., p_bot=1.1e5):
"""Get level thickness of pressure data, incorporating surface pressure.
Level edges are defined as halfway between the levels, as well as the user-
specified uppermost and lowermost values. The dp of levels whose bottom
pressure is less than the surface pressure is not changed by ps, since they
don't intersect the surface. If ps is in between a level's top and bottom
pressures, then its dp becomes the pressure difference between its top and
ps. If ps is less than a level's top and bottom pressures, then that level
is underground and its values are masked.
Note that postprocessing routines (e.g. at GFDL) typically mask out data
wherever the surface pressure is less than the level's given value, not the
level's upper edge. This masks out more levels than the
"""
p_str = get_dim_name(p, (internal_names.PLEVEL_STR, 'plev'))
p_vals = to_pascal(p.values.copy())
# Layer edges are halfway between the given pressure levels.
p_edges_interior = 0.5*(p_vals[:-1] + p_vals[1:])
p_edges = np.concatenate(([p_bot], p_edges_interior, [p_top]))
p_edge_above = p_edges[1:]
p_edge_below = p_edges[:-1]
dp = p_edge_below - p_edge_above
if not all(np.sign(dp)):
raise ValueError("dp array not all > 0 : {}".format(dp))
# Pressure difference between ps and the upper edge of each pressure level.
p_edge_above_xr = xr.DataArray(p_edge_above, dims=p.dims, coords=p.coords)
dp_to_sfc = ps - p_edge_above_xr
# Find the level adjacent to the masked, under-ground levels.
change = xr.DataArray(np.zeros(dp_to_sfc.shape), dims=dp_to_sfc.dims,
coords=dp_to_sfc.coords)
change[{p_str: slice(1, None)}] = np.diff(
np.sign(ps - to_pascal(p.copy()))
| python | {
"resource": ""
} |
q4889 | level_thickness | train | def level_thickness(p, p_top=0., p_bot=1.01325e5):
"""
Calculates the thickness, in Pa, of each pressure level.
Assumes that the pressure values given are at the center of that model
level, except for the lowest value (typically 1000 hPa), which is the
bottom boundary. The uppermost level extends to 0 hPa.
Unlike `dp_from_p`, this does not incorporate the surface pressure.
"""
p_vals = to_pascal(p.values.copy())
dp_vals = np.empty_like(p_vals)
# Bottom level extends from p[0] to halfway | python | {
"resource": ""
} |
q4890 | does_coord_increase_w_index | train | def does_coord_increase_w_index(arr):
"""Determine if the array values increase with the index.
Useful, e.g., for pressure, which sometimes is indexed surface to TOA and
sometimes the opposite.
"""
diff = np.diff(arr)
if not np.all(np.abs(np.sign(diff))):
raise | python | {
"resource": ""
} |
q4891 | apply_time_offset | train | def apply_time_offset(time, years=0, months=0, days=0, hours=0):
"""Apply a specified offset to the given time array.
This is useful for GFDL model output of instantaneous values. For example,
3 hourly data postprocessed to netCDF files spanning 1 year each will
actually have time values that are offset by 3 hours, such that the first
value is for 1 Jan 03:00 and the last value is 1 Jan 00:00 of the
subsequent year. This causes problems in xarray, e.g. when trying to group
by month. It is resolved by manually subtracting off those three hours,
such that the dates span from 1 Jan 00:00 to 31 Dec 21:00 as desired.
Parameters
----------
time : xarray.DataArray representing a timeseries
years, months, days, hours : int, optional
The number of years, months, days, and hours, respectively, to offset
the time array by. Positive values move the times later.
Returns
| python | {
"resource": ""
} |
q4892 | average_time_bounds | train | def average_time_bounds(ds):
"""Return the average of each set of time bounds in the Dataset.
Useful for creating a new time array to replace the Dataset's native time
array, in the case that the latter matches either the start or end bounds.
This can cause errors in grouping (akin to an off-by-one error) if the
timesteps span e.g. one full month each. Note that the Dataset's times
must not have already undergone "CF decoding", wherein they are converted
from floats using the 'units' attribute into datetime objects.
Parameters
----------
ds : xarray.Dataset
A Dataset containing a time bounds array with name matching
internal_names.TIME_BOUNDS_STR. This time bounds array must have two
dimensions, one of which's coordinates is the Dataset's time array, | python | {
"resource": ""
} |
q4893 | monthly_mean_at_each_ind | train | def monthly_mean_at_each_ind(monthly_means, sub_monthly_timeseries):
"""Copy monthly mean over each time index in that month.
Parameters
----------
monthly_means : xarray.DataArray
array of monthly means
sub_monthly_timeseries : xarray.DataArray
array of a timeseries at sub-monthly time resolution
Returns
-------
xarray.DataArray with eath monthly mean value from `monthly_means` repeated
at each time within that month from `sub_monthly_timeseries`
See Also
--------
| python | {
"resource": ""
} |
q4894 | yearly_average | train | def yearly_average(arr, dt):
"""Average a sub-yearly time-series over each year.
Resulting timeseries comprises one value for each year in which the
original array had valid data. Accounts for (i.e. ignores) masked values
in original data when computing the annual averages.
Parameters
----------
arr : xarray.DataArray
The array to be averaged
dt : xarray.DataArray
Array of the duration of each timestep
Returns
-------
xarray.DataArray
Has the same shape and mask as the original ``arr``, except for the
time dimension, which is | python | {
"resource": ""
} |
q4895 | ensure_datetime | train | def ensure_datetime(obj):
"""Return the object if it is a datetime-like object
Parameters
----------
obj : Object to be tested.
Returns
-------
The original object if it is a datetime-like object
Raises
------
TypeError if `obj` is not datetime-like
"""
_VALID_TYPES = (str, datetime.datetime, cftime.datetime,
| python | {
"resource": ""
} |
q4896 | month_indices | train | def month_indices(months):
"""Convert string labels for months to integer indices.
Parameters
----------
months : str, int
If int, number of the desired month, where January=1, February=2,
etc. If str, must match either 'ann' or some subset of
'jfmamjjasond'. If 'ann', use all months. Otherwise, use the
specified months.
Returns
-------
np.ndarray of integers corresponding to desired month indices
Raises
------
TypeError : If `months` is not an int or str
See also
--------
_month_conditional
"""
if not isinstance(months, (int, str)):
raise TypeError("`months` must be of type int or str: "
"type(months) == {}".format(type(months)))
if isinstance(months, int):
return [months]
if months.lower() == 'ann':
| python | {
"resource": ""
} |
q4897 | _month_conditional | train | def _month_conditional(time, months):
"""Create a conditional statement for selecting data in a DataArray.
Parameters
----------
time : xarray.DataArray
Array of times for which to subsample for specific months.
months : int, str, or xarray.DataArray of times
| python | {
"resource": ""
} |
q4898 | extract_months | train | def extract_months(time, months):
"""Extract times within specified months of the year.
Parameters
----------
time : xarray.DataArray
Array of times that can be represented by numpy.datetime64 objects
(i.e. the year is between 1678 and 2262).
months : Desired months of the year to include
| python | {
"resource": ""
} |
q4899 | ensure_time_avg_has_cf_metadata | train | def ensure_time_avg_has_cf_metadata(ds):
"""Add time interval length and bounds coordinates for time avg data.
If the Dataset or DataArray contains time average data, enforce
that there are coordinates that track the lower and upper bounds of
the time intervals, and that there is a coordinate that tracks the
amount of time per time average interval.
CF conventions require that a quantity stored as time averages
over time intervals must have time and time_bounds coordinates [1]_.
aospy further requires AVERAGE_DT for time average data, for accurate
time-weighted averages, which can be inferred from the CF-required
time_bounds coordinate if needed. This step should be done
prior to decoding CF metadata with xarray to ensure proper
computed timedeltas for different calendar types.
.. [1] http://cfconventions.org/cf-conventions/v1.6.0/cf-conventions.html#_data_representative_of_cells
Parameters
----------
ds : Dataset or DataArray
Input data
Returns
-------
Dataset or DataArray
Time average metadata attributes added if needed.
""" # noqa: E501
if TIME_WEIGHTS_STR not in ds:
time_weights = ds[TIME_BOUNDS_STR].diff(BOUNDS_STR)
time_weights = time_weights.rename(TIME_WEIGHTS_STR).squeeze()
if BOUNDS_STR in time_weights.coords:
time_weights = time_weights.drop(BOUNDS_STR)
ds[TIME_WEIGHTS_STR] = time_weights
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.