qoro-divi 0.2.0b1__py3-none-any.whl → 0.6.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. divi/__init__.py +1 -2
  2. divi/backends/__init__.py +10 -0
  3. divi/backends/_backend_properties_conversion.py +227 -0
  4. divi/backends/_circuit_runner.py +70 -0
  5. divi/backends/_execution_result.py +70 -0
  6. divi/backends/_parallel_simulator.py +486 -0
  7. divi/backends/_qoro_service.py +663 -0
  8. divi/backends/_qpu_system.py +101 -0
  9. divi/backends/_results_processing.py +133 -0
  10. divi/circuits/__init__.py +13 -0
  11. divi/{exp/cirq → circuits/_cirq}/__init__.py +1 -2
  12. divi/circuits/_cirq/_parser.py +110 -0
  13. divi/circuits/_cirq/_qasm_export.py +78 -0
  14. divi/circuits/_core.py +391 -0
  15. divi/{qasm.py → circuits/_qasm_conversion.py} +73 -14
  16. divi/circuits/_qasm_validation.py +694 -0
  17. divi/qprog/__init__.py +27 -8
  18. divi/qprog/_expectation.py +181 -0
  19. divi/qprog/_hamiltonians.py +281 -0
  20. divi/qprog/algorithms/__init__.py +16 -0
  21. divi/qprog/algorithms/_ansatze.py +368 -0
  22. divi/qprog/algorithms/_custom_vqa.py +263 -0
  23. divi/qprog/algorithms/_pce.py +262 -0
  24. divi/qprog/algorithms/_qaoa.py +579 -0
  25. divi/qprog/algorithms/_vqe.py +262 -0
  26. divi/qprog/batch.py +387 -74
  27. divi/qprog/checkpointing.py +556 -0
  28. divi/qprog/exceptions.py +9 -0
  29. divi/qprog/optimizers.py +1014 -43
  30. divi/qprog/quantum_program.py +243 -412
  31. divi/qprog/typing.py +62 -0
  32. divi/qprog/variational_quantum_algorithm.py +1208 -0
  33. divi/qprog/workflows/__init__.py +10 -0
  34. divi/qprog/{_graph_partitioning.py → workflows/_graph_partitioning.py} +139 -95
  35. divi/qprog/workflows/_qubo_partitioning.py +221 -0
  36. divi/qprog/workflows/_vqe_sweep.py +560 -0
  37. divi/reporting/__init__.py +7 -0
  38. divi/reporting/_pbar.py +127 -0
  39. divi/reporting/_qlogger.py +68 -0
  40. divi/reporting/_reporter.py +155 -0
  41. {qoro_divi-0.2.0b1.dist-info → qoro_divi-0.6.0.dist-info}/METADATA +43 -15
  42. qoro_divi-0.6.0.dist-info/RECORD +47 -0
  43. {qoro_divi-0.2.0b1.dist-info → qoro_divi-0.6.0.dist-info}/WHEEL +1 -1
  44. qoro_divi-0.6.0.dist-info/licenses/LICENSES/.license-header +3 -0
  45. divi/_pbar.py +0 -73
  46. divi/circuits.py +0 -139
  47. divi/exp/cirq/_lexer.py +0 -126
  48. divi/exp/cirq/_parser.py +0 -889
  49. divi/exp/cirq/_qasm_export.py +0 -37
  50. divi/exp/cirq/_qasm_import.py +0 -35
  51. divi/exp/cirq/exception.py +0 -21
  52. divi/exp/scipy/_cobyla.py +0 -342
  53. divi/exp/scipy/pyprima/LICENCE.txt +0 -28
  54. divi/exp/scipy/pyprima/__init__.py +0 -263
  55. divi/exp/scipy/pyprima/cobyla/__init__.py +0 -0
  56. divi/exp/scipy/pyprima/cobyla/cobyla.py +0 -599
  57. divi/exp/scipy/pyprima/cobyla/cobylb.py +0 -849
  58. divi/exp/scipy/pyprima/cobyla/geometry.py +0 -240
  59. divi/exp/scipy/pyprima/cobyla/initialize.py +0 -269
  60. divi/exp/scipy/pyprima/cobyla/trustregion.py +0 -540
  61. divi/exp/scipy/pyprima/cobyla/update.py +0 -331
  62. divi/exp/scipy/pyprima/common/__init__.py +0 -0
  63. divi/exp/scipy/pyprima/common/_bounds.py +0 -41
  64. divi/exp/scipy/pyprima/common/_linear_constraints.py +0 -46
  65. divi/exp/scipy/pyprima/common/_nonlinear_constraints.py +0 -64
  66. divi/exp/scipy/pyprima/common/_project.py +0 -224
  67. divi/exp/scipy/pyprima/common/checkbreak.py +0 -107
  68. divi/exp/scipy/pyprima/common/consts.py +0 -48
  69. divi/exp/scipy/pyprima/common/evaluate.py +0 -101
  70. divi/exp/scipy/pyprima/common/history.py +0 -39
  71. divi/exp/scipy/pyprima/common/infos.py +0 -30
  72. divi/exp/scipy/pyprima/common/linalg.py +0 -452
  73. divi/exp/scipy/pyprima/common/message.py +0 -336
  74. divi/exp/scipy/pyprima/common/powalg.py +0 -131
  75. divi/exp/scipy/pyprima/common/preproc.py +0 -393
  76. divi/exp/scipy/pyprima/common/present.py +0 -5
  77. divi/exp/scipy/pyprima/common/ratio.py +0 -56
  78. divi/exp/scipy/pyprima/common/redrho.py +0 -49
  79. divi/exp/scipy/pyprima/common/selectx.py +0 -346
  80. divi/interfaces.py +0 -25
  81. divi/parallel_simulator.py +0 -258
  82. divi/qlogger.py +0 -119
  83. divi/qoro_service.py +0 -343
  84. divi/qprog/_mlae.py +0 -182
  85. divi/qprog/_qaoa.py +0 -440
  86. divi/qprog/_vqe.py +0 -275
  87. divi/qprog/_vqe_sweep.py +0 -144
  88. divi/utils.py +0 -116
  89. qoro_divi-0.2.0b1.dist-info/RECORD +0 -58
  90. /divi/{qem.py → circuits/qem.py} +0 -0
  91. {qoro_divi-0.2.0b1.dist-info → qoro_divi-0.6.0.dist-info/licenses}/LICENSE +0 -0
  92. {qoro_divi-0.2.0b1.dist-info → qoro_divi-0.6.0.dist-info/licenses}/LICENSES/Apache-2.0.txt +0 -0
