def _get_scipy_resizer(): try: from scipy.misc import imresize except ImportError: try: from scipy import __version__ as __scipy_version__ except ImportError: return (None, ["Scipy not found (install 'scipy' or 'Pillow')"]) scipy_version_info = tuple( int(num) for num in __scipy_version__.split(".") if num.isdigit()) # ``scipy.misc.imresize`` was removed in v1.3.0 if scipy_version_info >= (1, 3, 0): return ( None, [ "scipy.misc.imresize not found (was removed in scipy v1.3.0," f" you are using v{__scipy_version__}, install 'Pillow')" ], ) # unknown reason return (None, "scipy.misc.imresize not found") def resizer(pic, new_size): return imresize(pic, map(int, new_size[::-1])) return (resizer, [])
def test_shgo_scipy_vs_lmfit_2(): """Test SHGO algorithm in lmfit versus SciPy.""" bounds = [(-512, 512), (-512, 512)] result_scipy = scipy.optimize.shgo(eggholder, bounds, n=60, iters=5, sampling_method='sobol') # in SciPy v1.7.0: "sobol was fixed and is now using scipy.stats.qmc.Sobol" # FIXME: clean this up after we require SciPy >= 1.7.0 if int(scipy_version.split('.')[1]) < 7: assert len(result_scipy.xl) == 39 else: assert len(result_scipy.xl) == 74 pars = lmfit.Parameters() pars.add_many(('x0', 0, True, -512, 512), ('x1', 0, True, -512, 512)) mini = lmfit.Minimizer(eggholder_lmfit, pars) result = mini.minimize(method='shgo', n=60, iters=5, sampling_method='sobol') assert_allclose(result_scipy.fun, result.residual) assert_allclose(result_scipy.xl, result.shgo_xl) assert_allclose(result_scipy.funl, result.shgo_funl)
def __init__(self, frequency, time_range, refresh_time=1): # frequency: rate of acceleration reading # time range: readings acquired during this time window are used for predictions # refresh time: how often is prediction function re-trained on the most recent data if ((int(scipy_version.split('.')[0]) == 0) and (int(scipy_version.split('.')[1]) < 17)): raise Exception("Your scipy is outdated. Minimal required version is 0.17.0. Your are currently running "+scipy_version) self.period = 1.0/frequency # period in seconds between each two data points # queue is updated every time update func is called. self.time_range = time_range # time range captured (size of window for fitting the curve) self.refresh_time = refresh_time # after this time new fit is performed self.queue = deque() self.required_queue_length = frequency * time_range # xdata & ydata are updated in time_range periods self.xdata = np.array([]) self.ydata = np.array([]) self.popt = np.array([0, 0, 0]) self.initializing = True self.last_refresh = 0 # time when last refresh occured
def test_scipy_supported_version(self): """scipy version is supported """ min_acceptable_version = (0, 13, 0) try: from scipy import __version__ as scipy_lib_version version = tuple(map(int, scipy_lib_version.split('.'))) pass_test = version >= min_acceptable_version version_string = str(scipy_lib_version) except ImportError: pass_test = False version_string = "Not installed" self.assertTrue( pass_test, "Unsupported scipy version. Must be >= %s, but running %s." % ('.'.join(map(str, min_acceptable_version)), version_string))
def __init__(self, peak_width_limits=(0.5, 12.0), max_n_peaks=np.inf, min_peak_height=0.0, peak_threshold=2.0, aperiodic_mode='fixed', verbose=True): """Initialize FOOOF object with run parameters.""" # Double check correct scipy version is being used from scipy import __version__ major, minor, _ = __version__.split('.') if int(major) < 1 and int(minor) < 19: raise ImportError('Scipy version of >= 0.19.0 required.') # Set input parameters self.peak_width_limits = peak_width_limits self.max_n_peaks = max_n_peaks self.min_peak_height = min_peak_height self.peak_threshold = peak_threshold self.aperiodic_mode = aperiodic_mode self.verbose = verbose ## SETTINGS - these are updateable by the user if required. # Noise threshold, as a percentage of the lowest magnitude values in the total data to fit. # Defines the minimum height, above residuals, to be considered a peak. self._ap_percentile_thresh = 0.025 # Guess parameters for aperiodic fitting, [offset, knee, exponent] # If offset guess is None, the first value of the power spectrum is used as offset guess self._ap_guess = (None, 0, 2) # Bounds for aperiodic fitting, as: ((offset_low_bound, knee_low_bound, sl_low_bound), # (offset_high_bound, knee_high_bound, sl_high_bound)) # By default, aperiodic fitting is unbound, but can be restricted here, if desired # Even if fitting without knee, leave bounds for knee (they are dropped later) self._ap_bounds = ((-np.inf, -np.inf, -np.inf), (np.inf, np.inf, np.inf)) # Threshold for how far (units of gaus std dev) a peak has to be from edge to keep. self._bw_std_edge = 1.0 # Degree of overlap (units of gauss std dev) between gaussians for one to be dropped self._gauss_overlap_thresh = 1.5 # Parameter bounds for center frequency when fitting gaussians - in terms of +/- std dev self._cf_bound = 1.5 # Set internal settings (based on inputs). Initialize data & results attributes. self._reset_internal_settings() self._reset_data_results()
def test_ampgo_local_solver(minimizer_Alpine02): """Test AMPGO algorithm with local solver.""" kws = {'local': 'Nelder-Mead'} # bounds in Nelder-Mead are supported since SciPy v1.7.0 # FIXME: clean this up after we require SciPy >= 1.7.0 if int(scipy_version.split('.')[1]) < 7: msg = r'Method Nelder-Mead cannot handle constraints nor bounds' with pytest.warns(RuntimeWarning, match=msg): out = minimizer_Alpine02.minimize(method='ampgo', **kws) else: out = minimizer_Alpine02.minimize(method='ampgo', **kws) out_x = np.array([out.params['x0'].value, out.params['x1'].value]) assert 'ampgo' and 'Nelder-Mead' in out.method assert_allclose(out.residual, fglob, rtol=1e-5) assert_allclose(min(out_x), min(global_optimum), rtol=1e-3) assert_allclose(max(out_x), max(global_optimum), rtol=1e-3) assert 'global' in out.ampgo_msg
# 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. from __future__ import division as _division import numpy as _np from scipy import __version__ as _scipy__version__ from scipy.spatial import distance as _distance import scipy.cluster.hierarchy as _hierarchy import matplotlib.pyplot as _plt from mpl_toolkits import axes_grid1 as _axes_grid1 __version__ = "0.1.3.dev0" _scipy_version = tuple(int(v) for v in _scipy__version__.split('.')[:2]) class HeatmapClusterResults(object): """ Instances of this class are returned by the function heatmapcluster(). """ def __init__(self, **kwds): for name, value in kwds.items(): setattr(self, name, value) def heatmapcluster(x, row_labels, col_labels, num_row_clusters=None, num_col_clusters=None, label_fontsize=8, cmap=None, show_colorbar=True,
#!/usr/bin/python # -*- coding: utf-8 -*- from scipy import exp from scipy import __version__ from scipy.constants import pi, Avogadro if int(__version__.split(".")[1]) < 10: from scipy.constants import Bolzmann as Boltzmann else: from scipy.constants import Boltzmann from lib.meos import MEoS from lib import unidades class Methanol(MEoS): """Multiparameter equation of state for methanol""" name = "methanol" CASNumber = "67-56-1" formula = "CH3OH" synonym = "" rhoc = unidades.Density(275.5626) Tc = unidades.Temperature(512.6) Pc = unidades.Pressure(8103.5, "kPa") M = 32.04216 # g/mol Tt = unidades.Temperature(175.61) Tb = unidades.Temperature(337.632) f_acent = 0.5625 momentoDipolar = unidades.DipoleMoment(1.7, "Debye") id = 117
the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.''' from scipy import exp from scipy import __version__ from scipy.constants import pi, Avogadro if int(__version__.split(".")[1]) < 10: from scipy.constants import Bolzmann as Boltzmann else: from scipy.constants import Boltzmann from lib.meos import MEoS from lib import unidades class Methanol(MEoS): """Multiparameter equation of state for methanol""" name = "methanol" CASNumber = "67-56-1" formula = "CH3OH" synonym = "" rhoc = unidades.Density(275.5626)
def integrate_scipy(rd, y0, tout, linear_solver='default', name='vode', dense_output=None, **kwargs): """ see :class:`Integration` Parameters ---------- rd: ReactionDiffusion y0: array_like Initial conditions tout: array-like At what times to report, e.g.: - ``np.linspace(t0, tend, nt)`` - ``np.logspace(np.log10(t0 + 1e-12), np.log10(tend), nt)`` linear_solver: str (default: 'default') 'dense' or 'banded' name: string (default: 'vode') dense_output: bool (default: None) if True, tout is taken to be length 2 tuple (t0, tend), if unspecified (None), length of tout decides (length 2 => True) Returns ======= yout: numpy array of shape ``(len(tout), rd.N, rd.n)``. """ from scipy import __version__ as __scipy_version__ from scipy.integrate import ode scipy_version = tuple(map(int, __scipy_version__.split('.')[:2])) new_kwargs = {} y0 = np.asarray(y0) if y0.size != rd.n*rd.N: fmtstr = "y0.size (={})not compatible with rd.n*rd.N (={})" raise ValueError(fmtstr.format(y0.size, rd.n*rd.N)) if linear_solver == 'default': if rd.N == 1: linear_solver = 'dense' elif rd.N > 1: linear_solver = 'banded' if linear_solver not in ('dense', 'banded'): raise NotImplementedError("Unkown linear_solver %s" % linear_solver) if linear_solver == 'banded': new_kwargs['lband'] = rd.n*rd.n_jac_diags new_kwargs['uband'] = rd.n*rd.n_jac_diags new_kwargs['atol'] = kwargs.pop('atol', DEFAULTS['atol']) new_kwargs['rtol'] = kwargs.pop('rtol', DEFAULTS['rtol']) new_kwargs['method'] = kwargs.pop('method', 'bdf') new_kwargs['with_jacobian'] = kwargs.pop('with_jacobian', True) new_kwargs['first_step'] = kwargs.pop('first_step', 0.0) if kwargs.pop('iter_type', 'undecided') != 'undecided': raise ValueError("iter_type unsupported by SciPy solver") if kwargs.pop('linear_solver', 'default') != 'default': raise ValueError("linear_solver unsupported by SciPy solver") if kwargs != {}: raise KeyError("Unkown kwargs: {}".format(kwargs)) # Create python callbacks with right signature fout = np.empty(rd.n*rd.N) def f(t, y, *f_args): # Python function closure circumvents reallocation f.neval += 1 rd.f(t, y, fout) return fout f.neval = 0 from_row = 0 if linear_solver == 'dense': jout = rd.alloc_jout(banded=False, order='F') elif linear_solver == 'banded': jout = rd.alloc_jout(banded=True, order='F', pad=True) if scipy_version[0] <= 0 and scipy_version[1] <= 14: pass else: # SciPy >= v0.15 need no extra padding from_row = rd.n*rd.n_jac_diags def jac(t, y, *j_args): jac.neval += 1 jout[...] = 0 # <--- this is very important (clear old LU decomp) if linear_solver == 'dense': rd.dense_jac_cmaj(t, y, jout) else: if scipy_version[0] <= 0 and scipy_version[1] <= 14: raise NotImplementedError("SciPy v0.15 or greater required.") rd.banded_jac_cmaj(t, y, jout) return jout[from_row:, :] jac.neval = 0 runner = ode(f, jac=jac if new_kwargs['with_jacobian'] else None) runner.set_integrator(name, **new_kwargs) runner.set_initial_value(y0.flatten(), tout[0]) if dense_output is None: dense_output = (len(tout) == 2) time_wall = time.time() time_cpu = time.process_time() if dense_output: import warnings if not len(tout) == 2: raise ValueError("dense_output implies tout == (t0, tend)") # suppress warning printed by Fortran runner._integrator.iwork[2] = -1 warnings.filterwarnings("ignore", category=UserWarning) yout = [y0] tstep = [tout[0]] while runner.t < tout[1]: runner.integrate(tout[1], step=True) tstep.append(runner.t) yout.append(runner.y) warnings.resetwarnings() tout = np.array(tstep) yout = np.array(yout) else: yout = np.empty((len(tout), rd.n*rd.N), order='C') yout[0, :] = y0 for i in range(1, len(tout)): runner.integrate(tout[i]) yout[i, :] = runner.y time_wall = time.time() - time_wall time_cpu = time.process_time() - time_cpu info = new_kwargs.copy() info.update({ 'success': runner.successful(), 'time_wall': time_wall, 'time_cpu': time_cpu, 'nfev': f.neval, 'njev': jac.neval, 'nsteps': -1, 'integrator': ['scipy'], }) return yout.reshape((len(tout), rd.N, rd.n)), tout, info
# version. # # pypid is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with # pypid. If not, see <http://www.gnu.org/licenses/>. """Provide :class:`ModelFitter` to make arbitrary model fitting easy. """ from numpy import arange, ndarray from scipy import __version__ as _scipy_version from scipy.optimize import leastsq _strings = _scipy_version.split('.') # Don't convert third string to an integer in case of (for example) '0.7.2rc3' _SCIPY_VERSION = (int(_strings[0]), int(_strings[1]), _strings[2]) del _strings class PoorFit(ValueError): pass class ModelFitter(object): """A convenient wrapper around :func:`scipy.optimize.leastsq`. TODO: look into :mod:`scipy.odr` as an alternative fitting algorithm (minimizing the sum of squares of orthogonal distances, vs. minimizing y distances).
def nsure_dir_xzists(dirname): if not os.path.exists(dirname): os.makedirs(dirname) # making sure directories for test data exist nsure_dir_xzists("tests/graphics") nsure_dir_xzists("tests/Data") nsure_dir_xzists("tests/Data/Movie2DContourFrames") nsure_dir_xzists("tests/Data/Movie1DFrames") # making sure user has a good version of python version = sys.hexversion if version < 34014192: print("You should be using python2.7 at least. This is your version:") print(sys.version) errorOccured = True # making sure user has the right scipy from scipy import __version__ as ver num = int(ver.split(".")[1]) if num < 13: print("Your scipy version, " + ver + " , might be too old. You need an up-to-date scipy.optimize") errorOccured= True if not errorOccured: print("Everything is OK.") else: print("Please fix your problems.")
def nsure_dir_xzists(dirname): if not os.path.exists(dirname): os.makedirs(dirname) # making sure directories for test data exist nsure_dir_xzists("tests/graphics") nsure_dir_xzists("tests/Data") nsure_dir_xzists("tests/Data/Movie2DContourFrames") nsure_dir_xzists("tests/Data/Movie1DFrames") # making sure user has a good version of python version = sys.hexversion if version < 34014192: print("You should be using python2.7 at least. This is your version:") print(sys.version) errorOccured = True # making sure user has the right scipy from scipy import __version__ as ver num = int(ver.split(".")[1]) if num < 13: print("Your scipy version, " + ver + " , might be too old. You need an up-to-date scipy.optimize") errorOccured = True if not errorOccured: print("Everything is OK.") else: print("Please fix your problems.")
# 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. from __future__ import division as _division import numpy as _np from scipy import __version__ as _scipy__version__ from scipy.spatial import distance as _distance import scipy.cluster.hierarchy as _hierarchy import matplotlib.pyplot as _plt from mpl_toolkits import axes_grid1 as _axes_grid1 __version__ = "0.1.3.dev0" _scipy_version = tuple(int(v) for v in _scipy__version__.split('.')[:2]) class HeatmapClusterResults(object): """ Instances of this class are returned by the function heatmapcluster(). """ def __init__(self, **kwds): for name, value in kwds.items(): setattr(self, name, value) def heatmapcluster(x, row_labels, col_labels, num_row_clusters=None,
from scipy.io import loadmat from obspy.core import AttribDict, UTCDateTime, Trace, Stream import numpy as np # scipy version handling from scipy import __version__ as sv scipyver = int(sv.split(".")[1]) def loadmat2trace(infile, debug=False): ''' wrapper function for scipy.io.loadmat reformats seismogram read from .mat file to ObsPy Trace object including all available tr.stats entries ''' ## conversion libraries tofloat = ['azimuth', 'calib', 'delta', 'sampling_rate'] toUTCDateTime = ['starttime'] toremove = ['__header__', '__globals__', '__version__', 'endtime'] # endtime is read-only st = loadmat(infile, squeeze_me=True) if debug: print "1) after loadmat" print st # remove unwanted keys for i in st.keys(): if i in toremove: del st[i] # remove Unicode from strings
# # pypid is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with # pypid. If not, see <http://www.gnu.org/licenses/>. """Provide :class:`ModelFitter` to make arbitrary model fitting easy. """ from numpy import arange, ndarray from scipy import __version__ as _scipy_version from scipy.optimize import leastsq _strings = _scipy_version.split('.') # Don't convert third string to an integer in case of (for example) '0.7.2rc3' _SCIPY_VERSION = (int(_strings[0]), int(_strings[1]), _strings[2]) del _strings class PoorFit (ValueError): pass class ModelFitter (object): """A convenient wrapper around :func:`scipy.optimize.leastsq`. TODO: look into :mod:`scipy.odr` as an alternative fitting algorithm (minimizing the sum of squares of orthogonal distances, vs. minimizing y distances).