Skip to content

Commit

Permalink
replace items removed from numpy namespace (#248)
Browse files Browse the repository at this point in the history
* replace asfarray with asarray of float64

* replace Inf and NaN with inf and nan

* replace a.ptp with np.ptp, and float_ with float64

* limit to numpy < 2.0.0b1
  • Loading branch information
mmckerns authored Aug 1, 2024
1 parent e95fe59 commit 82931b8
Show file tree
Hide file tree
Showing 12 changed files with 41 additions and 39 deletions.
14 changes: 7 additions & 7 deletions mystic/_scipy060optimize.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

import numpy
from numpy import atleast_1d, eye, mgrid, argmin, zeros, shape, empty, \
squeeze, isscalar, vectorize, asarray, absolute, sqrt, Inf, asfarray, isinf
squeeze, isscalar, vectorize, asarray, absolute, sqrt, inf, isinf
from mystic import linesearch
from collections.abc import Callable as _Callable

Expand All @@ -47,9 +47,9 @@ def min(m,axis=0):
_epsilon = sqrt(numpy.finfo(float).eps)

def vecnorm(x, ord=2):
if ord == Inf:
if ord == inf:
return numpy.amax(abs(x))
elif ord == -Inf:
elif ord == -inf:
return numpy.amin(abs(x))
else:
return numpy.sum(abs(x)**ord,axis=0)**(1.0/ord)
Expand Down Expand Up @@ -169,7 +169,7 @@ def fmin(func, x0, args=(), xtol=1e-4, ftol=1e-4, maxiter=None, maxfun=None,
of one or more variables.
"""
fcalls, func = wrap_function(func, args)
x0 = asfarray(x0).flatten()
x0 = asarray(x0, dtype='float64').flatten()
N = len(x0)
rank = len(x0.shape)
if not -1 < rank < 2:
Expand Down Expand Up @@ -626,7 +626,7 @@ def approx_fhess_p(x0,p,fprime,epsilon,*args):
f1 = fprime(*((x0,)+args))
return (f2 - f1)/epsilon

def fmin_bfgs(f, x0, fprime=None, args=(), gtol=1e-5, norm=Inf,
def fmin_bfgs(f, x0, fprime=None, args=(), gtol=1e-5, norm=inf,
epsilon=_epsilon, maxiter=None, full_output=0, disp=1,
retall=0, callback=None):
"""Minimize a function using the BFGS algorithm.
Expand All @@ -642,7 +642,7 @@ def fmin_bfgs(f, x0, fprime=None, args=(), gtol=1e-5, norm=Inf,
gtol : number
gradient norm must be less than gtol before succesful termination
norm : number
order of norm (Inf is max, -Inf is min)
order of norm (inf is max, -inf is min)
epsilon : number
if fprime is approximated use this value for
the step size (can be scalar or vector)
Expand Down Expand Up @@ -812,7 +812,7 @@ def fmin_bfgs(f, x0, fprime=None, args=(), gtol=1e-5, norm=Inf,

return retlist

def fmin_cg(f, x0, fprime=None, args=(), gtol=1e-5, norm=Inf, epsilon=_epsilon,
def fmin_cg(f, x0, fprime=None, args=(), gtol=1e-5, norm=inf, epsilon=_epsilon,
maxiter=None, full_output=0, disp=1, retall=0, callback=None):
"""Minimize a function with nonlinear conjugate gradient algorithm.
Expand Down
6 changes: 3 additions & 3 deletions mystic/abstract_solver.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ class interface, a simple function interface for a derived solver class

import random
import numpy
from numpy import inf, shape, asarray, absolute, asfarray, seterr
from numpy import inf, shape, asarray, absolute, seterr
from mystic.tools import wrap_function, wrap_nested, wrap_reducer
from mystic.tools import wrap_bounds, wrap_penalty, reduced
from klepto import isvalid, validate
Expand Down Expand Up @@ -472,7 +472,7 @@ def SetInitialPoints(self, x0, radius=0.05):
Returns:
None
"""
x0 = asfarray(x0)
x0 = asarray(x0, dtype='float64')
rank = len(x0.shape)
if rank == 0:
x0.shape = (1,)
Expand All @@ -482,7 +482,7 @@ def SetInitialPoints(self, x0, radius=0.05):
if len(x0) != self.nDim:
raise ValueError("Initial guess must be length %s" % self.nDim)

radius = asfarray(radius) # may be scalar or a nDim array
radius = asarray(radius, dtype='float64') # maybe scalar or a nDim array
_rank = len(radius.shape)

if _rank and len(radius) != self.nDim:
Expand Down
5 changes: 3 additions & 2 deletions mystic/collapse.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

import mystic.monitors as _m
inf = _m.numpy.inf
np = _m.numpy

##### parameter collapse detectors #####
def collapse_at(stepmon, target=None, tolerance=0.005, \
Expand Down Expand Up @@ -38,7 +39,7 @@ def collapse_at(stepmon, target=None, tolerance=0.005, \
tolerance = np.asarray(tolerance)
tolerance.shape = (-1,1)
params = _m._solutions(stepmon, generations)
if target is None: params = params.ptp(axis=0) <= tolerance
if target is None: params = np.ptp(params, axis=0) <= tolerance
else: params = abs(params - target).max(axis=0) <= tolerance
# get tuple of indices of where collapsed
params = np.where(params)[-1]
Expand Down Expand Up @@ -84,7 +85,7 @@ def collapse_as(stepmon, offset=False, tolerance=0.005, \
from mystic.tools import pairwise
distances, pairs = pairwise(distances, True)
if offset: # tracking at a distance
distances = distances.ptp(axis=0) <= tolerance
distances = np.ptp(distances, axis=0) <= tolerance
else: # tracking with the same position
distances = distances.max(axis=0) <= tolerance
# get the (index1,index2) pairs where the collapse occurs
Expand Down
4 changes: 2 additions & 2 deletions mystic/constraints.py
Original file line number Diff line number Diff line change
Expand Up @@ -720,7 +720,7 @@ def _constraint(x):
return cf


from numpy import asfarray, asarray, choose, zeros, ones, ndarray
from numpy import asarray, choose, zeros, ones, ndarray
from numpy import shape, broadcast, empty, atleast_1d
#from random import sample, choice
def discrete(samples, index=None):
Expand Down Expand Up @@ -1208,7 +1208,7 @@ def bounded(seq, bounds, index=None, clip=True, nearest=True):
if bounds is None or not bounds: return seq
if isinstance(index, int): index = (index,)
if not hasattr(bounds[0], '__len__'): bounds = (bounds,)
bounds = asfarray(bounds).T # is [(min,min,...),(max,max,...)]
bounds = asarray(bounds, dtype='float64').T # [(min,min,...),(max,max,...)]
# convert None to -inf or inf
bounds[0][isnan(bounds[0])] = -inf
bounds[1][isnan(bounds[1])] = inf
Expand Down
6 changes: 3 additions & 3 deletions mystic/differential_evolution.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@
from mystic.abstract_solver import AbstractSolver
from mystic.abstract_map_solver import AbstractMapSolver

from numpy import asfarray, ravel, isinf
from numpy import asarray, ravel, isinf
from collections.abc import Callable as _Callable

class DifferentialEvolutionSolver(AbstractSolver):
Expand Down Expand Up @@ -280,7 +280,7 @@ def _Step(self, cost=None, ExtraArgs=None, **kwds):
if not len(self._stepmon): # do generation = 0
init = True
strategy = None
self.population[0] = asfarray(self.population[0])
self.population[0] = asarray(self.population[0], dtype='float64')
# decouple bestSolution from population and bestEnergy from popEnergy
bs = self.population[0]
self.bestSolution = bs.copy() if hasattr(bs, 'copy') else bs[:]
Expand Down Expand Up @@ -529,7 +529,7 @@ def _Step(self, cost=None, ExtraArgs=None, **kwds):
if not len(self._stepmon): # do generation = 0
init = True
strategy = None
self.population[0] = asfarray(self.population[0])
self.population[0] = asarray(self.population[0], dtype='float64')
# decouple bestSolution from population and bestEnergy from popEnergy
bs = self.population[0]
self.bestSolution = bs.copy() if hasattr(bs, 'copy') else bs[:]
Expand Down
4 changes: 2 additions & 2 deletions mystic/math/_rbf.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ def _init_function(self, r):
return a0

def __init__(self, *args, **kwargs):
self.xi = np.asarray([np.asarray(a, dtype=np.float_).flatten()
self.xi = np.asarray([np.asarray(a, dtype=np.float64).flatten()
for a in args[:-1]])
self.N = self.xi.shape[-1]
self.di = np.asarray(args[-1]).flatten()
Expand Down Expand Up @@ -254,6 +254,6 @@ def __call__(self, *args):
if not all([x.shape == y.shape for x in args for y in args]):
raise ValueError("Array lengths must be equal")
shp = args[0].shape
xa = np.asarray([a.flatten() for a in args], dtype=np.float_)
xa = np.asarray([a.flatten() for a in args], dtype=np.float64)
r = self._call_norm(xa, self.xi)
return np.dot(self._function(r), self.nodes).reshape(shp)
2 changes: 1 addition & 1 deletion mystic/math/approx.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ def almostEqual(x, y, tol=1e-18, rel=1e-7):
-------
y : bool
Returns True if the two arrays are equal within the given
tolerance; False otherwise. If either array contains NaN, then
tolerance; False otherwise. If either array contains nan, then
False is returned.
Notes
Expand Down
18 changes: 9 additions & 9 deletions mystic/scipy_optimize.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@
from mystic.tools import wrap_bounds, wrap_penalty, reduced

import numpy
from numpy import eye, zeros, shape, asarray, absolute, asfarray
from numpy import eye, zeros, shape, asarray, absolute
from numpy import clip, squeeze

abs = absolute
Expand Down Expand Up @@ -262,8 +262,8 @@ def _Step(self, cost=None, ExtraArgs=None, **kwds):
if not len(self._stepmon): # do generation = 0
init = True
x0 = self.population[0]
x0 = asfarray(x0).flatten()
x0 = asfarray(constraints(x0))
x0 = asarray(x0, dtype='float64').flatten()
x0 = asarray(constraints(x0), dtype='float64')
#####XXX: this blows away __init__, so replace __init__ with this?
N = len(x0)
rank = len(x0.shape)
Expand Down Expand Up @@ -301,7 +301,7 @@ def _Step(self, cost=None, ExtraArgs=None, **kwds):
one2np1 = range(1,N+1)

# apply constraints #XXX: is this the only appropriate place???
sim[0] = asfarray(constraints(sim[0]))
sim[0] = asarray(constraints(sim[0]), dtype='float64')

xbar = numpy.add.reduce(sim[:-1],0) / N
xr = (1+rho)*xbar - rho*sim[-1]
Expand Down Expand Up @@ -646,8 +646,8 @@ def _Step(self, cost=None, ExtraArgs=None, **kwds):

if not len(self._stepmon): # do generation = 0
init = True
x = asfarray(x).flatten()
x = asfarray(constraints(x))
x = asarray(x, dtype='float64').flatten()
x = asarray(constraints(x), dtype='float64')
N = len(x) #XXX: this should be equal to self.nDim
rank = len(x.shape)
if not -1 < rank < 2:
Expand Down Expand Up @@ -680,7 +680,7 @@ def _Step(self, cost=None, ExtraArgs=None, **kwds):
bigind = i

# apply constraints
x = asfarray(constraints(x)) #XXX: use self._map?
x = asarray(constraints(x), dtype='float64') #XXX: self._map?
# decouple from 'best' energy
self.energy_history = self.energy_history + [fval]

Expand All @@ -702,7 +702,7 @@ def _Step(self, cost=None, ExtraArgs=None, **kwds):
direc[bigind] = direc[-1]
direc[-1] = direc1

# x = asfarray(constraints(x))
# x = asarray(constraints(x), dtype='float64')

self._direc = direc
self.population[0] = x # bestSolution
Expand All @@ -726,7 +726,7 @@ def _Step(self, cost=None, ExtraArgs=None, **kwds):
bigind = i

# apply constraints
x = asfarray(constraints(x)) #XXX: use self._map?
x = asarray(constraints(x), dtype='float64') #XXX: self._map?

# decouple from 'best' energy
self.energy_history = self.energy_history + [fval]
Expand Down
2 changes: 1 addition & 1 deletion mystic/scripts.py
Original file line number Diff line number Diff line change
Expand Up @@ -1077,7 +1077,7 @@ def model_plotter(model, logfile=None, **kwds):
For finer control, provide an array[float] the same length as ``params``.
"""
#FIXME: should be able to:
# - apply a constraint as a region of NaN -- apply when 'xx,yy=x[ij],y[ij]'
# - apply a constraint as a region of nan -- apply when 'xx,yy=x[ij],y[ij]'
# - apply a penalty by shifting the surface (plot w/alpha?) -- as above
# - build an appropriately-sized default grid (from logfile info)
# - move all mulit-id param/cost reading into read_history
Expand Down
13 changes: 7 additions & 6 deletions mystic/termination.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@
"""

import numpy
np = numpy
abs = numpy.absolute
inf = Inf = numpy.Inf
nan = NaN = numpy.NaN
inf = numpy.inf
nan = numpy.nan
null = ""
_type = type #NOTE: save builtin type
import mystic.collapse as ct #XXX: avoid if move Collapse* to collapse
Expand Down Expand Up @@ -355,7 +356,7 @@ def _PopulationSpread(inst, info=False):
_PopulationSpread.__doc__ = doc
return _PopulationSpread

def GradientNormTolerance(tolerance=1e-5, norm=Inf):
def GradientNormTolerance(tolerance=1e-5, norm=inf):
"""gradient norm is < tolerance, given user-supplied norm:
``sum( abs(gradient)**norm )**(1.0/norm) <= tolerance``
Expand Down Expand Up @@ -389,8 +390,8 @@ def EvaluationLimits(generations=None, evaluations=None):
'evaluations':evaluations}
maxfun = [evaluations]
maxiter = [generations]
if maxfun[0] is None: maxfun[0] = Inf
if maxiter[0] is None: maxiter[0] = Inf
if maxfun[0] is None: maxfun[0] = inf
if maxiter[0] is None: maxiter[0] = inf
def _EvaluationLimits(inst, info=False):
if info: info = lambda x:x
else: info = bool
Expand Down Expand Up @@ -421,7 +422,7 @@ def TimeLimits(seconds=86400, system=None): #NOTE: 24 hours
def _reset():
start[0] = timer()
delta = [getattr(seconds, 'total_seconds', seconds.__abs__)()]
if delta[0] is None: delta[0] = Inf
if delta[0] is None: delta[0] = inf
def _TimeLimits(inst, info=False):
if info: info = lambda x:x
else: info = bool
Expand Down
4 changes: 2 additions & 2 deletions mystic/tests/test_termination.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
NormalizedCostTarget(fval=None, tolerance=1e-6, generations=30)
VTRChangeOverGeneration(ftol=0.005, gtol=1e-6, generations=30)
PopulationSpread(tolerance=1e-6)
GradientNormTolerance(tolerance=1e-5, norm=Inf)
GradientNormTolerance(tolerance=1e-5, norm=inf)
EvaluationLimits(generations=None, evaluations=None)
TimeLimits(seconds=86400, system=None)
"""
Expand Down Expand Up @@ -190,7 +190,7 @@ def test08(terminate, func=lambda x:x[0], info=False, debug=False):
while test05-test06 returns a ndarray for population, popEnergy, bestSolution;
test07-test08 throw a RuntimeError "Too many iterations" due to "bracket()".
For x:inf, test01-test02 have 1e+20 in energy_history, popEnergy, bestEnergy;
while test03-test04 have inf; test05-test06 have Inf in popEnergy;
while test03-test04 have inf; test05-test06 have inf in popEnergy;
while test07-test08 have array(inf) for energy_history, popEnergy,
and inf for bestEnergy, and energy_history, popEnergy, population is list
of ndarrays, while bestSolution is an ndarray.
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ def has_ext_modules(foo):
pathos_version = 'pathos>=0.3.2'
pyina_version = 'pyina>=0.2.9'
cython_version = 'cython>=0.29.30' #XXX: required to build numpy from source
numpy_version = 'numpy>=1.0'
numpy_version = 'numpy>=1.0, <2.0.0b1'
sympy_version = 'sympy>=0.6.7'#, <0.7.4'
scipy_version = 'scipy>=0.6.0'
mpmath_version = 'mpmath>=0.19'
Expand Down

0 comments on commit 82931b8

Please sign in to comment.