ZTWHHH commited on
Commit
a3e9faf
·
verified ·
1 Parent(s): 27e4287

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +3 -0
  2. vila/lib/python3.10/site-packages/scipy/optimize/_basinhopping.py +753 -0
  3. vila/lib/python3.10/site-packages/scipy/optimize/_bglu_dense.cpython-310-x86_64-linux-gnu.so +3 -0
  4. vila/lib/python3.10/site-packages/scipy/optimize/_cobyqa_py.py +62 -0
  5. vila/lib/python3.10/site-packages/scipy/optimize/_constraints.py +590 -0
  6. vila/lib/python3.10/site-packages/scipy/optimize/_dcsrch.py +728 -0
  7. vila/lib/python3.10/site-packages/scipy/optimize/_direct.cpython-310-x86_64-linux-gnu.so +0 -0
  8. vila/lib/python3.10/site-packages/scipy/optimize/_direct_py.py +278 -0
  9. vila/lib/python3.10/site-packages/scipy/optimize/_group_columns.cpython-310-x86_64-linux-gnu.so +0 -0
  10. vila/lib/python3.10/site-packages/scipy/optimize/_hessian_update_strategy.py +475 -0
  11. vila/lib/python3.10/site-packages/scipy/optimize/_highs/__init__.py +0 -0
  12. vila/lib/python3.10/site-packages/scipy/optimize/_highs/_highs_constants.cpython-310-x86_64-linux-gnu.so +0 -0
  13. vila/lib/python3.10/site-packages/scipy/optimize/_highs/src/cython/HConst.pxd +106 -0
  14. vila/lib/python3.10/site-packages/scipy/optimize/_highs/src/cython/Highs.pxd +56 -0
  15. vila/lib/python3.10/site-packages/scipy/optimize/_highs/src/cython/HighsInfo.pxd +22 -0
  16. vila/lib/python3.10/site-packages/scipy/optimize/_highs/src/cython/HighsLp.pxd +46 -0
  17. vila/lib/python3.10/site-packages/scipy/optimize/_highs/src/cython/HighsLpUtils.pxd +9 -0
  18. vila/lib/python3.10/site-packages/scipy/optimize/_highs/src/cython/HighsModelUtils.pxd +10 -0
  19. vila/lib/python3.10/site-packages/scipy/optimize/_highs/src/cython/HighsOptions.pxd +110 -0
  20. vila/lib/python3.10/site-packages/scipy/optimize/_highs/src/cython/HighsRuntimeOptions.pxd +9 -0
  21. vila/lib/python3.10/site-packages/scipy/optimize/_highs/src/cython/HighsStatus.pxd +12 -0
  22. vila/lib/python3.10/site-packages/scipy/optimize/_lbfgsb_py.py +543 -0
  23. vila/lib/python3.10/site-packages/scipy/optimize/_linprog.py +716 -0
  24. vila/lib/python3.10/site-packages/scipy/optimize/_linprog_highs.py +440 -0
  25. vila/lib/python3.10/site-packages/scipy/optimize/_linprog_ip.py +1126 -0
  26. vila/lib/python3.10/site-packages/scipy/optimize/_linprog_rs.py +572 -0
  27. vila/lib/python3.10/site-packages/scipy/optimize/_linprog_simplex.py +661 -0
  28. vila/lib/python3.10/site-packages/scipy/optimize/_linprog_util.py +1522 -0
  29. vila/lib/python3.10/site-packages/scipy/optimize/_lsap.cpython-310-x86_64-linux-gnu.so +0 -0
  30. vila/lib/python3.10/site-packages/scipy/optimize/_milp.py +392 -0
  31. vila/lib/python3.10/site-packages/scipy/optimize/_minpack_py.py +1164 -0
  32. vila/lib/python3.10/site-packages/scipy/optimize/_moduleTNC.cpython-310-x86_64-linux-gnu.so +3 -0
  33. vila/lib/python3.10/site-packages/scipy/optimize/_nnls.py +164 -0
  34. vila/lib/python3.10/site-packages/scipy/optimize/_nonlin.py +1585 -0
  35. vila/lib/python3.10/site-packages/scipy/optimize/_numdiff.py +779 -0
  36. vila/lib/python3.10/site-packages/scipy/optimize/_optimize.py +0 -0
  37. vila/lib/python3.10/site-packages/scipy/optimize/_pava_pybind.cpython-310-x86_64-linux-gnu.so +3 -0
  38. vila/lib/python3.10/site-packages/scipy/optimize/_root_scalar.py +525 -0
  39. vila/lib/python3.10/site-packages/scipy/optimize/_shgo_lib/__init__.py +0 -0
  40. vila/lib/python3.10/site-packages/scipy/optimize/_shgo_lib/__pycache__/__init__.cpython-310.pyc +0 -0
  41. vila/lib/python3.10/site-packages/scipy/optimize/_shgo_lib/__pycache__/_complex.cpython-310.pyc +0 -0
  42. vila/lib/python3.10/site-packages/scipy/optimize/_shgo_lib/__pycache__/_vertex.cpython-310.pyc +0 -0
  43. vila/lib/python3.10/site-packages/scipy/optimize/_shgo_lib/_complex.py +1225 -0
  44. vila/lib/python3.10/site-packages/scipy/optimize/_shgo_lib/_vertex.py +460 -0
  45. vila/lib/python3.10/site-packages/scipy/optimize/_slsqp.cpython-310-x86_64-linux-gnu.so +0 -0
  46. vila/lib/python3.10/site-packages/scipy/optimize/_tnc.py +430 -0
  47. vila/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__init__.py +6 -0
  48. vila/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__pycache__/__init__.cpython-310.pyc +0 -0
  49. vila/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__pycache__/canonical_constraint.cpython-310.pyc +0 -0
  50. vila/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__pycache__/equality_constrained_sqp.cpython-310.pyc +0 -0
.gitattributes CHANGED
@@ -1077,3 +1077,6 @@ vila/lib/python3.10/site-packages/pandas/tests/io/__pycache__/test_sql.cpython-3
1077
  vila/lib/python3.10/site-packages/pandas/tests/tools/__pycache__/test_to_datetime.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1078
  vila/lib/python3.10/site-packages/av/bitstream.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1079
  vila/lib/python3.10/site-packages/av/enum.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
 
 
 
 
1077
  vila/lib/python3.10/site-packages/pandas/tests/tools/__pycache__/test_to_datetime.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1078
  vila/lib/python3.10/site-packages/av/bitstream.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1079
  vila/lib/python3.10/site-packages/av/enum.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1080
+ vila/lib/python3.10/site-packages/scipy/optimize/_pava_pybind.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1081
+ vila/lib/python3.10/site-packages/scipy/optimize/_bglu_dense.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1082
+ vila/lib/python3.10/site-packages/scipy/optimize/_moduleTNC.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
vila/lib/python3.10/site-packages/scipy/optimize/_basinhopping.py ADDED
@@ -0,0 +1,753 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ basinhopping: The basinhopping global optimization algorithm
3
+ """
4
+ import numpy as np
5
+ import math
6
+ import inspect
7
+ import scipy.optimize
8
+ from scipy._lib._util import check_random_state
9
+
10
+ __all__ = ['basinhopping']
11
+
12
+
13
+ _params = (inspect.Parameter('res_new', kind=inspect.Parameter.KEYWORD_ONLY),
14
+ inspect.Parameter('res_old', kind=inspect.Parameter.KEYWORD_ONLY))
15
+ _new_accept_test_signature = inspect.Signature(parameters=_params)
16
+
17
+
18
+ class Storage:
19
+ """
20
+ Class used to store the lowest energy structure
21
+ """
22
+ def __init__(self, minres):
23
+ self._add(minres)
24
+
25
+ def _add(self, minres):
26
+ self.minres = minres
27
+ self.minres.x = np.copy(minres.x)
28
+
29
+ def update(self, minres):
30
+ if minres.success and (minres.fun < self.minres.fun
31
+ or not self.minres.success):
32
+ self._add(minres)
33
+ return True
34
+ else:
35
+ return False
36
+
37
+ def get_lowest(self):
38
+ return self.minres
39
+
40
+
41
+ class BasinHoppingRunner:
42
+ """This class implements the core of the basinhopping algorithm.
43
+
44
+ x0 : ndarray
45
+ The starting coordinates.
46
+ minimizer : callable
47
+ The local minimizer, with signature ``result = minimizer(x)``.
48
+ The return value is an `optimize.OptimizeResult` object.
49
+ step_taking : callable
50
+ This function displaces the coordinates randomly. Signature should
51
+ be ``x_new = step_taking(x)``. Note that `x` may be modified in-place.
52
+ accept_tests : list of callables
53
+ Each test is passed the kwargs `f_new`, `x_new`, `f_old` and
54
+ `x_old`. These tests will be used to judge whether or not to accept
55
+ the step. The acceptable return values are True, False, or ``"force
56
+ accept"``. If any of the tests return False then the step is rejected.
57
+ If ``"force accept"``, then this will override any other tests in
58
+ order to accept the step. This can be used, for example, to forcefully
59
+ escape from a local minimum that ``basinhopping`` is trapped in.
60
+ disp : bool, optional
61
+ Display status messages.
62
+
63
+ """
64
+ def __init__(self, x0, minimizer, step_taking, accept_tests, disp=False):
65
+ self.x = np.copy(x0)
66
+ self.minimizer = minimizer
67
+ self.step_taking = step_taking
68
+ self.accept_tests = accept_tests
69
+ self.disp = disp
70
+
71
+ self.nstep = 0
72
+
73
+ # initialize return object
74
+ self.res = scipy.optimize.OptimizeResult()
75
+ self.res.minimization_failures = 0
76
+
77
+ # do initial minimization
78
+ minres = minimizer(self.x)
79
+ if not minres.success:
80
+ self.res.minimization_failures += 1
81
+ if self.disp:
82
+ print("warning: basinhopping: local minimization failure")
83
+ self.x = np.copy(minres.x)
84
+ self.energy = minres.fun
85
+ self.incumbent_minres = minres # best minimize result found so far
86
+ if self.disp:
87
+ print("basinhopping step %d: f %g" % (self.nstep, self.energy))
88
+
89
+ # initialize storage class
90
+ self.storage = Storage(minres)
91
+
92
+ if hasattr(minres, "nfev"):
93
+ self.res.nfev = minres.nfev
94
+ if hasattr(minres, "njev"):
95
+ self.res.njev = minres.njev
96
+ if hasattr(minres, "nhev"):
97
+ self.res.nhev = minres.nhev
98
+
99
+ def _monte_carlo_step(self):
100
+ """Do one Monte Carlo iteration
101
+
102
+ Randomly displace the coordinates, minimize, and decide whether
103
+ or not to accept the new coordinates.
104
+ """
105
+ # Take a random step. Make a copy of x because the step_taking
106
+ # algorithm might change x in place
107
+ x_after_step = np.copy(self.x)
108
+ x_after_step = self.step_taking(x_after_step)
109
+
110
+ # do a local minimization
111
+ minres = self.minimizer(x_after_step)
112
+ x_after_quench = minres.x
113
+ energy_after_quench = minres.fun
114
+ if not minres.success:
115
+ self.res.minimization_failures += 1
116
+ if self.disp:
117
+ print("warning: basinhopping: local minimization failure")
118
+ if hasattr(minres, "nfev"):
119
+ self.res.nfev += minres.nfev
120
+ if hasattr(minres, "njev"):
121
+ self.res.njev += minres.njev
122
+ if hasattr(minres, "nhev"):
123
+ self.res.nhev += minres.nhev
124
+
125
+ # accept the move based on self.accept_tests. If any test is False,
126
+ # then reject the step. If any test returns the special string
127
+ # 'force accept', then accept the step regardless. This can be used
128
+ # to forcefully escape from a local minimum if normal basin hopping
129
+ # steps are not sufficient.
130
+ accept = True
131
+ for test in self.accept_tests:
132
+ if inspect.signature(test) == _new_accept_test_signature:
133
+ testres = test(res_new=minres, res_old=self.incumbent_minres)
134
+ else:
135
+ testres = test(f_new=energy_after_quench, x_new=x_after_quench,
136
+ f_old=self.energy, x_old=self.x)
137
+
138
+ if testres == 'force accept':
139
+ accept = True
140
+ break
141
+ elif testres is None:
142
+ raise ValueError("accept_tests must return True, False, or "
143
+ "'force accept'")
144
+ elif not testres:
145
+ accept = False
146
+
147
+ # Report the result of the acceptance test to the take step class.
148
+ # This is for adaptive step taking
149
+ if hasattr(self.step_taking, "report"):
150
+ self.step_taking.report(accept, f_new=energy_after_quench,
151
+ x_new=x_after_quench, f_old=self.energy,
152
+ x_old=self.x)
153
+
154
+ return accept, minres
155
+
156
+ def one_cycle(self):
157
+ """Do one cycle of the basinhopping algorithm
158
+ """
159
+ self.nstep += 1
160
+ new_global_min = False
161
+
162
+ accept, minres = self._monte_carlo_step()
163
+
164
+ if accept:
165
+ self.energy = minres.fun
166
+ self.x = np.copy(minres.x)
167
+ self.incumbent_minres = minres # best minimize result found so far
168
+ new_global_min = self.storage.update(minres)
169
+
170
+ # print some information
171
+ if self.disp:
172
+ self.print_report(minres.fun, accept)
173
+ if new_global_min:
174
+ print("found new global minimum on step %d with function"
175
+ " value %g" % (self.nstep, self.energy))
176
+
177
+ # save some variables as BasinHoppingRunner attributes
178
+ self.xtrial = minres.x
179
+ self.energy_trial = minres.fun
180
+ self.accept = accept
181
+
182
+ return new_global_min
183
+
184
+ def print_report(self, energy_trial, accept):
185
+ """print a status update"""
186
+ minres = self.storage.get_lowest()
187
+ print("basinhopping step %d: f %g trial_f %g accepted %d "
188
+ " lowest_f %g" % (self.nstep, self.energy, energy_trial,
189
+ accept, minres.fun))
190
+
191
+
192
+ class AdaptiveStepsize:
193
+ """
194
+ Class to implement adaptive stepsize.
195
+
196
+ This class wraps the step taking class and modifies the stepsize to
197
+ ensure the true acceptance rate is as close as possible to the target.
198
+
199
+ Parameters
200
+ ----------
201
+ takestep : callable
202
+ The step taking routine. Must contain modifiable attribute
203
+ takestep.stepsize
204
+ accept_rate : float, optional
205
+ The target step acceptance rate
206
+ interval : int, optional
207
+ Interval for how often to update the stepsize
208
+ factor : float, optional
209
+ The step size is multiplied or divided by this factor upon each
210
+ update.
211
+ verbose : bool, optional
212
+ Print information about each update
213
+
214
+ """
215
+ def __init__(self, takestep, accept_rate=0.5, interval=50, factor=0.9,
216
+ verbose=True):
217
+ self.takestep = takestep
218
+ self.target_accept_rate = accept_rate
219
+ self.interval = interval
220
+ self.factor = factor
221
+ self.verbose = verbose
222
+
223
+ self.nstep = 0
224
+ self.nstep_tot = 0
225
+ self.naccept = 0
226
+
227
+ def __call__(self, x):
228
+ return self.take_step(x)
229
+
230
+ def _adjust_step_size(self):
231
+ old_stepsize = self.takestep.stepsize
232
+ accept_rate = float(self.naccept) / self.nstep
233
+ if accept_rate > self.target_accept_rate:
234
+ # We're accepting too many steps. This generally means we're
235
+ # trapped in a basin. Take bigger steps.
236
+ self.takestep.stepsize /= self.factor
237
+ else:
238
+ # We're not accepting enough steps. Take smaller steps.
239
+ self.takestep.stepsize *= self.factor
240
+ if self.verbose:
241
+ print(f"adaptive stepsize: acceptance rate {accept_rate:f} target "
242
+ f"{self.target_accept_rate:f} new stepsize "
243
+ f"{self.takestep.stepsize:g} old stepsize {old_stepsize:g}")
244
+
245
+ def take_step(self, x):
246
+ self.nstep += 1
247
+ self.nstep_tot += 1
248
+ if self.nstep % self.interval == 0:
249
+ self._adjust_step_size()
250
+ return self.takestep(x)
251
+
252
+ def report(self, accept, **kwargs):
253
+ "called by basinhopping to report the result of the step"
254
+ if accept:
255
+ self.naccept += 1
256
+
257
+
258
+ class RandomDisplacement:
259
+ """Add a random displacement of maximum size `stepsize` to each coordinate.
260
+
261
+ Calling this updates `x` in-place.
262
+
263
+ Parameters
264
+ ----------
265
+ stepsize : float, optional
266
+ Maximum stepsize in any dimension
267
+ random_gen : {None, int, `numpy.random.Generator`,
268
+ `numpy.random.RandomState`}, optional
269
+
270
+ If `seed` is None (or `np.random`), the `numpy.random.RandomState`
271
+ singleton is used.
272
+ If `seed` is an int, a new ``RandomState`` instance is used,
273
+ seeded with `seed`.
274
+ If `seed` is already a ``Generator`` or ``RandomState`` instance then
275
+ that instance is used.
276
+
277
+ """
278
+
279
+ def __init__(self, stepsize=0.5, random_gen=None):
280
+ self.stepsize = stepsize
281
+ self.random_gen = check_random_state(random_gen)
282
+
283
+ def __call__(self, x):
284
+ x += self.random_gen.uniform(-self.stepsize, self.stepsize,
285
+ np.shape(x))
286
+ return x
287
+
288
+
289
+ class MinimizerWrapper:
290
+ """
291
+ wrap a minimizer function as a minimizer class
292
+ """
293
+ def __init__(self, minimizer, func=None, **kwargs):
294
+ self.minimizer = minimizer
295
+ self.func = func
296
+ self.kwargs = kwargs
297
+
298
+ def __call__(self, x0):
299
+ if self.func is None:
300
+ return self.minimizer(x0, **self.kwargs)
301
+ else:
302
+ return self.minimizer(self.func, x0, **self.kwargs)
303
+
304
+
305
+ class Metropolis:
306
+ """Metropolis acceptance criterion.
307
+
308
+ Parameters
309
+ ----------
310
+ T : float
311
+ The "temperature" parameter for the accept or reject criterion.
312
+ random_gen : {None, int, `numpy.random.Generator`,
313
+ `numpy.random.RandomState`}, optional
314
+
315
+ If `seed` is None (or `np.random`), the `numpy.random.RandomState`
316
+ singleton is used.
317
+ If `seed` is an int, a new ``RandomState`` instance is used,
318
+ seeded with `seed`.
319
+ If `seed` is already a ``Generator`` or ``RandomState`` instance then
320
+ that instance is used.
321
+ Random number generator used for acceptance test.
322
+
323
+ """
324
+
325
+ def __init__(self, T, random_gen=None):
326
+ # Avoid ZeroDivisionError since "MBH can be regarded as a special case
327
+ # of the BH framework with the Metropolis criterion, where temperature
328
+ # T = 0." (Reject all steps that increase energy.)
329
+ self.beta = 1.0 / T if T != 0 else float('inf')
330
+ self.random_gen = check_random_state(random_gen)
331
+
332
+ def accept_reject(self, res_new, res_old):
333
+ """
334
+ Assuming the local search underlying res_new was successful:
335
+ If new energy is lower than old, it will always be accepted.
336
+ If new is higher than old, there is a chance it will be accepted,
337
+ less likely for larger differences.
338
+ """
339
+ with np.errstate(invalid='ignore'):
340
+ # The energy values being fed to Metropolis are 1-length arrays, and if
341
+ # they are equal, their difference is 0, which gets multiplied by beta,
342
+ # which is inf, and array([0]) * float('inf') causes
343
+ #
344
+ # RuntimeWarning: invalid value encountered in multiply
345
+ #
346
+ # Ignore this warning so when the algorithm is on a flat plane, it always
347
+ # accepts the step, to try to move off the plane.
348
+ prod = -(res_new.fun - res_old.fun) * self.beta
349
+ w = math.exp(min(0, prod))
350
+
351
+ rand = self.random_gen.uniform()
352
+ return w >= rand and (res_new.success or not res_old.success)
353
+
354
+ def __call__(self, *, res_new, res_old):
355
+ """
356
+ f_new and f_old are mandatory in kwargs
357
+ """
358
+ return bool(self.accept_reject(res_new, res_old))
359
+
360
+
361
+ def basinhopping(func, x0, niter=100, T=1.0, stepsize=0.5,
362
+ minimizer_kwargs=None, take_step=None, accept_test=None,
363
+ callback=None, interval=50, disp=False, niter_success=None,
364
+ seed=None, *, target_accept_rate=0.5, stepwise_factor=0.9):
365
+ """Find the global minimum of a function using the basin-hopping algorithm.
366
+
367
+ Basin-hopping is a two-phase method that combines a global stepping
368
+ algorithm with local minimization at each step. Designed to mimic
369
+ the natural process of energy minimization of clusters of atoms, it works
370
+ well for similar problems with "funnel-like, but rugged" energy landscapes
371
+ [5]_.
372
+
373
+ As the step-taking, step acceptance, and minimization methods are all
374
+ customizable, this function can also be used to implement other two-phase
375
+ methods.
376
+
377
+ Parameters
378
+ ----------
379
+ func : callable ``f(x, *args)``
380
+ Function to be optimized. ``args`` can be passed as an optional item
381
+ in the dict `minimizer_kwargs`
382
+ x0 : array_like
383
+ Initial guess.
384
+ niter : integer, optional
385
+ The number of basin-hopping iterations. There will be a total of
386
+ ``niter + 1`` runs of the local minimizer.
387
+ T : float, optional
388
+ The "temperature" parameter for the acceptance or rejection criterion.
389
+ Higher "temperatures" mean that larger jumps in function value will be
390
+ accepted. For best results `T` should be comparable to the
391
+ separation (in function value) between local minima.
392
+ stepsize : float, optional
393
+ Maximum step size for use in the random displacement.
394
+ minimizer_kwargs : dict, optional
395
+ Extra keyword arguments to be passed to the local minimizer
396
+ `scipy.optimize.minimize` Some important options could be:
397
+
398
+ method : str
399
+ The minimization method (e.g. ``"L-BFGS-B"``)
400
+ args : tuple
401
+ Extra arguments passed to the objective function (`func`) and
402
+ its derivatives (Jacobian, Hessian).
403
+
404
+ take_step : callable ``take_step(x)``, optional
405
+ Replace the default step-taking routine with this routine. The default
406
+ step-taking routine is a random displacement of the coordinates, but
407
+ other step-taking algorithms may be better for some systems.
408
+ `take_step` can optionally have the attribute ``take_step.stepsize``.
409
+ If this attribute exists, then `basinhopping` will adjust
410
+ ``take_step.stepsize`` in order to try to optimize the global minimum
411
+ search.
412
+ accept_test : callable, ``accept_test(f_new=f_new, x_new=x_new, f_old=fold, x_old=x_old)``, optional
413
+ Define a test which will be used to judge whether to accept the
414
+ step. This will be used in addition to the Metropolis test based on
415
+ "temperature" `T`. The acceptable return values are True,
416
+ False, or ``"force accept"``. If any of the tests return False
417
+ then the step is rejected. If the latter, then this will override any
418
+ other tests in order to accept the step. This can be used, for example,
419
+ to forcefully escape from a local minimum that `basinhopping` is
420
+ trapped in.
421
+ callback : callable, ``callback(x, f, accept)``, optional
422
+ A callback function which will be called for all minima found. ``x``
423
+ and ``f`` are the coordinates and function value of the trial minimum,
424
+ and ``accept`` is whether that minimum was accepted. This can
425
+ be used, for example, to save the lowest N minima found. Also,
426
+ `callback` can be used to specify a user defined stop criterion by
427
+ optionally returning True to stop the `basinhopping` routine.
428
+ interval : integer, optional
429
+ interval for how often to update the `stepsize`
430
+ disp : bool, optional
431
+ Set to True to print status messages
432
+ niter_success : integer, optional
433
+ Stop the run if the global minimum candidate remains the same for this
434
+ number of iterations.
435
+ seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
436
+
437
+ If `seed` is None (or `np.random`), the `numpy.random.RandomState`
438
+ singleton is used.
439
+ If `seed` is an int, a new ``RandomState`` instance is used,
440
+ seeded with `seed`.
441
+ If `seed` is already a ``Generator`` or ``RandomState`` instance then
442
+ that instance is used.
443
+ Specify `seed` for repeatable minimizations. The random numbers
444
+ generated with this seed only affect the default Metropolis
445
+ `accept_test` and the default `take_step`. If you supply your own
446
+ `take_step` and `accept_test`, and these functions use random
447
+ number generation, then those functions are responsible for the state
448
+ of their random number generator.
449
+ target_accept_rate : float, optional
450
+ The target acceptance rate that is used to adjust the `stepsize`.
451
+ If the current acceptance rate is greater than the target,
452
+ then the `stepsize` is increased. Otherwise, it is decreased.
453
+ Range is (0, 1). Default is 0.5.
454
+
455
+ .. versionadded:: 1.8.0
456
+
457
+ stepwise_factor : float, optional
458
+ The `stepsize` is multiplied or divided by this stepwise factor upon
459
+ each update. Range is (0, 1). Default is 0.9.
460
+
461
+ .. versionadded:: 1.8.0
462
+
463
+ Returns
464
+ -------
465
+ res : OptimizeResult
466
+ The optimization result represented as a `OptimizeResult` object.
467
+ Important attributes are: ``x`` the solution array, ``fun`` the value
468
+ of the function at the solution, and ``message`` which describes the
469
+ cause of the termination. The ``OptimizeResult`` object returned by the
470
+ selected minimizer at the lowest minimum is also contained within this
471
+ object and can be accessed through the ``lowest_optimization_result``
472
+ attribute. See `OptimizeResult` for a description of other attributes.
473
+
474
+ See Also
475
+ --------
476
+ minimize :
477
+ The local minimization function called once for each basinhopping step.
478
+ `minimizer_kwargs` is passed to this routine.
479
+
480
+ Notes
481
+ -----
482
+ Basin-hopping is a stochastic algorithm which attempts to find the global
483
+ minimum of a smooth scalar function of one or more variables [1]_ [2]_ [3]_
484
+ [4]_. The algorithm in its current form was described by David Wales and
485
+ Jonathan Doye [2]_ http://www-wales.ch.cam.ac.uk/.
486
+
487
+ The algorithm is iterative with each cycle composed of the following
488
+ features
489
+
490
+ 1) random perturbation of the coordinates
491
+
492
+ 2) local minimization
493
+
494
+ 3) accept or reject the new coordinates based on the minimized function
495
+ value
496
+
497
+ The acceptance test used here is the Metropolis criterion of standard Monte
498
+ Carlo algorithms, although there are many other possibilities [3]_.
499
+
500
+ This global minimization method has been shown to be extremely efficient
501
+ for a wide variety of problems in physics and chemistry. It is
502
+ particularly useful when the function has many minima separated by large
503
+ barriers. See the `Cambridge Cluster Database
504
+ <https://www-wales.ch.cam.ac.uk/CCD.html>`_ for databases of molecular
505
+ systems that have been optimized primarily using basin-hopping. This
506
+ database includes minimization problems exceeding 300 degrees of freedom.
507
+
508
+ See the free software program `GMIN <https://www-wales.ch.cam.ac.uk/GMIN>`_
509
+ for a Fortran implementation of basin-hopping. This implementation has many
510
+ variations of the procedure described above, including more
511
+ advanced step taking algorithms and alternate acceptance criterion.
512
+
513
+ For stochastic global optimization there is no way to determine if the true
514
+ global minimum has actually been found. Instead, as a consistency check,
515
+ the algorithm can be run from a number of different random starting points
516
+ to ensure the lowest minimum found in each example has converged to the
517
+ global minimum. For this reason, `basinhopping` will by default simply
518
+ run for the number of iterations `niter` and return the lowest minimum
519
+ found. It is left to the user to ensure that this is in fact the global
520
+ minimum.
521
+
522
+ Choosing `stepsize`: This is a crucial parameter in `basinhopping` and
523
+ depends on the problem being solved. The step is chosen uniformly in the
524
+ region from x0-stepsize to x0+stepsize, in each dimension. Ideally, it
525
+ should be comparable to the typical separation (in argument values) between
526
+ local minima of the function being optimized. `basinhopping` will, by
527
+ default, adjust `stepsize` to find an optimal value, but this may take
528
+ many iterations. You will get quicker results if you set a sensible
529
+ initial value for ``stepsize``.
530
+
531
+ Choosing `T`: The parameter `T` is the "temperature" used in the
532
+ Metropolis criterion. Basinhopping steps are always accepted if
533
+ ``func(xnew) < func(xold)``. Otherwise, they are accepted with
534
+ probability::
535
+
536
+ exp( -(func(xnew) - func(xold)) / T )
537
+
538
+ So, for best results, `T` should to be comparable to the typical
539
+ difference (in function values) between local minima. (The height of
540
+ "walls" between local minima is irrelevant.)
541
+
542
+ If `T` is 0, the algorithm becomes Monotonic Basin-Hopping, in which all
543
+ steps that increase energy are rejected.
544
+
545
+ .. versionadded:: 0.12.0
546
+
547
+ References
548
+ ----------
549
+ .. [1] Wales, David J. 2003, Energy Landscapes, Cambridge University Press,
550
+ Cambridge, UK.
551
+ .. [2] Wales, D J, and Doye J P K, Global Optimization by Basin-Hopping and
552
+ the Lowest Energy Structures of Lennard-Jones Clusters Containing up to
553
+ 110 Atoms. Journal of Physical Chemistry A, 1997, 101, 5111.
554
+ .. [3] Li, Z. and Scheraga, H. A., Monte Carlo-minimization approach to the
555
+ multiple-minima problem in protein folding, Proc. Natl. Acad. Sci. USA,
556
+ 1987, 84, 6611.
557
+ .. [4] Wales, D. J. and Scheraga, H. A., Global optimization of clusters,
558
+ crystals, and biomolecules, Science, 1999, 285, 1368.
559
+ .. [5] Olson, B., Hashmi, I., Molloy, K., and Shehu1, A., Basin Hopping as
560
+ a General and Versatile Optimization Framework for the Characterization
561
+ of Biological Macromolecules, Advances in Artificial Intelligence,
562
+ Volume 2012 (2012), Article ID 674832, :doi:`10.1155/2012/674832`
563
+
564
+ Examples
565
+ --------
566
+ The following example is a 1-D minimization problem, with many
567
+ local minima superimposed on a parabola.
568
+
569
+ >>> import numpy as np
570
+ >>> from scipy.optimize import basinhopping
571
+ >>> func = lambda x: np.cos(14.5 * x - 0.3) + (x + 0.2) * x
572
+ >>> x0 = [1.]
573
+
574
+ Basinhopping, internally, uses a local minimization algorithm. We will use
575
+ the parameter `minimizer_kwargs` to tell basinhopping which algorithm to
576
+ use and how to set up that minimizer. This parameter will be passed to
577
+ `scipy.optimize.minimize`.
578
+
579
+ >>> minimizer_kwargs = {"method": "BFGS"}
580
+ >>> ret = basinhopping(func, x0, minimizer_kwargs=minimizer_kwargs,
581
+ ... niter=200)
582
+ >>> # the global minimum is:
583
+ >>> ret.x, ret.fun
584
+ -0.1951, -1.0009
585
+
586
+ Next consider a 2-D minimization problem. Also, this time, we
587
+ will use gradient information to significantly speed up the search.
588
+
589
+ >>> def func2d(x):
590
+ ... f = np.cos(14.5 * x[0] - 0.3) + (x[1] + 0.2) * x[1] + (x[0] +
591
+ ... 0.2) * x[0]
592
+ ... df = np.zeros(2)
593
+ ... df[0] = -14.5 * np.sin(14.5 * x[0] - 0.3) + 2. * x[0] + 0.2
594
+ ... df[1] = 2. * x[1] + 0.2
595
+ ... return f, df
596
+
597
+ We'll also use a different local minimization algorithm. Also, we must tell
598
+ the minimizer that our function returns both energy and gradient (Jacobian).
599
+
600
+ >>> minimizer_kwargs = {"method":"L-BFGS-B", "jac":True}
601
+ >>> x0 = [1.0, 1.0]
602
+ >>> ret = basinhopping(func2d, x0, minimizer_kwargs=minimizer_kwargs,
603
+ ... niter=200)
604
+ >>> print("global minimum: x = [%.4f, %.4f], f(x) = %.4f" % (ret.x[0],
605
+ ... ret.x[1],
606
+ ... ret.fun))
607
+ global minimum: x = [-0.1951, -0.1000], f(x) = -1.0109
608
+
609
+ Here is an example using a custom step-taking routine. Imagine you want
610
+ the first coordinate to take larger steps than the rest of the coordinates.
611
+ This can be implemented like so:
612
+
613
+ >>> class MyTakeStep:
614
+ ... def __init__(self, stepsize=0.5):
615
+ ... self.stepsize = stepsize
616
+ ... self.rng = np.random.default_rng()
617
+ ... def __call__(self, x):
618
+ ... s = self.stepsize
619
+ ... x[0] += self.rng.uniform(-2.*s, 2.*s)
620
+ ... x[1:] += self.rng.uniform(-s, s, x[1:].shape)
621
+ ... return x
622
+
623
+ Since ``MyTakeStep.stepsize`` exists basinhopping will adjust the magnitude
624
+ of `stepsize` to optimize the search. We'll use the same 2-D function as
625
+ before
626
+
627
+ >>> mytakestep = MyTakeStep()
628
+ >>> ret = basinhopping(func2d, x0, minimizer_kwargs=minimizer_kwargs,
629
+ ... niter=200, take_step=mytakestep)
630
+ >>> print("global minimum: x = [%.4f, %.4f], f(x) = %.4f" % (ret.x[0],
631
+ ... ret.x[1],
632
+ ... ret.fun))
633
+ global minimum: x = [-0.1951, -0.1000], f(x) = -1.0109
634
+
635
+ Now, let's do an example using a custom callback function which prints the
636
+ value of every minimum found
637
+
638
+ >>> def print_fun(x, f, accepted):
639
+ ... print("at minimum %.4f accepted %d" % (f, int(accepted)))
640
+
641
+ We'll run it for only 10 basinhopping steps this time.
642
+
643
+ >>> rng = np.random.default_rng()
644
+ >>> ret = basinhopping(func2d, x0, minimizer_kwargs=minimizer_kwargs,
645
+ ... niter=10, callback=print_fun, seed=rng)
646
+ at minimum 0.4159 accepted 1
647
+ at minimum -0.4317 accepted 1
648
+ at minimum -1.0109 accepted 1
649
+ at minimum -0.9073 accepted 1
650
+ at minimum -0.4317 accepted 0
651
+ at minimum -0.1021 accepted 1
652
+ at minimum -0.7425 accepted 1
653
+ at minimum -0.9073 accepted 1
654
+ at minimum -0.4317 accepted 0
655
+ at minimum -0.7425 accepted 1
656
+ at minimum -0.9073 accepted 1
657
+
658
+ The minimum at -1.0109 is actually the global minimum, found already on the
659
+ 8th iteration.
660
+
661
+ """ # numpy/numpydoc#87 # noqa: E501
662
+ if target_accept_rate <= 0. or target_accept_rate >= 1.:
663
+ raise ValueError('target_accept_rate has to be in range (0, 1)')
664
+ if stepwise_factor <= 0. or stepwise_factor >= 1.:
665
+ raise ValueError('stepwise_factor has to be in range (0, 1)')
666
+
667
+ x0 = np.array(x0)
668
+
669
+ # set up the np.random generator
670
+ rng = check_random_state(seed)
671
+
672
+ # set up minimizer
673
+ if minimizer_kwargs is None:
674
+ minimizer_kwargs = dict()
675
+ wrapped_minimizer = MinimizerWrapper(scipy.optimize.minimize, func,
676
+ **minimizer_kwargs)
677
+
678
+ # set up step-taking algorithm
679
+ if take_step is not None:
680
+ if not callable(take_step):
681
+ raise TypeError("take_step must be callable")
682
+ # if take_step.stepsize exists then use AdaptiveStepsize to control
683
+ # take_step.stepsize
684
+ if hasattr(take_step, "stepsize"):
685
+ take_step_wrapped = AdaptiveStepsize(
686
+ take_step, interval=interval,
687
+ accept_rate=target_accept_rate,
688
+ factor=stepwise_factor,
689
+ verbose=disp)
690
+ else:
691
+ take_step_wrapped = take_step
692
+ else:
693
+ # use default
694
+ displace = RandomDisplacement(stepsize=stepsize, random_gen=rng)
695
+ take_step_wrapped = AdaptiveStepsize(displace, interval=interval,
696
+ accept_rate=target_accept_rate,
697
+ factor=stepwise_factor,
698
+ verbose=disp)
699
+
700
+ # set up accept tests
701
+ accept_tests = []
702
+ if accept_test is not None:
703
+ if not callable(accept_test):
704
+ raise TypeError("accept_test must be callable")
705
+ accept_tests = [accept_test]
706
+
707
+ # use default
708
+ metropolis = Metropolis(T, random_gen=rng)
709
+ accept_tests.append(metropolis)
710
+
711
+ if niter_success is None:
712
+ niter_success = niter + 2
713
+
714
+ bh = BasinHoppingRunner(x0, wrapped_minimizer, take_step_wrapped,
715
+ accept_tests, disp=disp)
716
+
717
+ # The wrapped minimizer is called once during construction of
718
+ # BasinHoppingRunner, so run the callback
719
+ if callable(callback):
720
+ callback(bh.storage.minres.x, bh.storage.minres.fun, True)
721
+
722
+ # start main iteration loop
723
+ count, i = 0, 0
724
+ message = ["requested number of basinhopping iterations completed"
725
+ " successfully"]
726
+ for i in range(niter):
727
+ new_global_min = bh.one_cycle()
728
+
729
+ if callable(callback):
730
+ # should we pass a copy of x?
731
+ val = callback(bh.xtrial, bh.energy_trial, bh.accept)
732
+ if val is not None:
733
+ if val:
734
+ message = ["callback function requested stop early by"
735
+ "returning True"]
736
+ break
737
+
738
+ count += 1
739
+ if new_global_min:
740
+ count = 0
741
+ elif count > niter_success:
742
+ message = ["success condition satisfied"]
743
+ break
744
+
745
+ # prepare return object
746
+ res = bh.res
747
+ res.lowest_optimization_result = bh.storage.get_lowest()
748
+ res.x = np.copy(res.lowest_optimization_result.x)
749
+ res.fun = res.lowest_optimization_result.fun
750
+ res.message = message
751
+ res.nit = i + 1
752
+ res.success = res.lowest_optimization_result.success
753
+ return res
vila/lib/python3.10/site-packages/scipy/optimize/_bglu_dense.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c45eca1a2737717c4e47975adcd7b7c1c1d02e98dba7d5103eea7e67787a6fea
3
+ size 364392
vila/lib/python3.10/site-packages/scipy/optimize/_cobyqa_py.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from ._optimize import _check_unknown_options
4
+
5
+
6
+ def _minimize_cobyqa(fun, x0, args=(), bounds=None, constraints=(),
7
+ callback=None, disp=False, maxfev=None, maxiter=None,
8
+ f_target=-np.inf, feasibility_tol=1e-8,
9
+ initial_tr_radius=1.0, final_tr_radius=1e-6, scale=False,
10
+ **unknown_options):
11
+ """
12
+ Minimize a scalar function of one or more variables using the
13
+ Constrained Optimization BY Quadratic Approximations (COBYQA) algorithm [1]_.
14
+
15
+ .. versionadded:: 1.14.0
16
+
17
+ Options
18
+ -------
19
+ disp : bool
20
+ Set to True to print information about the optimization procedure.
21
+ maxfev : int
22
+ Maximum number of function evaluations.
23
+ maxiter : int
24
+ Maximum number of iterations.
25
+ f_target : float
26
+ Target value for the objective function. The optimization procedure is
27
+ terminated when the objective function value of a feasible point (see
28
+ `feasibility_tol` below) is less than or equal to this target.
29
+ feasibility_tol : float
30
+ Absolute tolerance for the constraint violation.
31
+ initial_tr_radius : float
32
+ Initial trust-region radius. Typically, this value should be in the
33
+ order of one tenth of the greatest expected change to the variables.
34
+ final_tr_radius : float
35
+ Final trust-region radius. It should indicate the accuracy required in
36
+ the final values of the variables. If provided, this option overrides
37
+ the value of `tol` in the `minimize` function.
38
+ scale : bool
39
+ Set to True to scale the variables according to the bounds. If True and
40
+ if all the lower and upper bounds are finite, the variables are scaled
41
+ to be within the range :math:`[-1, 1]`. If any of the lower or upper
42
+ bounds is infinite, the variables are not scaled.
43
+
44
+ References
45
+ ----------
46
+ .. [1] COBYQA
47
+ https://www.cobyqa.com/stable/
48
+ """
49
+ from .._lib.cobyqa import minimize # import here to avoid circular imports
50
+
51
+ _check_unknown_options(unknown_options)
52
+ options = {
53
+ 'disp': bool(disp),
54
+ 'maxfev': int(maxfev) if maxfev is not None else 500 * len(x0),
55
+ 'maxiter': int(maxiter) if maxiter is not None else 1000 * len(x0),
56
+ 'target': float(f_target),
57
+ 'feasibility_tol': float(feasibility_tol),
58
+ 'radius_init': float(initial_tr_radius),
59
+ 'radius_final': float(final_tr_radius),
60
+ 'scale': bool(scale),
61
+ }
62
+ return minimize(fun, x0, args, bounds, constraints, callback, options)
vila/lib/python3.10/site-packages/scipy/optimize/_constraints.py ADDED
@@ -0,0 +1,590 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Constraints definition for minimize."""
2
+ import numpy as np
3
+ from ._hessian_update_strategy import BFGS
4
+ from ._differentiable_functions import (
5
+ VectorFunction, LinearVectorFunction, IdentityVectorFunction)
6
+ from ._optimize import OptimizeWarning
7
+ from warnings import warn, catch_warnings, simplefilter, filterwarnings
8
+ from scipy.sparse import issparse
9
+
10
+
11
+ def _arr_to_scalar(x):
12
+ # If x is a numpy array, return x.item(). This will
13
+ # fail if the array has more than one element.
14
+ return x.item() if isinstance(x, np.ndarray) else x
15
+
16
+
17
+ class NonlinearConstraint:
18
+ """Nonlinear constraint on the variables.
19
+
20
+ The constraint has the general inequality form::
21
+
22
+ lb <= fun(x) <= ub
23
+
24
+ Here the vector of independent variables x is passed as ndarray of shape
25
+ (n,) and ``fun`` returns a vector with m components.
26
+
27
+ It is possible to use equal bounds to represent an equality constraint or
28
+ infinite bounds to represent a one-sided constraint.
29
+
30
+ Parameters
31
+ ----------
32
+ fun : callable
33
+ The function defining the constraint.
34
+ The signature is ``fun(x) -> array_like, shape (m,)``.
35
+ lb, ub : array_like
36
+ Lower and upper bounds on the constraint. Each array must have the
37
+ shape (m,) or be a scalar, in the latter case a bound will be the same
38
+ for all components of the constraint. Use ``np.inf`` with an
39
+ appropriate sign to specify a one-sided constraint.
40
+ Set components of `lb` and `ub` equal to represent an equality
41
+ constraint. Note that you can mix constraints of different types:
42
+ interval, one-sided or equality, by setting different components of
43
+ `lb` and `ub` as necessary.
44
+ jac : {callable, '2-point', '3-point', 'cs'}, optional
45
+ Method of computing the Jacobian matrix (an m-by-n matrix,
46
+ where element (i, j) is the partial derivative of f[i] with
47
+ respect to x[j]). The keywords {'2-point', '3-point',
48
+ 'cs'} select a finite difference scheme for the numerical estimation.
49
+ A callable must have the following signature:
50
+ ``jac(x) -> {ndarray, sparse matrix}, shape (m, n)``.
51
+ Default is '2-point'.
52
+ hess : {callable, '2-point', '3-point', 'cs', HessianUpdateStrategy, None}, optional
53
+ Method for computing the Hessian matrix. The keywords
54
+ {'2-point', '3-point', 'cs'} select a finite difference scheme for
55
+ numerical estimation. Alternatively, objects implementing
56
+ `HessianUpdateStrategy` interface can be used to approximate the
57
+ Hessian. Currently available implementations are:
58
+
59
+ - `BFGS` (default option)
60
+ - `SR1`
61
+
62
+ A callable must return the Hessian matrix of ``dot(fun, v)`` and
63
+ must have the following signature:
64
+ ``hess(x, v) -> {LinearOperator, sparse matrix, array_like}, shape (n, n)``.
65
+ Here ``v`` is ndarray with shape (m,) containing Lagrange multipliers.
66
+ keep_feasible : array_like of bool, optional
67
+ Whether to keep the constraint components feasible throughout
68
+ iterations. A single value set this property for all components.
69
+ Default is False. Has no effect for equality constraints.
70
+ finite_diff_rel_step: None or array_like, optional
71
+ Relative step size for the finite difference approximation. Default is
72
+ None, which will select a reasonable value automatically depending
73
+ on a finite difference scheme.
74
+ finite_diff_jac_sparsity: {None, array_like, sparse matrix}, optional
75
+ Defines the sparsity structure of the Jacobian matrix for finite
76
+ difference estimation, its shape must be (m, n). If the Jacobian has
77
+ only few non-zero elements in *each* row, providing the sparsity
78
+ structure will greatly speed up the computations. A zero entry means
79
+ that a corresponding element in the Jacobian is identically zero.
80
+ If provided, forces the use of 'lsmr' trust-region solver.
81
+ If None (default) then dense differencing will be used.
82
+
83
+ Notes
84
+ -----
85
+ Finite difference schemes {'2-point', '3-point', 'cs'} may be used for
86
+ approximating either the Jacobian or the Hessian. We, however, do not allow
87
+ its use for approximating both simultaneously. Hence whenever the Jacobian
88
+ is estimated via finite-differences, we require the Hessian to be estimated
89
+ using one of the quasi-Newton strategies.
90
+
91
+ The scheme 'cs' is potentially the most accurate, but requires the function
92
+ to correctly handles complex inputs and be analytically continuable to the
93
+ complex plane. The scheme '3-point' is more accurate than '2-point' but
94
+ requires twice as many operations.
95
+
96
+ Examples
97
+ --------
98
+ Constrain ``x[0] < sin(x[1]) + 1.9``
99
+
100
+ >>> from scipy.optimize import NonlinearConstraint
101
+ >>> import numpy as np
102
+ >>> con = lambda x: x[0] - np.sin(x[1])
103
+ >>> nlc = NonlinearConstraint(con, -np.inf, 1.9)
104
+
105
+ """
106
+ def __init__(self, fun, lb, ub, jac='2-point', hess=BFGS(),
107
+ keep_feasible=False, finite_diff_rel_step=None,
108
+ finite_diff_jac_sparsity=None):
109
+ self.fun = fun
110
+ self.lb = lb
111
+ self.ub = ub
112
+ self.finite_diff_rel_step = finite_diff_rel_step
113
+ self.finite_diff_jac_sparsity = finite_diff_jac_sparsity
114
+ self.jac = jac
115
+ self.hess = hess
116
+ self.keep_feasible = keep_feasible
117
+
118
+
119
+ class LinearConstraint:
120
+ """Linear constraint on the variables.
121
+
122
+ The constraint has the general inequality form::
123
+
124
+ lb <= A.dot(x) <= ub
125
+
126
+ Here the vector of independent variables x is passed as ndarray of shape
127
+ (n,) and the matrix A has shape (m, n).
128
+
129
+ It is possible to use equal bounds to represent an equality constraint or
130
+ infinite bounds to represent a one-sided constraint.
131
+
132
+ Parameters
133
+ ----------
134
+ A : {array_like, sparse matrix}, shape (m, n)
135
+ Matrix defining the constraint.
136
+ lb, ub : dense array_like, optional
137
+ Lower and upper limits on the constraint. Each array must have the
138
+ shape (m,) or be a scalar, in the latter case a bound will be the same
139
+ for all components of the constraint. Use ``np.inf`` with an
140
+ appropriate sign to specify a one-sided constraint.
141
+ Set components of `lb` and `ub` equal to represent an equality
142
+ constraint. Note that you can mix constraints of different types:
143
+ interval, one-sided or equality, by setting different components of
144
+ `lb` and `ub` as necessary. Defaults to ``lb = -np.inf``
145
+ and ``ub = np.inf`` (no limits).
146
+ keep_feasible : dense array_like of bool, optional
147
+ Whether to keep the constraint components feasible throughout
148
+ iterations. A single value set this property for all components.
149
+ Default is False. Has no effect for equality constraints.
150
+ """
151
+ def _input_validation(self):
152
+ if self.A.ndim != 2:
153
+ message = "`A` must have exactly two dimensions."
154
+ raise ValueError(message)
155
+
156
+ try:
157
+ shape = self.A.shape[0:1]
158
+ self.lb = np.broadcast_to(self.lb, shape)
159
+ self.ub = np.broadcast_to(self.ub, shape)
160
+ self.keep_feasible = np.broadcast_to(self.keep_feasible, shape)
161
+ except ValueError:
162
+ message = ("`lb`, `ub`, and `keep_feasible` must be broadcastable "
163
+ "to shape `A.shape[0:1]`")
164
+ raise ValueError(message)
165
+
166
+ def __init__(self, A, lb=-np.inf, ub=np.inf, keep_feasible=False):
167
+ if not issparse(A):
168
+ # In some cases, if the constraint is not valid, this emits a
169
+ # VisibleDeprecationWarning about ragged nested sequences
170
+ # before eventually causing an error. `scipy.optimize.milp` would
171
+ # prefer that this just error out immediately so it can handle it
172
+ # rather than concerning the user.
173
+ with catch_warnings():
174
+ simplefilter("error")
175
+ self.A = np.atleast_2d(A).astype(np.float64)
176
+ else:
177
+ self.A = A
178
+ if issparse(lb) or issparse(ub):
179
+ raise ValueError("Constraint limits must be dense arrays.")
180
+ self.lb = np.atleast_1d(lb).astype(np.float64)
181
+ self.ub = np.atleast_1d(ub).astype(np.float64)
182
+
183
+ if issparse(keep_feasible):
184
+ raise ValueError("`keep_feasible` must be a dense array.")
185
+ self.keep_feasible = np.atleast_1d(keep_feasible).astype(bool)
186
+ self._input_validation()
187
+
188
+ def residual(self, x):
189
+ """
190
+ Calculate the residual between the constraint function and the limits
191
+
192
+ For a linear constraint of the form::
193
+
194
+ lb <= A@x <= ub
195
+
196
+ the lower and upper residuals between ``A@x`` and the limits are values
197
+ ``sl`` and ``sb`` such that::
198
+
199
+ lb + sl == A@x == ub - sb
200
+
201
+ When all elements of ``sl`` and ``sb`` are positive, all elements of
202
+ the constraint are satisfied; a negative element in ``sl`` or ``sb``
203
+ indicates that the corresponding element of the constraint is not
204
+ satisfied.
205
+
206
+ Parameters
207
+ ----------
208
+ x: array_like
209
+ Vector of independent variables
210
+
211
+ Returns
212
+ -------
213
+ sl, sb : array-like
214
+ The lower and upper residuals
215
+ """
216
+ return self.A@x - self.lb, self.ub - self.A@x
217
+
218
+
219
+ class Bounds:
220
+ """Bounds constraint on the variables.
221
+
222
+ The constraint has the general inequality form::
223
+
224
+ lb <= x <= ub
225
+
226
+ It is possible to use equal bounds to represent an equality constraint or
227
+ infinite bounds to represent a one-sided constraint.
228
+
229
+ Parameters
230
+ ----------
231
+ lb, ub : dense array_like, optional
232
+ Lower and upper bounds on independent variables. `lb`, `ub`, and
233
+ `keep_feasible` must be the same shape or broadcastable.
234
+ Set components of `lb` and `ub` equal
235
+ to fix a variable. Use ``np.inf`` with an appropriate sign to disable
236
+ bounds on all or some variables. Note that you can mix constraints of
237
+ different types: interval, one-sided or equality, by setting different
238
+ components of `lb` and `ub` as necessary. Defaults to ``lb = -np.inf``
239
+ and ``ub = np.inf`` (no bounds).
240
+ keep_feasible : dense array_like of bool, optional
241
+ Whether to keep the constraint components feasible throughout
242
+ iterations. Must be broadcastable with `lb` and `ub`.
243
+ Default is False. Has no effect for equality constraints.
244
+ """
245
+ def _input_validation(self):
246
+ try:
247
+ res = np.broadcast_arrays(self.lb, self.ub, self.keep_feasible)
248
+ self.lb, self.ub, self.keep_feasible = res
249
+ except ValueError:
250
+ message = "`lb`, `ub`, and `keep_feasible` must be broadcastable."
251
+ raise ValueError(message)
252
+
253
+ def __init__(self, lb=-np.inf, ub=np.inf, keep_feasible=False):
254
+ if issparse(lb) or issparse(ub):
255
+ raise ValueError("Lower and upper bounds must be dense arrays.")
256
+ self.lb = np.atleast_1d(lb)
257
+ self.ub = np.atleast_1d(ub)
258
+
259
+ if issparse(keep_feasible):
260
+ raise ValueError("`keep_feasible` must be a dense array.")
261
+ self.keep_feasible = np.atleast_1d(keep_feasible).astype(bool)
262
+ self._input_validation()
263
+
264
+ def __repr__(self):
265
+ start = f"{type(self).__name__}({self.lb!r}, {self.ub!r}"
266
+ if np.any(self.keep_feasible):
267
+ end = f", keep_feasible={self.keep_feasible!r})"
268
+ else:
269
+ end = ")"
270
+ return start + end
271
+
272
+ def residual(self, x):
273
+ """Calculate the residual (slack) between the input and the bounds
274
+
275
+ For a bound constraint of the form::
276
+
277
+ lb <= x <= ub
278
+
279
+ the lower and upper residuals between `x` and the bounds are values
280
+ ``sl`` and ``sb`` such that::
281
+
282
+ lb + sl == x == ub - sb
283
+
284
+ When all elements of ``sl`` and ``sb`` are positive, all elements of
285
+ ``x`` lie within the bounds; a negative element in ``sl`` or ``sb``
286
+ indicates that the corresponding element of ``x`` is out of bounds.
287
+
288
+ Parameters
289
+ ----------
290
+ x: array_like
291
+ Vector of independent variables
292
+
293
+ Returns
294
+ -------
295
+ sl, sb : array-like
296
+ The lower and upper residuals
297
+ """
298
+ return x - self.lb, self.ub - x
299
+
300
+
301
+ class PreparedConstraint:
302
+ """Constraint prepared from a user defined constraint.
303
+
304
+ On creation it will check whether a constraint definition is valid and
305
+ the initial point is feasible. If created successfully, it will contain
306
+ the attributes listed below.
307
+
308
+ Parameters
309
+ ----------
310
+ constraint : {NonlinearConstraint, LinearConstraint`, Bounds}
311
+ Constraint to check and prepare.
312
+ x0 : array_like
313
+ Initial vector of independent variables.
314
+ sparse_jacobian : bool or None, optional
315
+ If bool, then the Jacobian of the constraint will be converted
316
+ to the corresponded format if necessary. If None (default), such
317
+ conversion is not made.
318
+ finite_diff_bounds : 2-tuple, optional
319
+ Lower and upper bounds on the independent variables for the finite
320
+ difference approximation, if applicable. Defaults to no bounds.
321
+
322
+ Attributes
323
+ ----------
324
+ fun : {VectorFunction, LinearVectorFunction, IdentityVectorFunction}
325
+ Function defining the constraint wrapped by one of the convenience
326
+ classes.
327
+ bounds : 2-tuple
328
+ Contains lower and upper bounds for the constraints --- lb and ub.
329
+ These are converted to ndarray and have a size equal to the number of
330
+ the constraints.
331
+ keep_feasible : ndarray
332
+ Array indicating which components must be kept feasible with a size
333
+ equal to the number of the constraints.
334
+ """
335
+ def __init__(self, constraint, x0, sparse_jacobian=None,
336
+ finite_diff_bounds=(-np.inf, np.inf)):
337
+ if isinstance(constraint, NonlinearConstraint):
338
+ fun = VectorFunction(constraint.fun, x0,
339
+ constraint.jac, constraint.hess,
340
+ constraint.finite_diff_rel_step,
341
+ constraint.finite_diff_jac_sparsity,
342
+ finite_diff_bounds, sparse_jacobian)
343
+ elif isinstance(constraint, LinearConstraint):
344
+ fun = LinearVectorFunction(constraint.A, x0, sparse_jacobian)
345
+ elif isinstance(constraint, Bounds):
346
+ fun = IdentityVectorFunction(x0, sparse_jacobian)
347
+ else:
348
+ raise ValueError("`constraint` of an unknown type is passed.")
349
+
350
+ m = fun.m
351
+
352
+ lb = np.asarray(constraint.lb, dtype=float)
353
+ ub = np.asarray(constraint.ub, dtype=float)
354
+ keep_feasible = np.asarray(constraint.keep_feasible, dtype=bool)
355
+
356
+ lb = np.broadcast_to(lb, m)
357
+ ub = np.broadcast_to(ub, m)
358
+ keep_feasible = np.broadcast_to(keep_feasible, m)
359
+
360
+ if keep_feasible.shape != (m,):
361
+ raise ValueError("`keep_feasible` has a wrong shape.")
362
+
363
+ mask = keep_feasible & (lb != ub)
364
+ f0 = fun.f
365
+ if np.any(f0[mask] < lb[mask]) or np.any(f0[mask] > ub[mask]):
366
+ raise ValueError("`x0` is infeasible with respect to some "
367
+ "inequality constraint with `keep_feasible` "
368
+ "set to True.")
369
+
370
+ self.fun = fun
371
+ self.bounds = (lb, ub)
372
+ self.keep_feasible = keep_feasible
373
+
374
+ def violation(self, x):
375
+ """How much the constraint is exceeded by.
376
+
377
+ Parameters
378
+ ----------
379
+ x : array-like
380
+ Vector of independent variables
381
+
382
+ Returns
383
+ -------
384
+ excess : array-like
385
+ How much the constraint is exceeded by, for each of the
386
+ constraints specified by `PreparedConstraint.fun`.
387
+ """
388
+ with catch_warnings():
389
+ # Ignore the following warning, it's not important when
390
+ # figuring out total violation
391
+ # UserWarning: delta_grad == 0.0. Check if the approximated
392
+ # function is linear
393
+ filterwarnings("ignore", "delta_grad", UserWarning)
394
+ ev = self.fun.fun(np.asarray(x))
395
+
396
+ excess_lb = np.maximum(self.bounds[0] - ev, 0)
397
+ excess_ub = np.maximum(ev - self.bounds[1], 0)
398
+
399
+ return excess_lb + excess_ub
400
+
401
+
402
+ def new_bounds_to_old(lb, ub, n):
403
+ """Convert the new bounds representation to the old one.
404
+
405
+ The new representation is a tuple (lb, ub) and the old one is a list
406
+ containing n tuples, ith containing lower and upper bound on a ith
407
+ variable.
408
+ If any of the entries in lb/ub are -np.inf/np.inf they are replaced by
409
+ None.
410
+ """
411
+ lb = np.broadcast_to(lb, n)
412
+ ub = np.broadcast_to(ub, n)
413
+
414
+ lb = [float(x) if x > -np.inf else None for x in lb]
415
+ ub = [float(x) if x < np.inf else None for x in ub]
416
+
417
+ return list(zip(lb, ub))
418
+
419
+
420
+ def old_bound_to_new(bounds):
421
+ """Convert the old bounds representation to the new one.
422
+
423
+ The new representation is a tuple (lb, ub) and the old one is a list
424
+ containing n tuples, ith containing lower and upper bound on a ith
425
+ variable.
426
+ If any of the entries in lb/ub are None they are replaced by
427
+ -np.inf/np.inf.
428
+ """
429
+ lb, ub = zip(*bounds)
430
+
431
+ # Convert occurrences of None to -inf or inf, and replace occurrences of
432
+ # any numpy array x with x.item(). Then wrap the results in numpy arrays.
433
+ lb = np.array([float(_arr_to_scalar(x)) if x is not None else -np.inf
434
+ for x in lb])
435
+ ub = np.array([float(_arr_to_scalar(x)) if x is not None else np.inf
436
+ for x in ub])
437
+
438
+ return lb, ub
439
+
440
+
441
+ def strict_bounds(lb, ub, keep_feasible, n_vars):
442
+ """Remove bounds which are not asked to be kept feasible."""
443
+ strict_lb = np.resize(lb, n_vars).astype(float)
444
+ strict_ub = np.resize(ub, n_vars).astype(float)
445
+ keep_feasible = np.resize(keep_feasible, n_vars)
446
+ strict_lb[~keep_feasible] = -np.inf
447
+ strict_ub[~keep_feasible] = np.inf
448
+ return strict_lb, strict_ub
449
+
450
+
451
+ def new_constraint_to_old(con, x0):
452
+ """
453
+ Converts new-style constraint objects to old-style constraint dictionaries.
454
+ """
455
+ if isinstance(con, NonlinearConstraint):
456
+ if (con.finite_diff_jac_sparsity is not None or
457
+ con.finite_diff_rel_step is not None or
458
+ not isinstance(con.hess, BFGS) or # misses user specified BFGS
459
+ con.keep_feasible):
460
+ warn("Constraint options `finite_diff_jac_sparsity`, "
461
+ "`finite_diff_rel_step`, `keep_feasible`, and `hess`"
462
+ "are ignored by this method.",
463
+ OptimizeWarning, stacklevel=3)
464
+
465
+ fun = con.fun
466
+ if callable(con.jac):
467
+ jac = con.jac
468
+ else:
469
+ jac = None
470
+
471
+ else: # LinearConstraint
472
+ if np.any(con.keep_feasible):
473
+ warn("Constraint option `keep_feasible` is ignored by this method.",
474
+ OptimizeWarning, stacklevel=3)
475
+
476
+ A = con.A
477
+ if issparse(A):
478
+ A = A.toarray()
479
+ def fun(x):
480
+ return np.dot(A, x)
481
+ def jac(x):
482
+ return A
483
+
484
+ # FIXME: when bugs in VectorFunction/LinearVectorFunction are worked out,
485
+ # use pcon.fun.fun and pcon.fun.jac. Until then, get fun/jac above.
486
+ pcon = PreparedConstraint(con, x0)
487
+ lb, ub = pcon.bounds
488
+
489
+ i_eq = lb == ub
490
+ i_bound_below = np.logical_xor(lb != -np.inf, i_eq)
491
+ i_bound_above = np.logical_xor(ub != np.inf, i_eq)
492
+ i_unbounded = np.logical_and(lb == -np.inf, ub == np.inf)
493
+
494
+ if np.any(i_unbounded):
495
+ warn("At least one constraint is unbounded above and below. Such "
496
+ "constraints are ignored.",
497
+ OptimizeWarning, stacklevel=3)
498
+
499
+ ceq = []
500
+ if np.any(i_eq):
501
+ def f_eq(x):
502
+ y = np.array(fun(x)).flatten()
503
+ return y[i_eq] - lb[i_eq]
504
+ ceq = [{"type": "eq", "fun": f_eq}]
505
+
506
+ if jac is not None:
507
+ def j_eq(x):
508
+ dy = jac(x)
509
+ if issparse(dy):
510
+ dy = dy.toarray()
511
+ dy = np.atleast_2d(dy)
512
+ return dy[i_eq, :]
513
+ ceq[0]["jac"] = j_eq
514
+
515
+ cineq = []
516
+ n_bound_below = np.sum(i_bound_below)
517
+ n_bound_above = np.sum(i_bound_above)
518
+ if n_bound_below + n_bound_above:
519
+ def f_ineq(x):
520
+ y = np.zeros(n_bound_below + n_bound_above)
521
+ y_all = np.array(fun(x)).flatten()
522
+ y[:n_bound_below] = y_all[i_bound_below] - lb[i_bound_below]
523
+ y[n_bound_below:] = -(y_all[i_bound_above] - ub[i_bound_above])
524
+ return y
525
+ cineq = [{"type": "ineq", "fun": f_ineq}]
526
+
527
+ if jac is not None:
528
+ def j_ineq(x):
529
+ dy = np.zeros((n_bound_below + n_bound_above, len(x0)))
530
+ dy_all = jac(x)
531
+ if issparse(dy_all):
532
+ dy_all = dy_all.toarray()
533
+ dy_all = np.atleast_2d(dy_all)
534
+ dy[:n_bound_below, :] = dy_all[i_bound_below]
535
+ dy[n_bound_below:, :] = -dy_all[i_bound_above]
536
+ return dy
537
+ cineq[0]["jac"] = j_ineq
538
+
539
+ old_constraints = ceq + cineq
540
+
541
+ if len(old_constraints) > 1:
542
+ warn("Equality and inequality constraints are specified in the same "
543
+ "element of the constraint list. For efficient use with this "
544
+ "method, equality and inequality constraints should be specified "
545
+ "in separate elements of the constraint list. ",
546
+ OptimizeWarning, stacklevel=3)
547
+ return old_constraints
548
+
549
+
550
+ def old_constraint_to_new(ic, con):
551
+ """
552
+ Converts old-style constraint dictionaries to new-style constraint objects.
553
+ """
554
+ # check type
555
+ try:
556
+ ctype = con['type'].lower()
557
+ except KeyError as e:
558
+ raise KeyError('Constraint %d has no type defined.' % ic) from e
559
+ except TypeError as e:
560
+ raise TypeError(
561
+ 'Constraints must be a sequence of dictionaries.'
562
+ ) from e
563
+ except AttributeError as e:
564
+ raise TypeError("Constraint's type must be a string.") from e
565
+ else:
566
+ if ctype not in ['eq', 'ineq']:
567
+ raise ValueError("Unknown constraint type '%s'." % con['type'])
568
+ if 'fun' not in con:
569
+ raise ValueError('Constraint %d has no function defined.' % ic)
570
+
571
+ lb = 0
572
+ if ctype == 'eq':
573
+ ub = 0
574
+ else:
575
+ ub = np.inf
576
+
577
+ jac = '2-point'
578
+ if 'args' in con:
579
+ args = con['args']
580
+ def fun(x):
581
+ return con["fun"](x, *args)
582
+ if 'jac' in con:
583
+ def jac(x):
584
+ return con["jac"](x, *args)
585
+ else:
586
+ fun = con['fun']
587
+ if 'jac' in con:
588
+ jac = con['jac']
589
+
590
+ return NonlinearConstraint(fun, lb, ub, jac)
vila/lib/python3.10/site-packages/scipy/optimize/_dcsrch.py ADDED
@@ -0,0 +1,728 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ """
4
+ # 2023 - ported from minpack2.dcsrch, dcstep (Fortran) to Python
5
+ c MINPACK-1 Project. June 1983.
6
+ c Argonne National Laboratory.
7
+ c Jorge J. More' and David J. Thuente.
8
+ c
9
+ c MINPACK-2 Project. November 1993.
10
+ c Argonne National Laboratory and University of Minnesota.
11
+ c Brett M. Averick, Richard G. Carter, and Jorge J. More'.
12
+ """
13
+
14
+ # NOTE this file was linted by black on first commit, and can be kept that way.
15
+
16
+
17
+ class DCSRCH:
18
+ """
19
+ Parameters
20
+ ----------
21
+ phi : callable phi(alpha)
22
+ Function at point `alpha`
23
+ derphi : callable phi'(alpha)
24
+ Objective function derivative. Returns a scalar.
25
+ ftol : float
26
+ A nonnegative tolerance for the sufficient decrease condition.
27
+ gtol : float
28
+ A nonnegative tolerance for the curvature condition.
29
+ xtol : float
30
+ A nonnegative relative tolerance for an acceptable step. The
31
+ subroutine exits with a warning if the relative difference between
32
+ sty and stx is less than xtol.
33
+ stpmin : float
34
+ A nonnegative lower bound for the step.
35
+ stpmax :
36
+ A nonnegative upper bound for the step.
37
+
38
+ Notes
39
+ -----
40
+
41
+ This subroutine finds a step that satisfies a sufficient
42
+ decrease condition and a curvature condition.
43
+
44
+ Each call of the subroutine updates an interval with
45
+ endpoints stx and sty. The interval is initially chosen
46
+ so that it contains a minimizer of the modified function
47
+
48
+ psi(stp) = f(stp) - f(0) - ftol*stp*f'(0).
49
+
50
+ If psi(stp) <= 0 and f'(stp) >= 0 for some step, then the
51
+ interval is chosen so that it contains a minimizer of f.
52
+
53
+ The algorithm is designed to find a step that satisfies
54
+ the sufficient decrease condition
55
+
56
+ f(stp) <= f(0) + ftol*stp*f'(0),
57
+
58
+ and the curvature condition
59
+
60
+ abs(f'(stp)) <= gtol*abs(f'(0)).
61
+
62
+ If ftol is less than gtol and if, for example, the function
63
+ is bounded below, then there is always a step which satisfies
64
+ both conditions.
65
+
66
+ If no step can be found that satisfies both conditions, then
67
+ the algorithm stops with a warning. In this case stp only
68
+ satisfies the sufficient decrease condition.
69
+
70
+ A typical invocation of dcsrch has the following outline:
71
+
72
+ Evaluate the function at stp = 0.0d0; store in f.
73
+ Evaluate the gradient at stp = 0.0d0; store in g.
74
+ Choose a starting step stp.
75
+
76
+ task = 'START'
77
+ 10 continue
78
+ call dcsrch(stp,f,g,ftol,gtol,xtol,task,stpmin,stpmax,
79
+ isave,dsave)
80
+ if (task .eq. 'FG') then
81
+ Evaluate the function and the gradient at stp
82
+ go to 10
83
+ end if
84
+
85
+ NOTE: The user must not alter work arrays between calls.
86
+
87
+ The subroutine statement is
88
+
89
+ subroutine dcsrch(f,g,stp,ftol,gtol,xtol,stpmin,stpmax,
90
+ task,isave,dsave)
91
+ where
92
+
93
+ stp is a double precision variable.
94
+ On entry stp is the current estimate of a satisfactory
95
+ step. On initial entry, a positive initial estimate
96
+ must be provided.
97
+ On exit stp is the current estimate of a satisfactory step
98
+ if task = 'FG'. If task = 'CONV' then stp satisfies
99
+ the sufficient decrease and curvature condition.
100
+
101
+ f is a double precision variable.
102
+ On initial entry f is the value of the function at 0.
103
+ On subsequent entries f is the value of the
104
+ function at stp.
105
+ On exit f is the value of the function at stp.
106
+
107
+ g is a double precision variable.
108
+ On initial entry g is the derivative of the function at 0.
109
+ On subsequent entries g is the derivative of the
110
+ function at stp.
111
+ On exit g is the derivative of the function at stp.
112
+
113
+ ftol is a double precision variable.
114
+ On entry ftol specifies a nonnegative tolerance for the
115
+ sufficient decrease condition.
116
+ On exit ftol is unchanged.
117
+
118
+ gtol is a double precision variable.
119
+ On entry gtol specifies a nonnegative tolerance for the
120
+ curvature condition.
121
+ On exit gtol is unchanged.
122
+
123
+ xtol is a double precision variable.
124
+ On entry xtol specifies a nonnegative relative tolerance
125
+ for an acceptable step. The subroutine exits with a
126
+ warning if the relative difference between sty and stx
127
+ is less than xtol.
128
+
129
+ On exit xtol is unchanged.
130
+
131
+ task is a character variable of length at least 60.
132
+ On initial entry task must be set to 'START'.
133
+ On exit task indicates the required action:
134
+
135
+ If task(1:2) = 'FG' then evaluate the function and
136
+ derivative at stp and call dcsrch again.
137
+
138
+ If task(1:4) = 'CONV' then the search is successful.
139
+
140
+ If task(1:4) = 'WARN' then the subroutine is not able
141
+ to satisfy the convergence conditions. The exit value of
142
+ stp contains the best point found during the search.
143
+
144
+ If task(1:5) = 'ERROR' then there is an error in the
145
+ input arguments.
146
+
147
+ On exit with convergence, a warning or an error, the
148
+ variable task contains additional information.
149
+
150
+ stpmin is a double precision variable.
151
+ On entry stpmin is a nonnegative lower bound for the step.
152
+ On exit stpmin is unchanged.
153
+
154
+ stpmax is a double precision variable.
155
+ On entry stpmax is a nonnegative upper bound for the step.
156
+ On exit stpmax is unchanged.
157
+
158
+ isave is an integer work array of dimension 2.
159
+
160
+ dsave is a double precision work array of dimension 13.
161
+
162
+ Subprograms called
163
+
164
+ MINPACK-2 ... dcstep
165
+ MINPACK-1 Project. June 1983.
166
+ Argonne National Laboratory.
167
+ Jorge J. More' and David J. Thuente.
168
+
169
+ MINPACK-2 Project. November 1993.
170
+ Argonne National Laboratory and University of Minnesota.
171
+ Brett M. Averick, Richard G. Carter, and Jorge J. More'.
172
+ """
173
+
174
+ def __init__(self, phi, derphi, ftol, gtol, xtol, stpmin, stpmax):
175
+ self.stage = None
176
+ self.ginit = None
177
+ self.gtest = None
178
+ self.gx = None
179
+ self.gy = None
180
+ self.finit = None
181
+ self.fx = None
182
+ self.fy = None
183
+ self.stx = None
184
+ self.sty = None
185
+ self.stmin = None
186
+ self.stmax = None
187
+ self.width = None
188
+ self.width1 = None
189
+
190
+ # leave all assessment of tolerances/limits to the first call of
191
+ # this object
192
+ self.ftol = ftol
193
+ self.gtol = gtol
194
+ self.xtol = xtol
195
+ self.stpmin = stpmin
196
+ self.stpmax = stpmax
197
+
198
+ self.phi = phi
199
+ self.derphi = derphi
200
+
201
+ def __call__(self, alpha1, phi0=None, derphi0=None, maxiter=100):
202
+ """
203
+ Parameters
204
+ ----------
205
+ alpha1 : float
206
+ alpha1 is the current estimate of a satisfactory
207
+ step. A positive initial estimate must be provided.
208
+ phi0 : float
209
+ the value of `phi` at 0 (if known).
210
+ derphi0 : float
211
+ the derivative of `derphi` at 0 (if known).
212
+ maxiter : int
213
+
214
+ Returns
215
+ -------
216
+ alpha : float
217
+ Step size, or None if no suitable step was found.
218
+ phi : float
219
+ Value of `phi` at the new point `alpha`.
220
+ phi0 : float
221
+ Value of `phi` at `alpha=0`.
222
+ task : bytes
223
+ On exit task indicates status information.
224
+
225
+ If task[:4] == b'CONV' then the search is successful.
226
+
227
+ If task[:4] == b'WARN' then the subroutine is not able
228
+ to satisfy the convergence conditions. The exit value of
229
+ stp contains the best point found during the search.
230
+
231
+ If task[:5] == b'ERROR' then there is an error in the
232
+ input arguments.
233
+ """
234
+ if phi0 is None:
235
+ phi0 = self.phi(0.0)
236
+ if derphi0 is None:
237
+ derphi0 = self.derphi(0.0)
238
+
239
+ phi1 = phi0
240
+ derphi1 = derphi0
241
+
242
+ task = b"START"
243
+ for i in range(maxiter):
244
+ stp, phi1, derphi1, task = self._iterate(
245
+ alpha1, phi1, derphi1, task
246
+ )
247
+
248
+ if not np.isfinite(stp):
249
+ task = b"WARN"
250
+ stp = None
251
+ break
252
+
253
+ if task[:2] == b"FG":
254
+ alpha1 = stp
255
+ phi1 = self.phi(stp)
256
+ derphi1 = self.derphi(stp)
257
+ else:
258
+ break
259
+ else:
260
+ # maxiter reached, the line search did not converge
261
+ stp = None
262
+ task = b"WARNING: dcsrch did not converge within max iterations"
263
+
264
+ if task[:5] == b"ERROR" or task[:4] == b"WARN":
265
+ stp = None # failed
266
+
267
+ return stp, phi1, phi0, task
268
+
269
+ def _iterate(self, stp, f, g, task):
270
+ """
271
+ Parameters
272
+ ----------
273
+ stp : float
274
+ The current estimate of a satisfactory step. On initial entry, a
275
+ positive initial estimate must be provided.
276
+ f : float
277
+ On first call f is the value of the function at 0. On subsequent
278
+ entries f should be the value of the function at stp.
279
+ g : float
280
+ On initial entry g is the derivative of the function at 0. On
281
+ subsequent entries g is the derivative of the function at stp.
282
+ task : bytes
283
+ On initial entry task must be set to 'START'.
284
+
285
+ On exit with convergence, a warning or an error, the
286
+ variable task contains additional information.
287
+
288
+
289
+ Returns
290
+ -------
291
+ stp, f, g, task: tuple
292
+
293
+ stp : float
294
+ the current estimate of a satisfactory step if task = 'FG'. If
295
+ task = 'CONV' then stp satisfies the sufficient decrease and
296
+ curvature condition.
297
+ f : float
298
+ the value of the function at stp.
299
+ g : float
300
+ the derivative of the function at stp.
301
+ task : bytes
302
+ On exit task indicates the required action:
303
+
304
+ If task(1:2) == b'FG' then evaluate the function and
305
+ derivative at stp and call dcsrch again.
306
+
307
+ If task(1:4) == b'CONV' then the search is successful.
308
+
309
+ If task(1:4) == b'WARN' then the subroutine is not able
310
+ to satisfy the convergence conditions. The exit value of
311
+ stp contains the best point found during the search.
312
+
313
+ If task(1:5) == b'ERROR' then there is an error in the
314
+ input arguments.
315
+ """
316
+ p5 = 0.5
317
+ p66 = 0.66
318
+ xtrapl = 1.1
319
+ xtrapu = 4.0
320
+
321
+ if task[:5] == b"START":
322
+ if stp < self.stpmin:
323
+ task = b"ERROR: STP .LT. STPMIN"
324
+ if stp > self.stpmax:
325
+ task = b"ERROR: STP .GT. STPMAX"
326
+ if g >= 0:
327
+ task = b"ERROR: INITIAL G .GE. ZERO"
328
+ if self.ftol < 0:
329
+ task = b"ERROR: FTOL .LT. ZERO"
330
+ if self.gtol < 0:
331
+ task = b"ERROR: GTOL .LT. ZERO"
332
+ if self.xtol < 0:
333
+ task = b"ERROR: XTOL .LT. ZERO"
334
+ if self.stpmin < 0:
335
+ task = b"ERROR: STPMIN .LT. ZERO"
336
+ if self.stpmax < self.stpmin:
337
+ task = b"ERROR: STPMAX .LT. STPMIN"
338
+
339
+ if task[:5] == b"ERROR":
340
+ return stp, f, g, task
341
+
342
+ # Initialize local variables.
343
+
344
+ self.brackt = False
345
+ self.stage = 1
346
+ self.finit = f
347
+ self.ginit = g
348
+ self.gtest = self.ftol * self.ginit
349
+ self.width = self.stpmax - self.stpmin
350
+ self.width1 = self.width / p5
351
+
352
+ # The variables stx, fx, gx contain the values of the step,
353
+ # function, and derivative at the best step.
354
+ # The variables sty, fy, gy contain the value of the step,
355
+ # function, and derivative at sty.
356
+ # The variables stp, f, g contain the values of the step,
357
+ # function, and derivative at stp.
358
+
359
+ self.stx = 0.0
360
+ self.fx = self.finit
361
+ self.gx = self.ginit
362
+ self.sty = 0.0
363
+ self.fy = self.finit
364
+ self.gy = self.ginit
365
+ self.stmin = 0
366
+ self.stmax = stp + xtrapu * stp
367
+ task = b"FG"
368
+ return stp, f, g, task
369
+
370
+ # in the original Fortran this was a location to restore variables
371
+ # we don't need to do that because they're attributes.
372
+
373
+ # If psi(stp) <= 0 and f'(stp) >= 0 for some step, then the
374
+ # algorithm enters the second stage.
375
+ ftest = self.finit + stp * self.gtest
376
+
377
+ if self.stage == 1 and f <= ftest and g >= 0:
378
+ self.stage = 2
379
+
380
+ # test for warnings
381
+ if self.brackt and (stp <= self.stmin or stp >= self.stmax):
382
+ task = b"WARNING: ROUNDING ERRORS PREVENT PROGRESS"
383
+ if self.brackt and self.stmax - self.stmin <= self.xtol * self.stmax:
384
+ task = b"WARNING: XTOL TEST SATISFIED"
385
+ if stp == self.stpmax and f <= ftest and g <= self.gtest:
386
+ task = b"WARNING: STP = STPMAX"
387
+ if stp == self.stpmin and (f > ftest or g >= self.gtest):
388
+ task = b"WARNING: STP = STPMIN"
389
+
390
+ # test for convergence
391
+ if f <= ftest and abs(g) <= self.gtol * -self.ginit:
392
+ task = b"CONVERGENCE"
393
+
394
+ # test for termination
395
+ if task[:4] == b"WARN" or task[:4] == b"CONV":
396
+ return stp, f, g, task
397
+
398
+ # A modified function is used to predict the step during the
399
+ # first stage if a lower function value has been obtained but
400
+ # the decrease is not sufficient.
401
+ if self.stage == 1 and f <= self.fx and f > ftest:
402
+ # Define the modified function and derivative values.
403
+ fm = f - stp * self.gtest
404
+ fxm = self.fx - self.stx * self.gtest
405
+ fym = self.fy - self.sty * self.gtest
406
+ gm = g - self.gtest
407
+ gxm = self.gx - self.gtest
408
+ gym = self.gy - self.gtest
409
+
410
+ # Call dcstep to update stx, sty, and to compute the new step.
411
+ # dcstep can have several operations which can produce NaN
412
+ # e.g. inf/inf. Filter these out.
413
+ with np.errstate(invalid="ignore", over="ignore"):
414
+ tup = dcstep(
415
+ self.stx,
416
+ fxm,
417
+ gxm,
418
+ self.sty,
419
+ fym,
420
+ gym,
421
+ stp,
422
+ fm,
423
+ gm,
424
+ self.brackt,
425
+ self.stmin,
426
+ self.stmax,
427
+ )
428
+ self.stx, fxm, gxm, self.sty, fym, gym, stp, self.brackt = tup
429
+
430
+ # Reset the function and derivative values for f
431
+ self.fx = fxm + self.stx * self.gtest
432
+ self.fy = fym + self.sty * self.gtest
433
+ self.gx = gxm + self.gtest
434
+ self.gy = gym + self.gtest
435
+
436
+ else:
437
+ # Call dcstep to update stx, sty, and to compute the new step.
438
+ # dcstep can have several operations which can produce NaN
439
+ # e.g. inf/inf. Filter these out.
440
+
441
+ with np.errstate(invalid="ignore", over="ignore"):
442
+ tup = dcstep(
443
+ self.stx,
444
+ self.fx,
445
+ self.gx,
446
+ self.sty,
447
+ self.fy,
448
+ self.gy,
449
+ stp,
450
+ f,
451
+ g,
452
+ self.brackt,
453
+ self.stmin,
454
+ self.stmax,
455
+ )
456
+ (
457
+ self.stx,
458
+ self.fx,
459
+ self.gx,
460
+ self.sty,
461
+ self.fy,
462
+ self.gy,
463
+ stp,
464
+ self.brackt,
465
+ ) = tup
466
+
467
+ # Decide if a bisection step is needed
468
+ if self.brackt:
469
+ if abs(self.sty - self.stx) >= p66 * self.width1:
470
+ stp = self.stx + p5 * (self.sty - self.stx)
471
+ self.width1 = self.width
472
+ self.width = abs(self.sty - self.stx)
473
+
474
+ # Set the minimum and maximum steps allowed for stp.
475
+ if self.brackt:
476
+ self.stmin = min(self.stx, self.sty)
477
+ self.stmax = max(self.stx, self.sty)
478
+ else:
479
+ self.stmin = stp + xtrapl * (stp - self.stx)
480
+ self.stmax = stp + xtrapu * (stp - self.stx)
481
+
482
+ # Force the step to be within the bounds stpmax and stpmin.
483
+ stp = np.clip(stp, self.stpmin, self.stpmax)
484
+
485
+ # If further progress is not possible, let stp be the best
486
+ # point obtained during the search.
487
+ if (
488
+ self.brackt
489
+ and (stp <= self.stmin or stp >= self.stmax)
490
+ or (
491
+ self.brackt
492
+ and self.stmax - self.stmin <= self.xtol * self.stmax
493
+ )
494
+ ):
495
+ stp = self.stx
496
+
497
+ # Obtain another function and derivative
498
+ task = b"FG"
499
+ return stp, f, g, task
500
+
501
+
502
+ def dcstep(stx, fx, dx, sty, fy, dy, stp, fp, dp, brackt, stpmin, stpmax):
503
+ """
504
+ Subroutine dcstep
505
+
506
+ This subroutine computes a safeguarded step for a search
507
+ procedure and updates an interval that contains a step that
508
+ satisfies a sufficient decrease and a curvature condition.
509
+
510
+ The parameter stx contains the step with the least function
511
+ value. If brackt is set to .true. then a minimizer has
512
+ been bracketed in an interval with endpoints stx and sty.
513
+ The parameter stp contains the current step.
514
+ The subroutine assumes that if brackt is set to .true. then
515
+
516
+ min(stx,sty) < stp < max(stx,sty),
517
+
518
+ and that the derivative at stx is negative in the direction
519
+ of the step.
520
+
521
+ The subroutine statement is
522
+
523
+ subroutine dcstep(stx,fx,dx,sty,fy,dy,stp,fp,dp,brackt,
524
+ stpmin,stpmax)
525
+
526
+ where
527
+
528
+ stx is a double precision variable.
529
+ On entry stx is the best step obtained so far and is an
530
+ endpoint of the interval that contains the minimizer.
531
+ On exit stx is the updated best step.
532
+
533
+ fx is a double precision variable.
534
+ On entry fx is the function at stx.
535
+ On exit fx is the function at stx.
536
+
537
+ dx is a double precision variable.
538
+ On entry dx is the derivative of the function at
539
+ stx. The derivative must be negative in the direction of
540
+ the step, that is, dx and stp - stx must have opposite
541
+ signs.
542
+ On exit dx is the derivative of the function at stx.
543
+
544
+ sty is a double precision variable.
545
+ On entry sty is the second endpoint of the interval that
546
+ contains the minimizer.
547
+ On exit sty is the updated endpoint of the interval that
548
+ contains the minimizer.
549
+
550
+ fy is a double precision variable.
551
+ On entry fy is the function at sty.
552
+ On exit fy is the function at sty.
553
+
554
+ dy is a double precision variable.
555
+ On entry dy is the derivative of the function at sty.
556
+ On exit dy is the derivative of the function at the exit sty.
557
+
558
+ stp is a double precision variable.
559
+ On entry stp is the current step. If brackt is set to .true.
560
+ then on input stp must be between stx and sty.
561
+ On exit stp is a new trial step.
562
+
563
+ fp is a double precision variable.
564
+ On entry fp is the function at stp
565
+ On exit fp is unchanged.
566
+
567
+ dp is a double precision variable.
568
+ On entry dp is the derivative of the function at stp.
569
+ On exit dp is unchanged.
570
+
571
+ brackt is an logical variable.
572
+ On entry brackt specifies if a minimizer has been bracketed.
573
+ Initially brackt must be set to .false.
574
+ On exit brackt specifies if a minimizer has been bracketed.
575
+ When a minimizer is bracketed brackt is set to .true.
576
+
577
+ stpmin is a double precision variable.
578
+ On entry stpmin is a lower bound for the step.
579
+ On exit stpmin is unchanged.
580
+
581
+ stpmax is a double precision variable.
582
+ On entry stpmax is an upper bound for the step.
583
+ On exit stpmax is unchanged.
584
+
585
+ MINPACK-1 Project. June 1983
586
+ Argonne National Laboratory.
587
+ Jorge J. More' and David J. Thuente.
588
+
589
+ MINPACK-2 Project. November 1993.
590
+ Argonne National Laboratory and University of Minnesota.
591
+ Brett M. Averick and Jorge J. More'.
592
+
593
+ """
594
+ sgn_dp = np.sign(dp)
595
+ sgn_dx = np.sign(dx)
596
+
597
+ # sgnd = dp * (dx / abs(dx))
598
+ sgnd = sgn_dp * sgn_dx
599
+
600
+ # First case: A higher function value. The minimum is bracketed.
601
+ # If the cubic step is closer to stx than the quadratic step, the
602
+ # cubic step is taken, otherwise the average of the cubic and
603
+ # quadratic steps is taken.
604
+ if fp > fx:
605
+ theta = 3.0 * (fx - fp) / (stp - stx) + dx + dp
606
+ s = max(abs(theta), abs(dx), abs(dp))
607
+ gamma = s * np.sqrt((theta / s) ** 2 - (dx / s) * (dp / s))
608
+ if stp < stx:
609
+ gamma *= -1
610
+ p = (gamma - dx) + theta
611
+ q = ((gamma - dx) + gamma) + dp
612
+ r = p / q
613
+ stpc = stx + r * (stp - stx)
614
+ stpq = stx + ((dx / ((fx - fp) / (stp - stx) + dx)) / 2.0) * (stp - stx)
615
+ if abs(stpc - stx) <= abs(stpq - stx):
616
+ stpf = stpc
617
+ else:
618
+ stpf = stpc + (stpq - stpc) / 2.0
619
+ brackt = True
620
+ elif sgnd < 0.0:
621
+ # Second case: A lower function value and derivatives of opposite
622
+ # sign. The minimum is bracketed. If the cubic step is farther from
623
+ # stp than the secant step, the cubic step is taken, otherwise the
624
+ # secant step is taken.
625
+ theta = 3 * (fx - fp) / (stp - stx) + dx + dp
626
+ s = max(abs(theta), abs(dx), abs(dp))
627
+ gamma = s * np.sqrt((theta / s) ** 2 - (dx / s) * (dp / s))
628
+ if stp > stx:
629
+ gamma *= -1
630
+ p = (gamma - dp) + theta
631
+ q = ((gamma - dp) + gamma) + dx
632
+ r = p / q
633
+ stpc = stp + r * (stx - stp)
634
+ stpq = stp + (dp / (dp - dx)) * (stx - stp)
635
+ if abs(stpc - stp) > abs(stpq - stp):
636
+ stpf = stpc
637
+ else:
638
+ stpf = stpq
639
+ brackt = True
640
+ elif abs(dp) < abs(dx):
641
+ # Third case: A lower function value, derivatives of the same sign,
642
+ # and the magnitude of the derivative decreases.
643
+
644
+ # The cubic step is computed only if the cubic tends to infinity
645
+ # in the direction of the step or if the minimum of the cubic
646
+ # is beyond stp. Otherwise the cubic step is defined to be the
647
+ # secant step.
648
+ theta = 3 * (fx - fp) / (stp - stx) + dx + dp
649
+ s = max(abs(theta), abs(dx), abs(dp))
650
+
651
+ # The case gamma = 0 only arises if the cubic does not tend
652
+ # to infinity in the direction of the step.
653
+ gamma = s * np.sqrt(max(0, (theta / s) ** 2 - (dx / s) * (dp / s)))
654
+ if stp > stx:
655
+ gamma = -gamma
656
+ p = (gamma - dp) + theta
657
+ q = (gamma + (dx - dp)) + gamma
658
+ r = p / q
659
+ if r < 0 and gamma != 0:
660
+ stpc = stp + r * (stx - stp)
661
+ elif stp > stx:
662
+ stpc = stpmax
663
+ else:
664
+ stpc = stpmin
665
+ stpq = stp + (dp / (dp - dx)) * (stx - stp)
666
+
667
+ if brackt:
668
+ # A minimizer has been bracketed. If the cubic step is
669
+ # closer to stp than the secant step, the cubic step is
670
+ # taken, otherwise the secant step is taken.
671
+ if abs(stpc - stp) < abs(stpq - stp):
672
+ stpf = stpc
673
+ else:
674
+ stpf = stpq
675
+
676
+ if stp > stx:
677
+ stpf = min(stp + 0.66 * (sty - stp), stpf)
678
+ else:
679
+ stpf = max(stp + 0.66 * (sty - stp), stpf)
680
+ else:
681
+ # A minimizer has not been bracketed. If the cubic step is
682
+ # farther from stp than the secant step, the cubic step is
683
+ # taken, otherwise the secant step is taken.
684
+ if abs(stpc - stp) > abs(stpq - stp):
685
+ stpf = stpc
686
+ else:
687
+ stpf = stpq
688
+ stpf = np.clip(stpf, stpmin, stpmax)
689
+
690
+ else:
691
+ # Fourth case: A lower function value, derivatives of the same sign,
692
+ # and the magnitude of the derivative does not decrease. If the
693
+ # minimum is not bracketed, the step is either stpmin or stpmax,
694
+ # otherwise the cubic step is taken.
695
+ if brackt:
696
+ theta = 3.0 * (fp - fy) / (sty - stp) + dy + dp
697
+ s = max(abs(theta), abs(dy), abs(dp))
698
+ gamma = s * np.sqrt((theta / s) ** 2 - (dy / s) * (dp / s))
699
+ if stp > sty:
700
+ gamma = -gamma
701
+ p = (gamma - dp) + theta
702
+ q = ((gamma - dp) + gamma) + dy
703
+ r = p / q
704
+ stpc = stp + r * (sty - stp)
705
+ stpf = stpc
706
+ elif stp > stx:
707
+ stpf = stpmax
708
+ else:
709
+ stpf = stpmin
710
+
711
+ # Update the interval which contains a minimizer.
712
+ if fp > fx:
713
+ sty = stp
714
+ fy = fp
715
+ dy = dp
716
+ else:
717
+ if sgnd < 0:
718
+ sty = stx
719
+ fy = fx
720
+ dy = dx
721
+ stx = stp
722
+ fx = fp
723
+ dx = dp
724
+
725
+ # Compute the new step.
726
+ stp = stpf
727
+
728
+ return stx, fx, dx, sty, fy, dy, stp, brackt
vila/lib/python3.10/site-packages/scipy/optimize/_direct.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (43.5 kB). View file
 
vila/lib/python3.10/site-packages/scipy/optimize/_direct_py.py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from typing import ( # noqa: UP035
3
+ Any, Callable, Iterable, TYPE_CHECKING
4
+ )
5
+
6
+ import numpy as np
7
+ from scipy.optimize import OptimizeResult
8
+ from ._constraints import old_bound_to_new, Bounds
9
+ from ._direct import direct as _direct # type: ignore
10
+
11
+ if TYPE_CHECKING:
12
+ import numpy.typing as npt
13
+
14
+ __all__ = ['direct']
15
+
16
+ ERROR_MESSAGES = (
17
+ "Number of function evaluations done is larger than maxfun={}",
18
+ "Number of iterations is larger than maxiter={}",
19
+ "u[i] < l[i] for some i",
20
+ "maxfun is too large",
21
+ "Initialization failed",
22
+ "There was an error in the creation of the sample points",
23
+ "An error occurred while the function was sampled",
24
+ "Maximum number of levels has been reached.",
25
+ "Forced stop",
26
+ "Invalid arguments",
27
+ "Out of memory",
28
+ )
29
+
30
+ SUCCESS_MESSAGES = (
31
+ ("The best function value found is within a relative error={} "
32
+ "of the (known) global optimum f_min"),
33
+ ("The volume of the hyperrectangle containing the lowest function value "
34
+ "found is below vol_tol={}"),
35
+ ("The side length measure of the hyperrectangle containing the lowest "
36
+ "function value found is below len_tol={}"),
37
+ )
38
+
39
+
40
+ def direct(
41
+ func: Callable[[npt.ArrayLike, tuple[Any]], float],
42
+ bounds: Iterable | Bounds,
43
+ *,
44
+ args: tuple = (),
45
+ eps: float = 1e-4,
46
+ maxfun: int | None = None,
47
+ maxiter: int = 1000,
48
+ locally_biased: bool = True,
49
+ f_min: float = -np.inf,
50
+ f_min_rtol: float = 1e-4,
51
+ vol_tol: float = 1e-16,
52
+ len_tol: float = 1e-6,
53
+ callback: Callable[[npt.ArrayLike], None] | None = None
54
+ ) -> OptimizeResult:
55
+ """
56
+ Finds the global minimum of a function using the
57
+ DIRECT algorithm.
58
+
59
+ Parameters
60
+ ----------
61
+ func : callable
62
+ The objective function to be minimized.
63
+ ``func(x, *args) -> float``
64
+ where ``x`` is an 1-D array with shape (n,) and ``args`` is a tuple of
65
+ the fixed parameters needed to completely specify the function.
66
+ bounds : sequence or `Bounds`
67
+ Bounds for variables. There are two ways to specify the bounds:
68
+
69
+ 1. Instance of `Bounds` class.
70
+ 2. ``(min, max)`` pairs for each element in ``x``.
71
+
72
+ args : tuple, optional
73
+ Any additional fixed parameters needed to
74
+ completely specify the objective function.
75
+ eps : float, optional
76
+ Minimal required difference of the objective function values
77
+ between the current best hyperrectangle and the next potentially
78
+ optimal hyperrectangle to be divided. In consequence, `eps` serves as a
79
+ tradeoff between local and global search: the smaller, the more local
80
+ the search becomes. Default is 1e-4.
81
+ maxfun : int or None, optional
82
+ Approximate upper bound on objective function evaluations.
83
+ If `None`, will be automatically set to ``1000 * N`` where ``N``
84
+ represents the number of dimensions. Will be capped if necessary to
85
+ limit DIRECT's RAM usage to app. 1GiB. This will only occur for very
86
+ high dimensional problems and excessive `max_fun`. Default is `None`.
87
+ maxiter : int, optional
88
+ Maximum number of iterations. Default is 1000.
89
+ locally_biased : bool, optional
90
+ If `True` (default), use the locally biased variant of the
91
+ algorithm known as DIRECT_L. If `False`, use the original unbiased
92
+ DIRECT algorithm. For hard problems with many local minima,
93
+ `False` is recommended.
94
+ f_min : float, optional
95
+ Function value of the global optimum. Set this value only if the
96
+ global optimum is known. Default is ``-np.inf``, so that this
97
+ termination criterion is deactivated.
98
+ f_min_rtol : float, optional
99
+ Terminate the optimization once the relative error between the
100
+ current best minimum `f` and the supplied global minimum `f_min`
101
+ is smaller than `f_min_rtol`. This parameter is only used if
102
+ `f_min` is also set. Must lie between 0 and 1. Default is 1e-4.
103
+ vol_tol : float, optional
104
+ Terminate the optimization once the volume of the hyperrectangle
105
+ containing the lowest function value is smaller than `vol_tol`
106
+ of the complete search space. Must lie between 0 and 1.
107
+ Default is 1e-16.
108
+ len_tol : float, optional
109
+ If `locally_biased=True`, terminate the optimization once half of
110
+ the normalized maximal side length of the hyperrectangle containing
111
+ the lowest function value is smaller than `len_tol`.
112
+ If `locally_biased=False`, terminate the optimization once half of
113
+ the normalized diagonal of the hyperrectangle containing the lowest
114
+ function value is smaller than `len_tol`. Must lie between 0 and 1.
115
+ Default is 1e-6.
116
+ callback : callable, optional
117
+ A callback function with signature ``callback(xk)`` where ``xk``
118
+ represents the best function value found so far.
119
+
120
+ Returns
121
+ -------
122
+ res : OptimizeResult
123
+ The optimization result represented as a ``OptimizeResult`` object.
124
+ Important attributes are: ``x`` the solution array, ``success`` a
125
+ Boolean flag indicating if the optimizer exited successfully and
126
+ ``message`` which describes the cause of the termination. See
127
+ `OptimizeResult` for a description of other attributes.
128
+
129
+ Notes
130
+ -----
131
+ DIviding RECTangles (DIRECT) is a deterministic global
132
+ optimization algorithm capable of minimizing a black box function with
133
+ its variables subject to lower and upper bound constraints by sampling
134
+ potential solutions in the search space [1]_. The algorithm starts by
135
+ normalising the search space to an n-dimensional unit hypercube.
136
+ It samples the function at the center of this hypercube and at 2n
137
+ (n is the number of variables) more points, 2 in each coordinate
138
+ direction. Using these function values, DIRECT then divides the
139
+ domain into hyperrectangles, each having exactly one of the sampling
140
+ points as its center. In each iteration, DIRECT chooses, using the `eps`
141
+ parameter which defaults to 1e-4, some of the existing hyperrectangles
142
+ to be further divided. This division process continues until either the
143
+ maximum number of iterations or maximum function evaluations allowed
144
+ are exceeded, or the hyperrectangle containing the minimal value found
145
+ so far becomes small enough. If `f_min` is specified, the optimization
146
+ will stop once this function value is reached within a relative tolerance.
147
+ The locally biased variant of DIRECT (originally called DIRECT_L) [2]_ is
148
+ used by default. It makes the search more locally biased and more
149
+ efficient for cases with only a few local minima.
150
+
151
+ A note about termination criteria: `vol_tol` refers to the volume of the
152
+ hyperrectangle containing the lowest function value found so far. This
153
+ volume decreases exponentially with increasing dimensionality of the
154
+ problem. Therefore `vol_tol` should be decreased to avoid premature
155
+ termination of the algorithm for higher dimensions. This does not hold
156
+ for `len_tol`: it refers either to half of the maximal side length
157
+ (for ``locally_biased=True``) or half of the diagonal of the
158
+ hyperrectangle (for ``locally_biased=False``).
159
+
160
+ This code is based on the DIRECT 2.0.4 Fortran code by Gablonsky et al. at
161
+ https://ctk.math.ncsu.edu/SOFTWARE/DIRECTv204.tar.gz .
162
+ This original version was initially converted via f2c and then cleaned up
163
+ and reorganized by Steven G. Johnson, August 2007, for the NLopt project.
164
+ The `direct` function wraps the C implementation.
165
+
166
+ .. versionadded:: 1.9.0
167
+
168
+ References
169
+ ----------
170
+ .. [1] Jones, D.R., Perttunen, C.D. & Stuckman, B.E. Lipschitzian
171
+ optimization without the Lipschitz constant. J Optim Theory Appl
172
+ 79, 157-181 (1993).
173
+ .. [2] Gablonsky, J., Kelley, C. A Locally-Biased form of the DIRECT
174
+ Algorithm. Journal of Global Optimization 21, 27-37 (2001).
175
+
176
+ Examples
177
+ --------
178
+ The following example is a 2-D problem with four local minima: minimizing
179
+ the Styblinski-Tang function
180
+ (https://en.wikipedia.org/wiki/Test_functions_for_optimization).
181
+
182
+ >>> from scipy.optimize import direct, Bounds
183
+ >>> def styblinski_tang(pos):
184
+ ... x, y = pos
185
+ ... return 0.5 * (x**4 - 16*x**2 + 5*x + y**4 - 16*y**2 + 5*y)
186
+ >>> bounds = Bounds([-4., -4.], [4., 4.])
187
+ >>> result = direct(styblinski_tang, bounds)
188
+ >>> result.x, result.fun, result.nfev
189
+ array([-2.90321597, -2.90321597]), -78.3323279095383, 2011
190
+
191
+ The correct global minimum was found but with a huge number of function
192
+ evaluations (2011). Loosening the termination tolerances `vol_tol` and
193
+ `len_tol` can be used to stop DIRECT earlier.
194
+
195
+ >>> result = direct(styblinski_tang, bounds, len_tol=1e-3)
196
+ >>> result.x, result.fun, result.nfev
197
+ array([-2.9044353, -2.9044353]), -78.33230330754142, 207
198
+
199
+ """
200
+ # convert bounds to new Bounds class if necessary
201
+ if not isinstance(bounds, Bounds):
202
+ if isinstance(bounds, list) or isinstance(bounds, tuple):
203
+ lb, ub = old_bound_to_new(bounds)
204
+ bounds = Bounds(lb, ub)
205
+ else:
206
+ message = ("bounds must be a sequence or "
207
+ "instance of Bounds class")
208
+ raise ValueError(message)
209
+
210
+ lb = np.ascontiguousarray(bounds.lb, dtype=np.float64)
211
+ ub = np.ascontiguousarray(bounds.ub, dtype=np.float64)
212
+
213
+ # validate bounds
214
+ # check that lower bounds are smaller than upper bounds
215
+ if not np.all(lb < ub):
216
+ raise ValueError('Bounds are not consistent min < max')
217
+ # check for infs
218
+ if (np.any(np.isinf(lb)) or np.any(np.isinf(ub))):
219
+ raise ValueError("Bounds must not be inf.")
220
+
221
+ # validate tolerances
222
+ if (vol_tol < 0 or vol_tol > 1):
223
+ raise ValueError("vol_tol must be between 0 and 1.")
224
+ if (len_tol < 0 or len_tol > 1):
225
+ raise ValueError("len_tol must be between 0 and 1.")
226
+ if (f_min_rtol < 0 or f_min_rtol > 1):
227
+ raise ValueError("f_min_rtol must be between 0 and 1.")
228
+
229
+ # validate maxfun and maxiter
230
+ if maxfun is None:
231
+ maxfun = 1000 * lb.shape[0]
232
+ if not isinstance(maxfun, int):
233
+ raise ValueError("maxfun must be of type int.")
234
+ if maxfun < 0:
235
+ raise ValueError("maxfun must be > 0.")
236
+ if not isinstance(maxiter, int):
237
+ raise ValueError("maxiter must be of type int.")
238
+ if maxiter < 0:
239
+ raise ValueError("maxiter must be > 0.")
240
+
241
+ # validate boolean parameters
242
+ if not isinstance(locally_biased, bool):
243
+ raise ValueError("locally_biased must be True or False.")
244
+
245
+ def _func_wrap(x, args=None):
246
+ x = np.asarray(x)
247
+ if args is None:
248
+ f = func(x)
249
+ else:
250
+ f = func(x, *args)
251
+ # always return a float
252
+ return np.asarray(f).item()
253
+
254
+ # TODO: fix disp argument
255
+ x, fun, ret_code, nfev, nit = _direct(
256
+ _func_wrap,
257
+ np.asarray(lb), np.asarray(ub),
258
+ args,
259
+ False, eps, maxfun, maxiter,
260
+ locally_biased,
261
+ f_min, f_min_rtol,
262
+ vol_tol, len_tol, callback
263
+ )
264
+
265
+ format_val = (maxfun, maxiter, f_min_rtol, vol_tol, len_tol)
266
+ if ret_code > 2:
267
+ message = SUCCESS_MESSAGES[ret_code - 3].format(
268
+ format_val[ret_code - 1])
269
+ elif 0 < ret_code <= 2:
270
+ message = ERROR_MESSAGES[ret_code - 1].format(format_val[ret_code - 1])
271
+ elif 0 > ret_code > -100:
272
+ message = ERROR_MESSAGES[abs(ret_code) + 1]
273
+ else:
274
+ message = ERROR_MESSAGES[ret_code + 99]
275
+
276
+ return OptimizeResult(x=np.asarray(x), fun=fun, status=ret_code,
277
+ success=ret_code > 2, message=message,
278
+ nfev=nfev, nit=nit)
vila/lib/python3.10/site-packages/scipy/optimize/_group_columns.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (99.8 kB). View file
 
vila/lib/python3.10/site-packages/scipy/optimize/_hessian_update_strategy.py ADDED
@@ -0,0 +1,475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hessian update strategies for quasi-Newton optimization methods."""
2
+ import numpy as np
3
+ from numpy.linalg import norm
4
+ from scipy.linalg import get_blas_funcs, issymmetric
5
+ from warnings import warn
6
+
7
+
8
+ __all__ = ['HessianUpdateStrategy', 'BFGS', 'SR1']
9
+
10
+
11
+ class HessianUpdateStrategy:
12
+ """Interface for implementing Hessian update strategies.
13
+
14
+ Many optimization methods make use of Hessian (or inverse Hessian)
15
+ approximations, such as the quasi-Newton methods BFGS, SR1, L-BFGS.
16
+ Some of these approximations, however, do not actually need to store
17
+ the entire matrix or can compute the internal matrix product with a
18
+ given vector in a very efficiently manner. This class serves as an
19
+ abstract interface between the optimization algorithm and the
20
+ quasi-Newton update strategies, giving freedom of implementation
21
+ to store and update the internal matrix as efficiently as possible.
22
+ Different choices of initialization and update procedure will result
23
+ in different quasi-Newton strategies.
24
+
25
+ Four methods should be implemented in derived classes: ``initialize``,
26
+ ``update``, ``dot`` and ``get_matrix``.
27
+
28
+ Notes
29
+ -----
30
+ Any instance of a class that implements this interface,
31
+ can be accepted by the method ``minimize`` and used by
32
+ the compatible solvers to approximate the Hessian (or
33
+ inverse Hessian) used by the optimization algorithms.
34
+ """
35
+
36
+ def initialize(self, n, approx_type):
37
+ """Initialize internal matrix.
38
+
39
+ Allocate internal memory for storing and updating
40
+ the Hessian or its inverse.
41
+
42
+ Parameters
43
+ ----------
44
+ n : int
45
+ Problem dimension.
46
+ approx_type : {'hess', 'inv_hess'}
47
+ Selects either the Hessian or the inverse Hessian.
48
+ When set to 'hess' the Hessian will be stored and updated.
49
+ When set to 'inv_hess' its inverse will be used instead.
50
+ """
51
+ raise NotImplementedError("The method ``initialize(n, approx_type)``"
52
+ " is not implemented.")
53
+
54
+ def update(self, delta_x, delta_grad):
55
+ """Update internal matrix.
56
+
57
+ Update Hessian matrix or its inverse (depending on how 'approx_type'
58
+ is defined) using information about the last evaluated points.
59
+
60
+ Parameters
61
+ ----------
62
+ delta_x : ndarray
63
+ The difference between two points the gradient
64
+ function have been evaluated at: ``delta_x = x2 - x1``.
65
+ delta_grad : ndarray
66
+ The difference between the gradients:
67
+ ``delta_grad = grad(x2) - grad(x1)``.
68
+ """
69
+ raise NotImplementedError("The method ``update(delta_x, delta_grad)``"
70
+ " is not implemented.")
71
+
72
+ def dot(self, p):
73
+ """Compute the product of the internal matrix with the given vector.
74
+
75
+ Parameters
76
+ ----------
77
+ p : array_like
78
+ 1-D array representing a vector.
79
+
80
+ Returns
81
+ -------
82
+ Hp : array
83
+ 1-D represents the result of multiplying the approximation matrix
84
+ by vector p.
85
+ """
86
+ raise NotImplementedError("The method ``dot(p)``"
87
+ " is not implemented.")
88
+
89
+ def get_matrix(self):
90
+ """Return current internal matrix.
91
+
92
+ Returns
93
+ -------
94
+ H : ndarray, shape (n, n)
95
+ Dense matrix containing either the Hessian
96
+ or its inverse (depending on how 'approx_type'
97
+ is defined).
98
+ """
99
+ raise NotImplementedError("The method ``get_matrix(p)``"
100
+ " is not implemented.")
101
+
102
+
103
+ class FullHessianUpdateStrategy(HessianUpdateStrategy):
104
+ """Hessian update strategy with full dimensional internal representation.
105
+ """
106
+ _syr = get_blas_funcs('syr', dtype='d') # Symmetric rank 1 update
107
+ _syr2 = get_blas_funcs('syr2', dtype='d') # Symmetric rank 2 update
108
+ # Symmetric matrix-vector product
109
+ _symv = get_blas_funcs('symv', dtype='d')
110
+
111
+ def __init__(self, init_scale='auto'):
112
+ self.init_scale = init_scale
113
+ # Until initialize is called we can't really use the class,
114
+ # so it makes sense to set everything to None.
115
+ self.first_iteration = None
116
+ self.approx_type = None
117
+ self.B = None
118
+ self.H = None
119
+
120
+ def initialize(self, n, approx_type):
121
+ """Initialize internal matrix.
122
+
123
+ Allocate internal memory for storing and updating
124
+ the Hessian or its inverse.
125
+
126
+ Parameters
127
+ ----------
128
+ n : int
129
+ Problem dimension.
130
+ approx_type : {'hess', 'inv_hess'}
131
+ Selects either the Hessian or the inverse Hessian.
132
+ When set to 'hess' the Hessian will be stored and updated.
133
+ When set to 'inv_hess' its inverse will be used instead.
134
+ """
135
+ self.first_iteration = True
136
+ self.n = n
137
+ self.approx_type = approx_type
138
+ if approx_type not in ('hess', 'inv_hess'):
139
+ raise ValueError("`approx_type` must be 'hess' or 'inv_hess'.")
140
+ # Create matrix
141
+ if self.approx_type == 'hess':
142
+ self.B = np.eye(n, dtype=float)
143
+ else:
144
+ self.H = np.eye(n, dtype=float)
145
+
146
+ def _auto_scale(self, delta_x, delta_grad):
147
+ # Heuristic to scale matrix at first iteration.
148
+ # Described in Nocedal and Wright "Numerical Optimization"
149
+ # p.143 formula (6.20).
150
+ s_norm2 = np.dot(delta_x, delta_x)
151
+ y_norm2 = np.dot(delta_grad, delta_grad)
152
+ ys = np.abs(np.dot(delta_grad, delta_x))
153
+ if ys == 0.0 or y_norm2 == 0 or s_norm2 == 0:
154
+ return 1
155
+ if self.approx_type == 'hess':
156
+ return y_norm2 / ys
157
+ else:
158
+ return ys / y_norm2
159
+
160
+ def _update_implementation(self, delta_x, delta_grad):
161
+ raise NotImplementedError("The method ``_update_implementation``"
162
+ " is not implemented.")
163
+
164
+ def update(self, delta_x, delta_grad):
165
+ """Update internal matrix.
166
+
167
+ Update Hessian matrix or its inverse (depending on how 'approx_type'
168
+ is defined) using information about the last evaluated points.
169
+
170
+ Parameters
171
+ ----------
172
+ delta_x : ndarray
173
+ The difference between two points the gradient
174
+ function have been evaluated at: ``delta_x = x2 - x1``.
175
+ delta_grad : ndarray
176
+ The difference between the gradients:
177
+ ``delta_grad = grad(x2) - grad(x1)``.
178
+ """
179
+ if np.all(delta_x == 0.0):
180
+ return
181
+ if np.all(delta_grad == 0.0):
182
+ warn('delta_grad == 0.0. Check if the approximated '
183
+ 'function is linear. If the function is linear '
184
+ 'better results can be obtained by defining the '
185
+ 'Hessian as zero instead of using quasi-Newton '
186
+ 'approximations.',
187
+ UserWarning, stacklevel=2)
188
+ return
189
+ if self.first_iteration:
190
+ # Get user specific scale
191
+ if isinstance(self.init_scale, str) and self.init_scale == "auto":
192
+ scale = self._auto_scale(delta_x, delta_grad)
193
+ else:
194
+ scale = self.init_scale
195
+
196
+ # Check for complex: numpy will silently cast a complex array to
197
+ # a real one but not so for scalar as it raises a TypeError.
198
+ # Checking here brings a consistent behavior.
199
+ replace = False
200
+ if np.size(scale) == 1:
201
+ # to account for the legacy behavior having the exact same cast
202
+ scale = float(scale)
203
+ elif np.iscomplexobj(scale):
204
+ raise TypeError("init_scale contains complex elements, "
205
+ "must be real.")
206
+ else: # test explicitly for allowed shapes and values
207
+ replace = True
208
+ if self.approx_type == 'hess':
209
+ shape = np.shape(self.B)
210
+ dtype = self.B.dtype
211
+ else:
212
+ shape = np.shape(self.H)
213
+ dtype = self.H.dtype
214
+ # copy, will replace the original
215
+ scale = np.array(scale, dtype=dtype, copy=True)
216
+
217
+ # it has to match the shape of the matrix for the multiplication,
218
+ # no implicit broadcasting is allowed
219
+ if shape != (init_shape := np.shape(scale)):
220
+ raise ValueError("If init_scale is an array, it must have the "
221
+ f"dimensions of the hess/inv_hess: {shape}."
222
+ f" Got {init_shape}.")
223
+ if not issymmetric(scale):
224
+ raise ValueError("If init_scale is an array, it must be"
225
+ " symmetric (passing scipy.linalg.issymmetric)"
226
+ " to be an approximation of a hess/inv_hess.")
227
+
228
+ # Scale initial matrix with ``scale * np.eye(n)`` or replace
229
+ # This is not ideal, we could assign the scale directly in
230
+ # initialize, but we would need to
231
+ if self.approx_type == 'hess':
232
+ if replace:
233
+ self.B = scale
234
+ else:
235
+ self.B *= scale
236
+ else:
237
+ if replace:
238
+ self.H = scale
239
+ else:
240
+ self.H *= scale
241
+ self.first_iteration = False
242
+ self._update_implementation(delta_x, delta_grad)
243
+
244
+ def dot(self, p):
245
+ """Compute the product of the internal matrix with the given vector.
246
+
247
+ Parameters
248
+ ----------
249
+ p : array_like
250
+ 1-D array representing a vector.
251
+
252
+ Returns
253
+ -------
254
+ Hp : array
255
+ 1-D represents the result of multiplying the approximation matrix
256
+ by vector p.
257
+ """
258
+ if self.approx_type == 'hess':
259
+ return self._symv(1, self.B, p)
260
+ else:
261
+ return self._symv(1, self.H, p)
262
+
263
+ def get_matrix(self):
264
+ """Return the current internal matrix.
265
+
266
+ Returns
267
+ -------
268
+ M : ndarray, shape (n, n)
269
+ Dense matrix containing either the Hessian or its inverse
270
+ (depending on how `approx_type` was defined).
271
+ """
272
+ if self.approx_type == 'hess':
273
+ M = np.copy(self.B)
274
+ else:
275
+ M = np.copy(self.H)
276
+ li = np.tril_indices_from(M, k=-1)
277
+ M[li] = M.T[li]
278
+ return M
279
+
280
+
281
+ class BFGS(FullHessianUpdateStrategy):
282
+ """Broyden-Fletcher-Goldfarb-Shanno (BFGS) Hessian update strategy.
283
+
284
+ Parameters
285
+ ----------
286
+ exception_strategy : {'skip_update', 'damp_update'}, optional
287
+ Define how to proceed when the curvature condition is violated.
288
+ Set it to 'skip_update' to just skip the update. Or, alternatively,
289
+ set it to 'damp_update' to interpolate between the actual BFGS
290
+ result and the unmodified matrix. Both exceptions strategies
291
+ are explained in [1]_, p.536-537.
292
+ min_curvature : float
293
+ This number, scaled by a normalization factor, defines the
294
+ minimum curvature ``dot(delta_grad, delta_x)`` allowed to go
295
+ unaffected by the exception strategy. By default is equal to
296
+ 1e-8 when ``exception_strategy = 'skip_update'`` and equal
297
+ to 0.2 when ``exception_strategy = 'damp_update'``.
298
+ init_scale : {float, np.array, 'auto'}
299
+ This parameter can be used to initialize the Hessian or its
300
+ inverse. When a float is given, the relevant array is initialized
301
+ to ``np.eye(n) * init_scale``, where ``n`` is the problem dimension.
302
+ Alternatively, if a precisely ``(n, n)`` shaped, symmetric array is given,
303
+ this array will be used. Otherwise an error is generated.
304
+ Set it to 'auto' in order to use an automatic heuristic for choosing
305
+ the initial scale. The heuristic is described in [1]_, p.143.
306
+ The default is 'auto'.
307
+
308
+ Notes
309
+ -----
310
+ The update is based on the description in [1]_, p.140.
311
+
312
+ References
313
+ ----------
314
+ .. [1] Nocedal, Jorge, and Stephen J. Wright. "Numerical optimization"
315
+ Second Edition (2006).
316
+ """
317
+
318
+ def __init__(self, exception_strategy='skip_update', min_curvature=None,
319
+ init_scale='auto'):
320
+ if exception_strategy == 'skip_update':
321
+ if min_curvature is not None:
322
+ self.min_curvature = min_curvature
323
+ else:
324
+ self.min_curvature = 1e-8
325
+ elif exception_strategy == 'damp_update':
326
+ if min_curvature is not None:
327
+ self.min_curvature = min_curvature
328
+ else:
329
+ self.min_curvature = 0.2
330
+ else:
331
+ raise ValueError("`exception_strategy` must be 'skip_update' "
332
+ "or 'damp_update'.")
333
+
334
+ super().__init__(init_scale)
335
+ self.exception_strategy = exception_strategy
336
+
337
+ def _update_inverse_hessian(self, ys, Hy, yHy, s):
338
+ """Update the inverse Hessian matrix.
339
+
340
+ BFGS update using the formula:
341
+
342
+ ``H <- H + ((H*y).T*y + s.T*y)/(s.T*y)^2 * (s*s.T)
343
+ - 1/(s.T*y) * ((H*y)*s.T + s*(H*y).T)``
344
+
345
+ where ``s = delta_x`` and ``y = delta_grad``. This formula is
346
+ equivalent to (6.17) in [1]_ written in a more efficient way
347
+ for implementation.
348
+
349
+ References
350
+ ----------
351
+ .. [1] Nocedal, Jorge, and Stephen J. Wright. "Numerical optimization"
352
+ Second Edition (2006).
353
+ """
354
+ self.H = self._syr2(-1.0 / ys, s, Hy, a=self.H)
355
+ self.H = self._syr((ys + yHy) / ys ** 2, s, a=self.H)
356
+
357
+ def _update_hessian(self, ys, Bs, sBs, y):
358
+ """Update the Hessian matrix.
359
+
360
+ BFGS update using the formula:
361
+
362
+ ``B <- B - (B*s)*(B*s).T/s.T*(B*s) + y*y^T/s.T*y``
363
+
364
+ where ``s`` is short for ``delta_x`` and ``y`` is short
365
+ for ``delta_grad``. Formula (6.19) in [1]_.
366
+
367
+ References
368
+ ----------
369
+ .. [1] Nocedal, Jorge, and Stephen J. Wright. "Numerical optimization"
370
+ Second Edition (2006).
371
+ """
372
+ self.B = self._syr(1.0 / ys, y, a=self.B)
373
+ self.B = self._syr(-1.0 / sBs, Bs, a=self.B)
374
+
375
+ def _update_implementation(self, delta_x, delta_grad):
376
+ # Auxiliary variables w and z
377
+ if self.approx_type == 'hess':
378
+ w = delta_x
379
+ z = delta_grad
380
+ else:
381
+ w = delta_grad
382
+ z = delta_x
383
+ # Do some common operations
384
+ wz = np.dot(w, z)
385
+ Mw = self.dot(w)
386
+ wMw = Mw.dot(w)
387
+ # Guarantee that wMw > 0 by reinitializing matrix.
388
+ # While this is always true in exact arithmetic,
389
+ # indefinite matrix may appear due to roundoff errors.
390
+ if wMw <= 0.0:
391
+ scale = self._auto_scale(delta_x, delta_grad)
392
+ # Reinitialize matrix
393
+ if self.approx_type == 'hess':
394
+ self.B = scale * np.eye(self.n, dtype=float)
395
+ else:
396
+ self.H = scale * np.eye(self.n, dtype=float)
397
+ # Do common operations for new matrix
398
+ Mw = self.dot(w)
399
+ wMw = Mw.dot(w)
400
+ # Check if curvature condition is violated
401
+ if wz <= self.min_curvature * wMw:
402
+ # If the option 'skip_update' is set
403
+ # we just skip the update when the condition
404
+ # is violated.
405
+ if self.exception_strategy == 'skip_update':
406
+ return
407
+ # If the option 'damp_update' is set we
408
+ # interpolate between the actual BFGS
409
+ # result and the unmodified matrix.
410
+ elif self.exception_strategy == 'damp_update':
411
+ update_factor = (1-self.min_curvature) / (1 - wz/wMw)
412
+ z = update_factor*z + (1-update_factor)*Mw
413
+ wz = np.dot(w, z)
414
+ # Update matrix
415
+ if self.approx_type == 'hess':
416
+ self._update_hessian(wz, Mw, wMw, z)
417
+ else:
418
+ self._update_inverse_hessian(wz, Mw, wMw, z)
419
+
420
+
421
+ class SR1(FullHessianUpdateStrategy):
422
+ """Symmetric-rank-1 Hessian update strategy.
423
+
424
+ Parameters
425
+ ----------
426
+ min_denominator : float
427
+ This number, scaled by a normalization factor,
428
+ defines the minimum denominator magnitude allowed
429
+ in the update. When the condition is violated we skip
430
+ the update. By default uses ``1e-8``.
431
+ init_scale : {float, np.array, 'auto'}, optional
432
+ This parameter can be used to initialize the Hessian or its
433
+ inverse. When a float is given, the relevant array is initialized
434
+ to ``np.eye(n) * init_scale``, where ``n`` is the problem dimension.
435
+ Alternatively, if a precisely ``(n, n)`` shaped, symmetric array is given,
436
+ this array will be used. Otherwise an error is generated.
437
+ Set it to 'auto' in order to use an automatic heuristic for choosing
438
+ the initial scale. The heuristic is described in [1]_, p.143.
439
+ The default is 'auto'.
440
+
441
+ Notes
442
+ -----
443
+ The update is based on the description in [1]_, p.144-146.
444
+
445
+ References
446
+ ----------
447
+ .. [1] Nocedal, Jorge, and Stephen J. Wright. "Numerical optimization"
448
+ Second Edition (2006).
449
+ """
450
+
451
+ def __init__(self, min_denominator=1e-8, init_scale='auto'):
452
+ self.min_denominator = min_denominator
453
+ super().__init__(init_scale)
454
+
455
+ def _update_implementation(self, delta_x, delta_grad):
456
+ # Auxiliary variables w and z
457
+ if self.approx_type == 'hess':
458
+ w = delta_x
459
+ z = delta_grad
460
+ else:
461
+ w = delta_grad
462
+ z = delta_x
463
+ # Do some common operations
464
+ Mw = self.dot(w)
465
+ z_minus_Mw = z - Mw
466
+ denominator = np.dot(w, z_minus_Mw)
467
+ # If the denominator is too small
468
+ # we just skip the update.
469
+ if np.abs(denominator) <= self.min_denominator*norm(w)*norm(z_minus_Mw):
470
+ return
471
+ # Update matrix
472
+ if self.approx_type == 'hess':
473
+ self.B = self._syr(1/denominator, z_minus_Mw, a=self.B)
474
+ else:
475
+ self.H = self._syr(1/denominator, z_minus_Mw, a=self.H)
vila/lib/python3.10/site-packages/scipy/optimize/_highs/__init__.py ADDED
File without changes
vila/lib/python3.10/site-packages/scipy/optimize/_highs/_highs_constants.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (36.1 kB). View file
 
vila/lib/python3.10/site-packages/scipy/optimize/_highs/src/cython/HConst.pxd ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # cython: language_level=3
2
+
3
+ from libcpp cimport bool
4
+ from libcpp.string cimport string
5
+
6
+ cdef extern from "HConst.h" nogil:
7
+
8
+ const int HIGHS_CONST_I_INF "kHighsIInf"
9
+ const double HIGHS_CONST_INF "kHighsInf"
10
+ const double kHighsTiny
11
+ const double kHighsZero
12
+ const int kHighsThreadLimit
13
+
14
+ cdef enum HighsDebugLevel:
15
+ HighsDebugLevel_kHighsDebugLevelNone "kHighsDebugLevelNone" = 0
16
+ HighsDebugLevel_kHighsDebugLevelCheap "kHighsDebugLevelCheap"
17
+ HighsDebugLevel_kHighsDebugLevelCostly "kHighsDebugLevelCostly"
18
+ HighsDebugLevel_kHighsDebugLevelExpensive "kHighsDebugLevelExpensive"
19
+ HighsDebugLevel_kHighsDebugLevelMin "kHighsDebugLevelMin" = HighsDebugLevel_kHighsDebugLevelNone
20
+ HighsDebugLevel_kHighsDebugLevelMax "kHighsDebugLevelMax" = HighsDebugLevel_kHighsDebugLevelExpensive
21
+
22
+ ctypedef enum HighsModelStatus:
23
+ HighsModelStatusNOTSET "HighsModelStatus::kNotset" = 0
24
+ HighsModelStatusLOAD_ERROR "HighsModelStatus::kLoadError"
25
+ HighsModelStatusMODEL_ERROR "HighsModelStatus::kModelError"
26
+ HighsModelStatusPRESOLVE_ERROR "HighsModelStatus::kPresolveError"
27
+ HighsModelStatusSOLVE_ERROR "HighsModelStatus::kSolveError"
28
+ HighsModelStatusPOSTSOLVE_ERROR "HighsModelStatus::kPostsolveError"
29
+ HighsModelStatusMODEL_EMPTY "HighsModelStatus::kModelEmpty"
30
+ HighsModelStatusOPTIMAL "HighsModelStatus::kOptimal"
31
+ HighsModelStatusINFEASIBLE "HighsModelStatus::kInfeasible"
32
+ HighsModelStatus_UNBOUNDED_OR_INFEASIBLE "HighsModelStatus::kUnboundedOrInfeasible"
33
+ HighsModelStatusUNBOUNDED "HighsModelStatus::kUnbounded"
34
+ HighsModelStatusREACHED_DUAL_OBJECTIVE_VALUE_UPPER_BOUND "HighsModelStatus::kObjectiveBound"
35
+ HighsModelStatusREACHED_OBJECTIVE_TARGET "HighsModelStatus::kObjectiveTarget"
36
+ HighsModelStatusREACHED_TIME_LIMIT "HighsModelStatus::kTimeLimit"
37
+ HighsModelStatusREACHED_ITERATION_LIMIT "HighsModelStatus::kIterationLimit"
38
+ HighsModelStatusUNKNOWN "HighsModelStatus::kUnknown"
39
+ HighsModelStatusHIGHS_MODEL_STATUS_MIN "HighsModelStatus::kMin" = HighsModelStatusNOTSET
40
+ HighsModelStatusHIGHS_MODEL_STATUS_MAX "HighsModelStatus::kMax" = HighsModelStatusUNKNOWN
41
+
42
+ cdef enum HighsBasisStatus:
43
+ HighsBasisStatusLOWER "HighsBasisStatus::kLower" = 0, # (slack) variable is at its lower bound [including fixed variables]
44
+ HighsBasisStatusBASIC "HighsBasisStatus::kBasic" # (slack) variable is basic
45
+ HighsBasisStatusUPPER "HighsBasisStatus::kUpper" # (slack) variable is at its upper bound
46
+ HighsBasisStatusZERO "HighsBasisStatus::kZero" # free variable is non-basic and set to zero
47
+ HighsBasisStatusNONBASIC "HighsBasisStatus::kNonbasic" # nonbasic with no specific bound information - useful for users and postsolve
48
+
49
+ cdef enum SolverOption:
50
+ SOLVER_OPTION_SIMPLEX "SolverOption::SOLVER_OPTION_SIMPLEX" = -1
51
+ SOLVER_OPTION_CHOOSE "SolverOption::SOLVER_OPTION_CHOOSE"
52
+ SOLVER_OPTION_IPM "SolverOption::SOLVER_OPTION_IPM"
53
+
54
+ cdef enum PrimalDualStatus:
55
+ PrimalDualStatusSTATUS_NOT_SET "PrimalDualStatus::STATUS_NOT_SET" = -1
56
+ PrimalDualStatusSTATUS_MIN "PrimalDualStatus::STATUS_MIN" = PrimalDualStatusSTATUS_NOT_SET
57
+ PrimalDualStatusSTATUS_NO_SOLUTION "PrimalDualStatus::STATUS_NO_SOLUTION"
58
+ PrimalDualStatusSTATUS_UNKNOWN "PrimalDualStatus::STATUS_UNKNOWN"
59
+ PrimalDualStatusSTATUS_INFEASIBLE_POINT "PrimalDualStatus::STATUS_INFEASIBLE_POINT"
60
+ PrimalDualStatusSTATUS_FEASIBLE_POINT "PrimalDualStatus::STATUS_FEASIBLE_POINT"
61
+ PrimalDualStatusSTATUS_MAX "PrimalDualStatus::STATUS_MAX" = PrimalDualStatusSTATUS_FEASIBLE_POINT
62
+
63
+ cdef enum HighsOptionType:
64
+ HighsOptionTypeBOOL "HighsOptionType::kBool" = 0
65
+ HighsOptionTypeINT "HighsOptionType::kInt"
66
+ HighsOptionTypeDOUBLE "HighsOptionType::kDouble"
67
+ HighsOptionTypeSTRING "HighsOptionType::kString"
68
+
69
+ # workaround for lack of enum class support in Cython < 3.x
70
+ # cdef enum class ObjSense(int):
71
+ # ObjSenseMINIMIZE "ObjSense::kMinimize" = 1
72
+ # ObjSenseMAXIMIZE "ObjSense::kMaximize" = -1
73
+
74
+ cdef cppclass ObjSense:
75
+ pass
76
+
77
+ cdef ObjSense ObjSenseMINIMIZE "ObjSense::kMinimize"
78
+ cdef ObjSense ObjSenseMAXIMIZE "ObjSense::kMaximize"
79
+
80
+ # cdef enum class MatrixFormat(int):
81
+ # MatrixFormatkColwise "MatrixFormat::kColwise" = 1
82
+ # MatrixFormatkRowwise "MatrixFormat::kRowwise"
83
+ # MatrixFormatkRowwisePartitioned "MatrixFormat::kRowwisePartitioned"
84
+
85
+ cdef cppclass MatrixFormat:
86
+ pass
87
+
88
+ cdef MatrixFormat MatrixFormatkColwise "MatrixFormat::kColwise"
89
+ cdef MatrixFormat MatrixFormatkRowwise "MatrixFormat::kRowwise"
90
+ cdef MatrixFormat MatrixFormatkRowwisePartitioned "MatrixFormat::kRowwisePartitioned"
91
+
92
+ # cdef enum class HighsVarType(int):
93
+ # kContinuous "HighsVarType::kContinuous"
94
+ # kInteger "HighsVarType::kInteger"
95
+ # kSemiContinuous "HighsVarType::kSemiContinuous"
96
+ # kSemiInteger "HighsVarType::kSemiInteger"
97
+ # kImplicitInteger "HighsVarType::kImplicitInteger"
98
+
99
+ cdef cppclass HighsVarType:
100
+ pass
101
+
102
+ cdef HighsVarType kContinuous "HighsVarType::kContinuous"
103
+ cdef HighsVarType kInteger "HighsVarType::kInteger"
104
+ cdef HighsVarType kSemiContinuous "HighsVarType::kSemiContinuous"
105
+ cdef HighsVarType kSemiInteger "HighsVarType::kSemiInteger"
106
+ cdef HighsVarType kImplicitInteger "HighsVarType::kImplicitInteger"
vila/lib/python3.10/site-packages/scipy/optimize/_highs/src/cython/Highs.pxd ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # cython: language_level=3
2
+
3
+ from libc.stdio cimport FILE
4
+
5
+ from libcpp cimport bool
6
+ from libcpp.string cimport string
7
+
8
+ from .HighsStatus cimport HighsStatus
9
+ from .HighsOptions cimport HighsOptions
10
+ from .HighsInfo cimport HighsInfo
11
+ from .HighsLp cimport (
12
+ HighsLp,
13
+ HighsSolution,
14
+ HighsBasis,
15
+ ObjSense,
16
+ )
17
+ from .HConst cimport HighsModelStatus
18
+
19
+ cdef extern from "Highs.h":
20
+ # From HiGHS/src/Highs.h
21
+ cdef cppclass Highs:
22
+ HighsStatus passHighsOptions(const HighsOptions& options)
23
+ HighsStatus passModel(const HighsLp& lp)
24
+ HighsStatus run()
25
+ HighsStatus setHighsLogfile(FILE* logfile)
26
+ HighsStatus setHighsOutput(FILE* output)
27
+ HighsStatus writeHighsOptions(const string filename, const bool report_only_non_default_values = true)
28
+
29
+ # split up for cython below
30
+ #const HighsModelStatus& getModelStatus(const bool scaled_model = False) const
31
+ const HighsModelStatus & getModelStatus() const
32
+
33
+ const HighsInfo& getHighsInfo "getInfo" () const
34
+ string modelStatusToString(const HighsModelStatus model_status) const
35
+ #HighsStatus getHighsInfoValue(const string& info, int& value)
36
+ HighsStatus getHighsInfoValue(const string& info, double& value) const
37
+ const HighsOptions& getHighsOptions() const
38
+
39
+ const HighsLp& getLp() const
40
+
41
+ HighsStatus writeSolution(const string filename, const bool pretty) const
42
+
43
+ HighsStatus setBasis()
44
+ const HighsSolution& getSolution() const
45
+ const HighsBasis& getBasis() const
46
+
47
+ bool changeObjectiveSense(const ObjSense sense)
48
+
49
+ HighsStatus setHighsOptionValueBool "setOptionValue" (const string & option, const bool value)
50
+ HighsStatus setHighsOptionValueInt "setOptionValue" (const string & option, const int value)
51
+ HighsStatus setHighsOptionValueStr "setOptionValue" (const string & option, const string & value)
52
+ HighsStatus setHighsOptionValueDbl "setOptionValue" (const string & option, const double value)
53
+
54
+ string primalDualStatusToString(const int primal_dual_status)
55
+
56
+ void resetGlobalScheduler(bool blocking)
vila/lib/python3.10/site-packages/scipy/optimize/_highs/src/cython/HighsInfo.pxd ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # cython: language_level=3
2
+
3
+ cdef extern from "HighsInfo.h" nogil:
4
+ # From HiGHS/src/lp_data/HighsInfo.h
5
+ cdef cppclass HighsInfo:
6
+ # Inherited from HighsInfoStruct:
7
+ int mip_node_count
8
+ int simplex_iteration_count
9
+ int ipm_iteration_count
10
+ int crossover_iteration_count
11
+ int primal_solution_status
12
+ int dual_solution_status
13
+ int basis_validity
14
+ double objective_function_value
15
+ double mip_dual_bound
16
+ double mip_gap
17
+ int num_primal_infeasibilities
18
+ double max_primal_infeasibility
19
+ double sum_primal_infeasibilities
20
+ int num_dual_infeasibilities
21
+ double max_dual_infeasibility
22
+ double sum_dual_infeasibilities
vila/lib/python3.10/site-packages/scipy/optimize/_highs/src/cython/HighsLp.pxd ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # cython: language_level=3
2
+
3
+ from libcpp cimport bool
4
+ from libcpp.string cimport string
5
+ from libcpp.vector cimport vector
6
+
7
+ from .HConst cimport HighsBasisStatus, ObjSense, HighsVarType
8
+ from .HighsSparseMatrix cimport HighsSparseMatrix
9
+
10
+
11
+ cdef extern from "HighsLp.h" nogil:
12
+ # From HiGHS/src/lp_data/HighsLp.h
13
+ cdef cppclass HighsLp:
14
+ int num_col_
15
+ int num_row_
16
+
17
+ vector[double] col_cost_
18
+ vector[double] col_lower_
19
+ vector[double] col_upper_
20
+ vector[double] row_lower_
21
+ vector[double] row_upper_
22
+
23
+ HighsSparseMatrix a_matrix_
24
+
25
+ ObjSense sense_
26
+ double offset_
27
+
28
+ string model_name_
29
+
30
+ vector[string] row_names_
31
+ vector[string] col_names_
32
+
33
+ vector[HighsVarType] integrality_
34
+
35
+ bool isMip() const
36
+
37
+ cdef cppclass HighsSolution:
38
+ vector[double] col_value
39
+ vector[double] col_dual
40
+ vector[double] row_value
41
+ vector[double] row_dual
42
+
43
+ cdef cppclass HighsBasis:
44
+ bool valid_
45
+ vector[HighsBasisStatus] col_status
46
+ vector[HighsBasisStatus] row_status
vila/lib/python3.10/site-packages/scipy/optimize/_highs/src/cython/HighsLpUtils.pxd ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # cython: language_level=3
2
+
3
+ from .HighsStatus cimport HighsStatus
4
+ from .HighsLp cimport HighsLp
5
+ from .HighsOptions cimport HighsOptions
6
+
7
+ cdef extern from "HighsLpUtils.h" nogil:
8
+ # From HiGHS/src/lp_data/HighsLpUtils.h
9
+ HighsStatus assessLp(HighsLp& lp, const HighsOptions& options)
vila/lib/python3.10/site-packages/scipy/optimize/_highs/src/cython/HighsModelUtils.pxd ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # cython: language_level=3
2
+
3
+ from libcpp.string cimport string
4
+
5
+ from .HConst cimport HighsModelStatus
6
+
7
+ cdef extern from "HighsModelUtils.h" nogil:
8
+ # From HiGHS/src/lp_data/HighsModelUtils.h
9
+ string utilHighsModelStatusToString(const HighsModelStatus model_status)
10
+ string utilBasisStatusToString(const int primal_dual_status)
vila/lib/python3.10/site-packages/scipy/optimize/_highs/src/cython/HighsOptions.pxd ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # cython: language_level=3
2
+
3
+ from libc.stdio cimport FILE
4
+
5
+ from libcpp cimport bool
6
+ from libcpp.string cimport string
7
+ from libcpp.vector cimport vector
8
+
9
+ from .HConst cimport HighsOptionType
10
+
11
+ cdef extern from "HighsOptions.h" nogil:
12
+
13
+ cdef cppclass OptionRecord:
14
+ HighsOptionType type
15
+ string name
16
+ string description
17
+ bool advanced
18
+
19
+ cdef cppclass OptionRecordBool(OptionRecord):
20
+ bool* value
21
+ bool default_value
22
+
23
+ cdef cppclass OptionRecordInt(OptionRecord):
24
+ int* value
25
+ int lower_bound
26
+ int default_value
27
+ int upper_bound
28
+
29
+ cdef cppclass OptionRecordDouble(OptionRecord):
30
+ double* value
31
+ double lower_bound
32
+ double default_value
33
+ double upper_bound
34
+
35
+ cdef cppclass OptionRecordString(OptionRecord):
36
+ string* value
37
+ string default_value
38
+
39
+ cdef cppclass HighsOptions:
40
+ # From HighsOptionsStruct:
41
+
42
+ # Options read from the command line
43
+ string model_file
44
+ string presolve
45
+ string solver
46
+ string parallel
47
+ double time_limit
48
+ string options_file
49
+
50
+ # Options read from the file
51
+ double infinite_cost
52
+ double infinite_bound
53
+ double small_matrix_value
54
+ double large_matrix_value
55
+ double primal_feasibility_tolerance
56
+ double dual_feasibility_tolerance
57
+ double ipm_optimality_tolerance
58
+ double dual_objective_value_upper_bound
59
+ int highs_debug_level
60
+ int simplex_strategy
61
+ int simplex_scale_strategy
62
+ int simplex_crash_strategy
63
+ int simplex_dual_edge_weight_strategy
64
+ int simplex_primal_edge_weight_strategy
65
+ int simplex_iteration_limit
66
+ int simplex_update_limit
67
+ int ipm_iteration_limit
68
+ int highs_min_threads
69
+ int highs_max_threads
70
+ int message_level
71
+ string solution_file
72
+ bool write_solution_to_file
73
+ bool write_solution_pretty
74
+
75
+ # Advanced options
76
+ bool run_crossover
77
+ bool mps_parser_type_free
78
+ int keep_n_rows
79
+ int allowed_simplex_matrix_scale_factor
80
+ int allowed_simplex_cost_scale_factor
81
+ int simplex_dualise_strategy
82
+ int simplex_permute_strategy
83
+ int dual_simplex_cleanup_strategy
84
+ int simplex_price_strategy
85
+ int dual_chuzc_sort_strategy
86
+ bool simplex_initial_condition_check
87
+ double simplex_initial_condition_tolerance
88
+ double dual_steepest_edge_weight_log_error_threshhold
89
+ double dual_simplex_cost_perturbation_multiplier
90
+ double start_crossover_tolerance
91
+ bool less_infeasible_DSE_check
92
+ bool less_infeasible_DSE_choose_row
93
+ bool use_original_HFactor_logic
94
+
95
+ # Options for MIP solver
96
+ int mip_max_nodes
97
+ int mip_report_level
98
+
99
+ # Switch for MIP solver
100
+ bool mip
101
+
102
+ # Options for HighsPrintMessage and HighsLogMessage
103
+ FILE* logfile
104
+ FILE* output
105
+ int message_level
106
+ string solution_file
107
+ bool write_solution_to_file
108
+ bool write_solution_pretty
109
+
110
+ vector[OptionRecord*] records
vila/lib/python3.10/site-packages/scipy/optimize/_highs/src/cython/HighsRuntimeOptions.pxd ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # cython: language_level=3
2
+
3
+ from libcpp cimport bool
4
+
5
+ from .HighsOptions cimport HighsOptions
6
+
7
+ cdef extern from "HighsRuntimeOptions.h" nogil:
8
+ # From HiGHS/src/lp_data/HighsRuntimeOptions.h
9
+ bool loadOptions(int argc, char** argv, HighsOptions& options)
vila/lib/python3.10/site-packages/scipy/optimize/_highs/src/cython/HighsStatus.pxd ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # cython: language_level=3
2
+
3
+ from libcpp.string cimport string
4
+
5
+ cdef extern from "HighsStatus.h" nogil:
6
+ ctypedef enum HighsStatus:
7
+ HighsStatusError "HighsStatus::kError" = -1
8
+ HighsStatusOK "HighsStatus::kOk" = 0
9
+ HighsStatusWarning "HighsStatus::kWarning" = 1
10
+
11
+
12
+ string highsStatusToString(HighsStatus status)
vila/lib/python3.10/site-packages/scipy/optimize/_lbfgsb_py.py ADDED
@@ -0,0 +1,543 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Functions
3
+ ---------
4
+ .. autosummary::
5
+ :toctree: generated/
6
+
7
+ fmin_l_bfgs_b
8
+
9
+ """
10
+
11
+ ## License for the Python wrapper
12
+ ## ==============================
13
+
14
+ ## Copyright (c) 2004 David M. Cooke <cookedm@physics.mcmaster.ca>
15
+
16
+ ## Permission is hereby granted, free of charge, to any person obtaining a
17
+ ## copy of this software and associated documentation files (the "Software"),
18
+ ## to deal in the Software without restriction, including without limitation
19
+ ## the rights to use, copy, modify, merge, publish, distribute, sublicense,
20
+ ## and/or sell copies of the Software, and to permit persons to whom the
21
+ ## Software is furnished to do so, subject to the following conditions:
22
+
23
+ ## The above copyright notice and this permission notice shall be included in
24
+ ## all copies or substantial portions of the Software.
25
+
26
+ ## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
27
+ ## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
28
+ ## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
29
+ ## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
30
+ ## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
31
+ ## FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
32
+ ## DEALINGS IN THE SOFTWARE.
33
+
34
+ ## Modifications by Travis Oliphant and Enthought, Inc. for inclusion in SciPy
35
+
36
+ import numpy as np
37
+ from numpy import array, asarray, float64, zeros
38
+ from . import _lbfgsb
39
+ from ._optimize import (MemoizeJac, OptimizeResult, _call_callback_maybe_halt,
40
+ _wrap_callback, _check_unknown_options,
41
+ _prepare_scalar_function)
42
+ from ._constraints import old_bound_to_new
43
+
44
+ from scipy.sparse.linalg import LinearOperator
45
+
46
+ __all__ = ['fmin_l_bfgs_b', 'LbfgsInvHessProduct']
47
+
48
+
49
+ def fmin_l_bfgs_b(func, x0, fprime=None, args=(),
50
+ approx_grad=0,
51
+ bounds=None, m=10, factr=1e7, pgtol=1e-5,
52
+ epsilon=1e-8,
53
+ iprint=-1, maxfun=15000, maxiter=15000, disp=None,
54
+ callback=None, maxls=20):
55
+ """
56
+ Minimize a function func using the L-BFGS-B algorithm.
57
+
58
+ Parameters
59
+ ----------
60
+ func : callable f(x,*args)
61
+ Function to minimize.
62
+ x0 : ndarray
63
+ Initial guess.
64
+ fprime : callable fprime(x,*args), optional
65
+ The gradient of `func`. If None, then `func` returns the function
66
+ value and the gradient (``f, g = func(x, *args)``), unless
67
+ `approx_grad` is True in which case `func` returns only ``f``.
68
+ args : sequence, optional
69
+ Arguments to pass to `func` and `fprime`.
70
+ approx_grad : bool, optional
71
+ Whether to approximate the gradient numerically (in which case
72
+ `func` returns only the function value).
73
+ bounds : list, optional
74
+ ``(min, max)`` pairs for each element in ``x``, defining
75
+ the bounds on that parameter. Use None or +-inf for one of ``min`` or
76
+ ``max`` when there is no bound in that direction.
77
+ m : int, optional
78
+ The maximum number of variable metric corrections
79
+ used to define the limited memory matrix. (The limited memory BFGS
80
+ method does not store the full hessian but uses this many terms in an
81
+ approximation to it.)
82
+ factr : float, optional
83
+ The iteration stops when
84
+ ``(f^k - f^{k+1})/max{|f^k|,|f^{k+1}|,1} <= factr * eps``,
85
+ where ``eps`` is the machine precision, which is automatically
86
+ generated by the code. Typical values for `factr` are: 1e12 for
87
+ low accuracy; 1e7 for moderate accuracy; 10.0 for extremely
88
+ high accuracy. See Notes for relationship to `ftol`, which is exposed
89
+ (instead of `factr`) by the `scipy.optimize.minimize` interface to
90
+ L-BFGS-B.
91
+ pgtol : float, optional
92
+ The iteration will stop when
93
+ ``max{|proj g_i | i = 1, ..., n} <= pgtol``
94
+ where ``proj g_i`` is the i-th component of the projected gradient.
95
+ epsilon : float, optional
96
+ Step size used when `approx_grad` is True, for numerically
97
+ calculating the gradient
98
+ iprint : int, optional
99
+ Controls the frequency of output. ``iprint < 0`` means no output;
100
+ ``iprint = 0`` print only one line at the last iteration;
101
+ ``0 < iprint < 99`` print also f and ``|proj g|`` every iprint iterations;
102
+ ``iprint = 99`` print details of every iteration except n-vectors;
103
+ ``iprint = 100`` print also the changes of active set and final x;
104
+ ``iprint > 100`` print details of every iteration including x and g.
105
+ disp : int, optional
106
+ If zero, then no output. If a positive number, then this over-rides
107
+ `iprint` (i.e., `iprint` gets the value of `disp`).
108
+ maxfun : int, optional
109
+ Maximum number of function evaluations. Note that this function
110
+ may violate the limit because of evaluating gradients by numerical
111
+ differentiation.
112
+ maxiter : int, optional
113
+ Maximum number of iterations.
114
+ callback : callable, optional
115
+ Called after each iteration, as ``callback(xk)``, where ``xk`` is the
116
+ current parameter vector.
117
+ maxls : int, optional
118
+ Maximum number of line search steps (per iteration). Default is 20.
119
+
120
+ Returns
121
+ -------
122
+ x : array_like
123
+ Estimated position of the minimum.
124
+ f : float
125
+ Value of `func` at the minimum.
126
+ d : dict
127
+ Information dictionary.
128
+
129
+ * d['warnflag'] is
130
+
131
+ - 0 if converged,
132
+ - 1 if too many function evaluations or too many iterations,
133
+ - 2 if stopped for another reason, given in d['task']
134
+
135
+ * d['grad'] is the gradient at the minimum (should be 0 ish)
136
+ * d['funcalls'] is the number of function calls made.
137
+ * d['nit'] is the number of iterations.
138
+
139
+ See also
140
+ --------
141
+ minimize: Interface to minimization algorithms for multivariate
142
+ functions. See the 'L-BFGS-B' `method` in particular. Note that the
143
+ `ftol` option is made available via that interface, while `factr` is
144
+ provided via this interface, where `factr` is the factor multiplying
145
+ the default machine floating-point precision to arrive at `ftol`:
146
+ ``ftol = factr * numpy.finfo(float).eps``.
147
+
148
+ Notes
149
+ -----
150
+ License of L-BFGS-B (FORTRAN code):
151
+
152
+ The version included here (in fortran code) is 3.0
153
+ (released April 25, 2011). It was written by Ciyou Zhu, Richard Byrd,
154
+ and Jorge Nocedal <nocedal@ece.nwu.edu>. It carries the following
155
+ condition for use:
156
+
157
+ This software is freely available, but we expect that all publications
158
+ describing work using this software, or all commercial products using it,
159
+ quote at least one of the references given below. This software is released
160
+ under the BSD License.
161
+
162
+ References
163
+ ----------
164
+ * R. H. Byrd, P. Lu and J. Nocedal. A Limited Memory Algorithm for Bound
165
+ Constrained Optimization, (1995), SIAM Journal on Scientific and
166
+ Statistical Computing, 16, 5, pp. 1190-1208.
167
+ * C. Zhu, R. H. Byrd and J. Nocedal. L-BFGS-B: Algorithm 778: L-BFGS-B,
168
+ FORTRAN routines for large scale bound constrained optimization (1997),
169
+ ACM Transactions on Mathematical Software, 23, 4, pp. 550 - 560.
170
+ * J.L. Morales and J. Nocedal. L-BFGS-B: Remark on Algorithm 778: L-BFGS-B,
171
+ FORTRAN routines for large scale bound constrained optimization (2011),
172
+ ACM Transactions on Mathematical Software, 38, 1.
173
+
174
+ Examples
175
+ --------
176
+ Solve a linear regression problem via `fmin_l_bfgs_b`. To do this, first we define
177
+ an objective function ``f(m, b) = (y - y_model)**2``, where `y` describes the
178
+ observations and `y_model` the prediction of the linear model as
179
+ ``y_model = m*x + b``. The bounds for the parameters, ``m`` and ``b``, are arbitrarily
180
+ chosen as ``(0,5)`` and ``(5,10)`` for this example.
181
+
182
+ >>> import numpy as np
183
+ >>> from scipy.optimize import fmin_l_bfgs_b
184
+ >>> X = np.arange(0, 10, 1)
185
+ >>> M = 2
186
+ >>> B = 3
187
+ >>> Y = M * X + B
188
+ >>> def func(parameters, *args):
189
+ ... x = args[0]
190
+ ... y = args[1]
191
+ ... m, b = parameters
192
+ ... y_model = m*x + b
193
+ ... error = sum(np.power((y - y_model), 2))
194
+ ... return error
195
+
196
+ >>> initial_values = np.array([0.0, 1.0])
197
+
198
+ >>> x_opt, f_opt, info = fmin_l_bfgs_b(func, x0=initial_values, args=(X, Y),
199
+ ... approx_grad=True)
200
+ >>> x_opt, f_opt
201
+ array([1.99999999, 3.00000006]), 1.7746231151323805e-14 # may vary
202
+
203
+ The optimized parameters in ``x_opt`` agree with the ground truth parameters
204
+ ``m`` and ``b``. Next, let us perform a bound contrained optimization using the `bounds`
205
+ parameter.
206
+
207
+ >>> bounds = [(0, 5), (5, 10)]
208
+ >>> x_opt, f_op, info = fmin_l_bfgs_b(func, x0=initial_values, args=(X, Y),
209
+ ... approx_grad=True, bounds=bounds)
210
+ >>> x_opt, f_opt
211
+ array([1.65990508, 5.31649385]), 15.721334516453945 # may vary
212
+ """
213
+ # handle fprime/approx_grad
214
+ if approx_grad:
215
+ fun = func
216
+ jac = None
217
+ elif fprime is None:
218
+ fun = MemoizeJac(func)
219
+ jac = fun.derivative
220
+ else:
221
+ fun = func
222
+ jac = fprime
223
+
224
+ # build options
225
+ callback = _wrap_callback(callback)
226
+ opts = {'disp': disp,
227
+ 'iprint': iprint,
228
+ 'maxcor': m,
229
+ 'ftol': factr * np.finfo(float).eps,
230
+ 'gtol': pgtol,
231
+ 'eps': epsilon,
232
+ 'maxfun': maxfun,
233
+ 'maxiter': maxiter,
234
+ 'callback': callback,
235
+ 'maxls': maxls}
236
+
237
+ res = _minimize_lbfgsb(fun, x0, args=args, jac=jac, bounds=bounds,
238
+ **opts)
239
+ d = {'grad': res['jac'],
240
+ 'task': res['message'],
241
+ 'funcalls': res['nfev'],
242
+ 'nit': res['nit'],
243
+ 'warnflag': res['status']}
244
+ f = res['fun']
245
+ x = res['x']
246
+
247
+ return x, f, d
248
+
249
+
250
+ def _minimize_lbfgsb(fun, x0, args=(), jac=None, bounds=None,
251
+ disp=None, maxcor=10, ftol=2.2204460492503131e-09,
252
+ gtol=1e-5, eps=1e-8, maxfun=15000, maxiter=15000,
253
+ iprint=-1, callback=None, maxls=20,
254
+ finite_diff_rel_step=None, **unknown_options):
255
+ """
256
+ Minimize a scalar function of one or more variables using the L-BFGS-B
257
+ algorithm.
258
+
259
+ Options
260
+ -------
261
+ disp : None or int
262
+ If `disp is None` (the default), then the supplied version of `iprint`
263
+ is used. If `disp is not None`, then it overrides the supplied version
264
+ of `iprint` with the behaviour you outlined.
265
+ maxcor : int
266
+ The maximum number of variable metric corrections used to
267
+ define the limited memory matrix. (The limited memory BFGS
268
+ method does not store the full hessian but uses this many terms
269
+ in an approximation to it.)
270
+ ftol : float
271
+ The iteration stops when ``(f^k -
272
+ f^{k+1})/max{|f^k|,|f^{k+1}|,1} <= ftol``.
273
+ gtol : float
274
+ The iteration will stop when ``max{|proj g_i | i = 1, ..., n}
275
+ <= gtol`` where ``proj g_i`` is the i-th component of the
276
+ projected gradient.
277
+ eps : float or ndarray
278
+ If `jac is None` the absolute step size used for numerical
279
+ approximation of the jacobian via forward differences.
280
+ maxfun : int
281
+ Maximum number of function evaluations. Note that this function
282
+ may violate the limit because of evaluating gradients by numerical
283
+ differentiation.
284
+ maxiter : int
285
+ Maximum number of iterations.
286
+ iprint : int, optional
287
+ Controls the frequency of output. ``iprint < 0`` means no output;
288
+ ``iprint = 0`` print only one line at the last iteration;
289
+ ``0 < iprint < 99`` print also f and ``|proj g|`` every iprint iterations;
290
+ ``iprint = 99`` print details of every iteration except n-vectors;
291
+ ``iprint = 100`` print also the changes of active set and final x;
292
+ ``iprint > 100`` print details of every iteration including x and g.
293
+ maxls : int, optional
294
+ Maximum number of line search steps (per iteration). Default is 20.
295
+ finite_diff_rel_step : None or array_like, optional
296
+ If `jac in ['2-point', '3-point', 'cs']` the relative step size to
297
+ use for numerical approximation of the jacobian. The absolute step
298
+ size is computed as ``h = rel_step * sign(x) * max(1, abs(x))``,
299
+ possibly adjusted to fit into the bounds. For ``method='3-point'``
300
+ the sign of `h` is ignored. If None (default) then step is selected
301
+ automatically.
302
+
303
+ Notes
304
+ -----
305
+ The option `ftol` is exposed via the `scipy.optimize.minimize` interface,
306
+ but calling `scipy.optimize.fmin_l_bfgs_b` directly exposes `factr`. The
307
+ relationship between the two is ``ftol = factr * numpy.finfo(float).eps``.
308
+ I.e., `factr` multiplies the default machine floating-point precision to
309
+ arrive at `ftol`.
310
+
311
+ """
312
+ _check_unknown_options(unknown_options)
313
+ m = maxcor
314
+ pgtol = gtol
315
+ factr = ftol / np.finfo(float).eps
316
+
317
+ x0 = asarray(x0).ravel()
318
+ n, = x0.shape
319
+
320
+ # historically old-style bounds were/are expected by lbfgsb.
321
+ # That's still the case but we'll deal with new-style from here on,
322
+ # it's easier
323
+ if bounds is None:
324
+ pass
325
+ elif len(bounds) != n:
326
+ raise ValueError('length of x0 != length of bounds')
327
+ else:
328
+ bounds = np.array(old_bound_to_new(bounds))
329
+
330
+ # check bounds
331
+ if (bounds[0] > bounds[1]).any():
332
+ raise ValueError(
333
+ "LBFGSB - one of the lower bounds is greater than an upper bound."
334
+ )
335
+
336
+ # initial vector must lie within the bounds. Otherwise ScalarFunction and
337
+ # approx_derivative will cause problems
338
+ x0 = np.clip(x0, bounds[0], bounds[1])
339
+
340
+ if disp is not None:
341
+ if disp == 0:
342
+ iprint = -1
343
+ else:
344
+ iprint = disp
345
+
346
+ # _prepare_scalar_function can use bounds=None to represent no bounds
347
+ sf = _prepare_scalar_function(fun, x0, jac=jac, args=args, epsilon=eps,
348
+ bounds=bounds,
349
+ finite_diff_rel_step=finite_diff_rel_step)
350
+
351
+ func_and_grad = sf.fun_and_grad
352
+
353
+ fortran_int = _lbfgsb.types.intvar.dtype
354
+
355
+ nbd = zeros(n, fortran_int)
356
+ low_bnd = zeros(n, float64)
357
+ upper_bnd = zeros(n, float64)
358
+ bounds_map = {(-np.inf, np.inf): 0,
359
+ (1, np.inf): 1,
360
+ (1, 1): 2,
361
+ (-np.inf, 1): 3}
362
+
363
+ if bounds is not None:
364
+ for i in range(0, n):
365
+ l, u = bounds[0, i], bounds[1, i]
366
+ if not np.isinf(l):
367
+ low_bnd[i] = l
368
+ l = 1
369
+ if not np.isinf(u):
370
+ upper_bnd[i] = u
371
+ u = 1
372
+ nbd[i] = bounds_map[l, u]
373
+
374
+ if not maxls > 0:
375
+ raise ValueError('maxls must be positive.')
376
+
377
+ x = array(x0, float64)
378
+ f = array(0.0, float64)
379
+ g = zeros((n,), float64)
380
+ wa = zeros(2*m*n + 5*n + 11*m*m + 8*m, float64)
381
+ iwa = zeros(3*n, fortran_int)
382
+ task = zeros(1, 'S60')
383
+ csave = zeros(1, 'S60')
384
+ lsave = zeros(4, fortran_int)
385
+ isave = zeros(44, fortran_int)
386
+ dsave = zeros(29, float64)
387
+
388
+ task[:] = 'START'
389
+
390
+ n_iterations = 0
391
+
392
+ while 1:
393
+ # g may become float32 if a user provides a function that calculates
394
+ # the Jacobian in float32 (see gh-18730). The underlying Fortran code
395
+ # expects float64, so upcast it
396
+ g = g.astype(np.float64)
397
+ # x, f, g, wa, iwa, task, csave, lsave, isave, dsave = \
398
+ _lbfgsb.setulb(m, x, low_bnd, upper_bnd, nbd, f, g, factr,
399
+ pgtol, wa, iwa, task, iprint, csave, lsave,
400
+ isave, dsave, maxls)
401
+ task_str = task.tobytes()
402
+ if task_str.startswith(b'FG'):
403
+ # The minimization routine wants f and g at the current x.
404
+ # Note that interruptions due to maxfun are postponed
405
+ # until the completion of the current minimization iteration.
406
+ # Overwrite f and g:
407
+ f, g = func_and_grad(x)
408
+ elif task_str.startswith(b'NEW_X'):
409
+ # new iteration
410
+ n_iterations += 1
411
+
412
+ intermediate_result = OptimizeResult(x=x, fun=f)
413
+ if _call_callback_maybe_halt(callback, intermediate_result):
414
+ task[:] = 'STOP: CALLBACK REQUESTED HALT'
415
+ if n_iterations >= maxiter:
416
+ task[:] = 'STOP: TOTAL NO. of ITERATIONS REACHED LIMIT'
417
+ elif sf.nfev > maxfun:
418
+ task[:] = ('STOP: TOTAL NO. of f AND g EVALUATIONS '
419
+ 'EXCEEDS LIMIT')
420
+ else:
421
+ break
422
+
423
+ task_str = task.tobytes().strip(b'\x00').strip()
424
+ if task_str.startswith(b'CONV'):
425
+ warnflag = 0
426
+ elif sf.nfev > maxfun or n_iterations >= maxiter:
427
+ warnflag = 1
428
+ else:
429
+ warnflag = 2
430
+
431
+ # These two portions of the workspace are described in the mainlb
432
+ # subroutine in lbfgsb.f. See line 363.
433
+ s = wa[0: m*n].reshape(m, n)
434
+ y = wa[m*n: 2*m*n].reshape(m, n)
435
+
436
+ # See lbfgsb.f line 160 for this portion of the workspace.
437
+ # isave(31) = the total number of BFGS updates prior the current iteration;
438
+ n_bfgs_updates = isave[30]
439
+
440
+ n_corrs = min(n_bfgs_updates, maxcor)
441
+ hess_inv = LbfgsInvHessProduct(s[:n_corrs], y[:n_corrs])
442
+
443
+ task_str = task_str.decode()
444
+ return OptimizeResult(fun=f, jac=g, nfev=sf.nfev,
445
+ njev=sf.ngev,
446
+ nit=n_iterations, status=warnflag, message=task_str,
447
+ x=x, success=(warnflag == 0), hess_inv=hess_inv)
448
+
449
+
450
+ class LbfgsInvHessProduct(LinearOperator):
451
+ """Linear operator for the L-BFGS approximate inverse Hessian.
452
+
453
+ This operator computes the product of a vector with the approximate inverse
454
+ of the Hessian of the objective function, using the L-BFGS limited
455
+ memory approximation to the inverse Hessian, accumulated during the
456
+ optimization.
457
+
458
+ Objects of this class implement the ``scipy.sparse.linalg.LinearOperator``
459
+ interface.
460
+
461
+ Parameters
462
+ ----------
463
+ sk : array_like, shape=(n_corr, n)
464
+ Array of `n_corr` most recent updates to the solution vector.
465
+ (See [1]).
466
+ yk : array_like, shape=(n_corr, n)
467
+ Array of `n_corr` most recent updates to the gradient. (See [1]).
468
+
469
+ References
470
+ ----------
471
+ .. [1] Nocedal, Jorge. "Updating quasi-Newton matrices with limited
472
+ storage." Mathematics of computation 35.151 (1980): 773-782.
473
+
474
+ """
475
+
476
+ def __init__(self, sk, yk):
477
+ """Construct the operator."""
478
+ if sk.shape != yk.shape or sk.ndim != 2:
479
+ raise ValueError('sk and yk must have matching shape, (n_corrs, n)')
480
+ n_corrs, n = sk.shape
481
+
482
+ super().__init__(dtype=np.float64, shape=(n, n))
483
+
484
+ self.sk = sk
485
+ self.yk = yk
486
+ self.n_corrs = n_corrs
487
+ self.rho = 1 / np.einsum('ij,ij->i', sk, yk)
488
+
489
+ def _matvec(self, x):
490
+ """Efficient matrix-vector multiply with the BFGS matrices.
491
+
492
+ This calculation is described in Section (4) of [1].
493
+
494
+ Parameters
495
+ ----------
496
+ x : ndarray
497
+ An array with shape (n,) or (n,1).
498
+
499
+ Returns
500
+ -------
501
+ y : ndarray
502
+ The matrix-vector product
503
+
504
+ """
505
+ s, y, n_corrs, rho = self.sk, self.yk, self.n_corrs, self.rho
506
+ q = np.array(x, dtype=self.dtype, copy=True)
507
+ if q.ndim == 2 and q.shape[1] == 1:
508
+ q = q.reshape(-1)
509
+
510
+ alpha = np.empty(n_corrs)
511
+
512
+ for i in range(n_corrs-1, -1, -1):
513
+ alpha[i] = rho[i] * np.dot(s[i], q)
514
+ q = q - alpha[i]*y[i]
515
+
516
+ r = q
517
+ for i in range(n_corrs):
518
+ beta = rho[i] * np.dot(y[i], r)
519
+ r = r + s[i] * (alpha[i] - beta)
520
+
521
+ return r
522
+
523
+ def todense(self):
524
+ """Return a dense array representation of this operator.
525
+
526
+ Returns
527
+ -------
528
+ arr : ndarray, shape=(n, n)
529
+ An array with the same shape and containing
530
+ the same data represented by this `LinearOperator`.
531
+
532
+ """
533
+ s, y, n_corrs, rho = self.sk, self.yk, self.n_corrs, self.rho
534
+ I = np.eye(*self.shape, dtype=self.dtype)
535
+ Hk = I
536
+
537
+ for i in range(n_corrs):
538
+ A1 = I - s[i][:, np.newaxis] * y[i][np.newaxis, :] * rho[i]
539
+ A2 = I - y[i][:, np.newaxis] * s[i][np.newaxis, :] * rho[i]
540
+
541
+ Hk = np.dot(A1, np.dot(Hk, A2)) + (rho[i] * s[i][:, np.newaxis] *
542
+ s[i][np.newaxis, :])
543
+ return Hk
vila/lib/python3.10/site-packages/scipy/optimize/_linprog.py ADDED
@@ -0,0 +1,716 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A top-level linear programming interface.
3
+
4
+ .. versionadded:: 0.15.0
5
+
6
+ Functions
7
+ ---------
8
+ .. autosummary::
9
+ :toctree: generated/
10
+
11
+ linprog
12
+ linprog_verbose_callback
13
+ linprog_terse_callback
14
+
15
+ """
16
+
17
+ import numpy as np
18
+
19
+ from ._optimize import OptimizeResult, OptimizeWarning
20
+ from warnings import warn
21
+ from ._linprog_highs import _linprog_highs
22
+ from ._linprog_ip import _linprog_ip
23
+ from ._linprog_simplex import _linprog_simplex
24
+ from ._linprog_rs import _linprog_rs
25
+ from ._linprog_doc import (_linprog_highs_doc, _linprog_ip_doc, # noqa: F401
26
+ _linprog_rs_doc, _linprog_simplex_doc,
27
+ _linprog_highs_ipm_doc, _linprog_highs_ds_doc)
28
+ from ._linprog_util import (
29
+ _parse_linprog, _presolve, _get_Abc, _LPProblem, _autoscale,
30
+ _postsolve, _check_result, _display_summary)
31
+ from copy import deepcopy
32
+
33
+ __all__ = ['linprog', 'linprog_verbose_callback', 'linprog_terse_callback']
34
+
35
+ __docformat__ = "restructuredtext en"
36
+
37
+ LINPROG_METHODS = [
38
+ 'simplex', 'revised simplex', 'interior-point', 'highs', 'highs-ds', 'highs-ipm'
39
+ ]
40
+
41
+
42
+ def linprog_verbose_callback(res):
43
+ """
44
+ A sample callback function demonstrating the linprog callback interface.
45
+ This callback produces detailed output to sys.stdout before each iteration
46
+ and after the final iteration of the simplex algorithm.
47
+
48
+ Parameters
49
+ ----------
50
+ res : A `scipy.optimize.OptimizeResult` consisting of the following fields:
51
+
52
+ x : 1-D array
53
+ The independent variable vector which optimizes the linear
54
+ programming problem.
55
+ fun : float
56
+ Value of the objective function.
57
+ success : bool
58
+ True if the algorithm succeeded in finding an optimal solution.
59
+ slack : 1-D array
60
+ The values of the slack variables. Each slack variable corresponds
61
+ to an inequality constraint. If the slack is zero, then the
62
+ corresponding constraint is active.
63
+ con : 1-D array
64
+ The (nominally zero) residuals of the equality constraints, that is,
65
+ ``b - A_eq @ x``
66
+ phase : int
67
+ The phase of the optimization being executed. In phase 1 a basic
68
+ feasible solution is sought and the T has an additional row
69
+ representing an alternate objective function.
70
+ status : int
71
+ An integer representing the exit status of the optimization::
72
+
73
+ 0 : Optimization terminated successfully
74
+ 1 : Iteration limit reached
75
+ 2 : Problem appears to be infeasible
76
+ 3 : Problem appears to be unbounded
77
+ 4 : Serious numerical difficulties encountered
78
+
79
+ nit : int
80
+ The number of iterations performed.
81
+ message : str
82
+ A string descriptor of the exit status of the optimization.
83
+ """
84
+ x = res['x']
85
+ fun = res['fun']
86
+ phase = res['phase']
87
+ status = res['status']
88
+ nit = res['nit']
89
+ message = res['message']
90
+ complete = res['complete']
91
+
92
+ saved_printoptions = np.get_printoptions()
93
+ np.set_printoptions(linewidth=500,
94
+ formatter={'float': lambda x: f"{x: 12.4f}"})
95
+ if status:
96
+ print('--------- Simplex Early Exit -------\n')
97
+ print(f'The simplex method exited early with status {status:d}')
98
+ print(message)
99
+ elif complete:
100
+ print('--------- Simplex Complete --------\n')
101
+ print(f'Iterations required: {nit}')
102
+ else:
103
+ print(f'--------- Iteration {nit:d} ---------\n')
104
+
105
+ if nit > 0:
106
+ if phase == 1:
107
+ print('Current Pseudo-Objective Value:')
108
+ else:
109
+ print('Current Objective Value:')
110
+ print('f = ', fun)
111
+ print()
112
+ print('Current Solution Vector:')
113
+ print('x = ', x)
114
+ print()
115
+
116
+ np.set_printoptions(**saved_printoptions)
117
+
118
+
119
+ def linprog_terse_callback(res):
120
+ """
121
+ A sample callback function demonstrating the linprog callback interface.
122
+ This callback produces brief output to sys.stdout before each iteration
123
+ and after the final iteration of the simplex algorithm.
124
+
125
+ Parameters
126
+ ----------
127
+ res : A `scipy.optimize.OptimizeResult` consisting of the following fields:
128
+
129
+ x : 1-D array
130
+ The independent variable vector which optimizes the linear
131
+ programming problem.
132
+ fun : float
133
+ Value of the objective function.
134
+ success : bool
135
+ True if the algorithm succeeded in finding an optimal solution.
136
+ slack : 1-D array
137
+ The values of the slack variables. Each slack variable corresponds
138
+ to an inequality constraint. If the slack is zero, then the
139
+ corresponding constraint is active.
140
+ con : 1-D array
141
+ The (nominally zero) residuals of the equality constraints, that is,
142
+ ``b - A_eq @ x``.
143
+ phase : int
144
+ The phase of the optimization being executed. In phase 1 a basic
145
+ feasible solution is sought and the T has an additional row
146
+ representing an alternate objective function.
147
+ status : int
148
+ An integer representing the exit status of the optimization::
149
+
150
+ 0 : Optimization terminated successfully
151
+ 1 : Iteration limit reached
152
+ 2 : Problem appears to be infeasible
153
+ 3 : Problem appears to be unbounded
154
+ 4 : Serious numerical difficulties encountered
155
+
156
+ nit : int
157
+ The number of iterations performed.
158
+ message : str
159
+ A string descriptor of the exit status of the optimization.
160
+ """
161
+ nit = res['nit']
162
+ x = res['x']
163
+
164
+ if nit == 0:
165
+ print("Iter: X:")
166
+ print(f"{nit: <5d} ", end="")
167
+ print(x)
168
+
169
+
170
+ def linprog(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None,
171
+ bounds=(0, None), method='highs', callback=None,
172
+ options=None, x0=None, integrality=None):
173
+ r"""
174
+ Linear programming: minimize a linear objective function subject to linear
175
+ equality and inequality constraints.
176
+
177
+ Linear programming solves problems of the following form:
178
+
179
+ .. math::
180
+
181
+ \min_x \ & c^T x \\
182
+ \mbox{such that} \ & A_{ub} x \leq b_{ub},\\
183
+ & A_{eq} x = b_{eq},\\
184
+ & l \leq x \leq u ,
185
+
186
+ where :math:`x` is a vector of decision variables; :math:`c`,
187
+ :math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and
188
+ :math:`A_{ub}` and :math:`A_{eq}` are matrices.
189
+
190
+ Alternatively, that's:
191
+
192
+ - minimize ::
193
+
194
+ c @ x
195
+
196
+ - such that ::
197
+
198
+ A_ub @ x <= b_ub
199
+ A_eq @ x == b_eq
200
+ lb <= x <= ub
201
+
202
+ Note that by default ``lb = 0`` and ``ub = None``. Other bounds can be
203
+ specified with ``bounds``.
204
+
205
+ Parameters
206
+ ----------
207
+ c : 1-D array
208
+ The coefficients of the linear objective function to be minimized.
209
+ A_ub : 2-D array, optional
210
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
211
+ coefficients of a linear inequality constraint on ``x``.
212
+ b_ub : 1-D array, optional
213
+ The inequality constraint vector. Each element represents an
214
+ upper bound on the corresponding value of ``A_ub @ x``.
215
+ A_eq : 2-D array, optional
216
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
217
+ coefficients of a linear equality constraint on ``x``.
218
+ b_eq : 1-D array, optional
219
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
220
+ the corresponding element of ``b_eq``.
221
+ bounds : sequence, optional
222
+ A sequence of ``(min, max)`` pairs for each element in ``x``, defining
223
+ the minimum and maximum values of that decision variable.
224
+ If a single tuple ``(min, max)`` is provided, then ``min`` and ``max``
225
+ will serve as bounds for all decision variables.
226
+ Use ``None`` to indicate that there is no bound. For instance, the
227
+ default bound ``(0, None)`` means that all decision variables are
228
+ non-negative, and the pair ``(None, None)`` means no bounds at all,
229
+ i.e. all variables are allowed to be any real.
230
+ method : str, optional
231
+ The algorithm used to solve the standard form problem.
232
+ :ref:`'highs' <optimize.linprog-highs>` (default),
233
+ :ref:`'highs-ds' <optimize.linprog-highs-ds>`,
234
+ :ref:`'highs-ipm' <optimize.linprog-highs-ipm>`,
235
+ :ref:`'interior-point' <optimize.linprog-interior-point>` (legacy),
236
+ :ref:`'revised simplex' <optimize.linprog-revised_simplex>` (legacy),
237
+ and
238
+ :ref:`'simplex' <optimize.linprog-simplex>` (legacy) are supported.
239
+ The legacy methods are deprecated and will be removed in SciPy 1.11.0.
240
+ callback : callable, optional
241
+ If a callback function is provided, it will be called at least once per
242
+ iteration of the algorithm. The callback function must accept a single
243
+ `scipy.optimize.OptimizeResult` consisting of the following fields:
244
+
245
+ x : 1-D array
246
+ The current solution vector.
247
+ fun : float
248
+ The current value of the objective function ``c @ x``.
249
+ success : bool
250
+ ``True`` when the algorithm has completed successfully.
251
+ slack : 1-D array
252
+ The (nominally positive) values of the slack,
253
+ ``b_ub - A_ub @ x``.
254
+ con : 1-D array
255
+ The (nominally zero) residuals of the equality constraints,
256
+ ``b_eq - A_eq @ x``.
257
+ phase : int
258
+ The phase of the algorithm being executed.
259
+ status : int
260
+ An integer representing the status of the algorithm.
261
+
262
+ ``0`` : Optimization proceeding nominally.
263
+
264
+ ``1`` : Iteration limit reached.
265
+
266
+ ``2`` : Problem appears to be infeasible.
267
+
268
+ ``3`` : Problem appears to be unbounded.
269
+
270
+ ``4`` : Numerical difficulties encountered.
271
+
272
+ nit : int
273
+ The current iteration number.
274
+ message : str
275
+ A string descriptor of the algorithm status.
276
+
277
+ Callback functions are not currently supported by the HiGHS methods.
278
+
279
+ options : dict, optional
280
+ A dictionary of solver options. All methods accept the following
281
+ options:
282
+
283
+ maxiter : int
284
+ Maximum number of iterations to perform.
285
+ Default: see method-specific documentation.
286
+ disp : bool
287
+ Set to ``True`` to print convergence messages.
288
+ Default: ``False``.
289
+ presolve : bool
290
+ Set to ``False`` to disable automatic presolve.
291
+ Default: ``True``.
292
+
293
+ All methods except the HiGHS solvers also accept:
294
+
295
+ tol : float
296
+ A tolerance which determines when a residual is "close enough" to
297
+ zero to be considered exactly zero.
298
+ autoscale : bool
299
+ Set to ``True`` to automatically perform equilibration.
300
+ Consider using this option if the numerical values in the
301
+ constraints are separated by several orders of magnitude.
302
+ Default: ``False``.
303
+ rr : bool
304
+ Set to ``False`` to disable automatic redundancy removal.
305
+ Default: ``True``.
306
+ rr_method : string
307
+ Method used to identify and remove redundant rows from the
308
+ equality constraint matrix after presolve. For problems with
309
+ dense input, the available methods for redundancy removal are:
310
+
311
+ "SVD":
312
+ Repeatedly performs singular value decomposition on
313
+ the matrix, detecting redundant rows based on nonzeros
314
+ in the left singular vectors that correspond with
315
+ zero singular values. May be fast when the matrix is
316
+ nearly full rank.
317
+ "pivot":
318
+ Uses the algorithm presented in [5]_ to identify
319
+ redundant rows.
320
+ "ID":
321
+ Uses a randomized interpolative decomposition.
322
+ Identifies columns of the matrix transpose not used in
323
+ a full-rank interpolative decomposition of the matrix.
324
+ None:
325
+ Uses "svd" if the matrix is nearly full rank, that is,
326
+ the difference between the matrix rank and the number
327
+ of rows is less than five. If not, uses "pivot". The
328
+ behavior of this default is subject to change without
329
+ prior notice.
330
+
331
+ Default: None.
332
+ For problems with sparse input, this option is ignored, and the
333
+ pivot-based algorithm presented in [5]_ is used.
334
+
335
+ For method-specific options, see
336
+ :func:`show_options('linprog') <show_options>`.
337
+
338
+ x0 : 1-D array, optional
339
+ Guess values of the decision variables, which will be refined by
340
+ the optimization algorithm. This argument is currently used only by the
341
+ 'revised simplex' method, and can only be used if `x0` represents a
342
+ basic feasible solution.
343
+
344
+ integrality : 1-D array or int, optional
345
+ Indicates the type of integrality constraint on each decision variable.
346
+
347
+ ``0`` : Continuous variable; no integrality constraint.
348
+
349
+ ``1`` : Integer variable; decision variable must be an integer
350
+ within `bounds`.
351
+
352
+ ``2`` : Semi-continuous variable; decision variable must be within
353
+ `bounds` or take value ``0``.
354
+
355
+ ``3`` : Semi-integer variable; decision variable must be an integer
356
+ within `bounds` or take value ``0``.
357
+
358
+ By default, all variables are continuous.
359
+
360
+ For mixed integrality constraints, supply an array of shape `c.shape`.
361
+ To infer a constraint on each decision variable from shorter inputs,
362
+ the argument will be broadcasted to `c.shape` using `np.broadcast_to`.
363
+
364
+ This argument is currently used only by the ``'highs'`` method and
365
+ ignored otherwise.
366
+
367
+ Returns
368
+ -------
369
+ res : OptimizeResult
370
+ A :class:`scipy.optimize.OptimizeResult` consisting of the fields
371
+ below. Note that the return types of the fields may depend on whether
372
+ the optimization was successful, therefore it is recommended to check
373
+ `OptimizeResult.status` before relying on the other fields:
374
+
375
+ x : 1-D array
376
+ The values of the decision variables that minimizes the
377
+ objective function while satisfying the constraints.
378
+ fun : float
379
+ The optimal value of the objective function ``c @ x``.
380
+ slack : 1-D array
381
+ The (nominally positive) values of the slack variables,
382
+ ``b_ub - A_ub @ x``.
383
+ con : 1-D array
384
+ The (nominally zero) residuals of the equality constraints,
385
+ ``b_eq - A_eq @ x``.
386
+ success : bool
387
+ ``True`` when the algorithm succeeds in finding an optimal
388
+ solution.
389
+ status : int
390
+ An integer representing the exit status of the algorithm.
391
+
392
+ ``0`` : Optimization terminated successfully.
393
+
394
+ ``1`` : Iteration limit reached.
395
+
396
+ ``2`` : Problem appears to be infeasible.
397
+
398
+ ``3`` : Problem appears to be unbounded.
399
+
400
+ ``4`` : Numerical difficulties encountered.
401
+
402
+ nit : int
403
+ The total number of iterations performed in all phases.
404
+ message : str
405
+ A string descriptor of the exit status of the algorithm.
406
+
407
+ See Also
408
+ --------
409
+ show_options : Additional options accepted by the solvers.
410
+
411
+ Notes
412
+ -----
413
+ This section describes the available solvers that can be selected by the
414
+ 'method' parameter.
415
+
416
+ `'highs-ds'` and
417
+ `'highs-ipm'` are interfaces to the
418
+ HiGHS simplex and interior-point method solvers [13]_, respectively.
419
+ `'highs'` (default) chooses between
420
+ the two automatically. These are the fastest linear
421
+ programming solvers in SciPy, especially for large, sparse problems;
422
+ which of these two is faster is problem-dependent.
423
+ The other solvers (`'interior-point'`, `'revised simplex'`, and
424
+ `'simplex'`) are legacy methods and will be removed in SciPy 1.11.0.
425
+
426
+ Method *highs-ds* is a wrapper of the C++ high performance dual
427
+ revised simplex implementation (HSOL) [13]_, [14]_. Method *highs-ipm*
428
+ is a wrapper of a C++ implementation of an **i**\ nterior-\ **p**\ oint
429
+ **m**\ ethod [13]_; it features a crossover routine, so it is as accurate
430
+ as a simplex solver. Method *highs* chooses between the two automatically.
431
+ For new code involving `linprog`, we recommend explicitly choosing one of
432
+ these three method values.
433
+
434
+ .. versionadded:: 1.6.0
435
+
436
+ Method *interior-point* uses the primal-dual path following algorithm
437
+ as outlined in [4]_. This algorithm supports sparse constraint matrices and
438
+ is typically faster than the simplex methods, especially for large, sparse
439
+ problems. Note, however, that the solution returned may be slightly less
440
+ accurate than those of the simplex methods and will not, in general,
441
+ correspond with a vertex of the polytope defined by the constraints.
442
+
443
+ .. versionadded:: 1.0.0
444
+
445
+ Method *revised simplex* uses the revised simplex method as described in
446
+ [9]_, except that a factorization [11]_ of the basis matrix, rather than
447
+ its inverse, is efficiently maintained and used to solve the linear systems
448
+ at each iteration of the algorithm.
449
+
450
+ .. versionadded:: 1.3.0
451
+
452
+ Method *simplex* uses a traditional, full-tableau implementation of
453
+ Dantzig's simplex algorithm [1]_, [2]_ (*not* the
454
+ Nelder-Mead simplex). This algorithm is included for backwards
455
+ compatibility and educational purposes.
456
+
457
+ .. versionadded:: 0.15.0
458
+
459
+ Before applying *interior-point*, *revised simplex*, or *simplex*,
460
+ a presolve procedure based on [8]_ attempts
461
+ to identify trivial infeasibilities, trivial unboundedness, and potential
462
+ problem simplifications. Specifically, it checks for:
463
+
464
+ - rows of zeros in ``A_eq`` or ``A_ub``, representing trivial constraints;
465
+ - columns of zeros in ``A_eq`` `and` ``A_ub``, representing unconstrained
466
+ variables;
467
+ - column singletons in ``A_eq``, representing fixed variables; and
468
+ - column singletons in ``A_ub``, representing simple bounds.
469
+
470
+ If presolve reveals that the problem is unbounded (e.g. an unconstrained
471
+ and unbounded variable has negative cost) or infeasible (e.g., a row of
472
+ zeros in ``A_eq`` corresponds with a nonzero in ``b_eq``), the solver
473
+ terminates with the appropriate status code. Note that presolve terminates
474
+ as soon as any sign of unboundedness is detected; consequently, a problem
475
+ may be reported as unbounded when in reality the problem is infeasible
476
+ (but infeasibility has not been detected yet). Therefore, if it is
477
+ important to know whether the problem is actually infeasible, solve the
478
+ problem again with option ``presolve=False``.
479
+
480
+ If neither infeasibility nor unboundedness are detected in a single pass
481
+ of the presolve, bounds are tightened where possible and fixed
482
+ variables are removed from the problem. Then, linearly dependent rows
483
+ of the ``A_eq`` matrix are removed, (unless they represent an
484
+ infeasibility) to avoid numerical difficulties in the primary solve
485
+ routine. Note that rows that are nearly linearly dependent (within a
486
+ prescribed tolerance) may also be removed, which can change the optimal
487
+ solution in rare cases. If this is a concern, eliminate redundancy from
488
+ your problem formulation and run with option ``rr=False`` or
489
+ ``presolve=False``.
490
+
491
+ Several potential improvements can be made here: additional presolve
492
+ checks outlined in [8]_ should be implemented, the presolve routine should
493
+ be run multiple times (until no further simplifications can be made), and
494
+ more of the efficiency improvements from [5]_ should be implemented in the
495
+ redundancy removal routines.
496
+
497
+ After presolve, the problem is transformed to standard form by converting
498
+ the (tightened) simple bounds to upper bound constraints, introducing
499
+ non-negative slack variables for inequality constraints, and expressing
500
+ unbounded variables as the difference between two non-negative variables.
501
+ Optionally, the problem is automatically scaled via equilibration [12]_.
502
+ The selected algorithm solves the standard form problem, and a
503
+ postprocessing routine converts the result to a solution to the original
504
+ problem.
505
+
506
+ References
507
+ ----------
508
+ .. [1] Dantzig, George B., Linear programming and extensions. Rand
509
+ Corporation Research Study Princeton Univ. Press, Princeton, NJ,
510
+ 1963
511
+ .. [2] Hillier, S.H. and Lieberman, G.J. (1995), "Introduction to
512
+ Mathematical Programming", McGraw-Hill, Chapter 4.
513
+ .. [3] Bland, Robert G. New finite pivoting rules for the simplex method.
514
+ Mathematics of Operations Research (2), 1977: pp. 103-107.
515
+ .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
516
+ optimizer for linear programming: an implementation of the
517
+ homogeneous algorithm." High performance optimization. Springer US,
518
+ 2000. 197-232.
519
+ .. [5] Andersen, Erling D. "Finding all linearly dependent rows in
520
+ large-scale linear programming." Optimization Methods and Software
521
+ 6.3 (1995): 219-227.
522
+ .. [6] Freund, Robert M. "Primal-Dual Interior-Point Methods for Linear
523
+ Programming based on Newton's Method." Unpublished Course Notes,
524
+ March 2004. Available 2/25/2017 at
525
+ https://ocw.mit.edu/courses/sloan-school-of-management/15-084j-nonlinear-programming-spring-2004/lecture-notes/lec14_int_pt_mthd.pdf
526
+ .. [7] Fourer, Robert. "Solving Linear Programs by Interior-Point Methods."
527
+ Unpublished Course Notes, August 26, 2005. Available 2/25/2017 at
528
+ http://www.4er.org/CourseNotes/Book%20B/B-III.pdf
529
+ .. [8] Andersen, Erling D., and Knud D. Andersen. "Presolving in linear
530
+ programming." Mathematical Programming 71.2 (1995): 221-245.
531
+ .. [9] Bertsimas, Dimitris, and J. Tsitsiklis. "Introduction to linear
532
+ programming." Athena Scientific 1 (1997): 997.
533
+ .. [10] Andersen, Erling D., et al. Implementation of interior point
534
+ methods for large scale linear programming. HEC/Universite de
535
+ Geneve, 1996.
536
+ .. [11] Bartels, Richard H. "A stabilization of the simplex method."
537
+ Journal in Numerische Mathematik 16.5 (1971): 414-434.
538
+ .. [12] Tomlin, J. A. "On scaling linear programming problems."
539
+ Mathematical Programming Study 4 (1975): 146-166.
540
+ .. [13] Huangfu, Q., Galabova, I., Feldmeier, M., and Hall, J. A. J.
541
+ "HiGHS - high performance software for linear optimization."
542
+ https://highs.dev/
543
+ .. [14] Huangfu, Q. and Hall, J. A. J. "Parallelizing the dual revised
544
+ simplex method." Mathematical Programming Computation, 10 (1),
545
+ 119-142, 2018. DOI: 10.1007/s12532-017-0130-5
546
+
547
+ Examples
548
+ --------
549
+ Consider the following problem:
550
+
551
+ .. math::
552
+
553
+ \min_{x_0, x_1} \ -x_0 + 4x_1 & \\
554
+ \mbox{such that} \ -3x_0 + x_1 & \leq 6,\\
555
+ -x_0 - 2x_1 & \geq -4,\\
556
+ x_1 & \geq -3.
557
+
558
+ The problem is not presented in the form accepted by `linprog`. This is
559
+ easily remedied by converting the "greater than" inequality
560
+ constraint to a "less than" inequality constraint by
561
+ multiplying both sides by a factor of :math:`-1`. Note also that the last
562
+ constraint is really the simple bound :math:`-3 \leq x_1 \leq \infty`.
563
+ Finally, since there are no bounds on :math:`x_0`, we must explicitly
564
+ specify the bounds :math:`-\infty \leq x_0 \leq \infty`, as the
565
+ default is for variables to be non-negative. After collecting coeffecients
566
+ into arrays and tuples, the input for this problem is:
567
+
568
+ >>> from scipy.optimize import linprog
569
+ >>> c = [-1, 4]
570
+ >>> A = [[-3, 1], [1, 2]]
571
+ >>> b = [6, 4]
572
+ >>> x0_bounds = (None, None)
573
+ >>> x1_bounds = (-3, None)
574
+ >>> res = linprog(c, A_ub=A, b_ub=b, bounds=[x0_bounds, x1_bounds])
575
+ >>> res.fun
576
+ -22.0
577
+ >>> res.x
578
+ array([10., -3.])
579
+ >>> res.message
580
+ 'Optimization terminated successfully. (HiGHS Status 7: Optimal)'
581
+
582
+ The marginals (AKA dual values / shadow prices / Lagrange multipliers)
583
+ and residuals (slacks) are also available.
584
+
585
+ >>> res.ineqlin
586
+ residual: [ 3.900e+01 0.000e+00]
587
+ marginals: [-0.000e+00 -1.000e+00]
588
+
589
+ For example, because the marginal associated with the second inequality
590
+ constraint is -1, we expect the optimal value of the objective function
591
+ to decrease by ``eps`` if we add a small amount ``eps`` to the right hand
592
+ side of the second inequality constraint:
593
+
594
+ >>> eps = 0.05
595
+ >>> b[1] += eps
596
+ >>> linprog(c, A_ub=A, b_ub=b, bounds=[x0_bounds, x1_bounds]).fun
597
+ -22.05
598
+
599
+ Also, because the residual on the first inequality constraint is 39, we
600
+ can decrease the right hand side of the first constraint by 39 without
601
+ affecting the optimal solution.
602
+
603
+ >>> b = [6, 4] # reset to original values
604
+ >>> b[0] -= 39
605
+ >>> linprog(c, A_ub=A, b_ub=b, bounds=[x0_bounds, x1_bounds]).fun
606
+ -22.0
607
+
608
+ """
609
+
610
+ meth = method.lower()
611
+ methods = {"highs", "highs-ds", "highs-ipm",
612
+ "simplex", "revised simplex", "interior-point"}
613
+
614
+ if meth not in methods:
615
+ raise ValueError(f"Unknown solver '{method}'")
616
+
617
+ if x0 is not None and meth != "revised simplex":
618
+ warning_message = "x0 is used only when method is 'revised simplex'. "
619
+ warn(warning_message, OptimizeWarning, stacklevel=2)
620
+
621
+ if np.any(integrality) and not meth == "highs":
622
+ integrality = None
623
+ warning_message = ("Only `method='highs'` supports integer "
624
+ "constraints. Ignoring `integrality`.")
625
+ warn(warning_message, OptimizeWarning, stacklevel=2)
626
+ elif np.any(integrality):
627
+ integrality = np.broadcast_to(integrality, np.shape(c))
628
+ else:
629
+ integrality = None
630
+
631
+ lp = _LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0, integrality)
632
+ lp, solver_options = _parse_linprog(lp, options, meth)
633
+ tol = solver_options.get('tol', 1e-9)
634
+
635
+ # Give unmodified problem to HiGHS
636
+ if meth.startswith('highs'):
637
+ if callback is not None:
638
+ raise NotImplementedError("HiGHS solvers do not support the "
639
+ "callback interface.")
640
+ highs_solvers = {'highs-ipm': 'ipm', 'highs-ds': 'simplex',
641
+ 'highs': None}
642
+
643
+ sol = _linprog_highs(lp, solver=highs_solvers[meth],
644
+ **solver_options)
645
+ sol['status'], sol['message'] = (
646
+ _check_result(sol['x'], sol['fun'], sol['status'], sol['slack'],
647
+ sol['con'], lp.bounds, tol, sol['message'],
648
+ integrality))
649
+ sol['success'] = sol['status'] == 0
650
+ return OptimizeResult(sol)
651
+
652
+ warn(f"`method='{meth}'` is deprecated and will be removed in SciPy "
653
+ "1.11.0. Please use one of the HiGHS solvers (e.g. "
654
+ "`method='highs'`) in new code.", DeprecationWarning, stacklevel=2)
655
+
656
+ iteration = 0
657
+ complete = False # will become True if solved in presolve
658
+ undo = []
659
+
660
+ # Keep the original arrays to calculate slack/residuals for original
661
+ # problem.
662
+ lp_o = deepcopy(lp)
663
+
664
+ # Solve trivial problem, eliminate variables, tighten bounds, etc.
665
+ rr_method = solver_options.pop('rr_method', None) # need to pop these;
666
+ rr = solver_options.pop('rr', True) # they're not passed to methods
667
+ c0 = 0 # we might get a constant term in the objective
668
+ if solver_options.pop('presolve', True):
669
+ (lp, c0, x, undo, complete, status, message) = _presolve(lp, rr,
670
+ rr_method,
671
+ tol)
672
+
673
+ C, b_scale = 1, 1 # for trivial unscaling if autoscale is not used
674
+ postsolve_args = (lp_o._replace(bounds=lp.bounds), undo, C, b_scale)
675
+
676
+ if not complete:
677
+ A, b, c, c0, x0 = _get_Abc(lp, c0)
678
+ if solver_options.pop('autoscale', False):
679
+ A, b, c, x0, C, b_scale = _autoscale(A, b, c, x0)
680
+ postsolve_args = postsolve_args[:-2] + (C, b_scale)
681
+
682
+ if meth == 'simplex':
683
+ x, status, message, iteration = _linprog_simplex(
684
+ c, c0=c0, A=A, b=b, callback=callback,
685
+ postsolve_args=postsolve_args, **solver_options)
686
+ elif meth == 'interior-point':
687
+ x, status, message, iteration = _linprog_ip(
688
+ c, c0=c0, A=A, b=b, callback=callback,
689
+ postsolve_args=postsolve_args, **solver_options)
690
+ elif meth == 'revised simplex':
691
+ x, status, message, iteration = _linprog_rs(
692
+ c, c0=c0, A=A, b=b, x0=x0, callback=callback,
693
+ postsolve_args=postsolve_args, **solver_options)
694
+
695
+ # Eliminate artificial variables, re-introduce presolved variables, etc.
696
+ disp = solver_options.get('disp', False)
697
+
698
+ x, fun, slack, con = _postsolve(x, postsolve_args, complete)
699
+
700
+ status, message = _check_result(x, fun, status, slack, con, lp_o.bounds,
701
+ tol, message, integrality)
702
+
703
+ if disp:
704
+ _display_summary(message, status, fun, iteration)
705
+
706
+ sol = {
707
+ 'x': x,
708
+ 'fun': fun,
709
+ 'slack': slack,
710
+ 'con': con,
711
+ 'status': status,
712
+ 'message': message,
713
+ 'nit': iteration,
714
+ 'success': status == 0}
715
+
716
+ return OptimizeResult(sol)
vila/lib/python3.10/site-packages/scipy/optimize/_linprog_highs.py ADDED
@@ -0,0 +1,440 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HiGHS Linear Optimization Methods
2
+
3
+ Interface to HiGHS linear optimization software.
4
+ https://highs.dev/
5
+
6
+ .. versionadded:: 1.5.0
7
+
8
+ References
9
+ ----------
10
+ .. [1] Q. Huangfu and J.A.J. Hall. "Parallelizing the dual revised simplex
11
+ method." Mathematical Programming Computation, 10 (1), 119-142,
12
+ 2018. DOI: 10.1007/s12532-017-0130-5
13
+
14
+ """
15
+
16
+ import inspect
17
+ import numpy as np
18
+ from ._optimize import OptimizeWarning, OptimizeResult
19
+ from warnings import warn
20
+ from ._highs._highs_wrapper import _highs_wrapper
21
+ from ._highs._highs_constants import (
22
+ CONST_INF,
23
+ MESSAGE_LEVEL_NONE,
24
+ HIGHS_OBJECTIVE_SENSE_MINIMIZE,
25
+
26
+ MODEL_STATUS_NOTSET,
27
+ MODEL_STATUS_LOAD_ERROR,
28
+ MODEL_STATUS_MODEL_ERROR,
29
+ MODEL_STATUS_PRESOLVE_ERROR,
30
+ MODEL_STATUS_SOLVE_ERROR,
31
+ MODEL_STATUS_POSTSOLVE_ERROR,
32
+ MODEL_STATUS_MODEL_EMPTY,
33
+ MODEL_STATUS_OPTIMAL,
34
+ MODEL_STATUS_INFEASIBLE,
35
+ MODEL_STATUS_UNBOUNDED_OR_INFEASIBLE,
36
+ MODEL_STATUS_UNBOUNDED,
37
+ MODEL_STATUS_REACHED_DUAL_OBJECTIVE_VALUE_UPPER_BOUND
38
+ as MODEL_STATUS_RDOVUB,
39
+ MODEL_STATUS_REACHED_OBJECTIVE_TARGET,
40
+ MODEL_STATUS_REACHED_TIME_LIMIT,
41
+ MODEL_STATUS_REACHED_ITERATION_LIMIT,
42
+
43
+ HIGHS_SIMPLEX_STRATEGY_DUAL,
44
+
45
+ HIGHS_SIMPLEX_CRASH_STRATEGY_OFF,
46
+
47
+ HIGHS_SIMPLEX_EDGE_WEIGHT_STRATEGY_CHOOSE,
48
+ HIGHS_SIMPLEX_EDGE_WEIGHT_STRATEGY_DANTZIG,
49
+ HIGHS_SIMPLEX_EDGE_WEIGHT_STRATEGY_DEVEX,
50
+ HIGHS_SIMPLEX_EDGE_WEIGHT_STRATEGY_STEEPEST_EDGE,
51
+ )
52
+ from scipy.sparse import csc_matrix, vstack, issparse
53
+
54
+
55
+ def _highs_to_scipy_status_message(highs_status, highs_message):
56
+ """Converts HiGHS status number/message to SciPy status number/message"""
57
+
58
+ scipy_statuses_messages = {
59
+ None: (4, "HiGHS did not provide a status code. "),
60
+ MODEL_STATUS_NOTSET: (4, ""),
61
+ MODEL_STATUS_LOAD_ERROR: (4, ""),
62
+ MODEL_STATUS_MODEL_ERROR: (2, ""),
63
+ MODEL_STATUS_PRESOLVE_ERROR: (4, ""),
64
+ MODEL_STATUS_SOLVE_ERROR: (4, ""),
65
+ MODEL_STATUS_POSTSOLVE_ERROR: (4, ""),
66
+ MODEL_STATUS_MODEL_EMPTY: (4, ""),
67
+ MODEL_STATUS_RDOVUB: (4, ""),
68
+ MODEL_STATUS_REACHED_OBJECTIVE_TARGET: (4, ""),
69
+ MODEL_STATUS_OPTIMAL: (0, "Optimization terminated successfully. "),
70
+ MODEL_STATUS_REACHED_TIME_LIMIT: (1, "Time limit reached. "),
71
+ MODEL_STATUS_REACHED_ITERATION_LIMIT: (1, "Iteration limit reached. "),
72
+ MODEL_STATUS_INFEASIBLE: (2, "The problem is infeasible. "),
73
+ MODEL_STATUS_UNBOUNDED: (3, "The problem is unbounded. "),
74
+ MODEL_STATUS_UNBOUNDED_OR_INFEASIBLE: (4, "The problem is unbounded "
75
+ "or infeasible. ")}
76
+ unrecognized = (4, "The HiGHS status code was not recognized. ")
77
+ scipy_status, scipy_message = (
78
+ scipy_statuses_messages.get(highs_status, unrecognized))
79
+ scipy_message = (f"{scipy_message}"
80
+ f"(HiGHS Status {highs_status}: {highs_message})")
81
+ return scipy_status, scipy_message
82
+
83
+
84
+ def _replace_inf(x):
85
+ # Replace `np.inf` with CONST_INF
86
+ infs = np.isinf(x)
87
+ with np.errstate(invalid="ignore"):
88
+ x[infs] = np.sign(x[infs])*CONST_INF
89
+ return x
90
+
91
+
92
+ def _convert_to_highs_enum(option, option_str, choices):
93
+ # If option is in the choices we can look it up, if not use
94
+ # the default value taken from function signature and warn:
95
+ try:
96
+ return choices[option.lower()]
97
+ except AttributeError:
98
+ return choices[option]
99
+ except KeyError:
100
+ sig = inspect.signature(_linprog_highs)
101
+ default_str = sig.parameters[option_str].default
102
+ warn(f"Option {option_str} is {option}, but only values in "
103
+ f"{set(choices.keys())} are allowed. Using default: "
104
+ f"{default_str}.",
105
+ OptimizeWarning, stacklevel=3)
106
+ return choices[default_str]
107
+
108
+
109
+ def _linprog_highs(lp, solver, time_limit=None, presolve=True,
110
+ disp=False, maxiter=None,
111
+ dual_feasibility_tolerance=None,
112
+ primal_feasibility_tolerance=None,
113
+ ipm_optimality_tolerance=None,
114
+ simplex_dual_edge_weight_strategy=None,
115
+ mip_rel_gap=None,
116
+ mip_max_nodes=None,
117
+ **unknown_options):
118
+ r"""
119
+ Solve the following linear programming problem using one of the HiGHS
120
+ solvers:
121
+
122
+ User-facing documentation is in _linprog_doc.py.
123
+
124
+ Parameters
125
+ ----------
126
+ lp : _LPProblem
127
+ A ``scipy.optimize._linprog_util._LPProblem`` ``namedtuple``.
128
+ solver : "ipm" or "simplex" or None
129
+ Which HiGHS solver to use. If ``None``, "simplex" will be used.
130
+
131
+ Options
132
+ -------
133
+ maxiter : int
134
+ The maximum number of iterations to perform in either phase. For
135
+ ``solver='ipm'``, this does not include the number of crossover
136
+ iterations. Default is the largest possible value for an ``int``
137
+ on the platform.
138
+ disp : bool
139
+ Set to ``True`` if indicators of optimization status are to be printed
140
+ to the console each iteration; default ``False``.
141
+ time_limit : float
142
+ The maximum time in seconds allotted to solve the problem; default is
143
+ the largest possible value for a ``double`` on the platform.
144
+ presolve : bool
145
+ Presolve attempts to identify trivial infeasibilities,
146
+ identify trivial unboundedness, and simplify the problem before
147
+ sending it to the main solver. It is generally recommended
148
+ to keep the default setting ``True``; set to ``False`` if presolve is
149
+ to be disabled.
150
+ dual_feasibility_tolerance : double
151
+ Dual feasibility tolerance. Default is 1e-07.
152
+ The minimum of this and ``primal_feasibility_tolerance``
153
+ is used for the feasibility tolerance when ``solver='ipm'``.
154
+ primal_feasibility_tolerance : double
155
+ Primal feasibility tolerance. Default is 1e-07.
156
+ The minimum of this and ``dual_feasibility_tolerance``
157
+ is used for the feasibility tolerance when ``solver='ipm'``.
158
+ ipm_optimality_tolerance : double
159
+ Optimality tolerance for ``solver='ipm'``. Default is 1e-08.
160
+ Minimum possible value is 1e-12 and must be smaller than the largest
161
+ possible value for a ``double`` on the platform.
162
+ simplex_dual_edge_weight_strategy : str (default: None)
163
+ Strategy for simplex dual edge weights. The default, ``None``,
164
+ automatically selects one of the following.
165
+
166
+ ``'dantzig'`` uses Dantzig's original strategy of choosing the most
167
+ negative reduced cost.
168
+
169
+ ``'devex'`` uses the strategy described in [15]_.
170
+
171
+ ``steepest`` uses the exact steepest edge strategy as described in
172
+ [16]_.
173
+
174
+ ``'steepest-devex'`` begins with the exact steepest edge strategy
175
+ until the computation is too costly or inexact and then switches to
176
+ the devex method.
177
+
178
+ Currently, using ``None`` always selects ``'steepest-devex'``, but this
179
+ may change as new options become available.
180
+
181
+ mip_max_nodes : int
182
+ The maximum number of nodes allotted to solve the problem; default is
183
+ the largest possible value for a ``HighsInt`` on the platform.
184
+ Ignored if not using the MIP solver.
185
+ unknown_options : dict
186
+ Optional arguments not used by this particular solver. If
187
+ ``unknown_options`` is non-empty, a warning is issued listing all
188
+ unused options.
189
+
190
+ Returns
191
+ -------
192
+ sol : dict
193
+ A dictionary consisting of the fields:
194
+
195
+ x : 1D array
196
+ The values of the decision variables that minimizes the
197
+ objective function while satisfying the constraints.
198
+ fun : float
199
+ The optimal value of the objective function ``c @ x``.
200
+ slack : 1D array
201
+ The (nominally positive) values of the slack,
202
+ ``b_ub - A_ub @ x``.
203
+ con : 1D array
204
+ The (nominally zero) residuals of the equality constraints,
205
+ ``b_eq - A_eq @ x``.
206
+ success : bool
207
+ ``True`` when the algorithm succeeds in finding an optimal
208
+ solution.
209
+ status : int
210
+ An integer representing the exit status of the algorithm.
211
+
212
+ ``0`` : Optimization terminated successfully.
213
+
214
+ ``1`` : Iteration or time limit reached.
215
+
216
+ ``2`` : Problem appears to be infeasible.
217
+
218
+ ``3`` : Problem appears to be unbounded.
219
+
220
+ ``4`` : The HiGHS solver ran into a problem.
221
+
222
+ message : str
223
+ A string descriptor of the exit status of the algorithm.
224
+ nit : int
225
+ The total number of iterations performed.
226
+ For ``solver='simplex'``, this includes iterations in all
227
+ phases. For ``solver='ipm'``, this does not include
228
+ crossover iterations.
229
+ crossover_nit : int
230
+ The number of primal/dual pushes performed during the
231
+ crossover routine for ``solver='ipm'``. This is ``0``
232
+ for ``solver='simplex'``.
233
+ ineqlin : OptimizeResult
234
+ Solution and sensitivity information corresponding to the
235
+ inequality constraints, `b_ub`. A dictionary consisting of the
236
+ fields:
237
+
238
+ residual : np.ndnarray
239
+ The (nominally positive) values of the slack variables,
240
+ ``b_ub - A_ub @ x``. This quantity is also commonly
241
+ referred to as "slack".
242
+
243
+ marginals : np.ndarray
244
+ The sensitivity (partial derivative) of the objective
245
+ function with respect to the right-hand side of the
246
+ inequality constraints, `b_ub`.
247
+
248
+ eqlin : OptimizeResult
249
+ Solution and sensitivity information corresponding to the
250
+ equality constraints, `b_eq`. A dictionary consisting of the
251
+ fields:
252
+
253
+ residual : np.ndarray
254
+ The (nominally zero) residuals of the equality constraints,
255
+ ``b_eq - A_eq @ x``.
256
+
257
+ marginals : np.ndarray
258
+ The sensitivity (partial derivative) of the objective
259
+ function with respect to the right-hand side of the
260
+ equality constraints, `b_eq`.
261
+
262
+ lower, upper : OptimizeResult
263
+ Solution and sensitivity information corresponding to the
264
+ lower and upper bounds on decision variables, `bounds`.
265
+
266
+ residual : np.ndarray
267
+ The (nominally positive) values of the quantity
268
+ ``x - lb`` (lower) or ``ub - x`` (upper).
269
+
270
+ marginals : np.ndarray
271
+ The sensitivity (partial derivative) of the objective
272
+ function with respect to the lower and upper
273
+ `bounds`.
274
+
275
+ mip_node_count : int
276
+ The number of subproblems or "nodes" solved by the MILP
277
+ solver. Only present when `integrality` is not `None`.
278
+
279
+ mip_dual_bound : float
280
+ The MILP solver's final estimate of the lower bound on the
281
+ optimal solution. Only present when `integrality` is not
282
+ `None`.
283
+
284
+ mip_gap : float
285
+ The difference between the final objective function value
286
+ and the final dual bound, scaled by the final objective
287
+ function value. Only present when `integrality` is not
288
+ `None`.
289
+
290
+ Notes
291
+ -----
292
+ The result fields `ineqlin`, `eqlin`, `lower`, and `upper` all contain
293
+ `marginals`, or partial derivatives of the objective function with respect
294
+ to the right-hand side of each constraint. These partial derivatives are
295
+ also referred to as "Lagrange multipliers", "dual values", and
296
+ "shadow prices". The sign convention of `marginals` is opposite that
297
+ of Lagrange multipliers produced by many nonlinear solvers.
298
+
299
+ References
300
+ ----------
301
+ .. [15] Harris, Paula MJ. "Pivot selection methods of the Devex LP code."
302
+ Mathematical programming 5.1 (1973): 1-28.
303
+ .. [16] Goldfarb, Donald, and John Ker Reid. "A practicable steepest-edge
304
+ simplex algorithm." Mathematical Programming 12.1 (1977): 361-371.
305
+ """
306
+ if unknown_options:
307
+ message = (f"Unrecognized options detected: {unknown_options}. "
308
+ "These will be passed to HiGHS verbatim.")
309
+ warn(message, OptimizeWarning, stacklevel=3)
310
+
311
+ # Map options to HiGHS enum values
312
+ simplex_dual_edge_weight_strategy_enum = _convert_to_highs_enum(
313
+ simplex_dual_edge_weight_strategy,
314
+ 'simplex_dual_edge_weight_strategy',
315
+ choices={'dantzig': HIGHS_SIMPLEX_EDGE_WEIGHT_STRATEGY_DANTZIG,
316
+ 'devex': HIGHS_SIMPLEX_EDGE_WEIGHT_STRATEGY_DEVEX,
317
+ 'steepest-devex': HIGHS_SIMPLEX_EDGE_WEIGHT_STRATEGY_CHOOSE,
318
+ 'steepest':
319
+ HIGHS_SIMPLEX_EDGE_WEIGHT_STRATEGY_STEEPEST_EDGE,
320
+ None: None})
321
+
322
+ c, A_ub, b_ub, A_eq, b_eq, bounds, x0, integrality = lp
323
+
324
+ lb, ub = bounds.T.copy() # separate bounds, copy->C-cntgs
325
+ # highs_wrapper solves LHS <= A*x <= RHS, not equality constraints
326
+ with np.errstate(invalid="ignore"):
327
+ lhs_ub = -np.ones_like(b_ub)*np.inf # LHS of UB constraints is -inf
328
+ rhs_ub = b_ub # RHS of UB constraints is b_ub
329
+ lhs_eq = b_eq # Equality constraint is inequality
330
+ rhs_eq = b_eq # constraint with LHS=RHS
331
+ lhs = np.concatenate((lhs_ub, lhs_eq))
332
+ rhs = np.concatenate((rhs_ub, rhs_eq))
333
+
334
+ if issparse(A_ub) or issparse(A_eq):
335
+ A = vstack((A_ub, A_eq))
336
+ else:
337
+ A = np.vstack((A_ub, A_eq))
338
+ A = csc_matrix(A)
339
+
340
+ options = {
341
+ 'presolve': presolve,
342
+ 'sense': HIGHS_OBJECTIVE_SENSE_MINIMIZE,
343
+ 'solver': solver,
344
+ 'time_limit': time_limit,
345
+ 'highs_debug_level': MESSAGE_LEVEL_NONE,
346
+ 'dual_feasibility_tolerance': dual_feasibility_tolerance,
347
+ 'ipm_optimality_tolerance': ipm_optimality_tolerance,
348
+ 'log_to_console': disp,
349
+ 'mip_max_nodes': mip_max_nodes,
350
+ 'output_flag': disp,
351
+ 'primal_feasibility_tolerance': primal_feasibility_tolerance,
352
+ 'simplex_dual_edge_weight_strategy':
353
+ simplex_dual_edge_weight_strategy_enum,
354
+ 'simplex_strategy': HIGHS_SIMPLEX_STRATEGY_DUAL,
355
+ 'simplex_crash_strategy': HIGHS_SIMPLEX_CRASH_STRATEGY_OFF,
356
+ 'ipm_iteration_limit': maxiter,
357
+ 'simplex_iteration_limit': maxiter,
358
+ 'mip_rel_gap': mip_rel_gap,
359
+ }
360
+ options.update(unknown_options)
361
+
362
+ # np.inf doesn't work; use very large constant
363
+ rhs = _replace_inf(rhs)
364
+ lhs = _replace_inf(lhs)
365
+ lb = _replace_inf(lb)
366
+ ub = _replace_inf(ub)
367
+
368
+ if integrality is None or np.sum(integrality) == 0:
369
+ integrality = np.empty(0)
370
+ else:
371
+ integrality = np.array(integrality)
372
+
373
+ res = _highs_wrapper(c, A.indptr, A.indices, A.data, lhs, rhs,
374
+ lb, ub, integrality.astype(np.uint8), options)
375
+
376
+ # HiGHS represents constraints as lhs/rhs, so
377
+ # Ax + s = b => Ax = b - s
378
+ # and we need to split up s by A_ub and A_eq
379
+ if 'slack' in res:
380
+ slack = res['slack']
381
+ con = np.array(slack[len(b_ub):])
382
+ slack = np.array(slack[:len(b_ub)])
383
+ else:
384
+ slack, con = None, None
385
+
386
+ # lagrange multipliers for equalities/inequalities and upper/lower bounds
387
+ if 'lambda' in res:
388
+ lamda = res['lambda']
389
+ marg_ineqlin = np.array(lamda[:len(b_ub)])
390
+ marg_eqlin = np.array(lamda[len(b_ub):])
391
+ marg_upper = np.array(res['marg_bnds'][1, :])
392
+ marg_lower = np.array(res['marg_bnds'][0, :])
393
+ else:
394
+ marg_ineqlin, marg_eqlin = None, None
395
+ marg_upper, marg_lower = None, None
396
+
397
+ # this needs to be updated if we start choosing the solver intelligently
398
+
399
+ # Convert to scipy-style status and message
400
+ highs_status = res.get('status', None)
401
+ highs_message = res.get('message', None)
402
+ status, message = _highs_to_scipy_status_message(highs_status,
403
+ highs_message)
404
+
405
+ x = np.array(res['x']) if 'x' in res else None
406
+ sol = {'x': x,
407
+ 'slack': slack,
408
+ 'con': con,
409
+ 'ineqlin': OptimizeResult({
410
+ 'residual': slack,
411
+ 'marginals': marg_ineqlin,
412
+ }),
413
+ 'eqlin': OptimizeResult({
414
+ 'residual': con,
415
+ 'marginals': marg_eqlin,
416
+ }),
417
+ 'lower': OptimizeResult({
418
+ 'residual': None if x is None else x - lb,
419
+ 'marginals': marg_lower,
420
+ }),
421
+ 'upper': OptimizeResult({
422
+ 'residual': None if x is None else ub - x,
423
+ 'marginals': marg_upper
424
+ }),
425
+ 'fun': res.get('fun'),
426
+ 'status': status,
427
+ 'success': res['status'] == MODEL_STATUS_OPTIMAL,
428
+ 'message': message,
429
+ 'nit': res.get('simplex_nit', 0) or res.get('ipm_nit', 0),
430
+ 'crossover_nit': res.get('crossover_nit'),
431
+ }
432
+
433
+ if np.any(x) and integrality is not None:
434
+ sol.update({
435
+ 'mip_node_count': res.get('mip_node_count', 0),
436
+ 'mip_dual_bound': res.get('mip_dual_bound', 0.0),
437
+ 'mip_gap': res.get('mip_gap', 0.0),
438
+ })
439
+
440
+ return sol
vila/lib/python3.10/site-packages/scipy/optimize/_linprog_ip.py ADDED
@@ -0,0 +1,1126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Interior-point method for linear programming
2
+
3
+ The *interior-point* method uses the primal-dual path following algorithm
4
+ outlined in [1]_. This algorithm supports sparse constraint matrices and
5
+ is typically faster than the simplex methods, especially for large, sparse
6
+ problems. Note, however, that the solution returned may be slightly less
7
+ accurate than those of the simplex methods and will not, in general,
8
+ correspond with a vertex of the polytope defined by the constraints.
9
+
10
+ .. versionadded:: 1.0.0
11
+
12
+ References
13
+ ----------
14
+ .. [1] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
15
+ optimizer for linear programming: an implementation of the
16
+ homogeneous algorithm." High performance optimization. Springer US,
17
+ 2000. 197-232.
18
+ """
19
+ # Author: Matt Haberland
20
+
21
+ import numpy as np
22
+ import scipy as sp
23
+ import scipy.sparse as sps
24
+ from warnings import warn
25
+ from scipy.linalg import LinAlgError
26
+ from ._optimize import OptimizeWarning, OptimizeResult, _check_unknown_options
27
+ from ._linprog_util import _postsolve
28
+ has_umfpack = True
29
+ has_cholmod = True
30
+ try:
31
+ import sksparse # noqa: F401
32
+ from sksparse.cholmod import cholesky as cholmod # noqa: F401
33
+ from sksparse.cholmod import analyze as cholmod_analyze
34
+ except ImportError:
35
+ has_cholmod = False
36
+ try:
37
+ import scikits.umfpack # test whether to use factorized # noqa: F401
38
+ except ImportError:
39
+ has_umfpack = False
40
+
41
+
42
+ def _get_solver(M, sparse=False, lstsq=False, sym_pos=True,
43
+ cholesky=True, permc_spec='MMD_AT_PLUS_A'):
44
+ """
45
+ Given solver options, return a handle to the appropriate linear system
46
+ solver.
47
+
48
+ Parameters
49
+ ----------
50
+ M : 2-D array
51
+ As defined in [4] Equation 8.31
52
+ sparse : bool (default = False)
53
+ True if the system to be solved is sparse. This is typically set
54
+ True when the original ``A_ub`` and ``A_eq`` arrays are sparse.
55
+ lstsq : bool (default = False)
56
+ True if the system is ill-conditioned and/or (nearly) singular and
57
+ thus a more robust least-squares solver is desired. This is sometimes
58
+ needed as the solution is approached.
59
+ sym_pos : bool (default = True)
60
+ True if the system matrix is symmetric positive definite
61
+ Sometimes this needs to be set false as the solution is approached,
62
+ even when the system should be symmetric positive definite, due to
63
+ numerical difficulties.
64
+ cholesky : bool (default = True)
65
+ True if the system is to be solved by Cholesky, rather than LU,
66
+ decomposition. This is typically faster unless the problem is very
67
+ small or prone to numerical difficulties.
68
+ permc_spec : str (default = 'MMD_AT_PLUS_A')
69
+ Sparsity preservation strategy used by SuperLU. Acceptable values are:
70
+
71
+ - ``NATURAL``: natural ordering.
72
+ - ``MMD_ATA``: minimum degree ordering on the structure of A^T A.
73
+ - ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A.
74
+ - ``COLAMD``: approximate minimum degree column ordering.
75
+
76
+ See SuperLU documentation.
77
+
78
+ Returns
79
+ -------
80
+ solve : function
81
+ Handle to the appropriate solver function
82
+
83
+ """
84
+ try:
85
+ if sparse:
86
+ if lstsq:
87
+ def solve(r, sym_pos=False):
88
+ return sps.linalg.lsqr(M, r)[0]
89
+ elif cholesky:
90
+ try:
91
+ # Will raise an exception in the first call,
92
+ # or when the matrix changes due to a new problem
93
+ _get_solver.cholmod_factor.cholesky_inplace(M)
94
+ except Exception:
95
+ _get_solver.cholmod_factor = cholmod_analyze(M)
96
+ _get_solver.cholmod_factor.cholesky_inplace(M)
97
+ solve = _get_solver.cholmod_factor
98
+ else:
99
+ if has_umfpack and sym_pos:
100
+ solve = sps.linalg.factorized(M)
101
+ else: # factorized doesn't pass permc_spec
102
+ solve = sps.linalg.splu(M, permc_spec=permc_spec).solve
103
+
104
+ else:
105
+ if lstsq: # sometimes necessary as solution is approached
106
+ def solve(r):
107
+ return sp.linalg.lstsq(M, r)[0]
108
+ elif cholesky:
109
+ L = sp.linalg.cho_factor(M)
110
+
111
+ def solve(r):
112
+ return sp.linalg.cho_solve(L, r)
113
+ else:
114
+ # this seems to cache the matrix factorization, so solving
115
+ # with multiple right hand sides is much faster
116
+ def solve(r, sym_pos=sym_pos):
117
+ if sym_pos:
118
+ return sp.linalg.solve(M, r, assume_a="pos")
119
+ else:
120
+ return sp.linalg.solve(M, r)
121
+ # There are many things that can go wrong here, and it's hard to say
122
+ # what all of them are. It doesn't really matter: if the matrix can't be
123
+ # factorized, return None. get_solver will be called again with different
124
+ # inputs, and a new routine will try to factorize the matrix.
125
+ except KeyboardInterrupt:
126
+ raise
127
+ except Exception:
128
+ return None
129
+ return solve
130
+
131
+
132
+ def _get_delta(A, b, c, x, y, z, tau, kappa, gamma, eta, sparse=False,
133
+ lstsq=False, sym_pos=True, cholesky=True, pc=True, ip=False,
134
+ permc_spec='MMD_AT_PLUS_A'):
135
+ """
136
+ Given standard form problem defined by ``A``, ``b``, and ``c``;
137
+ current variable estimates ``x``, ``y``, ``z``, ``tau``, and ``kappa``;
138
+ algorithmic parameters ``gamma and ``eta;
139
+ and options ``sparse``, ``lstsq``, ``sym_pos``, ``cholesky``, ``pc``
140
+ (predictor-corrector), and ``ip`` (initial point improvement),
141
+ get the search direction for increments to the variable estimates.
142
+
143
+ Parameters
144
+ ----------
145
+ As defined in [4], except:
146
+ sparse : bool
147
+ True if the system to be solved is sparse. This is typically set
148
+ True when the original ``A_ub`` and ``A_eq`` arrays are sparse.
149
+ lstsq : bool
150
+ True if the system is ill-conditioned and/or (nearly) singular and
151
+ thus a more robust least-squares solver is desired. This is sometimes
152
+ needed as the solution is approached.
153
+ sym_pos : bool
154
+ True if the system matrix is symmetric positive definite
155
+ Sometimes this needs to be set false as the solution is approached,
156
+ even when the system should be symmetric positive definite, due to
157
+ numerical difficulties.
158
+ cholesky : bool
159
+ True if the system is to be solved by Cholesky, rather than LU,
160
+ decomposition. This is typically faster unless the problem is very
161
+ small or prone to numerical difficulties.
162
+ pc : bool
163
+ True if the predictor-corrector method of Mehrota is to be used. This
164
+ is almost always (if not always) beneficial. Even though it requires
165
+ the solution of an additional linear system, the factorization
166
+ is typically (implicitly) reused so solution is efficient, and the
167
+ number of algorithm iterations is typically reduced.
168
+ ip : bool
169
+ True if the improved initial point suggestion due to [4] section 4.3
170
+ is desired. It's unclear whether this is beneficial.
171
+ permc_spec : str (default = 'MMD_AT_PLUS_A')
172
+ (Has effect only with ``sparse = True``, ``lstsq = False``, ``sym_pos =
173
+ True``.) A matrix is factorized in each iteration of the algorithm.
174
+ This option specifies how to permute the columns of the matrix for
175
+ sparsity preservation. Acceptable values are:
176
+
177
+ - ``NATURAL``: natural ordering.
178
+ - ``MMD_ATA``: minimum degree ordering on the structure of A^T A.
179
+ - ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A.
180
+ - ``COLAMD``: approximate minimum degree column ordering.
181
+
182
+ This option can impact the convergence of the
183
+ interior point algorithm; test different values to determine which
184
+ performs best for your problem. For more information, refer to
185
+ ``scipy.sparse.linalg.splu``.
186
+
187
+ Returns
188
+ -------
189
+ Search directions as defined in [4]
190
+
191
+ References
192
+ ----------
193
+ .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
194
+ optimizer for linear programming: an implementation of the
195
+ homogeneous algorithm." High performance optimization. Springer US,
196
+ 2000. 197-232.
197
+
198
+ """
199
+ if A.shape[0] == 0:
200
+ # If there are no constraints, some solvers fail (understandably)
201
+ # rather than returning empty solution. This gets the job done.
202
+ sparse, lstsq, sym_pos, cholesky = False, False, True, False
203
+ n_x = len(x)
204
+
205
+ # [4] Equation 8.8
206
+ r_P = b * tau - A.dot(x)
207
+ r_D = c * tau - A.T.dot(y) - z
208
+ r_G = c.dot(x) - b.transpose().dot(y) + kappa
209
+ mu = (x.dot(z) + tau * kappa) / (n_x + 1)
210
+
211
+ # Assemble M from [4] Equation 8.31
212
+ Dinv = x / z
213
+
214
+ if sparse:
215
+ M = A.dot(sps.diags(Dinv, 0, format="csc").dot(A.T))
216
+ else:
217
+ M = A.dot(Dinv.reshape(-1, 1) * A.T)
218
+ solve = _get_solver(M, sparse, lstsq, sym_pos, cholesky, permc_spec)
219
+
220
+ # pc: "predictor-corrector" [4] Section 4.1
221
+ # In development this option could be turned off
222
+ # but it always seems to improve performance substantially
223
+ n_corrections = 1 if pc else 0
224
+
225
+ i = 0
226
+ alpha, d_x, d_z, d_tau, d_kappa = 0, 0, 0, 0, 0
227
+ while i <= n_corrections:
228
+ # Reference [4] Eq. 8.6
229
+ rhatp = eta(gamma) * r_P
230
+ rhatd = eta(gamma) * r_D
231
+ rhatg = eta(gamma) * r_G
232
+
233
+ # Reference [4] Eq. 8.7
234
+ rhatxs = gamma * mu - x * z
235
+ rhattk = gamma * mu - tau * kappa
236
+
237
+ if i == 1:
238
+ if ip: # if the correction is to get "initial point"
239
+ # Reference [4] Eq. 8.23
240
+ rhatxs = ((1 - alpha) * gamma * mu -
241
+ x * z - alpha**2 * d_x * d_z)
242
+ rhattk = ((1 - alpha) * gamma * mu -
243
+ tau * kappa -
244
+ alpha**2 * d_tau * d_kappa)
245
+ else: # if the correction is for "predictor-corrector"
246
+ # Reference [4] Eq. 8.13
247
+ rhatxs -= d_x * d_z
248
+ rhattk -= d_tau * d_kappa
249
+
250
+ # sometimes numerical difficulties arise as the solution is approached
251
+ # this loop tries to solve the equations using a sequence of functions
252
+ # for solve. For dense systems, the order is:
253
+ # 1. scipy.linalg.cho_factor/scipy.linalg.cho_solve,
254
+ # 2. scipy.linalg.solve w/ sym_pos = True,
255
+ # 3. scipy.linalg.solve w/ sym_pos = False, and if all else fails
256
+ # 4. scipy.linalg.lstsq
257
+ # For sparse systems, the order is:
258
+ # 1. sksparse.cholmod.cholesky (if available)
259
+ # 2. scipy.sparse.linalg.factorized (if umfpack available)
260
+ # 3. scipy.sparse.linalg.splu
261
+ # 4. scipy.sparse.linalg.lsqr
262
+ solved = False
263
+ while not solved:
264
+ try:
265
+ # [4] Equation 8.28
266
+ p, q = _sym_solve(Dinv, A, c, b, solve)
267
+ # [4] Equation 8.29
268
+ u, v = _sym_solve(Dinv, A, rhatd -
269
+ (1 / x) * rhatxs, rhatp, solve)
270
+ if np.any(np.isnan(p)) or np.any(np.isnan(q)):
271
+ raise LinAlgError
272
+ solved = True
273
+ except (LinAlgError, ValueError, TypeError) as e:
274
+ # Usually this doesn't happen. If it does, it happens when
275
+ # there are redundant constraints or when approaching the
276
+ # solution. If so, change solver.
277
+ if cholesky:
278
+ cholesky = False
279
+ warn(
280
+ "Solving system with option 'cholesky':True "
281
+ "failed. It is normal for this to happen "
282
+ "occasionally, especially as the solution is "
283
+ "approached. However, if you see this frequently, "
284
+ "consider setting option 'cholesky' to False.",
285
+ OptimizeWarning, stacklevel=5)
286
+ elif sym_pos:
287
+ sym_pos = False
288
+ warn(
289
+ "Solving system with option 'sym_pos':True "
290
+ "failed. It is normal for this to happen "
291
+ "occasionally, especially as the solution is "
292
+ "approached. However, if you see this frequently, "
293
+ "consider setting option 'sym_pos' to False.",
294
+ OptimizeWarning, stacklevel=5)
295
+ elif not lstsq:
296
+ lstsq = True
297
+ warn(
298
+ "Solving system with option 'sym_pos':False "
299
+ "failed. This may happen occasionally, "
300
+ "especially as the solution is "
301
+ "approached. However, if you see this frequently, "
302
+ "your problem may be numerically challenging. "
303
+ "If you cannot improve the formulation, consider "
304
+ "setting 'lstsq' to True. Consider also setting "
305
+ "`presolve` to True, if it is not already.",
306
+ OptimizeWarning, stacklevel=5)
307
+ else:
308
+ raise e
309
+ solve = _get_solver(M, sparse, lstsq, sym_pos,
310
+ cholesky, permc_spec)
311
+ # [4] Results after 8.29
312
+ d_tau = ((rhatg + 1 / tau * rhattk - (-c.dot(u) + b.dot(v))) /
313
+ (1 / tau * kappa + (-c.dot(p) + b.dot(q))))
314
+ d_x = u + p * d_tau
315
+ d_y = v + q * d_tau
316
+
317
+ # [4] Relations between after 8.25 and 8.26
318
+ d_z = (1 / x) * (rhatxs - z * d_x)
319
+ d_kappa = 1 / tau * (rhattk - kappa * d_tau)
320
+
321
+ # [4] 8.12 and "Let alpha be the maximal possible step..." before 8.23
322
+ alpha = _get_step(x, d_x, z, d_z, tau, d_tau, kappa, d_kappa, 1)
323
+ if ip: # initial point - see [4] 4.4
324
+ gamma = 10
325
+ else: # predictor-corrector, [4] definition after 8.12
326
+ beta1 = 0.1 # [4] pg. 220 (Table 8.1)
327
+ gamma = (1 - alpha)**2 * min(beta1, (1 - alpha))
328
+ i += 1
329
+
330
+ return d_x, d_y, d_z, d_tau, d_kappa
331
+
332
+
333
+ def _sym_solve(Dinv, A, r1, r2, solve):
334
+ """
335
+ An implementation of [4] equation 8.31 and 8.32
336
+
337
+ References
338
+ ----------
339
+ .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
340
+ optimizer for linear programming: an implementation of the
341
+ homogeneous algorithm." High performance optimization. Springer US,
342
+ 2000. 197-232.
343
+
344
+ """
345
+ # [4] 8.31
346
+ r = r2 + A.dot(Dinv * r1)
347
+ v = solve(r)
348
+ # [4] 8.32
349
+ u = Dinv * (A.T.dot(v) - r1)
350
+ return u, v
351
+
352
+
353
+ def _get_step(x, d_x, z, d_z, tau, d_tau, kappa, d_kappa, alpha0):
354
+ """
355
+ An implementation of [4] equation 8.21
356
+
357
+ References
358
+ ----------
359
+ .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
360
+ optimizer for linear programming: an implementation of the
361
+ homogeneous algorithm." High performance optimization. Springer US,
362
+ 2000. 197-232.
363
+
364
+ """
365
+ # [4] 4.3 Equation 8.21, ignoring 8.20 requirement
366
+ # same step is taken in primal and dual spaces
367
+ # alpha0 is basically beta3 from [4] Table 8.1, but instead of beta3
368
+ # the value 1 is used in Mehrota corrector and initial point correction
369
+ i_x = d_x < 0
370
+ i_z = d_z < 0
371
+ alpha_x = alpha0 * np.min(x[i_x] / -d_x[i_x]) if np.any(i_x) else 1
372
+ alpha_tau = alpha0 * tau / -d_tau if d_tau < 0 else 1
373
+ alpha_z = alpha0 * np.min(z[i_z] / -d_z[i_z]) if np.any(i_z) else 1
374
+ alpha_kappa = alpha0 * kappa / -d_kappa if d_kappa < 0 else 1
375
+ alpha = np.min([1, alpha_x, alpha_tau, alpha_z, alpha_kappa])
376
+ return alpha
377
+
378
+
379
+ def _get_message(status):
380
+ """
381
+ Given problem status code, return a more detailed message.
382
+
383
+ Parameters
384
+ ----------
385
+ status : int
386
+ An integer representing the exit status of the optimization::
387
+
388
+ 0 : Optimization terminated successfully
389
+ 1 : Iteration limit reached
390
+ 2 : Problem appears to be infeasible
391
+ 3 : Problem appears to be unbounded
392
+ 4 : Serious numerical difficulties encountered
393
+
394
+ Returns
395
+ -------
396
+ message : str
397
+ A string descriptor of the exit status of the optimization.
398
+
399
+ """
400
+ messages = (
401
+ ["Optimization terminated successfully.",
402
+ "The iteration limit was reached before the algorithm converged.",
403
+ "The algorithm terminated successfully and determined that the "
404
+ "problem is infeasible.",
405
+ "The algorithm terminated successfully and determined that the "
406
+ "problem is unbounded.",
407
+ "Numerical difficulties were encountered before the problem "
408
+ "converged. Please check your problem formulation for errors, "
409
+ "independence of linear equality constraints, and reasonable "
410
+ "scaling and matrix condition numbers. If you continue to "
411
+ "encounter this error, please submit a bug report."
412
+ ])
413
+ return messages[status]
414
+
415
+
416
+ def _do_step(x, y, z, tau, kappa, d_x, d_y, d_z, d_tau, d_kappa, alpha):
417
+ """
418
+ An implementation of [4] Equation 8.9
419
+
420
+ References
421
+ ----------
422
+ .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
423
+ optimizer for linear programming: an implementation of the
424
+ homogeneous algorithm." High performance optimization. Springer US,
425
+ 2000. 197-232.
426
+
427
+ """
428
+ x = x + alpha * d_x
429
+ tau = tau + alpha * d_tau
430
+ z = z + alpha * d_z
431
+ kappa = kappa + alpha * d_kappa
432
+ y = y + alpha * d_y
433
+ return x, y, z, tau, kappa
434
+
435
+
436
+ def _get_blind_start(shape):
437
+ """
438
+ Return the starting point from [4] 4.4
439
+
440
+ References
441
+ ----------
442
+ .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
443
+ optimizer for linear programming: an implementation of the
444
+ homogeneous algorithm." High performance optimization. Springer US,
445
+ 2000. 197-232.
446
+
447
+ """
448
+ m, n = shape
449
+ x0 = np.ones(n)
450
+ y0 = np.zeros(m)
451
+ z0 = np.ones(n)
452
+ tau0 = 1
453
+ kappa0 = 1
454
+ return x0, y0, z0, tau0, kappa0
455
+
456
+
457
+ def _indicators(A, b, c, c0, x, y, z, tau, kappa):
458
+ """
459
+ Implementation of several equations from [4] used as indicators of
460
+ the status of optimization.
461
+
462
+ References
463
+ ----------
464
+ .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
465
+ optimizer for linear programming: an implementation of the
466
+ homogeneous algorithm." High performance optimization. Springer US,
467
+ 2000. 197-232.
468
+
469
+ """
470
+
471
+ # residuals for termination are relative to initial values
472
+ x0, y0, z0, tau0, kappa0 = _get_blind_start(A.shape)
473
+
474
+ # See [4], Section 4 - The Homogeneous Algorithm, Equation 8.8
475
+ def r_p(x, tau):
476
+ return b * tau - A.dot(x)
477
+
478
+ def r_d(y, z, tau):
479
+ return c * tau - A.T.dot(y) - z
480
+
481
+ def r_g(x, y, kappa):
482
+ return kappa + c.dot(x) - b.dot(y)
483
+
484
+ # np.dot unpacks if they are arrays of size one
485
+ def mu(x, tau, z, kappa):
486
+ return (x.dot(z) + np.dot(tau, kappa)) / (len(x) + 1)
487
+
488
+ obj = c.dot(x / tau) + c0
489
+
490
+ def norm(a):
491
+ return np.linalg.norm(a)
492
+
493
+ # See [4], Section 4.5 - The Stopping Criteria
494
+ r_p0 = r_p(x0, tau0)
495
+ r_d0 = r_d(y0, z0, tau0)
496
+ r_g0 = r_g(x0, y0, kappa0)
497
+ mu_0 = mu(x0, tau0, z0, kappa0)
498
+ rho_A = norm(c.T.dot(x) - b.T.dot(y)) / (tau + norm(b.T.dot(y)))
499
+ rho_p = norm(r_p(x, tau)) / max(1, norm(r_p0))
500
+ rho_d = norm(r_d(y, z, tau)) / max(1, norm(r_d0))
501
+ rho_g = norm(r_g(x, y, kappa)) / max(1, norm(r_g0))
502
+ rho_mu = mu(x, tau, z, kappa) / mu_0
503
+ return rho_p, rho_d, rho_A, rho_g, rho_mu, obj
504
+
505
+
506
+ def _display_iter(rho_p, rho_d, rho_g, alpha, rho_mu, obj, header=False):
507
+ """
508
+ Print indicators of optimization status to the console.
509
+
510
+ Parameters
511
+ ----------
512
+ rho_p : float
513
+ The (normalized) primal feasibility, see [4] 4.5
514
+ rho_d : float
515
+ The (normalized) dual feasibility, see [4] 4.5
516
+ rho_g : float
517
+ The (normalized) duality gap, see [4] 4.5
518
+ alpha : float
519
+ The step size, see [4] 4.3
520
+ rho_mu : float
521
+ The (normalized) path parameter, see [4] 4.5
522
+ obj : float
523
+ The objective function value of the current iterate
524
+ header : bool
525
+ True if a header is to be printed
526
+
527
+ References
528
+ ----------
529
+ .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
530
+ optimizer for linear programming: an implementation of the
531
+ homogeneous algorithm." High performance optimization. Springer US,
532
+ 2000. 197-232.
533
+
534
+ """
535
+ if header:
536
+ print("Primal Feasibility ",
537
+ "Dual Feasibility ",
538
+ "Duality Gap ",
539
+ "Step ",
540
+ "Path Parameter ",
541
+ "Objective ")
542
+
543
+ # no clue why this works
544
+ fmt = '{0:<20.13}{1:<20.13}{2:<20.13}{3:<17.13}{4:<20.13}{5:<20.13}'
545
+ print(fmt.format(
546
+ float(rho_p),
547
+ float(rho_d),
548
+ float(rho_g),
549
+ alpha if isinstance(alpha, str) else float(alpha),
550
+ float(rho_mu),
551
+ float(obj)))
552
+
553
+
554
+ def _ip_hsd(A, b, c, c0, alpha0, beta, maxiter, disp, tol, sparse, lstsq,
555
+ sym_pos, cholesky, pc, ip, permc_spec, callback, postsolve_args):
556
+ r"""
557
+ Solve a linear programming problem in standard form:
558
+
559
+ Minimize::
560
+
561
+ c @ x
562
+
563
+ Subject to::
564
+
565
+ A @ x == b
566
+ x >= 0
567
+
568
+ using the interior point method of [4].
569
+
570
+ Parameters
571
+ ----------
572
+ A : 2-D array
573
+ 2-D array such that ``A @ x``, gives the values of the equality
574
+ constraints at ``x``.
575
+ b : 1-D array
576
+ 1-D array of values representing the RHS of each equality constraint
577
+ (row) in ``A`` (for standard form problem).
578
+ c : 1-D array
579
+ Coefficients of the linear objective function to be minimized (for
580
+ standard form problem).
581
+ c0 : float
582
+ Constant term in objective function due to fixed (and eliminated)
583
+ variables. (Purely for display.)
584
+ alpha0 : float
585
+ The maximal step size for Mehrota's predictor-corrector search
586
+ direction; see :math:`\beta_3`of [4] Table 8.1
587
+ beta : float
588
+ The desired reduction of the path parameter :math:`\mu` (see [6]_)
589
+ maxiter : int
590
+ The maximum number of iterations of the algorithm.
591
+ disp : bool
592
+ Set to ``True`` if indicators of optimization status are to be printed
593
+ to the console each iteration.
594
+ tol : float
595
+ Termination tolerance; see [4]_ Section 4.5.
596
+ sparse : bool
597
+ Set to ``True`` if the problem is to be treated as sparse. However,
598
+ the inputs ``A_eq`` and ``A_ub`` should nonetheless be provided as
599
+ (dense) arrays rather than sparse matrices.
600
+ lstsq : bool
601
+ Set to ``True`` if the problem is expected to be very poorly
602
+ conditioned. This should always be left as ``False`` unless severe
603
+ numerical difficulties are frequently encountered, and a better option
604
+ would be to improve the formulation of the problem.
605
+ sym_pos : bool
606
+ Leave ``True`` if the problem is expected to yield a well conditioned
607
+ symmetric positive definite normal equation matrix (almost always).
608
+ cholesky : bool
609
+ Set to ``True`` if the normal equations are to be solved by explicit
610
+ Cholesky decomposition followed by explicit forward/backward
611
+ substitution. This is typically faster for moderate, dense problems
612
+ that are numerically well-behaved.
613
+ pc : bool
614
+ Leave ``True`` if the predictor-corrector method of Mehrota is to be
615
+ used. This is almost always (if not always) beneficial.
616
+ ip : bool
617
+ Set to ``True`` if the improved initial point suggestion due to [4]_
618
+ Section 4.3 is desired. It's unclear whether this is beneficial.
619
+ permc_spec : str (default = 'MMD_AT_PLUS_A')
620
+ (Has effect only with ``sparse = True``, ``lstsq = False``, ``sym_pos =
621
+ True``.) A matrix is factorized in each iteration of the algorithm.
622
+ This option specifies how to permute the columns of the matrix for
623
+ sparsity preservation. Acceptable values are:
624
+
625
+ - ``NATURAL``: natural ordering.
626
+ - ``MMD_ATA``: minimum degree ordering on the structure of A^T A.
627
+ - ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A.
628
+ - ``COLAMD``: approximate minimum degree column ordering.
629
+
630
+ This option can impact the convergence of the
631
+ interior point algorithm; test different values to determine which
632
+ performs best for your problem. For more information, refer to
633
+ ``scipy.sparse.linalg.splu``.
634
+ callback : callable, optional
635
+ If a callback function is provided, it will be called within each
636
+ iteration of the algorithm. The callback function must accept a single
637
+ `scipy.optimize.OptimizeResult` consisting of the following fields:
638
+
639
+ x : 1-D array
640
+ Current solution vector
641
+ fun : float
642
+ Current value of the objective function
643
+ success : bool
644
+ True only when an algorithm has completed successfully,
645
+ so this is always False as the callback function is called
646
+ only while the algorithm is still iterating.
647
+ slack : 1-D array
648
+ The values of the slack variables. Each slack variable
649
+ corresponds to an inequality constraint. If the slack is zero,
650
+ the corresponding constraint is active.
651
+ con : 1-D array
652
+ The (nominally zero) residuals of the equality constraints,
653
+ that is, ``b - A_eq @ x``
654
+ phase : int
655
+ The phase of the algorithm being executed. This is always
656
+ 1 for the interior-point method because it has only one phase.
657
+ status : int
658
+ For revised simplex, this is always 0 because if a different
659
+ status is detected, the algorithm terminates.
660
+ nit : int
661
+ The number of iterations performed.
662
+ message : str
663
+ A string descriptor of the exit status of the optimization.
664
+ postsolve_args : tuple
665
+ Data needed by _postsolve to convert the solution to the standard-form
666
+ problem into the solution to the original problem.
667
+
668
+ Returns
669
+ -------
670
+ x_hat : float
671
+ Solution vector (for standard form problem).
672
+ status : int
673
+ An integer representing the exit status of the optimization::
674
+
675
+ 0 : Optimization terminated successfully
676
+ 1 : Iteration limit reached
677
+ 2 : Problem appears to be infeasible
678
+ 3 : Problem appears to be unbounded
679
+ 4 : Serious numerical difficulties encountered
680
+
681
+ message : str
682
+ A string descriptor of the exit status of the optimization.
683
+ iteration : int
684
+ The number of iterations taken to solve the problem
685
+
686
+ References
687
+ ----------
688
+ .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
689
+ optimizer for linear programming: an implementation of the
690
+ homogeneous algorithm." High performance optimization. Springer US,
691
+ 2000. 197-232.
692
+ .. [6] Freund, Robert M. "Primal-Dual Interior-Point Methods for Linear
693
+ Programming based on Newton's Method." Unpublished Course Notes,
694
+ March 2004. Available 2/25/2017 at:
695
+ https://ocw.mit.edu/courses/sloan-school-of-management/15-084j-nonlinear-programming-spring-2004/lecture-notes/lec14_int_pt_mthd.pdf
696
+
697
+ """
698
+
699
+ iteration = 0
700
+
701
+ # default initial point
702
+ x, y, z, tau, kappa = _get_blind_start(A.shape)
703
+
704
+ # first iteration is special improvement of initial point
705
+ ip = ip if pc else False
706
+
707
+ # [4] 4.5
708
+ rho_p, rho_d, rho_A, rho_g, rho_mu, obj = _indicators(
709
+ A, b, c, c0, x, y, z, tau, kappa)
710
+ go = rho_p > tol or rho_d > tol or rho_A > tol # we might get lucky : )
711
+
712
+ if disp:
713
+ _display_iter(rho_p, rho_d, rho_g, "-", rho_mu, obj, header=True)
714
+ if callback is not None:
715
+ x_o, fun, slack, con = _postsolve(x/tau, postsolve_args)
716
+ res = OptimizeResult({'x': x_o, 'fun': fun, 'slack': slack,
717
+ 'con': con, 'nit': iteration, 'phase': 1,
718
+ 'complete': False, 'status': 0,
719
+ 'message': "", 'success': False})
720
+ callback(res)
721
+
722
+ status = 0
723
+ message = "Optimization terminated successfully."
724
+
725
+ if sparse:
726
+ A = sps.csc_matrix(A)
727
+
728
+ while go:
729
+
730
+ iteration += 1
731
+
732
+ if ip: # initial point
733
+ # [4] Section 4.4
734
+ gamma = 1
735
+
736
+ def eta(g):
737
+ return 1
738
+ else:
739
+ # gamma = 0 in predictor step according to [4] 4.1
740
+ # if predictor/corrector is off, use mean of complementarity [6]
741
+ # 5.1 / [4] Below Figure 10-4
742
+ gamma = 0 if pc else beta * np.mean(z * x)
743
+ # [4] Section 4.1
744
+
745
+ def eta(g=gamma):
746
+ return 1 - g
747
+
748
+ try:
749
+ # Solve [4] 8.6 and 8.7/8.13/8.23
750
+ d_x, d_y, d_z, d_tau, d_kappa = _get_delta(
751
+ A, b, c, x, y, z, tau, kappa, gamma, eta,
752
+ sparse, lstsq, sym_pos, cholesky, pc, ip, permc_spec)
753
+
754
+ if ip: # initial point
755
+ # [4] 4.4
756
+ # Formula after 8.23 takes a full step regardless if this will
757
+ # take it negative
758
+ alpha = 1.0
759
+ x, y, z, tau, kappa = _do_step(
760
+ x, y, z, tau, kappa, d_x, d_y,
761
+ d_z, d_tau, d_kappa, alpha)
762
+ x[x < 1] = 1
763
+ z[z < 1] = 1
764
+ tau = max(1, tau)
765
+ kappa = max(1, kappa)
766
+ ip = False # done with initial point
767
+ else:
768
+ # [4] Section 4.3
769
+ alpha = _get_step(x, d_x, z, d_z, tau,
770
+ d_tau, kappa, d_kappa, alpha0)
771
+ # [4] Equation 8.9
772
+ x, y, z, tau, kappa = _do_step(
773
+ x, y, z, tau, kappa, d_x, d_y, d_z, d_tau, d_kappa, alpha)
774
+
775
+ except (LinAlgError, FloatingPointError,
776
+ ValueError, ZeroDivisionError):
777
+ # this can happen when sparse solver is used and presolve
778
+ # is turned off. Also observed ValueError in AppVeyor Python 3.6
779
+ # Win32 build (PR #8676). I've never seen it otherwise.
780
+ status = 4
781
+ message = _get_message(status)
782
+ break
783
+
784
+ # [4] 4.5
785
+ rho_p, rho_d, rho_A, rho_g, rho_mu, obj = _indicators(
786
+ A, b, c, c0, x, y, z, tau, kappa)
787
+ go = rho_p > tol or rho_d > tol or rho_A > tol
788
+
789
+ if disp:
790
+ _display_iter(rho_p, rho_d, rho_g, alpha, rho_mu, obj)
791
+ if callback is not None:
792
+ x_o, fun, slack, con = _postsolve(x/tau, postsolve_args)
793
+ res = OptimizeResult({'x': x_o, 'fun': fun, 'slack': slack,
794
+ 'con': con, 'nit': iteration, 'phase': 1,
795
+ 'complete': False, 'status': 0,
796
+ 'message': "", 'success': False})
797
+ callback(res)
798
+
799
+ # [4] 4.5
800
+ inf1 = (rho_p < tol and rho_d < tol and rho_g < tol and tau < tol *
801
+ max(1, kappa))
802
+ inf2 = rho_mu < tol and tau < tol * min(1, kappa)
803
+ if inf1 or inf2:
804
+ # [4] Lemma 8.4 / Theorem 8.3
805
+ if b.transpose().dot(y) > tol:
806
+ status = 2
807
+ else: # elif c.T.dot(x) < tol: ? Probably not necessary.
808
+ status = 3
809
+ message = _get_message(status)
810
+ break
811
+ elif iteration >= maxiter:
812
+ status = 1
813
+ message = _get_message(status)
814
+ break
815
+
816
+ x_hat = x / tau
817
+ # [4] Statement after Theorem 8.2
818
+ return x_hat, status, message, iteration
819
+
820
+
821
+ def _linprog_ip(c, c0, A, b, callback, postsolve_args, maxiter=1000, tol=1e-8,
822
+ disp=False, alpha0=.99995, beta=0.1, sparse=False, lstsq=False,
823
+ sym_pos=True, cholesky=None, pc=True, ip=False,
824
+ permc_spec='MMD_AT_PLUS_A', **unknown_options):
825
+ r"""
826
+ Minimize a linear objective function subject to linear
827
+ equality and non-negativity constraints using the interior point method
828
+ of [4]_. Linear programming is intended to solve problems
829
+ of the following form:
830
+
831
+ Minimize::
832
+
833
+ c @ x
834
+
835
+ Subject to::
836
+
837
+ A @ x == b
838
+ x >= 0
839
+
840
+ User-facing documentation is in _linprog_doc.py.
841
+
842
+ Parameters
843
+ ----------
844
+ c : 1-D array
845
+ Coefficients of the linear objective function to be minimized.
846
+ c0 : float
847
+ Constant term in objective function due to fixed (and eliminated)
848
+ variables. (Purely for display.)
849
+ A : 2-D array
850
+ 2-D array such that ``A @ x``, gives the values of the equality
851
+ constraints at ``x``.
852
+ b : 1-D array
853
+ 1-D array of values representing the right hand side of each equality
854
+ constraint (row) in ``A``.
855
+ callback : callable, optional
856
+ Callback function to be executed once per iteration.
857
+ postsolve_args : tuple
858
+ Data needed by _postsolve to convert the solution to the standard-form
859
+ problem into the solution to the original problem.
860
+
861
+ Options
862
+ -------
863
+ maxiter : int (default = 1000)
864
+ The maximum number of iterations of the algorithm.
865
+ tol : float (default = 1e-8)
866
+ Termination tolerance to be used for all termination criteria;
867
+ see [4]_ Section 4.5.
868
+ disp : bool (default = False)
869
+ Set to ``True`` if indicators of optimization status are to be printed
870
+ to the console each iteration.
871
+ alpha0 : float (default = 0.99995)
872
+ The maximal step size for Mehrota's predictor-corrector search
873
+ direction; see :math:`\beta_{3}` of [4]_ Table 8.1.
874
+ beta : float (default = 0.1)
875
+ The desired reduction of the path parameter :math:`\mu` (see [6]_)
876
+ when Mehrota's predictor-corrector is not in use (uncommon).
877
+ sparse : bool (default = False)
878
+ Set to ``True`` if the problem is to be treated as sparse after
879
+ presolve. If either ``A_eq`` or ``A_ub`` is a sparse matrix,
880
+ this option will automatically be set ``True``, and the problem
881
+ will be treated as sparse even during presolve. If your constraint
882
+ matrices contain mostly zeros and the problem is not very small (less
883
+ than about 100 constraints or variables), consider setting ``True``
884
+ or providing ``A_eq`` and ``A_ub`` as sparse matrices.
885
+ lstsq : bool (default = False)
886
+ Set to ``True`` if the problem is expected to be very poorly
887
+ conditioned. This should always be left ``False`` unless severe
888
+ numerical difficulties are encountered. Leave this at the default
889
+ unless you receive a warning message suggesting otherwise.
890
+ sym_pos : bool (default = True)
891
+ Leave ``True`` if the problem is expected to yield a well conditioned
892
+ symmetric positive definite normal equation matrix
893
+ (almost always). Leave this at the default unless you receive
894
+ a warning message suggesting otherwise.
895
+ cholesky : bool (default = True)
896
+ Set to ``True`` if the normal equations are to be solved by explicit
897
+ Cholesky decomposition followed by explicit forward/backward
898
+ substitution. This is typically faster for problems
899
+ that are numerically well-behaved.
900
+ pc : bool (default = True)
901
+ Leave ``True`` if the predictor-corrector method of Mehrota is to be
902
+ used. This is almost always (if not always) beneficial.
903
+ ip : bool (default = False)
904
+ Set to ``True`` if the improved initial point suggestion due to [4]_
905
+ Section 4.3 is desired. Whether this is beneficial or not
906
+ depends on the problem.
907
+ permc_spec : str (default = 'MMD_AT_PLUS_A')
908
+ (Has effect only with ``sparse = True``, ``lstsq = False``, ``sym_pos =
909
+ True``, and no SuiteSparse.)
910
+ A matrix is factorized in each iteration of the algorithm.
911
+ This option specifies how to permute the columns of the matrix for
912
+ sparsity preservation. Acceptable values are:
913
+
914
+ - ``NATURAL``: natural ordering.
915
+ - ``MMD_ATA``: minimum degree ordering on the structure of A^T A.
916
+ - ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A.
917
+ - ``COLAMD``: approximate minimum degree column ordering.
918
+
919
+ This option can impact the convergence of the
920
+ interior point algorithm; test different values to determine which
921
+ performs best for your problem. For more information, refer to
922
+ ``scipy.sparse.linalg.splu``.
923
+ unknown_options : dict
924
+ Optional arguments not used by this particular solver. If
925
+ `unknown_options` is non-empty a warning is issued listing all
926
+ unused options.
927
+
928
+ Returns
929
+ -------
930
+ x : 1-D array
931
+ Solution vector.
932
+ status : int
933
+ An integer representing the exit status of the optimization::
934
+
935
+ 0 : Optimization terminated successfully
936
+ 1 : Iteration limit reached
937
+ 2 : Problem appears to be infeasible
938
+ 3 : Problem appears to be unbounded
939
+ 4 : Serious numerical difficulties encountered
940
+
941
+ message : str
942
+ A string descriptor of the exit status of the optimization.
943
+ iteration : int
944
+ The number of iterations taken to solve the problem.
945
+
946
+ Notes
947
+ -----
948
+ This method implements the algorithm outlined in [4]_ with ideas from [8]_
949
+ and a structure inspired by the simpler methods of [6]_.
950
+
951
+ The primal-dual path following method begins with initial 'guesses' of
952
+ the primal and dual variables of the standard form problem and iteratively
953
+ attempts to solve the (nonlinear) Karush-Kuhn-Tucker conditions for the
954
+ problem with a gradually reduced logarithmic barrier term added to the
955
+ objective. This particular implementation uses a homogeneous self-dual
956
+ formulation, which provides certificates of infeasibility or unboundedness
957
+ where applicable.
958
+
959
+ The default initial point for the primal and dual variables is that
960
+ defined in [4]_ Section 4.4 Equation 8.22. Optionally (by setting initial
961
+ point option ``ip=True``), an alternate (potentially improved) starting
962
+ point can be calculated according to the additional recommendations of
963
+ [4]_ Section 4.4.
964
+
965
+ A search direction is calculated using the predictor-corrector method
966
+ (single correction) proposed by Mehrota and detailed in [4]_ Section 4.1.
967
+ (A potential improvement would be to implement the method of multiple
968
+ corrections described in [4]_ Section 4.2.) In practice, this is
969
+ accomplished by solving the normal equations, [4]_ Section 5.1 Equations
970
+ 8.31 and 8.32, derived from the Newton equations [4]_ Section 5 Equations
971
+ 8.25 (compare to [4]_ Section 4 Equations 8.6-8.8). The advantage of
972
+ solving the normal equations rather than 8.25 directly is that the
973
+ matrices involved are symmetric positive definite, so Cholesky
974
+ decomposition can be used rather than the more expensive LU factorization.
975
+
976
+ With default options, the solver used to perform the factorization depends
977
+ on third-party software availability and the conditioning of the problem.
978
+
979
+ For dense problems, solvers are tried in the following order:
980
+
981
+ 1. ``scipy.linalg.cho_factor``
982
+
983
+ 2. ``scipy.linalg.solve`` with option ``sym_pos=True``
984
+
985
+ 3. ``scipy.linalg.solve`` with option ``sym_pos=False``
986
+
987
+ 4. ``scipy.linalg.lstsq``
988
+
989
+ For sparse problems:
990
+
991
+ 1. ``sksparse.cholmod.cholesky`` (if scikit-sparse and SuiteSparse are installed)
992
+
993
+ 2. ``scipy.sparse.linalg.factorized``
994
+ (if scikit-umfpack and SuiteSparse are installed)
995
+
996
+ 3. ``scipy.sparse.linalg.splu`` (which uses SuperLU distributed with SciPy)
997
+
998
+ 4. ``scipy.sparse.linalg.lsqr``
999
+
1000
+ If the solver fails for any reason, successively more robust (but slower)
1001
+ solvers are attempted in the order indicated. Attempting, failing, and
1002
+ re-starting factorization can be time consuming, so if the problem is
1003
+ numerically challenging, options can be set to bypass solvers that are
1004
+ failing. Setting ``cholesky=False`` skips to solver 2,
1005
+ ``sym_pos=False`` skips to solver 3, and ``lstsq=True`` skips
1006
+ to solver 4 for both sparse and dense problems.
1007
+
1008
+ Potential improvements for combatting issues associated with dense
1009
+ columns in otherwise sparse problems are outlined in [4]_ Section 5.3 and
1010
+ [10]_ Section 4.1-4.2; the latter also discusses the alleviation of
1011
+ accuracy issues associated with the substitution approach to free
1012
+ variables.
1013
+
1014
+ After calculating the search direction, the maximum possible step size
1015
+ that does not activate the non-negativity constraints is calculated, and
1016
+ the smaller of this step size and unity is applied (as in [4]_ Section
1017
+ 4.1.) [4]_ Section 4.3 suggests improvements for choosing the step size.
1018
+
1019
+ The new point is tested according to the termination conditions of [4]_
1020
+ Section 4.5. The same tolerance, which can be set using the ``tol`` option,
1021
+ is used for all checks. (A potential improvement would be to expose
1022
+ the different tolerances to be set independently.) If optimality,
1023
+ unboundedness, or infeasibility is detected, the solve procedure
1024
+ terminates; otherwise it repeats.
1025
+
1026
+ The expected problem formulation differs between the top level ``linprog``
1027
+ module and the method specific solvers. The method specific solvers expect a
1028
+ problem in standard form:
1029
+
1030
+ Minimize::
1031
+
1032
+ c @ x
1033
+
1034
+ Subject to::
1035
+
1036
+ A @ x == b
1037
+ x >= 0
1038
+
1039
+ Whereas the top level ``linprog`` module expects a problem of form:
1040
+
1041
+ Minimize::
1042
+
1043
+ c @ x
1044
+
1045
+ Subject to::
1046
+
1047
+ A_ub @ x <= b_ub
1048
+ A_eq @ x == b_eq
1049
+ lb <= x <= ub
1050
+
1051
+ where ``lb = 0`` and ``ub = None`` unless set in ``bounds``.
1052
+
1053
+ The original problem contains equality, upper-bound and variable constraints
1054
+ whereas the method specific solver requires equality constraints and
1055
+ variable non-negativity.
1056
+
1057
+ ``linprog`` module converts the original problem to standard form by
1058
+ converting the simple bounds to upper bound constraints, introducing
1059
+ non-negative slack variables for inequality constraints, and expressing
1060
+ unbounded variables as the difference between two non-negative variables.
1061
+
1062
+
1063
+ References
1064
+ ----------
1065
+ .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
1066
+ optimizer for linear programming: an implementation of the
1067
+ homogeneous algorithm." High performance optimization. Springer US,
1068
+ 2000. 197-232.
1069
+ .. [6] Freund, Robert M. "Primal-Dual Interior-Point Methods for Linear
1070
+ Programming based on Newton's Method." Unpublished Course Notes,
1071
+ March 2004. Available 2/25/2017 at
1072
+ https://ocw.mit.edu/courses/sloan-school-of-management/15-084j-nonlinear-programming-spring-2004/lecture-notes/lec14_int_pt_mthd.pdf
1073
+ .. [8] Andersen, Erling D., and Knud D. Andersen. "Presolving in linear
1074
+ programming." Mathematical Programming 71.2 (1995): 221-245.
1075
+ .. [9] Bertsimas, Dimitris, and J. Tsitsiklis. "Introduction to linear
1076
+ programming." Athena Scientific 1 (1997): 997.
1077
+ .. [10] Andersen, Erling D., et al. Implementation of interior point methods
1078
+ for large scale linear programming. HEC/Universite de Geneve, 1996.
1079
+
1080
+ """
1081
+
1082
+ _check_unknown_options(unknown_options)
1083
+
1084
+ # These should be warnings, not errors
1085
+ if (cholesky or cholesky is None) and sparse and not has_cholmod:
1086
+ if cholesky:
1087
+ warn("Sparse cholesky is only available with scikit-sparse. "
1088
+ "Setting `cholesky = False`",
1089
+ OptimizeWarning, stacklevel=3)
1090
+ cholesky = False
1091
+
1092
+ if sparse and lstsq:
1093
+ warn("Option combination 'sparse':True and 'lstsq':True "
1094
+ "is not recommended.",
1095
+ OptimizeWarning, stacklevel=3)
1096
+
1097
+ if lstsq and cholesky:
1098
+ warn("Invalid option combination 'lstsq':True "
1099
+ "and 'cholesky':True; option 'cholesky' has no effect when "
1100
+ "'lstsq' is set True.",
1101
+ OptimizeWarning, stacklevel=3)
1102
+
1103
+ valid_permc_spec = ('NATURAL', 'MMD_ATA', 'MMD_AT_PLUS_A', 'COLAMD')
1104
+ if permc_spec.upper() not in valid_permc_spec:
1105
+ warn("Invalid permc_spec option: '" + str(permc_spec) + "'. "
1106
+ "Acceptable values are 'NATURAL', 'MMD_ATA', 'MMD_AT_PLUS_A', "
1107
+ "and 'COLAMD'. Reverting to default.",
1108
+ OptimizeWarning, stacklevel=3)
1109
+ permc_spec = 'MMD_AT_PLUS_A'
1110
+
1111
+ # This can be an error
1112
+ if not sym_pos and cholesky:
1113
+ raise ValueError(
1114
+ "Invalid option combination 'sym_pos':False "
1115
+ "and 'cholesky':True: Cholesky decomposition is only possible "
1116
+ "for symmetric positive definite matrices.")
1117
+
1118
+ cholesky = cholesky or (cholesky is None and sym_pos and not lstsq)
1119
+
1120
+ x, status, message, iteration = _ip_hsd(A, b, c, c0, alpha0, beta,
1121
+ maxiter, disp, tol, sparse,
1122
+ lstsq, sym_pos, cholesky,
1123
+ pc, ip, permc_spec, callback,
1124
+ postsolve_args)
1125
+
1126
+ return x, status, message, iteration
vila/lib/python3.10/site-packages/scipy/optimize/_linprog_rs.py ADDED
@@ -0,0 +1,572 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Revised simplex method for linear programming
2
+
3
+ The *revised simplex* method uses the method described in [1]_, except
4
+ that a factorization [2]_ of the basis matrix, rather than its inverse,
5
+ is efficiently maintained and used to solve the linear systems at each
6
+ iteration of the algorithm.
7
+
8
+ .. versionadded:: 1.3.0
9
+
10
+ References
11
+ ----------
12
+ .. [1] Bertsimas, Dimitris, and J. Tsitsiklis. "Introduction to linear
13
+ programming." Athena Scientific 1 (1997): 997.
14
+ .. [2] Bartels, Richard H. "A stabilization of the simplex method."
15
+ Journal in Numerische Mathematik 16.5 (1971): 414-434.
16
+
17
+ """
18
+ # Author: Matt Haberland
19
+
20
+ import numpy as np
21
+ from numpy.linalg import LinAlgError
22
+
23
+ from scipy.linalg import solve
24
+ from ._optimize import _check_unknown_options
25
+ from ._bglu_dense import LU
26
+ from ._bglu_dense import BGLU as BGLU
27
+ from ._linprog_util import _postsolve
28
+ from ._optimize import OptimizeResult
29
+
30
+
31
+ def _phase_one(A, b, x0, callback, postsolve_args, maxiter, tol, disp,
32
+ maxupdate, mast, pivot):
33
+ """
34
+ The purpose of phase one is to find an initial basic feasible solution
35
+ (BFS) to the original problem.
36
+
37
+ Generates an auxiliary problem with a trivial BFS and an objective that
38
+ minimizes infeasibility of the original problem. Solves the auxiliary
39
+ problem using the main simplex routine (phase two). This either yields
40
+ a BFS to the original problem or determines that the original problem is
41
+ infeasible. If feasible, phase one detects redundant rows in the original
42
+ constraint matrix and removes them, then chooses additional indices as
43
+ necessary to complete a basis/BFS for the original problem.
44
+ """
45
+
46
+ m, n = A.shape
47
+ status = 0
48
+
49
+ # generate auxiliary problem to get initial BFS
50
+ A, b, c, basis, x, status = _generate_auxiliary_problem(A, b, x0, tol)
51
+
52
+ if status == 6:
53
+ residual = c.dot(x)
54
+ iter_k = 0
55
+ return x, basis, A, b, residual, status, iter_k
56
+
57
+ # solve auxiliary problem
58
+ phase_one_n = n
59
+ iter_k = 0
60
+ x, basis, status, iter_k = _phase_two(c, A, x, basis, callback,
61
+ postsolve_args,
62
+ maxiter, tol, disp,
63
+ maxupdate, mast, pivot,
64
+ iter_k, phase_one_n)
65
+
66
+ # check for infeasibility
67
+ residual = c.dot(x)
68
+ if status == 0 and residual > tol:
69
+ status = 2
70
+
71
+ # drive artificial variables out of basis
72
+ # TODO: test redundant row removal better
73
+ # TODO: make solve more efficient with BGLU? This could take a while.
74
+ keep_rows = np.ones(m, dtype=bool)
75
+ for basis_column in basis[basis >= n]:
76
+ B = A[:, basis]
77
+ try:
78
+ basis_finder = np.abs(solve(B, A)) # inefficient
79
+ pertinent_row = np.argmax(basis_finder[:, basis_column])
80
+ eligible_columns = np.ones(n, dtype=bool)
81
+ eligible_columns[basis[basis < n]] = 0
82
+ eligible_column_indices = np.where(eligible_columns)[0]
83
+ index = np.argmax(basis_finder[:, :n]
84
+ [pertinent_row, eligible_columns])
85
+ new_basis_column = eligible_column_indices[index]
86
+ if basis_finder[pertinent_row, new_basis_column] < tol:
87
+ keep_rows[pertinent_row] = False
88
+ else:
89
+ basis[basis == basis_column] = new_basis_column
90
+ except LinAlgError:
91
+ status = 4
92
+
93
+ # form solution to original problem
94
+ A = A[keep_rows, :n]
95
+ basis = basis[keep_rows]
96
+ x = x[:n]
97
+ m = A.shape[0]
98
+ return x, basis, A, b, residual, status, iter_k
99
+
100
+
101
+ def _get_more_basis_columns(A, basis):
102
+ """
103
+ Called when the auxiliary problem terminates with artificial columns in
104
+ the basis, which must be removed and replaced with non-artificial
105
+ columns. Finds additional columns that do not make the matrix singular.
106
+ """
107
+ m, n = A.shape
108
+
109
+ # options for inclusion are those that aren't already in the basis
110
+ a = np.arange(m+n)
111
+ bl = np.zeros(len(a), dtype=bool)
112
+ bl[basis] = 1
113
+ options = a[~bl]
114
+ options = options[options < n] # and they have to be non-artificial
115
+
116
+ # form basis matrix
117
+ B = np.zeros((m, m))
118
+ B[:, 0:len(basis)] = A[:, basis]
119
+
120
+ if (basis.size > 0 and
121
+ np.linalg.matrix_rank(B[:, :len(basis)]) < len(basis)):
122
+ raise Exception("Basis has dependent columns")
123
+
124
+ rank = 0 # just enter the loop
125
+ for i in range(n): # somewhat arbitrary, but we need another way out
126
+ # permute the options, and take as many as needed
127
+ new_basis = np.random.permutation(options)[:m-len(basis)]
128
+ B[:, len(basis):] = A[:, new_basis] # update the basis matrix
129
+ rank = np.linalg.matrix_rank(B) # check the rank
130
+ if rank == m:
131
+ break
132
+
133
+ return np.concatenate((basis, new_basis))
134
+
135
+
136
+ def _generate_auxiliary_problem(A, b, x0, tol):
137
+ """
138
+ Modifies original problem to create an auxiliary problem with a trivial
139
+ initial basic feasible solution and an objective that minimizes
140
+ infeasibility in the original problem.
141
+
142
+ Conceptually, this is done by stacking an identity matrix on the right of
143
+ the original constraint matrix, adding artificial variables to correspond
144
+ with each of these new columns, and generating a cost vector that is all
145
+ zeros except for ones corresponding with each of the new variables.
146
+
147
+ A initial basic feasible solution is trivial: all variables are zero
148
+ except for the artificial variables, which are set equal to the
149
+ corresponding element of the right hand side `b`.
150
+
151
+ Running the simplex method on this auxiliary problem drives all of the
152
+ artificial variables - and thus the cost - to zero if the original problem
153
+ is feasible. The original problem is declared infeasible otherwise.
154
+
155
+ Much of the complexity below is to improve efficiency by using singleton
156
+ columns in the original problem where possible, thus generating artificial
157
+ variables only as necessary, and using an initial 'guess' basic feasible
158
+ solution.
159
+ """
160
+ status = 0
161
+ m, n = A.shape
162
+
163
+ if x0 is not None:
164
+ x = x0
165
+ else:
166
+ x = np.zeros(n)
167
+
168
+ r = b - A@x # residual; this must be all zeros for feasibility
169
+
170
+ A[r < 0] = -A[r < 0] # express problem with RHS positive for trivial BFS
171
+ b[r < 0] = -b[r < 0] # to the auxiliary problem
172
+ r[r < 0] *= -1
173
+
174
+ # Rows which we will need to find a trivial way to zero.
175
+ # This should just be the rows where there is a nonzero residual.
176
+ # But then we would not necessarily have a column singleton in every row.
177
+ # This makes it difficult to find an initial basis.
178
+ if x0 is None:
179
+ nonzero_constraints = np.arange(m)
180
+ else:
181
+ nonzero_constraints = np.where(r > tol)[0]
182
+
183
+ # these are (at least some of) the initial basis columns
184
+ basis = np.where(np.abs(x) > tol)[0]
185
+
186
+ if len(nonzero_constraints) == 0 and len(basis) <= m: # already a BFS
187
+ c = np.zeros(n)
188
+ basis = _get_more_basis_columns(A, basis)
189
+ return A, b, c, basis, x, status
190
+ elif (len(nonzero_constraints) > m - len(basis) or
191
+ np.any(x < 0)): # can't get trivial BFS
192
+ c = np.zeros(n)
193
+ status = 6
194
+ return A, b, c, basis, x, status
195
+
196
+ # chooses existing columns appropriate for inclusion in initial basis
197
+ cols, rows = _select_singleton_columns(A, r)
198
+
199
+ # find the rows we need to zero that we _can_ zero with column singletons
200
+ i_tofix = np.isin(rows, nonzero_constraints)
201
+ # these columns can't already be in the basis, though
202
+ # we are going to add them to the basis and change the corresponding x val
203
+ i_notinbasis = np.logical_not(np.isin(cols, basis))
204
+ i_fix_without_aux = np.logical_and(i_tofix, i_notinbasis)
205
+ rows = rows[i_fix_without_aux]
206
+ cols = cols[i_fix_without_aux]
207
+
208
+ # indices of the rows we can only zero with auxiliary variable
209
+ # these rows will get a one in each auxiliary column
210
+ arows = nonzero_constraints[np.logical_not(
211
+ np.isin(nonzero_constraints, rows))]
212
+ n_aux = len(arows)
213
+ acols = n + np.arange(n_aux) # indices of auxiliary columns
214
+
215
+ basis_ng = np.concatenate((cols, acols)) # basis columns not from guess
216
+ basis_ng_rows = np.concatenate((rows, arows)) # rows we need to zero
217
+
218
+ # add auxiliary singleton columns
219
+ A = np.hstack((A, np.zeros((m, n_aux))))
220
+ A[arows, acols] = 1
221
+
222
+ # generate initial BFS
223
+ x = np.concatenate((x, np.zeros(n_aux)))
224
+ x[basis_ng] = r[basis_ng_rows]/A[basis_ng_rows, basis_ng]
225
+
226
+ # generate costs to minimize infeasibility
227
+ c = np.zeros(n_aux + n)
228
+ c[acols] = 1
229
+
230
+ # basis columns correspond with nonzeros in guess, those with column
231
+ # singletons we used to zero remaining constraints, and any additional
232
+ # columns to get a full set (m columns)
233
+ basis = np.concatenate((basis, basis_ng))
234
+ basis = _get_more_basis_columns(A, basis) # add columns as needed
235
+
236
+ return A, b, c, basis, x, status
237
+
238
+
239
+ def _select_singleton_columns(A, b):
240
+ """
241
+ Finds singleton columns for which the singleton entry is of the same sign
242
+ as the right-hand side; these columns are eligible for inclusion in an
243
+ initial basis. Determines the rows in which the singleton entries are
244
+ located. For each of these rows, returns the indices of the one singleton
245
+ column and its corresponding row.
246
+ """
247
+ # find indices of all singleton columns and corresponding row indices
248
+ column_indices = np.nonzero(np.sum(np.abs(A) != 0, axis=0) == 1)[0]
249
+ columns = A[:, column_indices] # array of singleton columns
250
+ row_indices = np.zeros(len(column_indices), dtype=int)
251
+ nonzero_rows, nonzero_columns = np.nonzero(columns)
252
+ row_indices[nonzero_columns] = nonzero_rows # corresponding row indices
253
+
254
+ # keep only singletons with entries that have same sign as RHS
255
+ # this is necessary because all elements of BFS must be non-negative
256
+ same_sign = A[row_indices, column_indices]*b[row_indices] >= 0
257
+ column_indices = column_indices[same_sign][::-1]
258
+ row_indices = row_indices[same_sign][::-1]
259
+ # Reversing the order so that steps below select rightmost columns
260
+ # for initial basis, which will tend to be slack variables. (If the
261
+ # guess corresponds with a basic feasible solution but a constraint
262
+ # is not satisfied with the corresponding slack variable zero, the slack
263
+ # variable must be basic.)
264
+
265
+ # for each row, keep rightmost singleton column with an entry in that row
266
+ unique_row_indices, first_columns = np.unique(row_indices,
267
+ return_index=True)
268
+ return column_indices[first_columns], unique_row_indices
269
+
270
+
271
+ def _find_nonzero_rows(A, tol):
272
+ """
273
+ Returns logical array indicating the locations of rows with at least
274
+ one nonzero element.
275
+ """
276
+ return np.any(np.abs(A) > tol, axis=1)
277
+
278
+
279
+ def _select_enter_pivot(c_hat, bl, a, rule="bland", tol=1e-12):
280
+ """
281
+ Selects a pivot to enter the basis. Currently Bland's rule - the smallest
282
+ index that has a negative reduced cost - is the default.
283
+ """
284
+ if rule.lower() == "mrc": # index with minimum reduced cost
285
+ return a[~bl][np.argmin(c_hat)]
286
+ else: # smallest index w/ negative reduced cost
287
+ return a[~bl][c_hat < -tol][0]
288
+
289
+
290
+ def _display_iter(phase, iteration, slack, con, fun):
291
+ """
292
+ Print indicators of optimization status to the console.
293
+ """
294
+ header = True if not iteration % 20 else False
295
+
296
+ if header:
297
+ print("Phase",
298
+ "Iteration",
299
+ "Minimum Slack ",
300
+ "Constraint Residual",
301
+ "Objective ")
302
+
303
+ # :<X.Y left aligns Y digits in X digit spaces
304
+ fmt = '{0:<6}{1:<10}{2:<20.13}{3:<20.13}{4:<20.13}'
305
+ try:
306
+ slack = np.min(slack)
307
+ except ValueError:
308
+ slack = "NA"
309
+ print(fmt.format(phase, iteration, slack, np.linalg.norm(con), fun))
310
+
311
+
312
+ def _display_and_callback(phase_one_n, x, postsolve_args, status,
313
+ iteration, disp, callback):
314
+ if phase_one_n is not None:
315
+ phase = 1
316
+ x_postsolve = x[:phase_one_n]
317
+ else:
318
+ phase = 2
319
+ x_postsolve = x
320
+ x_o, fun, slack, con = _postsolve(x_postsolve,
321
+ postsolve_args)
322
+
323
+ if callback is not None:
324
+ res = OptimizeResult({'x': x_o, 'fun': fun, 'slack': slack,
325
+ 'con': con, 'nit': iteration,
326
+ 'phase': phase, 'complete': False,
327
+ 'status': status, 'message': "",
328
+ 'success': False})
329
+ callback(res)
330
+ if disp:
331
+ _display_iter(phase, iteration, slack, con, fun)
332
+
333
+
334
+ def _phase_two(c, A, x, b, callback, postsolve_args, maxiter, tol, disp,
335
+ maxupdate, mast, pivot, iteration=0, phase_one_n=None):
336
+ """
337
+ The heart of the simplex method. Beginning with a basic feasible solution,
338
+ moves to adjacent basic feasible solutions successively lower reduced cost.
339
+ Terminates when there are no basic feasible solutions with lower reduced
340
+ cost or if the problem is determined to be unbounded.
341
+
342
+ This implementation follows the revised simplex method based on LU
343
+ decomposition. Rather than maintaining a tableau or an inverse of the
344
+ basis matrix, we keep a factorization of the basis matrix that allows
345
+ efficient solution of linear systems while avoiding stability issues
346
+ associated with inverted matrices.
347
+ """
348
+ m, n = A.shape
349
+ status = 0
350
+ a = np.arange(n) # indices of columns of A
351
+ ab = np.arange(m) # indices of columns of B
352
+ if maxupdate:
353
+ # basis matrix factorization object; similar to B = A[:, b]
354
+ B = BGLU(A, b, maxupdate, mast)
355
+ else:
356
+ B = LU(A, b)
357
+
358
+ for iteration in range(iteration, maxiter):
359
+
360
+ if disp or callback is not None:
361
+ _display_and_callback(phase_one_n, x, postsolve_args, status,
362
+ iteration, disp, callback)
363
+
364
+ bl = np.zeros(len(a), dtype=bool)
365
+ bl[b] = 1
366
+
367
+ xb = x[b] # basic variables
368
+ cb = c[b] # basic costs
369
+
370
+ try:
371
+ v = B.solve(cb, transposed=True) # similar to v = solve(B.T, cb)
372
+ except LinAlgError:
373
+ status = 4
374
+ break
375
+
376
+ # TODO: cythonize?
377
+ c_hat = c - v.dot(A) # reduced cost
378
+ c_hat = c_hat[~bl]
379
+ # Above is much faster than:
380
+ # N = A[:, ~bl] # slow!
381
+ # c_hat = c[~bl] - v.T.dot(N)
382
+ # Can we perform the multiplication only on the nonbasic columns?
383
+
384
+ if np.all(c_hat >= -tol): # all reduced costs positive -> terminate
385
+ break
386
+
387
+ j = _select_enter_pivot(c_hat, bl, a, rule=pivot, tol=tol)
388
+ u = B.solve(A[:, j]) # similar to u = solve(B, A[:, j])
389
+
390
+ i = u > tol # if none of the u are positive, unbounded
391
+ if not np.any(i):
392
+ status = 3
393
+ break
394
+
395
+ th = xb[i]/u[i]
396
+ l = np.argmin(th) # implicitly selects smallest subscript
397
+ th_star = th[l] # step size
398
+
399
+ x[b] = x[b] - th_star*u # take step
400
+ x[j] = th_star
401
+ B.update(ab[i][l], j) # modify basis
402
+ b = B.b # similar to b[ab[i][l]] =
403
+
404
+ else:
405
+ # If the end of the for loop is reached (without a break statement),
406
+ # then another step has been taken, so the iteration counter should
407
+ # increment, info should be displayed, and callback should be called.
408
+ iteration += 1
409
+ status = 1
410
+ if disp or callback is not None:
411
+ _display_and_callback(phase_one_n, x, postsolve_args, status,
412
+ iteration, disp, callback)
413
+
414
+ return x, b, status, iteration
415
+
416
+
417
+ def _linprog_rs(c, c0, A, b, x0, callback, postsolve_args,
418
+ maxiter=5000, tol=1e-12, disp=False,
419
+ maxupdate=10, mast=False, pivot="mrc",
420
+ **unknown_options):
421
+ """
422
+ Solve the following linear programming problem via a two-phase
423
+ revised simplex algorithm.::
424
+
425
+ minimize: c @ x
426
+
427
+ subject to: A @ x == b
428
+ 0 <= x < oo
429
+
430
+ User-facing documentation is in _linprog_doc.py.
431
+
432
+ Parameters
433
+ ----------
434
+ c : 1-D array
435
+ Coefficients of the linear objective function to be minimized.
436
+ c0 : float
437
+ Constant term in objective function due to fixed (and eliminated)
438
+ variables. (Currently unused.)
439
+ A : 2-D array
440
+ 2-D array which, when matrix-multiplied by ``x``, gives the values of
441
+ the equality constraints at ``x``.
442
+ b : 1-D array
443
+ 1-D array of values representing the RHS of each equality constraint
444
+ (row) in ``A_eq``.
445
+ x0 : 1-D array, optional
446
+ Starting values of the independent variables, which will be refined by
447
+ the optimization algorithm. For the revised simplex method, these must
448
+ correspond with a basic feasible solution.
449
+ callback : callable, optional
450
+ If a callback function is provided, it will be called within each
451
+ iteration of the algorithm. The callback function must accept a single
452
+ `scipy.optimize.OptimizeResult` consisting of the following fields:
453
+
454
+ x : 1-D array
455
+ Current solution vector.
456
+ fun : float
457
+ Current value of the objective function ``c @ x``.
458
+ success : bool
459
+ True only when an algorithm has completed successfully,
460
+ so this is always False as the callback function is called
461
+ only while the algorithm is still iterating.
462
+ slack : 1-D array
463
+ The values of the slack variables. Each slack variable
464
+ corresponds to an inequality constraint. If the slack is zero,
465
+ the corresponding constraint is active.
466
+ con : 1-D array
467
+ The (nominally zero) residuals of the equality constraints,
468
+ that is, ``b - A_eq @ x``.
469
+ phase : int
470
+ The phase of the algorithm being executed.
471
+ status : int
472
+ For revised simplex, this is always 0 because if a different
473
+ status is detected, the algorithm terminates.
474
+ nit : int
475
+ The number of iterations performed.
476
+ message : str
477
+ A string descriptor of the exit status of the optimization.
478
+ postsolve_args : tuple
479
+ Data needed by _postsolve to convert the solution to the standard-form
480
+ problem into the solution to the original problem.
481
+
482
+ Options
483
+ -------
484
+ maxiter : int
485
+ The maximum number of iterations to perform in either phase.
486
+ tol : float
487
+ The tolerance which determines when a solution is "close enough" to
488
+ zero in Phase 1 to be considered a basic feasible solution or close
489
+ enough to positive to serve as an optimal solution.
490
+ disp : bool
491
+ Set to ``True`` if indicators of optimization status are to be printed
492
+ to the console each iteration.
493
+ maxupdate : int
494
+ The maximum number of updates performed on the LU factorization.
495
+ After this many updates is reached, the basis matrix is factorized
496
+ from scratch.
497
+ mast : bool
498
+ Minimize Amortized Solve Time. If enabled, the average time to solve
499
+ a linear system using the basis factorization is measured. Typically,
500
+ the average solve time will decrease with each successive solve after
501
+ initial factorization, as factorization takes much more time than the
502
+ solve operation (and updates). Eventually, however, the updated
503
+ factorization becomes sufficiently complex that the average solve time
504
+ begins to increase. When this is detected, the basis is refactorized
505
+ from scratch. Enable this option to maximize speed at the risk of
506
+ nondeterministic behavior. Ignored if ``maxupdate`` is 0.
507
+ pivot : "mrc" or "bland"
508
+ Pivot rule: Minimum Reduced Cost (default) or Bland's rule. Choose
509
+ Bland's rule if iteration limit is reached and cycling is suspected.
510
+ unknown_options : dict
511
+ Optional arguments not used by this particular solver. If
512
+ `unknown_options` is non-empty a warning is issued listing all
513
+ unused options.
514
+
515
+ Returns
516
+ -------
517
+ x : 1-D array
518
+ Solution vector.
519
+ status : int
520
+ An integer representing the exit status of the optimization::
521
+
522
+ 0 : Optimization terminated successfully
523
+ 1 : Iteration limit reached
524
+ 2 : Problem appears to be infeasible
525
+ 3 : Problem appears to be unbounded
526
+ 4 : Numerical difficulties encountered
527
+ 5 : No constraints; turn presolve on
528
+ 6 : Guess x0 cannot be converted to a basic feasible solution
529
+
530
+ message : str
531
+ A string descriptor of the exit status of the optimization.
532
+ iteration : int
533
+ The number of iterations taken to solve the problem.
534
+ """
535
+
536
+ _check_unknown_options(unknown_options)
537
+
538
+ messages = ["Optimization terminated successfully.",
539
+ "Iteration limit reached.",
540
+ "The problem appears infeasible, as the phase one auxiliary "
541
+ "problem terminated successfully with a residual of {0:.1e}, "
542
+ "greater than the tolerance {1} required for the solution to "
543
+ "be considered feasible. Consider increasing the tolerance to "
544
+ "be greater than {0:.1e}. If this tolerance is unnaceptably "
545
+ "large, the problem is likely infeasible.",
546
+ "The problem is unbounded, as the simplex algorithm found "
547
+ "a basic feasible solution from which there is a direction "
548
+ "with negative reduced cost in which all decision variables "
549
+ "increase.",
550
+ "Numerical difficulties encountered; consider trying "
551
+ "method='interior-point'.",
552
+ "Problems with no constraints are trivially solved; please "
553
+ "turn presolve on.",
554
+ "The guess x0 cannot be converted to a basic feasible "
555
+ "solution. "
556
+ ]
557
+
558
+ if A.size == 0: # address test_unbounded_below_no_presolve_corrected
559
+ return np.zeros(c.shape), 5, messages[5], 0
560
+
561
+ x, basis, A, b, residual, status, iteration = (
562
+ _phase_one(A, b, x0, callback, postsolve_args,
563
+ maxiter, tol, disp, maxupdate, mast, pivot))
564
+
565
+ if status == 0:
566
+ x, basis, status, iteration = _phase_two(c, A, x, basis, callback,
567
+ postsolve_args,
568
+ maxiter, tol, disp,
569
+ maxupdate, mast, pivot,
570
+ iteration)
571
+
572
+ return x, status, messages[status].format(residual, tol), iteration
vila/lib/python3.10/site-packages/scipy/optimize/_linprog_simplex.py ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Simplex method for linear programming
2
+
3
+ The *simplex* method uses a traditional, full-tableau implementation of
4
+ Dantzig's simplex algorithm [1]_, [2]_ (*not* the Nelder-Mead simplex).
5
+ This algorithm is included for backwards compatibility and educational
6
+ purposes.
7
+
8
+ .. versionadded:: 0.15.0
9
+
10
+ Warnings
11
+ --------
12
+
13
+ The simplex method may encounter numerical difficulties when pivot
14
+ values are close to the specified tolerance. If encountered try
15
+ remove any redundant constraints, change the pivot strategy to Bland's
16
+ rule or increase the tolerance value.
17
+
18
+ Alternatively, more robust methods maybe be used. See
19
+ :ref:`'interior-point' <optimize.linprog-interior-point>` and
20
+ :ref:`'revised simplex' <optimize.linprog-revised_simplex>`.
21
+
22
+ References
23
+ ----------
24
+ .. [1] Dantzig, George B., Linear programming and extensions. Rand
25
+ Corporation Research Study Princeton Univ. Press, Princeton, NJ,
26
+ 1963
27
+ .. [2] Hillier, S.H. and Lieberman, G.J. (1995), "Introduction to
28
+ Mathematical Programming", McGraw-Hill, Chapter 4.
29
+ """
30
+
31
+ import numpy as np
32
+ from warnings import warn
33
+ from ._optimize import OptimizeResult, OptimizeWarning, _check_unknown_options
34
+ from ._linprog_util import _postsolve
35
+
36
+
37
+ def _pivot_col(T, tol=1e-9, bland=False):
38
+ """
39
+ Given a linear programming simplex tableau, determine the column
40
+ of the variable to enter the basis.
41
+
42
+ Parameters
43
+ ----------
44
+ T : 2-D array
45
+ A 2-D array representing the simplex tableau, T, corresponding to the
46
+ linear programming problem. It should have the form:
47
+
48
+ [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
49
+ [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
50
+ .
51
+ .
52
+ .
53
+ [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
54
+ [c[0], c[1], ..., c[n_total], 0]]
55
+
56
+ for a Phase 2 problem, or the form:
57
+
58
+ [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
59
+ [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
60
+ .
61
+ .
62
+ .
63
+ [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
64
+ [c[0], c[1], ..., c[n_total], 0],
65
+ [c'[0], c'[1], ..., c'[n_total], 0]]
66
+
67
+ for a Phase 1 problem (a problem in which a basic feasible solution is
68
+ sought prior to maximizing the actual objective. ``T`` is modified in
69
+ place by ``_solve_simplex``.
70
+ tol : float
71
+ Elements in the objective row larger than -tol will not be considered
72
+ for pivoting. Nominally this value is zero, but numerical issues
73
+ cause a tolerance about zero to be necessary.
74
+ bland : bool
75
+ If True, use Bland's rule for selection of the column (select the
76
+ first column with a negative coefficient in the objective row,
77
+ regardless of magnitude).
78
+
79
+ Returns
80
+ -------
81
+ status: bool
82
+ True if a suitable pivot column was found, otherwise False.
83
+ A return of False indicates that the linear programming simplex
84
+ algorithm is complete.
85
+ col: int
86
+ The index of the column of the pivot element.
87
+ If status is False, col will be returned as nan.
88
+ """
89
+ ma = np.ma.masked_where(T[-1, :-1] >= -tol, T[-1, :-1], copy=False)
90
+ if ma.count() == 0:
91
+ return False, np.nan
92
+ if bland:
93
+ # ma.mask is sometimes 0d
94
+ return True, np.nonzero(np.logical_not(np.atleast_1d(ma.mask)))[0][0]
95
+ return True, np.ma.nonzero(ma == ma.min())[0][0]
96
+
97
+
98
+ def _pivot_row(T, basis, pivcol, phase, tol=1e-9, bland=False):
99
+ """
100
+ Given a linear programming simplex tableau, determine the row for the
101
+ pivot operation.
102
+
103
+ Parameters
104
+ ----------
105
+ T : 2-D array
106
+ A 2-D array representing the simplex tableau, T, corresponding to the
107
+ linear programming problem. It should have the form:
108
+
109
+ [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
110
+ [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
111
+ .
112
+ .
113
+ .
114
+ [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
115
+ [c[0], c[1], ..., c[n_total], 0]]
116
+
117
+ for a Phase 2 problem, or the form:
118
+
119
+ [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
120
+ [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
121
+ .
122
+ .
123
+ .
124
+ [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
125
+ [c[0], c[1], ..., c[n_total], 0],
126
+ [c'[0], c'[1], ..., c'[n_total], 0]]
127
+
128
+ for a Phase 1 problem (a Problem in which a basic feasible solution is
129
+ sought prior to maximizing the actual objective. ``T`` is modified in
130
+ place by ``_solve_simplex``.
131
+ basis : array
132
+ A list of the current basic variables.
133
+ pivcol : int
134
+ The index of the pivot column.
135
+ phase : int
136
+ The phase of the simplex algorithm (1 or 2).
137
+ tol : float
138
+ Elements in the pivot column smaller than tol will not be considered
139
+ for pivoting. Nominally this value is zero, but numerical issues
140
+ cause a tolerance about zero to be necessary.
141
+ bland : bool
142
+ If True, use Bland's rule for selection of the row (if more than one
143
+ row can be used, choose the one with the lowest variable index).
144
+
145
+ Returns
146
+ -------
147
+ status: bool
148
+ True if a suitable pivot row was found, otherwise False. A return
149
+ of False indicates that the linear programming problem is unbounded.
150
+ row: int
151
+ The index of the row of the pivot element. If status is False, row
152
+ will be returned as nan.
153
+ """
154
+ if phase == 1:
155
+ k = 2
156
+ else:
157
+ k = 1
158
+ ma = np.ma.masked_where(T[:-k, pivcol] <= tol, T[:-k, pivcol], copy=False)
159
+ if ma.count() == 0:
160
+ return False, np.nan
161
+ mb = np.ma.masked_where(T[:-k, pivcol] <= tol, T[:-k, -1], copy=False)
162
+ q = mb / ma
163
+ min_rows = np.ma.nonzero(q == q.min())[0]
164
+ if bland:
165
+ return True, min_rows[np.argmin(np.take(basis, min_rows))]
166
+ return True, min_rows[0]
167
+
168
+
169
+ def _apply_pivot(T, basis, pivrow, pivcol, tol=1e-9):
170
+ """
171
+ Pivot the simplex tableau inplace on the element given by (pivrow, pivol).
172
+ The entering variable corresponds to the column given by pivcol forcing
173
+ the variable basis[pivrow] to leave the basis.
174
+
175
+ Parameters
176
+ ----------
177
+ T : 2-D array
178
+ A 2-D array representing the simplex tableau, T, corresponding to the
179
+ linear programming problem. It should have the form:
180
+
181
+ [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
182
+ [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
183
+ .
184
+ .
185
+ .
186
+ [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
187
+ [c[0], c[1], ..., c[n_total], 0]]
188
+
189
+ for a Phase 2 problem, or the form:
190
+
191
+ [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
192
+ [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
193
+ .
194
+ .
195
+ .
196
+ [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
197
+ [c[0], c[1], ..., c[n_total], 0],
198
+ [c'[0], c'[1], ..., c'[n_total], 0]]
199
+
200
+ for a Phase 1 problem (a problem in which a basic feasible solution is
201
+ sought prior to maximizing the actual objective. ``T`` is modified in
202
+ place by ``_solve_simplex``.
203
+ basis : 1-D array
204
+ An array of the indices of the basic variables, such that basis[i]
205
+ contains the column corresponding to the basic variable for row i.
206
+ Basis is modified in place by _apply_pivot.
207
+ pivrow : int
208
+ Row index of the pivot.
209
+ pivcol : int
210
+ Column index of the pivot.
211
+ """
212
+ basis[pivrow] = pivcol
213
+ pivval = T[pivrow, pivcol]
214
+ T[pivrow] = T[pivrow] / pivval
215
+ for irow in range(T.shape[0]):
216
+ if irow != pivrow:
217
+ T[irow] = T[irow] - T[pivrow] * T[irow, pivcol]
218
+
219
+ # The selected pivot should never lead to a pivot value less than the tol.
220
+ if np.isclose(pivval, tol, atol=0, rtol=1e4):
221
+ message = (
222
+ f"The pivot operation produces a pivot value of:{pivval: .1e}, "
223
+ "which is only slightly greater than the specified "
224
+ f"tolerance{tol: .1e}. This may lead to issues regarding the "
225
+ "numerical stability of the simplex method. "
226
+ "Removing redundant constraints, changing the pivot strategy "
227
+ "via Bland's rule or increasing the tolerance may "
228
+ "help reduce the issue.")
229
+ warn(message, OptimizeWarning, stacklevel=5)
230
+
231
+
232
+ def _solve_simplex(T, n, basis, callback, postsolve_args,
233
+ maxiter=1000, tol=1e-9, phase=2, bland=False, nit0=0,
234
+ ):
235
+ """
236
+ Solve a linear programming problem in "standard form" using the Simplex
237
+ Method. Linear Programming is intended to solve the following problem form:
238
+
239
+ Minimize::
240
+
241
+ c @ x
242
+
243
+ Subject to::
244
+
245
+ A @ x == b
246
+ x >= 0
247
+
248
+ Parameters
249
+ ----------
250
+ T : 2-D array
251
+ A 2-D array representing the simplex tableau, T, corresponding to the
252
+ linear programming problem. It should have the form:
253
+
254
+ [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
255
+ [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
256
+ .
257
+ .
258
+ .
259
+ [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
260
+ [c[0], c[1], ..., c[n_total], 0]]
261
+
262
+ for a Phase 2 problem, or the form:
263
+
264
+ [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
265
+ [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
266
+ .
267
+ .
268
+ .
269
+ [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
270
+ [c[0], c[1], ..., c[n_total], 0],
271
+ [c'[0], c'[1], ..., c'[n_total], 0]]
272
+
273
+ for a Phase 1 problem (a problem in which a basic feasible solution is
274
+ sought prior to maximizing the actual objective. ``T`` is modified in
275
+ place by ``_solve_simplex``.
276
+ n : int
277
+ The number of true variables in the problem.
278
+ basis : 1-D array
279
+ An array of the indices of the basic variables, such that basis[i]
280
+ contains the column corresponding to the basic variable for row i.
281
+ Basis is modified in place by _solve_simplex
282
+ callback : callable, optional
283
+ If a callback function is provided, it will be called within each
284
+ iteration of the algorithm. The callback must accept a
285
+ `scipy.optimize.OptimizeResult` consisting of the following fields:
286
+
287
+ x : 1-D array
288
+ Current solution vector
289
+ fun : float
290
+ Current value of the objective function
291
+ success : bool
292
+ True only when a phase has completed successfully. This
293
+ will be False for most iterations.
294
+ slack : 1-D array
295
+ The values of the slack variables. Each slack variable
296
+ corresponds to an inequality constraint. If the slack is zero,
297
+ the corresponding constraint is active.
298
+ con : 1-D array
299
+ The (nominally zero) residuals of the equality constraints,
300
+ that is, ``b - A_eq @ x``
301
+ phase : int
302
+ The phase of the optimization being executed. In phase 1 a basic
303
+ feasible solution is sought and the T has an additional row
304
+ representing an alternate objective function.
305
+ status : int
306
+ An integer representing the exit status of the optimization::
307
+
308
+ 0 : Optimization terminated successfully
309
+ 1 : Iteration limit reached
310
+ 2 : Problem appears to be infeasible
311
+ 3 : Problem appears to be unbounded
312
+ 4 : Serious numerical difficulties encountered
313
+
314
+ nit : int
315
+ The number of iterations performed.
316
+ message : str
317
+ A string descriptor of the exit status of the optimization.
318
+ postsolve_args : tuple
319
+ Data needed by _postsolve to convert the solution to the standard-form
320
+ problem into the solution to the original problem.
321
+ maxiter : int
322
+ The maximum number of iterations to perform before aborting the
323
+ optimization.
324
+ tol : float
325
+ The tolerance which determines when a solution is "close enough" to
326
+ zero in Phase 1 to be considered a basic feasible solution or close
327
+ enough to positive to serve as an optimal solution.
328
+ phase : int
329
+ The phase of the optimization being executed. In phase 1 a basic
330
+ feasible solution is sought and the T has an additional row
331
+ representing an alternate objective function.
332
+ bland : bool
333
+ If True, choose pivots using Bland's rule [3]_. In problems which
334
+ fail to converge due to cycling, using Bland's rule can provide
335
+ convergence at the expense of a less optimal path about the simplex.
336
+ nit0 : int
337
+ The initial iteration number used to keep an accurate iteration total
338
+ in a two-phase problem.
339
+
340
+ Returns
341
+ -------
342
+ nit : int
343
+ The number of iterations. Used to keep an accurate iteration total
344
+ in the two-phase problem.
345
+ status : int
346
+ An integer representing the exit status of the optimization::
347
+
348
+ 0 : Optimization terminated successfully
349
+ 1 : Iteration limit reached
350
+ 2 : Problem appears to be infeasible
351
+ 3 : Problem appears to be unbounded
352
+ 4 : Serious numerical difficulties encountered
353
+
354
+ """
355
+ nit = nit0
356
+ status = 0
357
+ message = ''
358
+ complete = False
359
+
360
+ if phase == 1:
361
+ m = T.shape[1]-2
362
+ elif phase == 2:
363
+ m = T.shape[1]-1
364
+ else:
365
+ raise ValueError("Argument 'phase' to _solve_simplex must be 1 or 2")
366
+
367
+ if phase == 2:
368
+ # Check if any artificial variables are still in the basis.
369
+ # If yes, check if any coefficients from this row and a column
370
+ # corresponding to one of the non-artificial variable is non-zero.
371
+ # If found, pivot at this term. If not, start phase 2.
372
+ # Do this for all artificial variables in the basis.
373
+ # Ref: "An Introduction to Linear Programming and Game Theory"
374
+ # by Paul R. Thie, Gerard E. Keough, 3rd Ed,
375
+ # Chapter 3.7 Redundant Systems (pag 102)
376
+ for pivrow in [row for row in range(basis.size)
377
+ if basis[row] > T.shape[1] - 2]:
378
+ non_zero_row = [col for col in range(T.shape[1] - 1)
379
+ if abs(T[pivrow, col]) > tol]
380
+ if len(non_zero_row) > 0:
381
+ pivcol = non_zero_row[0]
382
+ _apply_pivot(T, basis, pivrow, pivcol, tol)
383
+ nit += 1
384
+
385
+ if len(basis[:m]) == 0:
386
+ solution = np.empty(T.shape[1] - 1, dtype=np.float64)
387
+ else:
388
+ solution = np.empty(max(T.shape[1] - 1, max(basis[:m]) + 1),
389
+ dtype=np.float64)
390
+
391
+ while not complete:
392
+ # Find the pivot column
393
+ pivcol_found, pivcol = _pivot_col(T, tol, bland)
394
+ if not pivcol_found:
395
+ pivcol = np.nan
396
+ pivrow = np.nan
397
+ status = 0
398
+ complete = True
399
+ else:
400
+ # Find the pivot row
401
+ pivrow_found, pivrow = _pivot_row(T, basis, pivcol, phase, tol, bland)
402
+ if not pivrow_found:
403
+ status = 3
404
+ complete = True
405
+
406
+ if callback is not None:
407
+ solution[:] = 0
408
+ solution[basis[:n]] = T[:n, -1]
409
+ x = solution[:m]
410
+ x, fun, slack, con = _postsolve(
411
+ x, postsolve_args
412
+ )
413
+ res = OptimizeResult({
414
+ 'x': x,
415
+ 'fun': fun,
416
+ 'slack': slack,
417
+ 'con': con,
418
+ 'status': status,
419
+ 'message': message,
420
+ 'nit': nit,
421
+ 'success': status == 0 and complete,
422
+ 'phase': phase,
423
+ 'complete': complete,
424
+ })
425
+ callback(res)
426
+
427
+ if not complete:
428
+ if nit >= maxiter:
429
+ # Iteration limit exceeded
430
+ status = 1
431
+ complete = True
432
+ else:
433
+ _apply_pivot(T, basis, pivrow, pivcol, tol)
434
+ nit += 1
435
+ return nit, status
436
+
437
+
438
+ def _linprog_simplex(c, c0, A, b, callback, postsolve_args,
439
+ maxiter=1000, tol=1e-9, disp=False, bland=False,
440
+ **unknown_options):
441
+ """
442
+ Minimize a linear objective function subject to linear equality and
443
+ non-negativity constraints using the two phase simplex method.
444
+ Linear programming is intended to solve problems of the following form:
445
+
446
+ Minimize::
447
+
448
+ c @ x
449
+
450
+ Subject to::
451
+
452
+ A @ x == b
453
+ x >= 0
454
+
455
+ User-facing documentation is in _linprog_doc.py.
456
+
457
+ Parameters
458
+ ----------
459
+ c : 1-D array
460
+ Coefficients of the linear objective function to be minimized.
461
+ c0 : float
462
+ Constant term in objective function due to fixed (and eliminated)
463
+ variables. (Purely for display.)
464
+ A : 2-D array
465
+ 2-D array such that ``A @ x``, gives the values of the equality
466
+ constraints at ``x``.
467
+ b : 1-D array
468
+ 1-D array of values representing the right hand side of each equality
469
+ constraint (row) in ``A``.
470
+ callback : callable, optional
471
+ If a callback function is provided, it will be called within each
472
+ iteration of the algorithm. The callback function must accept a single
473
+ `scipy.optimize.OptimizeResult` consisting of the following fields:
474
+
475
+ x : 1-D array
476
+ Current solution vector
477
+ fun : float
478
+ Current value of the objective function
479
+ success : bool
480
+ True when an algorithm has completed successfully.
481
+ slack : 1-D array
482
+ The values of the slack variables. Each slack variable
483
+ corresponds to an inequality constraint. If the slack is zero,
484
+ the corresponding constraint is active.
485
+ con : 1-D array
486
+ The (nominally zero) residuals of the equality constraints,
487
+ that is, ``b - A_eq @ x``
488
+ phase : int
489
+ The phase of the algorithm being executed.
490
+ status : int
491
+ An integer representing the status of the optimization::
492
+
493
+ 0 : Algorithm proceeding nominally
494
+ 1 : Iteration limit reached
495
+ 2 : Problem appears to be infeasible
496
+ 3 : Problem appears to be unbounded
497
+ 4 : Serious numerical difficulties encountered
498
+ nit : int
499
+ The number of iterations performed.
500
+ message : str
501
+ A string descriptor of the exit status of the optimization.
502
+ postsolve_args : tuple
503
+ Data needed by _postsolve to convert the solution to the standard-form
504
+ problem into the solution to the original problem.
505
+
506
+ Options
507
+ -------
508
+ maxiter : int
509
+ The maximum number of iterations to perform.
510
+ disp : bool
511
+ If True, print exit status message to sys.stdout
512
+ tol : float
513
+ The tolerance which determines when a solution is "close enough" to
514
+ zero in Phase 1 to be considered a basic feasible solution or close
515
+ enough to positive to serve as an optimal solution.
516
+ bland : bool
517
+ If True, use Bland's anti-cycling rule [3]_ to choose pivots to
518
+ prevent cycling. If False, choose pivots which should lead to a
519
+ converged solution more quickly. The latter method is subject to
520
+ cycling (non-convergence) in rare instances.
521
+ unknown_options : dict
522
+ Optional arguments not used by this particular solver. If
523
+ `unknown_options` is non-empty a warning is issued listing all
524
+ unused options.
525
+
526
+ Returns
527
+ -------
528
+ x : 1-D array
529
+ Solution vector.
530
+ status : int
531
+ An integer representing the exit status of the optimization::
532
+
533
+ 0 : Optimization terminated successfully
534
+ 1 : Iteration limit reached
535
+ 2 : Problem appears to be infeasible
536
+ 3 : Problem appears to be unbounded
537
+ 4 : Serious numerical difficulties encountered
538
+
539
+ message : str
540
+ A string descriptor of the exit status of the optimization.
541
+ iteration : int
542
+ The number of iterations taken to solve the problem.
543
+
544
+ References
545
+ ----------
546
+ .. [1] Dantzig, George B., Linear programming and extensions. Rand
547
+ Corporation Research Study Princeton Univ. Press, Princeton, NJ,
548
+ 1963
549
+ .. [2] Hillier, S.H. and Lieberman, G.J. (1995), "Introduction to
550
+ Mathematical Programming", McGraw-Hill, Chapter 4.
551
+ .. [3] Bland, Robert G. New finite pivoting rules for the simplex method.
552
+ Mathematics of Operations Research (2), 1977: pp. 103-107.
553
+
554
+
555
+ Notes
556
+ -----
557
+ The expected problem formulation differs between the top level ``linprog``
558
+ module and the method specific solvers. The method specific solvers expect a
559
+ problem in standard form:
560
+
561
+ Minimize::
562
+
563
+ c @ x
564
+
565
+ Subject to::
566
+
567
+ A @ x == b
568
+ x >= 0
569
+
570
+ Whereas the top level ``linprog`` module expects a problem of form:
571
+
572
+ Minimize::
573
+
574
+ c @ x
575
+
576
+ Subject to::
577
+
578
+ A_ub @ x <= b_ub
579
+ A_eq @ x == b_eq
580
+ lb <= x <= ub
581
+
582
+ where ``lb = 0`` and ``ub = None`` unless set in ``bounds``.
583
+
584
+ The original problem contains equality, upper-bound and variable constraints
585
+ whereas the method specific solver requires equality constraints and
586
+ variable non-negativity.
587
+
588
+ ``linprog`` module converts the original problem to standard form by
589
+ converting the simple bounds to upper bound constraints, introducing
590
+ non-negative slack variables for inequality constraints, and expressing
591
+ unbounded variables as the difference between two non-negative variables.
592
+ """
593
+ _check_unknown_options(unknown_options)
594
+
595
+ status = 0
596
+ messages = {0: "Optimization terminated successfully.",
597
+ 1: "Iteration limit reached.",
598
+ 2: "Optimization failed. Unable to find a feasible"
599
+ " starting point.",
600
+ 3: "Optimization failed. The problem appears to be unbounded.",
601
+ 4: "Optimization failed. Singular matrix encountered."}
602
+
603
+ n, m = A.shape
604
+
605
+ # All constraints must have b >= 0.
606
+ is_negative_constraint = np.less(b, 0)
607
+ A[is_negative_constraint] *= -1
608
+ b[is_negative_constraint] *= -1
609
+
610
+ # As all constraints are equality constraints the artificial variables
611
+ # will also be basic variables.
612
+ av = np.arange(n) + m
613
+ basis = av.copy()
614
+
615
+ # Format the phase one tableau by adding artificial variables and stacking
616
+ # the constraints, the objective row and pseudo-objective row.
617
+ row_constraints = np.hstack((A, np.eye(n), b[:, np.newaxis]))
618
+ row_objective = np.hstack((c, np.zeros(n), c0))
619
+ row_pseudo_objective = -row_constraints.sum(axis=0)
620
+ row_pseudo_objective[av] = 0
621
+ T = np.vstack((row_constraints, row_objective, row_pseudo_objective))
622
+
623
+ nit1, status = _solve_simplex(T, n, basis, callback=callback,
624
+ postsolve_args=postsolve_args,
625
+ maxiter=maxiter, tol=tol, phase=1,
626
+ bland=bland
627
+ )
628
+ # if pseudo objective is zero, remove the last row from the tableau and
629
+ # proceed to phase 2
630
+ nit2 = nit1
631
+ if abs(T[-1, -1]) < tol:
632
+ # Remove the pseudo-objective row from the tableau
633
+ T = T[:-1, :]
634
+ # Remove the artificial variable columns from the tableau
635
+ T = np.delete(T, av, 1)
636
+ else:
637
+ # Failure to find a feasible starting point
638
+ status = 2
639
+ messages[status] = (
640
+ "Phase 1 of the simplex method failed to find a feasible "
641
+ "solution. The pseudo-objective function evaluates to {0:.1e} "
642
+ "which exceeds the required tolerance of {1} for a solution to be "
643
+ "considered 'close enough' to zero to be a basic solution. "
644
+ "Consider increasing the tolerance to be greater than {0:.1e}. "
645
+ "If this tolerance is unacceptably large the problem may be "
646
+ "infeasible.".format(abs(T[-1, -1]), tol)
647
+ )
648
+
649
+ if status == 0:
650
+ # Phase 2
651
+ nit2, status = _solve_simplex(T, n, basis, callback=callback,
652
+ postsolve_args=postsolve_args,
653
+ maxiter=maxiter, tol=tol, phase=2,
654
+ bland=bland, nit0=nit1
655
+ )
656
+
657
+ solution = np.zeros(n + m)
658
+ solution[basis[:n]] = T[:n, -1]
659
+ x = solution[:m]
660
+
661
+ return x, status, messages[status], int(nit2)
vila/lib/python3.10/site-packages/scipy/optimize/_linprog_util.py ADDED
@@ -0,0 +1,1522 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Method agnostic utility functions for linear programming
3
+ """
4
+
5
+ import numpy as np
6
+ import scipy.sparse as sps
7
+ from warnings import warn
8
+ from ._optimize import OptimizeWarning
9
+ from scipy.optimize._remove_redundancy import (
10
+ _remove_redundancy_svd, _remove_redundancy_pivot_sparse,
11
+ _remove_redundancy_pivot_dense, _remove_redundancy_id
12
+ )
13
+ from collections import namedtuple
14
+
15
+ _LPProblem = namedtuple('_LPProblem',
16
+ 'c A_ub b_ub A_eq b_eq bounds x0 integrality')
17
+ _LPProblem.__new__.__defaults__ = (None,) * 7 # make c the only required arg
18
+ _LPProblem.__doc__ = \
19
+ """ Represents a linear-programming problem.
20
+
21
+ Attributes
22
+ ----------
23
+ c : 1D array
24
+ The coefficients of the linear objective function to be minimized.
25
+ A_ub : 2D array, optional
26
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
27
+ coefficients of a linear inequality constraint on ``x``.
28
+ b_ub : 1D array, optional
29
+ The inequality constraint vector. Each element represents an
30
+ upper bound on the corresponding value of ``A_ub @ x``.
31
+ A_eq : 2D array, optional
32
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
33
+ coefficients of a linear equality constraint on ``x``.
34
+ b_eq : 1D array, optional
35
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
36
+ the corresponding element of ``b_eq``.
37
+ bounds : various valid formats, optional
38
+ The bounds of ``x``, as ``min`` and ``max`` pairs.
39
+ If bounds are specified for all N variables separately, valid formats
40
+ are:
41
+ * a 2D array (N x 2);
42
+ * a sequence of N sequences, each with 2 values.
43
+ If all variables have the same bounds, the bounds can be specified as
44
+ a 1-D or 2-D array or sequence with 2 scalar values.
45
+ If all variables have a lower bound of 0 and no upper bound, the bounds
46
+ parameter can be omitted (or given as None).
47
+ Absent lower and/or upper bounds can be specified as -numpy.inf (no
48
+ lower bound), numpy.inf (no upper bound) or None (both).
49
+ x0 : 1D array, optional
50
+ Guess values of the decision variables, which will be refined by
51
+ the optimization algorithm. This argument is currently used only by the
52
+ 'revised simplex' method, and can only be used if `x0` represents a
53
+ basic feasible solution.
54
+ integrality : 1-D array or int, optional
55
+ Indicates the type of integrality constraint on each decision variable.
56
+
57
+ ``0`` : Continuous variable; no integrality constraint.
58
+
59
+ ``1`` : Integer variable; decision variable must be an integer
60
+ within `bounds`.
61
+
62
+ ``2`` : Semi-continuous variable; decision variable must be within
63
+ `bounds` or take value ``0``.
64
+
65
+ ``3`` : Semi-integer variable; decision variable must be an integer
66
+ within `bounds` or take value ``0``.
67
+
68
+ By default, all variables are continuous.
69
+
70
+ For mixed integrality constraints, supply an array of shape `c.shape`.
71
+ To infer a constraint on each decision variable from shorter inputs,
72
+ the argument will be broadcasted to `c.shape` using `np.broadcast_to`.
73
+
74
+ This argument is currently used only by the ``'highs'`` method and
75
+ ignored otherwise.
76
+
77
+ Notes
78
+ -----
79
+ This namedtuple supports 2 ways of initialization:
80
+ >>> lp1 = _LPProblem(c=[-1, 4], A_ub=[[-3, 1], [1, 2]], b_ub=[6, 4])
81
+ >>> lp2 = _LPProblem([-1, 4], [[-3, 1], [1, 2]], [6, 4])
82
+
83
+ Note that only ``c`` is a required argument here, whereas all other arguments
84
+ ``A_ub``, ``b_ub``, ``A_eq``, ``b_eq``, ``bounds``, ``x0`` are optional with
85
+ default values of None.
86
+ For example, ``A_eq`` and ``b_eq`` can be set without ``A_ub`` or ``b_ub``:
87
+ >>> lp3 = _LPProblem(c=[-1, 4], A_eq=[[2, 1]], b_eq=[10])
88
+ """
89
+
90
+
91
+ def _check_sparse_inputs(options, meth, A_ub, A_eq):
92
+ """
93
+ Check the provided ``A_ub`` and ``A_eq`` matrices conform to the specified
94
+ optional sparsity variables.
95
+
96
+ Parameters
97
+ ----------
98
+ A_ub : 2-D array, optional
99
+ 2-D array such that ``A_ub @ x`` gives the values of the upper-bound
100
+ inequality constraints at ``x``.
101
+ A_eq : 2-D array, optional
102
+ 2-D array such that ``A_eq @ x`` gives the values of the equality
103
+ constraints at ``x``.
104
+ options : dict
105
+ A dictionary of solver options. All methods accept the following
106
+ generic options:
107
+
108
+ maxiter : int
109
+ Maximum number of iterations to perform.
110
+ disp : bool
111
+ Set to True to print convergence messages.
112
+
113
+ For method-specific options, see :func:`show_options('linprog')`.
114
+ method : str, optional
115
+ The algorithm used to solve the standard form problem.
116
+
117
+ Returns
118
+ -------
119
+ A_ub : 2-D array, optional
120
+ 2-D array such that ``A_ub @ x`` gives the values of the upper-bound
121
+ inequality constraints at ``x``.
122
+ A_eq : 2-D array, optional
123
+ 2-D array such that ``A_eq @ x`` gives the values of the equality
124
+ constraints at ``x``.
125
+ options : dict
126
+ A dictionary of solver options. All methods accept the following
127
+ generic options:
128
+
129
+ maxiter : int
130
+ Maximum number of iterations to perform.
131
+ disp : bool
132
+ Set to True to print convergence messages.
133
+
134
+ For method-specific options, see :func:`show_options('linprog')`.
135
+ """
136
+ # This is an undocumented option for unit testing sparse presolve
137
+ _sparse_presolve = options.pop('_sparse_presolve', False)
138
+ if _sparse_presolve and A_eq is not None:
139
+ A_eq = sps.coo_matrix(A_eq)
140
+ if _sparse_presolve and A_ub is not None:
141
+ A_ub = sps.coo_matrix(A_ub)
142
+
143
+ sparse_constraint = sps.issparse(A_eq) or sps.issparse(A_ub)
144
+
145
+ preferred_methods = {"highs", "highs-ds", "highs-ipm"}
146
+ dense_methods = {"simplex", "revised simplex"}
147
+ if meth in dense_methods and sparse_constraint:
148
+ raise ValueError(f"Method '{meth}' does not support sparse "
149
+ "constraint matrices. Please consider using one of "
150
+ f"{preferred_methods}.")
151
+
152
+ sparse = options.get('sparse', False)
153
+ if not sparse and sparse_constraint and meth == 'interior-point':
154
+ options['sparse'] = True
155
+ warn("Sparse constraint matrix detected; setting 'sparse':True.",
156
+ OptimizeWarning, stacklevel=4)
157
+ return options, A_ub, A_eq
158
+
159
+
160
+ def _format_A_constraints(A, n_x, sparse_lhs=False):
161
+ """Format the left hand side of the constraints to a 2-D array
162
+
163
+ Parameters
164
+ ----------
165
+ A : 2-D array
166
+ 2-D array such that ``A @ x`` gives the values of the upper-bound
167
+ (in)equality constraints at ``x``.
168
+ n_x : int
169
+ The number of variables in the linear programming problem.
170
+ sparse_lhs : bool
171
+ Whether either of `A_ub` or `A_eq` are sparse. If true return a
172
+ coo_matrix instead of a numpy array.
173
+
174
+ Returns
175
+ -------
176
+ np.ndarray or sparse.coo_matrix
177
+ 2-D array such that ``A @ x`` gives the values of the upper-bound
178
+ (in)equality constraints at ``x``.
179
+
180
+ """
181
+ if sparse_lhs:
182
+ return sps.coo_matrix(
183
+ (0, n_x) if A is None else A, dtype=float, copy=True
184
+ )
185
+ elif A is None:
186
+ return np.zeros((0, n_x), dtype=float)
187
+ else:
188
+ return np.array(A, dtype=float, copy=True)
189
+
190
+
191
+ def _format_b_constraints(b):
192
+ """Format the upper bounds of the constraints to a 1-D array
193
+
194
+ Parameters
195
+ ----------
196
+ b : 1-D array
197
+ 1-D array of values representing the upper-bound of each (in)equality
198
+ constraint (row) in ``A``.
199
+
200
+ Returns
201
+ -------
202
+ 1-D np.array
203
+ 1-D array of values representing the upper-bound of each (in)equality
204
+ constraint (row) in ``A``.
205
+
206
+ """
207
+ if b is None:
208
+ return np.array([], dtype=float)
209
+ b = np.array(b, dtype=float, copy=True).squeeze()
210
+ return b if b.size != 1 else b.reshape(-1)
211
+
212
+
213
+ def _clean_inputs(lp):
214
+ """
215
+ Given user inputs for a linear programming problem, return the
216
+ objective vector, upper bound constraints, equality constraints,
217
+ and simple bounds in a preferred format.
218
+
219
+ Parameters
220
+ ----------
221
+ lp : A `scipy.optimize._linprog_util._LPProblem` consisting of the following fields:
222
+
223
+ c : 1D array
224
+ The coefficients of the linear objective function to be minimized.
225
+ A_ub : 2D array, optional
226
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
227
+ coefficients of a linear inequality constraint on ``x``.
228
+ b_ub : 1D array, optional
229
+ The inequality constraint vector. Each element represents an
230
+ upper bound on the corresponding value of ``A_ub @ x``.
231
+ A_eq : 2D array, optional
232
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
233
+ coefficients of a linear equality constraint on ``x``.
234
+ b_eq : 1D array, optional
235
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
236
+ the corresponding element of ``b_eq``.
237
+ bounds : various valid formats, optional
238
+ The bounds of ``x``, as ``min`` and ``max`` pairs.
239
+ If bounds are specified for all N variables separately, valid formats are:
240
+ * a 2D array (2 x N or N x 2);
241
+ * a sequence of N sequences, each with 2 values.
242
+ If all variables have the same bounds, a single pair of values can
243
+ be specified. Valid formats are:
244
+ * a sequence with 2 scalar values;
245
+ * a sequence with a single element containing 2 scalar values.
246
+ If all variables have a lower bound of 0 and no upper bound, the bounds
247
+ parameter can be omitted (or given as None).
248
+ x0 : 1D array, optional
249
+ Guess values of the decision variables, which will be refined by
250
+ the optimization algorithm. This argument is currently used only by the
251
+ 'revised simplex' method, and can only be used if `x0` represents a
252
+ basic feasible solution.
253
+
254
+ Returns
255
+ -------
256
+ lp : A `scipy.optimize._linprog_util._LPProblem` consisting of the following fields:
257
+
258
+ c : 1D array
259
+ The coefficients of the linear objective function to be minimized.
260
+ A_ub : 2D array, optional
261
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
262
+ coefficients of a linear inequality constraint on ``x``.
263
+ b_ub : 1D array, optional
264
+ The inequality constraint vector. Each element represents an
265
+ upper bound on the corresponding value of ``A_ub @ x``.
266
+ A_eq : 2D array, optional
267
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
268
+ coefficients of a linear equality constraint on ``x``.
269
+ b_eq : 1D array, optional
270
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
271
+ the corresponding element of ``b_eq``.
272
+ bounds : 2D array
273
+ The bounds of ``x``, as ``min`` and ``max`` pairs, one for each of the N
274
+ elements of ``x``. The N x 2 array contains lower bounds in the first
275
+ column and upper bounds in the 2nd. Unbounded variables have lower
276
+ bound -np.inf and/or upper bound np.inf.
277
+ x0 : 1D array, optional
278
+ Guess values of the decision variables, which will be refined by
279
+ the optimization algorithm. This argument is currently used only by the
280
+ 'revised simplex' method, and can only be used if `x0` represents a
281
+ basic feasible solution.
282
+
283
+ """
284
+ c, A_ub, b_ub, A_eq, b_eq, bounds, x0, integrality = lp
285
+
286
+ if c is None:
287
+ raise TypeError
288
+
289
+ try:
290
+ c = np.array(c, dtype=np.float64, copy=True).squeeze()
291
+ except ValueError as e:
292
+ raise TypeError(
293
+ "Invalid input for linprog: c must be a 1-D array of numerical "
294
+ "coefficients") from e
295
+ else:
296
+ # If c is a single value, convert it to a 1-D array.
297
+ if c.size == 1:
298
+ c = c.reshape(-1)
299
+
300
+ n_x = len(c)
301
+ if n_x == 0 or len(c.shape) != 1:
302
+ raise ValueError(
303
+ "Invalid input for linprog: c must be a 1-D array and must "
304
+ "not have more than one non-singleton dimension")
305
+ if not np.isfinite(c).all():
306
+ raise ValueError(
307
+ "Invalid input for linprog: c must not contain values "
308
+ "inf, nan, or None")
309
+
310
+ sparse_lhs = sps.issparse(A_eq) or sps.issparse(A_ub)
311
+ try:
312
+ A_ub = _format_A_constraints(A_ub, n_x, sparse_lhs=sparse_lhs)
313
+ except ValueError as e:
314
+ raise TypeError(
315
+ "Invalid input for linprog: A_ub must be a 2-D array "
316
+ "of numerical values") from e
317
+ else:
318
+ n_ub = A_ub.shape[0]
319
+ if len(A_ub.shape) != 2 or A_ub.shape[1] != n_x:
320
+ raise ValueError(
321
+ "Invalid input for linprog: A_ub must have exactly two "
322
+ "dimensions, and the number of columns in A_ub must be "
323
+ "equal to the size of c")
324
+ if (sps.issparse(A_ub) and not np.isfinite(A_ub.data).all()
325
+ or not sps.issparse(A_ub) and not np.isfinite(A_ub).all()):
326
+ raise ValueError(
327
+ "Invalid input for linprog: A_ub must not contain values "
328
+ "inf, nan, or None")
329
+
330
+ try:
331
+ b_ub = _format_b_constraints(b_ub)
332
+ except ValueError as e:
333
+ raise TypeError(
334
+ "Invalid input for linprog: b_ub must be a 1-D array of "
335
+ "numerical values, each representing the upper bound of an "
336
+ "inequality constraint (row) in A_ub") from e
337
+ else:
338
+ if b_ub.shape != (n_ub,):
339
+ raise ValueError(
340
+ "Invalid input for linprog: b_ub must be a 1-D array; b_ub "
341
+ "must not have more than one non-singleton dimension and "
342
+ "the number of rows in A_ub must equal the number of values "
343
+ "in b_ub")
344
+ if not np.isfinite(b_ub).all():
345
+ raise ValueError(
346
+ "Invalid input for linprog: b_ub must not contain values "
347
+ "inf, nan, or None")
348
+
349
+ try:
350
+ A_eq = _format_A_constraints(A_eq, n_x, sparse_lhs=sparse_lhs)
351
+ except ValueError as e:
352
+ raise TypeError(
353
+ "Invalid input for linprog: A_eq must be a 2-D array "
354
+ "of numerical values") from e
355
+ else:
356
+ n_eq = A_eq.shape[0]
357
+ if len(A_eq.shape) != 2 or A_eq.shape[1] != n_x:
358
+ raise ValueError(
359
+ "Invalid input for linprog: A_eq must have exactly two "
360
+ "dimensions, and the number of columns in A_eq must be "
361
+ "equal to the size of c")
362
+
363
+ if (sps.issparse(A_eq) and not np.isfinite(A_eq.data).all()
364
+ or not sps.issparse(A_eq) and not np.isfinite(A_eq).all()):
365
+ raise ValueError(
366
+ "Invalid input for linprog: A_eq must not contain values "
367
+ "inf, nan, or None")
368
+
369
+ try:
370
+ b_eq = _format_b_constraints(b_eq)
371
+ except ValueError as e:
372
+ raise TypeError(
373
+ "Invalid input for linprog: b_eq must be a dense, 1-D array of "
374
+ "numerical values, each representing the right hand side of an "
375
+ "equality constraint (row) in A_eq") from e
376
+ else:
377
+ if b_eq.shape != (n_eq,):
378
+ raise ValueError(
379
+ "Invalid input for linprog: b_eq must be a 1-D array; b_eq "
380
+ "must not have more than one non-singleton dimension and "
381
+ "the number of rows in A_eq must equal the number of values "
382
+ "in b_eq")
383
+ if not np.isfinite(b_eq).all():
384
+ raise ValueError(
385
+ "Invalid input for linprog: b_eq must not contain values "
386
+ "inf, nan, or None")
387
+
388
+ # x0 gives a (optional) starting solution to the solver. If x0 is None,
389
+ # skip the checks. Initial solution will be generated automatically.
390
+ if x0 is not None:
391
+ try:
392
+ x0 = np.array(x0, dtype=float, copy=True).squeeze()
393
+ except ValueError as e:
394
+ raise TypeError(
395
+ "Invalid input for linprog: x0 must be a 1-D array of "
396
+ "numerical coefficients") from e
397
+ if x0.ndim == 0:
398
+ x0 = x0.reshape(-1)
399
+ if len(x0) == 0 or x0.ndim != 1:
400
+ raise ValueError(
401
+ "Invalid input for linprog: x0 should be a 1-D array; it "
402
+ "must not have more than one non-singleton dimension")
403
+ if not x0.size == c.size:
404
+ raise ValueError(
405
+ "Invalid input for linprog: x0 and c should contain the "
406
+ "same number of elements")
407
+ if not np.isfinite(x0).all():
408
+ raise ValueError(
409
+ "Invalid input for linprog: x0 must not contain values "
410
+ "inf, nan, or None")
411
+
412
+ # Bounds can be one of these formats:
413
+ # (1) a 2-D array or sequence, with shape N x 2
414
+ # (2) a 1-D or 2-D sequence or array with 2 scalars
415
+ # (3) None (or an empty sequence or array)
416
+ # Unspecified bounds can be represented by None or (-)np.inf.
417
+ # All formats are converted into a N x 2 np.array with (-)np.inf where
418
+ # bounds are unspecified.
419
+
420
+ # Prepare clean bounds array
421
+ bounds_clean = np.zeros((n_x, 2), dtype=float)
422
+
423
+ # Convert to a numpy array.
424
+ # np.array(..,dtype=float) raises an error if dimensions are inconsistent
425
+ # or if there are invalid data types in bounds. Just add a linprog prefix
426
+ # to the error and re-raise.
427
+ # Creating at least a 2-D array simplifies the cases to distinguish below.
428
+ if bounds is None or np.array_equal(bounds, []) or np.array_equal(bounds, [[]]):
429
+ bounds = (0, np.inf)
430
+ try:
431
+ bounds_conv = np.atleast_2d(np.array(bounds, dtype=float))
432
+ except ValueError as e:
433
+ raise ValueError(
434
+ "Invalid input for linprog: unable to interpret bounds, "
435
+ "check values and dimensions: " + e.args[0]) from e
436
+ except TypeError as e:
437
+ raise TypeError(
438
+ "Invalid input for linprog: unable to interpret bounds, "
439
+ "check values and dimensions: " + e.args[0]) from e
440
+
441
+ # Check bounds options
442
+ bsh = bounds_conv.shape
443
+ if len(bsh) > 2:
444
+ # Do not try to handle multidimensional bounds input
445
+ raise ValueError(
446
+ "Invalid input for linprog: provide a 2-D array for bounds, "
447
+ f"not a {len(bsh):d}-D array.")
448
+ elif np.all(bsh == (n_x, 2)):
449
+ # Regular N x 2 array
450
+ bounds_clean = bounds_conv
451
+ elif (np.all(bsh == (2, 1)) or np.all(bsh == (1, 2))):
452
+ # 2 values: interpret as overall lower and upper bound
453
+ bounds_flat = bounds_conv.flatten()
454
+ bounds_clean[:, 0] = bounds_flat[0]
455
+ bounds_clean[:, 1] = bounds_flat[1]
456
+ elif np.all(bsh == (2, n_x)):
457
+ # Reject a 2 x N array
458
+ raise ValueError(
459
+ f"Invalid input for linprog: provide a {n_x:d} x 2 array for bounds, "
460
+ f"not a 2 x {n_x:d} array.")
461
+ else:
462
+ raise ValueError(
463
+ "Invalid input for linprog: unable to interpret bounds with this "
464
+ f"dimension tuple: {bsh}.")
465
+
466
+ # The process above creates nan-s where the input specified None
467
+ # Convert the nan-s in the 1st column to -np.inf and in the 2nd column
468
+ # to np.inf
469
+ i_none = np.isnan(bounds_clean[:, 0])
470
+ bounds_clean[i_none, 0] = -np.inf
471
+ i_none = np.isnan(bounds_clean[:, 1])
472
+ bounds_clean[i_none, 1] = np.inf
473
+
474
+ return _LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds_clean, x0, integrality)
475
+
476
+
477
+ def _presolve(lp, rr, rr_method, tol=1e-9):
478
+ """
479
+ Given inputs for a linear programming problem in preferred format,
480
+ presolve the problem: identify trivial infeasibilities, redundancies,
481
+ and unboundedness, tighten bounds where possible, and eliminate fixed
482
+ variables.
483
+
484
+ Parameters
485
+ ----------
486
+ lp : A `scipy.optimize._linprog_util._LPProblem` consisting of the following fields:
487
+
488
+ c : 1D array
489
+ The coefficients of the linear objective function to be minimized.
490
+ A_ub : 2D array, optional
491
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
492
+ coefficients of a linear inequality constraint on ``x``.
493
+ b_ub : 1D array, optional
494
+ The inequality constraint vector. Each element represents an
495
+ upper bound on the corresponding value of ``A_ub @ x``.
496
+ A_eq : 2D array, optional
497
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
498
+ coefficients of a linear equality constraint on ``x``.
499
+ b_eq : 1D array, optional
500
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
501
+ the corresponding element of ``b_eq``.
502
+ bounds : 2D array
503
+ The bounds of ``x``, as ``min`` and ``max`` pairs, one for each of the N
504
+ elements of ``x``. The N x 2 array contains lower bounds in the first
505
+ column and upper bounds in the 2nd. Unbounded variables have lower
506
+ bound -np.inf and/or upper bound np.inf.
507
+ x0 : 1D array, optional
508
+ Guess values of the decision variables, which will be refined by
509
+ the optimization algorithm. This argument is currently used only by the
510
+ 'revised simplex' method, and can only be used if `x0` represents a
511
+ basic feasible solution.
512
+
513
+ rr : bool
514
+ If ``True`` attempts to eliminate any redundant rows in ``A_eq``.
515
+ Set False if ``A_eq`` is known to be of full row rank, or if you are
516
+ looking for a potential speedup (at the expense of reliability).
517
+ rr_method : string
518
+ Method used to identify and remove redundant rows from the
519
+ equality constraint matrix after presolve.
520
+ tol : float
521
+ The tolerance which determines when a solution is "close enough" to
522
+ zero in Phase 1 to be considered a basic feasible solution or close
523
+ enough to positive to serve as an optimal solution.
524
+
525
+ Returns
526
+ -------
527
+ lp : A `scipy.optimize._linprog_util._LPProblem` consisting of the following fields:
528
+
529
+ c : 1D array
530
+ The coefficients of the linear objective function to be minimized.
531
+ A_ub : 2D array, optional
532
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
533
+ coefficients of a linear inequality constraint on ``x``.
534
+ b_ub : 1D array, optional
535
+ The inequality constraint vector. Each element represents an
536
+ upper bound on the corresponding value of ``A_ub @ x``.
537
+ A_eq : 2D array, optional
538
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
539
+ coefficients of a linear equality constraint on ``x``.
540
+ b_eq : 1D array, optional
541
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
542
+ the corresponding element of ``b_eq``.
543
+ bounds : 2D array
544
+ The bounds of ``x``, as ``min`` and ``max`` pairs, possibly tightened.
545
+ x0 : 1D array, optional
546
+ Guess values of the decision variables, which will be refined by
547
+ the optimization algorithm. This argument is currently used only by the
548
+ 'revised simplex' method, and can only be used if `x0` represents a
549
+ basic feasible solution.
550
+
551
+ c0 : 1D array
552
+ Constant term in objective function due to fixed (and eliminated)
553
+ variables.
554
+ x : 1D array
555
+ Solution vector (when the solution is trivial and can be determined
556
+ in presolve)
557
+ revstack: list of functions
558
+ the functions in the list reverse the operations of _presolve()
559
+ the function signature is x_org = f(x_mod), where x_mod is the result
560
+ of a presolve step and x_org the value at the start of the step
561
+ (currently, the revstack contains only one function)
562
+ complete: bool
563
+ Whether the solution is complete (solved or determined to be infeasible
564
+ or unbounded in presolve)
565
+ status : int
566
+ An integer representing the exit status of the optimization::
567
+
568
+ 0 : Optimization terminated successfully
569
+ 1 : Iteration limit reached
570
+ 2 : Problem appears to be infeasible
571
+ 3 : Problem appears to be unbounded
572
+ 4 : Serious numerical difficulties encountered
573
+
574
+ message : str
575
+ A string descriptor of the exit status of the optimization.
576
+
577
+ References
578
+ ----------
579
+ .. [5] Andersen, Erling D. "Finding all linearly dependent rows in
580
+ large-scale linear programming." Optimization Methods and Software
581
+ 6.3 (1995): 219-227.
582
+ .. [8] Andersen, Erling D., and Knud D. Andersen. "Presolving in linear
583
+ programming." Mathematical Programming 71.2 (1995): 221-245.
584
+
585
+ """
586
+ # ideas from Reference [5] by Andersen and Andersen
587
+ # however, unlike the reference, this is performed before converting
588
+ # problem to standard form
589
+ # There are a few advantages:
590
+ # * artificial variables have not been added, so matrices are smaller
591
+ # * bounds have not been converted to constraints yet. (It is better to
592
+ # do that after presolve because presolve may adjust the simple bounds.)
593
+ # There are many improvements that can be made, namely:
594
+ # * implement remaining checks from [5]
595
+ # * loop presolve until no additional changes are made
596
+ # * implement additional efficiency improvements in redundancy removal [2]
597
+
598
+ c, A_ub, b_ub, A_eq, b_eq, bounds, x0, _ = lp
599
+
600
+ revstack = [] # record of variables eliminated from problem
601
+ # constant term in cost function may be added if variables are eliminated
602
+ c0 = 0
603
+ complete = False # complete is True if detected infeasible/unbounded
604
+ x = np.zeros(c.shape) # this is solution vector if completed in presolve
605
+
606
+ status = 0 # all OK unless determined otherwise
607
+ message = ""
608
+
609
+ # Lower and upper bounds. Copy to prevent feedback.
610
+ lb = bounds[:, 0].copy()
611
+ ub = bounds[:, 1].copy()
612
+
613
+ m_eq, n = A_eq.shape
614
+ m_ub, n = A_ub.shape
615
+
616
+ if (rr_method is not None
617
+ and rr_method.lower() not in {"svd", "pivot", "id"}):
618
+ message = ("'" + str(rr_method) + "' is not a valid option "
619
+ "for redundancy removal. Valid options are 'SVD', "
620
+ "'pivot', and 'ID'.")
621
+ raise ValueError(message)
622
+
623
+ if sps.issparse(A_eq):
624
+ A_eq = A_eq.tocsr()
625
+ A_ub = A_ub.tocsr()
626
+
627
+ def where(A):
628
+ return A.nonzero()
629
+
630
+ vstack = sps.vstack
631
+ else:
632
+ where = np.where
633
+ vstack = np.vstack
634
+
635
+ # upper bounds > lower bounds
636
+ if np.any(ub < lb) or np.any(lb == np.inf) or np.any(ub == -np.inf):
637
+ status = 2
638
+ message = ("The problem is (trivially) infeasible since one "
639
+ "or more upper bounds are smaller than the corresponding "
640
+ "lower bounds, a lower bound is np.inf or an upper bound "
641
+ "is -np.inf.")
642
+ complete = True
643
+ return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0),
644
+ c0, x, revstack, complete, status, message)
645
+
646
+ # zero row in equality constraints
647
+ zero_row = np.array(np.sum(A_eq != 0, axis=1) == 0).flatten()
648
+ if np.any(zero_row):
649
+ if np.any(
650
+ np.logical_and(
651
+ zero_row,
652
+ np.abs(b_eq) > tol)): # test_zero_row_1
653
+ # infeasible if RHS is not zero
654
+ status = 2
655
+ message = ("The problem is (trivially) infeasible due to a row "
656
+ "of zeros in the equality constraint matrix with a "
657
+ "nonzero corresponding constraint value.")
658
+ complete = True
659
+ return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0),
660
+ c0, x, revstack, complete, status, message)
661
+ else: # test_zero_row_2
662
+ # if RHS is zero, we can eliminate this equation entirely
663
+ A_eq = A_eq[np.logical_not(zero_row), :]
664
+ b_eq = b_eq[np.logical_not(zero_row)]
665
+
666
+ # zero row in inequality constraints
667
+ zero_row = np.array(np.sum(A_ub != 0, axis=1) == 0).flatten()
668
+ if np.any(zero_row):
669
+ if np.any(np.logical_and(zero_row, b_ub < -tol)): # test_zero_row_1
670
+ # infeasible if RHS is less than zero (because LHS is zero)
671
+ status = 2
672
+ message = ("The problem is (trivially) infeasible due to a row "
673
+ "of zeros in the equality constraint matrix with a "
674
+ "nonzero corresponding constraint value.")
675
+ complete = True
676
+ return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0),
677
+ c0, x, revstack, complete, status, message)
678
+ else: # test_zero_row_2
679
+ # if LHS is >= 0, we can eliminate this constraint entirely
680
+ A_ub = A_ub[np.logical_not(zero_row), :]
681
+ b_ub = b_ub[np.logical_not(zero_row)]
682
+
683
+ # zero column in (both) constraints
684
+ # this indicates that a variable isn't constrained and can be removed
685
+ A = vstack((A_eq, A_ub))
686
+ if A.shape[0] > 0:
687
+ zero_col = np.array(np.sum(A != 0, axis=0) == 0).flatten()
688
+ # variable will be at upper or lower bound, depending on objective
689
+ x[np.logical_and(zero_col, c < 0)] = ub[
690
+ np.logical_and(zero_col, c < 0)]
691
+ x[np.logical_and(zero_col, c > 0)] = lb[
692
+ np.logical_and(zero_col, c > 0)]
693
+ if np.any(np.isinf(x)): # if an unconstrained variable has no bound
694
+ status = 3
695
+ message = ("If feasible, the problem is (trivially) unbounded "
696
+ "due to a zero column in the constraint matrices. If "
697
+ "you wish to check whether the problem is infeasible, "
698
+ "turn presolve off.")
699
+ complete = True
700
+ return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0),
701
+ c0, x, revstack, complete, status, message)
702
+ # variables will equal upper/lower bounds will be removed later
703
+ lb[np.logical_and(zero_col, c < 0)] = ub[
704
+ np.logical_and(zero_col, c < 0)]
705
+ ub[np.logical_and(zero_col, c > 0)] = lb[
706
+ np.logical_and(zero_col, c > 0)]
707
+
708
+ # row singleton in equality constraints
709
+ # this fixes a variable and removes the constraint
710
+ singleton_row = np.array(np.sum(A_eq != 0, axis=1) == 1).flatten()
711
+ rows = where(singleton_row)[0]
712
+ cols = where(A_eq[rows, :])[1]
713
+ if len(rows) > 0:
714
+ for row, col in zip(rows, cols):
715
+ val = b_eq[row] / A_eq[row, col]
716
+ if not lb[col] - tol <= val <= ub[col] + tol:
717
+ # infeasible if fixed value is not within bounds
718
+ status = 2
719
+ message = ("The problem is (trivially) infeasible because a "
720
+ "singleton row in the equality constraints is "
721
+ "inconsistent with the bounds.")
722
+ complete = True
723
+ return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0),
724
+ c0, x, revstack, complete, status, message)
725
+ else:
726
+ # sets upper and lower bounds at that fixed value - variable
727
+ # will be removed later
728
+ lb[col] = val
729
+ ub[col] = val
730
+ A_eq = A_eq[np.logical_not(singleton_row), :]
731
+ b_eq = b_eq[np.logical_not(singleton_row)]
732
+
733
+ # row singleton in inequality constraints
734
+ # this indicates a simple bound and the constraint can be removed
735
+ # simple bounds may be adjusted here
736
+ # After all of the simple bound information is combined here, get_Abc will
737
+ # turn the simple bounds into constraints
738
+ singleton_row = np.array(np.sum(A_ub != 0, axis=1) == 1).flatten()
739
+ cols = where(A_ub[singleton_row, :])[1]
740
+ rows = where(singleton_row)[0]
741
+ if len(rows) > 0:
742
+ for row, col in zip(rows, cols):
743
+ val = b_ub[row] / A_ub[row, col]
744
+ if A_ub[row, col] > 0: # upper bound
745
+ if val < lb[col] - tol: # infeasible
746
+ complete = True
747
+ elif val < ub[col]: # new upper bound
748
+ ub[col] = val
749
+ else: # lower bound
750
+ if val > ub[col] + tol: # infeasible
751
+ complete = True
752
+ elif val > lb[col]: # new lower bound
753
+ lb[col] = val
754
+ if complete:
755
+ status = 2
756
+ message = ("The problem is (trivially) infeasible because a "
757
+ "singleton row in the upper bound constraints is "
758
+ "inconsistent with the bounds.")
759
+ return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0),
760
+ c0, x, revstack, complete, status, message)
761
+ A_ub = A_ub[np.logical_not(singleton_row), :]
762
+ b_ub = b_ub[np.logical_not(singleton_row)]
763
+
764
+ # identical bounds indicate that variable can be removed
765
+ i_f = np.abs(lb - ub) < tol # indices of "fixed" variables
766
+ i_nf = np.logical_not(i_f) # indices of "not fixed" variables
767
+
768
+ # test_bounds_equal_but_infeasible
769
+ if np.all(i_f): # if bounds define solution, check for consistency
770
+ residual = b_eq - A_eq.dot(lb)
771
+ slack = b_ub - A_ub.dot(lb)
772
+ if ((A_ub.size > 0 and np.any(slack < 0)) or
773
+ (A_eq.size > 0 and not np.allclose(residual, 0))):
774
+ status = 2
775
+ message = ("The problem is (trivially) infeasible because the "
776
+ "bounds fix all variables to values inconsistent with "
777
+ "the constraints")
778
+ complete = True
779
+ return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0),
780
+ c0, x, revstack, complete, status, message)
781
+
782
+ ub_mod = ub
783
+ lb_mod = lb
784
+ if np.any(i_f):
785
+ c0 += c[i_f].dot(lb[i_f])
786
+ b_eq = b_eq - A_eq[:, i_f].dot(lb[i_f])
787
+ b_ub = b_ub - A_ub[:, i_f].dot(lb[i_f])
788
+ c = c[i_nf]
789
+ x_undo = lb[i_f] # not x[i_f], x is just zeroes
790
+ x = x[i_nf]
791
+ # user guess x0 stays separate from presolve solution x
792
+ if x0 is not None:
793
+ x0 = x0[i_nf]
794
+ A_eq = A_eq[:, i_nf]
795
+ A_ub = A_ub[:, i_nf]
796
+ # modify bounds
797
+ lb_mod = lb[i_nf]
798
+ ub_mod = ub[i_nf]
799
+
800
+ def rev(x_mod):
801
+ # Function to restore x: insert x_undo into x_mod.
802
+ # When elements have been removed at positions k1, k2, k3, ...
803
+ # then these must be replaced at (after) positions k1-1, k2-2,
804
+ # k3-3, ... in the modified array to recreate the original
805
+ i = np.flatnonzero(i_f)
806
+ # Number of variables to restore
807
+ N = len(i)
808
+ index_offset = np.arange(N)
809
+ # Create insert indices
810
+ insert_indices = i - index_offset
811
+ x_rev = np.insert(x_mod.astype(float), insert_indices, x_undo)
812
+ return x_rev
813
+
814
+ # Use revstack as a list of functions, currently just this one.
815
+ revstack.append(rev)
816
+
817
+ # no constraints indicates that problem is trivial
818
+ if A_eq.size == 0 and A_ub.size == 0:
819
+ b_eq = np.array([])
820
+ b_ub = np.array([])
821
+ # test_empty_constraint_1
822
+ if c.size == 0:
823
+ status = 0
824
+ message = ("The solution was determined in presolve as there are "
825
+ "no non-trivial constraints.")
826
+ elif (np.any(np.logical_and(c < 0, ub_mod == np.inf)) or
827
+ np.any(np.logical_and(c > 0, lb_mod == -np.inf))):
828
+ # test_no_constraints()
829
+ # test_unbounded_no_nontrivial_constraints_1
830
+ # test_unbounded_no_nontrivial_constraints_2
831
+ status = 3
832
+ message = ("The problem is (trivially) unbounded "
833
+ "because there are no non-trivial constraints and "
834
+ "a) at least one decision variable is unbounded "
835
+ "above and its corresponding cost is negative, or "
836
+ "b) at least one decision variable is unbounded below "
837
+ "and its corresponding cost is positive. ")
838
+ else: # test_empty_constraint_2
839
+ status = 0
840
+ message = ("The solution was determined in presolve as there are "
841
+ "no non-trivial constraints.")
842
+ complete = True
843
+ x[c < 0] = ub_mod[c < 0]
844
+ x[c > 0] = lb_mod[c > 0]
845
+ # where c is zero, set x to a finite bound or zero
846
+ x_zero_c = ub_mod[c == 0]
847
+ x_zero_c[np.isinf(x_zero_c)] = ub_mod[c == 0][np.isinf(x_zero_c)]
848
+ x_zero_c[np.isinf(x_zero_c)] = 0
849
+ x[c == 0] = x_zero_c
850
+ # if this is not the last step of presolve, should convert bounds back
851
+ # to array and return here
852
+
853
+ # Convert modified lb and ub back into N x 2 bounds
854
+ bounds = np.hstack((lb_mod[:, np.newaxis], ub_mod[:, np.newaxis]))
855
+
856
+ # remove redundant (linearly dependent) rows from equality constraints
857
+ n_rows_A = A_eq.shape[0]
858
+ redundancy_warning = ("A_eq does not appear to be of full row rank. To "
859
+ "improve performance, check the problem formulation "
860
+ "for redundant equality constraints.")
861
+ if (sps.issparse(A_eq)):
862
+ if rr and A_eq.size > 0: # TODO: Fast sparse rank check?
863
+ rr_res = _remove_redundancy_pivot_sparse(A_eq, b_eq)
864
+ A_eq, b_eq, status, message = rr_res
865
+ if A_eq.shape[0] < n_rows_A:
866
+ warn(redundancy_warning, OptimizeWarning, stacklevel=1)
867
+ if status != 0:
868
+ complete = True
869
+ return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0),
870
+ c0, x, revstack, complete, status, message)
871
+
872
+ # This is a wild guess for which redundancy removal algorithm will be
873
+ # faster. More testing would be good.
874
+ small_nullspace = 5
875
+ if rr and A_eq.size > 0:
876
+ try: # TODO: use results of first SVD in _remove_redundancy_svd
877
+ rank = np.linalg.matrix_rank(A_eq)
878
+ # oh well, we'll have to go with _remove_redundancy_pivot_dense
879
+ except Exception:
880
+ rank = 0
881
+ if rr and A_eq.size > 0 and rank < A_eq.shape[0]:
882
+ warn(redundancy_warning, OptimizeWarning, stacklevel=3)
883
+ dim_row_nullspace = A_eq.shape[0]-rank
884
+ if rr_method is None:
885
+ if dim_row_nullspace <= small_nullspace:
886
+ rr_res = _remove_redundancy_svd(A_eq, b_eq)
887
+ A_eq, b_eq, status, message = rr_res
888
+ if dim_row_nullspace > small_nullspace or status == 4:
889
+ rr_res = _remove_redundancy_pivot_dense(A_eq, b_eq)
890
+ A_eq, b_eq, status, message = rr_res
891
+
892
+ else:
893
+ rr_method = rr_method.lower()
894
+ if rr_method == "svd":
895
+ rr_res = _remove_redundancy_svd(A_eq, b_eq)
896
+ A_eq, b_eq, status, message = rr_res
897
+ elif rr_method == "pivot":
898
+ rr_res = _remove_redundancy_pivot_dense(A_eq, b_eq)
899
+ A_eq, b_eq, status, message = rr_res
900
+ elif rr_method == "id":
901
+ rr_res = _remove_redundancy_id(A_eq, b_eq, rank)
902
+ A_eq, b_eq, status, message = rr_res
903
+ else: # shouldn't get here; option validity checked above
904
+ pass
905
+ if A_eq.shape[0] < rank:
906
+ message = ("Due to numerical issues, redundant equality "
907
+ "constraints could not be removed automatically. "
908
+ "Try providing your constraint matrices as sparse "
909
+ "matrices to activate sparse presolve, try turning "
910
+ "off redundancy removal, or try turning off presolve "
911
+ "altogether.")
912
+ status = 4
913
+ if status != 0:
914
+ complete = True
915
+ return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0),
916
+ c0, x, revstack, complete, status, message)
917
+
918
+
919
+ def _parse_linprog(lp, options, meth):
920
+ """
921
+ Parse the provided linear programming problem
922
+
923
+ ``_parse_linprog`` employs two main steps ``_check_sparse_inputs`` and
924
+ ``_clean_inputs``. ``_check_sparse_inputs`` checks for sparsity in the
925
+ provided constraints (``A_ub`` and ``A_eq) and if these match the provided
926
+ sparsity optional values.
927
+
928
+ ``_clean inputs`` checks of the provided inputs. If no violations are
929
+ identified the objective vector, upper bound constraints, equality
930
+ constraints, and simple bounds are returned in the expected format.
931
+
932
+ Parameters
933
+ ----------
934
+ lp : A `scipy.optimize._linprog_util._LPProblem` consisting of the following fields:
935
+
936
+ c : 1D array
937
+ The coefficients of the linear objective function to be minimized.
938
+ A_ub : 2D array, optional
939
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
940
+ coefficients of a linear inequality constraint on ``x``.
941
+ b_ub : 1D array, optional
942
+ The inequality constraint vector. Each element represents an
943
+ upper bound on the corresponding value of ``A_ub @ x``.
944
+ A_eq : 2D array, optional
945
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
946
+ coefficients of a linear equality constraint on ``x``.
947
+ b_eq : 1D array, optional
948
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
949
+ the corresponding element of ``b_eq``.
950
+ bounds : various valid formats, optional
951
+ The bounds of ``x``, as ``min`` and ``max`` pairs.
952
+ If bounds are specified for all N variables separately, valid formats are:
953
+ * a 2D array (2 x N or N x 2);
954
+ * a sequence of N sequences, each with 2 values.
955
+ If all variables have the same bounds, a single pair of values can
956
+ be specified. Valid formats are:
957
+ * a sequence with 2 scalar values;
958
+ * a sequence with a single element containing 2 scalar values.
959
+ If all variables have a lower bound of 0 and no upper bound, the bounds
960
+ parameter can be omitted (or given as None).
961
+ x0 : 1D array, optional
962
+ Guess values of the decision variables, which will be refined by
963
+ the optimization algorithm. This argument is currently used only by the
964
+ 'revised simplex' method, and can only be used if `x0` represents a
965
+ basic feasible solution.
966
+
967
+ options : dict
968
+ A dictionary of solver options. All methods accept the following
969
+ generic options:
970
+
971
+ maxiter : int
972
+ Maximum number of iterations to perform.
973
+ disp : bool
974
+ Set to True to print convergence messages.
975
+
976
+ For method-specific options, see :func:`show_options('linprog')`.
977
+
978
+ Returns
979
+ -------
980
+ lp : A `scipy.optimize._linprog_util._LPProblem` consisting of the following fields:
981
+
982
+ c : 1D array
983
+ The coefficients of the linear objective function to be minimized.
984
+ A_ub : 2D array, optional
985
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
986
+ coefficients of a linear inequality constraint on ``x``.
987
+ b_ub : 1D array, optional
988
+ The inequality constraint vector. Each element represents an
989
+ upper bound on the corresponding value of ``A_ub @ x``.
990
+ A_eq : 2D array, optional
991
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
992
+ coefficients of a linear equality constraint on ``x``.
993
+ b_eq : 1D array, optional
994
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
995
+ the corresponding element of ``b_eq``.
996
+ bounds : 2D array
997
+ The bounds of ``x``, as ``min`` and ``max`` pairs, one for each of the N
998
+ elements of ``x``. The N x 2 array contains lower bounds in the first
999
+ column and upper bounds in the 2nd. Unbounded variables have lower
1000
+ bound -np.inf and/or upper bound np.inf.
1001
+ x0 : 1D array, optional
1002
+ Guess values of the decision variables, which will be refined by
1003
+ the optimization algorithm. This argument is currently used only by the
1004
+ 'revised simplex' method, and can only be used if `x0` represents a
1005
+ basic feasible solution.
1006
+
1007
+ options : dict, optional
1008
+ A dictionary of solver options. All methods accept the following
1009
+ generic options:
1010
+
1011
+ maxiter : int
1012
+ Maximum number of iterations to perform.
1013
+ disp : bool
1014
+ Set to True to print convergence messages.
1015
+
1016
+ For method-specific options, see :func:`show_options('linprog')`.
1017
+
1018
+ """
1019
+ if options is None:
1020
+ options = {}
1021
+
1022
+ solver_options = {k: v for k, v in options.items()}
1023
+ solver_options, A_ub, A_eq = _check_sparse_inputs(solver_options, meth,
1024
+ lp.A_ub, lp.A_eq)
1025
+ # Convert lists to numpy arrays, etc...
1026
+ lp = _clean_inputs(lp._replace(A_ub=A_ub, A_eq=A_eq))
1027
+ return lp, solver_options
1028
+
1029
+
1030
+ def _get_Abc(lp, c0):
1031
+ """
1032
+ Given a linear programming problem of the form:
1033
+
1034
+ Minimize::
1035
+
1036
+ c @ x
1037
+
1038
+ Subject to::
1039
+
1040
+ A_ub @ x <= b_ub
1041
+ A_eq @ x == b_eq
1042
+ lb <= x <= ub
1043
+
1044
+ where ``lb = 0`` and ``ub = None`` unless set in ``bounds``.
1045
+
1046
+ Return the problem in standard form:
1047
+
1048
+ Minimize::
1049
+
1050
+ c @ x
1051
+
1052
+ Subject to::
1053
+
1054
+ A @ x == b
1055
+ x >= 0
1056
+
1057
+ by adding slack variables and making variable substitutions as necessary.
1058
+
1059
+ Parameters
1060
+ ----------
1061
+ lp : A `scipy.optimize._linprog_util._LPProblem` consisting of the following fields:
1062
+
1063
+ c : 1D array
1064
+ The coefficients of the linear objective function to be minimized.
1065
+ A_ub : 2D array, optional
1066
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
1067
+ coefficients of a linear inequality constraint on ``x``.
1068
+ b_ub : 1D array, optional
1069
+ The inequality constraint vector. Each element represents an
1070
+ upper bound on the corresponding value of ``A_ub @ x``.
1071
+ A_eq : 2D array, optional
1072
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
1073
+ coefficients of a linear equality constraint on ``x``.
1074
+ b_eq : 1D array, optional
1075
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
1076
+ the corresponding element of ``b_eq``.
1077
+ bounds : 2D array
1078
+ The bounds of ``x``, lower bounds in the 1st column, upper
1079
+ bounds in the 2nd column. The bounds are possibly tightened
1080
+ by the presolve procedure.
1081
+ x0 : 1D array, optional
1082
+ Guess values of the decision variables, which will be refined by
1083
+ the optimization algorithm. This argument is currently used only by the
1084
+ 'revised simplex' method, and can only be used if `x0` represents a
1085
+ basic feasible solution.
1086
+
1087
+ c0 : float
1088
+ Constant term in objective function due to fixed (and eliminated)
1089
+ variables.
1090
+
1091
+ Returns
1092
+ -------
1093
+ A : 2-D array
1094
+ 2-D array such that ``A`` @ ``x``, gives the values of the equality
1095
+ constraints at ``x``.
1096
+ b : 1-D array
1097
+ 1-D array of values representing the RHS of each equality constraint
1098
+ (row) in A (for standard form problem).
1099
+ c : 1-D array
1100
+ Coefficients of the linear objective function to be minimized (for
1101
+ standard form problem).
1102
+ c0 : float
1103
+ Constant term in objective function due to fixed (and eliminated)
1104
+ variables.
1105
+ x0 : 1-D array
1106
+ Starting values of the independent variables, which will be refined by
1107
+ the optimization algorithm
1108
+
1109
+ References
1110
+ ----------
1111
+ .. [9] Bertsimas, Dimitris, and J. Tsitsiklis. "Introduction to linear
1112
+ programming." Athena Scientific 1 (1997): 997.
1113
+
1114
+ """
1115
+ c, A_ub, b_ub, A_eq, b_eq, bounds, x0, integrality = lp
1116
+
1117
+ if sps.issparse(A_eq):
1118
+ sparse = True
1119
+ A_eq = sps.csr_matrix(A_eq)
1120
+ A_ub = sps.csr_matrix(A_ub)
1121
+
1122
+ def hstack(blocks):
1123
+ return sps.hstack(blocks, format="csr")
1124
+
1125
+ def vstack(blocks):
1126
+ return sps.vstack(blocks, format="csr")
1127
+
1128
+ zeros = sps.csr_matrix
1129
+ eye = sps.eye
1130
+ else:
1131
+ sparse = False
1132
+ hstack = np.hstack
1133
+ vstack = np.vstack
1134
+ zeros = np.zeros
1135
+ eye = np.eye
1136
+
1137
+ # Variables lbs and ubs (see below) may be changed, which feeds back into
1138
+ # bounds, so copy.
1139
+ bounds = np.array(bounds, copy=True)
1140
+
1141
+ # modify problem such that all variables have only non-negativity bounds
1142
+ lbs = bounds[:, 0]
1143
+ ubs = bounds[:, 1]
1144
+ m_ub, n_ub = A_ub.shape
1145
+
1146
+ lb_none = np.equal(lbs, -np.inf)
1147
+ ub_none = np.equal(ubs, np.inf)
1148
+ lb_some = np.logical_not(lb_none)
1149
+ ub_some = np.logical_not(ub_none)
1150
+
1151
+ # unbounded below: substitute xi = -xi' (unbounded above)
1152
+ # if -inf <= xi <= ub, then -ub <= -xi <= inf, so swap and invert bounds
1153
+ l_nolb_someub = np.logical_and(lb_none, ub_some)
1154
+ i_nolb = np.nonzero(l_nolb_someub)[0]
1155
+ lbs[l_nolb_someub], ubs[l_nolb_someub] = (
1156
+ -ubs[l_nolb_someub], -lbs[l_nolb_someub])
1157
+ lb_none = np.equal(lbs, -np.inf)
1158
+ ub_none = np.equal(ubs, np.inf)
1159
+ lb_some = np.logical_not(lb_none)
1160
+ ub_some = np.logical_not(ub_none)
1161
+ c[i_nolb] *= -1
1162
+ if x0 is not None:
1163
+ x0[i_nolb] *= -1
1164
+ if len(i_nolb) > 0:
1165
+ if A_ub.shape[0] > 0: # sometimes needed for sparse arrays... weird
1166
+ A_ub[:, i_nolb] *= -1
1167
+ if A_eq.shape[0] > 0:
1168
+ A_eq[:, i_nolb] *= -1
1169
+
1170
+ # upper bound: add inequality constraint
1171
+ i_newub, = ub_some.nonzero()
1172
+ ub_newub = ubs[ub_some]
1173
+ n_bounds = len(i_newub)
1174
+ if n_bounds > 0:
1175
+ shape = (n_bounds, A_ub.shape[1])
1176
+ if sparse:
1177
+ idxs = (np.arange(n_bounds), i_newub)
1178
+ A_ub = vstack((A_ub, sps.csr_matrix((np.ones(n_bounds), idxs),
1179
+ shape=shape)))
1180
+ else:
1181
+ A_ub = vstack((A_ub, np.zeros(shape)))
1182
+ A_ub[np.arange(m_ub, A_ub.shape[0]), i_newub] = 1
1183
+ b_ub = np.concatenate((b_ub, np.zeros(n_bounds)))
1184
+ b_ub[m_ub:] = ub_newub
1185
+
1186
+ A1 = vstack((A_ub, A_eq))
1187
+ b = np.concatenate((b_ub, b_eq))
1188
+ c = np.concatenate((c, np.zeros((A_ub.shape[0],))))
1189
+ if x0 is not None:
1190
+ x0 = np.concatenate((x0, np.zeros((A_ub.shape[0],))))
1191
+ # unbounded: substitute xi = xi+ + xi-
1192
+ l_free = np.logical_and(lb_none, ub_none)
1193
+ i_free = np.nonzero(l_free)[0]
1194
+ n_free = len(i_free)
1195
+ c = np.concatenate((c, np.zeros(n_free)))
1196
+ if x0 is not None:
1197
+ x0 = np.concatenate((x0, np.zeros(n_free)))
1198
+ A1 = hstack((A1[:, :n_ub], -A1[:, i_free]))
1199
+ c[n_ub:n_ub+n_free] = -c[i_free]
1200
+ if x0 is not None:
1201
+ i_free_neg = x0[i_free] < 0
1202
+ x0[np.arange(n_ub, A1.shape[1])[i_free_neg]] = -x0[i_free[i_free_neg]]
1203
+ x0[i_free[i_free_neg]] = 0
1204
+
1205
+ # add slack variables
1206
+ A2 = vstack([eye(A_ub.shape[0]), zeros((A_eq.shape[0], A_ub.shape[0]))])
1207
+
1208
+ A = hstack([A1, A2])
1209
+
1210
+ # lower bound: substitute xi = xi' + lb
1211
+ # now there is a constant term in objective
1212
+ i_shift = np.nonzero(lb_some)[0]
1213
+ lb_shift = lbs[lb_some].astype(float)
1214
+ c0 += np.sum(lb_shift * c[i_shift])
1215
+ if sparse:
1216
+ b = b.reshape(-1, 1)
1217
+ A = A.tocsc()
1218
+ b -= (A[:, i_shift] * sps.diags(lb_shift)).sum(axis=1)
1219
+ b = b.ravel()
1220
+ else:
1221
+ b -= (A[:, i_shift] * lb_shift).sum(axis=1)
1222
+ if x0 is not None:
1223
+ x0[i_shift] -= lb_shift
1224
+
1225
+ return A, b, c, c0, x0
1226
+
1227
+
1228
+ def _round_to_power_of_two(x):
1229
+ """
1230
+ Round elements of the array to the nearest power of two.
1231
+ """
1232
+ return 2**np.around(np.log2(x))
1233
+
1234
+
1235
+ def _autoscale(A, b, c, x0):
1236
+ """
1237
+ Scales the problem according to equilibration from [12].
1238
+ Also normalizes the right hand side vector by its maximum element.
1239
+ """
1240
+ m, n = A.shape
1241
+
1242
+ C = 1
1243
+ R = 1
1244
+
1245
+ if A.size > 0:
1246
+
1247
+ R = np.max(np.abs(A), axis=1)
1248
+ if sps.issparse(A):
1249
+ R = R.toarray().flatten()
1250
+ R[R == 0] = 1
1251
+ R = 1/_round_to_power_of_two(R)
1252
+ A = sps.diags(R)*A if sps.issparse(A) else A*R.reshape(m, 1)
1253
+ b = b*R
1254
+
1255
+ C = np.max(np.abs(A), axis=0)
1256
+ if sps.issparse(A):
1257
+ C = C.toarray().flatten()
1258
+ C[C == 0] = 1
1259
+ C = 1/_round_to_power_of_two(C)
1260
+ A = A*sps.diags(C) if sps.issparse(A) else A*C
1261
+ c = c*C
1262
+
1263
+ b_scale = np.max(np.abs(b)) if b.size > 0 else 1
1264
+ if b_scale == 0:
1265
+ b_scale = 1.
1266
+ b = b/b_scale
1267
+
1268
+ if x0 is not None:
1269
+ x0 = x0/b_scale*(1/C)
1270
+ return A, b, c, x0, C, b_scale
1271
+
1272
+
1273
+ def _unscale(x, C, b_scale):
1274
+ """
1275
+ Converts solution to _autoscale problem -> solution to original problem.
1276
+ """
1277
+
1278
+ try:
1279
+ n = len(C)
1280
+ # fails if sparse or scalar; that's OK.
1281
+ # this is only needed for original simplex (never sparse)
1282
+ except TypeError:
1283
+ n = len(x)
1284
+
1285
+ return x[:n]*b_scale*C
1286
+
1287
+
1288
+ def _display_summary(message, status, fun, iteration):
1289
+ """
1290
+ Print the termination summary of the linear program
1291
+
1292
+ Parameters
1293
+ ----------
1294
+ message : str
1295
+ A string descriptor of the exit status of the optimization.
1296
+ status : int
1297
+ An integer representing the exit status of the optimization::
1298
+
1299
+ 0 : Optimization terminated successfully
1300
+ 1 : Iteration limit reached
1301
+ 2 : Problem appears to be infeasible
1302
+ 3 : Problem appears to be unbounded
1303
+ 4 : Serious numerical difficulties encountered
1304
+
1305
+ fun : float
1306
+ Value of the objective function.
1307
+ iteration : iteration
1308
+ The number of iterations performed.
1309
+ """
1310
+ print(message)
1311
+ if status in (0, 1):
1312
+ print(f" Current function value: {fun: <12.6f}")
1313
+ print(f" Iterations: {iteration:d}")
1314
+
1315
+
1316
+ def _postsolve(x, postsolve_args, complete=False):
1317
+ """
1318
+ Given solution x to presolved, standard form linear program x, add
1319
+ fixed variables back into the problem and undo the variable substitutions
1320
+ to get solution to original linear program. Also, calculate the objective
1321
+ function value, slack in original upper bound constraints, and residuals
1322
+ in original equality constraints.
1323
+
1324
+ Parameters
1325
+ ----------
1326
+ x : 1-D array
1327
+ Solution vector to the standard-form problem.
1328
+ postsolve_args : tuple
1329
+ Data needed by _postsolve to convert the solution to the standard-form
1330
+ problem into the solution to the original problem, including:
1331
+
1332
+ lp : A `scipy.optimize._linprog_util._LPProblem` consisting of the following fields:
1333
+
1334
+ c : 1D array
1335
+ The coefficients of the linear objective function to be minimized.
1336
+ A_ub : 2D array, optional
1337
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
1338
+ coefficients of a linear inequality constraint on ``x``.
1339
+ b_ub : 1D array, optional
1340
+ The inequality constraint vector. Each element represents an
1341
+ upper bound on the corresponding value of ``A_ub @ x``.
1342
+ A_eq : 2D array, optional
1343
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
1344
+ coefficients of a linear equality constraint on ``x``.
1345
+ b_eq : 1D array, optional
1346
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
1347
+ the corresponding element of ``b_eq``.
1348
+ bounds : 2D array
1349
+ The bounds of ``x``, lower bounds in the 1st column, upper
1350
+ bounds in the 2nd column. The bounds are possibly tightened
1351
+ by the presolve procedure.
1352
+ x0 : 1D array, optional
1353
+ Guess values of the decision variables, which will be refined by
1354
+ the optimization algorithm. This argument is currently used only by the
1355
+ 'revised simplex' method, and can only be used if `x0` represents a
1356
+ basic feasible solution.
1357
+
1358
+ revstack: list of functions
1359
+ the functions in the list reverse the operations of _presolve()
1360
+ the function signature is x_org = f(x_mod), where x_mod is the result
1361
+ of a presolve step and x_org the value at the start of the step
1362
+ complete : bool
1363
+ Whether the solution is was determined in presolve (``True`` if so)
1364
+
1365
+ Returns
1366
+ -------
1367
+ x : 1-D array
1368
+ Solution vector to original linear programming problem
1369
+ fun: float
1370
+ optimal objective value for original problem
1371
+ slack : 1-D array
1372
+ The (non-negative) slack in the upper bound constraints, that is,
1373
+ ``b_ub - A_ub @ x``
1374
+ con : 1-D array
1375
+ The (nominally zero) residuals of the equality constraints, that is,
1376
+ ``b - A_eq @ x``
1377
+ """
1378
+ # note that all the inputs are the ORIGINAL, unmodified versions
1379
+ # no rows, columns have been removed
1380
+
1381
+ c, A_ub, b_ub, A_eq, b_eq, bounds, x0, integrality = postsolve_args[0]
1382
+ revstack, C, b_scale = postsolve_args[1:]
1383
+
1384
+ x = _unscale(x, C, b_scale)
1385
+
1386
+ # Undo variable substitutions of _get_Abc()
1387
+ # if "complete", problem was solved in presolve; don't do anything here
1388
+ n_x = bounds.shape[0]
1389
+ if not complete and bounds is not None: # bounds are never none, probably
1390
+ n_unbounded = 0
1391
+ for i, bi in enumerate(bounds):
1392
+ lbi = bi[0]
1393
+ ubi = bi[1]
1394
+ if lbi == -np.inf and ubi == np.inf:
1395
+ n_unbounded += 1
1396
+ x[i] = x[i] - x[n_x + n_unbounded - 1]
1397
+ else:
1398
+ if lbi == -np.inf:
1399
+ x[i] = ubi - x[i]
1400
+ else:
1401
+ x[i] += lbi
1402
+ # all the rest of the variables were artificial
1403
+ x = x[:n_x]
1404
+
1405
+ # If there were variables removed from the problem, add them back into the
1406
+ # solution vector
1407
+ # Apply the functions in revstack (reverse direction)
1408
+ for rev in reversed(revstack):
1409
+ x = rev(x)
1410
+
1411
+ fun = x.dot(c)
1412
+ slack = b_ub - A_ub.dot(x) # report slack for ORIGINAL UB constraints
1413
+ # report residuals of ORIGINAL EQ constraints
1414
+ con = b_eq - A_eq.dot(x)
1415
+
1416
+ return x, fun, slack, con
1417
+
1418
+
1419
+ def _check_result(x, fun, status, slack, con, bounds, tol, message,
1420
+ integrality):
1421
+ """
1422
+ Check the validity of the provided solution.
1423
+
1424
+ A valid (optimal) solution satisfies all bounds, all slack variables are
1425
+ negative and all equality constraint residuals are strictly non-zero.
1426
+ Further, the lower-bounds, upper-bounds, slack and residuals contain
1427
+ no nan values.
1428
+
1429
+ Parameters
1430
+ ----------
1431
+ x : 1-D array
1432
+ Solution vector to original linear programming problem
1433
+ fun: float
1434
+ optimal objective value for original problem
1435
+ status : int
1436
+ An integer representing the exit status of the optimization::
1437
+
1438
+ 0 : Optimization terminated successfully
1439
+ 1 : Iteration limit reached
1440
+ 2 : Problem appears to be infeasible
1441
+ 3 : Problem appears to be unbounded
1442
+ 4 : Serious numerical difficulties encountered
1443
+
1444
+ slack : 1-D array
1445
+ The (non-negative) slack in the upper bound constraints, that is,
1446
+ ``b_ub - A_ub @ x``
1447
+ con : 1-D array
1448
+ The (nominally zero) residuals of the equality constraints, that is,
1449
+ ``b - A_eq @ x``
1450
+ bounds : 2D array
1451
+ The bounds on the original variables ``x``
1452
+ message : str
1453
+ A string descriptor of the exit status of the optimization.
1454
+ tol : float
1455
+ Termination tolerance; see [1]_ Section 4.5.
1456
+
1457
+ Returns
1458
+ -------
1459
+ status : int
1460
+ An integer representing the exit status of the optimization::
1461
+
1462
+ 0 : Optimization terminated successfully
1463
+ 1 : Iteration limit reached
1464
+ 2 : Problem appears to be infeasible
1465
+ 3 : Problem appears to be unbounded
1466
+ 4 : Serious numerical difficulties encountered
1467
+
1468
+ message : str
1469
+ A string descriptor of the exit status of the optimization.
1470
+ """
1471
+ # Somewhat arbitrary
1472
+ tol = np.sqrt(tol) * 10
1473
+
1474
+ if x is None:
1475
+ # HiGHS does not provide x if infeasible/unbounded
1476
+ if status == 0: # Observed with HiGHS Simplex Primal
1477
+ status = 4
1478
+ message = ("The solver did not provide a solution nor did it "
1479
+ "report a failure. Please submit a bug report.")
1480
+ return status, message
1481
+
1482
+ contains_nans = (
1483
+ np.isnan(x).any()
1484
+ or np.isnan(fun)
1485
+ or np.isnan(slack).any()
1486
+ or np.isnan(con).any()
1487
+ )
1488
+
1489
+ if contains_nans:
1490
+ is_feasible = False
1491
+ else:
1492
+ if integrality is None:
1493
+ integrality = 0
1494
+ valid_bounds = (x >= bounds[:, 0] - tol) & (x <= bounds[:, 1] + tol)
1495
+ # When integrality is 2 or 3, x must be within bounds OR take value 0
1496
+ valid_bounds |= (integrality > 1) & np.isclose(x, 0, atol=tol)
1497
+ invalid_bounds = not np.all(valid_bounds)
1498
+
1499
+ invalid_slack = status != 3 and (slack < -tol).any()
1500
+ invalid_con = status != 3 and (np.abs(con) > tol).any()
1501
+ is_feasible = not (invalid_bounds or invalid_slack or invalid_con)
1502
+
1503
+ if status == 0 and not is_feasible:
1504
+ status = 4
1505
+ message = ("The solution does not satisfy the constraints within the "
1506
+ "required tolerance of " + f"{tol:.2E}" + ", yet "
1507
+ "no errors were raised and there is no certificate of "
1508
+ "infeasibility or unboundedness. Check whether "
1509
+ "the slack and constraint residuals are acceptable; "
1510
+ "if not, consider enabling presolve, adjusting the "
1511
+ "tolerance option(s), and/or using a different method. "
1512
+ "Please consider submitting a bug report.")
1513
+ elif status == 2 and is_feasible:
1514
+ # Occurs if the simplex method exits after phase one with a very
1515
+ # nearly basic feasible solution. Postsolving can make the solution
1516
+ # basic, however, this solution is NOT optimal
1517
+ status = 4
1518
+ message = ("The solution is feasible, but the solver did not report "
1519
+ "that the solution was optimal. Please try a different "
1520
+ "method.")
1521
+
1522
+ return status, message
vila/lib/python3.10/site-packages/scipy/optimize/_lsap.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (27.1 kB). View file
 
vila/lib/python3.10/site-packages/scipy/optimize/_milp.py ADDED
@@ -0,0 +1,392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ import numpy as np
3
+ from scipy.sparse import csc_array, vstack, issparse
4
+ from scipy._lib._util import VisibleDeprecationWarning
5
+ from ._highs._highs_wrapper import _highs_wrapper # type: ignore[import-not-found,import-untyped]
6
+ from ._constraints import LinearConstraint, Bounds
7
+ from ._optimize import OptimizeResult
8
+ from ._linprog_highs import _highs_to_scipy_status_message
9
+
10
+
11
+ def _constraints_to_components(constraints):
12
+ """
13
+ Convert sequence of constraints to a single set of components A, b_l, b_u.
14
+
15
+ `constraints` could be
16
+
17
+ 1. A LinearConstraint
18
+ 2. A tuple representing a LinearConstraint
19
+ 3. An invalid object
20
+ 4. A sequence of composed entirely of objects of type 1/2
21
+ 5. A sequence containing at least one object of type 3
22
+
23
+ We want to accept 1, 2, and 4 and reject 3 and 5.
24
+ """
25
+ message = ("`constraints` (or each element within `constraints`) must be "
26
+ "convertible into an instance of "
27
+ "`scipy.optimize.LinearConstraint`.")
28
+ As = []
29
+ b_ls = []
30
+ b_us = []
31
+
32
+ # Accept case 1 by standardizing as case 4
33
+ if isinstance(constraints, LinearConstraint):
34
+ constraints = [constraints]
35
+ else:
36
+ # Reject case 3
37
+ try:
38
+ iter(constraints)
39
+ except TypeError as exc:
40
+ raise ValueError(message) from exc
41
+
42
+ # Accept case 2 by standardizing as case 4
43
+ if len(constraints) == 3:
44
+ # argument could be a single tuple representing a LinearConstraint
45
+ try:
46
+ constraints = [LinearConstraint(*constraints)]
47
+ except (TypeError, ValueError, VisibleDeprecationWarning):
48
+ # argument was not a tuple representing a LinearConstraint
49
+ pass
50
+
51
+ # Address cases 4/5
52
+ for constraint in constraints:
53
+ # if it's not a LinearConstraint or something that represents a
54
+ # LinearConstraint at this point, it's invalid
55
+ if not isinstance(constraint, LinearConstraint):
56
+ try:
57
+ constraint = LinearConstraint(*constraint)
58
+ except TypeError as exc:
59
+ raise ValueError(message) from exc
60
+ As.append(csc_array(constraint.A))
61
+ b_ls.append(np.atleast_1d(constraint.lb).astype(np.float64))
62
+ b_us.append(np.atleast_1d(constraint.ub).astype(np.float64))
63
+
64
+ if len(As) > 1:
65
+ A = vstack(As, format="csc")
66
+ b_l = np.concatenate(b_ls)
67
+ b_u = np.concatenate(b_us)
68
+ else: # avoid unnecessary copying
69
+ A = As[0]
70
+ b_l = b_ls[0]
71
+ b_u = b_us[0]
72
+
73
+ return A, b_l, b_u
74
+
75
+
76
+ def _milp_iv(c, integrality, bounds, constraints, options):
77
+ # objective IV
78
+ if issparse(c):
79
+ raise ValueError("`c` must be a dense array.")
80
+ c = np.atleast_1d(c).astype(np.float64)
81
+ if c.ndim != 1 or c.size == 0 or not np.all(np.isfinite(c)):
82
+ message = ("`c` must be a one-dimensional array of finite numbers "
83
+ "with at least one element.")
84
+ raise ValueError(message)
85
+
86
+ # integrality IV
87
+ if issparse(integrality):
88
+ raise ValueError("`integrality` must be a dense array.")
89
+ message = ("`integrality` must contain integers 0-3 and be broadcastable "
90
+ "to `c.shape`.")
91
+ if integrality is None:
92
+ integrality = 0
93
+ try:
94
+ integrality = np.broadcast_to(integrality, c.shape).astype(np.uint8)
95
+ except ValueError:
96
+ raise ValueError(message)
97
+ if integrality.min() < 0 or integrality.max() > 3:
98
+ raise ValueError(message)
99
+
100
+ # bounds IV
101
+ if bounds is None:
102
+ bounds = Bounds(0, np.inf)
103
+ elif not isinstance(bounds, Bounds):
104
+ message = ("`bounds` must be convertible into an instance of "
105
+ "`scipy.optimize.Bounds`.")
106
+ try:
107
+ bounds = Bounds(*bounds)
108
+ except TypeError as exc:
109
+ raise ValueError(message) from exc
110
+
111
+ try:
112
+ lb = np.broadcast_to(bounds.lb, c.shape).astype(np.float64)
113
+ ub = np.broadcast_to(bounds.ub, c.shape).astype(np.float64)
114
+ except (ValueError, TypeError) as exc:
115
+ message = ("`bounds.lb` and `bounds.ub` must contain reals and "
116
+ "be broadcastable to `c.shape`.")
117
+ raise ValueError(message) from exc
118
+
119
+ # constraints IV
120
+ if not constraints:
121
+ constraints = [LinearConstraint(np.empty((0, c.size)),
122
+ np.empty((0,)), np.empty((0,)))]
123
+ try:
124
+ A, b_l, b_u = _constraints_to_components(constraints)
125
+ except ValueError as exc:
126
+ message = ("`constraints` (or each element within `constraints`) must "
127
+ "be convertible into an instance of "
128
+ "`scipy.optimize.LinearConstraint`.")
129
+ raise ValueError(message) from exc
130
+
131
+ if A.shape != (b_l.size, c.size):
132
+ message = "The shape of `A` must be (len(b_l), len(c))."
133
+ raise ValueError(message)
134
+ indptr, indices, data = A.indptr, A.indices, A.data.astype(np.float64)
135
+
136
+ # options IV
137
+ options = options or {}
138
+ supported_options = {'disp', 'presolve', 'time_limit', 'node_limit',
139
+ 'mip_rel_gap'}
140
+ unsupported_options = set(options).difference(supported_options)
141
+ if unsupported_options:
142
+ message = (f"Unrecognized options detected: {unsupported_options}. "
143
+ "These will be passed to HiGHS verbatim.")
144
+ warnings.warn(message, RuntimeWarning, stacklevel=3)
145
+ options_iv = {'log_to_console': options.pop("disp", False),
146
+ 'mip_max_nodes': options.pop("node_limit", None)}
147
+ options_iv.update(options)
148
+
149
+ return c, integrality, lb, ub, indptr, indices, data, b_l, b_u, options_iv
150
+
151
+
152
+ def milp(c, *, integrality=None, bounds=None, constraints=None, options=None):
153
+ r"""
154
+ Mixed-integer linear programming
155
+
156
+ Solves problems of the following form:
157
+
158
+ .. math::
159
+
160
+ \min_x \ & c^T x \\
161
+ \mbox{such that} \ & b_l \leq A x \leq b_u,\\
162
+ & l \leq x \leq u, \\
163
+ & x_i \in \mathbb{Z}, i \in X_i
164
+
165
+ where :math:`x` is a vector of decision variables;
166
+ :math:`c`, :math:`b_l`, :math:`b_u`, :math:`l`, and :math:`u` are vectors;
167
+ :math:`A` is a matrix, and :math:`X_i` is the set of indices of
168
+ decision variables that must be integral. (In this context, a
169
+ variable that can assume only integer values is said to be "integral";
170
+ it has an "integrality" constraint.)
171
+
172
+ Alternatively, that's:
173
+
174
+ minimize::
175
+
176
+ c @ x
177
+
178
+ such that::
179
+
180
+ b_l <= A @ x <= b_u
181
+ l <= x <= u
182
+ Specified elements of x must be integers
183
+
184
+ By default, ``l = 0`` and ``u = np.inf`` unless specified with
185
+ ``bounds``.
186
+
187
+ Parameters
188
+ ----------
189
+ c : 1D dense array_like
190
+ The coefficients of the linear objective function to be minimized.
191
+ `c` is converted to a double precision array before the problem is
192
+ solved.
193
+ integrality : 1D dense array_like, optional
194
+ Indicates the type of integrality constraint on each decision variable.
195
+
196
+ ``0`` : Continuous variable; no integrality constraint.
197
+
198
+ ``1`` : Integer variable; decision variable must be an integer
199
+ within `bounds`.
200
+
201
+ ``2`` : Semi-continuous variable; decision variable must be within
202
+ `bounds` or take value ``0``.
203
+
204
+ ``3`` : Semi-integer variable; decision variable must be an integer
205
+ within `bounds` or take value ``0``.
206
+
207
+ By default, all variables are continuous. `integrality` is converted
208
+ to an array of integers before the problem is solved.
209
+
210
+ bounds : scipy.optimize.Bounds, optional
211
+ Bounds on the decision variables. Lower and upper bounds are converted
212
+ to double precision arrays before the problem is solved. The
213
+ ``keep_feasible`` parameter of the `Bounds` object is ignored. If
214
+ not specified, all decision variables are constrained to be
215
+ non-negative.
216
+ constraints : sequence of scipy.optimize.LinearConstraint, optional
217
+ Linear constraints of the optimization problem. Arguments may be
218
+ one of the following:
219
+
220
+ 1. A single `LinearConstraint` object
221
+ 2. A single tuple that can be converted to a `LinearConstraint` object
222
+ as ``LinearConstraint(*constraints)``
223
+ 3. A sequence composed entirely of objects of type 1. and 2.
224
+
225
+ Before the problem is solved, all values are converted to double
226
+ precision, and the matrices of constraint coefficients are converted to
227
+ instances of `scipy.sparse.csc_array`. The ``keep_feasible`` parameter
228
+ of `LinearConstraint` objects is ignored.
229
+ options : dict, optional
230
+ A dictionary of solver options. The following keys are recognized.
231
+
232
+ disp : bool (default: ``False``)
233
+ Set to ``True`` if indicators of optimization status are to be
234
+ printed to the console during optimization.
235
+ node_limit : int, optional
236
+ The maximum number of nodes (linear program relaxations) to solve
237
+ before stopping. Default is no maximum number of nodes.
238
+ presolve : bool (default: ``True``)
239
+ Presolve attempts to identify trivial infeasibilities,
240
+ identify trivial unboundedness, and simplify the problem before
241
+ sending it to the main solver.
242
+ time_limit : float, optional
243
+ The maximum number of seconds allotted to solve the problem.
244
+ Default is no time limit.
245
+ mip_rel_gap : float, optional
246
+ Termination criterion for MIP solver: solver will terminate when
247
+ the gap between the primal objective value and the dual objective
248
+ bound, scaled by the primal objective value, is <= mip_rel_gap.
249
+
250
+ Returns
251
+ -------
252
+ res : OptimizeResult
253
+ An instance of :class:`scipy.optimize.OptimizeResult`. The object
254
+ is guaranteed to have the following attributes.
255
+
256
+ status : int
257
+ An integer representing the exit status of the algorithm.
258
+
259
+ ``0`` : Optimal solution found.
260
+
261
+ ``1`` : Iteration or time limit reached.
262
+
263
+ ``2`` : Problem is infeasible.
264
+
265
+ ``3`` : Problem is unbounded.
266
+
267
+ ``4`` : Other; see message for details.
268
+
269
+ success : bool
270
+ ``True`` when an optimal solution is found and ``False`` otherwise.
271
+
272
+ message : str
273
+ A string descriptor of the exit status of the algorithm.
274
+
275
+ The following attributes will also be present, but the values may be
276
+ ``None``, depending on the solution status.
277
+
278
+ x : ndarray
279
+ The values of the decision variables that minimize the
280
+ objective function while satisfying the constraints.
281
+ fun : float
282
+ The optimal value of the objective function ``c @ x``.
283
+ mip_node_count : int
284
+ The number of subproblems or "nodes" solved by the MILP solver.
285
+ mip_dual_bound : float
286
+ The MILP solver's final estimate of the lower bound on the optimal
287
+ solution.
288
+ mip_gap : float
289
+ The difference between the primal objective value and the dual
290
+ objective bound, scaled by the primal objective value.
291
+
292
+ Notes
293
+ -----
294
+ `milp` is a wrapper of the HiGHS linear optimization software [1]_. The
295
+ algorithm is deterministic, and it typically finds the global optimum of
296
+ moderately challenging mixed-integer linear programs (when it exists).
297
+
298
+ References
299
+ ----------
300
+ .. [1] Huangfu, Q., Galabova, I., Feldmeier, M., and Hall, J. A. J.
301
+ "HiGHS - high performance software for linear optimization."
302
+ https://highs.dev/
303
+ .. [2] Huangfu, Q. and Hall, J. A. J. "Parallelizing the dual revised
304
+ simplex method." Mathematical Programming Computation, 10 (1),
305
+ 119-142, 2018. DOI: 10.1007/s12532-017-0130-5
306
+
307
+ Examples
308
+ --------
309
+ Consider the problem at
310
+ https://en.wikipedia.org/wiki/Integer_programming#Example, which is
311
+ expressed as a maximization problem of two variables. Since `milp` requires
312
+ that the problem be expressed as a minimization problem, the objective
313
+ function coefficients on the decision variables are:
314
+
315
+ >>> import numpy as np
316
+ >>> c = -np.array([0, 1])
317
+
318
+ Note the negative sign: we maximize the original objective function
319
+ by minimizing the negative of the objective function.
320
+
321
+ We collect the coefficients of the constraints into arrays like:
322
+
323
+ >>> A = np.array([[-1, 1], [3, 2], [2, 3]])
324
+ >>> b_u = np.array([1, 12, 12])
325
+ >>> b_l = np.full_like(b_u, -np.inf, dtype=float)
326
+
327
+ Because there is no lower limit on these constraints, we have defined a
328
+ variable ``b_l`` full of values representing negative infinity. This may
329
+ be unfamiliar to users of `scipy.optimize.linprog`, which only accepts
330
+ "less than" (or "upper bound") inequality constraints of the form
331
+ ``A_ub @ x <= b_u``. By accepting both ``b_l`` and ``b_u`` of constraints
332
+ ``b_l <= A_ub @ x <= b_u``, `milp` makes it easy to specify "greater than"
333
+ inequality constraints, "less than" inequality constraints, and equality
334
+ constraints concisely.
335
+
336
+ These arrays are collected into a single `LinearConstraint` object like:
337
+
338
+ >>> from scipy.optimize import LinearConstraint
339
+ >>> constraints = LinearConstraint(A, b_l, b_u)
340
+
341
+ The non-negativity bounds on the decision variables are enforced by
342
+ default, so we do not need to provide an argument for `bounds`.
343
+
344
+ Finally, the problem states that both decision variables must be integers:
345
+
346
+ >>> integrality = np.ones_like(c)
347
+
348
+ We solve the problem like:
349
+
350
+ >>> from scipy.optimize import milp
351
+ >>> res = milp(c=c, constraints=constraints, integrality=integrality)
352
+ >>> res.x
353
+ [2.0, 2.0]
354
+
355
+ Note that had we solved the relaxed problem (without integrality
356
+ constraints):
357
+
358
+ >>> res = milp(c=c, constraints=constraints) # OR:
359
+ >>> # from scipy.optimize import linprog; res = linprog(c, A, b_u)
360
+ >>> res.x
361
+ [1.8, 2.8]
362
+
363
+ we would not have obtained the correct solution by rounding to the nearest
364
+ integers.
365
+
366
+ Other examples are given :ref:`in the tutorial <tutorial-optimize_milp>`.
367
+
368
+ """
369
+ args_iv = _milp_iv(c, integrality, bounds, constraints, options)
370
+ c, integrality, lb, ub, indptr, indices, data, b_l, b_u, options = args_iv
371
+
372
+ highs_res = _highs_wrapper(c, indptr, indices, data, b_l, b_u,
373
+ lb, ub, integrality, options)
374
+
375
+ res = {}
376
+
377
+ # Convert to scipy-style status and message
378
+ highs_status = highs_res.get('status', None)
379
+ highs_message = highs_res.get('message', None)
380
+ status, message = _highs_to_scipy_status_message(highs_status,
381
+ highs_message)
382
+ res['status'] = status
383
+ res['message'] = message
384
+ res['success'] = (status == 0)
385
+ x = highs_res.get('x', None)
386
+ res['x'] = np.array(x) if x is not None else None
387
+ res['fun'] = highs_res.get('fun', None)
388
+ res['mip_node_count'] = highs_res.get('mip_node_count', None)
389
+ res['mip_dual_bound'] = highs_res.get('mip_dual_bound', None)
390
+ res['mip_gap'] = highs_res.get('mip_gap', None)
391
+
392
+ return OptimizeResult(res)
vila/lib/python3.10/site-packages/scipy/optimize/_minpack_py.py ADDED
@@ -0,0 +1,1164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ from . import _minpack
3
+
4
+ import numpy as np
5
+ from numpy import (atleast_1d, triu, shape, transpose, zeros, prod, greater,
6
+ asarray, inf,
7
+ finfo, inexact, issubdtype, dtype)
8
+ from scipy import linalg
9
+ from scipy.linalg import svd, cholesky, solve_triangular, LinAlgError
10
+ from scipy._lib._util import _asarray_validated, _lazywhere, _contains_nan
11
+ from scipy._lib._util import getfullargspec_no_self as _getfullargspec
12
+ from ._optimize import OptimizeResult, _check_unknown_options, OptimizeWarning
13
+ from ._lsq import least_squares
14
+ # from ._lsq.common import make_strictly_feasible
15
+ from ._lsq.least_squares import prepare_bounds
16
+ from scipy.optimize._minimize import Bounds
17
+
18
+ __all__ = ['fsolve', 'leastsq', 'fixed_point', 'curve_fit']
19
+
20
+
21
+ def _check_func(checker, argname, thefunc, x0, args, numinputs,
22
+ output_shape=None):
23
+ res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
24
+ if (output_shape is not None) and (shape(res) != output_shape):
25
+ if (output_shape[0] != 1):
26
+ if len(output_shape) > 1:
27
+ if output_shape[1] == 1:
28
+ return shape(res)
29
+ msg = f"{checker}: there is a mismatch between the input and output " \
30
+ f"shape of the '{argname}' argument"
31
+ func_name = getattr(thefunc, '__name__', None)
32
+ if func_name:
33
+ msg += " '%s'." % func_name
34
+ else:
35
+ msg += "."
36
+ msg += f'Shape should be {output_shape} but it is {shape(res)}.'
37
+ raise TypeError(msg)
38
+ if issubdtype(res.dtype, inexact):
39
+ dt = res.dtype
40
+ else:
41
+ dt = dtype(float)
42
+ return shape(res), dt
43
+
44
+
45
+ def fsolve(func, x0, args=(), fprime=None, full_output=0,
46
+ col_deriv=0, xtol=1.49012e-8, maxfev=0, band=None,
47
+ epsfcn=None, factor=100, diag=None):
48
+ """
49
+ Find the roots of a function.
50
+
51
+ Return the roots of the (non-linear) equations defined by
52
+ ``func(x) = 0`` given a starting estimate.
53
+
54
+ Parameters
55
+ ----------
56
+ func : callable ``f(x, *args)``
57
+ A function that takes at least one (possibly vector) argument,
58
+ and returns a value of the same length.
59
+ x0 : ndarray
60
+ The starting estimate for the roots of ``func(x) = 0``.
61
+ args : tuple, optional
62
+ Any extra arguments to `func`.
63
+ fprime : callable ``f(x, *args)``, optional
64
+ A function to compute the Jacobian of `func` with derivatives
65
+ across the rows. By default, the Jacobian will be estimated.
66
+ full_output : bool, optional
67
+ If True, return optional outputs.
68
+ col_deriv : bool, optional
69
+ Specify whether the Jacobian function computes derivatives down
70
+ the columns (faster, because there is no transpose operation).
71
+ xtol : float, optional
72
+ The calculation will terminate if the relative error between two
73
+ consecutive iterates is at most `xtol`.
74
+ maxfev : int, optional
75
+ The maximum number of calls to the function. If zero, then
76
+ ``100*(N+1)`` is the maximum where N is the number of elements
77
+ in `x0`.
78
+ band : tuple, optional
79
+ If set to a two-sequence containing the number of sub- and
80
+ super-diagonals within the band of the Jacobi matrix, the
81
+ Jacobi matrix is considered banded (only for ``fprime=None``).
82
+ epsfcn : float, optional
83
+ A suitable step length for the forward-difference
84
+ approximation of the Jacobian (for ``fprime=None``). If
85
+ `epsfcn` is less than the machine precision, it is assumed
86
+ that the relative errors in the functions are of the order of
87
+ the machine precision.
88
+ factor : float, optional
89
+ A parameter determining the initial step bound
90
+ (``factor * || diag * x||``). Should be in the interval
91
+ ``(0.1, 100)``.
92
+ diag : sequence, optional
93
+ N positive entries that serve as a scale factors for the
94
+ variables.
95
+
96
+ Returns
97
+ -------
98
+ x : ndarray
99
+ The solution (or the result of the last iteration for
100
+ an unsuccessful call).
101
+ infodict : dict
102
+ A dictionary of optional outputs with the keys:
103
+
104
+ ``nfev``
105
+ number of function calls
106
+ ``njev``
107
+ number of Jacobian calls
108
+ ``fvec``
109
+ function evaluated at the output
110
+ ``fjac``
111
+ the orthogonal matrix, q, produced by the QR
112
+ factorization of the final approximate Jacobian
113
+ matrix, stored column wise
114
+ ``r``
115
+ upper triangular matrix produced by QR factorization
116
+ of the same matrix
117
+ ``qtf``
118
+ the vector ``(transpose(q) * fvec)``
119
+
120
+ ier : int
121
+ An integer flag. Set to 1 if a solution was found, otherwise refer
122
+ to `mesg` for more information.
123
+ mesg : str
124
+ If no solution is found, `mesg` details the cause of failure.
125
+
126
+ See Also
127
+ --------
128
+ root : Interface to root finding algorithms for multivariate
129
+ functions. See the ``method='hybr'`` in particular.
130
+
131
+ Notes
132
+ -----
133
+ ``fsolve`` is a wrapper around MINPACK's hybrd and hybrj algorithms.
134
+
135
+ Examples
136
+ --------
137
+ Find a solution to the system of equations:
138
+ ``x0*cos(x1) = 4, x1*x0 - x1 = 5``.
139
+
140
+ >>> import numpy as np
141
+ >>> from scipy.optimize import fsolve
142
+ >>> def func(x):
143
+ ... return [x[0] * np.cos(x[1]) - 4,
144
+ ... x[1] * x[0] - x[1] - 5]
145
+ >>> root = fsolve(func, [1, 1])
146
+ >>> root
147
+ array([6.50409711, 0.90841421])
148
+ >>> np.isclose(func(root), [0.0, 0.0]) # func(root) should be almost 0.0.
149
+ array([ True, True])
150
+
151
+ """
152
+ def _wrapped_func(*fargs):
153
+ """
154
+ Wrapped `func` to track the number of times
155
+ the function has been called.
156
+ """
157
+ _wrapped_func.nfev += 1
158
+ return func(*fargs)
159
+
160
+ _wrapped_func.nfev = 0
161
+
162
+ options = {'col_deriv': col_deriv,
163
+ 'xtol': xtol,
164
+ 'maxfev': maxfev,
165
+ 'band': band,
166
+ 'eps': epsfcn,
167
+ 'factor': factor,
168
+ 'diag': diag}
169
+
170
+ res = _root_hybr(_wrapped_func, x0, args, jac=fprime, **options)
171
+ res.nfev = _wrapped_func.nfev
172
+
173
+ if full_output:
174
+ x = res['x']
175
+ info = {k: res.get(k)
176
+ for k in ('nfev', 'njev', 'fjac', 'r', 'qtf') if k in res}
177
+ info['fvec'] = res['fun']
178
+ return x, info, res['status'], res['message']
179
+ else:
180
+ status = res['status']
181
+ msg = res['message']
182
+ if status == 0:
183
+ raise TypeError(msg)
184
+ elif status == 1:
185
+ pass
186
+ elif status in [2, 3, 4, 5]:
187
+ warnings.warn(msg, RuntimeWarning, stacklevel=2)
188
+ else:
189
+ raise TypeError(msg)
190
+ return res['x']
191
+
192
+
193
+ def _root_hybr(func, x0, args=(), jac=None,
194
+ col_deriv=0, xtol=1.49012e-08, maxfev=0, band=None, eps=None,
195
+ factor=100, diag=None, **unknown_options):
196
+ """
197
+ Find the roots of a multivariate function using MINPACK's hybrd and
198
+ hybrj routines (modified Powell method).
199
+
200
+ Options
201
+ -------
202
+ col_deriv : bool
203
+ Specify whether the Jacobian function computes derivatives down
204
+ the columns (faster, because there is no transpose operation).
205
+ xtol : float
206
+ The calculation will terminate if the relative error between two
207
+ consecutive iterates is at most `xtol`.
208
+ maxfev : int
209
+ The maximum number of calls to the function. If zero, then
210
+ ``100*(N+1)`` is the maximum where N is the number of elements
211
+ in `x0`.
212
+ band : tuple
213
+ If set to a two-sequence containing the number of sub- and
214
+ super-diagonals within the band of the Jacobi matrix, the
215
+ Jacobi matrix is considered banded (only for ``fprime=None``).
216
+ eps : float
217
+ A suitable step length for the forward-difference
218
+ approximation of the Jacobian (for ``fprime=None``). If
219
+ `eps` is less than the machine precision, it is assumed
220
+ that the relative errors in the functions are of the order of
221
+ the machine precision.
222
+ factor : float
223
+ A parameter determining the initial step bound
224
+ (``factor * || diag * x||``). Should be in the interval
225
+ ``(0.1, 100)``.
226
+ diag : sequence
227
+ N positive entries that serve as a scale factors for the
228
+ variables.
229
+
230
+ """
231
+ _check_unknown_options(unknown_options)
232
+ epsfcn = eps
233
+
234
+ x0 = asarray(x0).flatten()
235
+ n = len(x0)
236
+ if not isinstance(args, tuple):
237
+ args = (args,)
238
+ shape, dtype = _check_func('fsolve', 'func', func, x0, args, n, (n,))
239
+ if epsfcn is None:
240
+ epsfcn = finfo(dtype).eps
241
+ Dfun = jac
242
+ if Dfun is None:
243
+ if band is None:
244
+ ml, mu = -10, -10
245
+ else:
246
+ ml, mu = band[:2]
247
+ if maxfev == 0:
248
+ maxfev = 200 * (n + 1)
249
+ retval = _minpack._hybrd(func, x0, args, 1, xtol, maxfev,
250
+ ml, mu, epsfcn, factor, diag)
251
+ else:
252
+ _check_func('fsolve', 'fprime', Dfun, x0, args, n, (n, n))
253
+ if (maxfev == 0):
254
+ maxfev = 100 * (n + 1)
255
+ retval = _minpack._hybrj(func, Dfun, x0, args, 1,
256
+ col_deriv, xtol, maxfev, factor, diag)
257
+
258
+ x, status = retval[0], retval[-1]
259
+
260
+ errors = {0: "Improper input parameters were entered.",
261
+ 1: "The solution converged.",
262
+ 2: "The number of calls to function has "
263
+ "reached maxfev = %d." % maxfev,
264
+ 3: "xtol=%f is too small, no further improvement "
265
+ "in the approximate\n solution "
266
+ "is possible." % xtol,
267
+ 4: "The iteration is not making good progress, as measured "
268
+ "by the \n improvement from the last five "
269
+ "Jacobian evaluations.",
270
+ 5: "The iteration is not making good progress, "
271
+ "as measured by the \n improvement from the last "
272
+ "ten iterations.",
273
+ 'unknown': "An error occurred."}
274
+
275
+ info = retval[1]
276
+ info['fun'] = info.pop('fvec')
277
+ sol = OptimizeResult(x=x, success=(status == 1), status=status,
278
+ method="hybr")
279
+ sol.update(info)
280
+ try:
281
+ sol['message'] = errors[status]
282
+ except KeyError:
283
+ sol['message'] = errors['unknown']
284
+
285
+ return sol
286
+
287
+
288
+ LEASTSQ_SUCCESS = [1, 2, 3, 4]
289
+ LEASTSQ_FAILURE = [5, 6, 7, 8]
290
+
291
+
292
+ def leastsq(func, x0, args=(), Dfun=None, full_output=False,
293
+ col_deriv=False, ftol=1.49012e-8, xtol=1.49012e-8,
294
+ gtol=0.0, maxfev=0, epsfcn=None, factor=100, diag=None):
295
+ """
296
+ Minimize the sum of squares of a set of equations.
297
+
298
+ ::
299
+
300
+ x = arg min(sum(func(y)**2,axis=0))
301
+ y
302
+
303
+ Parameters
304
+ ----------
305
+ func : callable
306
+ Should take at least one (possibly length ``N`` vector) argument and
307
+ returns ``M`` floating point numbers. It must not return NaNs or
308
+ fitting might fail. ``M`` must be greater than or equal to ``N``.
309
+ x0 : ndarray
310
+ The starting estimate for the minimization.
311
+ args : tuple, optional
312
+ Any extra arguments to func are placed in this tuple.
313
+ Dfun : callable, optional
314
+ A function or method to compute the Jacobian of func with derivatives
315
+ across the rows. If this is None, the Jacobian will be estimated.
316
+ full_output : bool, optional
317
+ If ``True``, return all optional outputs (not just `x` and `ier`).
318
+ col_deriv : bool, optional
319
+ If ``True``, specify that the Jacobian function computes derivatives
320
+ down the columns (faster, because there is no transpose operation).
321
+ ftol : float, optional
322
+ Relative error desired in the sum of squares.
323
+ xtol : float, optional
324
+ Relative error desired in the approximate solution.
325
+ gtol : float, optional
326
+ Orthogonality desired between the function vector and the columns of
327
+ the Jacobian.
328
+ maxfev : int, optional
329
+ The maximum number of calls to the function. If `Dfun` is provided,
330
+ then the default `maxfev` is 100*(N+1) where N is the number of elements
331
+ in x0, otherwise the default `maxfev` is 200*(N+1).
332
+ epsfcn : float, optional
333
+ A variable used in determining a suitable step length for the forward-
334
+ difference approximation of the Jacobian (for Dfun=None).
335
+ Normally the actual step length will be sqrt(epsfcn)*x
336
+ If epsfcn is less than the machine precision, it is assumed that the
337
+ relative errors are of the order of the machine precision.
338
+ factor : float, optional
339
+ A parameter determining the initial step bound
340
+ (``factor * || diag * x||``). Should be in interval ``(0.1, 100)``.
341
+ diag : sequence, optional
342
+ N positive entries that serve as a scale factors for the variables.
343
+
344
+ Returns
345
+ -------
346
+ x : ndarray
347
+ The solution (or the result of the last iteration for an unsuccessful
348
+ call).
349
+ cov_x : ndarray
350
+ The inverse of the Hessian. `fjac` and `ipvt` are used to construct an
351
+ estimate of the Hessian. A value of None indicates a singular matrix,
352
+ which means the curvature in parameters `x` is numerically flat. To
353
+ obtain the covariance matrix of the parameters `x`, `cov_x` must be
354
+ multiplied by the variance of the residuals -- see curve_fit. Only
355
+ returned if `full_output` is ``True``.
356
+ infodict : dict
357
+ a dictionary of optional outputs with the keys:
358
+
359
+ ``nfev``
360
+ The number of function calls
361
+ ``fvec``
362
+ The function evaluated at the output
363
+ ``fjac``
364
+ A permutation of the R matrix of a QR
365
+ factorization of the final approximate
366
+ Jacobian matrix, stored column wise.
367
+ Together with ipvt, the covariance of the
368
+ estimate can be approximated.
369
+ ``ipvt``
370
+ An integer array of length N which defines
371
+ a permutation matrix, p, such that
372
+ fjac*p = q*r, where r is upper triangular
373
+ with diagonal elements of nonincreasing
374
+ magnitude. Column j of p is column ipvt(j)
375
+ of the identity matrix.
376
+ ``qtf``
377
+ The vector (transpose(q) * fvec).
378
+
379
+ Only returned if `full_output` is ``True``.
380
+ mesg : str
381
+ A string message giving information about the cause of failure.
382
+ Only returned if `full_output` is ``True``.
383
+ ier : int
384
+ An integer flag. If it is equal to 1, 2, 3 or 4, the solution was
385
+ found. Otherwise, the solution was not found. In either case, the
386
+ optional output variable 'mesg' gives more information.
387
+
388
+ See Also
389
+ --------
390
+ least_squares : Newer interface to solve nonlinear least-squares problems
391
+ with bounds on the variables. See ``method='lm'`` in particular.
392
+
393
+ Notes
394
+ -----
395
+ "leastsq" is a wrapper around MINPACK's lmdif and lmder algorithms.
396
+
397
+ cov_x is a Jacobian approximation to the Hessian of the least squares
398
+ objective function.
399
+ This approximation assumes that the objective function is based on the
400
+ difference between some observed target data (ydata) and a (non-linear)
401
+ function of the parameters `f(xdata, params)` ::
402
+
403
+ func(params) = ydata - f(xdata, params)
404
+
405
+ so that the objective function is ::
406
+
407
+ min sum((ydata - f(xdata, params))**2, axis=0)
408
+ params
409
+
410
+ The solution, `x`, is always a 1-D array, regardless of the shape of `x0`,
411
+ or whether `x0` is a scalar.
412
+
413
+ Examples
414
+ --------
415
+ >>> from scipy.optimize import leastsq
416
+ >>> def func(x):
417
+ ... return 2*(x-3)**2+1
418
+ >>> leastsq(func, 0)
419
+ (array([2.99999999]), 1)
420
+
421
+ """
422
+ x0 = asarray(x0).flatten()
423
+ n = len(x0)
424
+ if not isinstance(args, tuple):
425
+ args = (args,)
426
+ shape, dtype = _check_func('leastsq', 'func', func, x0, args, n)
427
+ m = shape[0]
428
+
429
+ if n > m:
430
+ raise TypeError(f"Improper input: func input vector length N={n} must"
431
+ f" not exceed func output vector length M={m}")
432
+
433
+ if epsfcn is None:
434
+ epsfcn = finfo(dtype).eps
435
+
436
+ if Dfun is None:
437
+ if maxfev == 0:
438
+ maxfev = 200*(n + 1)
439
+ retval = _minpack._lmdif(func, x0, args, full_output, ftol, xtol,
440
+ gtol, maxfev, epsfcn, factor, diag)
441
+ else:
442
+ if col_deriv:
443
+ _check_func('leastsq', 'Dfun', Dfun, x0, args, n, (n, m))
444
+ else:
445
+ _check_func('leastsq', 'Dfun', Dfun, x0, args, n, (m, n))
446
+ if maxfev == 0:
447
+ maxfev = 100 * (n + 1)
448
+ retval = _minpack._lmder(func, Dfun, x0, args, full_output,
449
+ col_deriv, ftol, xtol, gtol, maxfev,
450
+ factor, diag)
451
+
452
+ errors = {0: ["Improper input parameters.", TypeError],
453
+ 1: ["Both actual and predicted relative reductions "
454
+ "in the sum of squares\n are at most %f" % ftol, None],
455
+ 2: ["The relative error between two consecutive "
456
+ "iterates is at most %f" % xtol, None],
457
+ 3: ["Both actual and predicted relative reductions in "
458
+ f"the sum of squares\n are at most {ftol:f} and the "
459
+ "relative error between two consecutive "
460
+ f"iterates is at \n most {xtol:f}", None],
461
+ 4: ["The cosine of the angle between func(x) and any "
462
+ "column of the\n Jacobian is at most %f in "
463
+ "absolute value" % gtol, None],
464
+ 5: ["Number of calls to function has reached "
465
+ "maxfev = %d." % maxfev, ValueError],
466
+ 6: ["ftol=%f is too small, no further reduction "
467
+ "in the sum of squares\n is possible." % ftol,
468
+ ValueError],
469
+ 7: ["xtol=%f is too small, no further improvement in "
470
+ "the approximate\n solution is possible." % xtol,
471
+ ValueError],
472
+ 8: ["gtol=%f is too small, func(x) is orthogonal to the "
473
+ "columns of\n the Jacobian to machine "
474
+ "precision." % gtol, ValueError]}
475
+
476
+ # The FORTRAN return value (possible return values are >= 0 and <= 8)
477
+ info = retval[-1]
478
+
479
+ if full_output:
480
+ cov_x = None
481
+ if info in LEASTSQ_SUCCESS:
482
+ # This was
483
+ # perm = take(eye(n), retval[1]['ipvt'] - 1, 0)
484
+ # r = triu(transpose(retval[1]['fjac'])[:n, :])
485
+ # R = dot(r, perm)
486
+ # cov_x = inv(dot(transpose(R), R))
487
+ # but the explicit dot product was not necessary and sometimes
488
+ # the result was not symmetric positive definite. See gh-4555.
489
+ perm = retval[1]['ipvt'] - 1
490
+ n = len(perm)
491
+ r = triu(transpose(retval[1]['fjac'])[:n, :])
492
+ inv_triu = linalg.get_lapack_funcs('trtri', (r,))
493
+ try:
494
+ # inverse of permuted matrix is a permutation of matrix inverse
495
+ invR, trtri_info = inv_triu(r) # default: upper, non-unit diag
496
+ if trtri_info != 0: # explicit comparison for readability
497
+ raise LinAlgError(f'trtri returned info {trtri_info}')
498
+ invR[perm] = invR.copy()
499
+ cov_x = invR @ invR.T
500
+ except (LinAlgError, ValueError):
501
+ pass
502
+ return (retval[0], cov_x) + retval[1:-1] + (errors[info][0], info)
503
+ else:
504
+ if info in LEASTSQ_FAILURE:
505
+ warnings.warn(errors[info][0], RuntimeWarning, stacklevel=2)
506
+ elif info == 0:
507
+ raise errors[info][1](errors[info][0])
508
+ return retval[0], info
509
+
510
+
511
+ def _lightweight_memoizer(f):
512
+ # very shallow memoization to address gh-13670: only remember the first set
513
+ # of parameters and corresponding function value, and only attempt to use
514
+ # them twice (the number of times the function is evaluated at x0).
515
+ def _memoized_func(params):
516
+ if _memoized_func.skip_lookup:
517
+ return f(params)
518
+
519
+ if np.all(_memoized_func.last_params == params):
520
+ return _memoized_func.last_val
521
+ elif _memoized_func.last_params is not None:
522
+ _memoized_func.skip_lookup = True
523
+
524
+ val = f(params)
525
+
526
+ if _memoized_func.last_params is None:
527
+ _memoized_func.last_params = np.copy(params)
528
+ _memoized_func.last_val = val
529
+
530
+ return val
531
+
532
+ _memoized_func.last_params = None
533
+ _memoized_func.last_val = None
534
+ _memoized_func.skip_lookup = False
535
+ return _memoized_func
536
+
537
+
538
+ def _wrap_func(func, xdata, ydata, transform):
539
+ if transform is None:
540
+ def func_wrapped(params):
541
+ return func(xdata, *params) - ydata
542
+ elif transform.size == 1 or transform.ndim == 1:
543
+ def func_wrapped(params):
544
+ return transform * (func(xdata, *params) - ydata)
545
+ else:
546
+ # Chisq = (y - yd)^T C^{-1} (y-yd)
547
+ # transform = L such that C = L L^T
548
+ # C^{-1} = L^{-T} L^{-1}
549
+ # Chisq = (y - yd)^T L^{-T} L^{-1} (y-yd)
550
+ # Define (y-yd)' = L^{-1} (y-yd)
551
+ # by solving
552
+ # L (y-yd)' = (y-yd)
553
+ # and minimize (y-yd)'^T (y-yd)'
554
+ def func_wrapped(params):
555
+ return solve_triangular(transform, func(xdata, *params) - ydata, lower=True)
556
+ return func_wrapped
557
+
558
+
559
+ def _wrap_jac(jac, xdata, transform):
560
+ if transform is None:
561
+ def jac_wrapped(params):
562
+ return jac(xdata, *params)
563
+ elif transform.ndim == 1:
564
+ def jac_wrapped(params):
565
+ return transform[:, np.newaxis] * np.asarray(jac(xdata, *params))
566
+ else:
567
+ def jac_wrapped(params):
568
+ return solve_triangular(transform,
569
+ np.asarray(jac(xdata, *params)),
570
+ lower=True)
571
+ return jac_wrapped
572
+
573
+
574
+ def _initialize_feasible(lb, ub):
575
+ p0 = np.ones_like(lb)
576
+ lb_finite = np.isfinite(lb)
577
+ ub_finite = np.isfinite(ub)
578
+
579
+ mask = lb_finite & ub_finite
580
+ p0[mask] = 0.5 * (lb[mask] + ub[mask])
581
+
582
+ mask = lb_finite & ~ub_finite
583
+ p0[mask] = lb[mask] + 1
584
+
585
+ mask = ~lb_finite & ub_finite
586
+ p0[mask] = ub[mask] - 1
587
+
588
+ return p0
589
+
590
+
591
+ def curve_fit(f, xdata, ydata, p0=None, sigma=None, absolute_sigma=False,
592
+ check_finite=None, bounds=(-np.inf, np.inf), method=None,
593
+ jac=None, *, full_output=False, nan_policy=None,
594
+ **kwargs):
595
+ """
596
+ Use non-linear least squares to fit a function, f, to data.
597
+
598
+ Assumes ``ydata = f(xdata, *params) + eps``.
599
+
600
+ Parameters
601
+ ----------
602
+ f : callable
603
+ The model function, f(x, ...). It must take the independent
604
+ variable as the first argument and the parameters to fit as
605
+ separate remaining arguments.
606
+ xdata : array_like
607
+ The independent variable where the data is measured.
608
+ Should usually be an M-length sequence or an (k,M)-shaped array for
609
+ functions with k predictors, and each element should be float
610
+ convertible if it is an array like object.
611
+ ydata : array_like
612
+ The dependent data, a length M array - nominally ``f(xdata, ...)``.
613
+ p0 : array_like, optional
614
+ Initial guess for the parameters (length N). If None, then the
615
+ initial values will all be 1 (if the number of parameters for the
616
+ function can be determined using introspection, otherwise a
617
+ ValueError is raised).
618
+ sigma : None or scalar or M-length sequence or MxM array, optional
619
+ Determines the uncertainty in `ydata`. If we define residuals as
620
+ ``r = ydata - f(xdata, *popt)``, then the interpretation of `sigma`
621
+ depends on its number of dimensions:
622
+
623
+ - A scalar or 1-D `sigma` should contain values of standard deviations of
624
+ errors in `ydata`. In this case, the optimized function is
625
+ ``chisq = sum((r / sigma) ** 2)``.
626
+
627
+ - A 2-D `sigma` should contain the covariance matrix of
628
+ errors in `ydata`. In this case, the optimized function is
629
+ ``chisq = r.T @ inv(sigma) @ r``.
630
+
631
+ .. versionadded:: 0.19
632
+
633
+ None (default) is equivalent of 1-D `sigma` filled with ones.
634
+ absolute_sigma : bool, optional
635
+ If True, `sigma` is used in an absolute sense and the estimated parameter
636
+ covariance `pcov` reflects these absolute values.
637
+
638
+ If False (default), only the relative magnitudes of the `sigma` values matter.
639
+ The returned parameter covariance matrix `pcov` is based on scaling
640
+ `sigma` by a constant factor. This constant is set by demanding that the
641
+ reduced `chisq` for the optimal parameters `popt` when using the
642
+ *scaled* `sigma` equals unity. In other words, `sigma` is scaled to
643
+ match the sample variance of the residuals after the fit. Default is False.
644
+ Mathematically,
645
+ ``pcov(absolute_sigma=False) = pcov(absolute_sigma=True) * chisq(popt)/(M-N)``
646
+ check_finite : bool, optional
647
+ If True, check that the input arrays do not contain nans of infs,
648
+ and raise a ValueError if they do. Setting this parameter to
649
+ False may silently produce nonsensical results if the input arrays
650
+ do contain nans. Default is True if `nan_policy` is not specified
651
+ explicitly and False otherwise.
652
+ bounds : 2-tuple of array_like or `Bounds`, optional
653
+ Lower and upper bounds on parameters. Defaults to no bounds.
654
+ There are two ways to specify the bounds:
655
+
656
+ - Instance of `Bounds` class.
657
+
658
+ - 2-tuple of array_like: Each element of the tuple must be either
659
+ an array with the length equal to the number of parameters, or a
660
+ scalar (in which case the bound is taken to be the same for all
661
+ parameters). Use ``np.inf`` with an appropriate sign to disable
662
+ bounds on all or some parameters.
663
+
664
+ method : {'lm', 'trf', 'dogbox'}, optional
665
+ Method to use for optimization. See `least_squares` for more details.
666
+ Default is 'lm' for unconstrained problems and 'trf' if `bounds` are
667
+ provided. The method 'lm' won't work when the number of observations
668
+ is less than the number of variables, use 'trf' or 'dogbox' in this
669
+ case.
670
+
671
+ .. versionadded:: 0.17
672
+ jac : callable, string or None, optional
673
+ Function with signature ``jac(x, ...)`` which computes the Jacobian
674
+ matrix of the model function with respect to parameters as a dense
675
+ array_like structure. It will be scaled according to provided `sigma`.
676
+ If None (default), the Jacobian will be estimated numerically.
677
+ String keywords for 'trf' and 'dogbox' methods can be used to select
678
+ a finite difference scheme, see `least_squares`.
679
+
680
+ .. versionadded:: 0.18
681
+ full_output : boolean, optional
682
+ If True, this function returns additioal information: `infodict`,
683
+ `mesg`, and `ier`.
684
+
685
+ .. versionadded:: 1.9
686
+ nan_policy : {'raise', 'omit', None}, optional
687
+ Defines how to handle when input contains nan.
688
+ The following options are available (default is None):
689
+
690
+ * 'raise': throws an error
691
+ * 'omit': performs the calculations ignoring nan values
692
+ * None: no special handling of NaNs is performed
693
+ (except what is done by check_finite); the behavior when NaNs
694
+ are present is implementation-dependent and may change.
695
+
696
+ Note that if this value is specified explicitly (not None),
697
+ `check_finite` will be set as False.
698
+
699
+ .. versionadded:: 1.11
700
+ **kwargs
701
+ Keyword arguments passed to `leastsq` for ``method='lm'`` or
702
+ `least_squares` otherwise.
703
+
704
+ Returns
705
+ -------
706
+ popt : array
707
+ Optimal values for the parameters so that the sum of the squared
708
+ residuals of ``f(xdata, *popt) - ydata`` is minimized.
709
+ pcov : 2-D array
710
+ The estimated approximate covariance of popt. The diagonals provide
711
+ the variance of the parameter estimate. To compute one standard
712
+ deviation errors on the parameters, use
713
+ ``perr = np.sqrt(np.diag(pcov))``. Note that the relationship between
714
+ `cov` and parameter error estimates is derived based on a linear
715
+ approximation to the model function around the optimum [1].
716
+ When this approximation becomes inaccurate, `cov` may not provide an
717
+ accurate measure of uncertainty.
718
+
719
+ How the `sigma` parameter affects the estimated covariance
720
+ depends on `absolute_sigma` argument, as described above.
721
+
722
+ If the Jacobian matrix at the solution doesn't have a full rank, then
723
+ 'lm' method returns a matrix filled with ``np.inf``, on the other hand
724
+ 'trf' and 'dogbox' methods use Moore-Penrose pseudoinverse to compute
725
+ the covariance matrix. Covariance matrices with large condition numbers
726
+ (e.g. computed with `numpy.linalg.cond`) may indicate that results are
727
+ unreliable.
728
+ infodict : dict (returned only if `full_output` is True)
729
+ a dictionary of optional outputs with the keys:
730
+
731
+ ``nfev``
732
+ The number of function calls. Methods 'trf' and 'dogbox' do not
733
+ count function calls for numerical Jacobian approximation,
734
+ as opposed to 'lm' method.
735
+ ``fvec``
736
+ The residual values evaluated at the solution, for a 1-D `sigma`
737
+ this is ``(f(x, *popt) - ydata)/sigma``.
738
+ ``fjac``
739
+ A permutation of the R matrix of a QR
740
+ factorization of the final approximate
741
+ Jacobian matrix, stored column wise.
742
+ Together with ipvt, the covariance of the
743
+ estimate can be approximated.
744
+ Method 'lm' only provides this information.
745
+ ``ipvt``
746
+ An integer array of length N which defines
747
+ a permutation matrix, p, such that
748
+ fjac*p = q*r, where r is upper triangular
749
+ with diagonal elements of nonincreasing
750
+ magnitude. Column j of p is column ipvt(j)
751
+ of the identity matrix.
752
+ Method 'lm' only provides this information.
753
+ ``qtf``
754
+ The vector (transpose(q) * fvec).
755
+ Method 'lm' only provides this information.
756
+
757
+ .. versionadded:: 1.9
758
+ mesg : str (returned only if `full_output` is True)
759
+ A string message giving information about the solution.
760
+
761
+ .. versionadded:: 1.9
762
+ ier : int (returned only if `full_output` is True)
763
+ An integer flag. If it is equal to 1, 2, 3 or 4, the solution was
764
+ found. Otherwise, the solution was not found. In either case, the
765
+ optional output variable `mesg` gives more information.
766
+
767
+ .. versionadded:: 1.9
768
+
769
+ Raises
770
+ ------
771
+ ValueError
772
+ if either `ydata` or `xdata` contain NaNs, or if incompatible options
773
+ are used.
774
+
775
+ RuntimeError
776
+ if the least-squares minimization fails.
777
+
778
+ OptimizeWarning
779
+ if covariance of the parameters can not be estimated.
780
+
781
+ See Also
782
+ --------
783
+ least_squares : Minimize the sum of squares of nonlinear functions.
784
+ scipy.stats.linregress : Calculate a linear least squares regression for
785
+ two sets of measurements.
786
+
787
+ Notes
788
+ -----
789
+ Users should ensure that inputs `xdata`, `ydata`, and the output of `f`
790
+ are ``float64``, or else the optimization may return incorrect results.
791
+
792
+ With ``method='lm'``, the algorithm uses the Levenberg-Marquardt algorithm
793
+ through `leastsq`. Note that this algorithm can only deal with
794
+ unconstrained problems.
795
+
796
+ Box constraints can be handled by methods 'trf' and 'dogbox'. Refer to
797
+ the docstring of `least_squares` for more information.
798
+
799
+ Parameters to be fitted must have similar scale. Differences of multiple
800
+ orders of magnitude can lead to incorrect results. For the 'trf' and
801
+ 'dogbox' methods, the `x_scale` keyword argument can be used to scale
802
+ the parameters.
803
+
804
+ References
805
+ ----------
806
+ [1] K. Vugrin et al. Confidence region estimation techniques for nonlinear
807
+ regression in groundwater flow: Three case studies. Water Resources
808
+ Research, Vol. 43, W03423, :doi:`10.1029/2005WR004804`
809
+
810
+ Examples
811
+ --------
812
+ >>> import numpy as np
813
+ >>> import matplotlib.pyplot as plt
814
+ >>> from scipy.optimize import curve_fit
815
+
816
+ >>> def func(x, a, b, c):
817
+ ... return a * np.exp(-b * x) + c
818
+
819
+ Define the data to be fit with some noise:
820
+
821
+ >>> xdata = np.linspace(0, 4, 50)
822
+ >>> y = func(xdata, 2.5, 1.3, 0.5)
823
+ >>> rng = np.random.default_rng()
824
+ >>> y_noise = 0.2 * rng.normal(size=xdata.size)
825
+ >>> ydata = y + y_noise
826
+ >>> plt.plot(xdata, ydata, 'b-', label='data')
827
+
828
+ Fit for the parameters a, b, c of the function `func`:
829
+
830
+ >>> popt, pcov = curve_fit(func, xdata, ydata)
831
+ >>> popt
832
+ array([2.56274217, 1.37268521, 0.47427475])
833
+ >>> plt.plot(xdata, func(xdata, *popt), 'r-',
834
+ ... label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))
835
+
836
+ Constrain the optimization to the region of ``0 <= a <= 3``,
837
+ ``0 <= b <= 1`` and ``0 <= c <= 0.5``:
838
+
839
+ >>> popt, pcov = curve_fit(func, xdata, ydata, bounds=(0, [3., 1., 0.5]))
840
+ >>> popt
841
+ array([2.43736712, 1. , 0.34463856])
842
+ >>> plt.plot(xdata, func(xdata, *popt), 'g--',
843
+ ... label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))
844
+
845
+ >>> plt.xlabel('x')
846
+ >>> plt.ylabel('y')
847
+ >>> plt.legend()
848
+ >>> plt.show()
849
+
850
+ For reliable results, the model `func` should not be overparametrized;
851
+ redundant parameters can cause unreliable covariance matrices and, in some
852
+ cases, poorer quality fits. As a quick check of whether the model may be
853
+ overparameterized, calculate the condition number of the covariance matrix:
854
+
855
+ >>> np.linalg.cond(pcov)
856
+ 34.571092161547405 # may vary
857
+
858
+ The value is small, so it does not raise much concern. If, however, we were
859
+ to add a fourth parameter ``d`` to `func` with the same effect as ``a``:
860
+
861
+ >>> def func2(x, a, b, c, d):
862
+ ... return a * d * np.exp(-b * x) + c # a and d are redundant
863
+ >>> popt, pcov = curve_fit(func2, xdata, ydata)
864
+ >>> np.linalg.cond(pcov)
865
+ 1.13250718925596e+32 # may vary
866
+
867
+ Such a large value is cause for concern. The diagonal elements of the
868
+ covariance matrix, which is related to uncertainty of the fit, gives more
869
+ information:
870
+
871
+ >>> np.diag(pcov)
872
+ array([1.48814742e+29, 3.78596560e-02, 5.39253738e-03, 2.76417220e+28]) # may vary
873
+
874
+ Note that the first and last terms are much larger than the other elements,
875
+ suggesting that the optimal values of these parameters are ambiguous and
876
+ that only one of these parameters is needed in the model.
877
+
878
+ If the optimal parameters of `f` differ by multiple orders of magnitude, the
879
+ resulting fit can be inaccurate. Sometimes, `curve_fit` can fail to find any
880
+ results:
881
+
882
+ >>> ydata = func(xdata, 500000, 0.01, 15)
883
+ >>> try:
884
+ ... popt, pcov = curve_fit(func, xdata, ydata, method = 'trf')
885
+ ... except RuntimeError as e:
886
+ ... print(e)
887
+ Optimal parameters not found: The maximum number of function evaluations is
888
+ exceeded.
889
+
890
+ If parameter scale is roughly known beforehand, it can be defined in
891
+ `x_scale` argument:
892
+
893
+ >>> popt, pcov = curve_fit(func, xdata, ydata, method = 'trf',
894
+ ... x_scale = [1000, 1, 1])
895
+ >>> popt
896
+ array([5.00000000e+05, 1.00000000e-02, 1.49999999e+01])
897
+ """
898
+ if p0 is None:
899
+ # determine number of parameters by inspecting the function
900
+ sig = _getfullargspec(f)
901
+ args = sig.args
902
+ if len(args) < 2:
903
+ raise ValueError("Unable to determine number of fit parameters.")
904
+ n = len(args) - 1
905
+ else:
906
+ p0 = np.atleast_1d(p0)
907
+ n = p0.size
908
+
909
+ if isinstance(bounds, Bounds):
910
+ lb, ub = bounds.lb, bounds.ub
911
+ else:
912
+ lb, ub = prepare_bounds(bounds, n)
913
+ if p0 is None:
914
+ p0 = _initialize_feasible(lb, ub)
915
+
916
+ bounded_problem = np.any((lb > -np.inf) | (ub < np.inf))
917
+ if method is None:
918
+ if bounded_problem:
919
+ method = 'trf'
920
+ else:
921
+ method = 'lm'
922
+
923
+ if method == 'lm' and bounded_problem:
924
+ raise ValueError("Method 'lm' only works for unconstrained problems. "
925
+ "Use 'trf' or 'dogbox' instead.")
926
+
927
+ if check_finite is None:
928
+ check_finite = True if nan_policy is None else False
929
+
930
+ # optimization may produce garbage for float32 inputs, cast them to float64
931
+ if check_finite:
932
+ ydata = np.asarray_chkfinite(ydata, float)
933
+ else:
934
+ ydata = np.asarray(ydata, float)
935
+
936
+ if isinstance(xdata, (list, tuple, np.ndarray)):
937
+ # `xdata` is passed straight to the user-defined `f`, so allow
938
+ # non-array_like `xdata`.
939
+ if check_finite:
940
+ xdata = np.asarray_chkfinite(xdata, float)
941
+ else:
942
+ xdata = np.asarray(xdata, float)
943
+
944
+ if ydata.size == 0:
945
+ raise ValueError("`ydata` must not be empty!")
946
+
947
+ # nan handling is needed only if check_finite is False because if True,
948
+ # the x-y data are already checked, and they don't contain nans.
949
+ if not check_finite and nan_policy is not None:
950
+ if nan_policy == "propagate":
951
+ raise ValueError("`nan_policy='propagate'` is not supported "
952
+ "by this function.")
953
+
954
+ policies = [None, 'raise', 'omit']
955
+ x_contains_nan, nan_policy = _contains_nan(xdata, nan_policy,
956
+ policies=policies)
957
+ y_contains_nan, nan_policy = _contains_nan(ydata, nan_policy,
958
+ policies=policies)
959
+
960
+ if (x_contains_nan or y_contains_nan) and nan_policy == 'omit':
961
+ # ignore NaNs for N dimensional arrays
962
+ has_nan = np.isnan(xdata)
963
+ has_nan = has_nan.any(axis=tuple(range(has_nan.ndim-1)))
964
+ has_nan |= np.isnan(ydata)
965
+
966
+ xdata = xdata[..., ~has_nan]
967
+ ydata = ydata[~has_nan]
968
+
969
+ # Determine type of sigma
970
+ if sigma is not None:
971
+ sigma = np.asarray(sigma)
972
+
973
+ # if 1-D or a scalar, sigma are errors, define transform = 1/sigma
974
+ if sigma.size == 1 or sigma.shape == (ydata.size, ):
975
+ transform = 1.0 / sigma
976
+ # if 2-D, sigma is the covariance matrix,
977
+ # define transform = L such that L L^T = C
978
+ elif sigma.shape == (ydata.size, ydata.size):
979
+ try:
980
+ # scipy.linalg.cholesky requires lower=True to return L L^T = A
981
+ transform = cholesky(sigma, lower=True)
982
+ except LinAlgError as e:
983
+ raise ValueError("`sigma` must be positive definite.") from e
984
+ else:
985
+ raise ValueError("`sigma` has incorrect shape.")
986
+ else:
987
+ transform = None
988
+
989
+ func = _lightweight_memoizer(_wrap_func(f, xdata, ydata, transform))
990
+
991
+ if callable(jac):
992
+ jac = _lightweight_memoizer(_wrap_jac(jac, xdata, transform))
993
+ elif jac is None and method != 'lm':
994
+ jac = '2-point'
995
+
996
+ if 'args' in kwargs:
997
+ # The specification for the model function `f` does not support
998
+ # additional arguments. Refer to the `curve_fit` docstring for
999
+ # acceptable call signatures of `f`.
1000
+ raise ValueError("'args' is not a supported keyword argument.")
1001
+
1002
+ if method == 'lm':
1003
+ # if ydata.size == 1, this might be used for broadcast.
1004
+ if ydata.size != 1 and n > ydata.size:
1005
+ raise TypeError(f"The number of func parameters={n} must not"
1006
+ f" exceed the number of data points={ydata.size}")
1007
+ res = leastsq(func, p0, Dfun=jac, full_output=1, **kwargs)
1008
+ popt, pcov, infodict, errmsg, ier = res
1009
+ ysize = len(infodict['fvec'])
1010
+ cost = np.sum(infodict['fvec'] ** 2)
1011
+ if ier not in [1, 2, 3, 4]:
1012
+ raise RuntimeError("Optimal parameters not found: " + errmsg)
1013
+ else:
1014
+ # Rename maxfev (leastsq) to max_nfev (least_squares), if specified.
1015
+ if 'max_nfev' not in kwargs:
1016
+ kwargs['max_nfev'] = kwargs.pop('maxfev', None)
1017
+
1018
+ res = least_squares(func, p0, jac=jac, bounds=bounds, method=method,
1019
+ **kwargs)
1020
+
1021
+ if not res.success:
1022
+ raise RuntimeError("Optimal parameters not found: " + res.message)
1023
+
1024
+ infodict = dict(nfev=res.nfev, fvec=res.fun)
1025
+ ier = res.status
1026
+ errmsg = res.message
1027
+
1028
+ ysize = len(res.fun)
1029
+ cost = 2 * res.cost # res.cost is half sum of squares!
1030
+ popt = res.x
1031
+
1032
+ # Do Moore-Penrose inverse discarding zero singular values.
1033
+ _, s, VT = svd(res.jac, full_matrices=False)
1034
+ threshold = np.finfo(float).eps * max(res.jac.shape) * s[0]
1035
+ s = s[s > threshold]
1036
+ VT = VT[:s.size]
1037
+ pcov = np.dot(VT.T / s**2, VT)
1038
+
1039
+ warn_cov = False
1040
+ if pcov is None or np.isnan(pcov).any():
1041
+ # indeterminate covariance
1042
+ pcov = zeros((len(popt), len(popt)), dtype=float)
1043
+ pcov.fill(inf)
1044
+ warn_cov = True
1045
+ elif not absolute_sigma:
1046
+ if ysize > p0.size:
1047
+ s_sq = cost / (ysize - p0.size)
1048
+ pcov = pcov * s_sq
1049
+ else:
1050
+ pcov.fill(inf)
1051
+ warn_cov = True
1052
+
1053
+ if warn_cov:
1054
+ warnings.warn('Covariance of the parameters could not be estimated',
1055
+ category=OptimizeWarning, stacklevel=2)
1056
+
1057
+ if full_output:
1058
+ return popt, pcov, infodict, errmsg, ier
1059
+ else:
1060
+ return popt, pcov
1061
+
1062
+
1063
+ def check_gradient(fcn, Dfcn, x0, args=(), col_deriv=0):
1064
+ """Perform a simple check on the gradient for correctness.
1065
+
1066
+ """
1067
+
1068
+ x = atleast_1d(x0)
1069
+ n = len(x)
1070
+ x = x.reshape((n,))
1071
+ fvec = atleast_1d(fcn(x, *args))
1072
+ m = len(fvec)
1073
+ fvec = fvec.reshape((m,))
1074
+ ldfjac = m
1075
+ fjac = atleast_1d(Dfcn(x, *args))
1076
+ fjac = fjac.reshape((m, n))
1077
+ if col_deriv == 0:
1078
+ fjac = transpose(fjac)
1079
+
1080
+ xp = zeros((n,), float)
1081
+ err = zeros((m,), float)
1082
+ fvecp = None
1083
+ _minpack._chkder(m, n, x, fvec, fjac, ldfjac, xp, fvecp, 1, err)
1084
+
1085
+ fvecp = atleast_1d(fcn(xp, *args))
1086
+ fvecp = fvecp.reshape((m,))
1087
+ _minpack._chkder(m, n, x, fvec, fjac, ldfjac, xp, fvecp, 2, err)
1088
+
1089
+ good = (prod(greater(err, 0.5), axis=0))
1090
+
1091
+ return (good, err)
1092
+
1093
+
1094
+ def _del2(p0, p1, d):
1095
+ return p0 - np.square(p1 - p0) / d
1096
+
1097
+
1098
+ def _relerr(actual, desired):
1099
+ return (actual - desired) / desired
1100
+
1101
+
1102
+ def _fixed_point_helper(func, x0, args, xtol, maxiter, use_accel):
1103
+ p0 = x0
1104
+ for i in range(maxiter):
1105
+ p1 = func(p0, *args)
1106
+ if use_accel:
1107
+ p2 = func(p1, *args)
1108
+ d = p2 - 2.0 * p1 + p0
1109
+ p = _lazywhere(d != 0, (p0, p1, d), f=_del2, fillvalue=p2)
1110
+ else:
1111
+ p = p1
1112
+ relerr = _lazywhere(p0 != 0, (p, p0), f=_relerr, fillvalue=p)
1113
+ if np.all(np.abs(relerr) < xtol):
1114
+ return p
1115
+ p0 = p
1116
+ msg = "Failed to converge after %d iterations, value is %s" % (maxiter, p)
1117
+ raise RuntimeError(msg)
1118
+
1119
+
1120
+ def fixed_point(func, x0, args=(), xtol=1e-8, maxiter=500, method='del2'):
1121
+ """
1122
+ Find a fixed point of the function.
1123
+
1124
+ Given a function of one or more variables and a starting point, find a
1125
+ fixed point of the function: i.e., where ``func(x0) == x0``.
1126
+
1127
+ Parameters
1128
+ ----------
1129
+ func : function
1130
+ Function to evaluate.
1131
+ x0 : array_like
1132
+ Fixed point of function.
1133
+ args : tuple, optional
1134
+ Extra arguments to `func`.
1135
+ xtol : float, optional
1136
+ Convergence tolerance, defaults to 1e-08.
1137
+ maxiter : int, optional
1138
+ Maximum number of iterations, defaults to 500.
1139
+ method : {"del2", "iteration"}, optional
1140
+ Method of finding the fixed-point, defaults to "del2",
1141
+ which uses Steffensen's Method with Aitken's ``Del^2``
1142
+ convergence acceleration [1]_. The "iteration" method simply iterates
1143
+ the function until convergence is detected, without attempting to
1144
+ accelerate the convergence.
1145
+
1146
+ References
1147
+ ----------
1148
+ .. [1] Burden, Faires, "Numerical Analysis", 5th edition, pg. 80
1149
+
1150
+ Examples
1151
+ --------
1152
+ >>> import numpy as np
1153
+ >>> from scipy import optimize
1154
+ >>> def func(x, c1, c2):
1155
+ ... return np.sqrt(c1/(x+c2))
1156
+ >>> c1 = np.array([10,12.])
1157
+ >>> c2 = np.array([3, 5.])
1158
+ >>> optimize.fixed_point(func, [1.2, 1.3], args=(c1,c2))
1159
+ array([ 1.4920333 , 1.37228132])
1160
+
1161
+ """
1162
+ use_accel = {'del2': True, 'iteration': False}[method]
1163
+ x0 = _asarray_validated(x0, as_inexact=True)
1164
+ return _fixed_point_helper(func, x0, args, xtol, maxiter, use_accel)
vila/lib/python3.10/site-packages/scipy/optimize/_moduleTNC.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d7584b3d74b2c7f2804c049af2291355762236b8a294520a6c7a83085ac11544
3
+ size 152168
vila/lib/python3.10/site-packages/scipy/optimize/_nnls.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from scipy.linalg import solve, LinAlgWarning
3
+ import warnings
4
+
5
+ __all__ = ['nnls']
6
+
7
+
8
+ def nnls(A, b, maxiter=None, *, atol=None):
9
+ """
10
+ Solve ``argmin_x || Ax - b ||_2`` for ``x>=0``.
11
+
12
+ This problem, often called as NonNegative Least Squares, is a convex
13
+ optimization problem with convex constraints. It typically arises when
14
+ the ``x`` models quantities for which only nonnegative values are
15
+ attainable; weight of ingredients, component costs and so on.
16
+
17
+ Parameters
18
+ ----------
19
+ A : (m, n) ndarray
20
+ Coefficient array
21
+ b : (m,) ndarray, float
22
+ Right-hand side vector.
23
+ maxiter: int, optional
24
+ Maximum number of iterations, optional. Default value is ``3 * n``.
25
+ atol: float
26
+ Tolerance value used in the algorithm to assess closeness to zero in
27
+ the projected residual ``(A.T @ (A x - b)`` entries. Increasing this
28
+ value relaxes the solution constraints. A typical relaxation value can
29
+ be selected as ``max(m, n) * np.linalg.norm(a, 1) * np.spacing(1.)``.
30
+ This value is not set as default since the norm operation becomes
31
+ expensive for large problems hence can be used only when necessary.
32
+
33
+ Returns
34
+ -------
35
+ x : ndarray
36
+ Solution vector.
37
+ rnorm : float
38
+ The 2-norm of the residual, ``|| Ax-b ||_2``.
39
+
40
+ See Also
41
+ --------
42
+ lsq_linear : Linear least squares with bounds on the variables
43
+
44
+ Notes
45
+ -----
46
+ The code is based on [2]_ which is an improved version of the classical
47
+ algorithm of [1]_. It utilizes an active set method and solves the KKT
48
+ (Karush-Kuhn-Tucker) conditions for the non-negative least squares problem.
49
+
50
+ References
51
+ ----------
52
+ .. [1] : Lawson C., Hanson R.J., "Solving Least Squares Problems", SIAM,
53
+ 1995, :doi:`10.1137/1.9781611971217`
54
+ .. [2] : Bro, Rasmus and de Jong, Sijmen, "A Fast Non-Negativity-
55
+ Constrained Least Squares Algorithm", Journal Of Chemometrics, 1997,
56
+ :doi:`10.1002/(SICI)1099-128X(199709/10)11:5<393::AID-CEM483>3.0.CO;2-L`
57
+
58
+ Examples
59
+ --------
60
+ >>> import numpy as np
61
+ >>> from scipy.optimize import nnls
62
+ ...
63
+ >>> A = np.array([[1, 0], [1, 0], [0, 1]])
64
+ >>> b = np.array([2, 1, 1])
65
+ >>> nnls(A, b)
66
+ (array([1.5, 1. ]), 0.7071067811865475)
67
+
68
+ >>> b = np.array([-1, -1, -1])
69
+ >>> nnls(A, b)
70
+ (array([0., 0.]), 1.7320508075688772)
71
+
72
+ """
73
+
74
+ A = np.asarray_chkfinite(A)
75
+ b = np.asarray_chkfinite(b)
76
+
77
+ if len(A.shape) != 2:
78
+ raise ValueError("Expected a two-dimensional array (matrix)" +
79
+ f", but the shape of A is {A.shape}")
80
+ if len(b.shape) != 1:
81
+ raise ValueError("Expected a one-dimensional array (vector)" +
82
+ f", but the shape of b is {b.shape}")
83
+
84
+ m, n = A.shape
85
+
86
+ if m != b.shape[0]:
87
+ raise ValueError(
88
+ "Incompatible dimensions. The first dimension of " +
89
+ f"A is {m}, while the shape of b is {(b.shape[0], )}")
90
+
91
+ x, rnorm, mode = _nnls(A, b, maxiter, tol=atol)
92
+ if mode != 1:
93
+ raise RuntimeError("Maximum number of iterations reached.")
94
+
95
+ return x, rnorm
96
+
97
+
98
+ def _nnls(A, b, maxiter=None, tol=None):
99
+ """
100
+ This is a single RHS algorithm from ref [2] above. For multiple RHS
101
+ support, the algorithm is given in :doi:`10.1002/cem.889`
102
+ """
103
+ m, n = A.shape
104
+
105
+ AtA = A.T @ A
106
+ Atb = b @ A # Result is 1D - let NumPy figure it out
107
+
108
+ if not maxiter:
109
+ maxiter = 3*n
110
+ if tol is None:
111
+ tol = 10 * max(m, n) * np.spacing(1.)
112
+
113
+ # Initialize vars
114
+ x = np.zeros(n, dtype=np.float64)
115
+ s = np.zeros(n, dtype=np.float64)
116
+ # Inactive constraint switches
117
+ P = np.zeros(n, dtype=bool)
118
+
119
+ # Projected residual
120
+ w = Atb.copy().astype(np.float64) # x=0. Skip (-AtA @ x) term
121
+
122
+ # Overall iteration counter
123
+ # Outer loop is not counted, inner iter is counted across outer spins
124
+ iter = 0
125
+
126
+ while (not P.all()) and (w[~P] > tol).any(): # B
127
+ # Get the "most" active coeff index and move to inactive set
128
+ k = np.argmax(w * (~P)) # B.2
129
+ P[k] = True # B.3
130
+
131
+ # Iteration solution
132
+ s[:] = 0.
133
+ # B.4
134
+ with warnings.catch_warnings():
135
+ warnings.filterwarnings('ignore', message='Ill-conditioned matrix',
136
+ category=LinAlgWarning)
137
+ s[P] = solve(AtA[np.ix_(P, P)], Atb[P], assume_a='sym', check_finite=False)
138
+
139
+ # Inner loop
140
+ while (iter < maxiter) and (s[P].min() < 0): # C.1
141
+ iter += 1
142
+ inds = P * (s < 0)
143
+ alpha = (x[inds] / (x[inds] - s[inds])).min() # C.2
144
+ x *= (1 - alpha)
145
+ x += alpha*s
146
+ P[x <= tol] = False
147
+ with warnings.catch_warnings():
148
+ warnings.filterwarnings('ignore', message='Ill-conditioned matrix',
149
+ category=LinAlgWarning)
150
+ s[P] = solve(AtA[np.ix_(P, P)], Atb[P], assume_a='sym',
151
+ check_finite=False)
152
+ s[~P] = 0 # C.6
153
+
154
+ x[:] = s[:]
155
+ w[:] = Atb - AtA @ x
156
+
157
+ if iter == maxiter:
158
+ # Typically following line should return
159
+ # return x, np.linalg.norm(A@x - b), -1
160
+ # however at the top level, -1 raises an exception wasting norm
161
+ # Instead return dummy number 0.
162
+ return x, 0., -1
163
+
164
+ return x, np.linalg.norm(A@x - b), 1
vila/lib/python3.10/site-packages/scipy/optimize/_nonlin.py ADDED
@@ -0,0 +1,1585 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2009, Pauli Virtanen <pav@iki.fi>
2
+ # Distributed under the same license as SciPy.
3
+
4
+ import inspect
5
+ import sys
6
+ import warnings
7
+
8
+ import numpy as np
9
+ from numpy import asarray, dot, vdot
10
+
11
+ from scipy.linalg import norm, solve, inv, qr, svd, LinAlgError
12
+ import scipy.sparse.linalg
13
+ import scipy.sparse
14
+ from scipy.linalg import get_blas_funcs
15
+ from scipy._lib._util import copy_if_needed
16
+ from scipy._lib._util import getfullargspec_no_self as _getfullargspec
17
+ from ._linesearch import scalar_search_wolfe1, scalar_search_armijo
18
+
19
+
20
+ __all__ = [
21
+ 'broyden1', 'broyden2', 'anderson', 'linearmixing',
22
+ 'diagbroyden', 'excitingmixing', 'newton_krylov',
23
+ 'BroydenFirst', 'KrylovJacobian', 'InverseJacobian', 'NoConvergence']
24
+
25
+ #------------------------------------------------------------------------------
26
+ # Utility functions
27
+ #------------------------------------------------------------------------------
28
+
29
+
30
+ class NoConvergence(Exception):
31
+ """Exception raised when nonlinear solver fails to converge within the specified
32
+ `maxiter`."""
33
+ pass
34
+
35
+
36
+ def maxnorm(x):
37
+ return np.absolute(x).max()
38
+
39
+
40
+ def _as_inexact(x):
41
+ """Return `x` as an array, of either floats or complex floats"""
42
+ x = asarray(x)
43
+ if not np.issubdtype(x.dtype, np.inexact):
44
+ return asarray(x, dtype=np.float64)
45
+ return x
46
+
47
+
48
+ def _array_like(x, x0):
49
+ """Return ndarray `x` as same array subclass and shape as `x0`"""
50
+ x = np.reshape(x, np.shape(x0))
51
+ wrap = getattr(x0, '__array_wrap__', x.__array_wrap__)
52
+ return wrap(x)
53
+
54
+
55
+ def _safe_norm(v):
56
+ if not np.isfinite(v).all():
57
+ return np.array(np.inf)
58
+ return norm(v)
59
+
60
+ #------------------------------------------------------------------------------
61
+ # Generic nonlinear solver machinery
62
+ #------------------------------------------------------------------------------
63
+
64
+
65
+ _doc_parts = dict(
66
+ params_basic="""
67
+ F : function(x) -> f
68
+ Function whose root to find; should take and return an array-like
69
+ object.
70
+ xin : array_like
71
+ Initial guess for the solution
72
+ """.strip(),
73
+ params_extra="""
74
+ iter : int, optional
75
+ Number of iterations to make. If omitted (default), make as many
76
+ as required to meet tolerances.
77
+ verbose : bool, optional
78
+ Print status to stdout on every iteration.
79
+ maxiter : int, optional
80
+ Maximum number of iterations to make. If more are needed to
81
+ meet convergence, `NoConvergence` is raised.
82
+ f_tol : float, optional
83
+ Absolute tolerance (in max-norm) for the residual.
84
+ If omitted, default is 6e-6.
85
+ f_rtol : float, optional
86
+ Relative tolerance for the residual. If omitted, not used.
87
+ x_tol : float, optional
88
+ Absolute minimum step size, as determined from the Jacobian
89
+ approximation. If the step size is smaller than this, optimization
90
+ is terminated as successful. If omitted, not used.
91
+ x_rtol : float, optional
92
+ Relative minimum step size. If omitted, not used.
93
+ tol_norm : function(vector) -> scalar, optional
94
+ Norm to use in convergence check. Default is the maximum norm.
95
+ line_search : {None, 'armijo' (default), 'wolfe'}, optional
96
+ Which type of a line search to use to determine the step size in the
97
+ direction given by the Jacobian approximation. Defaults to 'armijo'.
98
+ callback : function, optional
99
+ Optional callback function. It is called on every iteration as
100
+ ``callback(x, f)`` where `x` is the current solution and `f`
101
+ the corresponding residual.
102
+
103
+ Returns
104
+ -------
105
+ sol : ndarray
106
+ An array (of similar array type as `x0`) containing the final solution.
107
+
108
+ Raises
109
+ ------
110
+ NoConvergence
111
+ When a solution was not found.
112
+
113
+ """.strip()
114
+ )
115
+
116
+
117
+ def _set_doc(obj):
118
+ if obj.__doc__:
119
+ obj.__doc__ = obj.__doc__ % _doc_parts
120
+
121
+
122
+ def nonlin_solve(F, x0, jacobian='krylov', iter=None, verbose=False,
123
+ maxiter=None, f_tol=None, f_rtol=None, x_tol=None, x_rtol=None,
124
+ tol_norm=None, line_search='armijo', callback=None,
125
+ full_output=False, raise_exception=True):
126
+ """
127
+ Find a root of a function, in a way suitable for large-scale problems.
128
+
129
+ Parameters
130
+ ----------
131
+ %(params_basic)s
132
+ jacobian : Jacobian
133
+ A Jacobian approximation: `Jacobian` object or something that
134
+ `asjacobian` can transform to one. Alternatively, a string specifying
135
+ which of the builtin Jacobian approximations to use:
136
+
137
+ krylov, broyden1, broyden2, anderson
138
+ diagbroyden, linearmixing, excitingmixing
139
+
140
+ %(params_extra)s
141
+ full_output : bool
142
+ If true, returns a dictionary `info` containing convergence
143
+ information.
144
+ raise_exception : bool
145
+ If True, a `NoConvergence` exception is raise if no solution is found.
146
+
147
+ See Also
148
+ --------
149
+ asjacobian, Jacobian
150
+
151
+ Notes
152
+ -----
153
+ This algorithm implements the inexact Newton method, with
154
+ backtracking or full line searches. Several Jacobian
155
+ approximations are available, including Krylov and Quasi-Newton
156
+ methods.
157
+
158
+ References
159
+ ----------
160
+ .. [KIM] C. T. Kelley, \"Iterative Methods for Linear and Nonlinear
161
+ Equations\". Society for Industrial and Applied Mathematics. (1995)
162
+ https://archive.siam.org/books/kelley/fr16/
163
+
164
+ """
165
+ # Can't use default parameters because it's being explicitly passed as None
166
+ # from the calling function, so we need to set it here.
167
+ tol_norm = maxnorm if tol_norm is None else tol_norm
168
+ condition = TerminationCondition(f_tol=f_tol, f_rtol=f_rtol,
169
+ x_tol=x_tol, x_rtol=x_rtol,
170
+ iter=iter, norm=tol_norm)
171
+
172
+ x0 = _as_inexact(x0)
173
+ def func(z):
174
+ return _as_inexact(F(_array_like(z, x0))).flatten()
175
+ x = x0.flatten()
176
+
177
+ dx = np.full_like(x, np.inf)
178
+ Fx = func(x)
179
+ Fx_norm = norm(Fx)
180
+
181
+ jacobian = asjacobian(jacobian)
182
+ jacobian.setup(x.copy(), Fx, func)
183
+
184
+ if maxiter is None:
185
+ if iter is not None:
186
+ maxiter = iter + 1
187
+ else:
188
+ maxiter = 100*(x.size+1)
189
+
190
+ if line_search is True:
191
+ line_search = 'armijo'
192
+ elif line_search is False:
193
+ line_search = None
194
+
195
+ if line_search not in (None, 'armijo', 'wolfe'):
196
+ raise ValueError("Invalid line search")
197
+
198
+ # Solver tolerance selection
199
+ gamma = 0.9
200
+ eta_max = 0.9999
201
+ eta_treshold = 0.1
202
+ eta = 1e-3
203
+
204
+ for n in range(maxiter):
205
+ status = condition.check(Fx, x, dx)
206
+ if status:
207
+ break
208
+
209
+ # The tolerance, as computed for scipy.sparse.linalg.* routines
210
+ tol = min(eta, eta*Fx_norm)
211
+ dx = -jacobian.solve(Fx, tol=tol)
212
+
213
+ if norm(dx) == 0:
214
+ raise ValueError("Jacobian inversion yielded zero vector. "
215
+ "This indicates a bug in the Jacobian "
216
+ "approximation.")
217
+
218
+ # Line search, or Newton step
219
+ if line_search:
220
+ s, x, Fx, Fx_norm_new = _nonlin_line_search(func, x, Fx, dx,
221
+ line_search)
222
+ else:
223
+ s = 1.0
224
+ x = x + dx
225
+ Fx = func(x)
226
+ Fx_norm_new = norm(Fx)
227
+
228
+ jacobian.update(x.copy(), Fx)
229
+
230
+ if callback:
231
+ callback(x, Fx)
232
+
233
+ # Adjust forcing parameters for inexact methods
234
+ eta_A = gamma * Fx_norm_new**2 / Fx_norm**2
235
+ if gamma * eta**2 < eta_treshold:
236
+ eta = min(eta_max, eta_A)
237
+ else:
238
+ eta = min(eta_max, max(eta_A, gamma*eta**2))
239
+
240
+ Fx_norm = Fx_norm_new
241
+
242
+ # Print status
243
+ if verbose:
244
+ sys.stdout.write("%d: |F(x)| = %g; step %g\n" % (
245
+ n, tol_norm(Fx), s))
246
+ sys.stdout.flush()
247
+ else:
248
+ if raise_exception:
249
+ raise NoConvergence(_array_like(x, x0))
250
+ else:
251
+ status = 2
252
+
253
+ if full_output:
254
+ info = {'nit': condition.iteration,
255
+ 'fun': Fx,
256
+ 'status': status,
257
+ 'success': status == 1,
258
+ 'message': {1: 'A solution was found at the specified '
259
+ 'tolerance.',
260
+ 2: 'The maximum number of iterations allowed '
261
+ 'has been reached.'
262
+ }[status]
263
+ }
264
+ return _array_like(x, x0), info
265
+ else:
266
+ return _array_like(x, x0)
267
+
268
+
269
+ _set_doc(nonlin_solve)
270
+
271
+
272
+ def _nonlin_line_search(func, x, Fx, dx, search_type='armijo', rdiff=1e-8,
273
+ smin=1e-2):
274
+ tmp_s = [0]
275
+ tmp_Fx = [Fx]
276
+ tmp_phi = [norm(Fx)**2]
277
+ s_norm = norm(x) / norm(dx)
278
+
279
+ def phi(s, store=True):
280
+ if s == tmp_s[0]:
281
+ return tmp_phi[0]
282
+ xt = x + s*dx
283
+ v = func(xt)
284
+ p = _safe_norm(v)**2
285
+ if store:
286
+ tmp_s[0] = s
287
+ tmp_phi[0] = p
288
+ tmp_Fx[0] = v
289
+ return p
290
+
291
+ def derphi(s):
292
+ ds = (abs(s) + s_norm + 1) * rdiff
293
+ return (phi(s+ds, store=False) - phi(s)) / ds
294
+
295
+ if search_type == 'wolfe':
296
+ s, phi1, phi0 = scalar_search_wolfe1(phi, derphi, tmp_phi[0],
297
+ xtol=1e-2, amin=smin)
298
+ elif search_type == 'armijo':
299
+ s, phi1 = scalar_search_armijo(phi, tmp_phi[0], -tmp_phi[0],
300
+ amin=smin)
301
+
302
+ if s is None:
303
+ # XXX: No suitable step length found. Take the full Newton step,
304
+ # and hope for the best.
305
+ s = 1.0
306
+
307
+ x = x + s*dx
308
+ if s == tmp_s[0]:
309
+ Fx = tmp_Fx[0]
310
+ else:
311
+ Fx = func(x)
312
+ Fx_norm = norm(Fx)
313
+
314
+ return s, x, Fx, Fx_norm
315
+
316
+
317
+ class TerminationCondition:
318
+ """
319
+ Termination condition for an iteration. It is terminated if
320
+
321
+ - |F| < f_rtol*|F_0|, AND
322
+ - |F| < f_tol
323
+
324
+ AND
325
+
326
+ - |dx| < x_rtol*|x|, AND
327
+ - |dx| < x_tol
328
+
329
+ """
330
+ def __init__(self, f_tol=None, f_rtol=None, x_tol=None, x_rtol=None,
331
+ iter=None, norm=maxnorm):
332
+
333
+ if f_tol is None:
334
+ f_tol = np.finfo(np.float64).eps ** (1./3)
335
+ if f_rtol is None:
336
+ f_rtol = np.inf
337
+ if x_tol is None:
338
+ x_tol = np.inf
339
+ if x_rtol is None:
340
+ x_rtol = np.inf
341
+
342
+ self.x_tol = x_tol
343
+ self.x_rtol = x_rtol
344
+ self.f_tol = f_tol
345
+ self.f_rtol = f_rtol
346
+
347
+ self.norm = norm
348
+
349
+ self.iter = iter
350
+
351
+ self.f0_norm = None
352
+ self.iteration = 0
353
+
354
+ def check(self, f, x, dx):
355
+ self.iteration += 1
356
+ f_norm = self.norm(f)
357
+ x_norm = self.norm(x)
358
+ dx_norm = self.norm(dx)
359
+
360
+ if self.f0_norm is None:
361
+ self.f0_norm = f_norm
362
+
363
+ if f_norm == 0:
364
+ return 1
365
+
366
+ if self.iter is not None:
367
+ # backwards compatibility with SciPy 0.6.0
368
+ return 2 * (self.iteration > self.iter)
369
+
370
+ # NB: condition must succeed for rtol=inf even if norm == 0
371
+ return int((f_norm <= self.f_tol
372
+ and f_norm/self.f_rtol <= self.f0_norm)
373
+ and (dx_norm <= self.x_tol
374
+ and dx_norm/self.x_rtol <= x_norm))
375
+
376
+
377
+ #------------------------------------------------------------------------------
378
+ # Generic Jacobian approximation
379
+ #------------------------------------------------------------------------------
380
+
381
+ class Jacobian:
382
+ """
383
+ Common interface for Jacobians or Jacobian approximations.
384
+
385
+ The optional methods come useful when implementing trust region
386
+ etc., algorithms that often require evaluating transposes of the
387
+ Jacobian.
388
+
389
+ Methods
390
+ -------
391
+ solve
392
+ Returns J^-1 * v
393
+ update
394
+ Updates Jacobian to point `x` (where the function has residual `Fx`)
395
+
396
+ matvec : optional
397
+ Returns J * v
398
+ rmatvec : optional
399
+ Returns A^H * v
400
+ rsolve : optional
401
+ Returns A^-H * v
402
+ matmat : optional
403
+ Returns A * V, where V is a dense matrix with dimensions (N,K).
404
+ todense : optional
405
+ Form the dense Jacobian matrix. Necessary for dense trust region
406
+ algorithms, and useful for testing.
407
+
408
+ Attributes
409
+ ----------
410
+ shape
411
+ Matrix dimensions (M, N)
412
+ dtype
413
+ Data type of the matrix.
414
+ func : callable, optional
415
+ Function the Jacobian corresponds to
416
+
417
+ """
418
+
419
+ def __init__(self, **kw):
420
+ names = ["solve", "update", "matvec", "rmatvec", "rsolve",
421
+ "matmat", "todense", "shape", "dtype"]
422
+ for name, value in kw.items():
423
+ if name not in names:
424
+ raise ValueError("Unknown keyword argument %s" % name)
425
+ if value is not None:
426
+ setattr(self, name, kw[name])
427
+
428
+
429
+ if hasattr(self, "todense"):
430
+ def __array__(self, dtype=None, copy=None):
431
+ if dtype is not None:
432
+ raise ValueError(f"`dtype` must be None, was {dtype}")
433
+ return self.todense()
434
+
435
+ def aspreconditioner(self):
436
+ return InverseJacobian(self)
437
+
438
+ def solve(self, v, tol=0):
439
+ raise NotImplementedError
440
+
441
+ def update(self, x, F):
442
+ pass
443
+
444
+ def setup(self, x, F, func):
445
+ self.func = func
446
+ self.shape = (F.size, x.size)
447
+ self.dtype = F.dtype
448
+ if self.__class__.setup is Jacobian.setup:
449
+ # Call on the first point unless overridden
450
+ self.update(x, F)
451
+
452
+
453
+ class InverseJacobian:
454
+ def __init__(self, jacobian):
455
+ self.jacobian = jacobian
456
+ self.matvec = jacobian.solve
457
+ self.update = jacobian.update
458
+ if hasattr(jacobian, 'setup'):
459
+ self.setup = jacobian.setup
460
+ if hasattr(jacobian, 'rsolve'):
461
+ self.rmatvec = jacobian.rsolve
462
+
463
+ @property
464
+ def shape(self):
465
+ return self.jacobian.shape
466
+
467
+ @property
468
+ def dtype(self):
469
+ return self.jacobian.dtype
470
+
471
+
472
+ def asjacobian(J):
473
+ """
474
+ Convert given object to one suitable for use as a Jacobian.
475
+ """
476
+ spsolve = scipy.sparse.linalg.spsolve
477
+ if isinstance(J, Jacobian):
478
+ return J
479
+ elif inspect.isclass(J) and issubclass(J, Jacobian):
480
+ return J()
481
+ elif isinstance(J, np.ndarray):
482
+ if J.ndim > 2:
483
+ raise ValueError('array must have rank <= 2')
484
+ J = np.atleast_2d(np.asarray(J))
485
+ if J.shape[0] != J.shape[1]:
486
+ raise ValueError('array must be square')
487
+
488
+ return Jacobian(matvec=lambda v: dot(J, v),
489
+ rmatvec=lambda v: dot(J.conj().T, v),
490
+ solve=lambda v, tol=0: solve(J, v),
491
+ rsolve=lambda v, tol=0: solve(J.conj().T, v),
492
+ dtype=J.dtype, shape=J.shape)
493
+ elif scipy.sparse.issparse(J):
494
+ if J.shape[0] != J.shape[1]:
495
+ raise ValueError('matrix must be square')
496
+ return Jacobian(matvec=lambda v: J @ v,
497
+ rmatvec=lambda v: J.conj().T @ v,
498
+ solve=lambda v, tol=0: spsolve(J, v),
499
+ rsolve=lambda v, tol=0: spsolve(J.conj().T, v),
500
+ dtype=J.dtype, shape=J.shape)
501
+ elif hasattr(J, 'shape') and hasattr(J, 'dtype') and hasattr(J, 'solve'):
502
+ return Jacobian(matvec=getattr(J, 'matvec'),
503
+ rmatvec=getattr(J, 'rmatvec'),
504
+ solve=J.solve,
505
+ rsolve=getattr(J, 'rsolve'),
506
+ update=getattr(J, 'update'),
507
+ setup=getattr(J, 'setup'),
508
+ dtype=J.dtype,
509
+ shape=J.shape)
510
+ elif callable(J):
511
+ # Assume it's a function J(x) that returns the Jacobian
512
+ class Jac(Jacobian):
513
+ def update(self, x, F):
514
+ self.x = x
515
+
516
+ def solve(self, v, tol=0):
517
+ m = J(self.x)
518
+ if isinstance(m, np.ndarray):
519
+ return solve(m, v)
520
+ elif scipy.sparse.issparse(m):
521
+ return spsolve(m, v)
522
+ else:
523
+ raise ValueError("Unknown matrix type")
524
+
525
+ def matvec(self, v):
526
+ m = J(self.x)
527
+ if isinstance(m, np.ndarray):
528
+ return dot(m, v)
529
+ elif scipy.sparse.issparse(m):
530
+ return m @ v
531
+ else:
532
+ raise ValueError("Unknown matrix type")
533
+
534
+ def rsolve(self, v, tol=0):
535
+ m = J(self.x)
536
+ if isinstance(m, np.ndarray):
537
+ return solve(m.conj().T, v)
538
+ elif scipy.sparse.issparse(m):
539
+ return spsolve(m.conj().T, v)
540
+ else:
541
+ raise ValueError("Unknown matrix type")
542
+
543
+ def rmatvec(self, v):
544
+ m = J(self.x)
545
+ if isinstance(m, np.ndarray):
546
+ return dot(m.conj().T, v)
547
+ elif scipy.sparse.issparse(m):
548
+ return m.conj().T @ v
549
+ else:
550
+ raise ValueError("Unknown matrix type")
551
+ return Jac()
552
+ elif isinstance(J, str):
553
+ return dict(broyden1=BroydenFirst,
554
+ broyden2=BroydenSecond,
555
+ anderson=Anderson,
556
+ diagbroyden=DiagBroyden,
557
+ linearmixing=LinearMixing,
558
+ excitingmixing=ExcitingMixing,
559
+ krylov=KrylovJacobian)[J]()
560
+ else:
561
+ raise TypeError('Cannot convert object to a Jacobian')
562
+
563
+
564
+ #------------------------------------------------------------------------------
565
+ # Broyden
566
+ #------------------------------------------------------------------------------
567
+
568
+ class GenericBroyden(Jacobian):
569
+ def setup(self, x0, f0, func):
570
+ Jacobian.setup(self, x0, f0, func)
571
+ self.last_f = f0
572
+ self.last_x = x0
573
+
574
+ if hasattr(self, 'alpha') and self.alpha is None:
575
+ # Autoscale the initial Jacobian parameter
576
+ # unless we have already guessed the solution.
577
+ normf0 = norm(f0)
578
+ if normf0:
579
+ self.alpha = 0.5*max(norm(x0), 1) / normf0
580
+ else:
581
+ self.alpha = 1.0
582
+
583
+ def _update(self, x, f, dx, df, dx_norm, df_norm):
584
+ raise NotImplementedError
585
+
586
+ def update(self, x, f):
587
+ df = f - self.last_f
588
+ dx = x - self.last_x
589
+ self._update(x, f, dx, df, norm(dx), norm(df))
590
+ self.last_f = f
591
+ self.last_x = x
592
+
593
+
594
+ class LowRankMatrix:
595
+ r"""
596
+ A matrix represented as
597
+
598
+ .. math:: \alpha I + \sum_{n=0}^{n=M} c_n d_n^\dagger
599
+
600
+ However, if the rank of the matrix reaches the dimension of the vectors,
601
+ full matrix representation will be used thereon.
602
+
603
+ """
604
+
605
+ def __init__(self, alpha, n, dtype):
606
+ self.alpha = alpha
607
+ self.cs = []
608
+ self.ds = []
609
+ self.n = n
610
+ self.dtype = dtype
611
+ self.collapsed = None
612
+
613
+ @staticmethod
614
+ def _matvec(v, alpha, cs, ds):
615
+ axpy, scal, dotc = get_blas_funcs(['axpy', 'scal', 'dotc'],
616
+ cs[:1] + [v])
617
+ w = alpha * v
618
+ for c, d in zip(cs, ds):
619
+ a = dotc(d, v)
620
+ w = axpy(c, w, w.size, a)
621
+ return w
622
+
623
+ @staticmethod
624
+ def _solve(v, alpha, cs, ds):
625
+ """Evaluate w = M^-1 v"""
626
+ if len(cs) == 0:
627
+ return v/alpha
628
+
629
+ # (B + C D^H)^-1 = B^-1 - B^-1 C (I + D^H B^-1 C)^-1 D^H B^-1
630
+
631
+ axpy, dotc = get_blas_funcs(['axpy', 'dotc'], cs[:1] + [v])
632
+
633
+ c0 = cs[0]
634
+ A = alpha * np.identity(len(cs), dtype=c0.dtype)
635
+ for i, d in enumerate(ds):
636
+ for j, c in enumerate(cs):
637
+ A[i,j] += dotc(d, c)
638
+
639
+ q = np.zeros(len(cs), dtype=c0.dtype)
640
+ for j, d in enumerate(ds):
641
+ q[j] = dotc(d, v)
642
+ q /= alpha
643
+ q = solve(A, q)
644
+
645
+ w = v/alpha
646
+ for c, qc in zip(cs, q):
647
+ w = axpy(c, w, w.size, -qc)
648
+
649
+ return w
650
+
651
+ def matvec(self, v):
652
+ """Evaluate w = M v"""
653
+ if self.collapsed is not None:
654
+ return np.dot(self.collapsed, v)
655
+ return LowRankMatrix._matvec(v, self.alpha, self.cs, self.ds)
656
+
657
+ def rmatvec(self, v):
658
+ """Evaluate w = M^H v"""
659
+ if self.collapsed is not None:
660
+ return np.dot(self.collapsed.T.conj(), v)
661
+ return LowRankMatrix._matvec(v, np.conj(self.alpha), self.ds, self.cs)
662
+
663
+ def solve(self, v, tol=0):
664
+ """Evaluate w = M^-1 v"""
665
+ if self.collapsed is not None:
666
+ return solve(self.collapsed, v)
667
+ return LowRankMatrix._solve(v, self.alpha, self.cs, self.ds)
668
+
669
+ def rsolve(self, v, tol=0):
670
+ """Evaluate w = M^-H v"""
671
+ if self.collapsed is not None:
672
+ return solve(self.collapsed.T.conj(), v)
673
+ return LowRankMatrix._solve(v, np.conj(self.alpha), self.ds, self.cs)
674
+
675
+ def append(self, c, d):
676
+ if self.collapsed is not None:
677
+ self.collapsed += c[:,None] * d[None,:].conj()
678
+ return
679
+
680
+ self.cs.append(c)
681
+ self.ds.append(d)
682
+
683
+ if len(self.cs) > c.size:
684
+ self.collapse()
685
+
686
+ def __array__(self, dtype=None, copy=None):
687
+ if dtype is not None:
688
+ warnings.warn("LowRankMatrix is scipy-internal code, `dtype` "
689
+ f"should only be None but was {dtype} (not handled)",
690
+ stacklevel=3)
691
+ if copy is not None:
692
+ warnings.warn("LowRankMatrix is scipy-internal code, `copy` "
693
+ f"should only be None but was {copy} (not handled)",
694
+ stacklevel=3)
695
+ if self.collapsed is not None:
696
+ return self.collapsed
697
+
698
+ Gm = self.alpha*np.identity(self.n, dtype=self.dtype)
699
+ for c, d in zip(self.cs, self.ds):
700
+ Gm += c[:,None]*d[None,:].conj()
701
+ return Gm
702
+
703
+ def collapse(self):
704
+ """Collapse the low-rank matrix to a full-rank one."""
705
+ self.collapsed = np.array(self, copy=copy_if_needed)
706
+ self.cs = None
707
+ self.ds = None
708
+ self.alpha = None
709
+
710
+ def restart_reduce(self, rank):
711
+ """
712
+ Reduce the rank of the matrix by dropping all vectors.
713
+ """
714
+ if self.collapsed is not None:
715
+ return
716
+ assert rank > 0
717
+ if len(self.cs) > rank:
718
+ del self.cs[:]
719
+ del self.ds[:]
720
+
721
+ def simple_reduce(self, rank):
722
+ """
723
+ Reduce the rank of the matrix by dropping oldest vectors.
724
+ """
725
+ if self.collapsed is not None:
726
+ return
727
+ assert rank > 0
728
+ while len(self.cs) > rank:
729
+ del self.cs[0]
730
+ del self.ds[0]
731
+
732
+ def svd_reduce(self, max_rank, to_retain=None):
733
+ """
734
+ Reduce the rank of the matrix by retaining some SVD components.
735
+
736
+ This corresponds to the \"Broyden Rank Reduction Inverse\"
737
+ algorithm described in [1]_.
738
+
739
+ Note that the SVD decomposition can be done by solving only a
740
+ problem whose size is the effective rank of this matrix, which
741
+ is viable even for large problems.
742
+
743
+ Parameters
744
+ ----------
745
+ max_rank : int
746
+ Maximum rank of this matrix after reduction.
747
+ to_retain : int, optional
748
+ Number of SVD components to retain when reduction is done
749
+ (ie. rank > max_rank). Default is ``max_rank - 2``.
750
+
751
+ References
752
+ ----------
753
+ .. [1] B.A. van der Rotten, PhD thesis,
754
+ \"A limited memory Broyden method to solve high-dimensional
755
+ systems of nonlinear equations\". Mathematisch Instituut,
756
+ Universiteit Leiden, The Netherlands (2003).
757
+
758
+ https://web.archive.org/web/20161022015821/http://www.math.leidenuniv.nl/scripties/Rotten.pdf
759
+
760
+ """
761
+ if self.collapsed is not None:
762
+ return
763
+
764
+ p = max_rank
765
+ if to_retain is not None:
766
+ q = to_retain
767
+ else:
768
+ q = p - 2
769
+
770
+ if self.cs:
771
+ p = min(p, len(self.cs[0]))
772
+ q = max(0, min(q, p-1))
773
+
774
+ m = len(self.cs)
775
+ if m < p:
776
+ # nothing to do
777
+ return
778
+
779
+ C = np.array(self.cs).T
780
+ D = np.array(self.ds).T
781
+
782
+ D, R = qr(D, mode='economic')
783
+ C = dot(C, R.T.conj())
784
+
785
+ U, S, WH = svd(C, full_matrices=False)
786
+
787
+ C = dot(C, inv(WH))
788
+ D = dot(D, WH.T.conj())
789
+
790
+ for k in range(q):
791
+ self.cs[k] = C[:,k].copy()
792
+ self.ds[k] = D[:,k].copy()
793
+
794
+ del self.cs[q:]
795
+ del self.ds[q:]
796
+
797
+
798
+ _doc_parts['broyden_params'] = """
799
+ alpha : float, optional
800
+ Initial guess for the Jacobian is ``(-1/alpha)``.
801
+ reduction_method : str or tuple, optional
802
+ Method used in ensuring that the rank of the Broyden matrix
803
+ stays low. Can either be a string giving the name of the method,
804
+ or a tuple of the form ``(method, param1, param2, ...)``
805
+ that gives the name of the method and values for additional parameters.
806
+
807
+ Methods available:
808
+
809
+ - ``restart``: drop all matrix columns. Has no extra parameters.
810
+ - ``simple``: drop oldest matrix column. Has no extra parameters.
811
+ - ``svd``: keep only the most significant SVD components.
812
+ Takes an extra parameter, ``to_retain``, which determines the
813
+ number of SVD components to retain when rank reduction is done.
814
+ Default is ``max_rank - 2``.
815
+
816
+ max_rank : int, optional
817
+ Maximum rank for the Broyden matrix.
818
+ Default is infinity (i.e., no rank reduction).
819
+ """.strip()
820
+
821
+
822
+ class BroydenFirst(GenericBroyden):
823
+ r"""
824
+ Find a root of a function, using Broyden's first Jacobian approximation.
825
+
826
+ This method is also known as \"Broyden's good method\".
827
+
828
+ Parameters
829
+ ----------
830
+ %(params_basic)s
831
+ %(broyden_params)s
832
+ %(params_extra)s
833
+
834
+ See Also
835
+ --------
836
+ root : Interface to root finding algorithms for multivariate
837
+ functions. See ``method='broyden1'`` in particular.
838
+
839
+ Notes
840
+ -----
841
+ This algorithm implements the inverse Jacobian Quasi-Newton update
842
+
843
+ .. math:: H_+ = H + (dx - H df) dx^\dagger H / ( dx^\dagger H df)
844
+
845
+ which corresponds to Broyden's first Jacobian update
846
+
847
+ .. math:: J_+ = J + (df - J dx) dx^\dagger / dx^\dagger dx
848
+
849
+
850
+ References
851
+ ----------
852
+ .. [1] B.A. van der Rotten, PhD thesis,
853
+ \"A limited memory Broyden method to solve high-dimensional
854
+ systems of nonlinear equations\". Mathematisch Instituut,
855
+ Universiteit Leiden, The Netherlands (2003).
856
+
857
+ https://web.archive.org/web/20161022015821/http://www.math.leidenuniv.nl/scripties/Rotten.pdf
858
+
859
+ Examples
860
+ --------
861
+ The following functions define a system of nonlinear equations
862
+
863
+ >>> def fun(x):
864
+ ... return [x[0] + 0.5 * (x[0] - x[1])**3 - 1.0,
865
+ ... 0.5 * (x[1] - x[0])**3 + x[1]]
866
+
867
+ A solution can be obtained as follows.
868
+
869
+ >>> from scipy import optimize
870
+ >>> sol = optimize.broyden1(fun, [0, 0])
871
+ >>> sol
872
+ array([0.84116396, 0.15883641])
873
+
874
+ """
875
+
876
+ def __init__(self, alpha=None, reduction_method='restart', max_rank=None):
877
+ GenericBroyden.__init__(self)
878
+ self.alpha = alpha
879
+ self.Gm = None
880
+
881
+ if max_rank is None:
882
+ max_rank = np.inf
883
+ self.max_rank = max_rank
884
+
885
+ if isinstance(reduction_method, str):
886
+ reduce_params = ()
887
+ else:
888
+ reduce_params = reduction_method[1:]
889
+ reduction_method = reduction_method[0]
890
+ reduce_params = (max_rank - 1,) + reduce_params
891
+
892
+ if reduction_method == 'svd':
893
+ self._reduce = lambda: self.Gm.svd_reduce(*reduce_params)
894
+ elif reduction_method == 'simple':
895
+ self._reduce = lambda: self.Gm.simple_reduce(*reduce_params)
896
+ elif reduction_method == 'restart':
897
+ self._reduce = lambda: self.Gm.restart_reduce(*reduce_params)
898
+ else:
899
+ raise ValueError("Unknown rank reduction method '%s'" %
900
+ reduction_method)
901
+
902
+ def setup(self, x, F, func):
903
+ GenericBroyden.setup(self, x, F, func)
904
+ self.Gm = LowRankMatrix(-self.alpha, self.shape[0], self.dtype)
905
+
906
+ def todense(self):
907
+ return inv(self.Gm)
908
+
909
+ def solve(self, f, tol=0):
910
+ r = self.Gm.matvec(f)
911
+ if not np.isfinite(r).all():
912
+ # singular; reset the Jacobian approximation
913
+ self.setup(self.last_x, self.last_f, self.func)
914
+ return self.Gm.matvec(f)
915
+ return r
916
+
917
+ def matvec(self, f):
918
+ return self.Gm.solve(f)
919
+
920
+ def rsolve(self, f, tol=0):
921
+ return self.Gm.rmatvec(f)
922
+
923
+ def rmatvec(self, f):
924
+ return self.Gm.rsolve(f)
925
+
926
+ def _update(self, x, f, dx, df, dx_norm, df_norm):
927
+ self._reduce() # reduce first to preserve secant condition
928
+
929
+ v = self.Gm.rmatvec(dx)
930
+ c = dx - self.Gm.matvec(df)
931
+ d = v / vdot(df, v)
932
+
933
+ self.Gm.append(c, d)
934
+
935
+
936
+ class BroydenSecond(BroydenFirst):
937
+ """
938
+ Find a root of a function, using Broyden\'s second Jacobian approximation.
939
+
940
+ This method is also known as \"Broyden's bad method\".
941
+
942
+ Parameters
943
+ ----------
944
+ %(params_basic)s
945
+ %(broyden_params)s
946
+ %(params_extra)s
947
+
948
+ See Also
949
+ --------
950
+ root : Interface to root finding algorithms for multivariate
951
+ functions. See ``method='broyden2'`` in particular.
952
+
953
+ Notes
954
+ -----
955
+ This algorithm implements the inverse Jacobian Quasi-Newton update
956
+
957
+ .. math:: H_+ = H + (dx - H df) df^\\dagger / ( df^\\dagger df)
958
+
959
+ corresponding to Broyden's second method.
960
+
961
+ References
962
+ ----------
963
+ .. [1] B.A. van der Rotten, PhD thesis,
964
+ \"A limited memory Broyden method to solve high-dimensional
965
+ systems of nonlinear equations\". Mathematisch Instituut,
966
+ Universiteit Leiden, The Netherlands (2003).
967
+
968
+ https://web.archive.org/web/20161022015821/http://www.math.leidenuniv.nl/scripties/Rotten.pdf
969
+
970
+ Examples
971
+ --------
972
+ The following functions define a system of nonlinear equations
973
+
974
+ >>> def fun(x):
975
+ ... return [x[0] + 0.5 * (x[0] - x[1])**3 - 1.0,
976
+ ... 0.5 * (x[1] - x[0])**3 + x[1]]
977
+
978
+ A solution can be obtained as follows.
979
+
980
+ >>> from scipy import optimize
981
+ >>> sol = optimize.broyden2(fun, [0, 0])
982
+ >>> sol
983
+ array([0.84116365, 0.15883529])
984
+
985
+ """
986
+
987
+ def _update(self, x, f, dx, df, dx_norm, df_norm):
988
+ self._reduce() # reduce first to preserve secant condition
989
+
990
+ v = df
991
+ c = dx - self.Gm.matvec(df)
992
+ d = v / df_norm**2
993
+ self.Gm.append(c, d)
994
+
995
+
996
+ #------------------------------------------------------------------------------
997
+ # Broyden-like (restricted memory)
998
+ #------------------------------------------------------------------------------
999
+
1000
+ class Anderson(GenericBroyden):
1001
+ """
1002
+ Find a root of a function, using (extended) Anderson mixing.
1003
+
1004
+ The Jacobian is formed by for a 'best' solution in the space
1005
+ spanned by last `M` vectors. As a result, only a MxM matrix
1006
+ inversions and MxN multiplications are required. [Ey]_
1007
+
1008
+ Parameters
1009
+ ----------
1010
+ %(params_basic)s
1011
+ alpha : float, optional
1012
+ Initial guess for the Jacobian is (-1/alpha).
1013
+ M : float, optional
1014
+ Number of previous vectors to retain. Defaults to 5.
1015
+ w0 : float, optional
1016
+ Regularization parameter for numerical stability.
1017
+ Compared to unity, good values of the order of 0.01.
1018
+ %(params_extra)s
1019
+
1020
+ See Also
1021
+ --------
1022
+ root : Interface to root finding algorithms for multivariate
1023
+ functions. See ``method='anderson'`` in particular.
1024
+
1025
+ References
1026
+ ----------
1027
+ .. [Ey] V. Eyert, J. Comp. Phys., 124, 271 (1996).
1028
+
1029
+ Examples
1030
+ --------
1031
+ The following functions define a system of nonlinear equations
1032
+
1033
+ >>> def fun(x):
1034
+ ... return [x[0] + 0.5 * (x[0] - x[1])**3 - 1.0,
1035
+ ... 0.5 * (x[1] - x[0])**3 + x[1]]
1036
+
1037
+ A solution can be obtained as follows.
1038
+
1039
+ >>> from scipy import optimize
1040
+ >>> sol = optimize.anderson(fun, [0, 0])
1041
+ >>> sol
1042
+ array([0.84116588, 0.15883789])
1043
+
1044
+ """
1045
+
1046
+ # Note:
1047
+ #
1048
+ # Anderson method maintains a rank M approximation of the inverse Jacobian,
1049
+ #
1050
+ # J^-1 v ~ -v*alpha + (dX + alpha dF) A^-1 dF^H v
1051
+ # A = W + dF^H dF
1052
+ # W = w0^2 diag(dF^H dF)
1053
+ #
1054
+ # so that for w0 = 0 the secant condition applies for last M iterates, i.e.,
1055
+ #
1056
+ # J^-1 df_j = dx_j
1057
+ #
1058
+ # for all j = 0 ... M-1.
1059
+ #
1060
+ # Moreover, (from Sherman-Morrison-Woodbury formula)
1061
+ #
1062
+ # J v ~ [ b I - b^2 C (I + b dF^H A^-1 C)^-1 dF^H ] v
1063
+ # C = (dX + alpha dF) A^-1
1064
+ # b = -1/alpha
1065
+ #
1066
+ # and after simplification
1067
+ #
1068
+ # J v ~ -v/alpha + (dX/alpha + dF) (dF^H dX - alpha W)^-1 dF^H v
1069
+ #
1070
+
1071
+ def __init__(self, alpha=None, w0=0.01, M=5):
1072
+ GenericBroyden.__init__(self)
1073
+ self.alpha = alpha
1074
+ self.M = M
1075
+ self.dx = []
1076
+ self.df = []
1077
+ self.gamma = None
1078
+ self.w0 = w0
1079
+
1080
+ def solve(self, f, tol=0):
1081
+ dx = -self.alpha*f
1082
+
1083
+ n = len(self.dx)
1084
+ if n == 0:
1085
+ return dx
1086
+
1087
+ df_f = np.empty(n, dtype=f.dtype)
1088
+ for k in range(n):
1089
+ df_f[k] = vdot(self.df[k], f)
1090
+
1091
+ try:
1092
+ gamma = solve(self.a, df_f)
1093
+ except LinAlgError:
1094
+ # singular; reset the Jacobian approximation
1095
+ del self.dx[:]
1096
+ del self.df[:]
1097
+ return dx
1098
+
1099
+ for m in range(n):
1100
+ dx += gamma[m]*(self.dx[m] + self.alpha*self.df[m])
1101
+ return dx
1102
+
1103
+ def matvec(self, f):
1104
+ dx = -f/self.alpha
1105
+
1106
+ n = len(self.dx)
1107
+ if n == 0:
1108
+ return dx
1109
+
1110
+ df_f = np.empty(n, dtype=f.dtype)
1111
+ for k in range(n):
1112
+ df_f[k] = vdot(self.df[k], f)
1113
+
1114
+ b = np.empty((n, n), dtype=f.dtype)
1115
+ for i in range(n):
1116
+ for j in range(n):
1117
+ b[i,j] = vdot(self.df[i], self.dx[j])
1118
+ if i == j and self.w0 != 0:
1119
+ b[i,j] -= vdot(self.df[i], self.df[i])*self.w0**2*self.alpha
1120
+ gamma = solve(b, df_f)
1121
+
1122
+ for m in range(n):
1123
+ dx += gamma[m]*(self.df[m] + self.dx[m]/self.alpha)
1124
+ return dx
1125
+
1126
+ def _update(self, x, f, dx, df, dx_norm, df_norm):
1127
+ if self.M == 0:
1128
+ return
1129
+
1130
+ self.dx.append(dx)
1131
+ self.df.append(df)
1132
+
1133
+ while len(self.dx) > self.M:
1134
+ self.dx.pop(0)
1135
+ self.df.pop(0)
1136
+
1137
+ n = len(self.dx)
1138
+ a = np.zeros((n, n), dtype=f.dtype)
1139
+
1140
+ for i in range(n):
1141
+ for j in range(i, n):
1142
+ if i == j:
1143
+ wd = self.w0**2
1144
+ else:
1145
+ wd = 0
1146
+ a[i,j] = (1+wd)*vdot(self.df[i], self.df[j])
1147
+
1148
+ a += np.triu(a, 1).T.conj()
1149
+ self.a = a
1150
+
1151
+ #------------------------------------------------------------------------------
1152
+ # Simple iterations
1153
+ #------------------------------------------------------------------------------
1154
+
1155
+
1156
+ class DiagBroyden(GenericBroyden):
1157
+ """
1158
+ Find a root of a function, using diagonal Broyden Jacobian approximation.
1159
+
1160
+ The Jacobian approximation is derived from previous iterations, by
1161
+ retaining only the diagonal of Broyden matrices.
1162
+
1163
+ .. warning::
1164
+
1165
+ This algorithm may be useful for specific problems, but whether
1166
+ it will work may depend strongly on the problem.
1167
+
1168
+ Parameters
1169
+ ----------
1170
+ %(params_basic)s
1171
+ alpha : float, optional
1172
+ Initial guess for the Jacobian is (-1/alpha).
1173
+ %(params_extra)s
1174
+
1175
+ See Also
1176
+ --------
1177
+ root : Interface to root finding algorithms for multivariate
1178
+ functions. See ``method='diagbroyden'`` in particular.
1179
+
1180
+ Examples
1181
+ --------
1182
+ The following functions define a system of nonlinear equations
1183
+
1184
+ >>> def fun(x):
1185
+ ... return [x[0] + 0.5 * (x[0] - x[1])**3 - 1.0,
1186
+ ... 0.5 * (x[1] - x[0])**3 + x[1]]
1187
+
1188
+ A solution can be obtained as follows.
1189
+
1190
+ >>> from scipy import optimize
1191
+ >>> sol = optimize.diagbroyden(fun, [0, 0])
1192
+ >>> sol
1193
+ array([0.84116403, 0.15883384])
1194
+
1195
+ """
1196
+
1197
+ def __init__(self, alpha=None):
1198
+ GenericBroyden.__init__(self)
1199
+ self.alpha = alpha
1200
+
1201
+ def setup(self, x, F, func):
1202
+ GenericBroyden.setup(self, x, F, func)
1203
+ self.d = np.full((self.shape[0],), 1 / self.alpha, dtype=self.dtype)
1204
+
1205
+ def solve(self, f, tol=0):
1206
+ return -f / self.d
1207
+
1208
+ def matvec(self, f):
1209
+ return -f * self.d
1210
+
1211
+ def rsolve(self, f, tol=0):
1212
+ return -f / self.d.conj()
1213
+
1214
+ def rmatvec(self, f):
1215
+ return -f * self.d.conj()
1216
+
1217
+ def todense(self):
1218
+ return np.diag(-self.d)
1219
+
1220
+ def _update(self, x, f, dx, df, dx_norm, df_norm):
1221
+ self.d -= (df + self.d*dx)*dx/dx_norm**2
1222
+
1223
+
1224
+ class LinearMixing(GenericBroyden):
1225
+ """
1226
+ Find a root of a function, using a scalar Jacobian approximation.
1227
+
1228
+ .. warning::
1229
+
1230
+ This algorithm may be useful for specific problems, but whether
1231
+ it will work may depend strongly on the problem.
1232
+
1233
+ Parameters
1234
+ ----------
1235
+ %(params_basic)s
1236
+ alpha : float, optional
1237
+ The Jacobian approximation is (-1/alpha).
1238
+ %(params_extra)s
1239
+
1240
+ See Also
1241
+ --------
1242
+ root : Interface to root finding algorithms for multivariate
1243
+ functions. See ``method='linearmixing'`` in particular.
1244
+
1245
+ """
1246
+
1247
+ def __init__(self, alpha=None):
1248
+ GenericBroyden.__init__(self)
1249
+ self.alpha = alpha
1250
+
1251
+ def solve(self, f, tol=0):
1252
+ return -f*self.alpha
1253
+
1254
+ def matvec(self, f):
1255
+ return -f/self.alpha
1256
+
1257
+ def rsolve(self, f, tol=0):
1258
+ return -f*np.conj(self.alpha)
1259
+
1260
+ def rmatvec(self, f):
1261
+ return -f/np.conj(self.alpha)
1262
+
1263
+ def todense(self):
1264
+ return np.diag(np.full(self.shape[0], -1/self.alpha))
1265
+
1266
+ def _update(self, x, f, dx, df, dx_norm, df_norm):
1267
+ pass
1268
+
1269
+
1270
+ class ExcitingMixing(GenericBroyden):
1271
+ """
1272
+ Find a root of a function, using a tuned diagonal Jacobian approximation.
1273
+
1274
+ The Jacobian matrix is diagonal and is tuned on each iteration.
1275
+
1276
+ .. warning::
1277
+
1278
+ This algorithm may be useful for specific problems, but whether
1279
+ it will work may depend strongly on the problem.
1280
+
1281
+ See Also
1282
+ --------
1283
+ root : Interface to root finding algorithms for multivariate
1284
+ functions. See ``method='excitingmixing'`` in particular.
1285
+
1286
+ Parameters
1287
+ ----------
1288
+ %(params_basic)s
1289
+ alpha : float, optional
1290
+ Initial Jacobian approximation is (-1/alpha).
1291
+ alphamax : float, optional
1292
+ The entries of the diagonal Jacobian are kept in the range
1293
+ ``[alpha, alphamax]``.
1294
+ %(params_extra)s
1295
+ """
1296
+
1297
+ def __init__(self, alpha=None, alphamax=1.0):
1298
+ GenericBroyden.__init__(self)
1299
+ self.alpha = alpha
1300
+ self.alphamax = alphamax
1301
+ self.beta = None
1302
+
1303
+ def setup(self, x, F, func):
1304
+ GenericBroyden.setup(self, x, F, func)
1305
+ self.beta = np.full((self.shape[0],), self.alpha, dtype=self.dtype)
1306
+
1307
+ def solve(self, f, tol=0):
1308
+ return -f*self.beta
1309
+
1310
+ def matvec(self, f):
1311
+ return -f/self.beta
1312
+
1313
+ def rsolve(self, f, tol=0):
1314
+ return -f*self.beta.conj()
1315
+
1316
+ def rmatvec(self, f):
1317
+ return -f/self.beta.conj()
1318
+
1319
+ def todense(self):
1320
+ return np.diag(-1/self.beta)
1321
+
1322
+ def _update(self, x, f, dx, df, dx_norm, df_norm):
1323
+ incr = f*self.last_f > 0
1324
+ self.beta[incr] += self.alpha
1325
+ self.beta[~incr] = self.alpha
1326
+ np.clip(self.beta, 0, self.alphamax, out=self.beta)
1327
+
1328
+
1329
+ #------------------------------------------------------------------------------
1330
+ # Iterative/Krylov approximated Jacobians
1331
+ #------------------------------------------------------------------------------
1332
+
1333
+ class KrylovJacobian(Jacobian):
1334
+ r"""
1335
+ Find a root of a function, using Krylov approximation for inverse Jacobian.
1336
+
1337
+ This method is suitable for solving large-scale problems.
1338
+
1339
+ Parameters
1340
+ ----------
1341
+ %(params_basic)s
1342
+ rdiff : float, optional
1343
+ Relative step size to use in numerical differentiation.
1344
+ method : str or callable, optional
1345
+ Krylov method to use to approximate the Jacobian. Can be a string,
1346
+ or a function implementing the same interface as the iterative
1347
+ solvers in `scipy.sparse.linalg`. If a string, needs to be one of:
1348
+ ``'lgmres'``, ``'gmres'``, ``'bicgstab'``, ``'cgs'``, ``'minres'``,
1349
+ ``'tfqmr'``.
1350
+
1351
+ The default is `scipy.sparse.linalg.lgmres`.
1352
+ inner_maxiter : int, optional
1353
+ Parameter to pass to the "inner" Krylov solver: maximum number of
1354
+ iterations. Iteration will stop after maxiter steps even if the
1355
+ specified tolerance has not been achieved.
1356
+ inner_M : LinearOperator or InverseJacobian
1357
+ Preconditioner for the inner Krylov iteration.
1358
+ Note that you can use also inverse Jacobians as (adaptive)
1359
+ preconditioners. For example,
1360
+
1361
+ >>> from scipy.optimize import BroydenFirst, KrylovJacobian
1362
+ >>> from scipy.optimize import InverseJacobian
1363
+ >>> jac = BroydenFirst()
1364
+ >>> kjac = KrylovJacobian(inner_M=InverseJacobian(jac))
1365
+
1366
+ If the preconditioner has a method named 'update', it will be called
1367
+ as ``update(x, f)`` after each nonlinear step, with ``x`` giving
1368
+ the current point, and ``f`` the current function value.
1369
+ outer_k : int, optional
1370
+ Size of the subspace kept across LGMRES nonlinear iterations.
1371
+ See `scipy.sparse.linalg.lgmres` for details.
1372
+ inner_kwargs : kwargs
1373
+ Keyword parameters for the "inner" Krylov solver
1374
+ (defined with `method`). Parameter names must start with
1375
+ the `inner_` prefix which will be stripped before passing on
1376
+ the inner method. See, e.g., `scipy.sparse.linalg.gmres` for details.
1377
+ %(params_extra)s
1378
+
1379
+ See Also
1380
+ --------
1381
+ root : Interface to root finding algorithms for multivariate
1382
+ functions. See ``method='krylov'`` in particular.
1383
+ scipy.sparse.linalg.gmres
1384
+ scipy.sparse.linalg.lgmres
1385
+
1386
+ Notes
1387
+ -----
1388
+ This function implements a Newton-Krylov solver. The basic idea is
1389
+ to compute the inverse of the Jacobian with an iterative Krylov
1390
+ method. These methods require only evaluating the Jacobian-vector
1391
+ products, which are conveniently approximated by a finite difference:
1392
+
1393
+ .. math:: J v \approx (f(x + \omega*v/|v|) - f(x)) / \omega
1394
+
1395
+ Due to the use of iterative matrix inverses, these methods can
1396
+ deal with large nonlinear problems.
1397
+
1398
+ SciPy's `scipy.sparse.linalg` module offers a selection of Krylov
1399
+ solvers to choose from. The default here is `lgmres`, which is a
1400
+ variant of restarted GMRES iteration that reuses some of the
1401
+ information obtained in the previous Newton steps to invert
1402
+ Jacobians in subsequent steps.
1403
+
1404
+ For a review on Newton-Krylov methods, see for example [1]_,
1405
+ and for the LGMRES sparse inverse method, see [2]_.
1406
+
1407
+ References
1408
+ ----------
1409
+ .. [1] C. T. Kelley, Solving Nonlinear Equations with Newton's Method,
1410
+ SIAM, pp.57-83, 2003.
1411
+ :doi:`10.1137/1.9780898718898.ch3`
1412
+ .. [2] D.A. Knoll and D.E. Keyes, J. Comp. Phys. 193, 357 (2004).
1413
+ :doi:`10.1016/j.jcp.2003.08.010`
1414
+ .. [3] A.H. Baker and E.R. Jessup and T. Manteuffel,
1415
+ SIAM J. Matrix Anal. Appl. 26, 962 (2005).
1416
+ :doi:`10.1137/S0895479803422014`
1417
+
1418
+ Examples
1419
+ --------
1420
+ The following functions define a system of nonlinear equations
1421
+
1422
+ >>> def fun(x):
1423
+ ... return [x[0] + 0.5 * x[1] - 1.0,
1424
+ ... 0.5 * (x[1] - x[0]) ** 2]
1425
+
1426
+ A solution can be obtained as follows.
1427
+
1428
+ >>> from scipy import optimize
1429
+ >>> sol = optimize.newton_krylov(fun, [0, 0])
1430
+ >>> sol
1431
+ array([0.66731771, 0.66536458])
1432
+
1433
+ """
1434
+
1435
+ def __init__(self, rdiff=None, method='lgmres', inner_maxiter=20,
1436
+ inner_M=None, outer_k=10, **kw):
1437
+ self.preconditioner = inner_M
1438
+ self.rdiff = rdiff
1439
+ # Note that this retrieves one of the named functions, or otherwise
1440
+ # uses `method` as is (i.e., for a user-provided callable).
1441
+ self.method = dict(
1442
+ bicgstab=scipy.sparse.linalg.bicgstab,
1443
+ gmres=scipy.sparse.linalg.gmres,
1444
+ lgmres=scipy.sparse.linalg.lgmres,
1445
+ cgs=scipy.sparse.linalg.cgs,
1446
+ minres=scipy.sparse.linalg.minres,
1447
+ tfqmr=scipy.sparse.linalg.tfqmr,
1448
+ ).get(method, method)
1449
+
1450
+ self.method_kw = dict(maxiter=inner_maxiter, M=self.preconditioner)
1451
+
1452
+ if self.method is scipy.sparse.linalg.gmres:
1453
+ # Replace GMRES's outer iteration with Newton steps
1454
+ self.method_kw['restart'] = inner_maxiter
1455
+ self.method_kw['maxiter'] = 1
1456
+ self.method_kw.setdefault('atol', 0)
1457
+ elif self.method in (scipy.sparse.linalg.gcrotmk,
1458
+ scipy.sparse.linalg.bicgstab,
1459
+ scipy.sparse.linalg.cgs):
1460
+ self.method_kw.setdefault('atol', 0)
1461
+ elif self.method is scipy.sparse.linalg.lgmres:
1462
+ self.method_kw['outer_k'] = outer_k
1463
+ # Replace LGMRES's outer iteration with Newton steps
1464
+ self.method_kw['maxiter'] = 1
1465
+ # Carry LGMRES's `outer_v` vectors across nonlinear iterations
1466
+ self.method_kw.setdefault('outer_v', [])
1467
+ self.method_kw.setdefault('prepend_outer_v', True)
1468
+ # But don't carry the corresponding Jacobian*v products, in case
1469
+ # the Jacobian changes a lot in the nonlinear step
1470
+ #
1471
+ # XXX: some trust-region inspired ideas might be more efficient...
1472
+ # See e.g., Brown & Saad. But needs to be implemented separately
1473
+ # since it's not an inexact Newton method.
1474
+ self.method_kw.setdefault('store_outer_Av', False)
1475
+ self.method_kw.setdefault('atol', 0)
1476
+
1477
+ for key, value in kw.items():
1478
+ if not key.startswith('inner_'):
1479
+ raise ValueError("Unknown parameter %s" % key)
1480
+ self.method_kw[key[6:]] = value
1481
+
1482
+ def _update_diff_step(self):
1483
+ mx = abs(self.x0).max()
1484
+ mf = abs(self.f0).max()
1485
+ self.omega = self.rdiff * max(1, mx) / max(1, mf)
1486
+
1487
+ def matvec(self, v):
1488
+ nv = norm(v)
1489
+ if nv == 0:
1490
+ return 0*v
1491
+ sc = self.omega / nv
1492
+ r = (self.func(self.x0 + sc*v) - self.f0) / sc
1493
+ if not np.all(np.isfinite(r)) and np.all(np.isfinite(v)):
1494
+ raise ValueError('Function returned non-finite results')
1495
+ return r
1496
+
1497
+ def solve(self, rhs, tol=0):
1498
+ if 'rtol' in self.method_kw:
1499
+ sol, info = self.method(self.op, rhs, **self.method_kw)
1500
+ else:
1501
+ sol, info = self.method(self.op, rhs, rtol=tol, **self.method_kw)
1502
+ return sol
1503
+
1504
+ def update(self, x, f):
1505
+ self.x0 = x
1506
+ self.f0 = f
1507
+ self._update_diff_step()
1508
+
1509
+ # Update also the preconditioner, if possible
1510
+ if self.preconditioner is not None:
1511
+ if hasattr(self.preconditioner, 'update'):
1512
+ self.preconditioner.update(x, f)
1513
+
1514
+ def setup(self, x, f, func):
1515
+ Jacobian.setup(self, x, f, func)
1516
+ self.x0 = x
1517
+ self.f0 = f
1518
+ self.op = scipy.sparse.linalg.aslinearoperator(self)
1519
+
1520
+ if self.rdiff is None:
1521
+ self.rdiff = np.finfo(x.dtype).eps ** (1./2)
1522
+
1523
+ self._update_diff_step()
1524
+
1525
+ # Setup also the preconditioner, if possible
1526
+ if self.preconditioner is not None:
1527
+ if hasattr(self.preconditioner, 'setup'):
1528
+ self.preconditioner.setup(x, f, func)
1529
+
1530
+
1531
+ #------------------------------------------------------------------------------
1532
+ # Wrapper functions
1533
+ #------------------------------------------------------------------------------
1534
+
1535
+ def _nonlin_wrapper(name, jac):
1536
+ """
1537
+ Construct a solver wrapper with given name and Jacobian approx.
1538
+
1539
+ It inspects the keyword arguments of ``jac.__init__``, and allows to
1540
+ use the same arguments in the wrapper function, in addition to the
1541
+ keyword arguments of `nonlin_solve`
1542
+
1543
+ """
1544
+ signature = _getfullargspec(jac.__init__)
1545
+ args, varargs, varkw, defaults, kwonlyargs, kwdefaults, _ = signature
1546
+ kwargs = list(zip(args[-len(defaults):], defaults))
1547
+ kw_str = ", ".join([f"{k}={v!r}" for k, v in kwargs])
1548
+ if kw_str:
1549
+ kw_str = ", " + kw_str
1550
+ kwkw_str = ", ".join([f"{k}={k}" for k, v in kwargs])
1551
+ if kwkw_str:
1552
+ kwkw_str = kwkw_str + ", "
1553
+ if kwonlyargs:
1554
+ raise ValueError('Unexpected signature %s' % signature)
1555
+
1556
+ # Construct the wrapper function so that its keyword arguments
1557
+ # are visible in pydoc.help etc.
1558
+ wrapper = """
1559
+ def %(name)s(F, xin, iter=None %(kw)s, verbose=False, maxiter=None,
1560
+ f_tol=None, f_rtol=None, x_tol=None, x_rtol=None,
1561
+ tol_norm=None, line_search='armijo', callback=None, **kw):
1562
+ jac = %(jac)s(%(kwkw)s **kw)
1563
+ return nonlin_solve(F, xin, jac, iter, verbose, maxiter,
1564
+ f_tol, f_rtol, x_tol, x_rtol, tol_norm, line_search,
1565
+ callback)
1566
+ """
1567
+
1568
+ wrapper = wrapper % dict(name=name, kw=kw_str, jac=jac.__name__,
1569
+ kwkw=kwkw_str)
1570
+ ns = {}
1571
+ ns.update(globals())
1572
+ exec(wrapper, ns)
1573
+ func = ns[name]
1574
+ func.__doc__ = jac.__doc__
1575
+ _set_doc(func)
1576
+ return func
1577
+
1578
+
1579
+ broyden1 = _nonlin_wrapper('broyden1', BroydenFirst)
1580
+ broyden2 = _nonlin_wrapper('broyden2', BroydenSecond)
1581
+ anderson = _nonlin_wrapper('anderson', Anderson)
1582
+ linearmixing = _nonlin_wrapper('linearmixing', LinearMixing)
1583
+ diagbroyden = _nonlin_wrapper('diagbroyden', DiagBroyden)
1584
+ excitingmixing = _nonlin_wrapper('excitingmixing', ExcitingMixing)
1585
+ newton_krylov = _nonlin_wrapper('newton_krylov', KrylovJacobian)
vila/lib/python3.10/site-packages/scipy/optimize/_numdiff.py ADDED
@@ -0,0 +1,779 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Routines for numerical differentiation."""
2
+ import functools
3
+ import numpy as np
4
+ from numpy.linalg import norm
5
+
6
+ from scipy.sparse.linalg import LinearOperator
7
+ from ..sparse import issparse, csc_matrix, csr_matrix, coo_matrix, find
8
+ from ._group_columns import group_dense, group_sparse
9
+ from scipy._lib._array_api import atleast_nd, array_namespace
10
+
11
+
12
+ def _adjust_scheme_to_bounds(x0, h, num_steps, scheme, lb, ub):
13
+ """Adjust final difference scheme to the presence of bounds.
14
+
15
+ Parameters
16
+ ----------
17
+ x0 : ndarray, shape (n,)
18
+ Point at which we wish to estimate derivative.
19
+ h : ndarray, shape (n,)
20
+ Desired absolute finite difference steps.
21
+ num_steps : int
22
+ Number of `h` steps in one direction required to implement finite
23
+ difference scheme. For example, 2 means that we need to evaluate
24
+ f(x0 + 2 * h) or f(x0 - 2 * h)
25
+ scheme : {'1-sided', '2-sided'}
26
+ Whether steps in one or both directions are required. In other
27
+ words '1-sided' applies to forward and backward schemes, '2-sided'
28
+ applies to center schemes.
29
+ lb : ndarray, shape (n,)
30
+ Lower bounds on independent variables.
31
+ ub : ndarray, shape (n,)
32
+ Upper bounds on independent variables.
33
+
34
+ Returns
35
+ -------
36
+ h_adjusted : ndarray, shape (n,)
37
+ Adjusted absolute step sizes. Step size decreases only if a sign flip
38
+ or switching to one-sided scheme doesn't allow to take a full step.
39
+ use_one_sided : ndarray of bool, shape (n,)
40
+ Whether to switch to one-sided scheme. Informative only for
41
+ ``scheme='2-sided'``.
42
+ """
43
+ if scheme == '1-sided':
44
+ use_one_sided = np.ones_like(h, dtype=bool)
45
+ elif scheme == '2-sided':
46
+ h = np.abs(h)
47
+ use_one_sided = np.zeros_like(h, dtype=bool)
48
+ else:
49
+ raise ValueError("`scheme` must be '1-sided' or '2-sided'.")
50
+
51
+ if np.all((lb == -np.inf) & (ub == np.inf)):
52
+ return h, use_one_sided
53
+
54
+ h_total = h * num_steps
55
+ h_adjusted = h.copy()
56
+
57
+ lower_dist = x0 - lb
58
+ upper_dist = ub - x0
59
+
60
+ if scheme == '1-sided':
61
+ x = x0 + h_total
62
+ violated = (x < lb) | (x > ub)
63
+ fitting = np.abs(h_total) <= np.maximum(lower_dist, upper_dist)
64
+ h_adjusted[violated & fitting] *= -1
65
+
66
+ forward = (upper_dist >= lower_dist) & ~fitting
67
+ h_adjusted[forward] = upper_dist[forward] / num_steps
68
+ backward = (upper_dist < lower_dist) & ~fitting
69
+ h_adjusted[backward] = -lower_dist[backward] / num_steps
70
+ elif scheme == '2-sided':
71
+ central = (lower_dist >= h_total) & (upper_dist >= h_total)
72
+
73
+ forward = (upper_dist >= lower_dist) & ~central
74
+ h_adjusted[forward] = np.minimum(
75
+ h[forward], 0.5 * upper_dist[forward] / num_steps)
76
+ use_one_sided[forward] = True
77
+
78
+ backward = (upper_dist < lower_dist) & ~central
79
+ h_adjusted[backward] = -np.minimum(
80
+ h[backward], 0.5 * lower_dist[backward] / num_steps)
81
+ use_one_sided[backward] = True
82
+
83
+ min_dist = np.minimum(upper_dist, lower_dist) / num_steps
84
+ adjusted_central = (~central & (np.abs(h_adjusted) <= min_dist))
85
+ h_adjusted[adjusted_central] = min_dist[adjusted_central]
86
+ use_one_sided[adjusted_central] = False
87
+
88
+ return h_adjusted, use_one_sided
89
+
90
+
91
+ @functools.lru_cache
92
+ def _eps_for_method(x0_dtype, f0_dtype, method):
93
+ """
94
+ Calculates relative EPS step to use for a given data type
95
+ and numdiff step method.
96
+
97
+ Progressively smaller steps are used for larger floating point types.
98
+
99
+ Parameters
100
+ ----------
101
+ f0_dtype: np.dtype
102
+ dtype of function evaluation
103
+
104
+ x0_dtype: np.dtype
105
+ dtype of parameter vector
106
+
107
+ method: {'2-point', '3-point', 'cs'}
108
+
109
+ Returns
110
+ -------
111
+ EPS: float
112
+ relative step size. May be np.float16, np.float32, np.float64
113
+
114
+ Notes
115
+ -----
116
+ The default relative step will be np.float64. However, if x0 or f0 are
117
+ smaller floating point types (np.float16, np.float32), then the smallest
118
+ floating point type is chosen.
119
+ """
120
+ # the default EPS value
121
+ EPS = np.finfo(np.float64).eps
122
+
123
+ x0_is_fp = False
124
+ if np.issubdtype(x0_dtype, np.inexact):
125
+ # if you're a floating point type then over-ride the default EPS
126
+ EPS = np.finfo(x0_dtype).eps
127
+ x0_itemsize = np.dtype(x0_dtype).itemsize
128
+ x0_is_fp = True
129
+
130
+ if np.issubdtype(f0_dtype, np.inexact):
131
+ f0_itemsize = np.dtype(f0_dtype).itemsize
132
+ # choose the smallest itemsize between x0 and f0
133
+ if x0_is_fp and f0_itemsize < x0_itemsize:
134
+ EPS = np.finfo(f0_dtype).eps
135
+
136
+ if method in ["2-point", "cs"]:
137
+ return EPS**0.5
138
+ elif method in ["3-point"]:
139
+ return EPS**(1/3)
140
+ else:
141
+ raise RuntimeError("Unknown step method, should be one of "
142
+ "{'2-point', '3-point', 'cs'}")
143
+
144
+
145
+ def _compute_absolute_step(rel_step, x0, f0, method):
146
+ """
147
+ Computes an absolute step from a relative step for finite difference
148
+ calculation.
149
+
150
+ Parameters
151
+ ----------
152
+ rel_step: None or array-like
153
+ Relative step for the finite difference calculation
154
+ x0 : np.ndarray
155
+ Parameter vector
156
+ f0 : np.ndarray or scalar
157
+ method : {'2-point', '3-point', 'cs'}
158
+
159
+ Returns
160
+ -------
161
+ h : float
162
+ The absolute step size
163
+
164
+ Notes
165
+ -----
166
+ `h` will always be np.float64. However, if `x0` or `f0` are
167
+ smaller floating point dtypes (e.g. np.float32), then the absolute
168
+ step size will be calculated from the smallest floating point size.
169
+ """
170
+ # this is used instead of np.sign(x0) because we need
171
+ # sign_x0 to be 1 when x0 == 0.
172
+ sign_x0 = (x0 >= 0).astype(float) * 2 - 1
173
+
174
+ rstep = _eps_for_method(x0.dtype, f0.dtype, method)
175
+
176
+ if rel_step is None:
177
+ abs_step = rstep * sign_x0 * np.maximum(1.0, np.abs(x0))
178
+ else:
179
+ # User has requested specific relative steps.
180
+ # Don't multiply by max(1, abs(x0) because if x0 < 1 then their
181
+ # requested step is not used.
182
+ abs_step = rel_step * sign_x0 * np.abs(x0)
183
+
184
+ # however we don't want an abs_step of 0, which can happen if
185
+ # rel_step is 0, or x0 is 0. Instead, substitute a realistic step
186
+ dx = ((x0 + abs_step) - x0)
187
+ abs_step = np.where(dx == 0,
188
+ rstep * sign_x0 * np.maximum(1.0, np.abs(x0)),
189
+ abs_step)
190
+
191
+ return abs_step
192
+
193
+
194
+ def _prepare_bounds(bounds, x0):
195
+ """
196
+ Prepares new-style bounds from a two-tuple specifying the lower and upper
197
+ limits for values in x0. If a value is not bound then the lower/upper bound
198
+ will be expected to be -np.inf/np.inf.
199
+
200
+ Examples
201
+ --------
202
+ >>> _prepare_bounds([(0, 1, 2), (1, 2, np.inf)], [0.5, 1.5, 2.5])
203
+ (array([0., 1., 2.]), array([ 1., 2., inf]))
204
+ """
205
+ lb, ub = (np.asarray(b, dtype=float) for b in bounds)
206
+ if lb.ndim == 0:
207
+ lb = np.resize(lb, x0.shape)
208
+
209
+ if ub.ndim == 0:
210
+ ub = np.resize(ub, x0.shape)
211
+
212
+ return lb, ub
213
+
214
+
215
+ def group_columns(A, order=0):
216
+ """Group columns of a 2-D matrix for sparse finite differencing [1]_.
217
+
218
+ Two columns are in the same group if in each row at least one of them
219
+ has zero. A greedy sequential algorithm is used to construct groups.
220
+
221
+ Parameters
222
+ ----------
223
+ A : array_like or sparse matrix, shape (m, n)
224
+ Matrix of which to group columns.
225
+ order : int, iterable of int with shape (n,) or None
226
+ Permutation array which defines the order of columns enumeration.
227
+ If int or None, a random permutation is used with `order` used as
228
+ a random seed. Default is 0, that is use a random permutation but
229
+ guarantee repeatability.
230
+
231
+ Returns
232
+ -------
233
+ groups : ndarray of int, shape (n,)
234
+ Contains values from 0 to n_groups-1, where n_groups is the number
235
+ of found groups. Each value ``groups[i]`` is an index of a group to
236
+ which ith column assigned. The procedure was helpful only if
237
+ n_groups is significantly less than n.
238
+
239
+ References
240
+ ----------
241
+ .. [1] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of
242
+ sparse Jacobian matrices", Journal of the Institute of Mathematics
243
+ and its Applications, 13 (1974), pp. 117-120.
244
+ """
245
+ if issparse(A):
246
+ A = csc_matrix(A)
247
+ else:
248
+ A = np.atleast_2d(A)
249
+ A = (A != 0).astype(np.int32)
250
+
251
+ if A.ndim != 2:
252
+ raise ValueError("`A` must be 2-dimensional.")
253
+
254
+ m, n = A.shape
255
+
256
+ if order is None or np.isscalar(order):
257
+ rng = np.random.RandomState(order)
258
+ order = rng.permutation(n)
259
+ else:
260
+ order = np.asarray(order)
261
+ if order.shape != (n,):
262
+ raise ValueError("`order` has incorrect shape.")
263
+
264
+ A = A[:, order]
265
+
266
+ if issparse(A):
267
+ groups = group_sparse(m, n, A.indices, A.indptr)
268
+ else:
269
+ groups = group_dense(m, n, A)
270
+
271
+ groups[order] = groups.copy()
272
+
273
+ return groups
274
+
275
+
276
+ def approx_derivative(fun, x0, method='3-point', rel_step=None, abs_step=None,
277
+ f0=None, bounds=(-np.inf, np.inf), sparsity=None,
278
+ as_linear_operator=False, args=(), kwargs={}):
279
+ """Compute finite difference approximation of the derivatives of a
280
+ vector-valued function.
281
+
282
+ If a function maps from R^n to R^m, its derivatives form m-by-n matrix
283
+ called the Jacobian, where an element (i, j) is a partial derivative of
284
+ f[i] with respect to x[j].
285
+
286
+ Parameters
287
+ ----------
288
+ fun : callable
289
+ Function of which to estimate the derivatives. The argument x
290
+ passed to this function is ndarray of shape (n,) (never a scalar
291
+ even if n=1). It must return 1-D array_like of shape (m,) or a scalar.
292
+ x0 : array_like of shape (n,) or float
293
+ Point at which to estimate the derivatives. Float will be converted
294
+ to a 1-D array.
295
+ method : {'3-point', '2-point', 'cs'}, optional
296
+ Finite difference method to use:
297
+ - '2-point' - use the first order accuracy forward or backward
298
+ difference.
299
+ - '3-point' - use central difference in interior points and the
300
+ second order accuracy forward or backward difference
301
+ near the boundary.
302
+ - 'cs' - use a complex-step finite difference scheme. This assumes
303
+ that the user function is real-valued and can be
304
+ analytically continued to the complex plane. Otherwise,
305
+ produces bogus results.
306
+ rel_step : None or array_like, optional
307
+ Relative step size to use. If None (default) the absolute step size is
308
+ computed as ``h = rel_step * sign(x0) * max(1, abs(x0))``, with
309
+ `rel_step` being selected automatically, see Notes. Otherwise
310
+ ``h = rel_step * sign(x0) * abs(x0)``. For ``method='3-point'`` the
311
+ sign of `h` is ignored. The calculated step size is possibly adjusted
312
+ to fit into the bounds.
313
+ abs_step : array_like, optional
314
+ Absolute step size to use, possibly adjusted to fit into the bounds.
315
+ For ``method='3-point'`` the sign of `abs_step` is ignored. By default
316
+ relative steps are used, only if ``abs_step is not None`` are absolute
317
+ steps used.
318
+ f0 : None or array_like, optional
319
+ If not None it is assumed to be equal to ``fun(x0)``, in this case
320
+ the ``fun(x0)`` is not called. Default is None.
321
+ bounds : tuple of array_like, optional
322
+ Lower and upper bounds on independent variables. Defaults to no bounds.
323
+ Each bound must match the size of `x0` or be a scalar, in the latter
324
+ case the bound will be the same for all variables. Use it to limit the
325
+ range of function evaluation. Bounds checking is not implemented
326
+ when `as_linear_operator` is True.
327
+ sparsity : {None, array_like, sparse matrix, 2-tuple}, optional
328
+ Defines a sparsity structure of the Jacobian matrix. If the Jacobian
329
+ matrix is known to have only few non-zero elements in each row, then
330
+ it's possible to estimate its several columns by a single function
331
+ evaluation [3]_. To perform such economic computations two ingredients
332
+ are required:
333
+
334
+ * structure : array_like or sparse matrix of shape (m, n). A zero
335
+ element means that a corresponding element of the Jacobian
336
+ identically equals to zero.
337
+ * groups : array_like of shape (n,). A column grouping for a given
338
+ sparsity structure, use `group_columns` to obtain it.
339
+
340
+ A single array or a sparse matrix is interpreted as a sparsity
341
+ structure, and groups are computed inside the function. A tuple is
342
+ interpreted as (structure, groups). If None (default), a standard
343
+ dense differencing will be used.
344
+
345
+ Note, that sparse differencing makes sense only for large Jacobian
346
+ matrices where each row contains few non-zero elements.
347
+ as_linear_operator : bool, optional
348
+ When True the function returns an `scipy.sparse.linalg.LinearOperator`.
349
+ Otherwise it returns a dense array or a sparse matrix depending on
350
+ `sparsity`. The linear operator provides an efficient way of computing
351
+ ``J.dot(p)`` for any vector ``p`` of shape (n,), but does not allow
352
+ direct access to individual elements of the matrix. By default
353
+ `as_linear_operator` is False.
354
+ args, kwargs : tuple and dict, optional
355
+ Additional arguments passed to `fun`. Both empty by default.
356
+ The calling signature is ``fun(x, *args, **kwargs)``.
357
+
358
+ Returns
359
+ -------
360
+ J : {ndarray, sparse matrix, LinearOperator}
361
+ Finite difference approximation of the Jacobian matrix.
362
+ If `as_linear_operator` is True returns a LinearOperator
363
+ with shape (m, n). Otherwise it returns a dense array or sparse
364
+ matrix depending on how `sparsity` is defined. If `sparsity`
365
+ is None then a ndarray with shape (m, n) is returned. If
366
+ `sparsity` is not None returns a csr_matrix with shape (m, n).
367
+ For sparse matrices and linear operators it is always returned as
368
+ a 2-D structure, for ndarrays, if m=1 it is returned
369
+ as a 1-D gradient array with shape (n,).
370
+
371
+ See Also
372
+ --------
373
+ check_derivative : Check correctness of a function computing derivatives.
374
+
375
+ Notes
376
+ -----
377
+ If `rel_step` is not provided, it assigned as ``EPS**(1/s)``, where EPS is
378
+ determined from the smallest floating point dtype of `x0` or `fun(x0)`,
379
+ ``np.finfo(x0.dtype).eps``, s=2 for '2-point' method and
380
+ s=3 for '3-point' method. Such relative step approximately minimizes a sum
381
+ of truncation and round-off errors, see [1]_. Relative steps are used by
382
+ default. However, absolute steps are used when ``abs_step is not None``.
383
+ If any of the absolute or relative steps produces an indistinguishable
384
+ difference from the original `x0`, ``(x0 + dx) - x0 == 0``, then a
385
+ automatic step size is substituted for that particular entry.
386
+
387
+ A finite difference scheme for '3-point' method is selected automatically.
388
+ The well-known central difference scheme is used for points sufficiently
389
+ far from the boundary, and 3-point forward or backward scheme is used for
390
+ points near the boundary. Both schemes have the second-order accuracy in
391
+ terms of Taylor expansion. Refer to [2]_ for the formulas of 3-point
392
+ forward and backward difference schemes.
393
+
394
+ For dense differencing when m=1 Jacobian is returned with a shape (n,),
395
+ on the other hand when n=1 Jacobian is returned with a shape (m, 1).
396
+ Our motivation is the following: a) It handles a case of gradient
397
+ computation (m=1) in a conventional way. b) It clearly separates these two
398
+ different cases. b) In all cases np.atleast_2d can be called to get 2-D
399
+ Jacobian with correct dimensions.
400
+
401
+ References
402
+ ----------
403
+ .. [1] W. H. Press et. al. "Numerical Recipes. The Art of Scientific
404
+ Computing. 3rd edition", sec. 5.7.
405
+
406
+ .. [2] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of
407
+ sparse Jacobian matrices", Journal of the Institute of Mathematics
408
+ and its Applications, 13 (1974), pp. 117-120.
409
+
410
+ .. [3] B. Fornberg, "Generation of Finite Difference Formulas on
411
+ Arbitrarily Spaced Grids", Mathematics of Computation 51, 1988.
412
+
413
+ Examples
414
+ --------
415
+ >>> import numpy as np
416
+ >>> from scipy.optimize._numdiff import approx_derivative
417
+ >>>
418
+ >>> def f(x, c1, c2):
419
+ ... return np.array([x[0] * np.sin(c1 * x[1]),
420
+ ... x[0] * np.cos(c2 * x[1])])
421
+ ...
422
+ >>> x0 = np.array([1.0, 0.5 * np.pi])
423
+ >>> approx_derivative(f, x0, args=(1, 2))
424
+ array([[ 1., 0.],
425
+ [-1., 0.]])
426
+
427
+ Bounds can be used to limit the region of function evaluation.
428
+ In the example below we compute left and right derivative at point 1.0.
429
+
430
+ >>> def g(x):
431
+ ... return x**2 if x >= 1 else x
432
+ ...
433
+ >>> x0 = 1.0
434
+ >>> approx_derivative(g, x0, bounds=(-np.inf, 1.0))
435
+ array([ 1.])
436
+ >>> approx_derivative(g, x0, bounds=(1.0, np.inf))
437
+ array([ 2.])
438
+ """
439
+ if method not in ['2-point', '3-point', 'cs']:
440
+ raise ValueError("Unknown method '%s'. " % method)
441
+
442
+ xp = array_namespace(x0)
443
+ _x = atleast_nd(x0, ndim=1, xp=xp)
444
+ _dtype = xp.float64
445
+ if xp.isdtype(_x.dtype, "real floating"):
446
+ _dtype = _x.dtype
447
+
448
+ # promotes to floating
449
+ x0 = xp.astype(_x, _dtype)
450
+
451
+ if x0.ndim > 1:
452
+ raise ValueError("`x0` must have at most 1 dimension.")
453
+
454
+ lb, ub = _prepare_bounds(bounds, x0)
455
+
456
+ if lb.shape != x0.shape or ub.shape != x0.shape:
457
+ raise ValueError("Inconsistent shapes between bounds and `x0`.")
458
+
459
+ if as_linear_operator and not (np.all(np.isinf(lb))
460
+ and np.all(np.isinf(ub))):
461
+ raise ValueError("Bounds not supported when "
462
+ "`as_linear_operator` is True.")
463
+
464
+ def fun_wrapped(x):
465
+ # send user function same fp type as x0. (but only if cs is not being
466
+ # used
467
+ if xp.isdtype(x.dtype, "real floating"):
468
+ x = xp.astype(x, x0.dtype)
469
+
470
+ f = np.atleast_1d(fun(x, *args, **kwargs))
471
+ if f.ndim > 1:
472
+ raise RuntimeError("`fun` return value has "
473
+ "more than 1 dimension.")
474
+ return f
475
+
476
+ if f0 is None:
477
+ f0 = fun_wrapped(x0)
478
+ else:
479
+ f0 = np.atleast_1d(f0)
480
+ if f0.ndim > 1:
481
+ raise ValueError("`f0` passed has more than 1 dimension.")
482
+
483
+ if np.any((x0 < lb) | (x0 > ub)):
484
+ raise ValueError("`x0` violates bound constraints.")
485
+
486
+ if as_linear_operator:
487
+ if rel_step is None:
488
+ rel_step = _eps_for_method(x0.dtype, f0.dtype, method)
489
+
490
+ return _linear_operator_difference(fun_wrapped, x0,
491
+ f0, rel_step, method)
492
+ else:
493
+ # by default we use rel_step
494
+ if abs_step is None:
495
+ h = _compute_absolute_step(rel_step, x0, f0, method)
496
+ else:
497
+ # user specifies an absolute step
498
+ sign_x0 = (x0 >= 0).astype(float) * 2 - 1
499
+ h = abs_step
500
+
501
+ # cannot have a zero step. This might happen if x0 is very large
502
+ # or small. In which case fall back to relative step.
503
+ dx = ((x0 + h) - x0)
504
+ h = np.where(dx == 0,
505
+ _eps_for_method(x0.dtype, f0.dtype, method) *
506
+ sign_x0 * np.maximum(1.0, np.abs(x0)),
507
+ h)
508
+
509
+ if method == '2-point':
510
+ h, use_one_sided = _adjust_scheme_to_bounds(
511
+ x0, h, 1, '1-sided', lb, ub)
512
+ elif method == '3-point':
513
+ h, use_one_sided = _adjust_scheme_to_bounds(
514
+ x0, h, 1, '2-sided', lb, ub)
515
+ elif method == 'cs':
516
+ use_one_sided = False
517
+
518
+ if sparsity is None:
519
+ return _dense_difference(fun_wrapped, x0, f0, h,
520
+ use_one_sided, method)
521
+ else:
522
+ if not issparse(sparsity) and len(sparsity) == 2:
523
+ structure, groups = sparsity
524
+ else:
525
+ structure = sparsity
526
+ groups = group_columns(sparsity)
527
+
528
+ if issparse(structure):
529
+ structure = csc_matrix(structure)
530
+ else:
531
+ structure = np.atleast_2d(structure)
532
+
533
+ groups = np.atleast_1d(groups)
534
+ return _sparse_difference(fun_wrapped, x0, f0, h,
535
+ use_one_sided, structure,
536
+ groups, method)
537
+
538
+
539
+ def _linear_operator_difference(fun, x0, f0, h, method):
540
+ m = f0.size
541
+ n = x0.size
542
+
543
+ if method == '2-point':
544
+ def matvec(p):
545
+ if np.array_equal(p, np.zeros_like(p)):
546
+ return np.zeros(m)
547
+ dx = h / norm(p)
548
+ x = x0 + dx*p
549
+ df = fun(x) - f0
550
+ return df / dx
551
+
552
+ elif method == '3-point':
553
+ def matvec(p):
554
+ if np.array_equal(p, np.zeros_like(p)):
555
+ return np.zeros(m)
556
+ dx = 2*h / norm(p)
557
+ x1 = x0 - (dx/2)*p
558
+ x2 = x0 + (dx/2)*p
559
+ f1 = fun(x1)
560
+ f2 = fun(x2)
561
+ df = f2 - f1
562
+ return df / dx
563
+
564
+ elif method == 'cs':
565
+ def matvec(p):
566
+ if np.array_equal(p, np.zeros_like(p)):
567
+ return np.zeros(m)
568
+ dx = h / norm(p)
569
+ x = x0 + dx*p*1.j
570
+ f1 = fun(x)
571
+ df = f1.imag
572
+ return df / dx
573
+
574
+ else:
575
+ raise RuntimeError("Never be here.")
576
+
577
+ return LinearOperator((m, n), matvec)
578
+
579
+
580
+ def _dense_difference(fun, x0, f0, h, use_one_sided, method):
581
+ m = f0.size
582
+ n = x0.size
583
+ J_transposed = np.empty((n, m))
584
+ x1 = x0.copy()
585
+ x2 = x0.copy()
586
+ xc = x0.astype(complex, copy=True)
587
+
588
+ for i in range(h.size):
589
+ if method == '2-point':
590
+ x1[i] += h[i]
591
+ dx = x1[i] - x0[i] # Recompute dx as exactly representable number.
592
+ df = fun(x1) - f0
593
+ elif method == '3-point' and use_one_sided[i]:
594
+ x1[i] += h[i]
595
+ x2[i] += 2 * h[i]
596
+ dx = x2[i] - x0[i]
597
+ f1 = fun(x1)
598
+ f2 = fun(x2)
599
+ df = -3.0 * f0 + 4 * f1 - f2
600
+ elif method == '3-point' and not use_one_sided[i]:
601
+ x1[i] -= h[i]
602
+ x2[i] += h[i]
603
+ dx = x2[i] - x1[i]
604
+ f1 = fun(x1)
605
+ f2 = fun(x2)
606
+ df = f2 - f1
607
+ elif method == 'cs':
608
+ xc[i] += h[i] * 1.j
609
+ f1 = fun(xc)
610
+ df = f1.imag
611
+ dx = h[i]
612
+ else:
613
+ raise RuntimeError("Never be here.")
614
+
615
+ J_transposed[i] = df / dx
616
+ x1[i] = x2[i] = xc[i] = x0[i]
617
+
618
+ if m == 1:
619
+ J_transposed = np.ravel(J_transposed)
620
+
621
+ return J_transposed.T
622
+
623
+
624
+ def _sparse_difference(fun, x0, f0, h, use_one_sided,
625
+ structure, groups, method):
626
+ m = f0.size
627
+ n = x0.size
628
+ row_indices = []
629
+ col_indices = []
630
+ fractions = []
631
+
632
+ n_groups = np.max(groups) + 1
633
+ for group in range(n_groups):
634
+ # Perturb variables which are in the same group simultaneously.
635
+ e = np.equal(group, groups)
636
+ h_vec = h * e
637
+ if method == '2-point':
638
+ x = x0 + h_vec
639
+ dx = x - x0
640
+ df = fun(x) - f0
641
+ # The result is written to columns which correspond to perturbed
642
+ # variables.
643
+ cols, = np.nonzero(e)
644
+ # Find all non-zero elements in selected columns of Jacobian.
645
+ i, j, _ = find(structure[:, cols])
646
+ # Restore column indices in the full array.
647
+ j = cols[j]
648
+ elif method == '3-point':
649
+ # Here we do conceptually the same but separate one-sided
650
+ # and two-sided schemes.
651
+ x1 = x0.copy()
652
+ x2 = x0.copy()
653
+
654
+ mask_1 = use_one_sided & e
655
+ x1[mask_1] += h_vec[mask_1]
656
+ x2[mask_1] += 2 * h_vec[mask_1]
657
+
658
+ mask_2 = ~use_one_sided & e
659
+ x1[mask_2] -= h_vec[mask_2]
660
+ x2[mask_2] += h_vec[mask_2]
661
+
662
+ dx = np.zeros(n)
663
+ dx[mask_1] = x2[mask_1] - x0[mask_1]
664
+ dx[mask_2] = x2[mask_2] - x1[mask_2]
665
+
666
+ f1 = fun(x1)
667
+ f2 = fun(x2)
668
+
669
+ cols, = np.nonzero(e)
670
+ i, j, _ = find(structure[:, cols])
671
+ j = cols[j]
672
+
673
+ mask = use_one_sided[j]
674
+ df = np.empty(m)
675
+
676
+ rows = i[mask]
677
+ df[rows] = -3 * f0[rows] + 4 * f1[rows] - f2[rows]
678
+
679
+ rows = i[~mask]
680
+ df[rows] = f2[rows] - f1[rows]
681
+ elif method == 'cs':
682
+ f1 = fun(x0 + h_vec*1.j)
683
+ df = f1.imag
684
+ dx = h_vec
685
+ cols, = np.nonzero(e)
686
+ i, j, _ = find(structure[:, cols])
687
+ j = cols[j]
688
+ else:
689
+ raise ValueError("Never be here.")
690
+
691
+ # All that's left is to compute the fraction. We store i, j and
692
+ # fractions as separate arrays and later construct coo_matrix.
693
+ row_indices.append(i)
694
+ col_indices.append(j)
695
+ fractions.append(df[i] / dx[j])
696
+
697
+ row_indices = np.hstack(row_indices)
698
+ col_indices = np.hstack(col_indices)
699
+ fractions = np.hstack(fractions)
700
+ J = coo_matrix((fractions, (row_indices, col_indices)), shape=(m, n))
701
+ return csr_matrix(J)
702
+
703
+
704
+ def check_derivative(fun, jac, x0, bounds=(-np.inf, np.inf), args=(),
705
+ kwargs={}):
706
+ """Check correctness of a function computing derivatives (Jacobian or
707
+ gradient) by comparison with a finite difference approximation.
708
+
709
+ Parameters
710
+ ----------
711
+ fun : callable
712
+ Function of which to estimate the derivatives. The argument x
713
+ passed to this function is ndarray of shape (n,) (never a scalar
714
+ even if n=1). It must return 1-D array_like of shape (m,) or a scalar.
715
+ jac : callable
716
+ Function which computes Jacobian matrix of `fun`. It must work with
717
+ argument x the same way as `fun`. The return value must be array_like
718
+ or sparse matrix with an appropriate shape.
719
+ x0 : array_like of shape (n,) or float
720
+ Point at which to estimate the derivatives. Float will be converted
721
+ to 1-D array.
722
+ bounds : 2-tuple of array_like, optional
723
+ Lower and upper bounds on independent variables. Defaults to no bounds.
724
+ Each bound must match the size of `x0` or be a scalar, in the latter
725
+ case the bound will be the same for all variables. Use it to limit the
726
+ range of function evaluation.
727
+ args, kwargs : tuple and dict, optional
728
+ Additional arguments passed to `fun` and `jac`. Both empty by default.
729
+ The calling signature is ``fun(x, *args, **kwargs)`` and the same
730
+ for `jac`.
731
+
732
+ Returns
733
+ -------
734
+ accuracy : float
735
+ The maximum among all relative errors for elements with absolute values
736
+ higher than 1 and absolute errors for elements with absolute values
737
+ less or equal than 1. If `accuracy` is on the order of 1e-6 or lower,
738
+ then it is likely that your `jac` implementation is correct.
739
+
740
+ See Also
741
+ --------
742
+ approx_derivative : Compute finite difference approximation of derivative.
743
+
744
+ Examples
745
+ --------
746
+ >>> import numpy as np
747
+ >>> from scipy.optimize._numdiff import check_derivative
748
+ >>>
749
+ >>>
750
+ >>> def f(x, c1, c2):
751
+ ... return np.array([x[0] * np.sin(c1 * x[1]),
752
+ ... x[0] * np.cos(c2 * x[1])])
753
+ ...
754
+ >>> def jac(x, c1, c2):
755
+ ... return np.array([
756
+ ... [np.sin(c1 * x[1]), c1 * x[0] * np.cos(c1 * x[1])],
757
+ ... [np.cos(c2 * x[1]), -c2 * x[0] * np.sin(c2 * x[1])]
758
+ ... ])
759
+ ...
760
+ >>>
761
+ >>> x0 = np.array([1.0, 0.5 * np.pi])
762
+ >>> check_derivative(f, jac, x0, args=(1, 2))
763
+ 2.4492935982947064e-16
764
+ """
765
+ J_to_test = jac(x0, *args, **kwargs)
766
+ if issparse(J_to_test):
767
+ J_diff = approx_derivative(fun, x0, bounds=bounds, sparsity=J_to_test,
768
+ args=args, kwargs=kwargs)
769
+ J_to_test = csr_matrix(J_to_test)
770
+ abs_err = J_to_test - J_diff
771
+ i, j, abs_err_data = find(abs_err)
772
+ J_diff_data = np.asarray(J_diff[i, j]).ravel()
773
+ return np.max(np.abs(abs_err_data) /
774
+ np.maximum(1, np.abs(J_diff_data)))
775
+ else:
776
+ J_diff = approx_derivative(fun, x0, bounds=bounds,
777
+ args=args, kwargs=kwargs)
778
+ abs_err = np.abs(J_to_test - J_diff)
779
+ return np.max(abs_err / np.maximum(1, np.abs(J_diff)))
vila/lib/python3.10/site-packages/scipy/optimize/_optimize.py ADDED
The diff for this file is too large to render. See raw diff
 
vila/lib/python3.10/site-packages/scipy/optimize/_pava_pybind.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eea00160871368c5807d7825188089b3fdb35c1373133b5b4c504be8a5dc9d2c
3
+ size 223832
vila/lib/python3.10/site-packages/scipy/optimize/_root_scalar.py ADDED
@@ -0,0 +1,525 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Unified interfaces to root finding algorithms for real or complex
3
+ scalar functions.
4
+
5
+ Functions
6
+ ---------
7
+ - root : find a root of a scalar function.
8
+ """
9
+ import numpy as np
10
+
11
+ from . import _zeros_py as optzeros
12
+ from ._numdiff import approx_derivative
13
+
14
+ __all__ = ['root_scalar']
15
+
16
+ ROOT_SCALAR_METHODS = ['bisect', 'brentq', 'brenth', 'ridder', 'toms748',
17
+ 'newton', 'secant', 'halley']
18
+
19
+
20
+ class MemoizeDer:
21
+ """Decorator that caches the value and derivative(s) of function each
22
+ time it is called.
23
+
24
+ This is a simplistic memoizer that calls and caches a single value
25
+ of `f(x, *args)`.
26
+ It assumes that `args` does not change between invocations.
27
+ It supports the use case of a root-finder where `args` is fixed,
28
+ `x` changes, and only rarely, if at all, does x assume the same value
29
+ more than once."""
30
+ def __init__(self, fun):
31
+ self.fun = fun
32
+ self.vals = None
33
+ self.x = None
34
+ self.n_calls = 0
35
+
36
+ def __call__(self, x, *args):
37
+ r"""Calculate f or use cached value if available"""
38
+ # Derivative may be requested before the function itself, always check
39
+ if self.vals is None or x != self.x:
40
+ fg = self.fun(x, *args)
41
+ self.x = x
42
+ self.n_calls += 1
43
+ self.vals = fg[:]
44
+ return self.vals[0]
45
+
46
+ def fprime(self, x, *args):
47
+ r"""Calculate f' or use a cached value if available"""
48
+ if self.vals is None or x != self.x:
49
+ self(x, *args)
50
+ return self.vals[1]
51
+
52
+ def fprime2(self, x, *args):
53
+ r"""Calculate f'' or use a cached value if available"""
54
+ if self.vals is None or x != self.x:
55
+ self(x, *args)
56
+ return self.vals[2]
57
+
58
+ def ncalls(self):
59
+ return self.n_calls
60
+
61
+
62
+ def root_scalar(f, args=(), method=None, bracket=None,
63
+ fprime=None, fprime2=None,
64
+ x0=None, x1=None,
65
+ xtol=None, rtol=None, maxiter=None,
66
+ options=None):
67
+ """
68
+ Find a root of a scalar function.
69
+
70
+ Parameters
71
+ ----------
72
+ f : callable
73
+ A function to find a root of.
74
+ args : tuple, optional
75
+ Extra arguments passed to the objective function and its derivative(s).
76
+ method : str, optional
77
+ Type of solver. Should be one of
78
+
79
+ - 'bisect' :ref:`(see here) <optimize.root_scalar-bisect>`
80
+ - 'brentq' :ref:`(see here) <optimize.root_scalar-brentq>`
81
+ - 'brenth' :ref:`(see here) <optimize.root_scalar-brenth>`
82
+ - 'ridder' :ref:`(see here) <optimize.root_scalar-ridder>`
83
+ - 'toms748' :ref:`(see here) <optimize.root_scalar-toms748>`
84
+ - 'newton' :ref:`(see here) <optimize.root_scalar-newton>`
85
+ - 'secant' :ref:`(see here) <optimize.root_scalar-secant>`
86
+ - 'halley' :ref:`(see here) <optimize.root_scalar-halley>`
87
+
88
+ bracket: A sequence of 2 floats, optional
89
+ An interval bracketing a root. `f(x, *args)` must have different
90
+ signs at the two endpoints.
91
+ x0 : float, optional
92
+ Initial guess.
93
+ x1 : float, optional
94
+ A second guess.
95
+ fprime : bool or callable, optional
96
+ If `fprime` is a boolean and is True, `f` is assumed to return the
97
+ value of the objective function and of the derivative.
98
+ `fprime` can also be a callable returning the derivative of `f`. In
99
+ this case, it must accept the same arguments as `f`.
100
+ fprime2 : bool or callable, optional
101
+ If `fprime2` is a boolean and is True, `f` is assumed to return the
102
+ value of the objective function and of the
103
+ first and second derivatives.
104
+ `fprime2` can also be a callable returning the second derivative of `f`.
105
+ In this case, it must accept the same arguments as `f`.
106
+ xtol : float, optional
107
+ Tolerance (absolute) for termination.
108
+ rtol : float, optional
109
+ Tolerance (relative) for termination.
110
+ maxiter : int, optional
111
+ Maximum number of iterations.
112
+ options : dict, optional
113
+ A dictionary of solver options. E.g., ``k``, see
114
+ :obj:`show_options()` for details.
115
+
116
+ Returns
117
+ -------
118
+ sol : RootResults
119
+ The solution represented as a ``RootResults`` object.
120
+ Important attributes are: ``root`` the solution , ``converged`` a
121
+ boolean flag indicating if the algorithm exited successfully and
122
+ ``flag`` which describes the cause of the termination. See
123
+ `RootResults` for a description of other attributes.
124
+
125
+ See also
126
+ --------
127
+ show_options : Additional options accepted by the solvers
128
+ root : Find a root of a vector function.
129
+
130
+ Notes
131
+ -----
132
+ This section describes the available solvers that can be selected by the
133
+ 'method' parameter.
134
+
135
+ The default is to use the best method available for the situation
136
+ presented.
137
+ If a bracket is provided, it may use one of the bracketing methods.
138
+ If a derivative and an initial value are specified, it may
139
+ select one of the derivative-based methods.
140
+ If no method is judged applicable, it will raise an Exception.
141
+
142
+ Arguments for each method are as follows (x=required, o=optional).
143
+
144
+ +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+
145
+ | method | f | args | bracket | x0 | x1 | fprime | fprime2 | xtol | rtol | maxiter | options |
146
+ +===============================================+===+======+=========+====+====+========+=========+======+======+=========+=========+
147
+ | :ref:`bisect <optimize.root_scalar-bisect>` | x | o | x | | | | | o | o | o | o |
148
+ +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+
149
+ | :ref:`brentq <optimize.root_scalar-brentq>` | x | o | x | | | | | o | o | o | o |
150
+ +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+
151
+ | :ref:`brenth <optimize.root_scalar-brenth>` | x | o | x | | | | | o | o | o | o |
152
+ +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+
153
+ | :ref:`ridder <optimize.root_scalar-ridder>` | x | o | x | | | | | o | o | o | o |
154
+ +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+
155
+ | :ref:`toms748 <optimize.root_scalar-toms748>` | x | o | x | | | | | o | o | o | o |
156
+ +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+
157
+ | :ref:`secant <optimize.root_scalar-secant>` | x | o | | x | o | | | o | o | o | o |
158
+ +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+
159
+ | :ref:`newton <optimize.root_scalar-newton>` | x | o | | x | | o | | o | o | o | o |
160
+ +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+
161
+ | :ref:`halley <optimize.root_scalar-halley>` | x | o | | x | | x | x | o | o | o | o |
162
+ +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+
163
+
164
+ Examples
165
+ --------
166
+
167
+ Find the root of a simple cubic
168
+
169
+ >>> from scipy import optimize
170
+ >>> def f(x):
171
+ ... return (x**3 - 1) # only one real root at x = 1
172
+
173
+ >>> def fprime(x):
174
+ ... return 3*x**2
175
+
176
+ The `brentq` method takes as input a bracket
177
+
178
+ >>> sol = optimize.root_scalar(f, bracket=[0, 3], method='brentq')
179
+ >>> sol.root, sol.iterations, sol.function_calls
180
+ (1.0, 10, 11)
181
+
182
+ The `newton` method takes as input a single point and uses the
183
+ derivative(s).
184
+
185
+ >>> sol = optimize.root_scalar(f, x0=0.2, fprime=fprime, method='newton')
186
+ >>> sol.root, sol.iterations, sol.function_calls
187
+ (1.0, 11, 22)
188
+
189
+ The function can provide the value and derivative(s) in a single call.
190
+
191
+ >>> def f_p_pp(x):
192
+ ... return (x**3 - 1), 3*x**2, 6*x
193
+
194
+ >>> sol = optimize.root_scalar(
195
+ ... f_p_pp, x0=0.2, fprime=True, method='newton'
196
+ ... )
197
+ >>> sol.root, sol.iterations, sol.function_calls
198
+ (1.0, 11, 11)
199
+
200
+ >>> sol = optimize.root_scalar(
201
+ ... f_p_pp, x0=0.2, fprime=True, fprime2=True, method='halley'
202
+ ... )
203
+ >>> sol.root, sol.iterations, sol.function_calls
204
+ (1.0, 7, 8)
205
+
206
+
207
+ """ # noqa: E501
208
+ if not isinstance(args, tuple):
209
+ args = (args,)
210
+
211
+ if options is None:
212
+ options = {}
213
+
214
+ # fun also returns the derivative(s)
215
+ is_memoized = False
216
+ if fprime2 is not None and not callable(fprime2):
217
+ if bool(fprime2):
218
+ f = MemoizeDer(f)
219
+ is_memoized = True
220
+ fprime2 = f.fprime2
221
+ fprime = f.fprime
222
+ else:
223
+ fprime2 = None
224
+ if fprime is not None and not callable(fprime):
225
+ if bool(fprime):
226
+ f = MemoizeDer(f)
227
+ is_memoized = True
228
+ fprime = f.fprime
229
+ else:
230
+ fprime = None
231
+
232
+ # respect solver-specific default tolerances - only pass in if actually set
233
+ kwargs = {}
234
+ for k in ['xtol', 'rtol', 'maxiter']:
235
+ v = locals().get(k)
236
+ if v is not None:
237
+ kwargs[k] = v
238
+
239
+ # Set any solver-specific options
240
+ if options:
241
+ kwargs.update(options)
242
+ # Always request full_output from the underlying method as _root_scalar
243
+ # always returns a RootResults object
244
+ kwargs.update(full_output=True, disp=False)
245
+
246
+ # Pick a method if not specified.
247
+ # Use the "best" method available for the situation.
248
+ if not method:
249
+ if bracket:
250
+ method = 'brentq'
251
+ elif x0 is not None:
252
+ if fprime:
253
+ if fprime2:
254
+ method = 'halley'
255
+ else:
256
+ method = 'newton'
257
+ elif x1 is not None:
258
+ method = 'secant'
259
+ else:
260
+ method = 'newton'
261
+ if not method:
262
+ raise ValueError('Unable to select a solver as neither bracket '
263
+ 'nor starting point provided.')
264
+
265
+ meth = method.lower()
266
+ map2underlying = {'halley': 'newton', 'secant': 'newton'}
267
+
268
+ try:
269
+ methodc = getattr(optzeros, map2underlying.get(meth, meth))
270
+ except AttributeError as e:
271
+ raise ValueError('Unknown solver %s' % meth) from e
272
+
273
+ if meth in ['bisect', 'ridder', 'brentq', 'brenth', 'toms748']:
274
+ if not isinstance(bracket, (list, tuple, np.ndarray)):
275
+ raise ValueError('Bracket needed for %s' % method)
276
+
277
+ a, b = bracket[:2]
278
+ try:
279
+ r, sol = methodc(f, a, b, args=args, **kwargs)
280
+ except ValueError as e:
281
+ # gh-17622 fixed some bugs in low-level solvers by raising an error
282
+ # (rather than returning incorrect results) when the callable
283
+ # returns a NaN. It did so by wrapping the callable rather than
284
+ # modifying compiled code, so the iteration count is not available.
285
+ if hasattr(e, "_x"):
286
+ sol = optzeros.RootResults(root=e._x,
287
+ iterations=np.nan,
288
+ function_calls=e._function_calls,
289
+ flag=str(e), method=method)
290
+ else:
291
+ raise
292
+
293
+ elif meth in ['secant']:
294
+ if x0 is None:
295
+ raise ValueError('x0 must not be None for %s' % method)
296
+ if 'xtol' in kwargs:
297
+ kwargs['tol'] = kwargs.pop('xtol')
298
+ r, sol = methodc(f, x0, args=args, fprime=None, fprime2=None,
299
+ x1=x1, **kwargs)
300
+ elif meth in ['newton']:
301
+ if x0 is None:
302
+ raise ValueError('x0 must not be None for %s' % method)
303
+ if not fprime:
304
+ # approximate fprime with finite differences
305
+
306
+ def fprime(x, *args):
307
+ # `root_scalar` doesn't actually seem to support vectorized
308
+ # use of `newton`. In that case, `approx_derivative` will
309
+ # always get scalar input. Nonetheless, it always returns an
310
+ # array, so we extract the element to produce scalar output.
311
+ return approx_derivative(f, x, method='2-point', args=args)[0]
312
+
313
+ if 'xtol' in kwargs:
314
+ kwargs['tol'] = kwargs.pop('xtol')
315
+ r, sol = methodc(f, x0, args=args, fprime=fprime, fprime2=None,
316
+ **kwargs)
317
+ elif meth in ['halley']:
318
+ if x0 is None:
319
+ raise ValueError('x0 must not be None for %s' % method)
320
+ if not fprime:
321
+ raise ValueError('fprime must be specified for %s' % method)
322
+ if not fprime2:
323
+ raise ValueError('fprime2 must be specified for %s' % method)
324
+ if 'xtol' in kwargs:
325
+ kwargs['tol'] = kwargs.pop('xtol')
326
+ r, sol = methodc(f, x0, args=args, fprime=fprime, fprime2=fprime2, **kwargs)
327
+ else:
328
+ raise ValueError('Unknown solver %s' % method)
329
+
330
+ if is_memoized:
331
+ # Replace the function_calls count with the memoized count.
332
+ # Avoids double and triple-counting.
333
+ n_calls = f.n_calls
334
+ sol.function_calls = n_calls
335
+
336
+ return sol
337
+
338
+
339
+ def _root_scalar_brentq_doc():
340
+ r"""
341
+ Options
342
+ -------
343
+ args : tuple, optional
344
+ Extra arguments passed to the objective function.
345
+ bracket: A sequence of 2 floats, optional
346
+ An interval bracketing a root. `f(x, *args)` must have different
347
+ signs at the two endpoints.
348
+ xtol : float, optional
349
+ Tolerance (absolute) for termination.
350
+ rtol : float, optional
351
+ Tolerance (relative) for termination.
352
+ maxiter : int, optional
353
+ Maximum number of iterations.
354
+ options: dict, optional
355
+ Specifies any method-specific options not covered above
356
+
357
+ """
358
+ pass
359
+
360
+
361
+ def _root_scalar_brenth_doc():
362
+ r"""
363
+ Options
364
+ -------
365
+ args : tuple, optional
366
+ Extra arguments passed to the objective function.
367
+ bracket: A sequence of 2 floats, optional
368
+ An interval bracketing a root. `f(x, *args)` must have different
369
+ signs at the two endpoints.
370
+ xtol : float, optional
371
+ Tolerance (absolute) for termination.
372
+ rtol : float, optional
373
+ Tolerance (relative) for termination.
374
+ maxiter : int, optional
375
+ Maximum number of iterations.
376
+ options: dict, optional
377
+ Specifies any method-specific options not covered above.
378
+
379
+ """
380
+ pass
381
+
382
+ def _root_scalar_toms748_doc():
383
+ r"""
384
+ Options
385
+ -------
386
+ args : tuple, optional
387
+ Extra arguments passed to the objective function.
388
+ bracket: A sequence of 2 floats, optional
389
+ An interval bracketing a root. `f(x, *args)` must have different
390
+ signs at the two endpoints.
391
+ xtol : float, optional
392
+ Tolerance (absolute) for termination.
393
+ rtol : float, optional
394
+ Tolerance (relative) for termination.
395
+ maxiter : int, optional
396
+ Maximum number of iterations.
397
+ options: dict, optional
398
+ Specifies any method-specific options not covered above.
399
+
400
+ """
401
+ pass
402
+
403
+
404
+ def _root_scalar_secant_doc():
405
+ r"""
406
+ Options
407
+ -------
408
+ args : tuple, optional
409
+ Extra arguments passed to the objective function.
410
+ xtol : float, optional
411
+ Tolerance (absolute) for termination.
412
+ rtol : float, optional
413
+ Tolerance (relative) for termination.
414
+ maxiter : int, optional
415
+ Maximum number of iterations.
416
+ x0 : float, required
417
+ Initial guess.
418
+ x1 : float, required
419
+ A second guess.
420
+ options: dict, optional
421
+ Specifies any method-specific options not covered above.
422
+
423
+ """
424
+ pass
425
+
426
+
427
+ def _root_scalar_newton_doc():
428
+ r"""
429
+ Options
430
+ -------
431
+ args : tuple, optional
432
+ Extra arguments passed to the objective function and its derivative.
433
+ xtol : float, optional
434
+ Tolerance (absolute) for termination.
435
+ rtol : float, optional
436
+ Tolerance (relative) for termination.
437
+ maxiter : int, optional
438
+ Maximum number of iterations.
439
+ x0 : float, required
440
+ Initial guess.
441
+ fprime : bool or callable, optional
442
+ If `fprime` is a boolean and is True, `f` is assumed to return the
443
+ value of derivative along with the objective function.
444
+ `fprime` can also be a callable returning the derivative of `f`. In
445
+ this case, it must accept the same arguments as `f`.
446
+ options: dict, optional
447
+ Specifies any method-specific options not covered above.
448
+
449
+ """
450
+ pass
451
+
452
+
453
+ def _root_scalar_halley_doc():
454
+ r"""
455
+ Options
456
+ -------
457
+ args : tuple, optional
458
+ Extra arguments passed to the objective function and its derivatives.
459
+ xtol : float, optional
460
+ Tolerance (absolute) for termination.
461
+ rtol : float, optional
462
+ Tolerance (relative) for termination.
463
+ maxiter : int, optional
464
+ Maximum number of iterations.
465
+ x0 : float, required
466
+ Initial guess.
467
+ fprime : bool or callable, required
468
+ If `fprime` is a boolean and is True, `f` is assumed to return the
469
+ value of derivative along with the objective function.
470
+ `fprime` can also be a callable returning the derivative of `f`. In
471
+ this case, it must accept the same arguments as `f`.
472
+ fprime2 : bool or callable, required
473
+ If `fprime2` is a boolean and is True, `f` is assumed to return the
474
+ value of 1st and 2nd derivatives along with the objective function.
475
+ `fprime2` can also be a callable returning the 2nd derivative of `f`.
476
+ In this case, it must accept the same arguments as `f`.
477
+ options: dict, optional
478
+ Specifies any method-specific options not covered above.
479
+
480
+ """
481
+ pass
482
+
483
+
484
+ def _root_scalar_ridder_doc():
485
+ r"""
486
+ Options
487
+ -------
488
+ args : tuple, optional
489
+ Extra arguments passed to the objective function.
490
+ bracket: A sequence of 2 floats, optional
491
+ An interval bracketing a root. `f(x, *args)` must have different
492
+ signs at the two endpoints.
493
+ xtol : float, optional
494
+ Tolerance (absolute) for termination.
495
+ rtol : float, optional
496
+ Tolerance (relative) for termination.
497
+ maxiter : int, optional
498
+ Maximum number of iterations.
499
+ options: dict, optional
500
+ Specifies any method-specific options not covered above.
501
+
502
+ """
503
+ pass
504
+
505
+
506
+ def _root_scalar_bisect_doc():
507
+ r"""
508
+ Options
509
+ -------
510
+ args : tuple, optional
511
+ Extra arguments passed to the objective function.
512
+ bracket: A sequence of 2 floats, optional
513
+ An interval bracketing a root. `f(x, *args)` must have different
514
+ signs at the two endpoints.
515
+ xtol : float, optional
516
+ Tolerance (absolute) for termination.
517
+ rtol : float, optional
518
+ Tolerance (relative) for termination.
519
+ maxiter : int, optional
520
+ Maximum number of iterations.
521
+ options: dict, optional
522
+ Specifies any method-specific options not covered above.
523
+
524
+ """
525
+ pass
vila/lib/python3.10/site-packages/scipy/optimize/_shgo_lib/__init__.py ADDED
File without changes
vila/lib/python3.10/site-packages/scipy/optimize/_shgo_lib/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (174 Bytes). View file
 
vila/lib/python3.10/site-packages/scipy/optimize/_shgo_lib/__pycache__/_complex.cpython-310.pyc ADDED
Binary file (23 kB). View file
 
vila/lib/python3.10/site-packages/scipy/optimize/_shgo_lib/__pycache__/_vertex.cpython-310.pyc ADDED
Binary file (14.4 kB). View file
 
vila/lib/python3.10/site-packages/scipy/optimize/_shgo_lib/_complex.py ADDED
@@ -0,0 +1,1225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Base classes for low memory simplicial complex structures."""
2
+ import copy
3
+ import logging
4
+ import itertools
5
+ import decimal
6
+ from functools import cache
7
+
8
+ import numpy as np
9
+
10
+ from ._vertex import (VertexCacheField, VertexCacheIndex)
11
+
12
+
13
+ class Complex:
14
+ """
15
+ Base class for a simplicial complex described as a cache of vertices
16
+ together with their connections.
17
+
18
+ Important methods:
19
+ Domain triangulation:
20
+ Complex.triangulate, Complex.split_generation
21
+ Triangulating arbitrary points (must be traingulable,
22
+ may exist outside domain):
23
+ Complex.triangulate(sample_set)
24
+ Converting another simplicial complex structure data type to the
25
+ structure used in Complex (ex. OBJ wavefront)
26
+ Complex.convert(datatype, data)
27
+
28
+ Important objects:
29
+ HC.V: The cache of vertices and their connection
30
+ HC.H: Storage structure of all vertex groups
31
+
32
+ Parameters
33
+ ----------
34
+ dim : int
35
+ Spatial dimensionality of the complex R^dim
36
+ domain : list of tuples, optional
37
+ The bounds [x_l, x_u]^dim of the hyperrectangle space
38
+ ex. The default domain is the hyperrectangle [0, 1]^dim
39
+ Note: The domain must be convex, non-convex spaces can be cut
40
+ away from this domain using the non-linear
41
+ g_cons functions to define any arbitrary domain
42
+ (these domains may also be disconnected from each other)
43
+ sfield :
44
+ A scalar function defined in the associated domain f: R^dim --> R
45
+ sfield_args : tuple
46
+ Additional arguments to be passed to `sfield`
47
+ vfield :
48
+ A scalar function defined in the associated domain
49
+ f: R^dim --> R^m
50
+ (for example a gradient function of the scalar field)
51
+ vfield_args : tuple
52
+ Additional arguments to be passed to vfield
53
+ symmetry : None or list
54
+ Specify if the objective function contains symmetric variables.
55
+ The search space (and therefore performance) is decreased by up to
56
+ O(n!) times in the fully symmetric case.
57
+
58
+ E.g. f(x) = (x_1 + x_2 + x_3) + (x_4)**2 + (x_5)**2 + (x_6)**2
59
+
60
+ In this equation x_2 and x_3 are symmetric to x_1, while x_5 and
61
+ x_6 are symmetric to x_4, this can be specified to the solver as:
62
+
63
+ symmetry = [0, # Variable 1
64
+ 0, # symmetric to variable 1
65
+ 0, # symmetric to variable 1
66
+ 3, # Variable 4
67
+ 3, # symmetric to variable 4
68
+ 3, # symmetric to variable 4
69
+ ]
70
+
71
+ constraints : dict or sequence of dict, optional
72
+ Constraints definition.
73
+ Function(s) ``R**n`` in the form::
74
+
75
+ g(x) <= 0 applied as g : R^n -> R^m
76
+ h(x) == 0 applied as h : R^n -> R^p
77
+
78
+ Each constraint is defined in a dictionary with fields:
79
+
80
+ type : str
81
+ Constraint type: 'eq' for equality, 'ineq' for inequality.
82
+ fun : callable
83
+ The function defining the constraint.
84
+ jac : callable, optional
85
+ The Jacobian of `fun` (only for SLSQP).
86
+ args : sequence, optional
87
+ Extra arguments to be passed to the function and Jacobian.
88
+
89
+ Equality constraint means that the constraint function result is to
90
+ be zero whereas inequality means that it is to be
91
+ non-negative.constraints : dict or sequence of dict, optional
92
+ Constraints definition.
93
+ Function(s) ``R**n`` in the form::
94
+
95
+ g(x) <= 0 applied as g : R^n -> R^m
96
+ h(x) == 0 applied as h : R^n -> R^p
97
+
98
+ Each constraint is defined in a dictionary with fields:
99
+
100
+ type : str
101
+ Constraint type: 'eq' for equality, 'ineq' for inequality.
102
+ fun : callable
103
+ The function defining the constraint.
104
+ jac : callable, optional
105
+ The Jacobian of `fun` (unused).
106
+ args : sequence, optional
107
+ Extra arguments to be passed to the function and Jacobian.
108
+
109
+ Equality constraint means that the constraint function result is to
110
+ be zero whereas inequality means that it is to be non-negative.
111
+
112
+ workers : int optional
113
+ Uses `multiprocessing.Pool <multiprocessing>`) to compute the field
114
+ functions in parallel.
115
+ """
116
+ def __init__(self, dim, domain=None, sfield=None, sfield_args=(),
117
+ symmetry=None, constraints=None, workers=1):
118
+ self.dim = dim
119
+
120
+ # Domains
121
+ self.domain = domain
122
+ if domain is None:
123
+ self.bounds = [(0.0, 1.0), ] * dim
124
+ else:
125
+ self.bounds = domain
126
+ self.symmetry = symmetry
127
+ # here in init to avoid if checks
128
+
129
+ # Field functions
130
+ self.sfield = sfield
131
+ self.sfield_args = sfield_args
132
+
133
+ # Process constraints
134
+ # Constraints
135
+ # Process constraint dict sequence:
136
+ if constraints is not None:
137
+ self.min_cons = constraints
138
+ self.g_cons = []
139
+ self.g_args = []
140
+ if not isinstance(constraints, (tuple, list)):
141
+ constraints = (constraints,)
142
+
143
+ for cons in constraints:
144
+ if cons['type'] in ('ineq'):
145
+ self.g_cons.append(cons['fun'])
146
+ try:
147
+ self.g_args.append(cons['args'])
148
+ except KeyError:
149
+ self.g_args.append(())
150
+ self.g_cons = tuple(self.g_cons)
151
+ self.g_args = tuple(self.g_args)
152
+ else:
153
+ self.g_cons = None
154
+ self.g_args = None
155
+
156
+ # Homology properties
157
+ self.gen = 0
158
+ self.perm_cycle = 0
159
+
160
+ # Every cell is stored in a list of its generation,
161
+ # ex. the initial cell is stored in self.H[0]
162
+ # 1st get new cells are stored in self.H[1] etc.
163
+ # When a cell is sub-generated it is removed from this list
164
+
165
+ self.H = [] # Storage structure of vertex groups
166
+
167
+ # Cache of all vertices
168
+ if (sfield is not None) or (self.g_cons is not None):
169
+ # Initiate a vertex cache and an associated field cache, note that
170
+ # the field case is always initiated inside the vertex cache if an
171
+ # associated field scalar field is defined:
172
+ if sfield is not None:
173
+ self.V = VertexCacheField(field=sfield, field_args=sfield_args,
174
+ g_cons=self.g_cons,
175
+ g_cons_args=self.g_args,
176
+ workers=workers)
177
+ elif self.g_cons is not None:
178
+ self.V = VertexCacheField(field=sfield, field_args=sfield_args,
179
+ g_cons=self.g_cons,
180
+ g_cons_args=self.g_args,
181
+ workers=workers)
182
+ else:
183
+ self.V = VertexCacheIndex()
184
+
185
+ self.V_non_symm = [] # List of non-symmetric vertices
186
+
187
+ def __call__(self):
188
+ return self.H
189
+
190
+ # %% Triangulation methods
191
+ def cyclic_product(self, bounds, origin, supremum, centroid=True):
192
+ """Generate initial triangulation using cyclic product"""
193
+ # Define current hyperrectangle
194
+ vot = tuple(origin)
195
+ vut = tuple(supremum) # Hyperrectangle supremum
196
+ self.V[vot]
197
+ vo = self.V[vot]
198
+ yield vo.x
199
+ self.V[vut].connect(self.V[vot])
200
+ yield vut
201
+ # Cyclic group approach with second x_l --- x_u operation.
202
+
203
+ # These containers store the "lower" and "upper" vertices
204
+ # corresponding to the origin or supremum of every C2 group.
205
+ # It has the structure of `dim` times embedded lists each containing
206
+ # these vertices as the entire complex grows. Bounds[0] has to be done
207
+ # outside the loops before we have symmetric containers.
208
+ # NOTE: This means that bounds[0][1] must always exist
209
+ C0x = [[self.V[vot]]]
210
+ a_vo = copy.copy(list(origin))
211
+ a_vo[0] = vut[0] # Update aN Origin
212
+ a_vo = self.V[tuple(a_vo)]
213
+ # self.V[vot].connect(self.V[tuple(a_vo)])
214
+ self.V[vot].connect(a_vo)
215
+ yield a_vo.x
216
+ C1x = [[a_vo]]
217
+ # C1x = [[self.V[tuple(a_vo)]]]
218
+ ab_C = [] # Container for a + b operations
219
+
220
+ # Loop over remaining bounds
221
+ for i, x in enumerate(bounds[1:]):
222
+ # Update lower and upper containers
223
+ C0x.append([])
224
+ C1x.append([])
225
+ # try to access a second bound (if not, C1 is symmetric)
226
+ try:
227
+ # Early try so that we don't have to copy the cache before
228
+ # moving on to next C1/C2: Try to add the operation of a new
229
+ # C2 product by accessing the upper bound
230
+ x[1]
231
+ # Copy lists for iteration
232
+ cC0x = [x[:] for x in C0x[:i + 1]]
233
+ cC1x = [x[:] for x in C1x[:i + 1]]
234
+ for j, (VL, VU) in enumerate(zip(cC0x, cC1x)):
235
+ for k, (vl, vu) in enumerate(zip(VL, VU)):
236
+ # Build aN vertices for each lower-upper pair in N:
237
+ a_vl = list(vl.x)
238
+ a_vu = list(vu.x)
239
+ a_vl[i + 1] = vut[i + 1]
240
+ a_vu[i + 1] = vut[i + 1]
241
+ a_vl = self.V[tuple(a_vl)]
242
+
243
+ # Connect vertices in N to corresponding vertices
244
+ # in aN:
245
+ vl.connect(a_vl)
246
+
247
+ yield a_vl.x
248
+
249
+ a_vu = self.V[tuple(a_vu)]
250
+ # Connect vertices in N to corresponding vertices
251
+ # in aN:
252
+ vu.connect(a_vu)
253
+
254
+ # Connect new vertex pair in aN:
255
+ a_vl.connect(a_vu)
256
+
257
+ # Connect lower pair to upper (triangulation
258
+ # operation of a + b (two arbitrary operations):
259
+ vl.connect(a_vu)
260
+ ab_C.append((vl, a_vu))
261
+
262
+ # Update the containers
263
+ C0x[i + 1].append(vl)
264
+ C0x[i + 1].append(vu)
265
+ C1x[i + 1].append(a_vl)
266
+ C1x[i + 1].append(a_vu)
267
+
268
+ # Update old containers
269
+ C0x[j].append(a_vl)
270
+ C1x[j].append(a_vu)
271
+
272
+ # Yield new points
273
+ yield a_vu.x
274
+
275
+ # Try to connect aN lower source of previous a + b
276
+ # operation with a aN vertex
277
+ ab_Cc = copy.copy(ab_C)
278
+
279
+ for vp in ab_Cc:
280
+ b_v = list(vp[0].x)
281
+ ab_v = list(vp[1].x)
282
+ b_v[i + 1] = vut[i + 1]
283
+ ab_v[i + 1] = vut[i + 1]
284
+ b_v = self.V[tuple(b_v)] # b + vl
285
+ ab_v = self.V[tuple(ab_v)] # b + a_vl
286
+ # Note o---o is already connected
287
+ vp[0].connect(ab_v) # o-s
288
+ b_v.connect(ab_v) # s-s
289
+
290
+ # Add new list of cross pairs
291
+ ab_C.append((vp[0], ab_v))
292
+ ab_C.append((b_v, ab_v))
293
+
294
+ except IndexError:
295
+ cC0x = C0x[i]
296
+ cC1x = C1x[i]
297
+ VL, VU = cC0x, cC1x
298
+ for k, (vl, vu) in enumerate(zip(VL, VU)):
299
+ # Build aN vertices for each lower-upper pair in N:
300
+ a_vu = list(vu.x)
301
+ a_vu[i + 1] = vut[i + 1]
302
+ # Connect vertices in N to corresponding vertices
303
+ # in aN:
304
+ a_vu = self.V[tuple(a_vu)]
305
+ # Connect vertices in N to corresponding vertices
306
+ # in aN:
307
+ vu.connect(a_vu)
308
+ # Connect new vertex pair in aN:
309
+ # a_vl.connect(a_vu)
310
+ # Connect lower pair to upper (triangulation
311
+ # operation of a + b (two arbitrary operations):
312
+ vl.connect(a_vu)
313
+ ab_C.append((vl, a_vu))
314
+ C0x[i + 1].append(vu)
315
+ C1x[i + 1].append(a_vu)
316
+ # Yield new points
317
+ a_vu.connect(self.V[vut])
318
+ yield a_vu.x
319
+ ab_Cc = copy.copy(ab_C)
320
+ for vp in ab_Cc:
321
+ if vp[1].x[i] == vut[i]:
322
+ ab_v = list(vp[1].x)
323
+ ab_v[i + 1] = vut[i + 1]
324
+ ab_v = self.V[tuple(ab_v)] # b + a_vl
325
+ # Note o---o is already connected
326
+ vp[0].connect(ab_v) # o-s
327
+
328
+ # Add new list of cross pairs
329
+ ab_C.append((vp[0], ab_v))
330
+
331
+ # Clean class trash
332
+ try:
333
+ del C0x
334
+ del cC0x
335
+ del C1x
336
+ del cC1x
337
+ del ab_C
338
+ del ab_Cc
339
+ except UnboundLocalError:
340
+ pass
341
+
342
+ # Extra yield to ensure that the triangulation is completed
343
+ if centroid:
344
+ vo = self.V[vot]
345
+ vs = self.V[vut]
346
+ # Disconnect the origin and supremum
347
+ vo.disconnect(vs)
348
+ # Build centroid
349
+ vc = self.split_edge(vot, vut)
350
+ for v in vo.nn:
351
+ v.connect(vc)
352
+ yield vc.x
353
+ return vc.x
354
+ else:
355
+ yield vut
356
+ return vut
357
+
358
+ def triangulate(self, n=None, symmetry=None, centroid=True,
359
+ printout=False):
360
+ """
361
+ Triangulate the initial domain, if n is not None then a limited number
362
+ of points will be generated
363
+
364
+ Parameters
365
+ ----------
366
+ n : int, Number of points to be sampled.
367
+ symmetry :
368
+
369
+ Ex. Dictionary/hashtable
370
+ f(x) = (x_1 + x_2 + x_3) + (x_4)**2 + (x_5)**2 + (x_6)**2
371
+
372
+ symmetry = symmetry[0]: 0, # Variable 1
373
+ symmetry[1]: 0, # symmetric to variable 1
374
+ symmetry[2]: 0, # symmetric to variable 1
375
+ symmetry[3]: 3, # Variable 4
376
+ symmetry[4]: 3, # symmetric to variable 4
377
+ symmetry[5]: 3, # symmetric to variable 4
378
+ }
379
+ centroid : bool, if True add a central point to the hypercube
380
+ printout : bool, if True print out results
381
+
382
+ NOTES:
383
+ ------
384
+ Rather than using the combinatorial algorithm to connect vertices we
385
+ make the following observation:
386
+
387
+ The bound pairs are similar a C2 cyclic group and the structure is
388
+ formed using the cartesian product:
389
+
390
+ H = C2 x C2 x C2 ... x C2 (dim times)
391
+
392
+ So construct any normal subgroup N and consider H/N first, we connect
393
+ all vertices within N (ex. N is C2 (the first dimension), then we move
394
+ to a left coset aN (an operation moving around the defined H/N group by
395
+ for example moving from the lower bound in C2 (dimension 2) to the
396
+ higher bound in C2. During this operation connection all the vertices.
397
+ Now repeat the N connections. Note that these elements can be connected
398
+ in parallel.
399
+ """
400
+ # Inherit class arguments
401
+ if symmetry is None:
402
+ symmetry = self.symmetry
403
+ # Build origin and supremum vectors
404
+ origin = [i[0] for i in self.bounds]
405
+ self.origin = origin
406
+ supremum = [i[1] for i in self.bounds]
407
+
408
+ self.supremum = supremum
409
+
410
+ if symmetry is None:
411
+ cbounds = self.bounds
412
+ else:
413
+ cbounds = copy.copy(self.bounds)
414
+ for i, j in enumerate(symmetry):
415
+ if i is not j:
416
+ # pop second entry on second symmetry vars
417
+ cbounds[i] = [self.bounds[symmetry[i]][0]]
418
+ # Sole (first) entry is the sup value and there is no
419
+ # origin:
420
+ cbounds[i] = [self.bounds[symmetry[i]][1]]
421
+ if (self.bounds[symmetry[i]] is not
422
+ self.bounds[symmetry[j]]):
423
+ logging.warning(f"Variable {i} was specified as "
424
+ f"symmetetric to variable {j}, however"
425
+ f", the bounds {i} ="
426
+ f" {self.bounds[symmetry[i]]} and {j}"
427
+ f" ="
428
+ f" {self.bounds[symmetry[j]]} do not "
429
+ f"match, the mismatch was ignored in "
430
+ f"the initial triangulation.")
431
+ cbounds[i] = self.bounds[symmetry[j]]
432
+
433
+ if n is None:
434
+ # Build generator
435
+ self.cp = self.cyclic_product(cbounds, origin, supremum, centroid)
436
+ for i in self.cp:
437
+ i
438
+
439
+ try:
440
+ self.triangulated_vectors.append((tuple(self.origin),
441
+ tuple(self.supremum)))
442
+ except (AttributeError, KeyError):
443
+ self.triangulated_vectors = [(tuple(self.origin),
444
+ tuple(self.supremum))]
445
+
446
+ else:
447
+ # Check if generator already exists
448
+ try:
449
+ self.cp
450
+ except (AttributeError, KeyError):
451
+ self.cp = self.cyclic_product(cbounds, origin, supremum,
452
+ centroid)
453
+
454
+ try:
455
+ while len(self.V.cache) < n:
456
+ next(self.cp)
457
+ except StopIteration:
458
+ try:
459
+ self.triangulated_vectors.append((tuple(self.origin),
460
+ tuple(self.supremum)))
461
+ except (AttributeError, KeyError):
462
+ self.triangulated_vectors = [(tuple(self.origin),
463
+ tuple(self.supremum))]
464
+
465
+ if printout:
466
+ # for v in self.C0():
467
+ # v.print_out()
468
+ for v in self.V.cache:
469
+ self.V[v].print_out()
470
+
471
+ return
472
+
473
+ def refine(self, n=1):
474
+ if n is None:
475
+ try:
476
+ self.triangulated_vectors
477
+ self.refine_all()
478
+ return
479
+ except AttributeError as ae:
480
+ if str(ae) == "'Complex' object has no attribute " \
481
+ "'triangulated_vectors'":
482
+ self.triangulate(symmetry=self.symmetry)
483
+ return
484
+ else:
485
+ raise
486
+
487
+ nt = len(self.V.cache) + n # Target number of total vertices
488
+ # In the outer while loop we iterate until we have added an extra `n`
489
+ # vertices to the complex:
490
+ while len(self.V.cache) < nt: # while loop 1
491
+ try: # try 1
492
+ # Try to access triangulated_vectors, this should only be
493
+ # defined if an initial triangulation has already been
494
+ # performed:
495
+ self.triangulated_vectors
496
+ # Try a usual iteration of the current generator, if it
497
+ # does not exist or is exhausted then produce a new generator
498
+ try: # try 2
499
+ next(self.rls)
500
+ except (AttributeError, StopIteration, KeyError):
501
+ vp = self.triangulated_vectors[0]
502
+ self.rls = self.refine_local_space(*vp, bounds=self.bounds)
503
+ next(self.rls)
504
+
505
+ except (AttributeError, KeyError):
506
+ # If an initial triangulation has not been completed, then
507
+ # we start/continue the initial triangulation targeting `nt`
508
+ # vertices, if nt is greater than the initial number of
509
+ # vertices then the `refine` routine will move back to try 1.
510
+ self.triangulate(nt, self.symmetry)
511
+ return
512
+
513
+ def refine_all(self, centroids=True):
514
+ """Refine the entire domain of the current complex."""
515
+ try:
516
+ self.triangulated_vectors
517
+ tvs = copy.copy(self.triangulated_vectors)
518
+ for i, vp in enumerate(tvs):
519
+ self.rls = self.refine_local_space(*vp, bounds=self.bounds)
520
+ for i in self.rls:
521
+ i
522
+ except AttributeError as ae:
523
+ if str(ae) == "'Complex' object has no attribute " \
524
+ "'triangulated_vectors'":
525
+ self.triangulate(symmetry=self.symmetry, centroid=centroids)
526
+ else:
527
+ raise
528
+
529
+ # This adds a centroid to every new sub-domain generated and defined
530
+ # by self.triangulated_vectors, in addition the vertices ! to complete
531
+ # the triangulation
532
+ return
533
+
534
+ def refine_local_space(self, origin, supremum, bounds, centroid=1):
535
+ # Copy for later removal
536
+ origin_c = copy.copy(origin)
537
+ supremum_c = copy.copy(supremum)
538
+
539
+ # Initiate local variables redefined in later inner `for` loop:
540
+ vl, vu, a_vu = None, None, None
541
+
542
+ # Change the vector orientation so that it is only increasing
543
+ s_ov = list(origin)
544
+ s_origin = list(origin)
545
+ s_sv = list(supremum)
546
+ s_supremum = list(supremum)
547
+ for i, vi in enumerate(s_origin):
548
+ if s_ov[i] > s_sv[i]:
549
+ s_origin[i] = s_sv[i]
550
+ s_supremum[i] = s_ov[i]
551
+
552
+ vot = tuple(s_origin)
553
+ vut = tuple(s_supremum) # Hyperrectangle supremum
554
+
555
+ vo = self.V[vot] # initiate if doesn't exist yet
556
+ vs = self.V[vut]
557
+ # Start by finding the old centroid of the new space:
558
+ vco = self.split_edge(vo.x, vs.x) # Split in case not centroid arg
559
+
560
+ # Find set of extreme vertices in current local space
561
+ sup_set = copy.copy(vco.nn)
562
+ # Cyclic group approach with second x_l --- x_u operation.
563
+
564
+ # These containers store the "lower" and "upper" vertices
565
+ # corresponding to the origin or supremum of every C2 group.
566
+ # It has the structure of `dim` times embedded lists each containing
567
+ # these vertices as the entire complex grows. Bounds[0] has to be done
568
+ # outside the loops before we have symmetric containers.
569
+ # NOTE: This means that bounds[0][1] must always exist
570
+
571
+ a_vl = copy.copy(list(vot))
572
+ a_vl[0] = vut[0] # Update aN Origin
573
+ if tuple(a_vl) not in self.V.cache:
574
+ vo = self.V[vot] # initiate if doesn't exist yet
575
+ vs = self.V[vut]
576
+ # Start by finding the old centroid of the new space:
577
+ vco = self.split_edge(vo.x, vs.x) # Split in case not centroid arg
578
+
579
+ # Find set of extreme vertices in current local space
580
+ sup_set = copy.copy(vco.nn)
581
+ a_vl = copy.copy(list(vot))
582
+ a_vl[0] = vut[0] # Update aN Origin
583
+ a_vl = self.V[tuple(a_vl)]
584
+ else:
585
+ a_vl = self.V[tuple(a_vl)]
586
+
587
+ c_v = self.split_edge(vo.x, a_vl.x)
588
+ c_v.connect(vco)
589
+ yield c_v.x
590
+ Cox = [[vo]]
591
+ Ccx = [[c_v]]
592
+ Cux = [[a_vl]]
593
+ ab_C = [] # Container for a + b operations
594
+ s_ab_C = [] # Container for symmetric a + b operations
595
+
596
+ # Loop over remaining bounds
597
+ for i, x in enumerate(bounds[1:]):
598
+ # Update lower and upper containers
599
+ Cox.append([])
600
+ Ccx.append([])
601
+ Cux.append([])
602
+ # try to access a second bound (if not, C1 is symmetric)
603
+ try:
604
+ t_a_vl = list(vot)
605
+ t_a_vl[i + 1] = vut[i + 1]
606
+
607
+ # New: lists are used anyway, so copy all
608
+ # %%
609
+ # Copy lists for iteration
610
+ cCox = [x[:] for x in Cox[:i + 1]]
611
+ cCcx = [x[:] for x in Ccx[:i + 1]]
612
+ cCux = [x[:] for x in Cux[:i + 1]]
613
+ # Try to connect aN lower source of previous a + b
614
+ # operation with a aN vertex
615
+ ab_Cc = copy.copy(ab_C) # NOTE: We append ab_C in the
616
+ # (VL, VC, VU) for-loop, but we use the copy of the list in the
617
+ # ab_Cc for-loop.
618
+ s_ab_Cc = copy.copy(s_ab_C)
619
+
620
+ # Early try so that we don't have to copy the cache before
621
+ # moving on to next C1/C2: Try to add the operation of a new
622
+ # C2 product by accessing the upper bound
623
+ if tuple(t_a_vl) not in self.V.cache:
624
+ # Raise error to continue symmetric refine
625
+ raise IndexError
626
+ t_a_vu = list(vut)
627
+ t_a_vu[i + 1] = vut[i + 1]
628
+ if tuple(t_a_vu) not in self.V.cache:
629
+ # Raise error to continue symmetric refine:
630
+ raise IndexError
631
+
632
+ for vectors in s_ab_Cc:
633
+ # s_ab_C.append([c_vc, vl, vu, a_vu])
634
+ bc_vc = list(vectors[0].x)
635
+ b_vl = list(vectors[1].x)
636
+ b_vu = list(vectors[2].x)
637
+ ba_vu = list(vectors[3].x)
638
+
639
+ bc_vc[i + 1] = vut[i + 1]
640
+ b_vl[i + 1] = vut[i + 1]
641
+ b_vu[i + 1] = vut[i + 1]
642
+ ba_vu[i + 1] = vut[i + 1]
643
+
644
+ bc_vc = self.V[tuple(bc_vc)]
645
+ bc_vc.connect(vco) # NOTE: Unneeded?
646
+ yield bc_vc
647
+
648
+ # Split to centre, call this centre group "d = 0.5*a"
649
+ d_bc_vc = self.split_edge(vectors[0].x, bc_vc.x)
650
+ d_bc_vc.connect(bc_vc)
651
+ d_bc_vc.connect(vectors[1]) # Connect all to centroid
652
+ d_bc_vc.connect(vectors[2]) # Connect all to centroid
653
+ d_bc_vc.connect(vectors[3]) # Connect all to centroid
654
+ yield d_bc_vc.x
655
+ b_vl = self.V[tuple(b_vl)]
656
+ bc_vc.connect(b_vl) # Connect aN cross pairs
657
+ d_bc_vc.connect(b_vl) # Connect all to centroid
658
+
659
+ yield b_vl
660
+ b_vu = self.V[tuple(b_vu)]
661
+ bc_vc.connect(b_vu) # Connect aN cross pairs
662
+ d_bc_vc.connect(b_vu) # Connect all to centroid
663
+
664
+ b_vl_c = self.split_edge(b_vu.x, b_vl.x)
665
+ bc_vc.connect(b_vl_c)
666
+
667
+ yield b_vu
668
+ ba_vu = self.V[tuple(ba_vu)]
669
+ bc_vc.connect(ba_vu) # Connect aN cross pairs
670
+ d_bc_vc.connect(ba_vu) # Connect all to centroid
671
+
672
+ # Split the a + b edge of the initial triangulation:
673
+ os_v = self.split_edge(vectors[1].x, ba_vu.x) # o-s
674
+ ss_v = self.split_edge(b_vl.x, ba_vu.x) # s-s
675
+ b_vu_c = self.split_edge(b_vu.x, ba_vu.x)
676
+ bc_vc.connect(b_vu_c)
677
+ yield os_v.x # often equal to vco, but not always
678
+ yield ss_v.x # often equal to bc_vu, but not always
679
+ yield ba_vu
680
+ # Split remaining to centre, call this centre group
681
+ # "d = 0.5*a"
682
+ d_bc_vc = self.split_edge(vectors[0].x, bc_vc.x)
683
+ d_bc_vc.connect(vco) # NOTE: Unneeded?
684
+ yield d_bc_vc.x
685
+ d_b_vl = self.split_edge(vectors[1].x, b_vl.x)
686
+ d_bc_vc.connect(vco) # NOTE: Unneeded?
687
+ d_bc_vc.connect(d_b_vl) # Connect dN cross pairs
688
+ yield d_b_vl.x
689
+ d_b_vu = self.split_edge(vectors[2].x, b_vu.x)
690
+ d_bc_vc.connect(vco) # NOTE: Unneeded?
691
+ d_bc_vc.connect(d_b_vu) # Connect dN cross pairs
692
+ yield d_b_vu.x
693
+ d_ba_vu = self.split_edge(vectors[3].x, ba_vu.x)
694
+ d_bc_vc.connect(vco) # NOTE: Unneeded?
695
+ d_bc_vc.connect(d_ba_vu) # Connect dN cross pairs
696
+ yield d_ba_vu
697
+
698
+ # comb = [c_vc, vl, vu, a_vl, a_vu,
699
+ # bc_vc, b_vl, b_vu, ba_vl, ba_vu]
700
+ comb = [vl, vu, a_vu,
701
+ b_vl, b_vu, ba_vu]
702
+ comb_iter = itertools.combinations(comb, 2)
703
+ for vecs in comb_iter:
704
+ self.split_edge(vecs[0].x, vecs[1].x)
705
+ # Add new list of cross pairs
706
+ ab_C.append((d_bc_vc, vectors[1], b_vl, a_vu, ba_vu))
707
+ ab_C.append((d_bc_vc, vl, b_vl, a_vu, ba_vu)) # = prev
708
+
709
+ for vectors in ab_Cc:
710
+ bc_vc = list(vectors[0].x)
711
+ b_vl = list(vectors[1].x)
712
+ b_vu = list(vectors[2].x)
713
+ ba_vl = list(vectors[3].x)
714
+ ba_vu = list(vectors[4].x)
715
+ bc_vc[i + 1] = vut[i + 1]
716
+ b_vl[i + 1] = vut[i + 1]
717
+ b_vu[i + 1] = vut[i + 1]
718
+ ba_vl[i + 1] = vut[i + 1]
719
+ ba_vu[i + 1] = vut[i + 1]
720
+ bc_vc = self.V[tuple(bc_vc)]
721
+ bc_vc.connect(vco) # NOTE: Unneeded?
722
+ yield bc_vc
723
+
724
+ # Split to centre, call this centre group "d = 0.5*a"
725
+ d_bc_vc = self.split_edge(vectors[0].x, bc_vc.x)
726
+ d_bc_vc.connect(bc_vc)
727
+ d_bc_vc.connect(vectors[1]) # Connect all to centroid
728
+ d_bc_vc.connect(vectors[2]) # Connect all to centroid
729
+ d_bc_vc.connect(vectors[3]) # Connect all to centroid
730
+ d_bc_vc.connect(vectors[4]) # Connect all to centroid
731
+ yield d_bc_vc.x
732
+ b_vl = self.V[tuple(b_vl)]
733
+ bc_vc.connect(b_vl) # Connect aN cross pairs
734
+ d_bc_vc.connect(b_vl) # Connect all to centroid
735
+ yield b_vl
736
+ b_vu = self.V[tuple(b_vu)]
737
+ bc_vc.connect(b_vu) # Connect aN cross pairs
738
+ d_bc_vc.connect(b_vu) # Connect all to centroid
739
+ yield b_vu
740
+ ba_vl = self.V[tuple(ba_vl)]
741
+ bc_vc.connect(ba_vl) # Connect aN cross pairs
742
+ d_bc_vc.connect(ba_vl) # Connect all to centroid
743
+ self.split_edge(b_vu.x, ba_vl.x)
744
+ yield ba_vl
745
+ ba_vu = self.V[tuple(ba_vu)]
746
+ bc_vc.connect(ba_vu) # Connect aN cross pairs
747
+ d_bc_vc.connect(ba_vu) # Connect all to centroid
748
+ # Split the a + b edge of the initial triangulation:
749
+ os_v = self.split_edge(vectors[1].x, ba_vu.x) # o-s
750
+ ss_v = self.split_edge(b_vl.x, ba_vu.x) # s-s
751
+ yield os_v.x # often equal to vco, but not always
752
+ yield ss_v.x # often equal to bc_vu, but not always
753
+ yield ba_vu
754
+ # Split remaining to centre, call this centre group
755
+ # "d = 0.5*a"
756
+ d_bc_vc = self.split_edge(vectors[0].x, bc_vc.x)
757
+ d_bc_vc.connect(vco) # NOTE: Unneeded?
758
+ yield d_bc_vc.x
759
+ d_b_vl = self.split_edge(vectors[1].x, b_vl.x)
760
+ d_bc_vc.connect(vco) # NOTE: Unneeded?
761
+ d_bc_vc.connect(d_b_vl) # Connect dN cross pairs
762
+ yield d_b_vl.x
763
+ d_b_vu = self.split_edge(vectors[2].x, b_vu.x)
764
+ d_bc_vc.connect(vco) # NOTE: Unneeded?
765
+ d_bc_vc.connect(d_b_vu) # Connect dN cross pairs
766
+ yield d_b_vu.x
767
+ d_ba_vl = self.split_edge(vectors[3].x, ba_vl.x)
768
+ d_bc_vc.connect(vco) # NOTE: Unneeded?
769
+ d_bc_vc.connect(d_ba_vl) # Connect dN cross pairs
770
+ yield d_ba_vl
771
+ d_ba_vu = self.split_edge(vectors[4].x, ba_vu.x)
772
+ d_bc_vc.connect(vco) # NOTE: Unneeded?
773
+ d_bc_vc.connect(d_ba_vu) # Connect dN cross pairs
774
+ yield d_ba_vu
775
+ c_vc, vl, vu, a_vl, a_vu = vectors
776
+
777
+ comb = [vl, vu, a_vl, a_vu,
778
+ b_vl, b_vu, ba_vl, ba_vu]
779
+ comb_iter = itertools.combinations(comb, 2)
780
+ for vecs in comb_iter:
781
+ self.split_edge(vecs[0].x, vecs[1].x)
782
+
783
+ # Add new list of cross pairs
784
+ ab_C.append((bc_vc, b_vl, b_vu, ba_vl, ba_vu))
785
+ ab_C.append((d_bc_vc, d_b_vl, d_b_vu, d_ba_vl, d_ba_vu))
786
+ ab_C.append((d_bc_vc, vectors[1], b_vl, a_vu, ba_vu))
787
+ ab_C.append((d_bc_vc, vu, b_vu, a_vl, ba_vl))
788
+
789
+ for j, (VL, VC, VU) in enumerate(zip(cCox, cCcx, cCux)):
790
+ for k, (vl, vc, vu) in enumerate(zip(VL, VC, VU)):
791
+ # Build aN vertices for each lower-upper C3 group in N:
792
+ a_vl = list(vl.x)
793
+ a_vu = list(vu.x)
794
+ a_vl[i + 1] = vut[i + 1]
795
+ a_vu[i + 1] = vut[i + 1]
796
+ a_vl = self.V[tuple(a_vl)]
797
+ a_vu = self.V[tuple(a_vu)]
798
+ # Note, build (a + vc) later for consistent yields
799
+ # Split the a + b edge of the initial triangulation:
800
+ c_vc = self.split_edge(vl.x, a_vu.x)
801
+ self.split_edge(vl.x, vu.x) # Equal to vc
802
+ # Build cN vertices for each lower-upper C3 group in N:
803
+ c_vc.connect(vco)
804
+ c_vc.connect(vc)
805
+ c_vc.connect(vl) # Connect c + ac operations
806
+ c_vc.connect(vu) # Connect c + ac operations
807
+ c_vc.connect(a_vl) # Connect c + ac operations
808
+ c_vc.connect(a_vu) # Connect c + ac operations
809
+ yield c_vc.x
810
+ c_vl = self.split_edge(vl.x, a_vl.x)
811
+ c_vl.connect(vco)
812
+ c_vc.connect(c_vl) # Connect cN group vertices
813
+ yield c_vl.x
814
+ # yield at end of loop:
815
+ c_vu = self.split_edge(vu.x, a_vu.x)
816
+ c_vu.connect(vco)
817
+ # Connect remaining cN group vertices
818
+ c_vc.connect(c_vu) # Connect cN group vertices
819
+ yield c_vu.x
820
+
821
+ a_vc = self.split_edge(a_vl.x, a_vu.x) # is (a + vc) ?
822
+ a_vc.connect(vco)
823
+ a_vc.connect(c_vc)
824
+
825
+ # Storage for connecting c + ac operations:
826
+ ab_C.append((c_vc, vl, vu, a_vl, a_vu))
827
+
828
+ # Update the containers
829
+ Cox[i + 1].append(vl)
830
+ Cox[i + 1].append(vc)
831
+ Cox[i + 1].append(vu)
832
+ Ccx[i + 1].append(c_vl)
833
+ Ccx[i + 1].append(c_vc)
834
+ Ccx[i + 1].append(c_vu)
835
+ Cux[i + 1].append(a_vl)
836
+ Cux[i + 1].append(a_vc)
837
+ Cux[i + 1].append(a_vu)
838
+
839
+ # Update old containers
840
+ Cox[j].append(c_vl) # !
841
+ Cox[j].append(a_vl)
842
+ Ccx[j].append(c_vc) # !
843
+ Ccx[j].append(a_vc) # !
844
+ Cux[j].append(c_vu) # !
845
+ Cux[j].append(a_vu)
846
+
847
+ # Yield new points
848
+ yield a_vc.x
849
+
850
+ except IndexError:
851
+ for vectors in ab_Cc:
852
+ ba_vl = list(vectors[3].x)
853
+ ba_vu = list(vectors[4].x)
854
+ ba_vl[i + 1] = vut[i + 1]
855
+ ba_vu[i + 1] = vut[i + 1]
856
+ ba_vu = self.V[tuple(ba_vu)]
857
+ yield ba_vu
858
+ d_bc_vc = self.split_edge(vectors[1].x, ba_vu.x) # o-s
859
+ yield ba_vu
860
+ d_bc_vc.connect(vectors[1]) # Connect all to centroid
861
+ d_bc_vc.connect(vectors[2]) # Connect all to centroid
862
+ d_bc_vc.connect(vectors[3]) # Connect all to centroid
863
+ d_bc_vc.connect(vectors[4]) # Connect all to centroid
864
+ yield d_bc_vc.x
865
+ ba_vl = self.V[tuple(ba_vl)]
866
+ yield ba_vl
867
+ d_ba_vl = self.split_edge(vectors[3].x, ba_vl.x)
868
+ d_ba_vu = self.split_edge(vectors[4].x, ba_vu.x)
869
+ d_ba_vc = self.split_edge(d_ba_vl.x, d_ba_vu.x)
870
+ yield d_ba_vl
871
+ yield d_ba_vu
872
+ yield d_ba_vc
873
+ c_vc, vl, vu, a_vl, a_vu = vectors
874
+ comb = [vl, vu, a_vl, a_vu,
875
+ ba_vl,
876
+ ba_vu]
877
+ comb_iter = itertools.combinations(comb, 2)
878
+ for vecs in comb_iter:
879
+ self.split_edge(vecs[0].x, vecs[1].x)
880
+
881
+ # Copy lists for iteration
882
+ cCox = Cox[i]
883
+ cCcx = Ccx[i]
884
+ cCux = Cux[i]
885
+ VL, VC, VU = cCox, cCcx, cCux
886
+ for k, (vl, vc, vu) in enumerate(zip(VL, VC, VU)):
887
+ # Build aN vertices for each lower-upper pair in N:
888
+ a_vu = list(vu.x)
889
+ a_vu[i + 1] = vut[i + 1]
890
+
891
+ # Connect vertices in N to corresponding vertices
892
+ # in aN:
893
+ a_vu = self.V[tuple(a_vu)]
894
+ yield a_vl.x
895
+ # Split the a + b edge of the initial triangulation:
896
+ c_vc = self.split_edge(vl.x, a_vu.x)
897
+ self.split_edge(vl.x, vu.x) # Equal to vc
898
+ c_vc.connect(vco)
899
+ c_vc.connect(vc)
900
+ c_vc.connect(vl) # Connect c + ac operations
901
+ c_vc.connect(vu) # Connect c + ac operations
902
+ c_vc.connect(a_vu) # Connect c + ac operations
903
+ yield (c_vc.x)
904
+ c_vu = self.split_edge(vu.x,
905
+ a_vu.x) # yield at end of loop
906
+ c_vu.connect(vco)
907
+ # Connect remaining cN group vertices
908
+ c_vc.connect(c_vu) # Connect cN group vertices
909
+ yield (c_vu.x)
910
+
911
+ # Update the containers
912
+ Cox[i + 1].append(vu)
913
+ Ccx[i + 1].append(c_vu)
914
+ Cux[i + 1].append(a_vu)
915
+
916
+ # Update old containers
917
+ s_ab_C.append([c_vc, vl, vu, a_vu])
918
+
919
+ yield a_vu.x
920
+
921
+ # Clean class trash
922
+ try:
923
+ del Cox
924
+ del Ccx
925
+ del Cux
926
+ del ab_C
927
+ del ab_Cc
928
+ except UnboundLocalError:
929
+ pass
930
+
931
+ try:
932
+ self.triangulated_vectors.remove((tuple(origin_c),
933
+ tuple(supremum_c)))
934
+ except ValueError:
935
+ # Turn this into a logging warning?
936
+ pass
937
+ # Add newly triangulated vectors:
938
+ for vs in sup_set:
939
+ self.triangulated_vectors.append((tuple(vco.x), tuple(vs.x)))
940
+
941
+ # Extra yield to ensure that the triangulation is completed
942
+ if centroid:
943
+ vcn_set = set()
944
+ c_nn_lists = []
945
+ for vs in sup_set:
946
+ # Build centroid
947
+ c_nn = self.vpool(vco.x, vs.x)
948
+ try:
949
+ c_nn.remove(vcn_set)
950
+ except KeyError:
951
+ pass
952
+ c_nn_lists.append(c_nn)
953
+
954
+ for c_nn in c_nn_lists:
955
+ try:
956
+ c_nn.remove(vcn_set)
957
+ except KeyError:
958
+ pass
959
+
960
+ for vs, c_nn in zip(sup_set, c_nn_lists):
961
+ # Build centroid
962
+ vcn = self.split_edge(vco.x, vs.x)
963
+ vcn_set.add(vcn)
964
+ try: # Shouldn't be needed?
965
+ c_nn.remove(vcn_set)
966
+ except KeyError:
967
+ pass
968
+ for vnn in c_nn:
969
+ vcn.connect(vnn)
970
+ yield vcn.x
971
+ else:
972
+ pass
973
+
974
+ yield vut
975
+ return
976
+
977
+ def refine_star(self, v):
978
+ """Refine the star domain of a vertex `v`."""
979
+ # Copy lists before iteration
980
+ vnn = copy.copy(v.nn)
981
+ v1nn = []
982
+ d_v0v1_set = set()
983
+ for v1 in vnn:
984
+ v1nn.append(copy.copy(v1.nn))
985
+
986
+ for v1, v1nn in zip(vnn, v1nn):
987
+ vnnu = v1nn.intersection(vnn)
988
+
989
+ d_v0v1 = self.split_edge(v.x, v1.x)
990
+ for o_d_v0v1 in d_v0v1_set:
991
+ d_v0v1.connect(o_d_v0v1)
992
+ d_v0v1_set.add(d_v0v1)
993
+ for v2 in vnnu:
994
+ d_v1v2 = self.split_edge(v1.x, v2.x)
995
+ d_v0v1.connect(d_v1v2)
996
+ return
997
+
998
+ @cache
999
+ def split_edge(self, v1, v2):
1000
+ v1 = self.V[v1]
1001
+ v2 = self.V[v2]
1002
+ # Destroy original edge, if it exists:
1003
+ v1.disconnect(v2)
1004
+ # Compute vertex on centre of edge:
1005
+ try:
1006
+ vct = (v2.x_a - v1.x_a) / 2.0 + v1.x_a
1007
+ except TypeError: # Allow for decimal operations
1008
+ vct = (v2.x_a - v1.x_a) / decimal.Decimal(2.0) + v1.x_a
1009
+
1010
+ vc = self.V[tuple(vct)]
1011
+ # Connect to original 2 vertices to the new centre vertex
1012
+ vc.connect(v1)
1013
+ vc.connect(v2)
1014
+ return vc
1015
+
1016
+ def vpool(self, origin, supremum):
1017
+ vot = tuple(origin)
1018
+ vst = tuple(supremum)
1019
+ # Initiate vertices in case they don't exist
1020
+ vo = self.V[vot]
1021
+ vs = self.V[vst]
1022
+
1023
+ # Remove origin - supremum disconnect
1024
+
1025
+ # Find the lower/upper bounds of the refinement hyperrectangle
1026
+ bl = list(vot)
1027
+ bu = list(vst)
1028
+ for i, (voi, vsi) in enumerate(zip(vot, vst)):
1029
+ if bl[i] > vsi:
1030
+ bl[i] = vsi
1031
+ if bu[i] < voi:
1032
+ bu[i] = voi
1033
+
1034
+ # NOTE: This is mostly done with sets/lists because we aren't sure
1035
+ # how well the numpy arrays will scale to thousands of
1036
+ # dimensions.
1037
+ vn_pool = set()
1038
+ vn_pool.update(vo.nn)
1039
+ vn_pool.update(vs.nn)
1040
+ cvn_pool = copy.copy(vn_pool)
1041
+ for vn in cvn_pool:
1042
+ for i, xi in enumerate(vn.x):
1043
+ if bl[i] <= xi <= bu[i]:
1044
+ pass
1045
+ else:
1046
+ try:
1047
+ vn_pool.remove(vn)
1048
+ except KeyError:
1049
+ pass # NOTE: Not all neigbouds are in initial pool
1050
+ return vn_pool
1051
+
1052
+ def vf_to_vv(self, vertices, simplices):
1053
+ """
1054
+ Convert a vertex-face mesh to a vertex-vertex mesh used by this class
1055
+
1056
+ Parameters
1057
+ ----------
1058
+ vertices : list
1059
+ Vertices
1060
+ simplices : list
1061
+ Simplices
1062
+ """
1063
+ if self.dim > 1:
1064
+ for s in simplices:
1065
+ edges = itertools.combinations(s, self.dim)
1066
+ for e in edges:
1067
+ self.V[tuple(vertices[e[0]])].connect(
1068
+ self.V[tuple(vertices[e[1]])])
1069
+ else:
1070
+ for e in simplices:
1071
+ self.V[tuple(vertices[e[0]])].connect(
1072
+ self.V[tuple(vertices[e[1]])])
1073
+ return
1074
+
1075
+ def connect_vertex_non_symm(self, v_x, near=None):
1076
+ """
1077
+ Adds a vertex at coords v_x to the complex that is not symmetric to the
1078
+ initial triangulation and sub-triangulation.
1079
+
1080
+ If near is specified (for example; a star domain or collections of
1081
+ cells known to contain v) then only those simplices containd in near
1082
+ will be searched, this greatly speeds up the process.
1083
+
1084
+ If near is not specified this method will search the entire simplicial
1085
+ complex structure.
1086
+
1087
+ Parameters
1088
+ ----------
1089
+ v_x : tuple
1090
+ Coordinates of non-symmetric vertex
1091
+ near : set or list
1092
+ List of vertices, these are points near v to check for
1093
+ """
1094
+ if near is None:
1095
+ star = self.V
1096
+ else:
1097
+ star = near
1098
+ # Create the vertex origin
1099
+ if tuple(v_x) in self.V.cache:
1100
+ if self.V[v_x] in self.V_non_symm:
1101
+ pass
1102
+ else:
1103
+ return
1104
+
1105
+ self.V[v_x]
1106
+ found_nn = False
1107
+ S_rows = []
1108
+ for v in star:
1109
+ S_rows.append(v.x)
1110
+
1111
+ S_rows = np.array(S_rows)
1112
+ A = np.array(S_rows) - np.array(v_x)
1113
+ # Iterate through all the possible simplices of S_rows
1114
+ for s_i in itertools.combinations(range(S_rows.shape[0]),
1115
+ r=self.dim + 1):
1116
+ # Check if connected, else s_i is not a simplex
1117
+ valid_simplex = True
1118
+ for i in itertools.combinations(s_i, r=2):
1119
+ # Every combination of vertices must be connected, we check of
1120
+ # the current iteration of all combinations of s_i are
1121
+ # connected we break the loop if it is not.
1122
+ if ((self.V[tuple(S_rows[i[1]])] not in
1123
+ self.V[tuple(S_rows[i[0]])].nn)
1124
+ and (self.V[tuple(S_rows[i[0]])] not in
1125
+ self.V[tuple(S_rows[i[1]])].nn)):
1126
+ valid_simplex = False
1127
+ break
1128
+
1129
+ S = S_rows[tuple([s_i])]
1130
+ if valid_simplex:
1131
+ if self.deg_simplex(S, proj=None):
1132
+ valid_simplex = False
1133
+
1134
+ # If s_i is a valid simplex we can test if v_x is inside si
1135
+ if valid_simplex:
1136
+ # Find the A_j0 value from the precalculated values
1137
+ A_j0 = A[tuple([s_i])]
1138
+ if self.in_simplex(S, v_x, A_j0):
1139
+ found_nn = True
1140
+ # breaks the main for loop, s_i is the target simplex:
1141
+ break
1142
+
1143
+ # Connect the simplex to point
1144
+ if found_nn:
1145
+ for i in s_i:
1146
+ self.V[v_x].connect(self.V[tuple(S_rows[i])])
1147
+ # Attached the simplex to storage for all non-symmetric vertices
1148
+ self.V_non_symm.append(self.V[v_x])
1149
+ # this bool value indicates a successful connection if True:
1150
+ return found_nn
1151
+
1152
+ def in_simplex(self, S, v_x, A_j0=None):
1153
+ """Check if a vector v_x is in simplex `S`.
1154
+
1155
+ Parameters
1156
+ ----------
1157
+ S : array_like
1158
+ Array containing simplex entries of vertices as rows
1159
+ v_x :
1160
+ A candidate vertex
1161
+ A_j0 : array, optional,
1162
+ Allows for A_j0 to be pre-calculated
1163
+
1164
+ Returns
1165
+ -------
1166
+ res : boolean
1167
+ True if `v_x` is in `S`
1168
+ """
1169
+ A_11 = np.delete(S, 0, 0) - S[0]
1170
+
1171
+ sign_det_A_11 = np.sign(np.linalg.det(A_11))
1172
+ if sign_det_A_11 == 0:
1173
+ # NOTE: We keep the variable A_11, but we loop through A_jj
1174
+ # ind=
1175
+ # while sign_det_A_11 == 0:
1176
+ # A_11 = np.delete(S, ind, 0) - S[ind]
1177
+ # sign_det_A_11 = np.sign(np.linalg.det(A_11))
1178
+
1179
+ sign_det_A_11 = -1 # TODO: Choose another det of j instead?
1180
+ # TODO: Unlikely to work in many cases
1181
+
1182
+ if A_j0 is None:
1183
+ A_j0 = S - v_x
1184
+
1185
+ for d in range(self.dim + 1):
1186
+ det_A_jj = (-1)**d * sign_det_A_11
1187
+ # TODO: Note that scipy might be faster to add as an optional
1188
+ # dependency
1189
+ sign_det_A_j0 = np.sign(np.linalg.det(np.delete(A_j0, d,
1190
+ 0)))
1191
+ # TODO: Note if sign_det_A_j0 == then the point is coplanar to the
1192
+ # current simplex facet, so perhaps return True and attach?
1193
+ if det_A_jj == sign_det_A_j0:
1194
+ continue
1195
+ else:
1196
+ return False
1197
+
1198
+ return True
1199
+
1200
+ def deg_simplex(self, S, proj=None):
1201
+ """Test a simplex S for degeneracy (linear dependence in R^dim).
1202
+
1203
+ Parameters
1204
+ ----------
1205
+ S : np.array
1206
+ Simplex with rows as vertex vectors
1207
+ proj : array, optional,
1208
+ If the projection S[1:] - S[0] is already
1209
+ computed it can be added as an optional argument.
1210
+ """
1211
+ # Strategy: we test all combination of faces, if any of the
1212
+ # determinants are zero then the vectors lie on the same face and is
1213
+ # therefore linearly dependent in the space of R^dim
1214
+ if proj is None:
1215
+ proj = S[1:] - S[0]
1216
+
1217
+ # TODO: Is checking the projection of one vertex against faces of other
1218
+ # vertices sufficient? Or do we need to check more vertices in
1219
+ # dimensions higher than 2?
1220
+ # TODO: Literature seems to suggest using proj.T, but why is this
1221
+ # needed?
1222
+ if np.linalg.det(proj) == 0.0: # TODO: Repalace with tolerance?
1223
+ return True # Simplex is degenerate
1224
+ else:
1225
+ return False # Simplex is not degenerate
vila/lib/python3.10/site-packages/scipy/optimize/_shgo_lib/_vertex.py ADDED
@@ -0,0 +1,460 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+ from abc import ABC, abstractmethod
3
+
4
+ import numpy as np
5
+
6
+ from scipy._lib._util import MapWrapper
7
+
8
+
9
+ class VertexBase(ABC):
10
+ """
11
+ Base class for a vertex.
12
+ """
13
+ def __init__(self, x, nn=None, index=None):
14
+ """
15
+ Initiation of a vertex object.
16
+
17
+ Parameters
18
+ ----------
19
+ x : tuple or vector
20
+ The geometric location (domain).
21
+ nn : list, optional
22
+ Nearest neighbour list.
23
+ index : int, optional
24
+ Index of vertex.
25
+ """
26
+ self.x = x
27
+ self.hash = hash(self.x) # Save precomputed hash
28
+
29
+ if nn is not None:
30
+ self.nn = set(nn) # can use .indexupdate to add a new list
31
+ else:
32
+ self.nn = set()
33
+
34
+ self.index = index
35
+
36
+ def __hash__(self):
37
+ return self.hash
38
+
39
+ def __getattr__(self, item):
40
+ if item not in ['x_a']:
41
+ raise AttributeError(f"{type(self)} object has no attribute "
42
+ f"'{item}'")
43
+ if item == 'x_a':
44
+ self.x_a = np.array(self.x)
45
+ return self.x_a
46
+
47
+ @abstractmethod
48
+ def connect(self, v):
49
+ raise NotImplementedError("This method is only implemented with an "
50
+ "associated child of the base class.")
51
+
52
+ @abstractmethod
53
+ def disconnect(self, v):
54
+ raise NotImplementedError("This method is only implemented with an "
55
+ "associated child of the base class.")
56
+
57
+ def star(self):
58
+ """Returns the star domain ``st(v)`` of the vertex.
59
+
60
+ Parameters
61
+ ----------
62
+ v :
63
+ The vertex ``v`` in ``st(v)``
64
+
65
+ Returns
66
+ -------
67
+ st : set
68
+ A set containing all the vertices in ``st(v)``
69
+ """
70
+ self.st = self.nn
71
+ self.st.add(self)
72
+ return self.st
73
+
74
+
75
+ class VertexScalarField(VertexBase):
76
+ """
77
+ Add homology properties of a scalar field f: R^n --> R associated with
78
+ the geometry built from the VertexBase class
79
+ """
80
+
81
+ def __init__(self, x, field=None, nn=None, index=None, field_args=(),
82
+ g_cons=None, g_cons_args=()):
83
+ """
84
+ Parameters
85
+ ----------
86
+ x : tuple,
87
+ vector of vertex coordinates
88
+ field : callable, optional
89
+ a scalar field f: R^n --> R associated with the geometry
90
+ nn : list, optional
91
+ list of nearest neighbours
92
+ index : int, optional
93
+ index of the vertex
94
+ field_args : tuple, optional
95
+ additional arguments to be passed to field
96
+ g_cons : callable, optional
97
+ constraints on the vertex
98
+ g_cons_args : tuple, optional
99
+ additional arguments to be passed to g_cons
100
+
101
+ """
102
+ super().__init__(x, nn=nn, index=index)
103
+
104
+ # Note Vertex is only initiated once for all x so only
105
+ # evaluated once
106
+ # self.feasible = None
107
+
108
+ # self.f is externally defined by the cache to allow parallel
109
+ # processing
110
+ # None type that will break arithmetic operations unless defined
111
+ # self.f = None
112
+
113
+ self.check_min = True
114
+ self.check_max = True
115
+
116
+ def connect(self, v):
117
+ """Connects self to another vertex object v.
118
+
119
+ Parameters
120
+ ----------
121
+ v : VertexBase or VertexScalarField object
122
+ """
123
+ if v is not self and v not in self.nn:
124
+ self.nn.add(v)
125
+ v.nn.add(self)
126
+
127
+ # Flags for checking homology properties:
128
+ self.check_min = True
129
+ self.check_max = True
130
+ v.check_min = True
131
+ v.check_max = True
132
+
133
+ def disconnect(self, v):
134
+ if v in self.nn:
135
+ self.nn.remove(v)
136
+ v.nn.remove(self)
137
+
138
+ # Flags for checking homology properties:
139
+ self.check_min = True
140
+ self.check_max = True
141
+ v.check_min = True
142
+ v.check_max = True
143
+
144
+ def minimiser(self):
145
+ """Check whether this vertex is strictly less than all its
146
+ neighbours"""
147
+ if self.check_min:
148
+ self._min = all(self.f < v.f for v in self.nn)
149
+ self.check_min = False
150
+
151
+ return self._min
152
+
153
+ def maximiser(self):
154
+ """
155
+ Check whether this vertex is strictly greater than all its
156
+ neighbours.
157
+ """
158
+ if self.check_max:
159
+ self._max = all(self.f > v.f for v in self.nn)
160
+ self.check_max = False
161
+
162
+ return self._max
163
+
164
+
165
+ class VertexVectorField(VertexBase):
166
+ """
167
+ Add homology properties of a scalar field f: R^n --> R^m associated with
168
+ the geometry built from the VertexBase class.
169
+ """
170
+
171
+ def __init__(self, x, sfield=None, vfield=None, field_args=(),
172
+ vfield_args=(), g_cons=None,
173
+ g_cons_args=(), nn=None, index=None):
174
+ super().__init__(x, nn=nn, index=index)
175
+
176
+ raise NotImplementedError("This class is still a work in progress")
177
+
178
+
179
+ class VertexCacheBase:
180
+ """Base class for a vertex cache for a simplicial complex."""
181
+ def __init__(self):
182
+
183
+ self.cache = collections.OrderedDict()
184
+ self.nfev = 0 # Feasible points
185
+ self.index = -1
186
+
187
+ def __iter__(self):
188
+ for v in self.cache:
189
+ yield self.cache[v]
190
+ return
191
+
192
+ def size(self):
193
+ """Returns the size of the vertex cache."""
194
+ return self.index + 1
195
+
196
+ def print_out(self):
197
+ headlen = len(f"Vertex cache of size: {len(self.cache)}:")
198
+ print('=' * headlen)
199
+ print(f"Vertex cache of size: {len(self.cache)}:")
200
+ print('=' * headlen)
201
+ for v in self.cache:
202
+ self.cache[v].print_out()
203
+
204
+
205
+ class VertexCube(VertexBase):
206
+ """Vertex class to be used for a pure simplicial complex with no associated
207
+ differential geometry (single level domain that exists in R^n)"""
208
+ def __init__(self, x, nn=None, index=None):
209
+ super().__init__(x, nn=nn, index=index)
210
+
211
+ def connect(self, v):
212
+ if v is not self and v not in self.nn:
213
+ self.nn.add(v)
214
+ v.nn.add(self)
215
+
216
+ def disconnect(self, v):
217
+ if v in self.nn:
218
+ self.nn.remove(v)
219
+ v.nn.remove(self)
220
+
221
+
222
+ class VertexCacheIndex(VertexCacheBase):
223
+ def __init__(self):
224
+ """
225
+ Class for a vertex cache for a simplicial complex without an associated
226
+ field. Useful only for building and visualising a domain complex.
227
+
228
+ Parameters
229
+ ----------
230
+ """
231
+ super().__init__()
232
+ self.Vertex = VertexCube
233
+
234
+ def __getitem__(self, x, nn=None):
235
+ try:
236
+ return self.cache[x]
237
+ except KeyError:
238
+ self.index += 1
239
+ xval = self.Vertex(x, index=self.index)
240
+ # logging.info("New generated vertex at x = {}".format(x))
241
+ # NOTE: Surprisingly high performance increase if logging
242
+ # is commented out
243
+ self.cache[x] = xval
244
+ return self.cache[x]
245
+
246
+
247
+ class VertexCacheField(VertexCacheBase):
248
+ def __init__(self, field=None, field_args=(), g_cons=None, g_cons_args=(),
249
+ workers=1):
250
+ """
251
+ Class for a vertex cache for a simplicial complex with an associated
252
+ field.
253
+
254
+ Parameters
255
+ ----------
256
+ field : callable
257
+ Scalar or vector field callable.
258
+ field_args : tuple, optional
259
+ Any additional fixed parameters needed to completely specify the
260
+ field function
261
+ g_cons : dict or sequence of dict, optional
262
+ Constraints definition.
263
+ Function(s) ``R**n`` in the form::
264
+ g_cons_args : tuple, optional
265
+ Any additional fixed parameters needed to completely specify the
266
+ constraint functions
267
+ workers : int optional
268
+ Uses `multiprocessing.Pool <multiprocessing>`) to compute the field
269
+ functions in parallel.
270
+
271
+ """
272
+ super().__init__()
273
+ self.index = -1
274
+ self.Vertex = VertexScalarField
275
+ self.field = field
276
+ self.field_args = field_args
277
+ self.wfield = FieldWrapper(field, field_args) # if workers is not 1
278
+
279
+ self.g_cons = g_cons
280
+ self.g_cons_args = g_cons_args
281
+ self.wgcons = ConstraintWrapper(g_cons, g_cons_args)
282
+ self.gpool = set() # A set of tuples to process for feasibility
283
+
284
+ # Field processing objects
285
+ self.fpool = set() # A set of tuples to process for scalar function
286
+ self.sfc_lock = False # True if self.fpool is non-Empty
287
+
288
+ self.workers = workers
289
+ self._mapwrapper = MapWrapper(workers)
290
+
291
+ if workers == 1:
292
+ self.process_gpool = self.proc_gpool
293
+ if g_cons is None:
294
+ self.process_fpool = self.proc_fpool_nog
295
+ else:
296
+ self.process_fpool = self.proc_fpool_g
297
+ else:
298
+ self.process_gpool = self.pproc_gpool
299
+ if g_cons is None:
300
+ self.process_fpool = self.pproc_fpool_nog
301
+ else:
302
+ self.process_fpool = self.pproc_fpool_g
303
+
304
+ def __getitem__(self, x, nn=None):
305
+ try:
306
+ return self.cache[x]
307
+ except KeyError:
308
+ self.index += 1
309
+ xval = self.Vertex(x, field=self.field, nn=nn, index=self.index,
310
+ field_args=self.field_args,
311
+ g_cons=self.g_cons,
312
+ g_cons_args=self.g_cons_args)
313
+
314
+ self.cache[x] = xval # Define in cache
315
+ self.gpool.add(xval) # Add to pool for processing feasibility
316
+ self.fpool.add(xval) # Add to pool for processing field values
317
+ return self.cache[x]
318
+
319
+ def __getstate__(self):
320
+ self_dict = self.__dict__.copy()
321
+ del self_dict['pool']
322
+ return self_dict
323
+
324
+ def process_pools(self):
325
+ if self.g_cons is not None:
326
+ self.process_gpool()
327
+ self.process_fpool()
328
+ self.proc_minimisers()
329
+
330
+ def feasibility_check(self, v):
331
+ v.feasible = True
332
+ for g, args in zip(self.g_cons, self.g_cons_args):
333
+ # constraint may return more than 1 value.
334
+ if np.any(g(v.x_a, *args) < 0.0):
335
+ v.f = np.inf
336
+ v.feasible = False
337
+ break
338
+
339
+ def compute_sfield(self, v):
340
+ """Compute the scalar field values of a vertex object `v`.
341
+
342
+ Parameters
343
+ ----------
344
+ v : VertexBase or VertexScalarField object
345
+ """
346
+ try:
347
+ v.f = self.field(v.x_a, *self.field_args)
348
+ self.nfev += 1
349
+ except AttributeError:
350
+ v.f = np.inf
351
+ # logging.warning(f"Field function not found at x = {self.x_a}")
352
+ if np.isnan(v.f):
353
+ v.f = np.inf
354
+
355
+ def proc_gpool(self):
356
+ """Process all constraints."""
357
+ if self.g_cons is not None:
358
+ for v in self.gpool:
359
+ self.feasibility_check(v)
360
+ # Clean the pool
361
+ self.gpool = set()
362
+
363
+ def pproc_gpool(self):
364
+ """Process all constraints in parallel."""
365
+ gpool_l = []
366
+ for v in self.gpool:
367
+ gpool_l.append(v.x_a)
368
+
369
+ G = self._mapwrapper(self.wgcons.gcons, gpool_l)
370
+ for v, g in zip(self.gpool, G):
371
+ v.feasible = g # set vertex object attribute v.feasible = g (bool)
372
+
373
+ def proc_fpool_g(self):
374
+ """Process all field functions with constraints supplied."""
375
+ for v in self.fpool:
376
+ if v.feasible:
377
+ self.compute_sfield(v)
378
+ # Clean the pool
379
+ self.fpool = set()
380
+
381
+ def proc_fpool_nog(self):
382
+ """Process all field functions with no constraints supplied."""
383
+ for v in self.fpool:
384
+ self.compute_sfield(v)
385
+ # Clean the pool
386
+ self.fpool = set()
387
+
388
+ def pproc_fpool_g(self):
389
+ """
390
+ Process all field functions with constraints supplied in parallel.
391
+ """
392
+ self.wfield.func
393
+ fpool_l = []
394
+ for v in self.fpool:
395
+ if v.feasible:
396
+ fpool_l.append(v.x_a)
397
+ else:
398
+ v.f = np.inf
399
+ F = self._mapwrapper(self.wfield.func, fpool_l)
400
+ for va, f in zip(fpool_l, F):
401
+ vt = tuple(va)
402
+ self[vt].f = f # set vertex object attribute v.f = f
403
+ self.nfev += 1
404
+ # Clean the pool
405
+ self.fpool = set()
406
+
407
+ def pproc_fpool_nog(self):
408
+ """
409
+ Process all field functions with no constraints supplied in parallel.
410
+ """
411
+ self.wfield.func
412
+ fpool_l = []
413
+ for v in self.fpool:
414
+ fpool_l.append(v.x_a)
415
+ F = self._mapwrapper(self.wfield.func, fpool_l)
416
+ for va, f in zip(fpool_l, F):
417
+ vt = tuple(va)
418
+ self[vt].f = f # set vertex object attribute v.f = f
419
+ self.nfev += 1
420
+ # Clean the pool
421
+ self.fpool = set()
422
+
423
+ def proc_minimisers(self):
424
+ """Check for minimisers."""
425
+ for v in self:
426
+ v.minimiser()
427
+ v.maximiser()
428
+
429
+
430
+ class ConstraintWrapper:
431
+ """Object to wrap constraints to pass to `multiprocessing.Pool`."""
432
+ def __init__(self, g_cons, g_cons_args):
433
+ self.g_cons = g_cons
434
+ self.g_cons_args = g_cons_args
435
+
436
+ def gcons(self, v_x_a):
437
+ vfeasible = True
438
+ for g, args in zip(self.g_cons, self.g_cons_args):
439
+ # constraint may return more than 1 value.
440
+ if np.any(g(v_x_a, *args) < 0.0):
441
+ vfeasible = False
442
+ break
443
+ return vfeasible
444
+
445
+
446
+ class FieldWrapper:
447
+ """Object to wrap field to pass to `multiprocessing.Pool`."""
448
+ def __init__(self, field, field_args):
449
+ self.field = field
450
+ self.field_args = field_args
451
+
452
+ def func(self, v_x_a):
453
+ try:
454
+ v_f = self.field(v_x_a, *self.field_args)
455
+ except Exception:
456
+ v_f = np.inf
457
+ if np.isnan(v_f):
458
+ v_f = np.inf
459
+
460
+ return v_f
vila/lib/python3.10/site-packages/scipy/optimize/_slsqp.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (86.6 kB). View file
 
vila/lib/python3.10/site-packages/scipy/optimize/_tnc.py ADDED
@@ -0,0 +1,430 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # TNC Python interface
2
+ # @(#) $Jeannot: tnc.py,v 1.11 2005/01/28 18:27:31 js Exp $
3
+
4
+ # Copyright (c) 2004-2005, Jean-Sebastien Roy (js@jeannot.org)
5
+
6
+ # Permission is hereby granted, free of charge, to any person obtaining a
7
+ # copy of this software and associated documentation files (the
8
+ # "Software"), to deal in the Software without restriction, including
9
+ # without limitation the rights to use, copy, modify, merge, publish,
10
+ # distribute, sublicense, and/or sell copies of the Software, and to
11
+ # permit persons to whom the Software is furnished to do so, subject to
12
+ # the following conditions:
13
+
14
+ # The above copyright notice and this permission notice shall be included
15
+ # in all copies or substantial portions of the Software.
16
+
17
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
18
+ # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
20
+ # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
21
+ # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
22
+ # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
23
+ # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24
+
25
+ """
26
+ TNC: A Python interface to the TNC non-linear optimizer
27
+
28
+ TNC is a non-linear optimizer. To use it, you must provide a function to
29
+ minimize. The function must take one argument: the list of coordinates where to
30
+ evaluate the function; and it must return either a tuple, whose first element is the
31
+ value of the function, and whose second argument is the gradient of the function
32
+ (as a list of values); or None, to abort the minimization.
33
+ """
34
+
35
+ from scipy.optimize import _moduleTNC as moduleTNC
36
+ from ._optimize import (MemoizeJac, OptimizeResult, _check_unknown_options,
37
+ _prepare_scalar_function)
38
+ from ._constraints import old_bound_to_new
39
+ from scipy._lib._array_api import atleast_nd, array_namespace
40
+
41
+ from numpy import inf, array, zeros
42
+
43
+ __all__ = ['fmin_tnc']
44
+
45
+
46
+ MSG_NONE = 0 # No messages
47
+ MSG_ITER = 1 # One line per iteration
48
+ MSG_INFO = 2 # Informational messages
49
+ MSG_VERS = 4 # Version info
50
+ MSG_EXIT = 8 # Exit reasons
51
+ MSG_ALL = MSG_ITER + MSG_INFO + MSG_VERS + MSG_EXIT
52
+
53
+ MSGS = {
54
+ MSG_NONE: "No messages",
55
+ MSG_ITER: "One line per iteration",
56
+ MSG_INFO: "Informational messages",
57
+ MSG_VERS: "Version info",
58
+ MSG_EXIT: "Exit reasons",
59
+ MSG_ALL: "All messages"
60
+ }
61
+
62
+ INFEASIBLE = -1 # Infeasible (lower bound > upper bound)
63
+ LOCALMINIMUM = 0 # Local minimum reached (|pg| ~= 0)
64
+ FCONVERGED = 1 # Converged (|f_n-f_(n-1)| ~= 0)
65
+ XCONVERGED = 2 # Converged (|x_n-x_(n-1)| ~= 0)
66
+ MAXFUN = 3 # Max. number of function evaluations reached
67
+ LSFAIL = 4 # Linear search failed
68
+ CONSTANT = 5 # All lower bounds are equal to the upper bounds
69
+ NOPROGRESS = 6 # Unable to progress
70
+ USERABORT = 7 # User requested end of minimization
71
+
72
+ RCSTRINGS = {
73
+ INFEASIBLE: "Infeasible (lower bound > upper bound)",
74
+ LOCALMINIMUM: "Local minimum reached (|pg| ~= 0)",
75
+ FCONVERGED: "Converged (|f_n-f_(n-1)| ~= 0)",
76
+ XCONVERGED: "Converged (|x_n-x_(n-1)| ~= 0)",
77
+ MAXFUN: "Max. number of function evaluations reached",
78
+ LSFAIL: "Linear search failed",
79
+ CONSTANT: "All lower bounds are equal to the upper bounds",
80
+ NOPROGRESS: "Unable to progress",
81
+ USERABORT: "User requested end of minimization"
82
+ }
83
+
84
+ # Changes to interface made by Travis Oliphant, Apr. 2004 for inclusion in
85
+ # SciPy
86
+
87
+
88
+ def fmin_tnc(func, x0, fprime=None, args=(), approx_grad=0,
89
+ bounds=None, epsilon=1e-8, scale=None, offset=None,
90
+ messages=MSG_ALL, maxCGit=-1, maxfun=None, eta=-1,
91
+ stepmx=0, accuracy=0, fmin=0, ftol=-1, xtol=-1, pgtol=-1,
92
+ rescale=-1, disp=None, callback=None):
93
+ """
94
+ Minimize a function with variables subject to bounds, using
95
+ gradient information in a truncated Newton algorithm. This
96
+ method wraps a C implementation of the algorithm.
97
+
98
+ Parameters
99
+ ----------
100
+ func : callable ``func(x, *args)``
101
+ Function to minimize. Must do one of:
102
+
103
+ 1. Return f and g, where f is the value of the function and g its
104
+ gradient (a list of floats).
105
+
106
+ 2. Return the function value but supply gradient function
107
+ separately as `fprime`.
108
+
109
+ 3. Return the function value and set ``approx_grad=True``.
110
+
111
+ If the function returns None, the minimization
112
+ is aborted.
113
+ x0 : array_like
114
+ Initial estimate of minimum.
115
+ fprime : callable ``fprime(x, *args)``, optional
116
+ Gradient of `func`. If None, then either `func` must return the
117
+ function value and the gradient (``f,g = func(x, *args)``)
118
+ or `approx_grad` must be True.
119
+ args : tuple, optional
120
+ Arguments to pass to function.
121
+ approx_grad : bool, optional
122
+ If true, approximate the gradient numerically.
123
+ bounds : list, optional
124
+ (min, max) pairs for each element in x0, defining the
125
+ bounds on that parameter. Use None or +/-inf for one of
126
+ min or max when there is no bound in that direction.
127
+ epsilon : float, optional
128
+ Used if approx_grad is True. The stepsize in a finite
129
+ difference approximation for fprime.
130
+ scale : array_like, optional
131
+ Scaling factors to apply to each variable. If None, the
132
+ factors are up-low for interval bounded variables and
133
+ 1+|x| for the others. Defaults to None.
134
+ offset : array_like, optional
135
+ Value to subtract from each variable. If None, the
136
+ offsets are (up+low)/2 for interval bounded variables
137
+ and x for the others.
138
+ messages : int, optional
139
+ Bit mask used to select messages display during
140
+ minimization values defined in the MSGS dict. Defaults to
141
+ MGS_ALL.
142
+ disp : int, optional
143
+ Integer interface to messages. 0 = no message, 5 = all messages
144
+ maxCGit : int, optional
145
+ Maximum number of hessian*vector evaluations per main
146
+ iteration. If maxCGit == 0, the direction chosen is
147
+ -gradient if maxCGit < 0, maxCGit is set to
148
+ max(1,min(50,n/2)). Defaults to -1.
149
+ maxfun : int, optional
150
+ Maximum number of function evaluation. If None, maxfun is
151
+ set to max(100, 10*len(x0)). Defaults to None. Note that this function
152
+ may violate the limit because of evaluating gradients by numerical
153
+ differentiation.
154
+ eta : float, optional
155
+ Severity of the line search. If < 0 or > 1, set to 0.25.
156
+ Defaults to -1.
157
+ stepmx : float, optional
158
+ Maximum step for the line search. May be increased during
159
+ call. If too small, it will be set to 10.0. Defaults to 0.
160
+ accuracy : float, optional
161
+ Relative precision for finite difference calculations. If
162
+ <= machine_precision, set to sqrt(machine_precision).
163
+ Defaults to 0.
164
+ fmin : float, optional
165
+ Minimum function value estimate. Defaults to 0.
166
+ ftol : float, optional
167
+ Precision goal for the value of f in the stopping criterion.
168
+ If ftol < 0.0, ftol is set to 0.0 defaults to -1.
169
+ xtol : float, optional
170
+ Precision goal for the value of x in the stopping
171
+ criterion (after applying x scaling factors). If xtol <
172
+ 0.0, xtol is set to sqrt(machine_precision). Defaults to
173
+ -1.
174
+ pgtol : float, optional
175
+ Precision goal for the value of the projected gradient in
176
+ the stopping criterion (after applying x scaling factors).
177
+ If pgtol < 0.0, pgtol is set to 1e-2 * sqrt(accuracy).
178
+ Setting it to 0.0 is not recommended. Defaults to -1.
179
+ rescale : float, optional
180
+ Scaling factor (in log10) used to trigger f value
181
+ rescaling. If 0, rescale at each iteration. If a large
182
+ value, never rescale. If < 0, rescale is set to 1.3.
183
+ callback : callable, optional
184
+ Called after each iteration, as callback(xk), where xk is the
185
+ current parameter vector.
186
+
187
+ Returns
188
+ -------
189
+ x : ndarray
190
+ The solution.
191
+ nfeval : int
192
+ The number of function evaluations.
193
+ rc : int
194
+ Return code, see below
195
+
196
+ See also
197
+ --------
198
+ minimize: Interface to minimization algorithms for multivariate
199
+ functions. See the 'TNC' `method` in particular.
200
+
201
+ Notes
202
+ -----
203
+ The underlying algorithm is truncated Newton, also called
204
+ Newton Conjugate-Gradient. This method differs from
205
+ scipy.optimize.fmin_ncg in that
206
+
207
+ 1. it wraps a C implementation of the algorithm
208
+ 2. it allows each variable to be given an upper and lower bound.
209
+
210
+ The algorithm incorporates the bound constraints by determining
211
+ the descent direction as in an unconstrained truncated Newton,
212
+ but never taking a step-size large enough to leave the space
213
+ of feasible x's. The algorithm keeps track of a set of
214
+ currently active constraints, and ignores them when computing
215
+ the minimum allowable step size. (The x's associated with the
216
+ active constraint are kept fixed.) If the maximum allowable
217
+ step size is zero then a new constraint is added. At the end
218
+ of each iteration one of the constraints may be deemed no
219
+ longer active and removed. A constraint is considered
220
+ no longer active is if it is currently active
221
+ but the gradient for that variable points inward from the
222
+ constraint. The specific constraint removed is the one
223
+ associated with the variable of largest index whose
224
+ constraint is no longer active.
225
+
226
+ Return codes are defined as follows::
227
+
228
+ -1 : Infeasible (lower bound > upper bound)
229
+ 0 : Local minimum reached (|pg| ~= 0)
230
+ 1 : Converged (|f_n-f_(n-1)| ~= 0)
231
+ 2 : Converged (|x_n-x_(n-1)| ~= 0)
232
+ 3 : Max. number of function evaluations reached
233
+ 4 : Linear search failed
234
+ 5 : All lower bounds are equal to the upper bounds
235
+ 6 : Unable to progress
236
+ 7 : User requested end of minimization
237
+
238
+ References
239
+ ----------
240
+ Wright S., Nocedal J. (2006), 'Numerical Optimization'
241
+
242
+ Nash S.G. (1984), "Newton-Type Minimization Via the Lanczos Method",
243
+ SIAM Journal of Numerical Analysis 21, pp. 770-778
244
+
245
+ """
246
+ # handle fprime/approx_grad
247
+ if approx_grad:
248
+ fun = func
249
+ jac = None
250
+ elif fprime is None:
251
+ fun = MemoizeJac(func)
252
+ jac = fun.derivative
253
+ else:
254
+ fun = func
255
+ jac = fprime
256
+
257
+ if disp is not None: # disp takes precedence over messages
258
+ mesg_num = disp
259
+ else:
260
+ mesg_num = {0:MSG_NONE, 1:MSG_ITER, 2:MSG_INFO, 3:MSG_VERS,
261
+ 4:MSG_EXIT, 5:MSG_ALL}.get(messages, MSG_ALL)
262
+ # build options
263
+ opts = {'eps': epsilon,
264
+ 'scale': scale,
265
+ 'offset': offset,
266
+ 'mesg_num': mesg_num,
267
+ 'maxCGit': maxCGit,
268
+ 'maxfun': maxfun,
269
+ 'eta': eta,
270
+ 'stepmx': stepmx,
271
+ 'accuracy': accuracy,
272
+ 'minfev': fmin,
273
+ 'ftol': ftol,
274
+ 'xtol': xtol,
275
+ 'gtol': pgtol,
276
+ 'rescale': rescale,
277
+ 'disp': False}
278
+
279
+ res = _minimize_tnc(fun, x0, args, jac, bounds, callback=callback, **opts)
280
+
281
+ return res['x'], res['nfev'], res['status']
282
+
283
+
284
+ def _minimize_tnc(fun, x0, args=(), jac=None, bounds=None,
285
+ eps=1e-8, scale=None, offset=None, mesg_num=None,
286
+ maxCGit=-1, eta=-1, stepmx=0, accuracy=0,
287
+ minfev=0, ftol=-1, xtol=-1, gtol=-1, rescale=-1, disp=False,
288
+ callback=None, finite_diff_rel_step=None, maxfun=None,
289
+ **unknown_options):
290
+ """
291
+ Minimize a scalar function of one or more variables using a truncated
292
+ Newton (TNC) algorithm.
293
+
294
+ Options
295
+ -------
296
+ eps : float or ndarray
297
+ If `jac is None` the absolute step size used for numerical
298
+ approximation of the jacobian via forward differences.
299
+ scale : list of floats
300
+ Scaling factors to apply to each variable. If None, the
301
+ factors are up-low for interval bounded variables and
302
+ 1+|x] for the others. Defaults to None.
303
+ offset : float
304
+ Value to subtract from each variable. If None, the
305
+ offsets are (up+low)/2 for interval bounded variables
306
+ and x for the others.
307
+ disp : bool
308
+ Set to True to print convergence messages.
309
+ maxCGit : int
310
+ Maximum number of hessian*vector evaluations per main
311
+ iteration. If maxCGit == 0, the direction chosen is
312
+ -gradient if maxCGit < 0, maxCGit is set to
313
+ max(1,min(50,n/2)). Defaults to -1.
314
+ eta : float
315
+ Severity of the line search. If < 0 or > 1, set to 0.25.
316
+ Defaults to -1.
317
+ stepmx : float
318
+ Maximum step for the line search. May be increased during
319
+ call. If too small, it will be set to 10.0. Defaults to 0.
320
+ accuracy : float
321
+ Relative precision for finite difference calculations. If
322
+ <= machine_precision, set to sqrt(machine_precision).
323
+ Defaults to 0.
324
+ minfev : float
325
+ Minimum function value estimate. Defaults to 0.
326
+ ftol : float
327
+ Precision goal for the value of f in the stopping criterion.
328
+ If ftol < 0.0, ftol is set to 0.0 defaults to -1.
329
+ xtol : float
330
+ Precision goal for the value of x in the stopping
331
+ criterion (after applying x scaling factors). If xtol <
332
+ 0.0, xtol is set to sqrt(machine_precision). Defaults to
333
+ -1.
334
+ gtol : float
335
+ Precision goal for the value of the projected gradient in
336
+ the stopping criterion (after applying x scaling factors).
337
+ If gtol < 0.0, gtol is set to 1e-2 * sqrt(accuracy).
338
+ Setting it to 0.0 is not recommended. Defaults to -1.
339
+ rescale : float
340
+ Scaling factor (in log10) used to trigger f value
341
+ rescaling. If 0, rescale at each iteration. If a large
342
+ value, never rescale. If < 0, rescale is set to 1.3.
343
+ finite_diff_rel_step : None or array_like, optional
344
+ If `jac in ['2-point', '3-point', 'cs']` the relative step size to
345
+ use for numerical approximation of the jacobian. The absolute step
346
+ size is computed as ``h = rel_step * sign(x) * max(1, abs(x))``,
347
+ possibly adjusted to fit into the bounds. For ``method='3-point'``
348
+ the sign of `h` is ignored. If None (default) then step is selected
349
+ automatically.
350
+ maxfun : int
351
+ Maximum number of function evaluations. If None, `maxfun` is
352
+ set to max(100, 10*len(x0)). Defaults to None.
353
+ """
354
+ _check_unknown_options(unknown_options)
355
+ fmin = minfev
356
+ pgtol = gtol
357
+
358
+ xp = array_namespace(x0)
359
+ x0 = atleast_nd(x0, ndim=1, xp=xp)
360
+ dtype = xp.float64
361
+ if xp.isdtype(x0.dtype, "real floating"):
362
+ dtype = x0.dtype
363
+ x0 = xp.reshape(xp.astype(x0, dtype), -1)
364
+
365
+ n = len(x0)
366
+
367
+ if bounds is None:
368
+ bounds = [(None,None)] * n
369
+ if len(bounds) != n:
370
+ raise ValueError('length of x0 != length of bounds')
371
+ new_bounds = old_bound_to_new(bounds)
372
+
373
+ if mesg_num is not None:
374
+ messages = {0:MSG_NONE, 1:MSG_ITER, 2:MSG_INFO, 3:MSG_VERS,
375
+ 4:MSG_EXIT, 5:MSG_ALL}.get(mesg_num, MSG_ALL)
376
+ elif disp:
377
+ messages = MSG_ALL
378
+ else:
379
+ messages = MSG_NONE
380
+
381
+ sf = _prepare_scalar_function(fun, x0, jac=jac, args=args, epsilon=eps,
382
+ finite_diff_rel_step=finite_diff_rel_step,
383
+ bounds=new_bounds)
384
+ func_and_grad = sf.fun_and_grad
385
+
386
+ """
387
+ low, up : the bounds (lists of floats)
388
+ if low is None, the lower bounds are removed.
389
+ if up is None, the upper bounds are removed.
390
+ low and up defaults to None
391
+ """
392
+ low = zeros(n)
393
+ up = zeros(n)
394
+ for i in range(n):
395
+ if bounds[i] is None:
396
+ l, u = -inf, inf
397
+ else:
398
+ l,u = bounds[i]
399
+ if l is None:
400
+ low[i] = -inf
401
+ else:
402
+ low[i] = l
403
+ if u is None:
404
+ up[i] = inf
405
+ else:
406
+ up[i] = u
407
+
408
+ if scale is None:
409
+ scale = array([])
410
+
411
+ if offset is None:
412
+ offset = array([])
413
+
414
+ if maxfun is None:
415
+ maxfun = max(100, 10*len(x0))
416
+
417
+ rc, nf, nit, x, funv, jacv = moduleTNC.tnc_minimize(
418
+ func_and_grad, x0, low, up, scale,
419
+ offset, messages, maxCGit, maxfun,
420
+ eta, stepmx, accuracy, fmin, ftol,
421
+ xtol, pgtol, rescale, callback
422
+ )
423
+ # the TNC documentation states: "On output, x, f and g may be very
424
+ # slightly out of sync because of scaling". Therefore re-evaluate
425
+ # func_and_grad so they are synced.
426
+ funv, jacv = func_and_grad(x)
427
+
428
+ return OptimizeResult(x=x, fun=funv, jac=jacv, nfev=sf.nfev,
429
+ nit=nit, status=rc, message=RCSTRINGS[rc],
430
+ success=(-1 < rc < 3))
vila/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ """This module contains the equality constrained SQP solver."""
2
+
3
+
4
+ from .minimize_trustregion_constr import _minimize_trustregion_constr
5
+
6
+ __all__ = ['_minimize_trustregion_constr']
vila/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (360 Bytes). View file
 
vila/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__pycache__/canonical_constraint.cpython-310.pyc ADDED
Binary file (12.7 kB). View file
 
vila/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__pycache__/equality_constrained_sqp.cpython-310.pyc ADDED
Binary file (4.49 kB). View file