-
Notifications
You must be signed in to change notification settings - Fork 2
/
minuit2.cpp
1593 lines (1401 loc) · 51.9 KB
/
minuit2.cpp
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
// minuit2.cpp is Copyright (C) 2008 Johann Cohen-Tanugi <[email protected]>
// See http://seal.web.cern.ch/seal/MathLibs/5_0_8/Minuit2/html/
// for more information about SEAL Minuit 1.7.9.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
//
// Full licence is in the file COPYING and at http://www.gnu.org/copyleft/gpl.html
#include "minuit2.h"
#include <iostream>
using namespace ROOT::Minuit2;
/*
* PyVarObject_HEAD_INIT was added in Python 2.6. Its use is
* necessary to handle both Python 2 and 3. This replacement
* definition is for Python <=2.5
*/
#ifndef PyVarObject_HEAD_INIT
#define PyVarObject_HEAD_INIT(type, size) \
PyObject_HEAD_INIT(type) size,
#endif
#ifndef Py_TYPE
#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
#endif
#if PY_MAJOR_VERSION >= 3
#define MOD_DEF(ob, name, doc, methods) \
static struct PyModuleDef moduledef = { \
PyModuleDef_HEAD_INIT, name, doc, -1, methods, }; \
ob = PyModule_Create(&moduledef);
#else
#define MOD_DEF(ob, name, doc, methods) \
ob = Py_InitModule3(name, methods, doc);
#endif
/*
* Python 3 only has long.
*/
#if PY_MAJOR_VERSION >= 3
#define PyInt_AsLong PyLong_AsLong
#define PyInt_Check PyLong_Check
#endif
#if PY_MAJOR_VERSION >= 3
#define PyString_Check(x) 1
#define PyString_FromString(x) PyUnicode_FromString(x)
#define PyString_FromFormat(x,y) PyUnicode_FromFormat(x,y)
#define PyString_AsString(x) PyUnicode_AS_DATA(x)
#endif
static PyObject *PyExc_MinuitError;
static PyMemberDef minuit_Minuit_members[] = {
{(char*)"maxcalls", T_OBJECT, offsetof(minuit_Minuit, maxcalls), 0, (char*)"The maximum number of function calls before giving up on minimization."},
{(char*)"tol", T_DOUBLE, offsetof(minuit_Minuit, tol), 0, (char*)"Tolerance: minimization succeeds when the estimated vertical distance to the\nminimum is less than 0.001*tol*up."},
{(char*)"strategy", T_INT, offsetof(minuit_Minuit, strategy), 0, (char*)"Minimization strategy: 0 is fast, 1 is default, and 2 is thorough."},
{(char*)"up", T_DOUBLE, offsetof(minuit_Minuit, up), 0, (char*)"The vertical distance from the minimum that corresponds to one standard\ndeviation. This is 1.0 for chi^2 and 0.5 for -log likelihood."},
{(char*)"printMode", T_INT, offsetof(minuit_Minuit, printMode), 0, (char*)"Call-by-call printouts: 0 shows nothing, 1 shows parameter values, 2 shows\ndifferences from the starting point, and 3 shows differences from the previous\nvalue."},
{(char*)"fixed", T_OBJECT, offsetof(minuit_Minuit, fixed), 0, (char*)"Dictionary of fixed parameters; maps parameter strings to True/False."},
{(char*)"limits", T_OBJECT, offsetof(minuit_Minuit, limits), 0, (char*)"Dictionary of domain limits; maps parameter strings to (low, high) or None for\nunconstrained fitting."},
{(char*)"values", T_OBJECT, offsetof(minuit_Minuit, values), 0, (char*)"Dictionary of parameter values or starting points."},
{(char*)"args", T_OBJECT, offsetof(minuit_Minuit, args), READONLY, (char*)"Tuple of parameters or starting points in the order of the objective function's argument list."},
{(char*)"errors", T_OBJECT, offsetof(minuit_Minuit, errors), 0, (char*)"Dictionary of parameter errors or starting step sizes."},
{(char*)"merrors", T_OBJECT, offsetof(minuit_Minuit, merrors), READONLY, (char*)"Dictionary of all MINOS errors that have been calculated so far."},
{(char*)"covariance", T_OBJECT, offsetof(minuit_Minuit, covariance), READONLY, (char*)"Covariance matrix as a dictionary; maps pairs of parameter strings to matrix\nelements."},
{(char*)"fcn", T_OBJECT, offsetof(minuit_Minuit, fcn), READONLY, (char*)"The objective function: must accept only numeric arguments and return a number."},
{(char*)"fval", T_OBJECT, offsetof(minuit_Minuit, fval), READONLY, (char*)"The current minimum value of the objective function."},
{(char*)"ncalls", T_INT, offsetof(minuit_Minuit, ncalls), READONLY, (char*)"The number of times the objective function has been called: also known as NFCN."},
{(char*)"edm", T_OBJECT, offsetof(minuit_Minuit, edm), READONLY, (char*)"The current estimated vertical distance to the minimum."},
{(char*)"parameters", T_OBJECT, offsetof(minuit_Minuit, parameters), READONLY, (char*)"A tuple of parameters, in the order of the objective function's argument list."},
{NULL}
};
static PyMethodDef minuit_Minuit_methods[] = {
{(char*)"migrad", (PyCFunction)(minuit_Minuit_migrad), METH_NOARGS, (char*)"Attempt to minimize the function with the MIGRAD algorithm (recommended). No output if successful: see member values\nand errors."},
{(char*)"simplex", (PyCFunction)(minuit_Minuit_simplex), METH_NOARGS, (char*)"Attempt to minimize the function with the Simplex algorithm (not recommended). No output if successful: see member values\nand errors."},
{(char*)"hesse", (PyCFunction)(minuit_Minuit_hesse), METH_NOARGS, (char*)"Measure the covariance matrix with the current values."},
{(char*)"minos", (PyCFunction)(minuit_Minuit_minos), METH_VARARGS, (char*)"Measure non-linear error bounds after minimization. For all parameters, pass\nno arguments; for one parameter, pass parameter name and number of sigmas\n(negative for the other side)."},
{(char*)"contour", (PyCFunction)(minuit_Minuit_contour), METH_VARARGS | METH_KEYWORDS, (char*)"Measure a 2-dimensional contour line, given two parameter strings, a number of\nsigmas, and (optionally) a number of points."},
{(char*)"scan", (PyCFunction)(minuit_Minuit_scan), METH_VARARGS | METH_KEYWORDS, (char*)"Crudely minimize the function by scanning in N dimensions. Arguments are\n(parameter, bins, low, high), ..., for all parameters of interest. Keyword\narguments corners=True measures left edges, rather than centers of bins and\noutput=False suppresses the output tensor of measured values."},
{(char*)"matrix", (PyCFunction)(minuit_Minuit_matrix), METH_VARARGS | METH_KEYWORDS, (char*)"Express the covariance as a tuple-of-tuples matrix. Optional correlation=True\ncalculates the (normalized) correlation matrix instead, and skip_fixed=True\nremoves fixed parameters (which have zeroed entries)."},
{NULL}
};
static PyTypeObject minuit_MinuitType = {
PyVarObject_HEAD_INIT(NULL,0)
"minuit2.Minuit2", /*tp_name*/
sizeof(minuit_Minuit), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)minuit_Minuit_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT, /*tp_flags*/
"Represents a function to be minimized by Minuit. Pass a Python callable, and\noptionally param1=2., param2=3., ... to set initial values, err_param1=0.5 to\nset initial step sizes, fix_param1=True to prevent parameters from floating in\nthe fit, and limit_param1=(low, high) to set limits.\n\nTo minimize, call minuit(), for a covariance matrix, call hesse(), for\nnon-linear errors, minos() or minos(param, nsigmas), and for 2-dimensional\ncontour lines, call contour(param1, param2, nsigmas). You can also scan the\nfunction with scan((param1, bins, low, high), (param2, bins, low, high), ...).", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
minuit_Minuit_methods, /* tp_methods */
minuit_Minuit_members, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)minuit_Minuit_init, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
};
static int minuit_Minuit_init(minuit_Minuit *self, PyObject *args, PyObject *kwds) {
self->myfcn = NULL;
self->upar = NULL;
self->min = NULL;
self->scandepth = 0;
self->maxcalls = NULL;
self->fixed = NULL;
self->limits = NULL;
self->values = NULL;
self->args = NULL;
self->errors = NULL;
self->merrors = NULL;
self->covariance = NULL;
self->fval = NULL;
self->edm = NULL;
self->self = NULL;
PyObject *arg = NULL;
if (!PyArg_ParseTuple(args, "O", &arg) || !PyCallable_Check(arg)) {
PyErr_SetString(PyExc_TypeError, "First argument must be a callable function, instance method or instance.");
return -1;
}
PyObject *function = NULL;
if (PyFunction_Check(arg)){
function = arg;
}
else if (PyMethod_Check(arg)){
function = PyMethod_Function(arg);
self->self = PyMethod_Self(arg);
if (!self->self){
PyErr_SetString(PyExc_TypeError, "Unbound methods are not supported.");
return -1;
}
Py_INCREF(self->self);
}
else {
// __call__ has to exist because we checked that the object is callable
arg = PyObject_GetAttrString(arg,"__call__");
function = PyMethod_Function(arg);
self->self = PyMethod_Self(arg);
if (!self->self){
PyErr_SetString(PyExc_TypeError, "Unbound methods are not supported.");
return -1;
}
Py_DECREF(arg);
Py_INCREF(self->self);
}
self->fcn = function;
Py_INCREF(self->fcn);
PyObject *func_code = PyFunction_GetCode(self->fcn);
if (func_code == NULL) {
return -1;
}
PyObject *co_varnames = PyObject_GetAttrString(func_code, "co_varnames");
if (co_varnames == NULL) {
return -1;
}
PyObject *co_argcount = PyObject_GetAttrString(func_code, "co_argcount");
if (co_argcount == NULL) {
Py_DECREF(co_varnames);
return -1;
}
if (!PyTuple_Check(co_varnames)) {
PyErr_SetString(PyExc_TypeError, "function.func_code.co_varnames must be a tuple.");
Py_DECREF(co_varnames);
Py_DECREF(co_argcount);
return -1;
}
if (!PyInt_Check(co_argcount)) {
PyErr_SetString(PyExc_TypeError, "function.func_code.co_argcount must be an integer.");
Py_DECREF(co_varnames);
Py_DECREF(co_argcount);
return -1;
}
if (PyInt_AsLong(co_argcount) < 1) {
PyErr_SetString(PyExc_TypeError, "This function has no parameters to minimize.");
Py_DECREF(co_varnames);
Py_DECREF(co_argcount);
return -1;
}
// ensure that self->parameters does not contain self method parameter
if (self->self){
self->parameters = PyTuple_GetSlice(co_varnames, 1, PyInt_AsLong(co_argcount));
}
else{
self->parameters = PyTuple_GetSlice(co_varnames, 0, PyInt_AsLong(co_argcount));
}
Py_DECREF(co_varnames);
Py_DECREF(co_argcount);
self->npar = PyTuple_Size(self->parameters);
self->maxcalls = Py_BuildValue("O", Py_None);
self->tol = 0.1;
self->strategy = 1;
self->up = 1.;
self->printMode = 0;
self->fixed = PyDict_New();
self->limits = PyDict_New();
self->values = PyDict_New();
self->args = Py_BuildValue("O", Py_None);
self->errors = PyDict_New();
self->merrors = PyDict_New();
self->covariance = Py_BuildValue("O", Py_None);
self->fval = Py_BuildValue("O", Py_None);
self->ncalls = 0;
self->edm = Py_BuildValue("O", Py_None);
self->upar = new MnUserParameters();
Py_DECREF(self->args);
self->args = PyTuple_New(self->npar);
for (Py_ssize_t i = 0; i < self->npar; i++) {
PyObject *param = PyTuple_GetItem(self->parameters, i);
if (!PyString_Check(param)) {
PyErr_SetString(PyExc_RuntimeError, "function.func_code.co_varnames must be a tuple of strings.");
Py_DECREF(self->args);
self->args = Py_BuildValue("O", Py_None);
return -1;
}
double value = 0.;
double error = 0.1;
if (kwds != 0 && PyDict_Contains(kwds, param) == 1) {
if (!PyNumber_Check(PyDict_GetItem(kwds, param))) {
PyErr_SetString(PyExc_TypeError, "All values must be numbers.");
Py_DECREF(self->args);
self->args = Py_BuildValue("O", Py_None);
return -1;
}
value = PyFloat_AsDouble(PyDict_GetItem(kwds, param));
}
PyObject *pyvalue = Py_BuildValue("d", value);
if (PyDict_SetItem(self->values, param, pyvalue) != 0) {
Py_DECREF(pyvalue);
Py_DECREF(self->args);
self->args = Py_BuildValue("O", Py_None);
return -1;
}
if (PyTuple_SetItem(self->args, i, pyvalue) != 0) {
Py_DECREF(pyvalue);
Py_DECREF(self->args);
self->args = Py_BuildValue("O", Py_None);
return -1;
}
PyObject *err_param = PyString_FromFormat("err_%s", PyString_AsString(param));
if (kwds != 0 && PyDict_Contains(kwds, err_param) == 1) {
if (!PyNumber_Check(PyDict_GetItem(kwds, err_param))) {
PyErr_SetString(PyExc_TypeError, "All errors must be numbers.");
Py_DECREF(self->args);
self->args = Py_BuildValue("O", Py_None);
return -1;
}
error = PyFloat_AsDouble(PyDict_GetItem(kwds, err_param));
}
PyObject *pyerror = Py_BuildValue("d", error);
if (PyDict_SetItem(self->errors, param, pyerror) != 0) {
Py_DECREF(err_param);
Py_DECREF(pyerror);
return -1;
}
Py_DECREF(pyerror);
Py_DECREF(err_param);
PyObject *fixvalue = Py_False;
PyObject *fix_param = PyString_FromFormat("fix_%s", PyString_AsString(param));
if (kwds != 0 && PyDict_Contains(kwds, fix_param) == 1) {
fixvalue = PyDict_GetItem(kwds, fix_param);
if (fixvalue != Py_True && fixvalue != Py_False) {
PyErr_Format(PyExc_TypeError, "fix_%s must be True or False.", PyString_AsString(param));
Py_DECREF(self->args);
self->args = Py_BuildValue("O", Py_None);
return -1;
}
}
if (PyDict_SetItem(self->fixed, param, fixvalue) != 0) {
Py_DECREF(self->args);
self->args = Py_BuildValue("O", Py_None);
return -1;
}
PyObject *limitvalue = Py_None;
PyObject *limit_param = PyString_FromFormat("limit_%s", PyString_AsString(param));
if (kwds != 0 && PyDict_Contains(kwds, limit_param) == 1) {
limitvalue = PyDict_GetItem(kwds, limit_param);
if (limitvalue != Py_None) {
if (!(PyTuple_Check(limitvalue) && PyTuple_Size(limitvalue) == 2)) {
PyErr_Format(PyExc_TypeError, "limit_%s must be None or (low, high).", PyString_AsString(param));
Py_DECREF(self->args);
self->args = Py_BuildValue("O", Py_None);
return -1;
}
if (!PyNumber_Check(PyTuple_GetItem(limitvalue, 0))) {
PyErr_Format(PyExc_TypeError, "limit_%s[0] (lower limit) must be a number.", PyString_AsString(param));
Py_DECREF(self->args);
self->args = Py_BuildValue("O", Py_None);
return -1;
}
if (!PyNumber_Check(PyTuple_GetItem(limitvalue, 1))) {
PyErr_Format(PyExc_TypeError, "limit_%s[1] (upper limit) must be a number.", PyString_AsString(param));
Py_DECREF(self->args);
self->args = Py_BuildValue("O", Py_None);
return -1;
}
}
}
if (PyDict_SetItem(self->limits, param, limitvalue) != 0) {
Py_DECREF(self->args);
self->args = Py_BuildValue("O", Py_None);
return -1;
}
Py_DECREF(limit_param);
Py_DECREF(fix_param);
self->upar->Add(PyString_AsString(param), value, error);
}
self->myfcn = new MyFCN(self->fcn, self->self, self->npar);
self->myfcn->SetUp(self->up);
self->myfcn->SetPrintMode(self->printMode);
return 0;
}
static int minuit_Minuit_dealloc(minuit_Minuit *self) {
delete self->myfcn;
delete self->upar;
delete self->min;
self->myfcn = NULL;
self->upar = NULL;
self->min = NULL;
Py_XDECREF(self->self);
Py_XDECREF(self->fcn);
Py_XDECREF(self->parameters);
Py_XDECREF(self->maxcalls);
Py_XDECREF(self->fixed);
Py_XDECREF(self->limits);
Py_XDECREF(self->values);
Py_XDECREF(self->args);
Py_XDECREF(self->errors);
Py_XDECREF(self->merrors);
Py_XDECREF(self->covariance);
Py_XDECREF(self->fval);
Py_XDECREF(self->edm);
Py_TYPE(self)->tp_free((PyObject*)self);
return 0;
}
bool minuit_prepare(minuit_Minuit *self, int &maxcalls, std::vector<std::string> &floating) {
maxcalls = 0;
if (self->maxcalls == Py_None) { /* 0 means no limit */ }
else if (PyInt_Check(self->maxcalls)) {
maxcalls = int(PyInt_AsLong(self->maxcalls));
if (maxcalls <= 0) {
PyErr_SetString(PyExc_ValueError, "maxcalls must be positive (set to None for no limit).");
return false;
}
}
else {
PyErr_SetString(PyExc_TypeError, "maxcalls must be an integer or None");
return false;
}
if (self->tol <= 0.) {
PyErr_SetString(PyExc_ValueError, "tol must be positive.");
return false;
}
if (self->strategy != 0 && self->strategy != 1 && self->strategy != 2) {
PyErr_SetString(PyExc_ValueError, "strategy must be 0, 1, or 2.");
return false;
}
if (self->up <= 0.) {
PyErr_SetString(PyExc_ValueError, "tol must be positive.");
return false;
}
if (self->printMode != 0 && self->printMode != 1 && self->printMode != 2 && self->printMode != 3) {
PyErr_SetString(PyExc_ValueError, "printMode must be 0, 1, 2, or 3.");
return false;
}
if (!PyDict_Check(self->values)) {
PyErr_SetString(PyExc_TypeError, "values must be a dictionary.");
return false;
}
if (!PyDict_Check(self->errors)) {
PyErr_SetString(PyExc_TypeError, "errors must be a dictionary.");
return false;
}
if (!PyDict_Check(self->fixed)) {
PyErr_SetString(PyExc_TypeError, "fixed must be a dictionary.");
return false;
}
if (!PyDict_Check(self->limits)) {
PyErr_SetString(PyExc_TypeError, "limits must be a dictionary.");
return false;
}
int nfixed = 0;
floating.clear();
for (int i = 0; i < self->npar; i++) {
PyObject *value = PyDict_GetItemString(self->values, self->upar->Name(i));
if (value == NULL) {
PyErr_Format(PyExc_KeyError, "Parameter \"%s\" is missing from values.", self->upar->Name(i));
return false;
}
if (!PyNumber_Check(value)) {
PyErr_Format(PyExc_TypeError, "values[\"%s\"] must be a number.", self->upar->Name(i));
return false;
}
self->upar->SetValue(i, PyFloat_AsDouble(value));
PyObject *error = PyDict_GetItemString(self->errors, self->upar->Name(i));
if (error == NULL) {
PyErr_Format(PyExc_KeyError, "Parameter \"%s\" is missing from errors.", self->upar->Name(i));
return false;
}
if (!PyNumber_Check(error)) {
PyErr_Format(PyExc_TypeError, "errors[\"%s\"] must be a number.", self->upar->Name(i));
return false;
}
self->upar->SetError(i, PyFloat_AsDouble(error));
PyObject *fixed = PyDict_GetItemString(self->fixed, self->upar->Name(i));
if (fixed == NULL) {
PyErr_Format(PyExc_KeyError, "Parameter \"%s\" is missing from fixed.", self->upar->Name(i));
return false;
}
if (fixed != Py_True && fixed != Py_False) {
PyErr_Format(PyExc_TypeError, "fixed[\"%s\"] must be True or False.", self->upar->Name(i));
return false;
}
if (fixed == Py_True) {
if (!self->upar->Parameter(i).IsFixed()) {
self->upar->Fix(i);
}
nfixed++;
}
else {
if (self->upar->Parameter(i).IsFixed()) {
self->upar->Release(i);
}
floating.push_back(std::string(self->upar->Name(i)));
}
PyObject *limit = PyDict_GetItemString(self->limits, self->upar->Name(i));
if (limit == NULL) {
PyErr_Format(PyExc_KeyError, "Parameter \"%s\" is missing from limits.", self->upar->Name(i));
return false;
}
if (limit == Py_None) {
self->upar->RemoveLimits(i);
}
else if (PySequence_Check(limit) && PySequence_Size(limit) == 2) {
if (!PyNumber_Check(PySequence_GetItem(limit, 0))) {
PyErr_Format(PyExc_TypeError, "limits[\"%s\"][0] (lower limit) must be a number.", self->upar->Name(i));
return false;
}
if (!PyNumber_Check(PySequence_GetItem(limit, 1))) {
PyErr_Format(PyExc_TypeError, "limits[\"%s\"][1] (upper limit) must be a number.", self->upar->Name(i));
return false;
}
if (PyFloat_AsDouble(PySequence_GetItem(limit, 0)) >= PyFloat_AsDouble(PySequence_GetItem(limit, 1))) {
PyErr_Format(PyExc_ValueError, "limits[\"%s\"] has lower limit >= upper limit.", self->upar->Name(i));
return false;
}
self->upar->RemoveLimits(i);
self->upar->SetLimits(i, PyFloat_AsDouble(PySequence_GetItem(limit, 0)), PyFloat_AsDouble(PySequence_GetItem(limit, 1)));
}
else {
PyErr_Format(PyExc_TypeError, "limits[\"%s\"] must be None or (low, high).", self->upar->Name(i));
return false;
}
}
if (nfixed >= self->npar) {
PyErr_SetString(PyExc_RuntimeError, "Can't minimize if all parameters are fixed.");
return false;
}
self->myfcn->SetUp(self->up);
self->myfcn->SetPrintMode(self->printMode);
if (self->printMode > 0) {
switch (self->printMode) {
case 1:
printf(" FCN Result | Parameter values\n");
printf("-------------+--------------------------------------------------------\n");
break;
case 2:
printf(" FCN Result | Differences in parameter values from initial\n");
printf("-------------+--------------------------------------------------------\n");
self->myfcn->SetOriginal(self->upar->Params());
break;
case 3:
printf(" FCN Result | Differences in parameter values from the previous\n");
printf("-------------+--------------------------------------------------------\n");
self->myfcn->SetOriginal(self->upar->Params());
break;
}
}
return true;
}
static PyObject *minuit_Minuit_simplex(minuit_Minuit *self) {
int maxcalls = 0;
std::vector<std::string> floating;
if (!minuit_prepare(self, maxcalls, floating)) {
return NULL;
}
MnSimplex simplex(*self->myfcn, *self->upar, self->strategy);
if (self->min != NULL) {
delete self->min;
self->min = NULL;
}
try {
self->min = new FunctionMinimum(simplex(maxcalls, self->tol));
}
catch (ExceptionDuringMinimization theException) {
if (self->min != NULL) {
delete self->min;
self->min = NULL;
}
return NULL;
}
Py_DECREF(self->fval);
self->fval = PyFloat_FromDouble(self->min->Fval());
self->ncalls = self->min->NFcn();
Py_DECREF(self->edm);
self->edm = PyFloat_FromDouble(self->min->Edm());
Py_DECREF(self->args);
self->args = PyTuple_New(self->npar);
for (int i = 0; i < self->npar; i++) {
PyObject *value = PyFloat_FromDouble(self->min->UserParameters().Value(i));
if (PyDict_SetItemString(self->values, self->upar->Name(i), value) != 0) {
Py_DECREF(value);
if (self->min != NULL) {
delete self->min;
self->min = NULL;
}
Py_DECREF(self->args);
self->args = Py_BuildValue("O", Py_None);
return NULL;
}
if (PyTuple_SetItem(self->args, i, value) != 0) {
Py_DECREF(value);
if (self->min != NULL) {
delete self->min;
self->min = NULL;
}
Py_DECREF(self->args);
self->args = Py_BuildValue("O", Py_None);
return NULL;
}
PyObject *error = PyFloat_FromDouble(self->min->UserParameters().Error(i));
if (PyDict_SetItemString(self->errors, self->upar->Name(i), error) != 0) {
Py_DECREF(error);
if (self->min != NULL) {
delete self->min;
self->min = NULL;
}
Py_DECREF(self->args);
self->args = Py_BuildValue("O", Py_None);
return NULL;
}
Py_DECREF(error);
}
if (self->min->HasValidCovariance()) {
MnUserCovariance ucov(self->min->UserCovariance());
PyObject *cov = PyDict_New();
for (unsigned int i = 0; i < floating.size(); i++) {
for (unsigned int j = 0; j < floating.size(); j++) {
PyObject *key = Py_BuildValue("ss", floating[i].c_str(), floating[j].c_str());
if (key == NULL) {
Py_DECREF(cov);
if (self->min != NULL) {
delete self->min;
self->min = NULL;
}
return NULL;
}
PyObject *val = PyFloat_FromDouble(ucov(i, j));
if (val == NULL) {
Py_DECREF(cov);
Py_DECREF(key);
if (self->min != NULL) {
delete self->min;
self->min = NULL;
}
return NULL;
}
if (PyDict_SetItem(cov, key, val) != 0) {
Py_DECREF(cov);
if (self->min != NULL) {
delete self->min;
self->min = NULL;
}
return NULL;
}
Py_DECREF(key);
Py_DECREF(val);
}
}
Py_DECREF(self->covariance);
self->covariance = cov;
// one reference to cov == self->covariance is already counted
}
else {
Py_DECREF(self->covariance);
self->covariance = Py_BuildValue("O", Py_None);
}
if (!self->min->IsValid()) {
if (self->min->HasReachedCallLimit()) {
PyErr_SetString(PyExc_MinuitError, "Minuit reached the specified call limit (maxcalls).");
}
else if (self->min->IsAboveMaxEdm()) {
PyErr_SetString(PyExc_MinuitError, "Function value is above the specified estimated distance to the minimum (edm).");
}
else if (!self->min->HasPosDefCovar()) {
PyErr_SetString(PyExc_MinuitError, "Covariance is not positive definite.");
}
else if (!self->min->HasMadePosDefCovar()) {
PyErr_SetString(PyExc_MinuitError, "Covariance could not be made positive definite.");
}
else if (!self->min->HasAccurateCovar()) {
PyErr_SetString(PyExc_MinuitError, "Covariance is not accurate.");
}
else if (!self->min->HasValidCovariance()) {
PyErr_SetString(PyExc_MinuitError, "Covariance is not valid.");
}
else if (self->min->HesseFailed()) {
PyErr_SetString(PyExc_MinuitError, "HESSE failed.");
}
else if (!self->min->HasValidParameters()) {
PyErr_SetString(PyExc_MinuitError, "Parameters are not valid.");
}
else {
PyErr_SetString(PyExc_MinuitError, "Minuit failed.");
}
if (self->min != NULL) {
delete self->min;
self->min = NULL;
}
return NULL;
}
return Py_BuildValue("O", Py_None);
}
static PyObject *minuit_Minuit_migrad(minuit_Minuit *self) {
int maxcalls = 0;
std::vector<std::string> floating;
if (!minuit_prepare(self, maxcalls, floating)) {
return NULL;
}
MnMigrad migrad(*self->myfcn, *self->upar, self->strategy);
if (self->min != NULL) {
delete self->min;
self->min = NULL;
}
try {
self->min = new FunctionMinimum(migrad(maxcalls, self->tol));
}
catch (ExceptionDuringMinimization theException) {
if (self->min != NULL) {
delete self->min;
self->min = NULL;
}
return NULL;
}
Py_DECREF(self->fval);
self->fval = PyFloat_FromDouble(self->min->Fval());
self->ncalls = self->min->NFcn();
Py_DECREF(self->edm);
self->edm = PyFloat_FromDouble(self->min->Edm());
Py_DECREF(self->args);
self->args = PyTuple_New(self->npar);
for (int i = 0; i < self->npar; i++) {
PyObject *value = PyFloat_FromDouble(self->min->UserParameters().Value(i));
if (PyDict_SetItemString(self->values, self->upar->Name(i), value) != 0) {
Py_DECREF(value);
if (self->min != NULL) {
delete self->min;
self->min = NULL;
}
Py_DECREF(self->args);
self->args = Py_BuildValue("O", Py_None);
return NULL;
}
if (PyTuple_SetItem(self->args, i, value) != 0) {
Py_DECREF(value);
if (self->min != NULL) {
delete self->min;
self->min = NULL;
}
Py_DECREF(self->args);
self->args = Py_BuildValue("O", Py_None);
return NULL;
}
PyObject *error = PyFloat_FromDouble(self->min->UserParameters().Error(i));
if (PyDict_SetItemString(self->errors, self->upar->Name(i), error) != 0) {
Py_DECREF(error);
if (self->min != NULL) {
delete self->min;
self->min = NULL;
}
Py_DECREF(self->args);
self->args = Py_BuildValue("O", Py_None);
return NULL;
}
Py_DECREF(error);
}
if (self->min->HasValidCovariance()) {
MnUserCovariance ucov(self->min->UserCovariance());
PyObject *cov = PyDict_New();
for (unsigned int i = 0; i < floating.size(); i++) {
for (unsigned int j = 0; j < floating.size(); j++) {
PyObject *key = Py_BuildValue("ss", floating[i].c_str(), floating[j].c_str());
if (key == NULL) {
Py_DECREF(cov);
if (self->min != NULL) {
delete self->min;
self->min = NULL;
}
return NULL;
}
PyObject *val = PyFloat_FromDouble(ucov(i, j));
if (val == NULL) {
Py_DECREF(cov);
Py_DECREF(key);
if (self->min != NULL) {
delete self->min;
self->min = NULL;
}
return NULL;
}
if (PyDict_SetItem(cov, key, val) != 0) {
Py_DECREF(cov);
if (self->min != NULL) {
delete self->min;
self->min = NULL;
}
return NULL;
}
Py_DECREF(key);
Py_DECREF(val);
}
}
Py_DECREF(self->covariance);
self->covariance = cov;
// one reference to cov == self->covariance is already counted
}
else {
Py_DECREF(self->covariance);
self->covariance = Py_BuildValue("O", Py_None);
}
if (!self->min->IsValid()) {
if (self->min->HasReachedCallLimit()) {
PyErr_SetString(PyExc_MinuitError, "Minuit reached the specified call limit (maxcalls).");
}
else if (self->min->IsAboveMaxEdm()) {
PyErr_SetString(PyExc_MinuitError, "Function value is above the specified estimated distance to the minimum (edm).");
}
else if (!self->min->HasPosDefCovar()) {
PyErr_SetString(PyExc_MinuitError, "Covariance is not positive definite.");
}
else if (!self->min->HasMadePosDefCovar()) {
PyErr_SetString(PyExc_MinuitError, "Covariance could not be made positive definite.");
}
else if (!self->min->HasAccurateCovar()) {
PyErr_SetString(PyExc_MinuitError, "Covariance is not accurate.");
}
else if (!self->min->HasValidCovariance()) {
PyErr_SetString(PyExc_MinuitError, "Covariance is not valid.");
}
else if (self->min->HesseFailed()) {
PyErr_SetString(PyExc_MinuitError, "HESSE failed.");
}
else if (!self->min->HasValidParameters()) {
PyErr_SetString(PyExc_MinuitError, "Parameters are not valid.");
}
else {
PyErr_SetString(PyExc_MinuitError, "Minuit failed.");
}
if (self->min != NULL) {
delete self->min;
self->min = NULL;
}
return NULL;
}
return Py_BuildValue("O", Py_None);
}
static PyObject *minuit_Minuit_hesse(minuit_Minuit *self) {
int maxcalls = 0;
std::vector<std::string> floating;
if (!minuit_prepare(self, maxcalls, floating)) {
return NULL;
}
MnHesse hesse(self->strategy);
MnUserParameterState ustate;
try {
ustate = hesse(*self->myfcn, *self->upar, maxcalls);
}
catch (ExceptionDuringMinimization theException) {
return NULL;
}
self->ncalls = ustate.NFcn();
for (int i = 0; i < self->npar; i++) {
PyObject *error = PyFloat_FromDouble(ustate.Error(i));
if (PyDict_SetItemString(self->errors, self->upar->Name(i), error) != 0) {
Py_DECREF(error);
return NULL;
}
Py_DECREF(error);
}
if (ustate.HasCovariance()) {
MnUserCovariance ucov(ustate.Covariance());
PyObject *cov = PyDict_New();
for (unsigned int i = 0; i < floating.size(); i++) {
for (unsigned int j = 0; j < floating.size(); j++) {
PyObject *key = Py_BuildValue("ss", floating[i].c_str(), floating[j].c_str());
if (key == NULL) {
Py_DECREF(cov);
return NULL;
}
PyObject *val = PyFloat_FromDouble(ucov(i, j));
if (val == NULL) {
Py_DECREF(cov);
Py_DECREF(key);
return NULL;
}
if (PyDict_SetItem(cov, key, val) != 0) {
Py_DECREF(cov);
return NULL;
}
Py_DECREF(key);
Py_DECREF(val);
}
}
Py_DECREF(self->covariance);
self->covariance = cov;
// one reference to cov == self->covariance is already counted
}
else {
Py_DECREF(self->covariance);
self->covariance = Py_BuildValue("O", Py_None);
}
if (!ustate.IsValid()) {
PyErr_SetString(PyExc_MinuitError, "HESSE failed.");
return NULL;
}
return Py_BuildValue("O", Py_None);
}
static PyObject *minuit_Minuit_minos(minuit_Minuit *self, PyObject *args) {
if (args == NULL || PyTuple_Size(args) == 0) {
for (int i = 0; i < self->npar; i++) {
PyObject *subargs = Py_BuildValue("Od", PyTuple_GetItem(self->parameters, i), -1.);
if (minuit_Minuit_minos(self, subargs) == NULL) {
Py_DECREF(subargs);
return NULL;
}
Py_DECREF(subargs);
subargs = Py_BuildValue("Od", PyTuple_GetItem(self->parameters, i), 1.);
if (minuit_Minuit_minos(self, subargs) == NULL) {
Py_DECREF(subargs);
return NULL;
}
Py_DECREF(subargs);
}
return Py_BuildValue("O", Py_None);
}
char *param;
double sigmas;
if (!PyArg_ParseTuple(args, "sd", ¶m, &sigmas)) {
PyErr_SetString(PyExc_TypeError, "Either pass no arguments or parameter, number of sigmas.");
return NULL;
}
if (sigmas == 0.) {
PyErr_SetString(PyExc_TypeError, "Number of sigmas may not be zero.");
return NULL;
}