Skip to content

Commit

Permalink
Dropping distutils dependencies across the code (#793)
Browse files Browse the repository at this point in the history
In addition to the separate PR that removes distutils from setup.py, there were a number of distutils' LooseVersion() and StrictVersion() uses throughout the code. These have been replaced by packaging.version.parse.
  • Loading branch information
aprsa authored Nov 10, 2023
1 parent 40fbf57 commit 9afaa11
Show file tree
Hide file tree
Showing 9 changed files with 32 additions and 121 deletions.
4 changes: 2 additions & 2 deletions phoebe/dependencies/autofig/axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from matplotlib import gridspec as gridspec
from matplotlib import __version__ as _mplversion

from distutils.version import StrictVersion
from packaging.version import parse

from . import common
from . import callbacks
Expand Down Expand Up @@ -1011,7 +1011,7 @@ def append_subplot(self, fig=None, subplot_grid=None):

for i,ax in enumerate(axes):
try:
if StrictVersion(_mplversion) < StrictVersion("3.4.0"):
if parse(_mplversion) < parse("3.4.0"):
ax.change_geometry(rows, cols, i+1)
else:
ax.set_subplotspec(gridspec.SubplotSpec(gridspec.GridSpec(rows, cols, figure=fig), i))
Expand Down
12 changes: 6 additions & 6 deletions phoebe/dependencies/distl/distl.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import random as _random
import string as _string
from collections import OrderedDict
from distutils.version import StrictVersion
from packaging.version import parse

from . import stats_custom as _stats_custom

Expand Down Expand Up @@ -5689,7 +5689,7 @@ def __init__(self, samples, weights=None, bw_method=None, unit=None,
weights = weights[~nans]

super(Samples, self).__init__(unit, label, label_latex, wrap_at,
_stats.gaussian_kde, ('samples', 'bw_method') if StrictVersion(_scipy_version) < StrictVersion("1.2.0") else ('samples', 'bw_method', 'weights'),
_stats.gaussian_kde, ('samples', 'bw_method') if parse(_scipy_version) < parse("1.2.0") else ('samples', 'bw_method', 'weights'),
samples=samples, weights=weights,
bw_method=bw_method,
uniqueid=uniqueid)
Expand Down Expand Up @@ -5738,7 +5738,7 @@ def weights(self, value):
if value is None:
self._weights = None
else:
if StrictVersion(_scipy_version) < StrictVersion("1.2.0"):
if parse(_scipy_version) < parse("1.2.0"):
raise ImportError("weights for Samples requires scipy 1.2+")
self._weights = is_1d_array(value)
self._dist_constructor_object_clear_cache()
Expand Down Expand Up @@ -7549,7 +7549,7 @@ def __init__(self, samples, weights=None, bw_method=None, units=None,
# NOTE: the passed samples need to be transposed, so see the override
# in dist_constructor_args
super(MVSamples, self).__init__(units, labels, labels_latex, wrap_ats,
_stats.gaussian_kde, ('samples', 'bw_method') if StrictVersion(_scipy_version) < StrictVersion("1.2.0") else ('samples', 'bw_method', 'weights'),
_stats.gaussian_kde, ('samples', 'bw_method') if parse(_scipy_version) < parse("1.2.0") else ('samples', 'bw_method', 'weights'),
samples=samples, weights=weights, bw_method=bw_method,
uniqueid=uniqueid)

Expand Down Expand Up @@ -7577,7 +7577,7 @@ def weights(self, value):
if value is None:
self._weights = None
else:
if StrictVersion(_scipy_version) < StrictVersion("1.2.0"):
if parse(_scipy_version) < parse("1.2.0"):
raise ImportError("weights for Samples requires scipy 1.2+")
self._weights = is_1d_array(value)
self._dist_constructor_object_clear_cache()
Expand Down Expand Up @@ -8001,7 +8001,7 @@ def dist_constructor_func(self):

@property
def dist_constructor_argnames(self):
return ('samples', 'bw_method') if StrictVersion(_scipy_version) < StrictVersion("1.2.0") else ('samples', 'bw_method', 'weights')
return ('samples', 'bw_method') if parse(_scipy_version) < parse("1.2.0") else ('samples', 'bw_method', 'weights')

@property
def samples(self):
Expand Down
6 changes: 3 additions & 3 deletions phoebe/dependencies/nparray/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import json
import os

from distutils.version import LooseVersion
from packaging.version import parse

__version__ = '1.2.0'
version = __version__
Expand Down Expand Up @@ -175,12 +175,12 @@ def geomspace(start, stop, num, endpoint=True, unit=None):
-----------
* <Geomspace>
"""
if LooseVersion(np.__version__) >= LooseVersion("1.13"):
if parse(np.__version__) >= parse("1.13"):
return _wrappers.Geomspace(start, stop, num, endpoint, unit)
else:
raise NotImplementedError("geomspace requires numpy version >= 1.13")

if LooseVersion(np.__version__) >= LooseVersion("1.13"):
if parse(np.__version__) >= parse("1.13"):
geomspace.__doc__ = __docprefix__ + "\n".join([l.lstrip() for l in geomspace.__doc__.split("\n")]) + __docsep__ + np.geomspace.__doc__.replace("&gt;", ">")

def full(shape, fill_value, unit=None):
Expand Down
83 changes: 0 additions & 83 deletions phoebe/dependencies/unitsiau2015/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,88 +23,6 @@ def _register_unit(unit):
# TODO: pass namespace for units package so that prefixes are loaded (otherwise calling ksolMass will call from the old constants)
ns = None

from distutils.version import LooseVersion
if LooseVersion(astropyversion) < LooseVersion('2.0'):


"""
see https://www.iau.org/static/resolutions/IAU2015_English.pdf
Here we'll override astropy's constants to adhere to the IAU Resolution for nominal units
"""

# TODO: find correct error estimate for this value of G
G = Constant('G', "Gravitational constant", 6.67408e-11, 'm3 / (kg s2)', 0.00080e-11, 'NSFA 2011', system='si')
c.G = G
c.si.G = G

GM_sun = Constant('GM_sun', "Solar G*M", 1.3271244e20, 'm3 / (s2)', None, "IAU 2015 Resolution B3", system='si')
c.GM_sun = GM_sun
c.si.GM_sun = GM_sun

GM_earth = Constant('GM_earth', "Earth G*M", 3.986004e14, 'm3 / (s2)', None, "IAU 2015 Resolution B3", system='si')
c.GM_earth = GM_earth
c.si.GM_earth = GM_earth

GM_jup = Constant('GM_jup', "Juptiter G*M", 1.2668653e17, 'm3 / (s2)', None, "IAU 2015 Resolution B3", system='si')
c.GM_jup = GM_jup
c.si.GM_jup = GM_jup

M_sun = Constant('M_sun', "Solar mass", c.GM_sun.value/c.G.value, 'kg', None, "IAU 2015 Resolution B3 (derived from GM_sun and G)", system='si')
c.M_sun = M_sun
c.si.M_sun = M_sun

R_sun = Constant('R_sun', "Solar radius", 6.957e8, 'm', None, "IAU 2015 Resolution B3", system='si')
c.R_sun = R_sun
c.si.R_sun = R_sun

L_sun = Constant('L_sun', "Solar luminosity", 3.828e26, 'W', None, "IAU 2015 Resolution B3", system='si')
c.L_sun = L_sun
c.si.L_sun = L_sun

"""
Now we need to redefine the units to use these constants
"""


solMass = def_unit(['solMass', 'M_sun', 'Msun'], c.si.M_sun, namespace=ns,
prefixes=True, doc="Solar mass (nominal)",
format={'latex': r'{\mathcal{M}^{\rm N}_\odot}'})

_register_unit(solMass)


solRad = def_unit(['solRad', 'R_sun', 'Rsun'], c.si.R_sun, namespace=ns,
doc="Solar radius (nominal)", prefixes=True,
format={'latex': r'{\mathcal{R}^{\rm N}_\odot}'})

_register_unit(solRad)

solLum = def_unit(['solLum', 'L_sun', 'Lsun'], c.si.L_sun, namespace=ns,
prefixes=True, doc="Solar luminance (nominal)",
format={'latex': r'{\mathcal{L}^{\rm N}_\odot}'})

_register_unit(solLum)

"""
Let's cleanup the imports so these entries don't
show at the top-level
"""

del G
del GM_sun
del M_sun
del R_sun
del L_sun
del solMass
del solRad
del solLum


else:
# current defaults in astropy (as of 2.0) are codata2014 and iau2015
pass


"""
T_sun is not provided by astropy 2.0, so we'll set the constant and the unit
Expand Down Expand Up @@ -211,7 +129,6 @@ def to_solar(object):
"""
And lastly, let's do all remaining cleanup
"""
del LooseVersion

del T_sun
del Constant
Expand Down
20 changes: 10 additions & 10 deletions phoebe/frontend/bundle.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
import atexit
import time
from datetime import datetime
from distutils.version import StrictVersion
from packaging.version import parse
from copy import deepcopy as _deepcopy
import pickle as _pickle
from inspect import getsource as _getsource
Expand Down Expand Up @@ -615,8 +615,8 @@ def _ps_dict(ps, include_constrained=True):
b = cls(data)

version = b.get_value(qualifier='phoebe_version', check_default=False, check_visible=False)
phoebe_version_import = StrictVersion(version.split('.dev')[0])
phoebe_version_this = StrictVersion(__version__.split('.dev')[0])
phoebe_version_import = parse(version.split('.dev')[0])
phoebe_version_this = parse(__version__.split('.dev')[0])

logger.debug("importing from PHOEBE v {} into v {}".format(phoebe_version_import, phoebe_version_this))

Expand All @@ -641,7 +641,7 @@ def _ps_dict(ps, include_constrained=True):
logger.debug("temporarily disabling interactive_checks")
conf._interactive_checks = False

if phoebe_version_import < StrictVersion("2.1.0"):
if phoebe_version_import < parse("2.1.0"):
logger.warning("importing from an older version ({}) of PHOEBE into version {}".format(phoebe_version_import, phoebe_version_this))

# rpole -> requiv: https://github.com/phoebe-project/phoebe2/pull/300
Expand Down Expand Up @@ -727,13 +727,13 @@ def _ps_dict(ps, include_constrained=True):
# make sure constraints are updated according to conf.interactive_constraints
b.run_delayed_constraints()

if phoebe_version_import < StrictVersion("2.1.2"):
if phoebe_version_import < parse("2.1.2"):
b._import_before_v211 = True
warning = "importing from an older version ({}) of PHOEBE which did not support constraints in solar units. All constraints will remain in SI, but calling set_hierarchy will likely fail.".format(phoebe_version_import)
print("WARNING: {}".format(warning))
logger.warning(warning)

if phoebe_version_import < StrictVersion("2.2.0"):
if phoebe_version_import < parse("2.2.0"):
warning = "importing from an older version ({}) of PHOEBE to PHOEBE 2.2. Previous versions did not support compute_times, ld_mode/ld_coeffs_source, pblum_mode, l3_mode, etc... all datasets will be migrated to include all new options. This may take some time. Please check all values.".format(phoebe_version_import)
# print("WARNING: {}".format(warning))
logger.warning(warning)
Expand Down Expand Up @@ -838,7 +838,7 @@ def existing_value(param):
logger.debug("restoring previous models")
b._attach_params(ps_model, context='model')

if phoebe_version_import < StrictVersion("2.3.0"):
if phoebe_version_import < parse("2.3.0"):
warning = "importing from an older version ({}) of PHOEBE to PHOEBE 2.3. The previous versions did not support sample_from, etc... all compute options will be migrated to include all new options. Additionally, extinction parameters will be moved from the dataset to system context. This may take some time. Please check all values.".format(phoebe_version_import)
logger.warning(warning)

Expand Down Expand Up @@ -910,13 +910,13 @@ def existing_value(param):
# call set_hierarchy to force asini@component constraints (comp_asini) to be built
b.set_hierarchy()

elif phoebe_version_import < StrictVersion("2.3.25"):
elif phoebe_version_import < parse("2.3.25"):
# elif here since the if above already call set_hierarchy and we want to avoid doing that twice since its expensive

# call set_hierarchy to force mass constraints to be rebuilt
b.set_hierarchy()

if phoebe_version_import < StrictVersion("2.4.0") or ".dev" in version:
if phoebe_version_import < parse("2.4.0") or ".dev" in version:
warning = "importing from an older version ({}) of PHOEBE to PHOEBE 2.4. This may take some time. Please check all values.".format(phoebe_version_import)
logger.warning(warning)

Expand Down Expand Up @@ -983,7 +983,7 @@ def existing_value(param):
p = IntParameter(qualifier='nlags', value=int(nlags_default), limit=(1,1e6), description='number of lags to use when computing/plotting the autocorrelation function')
b._attach_params([p], context='solution', solution=solution, compute=solution_ps.compute, kind='emcee')

if phoebe_version_import < StrictVersion("2.4.4"):
if phoebe_version_import < parse("2.4.4"):
# update mass constraints
for constraint in b.filter(constraint_func=['mass', 'requivsumfrac', 'requivratio'], context='constraint', **_skip_filter_checks).to_list():
logger.warning("re-creating {} constraint".format(constraint.twig))
Expand Down
6 changes: 0 additions & 6 deletions phoebe/parameters/solver/estimator.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,5 @@

from phoebe.parameters import *
from phoebe import conf
from phoebe import geomspace as _geomspace
from phoebe import linspace as _linspace

from distutils.version import StrictVersion
import numpy as np


### NOTE: if creating new parameters, add to the _forbidden_labels list in parameters.py
Expand Down
4 changes: 2 additions & 2 deletions phoebe/solverbackends/rv_geometry.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from scipy.version import version as _scipy_version
from phoebe.constraints.builtin import t0_supconj_to_perpass
from copy import deepcopy
from distutils.version import LooseVersion
from packaging.version import parse

# if os.getenv('PHOEBE_ENABLE_PLOTTING', 'TRUE').upper() == 'TRUE':
# try:
Expand Down Expand Up @@ -163,7 +163,7 @@ def rv_model(phases, P, per0, ecc, asini, vgamma, ph_supconj, component=1):
ph0 = t0_supconj_to_perpass(ph_supconj, 1., ecc, per0, 0., 0., 0.)
# deepcopy is needed for scipy < 1.2.2 because of this bug: https://github.com/scipy/scipy/issues/9964
Es = newton(ecc_anomaly,
deepcopy(phases) if LooseVersion(_scipy_version) < LooseVersion("1.2.2") else phases,
deepcopy(phases) if parse(_scipy_version) < parse("1.2.2") else phases,
args=(phases, ph0*np.ones_like(phases), ecc*np.ones_like(phases)))

thetas = 2*np.arctan(((1+ecc)/(1-ecc))**0.5*np.tan(Es/2))
Expand Down
4 changes: 2 additions & 2 deletions phoebe/solverbackends/solverbackends.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
from phoebe.helpers import get_emcee_object as _get_emcee_object
from phoebe import pool as _pool

from distutils.version import LooseVersion, StrictVersion
from packaging.version import parse
from copy import deepcopy as _deepcopy
import multiprocessing
import pickle
Expand Down Expand Up @@ -1337,7 +1337,7 @@ def run_checks(self, b, solver, compute, **kwargs):
raise ImportError("could not import emcee. Install (pip install emcee) and restart phoebe.")

try:
if LooseVersion(emcee.__version__) < LooseVersion("3.0.0"):
if parse(emcee.__version__) < parse("3.0.0"):
raise ImportError("emcee backend requires emcee 3.0+, {} found. Update emcee and restart phoebe.".format(emcee.__version__))
except ValueError:
# see https://github.com/phoebe-project/phoebe2/issues/378
Expand Down
14 changes: 7 additions & 7 deletions tests/nosetests/test_backward_compatibility/test_import.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import phoebe
import numpy as np

from distutils.version import LooseVersion, StrictVersion
from packaging.version import parse

import os
dir = os.path.dirname(os.path.realpath(__file__))
Expand All @@ -18,7 +18,7 @@ def _export_21(filename, plot=False):
"""


if LooseVersion(phoebe.__version__) >= LooseVersion("2.2"):
if parse(phoebe.__version__) >= parse("2.2"):
raise ImportError("script runs on PHOEBE 2.1.x")
exit()

Expand All @@ -44,7 +44,7 @@ def _export_22(filename, plot=False):
"""


if LooseVersion(phoebe.__version__) >= LooseVersion("2.3"):
if parse(phoebe.__version__) >= parse("2.3"):
raise ImportError("script runs on PHOEBE 2.2.x")
exit()

Expand All @@ -70,7 +70,7 @@ def _export_23(filename, plot=False):
"""


if LooseVersion(phoebe.__version__) >= LooseVersion("2.4"):
if parse(phoebe.__version__) >= parse("2.4"):
raise ImportError("script runs on PHOEBE 2.3.x")
exit()

Expand Down Expand Up @@ -128,13 +128,13 @@ def test_23(verbose=False, plot=False):
if __name__ == '__main__':
logger = phoebe.logger(clevel='WARNING')

# if LooseVersion(phoebe.__version__) >= LooseVersion("2.1.0") and LooseVersion(phoebe.__version__) < LooseVersion("2.2.0"):
# if parse(phoebe.__version__) >= parse("2.1.0") and parse(phoebe.__version__) < parse("2.2.0"):
# _export_21('21_export.phoebe')
# exit()
# if LooseVersion(phoebe.__version__) >= LooseVersion("2.2.0") and LooseVersion(phoebe.__version__) < LooseVersion("2.3.0"):
# if parse(phoebe.__version__) >= parse("2.2.0") and parse(phoebe.__version__) < parse("2.3.0"):
# _export_22('22_export.phoebe')
# exit()
# if LooseVersion(phoebe.__version__) >= LooseVersion("2.3.0") and LooseVersion(phoebe.__version__) < LooseVersion("2.4.0"):
# if parse(phoebe.__version__) >= parse("2.3.0") and parse(phoebe.__version__) < parse("2.4.0"):
# _export_23('23_export.phoebe')
# exit()

Expand Down

0 comments on commit 9afaa11

Please sign in to comment.