def func_hook(self, np_func: _NpFn, wrapped: _MyFn[_Arr]) -> _MyFn[_Arr]: """This method is called on the wrapped function before returning Parameters ---------- np_func : Callable[...->ndarray] The `numpy` function being wrapped. wrapped : Callable[...->Array] The wrapped function. Returns ------- wrapped : Callable[...->Array] The wrapped function. """ super().func_hook(np_func, wrapped) old_name = f"{self._mod_name}.{np_func.__name__}" new_name = f"{np_func.__module__}.{np_func.__name__}" msg = "This function will be removed in numpy_linalg 0.4.0" new_wrapped = _np.deprecate(wrapped, old_name=old_name, new_name=new_name, message=msg) return super().func_hook(np_func, new_wrapped)
else: raise ValueError('1D option "%s" is strange' % oned_as) return shape class ByteOrder(object): ''' Namespace for byte ordering ''' little_endian = boc.sys_is_le native_code = boc.native_code swapped_code = boc.swapped_code to_numpy_code = boc.to_numpy_code ByteOrder = np.deprecate(ByteOrder, message=""" We no longer use the ByteOrder class, and deprecate it; we will remove it in future versions of scipy. Please use the scipy.io.matlab.byteordercodes module instead. """) class MatVarReader(object): ''' Abstract class defining required interface for var readers''' def __init__(self, file_reader): pass def read_header(self): ''' Returns header ''' pass def array_from_header(self, header): ''' Reads array given header '''
Partially flattened array. Raises ------ ValueError If `start > stop`. """ if stop is None: stop = arr.ndim newshape = arr.shape[:start] + (-1,) + arr.shape[stop:] if len(newshape) > arr.ndim + 1: raise ValueError(f"start={start} > stop={stop}") return np.reshape(arr, newshape) flattish = np.deprecate(ravelaxes, old_name='flattish', new_name='ravelaxes', message="This alias will be removed in v.0.4.0") @set_module('numpy_linalg') def unravelaxis(arr: np.ndarray, axis: int, shape: ty.Tuple[int, ...] ) -> np.ndarray: """Partial unflattening. Folds an `axis` into `shape`. Parameters ---------- arr : np.ndarray (...,L,M*N*...*P*Q,R,...) Array to be partially folded. axis : int Axis to be folded.
loader_path = os.path.abspath(loader_path) if not os.path.isdir(loader_path): libdir = os.path.dirname(loader_path) else: libdir = loader_path for ln in libname_ext: try: libpath = os.path.join(libdir, ln) return ctypes.cdll[libpath] except OSError, e: pass raise e ctypes_load_library = deprecate(load_library, 'ctypes_load_library', 'load_library') def _num_fromflags(flaglist): num = 0 for val in flaglist: num += _flagdict[val] return num _flagnames = ['C_CONTIGUOUS', 'F_CONTIGUOUS', 'ALIGNED', 'WRITEABLE', 'OWNDATA', 'UPDATEIFCOPY'] def _flags_fromnum(num): res = [] for key in _flagnames: value = _flagdict[key] if (num & value): res.append(key)
C[should_be_nan] = np.nan return C def maybe_unwrap_results(results): """ Gets raw results back from wrapped results. Can be used in plotting functions or other post-estimation type routines. """ return getattr(results, '_results', results) class Bunch(dict): """ Returns a dict-like object with keys accessible via attribute lookup. """ def __init__(self, **kw): dict.__init__(self, kw) self.__dict__ = self webuse = np.deprecate(webuse, old_name='statsmodels.tools.tools.webuse', new_name='statsmodels.datasets.webuse', message='webuse will be removed from the tools ' 'namespace in the 0.7.0 release. Please use the' ' new import.')
#Use this to add a new axis to an array #compatibility only NewAxis = None #deprecated UFuncType = type(um.sin) UfuncType = type(um.sin) ArrayType = mu.ndarray arraytype = mu.ndarray LittleEndian = (sys.byteorder == 'little') from numpy import deprecate # backward compatibility arrayrange = deprecate(functions.arange, 'arrayrange', 'arange') # deprecated names matrixmultiply = deprecate(mu.dot, 'matrixmultiply', 'dot') def DumpArray(m, fp): m.dump(fp) def LoadArray(fp): import cPickle return cPickle.load(fp) def array_constructor(shape, typecode, thestr, Endian=LittleEndian): if typecode == "O": x = array(thestr, "O") else:
from pandas import DatetimeIndex # pylint: disable=E0611 date_range = DatetimeIndex(start=start_date, freq=offset, periods=n) return data, date_range def get_logdet(m): from statsmodels.tools.linalg import logdet_symm return logdet_symm(m) get_logdet = np.deprecate( get_logdet, "statsmodels.tsa.vector_ar.util.get_logdet", "statsmodels.tools.linalg.logdet_symm", "get_logdet is deprecated and will be removed in " "0.8.0", ) def norm_signif_level(alpha=0.05): return stats.norm.ppf(1 - alpha / 2) def acf_to_acorr(acf): diag = np.diag(acf[0]) # numpy broadcasting sufficient return acf / np.sqrt(np.outer(diag, diag)) def varsim(coefs, intercept, sig_u, steps=100, initvalues=None, seed=None):
__all__ = ['bicg', 'bicgstab', 'cg', 'cgs', 'gmres', 'qmr'] # Deprecated on January 26, 2008 from scipy.sparse.linalg import isolve from numpy import deprecate for name in __all__: oldfn = getattr(isolve, name) oldname = 'scipy.linalg.' + name newname = 'scipy.sparse.linalg.' + name newfn = deprecate(oldfn, oldname=oldname, newname=newname) exec(name + ' = newfn')
import numpy as np np.deprecate(1) # E: No overload variant np.deprecate_with_doc(1) # E: incompatible type np.byte_bounds(1) # E: incompatible type np.who(1) # E: incompatible type np.lookfor(None) # E: incompatible type np.safe_eval(None) # E: incompatible type
""" if r is None: r = np_matrix_rank(X) V, D, U = L.svd(X, full_matrices=0) order = np.argsort(D) order = order[::-1] value = [] for i in range(r): value.append(V[:, order[i]]) return np.asarray(np.transpose(value)).astype(np.float64) StepFunction = np.deprecate(StepFunction, old_name='statsmodels.tools.tools.StepFunction', new_name='statsmodels.distributions.StepFunction') monotone_fn_inverter = np.deprecate(monotone_fn_inverter, old_name='statsmodels.tools.tools' '.monotone_fn_inverter', new_name='statsmodels.distributions' '.monotone_fn_inverter') ECDF = np.deprecate(ECDF, old_name='statsmodels.tools.tools.ECDF', new_name='statsmodels.distributions.ECDF') def unsqueeze(data, axis, oldshape): """ Unsqueeze a collapsed array
the same name as the module. """ dir,filename = os.path.split(module.__file__) filebase = filename.split('.')[0] fn = os.path.join(dir, filebase) f = dumb_shelve.open(fn, "r") #exec( 'import ' + module.__name__) for i in f.keys(): exec( 'import ' + module.__name__+ ';' + module.__name__+'.'+i + '=' + 'f["' + i + '"]') # print i, 'loaded...' # print 'done' load = deprecate(_load, message=""" This is an internal function used with scipy.io.save_as_module If you are saving arrays into a module, you should think about using HDF5 or .npz files instead. """) def _create_module(file_name): """ Create the module file. """ if not os.path.exists(file_name+'.py'): # don't clobber existing files module_name = os.path.split(file_name)[-1] f = open(file_name+'.py','w') f.write('import scipy.io.data_store as data_store\n') f.write('import %s\n' % module_name) f.write('data_store._load(%s)' % module_name) f.close()
libdir = os.path.dirname(loader_path) else: libdir = loader_path for ln in libname_ext: libpath = os.path.join(libdir, ln) if os.path.exists(libpath): try: return ctypes.cdll[libpath] except OSError: ## defective lib file raise ## if no successful return in the libname_ext loop: raise OSError("no file with expected extension") ctypes_load_library = deprecate(load_library, "ctypes_load_library", "load_library") def _num_fromflags(flaglist): num = 0 for val in flaglist: num += _flagdict[val] return num _flagnames = [ "C_CONTIGUOUS", "F_CONTIGUOUS", "ALIGNED", "WRITEABLE", "OWNDATA",
minus_ones = shape.count(-1) if minus_ones == 0: pass elif minus_ones == 1: known_dimensions_size = -np.product(shape, axis=0) * dt.itemsize unknown_dimension_size, illegal = divmod(self.remaining_bytes(), known_dimensions_size) if illegal: raise ValueError("unknown dimension doesn't match filesize") shape[shape.index(-1)] = unknown_dimension_size else: raise ValueError( "illegal -1 count; can only specify one unknown dimension") sz = dt.itemsize * np.product(shape) dt_endian = self._endian_from_dtype(dt) buf = self.file.read(sz) arr = np.ndarray(shape=shape, dtype=dt, buffer=buf, order=order) if (not endian == 'dtype') and (dt_endian != endian): return arr.byteswap() return arr.copy() npfile = np.deprecate(npfile, message=""" You can achieve the same effect as using npfile using numpy.save and numpy.load. You can use memory-mapped arrays and data-types to map out a file format for direct manipulation in NumPy. """)
if minus_ones == 0: pass elif minus_ones == 1: known_dimensions_size = -np.product(shape,axis=0) * dt.itemsize unknown_dimension_size, illegal = divmod(self.remaining_bytes(), known_dimensions_size) if illegal: raise ValueError("unknown dimension doesn't match filesize") shape[shape.index(-1)] = unknown_dimension_size else: raise ValueError( "illegal -1 count; can only specify one unknown dimension") sz = dt.itemsize * np.product(shape) dt_endian = self._endian_from_dtype(dt) buf = self.file.read(sz) arr = np.ndarray(shape=shape, dtype=dt, buffer=buf, order=order) if (not endian == 'dtype') and (dt_endian != endian): return arr.byteswap() return arr.copy() npfile = np.deprecate(npfile, message=""" You can achieve the same effect as using npfile using numpy.save and numpy.load. You can use memory-mapped arrays and data-types to map out a file format for direct manipulation in NumPy. """)
'find_edges':ImageFilter.FIND_EDGES, 'smooth':ImageFilter.SMOOTH, 'smooth_more':ImageFilter.SMOOTH_MORE, 'sharpen':ImageFilter.SHARPEN } im = toimage(arr) if ftype not in _tdict.keys(): raise ValueError("Unknown filter type.") return fromimage(im.filter(_tdict[ftype])) def radon(arr,theta=None): """`radon` is deprecated in scipy 0.11, and will be removed in 0.12 For this functionality, please use the "radon" function in scikits-image. """ if theta is None: theta = mgrid[0:180] s = zeros((arr.shape[1],len(theta)), float) k = 0 for th in theta: im = imrotate(arr,-th) s[:,k] = sum(im,axis=0) k += 1 return s radon = numpy.deprecate(radon)
clapack = _DeprecatedImport("scipy.linalg.blas.clapack", "scipy.linalg.lapack") flapack = _DeprecatedImport("scipy.linalg.blas.flapack", "scipy.linalg.lapack") # Expose all functions (only flapack --- clapack is an implementation detail) empty_module = None from scipy.linalg._flapack import * del empty_module _dep_message = """The `*gegv` family of routines has been deprecated in LAPACK 3.6.0 in favor of the `*ggev` family of routines. The corresponding wrappers will be removed from SciPy in a future release.""" cgegv = _np.deprecate(cgegv, old_name="cgegv", message=_dep_message) dgegv = _np.deprecate(dgegv, old_name="dgegv", message=_dep_message) sgegv = _np.deprecate(sgegv, old_name="sgegv", message=_dep_message) zgegv = _np.deprecate(zgegv, old_name="zgegv", message=_dep_message) # Modyfy _flapack in this scope so the deprecation warnings apply to # functions returned by get_lapack_funcs. _flapack.cgegv = cgegv _flapack.dgegv = dgegv _flapack.sgegv = sgegv _flapack.zgegv = zgegv # some convenience alias for complex functions _lapack_alias = { "corghr": "cunghr", "zorghr": "zunghr",
from info import __doc__ from numpy import deprecate # These are all deprecated (until the end deprecated tag) from npfile import npfile from data_store import save, load, create_module, create_shelf from array_import import read_array, write_array from pickler import objload, objsave from numpyio import packbits, unpackbits, bswap, fread, fwrite, \ convert_objectarray fread = deprecate(fread, message=""" scipy.io.fread can be replaced with NumPy I/O routines such as np.load, np.fromfile as well as NumPy's memory-mapping capabilities. """) fwrite = deprecate(fwrite, message=""" scipy.io.fwrite can be replaced with NumPy I/O routines such as np.save, np.savez and x.tofile. Also, files can be directly memory-mapped into NumPy arrays which is often a better way of reading large files. """) bswap = deprecate(bswap, message=""" scipy.io.bswap can be replaced with the byteswap method on an array. out = scipy.io.bswap(arr) --> out = arr.byteswap(True) """) packbits = deprecate(packbits, message=""" The functionality of scipy.io.packbits is now available as numpy.packbits
def _bessel_diff_formula(v, z, n, L, phase): # from AMS55. # L(v,z) = J(v,z), Y(v,z), H1(v,z), H2(v,z), phase = -1 # L(v,z) = I(v,z) or exp(v*pi*i)K(v,z), phase = 1 # For K, you can pull out the exp((v-k)*pi*i) into the caller p = 1.0 s = L(v - n, z) for i in xrange(1, n + 1): p = phase * (p * (n - i + 1)) / i # = choose(k, i) s += p * L(v - n + i * 2, z) return s / (2.**n) bessel_diff_formula = np.deprecate( _bessel_diff_formula, message="bessel_diff_formula is a private function, do not use it!") def jvp(v, z, n=1): """Return the nth derivative of Jv(z) with respect to z. """ if not isinstance(n, int) or (n < 0): raise ValueError("n must be a non-negative integer.") if n == 0: return jv(v, z) else: return _bessel_diff_formula(v, z, n, jv, -1) # return (jvp(v-1,z,n-1) - jvp(v+1,z,n-1))/2.0
gk *= 1.05 id = _gen_unique_rand(gk) j = np.floor(id * 1. / m).astype(tp) i = (id - j * m).astype(tp) vals = np.random.rand(k).astype(dtype) return coo_matrix((vals, (i, j)), shape=(m, n)).asformat(format) ################################# # Deprecated functions ################################ __all__ += ['speye', 'spidentity', 'spkron', 'lil_eye', 'lil_diags'] spkron = np.deprecate(kron, old_name='spkron', new_name='scipy.sparse.kron') speye = np.deprecate(eye, old_name='speye', new_name='scipy.sparse.eye') spidentity = np.deprecate(identity, old_name='spidentity', new_name='scipy.sparse.identity') def lil_eye((r, c), k=0, dtype='d'): """Generate a lil_matrix of dimensions (r,c) with the k-th diagonal set to 1. Parameters ---------- r,c : int row and column-dimensions of the output.
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE # GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import numpy from filters import * from fourier import * from interpolation import * from measurements import * from morphology import * from io import * # doccer is moved to scipy.misc in scipy 0.8 from scipy.misc import doccer doccer = numpy.deprecate(doccer, old_name='doccer', new_name='scipy.misc.doccer') from info import __doc__ __version__ = '2.0' from numpy.testing import Tester test = Tester().test
""" if r is None: r = rank(X) V, D, U = L.svd(X, full_matrices=0) order = np.argsort(D) order = order[::-1] value = [] for i in range(r): value.append(V[:, order[i]]) return np.asarray(np.transpose(value)).astype(np.float64) StepFunction = np.deprecate(StepFunction, old_name='statsmodels.tools.tools.StepFunction', new_name='statsmodels.distributions.StepFunction') monotone_fn_inverter = np.deprecate( monotone_fn_inverter, old_name='statsmodels.tools.tools.monotone_fn_inverter', new_name='statsmodels.distributions.monotone_fn_inverter') ECDF = np.deprecate(ECDF, old_name='statsmodels.tools.tools.ECDF', new_name='statsmodels.distributions.ECDF') def unsqueeze(data, axis, oldshape): """ Unsqueeze a collapsed array >>> from numpy import mean
using HDF5 or .npz files instead. """)(_create_module) def _create_shelf(file_name,data): """Use this to write the data to a new file """ shelf_name = file_name.split('.')[0] f = dumb_shelve.open(shelf_name,'w') for i in data.keys(): # print 'saving...',i f[i] = data[i] # print 'done' f.close() create_shelf = deprecate_with_doc(""" This is an internal function used with scipy.io.save_as_module If you are saving arrays into a module, you should think about using HDF5 or .npz files instead. """)(_create_shelf) def save_as_module(file_name=None,data=None): """ Save the dictionary "data" into a module and shelf named save """ _create_module(file_name) _create_shelf(file_name,data) save = deprecate(save_as_module, 'save', 'save_as_module')
if obs.ndim != code_book.ndim: raise ValueError("Observation and code_book should have the same rank") if obs.ndim == 1: obs = obs[:, np.newaxis] code_book = code_book[:, np.newaxis] dist = cdist(obs, code_book) code = dist.argmin(axis=1) min_dist = dist[np.arange(len(code)), code] return code, min_dist # py_vq2 was equivalent to py_vq py_vq2 = np.deprecate(py_vq, old_name='py_vq2', new_name='py_vq') def _kmeans(obs, guess, thresh=1e-5): """ "raw" version of k-means. Returns ------- code_book The lowest distortion codebook found. avg_dist The average distance a observation is from a code in the book. Lower means the code_book matches the data better. See Also --------
from .sf_error import SpecialFunctionWarning, SpecialFunctionError from ._ufuncs import * from .basic import * from ._logsumexp import logsumexp, softmax from . import specfun from . import orthogonal from .orthogonal import * from .spfun_stats import multigammaln from ._ellip_harm import ellip_harm, ellip_harm_2, ellip_normal from .lambertw import lambertw from ._spherical_bessel import (spherical_jn, spherical_yn, spherical_in, spherical_kn) from numpy import deprecate hyp2f0 = deprecate(hyp2f0, message="hyp2f0 is deprecated in SciPy 1.2") hyp1f2 = deprecate(hyp1f2, message="hyp1f2 is deprecated in SciPy 1.2") hyp3f0 = deprecate(hyp3f0, message="hyp3f0 is deprecated in SciPy 1.2") del deprecate __all__ = [s for s in dir() if not s.startswith('_')] from numpy.dual import register_func register_func('i0',i0) del register_func from scipy._lib._testutils import PytestTester test = PytestTester(__name__) del PytestTester
loader_path = os.path.abspath(loader_path) if not os.path.isdir(loader_path): libdir = os.path.dirname(loader_path) else: libdir = loader_path for ln in libname_ext: try: libpath = os.path.join(libdir, ln) return ctypes.cdll[libpath] except OSError, e: pass raise e ctypes_load_library = deprecate(load_library, 'ctypes_load_library', 'load_library') def _num_fromflags(flaglist): num = 0 for val in flaglist: num += _flagdict[val] return num _flagnames = [ 'C_CONTIGUOUS', 'F_CONTIGUOUS', 'ALIGNED', 'WRITEABLE', 'OWNDATA', 'UPDATEIFCOPY' ]
def _create_shelf(file_name, data): """Use this to write the data to a new file """ shelf_name = file_name.split('.')[0] f = dumb_shelve.open(shelf_name, 'w') for i in data.keys(): # print 'saving...',i f[i] = data[i] # print 'done' f.close() create_shelf = deprecate_with_doc(""" This is an internal function used with scipy.io.save_as_module If you are saving arrays into a module, you should think about using HDF5 or .npz files instead. """)(_create_shelf) def save_as_module(file_name=None, data=None): """ Save the dictionary "data" into a module and shelf named save """ _create_module(file_name) _create_shelf(file_name, data) save = deprecate(save_as_module, 'save', 'save_as_module')
d_ks = ksstat(z, stats.norm.cdf, alternative='two_sided') if pvalmethod == 'approx': pval = pval_lf(d_ks, nobs) elif pvalmethod == 'table': #pval = pval_lftable(d_ks, nobs) pval = lilliefors_table.prob(d_ks, nobs) return d_ks, pval lilliefors = kstest_normal lillifors = np.deprecate(lilliefors, 'lillifors', 'lilliefors', "Use lilliefors, lillifors will be " "removed in 0.9 \n(Note: misspelling missing 'e')") #old version: #------------ tble = '''\ 00 20 15 10 05 01 .1 4 .303 .321 .346 .376 .413 .433 5 .289 .303 .319 .343 .397 .439 6 .269 .281 .297 .323 .371 .424 7 .252 .264 .280 .304 .351 .402 8 .239 .250 .265 .288 .333 .384 9 .227 .238 .252 .274 .317 .365 10 .217 .228 .241 .262 .304 .352
dz = get_slice_spacing(series) return dx, dy, dz @csv_series def get_image_size(series: Series): rows = get_common_tag(series, 'Rows') columns = get_common_tag(series, 'Columns') slices = len(series) return rows, columns, slices # ------------------ DEPRECATED ------------------------ get_image_plane = np.deprecate(get_slices_plane, old_name='get_image_plane') get_xyz_spacing = np.deprecate(get_voxel_spacing, old_name='get_xyz_spacing') @np.deprecate def get_axes_permutation(row: pd.Series): return np.abs(get_orientation_matrix(row)).argmax(axis=0) @np.deprecate @csv_series def get_image_position_patient(series: Series): """Returns ImagePositionPatient stacked into array.""" return np.stack(list(map(_get_image_position_patient, series)))
from io import StringIO from typing import Any, Dict import numpy as np AR: np.ndarray[Any, np.dtype[np.float64]] AR_DICT: Dict[str, np.ndarray[Any, np.dtype[np.float64]]] FILE: StringIO def func(a: int) -> bool: ... reveal_type(np.deprecate(func)) # E: def (a: builtins.int) -> builtins.bool reveal_type(np.deprecate()) # E: _Deprecate reveal_type(np.deprecate_with_doc("test")) # E: _Deprecate reveal_type(np.deprecate_with_doc(None)) # E: _Deprecate reveal_type(np.byte_bounds(AR)) # E: Tuple[builtins.int, builtins.int] reveal_type(np.byte_bounds(np.float64())) # E: Tuple[builtins.int, builtins.int] reveal_type(np.who(None)) # E: None reveal_type(np.who(AR_DICT)) # E: None reveal_type(np.info(1, output=FILE)) # E: None reveal_type(np.source(np.interp, output=FILE)) # E: None reveal_type(np.lookfor("binary representation", output=FILE)) # E: None reveal_type(np.safe_eval("1 + 1")) # E: Any
from .sf_error import SpecialFunctionWarning, SpecialFunctionError from ._ufuncs import * from .basic import * from ._logsumexp import logsumexp, softmax from . import specfun from . import orthogonal from .orthogonal import * from .spfun_stats import multigammaln from ._ellip_harm import ellip_harm, ellip_harm_2, ellip_normal from .lambertw import lambertw from ._spherical_bessel import (spherical_jn, spherical_yn, spherical_in, spherical_kn) from numpy import deprecate hyp2f0 = deprecate(hyp2f0, message="hyp2f0 is deprecated in SciPy 1.2") hyp1f2 = deprecate(hyp1f2, message="hyp1f2 is deprecated in SciPy 1.2") hyp3f0 = deprecate(hyp3f0, message="hyp3f0 is deprecated in SciPy 1.2") del deprecate __all__ = [s for s in dir() if not s.startswith('_')] from numpy.dual import register_func register_func('i0', i0) del register_func from scipy._lib._testutils import PytestTester test = PytestTester(__name__) del PytestTester
'find_edges': ImageFilter.FIND_EDGES, 'smooth': ImageFilter.SMOOTH, 'smooth_more': ImageFilter.SMOOTH_MORE, 'sharpen': ImageFilter.SHARPEN } im = toimage(arr) if ftype not in _tdict.keys(): raise ValueError("Unknown filter type.") return fromimage(im.filter(_tdict[ftype])) def radon(arr, theta=None): """`radon` is deprecated in scipy 0.11, and will be removed in 0.12 For this functionality, please use the "radon" function in scikits-image. """ if theta is None: theta = mgrid[0:180] s = zeros((arr.shape[1], len(theta)), float) k = 0 for th in theta: im = imrotate(arr, -th) s[:, k] = sum(im, axis=0) k += 1 return s radon = numpy.deprecate(radon)
""" return getattr(results, '_results', results) class Bunch(dict): """ Returns a dict-like object with keys accessible via attribute lookup. """ def __init__(self, **kw): dict.__init__(self, kw) self.__dict__ = self webuse = np.deprecate(webuse, old_name='statsmodels.tools.tools.webuse', new_name='statsmodels.datasets.webuse', message='webuse will be removed from the tools ' 'namespace in the 0.7.0 release. Please use the' ' new import.') def _ensure_2d(x, ndarray=False): """ Parameters ---------- x : array, Series, DataFrame or None Input to verify dimensions, and to transform as necesary ndarray : bool Flag indicating whether to always return a NumPy array. Setting False will return an pandas DataFrame when the input is a Series or a DataFrame.
#Use this to add a new axis to an array #compatibility only NewAxis = None #deprecated UFuncType = type(um.sin) UfuncType = type(um.sin) ArrayType = mu.ndarray arraytype = mu.ndarray LittleEndian = (sys.byteorder == 'little') from numpy import deprecate # backward compatibility arrayrange = deprecate(functions.arange, 'arrayrange', 'arange') # deprecated names matrixmultiply = deprecate(mu.dot, 'matrixmultiply', 'dot') def DumpArray(m, fp): m.dump(fp) def LoadArray(fp): import cPickle return cPickle.load(fp) def array_constructor(shape, typecode, thestr, Endian=LittleEndian):
# Use this to add a new axis to an array # compatibility only NewAxis = None # deprecated UFuncType = type(um.sin) UfuncType = type(um.sin) ArrayType = mu.ndarray arraytype = mu.ndarray LittleEndian = sys.byteorder == "little" from numpy import deprecate # backward compatibility arrayrange = deprecate(functions.arange, "arrayrange", "arange") # deprecated names matrixmultiply = deprecate(mu.dot, "matrixmultiply", "dot") def DumpArray(m, fp): m.dump(fp) def LoadArray(fp): import cPickle return cPickle.load(fp)
def _bessel_diff_formula(v, z, n, L, phase): # from AMS55. # L(v,z) = J(v,z), Y(v,z), H1(v,z), H2(v,z), phase = -1 # L(v,z) = I(v,z) or exp(v*pi*i)K(v,z), phase = 1 # For K, you can pull out the exp((v-k)*pi*i) into the caller p = 1.0 s = L(v-n, z) for i in xrange(1, n+1): p = phase * (p * (n-i+1)) / i # = choose(k, i) s += p*L(v-n + i*2, z) return s / (2.**n) bessel_diff_formula = np.deprecate(_bessel_diff_formula, message="bessel_diff_formula is a private function, do not use it!") def jvp(v,z,n=1): """Return the nth derivative of Jv(z) with respect to z. """ if not isinstance(n,int) or (n < 0): raise ValueError("n must be a non-negative integer.") if n == 0: return jv(v,z) else: return _bessel_diff_formula(v, z, n, jv, -1) # return (jvp(v-1,z,n-1) - jvp(v+1,z,n-1))/2.0 def yvp(v,z,n=1):
if obs.ndim != code_book.ndim: raise ValueError("Observation and code_book should have the same rank") if obs.ndim == 1: obs = obs[:, np.newaxis] code_book = code_book[:, np.newaxis] dist = cdist(obs, code_book) code = dist.argmin(axis=1) min_dist = dist[np.arange(len(code)), code] return code, min_dist # py_vq2 was equivalent to py_vq py_vq2 = np.deprecate(py_vq, old_name='py_vq2', new_name='py_vq') def _kmeans(obs, guess, thresh=1e-5): """ "raw" version of k-means. Returns ------- code_book the lowest distortion codebook found. avg_dist the average distance a observation is from a code in the book. Lower means the code_book matches the data better. See Also --------
__all__ = ['who', 'source', 'info', 'doccer', 'pade', 'comb', 'factorial', 'factorial2', 'factorialk', 'logsumexp'] from . import doccer from .common import * from numpy import who as _who, source as _source, info as _info import numpy as np from scipy.interpolate._pade import pade as _pade from scipy.special import (comb as _comb, logsumexp as _lsm, factorial as _fact, factorial2 as _fact2, factorialk as _factk) import sys _msg = ("Importing `%(name)s` from scipy.misc is deprecated in scipy 1.0.0. Use " "`scipy.special.%(name)s` instead.") comb = np.deprecate(_comb, message=_msg % {"name": _comb.__name__}) logsumexp = np.deprecate(_lsm, message=_msg % {"name": _lsm.__name__}) factorial = np.deprecate(_fact, message=_msg % {"name": _fact.__name__}) factorial2 = np.deprecate(_fact2, message=_msg % {"name": _fact2.__name__}) factorialk = np.deprecate(_factk, message=_msg % {"name": _factk.__name__}) _msg = ("Importing `pade` from scipy.misc is deprecated in scipy 1.0.0. Use " "`scipy.interpolate.pade` instead.") pade = np.deprecate(_pade, message=_msg) _msg = ("Importing `%(name)s` from scipy.misc is deprecated in scipy 1.0.0. Use " "`numpy.%(name)s` instead.") who = np.deprecate(_who, message=_msg % {"name": "who"}) source = np.deprecate(_source, message=_msg % {"name": "source"}) @np.deprecate(message=_msg % {"name": "info.(..., toplevel='scipy')"})
libdir = os.path.dirname(loader_path) else: libdir = loader_path for ln in libname_ext: libpath = os.path.join(libdir, ln) if os.path.exists(libpath): try: return ctypes.cdll[libpath] except OSError: ## defective lib file raise ## if no successful return in the libname_ext loop: raise OSError("no file with expected extension") ctypes_load_library = deprecate(load_library, "ctypes_load_library", "load_library") def _num_fromflags(flaglist): num = 0 for val in flaglist: num += _flagdict[val] return num _flagnames = ["C_CONTIGUOUS", "F_CONTIGUOUS", "ALIGNED", "WRITEABLE", "OWNDATA", "UPDATEIFCOPY"] def _flags_fromnum(num): res = [] for key in _flagnames:
while id.size < k: gk *= 1.05 id = _gen_unique_rand(gk) j = np.floor(id * 1. / m).astype(tp) i = (id - j * m).astype(tp) vals = np.random.rand(k).astype(dtype) return coo_matrix((vals, (i, j)), shape=(m, n)).asformat(format) ################################# # Deprecated functions ################################ __all__ += [ 'speye','spidentity', 'spkron', 'lil_eye', 'lil_diags' ] spkron = np.deprecate(kron, old_name='spkron', new_name='scipy.sparse.kron') speye = np.deprecate(eye, old_name='speye', new_name='scipy.sparse.eye') spidentity = np.deprecate(identity, old_name='spidentity', new_name='scipy.sparse.identity') def lil_eye((r,c), k=0, dtype='d'): """Generate a lil_matrix of dimensions (r,c) with the k-th diagonal set to 1. Parameters ---------- r,c : int row and column-dimensions of the output. k : int
# Backward compatibility from scipy._lib._util import DeprecatedImport as _DeprecatedImport clapack = _DeprecatedImport("scipy.linalg.blas.clapack", "scipy.linalg.lapack") flapack = _DeprecatedImport("scipy.linalg.blas.flapack", "scipy.linalg.lapack") # Expose all functions (only flapack --- clapack is an implementation detail) empty_module = None from scipy.linalg._flapack import * del empty_module _dep_message = """The `*gegv` family of routines has been deprecated in LAPACK 3.6.0 in favor of the `*ggev` family of routines. The corresponding wrappers will be removed from SciPy in a future release.""" cgegv = _np.deprecate(cgegv, old_name='cgegv', message=_dep_message) dgegv = _np.deprecate(dgegv, old_name='dgegv', message=_dep_message) sgegv = _np.deprecate(sgegv, old_name='sgegv', message=_dep_message) zgegv = _np.deprecate(zgegv, old_name='zgegv', message=_dep_message) # Modyfy _flapack in this scope so the deprecation warnings apply to # functions returned by get_lapack_funcs. _flapack.cgegv = cgegv _flapack.dgegv = dgegv _flapack.sgegv = sgegv _flapack.zgegv = zgegv # Patching EVR Methods to handle value ranges _evr_doc = """ w,z,info = {name}(a,[jobz,range,uplo,il,iu,lwork,overwrite_a,vl,vu])
d_ks = ksstat(z, test_d, alternative='two_sided') if pvalmethod == 'approx': pval = pval_lf(d_ks, nobs) # check pval is in desired range if pval > 0.1: pval = lilliefors_table.prob(d_ks, nobs) elif pvalmethod == 'table': pval = lilliefors_table.prob(d_ks, nobs) return d_ks, pval lilliefors = kstest_fit lillifors = np.deprecate( lilliefors, 'lillifors', 'lilliefors', "Use lilliefors, lillifors will be " "removed in 0.9 \n(Note: misspelling missing 'e')") # namespace aliases from functools import partial kstest_normal = kstest_fit kstest_exponential = partial(kstest_fit, dist='exp') # old version: # ------------ ''' tble = \ 00 20 15 10 05 01 .1 4 .303 .321 .346 .376 .413 .433 5 .289 .303 .319 .343 .397 .439 6 .269 .281 .297 .323 .371 .424
__all__ = ['bicg','bicgstab','cg','cgs','gmres','qmr'] # Deprecated on January 26, 2008 from scipy.sparse.linalg import isolve from numpy import deprecate for name in __all__: oldfn = getattr(isolve, name) oldname='scipy.linalg.' + name newname='scipy.sparse.linalg.' + name newfn = deprecate(oldfn, old_name=oldname, new_name=newname) exec(name + ' = newfn')
This function is deprecated in scipy 0.11 and will be removed for 0.12 Parameters ---------- file_name : str, optional File name of the module to save. data : dict, optional The dictionary to store in the module. """ _create_module(file_name) _create_shelf(file_name,data) save_as_module = np.deprecate(save_as_module) def _load(module): """ Load data into module from a shelf with the same name as the module. """ dir,filename = os.path.split(module.__file__) filebase = filename.split('.')[0] fn = os.path.join(dir, filebase) f = dumb_shelve.open(fn, "r") #exec( 'import ' + module.__name__) for i in f.keys(): exec( 'import ' + module.__name__+ ';' + module.__name__+'.'+i + '=' + 'f["' + i + '"]')
""" if r is None: r = rank(X) V, D, U = L.svd(X, full_matrices=0) order = np.argsort(D) order = order[::-1] value = [] for i in range(r): value.append(V[:,order[i]]) return np.asarray(np.transpose(value)).astype(np.float64) StepFunction = np.deprecate(StepFunction, old_name = 'statsmodels.tools.tools.StepFunction', new_name = 'statsmodels.distributions.StepFunction') monotone_fn_inverter = np.deprecate(monotone_fn_inverter, old_name = 'statsmodels.tools.tools.monotone_fn_inverter', new_name = 'statsmodels.distributions.monotone_fn_inverter') ECDF = np.deprecate(ECDF, old_name = 'statsmodels.tools.tools.ECDF', new_name = 'statsmodels.distributions.ECDF') def unsqueeze(data, axis, oldshape): """ Unsqueeze a collapsed array >>> from numpy import mean >>> from numpy.random import standard_normal
from __future__ import annotations from io import StringIO from typing import Any import numpy as np FILE = StringIO() AR: np.ndarray[Any, np.dtype[np.float64]] = np.arange(10).astype(np.float64) def func(a: int) -> bool: ... np.deprecate(func) np.deprecate() np.deprecate_with_doc("test") np.deprecate_with_doc(None) np.byte_bounds(AR) np.byte_bounds(np.float64()) np.info(1, output=FILE) np.source(np.interp, output=FILE) np.lookfor("binary representation", output=FILE)
def irfft2(a, s=None, axes=(-2, -1)): """ Compute the 2-dimensional inverse fft of a real array. Parameters ---------- a : array (real) input array s : sequence (int) shape of the inverse fft axis : int axis over which to compute the inverse fft Notes ----- This is really irfftn with different default. """ return irfftn(a, s, axes) # Deprecated names from numpy import deprecate refft = deprecate(rfft, 'refft', 'rfft') irefft = deprecate(irfft, 'irefft', 'irfft') refft2 = deprecate(rfft2, 'refft2', 'rfft2') irefft2 = deprecate(irfft2, 'irefft2', 'irfft2') refftn = deprecate(rfftn, 'refftn', 'rfftn') irefftn = deprecate(irfftn, 'irefftn', 'irfftn')
] from . import doccer from .common import * from numpy import who as _who, source as _source, info as _info import numpy as np from scipy.interpolate._pade import pade as _pade from scipy.special import (comb as _comb, logsumexp as _lsm, factorial as _fact, factorial2 as _fact2, factorialk as _factk) import sys _msg = ( "Importing `%(name)s` from scipy.misc is deprecated in scipy 1.0.0. Use " "`scipy.special.%(name)s` instead.") comb = np.deprecate(_comb, message=_msg % {"name": _comb.__name__}) logsumexp = np.deprecate(_lsm, message=_msg % {"name": _lsm.__name__}) factorial = np.deprecate(_fact, message=_msg % {"name": _fact.__name__}) factorial2 = np.deprecate(_fact2, message=_msg % {"name": _fact2.__name__}) factorialk = np.deprecate(_factk, message=_msg % {"name": _factk.__name__}) _msg = ("Importing `pade` from scipy.misc is deprecated in scipy 1.0.0. Use " "`scipy.interpolate.pade` instead.") pade = np.deprecate(_pade, message=_msg) _msg = ( "Importing `%(name)s` from scipy.misc is deprecated in scipy 1.0.0. Use " "`numpy.%(name)s` instead.") who = np.deprecate(_who, message=_msg % {"name": "who"}) source = np.deprecate(_source, message=_msg % {"name": "source"})
from info import __doc__ from numpy import deprecate # These are all deprecated (until the end deprecated tag) from npfile import npfile from data_store import save, load, create_module, create_shelf from array_import import read_array, write_array from pickler import objload, objsave from numpyio import packbits, unpackbits, bswap, fread, fwrite, \ convert_objectarray fread = deprecate(fread, message=""" scipy.io.fread can be replaced with NumPy I/O routines such as np.load, np.fromfile as well as NumPy's memory-mapping capabilities. """) fwrite = deprecate(fwrite, message=""" scipy.io.fwrite can be replaced with NumPy I/O routines such as np.save, np.savez and x.tofile. Also, files can be directly memory-mapped into NumPy arrays which is often a better way of reading large files. """) bswap = deprecate(bswap, message=""" scipy.io.bswap can be replaced with the byteswap method on an array. out = scipy.io.bswap(arr) --> out = arr.byteswap(True) """)
def irfft2(a, s=None, axes=(-2,-1)): """ Compute the 2-dimensional inverse fft of a real array. Parameters ---------- a : array (real) input array s : sequence (int) shape of the inverse fft axis : int axis over which to compute the inverse fft Notes ----- This is really irfftn with different default. """ return irfftn(a, s, axes) # Deprecated names from numpy import deprecate refft = deprecate(rfft, 'refft', 'rfft') irefft = deprecate(irfft, 'irefft', 'irfft') refft2 = deprecate(rfft2, 'refft2', 'rfft2') irefft2 = deprecate(irfft2, 'irefft2', 'irfft2') refftn = deprecate(rfftn, 'refftn', 'rfftn') irefftn = deprecate(irfftn, 'irefftn', 'irfftn')
True >>> wgs72.f == 0.003352779454167505 True >>> wgs72.name 'WGS 72' >>> wgs72 == (6378135.0, 0.003352779454167505, 'WGS 72') True """ if isinstance(name, str): name = name.lower().replace(' ', '').partition('/')[0] ellipsoid_id = ELLIPSOID_IX.get(name, name) return ELLIPSOID[ellipsoid_id] select_ellipsoid = deprecate(get_ellipsoid, old_name='select_ellipsoid', new_name='get_ellipsoid') def unit(vector, norm_zero_vector=1, norm_zero_axis=0): """ Convert input vector to a vector of unit length. Parameters ---------- vector : 3 x m array m column vectors norm_zero_vector : one or NaN Defines the fill value used for zero length vectors. norm_zero_axis : 0, 1 or 2 Defines the direction that zero length vectors will point after the normalization is done.
# Backward compatibility from scipy._lib._util import DeprecatedImport as _DeprecatedImport clapack = _DeprecatedImport("scipy.linalg.blas.clapack", "scipy.linalg.lapack") flapack = _DeprecatedImport("scipy.linalg.blas.flapack", "scipy.linalg.lapack") # Expose all functions (only flapack --- clapack is an implementation detail) empty_module = None from scipy.linalg._flapack import * del empty_module _dep_message = """The `*gegv` family of routines has been deprecated in LAPACK 3.6.0 in favor of the `*ggev` family of routines. The corresponding wrappers will be removed from SciPy in a future release.""" cgegv = _np.deprecate(cgegv, old_name='cgegv', message=_dep_message) dgegv = _np.deprecate(dgegv, old_name='dgegv', message=_dep_message) sgegv = _np.deprecate(sgegv, old_name='sgegv', message=_dep_message) zgegv = _np.deprecate(zgegv, old_name='zgegv', message=_dep_message) # Modyfy _flapack in this scope so the deprecation warnings apply to # functions returned by get_lapack_funcs. _flapack.cgegv = cgegv _flapack.dgegv = dgegv _flapack.sgegv = sgegv _flapack.zgegv = zgegv # some convenience alias for complex functions _lapack_alias = { 'corghr': 'cunghr', 'zorghr': 'zunghr',
""" Compute the 2-dimensional inverse fft of a real array. Parameters ---------- a : array (real) input array s : sequence (int) shape of the inverse fft axis : int axis over which to compute the inverse fft Notes ----- This is really irfftn with different default. """ return irfftn(a, s, axes) # Deprecated names from numpy import deprecate refft = deprecate(rfft, "refft", "rfft") irefft = deprecate(irfft, "irefft", "irfft") refft2 = deprecate(rfft2, "refft2", "rfft2") irefft2 = deprecate(irfft2, "irefft2", "irfft2") refftn = deprecate(rfftn, "refftn", "rfftn") irefftn = deprecate(irfftn, "irefftn", "irfftn")
offset = offsets[freq] from pandas import DatetimeIndex # pylint: disable=E0611 date_range = DatetimeIndex(start=start_date, freq=offset, periods=n) return data, date_range def get_logdet(m): from statsmodels.tools.linalg import logdet_symm return logdet_symm(m) get_logdet = np.deprecate( get_logdet, "statsmodels.tsa.vector_ar.util.get_logdet", "statsmodels.tools.linalg.logdet_symm", "get_logdet is deprecated and will be removed in " "0.8.0") def norm_signif_level(alpha=0.05): return stats.norm.ppf(1 - alpha / 2) def acf_to_acorr(acf): diag = np.diag(acf[0]) # numpy broadcasting sufficient return acf / np.sqrt(np.outer(diag, diag)) def varsim(coefs, intercept, sig_u, steps=100, initvalues=None, seed=None):
filebase = filename.split('.')[0] fn = os.path.join(dir, filebase) f = dumb_shelve.open(fn, "r") #exec( 'import ' + module.__name__) for i in f.keys(): exec('import ' + module.__name__ + ';' + module.__name__ + '.' + i + '=' + 'f["' + i + '"]') # print i, 'loaded...' # print 'done' load = deprecate(_load, message=""" This is an internal function used with scipy.io.save_as_module If you are saving arrays into a module, you should think about using HDF5 or .npz files instead. """) def _create_module(file_name): """ Create the module file. """ if not os.path.exists(file_name + '.py'): # don't clobber existing files module_name = os.path.split(file_name)[-1] f = open(file_name + '.py', 'w') f.write('import scipy.io.data_store as data_store\n') f.write('import %s\n' % module_name) f.write('data_store._load(%s)' % module_name) f.close()