1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
|
import sys
import unittest
import numpy as np
from numpy import pi
from numpy.testing import assert_allclose, assert_almost_equal, assert_equal
import pytest
from scipy.optimize import rosen_der
from uncertainties import ufloat
from lmfit import Minimizer, Parameters, minimize
from lmfit.lineshapes import gaussian
from lmfit.minimizer import (HAS_EMCEE, SCALAR_METHODS, MinimizerResult,
coerce_float64)
from lmfit.models import SineModel
try:
import numdifftools # noqa: F401
HAS_NUMDIFFTOOLS = True
except ImportError:
HAS_NUMDIFFTOOLS = False
def check(para, real_val, sig=3):
err = abs(para.value - real_val)
assert err < sig * para.stderr
def check_wo_stderr(para, real_val, sig=0.1):
err = abs(para.value - real_val)
assert err < sig
def check_paras(para_fit, para_real, sig=3):
for i in para_fit:
check(para_fit[i], para_real[i].value, sig=sig)
def test_simple():
# create data to be fitted
np.random.seed(1)
x = np.linspace(0, 15, 301)
data = (5. * np.sin(2 * x - 0.1) * np.exp(-x*x*0.025) +
np.random.normal(size=len(x), scale=0.2))
# define objective function: returns the array to be minimized
def fcn2min(params, x, data):
"""model decaying sine wave, subtract data"""
amp = params['amp']
shift = params['shift']
omega = params['omega']
decay = params['decay']
model = amp * np.sin(x * omega + shift) * np.exp(-x*x*decay)
return model - data
# create a set of Parameters
params = Parameters()
params.add('amp', value=10, min=0)
params.add('decay', value=0.1)
params.add('shift', value=0.0, min=-pi/2., max=pi/2)
params.add('omega', value=3.0)
# do fit, here with leastsq model
result = minimize(fcn2min, params, args=(x, data))
# assert that the real parameters are found
for para, val in zip(result.params.values(), [5, 0.025, -.1, 2]):
check(para, val)
def test_lbfgsb():
p_true = Parameters()
p_true.add('amp', value=14.0)
p_true.add('period', value=5.33)
p_true.add('shift', value=0.123)
p_true.add('decay', value=0.010)
def residual(pars, x, data=None):
amp = pars['amp']
per = pars['period']
shift = pars['shift']
decay = pars['decay']
if abs(shift) > pi/2:
shift = shift - np.sign(shift) * pi
model = amp * np.sin(shift + x / per) * np.exp(-x * x * decay * decay)
if data is None:
return model
return model - data
n = 2500
xmin = 0.
xmax = 250.0
noise = np.random.normal(scale=0.7215, size=n)
x = np.linspace(xmin, xmax, n)
data = residual(p_true, x) + noise
fit_params = Parameters()
fit_params.add('amp', value=11.0, min=5, max=20)
fit_params.add('period', value=5., min=1., max=7)
fit_params.add('shift', value=.10, min=0.0, max=0.2)
fit_params.add('decay', value=6.e-3, min=0, max=0.1)
out = minimize(residual, fit_params, method='lbfgsb', args=(x,),
kws={'data': data})
for para, true_para in zip(out.params.values(), p_true.values()):
check_wo_stderr(para, true_para.value)
def test_derive():
def func(pars, x, data=None):
model = pars['a'] * np.exp(-pars['b'] * x) + pars['c']
if data is None:
return model
return model - data
def dfunc(pars, x, data=None):
v = np.exp(-pars['b']*x)
return np.array([v, -pars['a']*x*v, np.ones(len(x))])
def f(var, x):
return var[0] * np.exp(-var[1] * x) + var[2]
params1 = Parameters()
params1.add('a', value=10)
params1.add('b', value=10)
params1.add('c', value=10)
params2 = Parameters()
params2.add('a', value=10)
params2.add('b', value=10)
params2.add('c', value=10)
a, b, c = 2.5, 1.3, 0.8
x = np.linspace(0, 4, 50)
y = f([a, b, c], x)
data = y + 0.15*np.random.normal(size=len(x))
# fit without analytic derivative
min1 = Minimizer(func, params1, fcn_args=(x,), fcn_kws={'data': data})
out1 = min1.leastsq()
# fit with analytic derivative
min2 = Minimizer(func, params2, fcn_args=(x,), fcn_kws={'data': data})
out2 = min2.leastsq(Dfun=dfunc, col_deriv=1)
check_wo_stderr(out1.params['a'], out2.params['a'].value, 0.00005)
check_wo_stderr(out1.params['b'], out2.params['b'].value, 0.00005)
check_wo_stderr(out1.params['c'], out2.params['c'].value, 0.00005)
def test_peakfit():
def residual(pars, x, data=None):
g1 = gaussian(x, pars['a1'], pars['c1'], pars['w1'])
g2 = gaussian(x, pars['a2'], pars['c2'], pars['w2'])
model = g1 + g2
if data is None:
return model
return model - data
n = 601
xmin = 0.
xmax = 15.0
noise = np.random.normal(scale=.65, size=n)
x = np.linspace(xmin, xmax, n)
org_params = Parameters()
org_params.add_many(('a1', 12.0, True, None, None, None),
('c1', 5.3, True, None, None, None),
('w1', 1.0, True, None, None, None),
('a2', 9.1, True, None, None, None),
('c2', 8.1, True, None, None, None),
('w2', 2.5, True, None, None, None))
data = residual(org_params, x) + noise
fit_params = Parameters()
fit_params.add_many(('a1', 8.0, True, None, 14., None),
('c1', 5.0, True, None, None, None),
('w1', 0.7, True, None, None, None),
('a2', 3.1, True, None, None, None),
('c2', 8.8, True, None, None, None))
fit_params.add('w2', expr='2.5*w1')
myfit = Minimizer(residual, fit_params, fcn_args=(x,),
fcn_kws={'data': data})
myfit.prepare_fit()
out = myfit.leastsq()
check_paras(out.params, org_params)
def test_scalar_minimize_has_no_uncertainties():
# scalar_minimize doesn't calculate uncertainties.
# when a scalar_minimize is run the stderr and correl for each parameter
# should be None. (stderr and correl are set to None when a Parameter is
# initialised).
# This requires a reset after a leastsq fit has been done.
# Only when scalar_minimize calculates stderr and correl can this test
# be removed.
np.random.seed(1)
x = np.linspace(0, 15, 301)
data = (5. * np.sin(2 * x - 0.1) * np.exp(-x*x*0.025) +
np.random.normal(size=len(x), scale=0.2))
# define objective function: returns the array to be minimized
def fcn2min(params, x, data):
"""model decaying sine wave, subtract data"""
amp = params['amp']
shift = params['shift']
omega = params['omega']
decay = params['decay']
model = amp * np.sin(x * omega + shift) * np.exp(-x*x*decay)
return model - data
# create a set of Parameters
params = Parameters()
params.add('amp', value=10, min=0)
params.add('decay', value=0.1)
params.add('shift', value=0.0, min=-pi/2., max=pi/2)
params.add('omega', value=3.0)
mini = Minimizer(fcn2min, params, fcn_args=(x, data))
out = mini.minimize()
assert np.isfinite(out.params['amp'].stderr)
assert out.errorbars
out2 = mini.minimize(method='nelder-mead')
for par in ('amp', 'decay', 'shift', 'omega'):
assert HAS_NUMDIFFTOOLS == (out2.params[par].stderr is not None)
assert HAS_NUMDIFFTOOLS == (out2.params[par].correl is not None)
assert HAS_NUMDIFFTOOLS == out2.errorbars
def test_scalar_minimize_reduce_fcn():
# test that the reduce_fcn option for scalar_minimize
# gives different and improved results with outliers
np.random.seed(2)
x = np.linspace(0, 10, 101)
yo = 1.0 + 2.0*np.sin(4*x) * np.exp(-x / 5)
y = yo + np.random.normal(size=len(yo), scale=0.250)
outliers = np.random.randint(int(len(x)/3.0), len(x), int(len(x)/12))
y[outliers] += 5*np.random.random(len(outliers))
# define objective function: returns the array to be minimized
def objfunc(pars, x, data):
decay = pars['decay']
offset = pars['offset']
omega = pars['omega']
amp = pars['amp']
model = offset + amp * np.sin(x*omega) * np.exp(-x/decay)
return model - data
# create a set of Parameters
params = Parameters()
params.add('offset', 2.0)
params.add('omega', 3.3)
params.add('amp', 2.5)
params.add('decay', 1.0)
method = 'L-BFGS-B'
out1 = minimize(objfunc, params, args=(x, y), method=method)
out2 = minimize(objfunc, params, args=(x, y), method=method,
reduce_fcn='neglogcauchy')
assert_allclose(out1.params['omega'].value, 4.0, rtol=0.01)
assert_allclose(out1.params['decay'].value, 7.6, rtol=0.01)
assert_allclose(out2.params['omega'].value, 4.0, rtol=0.01)
assert_allclose(out2.params['decay'].value, 5.8, rtol=0.01)
def test_multidimensional_fit_GH205():
# test that you don't need to flatten the output from the objective
# function. Tests regression for GH205.
pos = np.linspace(0, 99, 100)
xv, yv = np.meshgrid(pos, pos)
f = lambda xv, yv, lambda1, lambda2: (np.sin(xv * lambda1) +
np.cos(yv * lambda2))
data = f(xv, yv, 0.3, 3)
assert data.ndim, 2
def fcn2min(params, xv, yv, data):
"""model decaying sine wave, subtract data"""
model = f(xv, yv, params['lambda1'], params['lambda2'])
return model - data
# create a set of Parameters
params = Parameters()
params.add('lambda1', value=0.4)
params.add('lambda2', value=3.2)
mini = Minimizer(fcn2min, params, fcn_args=(xv, yv, data))
mini.minimize()
def test_ufloat():
"""Test of ufloat from uncertainties."""
x = ufloat(1, 0.1)
assert_allclose(x.nominal_value, 1.0, rtol=1.e-7)
assert_allclose(x.std_dev, 0.1, rtol=1.e-7)
y = x*x
assert_allclose(y.nominal_value, 1.0, rtol=1.e-7)
assert_allclose(y.std_dev, 0.2, rtol=1.e-7)
y = x - x
assert_allclose(y.nominal_value, 0.0, rtol=1.e-7)
assert_allclose(y.std_dev, 0.0, rtol=1.e-7)
def test_stderr_propagation():
"""Test propagation of uncertainties to constraint expressions."""
model = SineModel()
params = model.make_params(amplitude=1, frequency=9.0, shift=0)
params.add("period", expr="1/frequency")
params.add("period_2a", expr="2*period")
params.add("period_2b", expr="2/frequency")
params.add("thing_1", expr="shift + frequency")
params.add("thing_2", expr="shift + 1/period")
np.random.seed(3)
xs = np.linspace(0, 1, 51)
ys = np.sin(7.45 * xs) + 0.01 * np.random.normal(size=xs.shape)
result = model.fit(ys, x=xs, params=params)
opars = result.params
assert_allclose(opars['period'].stderr, 1.1587e-04, rtol=1.e-3)
assert_allclose(opars['period_2b'].stderr, 2.3175e-04, rtol=1.e-3)
assert_allclose(opars['thing_1'].stderr, 0.0037291, rtol=1.e-3)
assert_allclose(opars['period_2a'].stderr, 2*opars['period'].stderr, rtol=1.e-5)
assert_allclose(opars['period_2b'].stderr, opars['period_2a'].stderr, rtol=1.e-5)
assert_allclose(opars['thing_1'].stderr, opars['thing_2'].stderr, rtol=1.e-5)
class CommonMinimizerTest(unittest.TestCase):
def setUp(self):
"""
test scale minimizers except newton-cg (needs jacobian) and
anneal (doesn't work out of the box).
"""
p_true = Parameters()
p_true.add('amp', value=14.0)
p_true.add('period', value=5.33)
p_true.add('shift', value=0.123)
p_true.add('decay', value=0.010)
self.p_true = p_true
n = 2500
xmin = 0.
xmax = 250.0
noise = np.random.normal(scale=0.7215, size=n)
self.x = np.linspace(xmin, xmax, n)
self.data = self.residual(p_true, self.x) + noise
fit_params = Parameters()
fit_params.add('amp', value=11.0, min=5, max=20)
fit_params.add('period', value=5., min=1., max=7)
fit_params.add('shift', value=.10, min=0.0, max=0.2)
fit_params.add('decay', value=6.e-3, min=0, max=0.1)
self.fit_params = fit_params
self.mini = Minimizer(self.residual, fit_params, [self.x, self.data])
def residual(self, pars, x, data=None):
amp = pars['amp']
per = pars['period']
shift = pars['shift']
decay = pars['decay']
if abs(shift) > pi/2:
shift = shift - np.sign(shift) * pi
model = amp*np.sin(shift + x/per) * np.exp(-x*x*decay*decay)
if data is None:
return model
return model - data
def test_diffev_bounds_check(self):
# You need finite (min, max) for each parameter if you're using
# differential_evolution.
self.fit_params['decay'].min = -np.inf
self.fit_params['decay'].vary = True
self.minimizer = 'differential_evolution'
pytest.raises(ValueError, self.scalar_minimizer)
# but only if a parameter is not fixed
self.fit_params['decay'].vary = False
self.mini.scalar_minimize(method='differential_evolution', max_nfev=1)
def test_scalar_minimizers(self):
# test all the scalar minimizers
for method in SCALAR_METHODS:
if method in ['newton', 'dogleg', 'trust-ncg', 'cg', 'trust-exact',
'trust-krylov', 'trust-constr']:
continue
self.minimizer = SCALAR_METHODS[method]
if method == 'Nelder-Mead':
sig = 0.2
else:
sig = 0.15
self.scalar_minimizer(sig=sig)
def scalar_minimizer(self, sig=0.15):
out = self.mini.scalar_minimize(method=self.minimizer)
self.residual(out.params, self.x)
for para, true_para in zip(out.params.values(), self.p_true.values()):
check_wo_stderr(para, true_para.value, sig=sig)
def test_coerce_float64(self):
# check that an error is raised if there are nan in
# the data returned by userfcn
self.data[0] = np.nan
for method in SCALAR_METHODS:
if method == 'cobyla' and sys.platform == 'darwin':
pytest.xfail("this aborts Python on macOS...")
elif method == 'differential_evolution':
pytest.raises(RuntimeError, self.mini.scalar_minimize,
SCALAR_METHODS[method])
else:
pytest.raises(ValueError, self.mini.scalar_minimize,
SCALAR_METHODS[method])
pytest.raises(ValueError, self.mini.minimize)
# now check that the fit proceeds if nan_policy is 'omit'
self.mini.nan_policy = 'omit'
res = self.mini.minimize()
assert_equal(res.ndata, np.size(self.data, 0) - 1)
for para, true_para in zip(res.params.values(), self.p_true.values()):
check_wo_stderr(para, true_para.value, sig=0.15)
def test_coerce_float64_function(self):
a = np.array([0, 1, 2, 3, np.nan])
pytest.raises(ValueError, coerce_float64, a)
assert np.isnan(coerce_float64(a, nan_policy='propagate')[-1])
assert_equal(coerce_float64(a, nan_policy='omit'), [0, 1, 2, 3])
a[-1] = np.inf
pytest.raises(ValueError, coerce_float64, a)
assert np.isposinf(coerce_float64(a, nan_policy='propagate')[-1])
assert_equal(coerce_float64(a, nan_policy='omit'), [0, 1, 2, 3])
assert_equal(coerce_float64(a, handle_inf=False), a)
def test_emcee(self):
# test emcee
if not HAS_EMCEE:
return
np.random.seed(123456)
out = self.mini.emcee(nwalkers=100, steps=200, burn=50, thin=10)
check_paras(out.params, self.p_true, sig=3)
def test_emcee_method_kwarg(self):
# test with emcee as method keyword argument
if not HAS_EMCEE:
return
np.random.seed(123456)
out = self.mini.minimize(method='emcee',
nwalkers=50, steps=200,
burn=50, thin=10)
assert out.method == 'emcee'
assert out.nfev == 50*200
check_paras(out.params, self.p_true, sig=3)
out_unweighted = self.mini.minimize(method='emcee',
nwalkers=50, steps=200,
burn=50, thin=10,
is_weighted=False)
assert out_unweighted.method == 'emcee'
def test_emcee_multiprocessing(self):
# test multiprocessing runs
raise pytest.skip("Pytest fails with multiprocessing")
pytest.importorskip("dill")
if not HAS_EMCEE:
return
self.mini.emcee(steps=50, workers=4, nwalkers=20)
def test_emcee_bounds_length(self):
# the log-probability functions check if the parameters are
# inside the bounds. Check that the bounds and parameters
# are the right lengths for comparison. This can be done
# if nvarys != nparams
if not HAS_EMCEE:
return
self.mini.params['amp'].vary = False
self.mini.params['period'].vary = False
self.mini.params['shift'].vary = False
self.mini.emcee(steps=10)
def test_emcee_partial_bounds(self):
# mcmc with partial bounds
if not HAS_EMCEE:
return
np.random.seed(123456)
# test mcmc output vs lm, some parameters not bounded
self.fit_params['amp'].max = np.inf
# self.fit_params['amp'].min = -np.inf
out = self.mini.emcee(nwalkers=100, steps=300, burn=100, thin=10)
check_paras(out.params, self.p_true, sig=3)
def test_emcee_init_with_chain(self):
# can you initialise with a previous chain
if not HAS_EMCEE:
return
out = self.mini.emcee(nwalkers=100, steps=5)
# can initialise with a chain
self.mini.emcee(nwalkers=100, steps=1, pos=out.chain)
# can initialise with a correct subset of a chain
self.mini.emcee(nwalkers=100, steps=1, pos=out.chain[-1, ...])
# but you can't initialise if the shape is wrong.
pytest.raises(ValueError,
self.mini.emcee,
nwalkers=100,
steps=1,
pos=out.chain[-1, :-1, ...])
def test_emcee_reuse_sampler(self):
if not HAS_EMCEE:
return
self.mini.emcee(nwalkers=20, steps=25)
# if you've run the sampler the Minimizer object should have a _lastpos
# attribute
assert hasattr(self.mini, '_lastpos')
# now try and reuse sampler
out2 = self.mini.emcee(steps=10, reuse_sampler=True)
assert out2.chain.shape == (35, 20, 4)
# you shouldn't be able to reuse the sampler if nvarys has changed.
self.mini.params['amp'].vary = False
pytest.raises(ValueError, self.mini.emcee, reuse_sampler=True)
def test_emcee_lnpost(self):
# check ln likelihood is calculated correctly. It should be
# -0.5 * chi**2.
result = self.mini.minimize()
# obtain the numeric values
# note - in this example all the parameters are varied
fvars = np.array([par.value for par in result.params.values()])
# calculate the cost function with scaled values (parameters all have
# lower and upper bounds.
scaled_fvars = []
for par, fvar in zip(result.params.values(), fvars):
par.value = fvar
scaled_fvars.append(par.setup_bounds())
val = self.mini.penalty(np.array(scaled_fvars))
# calculate the log-likelihood value
bounds = np.array([(par.min, par.max)
for par in result.params.values()])
val2 = self.mini._lnprob(fvars, self.residual, result.params,
result.var_names, bounds,
userargs=(self.x, self.data))
assert_almost_equal(-0.5 * val, val2)
def test_emcee_output(self):
# test mcmc output
if not HAS_EMCEE:
return
try:
from pandas import DataFrame
except ImportError:
return
out = self.mini.emcee(nwalkers=10, steps=20, burn=5, thin=2)
assert isinstance(out, MinimizerResult)
assert isinstance(out.flatchain, DataFrame)
# check that we can access the chains via parameter name
# print( out.flatchain['amp'].shape[0], 200)
assert out.flatchain['amp'].shape[0] == 70
assert out.errorbars
assert np.isfinite(out.params['amp'].correl['period'])
# the lnprob array should be the same as the chain size
assert np.size(out.chain)//out.nvarys == np.size(out.lnprob)
# test chain output shapes
print(out.lnprob.shape, out.chain.shape, out.flatchain.shape)
assert out.lnprob.shape == (7, 10)
assert out.chain.shape == (7, 10, 4)
assert out.flatchain.shape == (70, 4)
def test_emcee_float(self):
# test that it works if the residuals returns a float, not a vector
if not HAS_EMCEE:
return
def resid(pars, x, data=None):
return -0.5 * np.sum(self.residual(pars, x, data=data)**2)
# just return chi2
def resid2(pars, x, data=None):
return np.sum(self.residual(pars, x, data=data)**2)
self.mini.userfcn = resid
np.random.seed(123456)
out = self.mini.emcee(nwalkers=100, steps=200, burn=50, thin=10)
check_paras(out.params, self.p_true, sig=3)
self.mini.userfcn = resid2
np.random.seed(123456)
out = self.mini.emcee(nwalkers=100, steps=200,
burn=50, thin=10, float_behavior='chi2')
check_paras(out.params, self.p_true, sig=3)
def test_emcee_seed(self):
# test emcee seeding can reproduce a sampling run
if not HAS_EMCEE:
return
out = self.mini.emcee(params=self.fit_params,
nwalkers=100,
steps=1, seed=1)
out2 = self.mini.emcee(params=self.fit_params,
nwalkers=100,
steps=1, seed=1)
assert_almost_equal(out.chain, out2.chain)
def test_emcee_ntemps(self):
# check for DeprecationWarning when using ntemps > 1
if not HAS_EMCEE:
return
with pytest.raises(DeprecationWarning):
_ = self.mini.emcee(params=self.fit_params, ntemps=5)
def test_emcee_custom_pool(self):
# tests use of a custom pool
if not HAS_EMCEE:
return
global emcee_counter
emcee_counter = 0
class my_pool:
def map(self, f, arg):
global emcee_counter
emcee_counter += 1
return map(f, arg)
def cost_fun(params, **kwargs):
return rosen_der([params['a'], params['b']])
params = Parameters()
params.add('a', 1, min=-5, max=5, vary=True)
params.add('b', 1, min=-5, max=5, vary=True)
fitter = Minimizer(cost_fun, params)
fitter.emcee(workers=my_pool(), steps=1000, nwalkers=100)
assert emcee_counter > 500
def residual_for_multiprocessing(pars, x, data=None):
# a residual function defined in the top level is needed for
# multiprocessing. bound methods don't work.
amp = pars['amp']
per = pars['period']
shift = pars['shift']
decay = pars['decay']
if abs(shift) > pi/2:
shift = shift - np.sign(shift) * pi
model = amp*np.sin(shift + x/per) * np.exp(-x*x*decay*decay)
if data is None:
return model
return model - data
|