Skip to content

Commit d2da452

Browse files
authored
Merge pull request #151 from CalebBell/caleb/ruff_2024_07_26
Caleb/ruff 2024 07 26
2 parents 48c6cae + 7ede763 commit d2da452

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

53 files changed

+510
-543
lines changed

.ruff.toml

+19-2
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,28 @@ exclude = [
1010
# "UP031",
1111
# "UP032",
1212
# ]
13+
14+
15+
16+
[lint]
1317
select = ["ALL"]
18+
1419
extend-ignore = [
20+
"FIX002", # TODO are OK
21+
"FIX004", # HACK is OK
22+
1523
"D415", # First docstring line should end with a period, question mark, or exclamation point
1624
"DTZ004", # utcfromtimestamp makes sense for atmosphere model
1725
"PGH003", # type ignoring makes sense for numba-related things
1826
"S102", # Yes, exec is dangerous but it can be quite useful as well
1927

28+
"PYI056", # changing __all__
29+
30+
"RUF012", # not using typing today
31+
"PERF403", # obvious, use an autofix if one becomes available
32+
"PERF203", # `try`-`except` within a loop incurs performance overhead
33+
"PERF401", # PERF401 Use a list comprehension to create a transformed list
34+
2035
# chemicals specific
2136
"E701", # lots of this here
2237

@@ -139,13 +154,15 @@ extend-ignore = [
139154
"TRY002",
140155
"TRY003",
141156
"TRY004",
142-
"TRY200",
157+
"B904",
143158
"TRY201",
144159
"TRY300",
145160
"TRY301",
146161
"TRY400",
147162
"Q000",
148163
"Q002",
164+
165+
"PYI024", # PYI024 Use `typing.NamedTuple` instead of `collections.namedtuple
149166
]
150-
[mccabe]
167+
[lint.mccabe]
151168
max-complexity = 10

thermo/__init__.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,7 @@
9797
phase_identification,
9898
phases,
9999
property_package,
100+
redlich_kister,
100101
regular_solution,
101102
stream,
102103
thermal_conductivity,
@@ -107,7 +108,6 @@
107108
viscosity,
108109
volume,
109110
wilson,
110-
redlich_kister,
111111
)
112112
from .activity import * # noqa: F403
113113
from .bulk import * # noqa: F403
@@ -138,6 +138,7 @@
138138
from .phase_identification import * # noqa: F403
139139
from .phases import * # noqa: F403
140140
from .property_package import * # noqa: F403
141+
from .redlich_kister import * # noqa: F403
141142
from .regular_solution import * # noqa: F403
142143
from .stream import * # noqa: F403
143144
from .thermal_conductivity import * # noqa: F403
@@ -148,7 +149,6 @@
148149
from .viscosity import * # noqa: F403
149150
from .volume import * # noqa: F403
150151
from .wilson import * # noqa: F403
151-
from .redlich_kister import * # noqa: F403
152152

153153
#from chemicals import *
154154

@@ -271,7 +271,6 @@ def complete_lazy_loading():
271271
# pytest timings are hard to measure with lazy loading
272272
complete_lazy_loading()
273273

274-
global vectorized, numba, units, numba_vectorized
275274
if numerics.PY37:
276275
def __getattr__(name):
277276
global vectorized, numba, units, numba_vectorized

thermo/activity.py

+6-7
Original file line numberDiff line numberDiff line change
@@ -69,10 +69,9 @@
6969
__all__ = ['GibbsExcess', 'IdealSolution']
7070
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
7171
from fluids.constants import R, R_inv
72-
from fluids.numerics import exp, log, trunc_exp, derivative, jacobian, hessian
72+
from fluids.numerics import derivative, exp, hessian, jacobian, log, trunc_exp
7373
from fluids.numerics import numpy as np
7474

75-
from thermo import serialize
7675
from thermo.fitting import fit_customized
7776
from thermo.serialize import JsonOptEncodable
7877

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

334333
def __eq__(self, other):
@@ -391,7 +390,7 @@ def exact_hash(self):
391390
d = object_data(self)
392391
ans = hash_any_primitive((self.__class__.__name__, d))
393392
return ans
394-
393+
395394
def as_json(self, cache=None, option=0):
396395
r'''Method to create a JSON-friendly representation of the Gibbs Excess
397396
model which can be stored, and reloaded later.
@@ -448,9 +447,9 @@ def from_json(cls, json_repr, cache=None):
448447
def _custom_from_json(self, *args):
449448
vectorized = self.vectorized
450449
if vectorized and hasattr(self, 'cmp_group_idx'):
451-
setattr(self, 'cmp_group_idx', tuple(array(v) for v in getattr(self, 'cmp_group_idx')))
450+
self.cmp_group_idx = tuple(array(v) for v in self.cmp_group_idx)
452451
if vectorized and hasattr(self, 'group_cmp_idx'):
453-
setattr(self, 'group_cmp_idx', tuple(array(v) for v in getattr(self, 'group_cmp_idx')))
452+
self.group_cmp_idx = tuple(array(v) for v in self.group_cmp_idx)
454453

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

1031-
1030+
10321031
derivatives_added = [('dGE_dT', 'GE', 1),
10331032
('d2GE_dT2', 'GE', 2),
10341033
('d3GE_dT3', 'GE', 3),

thermo/bulk.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -73,13 +73,14 @@
7373

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

76-
from chemicals.utils import Joule_Thomson, isobaric_expansion, isothermal_compressibility, object_data, speed_of_sound, hash_any_primitive
76+
from chemicals.utils import Joule_Thomson, hash_any_primitive, isobaric_expansion, isothermal_compressibility, object_data, speed_of_sound
7777
from fluids.constants import R, atm
7878
from fluids.numerics import exp, log, sqrt
7979
from fluids.two_phase_voidage import gas_liquid_viscosity
80-
from thermo.serialize import arrays_to_lists, JsonOptEncodable, object_lookups
80+
8181
from thermo.phase_identification import DENSITY_MASS, PROP_SORT, S_ID_D2P_DVDT, VL_ID_PIP, WATER_NOT_SPECIAL
8282
from thermo.phases import Phase
83+
from thermo.serialize import JsonOptEncodable, object_lookups
8384

8485
"""Class designed to have multiple phases.
8586
@@ -1715,4 +1716,4 @@ def G_min_criteria(self):
17151716

17161717

17171718
object_lookups[Bulk.__full_path__] = Bulk
1718-
object_lookups[BulkSettings.__full_path__] = BulkSettings
1719+
object_lookups[BulkSettings.__full_path__] = BulkSettings

thermo/chemical.py

+11-11
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@
7171
from chemicals.volume import ideal_gas
7272
from fluids.constants import epsilon_0
7373
from fluids.core import Bond, Capillary, Grashof, Jakob, Peclet_heat, Prandtl, Reynolds, Weber, nu_mu_converter, thermal_diffusivity
74-
from fluids.numerics import exp, log, newton, secant
74+
from fluids.numerics import exp, log, secant
7575

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

@@ -755,11 +755,11 @@ def __init__(self, ID, T=298.15, P=101325, autocalc=True):
755755
self.formula = ID['formula']
756756
# DO NOT REMOVE molecular_weight until the database gets updated with consistent MWs
757757
self.MW = ID['MW'] if 'MW' in ID else molecular_weight(simple_formula_parser(self.formula))
758-
self.PubChem = ID['PubChem'] if 'PubChem' in ID else None
759-
self.smiles = ID['smiles'] if 'smiles' in ID else None
760-
self.InChI = ID['InChI'] if 'InChI' in ID else None
761-
self.InChI_Key = ID['InChI_Key'] if 'InChI_Key' in ID else None
762-
self.synonyms = ID['synonyms'] if 'synonyms' in ID else None
758+
self.PubChem = ID.get('PubChem', None)
759+
self.smiles = ID.get('smiles', None)
760+
self.InChI = ID.get('InChI', None)
761+
self.InChI_Key = ID.get('InChI_Key', None)
762+
self.synonyms = ID.get('synonyms', None)
763763
else:
764764
self.ID = ID
765765
# Identification
@@ -3249,15 +3249,15 @@ def Peclet_heat(self, V=None, D=None):
32493249
# Add the functional groups
32503250
def _make_getter_group(name):
32513251
def get(self):
3252-
base_name = 'is_%s' %(name)
3252+
base_name = f'is_{name}'
32533253
ref = getattr(functional_groups, base_name)
32543254
return ref(self.rdkitmol)
32553255

32563256
return get
32573257
for _name in group_names:
32583258
getter = property(_make_getter_group(_name))
3259-
name = 'is_%s' %(_name)
3260-
_add_attrs_doc = r"""Method to return whether or not this chemical is in the category %s, [-]
3261-
""" %(_name)
3259+
name = f'is_{_name}'
3260+
_add_attrs_doc = rf"""Method to return whether or not this chemical is in the category {_name}, [-]
3261+
"""
32623262
getter.__doc__ = _add_attrs_doc
32633263
setattr(Chemical, name, getter)

thermo/chemical_package.py

+17-10
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@
8484
from chemicals.safety import LFL, STEL, TWA, UFL, Carcinogen, Ceiling, Skin, T_autoignition, T_flash
8585
from chemicals.solubility import solubility_parameter
8686
from chemicals.triple import Pt, Tt
87-
from chemicals.utils import Parachor, hash_any_primitive, property_molar_to_mass
87+
from chemicals.utils import Parachor, hash_any_primitive
8888
from fluids.constants import R
8989

9090
from thermo.chemical import user_chemical_property_lookup
@@ -101,14 +101,21 @@
101101
from thermo.interface import SurfaceTension, SurfaceTensionMixture
102102
from thermo.permittivity import PermittivityLiquid
103103
from thermo.phase_change import EnthalpySublimation, EnthalpyVaporization
104-
from thermo.thermal_conductivity import ThermalConductivityGas, ThermalConductivityGasMixture, ThermalConductivityLiquid, ThermalConductivityLiquidMixture, ThermalConductivitySolid
104+
from thermo.serialize import JsonOptEncodable
105+
from thermo.thermal_conductivity import (
106+
ThermalConductivityGas,
107+
ThermalConductivityGasMixture,
108+
ThermalConductivityLiquid,
109+
ThermalConductivityLiquidMixture,
110+
ThermalConductivitySolid,
111+
)
105112
from thermo.unifac import UNIFAC_RQ, UNIFAC_group_assignment_DDBST, Van_der_Waals_area, Van_der_Waals_volume
106113
from thermo.utils import identify_phase
114+
from thermo.utils.mixture_property import MixtureProperty
107115
from thermo.vapor_pressure import SublimationPressure, VaporPressure
108116
from thermo.viscosity import ViscosityGas, ViscosityGasMixture, ViscosityLiquid, ViscosityLiquidMixture
109117
from thermo.volume import VolumeGas, VolumeGasMixture, VolumeLiquid, VolumeLiquidMixture, VolumeSolid, VolumeSolidMixture
110-
from thermo.utils.mixture_property import MixtureProperty
111-
from thermo.serialize import JsonOptEncodable
118+
112119
CAS_H2O = '7732-18-5'
113120

114121

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

130137

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

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

13821389
try:
@@ -1868,7 +1875,7 @@ def as_poly_fit(self, props=None):
18681875
else:
18691876
iter_props = self.pure_correlations
18701877

1871-
s = '%s(' %(self.__class__.__name__)
1878+
s = f'{self.__class__.__name__}('
18721879
s += 'constants=constants, skip_missing=True,\n'
18731880
for prop in iter_props:
18741881
prop_attr = getattr(self, prop)

thermo/chemical_utils.py

+8-6
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,12 @@
2323

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

26-
from fluids.numerics import quad
27-
from chemicals.reaction import standard_formation_reaction
28-
from thermo.heat_capacity import HeatCapacitySolid, HeatCapacityLiquid, HeatCapacityGas
2926
from chemicals.elements import periodic_table
27+
from chemicals.reaction import standard_formation_reaction
28+
from fluids.numerics import quad
29+
30+
from thermo.heat_capacity import HeatCapacityGas, HeatCapacityLiquid, HeatCapacitySolid
31+
3032

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

290-
solid_ele = set(['C'])
291-
liquid_ele = set([''])
292+
solid_ele = {'C'}
293+
liquid_ele = {''}
292294

293295
for coeff, ele_data in zip(elemental_counts, elemental_composition):
294-
ele = list(ele_data.keys())[0]
296+
ele = next(iter(ele_data.keys()))
295297
element_obj = periodic_table[ele]
296298
# element = Chemical(element_obj.CAS_standard)
297299
solid_obj = element_HeatCapacitySolid_cache(element_obj.CAS_standard)

thermo/coolprop.py

+3-10
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@
3434
from math import exp, log
3535

3636
from chemicals.utils import mark_numba_incompatible
37-
from fluids.numerics import assert_close1d
3837
from fluids.numerics import numpy as np
3938

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

5150
CPiP_min = 17
52-
global _PropsSI
53-
54-
global _has_CoolProp
5551
_has_CoolProp = None
5652
@mark_numba_incompatible
5753
def has_CoolProp():
@@ -72,7 +68,6 @@ def PropsSI(*args, **kwargs):
7268
from CoolProp.CoolProp import PropsSI as _PropsSI
7369
return _PropsSI(*args, **kwargs)
7470

75-
global _HAPropsSI
7671
_HAPropsSI = None
7772
@mark_numba_incompatible
7873
def HAPropsSI(*args, **kwargs):
@@ -81,7 +76,6 @@ def HAPropsSI(*args, **kwargs):
8176
from CoolProp.CoolProp import HAPropsSI as _HAPropsSI
8277
return _HAPropsSI(*args, **kwargs)
8378

84-
global _PhaseSI
8579
_PhaseSI = None
8680
@mark_numba_incompatible
8781
def PhaseSI(*args, **kwargs):
@@ -90,7 +84,6 @@ def PhaseSI(*args, **kwargs):
9084
from CoolProp.CoolProp import PhaseSI as _PhaseSI
9185
return _PhaseSI(*args, **kwargs)
9286

93-
global _AbstractState
9487
_AbstractState = None
9588
@mark_numba_incompatible
9689
def AbstractState(*args, **kwargs):
@@ -230,7 +223,7 @@ def store_coolprop_fluids():
230223

231224
data = {CASRN: coolprop_fluids[CASRN].as_json() for CASRN in coolprop_dict}
232225
ver = CoolProp.__version__
233-
file = open(os.path.join(data_dir, 'CoolPropFluids%s.json' %ver), 'w')
226+
file = open(os.path.join(data_dir, f'CoolPropFluids{ver}.json'), 'w')
234227
json.dump(data, file)
235228
file.close()
236229

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

241234
import CoolProp
242235
ver = CoolProp.__version__
243-
pth = os.path.join(data_dir, 'CoolPropFluids%s.json' %ver)
236+
pth = os.path.join(data_dir, f'CoolPropFluids{ver}.json')
244237
try:
245238
file = open(pth)
246239
except:
@@ -418,7 +411,7 @@ def CoolProp_json_alpha0_to_kwargs(json_data, as_np=False):
418411
# Not relevant
419412
continue
420413
else:
421-
raise ValueError("Unrecognized alpha0 type %s" %(d['type']))
414+
raise ValueError("Unrecognized alpha0 type {}".format(d['type']))
422415

423416
if as_np:
424417
for k, v in kwargs.items():

0 commit comments

Comments
 (0)