@@ -1,599 +0,0 @@
1
- """
2
- This module provides Powell's COBYLA algorithm.
3
-
4
- Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
5
-
6
- Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
7
-
8
- Python translation by Nickolai Belakovski.
9
-
10
- N.B.:
11
-
12
- 1. The modern-Fortran reference implementation in PRIMA contains bug fixes and improvements over the
13
- original Fortran 77 implementation by Powell. Consequently, the PRIMA implementation behaves differently
14
- from the original Fortran 77 implementation by Powell. Therefore, it is important to point out that
15
- you are using PRIMA rather than the original solvers if you want your results to be reproducible.
16
-
17
- 2. Compared to Powell's Fortran 77 implementation, the modern-Fortran implementation and hence any
18
- faithful translation like this one generally produce better solutions with fewer function evaluations,
19
- making them preferable for applications with expensive function evaluations. However, if function
20
- evaluations are not the dominant cost in your application, the Fortran 77 solvers are likely to be
21
- faster, as they are more efficient in terms of memory usage and flops thanks to the careful and
22
- ingenious (but unmaintained and unmaintainable) implementation by Powell.
23
-
24
- See the PRIMA documentation (www.libprima.net) for more information.
25
- """
26
-
27
- from copy import copy
28
- from dataclasses import dataclass
29
-
30
- import numpy as np
31
-
32
- from ..common.consts import (
33
- BOUNDMAX,
34
- CTOL_DEFAULT,
35
- CWEIGHT_DEFAULT,
36
- DEBUGGING,
37
- EPS,
38
- ETA1_DEFAULT,
39
- ETA2_DEFAULT,
40
- FTARGET_DEFAULT,
41
- GAMMA1_DEFAULT,
42
- GAMMA2_DEFAULT,
43
- IPRINT_DEFAULT,
44
- MAXFUN_DIM_DEFAULT,
45
- RHOBEG_DEFAULT,
46
- RHOEND_DEFAULT,
47
- )
48
- from ..common.evaluate import evaluate, moderatec, moderatef, moderatex
49
- from ..common.linalg import matprod
50
- from ..common.preproc import preproc
51
- from ..common.present import present
52
- from .cobylb import cobylb
53
-
54
-
55
- @dataclass
56
- class COBYLAResult:
57
- x: np.ndarray
58
- f: float
59
- constr: np.ndarray
60
- cstrv: float
61
- nf: int
62
- xhist: np.ndarray | None
63
- fhist: np.ndarray | None
64
- chist: np.ndarray | None
65
- conhist: np.ndarray | None
66
- info: int
67
-
68
-
69
- def cobyla(
70
- calcfc,
71
- m_nlcon,
72
- x,
73
- Aineq=None,
74
- bineq=None,
75
- Aeq=None,
76
- beq=None,
77
- xl=None,
78
- xu=None,
79
- f0=None,
80
- nlconstr0=None,
81
- rhobeg=None,
82
- rhoend=None,
83
- ftarget=FTARGET_DEFAULT,
84
- ctol=CTOL_DEFAULT,
85
- cweight=CWEIGHT_DEFAULT,
86
- maxfun=None,
87
- iprint=IPRINT_DEFAULT,
88
- eta1=None,
89
- eta2=None,
90
- gamma1=GAMMA1_DEFAULT,
91
- gamma2=GAMMA2_DEFAULT,
92
- maxhist=None,
93
- maxfilt=2000,
94
- callback=None,
95
- ):
96
- """
97
- Among all the arguments, only CALCFC, M_NLCON, and X are obligatory. The others are
98
- OPTIONAL and you can neglect them unless you are familiar with the algorithm. Any
99
- unspecified optional input will take the default value detailed below. For
100
- instance, we may invoke the solver as follows.
101
-
102
- # First define CALCFC, M_NLCON, and X, and then do the following.
103
- result = cobyla(calcfc, m_nlcon, x)
104
-
105
- or
106
-
107
- # First define CALCFC, M_NLCON, X, Aineq, and Bineq, and then do the following.
108
- result = cobyla(calcfc, m_nlcon, x, Aineq=Aineq, bineq=bineq, rhobeg=1.0e0,
109
- rhoend=1.0e-6)
110
-
111
- ####################################################################################
112
- # IMPORTANT NOTICE: The user must set M_NLCON correctly to the number of nonlinear
113
- # constraints, namely the size of NLCONSTR introduced below. Set it to 0 if there
114
- # is no nonlinear constraint.
115
- ####################################################################################
116
-
117
- See examples/cobyla/cobyla_example.py for a concrete example.
118
-
119
- A detailed introduction to the arguments is as follows.
120
-
121
- ####################################################################################
122
- # INPUTS
123
- ####################################################################################
124
-
125
- CALCFC
126
- Input, function.
127
- f, nlconstr = CALCFC(X) should evaluate the objective function and nonlinear
128
- constraints at the given vector X; it should return a tuple consisting of the
129
- objective function value and the nonlinear constraint value. It must be provided
130
- by the user, and its definition must conform to the following interface:
131
- #-------------------------------------------------------------------------#
132
- def calcfc(x):
133
- f = 0.0
134
- nlconstr = np.zeros(m_nlcon)
135
- return f, nlconstr
136
- #-------------------------------------------------------------------------#
137
-
138
- M_NLCON
139
- Input, scalar.
140
- M_NLCON must be set to the number of nonlinear constraints, namely the size of
141
- NLCONSTR(X).
142
- N.B.:
143
- 1. Why don't we define M_NLCON as optional and default it to 0 when it is absent?
144
- This is because we need to allocate memory for CONSTR_LOC using M_NLCON. To
145
- ensure that the size of CONSTR_LOC is correct, we require the user to specify
146
- M_NLCON explicitly.
147
-
148
- X
149
- Input, vector.
150
- As an input, X should be an N-dimensional vector that contains the starting
151
- point, N being the dimension of the problem.
152
-
153
- Aineq, Bineq
154
- Input, matrix of size [Mineq, N] and vector of size Mineq unless they are both
155
- empty, default: None and None.
156
- Aineq and Bineq represent the linear inequality constraints: Aineq*X <= Bineq.
157
-
158
- Aeq, Beq
159
- Input, matrix of size [Meq, N] and vector of size Meq unless they are both
160
- empty, default: None and None.
161
- Aeq and Beq represent the linear equality constraints: Aeq*X = Beq.
162
-
163
- XL, XU
164
- Input, vectors of size N unless they are both None, default: None and None.
165
- XL is the lower bound for X. If XL is None, X has no
166
- lower bound. Any entry of XL that is NaN or below -BOUNDMAX will be taken as
167
- -BOUNDMAX, which effectively means there is no lower bound for the corresponding
168
- entry of X. The value of BOUNDMAX is 0.25*HUGE(X), which is about 8.6E37 for
169
- single precision and 4.5E307 for double precision. XU is similar.
170
-
171
- F0
172
- Input, scalar.
173
- F0, if present, should be set to the objective function value of the starting X.
174
-
175
- NLCONSTR0
176
- Input, vector.
177
- NLCONSTR0, if present, should be set to the nonlinear constraint value at the
178
- starting X; in addition, SIZE(NLCONSTR0) must be M_NLCON, or the solver will
179
- abort.
180
-
181
- RHOBEG, RHOEND
182
- Inputs, scalars, default: RHOBEG = 1, RHOEND = 10^-6. RHOBEG and RHOEND must be
183
- set to the initial and final values of a trust-region radius, both being positive
184
- and RHOEND <= RHOBEG. Typically RHOBEG should be about one tenth of the greatest
185
- expected change to a variable, and RHOEND should indicate the accuracy that is
186
- required in the final values of the variables.
187
-
188
- FTARGET
189
- Input, scalar, default: -Inf.
190
- FTARGET is the target function value. The algorithm will terminate when a
191
- feasible point with a function value <= FTARGET is found.
192
-
193
- CTOL
194
- Input, scalar, default: sqrt(machine epsilon).
195
- CTOL is the tolerance of constraint violation. X is considered feasible if
196
- CSTRV(X) <= CTOL.
197
- N.B.:
198
- 1. CTOL is absolute, not relative.
199
- 2. CTOL is used only when selecting the returned X. It does not affect the
200
- iterations of the algorithm.
201
-
202
- CWEIGHT
203
- Input, scalar, default: CWEIGHT_DFT defined in common/consts.py.
204
- CWEIGHT is the weight that the constraint violation takes in the selection of the
205
- returned X.
206
-
207
- MAXFUN
208
- Input, integer scalar, default: MAXFUN_DIM_DFT*N with MAXFUN_DIM_DFT defined in
209
- common/consts.py. MAXFUN is the maximal number of calls of CALCFC.
210
-
211
- IPRINT
212
- Input, integer scalar, default: 0.
213
- The value of IPRINT should be set to 0, 1, -1, 2, -2, 3, or -3, which controls
214
- how much information will be printed during the computation:
215
- 0: there will be no printing;
216
- 1: a message will be printed to the screen at the return, showing the best vector
217
- of variables found and its objective function value;
218
- 2: in addition to 1, each new value of RHO is printed to the screen, with the
219
- best vector of variables so far and its objective function value; each new
220
- value of CPEN is also printed;
221
- 3: in addition to 2, each function evaluation with its variables will be printed
222
- to the screen; -1, -2, -3: the same information as 1, 2, 3 will be printed,
223
- not to the screen but to a file named COBYLA_output.txt; the file will be
224
- created if it does not exist; the new output will be appended to the end of
225
- this file if it already exists.
226
- Note that IPRINT = +/-3 can be costly in terms of time and/or space.
227
-
228
- ETA1, ETA2, GAMMA1, GAMMA2
229
- Input, scalars, default: ETA1 = 0.1, ETA2 = 0.7, GAMMA1 = 0.5, and GAMMA2 = 2.
230
- ETA1, ETA2, GAMMA1, and GAMMA2 are parameters in the updating scheme of the
231
- trust-region radius detailed in the subroutine TRRAD in trustregion.py. Roughly
232
- speaking, the trust-region radius is contracted by a factor of GAMMA1 when the
233
- reduction ratio is below ETA1, and enlarged by a factor of GAMMA2 when the
234
- reduction ratio is above ETA2. It is required that 0 < ETA1 <= ETA2 < 1 and
235
- 0 < GAMMA1 < 1 < GAMMA2. Normally, ETA1 <= 0.25. It is NOT advised to set
236
- ETA1 >= 0.5.
237
-
238
- MAXFILT
239
- Input, scalar.
240
- MAXFILT is a nonnegative integer indicating the maximal length of the filter used
241
- for selecting the returned solution; default: MAXFILT_DFT (a value lower than
242
- MIN_MAXFILT is not recommended);
243
- see common/consts.py for the definitions of MAXFILT_DFT and MIN_MAXFILT.
244
-
245
- CALLBACK
246
- Input, function to report progress and optionally request termination.
247
-
248
-
249
- ####################################################################################
250
- # OUTPUTS
251
- ####################################################################################
252
-
253
- The output is a single data structure, COBYLAResult, with the following fields:
254
-
255
- X
256
- Output, vector.
257
- As an output, X will be set to an approximate minimizer.
258
-
259
- F
260
- Output, scalar.
261
- F will be set to the objective function value of X at exit.
262
-
263
- CONSTR
264
- Output, vector.
265
- CONSTR will be set to the constraint value of X at exit.
266
-
267
- CSTRV
268
- Output, scalar.
269
- CSTRV will be set to the constraint violation of X at exit, i.e.,
270
- max([0, XL - X, X - XU, Aineq*X - Bineq, ABS(Aeq*X -Beq), NLCONSTR(X)]).
271
-
272
- NF
273
- Output, scalar.
274
- NF will be set to the number of calls of CALCFC at exit.
275
-
276
- XHIST, FHIST, CHIST, CONHIST, MAXHIST
277
- XHIST: Output, rank 2 array;
278
- FHIST: Output, rank 1 array;
279
- CHIST: Output, rank 1 array;
280
- CONHIST: Output, rank 2 array;
281
- MAXHIST: Input, scalar, default: MAXFUN
282
- XHIST, if present, will output the history of iterates; FHIST, if present, will
283
- output the history function values; CHIST, if present, will output the history of
284
- constraint violations; CONHIST, if present, will output the history of constraint
285
- values; MAXHIST should be a nonnegative integer, and XHIST/FHIST/CHIST/CONHIST
286
- will output only the history of the last MAXHIST iterations.
287
- Therefore, MAXHIST= 0 means XHIST/FHIST/CONHIST/CHIST will output
288
- nothing, while setting MAXHIST = MAXFUN requests XHIST/FHIST/CHIST/CONHIST to
289
- output all the history. If XHIST is present, its size at exit will be
290
- (N, min(NF, MAXHIST)); if FHIST is present, its size at exit will be
291
- min(NF, MAXHIST); if CHIST is present, its size at exit will be min(NF, MAXHIST);
292
- if CONHIST is present, its size at exit will be (M, min(NF, MAXHIST)).
293
-
294
- IMPORTANT NOTICE:
295
- Setting MAXHIST to a large value can be costly in terms of memory for large
296
- problems.
297
- MAXHIST will be reset to a smaller value if the memory needed exceeds MAXHISTMEM
298
- defined in common/consts.py
299
- Use *HIST with caution!!! (N.B.: the algorithm is NOT designed for large
300
- problems).
301
-
302
- INFO
303
- Output, scalar.
304
- INFO is the exit flag. It will be set to one of the following values defined in
305
- common/infos.py:
306
- SMALL_TR_RADIUS: the lower bound for the trust region radius is reached;
307
- FTARGET_ACHIEVED: the target function value is reached;
308
- MAXFUN_REACHED: the objective function has been evaluated MAXFUN times;
309
- MAXTR_REACHED: the trust region iteration has been performed MAXTR times (MAXTR = 2*MAXFUN);
310
- NAN_INF_X: NaN or Inf occurs in X;
311
- DAMAGING_ROUNDING: rounding errors are becoming damaging.
312
- #--------------------------------------------------------------------------#
313
- The following case(s) should NEVER occur unless there is a bug.
314
- NAN_INF_F: the objective function returns NaN or +Inf;
315
- NAN_INF_MODEL: NaN or Inf occurs in the model;
316
- TRSUBP_FAILED: a trust region step failed to reduce the model
317
- #--------------------------------------------------------------------------#
318
- """
319
-
320
- # Local variables
321
- solver = "COBYLA"
322
- srname = "COBYLA"
323
-
324
- # Sizes
325
- mineq = len(bineq) if present(bineq) else 0
326
- meq = len(beq) if present(beq) else 0
327
- mxl = sum(xl > -BOUNDMAX) if present(xl) else 0
328
- mxu = sum(xu < BOUNDMAX) if present(xu) else 0
329
- mmm = mxu + mxl + 2 * meq + mineq + m_nlcon
330
- num_vars = len(x)
331
-
332
- # Preconditions
333
- if DEBUGGING:
334
- assert m_nlcon >= 0, f"{srname} M_NLCON >= 0"
335
- assert num_vars >= 1, f"{srname} N >= 1"
336
-
337
- assert present(Aineq) == present(
338
- bineq
339
- ), f"{srname} Aineq and Bineq are both present or both absent"
340
- if present(Aineq):
341
- assert Aineq.shape == (
342
- mineq,
343
- num_vars,
344
- ), f"{srname} SIZE(Aineq) == [Mineq, N]"
345
-
346
- assert present(Aeq) == present(
347
- beq
348
- ), f"{srname} Aeq and Beq are both present or both absent"
349
- if present(Aeq):
350
- assert Aeq.shape == (meq, num_vars), f"{srname} SIZE(Aeq) == [Meq, N]"
351
-
352
- if present(xl):
353
- assert len(xl) == num_vars, f"{srname} SIZE(XL) == N"
354
- if present(xu):
355
- assert len(xu) == num_vars, f"{srname} SIZE(XU) == N"
356
-
357
- # N.B.: If NLCONSTR0 is present, then F0 must be present, and we assume that
358
- # F(X0) = F0 even if F0 is NaN; if NLCONSTR0 is absent, then F0 must be either
359
- # absent or NaN, both of which will be interpreted as F(X0) is not provided.
360
- if present(nlconstr0):
361
- assert present(f0), f"{srname} If NLCONSTR0 is present, then F0 is present"
362
- if present(f0):
363
- assert np.isnan(f0) or present(
364
- nlconstr0
365
- ), f"{srname} If F0 is present and not NaN, then NLCONSTR0 is present"
366
-
367
- # Exit if the size of NLCONSTR0 is inconsistent with M_NLCON.
368
- if present(nlconstr0):
369
- assert np.size(nlconstr0) == m_nlcon
370
-
371
- # Read the inputs.
372
-
373
- if xl is not None:
374
- xl = copy(xl)
375
- xl[np.isnan(xl)] = -BOUNDMAX
376
- xl[xl < -BOUNDMAX] = -BOUNDMAX
377
-
378
- if xu is not None:
379
- xu = copy(xu)
380
- xu[np.isnan(xu)] = BOUNDMAX
381
- xu[xu > BOUNDMAX] = BOUNDMAX
382
-
383
- # Wrap the linear and bound constraints into a single constraint: AMAT@X <= BVEC.
384
- amat, bvec = get_lincon(Aeq, Aineq, beq, bineq, xl, xu)
385
-
386
- # Create constraint vector
387
- constr = np.zeros(mmm)
388
-
389
- # Set [F_LOC, CONSTR_LOC] to [F(X0), CONSTR(X0)] after evaluating the latter if
390
- # needed. In this way, COBYLB only needs one interface.
391
- # N.B.: Due to the preconditions above, there are two possibilities for F0 and
392
- # NLCONSTR0.
393
- # If NLCONSTR0 is present, then F0 must be present, and we assume that F(X0) = F0
394
- # even if F0 is NaN.
395
- # If NLCONSTR0 is absent, then F0 must be either absent or NaN, both of which will
396
- # be interpreted as F(X0) is not provided and we have to evaluate F(X0) and
397
- # NLCONSTR(X0) now.
398
- if present(f0) and present(nlconstr0) and all(np.isfinite(x)):
399
- f = moderatef(f0)
400
- if amat is not None:
401
- constr[: mmm - m_nlcon] = moderatec(matprod(amat, x) - bvec)
402
- constr[mmm - m_nlcon :] = moderatec(nlconstr0)
403
- else:
404
- x = moderatex(x)
405
- f, constr = evaluate(calcfc, x, m_nlcon, amat, bvec)
406
- constr[: mmm - m_nlcon] = moderatec(constr[: mmm - m_nlcon])
407
- # N.B.: Do NOT call FMSG, SAVEHIST, or SAVEFILT for the function/constraint evaluation at X0.
408
- # They will be called during the initialization, which will read the function/constraint at X0.
409
- cstrv = max(np.append(0, constr))
410
-
411
- # If RHOBEG is present, use it; otherwise, RHOBEG takes the default value for
412
- # RHOBEG, taking the value of RHOEND into account. Note that RHOEND is considered
413
- # only if it is present and it is VALID (i.e., finite and positive). The other
414
- # inputs are read similarly.
415
- if present(rhobeg):
416
- rhobeg = rhobeg
417
- elif present(rhoend) and np.isfinite(rhoend) and rhoend > 0:
418
- rhobeg = max(10 * rhoend, RHOBEG_DEFAULT)
419
- else:
420
- rhobeg = RHOBEG_DEFAULT
421
-
422
- if present(rhoend):
423
- rhoend = rhoend
424
- elif rhobeg > 0:
425
- rhoend = max(EPS, min(RHOEND_DEFAULT / RHOBEG_DEFAULT * rhobeg, RHOEND_DEFAULT))
426
- else:
427
- rhoend = RHOEND_DEFAULT
428
-
429
- maxfun = maxfun if present(maxfun) else MAXFUN_DIM_DEFAULT * num_vars
430
-
431
- if present(eta1):
432
- eta1 = eta1
433
- elif present(eta2) and 0 < eta2 < 1:
434
- eta1 = max(EPS, eta2 / 7)
435
- else:
436
- eta1 = ETA1_DEFAULT
437
-
438
- if present(eta2):
439
- eta2 = eta2
440
- elif 0 < eta1 < 1:
441
- eta2 = (eta1 + 2) / 3
442
- else:
443
- eta2 = ETA2_DEFAULT
444
-
445
- maxhist = (
446
- maxhist
447
- if present(maxhist)
448
- else max(maxfun, num_vars + 2, MAXFUN_DIM_DEFAULT * num_vars)
449
- )
450
-
451
- # Preprocess the inputs in case some of them are invalid. It does nothing if all
452
- # inputs are valid.
453
- (
454
- iprint,
455
- maxfun,
456
- maxhist,
457
- ftarget,
458
- rhobeg,
459
- rhoend,
460
- npt, # Unused in COBYLA
461
- maxfilt,
462
- ctol,
463
- cweight,
464
- eta1,
465
- eta2,
466
- gamma1,
467
- gamma2,
468
- _x0, # Unused in COBYLA
469
- ) = preproc(
470
- solver,
471
- num_vars,
472
- iprint,
473
- maxfun,
474
- maxhist,
475
- ftarget,
476
- rhobeg,
477
- rhoend,
478
- num_constraints=mmm,
479
- maxfilt=maxfilt,
480
- ctol=ctol,
481
- cweight=cweight,
482
- eta1=eta1,
483
- eta2=eta2,
484
- gamma1=gamma1,
485
- gamma2=gamma2,
486
- is_constrained=(mmm > 0),
487
- )
488
-
489
- # Further revise MAXHIST according to MAXHISTMEM, and allocate memory for the history.
490
- # In MATLAB/Python/Julia/R implementation, we should simply set MAXHIST = MAXFUN and initialize
491
- # CHIST = NaN(1, MAXFUN), CONHIST = NaN(M, MAXFUN), FHIST = NaN(1, MAXFUN), XHIST = NaN(N, MAXFUN)
492
- # if they are requested; replace MAXFUN with 0 for the history that is not requested.
493
- # prehist(maxhist, num_vars, present(xhist), xhist_loc, present(fhist), fhist_loc, &
494
- # & present(chist), chist_loc, m, present(conhist), conhist_loc)
495
-
496
- # call cobylb, which performs the real calculations
497
- x, f, constr, cstrv, nf, xhist, fhist, chist, conhist, info = cobylb(
498
- calcfc,
499
- iprint,
500
- maxfilt,
501
- maxfun,
502
- amat,
503
- bvec,
504
- ctol,
505
- cweight,
506
- eta1,
507
- eta2,
508
- ftarget,
509
- gamma1,
510
- gamma2,
511
- rhobeg,
512
- rhoend,
513
- constr,
514
- f,
515
- x,
516
- maxhist,
517
- callback,
518
- )
519
-
520
- return COBYLAResult(x, f, constr, cstrv, nf, xhist, fhist, chist, conhist, info)
521
-
522
-
523
- def get_lincon(Aeq=None, Aineq=None, beq=None, bineq=None, xl=None, xu=None):
524
- """
525
- This subroutine wraps the linear and bound constraints into a single constraint:
526
- AMAT*X <= BVEC.
527
-
528
- N.B.:
529
-
530
- LINCOA normalizes the linear constraints so that each constraint has a gradient
531
- of norm 1. However, COBYLA does not do this.
532
- """
533
-
534
- # Sizes
535
- if Aeq is not None:
536
- num_vars = Aeq.shape[1]
537
- elif Aineq is not None:
538
- num_vars = Aineq.shape[1]
539
- elif xl is not None:
540
- num_vars = len(xl)
541
- elif xu is not None:
542
- num_vars = len(xu)
543
- else:
544
- return None, None
545
-
546
- # Preconditions
547
- if DEBUGGING:
548
- assert Aineq is None or Aineq.shape == (len(bineq), num_vars)
549
- assert Aeq is None or Aeq.shape == (len(beq), num_vars)
550
- assert (xl is None or xu is None) or len(xl) == len(xu) == num_vars
551
-
552
- # ====================#
553
- # Calculation starts #
554
- # ====================#
555
-
556
- # Define the indices of the nontrivial bound constraints.
557
- ixl = np.where(xl > -BOUNDMAX)[0] if xl is not None else None
558
- ixu = np.where(xu < BOUNDMAX)[0] if xu is not None else None
559
-
560
- # Wrap the linear constraints.
561
- # The bound constraint XL <= X <= XU is handled as two constraints:
562
- # -X <= -XL, X <= XU.
563
- # The equality constraint Aeq*X = Beq is handled as two constraints:
564
- # -Aeq*X <= -Beq, Aeq*X <= Beq.
565
- # N.B.:
566
- # 1. The treatment of the equality constraints is naive. One may choose to
567
- # eliminate them instead.
568
- idmat = np.eye(num_vars)
569
- amat = np.vstack(
570
- [
571
- -idmat[ixl, :] if ixl is not None else np.empty((0, num_vars)),
572
- idmat[ixu, :] if ixu is not None else np.empty((0, num_vars)),
573
- -Aeq if Aeq is not None else np.empty((0, num_vars)),
574
- Aeq if Aeq is not None else np.empty((0, num_vars)),
575
- Aineq if Aineq is not None else np.empty((0, num_vars)),
576
- ]
577
- )
578
- bvec = np.hstack(
579
- [
580
- -xl[ixl] if ixl is not None else np.empty(0),
581
- xu[ixu] if ixu is not None else np.empty(0),
582
- -beq if beq is not None else np.empty(0),
583
- beq if beq is not None else np.empty(0),
584
- bineq if bineq is not None else np.empty(0),
585
- ]
586
- )
587
-
588
- amat = amat if amat.shape[0] > 0 else None
589
- bvec = bvec if bvec.shape[0] > 0 else None
590
-
591
- # ==================#
592
- # Calculation ends #
593
- # ==================#
594
-
595
- # Postconditions
596
- if DEBUGGING:
597
- assert (amat is None and bvec is None) or amat.shape == (len(bvec), num_vars)
598
-
599
- return amat, bvec