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,224 +0,0 @@
1
- """
2
- This module provides the _project function that attempts to project the initial guess
3
- onto the feasible set.
4
-
5
- Adapted from the corresponding function in the PDFO package (https://www.pdfo.net) by
6
- Tom M. Ragonneau (https://ragonneau.github.io) and Zaikun Zhang (https://www.zhangzk.net).
7
- """
8
-
9
- import numpy as np
10
- from scipy.optimize import OptimizeResult
11
-
12
- from ._linear_constraints import LinearConstraint
13
-
14
- # All the accepted scalar types; np.generic correspond to all NumPy types.
15
- scalar_types = (int, float, np.generic)
16
- eps = np.finfo(np.float64).eps
17
-
18
-
19
- def _project(x0, lb, ub, constraints):
20
- """Projection of the initial guess onto the feasible set.
21
-
22
- Parameters
23
- ----------
24
- x0: ndarray, shape (n,)
25
- The same as in prepdfo.
26
- lb: ndarray, shape (n,)
27
- The same as in prepdfo.
28
- ub: ndarray, shape (n,)
29
- The same as in prepdfo.
30
- constraints: dict
31
- The general constraints of the problem, defined as a dictionary with
32
- fields:
33
- linear: LinearConstraint
34
- The linear constraints of the problem.
35
- nonlinear: dict
36
- The nonlinear constraints of the problem. When ``_project`` is called, the nonlinear constraints are
37
- None.
38
-
39
- Returns
40
- -------
41
- result: OptimizeResult
42
- The result of the projection.
43
-
44
- Authors
45
- -------
46
- Tom M. RAGONNEAU (ragonneau.github.io)
47
- and Zaikun ZHANG (www.zhangzk.net)
48
-
49
- Dedicated to the late Professor M. J. D. Powell FRS (1936--2015).
50
- """
51
- invoker = "prima"
52
-
53
- # Validate x0.
54
- if isinstance(x0, scalar_types):
55
- x0_c = [x0]
56
- elif hasattr(x0, "__len__"):
57
- x0_c = x0
58
- else:
59
- raise ValueError("{}: UNEXPECTED ERROR: x0 should be a vector.".format(invoker))
60
- try:
61
- x0_c = np.asarray(x0_c, dtype=np.float64)
62
- except ValueError:
63
- raise ValueError(
64
- "{}: UNEXPECTED ERROR: x0 should contain only scalars.".format(invoker)
65
- )
66
- if len(x0_c.shape) != 1:
67
- raise ValueError("{}: UNEXPECTED ERROR: x0 should be a vector.".format(invoker))
68
- lenx0 = x0_c.size
69
-
70
- # Validate lb.
71
- if isinstance(lb, scalar_types):
72
- lb_c = [lb]
73
- elif hasattr(lb, "__len__"):
74
- lb_c = lb
75
- else:
76
- raise ValueError("{}: UNEXPECTED ERROR: lb should be a vector.".format(invoker))
77
- try:
78
- lb_c = np.asarray(lb_c, dtype=np.float64)
79
- except ValueError:
80
- raise ValueError(
81
- "{}: UNEXPECTED ERROR: lb should contain only scalars.".format(invoker)
82
- )
83
- if len(lb_c.shape) != 1 or lb_c.size != lenx0:
84
- raise ValueError(
85
- "{}: UNEXPECTED ERROR: the size of lb is inconsistent with x0.".format(
86
- invoker
87
- )
88
- )
89
-
90
- # Validate ub.
91
- if isinstance(ub, scalar_types):
92
- ub_c = [ub]
93
- elif hasattr(ub, "__len__"):
94
- ub_c = ub
95
- else:
96
- raise ValueError("{}: UNEXPECTED ERROR: ub should be a vector.".format(invoker))
97
- try:
98
- ub_c = np.asarray(ub_c, dtype=np.float64)
99
- except ValueError:
100
- raise ValueError(
101
- "{}: UNEXPECTED ERROR: ub should contain only scalars.".format(invoker)
102
- )
103
- if len(ub_c.shape) != 1 or ub_c.size != lenx0:
104
- raise ValueError(
105
- "{}: UNEXPECTED ERROR: the size of ub is inconsistent with x0.".format(
106
- invoker
107
- )
108
- )
109
-
110
- # Validate constraints.
111
- if (
112
- not isinstance(constraints, dict)
113
- or not ({"linear", "nonlinear"} <= set(constraints.keys()))
114
- or not (
115
- isinstance(constraints["linear"], LinearConstraint)
116
- or constraints["linear"] is None
117
- )
118
- ):
119
- # the nonlinear constraints will not be taken into account in this function and are, therefore, not validated
120
- raise ValueError(
121
- "{}: UNEXPECTED ERROR: The constraints are ill-defined.".format(invoker)
122
- )
123
-
124
- max_con = 1e20 # Decide whether an inequality constraint can be ignored
125
-
126
- # Project onto the feasible set.
127
- if constraints["linear"] is None:
128
- # Direct projection onto the bound constraints
129
- x_proj = np.nanmin((np.nanmax((x0_c, lb_c), axis=0), ub_c), axis=0)
130
- return OptimizeResult(x=x_proj)
131
- elif (
132
- all(
133
- np.less_equal(
134
- np.abs(constraints["linear"].ub - constraints["linear"].lb), eps
135
- )
136
- )
137
- and np.max(lb_c) <= -max_con
138
- and np.min(ub_c) >= max_con
139
- ):
140
- # The linear constraints are all equality constraints. The projection can therefore be done by solving the
141
- # least-squares problem: min ||A*x - (b - A*x_0)||.
142
- a = constraints["linear"].A
143
- b = (constraints["linear"].lb + constraints["linear"].ub) / 2
144
- xi, _, _, _ = np.linalg.lstsq(a, b - np.dot(a, x0_c), rcond=None)
145
-
146
- # The problem is not bounded. However, if the least-square solver returned values bigger in absolute value
147
- # than max_con, they will be reduced to this bound.
148
- x_proj = np.nanmin((np.nanmax((x0_c + xi, lb_c), axis=0), ub_c), axis=0)
149
-
150
- return OptimizeResult(x=x_proj)
151
-
152
- if constraints["linear"] is not None:
153
- try:
154
- # Project the initial guess onto the linear constraints via SciPy.
155
- from scipy.optimize import Bounds as ScipyBounds
156
- from scipy.optimize import LinearConstraint as ScipyLinearConstraint
157
- from scipy.optimize import minimize
158
-
159
- linear = constraints["linear"]
160
-
161
- # To be more efficient, SciPy asks to separate the equality and the inequality constraints into two
162
- # different LinearConstraint structures
163
- pc_args_ineq, pc_args_eq = dict(), dict()
164
- pc_args_ineq["A"], pc_args_eq["A"] = np.asarray([[]]), np.asarray([[]])
165
- pc_args_ineq["A"] = pc_args_ineq["A"].reshape(0, linear.A.shape[1])
166
- pc_args_eq["A"] = pc_args_eq["A"].reshape(0, linear.A.shape[1])
167
- pc_args_ineq["lb"], pc_args_eq["lb"] = np.asarray([]), np.asarray([])
168
- pc_args_ineq["ub"], pc_args_eq["ub"] = np.asarray([]), np.asarray([])
169
-
170
- for i in range(linear.lb.size):
171
- if linear.lb[i] != linear.ub[i]:
172
- pc_args_ineq["A"] = np.concatenate(
173
- (pc_args_ineq["A"], linear.A[i : i + 1, :]), axis=0
174
- )
175
- pc_args_ineq["lb"] = np.r_[pc_args_ineq["lb"], linear.lb[i]]
176
- pc_args_ineq["ub"] = np.r_[pc_args_ineq["ub"], linear.ub[i]]
177
- else:
178
- pc_args_eq["A"] = np.concatenate(
179
- (pc_args_eq["A"], linear.A[i : i + 1, :]), axis=0
180
- )
181
- pc_args_eq["lb"] = np.r_[pc_args_eq["lb"], linear.lb[i]]
182
- pc_args_eq["ub"] = np.r_[pc_args_eq["ub"], linear.ub[i]]
183
-
184
- if (
185
- pc_args_ineq["A"].size > 0
186
- and pc_args_ineq["lb"].size > 0
187
- and pc_args_eq["lb"].size > 0
188
- ):
189
- project_constraints = [
190
- ScipyLinearConstraint(**pc_args_ineq),
191
- ScipyLinearConstraint(**pc_args_eq),
192
- ]
193
- elif pc_args_ineq["A"].size > 0 and pc_args_ineq["lb"].size > 0:
194
- project_constraints = ScipyLinearConstraint(**pc_args_ineq)
195
- elif pc_args_eq["A"].size > 0:
196
- project_constraints = ScipyLinearConstraint(**pc_args_eq)
197
- else:
198
- project_constraints = ()
199
-
200
- # Perform the actual projection.
201
- ax_ineq = np.dot(pc_args_ineq["A"], x0_c)
202
- ax_eq = np.dot(pc_args_eq["A"], x0_c)
203
- if (
204
- np.greater(ax_ineq, pc_args_ineq["ub"]).any()
205
- or np.greater(pc_args_ineq["lb"], ax_ineq).any()
206
- or np.not_equal(ax_eq, pc_args_eq["lb"]).any()
207
- or np.greater(x0_c, ub_c).any()
208
- or np.greater(lb_c, x0_c).any()
209
- ):
210
- return minimize(
211
- lambda x: np.dot(x - x0_c, x - x0_c) / 2,
212
- x0_c,
213
- jac=lambda x: (x - x0_c),
214
- bounds=ScipyBounds(lb_c, ub_c),
215
- constraints=project_constraints,
216
- )
217
- else:
218
- # Do not perform any projection if the initial guess is feasible.
219
- return OptimizeResult(x=x0_c)
220
-
221
- except ImportError:
222
- return OptimizeResult(x=x0_c)
223
-
224
- return OptimizeResult(x=x0_c)
@@ -1,107 +0,0 @@
1
- """
2
- This module checks whether to break out of the solver loop.
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
-
11
- import numpy as np
12
-
13
- from .infos import FTARGET_ACHIEVED, INFO_DEFAULT, MAXFUN_REACHED, NAN_INF_F, NAN_INF_X
14
-
15
-
16
- def checkbreak_unc(maxfun, nf, f, ftarget, x):
17
- """
18
- This module checks whether to break out of the solver loop in the unconstrained case.
19
- """
20
-
21
- # Outputs
22
- info = INFO_DEFAULT
23
-
24
- # Local variables
25
- srname = "CHECKbreak_UNC"
26
-
27
- # Preconditions
28
- assert INFO_DEFAULT not in [
29
- NAN_INF_X,
30
- NAN_INF_F,
31
- FTARGET_ACHIEVED,
32
- MAXFUN_REACHED,
33
- ], f"NAN_INF_X, NAN_INF_F, FTARGET_ACHIEVED, and MAXFUN_REACHED differ from INFO_DFT {srname}"
34
- # X does not contain NaN if the initial X does not contain NaN and the subroutines generating
35
- # trust-region/geometry steps work properly so that they never produce a step containing NaN/Inf.
36
- assert not any(np.isnan(x)), f"X does not contain NaN {srname}"
37
- # With the moderated extreme barrier, F cannot be NaN/+Inf.
38
- assert not (any(np.isnan(f)) or any(np.isposinf(f))), f"F is not NaN/+Inf {srname}"
39
-
40
- # ====================#
41
- # Calculation starts #
42
- # ====================#
43
-
44
- # Although X should not contain NaN unless there is a bug, we include the following for security.
45
- # X can be Inf, as finite + finite can be Inf numerically.
46
- if any(np.isnan(x)) or any(np.isinf(x)):
47
- info = NAN_INF_X
48
-
49
- # Although NAN_INF_F should not happen unless there is a bug, we include the following for security.
50
- if any(np.isnan(f)) or any(np.isposinf(f)):
51
- info = NAN_INF_F
52
-
53
- if f <= ftarget:
54
- info = FTARGET_ACHIEVED
55
-
56
- if nf >= maxfun:
57
- info = MAXFUN_REACHED
58
-
59
- return info
60
-
61
-
62
- def checkbreak_con(maxfun, nf, cstrv, ctol, f, ftarget, x):
63
- """
64
- This module checks whether to break out of the solver loop in the constrained case.
65
- """
66
-
67
- # Outputs
68
- info = INFO_DEFAULT
69
-
70
- # Local variables
71
- srname = "CHECKbreak_CON"
72
-
73
- # Preconditions
74
- assert INFO_DEFAULT not in [
75
- NAN_INF_X,
76
- NAN_INF_F,
77
- FTARGET_ACHIEVED,
78
- MAXFUN_REACHED,
79
- ], f"NAN_INF_X, NAN_INF_F, FTARGET_ACHIEVED, and MAXFUN_REACHED differ from INFO_DFT {srname}"
80
- # X does not contain NaN if the initial X does not contain NaN and the subroutines generating
81
- # trust-region/geometry steps work properly so that they never produce a step containing NaN/Inf.
82
- assert not any(np.isnan(x)), f"X does not contain NaN {srname}"
83
- # With the moderated extreme barrier, F or CSTRV cannot be NaN/+Inf.
84
- assert not (
85
- np.isnan(f) or np.isposinf(f) or np.isnan(cstrv) or np.isposinf(cstrv)
86
- ), f"F or CSTRV is not NaN/+Inf {srname}"
87
-
88
- # ====================#
89
- # Calculation starts #
90
- # ====================#
91
-
92
- # Although X should not contain NaN unless there is a bug, we include the following for security.
93
- # X can be Inf, as finite + finite can be Inf numerically.
94
- if any(np.isnan(x)) or any(np.isinf(x)):
95
- info = NAN_INF_X
96
-
97
- # Although NAN_INF_F should not happen unless there is a bug, we include the following for security.
98
- if np.isnan(f) or np.isposinf(f) or np.isnan(cstrv) or np.isposinf(cstrv):
99
- info = NAN_INF_F
100
-
101
- if cstrv <= ctol and f <= ftarget:
102
- info = FTARGET_ACHIEVED
103
-
104
- if nf >= maxfun:
105
- info = MAXFUN_REACHED
106
-
107
- return info
@@ -1,48 +0,0 @@
1
- """
2
- This is a module defining some constants.
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
-
11
- import os
12
-
13
- import numpy as np
14
-
15
- DEBUGGING = bool(os.getenv("PRIMA_DEBUGGING"))
16
-
17
- REALMIN = np.finfo(float).tiny
18
- REALMAX = np.finfo(float).max
19
- FUNCMAX = 10.0**30
20
- CONSTRMAX = FUNCMAX
21
- EPS = np.finfo(float).eps
22
-
23
- # Any bound with an absolute value at least BOUNDMAX is considered as no bound.
24
- BOUNDMAX = REALMAX / 4
25
-
26
- # Some default values
27
- RHOBEG_DEFAULT = 1
28
- RHOEND_DEFAULT = 1e-6
29
- FTARGET_DEFAULT = -REALMAX
30
- CTOL_DEFAULT = np.sqrt(EPS)
31
- CWEIGHT_DEFAULT = 1e8
32
- ETA1_DEFAULT = 0.1
33
- ETA2_DEFAULT = 0.7
34
- GAMMA1_DEFAULT = 0.5
35
- GAMMA2_DEFAULT = 2
36
- IPRINT_DEFAULT = 0
37
- MAXFUN_DIM_DEFAULT = 500
38
-
39
- PRIMA_MAX_HIST_MEM_MB = 300 # 1MB > 10^5*REAL64. 100 can be too small.
40
-
41
- # Maximal amount of memory (Byte) allowed for XHIST, FHIST, CONHIST, CHIST, and the filters.
42
- MHM = PRIMA_MAX_HIST_MEM_MB * 10**6
43
- # Make sure that MAXHISTMEM does not exceed HUGE(0) to avoid overflow and memory errors.
44
- MAXHISTMEM = min(MHM, np.iinfo(np.int32).max)
45
-
46
- # Maximal length of the filter used in constrained solvers.
47
- MIN_MAXFILT = 200 # Should be positive; < 200 is not recommended.
48
- MAXFILT_DEFAULT = 10 * MIN_MAXFILT
@@ -1,101 +0,0 @@
1
- """
2
- This is a module evaluating the objective/constraint function with Nan/Inf handling.
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
-
11
- import numpy as np
12
-
13
- from .consts import CONSTRMAX, DEBUGGING, FUNCMAX, REALMAX
14
- from .linalg import matprod, primasum
15
-
16
- # This is a module evaluating the objective/constraint function with Nan/Inf handling.
17
-
18
-
19
- def moderatex(x):
20
- """
21
- This function moderates a decision variable. It replaces NaN by 0 and Inf/-Inf by
22
- REALMAX/-REALMAX.
23
- """
24
- x[np.isnan(x)] = 0
25
- x = np.clip(x, -REALMAX, REALMAX)
26
- return x
27
-
28
-
29
- def moderatef(f):
30
- """
31
- This function moderates the function value of a MINIMIZATION problem. It replaces
32
- NaN and any value above FUNCMAX by FUNCMAX.
33
- """
34
- f = FUNCMAX if np.isnan(f) else f
35
- f = np.clip(f, -REALMAX, FUNCMAX)
36
- # We may moderate huge negative function values as follows, but we decide not to.
37
- # f = np.clip(f, -FUNCMAX, FUNCMAX)
38
- return f
39
-
40
-
41
- def moderatec(c):
42
- """
43
- This function moderates the constraint value, the constraint demanding this value
44
- to be NONNEGATIVE. It replaces any value below -CONSTRMAX by -CONSTRMAX, and any
45
- NaN or value above CONSTRMAX by CONSTRMAX.
46
- """
47
- np.nan_to_num(c, copy=False, nan=CONSTRMAX)
48
- c = np.clip(c, -CONSTRMAX, CONSTRMAX)
49
- return c
50
-
51
-
52
- def evaluate(calcfc, x, m_nlcon, amat, bvec):
53
- """
54
- This function evaluates CALCFC at X, returning the objective function value and the
55
- constraint value. Nan/Inf are handled by a moderated extreme barrier.
56
- """
57
-
58
- # Sizes
59
- m_lcon = len(bvec) if bvec is not None else 0
60
-
61
- # Preconditions
62
- if DEBUGGING:
63
- # X should not contain NaN if the initial X does not contain NaN and the
64
- # subroutines generating # trust-region/geometry steps work properly so that
65
- # they never produce a step containing NaN/Inf.
66
- assert not any(np.isnan(x))
67
-
68
- # ====================#
69
- # Calculation starts #
70
- # ====================#
71
-
72
- constr = np.zeros(m_lcon + m_nlcon)
73
- if amat is not None:
74
- constr[:m_lcon] = matprod(x, amat.T) - bvec
75
-
76
- if any(np.isnan(x)):
77
- # Although this should not happen unless there is a bug, we include this case
78
- # for robustness.
79
- f = primasum(x)
80
- constr = np.ones(m_nlcon) * f
81
- else:
82
- f, constr[m_lcon:] = calcfc(moderatex(x))
83
-
84
- # Moderated extreme barrier: replace NaN/huge objective or constraint values
85
- # with a large but finite value. This is naive, and better approaches surely
86
- # exist.
87
- f = moderatef(f)
88
- constr[m_lcon:] = moderatec(constr[m_lcon:])
89
-
90
- # ==================#
91
- # Calculation ends #
92
- # ==================#
93
-
94
- # Postconditions
95
- if DEBUGGING:
96
- # With X not containing NaN, and with the moderated extreme barrier, F cannot
97
- # be NaN/+Inf, and CONSTR cannot be NaN/-Inf.
98
- assert not (np.isnan(f) or np.isposinf(f))
99
- assert not any(np.isnan(constr) | np.isposinf(constr))
100
-
101
- return f, constr
@@ -1,39 +0,0 @@
1
- """
2
- This module provides subroutines that handle the X/F/C histories of the solver, taking into
3
- account that MAXHIST may be smaller than NF.
4
-
5
- Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
6
-
7
- Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
8
-
9
- Python translation by Nickolai Belakovski.
10
- """
11
-
12
-
13
- def savehist(maxhist, x, xhist, f, fhist, cstrv, chist, constr, conhist):
14
- """
15
- Save the data values to the history lists.
16
-
17
- The implementation of this function is vastly different from the Fortran implementation.
18
- This is mostly due to the ease of creating and appending to lists in Python
19
-
20
- However just like the Fortran version we should be concerned about both performance
21
- and memory constraints. It will probably be better to initialize an array of NaN for
22
- each of the histories and keep track of how many indices we have stored. Not needed for
23
- the moment.
24
- """
25
- if len(xhist) < maxhist:
26
- xhist.append(x)
27
- fhist.append(f)
28
- chist.append(cstrv)
29
- conhist.append(constr)
30
- else:
31
- # This effectively accomplishes what rangehist does in the Fortran implementation
32
- xhist.pop(0)
33
- fhist.pop(0)
34
- chist.pop(0)
35
- conhist.pop(0)
36
- xhist.append(x)
37
- fhist.append(f)
38
- chist.append(cstrv)
39
- conhist.append(constr)
@@ -1,30 +0,0 @@
1
- """
2
- This is a module defining exit flags.
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
-
11
- INFO_DEFAULT = 0
12
- SMALL_TR_RADIUS = 0
13
- FTARGET_ACHIEVED = 1
14
- TRSUBP_FAILED = 2
15
- MAXFUN_REACHED = 3
16
- MAXTR_REACHED = 20
17
- NAN_INF_X = -1
18
- NAN_INF_F = -2
19
- NAN_INF_MODEL = -3
20
- NO_SPACE_BETWEEN_BOUNDS = 6
21
- DAMAGING_ROUNDING = 7
22
- ZERO_LINEAR_CONSTRAINT = 8
23
- CALLBACK_TERMINATE = 30
24
-
25
- # Stop-codes.
26
- # The following codes are used by ERROR STOP as stop-codes, which should be default integers.
27
- INVALID_INPUT = 100
28
- ASSERTION_FAILS = 101
29
- VALIDATION_FAILS = 102
30
- MEMORY_ALLOCATION_FAILS = 103