GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Numerics/python/pynumerics/src/pynumerics/optimization.py at main · USACE-RMC/Numerics

Expand file tree

/

optimization.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
1736 lines (1390 loc) · 67.2 KB
/

optimization.py

Copy path

File metadata and controls

1736 lines (1390 loc) · 67.2 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Local, global, constrained and multi-objective optimization from ``Numerics.Mathematics.Optimization``.
Every optimizer class wraps the Numerics optimizer of the same name and shares the interface of
:class:`Optimizer`: settings are properties (and keyword arguments of the constructor), and
:meth:`Optimizer.minimize` and :meth:`Optimizer.maximize` run the Numerics search and return an
:class:`OptimizationResult` with the best parameters, the objective value, the counts, the status,
the Hessian and the best-so-far trace.
Objectives, gradients and constraint functions are Python callables of a float64 array, C# source
compiled by :func:`pynumerics.callbacks.compile_csharp`, or .NET delegates. A compiled or .NET
objective runs with no Python crossing per evaluation. With a Python callable the population
optimizers (:class:`DifferentialEvolution`, :class:`ParticleSwarm`) always evaluate serially, because
a Python callback holds the GIL (:func:`pynumerics.callbacks.apply_parallel_policy`); with a compiled
objective ``use_parallel=True`` evaluates each generation on several threads.
Settings left unset keep the Numerics defaults. Numerics minimizes internally: for a maximization it
stores the negated objective as the fitness, and :class:`OptimizationResult` reports the objective
value itself.
:class:`ParetoFront` (dominance, non-dominated sorting, crowding distance, hypervolume and the
generational distances) takes one row of objective values per point and minimizes every objective.
:func:`knapsack` solves the exact 0/1 knapsack, single or multi-constraint.
:class:`DynamicProgramming` solves finite-horizon and stationary discrete dynamic programs with
deterministic or stochastic transitions; its stage-value and transition functions are Python
callables, C# source or .NET delegates, and with a Python callable the solve runs serially
(:func:`pynumerics.callbacks.apply_parallel_policy`). The shortest-path solvers of the same
namespace are in :mod:`pynumerics.graphs`.
"""
from __future__ import annotations
from collections.abc import Callable, Sequence
from dataclasses import dataclass, field
from typing import Any
import numpy as np
from pynumerics import callbacks
from pynumerics._util import _opt, net_enum
from pynumerics.enums import NetEnum
from pynumerics.errors import translate_class, translate_public
from pynumerics.marshal import (
_int32_array,
_net_rectangular,
_numpy_rectangular,
to_net_doubles,
to_net_ints,
to_net_matrix,
to_numpy_doubles,
to_numpy_ints,
to_numpy_matrix,
)
class OptimizationStatus(NetEnum):
"""Optimizer outcomes (``Numerics.Mathematics.Optimization.OptimizationStatus``)."""
NONE = "None"
SUCCESS = "Success"
MAXIMUM_ITERATIONS_REACHED = "MaximumIterationsReached"
MAXIMUM_FUNCTION_EVALUATIONS_REACHED = "MaximumFunctionEvaluationsReached"
FAILURE = "Failure"
LINE_SEARCH_FAILED = "LineSearchFailed"
CANCELLED = "Cancelled"
class LocalMethod(NetEnum):
"""Local search methods of the multi-start and polishing steps (``LocalMethod``)."""
ADAM = "ADAM"
BFGS = "BFGS"
GRADIENT_DESCENT = "GradientDescent"
NELDER_MEAD = "NelderMead"
POWELL = "Powell"
LBFGSB = "LBFGSB"
class ConstraintType(NetEnum):
"""Constraint relations (``Numerics.Mathematics.Optimization.ConstraintType``)."""
EQUAL_TO = "EqualTo"
GREATER_THAN_OR_EQUAL_TO = "GreaterThanOrEqualTo"
LESSER_THAN_OR_EQUAL_TO = "LesserThanOrEqualTo"
@dataclass(frozen=True, eq=False, slots=True)
class ParameterSet:
"""A parameter vector with its fitness and weight (``Numerics.Mathematics.Optimization.ParameterSet``).
Parameters
----------
values : numpy.ndarray
The parameter values.
fitness : float
The fitness (the minimized objective; the negated objective of a maximization).
weight : float, optional
The weight; default 0.
"""
values: np.ndarray
fitness: float
weight: float = 0.0
@classmethod
def from_net(cls, net: Any) -> ParameterSet:
"""Copy a .NET ``ParameterSet`` into a :class:`ParameterSet`.
Parameters
----------
net : Numerics.Mathematics.Optimization.ParameterSet
The .NET value.
Returns
-------
ParameterSet
The copy; ``values`` is empty when the .NET values are null.
"""
values = net.Values
array = np.empty(0) if values is None else to_numpy_doubles(values)
return cls(array, float(net.Fitness), float(net.Weight))
def to_net(self) -> Any:
"""Return the .NET ``ParameterSet`` with these values, fitness and weight.
Returns
-------
Numerics.Mathematics.Optimization.ParameterSet
A new .NET value.
"""
return _opt().ParameterSet(to_net_doubles(self.values), float(self.fitness), float(self.weight))
def clone(self) -> ParameterSet:
"""Return a copy with its own values array (``ParameterSet.Clone``).
Returns
-------
ParameterSet
The copy.
"""
return ParameterSet(np.array(self.values, dtype=np.float64), self.fitness, self.weight)
def to_xml(self) -> str:
"""Return the Numerics XML form (``ParameterSet.ToXElement``).
Returns
-------
str
The ``ParameterSet`` element with its ``Values``, ``Fitness`` and ``Weight`` attributes.
"""
return str(self.to_net().ToXElement().ToString())
@classmethod
def from_xml(cls, xml: str) -> ParameterSet:
"""Read the Numerics XML form (the ``ParameterSet(XElement)`` constructor).
Parameters
----------
xml : str
A ``ParameterSet`` element, as written by :meth:`to_xml`.
Returns
-------
ParameterSet
The parameter set.
"""
opt = _opt()
from System.Xml.Linq import XElement # noqa: PLC0415 - the runtime is running
return cls.from_net(opt.ParameterSet(XElement.Parse(str(xml))))
@dataclass(frozen=True, eq=False, slots=True)
class OptimizationProgress:
"""A progress report of a running optimizer (``OptimizationProgress``).
Parameters
----------
iterations : int
Iterations completed.
function_evaluations : int
Objective evaluations completed.
best_fitness : float
The best fitness so far (the negated objective during a maximization).
best_values : numpy.ndarray
The parameters of the best fitness.
"""
iterations: int
function_evaluations: int
best_fitness: float
best_values: np.ndarray
@classmethod
def from_net(cls, net: Any) -> OptimizationProgress:
"""Copy a .NET ``OptimizationProgress``.
Parameters
----------
net : Numerics.Mathematics.Optimization.OptimizationProgress
The .NET report.
Returns
-------
OptimizationProgress
The copy.
"""
return cls(int(net.Iterations), int(net.FunctionEvaluations), float(net.BestFitness),
to_numpy_doubles(net.BestValues))
def to_net(self) -> Any:
"""Return the .NET ``OptimizationProgress`` with these values.
Returns
-------
Numerics.Mathematics.Optimization.OptimizationProgress
A new .NET report.
"""
return _opt().OptimizationProgress(int(self.iterations), int(self.function_evaluations),
float(self.best_fitness), to_net_doubles(self.best_values))
_TRACE_FLATTEN = """
static double[] Flatten(System.Collections.Generic.List<Numerics.Mathematics.Optimization.ParameterSet> trace)
{
int n = trace.Count, p = n == 0 ? 0 : trace[0].Values.Length;
var flat = new double[n * (p + 1)];
for (int i = 0; i < n; i++)
{
var item = trace[i];
System.Array.Copy(item.Values, 0, flat, i * (p + 1), p);
flat[i * (p + 1) + p] = item.Fitness;
}
return flat;
}
"""
BULK_TRACE_LENGTH = 2000
"""Trace length from which a trace crosses in one copy through a compiled flattener, when Roslyn is staged."""
def _trace_arrays(net_trace: Any, scale: float, bulk: bool | None = None) -> tuple[np.ndarray, np.ndarray]:
"""Return the parameters and objective values of a .NET ``List<ParameterSet>`` trace.
Long traces cross in one copy through a compiled C# flattener when Roslyn is staged; short ones, or
any trace without Roslyn, cross one entry at a time. Both paths copy the same bits.
"""
count = int(net_trace.Count)
if count == 0:
return np.empty((0, 0)), np.empty(0)
if bulk is None:
bulk = count >= BULK_TRACE_LENGTH and callbacks.roslyn_available()
if bulk:
import System # noqa: PLC0415 - the runtime is running
from System.Collections.Generic import List # noqa: PLC0415
dtype = System.Func[List[_opt().ParameterSet], System.Array[System.Double]]
flat = to_numpy_doubles(callbacks.compile_csharp(_TRACE_FLATTEN, dtype)(net_trace))
table = flat.reshape(count, -1)
return np.ascontiguousarray(table[:, :-1]), scale * table[:, -1]
parameters, fitness = [], np.empty(count)
for i, item in enumerate(net_trace):
parameters.append(to_numpy_doubles(item.Values))
fitness[i] = float(item.Fitness)
return np.vstack(parameters), scale * fitness
@dataclass(frozen=True, eq=False)
class OptimizationResult:
"""The outcome of an optimizer run, shared by every optimizer.
Parameters
----------
parameters : numpy.ndarray
The best parameters (``BestParameterSet.Values``).
value : float
The objective at ``parameters``: ``BestParameterSet.Fitness``, with the sign restored for a
maximization.
iterations : int
Iterations used (``Iterations``).
function_evaluations : int
Objective evaluations used (``FunctionEvaluations``).
status : OptimizationStatus
The outcome (``Status``).
maximized : bool, optional
Whether the run maximized; default False.
hessian : numpy.ndarray or None, optional
The Hessian of the objective at ``parameters`` when Numerics computed it (``ComputeHessian``).
net_trace : object, optional
The .NET ``ParameterSetTrace`` list that :attr:`trace_parameters` and :attr:`trace_values` copy on
first use.
"""
parameters: np.ndarray
value: float
iterations: int
function_evaluations: int
status: OptimizationStatus
maximized: bool = False
hessian: np.ndarray | None = None
net_trace: Any = field(default=None, repr=False)
_cache: dict = field(default_factory=dict, repr=False, init=False)
@property
def success(self) -> bool:
"""Whether the status is ``SUCCESS``."""
return self.status is OptimizationStatus.SUCCESS
def _trace(self) -> tuple[np.ndarray, np.ndarray]:
"""Copy the .NET trace once and cache it."""
if "trace" not in self._cache:
if self.net_trace is None:
self._cache["trace"] = (np.empty((0, 0)), np.empty(0))
else:
self._cache["trace"] = _trace_arrays(self.net_trace, -1.0 if self.maximized else 1.0)
return self._cache["trace"]
@property
def trace_parameters(self) -> np.ndarray:
"""The best parameters after each evaluation, one row per evaluation (``ParameterSetTrace``)."""
return self._trace()[0]
@property
def trace_values(self) -> np.ndarray:
"""The best objective value after each evaluation, with the sign restored for a maximization."""
return self._trace()[1]
def _vector(fn: Any) -> Any:
"""Return an objective or constraint function as a ``Func<double[], double>``."""
return callbacks.vector_function(fn)
def _gradient(fn: Any) -> Any:
"""Return a gradient as a ``Func<double[], double[]>``, or None."""
return None if fn is None else callbacks.to_delegate(fn, "Func<double[],double[]>")
def _setting(name: str, kind: type, doc: str) -> property:
"""Return a read-write property mirroring the .NET property ``name``, converted with ``kind``."""
def fget(self: Any) -> Any:
return kind(getattr(self.net, name))
def fset(self: Any, value: Any) -> None:
setattr(self.net, name, kind(value))
return property(fget, fset, doc=doc)
def _array(name: str, doc: str) -> property:
"""Return a read-only property copying the .NET ``double[]`` property ``name`` (null gives None)."""
def fget(self: Any) -> np.ndarray | None:
values = getattr(self.net, name)
return None if values is None else to_numpy_doubles(values)
return property(fget, doc=doc)
def _method_setting(name: str, doc: str) -> property:
"""Return a read-write :class:`LocalMethod` property mirroring the .NET property ``name``."""
def fget(self: Any) -> LocalMethod:
return LocalMethod(str(getattr(self.net, name)))
def fset(self: Any, value: Any) -> None:
setattr(self.net, name, net_enum(_opt().LocalMethod, LocalMethod(value).value))
return property(fget, fset, doc=doc)
_REPORTER: dict[str, Any] = {}
def _progress_reporter(fn: Callable[[OptimizationProgress], Any]) -> Any:
"""Return an ``IProgress<OptimizationProgress>`` that calls ``fn`` with each report, synchronously."""
reporter = _REPORTER.get("type")
if reporter is None:
opt = _opt()
from System import IProgress # noqa: PLC0415 - the runtime is running
class _Reporter(IProgress[opt.OptimizationProgress]):
__namespace__ = "pynumerics.optimization"
def Report(self, value: Any) -> None: # noqa: N802 - the .NET interface member
self.callback(OptimizationProgress.from_net(value))
reporter = _REPORTER["type"] = _Reporter
instance = reporter()
instance.callback = fn
return instance
class Optimizer:
"""The settings, run methods and results every optimizer shares (``Optimizer``).
Construct one of the concrete optimizers; this base class only wraps an existing .NET optimizer.
Parameters
----------
net : Numerics.Mathematics.Optimization.Optimizer
The .NET optimizer to wrap.
functions : sequence, optional
The callables given to it, for the parallel policy.
Attributes
----------
net : Numerics.Mathematics.Optimization.Optimizer
The wrapped .NET optimizer.
"""
def __init__(self, net: Any, functions: Sequence[Any] = ()) -> None:
self.net = net
self._functions = tuple(functions)
self._progress: Callable[[OptimizationProgress], Any] | None = None
self._maximized = False
callbacks.apply_parallel_policy(net, *self._functions)
def _configure(self, settings: dict[str, Any]) -> None:
"""Set each keyword setting through its property (None keeps the default), then re-apply the policy."""
for name, value in settings.items():
member = getattr(type(self), name, None)
if not isinstance(member, property) or member.fset is None:
raise TypeError(f"{type(self).__name__} has no setting {name!r}.")
if value is not None:
setattr(self, name, value)
callbacks.apply_parallel_policy(self.net, *self._functions)
max_iterations = _setting("MaxIterations", int, "Iteration limit (``MaxIterations``).")
max_function_evaluations = _setting("MaxFunctionEvaluations", int,
"Objective evaluation limit (``MaxFunctionEvaluations``).")
absolute_tolerance = _setting("AbsoluteTolerance", float, "Absolute convergence tolerance (``AbsoluteTolerance``).")
relative_tolerance = _setting("RelativeTolerance", float, "Relative convergence tolerance (``RelativeTolerance``).")
report_failure = _setting("ReportFailure", bool, "Whether a failed search raises (``ReportFailure``).")
record_traces = _setting("RecordTraces", bool, "Whether the best-so-far trace is recorded (``RecordTraces``).")
compute_hessian = _setting("ComputeHessian", bool,
"Whether the Hessian is computed after convergence (``ComputeHessian``).")
progress_interval = _setting("ProgressInterval", int,
"Evaluations between progress reports (``ProgressInterval``).")
@property
def cancellation_token(self) -> Any:
"""The ``System.Threading.CancellationToken`` that stops the search (``CancellationToken``)."""
return self.net.CancellationToken
@cancellation_token.setter
def cancellation_token(self, token: Any) -> None:
self.net.CancellationToken = token
@property
def progress(self) -> Callable[[OptimizationProgress], Any] | None:
"""A callable given an :class:`OptimizationProgress` every ``progress_interval`` evaluations (``Progress``).
It runs synchronously on the optimizer thread. None, the default, turns reporting off.
"""
return self._progress
@progress.setter
def progress(self, fn: Callable[[OptimizationProgress], Any] | None) -> None:
self.net.Progress = None if fn is None else _progress_reporter(fn)
self._progress = fn
@property
def objective_function(self) -> Any:
"""The objective as the .NET ``Func<double[], double>`` Numerics calls (``ObjectiveFunction``).
Setting it accepts a Python callable, C# source or a delegate, and re-applies the parallel policy.
"""
return self.net.ObjectiveFunction
@objective_function.setter
def objective_function(self, fn: Any) -> None:
self.net.ObjectiveFunction = _vector(fn)
self._functions = (fn, *self._functions[1:])
callbacks.apply_parallel_policy(self.net, *self._functions)
@property
def number_of_parameters(self) -> int:
"""The number of parameters (``NumberOfParameters``)."""
return int(self.net.NumberOfParameters)
@property
def iterations(self) -> int:
"""Iterations used by the last run (``Iterations``)."""
return int(self.net.Iterations)
@property
def function_evaluations(self) -> int:
"""Objective evaluations used by the last run (``FunctionEvaluations``)."""
return int(self.net.FunctionEvaluations)
@property
def status(self) -> OptimizationStatus:
"""The outcome of the last run (``Status``)."""
return OptimizationStatus(str(self.net.Status))
@property
def best_parameter_set(self) -> ParameterSet:
"""The best parameters and fitness (``BestParameterSet``; the fitness is negated after a maximization)."""
return ParameterSet.from_net(self.net.BestParameterSet)
@property
def parameter_set_trace(self) -> list[ParameterSet]:
"""The best parameter set after each evaluation, fitness as Numerics stores it (``ParameterSetTrace``)."""
return [ParameterSet.from_net(item) for item in self.net.ParameterSetTrace]
@property
def hessian(self) -> np.ndarray | None:
"""The Hessian at the best parameters, or None when it was not computed (``Hessian``)."""
matrix = self.net.Hessian
return None if matrix is None else to_numpy_matrix(matrix.ToArray())
@property
def result(self) -> OptimizationResult:
"""The :class:`OptimizationResult` of the last run."""
best = self.net.BestParameterSet
values = best.Values
scale = -1.0 if self._maximized else 1.0
return OptimizationResult(np.empty(0) if values is None else to_numpy_doubles(values),
scale * float(best.Fitness), self.iterations, self.function_evaluations,
self.status, self._maximized, self.hessian, self.net.ParameterSetTrace)
def minimize(self) -> OptimizationResult:
"""Minimize the objective (``Minimize``).
Returns
-------
OptimizationResult
The best parameters, the objective value, the counts and the status.
Raises
------
RuntimeError
Whatever Numerics throws, translated by ``pynumerics.errors``, for example when the search
fails with ``report_failure`` set.
"""
self._maximized = False
self.net.Minimize()
return self.result
def maximize(self) -> OptimizationResult:
"""Maximize the objective (``Maximize``).
Returns
-------
OptimizationResult
The best parameters, the objective value (not negated), the counts and the status.
Raises
------
RuntimeError
Whatever Numerics throws, translated by ``pynumerics.errors``.
"""
self._maximized = True
self.net.Maximize()
return self.result
def clear_results(self) -> None:
"""Reset the counts, best parameter set, trace, status and Hessian (``ClearResults``)."""
self.net.ClearResults()
def _bounds(*arrays: Any) -> list[Any]:
"""Copy parameter vectors to ``System.Double[]``."""
return [to_net_doubles(a) for a in arrays]
class _BoundedSearch(Optimizer):
"""Bounds shared by the multidimensional optimizers."""
lower_bounds = _array("LowerBounds", "The parameter lower bounds (``LowerBounds``).")
upper_bounds = _array("UpperBounds", "The parameter upper bounds (``UpperBounds``).")
class _LocalSearch(_BoundedSearch):
"""Initial values shared by the local optimizers."""
initial_values = _array("InitialValues", "The starting parameters (``InitialValues``).")
class _GradientSearch(_LocalSearch):
"""The optional analytic gradient of the gradient-based local optimizers."""
@property
def gradient(self) -> Any:
"""The analytic gradient as a .NET ``Func<double[], double[]>``, or None for finite differences (``Gradient``).
Setting it accepts a Python callable returning an array, C# source or a delegate.
"""
return self.net.Gradient
@gradient.setter
def gradient(self, fn: Any) -> None:
self.net.Gradient = _gradient(fn)
self._functions = (self._functions[0], fn)
callbacks.apply_parallel_policy(self.net, *self._functions)
class _ScalarSearch(Optimizer):
"""The interval of the one-dimensional optimizers."""
@property
def lower_bound(self) -> float:
"""The lower end of the search interval (``LowerBound``)."""
return float(self.net.LowerBound)
@property
def upper_bound(self) -> float:
"""The upper end of the search interval (``UpperBound``)."""
return float(self.net.UpperBound)
class BrentSearch(_ScalarSearch):
"""Brent's one-dimensional minimizer on a bounded interval (``BrentSearch``).
The search is a port of ``scipy.optimize.minimize_scalar(method="bounded")``. Its step tolerance is
``relative_tolerance * |x| + absolute_tolerance / 3``; the constructor sets ``absolute_tolerance`` to about
3.3e-19, so the default is ``1e-8 * |x| + 1.1e-19``. With ``relative_tolerance=math.sqrt(2.2e-16)``,
``absolute_tolerance=1e-5`` and ``max_function_evaluations=500`` (SciPy's ``xatol`` and ``maxiter``
defaults) the minimizer is bitwise equal to SciPy's.
Parameters
----------
objective : callable, str or System.Delegate
Objective of one float (``Func<double, double>``).
lower_bound, upper_bound : float
The search interval.
**settings
Initial values of any settings property, for example ``relative_tolerance``.
"""
def __init__(self, objective: Any, lower_bound: float, upper_bound: float, **settings: Any) -> None:
super().__init__(_opt().BrentSearch(callbacks.scalar_function(objective), float(lower_bound),
float(upper_bound)), (objective,))
self._configure(settings)
def bracket(self, s: float = 1e-2, k: float = 2.0) -> tuple[float, float]:
"""Move the interval downhill until it brackets a minimum (``Bracket``).
Parameters
----------
s : float, optional
Initial step; default 1e-2, as in Numerics.
k : float, optional
Step growth factor; default 2, as in Numerics.
Returns
-------
tuple of float
The new ``(lower_bound, upper_bound)``.
"""
self.net.Bracket(float(s), float(k))
return self.lower_bound, self.upper_bound
class GoldenSection(_ScalarSearch):
"""Golden-section one-dimensional minimizer on a bounded interval (``GoldenSection``).
Parameters
----------
objective : callable, str or System.Delegate
Objective of one float (``Func<double, double>``).
lower_bound, upper_bound : float
The search interval.
**settings
Initial values of any settings property.
"""
def __init__(self, objective: Any, lower_bound: float, upper_bound: float, **settings: Any) -> None:
super().__init__(_opt().GoldenSection(callbacks.scalar_function(objective), float(lower_bound),
float(upper_bound)), (objective,))
self._configure(settings)
class NelderMead(_LocalSearch):
"""Bounded Nelder-Mead downhill simplex (``NelderMead``).
Parameters
----------
objective : callable, str or System.Delegate
Objective of a float64 array (``Func<double[], double>``).
initial_values, lower_bounds, upper_bounds : array_like
Start point and bounds, one entry per parameter.
**settings
Initial values of any settings property, for example ``simplex_scale``.
"""
def __init__(self, objective: Any, initial_values: Any, lower_bounds: Any, upper_bounds: Any,
**settings: Any) -> None:
arrays = _bounds(initial_values, lower_bounds, upper_bounds)
super().__init__(_opt().NelderMead(_vector(objective), int(arrays[0].Length), *arrays), (objective,))
self._configure(settings)
simplex_scale = _setting("SimplexScale", float,
"Initial simplex size as a fraction of the range (``SimplexScale``).")
enable_start_point_probe = _setting("EnableStartPointProbe", bool,
"Whether probes near the start may replace it (``EnableStartPointProbe``).")
start_point_probe_count = _setting("StartPointProbeCount", int,
"Number of start probes (``StartPointProbeCount``).")
start_point_probe_radius = _setting("StartPointProbeRadius", float,
"Start probe radius as a fraction of the range (``StartPointProbeRadius``).")
class Powell(_LocalSearch):
"""Bounded Powell conjugate-direction search (``Powell``).
Parameters
----------
objective : callable, str or System.Delegate
Objective of a float64 array.
initial_values, lower_bounds, upper_bounds : array_like
Start point and bounds.
**settings
Initial values of any settings property.
"""
def __init__(self, objective: Any, initial_values: Any, lower_bounds: Any, upper_bounds: Any,
**settings: Any) -> None:
arrays = _bounds(initial_values, lower_bounds, upper_bounds)
super().__init__(_opt().Powell(_vector(objective), int(arrays[0].Length), *arrays), (objective,))
self._configure(settings)
class BFGS(_GradientSearch):
"""Bounded BFGS quasi-Newton search (``BFGS``).
Parameters
----------
objective : callable, str or System.Delegate
Objective of a float64 array.
initial_values, lower_bounds, upper_bounds : array_like
Start point and bounds.
gradient : callable, str or System.Delegate, optional
Analytic gradient returning an array; None, the default, uses finite differences.
**settings
Initial values of any settings property, for example ``scale_initial_inverse_hessian``.
"""
def __init__(self, objective: Any, initial_values: Any, lower_bounds: Any, upper_bounds: Any,
gradient: Any = None, **settings: Any) -> None:
arrays = _bounds(initial_values, lower_bounds, upper_bounds)
super().__init__(_opt().BFGS(_vector(objective), int(arrays[0].Length), *arrays, _gradient(gradient)),
(objective, gradient))
self._configure(settings)
scale_initial_inverse_hessian = _setting(
"ScaleInitialInverseHessian", bool,
"Whether the first inverse Hessian is scaled (``ScaleInitialInverseHessian``).")
class LBFGSB(_GradientSearch):
"""Limited-memory BFGS with bound constraints (``LBFGSB``).
Parameters
----------
objective : callable, str or System.Delegate
Objective of a float64 array.
initial_values, lower_bounds, upper_bounds : array_like
Start point and bounds.
gradient : callable, str or System.Delegate, optional
Analytic gradient; None, the default, uses finite differences.
**settings
Initial values of any settings property, for example ``memory_size``.
"""
def __init__(self, objective: Any, initial_values: Any, lower_bounds: Any, upper_bounds: Any,
gradient: Any = None, **settings: Any) -> None:
arrays = _bounds(initial_values, lower_bounds, upper_bounds)
super().__init__(_opt().LBFGSB(_vector(objective), int(arrays[0].Length), *arrays, _gradient(gradient)),
(objective, gradient))
self._configure(settings)
memory_size = _setting("MemorySize", int, "Number of correction pairs kept (``MemorySize``).")
max_line_search_steps = _setting("MaxLineSearchSteps", int, "Line-search step limit (``MaxLineSearchSteps``).")
class GradientDescent(_GradientSearch):
"""Bounded gradient descent (``GradientDescent``).
Parameters
----------
objective : callable, str or System.Delegate
Objective of a float64 array.
initial_values, lower_bounds, upper_bounds : array_like
Start point and bounds.
alpha : float, optional
Learning rate; None keeps the Numerics default.
gradient : callable, str or System.Delegate, optional
Analytic gradient; None, the default, uses finite differences.
**settings
Initial values of any settings property.
"""
def __init__(self, objective: Any, initial_values: Any, lower_bounds: Any, upper_bounds: Any,
alpha: float | None = None, gradient: Any = None, **settings: Any) -> None:
arrays = _bounds(initial_values, lower_bounds, upper_bounds)
net = _opt().GradientDescent(_vector(objective), int(arrays[0].Length), *arrays)
net.Gradient = _gradient(gradient)
super().__init__(net, (objective, gradient))
self._configure({"alpha": alpha, **settings})
alpha = _setting("Alpha", float, "Learning rate (``Alpha``).")
class ADAM(_GradientSearch):
"""Bounded Adam optimizer (``ADAM``).
Parameters
----------
objective : callable, str or System.Delegate
Objective of a float64 array.
initial_values, lower_bounds, upper_bounds : array_like
Start point and bounds.
alpha : float, optional
Learning rate; None keeps the Numerics default.
gradient : callable, str or System.Delegate, optional
Analytic gradient; None, the default, uses finite differences.
**settings
Initial values of any settings property, for example ``beta1``.
"""
def __init__(self, objective: Any, initial_values: Any, lower_bounds: Any, upper_bounds: Any,
alpha: float | None = None, gradient: Any = None, **settings: Any) -> None:
arrays = _bounds(initial_values, lower_bounds, upper_bounds)
net = _opt().ADAM(_vector(objective), int(arrays[0].Length), *arrays)
net.Gradient = _gradient(gradient)
super().__init__(net, (objective, gradient))
self._configure({"alpha": alpha, **settings})
alpha = _setting("Alpha", float, "Learning rate (``Alpha``).")
beta1 = _setting("Beta1", float, "First-moment decay rate (``Beta1``).")
beta2 = _setting("Beta2", float, "Second-moment decay rate (``Beta2``).")
class _GlobalSearch(_BoundedSearch):
"""The seed and polishing settings of the global optimizers."""
prng_seed = _setting("PRNGSeed", int, "Random seed (``PRNGSeed``).")
polish = _setting("Polish", bool, "Whether a local search polishes the best point (``Polish``).")
polish_method = _method_setting("PolishMethod", "The local method of the polishing step (``PolishMethod``).")
class _PopulationSearch(_GlobalSearch):
"""Population size and parallel evaluation of the population optimizers."""
population_size = _setting("PopulationSize", int, "Population size (``PopulationSize``).")
max_degree_of_parallelism = _setting(
"MaxDegreeOfParallelism", int,
"Concurrent evaluations when parallel, or -1 for no limit (``MaxDegreeOfParallelism``).")
@property
def use_parallel(self) -> bool:
"""Whether each generation is evaluated on several threads (``UseParallel``; Numerics default False).
Parallel evaluation runs the deferred (synchronous) variant of the search, whose result differs
from the serial search but not with the thread count. It stays off with a Python objective, which
serializes on the GIL.
"""
return bool(self.net.UseParallel)
@use_parallel.setter
def use_parallel(self, value: bool) -> None:
self.net.UseParallel = bool(value)
callbacks.apply_parallel_policy(self.net, *self._functions)
class DifferentialEvolution(_PopulationSearch):
"""Differential evolution (``DifferentialEvolution``).
Parameters
----------
objective : callable, str or System.Delegate
Objective of a float64 array.
lower_bounds, upper_bounds : array_like
Parameter bounds.
**settings
Initial values of any settings property, for example ``population_size`` or ``use_parallel``.
"""
def __init__(self, objective: Any, lower_bounds: Any, upper_bounds: Any, **settings: Any) -> None:
arrays = _bounds(lower_bounds, upper_bounds)
super().__init__(_opt().DifferentialEvolution(_vector(objective), int(arrays[0].Length), *arrays),
(objective,))
self._configure(settings)
mutation = _setting("Mutation", float, "Mutation (differential weight) factor (``Mutation``).")
dither_rate = _setting("DitherRate", float, "Mutation dithering rate (``DitherRate``).")
crossover_probability = _setting("CrossoverProbability", float,
"Crossover probability (``CrossoverProbability``).")
@property
def initial_population(self) -> np.ndarray | None:
"""Optional starting population, one row per member (``InitialPopulation``); None draws a Latin hypercube."""
population = self.net.InitialPopulation
return None if population is None else np.vstack([to_numpy_doubles(row) for row in population])
@initial_population.setter
def initial_population(self, rows: Any) -> None:
if rows is None:
self.net.InitialPopulation = None
return
import System # noqa: PLC0415 - the runtime is running
from System.Collections.Generic import List # noqa: PLC0415
population = List[System.Array[System.Double]]()
for row in np.atleast_2d(np.asarray(rows, dtype=np.float64)):
population.Add(to_net_doubles(row))
self.net.InitialPopulation = population
@property
def integer_parameters(self) -> np.ndarray | None:
"""Optional flags marking integer-valued parameters (``IntegerParameters``)."""
flags = self.net.IntegerParameters
return None if flags is None else np.array([bool(f) for f in flags])
@integer_parameters.setter
def integer_parameters(self, flags: Any) -> None:
import System # noqa: PLC0415 - the runtime is running
self.net.IntegerParameters = None if flags is None else System.Array[System.Boolean](
[bool(f) for f in flags])
class ParticleSwarm(_PopulationSearch):
"""Particle swarm optimization (``ParticleSwarm``).
Parameters
----------
objective : callable, str or System.Delegate
Objective of a float64 array.
lower_bounds, upper_bounds : array_like
Parameter bounds.
**settings
Initial values of any settings property, for example ``population_size``.
"""
def __init__(self, objective: Any, lower_bounds: Any, upper_bounds: Any, **settings: Any) -> None:
arrays = _bounds(lower_bounds, upper_bounds)
super().__init__(_opt().ParticleSwarm(_vector(objective), int(arrays[0].Length), *arrays), (objective,))
self._configure(settings)
class _StartedGlobalSearch(_GlobalSearch):
"""The optional start point of CMA-ES and DDS."""
initial_values = _array("InitialValues", "The optional starting parameters (``InitialValues``).")
def _started(factory: Any, objective: Any, lower_bounds: Any, upper_bounds: Any, initial_values: Any) -> Any:
"""Build a global optimizer with or without its optional start point."""
lower, upper = _bounds(lower_bounds, upper_bounds)
if initial_values is None:
return factory(_vector(objective), int(lower.Length), lower, upper)
return factory(_vector(objective), int(lower.Length), to_net_doubles(initial_values), lower, upper)
class CMAES(_StartedGlobalSearch):
"""Covariance matrix adaptation evolution strategy with restarts (``CMAES``).
Parameters
----------
objective : callable, str or System.Delegate
Objective of a float64 array.
lower_bounds, upper_bounds : array_like
Parameter bounds.
initial_values : array_like, optional
Start point; None lets Numerics choose it.
**settings
Initial values of any settings property, for example ``restarts``.
"""
def __init__(self, objective: Any, lower_bounds: Any, upper_bounds: Any, initial_values: Any = None,
**settings: Any) -> None:
super().__init__(_started(_opt().CMAES, objective, lower_bounds, upper_bounds, initial_values), (objective,))
self._configure(settings)
population_size = _setting("PopulationSize", int, "Offspring per generation (``PopulationSize``).")
initial_step_size = _setting("InitialStepSize", float,
"Initial step size as a fraction of the range (``InitialStepSize``).")
restarts = _setting("Restarts", int, "Maximum number of restarts (``Restarts``).")
@property
def restarts_performed(self) -> int:
"""Restarts performed by the last run (``RestartsPerformed``)."""
return int(self.net.RestartsPerformed)
class DynamicallyDimensionedSearch(_StartedGlobalSearch):
"""Dynamically dimensioned search (``DynamicallyDimensionedSearch``).
Parameters
----------
objective : callable, str or System.Delegate
Objective of a float64 array.
lower_bounds, upper_bounds : array_like
Parameter bounds.
initial_values : array_like, optional
Start point; None lets Numerics choose it.
**settings
View remainder of file in raw view
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.