code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
donor_pairs = [] data = namedtuple('hbonddonor', 'd d_orig_atom d_orig_idx h type') for donor in [a for a in all_atoms if a.OBAtom.IsHbondDonor() and a.idx not in self.altconf]: in_ring = False if not in_ring: for adj_atom in [a for a in pybel.ob.OBAtomAtomIter(donor.OBAtom) if a.IsHbondDonorH()]: d_orig_idx = self.Mapper.mapid(donor.idx, mtype=self.mtype, bsid=self.bsid) d_orig_atom = self.Mapper.id_to_atom(d_orig_idx) donor_pairs.append(data(d=donor, d_orig_atom=d_orig_atom, d_orig_idx=d_orig_idx, h=pybel.Atom(adj_atom), type='regular')) for carbon in hydroph_atoms: for adj_atom in [a for a in pybel.ob.OBAtomAtomIter(carbon.atom.OBAtom) if a.GetAtomicNum() == 1]: d_orig_idx = self.Mapper.mapid(carbon.atom.idx, mtype=self.mtype, bsid=self.bsid) d_orig_atom = self.Mapper.id_to_atom(d_orig_idx) donor_pairs.append(data(d=carbon, d_orig_atom=d_orig_atom, d_orig_idx=d_orig_idx, h=pybel.Atom(adj_atom), type='weak')) return donor_pairs
def find_hbd(self, all_atoms, hydroph_atoms)
Find all possible strong and weak hydrogen bonds donors (all hydrophobic C-H pairings)
2.660446
2.603281
1.021959
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 normals, assuming planarity ringv1 = vector(ring_atms[0], ring_atms[1]) ringv2 = vector(ring_atms[2], ring_atms[0]) atoms_orig_idx = [self.Mapper.mapid(r_atom.idx, mtype=self.mtype, bsid=self.bsid) for r_atom in r_atoms] orig_atoms = [self.Mapper.id_to_atom(idx) for idx in atoms_orig_idx] rings.append(data(atoms=r_atoms, orig_atoms=orig_atoms, atoms_orig_idx=atoms_orig_idx, normal=normalize_vector(np.cross(ringv1, ringv2)), obj=ring, center=centroid([ra.coords for ra in r_atoms]), type=typ)) return rings
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.
4.870939
4.61577
1.055282
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()]: if atom.idx not in involved_atoms: unpaired_hba.append(atom) for atom in [hbd.d for hbd in self.ligand.get_hbd()]: if atom.idx not in involved_atoms: unpaired_hbd.append(atom) # unpaired halogen bond donors in ligand (not used for the previous + halogen bonds) [involved_atoms.append(atom.don.x.idx) for atom in self.halogen_bonds] for atom in [haldon.x for haldon in self.ligand.halogenbond_don]: if atom.idx not in involved_atoms: unpaired_hal.append(atom) return unpaired_hba, unpaired_hbd, unpaired_hal
def find_unpaired_ligand(self)
Identify unpaired functional in groups in ligands, involving H-Bond donors, acceptors, halogen bond donors.
3.276624
3.187936
1.02782
sel = {} # 1. Rings interacting via stacking can't have additional hydrophobic contacts between each other. for pistack, h in itertools.product(pistacks, all_h): h1, h2 = h.bsatom.idx, h.ligatom.idx brs, lrs = [p1.idx for p1 in pistack.proteinring.atoms], [p2.idx for p2 in pistack.ligandring.atoms] if h1 in brs and h2 in lrs: sel[(h1, h2)] = "EXCLUDE" hydroph = [h for h in all_h if not (h.bsatom.idx, h.ligatom.idx) in sel] sel2 = {} # 2. If a ligand atom interacts with several binding site atoms in the same residue, # keep only the one with the closest distance for h in hydroph: if not (h.ligatom.idx, h.resnr) in sel2: sel2[(h.ligatom.idx, h.resnr)] = h else: if sel2[(h.ligatom.idx, h.resnr)].distance > h.distance: sel2[(h.ligatom.idx, h.resnr)] = h hydroph = [h for h in sel2.values()] hydroph_final = [] bsclust = {} # 3. If a protein atom interacts with several neighboring ligand atoms, just keep the one with the closest dist for h in hydroph: if h.bsatom.idx not in bsclust: bsclust[h.bsatom.idx] = [h, ] else: bsclust[h.bsatom.idx].append(h) idx_to_h = {} for bs in [a for a in bsclust if len(bsclust[a]) == 1]: hydroph_final.append(bsclust[bs][0]) # A list of tuples with the idx of an atom and one of its neighbours is created for bs in [a for a in bsclust if not len(bsclust[a]) == 1]: tuples = [] all_idx = [i.ligatom.idx for i in bsclust[bs]] for b in bsclust[bs]: idx = b.ligatom.idx neigh = [na for na in pybel.ob.OBAtomAtomIter(b.ligatom.OBAtom)] for n in neigh: n_idx = n.GetIdx() if n_idx in all_idx: if n_idx < idx: tuples.append((n_idx, idx)) else: tuples.append((idx, n_idx)) idx_to_h[idx] = b tuples = list(set(tuples)) tuples = sorted(tuples, key=itemgetter(1)) clusters = cluster_doubles(tuples) # Cluster connected atoms (i.e. find hydrophobic patches) for cluster in clusters: min_dist = float('inf') min_h = None for atm_idx in cluster: h = idx_to_h[atm_idx] if h.distance < min_dist: min_dist = h.distance min_h = h hydroph_final.append(min_h) before, reduced = len(all_h), len(hydroph_final) if not before == 0 and not before == reduced: write_message('Reduced number of hydrophobic contacts from %i to %i.\n' % (before, reduced), indent=True) return hydroph_final
def refine_hydrophobic(self, all_h, pistacks)
Apply several rules to reduce the number of hydrophobic interactions.
3.046341
3.027519
1.006217
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: i_set[hbond] = True # Allow only one hydrogen bond per donor, select interaction with larger donor angle second_set = {} hbls = [k for k in i_set.keys() if not i_set[k]] for hbl in hbls: if hbl.d.idx not in second_set: second_set[hbl.d.idx] = (hbl.angle, hbl) else: if second_set[hbl.d.idx][0] < hbl.angle: second_set[hbl.d.idx] = (hbl.angle, hbl) return [hb[1] for hb in second_set.values()]
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.
2.424083
2.398301
1.01075
i_set = [] for picat in all_picat: exclude = False for stack in stacks: if whichrestype(stack.proteinring.atoms[0]) == 'HIS' and picat.ring.obj == stack.ligandring.obj: exclude = True if not exclude: i_set.append(picat) return i_set
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.
6.023558
5.042306
1.194604
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 len(wb_dict2[water]) == 1: wb_dict2[water].append((abs(omega - wb_dict[wb_tuple].w_angle), wb_dict[wb_tuple])) wb_dict2[water] = sorted(wb_dict2[water]) else: if wb_dict2[water][1][0] < abs(omega - wb_dict[wb_tuple].w_angle): wb_dict2[water] = [wb_dict2[water][0], (wb_dict[wb_tuple].w_angle, wb_dict[wb_tuple])] filtered_wb = [] for fwbridges in wb_dict2.values(): [filtered_wb.append(fwb[1]) for fwb in fwbridges] return filtered_wb
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.
2.144624
2.024281
1.05945
data = namedtuple('hal_acceptor', 'o o_orig_idx y y_orig_idx') a_set = [] # All oxygens, nitrogen, sulfurs with neighboring carbon, phosphor, nitrogen or sulfur for a in [at for at in atoms if at.atomicnum in [8, 7, 16]]: n_atoms = [na for na in pybel.ob.OBAtomAtomIter(a.OBAtom) if na.GetAtomicNum() in [6, 7, 15, 16]] if len(n_atoms) == 1: # Proximal atom o_orig_idx = self.Mapper.mapid(a.idx, mtype=self.mtype, bsid=self.bsid) y_orig_idx = self.Mapper.mapid(n_atoms[0].GetIdx(), mtype=self.mtype, bsid=self.bsid) a_set.append(data(o=a, o_orig_idx=o_orig_idx, y=pybel.Atom(n_atoms[0]), y_orig_idx=y_orig_idx)) return a_set
def find_hal(self, atoms)
Look for halogen bond acceptors (Y-{O|P|N|S}, with Y=C,P,S)
3.694729
3.316266
1.114123
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())) if res.GetName() in ('GLU', 'ASP'): # Aspartic or Glutamic Acid for a in pybel.ob.OBResidueAtomIter(res): if a.GetType().startswith('O') 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='negative', center=centroid([ac.coords for ac in a_contributing]), restype=res.GetName(), resnr=res.GetNum(), reschain=res.GetChain())) return a_set
def find_charged(self, mol)
Looks for positive charges in arginine, histidine or lysine, for negative in aspartic and glutamic acid.
2.648996
2.538769
1.043418
data = namedtuple('metal_binding', 'atom atom_orig_idx type restype resnr reschain location') a_set = [] for res in pybel.ob.OBResidueIter(mol.OBMol): restype, reschain, resnr = res.GetName().upper(), res.GetChain(), res.GetNum() if restype in ['ASP', 'GLU', 'SER', 'THR', 'TYR']: # Look for oxygens here for a in pybel.ob.OBResidueAtomIter(res): if a.GetType().startswith('O') and res.GetAtomProperty(a, 8) \ and not self.Mapper.mapid(a.GetIdx(), mtype='protein') in self.altconf: atom_orig_idx = self.Mapper.mapid(a.GetIdx(), mtype=self.mtype, bsid=self.bsid) a_set.append(data(atom=pybel.Atom(a), atom_orig_idx=atom_orig_idx, type='O', restype=restype, resnr=resnr, reschain=reschain, location='protein.sidechain')) if restype == 'HIS': # Look for nitrogen here 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: atom_orig_idx = self.Mapper.mapid(a.GetIdx(), mtype=self.mtype, bsid=self.bsid) a_set.append(data(atom=pybel.Atom(a), atom_orig_idx=atom_orig_idx, type='N', restype=restype, resnr=resnr, reschain=reschain, location='protein.sidechain')) if restype == 'CYS': # Look for sulfur here for a in pybel.ob.OBResidueAtomIter(res): if a.GetType().startswith('S') and res.GetAtomProperty(a, 8) \ and not self.Mapper.mapid(a.GetIdx(), mtype='protein') in self.altconf: atom_orig_idx = self.Mapper.mapid(a.GetIdx(), mtype=self.mtype, bsid=self.bsid) a_set.append(data(atom=pybel.Atom(a), atom_orig_idx=atom_orig_idx, type='S', restype=restype, resnr=resnr, reschain=reschain, location='protein.sidechain')) for a in pybel.ob.OBResidueAtomIter(res): # All main chain oxygens if a.GetType().startswith('O') and res.GetAtomProperty(a, 2) \ and not self.Mapper.mapid(a.GetIdx(), mtype='protein') in self.altconf and restype != 'HOH': atom_orig_idx = self.Mapper.mapid(a.GetIdx(), mtype=self.mtype, bsid=self.bsid) a_set.append(data(atom=pybel.Atom(a), atom_orig_idx=atom_orig_idx, type='O', restype=res.GetName(), resnr=res.GetNum(), reschain=res.GetChain(), location='protein.mainchain')) return a_set
def find_metal_binding(self, mol)
Looks for atoms that could possibly be involved in chelating a metal ion. This can be any main chain oxygen atom or oxygen, nitrogen and sulfur from specific amino acids
1.844639
1.798853
1.025453
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 return True if group in ['carboxylate', 'guanidine'] and atom.atomicnum == 6: # It's a carbon atom if n_atoms.count(8) == 2 and n_atoms.count(6) == 1: # It's a carboxylate group return True if group == 'carboxylate' else False elif n_atoms.count(7) == 3 and len(n_atoms) == 3: # It's a guanidine group nitro_partners = [] for nitro in pybel.ob.OBAtomAtomIter(atom.OBAtom): nitro_partners.append(len([b_neighbor for b_neighbor in pybel.ob.OBAtomAtomIter(nitro)])) if min(nitro_partners) == 1: # One nitrogen is only connected to the carbon, can pick up a H return True if group == 'guanidine' else False if group == 'halocarbon' and atom.atomicnum in [9, 17, 35, 53]: # Halogen atoms n_atoms = [na for na in pybel.ob.OBAtomAtomIter(atom.OBAtom) if na.GetAtomicNum() == 6] if len(n_atoms) == 1: # Halocarbon return True else: return False
def is_functional_group(self, atom, group)
Given a pybel atom, look up if it belongs to a function group
2.890684
2.873008
1.006152
data = namedtuple('hal_donor', 'x orig_x x_orig_idx c c_orig_idx') a_set = [] for a in atoms: if self.is_functional_group(a, 'halocarbon'): n_atoms = [na for na in pybel.ob.OBAtomAtomIter(a.OBAtom) if na.GetAtomicNum() == 6] x_orig_idx = self.Mapper.mapid(a.idx, mtype=self.mtype, bsid=self.bsid) orig_x = self.Mapper.id_to_atom(x_orig_idx) c_orig_idx = [self.Mapper.mapid(na.GetIdx(), mtype=self.mtype, bsid=self.bsid) for na in n_atoms] a_set.append(data(x=a, orig_x=orig_x, x_orig_idx=x_orig_idx, c=pybel.Atom(n_atoms[0]), c_orig_idx=c_orig_idx)) if len(a_set) != 0: write_message('Ligand contains %i halogen atom(s).\n' % len(a_set), indent=True) return a_set
def find_hal(self, atoms)
Look for halogen bond donors (X-C, with X=F, Cl, Br, I)
3.756134
3.520526
1.066924
single_sites = [] for member in ligand.members: single_sites.append(':'.join([str(x) for x in member])) site = ' + '.join(single_sites) site = site if not len(site) > 20 else site[:20] + '...' longname = ligand.longname if not len(ligand.longname) > 20 else ligand.longname[:20] + '...' ligtype = 'Unspecified type' if ligand.type == 'UNSPECIFIED' else ligand.type ligtext = "\n%s [%s] -- %s" % (longname, ligtype, site) if ligtype == 'PEPTIDE': ligtext = '\n Chain %s [PEPTIDE / INTER-CHAIN]' % ligand.chain if ligtype == 'INTRA': ligtext = "\n Chain %s [INTRA-CHAIN]" % ligand.chain any_in_biolip = len(set([x[0] for x in ligand.members]).intersection(config.biolip_list)) != 0 write_message(ligtext) write_message('\n' + '-' * len(ligtext) + '\n') if ligtype not in ['POLYMER', 'DNA', 'ION', 'DNA+ION', 'RNA+ION', 'SMALLMOLECULE+ION'] and any_in_biolip: write_message('may be biologically irrelevant\n', mtype='info', indent=True) lig_obj = Ligand(self, ligand) cutoff = lig_obj.max_dist_to_center + config.BS_DIST bs_res = self.extract_bs(cutoff, lig_obj.centroid, self.resis) # Get a list of all atoms belonging to the binding site, search by idx bs_atoms = [self.atoms[idx] for idx in [i for i in self.atoms.keys() if self.atoms[i].OBAtom.GetResidue().GetIdx() in bs_res] if idx in self.Mapper.proteinmap and self.Mapper.mapid(idx, mtype='protein') not in self.altconf] if ligand.type == 'PEPTIDE': # If peptide, don't consider the peptide chain as part of the protein binding site bs_atoms = [a for a in bs_atoms if a.OBAtom.GetResidue().GetChain() != lig_obj.chain] if ligand.type == 'INTRA': # Interactions within the chain bs_atoms = [a for a in bs_atoms if a.OBAtom.GetResidue().GetChain() == lig_obj.chain] bs_atoms_refined = [] # Create hash with BSRES -> (MINDIST_TO_LIG, AA_TYPE) # and refine binding site atom selection with exact threshold min_dist = {} for r in bs_atoms: bs_res_id = ''.join([str(whichresnumber(r)), whichchain(r)]) for l in ligand.mol.atoms: distance = euclidean3d(r.coords, l.coords) if bs_res_id not in min_dist: min_dist[bs_res_id] = (distance, whichrestype(r)) elif min_dist[bs_res_id][0] > distance: min_dist[bs_res_id] = (distance, whichrestype(r)) if distance <= config.BS_DIST and r not in bs_atoms_refined: bs_atoms_refined.append(r) num_bs_atoms = len(bs_atoms_refined) write_message('Binding site atoms in vicinity (%.1f A max. dist: %i).\n' % (config.BS_DIST, num_bs_atoms), indent=True) bs_obj = BindingSite(bs_atoms_refined, self.protcomplex, self, self.altconf, min_dist, self.Mapper) pli_obj = PLInteraction(lig_obj, bs_obj, self) self.interaction_sets[ligand.mol.title] = pli_obj
def characterize_complex(self, ligand)
Handles all basic functions for characterizing the interactions for one ligand
4.272356
4.252169
1.004747
return [obres.GetIdx() for obres in resis if self.res_belongs_to_bs(obres, cutoff, ligcentroid)]
def extract_bs(self, cutoff, ligcentroid, resis)
Return list of ids from residues belonging to the binding site
6.687406
5.280663
1.266395
rescentroid = centroid([(atm.x(), atm.y(), atm.z()) for atm in pybel.ob.OBResidueAtomIter(res)]) # Check geometry near_enough = True if euclidean3d(rescentroid, ligcentroid) < cutoff else False # Check chain membership restricted_chain = True if res.GetChain() in config.PEPTIDES else False return (near_enough and not restricted_chain)
def res_belongs_to_bs(self, res, cutoff, ligcentroid)
Check for each residue if its centroid is within a certain distance to the ligand centroid. Additionally checks if a residue belongs to a chain restricted by the user (e.g. by defining a peptide chain)
6.303313
5.61337
1.122911
return { 'MEDIA_URL' : core_settings.MEDIA_URL, 'STATIC_URL': core_settings.STATIC_URL, 'VERSION' : core_settings.VERSION, 'SERVER_INFO' : core_settings.SERVER_INFO, 'SITE_NAME' : current_site_name, 'CURRENT_SITE': current_site, }
def url_info(request)
Make MEDIA_URL and current HttpRequest object available in template code.
3.153004
2.841515
1.109621
# never cache headers + ETag add_never_cache_headers(response) if not hasattr(request, '_cache_update_cache') or not request._cache_update_cache: # We don't need to update the cache, just return. return response if request.method != 'GET': # This is a stronger requirement than above. It is needed # because of interactions between this middleware and the # HTTPMiddleware, which throws the body of a HEAD-request # away before this middleware gets a chance to cache it. return response if not response.status_code == 200: return response # use the precomputed cache_key if request._cache_middleware_key: cache_key = request._cache_middleware_key else: cache_key = learn_cache_key(request, response, self.cache_timeout, self.key_prefix) # include the orig_time information within the cache cache.set(cache_key, (time.time(), response), self.cache_timeout) return response
def process_response(self, request, response)
Sets the cache, if needed.
5.445839
5.378323
1.012553
if self.cache_anonymous_only: assert hasattr(request, 'user'), "The Django cache middleware with CACHE_MIDDLEWARE_ANONYMOUS_ONLY=True requires authentication middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.auth.middleware.AuthenticationMiddleware' before the CacheMiddleware." if not request.method in ('GET', 'HEAD') or request.GET: request._cache_update_cache = False return None # Don't bother checking the cache. if self.cache_anonymous_only and request.user.is_authenticated(): request._cache_update_cache = False return None # Don't cache requests from authenticated users. cache_key = get_cache_key(request, self.key_prefix) request._cache_middleware_key = cache_key if cache_key is None: request._cache_update_cache = True return None # No cache information available, need to rebuild. response = cache.get(cache_key, None) if response is None: request._cache_update_cache = True return None # No cache information available, need to rebuild. orig_time, response = response # time to refresh the cache if orig_time and ((time.time() - orig_time) > self.cache_refresh_timeout): request._cache_update_cache = True # keep the response in the cache for just self.timeout seconds and mark it for update # other requests will continue werving this response from cache while I alone work on refreshing it cache.set(cache_key, (None, response), self.timeout) return None request._cache_update_cache = False return response
def process_request(self, request)
Checks whether the page is already cached and returns the cached version if available.
3.545065
3.533456
1.003285
collected = [] for func in finder_funcs: gathered = func(obj, count, collected, *args, **kwargs) if gathered: collected += gathered if len(collected) >= count: return collected[:count] return collected
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.
2.849141
2.893735
0.98459
return self.collect_related(self._get_finders(finder), obj, count, mods, only_from_same_site)
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 content. ``finder`` atribute uses ``RELATED_FINDERS`` settings to find out what finder function to use. If none is specified, ``default`` is used to perform the query.
4.329672
6.044493
0.7163
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 = [] while len(out) < count: skip = 0 # 2 i a reasonable value for padding, wouldn't you say dear Watson? for l in qset[offset:limit + 2]: if l.publishable_id not in seen: seen.add(l.publishable_id) out.append(l) if len(out) == count: break else: skip += 1 # no enough skipped, or not enough listings to work with, no need for another try if skip <= 2 or (len(out) + skip) < (count + 2): break # get another page to fill in the gaps offset += count limit += count return out
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
4.386189
4.454028
0.984769
tname, context = _do_paginator(context, adjacent_pages, template_name) return render_to_string(tname, context)
def paginator(context, adjacent_pages=2, template_name=None)
Renders a ``inclusion_tags/paginator.html`` or ``inc/paginator.html`` template with additional pagination context. To be used in conjunction with the ``object_list`` generic view. If ``TEMPLATE_NAME`` parameter is given, ``inclusion_tags/paginator_TEMPLATE_NAME.html`` or ``inc/paginator_TEMPLATE_NAME.html`` will be used instead. Adds pagination context variables for use in displaying first, adjacent pages and last page links in addition to those created by the ``object_list`` generic view. Taken from http://www.djangosnippets.org/snippets/73/ Syntax:: {% paginator [NUMBER_OF_ADJACENT_PAGES] [TEMPLATE_NAME] %} Examples:: {% paginator %} {% paginator 5 %} {% paginator 5 "special" %} # with Django 1.4 and above you can also do: {% paginator template_name="special" %}
4.747203
9.955762
0.47683
contents = token.split_contents() if len(contents) not in [5, 7]: raise template.TemplateSyntaxError('%r tag requires 4 or 6 arguments.' % contents[0]) elif len(contents) == 5: tag, obj_var, count, fill, var_name = contents return AuthorListingNode(obj_var, count, var_name) else: tag, obj_var, count, fill, var_name, filll, omit_var = contents return AuthorListingNode(obj_var, count, var_name, omit_var)
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**:: {% author_listing object.authors.all.0 10 as article_listing %}
3.076631
3.339848
0.921189
def f(T): pw = _Region1(T, P) gw = pw["h"]-T*pw["s"] pv = _Region2(T, P) gv = pv["h"]-T*pv["s"] ps = SeaWater._saline(T, P, S) return -ps["g"]+S*ps["gs"]-gw+gv Tb = fsolve(f, 300)[0] return Tb
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
6.78319
8.059806
0.841607
def f(T): T = float(T) pw = _Region1(T, P) gw = pw["h"]-T*pw["s"] gih = _Ice(T, P)["g"] ps = SeaWater._saline(T, P, S) return -ps["g"]+S*ps["gs"]-gw+gih Tf = fsolve(f, 300)[0] return Tf
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
10.562848
11.660273
0.905883
def f(parr): T, P = parr pw = _Region1(T, P) gw = pw["h"]-T*pw["s"] pv = _Region2(T, P) gv = pv["h"]-T*pv["s"] gih = _Ice(T, P)["g"] ps = SeaWater._saline(T, P, S) return -ps["g"]+S*ps["gs"]-gw+gih, -ps["g"]+S*ps["gs"]-gw+gv Tt, Pt = fsolve(f, [273, 6e-4]) prop = {} prop["Tt"] = Tt prop["Pt"] = Pt return prop
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
7.484588
6.413662
1.166976
pw = _Region1(T, P) gw = pw["h"]-T*pw["s"] def f(Posm): pw2 = _Region1(T, P+Posm) gw2 = pw2["h"]-T*pw2["s"] ps = SeaWater._saline(T, P+Posm, S) return -ps["g"]+S*ps["gs"]-gw+gw2 Posm = fsolve(f, 0)[0] return Posm
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
6.472671
7.133564
0.907355
# Check input parameters if T < 273.15 or T > 523.15 or P < 0 or P > 140 or S < 0 or S > 0.17: raise NotImplementedError("Incoming out of bound") # Eq 4 a1 = -7.180891e-5+1.831971e-7*P a2 = 1.048077e-3-4.494722e-6*P # Eq 5 b1 = 1.463375e-1+9.208586e-4*P b2 = -3.086908e-3+1.798489e-5*P a = a1*exp(a2*(T-273.15)) # Eq 2 b = b1*exp(b2*(T-273.15)) # Eq 3 # Eq 1 DL = a*(1000*S)**(1+b) return DL
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
3.974284
3.841416
1.034588
# Check input parameters if T < 523.15 or T > 623.15 or mH2SO4 < 0 or mH2SO4 > 0.75 or \ mNaCl < 0 or mNaCl > 2.25: raise NotImplementedError("Incoming out of bound") A00 = -0.8085987*T+81.4613752+0.10537803*T*log(T) A10 = 3.4636364*T-281.63322-0.46779874*T*log(T) A20 = -6.0029634*T+480.60108+0.81382854*T*log(T) A30 = 4.4540258*T-359.36872-0.60306734*T*log(T) A01 = 0.4909061*T-46.556271-0.064612393*T*log(T) A02 = -0.002781314*T+1.722695+0.0000013319698*T*log(T) A03 = -0.014074108*T+0.99020227+0.0019397832*T*log(T) A11 = -0.87146573*T+71.808756+0.11749585*T*log(T) S = A00 + A10*mH2SO4 + A20*mH2SO4**2 + A30*mH2SO4**3 + A01*mNaCl + \ A02*mNaCl**2 + A03*mNaCl**3 + A11*mH2SO4*mNaCl return S
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 References ---------- IAPWS, Solubility of Sodium Sulfate in Aqueous Mixtures of Sodium Chloride and Sulfuric Acid from Water to Concentrated Solutions, http://www.iapws.org/relguide/na2so4.pdf
3.608943
3.538986
1.019768
# 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 = Tc*(1 + 1.757e1*x - 3.026e2*x**1.5 + 2.838e3*x**2 - 1.349e4*x**2.5 + 3.278e4*x**3 - 3.674e4*x**3.5 + 1.437e4*x**4) f1 = (abs(10000*x-10-1)-abs(10000*x-10+1))/4+0.5 f2 = (abs(10000*x-10+1)-abs(10000*x-10-1))/4+0.5 # Eq 1 tc = f1*T1+f2*T2 # Eq 7 rc = rhoc*(1 + 1.7607e2*x - 2.9693e3*x**1.5 + 2.4886e4*x**2 - 1.1377e5*x**2.5 + 2.8847e5*x**3 - 3.8195e5*x**3.5 + 2.0633e5*x**4) # Eq 8 DT = tc-Tc pc = Pc*(1+9.1443e-3*DT+5.1636e-5*DT**2-2.5360e-7*DT**3+3.6494e-10*DT**4) prop = {} prop["Tc"] = tc prop["rhoc"] = rc prop["Pc"] = pc return prop
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
3.376898
3.296753
1.02431
T = self.kwargs["T"] P = self.kwargs["P"] S = self.kwargs["S"] self.m = S/(1-S)/Ms if self.kwargs["fast"] and T <= 313.15: pw = self._waterSupp(T, P) elif self.kwargs["IF97"]: pw = self._waterIF97(T, P) else: pw = self._water(T, P) ps = self._saline(T, P, S) prop = {} for key in ps: prop[key] = pw[key]+ps[key] self.__setattr__(key, prop[key]) self.T = T self.P = P self.rho = 1./prop["gp"] self.v = prop["gp"] self.s = -prop["gt"] self.cp = -T*prop["gtt"] self.cv = T*(prop["gtp"]**2/prop["gpp"]-prop["gtt"]) self.h = prop["g"]-T*prop["gt"] self.u = prop["g"]-T*prop["gt"]-P*1000*prop["gp"] self.a = prop["g"]-P*1000*prop["gp"] self.alfav = prop["gtp"]/prop["gp"] self.betas = -prop["gtp"]/prop["gtt"] self.xkappa = -prop["gpp"]/prop["gp"] self.ks = (prop["gtp"]**2-prop["gtt"]*prop["gpp"])/prop["gp"] / \ prop["gtt"] self.w = prop["gp"]*(prop["gtt"]*1000/(prop["gtp"]**2 - prop["gtt"]*1000*prop["gpp"]*1e-6))**0.5 if "thcond" in pw: kw = pw["thcond"] else: kw = _ThCond(1/pw["gp"], T) try: self.k = _ThCond_SeaWater(T, P, S)+kw except NotImplementedError: self.k = None if S: self.mu = prop["gs"] self.muw = prop["g"]-S*prop["gs"] self.mus = prop["g"]+(1-S)*prop["gs"] self.osm = -(ps["g"]-S*prop["gs"])/self.m/Rm/T self.haline = -prop["gsp"]/prop["gp"] else: self.mu = None self.muw = None self.mus = None self.osm = None self.haline = None
def calculo(self)
Calculate procedure
3.890736
3.866103
1.006372
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 prop["gpp"] = -1e6/(water.rho*water.w)**2-water.betas**2*1e3*water.cp/T prop["gs"] = 0 prop["gsp"] = 0 prop["thcond"] = water.k return prop
def _water(cls, T, P)
Get properties of pure water, Table4 pag 8
4.756545
4.729024
1.00582
fir = 0 # Polinomial terms nr1 = coef.get("nr1", []) d1 = coef.get("d1", []) t1 = coef.get("t1", []) for n, d, t in zip(nr1, d1, t1): fir += n*delta**d*tau**t # Exponential terms nr2 = coef.get("nr2", []) d2 = coef.get("d2", []) g2 = coef.get("gamma2", []) t2 = coef.get("t2", []) c2 = coef.get("c2", []) for n, d, g, t, c in zip(nr2, d2, g2, t2, c2): fir += n*delta**d*tau**t*exp(-g*delta**c) # Gaussian terms nr3 = coef.get("nr3", []) d3 = coef.get("d3", []) t3 = coef.get("t3", []) a3 = coef.get("alfa3", []) e3 = coef.get("epsilon3", []) b3 = coef.get("beta3", []) g3 = coef.get("gamma3", []) for n, d, t, a, e, b, g in zip(nr3, d3, t3, a3, e3, b3, g3): fir += n*delta**d*tau**t*exp(-a*(delta-e)**2-b*(tau-g)**2) # Non analitic terms nr4 = coef.get("nr4", []) a4 = coef.get("a4", []) b4 = coef.get("b4", []) Ai = coef.get("A", []) Bi = coef.get("B", []) Ci = coef.get("C", []) Di = coef.get("D", []) bt4 = coef.get("beta4", []) for n, a, b, A, B, C, D, bt in zip(nr4, a4, b4, Ai, Bi, Ci, Di, bt4): Tita = (1-tau)+A*((delta-1)**2)**(0.5/bt) F = exp(-C*(delta-1)**2-D*(tau-1)**2) Delta = Tita**2+B*((delta-1)**2)**a fir += n*Delta**b*delta*F return fir
def _phir(tau, delta, coef)
Residual contribution to the adimensional free Helmholtz energy Parameters ---------- tau : float Inverse reduced temperature Tc/T, [-] delta : float Reduced density rho/rhoc, [-] coef : dict Dictionary with equation of state parameters Returns ------- fir : float Adimensional free Helmholtz energy 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 5 http://www.iapws.org/relguide/IAPWS-95.html
2.154863
2.197437
0.980626
def decorator(f): # __doc__ is only writable in python3. # The doc build must be done with python3 so this snnippet do the work py_version = platform.python_version() if py_version[0] == "3": doc = f.__doc__.split(os.linesep) try: ind = doc.index("") except ValueError: ind = 1 doc1 = os.linesep.join(doc[:ind]) doc3 = os.linesep.join(doc[ind:]) doc2 = os.linesep.join(MEoS.__doc__.split(os.linesep)[3:]) f.__doc__ = doc1 + os.linesep + os.linesep + \ doc2 + os.linesep + os.linesep + doc3 return f return decorator
def mainClassDoc()
Function decorator used to automatic adiction of base class MEoS in subclass __doc__
4.506114
3.953447
1.139794
self._mode = "" if self.kwargs["T"] and self.kwargs["P"]: self._mode = "TP" elif self.kwargs["T"] and self.kwargs["rho"]: self._mode = "Trho" elif self.kwargs["T"] and self.kwargs["h"] is not None: self._mode = "Th" elif self.kwargs["T"] and self.kwargs["s"] is not None: self._mode = "Ts" elif self.kwargs["T"] and self.kwargs["u"] is not None: self._mode = "Tu" elif self.kwargs["P"] and self.kwargs["rho"]: self._mode = "Prho" elif self.kwargs["P"] and self.kwargs["h"] is not None: self._mode = "Ph" elif self.kwargs["P"] and self.kwargs["s"] is not None: self._mode = "Ps" elif self.kwargs["P"] and self.kwargs["u"] is not None: self._mode = "Pu" elif self.kwargs["rho"] and self.kwargs["h"] is not None: self._mode = "rhoh" elif self.kwargs["rho"] and self.kwargs["s"] is not None: self._mode = "rhos" elif self.kwargs["rho"] and self.kwargs["u"] is not None: self._mode = "rhou" elif self.kwargs["h"] is not None and self.kwargs["s"] is not None: self._mode = "hs" elif self.kwargs["h"] is not None and self.kwargs["u"] is not None: self._mode = "hu" elif self.kwargs["s"] is not None and self.kwargs["u"] is not None: self._mode = "su" elif self.kwargs["T"] and self.kwargs["x"] is not None: self._mode = "Tx" elif self.kwargs["P"] and self.kwargs["x"] is not None: self._mode = "Px" return bool(self._mode)
def calculable(self)
Check if inputs are enough to define state
1.370251
1.342476
1.02069
return deriv_H(self, z, x, y, fase)
def derivative(self, z, x, y, fase)
Wrapper derivative for custom derived properties where x, y, z can be: P, T, v, rho, u, h, s, g, a
6.776799
6.217253
1.089999
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) Kl = deltaL*phirdL+phirL+log(deltaL) Kv = deltaG*phirdG+phirG+log(deltaG) return Kv-Kl, Jv-Jl rhoL, rhoG = fsolve(f, [rhoLo, rhoGo]) if rhoL == rhoG: Ps = self.Pc else: deltaL = rhoL/self.rhoc deltaG = rhoG/self.rhoc firL = _phir(tau, deltaL, self._constants) firG = _phir(tau, deltaG, self._constants) Ps = self.R*T*rhoL*rhoG/(rhoL-rhoG)*(firL-firG+log(deltaL/deltaG)) return rhoL, rhoG, Ps
def _saturation(self, T)
Saturation calculation for two phase search
3.153778
3.15834
0.998556
if isinstance(rho, ndarray): rho = rho[0] if isinstance(T, ndarray): T = T[0] if rho < 0: rho = 1e-20 if T < 50: T = 50 rhoc = self._constants.get("rhoref", self.rhoc) Tc = self._constants.get("Tref", self.Tc) delta = rho/rhoc tau = Tc/T ideal = self._phi0(tau, delta) fio = ideal["fio"] fiot = ideal["fiot"] fiott = ideal["fiott"] res = self._phir(tau, delta) fir = res["fir"] firt = res["firt"] firtt = res["firtt"] fird = res["fird"] firdd = res["firdd"] firdt = res["firdt"] propiedades = {} propiedades["fir"] = fir propiedades["fird"] = fird propiedades["firdd"] = firdd propiedades["delta"] = delta propiedades["rho"] = rho propiedades["P"] = (1+delta*fird)*self.R*T*rho propiedades["h"] = self.R*T*(1+tau*(fiot+firt)+delta*fird) propiedades["s"] = self.R*(tau*(fiot+firt)-fio-fir) propiedades["cv"] = -self.R*tau**2*(fiott+firtt) propiedades["alfap"] = (1-delta*tau*firdt/(1+delta*fird))/T propiedades["betap"] = rho*( 1+(delta*fird+delta**2*firdd)/(1+delta*fird)) return propiedades
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 3 http://www.iapws.org/relguide/IAPWS-95.html
3.391468
2.946372
1.151066
rhoc = self._constants.get("rhoref", self.rhoc) Tc = self._constants.get("Tref", self.Tc) delta = rho/rhoc tau = Tc/T ideal = self._phi0(tau, delta) fio = ideal["fio"] fiot = ideal["fiot"] fiott = ideal["fiott"] propiedades = _fase() propiedades.h = self.R*T*(1+tau*fiot) propiedades.s = self.R*(tau*fiot-fio) propiedades.cv = -self.R*tau**2*fiott propiedades.cp = self.R*(-tau**2*fiott+1) propiedades.alfap = 1/T propiedades.betap = rho return propiedades
def _prop0(self, rho, T)
Ideal gas properties
4.84067
4.644521
1.042232
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: fiot += t*n*tau**(t-1) if t not in [0, 1]: fiott += n*t*(t-1)*tau**(t-2) for n, t in zip(Fi0["ao_exp"], Fi0["titao"]): fio += n*log(1-exp(-tau*t)) fiot += n*t*((1-exp(-t*tau))**-1-1) fiott -= n*t**2*exp(-t*tau)*(1-exp(-t*tau))**-2 # Extension to especial terms of air if "ao_exp2" in Fi0: for n, g, C in zip(Fi0["ao_exp2"], Fi0["titao2"], Fi0["sum2"]): fio += n*log(C+exp(g*tau)) fiot += n*g/(C*exp(-g*tau)+1) fiott += C*n*g**2*exp(-g*tau)/(C*exp(-g*tau)+1)**2 prop = {} prop["fio"] = fio prop["fiot"] = fiot prop["fiott"] = fiott prop["fiod"] = fiod prop["fiodd"] = fiodd prop["fiodt"] = fiodt return prop
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
3.180475
2.913843
1.091505
if not rho: prop = {} prop["fir"] = 0 prop["firt"] = 0 prop["fird"] = 0 prop["firtt"] = 0 prop["firdt"] = 0 prop["firdd"] = 0 return prop R = self._constants.get("R")/self._constants.get("M", self.M) rhoc = self._constants.get("rhoref", self.rhoc) Tc = self._constants.get("Tref", self.Tc) delta = rho/rhoc tau = Tc/T ideal = self._phi0(tau, delta) fio = ideal["fio"] fiot = ideal["fiot"] fiott = ideal["fiott"] fiod = ideal["fiod"] fiodd = ideal["fiodd"] res = self._phir(tau, delta) fir = res["fir"] firt = res["firt"] firtt = res["firtt"] fird = res["fird"] firdd = res["firdd"] firdt = res["firdt"] prop = {} prop["fir"] = R*T*(fio+fir) prop["firt"] = R*(fio+fir-(fiot+firt)*tau) prop["fird"] = R*T/rhoc*(fiod+fird) prop["firtt"] = R*tau**2/T*(fiott+firtt) prop["firdt"] = R/rhoc*(fiod+fird-firdt*tau) prop["firdd"] = R*T/rhoc**2*(fiodd+firdd) return prop
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
2.858429
2.479547
1.152803
tau = 1-T/self.Tc sigma = 0 for n, t in zip(self._surf["sigma"], self._surf["exp"]): sigma += n*tau**t return sigma
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 class with the parameters keys: sigma: coefficient exp: exponent
7.078767
5.866027
1.20674
Tita = 1-T/cls.Tc suma = 0 for n, x in zip(cls._Pv["ao"], cls._Pv["exp"]): suma += n*Tita**x Pr = exp(cls.Tc/T*suma) Pv = Pr*cls.Pc return Pv
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 September 1992, http://www.iapws.org/relguide/Supp-sat.html, Eq.1
7.195637
9.690859
0.742518
eq = cls._rhoL["eq"] Tita = 1-T/cls.Tc if eq == 2: Tita = Tita**(1./3) suma = 0 for n, x in zip(cls._rhoL["ao"], cls._rhoL["exp"]): suma += n*Tita**x Pr = suma+1 rho = Pr*cls.rhoc return rho
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 ---------- IAPWS, Revised Supplementary Release on Saturation Properties of Ordinary Water Substance September 1992, http://www.iapws.org/relguide/Supp-sat.html, Eq.2
6.495708
8.308781
0.781788
eq = cls._rhoG["eq"] Tita = 1-T/cls.Tc if eq == 4: Tita = Tita**(1./3) suma = 0 for n, x in zip(cls._rhoG["ao"], cls._rhoG["exp"]): suma += n*Tita**x Pr = exp(suma) rho = Pr*cls.rhoc return rho
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 ---------- IAPWS, Revised Supplementary Release on Saturation Properties of Ordinary Water Substance September 1992, http://www.iapws.org/relguide/Supp-sat.html, Eq.3
6.248743
8.06592
0.774709
Tita = 1-T/cls.Tc suma1 = 0 suma2 = 0 for n, x in zip(cls._Pv["ao"], cls._Pv["exp"]): suma1 -= n*x*Tita**(x-1)/cls.Tc suma2 += n*Tita**x Pr = (cls.Tc*suma1/T-cls.Tc/T**2*suma2)*exp(cls.Tc/T*suma2) dPdT = Pr*cls.Pc return dPdT
def _dPdT_sat(cls, T)
Auxiliary equation for the dP/dT along saturation line Parameters ---------- T : float Temperature, [K] Returns ------- dPdT : float dPdT, [MPa/K] References ---------- IAPWS, Revised Supplementary Release on Saturation Properties of Ordinary Water Substance September 1992, http://www.iapws.org/relguide/Supp-sat.html, derived from Eq.1
5.442887
6.440501
0.845103
# Check input parameters if T < 193 or T > 473 or P < 0 or P > 5 or x < 0 or x > 1: raise(NotImplementedError("Input not in range of validity")) R = 8.314462 # J/molK # Virial coefficients vir = _virial(T) # Eq 3 beta = x*(2-x)*vir["Bww"]+(1-x)**2*(2*vir["Baw"]-vir["Baa"]) # Eq 4 gamma = x**2*(3-2*x)*vir["Cwww"] + \ (1-x)**2*(6*x*vir["Caww"]+3*(1-2*x)*vir["Caaw"]-2*(1-x)*vir["Caaa"]) +\ (x**2*vir["Bww"]+2*x*(1-x)*vir["Baw"]+(1-x)**2*vir["Baa"]) * \ (x*(3*x-4)*vir["Bww"]+2*(1-x)*(3*x-2)*vir["Baw"]+3*(1-x)**2*vir["Baa"]) # Eq 2 fv = x*P*exp(beta*P*1e6/R/T+0.5*gamma*(P*1e6/R/T)**2) return fv
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
3.882554
3.540165
1.096715
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*exp(Tj/T*suma) return P
def _bubbleP(cls, T)
Using ancillary equation return the pressure of bubble point
6.226317
5.809285
1.071787
self._mode = "" if self.kwargs["T"] and self.kwargs["P"]: self._mode = "TP" elif self.kwargs["T"] and self.kwargs["rho"]: self._mode = "Trho" elif self.kwargs["P"] and self.kwargs["rho"]: self._mode = "Prho" # Composition definition self._composition = "" if self.kwargs["A"] is not None: self._composition = "A" elif self.kwargs["xa"] is not None: self._composition = "xa" return bool(self._mode) and bool(self._composition)
def calculable(self)
Check if inputs are enough to define state
2.862986
2.639065
1.084848
T = self.kwargs["T"] rho = self.kwargs["rho"] P = self.kwargs["P"] # Composition alternate definition if self._composition == "A": A = self.kwargs["A"] elif self._composition == "xa": xa = self.kwargs["xa"] A = xa/(1-(1-xa)*(1-Mw/Ma)) # Thermodynamic definition if self._mode == "TP": def f(rho): fav = self._fav(T, rho, A) return rho**2*fav["fird"]/1000-P rho = fsolve(f, 1)[0] elif self._mode == "Prho": def f(T): fav = self._fav(T, rho, A) return rho**2*fav["fird"]/1000-P T = fsolve(f, 300)[0] # General calculation procedure fav = self._fav(T, rho, A) # Common thermodynamic properties prop = self._prop(T, rho, fav) self.T = T self.rho = rho self.v = 1/rho self.P = prop["P"] self.s = prop["s"] self.cp = prop["cp"] self.h = prop["h"] self.g = prop["g"] self.u = self.h-self.P*1000*self.v self.alfav = prop["alfav"] self.betas = prop["betas"] self.xkappa = prop["xkappa"] self.ks = prop["ks"] self.w = prop["w"] # Coligative properties coligative = self._coligative(rho, A, fav) self.A = A self.W = 1-A self.mu = coligative["mu"] self.muw = coligative["muw"] self.M = coligative["M"] self.HR = coligative["HR"] self.xa = coligative["xa"] self.xw = coligative["xw"] self.Pv = (1-self.xa)*self.P # Saturation related properties A_sat = self._eq(self.T, self.P) self.xa_sat = A_sat*Mw/Ma/(1-A_sat*(1-Mw/Ma)) self.RH = (1-self.xa)/(1-self.xa_sat)
def calculo(self)
Calculate procedure
3.560818
3.511506
1.014043
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: a = 1 fa = self._fav(T, rho, a) muw = fa["fir"]+rho*fa["fird"]-a*fa["fira"] return gw-muw, rho**2*fa["fird"]/1000-P rinput = fsolve(f, [1, 0.95], full_output=True) Asat = rinput[0][1] return Asat
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]
7.666501
7.445586
1.029671
prop = {} prop["P"] = rho**2*fav["fird"]/1000 # Eq T1 prop["s"] = -fav["firt"] # Eq T2 prop["cp"] = -T*fav["firtt"]+T*rho*fav["firdt"]**2/( # Eq T3 2*fav["fird"]+rho*fav["firdd"]) prop["h"] = fav["fir"]-T*fav["firt"]+rho*fav["fird"] # Eq T4 prop["g"] = fav["fir"]+rho*fav["fird"] # Eq T5 prop["alfav"] = fav["firdt"]/(2*fav["fird"]+rho*fav["firdd"]) # Eq T6 prop["betas"] = 1000*fav["firdt"]/rho/( # Eq T7 rho*fav["firdt"]**2-fav["firtt"]*(2*fav["fird"]+rho*fav["firdd"])) prop["xkappa"] = 1e3/(rho**2*(2*fav["fird"]+rho*fav["firdd"])) # Eq T8 prop["ks"] = 1000*fav["firtt"]/rho**2/( # Eq T9 fav["firtt"]*(2*fav["fird"]+rho*fav["firdd"])-rho*fav["firdt"]**2) prop["w"] = (rho**2*1000*(fav["firtt"]*fav["firdd"]-fav["firdt"]**2) / fav["firtt"]+2*rho*fav["fird"]*1000)**0.5 # Eq T10 return prop
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 ---------- 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 5, http://www.iapws.org/relguide/SeaAir.html
3.395459
2.842951
1.194343
prop = {} prop["mu"] = fav["fira"] prop["muw"] = fav["fir"]+rho*fav["fird"]-A*fav["fira"] prop["M"] = 1/((1-A)/Mw+A/Ma) prop["HR"] = 1/A-1 prop["xa"] = A*Mw/Ma/(1-A*(1-Mw/Ma)) prop["xw"] = 1-prop["xa"] return prop
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 with the IAPWS Formulation 2008 for the Thermodynamic Properties of Seawater, Table 12, http://www.iapws.org/relguide/SeaAir.html
7.57799
4.485359
1.689495
if 50 <= T <= 273.16: Tita = T/Tt suma = 0 a = [-0.212144006e2, 0.273203819e2, -0.61059813e1] expo = [0.333333333e-2, 1.20666667, 1.70333333] for ai, expi in zip(a, expo): suma += ai*Tita**expi return exp(suma/Tita)*Pt else: raise NotImplementedError("Incoming out of bound")
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.
6.337557
6.001661
1.055967
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 ice == "III" and 251.165 < T <= 256.164: # Ice III Tref = 251.165 Pref = 208.566 Tita = T/Tref P = Pref*(1-0.299948*(1-Tita**60.)) elif (ice == "V" and 256.164 < T <= 273.15) or 273.15 < T <= 273.31: # Ice V Tref = 256.164 Pref = 350.100 Tita = T/Tref P = Pref*(1-1.18721*(1-Tita**8.)) elif 273.31 < T <= 355: # Ice VI Tref = 273.31 Pref = 632.400 Tita = T/Tref P = Pref*(1-1.07476*(1-Tita**4.6)) elif 355. < T <= 715: # Ice VII Tref = 355 Pref = 2216.000 Tita = T/Tref P = Pref*exp(1.73683*(1-1./Tita)-0.544606e-1*(1-Tita**5) + 0.806106e-7*(1-Tita**22)) else: raise NotImplementedError("Incoming out of bound") return P
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.
3.553023
3.335039
1.065362
if 248.15 <= T <= Tc: Tr = T/Tc return 1e-3*(235.8*(1-Tr)**1.256*(1-0.625*(1-Tr))) else: raise NotImplementedError("Incoming out of bound")
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 liquid metastable state Examples -------- >>> _Tension(300) 0.0716859625 >>> _Tension(450) 0.0428914992 References ---------- IAPWS, Revised Release on Surface Tension of Ordinary Water Substance June 2014, http://www.iapws.org/relguide/Surf-H2O.html
8.94697
9.01015
0.992988
# 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 = [0.978224486826, -0.957771379375, 0.237511794148, 0.714692244396, -0.298217036956, -0.108863472196, .949327488264e-1, -.980469816509e-2, .165167634970e-4, .937359795772e-4, -.12317921872e-9, .196096504426e-2] g = 1+n[11]*d/(Tc/228/Tr-1)**1.2 for i in range(11): g += n[i]*d**I[i]*Tr**J[i] A = Na*mu**2*rho*g/M*1000/epsilon0/k/T B = Na*alfa*rho/3/M*1000/epsilon0 e = (1+A+5*B+(9+2*A+18*B+A**2+10*A*B+9*B**2)**0.5)/4/(1-B) return e
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
5.268328
5.425134
0.971096
# Check input parameters if rho < 0 or rho > 1060 or T < 261.15 or T > 773.15 or l < 0.2 or l > 1.1: raise NotImplementedError("Incoming out of bound") Lir = 5.432937 Luv = 0.229202 d = rho/1000. Tr = T/273.15 L = l/0.589 a = [0.244257733, 0.974634476e-2, -0.373234996e-2, 0.268678472e-3, 0.158920570e-2, 0.245934259e-2, 0.900704920, -0.166626219e-1] A = d*(a[0]+a[1]*d+a[2]*Tr+a[3]*L**2*Tr+a[4]/L**2+a[5]/(L**2-Luv**2)+a[6]/( L**2-Lir**2)+a[7]*d**2) return ((2*A+1)/(1-A))**0.5
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
4.932283
4.487862
1.099027
# Check input parameters if rho < 0 or rho > 1250 or T < 273.15 or T > 1073.15: raise NotImplementedError("Incoming out of bound") # The internal method of calculation use rho in g/cm³ d = rho/1000. # Water molecular weight different Mw = 18.015268 gamma = [6.1415e-1, 4.825133e4, -6.770793e4, 1.01021e7] pKg = 0 for i, g in enumerate(gamma): pKg += g/T**i Q = d*exp(-0.864671+8659.19/T-22786.2/T**2*d**(2./3)) pKw = -12*(log10(1+Q)-Q/(Q+1)*d*(0.642044-56.8534/T-0.375754*d)) + \ pKg+2*log10(Mw/1000) return pKw
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
7.975711
7.087572
1.125309
# FIXME: Dont work rho_ = rho/1000 kw = 10**-_Kw(rho, T) A = [1850., 1410., 2.16417e-6, 1.81609e-7, -1.75297e-9, 7.20708e-12] B = [16., 11.6, 3.26e-4, -2.3e-6, 1.1e-8] t = T-273.15 Loo = A[0]-1/(1/A[1]+sum([A[i+2]*t**(i+1) for i in range(4)])) # Eq 5 rho_h = B[0]-1/(1/B[1]+sum([B[i+2]*t**(i+1) for i in range(3)])) # Eq 6 # Eq 4 L_o = (rho_h-rho_)*Loo/rho_h # Eq 1 k = 100*1e-3*L_o*kw**0.5*rho_ return k
def _Conductivity(rho, T)
Equation for the electrolytic conductivity of liquid and dense supercrítical water Parameters ---------- rho : float Density, [kg/m³] T : float Temperature, [K] Returns ------- K : float Electrolytic conductivity, [S/m] Notes ------ Raise :class:`NotImplementedError` if input isn't in limit: * 600 ≤ ρ ≤ 1200 * 273.15 ≤ T ≤ 1073.15 Examples -------- >>> _Conductivity(1000, 373.15) 1.13 References ---------- IAPWS, Electrolytic Conductivity (Specific Conductance) of Liquid and Dense Supercritical Water from 0°C to 800°C and Pressures up to 1000 MPa, http://www.iapws.org/relguide/conduct.pdf
4.976099
5.236702
0.950235
Tr = T/643.847 rhor = rho/358.0 no = [1.0, 0.940695, 0.578377, -0.202044] fi0 = Tr**0.5/sum([n/Tr**i for i, n in enumerate(no)]) Li = [0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 0, 1, 2, 5, 0, 1, 2, 3, 0, 1, 3, 5, 0, 1, 5, 3] Lj = [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 6] Lij = [0.4864192, -0.2448372, -0.8702035, 0.8716056, -1.051126, 0.3458395, 0.3509007, 1.315436, 1.297752, 1.353448, -0.2847572, -1.037026, -1.287846, -0.02148229, 0.07013759, 0.4660127, 0.2292075, -0.4857462, 0.01641220, -0.02884911, 0.1607171, -.009603846, -.01163815, -.008239587, 0.004559914, -0.003886659] arr = [lij*(1./Tr-1)**i*(rhor-1)**j for i, j, lij in zip(Li, Lj, Lij)] fi1 = exp(rhor*sum(arr)) return 55.2651e-6*fi0*fi1
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
4.256696
4.47804
0.950571
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] Lr = -167.31*(1-exp(-2.506*rhor))+sum( [Li*rhor**(i+1) for i, Li in enumerate(nr)]) f1 = exp(0.144847*Tr-5.64493*Tr**2) f2 = exp(-2.8*(rhor-1)**2)-0.080738543*exp(-17.943*(rhor-0.125698)**2) f3 = 1+exp(60*(tau-1)+20) f4 = 1+exp(100*(tau-1)+15) Lc = 35429.6*f1*f2*(1+f2**2*(5e9*f1**4/f3+3.5*f2/f4)) Ll = -741.112*f1**1.2*(1-exp(-(rhor/2.5)**10)) return 0.742128e-3*(Lo+Lr+Lc+Ll)
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
6.593382
7.057851
0.934191
if 210 <= T <= 276.969: Tita = T/276.969 suma = 0 ai = [-0.1314226e2, 0.3212969e2] ti = [-1.73, -1.42] for a, t in zip(ai, ti): suma += a*(1-Tita**t) return exp(suma)*0.00066159 else: raise NotImplementedError("Incoming out of bound")
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 -------- >>> _Sublimation_Pressure(245) 3.27390934e-5 References ---------- IAPWS, Revised Release on the IAPWS Formulation 2017 for the Thermodynamic Properties of Heavy Water, http://www.iapws.org/relguide/Heavy.html.
7.09549
6.185174
1.147177
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) P = suma*0.00066159 elif ice == "III" and 254.415 < T <= 258.661: # Ice III, Eq 10 Tita = T/254.415 P = 222.41*(1-0.802871*(1-Tita**33)) elif ice == "V" and 258.661 < T <= 275.748: # Ice V, Eq 11 Tita = T/258.661 P = 352.19*(1-1.280388*(1-Tita**7.6)) elif (ice == "VI" and 275.748 < T <= 276.969) or 276.969 < T <= 315: # Ice VI Tita = T/275.748 P = 634.53*(1-1.276026*(1-Tita**4)) else: raise NotImplementedError("Incoming out of bound") return P
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.
3.522918
3.214339
1.096001
# Avoid round problem P = round(P, 8) T = round(T, 8) if P > Pc and T > Tc: phase = "Supercritical fluid" elif T > Tc: phase = "Gas" elif P > Pc: phase = "Compressible liquid" elif P == Pc and T == Tc: phase = "Critical point" elif region == 4 and x == 1: phase = "Saturated vapor" elif region == 4 and x == 0: phase = "Saturated liquid" elif region == 4: phase = "Two phases" elif x == 1: phase = "Vapour" elif x == 0: phase = "Liquid" return phase
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 Phase name
2.808192
2.821534
0.995272
r # We use the relation between rho and v and his partial derivative # ∂v/∂b|c = -1/ρ² ∂ρ/∂b|c # ∂a/∂v|c = -ρ² ∂a/∂ρ|c mul = 1 if z == "rho": mul = -fase.rho**2 z = "v" if x == "rho": mul = -1/fase.rho**2 x = "v" if y == "rho": y = "v" dT = {"P": state.P*1000*fase.alfap, "T": 1, "v": 0, "u": fase.cv, "h": fase.cv+state.P*1000*fase.v*fase.alfap, "s": fase.cv/state.T, "g": state.P*1000*fase.v*fase.alfap-fase.s, "a": -fase.s} dv = {"P": -state.P*1000*fase.betap, "T": 0, "v": 1, "u": state.P*1000*(state.T*fase.alfap-1), "h": state.P*1000*(state.T*fase.alfap-fase.v*fase.betap), "s": state.P*1000*fase.alfap, "g": -state.P*1000*fase.v*fase.betap, "a": -state.P*1000} deriv = (dv[z]*dT[y]-dT[z]*dv[y])/(dv[x]*dT[y]-dT[x]*dv[y]) return mul*deriv
def deriv_H(state, z, x, y, fase)
r"""Calculate generic partial derivative :math:`\left.\frac{\partial z}{\partial x}\right|_{y}` from a fundamental helmholtz free energy equation of state Parameters ---------- state : any python object Only need to define P and T properties, non phase specific properties z : str Name of variables in numerator term of derivatives x : str Name of variables in denominator term of derivatives y : str Name of constant variable in partial derivaritive fase : any python object Define phase specific properties (v, cv, alfap, s, betap) Notes ----- x, y and z can be the following values: * P: Pressure * T: Temperature * v: Specific volume * rho: Density * u: Internal Energy * h: Enthalpy * s: Entropy * g: Gibbs free energy * a: Helmholtz free energy Returns ------- deriv : float ∂z/∂x|y References ---------- IAPWS, Revised Advisory Note No. 3: Thermodynamic Derivatives from IAPWS Formulations, http://www.iapws.org/relguide/Advise3.pdf
3.072343
2.67836
1.147099
r mul = 1 if z == "rho": mul = -fase.rho**2 z = "v" if x == "rho": mul = -1/fase.rho**2 x = "v" dT = {"P": 0, "T": 1, "v": fase.v*fase.alfav, "u": fase.cp-state.P*1000*fase.v*fase.alfav, "h": fase.cp, "s": fase.cp/state.T, "g": -fase.s, "a": -state.P*1000*fase.v*fase.alfav-fase.s} dP = {"P": 1, "T": 0, "v": -fase.v*fase.xkappa, "u": fase.v*(state.P*1000*fase.xkappa-state.T*fase.alfav), "h": fase.v*(1-state.T*fase.alfav), "s": -fase.v*fase.alfav, "g": fase.v, "a": state.P*1000*fase.v*fase.xkappa} deriv = (dP[z]*dT[y]-dT[z]*dP[y])/(dP[x]*dT[y]-dT[x]*dP[y]) return mul*deriv
def deriv_G(state, z, x, y, fase)
r"""Calculate generic partial derivative :math:`\left.\frac{\partial z}{\partial x}\right|_{y}` from a fundamental Gibbs free energy equation of state Parameters ---------- state : any python object Only need to define P and T properties, non phase specific properties z : str Name of variables in numerator term of derivatives x : str Name of variables in denominator term of derivatives y : str Name of constant variable in partial derivaritive fase : any python object Define phase specific properties (v, cp, alfav, s, xkappa) Notes ----- x, y and z can be the following values: * P: Pressure * T: Temperature * v: Specific volume * rho: Density * u: Internal Energy * h: Enthalpy * s: Entropy * g: Gibbs free energy * a: Helmholtz free energy Returns ------- deriv : float ∂z/∂x|y References ---------- IAPWS, Revised Advisory Note No. 3: Thermodynamic Derivatives from IAPWS Formulations, http://www.iapws.org/relguide/Advise3.pdf
2.917101
2.572085
1.134139
# Check input parameters if s < 3.397782955 or s > 3.77828134: raise NotImplementedError("Incoming out of bound") sigma = s/3.8 I = [0, 1, 1, 3, 5, 6] J = [0, -2, 2, -12, -4, -3] n = [0.913965547600543, -0.430944856041991e-4, 0.603235694765419e2, 0.117518273082168e-17, 0.220000904781292, -0.690815545851641e2] suma = 0 for i, j, ni in zip(I, J, n): suma += ni * (sigma-0.884)**i * (sigma-0.864)**j return 1700 * suma
def _h13_s(s)
Define the boundary between Region 1 and 3, h=f(s) Parameters ---------- s : float Specific entropy, [kJ/kgK] Returns ------- h : float Specific enthalpy, [kJ/kg] Notes ------ Raise :class:`NotImplementedError` if input isn't in limit: * s(100MPa,623.15K) ≤ s ≤ s'(623.15K) References ---------- IAPWS, Revised Supplementary Release on Backward Equations p(h,s) for Region 3, Equations as a Function of h and s for the Region Boundaries, and an Equation Tsat(h,s) for Region 4 of the IAPWS Industrial Formulation 1997 for the Thermodynamic Properties of Water and Steam, http://www.iapws.org/relguide/Supp-phs3-2014.pdf. Eq 7 Examples -------- >>> _h13_s(3.7) 1632.525047 >>> _h13_s(3.5) 1566.104611
6.54667
6.978097
0.938174
# Check input parameters if T < 273.15 or T > Tc: raise NotImplementedError("Incoming out of bound") n = [0, 0.11670521452767E+04, -0.72421316703206E+06, -0.17073846940092E+02, 0.12020824702470E+05, -0.32325550322333E+07, 0.14915108613530E+02, -0.48232657361591E+04, 0.40511340542057E+06, -0.23855557567849E+00, 0.65017534844798E+03] tita = T+n[9]/(T-n[10]) A = tita**2+n[1]*tita+n[2] B = n[3]*tita**2+n[4]*tita+n[5] C = n[6]*tita**2+n[7]*tita+n[8] return (2*C/(-B+(B**2-4*A*C)**0.5))**4
def _PSat_T(T)
Define the saturated line, P=f(T) Parameters ---------- T : float Temperature, [K] Returns ------- P : float Pressure, [MPa] Notes ------ Raise :class:`NotImplementedError` if input isn't in limit: * 273.15 ≤ T ≤ 647.096 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 30 Examples -------- >>> _PSat_T(500) 2.63889776
4.676261
4.955167
0.943714
# Check input parameters if P < 611.212677/1e6 or P > 22.064: raise NotImplementedError("Incoming out of bound") n = [0, 0.11670521452767E+04, -0.72421316703206E+06, -0.17073846940092E+02, 0.12020824702470E+05, -0.32325550322333E+07, 0.14915108613530E+02, -0.48232657361591E+04, 0.40511340542057E+06, -0.23855557567849E+00, 0.65017534844798E+03] beta = P**0.25 E = beta**2+n[3]*beta+n[6] F = n[1]*beta**2+n[4]*beta+n[7] G = n[2]*beta**2+n[5]*beta+n[8] D = 2*G/(-F-(F**2-4*E*G)**0.5) return (n[10]+D-((n[10]+D)**2-4*(n[9]+n[10]*D))**0.5)/2
def _TSat_P(P)
Define the saturated line, T=f(P) Parameters ---------- P : float Pressure, [MPa] Returns ------- T : float Temperature, [K] Notes ------ Raise :class:`NotImplementedError` if input isn't in limit: * 0.00061121 ≤ P ≤ 22.064 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 31 Examples -------- >>> _TSat_P(10) 584.149488
4.969
5.102876
0.973765
# Check input parameters hmin_Ps3 = _Region1(623.15, Ps_623)["h"] hmax_Ps3 = _Region2(623.15, Ps_623)["h"] if h < hmin_Ps3 or h > hmax_Ps3: raise NotImplementedError("Incoming out of bound") nu = h/2600 I = [0, 1, 1, 1, 1, 5, 7, 8, 14, 20, 22, 24, 28, 36] J = [0, 1, 3, 4, 36, 3, 0, 24, 16, 16, 3, 18, 8, 24] n = [0.600073641753024, -0.936203654849857e1, 0.246590798594147e2, -0.107014222858224e3, -0.915821315805768e14, -0.862332011700662e4, -0.235837344740032e2, 0.252304969384128e18, -0.389718771997719e19, -0.333775713645296e23, 0.356499469636328e11, -0.148547544720641e27, 0.330611514838798e19, 0.813641294467829e38] suma = 0 for i, j, ni in zip(I, J, n): suma += ni * (nu-1.02)**i * (nu-0.608)**j return 22*suma
def _PSat_h(h)
Define the saturated line, P=f(h) for region 3 Parameters ---------- h : float Specific enthalpy, [kJ/kg] Returns ------- P : float Pressure, [MPa] Notes ------ Raise :class:`NotImplementedError` if input isn't in limit: * h'(623.15K) ≤ h ≤ h''(623.15K) References ---------- IAPWS, Revised Supplementary Release on Backward Equations for the Functions T(p,h), v(p,h) and T(p,s), v(p,s) for Region 3 of the IAPWS Industrial Formulation 1997 for the Thermodynamic Properties of Water and Steam, http://www.iapws.org/relguide/Supp-Tv%28ph,ps%293-2014.pdf, Eq 10 Examples -------- >>> _PSat_h(1700) 17.24175718 >>> _PSat_h(2400) 20.18090839
5.35286
5.428909
0.985992
# Check input parameters smin_Ps3 = _Region1(623.15, Ps_623)["s"] smax_Ps3 = _Region2(623.15, Ps_623)["s"] if s < smin_Ps3 or s > smax_Ps3: raise NotImplementedError("Incoming out of bound") sigma = s/5.2 I = [0, 1, 1, 4, 12, 12, 16, 24, 28, 32] J = [0, 1, 32, 7, 4, 14, 36, 10, 0, 18] n = [0.639767553612785, -0.129727445396014e2, -0.224595125848403e16, 0.177466741801846e7, 0.717079349571538e10, -0.378829107169011e18, -0.955586736431328e35, 0.187269814676188e24, 0.119254746466473e12, 0.110649277244882e37] suma = 0 for i, j, ni in zip(I, J, n): suma += ni * (sigma-1.03)**i * (sigma-0.699)**j return 22*suma
def _PSat_s(s)
Define the saturated line, P=f(s) for region 3 Parameters ---------- s : float Specific entropy, [kJ/kgK] Returns ------- P : float Pressure, [MPa] Notes ------ Raise :class:`NotImplementedError` if input isn't in limit: * s'(623.15K) ≤ s ≤ s''(623.15K) References ---------- IAPWS, Revised Supplementary Release on Backward Equations for the Functions T(p,h), v(p,h) and T(p,s), v(p,s) for Region 3 of the IAPWS Industrial Formulation 1997 for the Thermodynamic Properties of Water and Steam, http://www.iapws.org/relguide/Supp-Tv%28ph,ps%293-2014.pdf, Eq 11 Examples -------- >>> _PSat_s(3.8) 16.87755057 >>> _PSat_s(5.2) 16.68968482
5.639427
5.718071
0.986246
I = [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3, 4, 5, 6] J = [0, 1, 2, 6, 22, 32, 0, 1, 2, 3, 4, 10, 32, 10, 32, 10, 32, 32, 32, 32] n = [-0.23872489924521e3, 0.40421188637945e3, 0.11349746881718e3, -0.58457616048039e1, -0.15285482413140e-3, -0.10866707695377e-5, -0.13391744872602e2, 0.43211039183559e2, -0.54010067170506e2, 0.30535892203916e2, -0.65964749423638e1, 0.93965400878363e-2, 0.11573647505340e-6, -0.25858641282073e-4, -0.40644363084799e-8, 0.66456186191635e-7, 0.80670734103027e-10, -0.93477771213947e-12, 0.58265442020601e-14, -0.15020185953503e-16] Pr = P/1 nu = h/2500 T = 0 for i, j, ni in zip(I, J, n): T += ni * Pr**i * (nu+1)**j return T
def _Backward1_T_Ph(P, h)
Backward equation for region 1, T=f(P,h) Parameters ---------- P : float Pressure, [MPa] h : float Specific enthalpy, [kJ/kg] Returns ------- T : float Temperature, [K] 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 11 Examples -------- >>> _Backward1_T_Ph(3,500) 391.798509 >>> _Backward1_T_Ph(80,1500) 611.041229
4.390492
4.483884
0.979172
I = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 3, 4, 4, 5] J = [0, 1, 2, 4, 5, 6, 8, 14, 0, 1, 4, 6, 0, 1, 10, 4, 1, 4, 0] n = [-0.691997014660582, -0.183612548787560e2, -0.928332409297335e1, 0.659639569909906e2, -0.162060388912024e2, 0.450620017338667e3, 0.854680678224170e3, 0.607523214001162e4, 0.326487682621856e2, -0.269408844582931e2, -0.319947848334300e3, -0.928354307043320e3, 0.303634537455249e2, -0.650540422444146e2, -0.430991316516130e4, -0.747512324096068e3, 0.730000345529245e3, 0.114284032569021e4, -0.436407041874559e3] nu = h/3400 sigma = s/7.6 P = 0 for i, j, ni in zip(I, J, n): P += ni * (nu+0.05)**i * (sigma+0.05)**j return 100*P
def _Backward1_P_hs(h, s)
Backward equation for region 1, P=f(h,s) Parameters ---------- h : float Specific enthalpy, [kJ/kg] s : float Specific entropy, [kJ/kgK] Returns ------- P : float Pressure, [MPa] References ---------- IAPWS, Revised Supplementary Release on Backward Equations for Pressure as a Function of Enthalpy and Entropy p(h,s) for Regions 1 and 2 of the IAPWS Industrial Formulation 1997 for the Thermodynamic Properties of Water and Steam, http://www.iapws.org/relguide/Supp-PHS12-2014.pdf, Eq 1 Examples -------- >>> _Backward1_P_hs(0.001,0) 0.0009800980612 >>> _Backward1_P_hs(90,0) 91.92954727 >>> _Backward1_P_hs(1500,3.4) 58.68294423
4.66144
4.835889
0.963926
Jo = [0, 1, -5, -4, -3, -2, -1, 2, 3] no = [-0.96927686500217E+01, 0.10086655968018E+02, -0.56087911283020E-02, 0.71452738081455E-01, -0.40710498223928E+00, 0.14240819171444E+01, -0.43839511319450E+01, -0.28408632460772E+00, 0.21268463753307E-01] go = log(Pr) gop = Pr**-1 gopp = -Pr**-2 got = gott = gopt = 0 for j, ni in zip(Jo, no): go += ni * Tr**j got += ni*j * Tr**(j-1) gott += ni*j*(j-1) * Tr**(j-2) return go, gop, gopp, got, gott, gopt
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
5.046224
5.06741
0.995819
smin = _Region2(_TSat_P(4), 4)["s"] smax = _Region2(1073.15, 4)["s"] if s < smin: h = 0 elif s > smax: h = 5000 else: h = -0.349898083432139e4 + 0.257560716905876e4*s - \ 0.421073558227969e3*s**2+0.276349063799944e2*s**3 return h
def _hab_s(s)
Define the boundary between Region 2a and 2b, h=f(s) Parameters ---------- s : float Specific entropy, [kJ/kgK] Returns ------- h : float Specific enthalpy, [kJ/kg] References ---------- IAPWS, Revised Supplementary Release on Backward Equations for Pressure as a Function of Enthalpy and Entropy p(h,s) for Regions 1 and 2 of the IAPWS Industrial Formulation 1997 for the Thermodynamic Properties of Water and Steam, http://www.iapws.org/relguide/Supp-PHS12-2014.pdf, Eq 2 Examples -------- >>> _hab_s(7) 3376.437884
6.952011
7.081943
0.981653
if P <= 4: T = _Backward2a_T_Ph(P, h) elif 4 < P <= 6.546699678: T = _Backward2b_T_Ph(P, h) else: hf = _hbc_P(P) if h >= hf: T = _Backward2b_T_Ph(P, h) else: T = _Backward2c_T_Ph(P, h) if P <= 22.064: Tsat = _TSat_P(P) T = max(Tsat, T) return T
def _Backward2_T_Ph(P, h)
Backward equation for region 2, T=f(P,h) Parameters ---------- P : float Pressure, [MPa] h : float Specific enthalpy, [kJ/kg] Returns ------- T : float Temperature, [K]
3.356407
3.377023
0.993895
if P <= 4: T = _Backward2a_T_Ps(P, s) elif s >= 5.85: T = _Backward2b_T_Ps(P, s) else: T = _Backward2c_T_Ps(P, s) if P <= 22.064: Tsat = _TSat_P(P) T = max(Tsat, T) return T
def _Backward2_T_Ps(P, s)
Backward equation for region 2, T=f(P,s) Parameters ---------- P : float Pressure, [MPa] s : float Specific entropy, [kJ/kgK] Returns ------- T : float Temperature, [K]
3.35488
3.512495
0.955127
sfbc = 5.85 hamin = _hab_s(s) if h <= hamin: P = _Backward2a_P_hs(h, s) elif s >= sfbc: P = _Backward2b_P_hs(h, s) else: P = _Backward2c_P_hs(h, s) return P
def _Backward2_P_hs(h, s)
Backward equation for region 2, P=f(h,s) Parameters ---------- h : float Specific enthalpy, [kJ/kg] s : float Specific entropy, [kJ/kgK] Returns ------- P : float Pressure, [MPa]
4.059367
4.321452
0.939353
I = [0, 1, 2, -1, -2] n = [0.154793642129415e4, -0.187661219490113e3, 0.213144632222113e2, -0.191887498864292e4, 0.918419702359447e3] Pr = P/1 T = 0 for i, ni in zip(I, n): T += ni * log(Pr)**i return T
def _tab_P(P)
Define the boundary between Region 3a-3b, T=f(P) Parameters ---------- P : float Pressure, [MPa] Returns ------- T : float Temperature, [K] References ---------- IAPWS, Revised Supplementary Release on Backward Equations for Specific Volume as a Function of Pressure and Temperature v(p,T) for Region 3 of the IAPWS Industrial Formulation 1997 for the Thermodynamic Properties of Water and Steam, http://www.iapws.org/relguide/Supp-VPT3-2016.pdf, Eq. 2 Examples -------- >>> _tab_P(40) 693.0341408
6.275052
6.959684
0.901629
hf = _h_3ab(P) if h <= hf: return _Backward3a_v_Ph(P, h) else: return _Backward3b_v_Ph(P, h)
def _Backward3_v_Ph(P, h)
Backward equation for region 3, v=f(P,h) Parameters ---------- P : float Pressure, [MPa] h : float Specific enthalpy, [kJ/kg] Returns ------- v : float Specific volume, [m³/kg]
3.790452
5.228876
0.724908
hf = _h_3ab(P) if h <= hf: T = _Backward3a_T_Ph(P, h) else: T = _Backward3b_T_Ph(P, h) return T
def _Backward3_T_Ph(P, h)
Backward equation for region 3, T=f(P,h) Parameters ---------- P : float Pressure, [MPa] h : float Specific enthalpy, [kJ/kg] Returns ------- T : float Temperature, [K]
3.811208
4.788145
0.795967
if s <= sc: return _Backward3a_v_Ps(P, s) else: return _Backward3b_v_Ps(P, s)
def _Backward3_v_Ps(P, s)
Backward equation for region 3, v=f(P,s) Parameters ---------- P : float Pressure, [MPa] s : float Specific entropy, [kJ/kgK] Returns ------- v : float Specific volume, [m³/kg]
3.05034
4.506558
0.676867
sc = 4.41202148223476 if s <= sc: T = _Backward3a_T_Ps(P, s) else: T = _Backward3b_T_Ps(P, s) return T
def _Backward3_T_Ps(P, s)
Backward equation for region 3, T=f(P,s) Parameters ---------- P : float Pressure, [MPa] s : float Specific entropy, [kJ/kgK] Returns ------- T : float Temperature, [K]
4.419693
5.088648
0.86854
sc = 4.41202148223476 if s <= sc: return _Backward3a_P_hs(h, s) else: return _Backward3b_P_hs(h, s)
def _Backward3_P_hs(h, s)
Backward equation for region 3, P=f(h,s) Parameters ---------- h : float Specific enthalpy, [kJ/kg] s : float Specific entropy, [kJ/kgK] Returns ------- P : float Pressure, [MPa]
4.515633
5.601849
0.806097
if x == 0: if P < 19.00881189: region = "c" elif P < 21.0434: region = "s" elif P < 21.9316: region = "u" else: region = "y" else: if P < 20.5: region = "t" elif P < 21.0434: region = "r" elif P < 21.9009: region = "x" else: region = "z" return _Backward3x_v_PT(T, P, region)
def _Backward3_sat_v_P(P, T, x)
Backward equation for region 3 for saturated state, vs=f(P,x) Parameters ---------- T : float Temperature, [K] P : float Pressure, [MPa] x : integer Vapor quality, [-] Returns ------- v : float Specific volume, [m³/kg] Notes ----- The vapor quality (x) can be 0 (saturated liquid) or 1 (saturated vapour)
3.438508
3.846781
0.893867
T = _TSat_P(P) if T > 623.15: rhol = 1./_Backward3_sat_v_P(P, T, 0) P1 = _Region3(rhol, T) rhov = 1./_Backward3_sat_v_P(P, T, 1) P2 = _Region3(rhov, T) else: P1 = _Region1(T, P) P2 = _Region2(T, P) propiedades = {} propiedades["T"] = T propiedades["P"] = P propiedades["v"] = P1["v"]+x*(P2["v"]-P1["v"]) propiedades["h"] = P1["h"]+x*(P2["h"]-P1["h"]) propiedades["s"] = P1["s"]+x*(P2["s"]-P1["s"]) propiedades["cp"] = None propiedades["cv"] = None propiedades["w"] = None propiedades["alfav"] = None propiedades["kt"] = None propiedades["region"] = 4 propiedades["x"] = x return propiedades
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]
2.565558
2.630445
0.975332
region = None if 1073.15 < T <= 2273.15 and Pmin <= P <= 50: region = 5 elif Pmin <= P <= Ps_623: Tsat = _TSat_P(P) if 273.15 <= T <= Tsat: region = 1 elif Tsat < T <= 1073.15: region = 2 elif Ps_623 < P <= 100: T_b23 = _t_P(P) if 273.15 <= T <= 623.15: region = 1 elif 623.15 < T < T_b23: region = 3 elif T_b23 <= T <= 1073.15: region = 2 return region
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
2.897358
3.075604
0.942045
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 = 4 elif h24 <= h <= h25: region = 2 elif h25 < h <= hmax: region = 5 elif Ps_623 < P < Pc: hmin = _Region1(273.15, P)["h"] h13 = _Region1(623.15, P)["h"] h32 = _Region2(_t_P(P), P)["h"] h25 = _Region2(1073.15, P)["h"] hmax = _Region5(2273.15, P)["h"] if hmin <= h <= h13: region = 1 elif h13 < h < h32: try: p34 = _PSat_h(h) except NotImplementedError: p34 = Pc if P < p34: region = 4 else: region = 3 elif h32 <= h <= h25: region = 2 elif h25 < h <= hmax: region = 5 elif Pc <= P <= 100: hmin = _Region1(273.15, P)["h"] h13 = _Region1(623.15, P)["h"] h32 = _Region2(_t_P(P), P)["h"] h25 = _Region2(1073.15, P)["h"] hmax = _Region5(2273.15, P)["h"] if hmin <= h <= h13: region = 1 elif h13 < h < h32: region = 3 elif h32 <= h <= h25: region = 2 elif P <= 50 and h25 <= h <= hmax: region = 5 return region
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
1.948719
2.025245
0.962214
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: region = 4 elif s24 <= s <= s25: region = 2 elif s25 < s <= smax: region = 5 elif Ps_623 < P < Pc: smin = _Region1(273.15, P)["s"] s13 = _Region1(623.15, P)["s"] s32 = _Region2(_t_P(P), P)["s"] s25 = _Region2(1073.15, P)["s"] smax = _Region5(2273.15, P)["s"] if smin <= s <= s13: region = 1 elif s13 < s < s32: try: p34 = _PSat_s(s) except NotImplementedError: p34 = Pc if P < p34: region = 4 else: region = 3 elif s32 <= s <= s25: region = 2 elif s25 < s <= smax: region = 5 elif Pc <= P <= 100: smin = _Region1(273.15, P)["s"] s13 = _Region1(623.15, P)["s"] s32 = _Region2(_t_P(P), P)["s"] s25 = _Region2(1073.15, P)["s"] smax = _Region5(2273.15, P)["s"] if smin <= s <= s13: region = 1 elif s13 < s < s32: region = 3 elif s32 <= s <= s25: region = 2 elif P <= 50 and s25 <= s <= smax: region = 5 return region
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
1.933741
1.969425
0.981881
if T <= 1073.15: Tr = 540/T Pr = P/1. go, gop, gopp, got, gott, gopt = Region2_cp0(Tr, Pr) else: Tr = 1000/T Pr = P/1. go, gop, gopp, got, gott, gopt = Region5_cp0(Tr, Pr) prop0 = {} prop0["v"] = Pr*gop*R*T/P/1000 prop0["h"] = Tr*got*R*T prop0["s"] = R*(Tr*got-go) prop0["cp"] = -R*Tr**2*gott prop0["cv"] = R*(-Tr**2*gott-1) prop0["w"] = (R*T*1000/(1+1/Tr**2/gott))**0.5 prop0["alfav"] = 1/T prop0["xkappa"] = 1/P return prop0
def prop0(T, P)
Ideal gas properties Parameters ---------- T : float Temperature, [K] P : float Pressure, [MPa] Returns ------- prop : dict Dict with calculated properties. The available properties are: * v: Specific volume, [m³/kg] * h: Specific enthalpy, [kJ/kg] * s: Specific entropy, [kJ/kgK] * cp: Specific isobaric heat capacity, [kJ/kgK] * cv: Specific isocoric heat capacity, [kJ/kgK] * w: Speed of sound, [m/s] * alfav: Cubic expansion coefficient, [1/K] * kt: Isothermal compressibility, [1/MPa]
4.411794
4.11308
1.072626
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: # self._thermo = "Ts" elif self.kwargs["h"] is not None and self.kwargs["s"] is not None: self._thermo = "hs" elif self.kwargs["T"] and self.kwargs["x"] is not None: self._thermo = "Tx" elif self.kwargs["P"] and self.kwargs["x"] is not None: self._thermo = "Px" return self._thermo
def calculable(self)
Check if class is calculable by its kwargs
2.137002
2.017005
1.059493
return deriv_G(self, z, x, y, fase)
def derivative(self, z, x, y, fase)
Wrapper derivative for custom derived properties where x, y, z can be: P, T, v, u, h, s, g, a
6.853547
6.316701
1.084988
if 0 <= x <= 0.33367: Ttr = 273.16*(1-0.3439823*x-1.3274271*x**2-274.973*x**3) elif 0.33367 < x <= 0.58396: Ttr = 193.549*(1-4.987368*(x-0.5)**2) elif 0.58396 < x <= 0.81473: Ttr = 194.38*(1-4.886151*(x-2/3)**2+10.37298*(x-2/3)**3) elif 0.81473 < x <= 1: Ttr = 195.495*(1-0.323998*(1-x)-15.87560*(1-x)**4) else: raise NotImplementedError("Incoming out of bound") return Ttr
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 Formulation 2001 for the Thermodynamic Properties of Ammonia-Water Mixtures, http://www.iapws.org/relguide/nh3h2o.pdf, Eq 9
4.058699
4.282547
0.94773
# FIXME: The values are good, bad difer by 1%, a error I can find # In Pressure happen and only use fird M = (1-x)*IAPWS95.M + x*NH3.M R = 8.314471/M phio = self._phi0(rho, T, x) fio = phio["fio"] tau0 = phio["tau"] fiot = phio["fiot"] fiott = phio["fiott"] phir = self._phir(rho, T, x) fir = phir["fir"] tau = phir["tau"] delta = phir["delta"] firt = phir["firt"] firtt = phir["firtt"] fird = phir["fird"] firdd = phir["firdd"] firdt = phir["firdt"] F = phir["F"] prop = {} Z = 1 + delta*fird prop["M"] = M prop["P"] = Z*R*T*rho/1000 prop["u"] = R*T*(tau0*fiot + tau*firt) prop["s"] = R*(tau0*fiot + tau*firt - fio - fir) prop["h"] = R*T*(1+delta*fird+tau0*fiot+tau*firt) prop["g"] = prop["h"]-T*prop["s"] prop["a"] = prop["u"]-T*prop["s"] cvR = -tau0**2*fiott - tau**2*firtt prop["cv"] = R*cvR prop["cp"] = R*(cvR+(1+delta*fird-delta*tau*firdt)**2 / (1+2*delta*fird+delta**2*firdd)) prop["w"] = (R*T*1000*(1+2*delta*fird+delta**2*firdd + (1+delta*fird-delta*tau*firdt)**2 / cvR))**0.5 prop["fugH2O"] = Z*exp(fir+delta*fird-x*F) prop["fugNH3"] = Z*exp(fir+delta*fird+(1-x)*F) return prop
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 the Thermodynamic Properties of Ammonia-Water Mixtures, http://www.iapws.org/relguide/nh3h2o.pdf, Table 4
4.817029
4.144177
1.162361
def func_wrapper(ds): return grid_attrs_to_aospy_names(func(ds, **kwargs), grid_attrs) return func_wrapper
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 : dict (optional) Overriding dictionary of grid attributes mapping aospy internal names to names of grid attributes used in a particular model. Returns ------- function A function that calls the provided function ``func`` on the Dataset before calling ``grid_attrs_to_aospy_names``; this is meant to be passed as a ``preprocess`` argument to ``xr.open_mfdataset``.
8.340243
3.777884
2.207649
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: raise ValueError( 'Unrecognized internal name, {!r}, specified for a custom ' 'grid attribute name. See the full list of valid internal ' 'names below:\n\n{}'.format(k, list(GRID_ATTRS.keys()))) attrs[k] = (v, ) dims_and_vars = set(data.variables).union(set(data.dims)) for name_int, names_ext in attrs.items(): data_coord_name = set(names_ext).intersection(dims_and_vars) if data_coord_name: data = data.rename({data_coord_name.pop(): name_int}) return set_grid_attrs_as_coords(data)
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
3.736628
3.733676
1.000791
grid_attrs_in_ds = set(GRID_ATTRS.keys()).intersection( set(ds.coords) | set(ds.data_vars)) ds = ds.set_coords(grid_attrs_in_ds) return ds
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 Returns ------- Dataset Dataset with grid attributes set as coordinates
3.298058
4.712453
0.69986
if da.dtype == np.float32: logging.warning('Datapoints were stored using the np.float32 datatype.' 'For accurate reduction operations using bottleneck, ' 'datapoints are being cast to the np.float64 datatype.' ' For more information see: https://github.com/pydata/' 'xarray/issues/1346') return da.astype(np.float64) else: return da
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
5.302079
5.850239
0.906301
for name in var.names: try: da = ds[name].rename(var.name) if upcast_float32: return _maybe_cast_to_float64(da) else: return da except KeyError: pass msg = '{0} not found among names: {1} in\n{2}'.format(var, var.names, ds) raise LookupError(msg)
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
3.696808
3.202641
1.1543