logit_utils_gen.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  1. """
  2. Providing class for logistic regression utilities with polynomial
  3. logit (log odds) function:
  4. p(x|pars) = 1/(1 + exp(-F(x|b(pars))))
  5. with log odds F of polynomial form:
  6. F(x|b) = sum_{i=0}^degree b_i x^i
  7. with decision function (aka logit) F and parameters
  8. b(pars) = [b(pars)_i]_{i=0}^degree
  9. where pars are regression parameters. Coefficients
  10. b(pars) can be constrained to be monotonic function of x by using
  11. monotonic cubic transformation:
  12. b(pars) = mc.forward_map(pars)
  13. where mc is module mono_cubic2.
  14. Author: Martin Horvat, January 2026
  15. """
  16. import numpy as np
  17. import scipy
  18. import scipy.optimize
  19. import mono_cubic2 as mc
  20. def resize_with_const(v, n, val=0):
  21. """
  22. Resize a 1D vector to a specified length `n`.
  23. If the input vector `v` is longer than `n`, it is truncated.
  24. If it is shorter, it is padded with the constant value `val`.
  25. If it is already of length `n`, it is returned unchanged.
  26. Parameters:
  27. v (array-like): Input 1D vector (list or NumPy array).
  28. n (int): Target length of the output vector.
  29. val (scalar, optional): Value used to pad if `v` is shorter than `n`. Default is 0.
  30. Returns:
  31. np.ndarray: Resized 1D NumPy array of length `n`.
  32. """
  33. v = np.asarray(v)
  34. if len(v) == n: return v
  35. if len(v) > n: return v[:n]
  36. return np.concatenate([v, np.full(n - len(v), val)])
  37. def safe_exp(x, max_exp = 700):
  38. """
  39. A numerically robust version of np.exp that avoids overflow by clipping the input.
  40. Parameters:
  41. x : array_like
  42. Input value or array.
  43. max_exp : float
  44. Maximum allowed exponent value. np.exp(709) ≈ 8.2e307 (close to float64 max).
  45. Returns:
  46. array_like
  47. The exponential of the input with overflow protection.
  48. """
  49. return np.exp(np.clip(x, -max_exp, max_exp))
  50. def safe_expit(x, max_exp = 700): return 1/(1 + safe_exp(-x, max_exp))
  51. """
  52. Fitting data
  53. {(x_i, y_i) : x_i in R, y_i in {0,1}, i = 0, ..., n-1 }
  54. to model function
  55. f(x|pars) = 1/(1 + exp(-F(x|beta))) beta = beta(pars)
  56. with log odds of polynomial form:
  57. log(f(x|pars)/(1 - f(x|pars))) = F(x|beta) beta = beta(pars)
  58. where F is decision function (aka logit)
  59. F(x|beta) = sum_{i=0}^degree beta_i x^i
  60. and coefficients
  61. beta = [beta_i(pars)]_{i=0}^degrees
  62. Conditional probability
  63. Prob(Y = y_i|x, pars) = 1/(1 + exp(-s(y) F(x|beta(pars)))
  64. with
  65. s(y) = 2*y -1
  66. """
  67. class LogisticPolyRegression:
  68. """
  69. Constructor
  70. Input:
  71. degree: int, degree of polynomial
  72. mono: boolean, default False
  73. lambda: None or tuple float, L1 and L2 regularization
  74. """
  75. def __init__(self, degree = 1, mono = False, lam = None):
  76. self.degree = degree
  77. self.mono = mono
  78. self.big = 200
  79. self.small = 1e-8
  80. self.lam = lam
  81. if mono:
  82. assert self.degree in [1, 3], f"Degree {self.degree} not supported in mono!"
  83. self.mono3 = self.mono and (self.degree == 3)
  84. """
  85. Mapping regression parameters pars to coefficients beta
  86. beta = beta(pars)
  87. used in decision function:
  88. F(x|beta) = sum_{i=0}^degree beta_i x^i
  89. Input:
  90. pars
  91. Return:
  92. beta
  93. """
  94. def get_beta(self, pars):
  95. beta = mc.forward_map(pars) if self.mono3 else pars
  96. return np.array(beta)
  97. """
  98. Mapping beta to regression parameters used in decision function.
  99. Input:
  100. beta: coefficient beta
  101. Return:
  102. pars
  103. """
  104. def get_pars(self, beta):
  105. pars = mc.backward_map(beta) if self.mono3 else beta
  106. return np.array(pars)
  107. """
  108. Calculate jacobian between beta and regression parameters
  109. J = d(beta)/d(pars)
  110. = [d(beta_i)/d(pars_a)]_{i,a}
  111. and
  112. H = [d^2 beta_i/(d(pars_a) d(pars_b))]_{i,a,b}
  113. Input:
  114. pars
  115. hess: boolean, False
  116. Return:
  117. J if hess = True
  118. (J, H) if hess = False
  119. """
  120. def get_jac_beta(self, pars, hess = False):
  121. n = len(pars)
  122. J = mc.forward_map_jacobian(pars) if self.mono3 else np.eye(n)
  123. if not hess: return J
  124. H = mc.forward_map_hessian(pars) if self.mono3 else np.zeros(shape = (n, n, n))
  125. return (J, H)
  126. """
  127. Model function
  128. f(x|pars) = 1/(1 + exp(-F(x|beta))) beta = beta(pars)
  129. Input:
  130. x: scalar value or a array of values
  131. pars: array of r = degree + 1 floats, model parameters array of floats
  132. Return:
  133. model function values
  134. """
  135. def model(self, x, pars):
  136. beta = self.get_beta(pars) # beta
  137. X = np.column_stack([x**i for i in range(len(beta))])
  138. F = X @ beta # decision function, X beta
  139. return safe_expit(F)
  140. """
  141. Calculate negative log-likelihood function
  142. nllf = -sum_i log(Prob(Y = y_i| x_i, pars)) : neg. log likelihood
  143. grad = [d(nllf)/d(pars_a)]_a : jacobian
  144. where
  145. Prob(Y = y_i| x_i, pars) = 1/(1 + exp(-s_i F(x_i| beta))) beta=beta(pars)
  146. s_i = 2*y_i - 1
  147. Input:
  148. x: array of n floats
  149. y: array of n int in {0,1}
  150. pars: array of r = degree + 1 floats, model parameters array of floats
  151. jac: boolean, default False, if jacobian is needed
  152. Return:
  153. nllf : if jac is false
  154. (nllf, grad) : if jac is true
  155. """
  156. def nllf(self, x, y, pars, jac = False):
  157. beta = self.get_beta(pars)
  158. X = np.column_stack([x**i for i in range(len(beta))])
  159. # signs
  160. s = 2.0*y - 1
  161. # decision function for conditional probability Prob(Y = y| x)
  162. F = s*(X @ beta)
  163. nllf = np.sum(np.log(1 + safe_exp(-F)))
  164. if not jac: return nllf
  165. J = self.get_jac_beta(pars)
  166. grad = -(s*safe_expit(-F)) @ (X @ J)
  167. return (nllf, grad)
  168. """
  169. Penalty function
  170. Input:
  171. pars: array of r = degree + 1 floats, model parameters array of floats
  172. jac: boolean, default False, if jacobian is needed
  173. Return:
  174. val : if jac is false
  175. (val, grad) : if jac is true
  176. """
  177. def penalty(self, pars, jac = False):
  178. val = self.lam[0]*np.sum(np.abs(pars)) + self.lam[1]*np.sum(pars**2)
  179. if jac:
  180. grad = self.lam[0]*np.sign(pars) + 2*self.lam[1]*pars
  181. return (val, grad)
  182. return val
  183. """
  184. Cost function
  185. """
  186. def cost(self, x, y, pars, jac = False):
  187. val = self.nllf(x, y, pars, jac)
  188. if self.lam is not None:
  189. pen = self.penalty(pars, jac)
  190. return (val[0] + pen[0], val[1] + pen[1]) if jac else val + pen
  191. return val
  192. """
  193. Estimate parameters.
  194. Input:
  195. x: array of n floats
  196. y: array of n int in {0,1}
  197. Return:
  198. pars0
  199. """
  200. def get_est_pars(self, x, y):
  201. L = np.log(2*len(x) + 1)
  202. if self.mono3:
  203. z = L*np.polyfit(x, 2.0*y - 1, 1)[::-1]
  204. beta = resize_with_const(z, self.degree + 1, 1e-8)
  205. else:
  206. beta = L*np.polyfit(x, 2.0*y - 1, self.degree)[::-1]
  207. return self.get_pars(beta)
  208. """
  209. Performing logistic regression with log odds of polynomial form:
  210. log(f(x|pars)/(1 - f(x|pars))) = F(x|beta) beta = beta(pars)
  211. and this gives
  212. f(x|pars) = 1/(1 + exp(-F(x|beta)))
  213. where coefficient beta = [beta_i(pars)]_{i=0}^degree, with decision
  214. function (aka logit)
  215. F(x|beta) = sum_{i=0}^degree beta_i x^i
  216. Input:
  217. x: array of n floats
  218. y: array of n int in {0, 1}
  219. Return:
  220. pars
  221. """
  222. def fit(self, x, y, pars0 = None, method = "local"):
  223. bnds = [(-self.big, self.big)]*(self.degree + 1)
  224. if method == "local":
  225. pars0 = self.get_est_pars(x, y)
  226. cf = lambda pars: self.cost(x, y, pars, jac = True)
  227. res = scipy.optimize.minimize(cf, x0 = pars0, method = 'L-BFGS-B',
  228. jac = True, bounds = bnds, tol=1e-12)
  229. elif method == "diff_evol":
  230. cf = lambda pars: self.cost(x, y, pars, jac = False)
  231. res = scipy.optimize.differential_evolution(cf, bounds = bnds,
  232. tol = 1e-8, polish = False)
  233. cf = lambda pars: self.cost(x, y, pars, jac = True)
  234. res = scipy.optimize.minimize(cf, x0 = res.x, method = 'L-BFGS-B',
  235. jac = True, bounds = bnds, tol=1e-12)
  236. elif method == "anneal":
  237. cf = lambda pars: self.cost(x, y, pars, jac = False)
  238. res = scipy.optimize.dual_annealing(cf, bounds = bnds)
  239. else:
  240. assert False, "This method is not supported."
  241. return {"pars": res.x, "cost": res.fun, "success": res.success}
  242. """
  243. Producing goodness of fit measures:
  244. LLF = log_likelihood function
  245. AIC = Akaike information criterion
  246. BIC = Bayesian information criterion
  247. Input:
  248. x: array of n floats
  249. y: array of n int in {0,1}
  250. pars: array of r = degree+1 floats, model parameters
  251. thresh: float, default 0.5, threshold value for classification
  252. Return:
  253. {"n": n, "k":k, "dof":n-k,
  254. "LLF": log_likelihood,
  255. "AIC": AIC,
  256. "BIC": BIC,
  257. "A": classification accuracy (threshold values = 0.5 prob)}
  258. Ref:
  259. https://en.wikipedia.org/wiki/Logistic_regression
  260. https://en.wikipedia.org/wiki/Akaike_information_criterion
  261. https://www.medicine.mcgill.ca/epidemiology/joseph/courses/epib-621/logfit.pdf
  262. """
  263. def goodness_of_fit(self, x, y, pars, thresh = 0.5):
  264. # model probabilities
  265. p = self.model(x, pars)
  266. # log likelihood
  267. llf = -self.nllf(x, y, pars)
  268. # information criteria
  269. k, n = len(pars), len(x)
  270. AIC = 2*k - 2*llf
  271. BIC = k*np.log(n) - 2*llf
  272. # chi2
  273. dof = n - k
  274. r = (y - p)/np.sqrt(p*(1-p) + self.small)
  275. chi2 = np.sum(r**2)
  276. p_val = scipy.stats.chi2.sf(chi2, dof)
  277. # using model as classifier
  278. matches = y == np.heaviside(p - thresh, 1)
  279. # accuracy A
  280. A = np.count_nonzero(matches)/n
  281. return {"LLF": llf,
  282. "AIC": AIC,
  283. "BIC": BIC,
  284. "A" : A,
  285. "chi2": chi2,
  286. "p-value(chi2)": p_val, # not very useful
  287. "n": n, "k": k, "dof": dof}
  288. """
  289. Calculation of asymptotic variance-covariance matrix of parameters pars
  290. cov_{asymp}[pars] = H^{-1}
  291. where H is hessian of nllf
  292. H = [d^2(nllf)/(d(pars)_a d(pars)_b ]_{a,b}
  293. for the logistic regression of the polynomial model:
  294. log(f(x)/(1 - f(x))) ~ sum_{i=0}^degree b_i(pars) x^i
  295. Input:
  296. x: array of n floats
  297. pars: array of r = degree+1 floats, model parameters
  298. Return:
  299. array of rxr floats; r = degree + 1
  300. Ref:
  301. https://stats.stackexchange.com/questions/89484/how-to-compute-the-standard-errors-of-a-logistic-regressions-coefficients
  302. https://goodboychan.github.io/machine_learning/2020/09/14/02-Regularized-likelihood-methods.html
  303. """
  304. def cov(self, x, y, pars):
  305. # coefficients
  306. beta = self.get_beta(pars)
  307. # design matrix -- add column of 1's at the beginning of your X_train matrix
  308. X = np.column_stack([x**i for i in range(len(beta))])
  309. # Jacobian J = [dbeta_i/dpars_j]_{ij}
  310. J, H = self.get_jac_beta(pars, hess = True)
  311. # signs
  312. s = 2.0*y - 1
  313. # decision function for conditional probability Prob(Y = y| x)
  314. F = s*(X @ beta)
  315. # probabilities p_i = P(Y=y_i | x_i)
  316. p = safe_expit(F)
  317. q = 1 - p
  318. # calculate hessian
  319. L = X @ J
  320. H = (L.T*(q*p))@L - np.tensordot((s*q)@X, H, axes = ([0], [0]))
  321. if self.lam is not None:
  322. Hp = H + 2*self.lam[1]*np.eye(len(pars)) # H' = H + lambda id
  323. iHp = np.linalg.inv(Hp) # inv(H')
  324. return iHp@H@iHp
  325. # covariance matrix C_params = H^-1
  326. return np.linalg.inv(H)
  327. """
  328. Calculating quantiles of the model parameters at given probabilities p
  329. for normal distribution of parameters:
  330. pars ~ N(mean_pars, cov_pars)
  331. Input:
  332. probs: array of m floats, probabilities
  333. mean_pars: array of r = degree+1 floats, mean model parameters
  334. cov_pars: array of rxr floats, variance-covariance matrix of parameters
  335. Return:
  336. array of mxr floats
  337. """
  338. def get_pars_quantiles_normal(self, probs, mean_pars, cov_pars):
  339. # mean and standard variance parameters
  340. locs = mean_pars
  341. scales = np.sqrt(np.diag(cov_pars))
  342. # computing quantiles of parameters
  343. return locs + np.outer(scipy.stats.norm.ppf(probs), scales)
  344. """
  345. Calculating quantiles of the model values
  346. f(x|pars) = 1/(1 + exp(-F(x|beta))) beta = beta(pars)
  347. with
  348. F(x|beta) = sum_{i=0}^degree x^i beta_i
  349. at given probabilities p and values x assuming
  350. normal distribution of parameters:
  351. pars ~ N(mean_pars, cov_pars)
  352. This distribution is asymptotic MLE distribution of parameters.
  353. Input:
  354. x: array of n float
  355. probs: array of m floats, probabilities
  356. mean_pars: array of r = degree+1 floats, mean model parameters
  357. cov_pars: array of rxr floats, variance-covariance matrix of parameters
  358. Return:
  359. array of mxn floats
  360. """
  361. def get_model_quantiles_normal(self, x, probs, mean_pars, cov_pars,
  362. exact = True, seed = 1977, m = 10**5):
  363. mean_beta = self.get_beta(mean_pars)
  364. X = np.column_stack([x**i for i in range(len(mean_beta))])
  365. if exact and self.mono3:
  366. # init random generator
  367. rng = np.random.default_rng(seed)
  368. pars = rng.multivariate_normal(mean_pars, cov_pars, size = m)
  369. # get betas
  370. beta = np.apply_along_axis(self.get_beta, 1, pars)
  371. # quantiles of decision function
  372. Q = np.quantile(X@beta.T, probs, axis = 1)
  373. return np.apply_along_axis(safe_expit, 1, Q)
  374. # J = d(beta)/d(pars)
  375. J = self.get_jac_beta(mean_pars)
  376. # transform data
  377. S = X@J
  378. # mean and standard variance of logit (aka log of odds)
  379. locs = X@mean_beta
  380. scales = np.sqrt(np.diag(S@cov_pars@S.T))
  381. # computing quantiles of logit
  382. Q = locs + np.outer(scipy.stats.norm.ppf(probs), scales)
  383. # convert logit to expit
  384. return safe_expit(Q)
  385. """
  386. Calculating quantiles using delta method of the model values
  387. f(x|pars) = 1/(1 + exp(-F(x|beta))) beta = beta(pars)
  388. with
  389. F(x|beta) = sum_{i=0}^degree x^i beta_i
  390. at given probabilities p and values x assuming
  391. normal distribution of parameters :
  392. pars ~ N(mean_pars, cov_pars)
  393. This distribution is asymptotic MLE distribution of parameters.
  394. We approximate exact model with linear expansion
  395. f(x|pars) = p(x|pars_mean) + dp/db(x|pars_mean) (pars - pars_mean)
  396. and the last term is normally distributed.
  397. Input:
  398. x: array of n float
  399. probs: array of m floats, probabilities
  400. mean_pars: array of r = degree+1 floats, mean model parameters
  401. cov_pars: array of rxr floats, variance-covariance matrix of parameters
  402. Return:
  403. array of mxn floats
  404. """
  405. def get_model_quantiles_delta(self, x, probs, mean_pars, cov_pars):
  406. mean_beta = self.get_beta(mean_pars)
  407. X = np.column_stack([x**i for i in range(len(mean_beta))])
  408. F = X@mean_beta
  409. # J = d(beta)/d(pars)
  410. J = self.get_jac_beta(mean_pars)
  411. # S = d(F)/d(pars)
  412. S = X@J
  413. # attributes of normal distribution of model values
  414. locs = safe_expit(F)
  415. scales = np.sqrt(np.diag(S@cov_pars@S.T))/(4*np.cosh(F/2)**2)
  416. # computing quantiles of logit
  417. Q = locs + np.outer(scipy.stats.norm.ppf(probs), scales)
  418. return np.clip(Q, a_min = 0, a_max = 1)
  419. """
  420. Generate parameters assuming normal distribution.
  421. Input:
  422. x : array of n floats
  423. y : array of n int in {0,1}
  424. m: integer, number of samples
  425. seed : int, seed for the random generator
  426. Return:
  427. array of mx(degree + 1)
  428. """
  429. def get_normal_pars(self, x, y, m, seed = 1977):
  430. res = self.fit(x, y, method = "diff_evol")
  431. assert res["success"], "Fit did not succeed."
  432. # optimal parameters
  433. pars = res["pars"]
  434. # covariance matrix of parameters
  435. cov = self.cov(x, y, pars)
  436. # init random generator
  437. rng = np.random.default_rng(seed)
  438. return rng.multivariate_normal(pars, cov, size = m)
  439. """
  440. Generate m parameters via non-parametric bootstrapping with a minimal constraint
  441. that both groups should be present in the sampled data:
  442. boostrapped sample = (xb, yb) by sampling with replacement pairs (x_i, y_i)
  443. with condition that yb can not be just 0 or just 1
  444. Input:
  445. x : array of n floats
  446. y : array of n int in {0,1}
  447. m: integer, number of samples
  448. seed : int, seed for the random generator
  449. Return:
  450. array of mx(degree + 1)
  451. """
  452. def get_nonparam_boots_pars(self, x, y, m, seed = 1977):
  453. # fitting original data
  454. res_fit = self.fit(x, y, method = "diff_evol")
  455. assert res_fit["success"]
  456. pars0 = res_fit["pars"]
  457. n = len(x)
  458. rng = np.random.default_rng(seed)
  459. # generate parameters
  460. lst = [pars0]
  461. while True:
  462. # create set indices for sampling with replacement + constraint
  463. idx = rng.choice(n, n)
  464. if np.sum(y[idx]) in [0, n]: continue
  465. # do fitting
  466. res_fit = self.fit(x[idx], y[idx], pars0, method="local")
  467. if not res_fit["success"]: continue
  468. # store pars
  469. lst.append(res_fit["pars"])
  470. if len(lst) == m: break
  471. return np.array(lst)
  472. """
  473. Generate m parameters via non-parametric stratified bootstrapping:
  474. boostrapped sample = (xb, yb)
  475. xb = (sampled with replacement from x0, sampled with replacement from x1)
  476. yb = (0...0, 1...1)
  477. Input:
  478. x : array of n floats
  479. y : array of n int in {0,1}
  480. m: integer, number of samples
  481. seed : int, seed for the random generator
  482. Return:
  483. array of mx(degree + 1)
  484. """
  485. def get_nonparam_stratified_boots_pars(self, x, y, m, seed = 1977):
  486. # pars of original data
  487. res_fit = self.fit(x, y, method = "diff_evol")
  488. assert res_fit["success"]
  489. pars0 = res_fit["pars"]
  490. # statistics about groups
  491. xs = [x[y == i] for i in range(2)]
  492. ns = [len(e) for e in xs]
  493. # common vector states
  494. yb = np.concatenate([np.full(ns[i], i) for i in range(2)])
  495. rng = np.random.default_rng(seed)
  496. # generate parameters
  497. lst = [pars0]
  498. for _ in range(m):
  499. # stratified sampling with replacement
  500. xb = np.concatenate([rng.choice(xs[i], ns[i]) for i in range(2)])
  501. # do fitting
  502. res_fit = self.fit(xb, yb, pars0, method="local")
  503. if not res_fit["success"]: continue
  504. # store pars
  505. lst.append(res_fit["pars"])
  506. if len(lst) == m: break
  507. return np.array(lst)
  508. """
  509. Generate m parameters via parametric bootstrapping:
  510. boostrapped sample = (x, yb) yb ~ B(model(x, fitted pars))
  511. where B is Bernoulli distribution
  512. Input:
  513. x : array of n floats
  514. y : array of n int in {0,1}
  515. m: integer, number of samples
  516. seed : int, seed for the random generator
  517. Return:
  518. array of mx(degree + 1)
  519. Ref:
  520. * https://www.scirp.org/journal/paperinformation?paperid=70962
  521. * https://en.wikipedia.org/wiki/Bernoulli_distribution
  522. """
  523. def get_parametric_boots_pars(self, x, y, m, seed = 1977):
  524. # first discuss original dataset
  525. res_fit = self.fit(x, y, method = "diff_evol")
  526. assert res_fit["success"]
  527. pars0 = res_fit["pars"]
  528. p = self.model(x, pars0)
  529. n = len(x)
  530. rng = np.random.default_rng(seed)
  531. # generate parameters
  532. lst = [pars0]
  533. while True:
  534. # Generate new binary outcomes from Bernoulli(p_i)
  535. y_sim = rng.binomial(n = 1, p = p)
  536. if np.sum(y_sim) in [0, n]: continue
  537. # do fitting
  538. res_fit = self.fit(x, y_sim, pars0, method="local")
  539. if not res_fit["success"]: continue
  540. # store pars
  541. lst.append(res_fit["pars"])
  542. if len(lst) == m: break
  543. return np.array(lst)