_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
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.proteincomple...
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 us...
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, pyrimidi...
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 r...
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. """ mapped_idx = self.mapid(idx, 'reversed') return pybel.Atom(self.original_structure.GetAtom(mapped_idx))
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 at...
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 = ...
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,...
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: p...
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 carri...
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_at...
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 c...
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 #...
python
{ "resource": "" }
q4814
PDBComplex.extract_bs
train
def extract_bs(self, cutoff, ligcentroid, resis): """Return list of ids from residues belonging to the binding site""" return [obres.GetIdx() for obres in resis if self.res_belongs_to_bs(obres, cutoff, ligcentroid)]
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, 'VERSION' : core_settings.VERSION, 'SERVER_INFO' : core_settings.SERVER_IN...
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 exhausted. """ collected = [] for func in finder_funcs: ...
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 l...
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...
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**:: ===========================...
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 ...
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 Not...
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] ...
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] ...
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 ...
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 Molalit...
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] * ...
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_Den...
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 wit...
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 ...
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 Dictio...
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] Notes ----- Need a _surf dict in the derived cla...
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 Sup...
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 --...
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 for i, n in zip(c["i"], c["n"]): suma += n*Tita**(i/2.) P = Pj...
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 ...
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 -...
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 der...
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] Retur...
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: * ...
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 unnece...
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 *...
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` i...
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, [-] Note...
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:`No...
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) ...
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(9...
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 i...
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, ...
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, [-] ...
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 ...
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...
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: Internation...
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: Int...
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: I...
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 sel...
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 inp...
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 ...
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 functio...
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.i...
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. Par...
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 np.flo...
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) Whethe...
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 b...
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 attribu...
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: setattr(obj, attr, default) else: setattr(obj, attr, value)
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 ---------...
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 op...
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 variabl...
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: time = times.apply_time_offset(da[TIME_STR], **time_offset) da[TIME_STR] = time return da
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: return self.file_map[in...
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...
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 np.ma.masked_outside(data, np.min(self.valid_range), np.max(self.valid_range))
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...
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 = "Conversion applied: hPa -> Pa to array: {}".format(arr) logging.debug(warn_msg) return arr*100. return arr
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.""" new_arr = arr.rename({old_dim: new_dim}) new_arr[new_dim] = new_coord return new_arr
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_co...
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 defined at pressure levels. Requires specification of values at surface and top of atmosphere. """ pha...
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 to_pfull_from_phalf(phalf_from_ps(bk, pk, ps), pfull_coord)
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, internal_names.PHALF_STR, internal_names.PFULL_STR, pfull_coord)
python
{ "resource": "" }
q4884
dp_from_ps
train
def dp_from_ps(bk, pk, ps, pfull_coord): """Compute pressure level thickness from surface pressure""" return d_deta_from_phalf(phalf_from_ps(bk, pk, ps), pfull_coord)
python
{ "resource": "" }
q4885
integrate
train
def integrate(arr, ddim, dim=False, is_pressure=False): """Integrate along the given dimension.""" if is_pressure: dim = vert_coord_name(ddim) return (arr*ddim).sum(dim=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 names arr attrs. if hasattr(arr, name): return name raise AttributeError("No attributes of the object `{0}` mat...
python
{ "resource": "" }
q4887
int_dp_g
train
def int_dp_g(arr, dp): """Mass weighted integral.""" return integrate(arr, to_pascal(dp, is_dp=True), vert_coord_name(dp)) / GRAV_EARTH
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 pr...
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 t...
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 ValueError("Array is not ...
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 offs...
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 err...
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 ...
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 -------...
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 = ...
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...
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 If int or str, passed ...
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...
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 trac...
python
{ "resource": "" }