Skip to content

Commit

Permalink
Merge pull request #151 from CalebBell/caleb/ruff_2024_07_26
Browse files Browse the repository at this point in the history
Caleb/ruff 2024 07 26
  • Loading branch information
CalebBell committed Jul 26, 2024
2 parents 48c6cae + 7ede763 commit d2da452
Show file tree
Hide file tree
Showing 53 changed files with 510 additions and 543 deletions.
21 changes: 19 additions & 2 deletions .ruff.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,28 @@ exclude = [
# "UP031",
# "UP032",
# ]



[lint]
select = ["ALL"]

extend-ignore = [
"FIX002", # TODO are OK
"FIX004", # HACK is OK

"D415", # First docstring line should end with a period, question mark, or exclamation point
"DTZ004", # utcfromtimestamp makes sense for atmosphere model
"PGH003", # type ignoring makes sense for numba-related things
"S102", # Yes, exec is dangerous but it can be quite useful as well

"PYI056", # changing __all__

"RUF012", # not using typing today
"PERF403", # obvious, use an autofix if one becomes available
"PERF203", # `try`-`except` within a loop incurs performance overhead
"PERF401", # PERF401 Use a list comprehension to create a transformed list

# chemicals specific
"E701", # lots of this here

Expand Down Expand Up @@ -139,13 +154,15 @@ extend-ignore = [
"TRY002",
"TRY003",
"TRY004",
"TRY200",
"B904",
"TRY201",
"TRY300",
"TRY301",
"TRY400",
"Q000",
"Q002",

"PYI024", # PYI024 Use `typing.NamedTuple` instead of `collections.namedtuple
]
[mccabe]
[lint.mccabe]
max-complexity = 10
5 changes: 2 additions & 3 deletions thermo/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@
phase_identification,
phases,
property_package,
redlich_kister,
regular_solution,
stream,
thermal_conductivity,
Expand All @@ -107,7 +108,6 @@
viscosity,
volume,
wilson,
redlich_kister,
)
from .activity import * # noqa: F403
from .bulk import * # noqa: F403
Expand Down Expand Up @@ -138,6 +138,7 @@
from .phase_identification import * # noqa: F403
from .phases import * # noqa: F403
from .property_package import * # noqa: F403
from .redlich_kister import * # noqa: F403
from .regular_solution import * # noqa: F403
from .stream import * # noqa: F403
from .thermal_conductivity import * # noqa: F403
Expand All @@ -148,7 +149,6 @@
from .viscosity import * # noqa: F403
from .volume import * # noqa: F403
from .wilson import * # noqa: F403
from .redlich_kister import * # noqa: F403

#from chemicals import *

Expand Down Expand Up @@ -271,7 +271,6 @@ def complete_lazy_loading():
# pytest timings are hard to measure with lazy loading
complete_lazy_loading()

global vectorized, numba, units, numba_vectorized
if numerics.PY37:
def __getattr__(name):
global vectorized, numba, units, numba_vectorized
Expand Down
13 changes: 6 additions & 7 deletions thermo/activity.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,9 @@
__all__ = ['GibbsExcess', 'IdealSolution']
from chemicals.utils import d2xs_to_dxdn_partials, dns_to_dn_partials, dxs_to_dn_partials, dxs_to_dns, hash_any_primitive, normalize, object_data
from fluids.constants import R, R_inv
from fluids.numerics import exp, log, trunc_exp, derivative, jacobian, hessian
from fluids.numerics import derivative, exp, hessian, jacobian, log, trunc_exp
from fluids.numerics import numpy as np

from thermo import serialize
from thermo.fitting import fit_customized
from thermo.serialize import JsonOptEncodable

Expand Down Expand Up @@ -328,7 +327,7 @@ def __repr__(self):
IdealSolution(T=300.0, xs=[.1, .2, .3, .4])
'''
# Other classes with different parameters should expose them here too
s = f'{self.__class__.__name__}(T={repr(self.T)}, xs={repr(self.xs)})'
s = f'{self.__class__.__name__}(T={self.T!r}, xs={self.xs!r})'
return s

def __eq__(self, other):
Expand Down Expand Up @@ -391,7 +390,7 @@ def exact_hash(self):
d = object_data(self)
ans = hash_any_primitive((self.__class__.__name__, d))
return ans

def as_json(self, cache=None, option=0):
r'''Method to create a JSON-friendly representation of the Gibbs Excess
model which can be stored, and reloaded later.
Expand Down Expand Up @@ -448,9 +447,9 @@ def from_json(cls, json_repr, cache=None):
def _custom_from_json(self, *args):
vectorized = self.vectorized
if vectorized and hasattr(self, 'cmp_group_idx'):
setattr(self, 'cmp_group_idx', tuple(array(v) for v in getattr(self, 'cmp_group_idx')))
self.cmp_group_idx = tuple(array(v) for v in self.cmp_group_idx)
if vectorized and hasattr(self, 'group_cmp_idx'):
setattr(self, 'group_cmp_idx', tuple(array(v) for v in getattr(self, 'group_cmp_idx')))
self.group_cmp_idx = tuple(array(v) for v in self.group_cmp_idx)

def HE(self):
r'''Calculate and return the excess entropy of a liquid phase using an
Expand Down Expand Up @@ -1028,7 +1027,7 @@ def _regress_binary_parameters(cls, gammas, xs, fitting_func, fit_parameters,
**fit_kwargs)
return res


derivatives_added = [('dGE_dT', 'GE', 1),
('d2GE_dT2', 'GE', 2),
('d3GE_dT3', 'GE', 3),
Expand Down
7 changes: 4 additions & 3 deletions thermo/bulk.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,13 +73,14 @@

__all__ = ['Bulk', 'BulkSettings', 'default_settings']

from chemicals.utils import Joule_Thomson, isobaric_expansion, isothermal_compressibility, object_data, speed_of_sound, hash_any_primitive
from chemicals.utils import Joule_Thomson, hash_any_primitive, isobaric_expansion, isothermal_compressibility, object_data, speed_of_sound
from fluids.constants import R, atm
from fluids.numerics import exp, log, sqrt
from fluids.two_phase_voidage import gas_liquid_viscosity
from thermo.serialize import arrays_to_lists, JsonOptEncodable, object_lookups

from thermo.phase_identification import DENSITY_MASS, PROP_SORT, S_ID_D2P_DVDT, VL_ID_PIP, WATER_NOT_SPECIAL
from thermo.phases import Phase
from thermo.serialize import JsonOptEncodable, object_lookups

"""Class designed to have multiple phases.
Expand Down Expand Up @@ -1715,4 +1716,4 @@ def G_min_criteria(self):


object_lookups[Bulk.__full_path__] = Bulk
object_lookups[BulkSettings.__full_path__] = BulkSettings
object_lookups[BulkSettings.__full_path__] = BulkSettings
22 changes: 11 additions & 11 deletions thermo/chemical.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@
from chemicals.volume import ideal_gas
from fluids.constants import epsilon_0
from fluids.core import Bond, Capillary, Grashof, Jakob, Peclet_heat, Prandtl, Reynolds, Weber, nu_mu_converter, thermal_diffusivity
from fluids.numerics import exp, log, newton, secant
from fluids.numerics import exp, log, secant

from thermo import functional_groups
from thermo.electrochem import conductivity, conductivity_methods
Expand Down Expand Up @@ -99,7 +99,7 @@
CHEMSEP = (298., 101325, 'g', 0, 0, True) # It has an option to add Hf to the reference
PRO_II = (298.15, 101325, 'gas', 0, 0, True)
HYSYS = (298.15, 101325, 'calc', 'Hf', 0, True)
UNISIM = HYSYS #
UNISIM = HYSYS
SUPERPRO = (298.15, 101325, 'calc', 0, 0, True) # No support for entropy found, 0 assumed
# note soecifying a phase works for chemicals but not mixtures.

Expand Down Expand Up @@ -755,11 +755,11 @@ def __init__(self, ID, T=298.15, P=101325, autocalc=True):
self.formula = ID['formula']
# DO NOT REMOVE molecular_weight until the database gets updated with consistent MWs
self.MW = ID['MW'] if 'MW' in ID else molecular_weight(simple_formula_parser(self.formula))
self.PubChem = ID['PubChem'] if 'PubChem' in ID else None
self.smiles = ID['smiles'] if 'smiles' in ID else None
self.InChI = ID['InChI'] if 'InChI' in ID else None
self.InChI_Key = ID['InChI_Key'] if 'InChI_Key' in ID else None
self.synonyms = ID['synonyms'] if 'synonyms' in ID else None
self.PubChem = ID.get('PubChem', None)
self.smiles = ID.get('smiles', None)
self.InChI = ID.get('InChI', None)
self.InChI_Key = ID.get('InChI_Key', None)
self.synonyms = ID.get('synonyms', None)
else:
self.ID = ID
# Identification
Expand Down Expand Up @@ -3249,15 +3249,15 @@ def Peclet_heat(self, V=None, D=None):
# Add the functional groups
def _make_getter_group(name):
def get(self):
base_name = 'is_%s' %(name)
base_name = f'is_{name}'
ref = getattr(functional_groups, base_name)
return ref(self.rdkitmol)

return get
for _name in group_names:
getter = property(_make_getter_group(_name))
name = 'is_%s' %(_name)
_add_attrs_doc = r"""Method to return whether or not this chemical is in the category %s, [-]
""" %(_name)
name = f'is_{_name}'
_add_attrs_doc = rf"""Method to return whether or not this chemical is in the category {_name}, [-]
"""
getter.__doc__ = _add_attrs_doc
setattr(Chemical, name, getter)
27 changes: 17 additions & 10 deletions thermo/chemical_package.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@
from chemicals.safety import LFL, STEL, TWA, UFL, Carcinogen, Ceiling, Skin, T_autoignition, T_flash
from chemicals.solubility import solubility_parameter
from chemicals.triple import Pt, Tt
from chemicals.utils import Parachor, hash_any_primitive, property_molar_to_mass
from chemicals.utils import Parachor, hash_any_primitive
from fluids.constants import R

from thermo.chemical import user_chemical_property_lookup
Expand All @@ -101,14 +101,21 @@
from thermo.interface import SurfaceTension, SurfaceTensionMixture
from thermo.permittivity import PermittivityLiquid
from thermo.phase_change import EnthalpySublimation, EnthalpyVaporization
from thermo.thermal_conductivity import ThermalConductivityGas, ThermalConductivityGasMixture, ThermalConductivityLiquid, ThermalConductivityLiquidMixture, ThermalConductivitySolid
from thermo.serialize import JsonOptEncodable
from thermo.thermal_conductivity import (
ThermalConductivityGas,
ThermalConductivityGasMixture,
ThermalConductivityLiquid,
ThermalConductivityLiquidMixture,
ThermalConductivitySolid,
)
from thermo.unifac import UNIFAC_RQ, UNIFAC_group_assignment_DDBST, Van_der_Waals_area, Van_der_Waals_volume
from thermo.utils import identify_phase
from thermo.utils.mixture_property import MixtureProperty
from thermo.vapor_pressure import SublimationPressure, VaporPressure
from thermo.viscosity import ViscosityGas, ViscosityGasMixture, ViscosityLiquid, ViscosityLiquidMixture
from thermo.volume import VolumeGas, VolumeGasMixture, VolumeLiquid, VolumeLiquidMixture, VolumeSolid, VolumeSolidMixture
from thermo.utils.mixture_property import MixtureProperty
from thermo.serialize import JsonOptEncodable

CAS_H2O = '7732-18-5'


Expand All @@ -128,7 +135,7 @@
fairly easily once the data entry is complete."""


class ChemicalConstantsPackage():
class ChemicalConstantsPackage:
non_vector_properties = ('atomss', 'Carcinogens', 'CASs', 'Ceilings', 'charges',
'conductivities', 'dipoles', 'economic_statuses', 'formulas', 'Gfgs',
'Gfgs_mass', 'GWPs', 'Hcs', 'Hcs_lower', 'Hcs_lower_mass', 'Hcs_mass',
Expand Down Expand Up @@ -186,7 +193,7 @@ def _custom_as_json(self, d, cache):
for k in ('PSRK_groups', 'UNIFAC_Dortmund_groups', 'UNIFAC_groups'):
# keys are stored as strings and not ints
d[k] = [{str(k): v for k, v in r.items()} if r is not None else r for r in d[k]]


# This is not so much a performance optimization as an improvement on file size
# and readability. Do not remove it! Comparing against an empty list is the
Expand Down Expand Up @@ -1374,9 +1381,9 @@ def __init__(self, CASs=None, names=None, MWs=None, Tms=None, Tbs=None,
"""
for name, (var_type, desc, units, return_desc) in constants_docstrings.items():
type_name = var_type if type(var_type) is str else var_type.__name__
new = """{} : {}
{}, {}.
""".format(name, type_name, desc, units)
new = f"""{name} : {type_name}
{desc}, {units}.
"""
constants_doc += new

try:
Expand Down Expand Up @@ -1868,7 +1875,7 @@ def as_poly_fit(self, props=None):
else:
iter_props = self.pure_correlations

s = '%s(' %(self.__class__.__name__)
s = f'{self.__class__.__name__}('
s += 'constants=constants, skip_missing=True,\n'
for prop in iter_props:
prop_attr = getattr(self, prop)
Expand Down
14 changes: 8 additions & 6 deletions thermo/chemical_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,12 @@

__all__ = ['standard_entropy', 'S0_basis_converter', 'standard_state_ideal_gas_formation']

from fluids.numerics import quad
from chemicals.reaction import standard_formation_reaction
from thermo.heat_capacity import HeatCapacitySolid, HeatCapacityLiquid, HeatCapacityGas
from chemicals.elements import periodic_table
from chemicals.reaction import standard_formation_reaction
from fluids.numerics import quad

from thermo.heat_capacity import HeatCapacityGas, HeatCapacityLiquid, HeatCapacitySolid


def standard_entropy(c=None, dS_trans_s=None, dH_trans_s=None, T_trans_s=None,
Cp_s_fun=None,
Expand Down Expand Up @@ -287,11 +289,11 @@ def _standard_state_ideal_gas_formation_direct(T, Hf_ref, Sf_ref, atoms, gas_Cp,
S_calc = reactant_coeff*Sf_ref + reactant_coeff*dS_compound
# if the compound is an element it will need special handling to go from solid liquid to gas if needed

solid_ele = set(['C'])
liquid_ele = set([''])
solid_ele = {'C'}
liquid_ele = {''}

for coeff, ele_data in zip(elemental_counts, elemental_composition):
ele = list(ele_data.keys())[0]
ele = next(iter(ele_data.keys()))
element_obj = periodic_table[ele]
# element = Chemical(element_obj.CAS_standard)
solid_obj = element_HeatCapacitySolid_cache(element_obj.CAS_standard)
Expand Down
13 changes: 3 additions & 10 deletions thermo/coolprop.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@
from math import exp, log

from chemicals.utils import mark_numba_incompatible
from fluids.numerics import assert_close1d
from fluids.numerics import numpy as np

from thermo.base import data_dir
Expand All @@ -49,9 +48,6 @@
#has_CoolProp = False # For testing

CPiP_min = 17
global _PropsSI

global _has_CoolProp
_has_CoolProp = None
@mark_numba_incompatible
def has_CoolProp():
Expand All @@ -72,7 +68,6 @@ def PropsSI(*args, **kwargs):
from CoolProp.CoolProp import PropsSI as _PropsSI
return _PropsSI(*args, **kwargs)

global _HAPropsSI
_HAPropsSI = None
@mark_numba_incompatible
def HAPropsSI(*args, **kwargs):
Expand All @@ -81,7 +76,6 @@ def HAPropsSI(*args, **kwargs):
from CoolProp.CoolProp import HAPropsSI as _HAPropsSI
return _HAPropsSI(*args, **kwargs)

global _PhaseSI
_PhaseSI = None
@mark_numba_incompatible
def PhaseSI(*args, **kwargs):
Expand All @@ -90,7 +84,6 @@ def PhaseSI(*args, **kwargs):
from CoolProp.CoolProp import PhaseSI as _PhaseSI
return _PhaseSI(*args, **kwargs)

global _AbstractState
_AbstractState = None
@mark_numba_incompatible
def AbstractState(*args, **kwargs):
Expand Down Expand Up @@ -230,7 +223,7 @@ def store_coolprop_fluids():

data = {CASRN: coolprop_fluids[CASRN].as_json() for CASRN in coolprop_dict}
ver = CoolProp.__version__
file = open(os.path.join(data_dir, 'CoolPropFluids%s.json' %ver), 'w')
file = open(os.path.join(data_dir, f'CoolPropFluids{ver}.json'), 'w')
json.dump(data, file)
file.close()

Expand All @@ -240,7 +233,7 @@ def load_coolprop_fluids(depth=0):

import CoolProp
ver = CoolProp.__version__
pth = os.path.join(data_dir, 'CoolPropFluids%s.json' %ver)
pth = os.path.join(data_dir, f'CoolPropFluids{ver}.json')
try:
file = open(pth)
except:
Expand Down Expand Up @@ -418,7 +411,7 @@ def CoolProp_json_alpha0_to_kwargs(json_data, as_np=False):
# Not relevant
continue
else:
raise ValueError("Unrecognized alpha0 type %s" %(d['type']))
raise ValueError("Unrecognized alpha0 type {}".format(d['type']))

if as_np:
for k, v in kwargs.items():
Expand Down
Loading

0 comments on commit d2da452

Please sign in to comment.