-
Notifications
You must be signed in to change notification settings - Fork 2
/
pgamodule.c
3635 lines (3435 loc) · 112 KB
/
pgamodule.c
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
/* Copyright (C) 2005-23 Dr. Ralf Schlatterbeck Open Source Consulting.
* Reichergasse 131, A-3411 Weidling.
* Web: http://www.runtux.com Email: office@runtux.com
* ****************************************************************************
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* ****************************************************************************
*/
#include <Python.h>
#include <pgapack.h>
#include <stdio.h>
#undef NDEBUG
#include <stddef.h>
#include <assert.h>
#include <Version.h>
#define IS_PY3 (PY_VERSION_HEX >= 0x3000000)
/* Conditional compilation for python2 vs python3 */
# if IS_PY3
# define PyInt_Type_Compat PyLong_Type
# define PyString_Check_Compat PyUnicode_Check
# define PyString_FromString_Compat(x) PyUnicode_FromString((x))
# define PyFileObject PyObject
# define FAIL NULL
# else /* Python 2 */
# define FAIL
# define PyString_Check_Compat PyString_Check
# define PyString_FromString_Compat(x) PyString_FromString((x))
# define PyInt_Type_Compat PyInt_Type
# endif /* Python 2 */
/* Necessary forward declarations */
static char **parse_argv (PyObject *argv, int *argcp);
/*
* Global data
*/
/* This is a dictionary for retrieving Python PGA objects by PGA ctx */
static PyObject *contexts = NULL;
/* Error handling macros */
#define SET_ERR(ctx) (*((int *)ctx->ga.CustomData) = 1)
#define HAS_ERR(ctx) (*((int *)(ctx)->ga.CustomData))
#define ERR_CHECK(ctx,x,r) do { \
if (!(x)) { \
SET_ERR(ctx); \
return r; \
} \
} while (0)
#define ERR_CHECK_ERRNO(ctx,x,r) do { \
if (!(x)) { \
PyErr_SetString (PyExc_RuntimeError, strerror (errno)); \
SET_ERR(ctx); \
return r; \
} \
} while (0)
#define ERR_CHECK_OCCURRED(ctx,r) do { \
if (HAS_ERR(ctx)) { \
if (!PyErr_Occurred ()) { \
PyErr_SetString \
(PyExc_RuntimeError, "PGA object is in status error"); \
} \
return r; \
} \
} while (0)
#define ERR_CHECK_X(ctx,x) do { \
if (!(x)) { \
SET_ERR(ctx); \
goto errout; \
} \
} while (0)
#define ERR_CHECK_X_OCCURRED(ctx) do { \
if (HAS_ERR(ctx)) { \
goto errout; \
} \
} while (0)
#define ERR_CHECK_RET(x) do { \
if (!(x)) { \
goto errout; \
} \
} while (0)
#define ERR_CHECK_VALUE_ERROR(x,e) do { \
if (!(x)) { \
PyErr_SetString (PyExc_ValueError, (e)); \
goto errout; \
} \
} while (0)
#define CHECK_VALUE(cond, errmsg) \
CHECK_VALUE_EXCEPTION ((cond), (errmsg), PyExc_ValueError, INIT_FAIL)
#define CHECK_VALUE_EXCEPTION(cond, errmsg, exc, ret) do { \
if (!(cond)) { \
PyErr_SetString ((exc), (errmsg)); \
return (ret); \
} \
} while (0)
#define CHECK_VALUE_AND_FREE(cond, errmsg, exc, tofree) do { \
if (!(cond)) { \
free ((tofree)); \
PyErr_SetString ((exc), (errmsg)); \
return INIT_FAIL; \
} \
} while (0)
#define ERR_RET(cond,ret) do { \
if (!(cond)) { \
return (ret); \
} \
} while (0)
#define ERR_DECREF_RET(cond, dec, ret) do { \
if (!(cond)) { \
Py_CLEAR (dec); \
return (ret); \
} \
} while (0)
#define ERR_DECREF_2_RET(cond, dec1, dec2, ret) do { \
if (!(cond)) { \
Py_CLEAR (dec1); \
Py_CLEAR (dec2); \
return (ret); \
} \
} while (0)
#define ERR_DECREF_3_RET(cond, dec1, dec2, dec3, ret) do { \
if (!(cond)) { \
Py_CLEAR (dec1); \
Py_CLEAR (dec2); \
Py_CLEAR (dec3); \
return (ret); \
} \
} while (0)
/*********************************
* Convenience functions in module
*********************************/
/* Visual C disable warning about unused variable "self" */
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable:4100)
#endif
static PyObject *das_dennis (PyObject *self, PyObject *args, PyObject *kw)
#ifdef _MSC_VER
#pragma warning(pop)
#endif
{
int i, j;
int dim, npart;
double scale = 1;
double *dir = NULL;
PyObject *direction = NULL;
PyObject *tuple = NULL;
PyObject *inner_tuple = NULL;
PyObject *ele = NULL;
void *result = NULL;
PyObject *res = NULL, *res2 = NULL;
int npoints;
static char *kwlist [] =
{ "dimension"
, "npartitions"
, "scale"
, "direction"
, NULL
};
if (!PyArg_ParseTupleAndKeywords
(args, kw, "ii|dO", kwlist, &dim, &npart, &scale, &direction)
)
{
return NULL;
}
ERR_CHECK_VALUE_ERROR (dim >= 1, "Dimension must be >= 1");
ERR_CHECK_VALUE_ERROR (npart >= 1, "npartitions must be >= 1");
if (direction != NULL) {
Py_ssize_t length;
ERR_CHECK_VALUE_ERROR \
( PySequence_Check (direction)
, "Expected sequence for direction parameter"
);
length = PySequence_Length (direction);
ERR_CHECK_VALUE_ERROR \
( length == dim
, "Direction must be sequence with length=dimension"
);
if ((dir = malloc (sizeof (double) * dim)) == NULL) {
return PyErr_NoMemory ();
}
for (i=0; i<length; i++) {
res = PySequence_GetItem (direction, i);
ERR_CHECK_RET (res != NULL);
res2 = PyNumber_Float (res);
ERR_CHECK_RET (res2 != NULL);
Py_CLEAR (res);
dir [i] = PyFloat_AsDouble (res2);
ERR_CHECK_RET (!PyErr_Occurred ());
Py_CLEAR (res2);
}
}
npoints = LIN_binom (dim + npart - 1, npart);
LIN_dasdennis (dim, npart, &result, 0, scale, dir);
tuple = PyTuple_New (npoints);
ERR_CHECK_RET (tuple != NULL);
PyTuple_SetItem (tuple, 0, ele);
for (i=0; i<npoints; i++) {
int r;
double (*points)[3] = (double (*)[3]) result;
inner_tuple = PyTuple_New (dim);
ERR_CHECK_RET (inner_tuple != NULL);
r = PyTuple_SetItem (tuple, i, inner_tuple);
assert (r == 0);
for (j=0; j<dim; j++) {
ele = Py_BuildValue ("d", points [i][j]);
ERR_CHECK_RET (ele != NULL);
r = PyTuple_SetItem (inner_tuple, j, ele);
assert (r == 0);
}
}
free (result);
return tuple;
errout:
if (dir != NULL) {
free (dir);
}
Py_CLEAR (tuple);
Py_CLEAR (res);
Py_CLEAR (res2);
return NULL;
}
/***********************
* Wrapped MPI functions
***********************/
/* These are needed whenever we want to perform *several* PGA
* optimization runs: In that case we need to do MPI_Init first (and
* finally an MPI_finit) because MPI_Init may be called only once.
* These are *module* methods (not PGA object methods)
*/
static PyObject *PGA_MPI_Init (PyObject *self, PyObject *args, PyObject *kw)
{
int argc;
int ret = 0;
char **c_argv = NULL;
PyObject *pyargv;
static char *kwlist [] = {"argv", NULL};
if (!PyArg_ParseTupleAndKeywords (args, kw, "O", kwlist, &pyargv)) {
return NULL;
}
c_argv = parse_argv (pyargv, &argc);
Py_DECREF (pyargv);
ret = MPI_Init (&argc, &c_argv);
return Py_BuildValue ("i", ret);
}
static PyObject *PGA_MPI_Abort (PyObject *self, PyObject *args, PyObject *kw)
{
int errorcode = 0;
int ret = 0;
static char *kwlist [] =
{ "errorcode"
, NULL
};
if (!PyArg_ParseTupleAndKeywords (args, kw, "i", kwlist, &errorcode)) {
return NULL;
}
ret = MPI_Abort (MPI_COMM_WORLD, errorcode);
return Py_BuildValue ("i", ret);
}
/* We don't care if someone calls this with arguments */
static PyObject *PGA_MPI_Finalize (PyObject *self, PyObject *args, PyObject *kw)
{
int ret = MPI_Finalize ();
return Py_BuildValue ("i", ret);
}
static PyMethodDef Module_Methods [] =
{ { "das_dennis", (PyCFunction)das_dennis, METH_VARARGS | METH_KEYWORDS
, "Return Das/Dennis points"
}
, { "MPI_Abort", (PyCFunction)PGA_MPI_Abort, METH_VARARGS | METH_KEYWORDS
, "Abort MPI"
}
, { "MPI_Finalize", (PyCFunction)PGA_MPI_Finalize, METH_VARARGS | METH_KEYWORDS
, "Finalize MPI"
}
, { "MPI_Init", (PyCFunction)PGA_MPI_Init, METH_VARARGS | METH_KEYWORDS
, "Initialize MPI"
}
, { NULL } /* EMPTY VALUE AS END-MARKER */
};
/***********************
* Constants (in Module)
***********************/
typedef struct
{
char *cd_name;
int cd_value;
} constdef_t;
/* These need to be kept sorted */
static constdef_t constdef [] =
{ {"PGA_CINIT_LOWER", PGA_CINIT_LOWER }
, {"PGA_CINIT_MIXED", PGA_CINIT_MIXED }
, {"PGA_CINIT_UPPER", PGA_CINIT_UPPER }
, {"PGA_CROSSOVER_EDGE", PGA_CROSSOVER_EDGE }
, {"PGA_CROSSOVER_ONEPT", PGA_CROSSOVER_ONEPT }
, {"PGA_CROSSOVER_SBX", PGA_CROSSOVER_SBX }
, {"PGA_CROSSOVER_TWOPT", PGA_CROSSOVER_TWOPT }
, {"PGA_CROSSOVER_UNIFORM", PGA_CROSSOVER_UNIFORM }
, {"PGA_DE_CROSSOVER_BIN", PGA_DE_CROSSOVER_BIN }
, {"PGA_DE_CROSSOVER_EXP", PGA_DE_CROSSOVER_EXP }
, {"PGA_DE_VARIANT_BEST", PGA_DE_VARIANT_BEST }
, {"PGA_DE_VARIANT_EITHER_OR", PGA_DE_VARIANT_EITHER_OR }
, {"PGA_DE_VARIANT_RAND", PGA_DE_VARIANT_RAND }
, {"PGA_FITNESSMIN_CMAX", PGA_FITNESSMIN_CMAX }
, {"PGA_FITNESSMIN_RECIPROCAL", PGA_FITNESSMIN_RECIPROCAL }
, {"PGA_FITNESS_NORMAL", PGA_FITNESS_NORMAL }
, {"PGA_FITNESS_RANKING", PGA_FITNESS_RANKING }
, {"PGA_FITNESS_RAW", PGA_FITNESS_RAW }
, {"PGA_MIX_MUTATE_AND_CROSS", PGA_MIX_MUTATE_AND_CROSS }
, {"PGA_MIX_MUTATE_ONLY", PGA_MIX_MUTATE_ONLY }
, {"PGA_MIX_MUTATE_OR_CROSS", PGA_MIX_MUTATE_OR_CROSS }
, {"PGA_MIX_TRADITIONAL", PGA_MIX_TRADITIONAL }
, {"PGA_MUTATION_CONSTANT", PGA_MUTATION_CONSTANT }
, {"PGA_MUTATION_DE", PGA_MUTATION_DE }
, {"PGA_MUTATION_GAUSSIAN", PGA_MUTATION_GAUSSIAN }
, {"PGA_MUTATION_PERMUTE", PGA_MUTATION_PERMUTE }
, {"PGA_MUTATION_POLY", PGA_MUTATION_POLY }
, {"PGA_MUTATION_RANGE", PGA_MUTATION_RANGE }
, {"PGA_MUTATION_UNIFORM", PGA_MUTATION_UNIFORM }
, {"PGA_NEWPOP", PGA_NEWPOP }
, {"PGA_OLDPOP", PGA_OLDPOP }
, {"PGA_POPREPL_BEST", PGA_POPREPL_BEST }
, {"PGA_POPREPL_NSGA_II", PGA_POPREPL_NSGA_II }
, {"PGA_POPREPL_NSGA_III", PGA_POPREPL_NSGA_III }
, {"PGA_POPREPL_PAIRWISE_BEST", PGA_POPREPL_PAIRWISE_BEST }
, {"PGA_POPREPL_RANDOM_NOREP", PGA_POPREPL_RANDOM_NOREP }
, {"PGA_POPREPL_RANDOM_REP", PGA_POPREPL_RANDOM_REP }
, {"PGA_POPREPL_RTR", PGA_POPREPL_RTR }
, {"PGA_REPORT_AVERAGE", PGA_REPORT_AVERAGE }
, {"PGA_REPORT_HAMMING", PGA_REPORT_HAMMING }
, {"PGA_REPORT_OFFLINE", PGA_REPORT_OFFLINE }
, {"PGA_REPORT_ONLINE", PGA_REPORT_ONLINE }
, {"PGA_REPORT_STRING", PGA_REPORT_STRING }
, {"PGA_REPORT_WORST", PGA_REPORT_WORST }
, {"PGA_SELECT_LINEAR", PGA_SELECT_LINEAR }
, {"PGA_SELECT_PROPORTIONAL", PGA_SELECT_PROPORTIONAL }
, {"PGA_SELECT_PTOURNAMENT", PGA_SELECT_PTOURNAMENT }
, {"PGA_SELECT_SUS", PGA_SELECT_SUS }
, {"PGA_SELECT_TOURNAMENT", PGA_SELECT_TOURNAMENT }
, {"PGA_SELECT_TRUNCATION", PGA_SELECT_TRUNCATION }
, {"PGA_STOP_MAXITER", PGA_STOP_MAXITER }
, {"PGA_STOP_NOCHANGE", PGA_STOP_NOCHANGE }
, {"PGA_STOP_TOOSIMILAR", PGA_STOP_TOOSIMILAR }
, {NULL, 0 }
};
int compare_constdef (const void *v1, const void *v2)
{
const constdef_t *p1 = v1, *p2 = v2;
return strcmp (p1->cd_name, p2->cd_name);
}
/***********************
* Exported Symbols
***********************/
/*
* Compute __all__, all exported symbols
* Return 0 on success, -1 on error
*/
static int all_symbols (PyObject *module)
{
PyObject *tuple = NULL;
PyObject *ele = NULL;
int nfun = sizeof (Module_Methods) / sizeof (PyMethodDef) - 1;
int nobj = 2; /* the PGA class and VERSION */
int ncon = sizeof (constdef) / sizeof (constdef_t) - 1;
int idx = 2;
int r = -1;
constdef_t *cd;
PyMethodDef *funp = NULL;
tuple = PyTuple_New (nfun + nobj + ncon);
ERR_RET (tuple != NULL, -1);
ele = Py_BuildValue ("s", "PGA");
ERR_CHECK_RET (ele != NULL);
r = PyTuple_SetItem (tuple, 0, ele);
ERR_CHECK_RET (r == 0);
ele = Py_BuildValue ("s", "VERSION");
ERR_CHECK_RET (ele != NULL);
r = PyTuple_SetItem (tuple, 1, ele);
ERR_CHECK_RET (r == 0);
/* Add constants */
for (cd = constdef; cd->cd_name; cd++) {
ele = Py_BuildValue ("s", cd->cd_name);
ERR_CHECK_RET (ele != NULL);
r = PyTuple_SetItem (tuple, idx++, ele);
ERR_CHECK_RET (r == 0);
}
for (funp = Module_Methods; funp->ml_name; funp++) {
ele = Py_BuildValue ("s", funp->ml_name);
ERR_CHECK_RET (ele != NULL);
r = PyTuple_SetItem (tuple, idx++, ele);
ERR_CHECK_RET (r == 0);
}
ele = NULL;
r = PyModule_AddObject (module, "__all__", tuple);
ERR_CHECK_RET (r == 0);
return 0;
errout:
Py_CLEAR (ele);
Py_CLEAR (tuple);
return -1;
}
/******************************************************
* Helpers for retriving ctx from self or self from ctx
******************************************************/
/*
* Retrieve the PGApack ctx from a PGA object
*/
static PGAContext *get_context (PyObject *self)
{
PyObject *PGA_ctx = NULL;
long long llctx;
PGA_ctx = PyObject_GetAttrString (self, "context");
if (!PGA_ctx) {
return NULL;
}
ERR_DECREF_RET (PyArg_Parse (PGA_ctx, "L", &llctx), PGA_ctx, NULL);
Py_DECREF (PGA_ctx);
/* If an error occurred */
if (*((int *)((PGAContext *)llctx)->ga.CustomData)) {
return NULL;
}
/* Visual C disable warning about size */
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable:4305)
#endif
return (PGAContext *)llctx;
#ifdef _MSC_VER
#pragma warning(pop)
#endif
}
/*
* Retrieve the FILE *fp from the PGA object
*/
static FILE *get_fp (PyObject *self, PyObject *file)
{
PyObject *pyfp = PyObject_GetAttrString (self, "_fp");
PyObject *fno = NULL;
long long lfp;
int fd_from_self = -1;
int fd_from_file = -1;
if (!pyfp) {
return NULL;
}
ERR_DECREF_RET (PyArg_Parse (pyfp, "L", &lfp), pyfp, NULL);
Py_DECREF (pyfp);
fd_from_self = fileno ((FILE *)lfp);
/* Now extract fd from file */
fno = PyObject_CallMethod (file, "fileno", "");
/* If an error happens here (should not) we return the fp anyway */
if (fno != NULL) {
if (PyArg_Parse (fno, "i", &fd_from_file)) {
ERR_DECREF_RET (fd_from_self == fd_from_file, fno, NULL);
}
Py_DECREF (fno);
}
/* Visual C disable warning about size */
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable:4305)
#endif
return (FILE *)lfp;
#ifdef _MSC_VER
#pragma warning(pop)
#endif
}
static PyObject *module_os = NULL;
/* Return a FILE created from dup'd fd from file, caller needs to close */
static FILE *get_fp_from_file (PyObject *file)
{
FILE *fp = NULL;
int fd = -1;
PyObject *fno = PyObject_CallMethod (file, "fileno", "");
PyObject *fdp = NULL;
if (fno == NULL) {
return NULL;
}
if (module_os == NULL) {
module_os = PyImport_ImportModule ("os");
if (!module_os) {
return NULL;
}
}
fdp = PyObject_CallMethod (module_os, "dup", "O", fno);
Py_DECREF (fno);
if (fdp == NULL) {
return NULL;
}
ERR_DECREF_RET (PyArg_Parse (fdp, "i", &fd), fdp, NULL);
Py_DECREF (fdp);
fp = fdopen (fd, "w");
CHECK_VALUE_EXCEPTION \
(fp != NULL, strerror (errno), PyExc_RuntimeError, NULL);
return fp;
}
/*
* Retrieve the PGA object via the PGApack ctx
*/
static PyObject *get_self (PGAContext *ctx)
{
PyObject *self, *PGA_ctx = Py_BuildValue ("L", (long long) ctx);
if (!PGA_ctx) {
return NULL;
}
self = PyObject_GetItem (contexts, PGA_ctx);
Py_DECREF (PGA_ctx);
return self;
}
/**************************************************
* PGApack callback functions
* These get a PGApack ctx and retrieve the object.
* Then they call into an object method
**************************************************/
/*
* Used if the calling object has an endofgen method.
* Otherwise use built-in default for the datatype.
* Called after each generation.
* Do something useful, display the population on a graphics output,
* let the user adjust the population, etc.
*/
static void endofgen (PGAContext *ctx)
{
PyObject *self = NULL, *r = NULL;
ERR_CHECK_X_OCCURRED (ctx);
self = get_self (ctx);
ERR_CHECK_X (ctx, self);
r = PyObject_CallMethod (self, "endofgen", "");
ERR_CHECK_X (ctx, r);
errout:
Py_CLEAR (r);
Py_CLEAR (self);
return;
}
/*
* Need a hash table of mapping ctx to PGA objects. Look up the
* appropriate object and call its PGA_evaluate
*/
static double evaluate (PGAContext *ctx, int p, int pop, double *aux)
{
double retval = 0.0;
PyObject *self = NULL, *res1 = NULL, *res2 = NULL, *res3 = NULL;
int r;
Py_ssize_t length, i;
ERR_CHECK_X_OCCURRED (ctx);
self = get_self (ctx);
ERR_CHECK_X (ctx, self);
res1 = PyObject_CallMethod (self, "evaluate", "ii", p, pop);
ERR_CHECK_X (ctx, res1);
if (PySequence_Check (res1)) {
length = PySequence_Length (res1);
if (length != ctx->ga.NumAuxEval + 1) {
char x [60];
sprintf
( x, "Invalid length %zd of evaluations, expect %d"
, length, ctx->ga.NumAuxEval + 1
);
PyErr_SetString (PyExc_ValueError, x);
SET_ERR (ctx);
goto errout;
}
res2 = PySequence_GetItem(res1, 0);
ERR_CHECK_X (ctx, res2);
res3 = PyNumber_Float (res2);
Py_CLEAR (res2);
ERR_CHECK_X (ctx, res3);
r = PyArg_Parse (res3, "d", &retval);
ERR_CHECK_X (ctx, r);
Py_CLEAR (res3);
for (i=1; i<length; i++) {
res2 = PySequence_GetItem (res1, i);
ERR_CHECK_X (ctx, res2);
res3 = PyNumber_Float (res2);
Py_CLEAR (res2);
ERR_CHECK_X (ctx, res3);
r = PyArg_Parse (res3, "d", aux + (i - 1));
ERR_CHECK_X (ctx, r);
Py_CLEAR (res3);
}
} else {
if (ctx->ga.NumAuxEval) {
char x [50];
sprintf (x, "Expected %d evaluations", ctx->ga.NumAuxEval + 1);
PyErr_SetString (PyExc_ValueError, x);
SET_ERR (ctx);
goto errout;
}
res2 = PyNumber_Float (res1);
ERR_CHECK_X (ctx, res2);
r = PyArg_Parse (res2, "d", &retval);
ERR_CHECK_X (ctx, r);
}
errout:
Py_CLEAR (self);
Py_CLEAR (res1);
Py_CLEAR (res2);
Py_CLEAR (res3);
return retval;
}
/*
* Hash function for duplicate checking
* This is used if we have user-defined datatypes
* The user datatype must be hashable (e.g. define a __hash__ method)
*/
static PGAHash build_hash (PGAContext *ctx, int p, int pop)
{
Py_hash_t hash = 0;
PyObject *self = NULL;
PGAIndividual *ind = NULL;
ERR_CHECK_X_OCCURRED (ctx);
self = get_self (ctx);
ERR_CHECK_X (ctx, self);
if (PyObject_HasAttrString (self, "hash")) {
int rr;
PyObject *r = PyObject_CallMethod (self, "hash", "ii", p, pop);
ERR_CHECK_X (ctx, r);
rr = PyArg_Parse (r, "L", &hash);
ERR_CHECK_X (ctx, rr);
hash = ((hash >> 32) ^ hash) & 0xFFFFFFFF;
return hash;
}
/* No custom hash method */
/* We checked before installing the user function if either a custom
* method is defined or we have user datatypes, so this assert
* should not trigger here.
*/
assert (ctx->ga.datatype == PGA_DATATYPE_USER);
ind = PGAGetIndividual (ctx, p, pop);
if (ind->chrom == NULL) {
PyErr_SetString (PyExc_ValueError, "This gene is not set");
goto errout;
}
hash = PyObject_Hash ((PyObject *)ind->chrom);
ERR_CHECK_X (ctx, hash != -1);
Py_CLEAR (self);
hash = ((hash >> 32) ^ hash) & 0xFFFFFFFF;
return (PGAHash)hash;
errout:
Py_CLEAR (self);
return 0;
}
/*
* Used if the calling object has a check_duplicate method.
* Otherwise use built-in default for the datatype.
* Perform duplicate checking, compare strings p1 and p2 to see if they
* are different. If they are, return non-zero, else return 0.
*/
static int check_duplicate (PGAContext *ctx, int p1, int pop1, int p2, int pop2)
{
PyObject *self = NULL, *r = NULL;
int rr, retval = 0;
ERR_CHECK_X_OCCURRED (ctx);
self = get_self (ctx);
ERR_CHECK_X (ctx, self);
r = PyObject_CallMethod
(self, "check_duplicate", "iiii", p1, pop1, p2, pop2);
ERR_CHECK_X (ctx, r);
rr = PyArg_Parse (r, "i", &retval);
ERR_CHECK_X (ctx, rr);
errout:
Py_CLEAR (r);
Py_CLEAR (self);
return !!retval;
}
/*
* Check stopping criteria, this is always active.
* User can set a stop_cond method to add stopping criteria.
* We perform the magic here that if during one of the callback
* functions (calling into python, e.g. evaluate) an error occurs, we
* check the error flag here and stop. This way we can return an error
* in one of the callback functions to python and raise the appropriate
* exception there.
*/
static int check_stop (PGAContext *ctx)
{
PyObject *self = NULL;
ERR_CHECK_OCCURRED (ctx, PGA_TRUE);
self = get_self (ctx);
ERR_CHECK (ctx, self, PGA_TRUE);
if (PyObject_HasAttrString (self, "stop_cond")) {
int retval = PGA_TRUE, rr;
PyObject *r = PyObject_CallMethod (self, "stop_cond", NULL);
ERR_CHECK_X (ctx, r);
rr = PyArg_Parse (r, "i", &retval);
ERR_CHECK_X (ctx, rr);
errout:
Py_CLEAR (r);
Py_CLEAR (self);
return !!retval;
}
Py_CLEAR (self);
return PGACheckStoppingConditions (ctx);
}
/*
* Used only for user defined data type.
* Copy the python object and update refcounts.
* We explicitly do *NOT* do a deepcopy!
* This is because the python implementation will in many cases allocate
* a new object anyway, so copying the to-be-overwritten object once
* doesn't make sense from a performance perspective.
*/
static void copystring (PGAContext *ctx, int p1, int pop1, int p2, int pop2)
{
PGAIndividual *src = PGAGetIndividual (ctx, p1, pop1);
PGAIndividual *dst = PGAGetIndividual (ctx, p2, pop2);
ERR_CHECK_X_OCCURRED (ctx);
ERR_CHECK_X (ctx, src->chrom);
if (src == dst) {
return;
}
if (dst->chrom != NULL) {
Py_DECREF (dst->chrom);
dst->chrom = NULL;
}
assert (src->chrom != NULL);
dst->chrom = src->chrom;
Py_INCREF (src->chrom);
errout:
return;
}
/*
* Used if the calling object has an initstring method.
* Otherwise use built-in default for the datatype.
* Note: In python this is also used when createstring requests
* initialization of a string.
*/
static void initstring (PGAContext *ctx, int p, int pop)
{
PyObject *self = NULL, *r = NULL;
ERR_CHECK_X_OCCURRED (ctx);
self = get_self (ctx);
ERR_CHECK_X (ctx, self);
r = PyObject_CallMethod (self, "initstring", "ii", p, pop);
ERR_CHECK_X (ctx, r);
errout:
Py_CLEAR (r);
Py_CLEAR (self);
return;
}
/*
* Used only for user defined data type.
* If the initflag is zero, we do no initialization and assert that the
* chromosome is a NULL pointer. Otherwise we call self.initstring.
*/
static void createstring (PGAContext *ctx, int p, int pop, int initflag)
{
PGAIndividual *ind = PGAGetIndividual (ctx, p, pop);
if (!initflag) {
assert (ind->chrom == NULL);
return;
}
initstring (ctx, p, pop);
}
/*
* Used if the calling object has a crossover method.
* Otherwise use built-in default for the datatype.
* Perform crossover from p1 and p2 into c1 and c2
*/
static void crossover
(PGAContext *ctx, int p1, int p2, int p_pop, int c1, int c2, int c_pop)
{
PyObject *self = NULL, *r = NULL;
ERR_CHECK_X_OCCURRED (ctx);
self = get_self (ctx);
ERR_CHECK_X (ctx, self);
r = PyObject_CallMethod
(self, "crossover", "iiiiii", p1, p2, p_pop, c1, c2, c_pop);
ERR_CHECK_X (ctx, r);
errout:
Py_CLEAR (r);
Py_CLEAR (self);
return;
}
/*
* Used if the calling object has a mutation method.
* Otherwise use built-in default for the datatype.
* Insert code to mutate Data.
* Remember to count the number of mutations that happen, and return
* that value!
*/
static int mutation (PGAContext *ctx, int p, int pop, double mr)
{
PyObject *self = NULL, *r = NULL;
int retval = 0, rr;
ERR_CHECK_X_OCCURRED (ctx);
self = get_self (ctx);
ERR_CHECK_X (ctx, self);
r = PyObject_CallMethod (self, "mutation", "iid", p, pop, mr);
ERR_CHECK_X (ctx, r);
rr = PyArg_Parse (r, "i", &retval);
ERR_CHECK_X (ctx, rr);
errout:
Py_CLEAR (r);
Py_CLEAR (self);
return retval;
}
/*
* Used if the calling object has a gene_distance method.
* Otherwise use built-in default for the datatype.
* Insert code to compute genetic difference of two individuals.
*/
static double gene_distance
(PGAContext *ctx, int p1, int pop1, int p2, int pop2)
{
PyObject *self = NULL, *r = NULL;
int rr;
double retval = 0.0;
ERR_CHECK_X_OCCURRED (ctx);
self = get_self (ctx);
ERR_CHECK_X (ctx, self);
r = PyObject_CallMethod
(self, "gene_distance", "iiii", p1, pop1, p2, pop2);
ERR_CHECK_X (ctx, r);
rr = PyArg_Parse (r, "d", &retval);
ERR_CHECK_X (ctx, rr);
errout:
Py_CLEAR (r);
Py_CLEAR (self);
return retval;
}
/*
* Used if the calling object has a pre_eval method.
*/
static void pre_eval (PGAContext *ctx, int pop)
{
PyObject *self = NULL, *r = NULL;
ERR_CHECK_X_OCCURRED (ctx);
self = get_self (ctx);
ERR_CHECK_X (ctx, self);
r = PyObject_CallMethod (self, "pre_eval", "i", pop);
ERR_CHECK_X (ctx, r);
errout:
Py_CLEAR (r);
Py_CLEAR (self);
return;
}
static PyObject *get_file_from_fp (PGAContext *ctx, PyObject *self, FILE *fp)
{
int retval = -1;
PyObject *file = NULL;
PyObject *pyfp = NULL;
int fd = fileno (fp);
/* Should never happen unles fp is not a valid stream */
ERR_CHECK_ERRNO (ctx, fd >= 0, NULL);
#if IS_PY3
file = PyFile_FromFd (fd, "", "w", -1, "utf-8", NULL, NULL, 0);
#else
{
FILE *fp2 = fdopen (fd, "w");
ERR_CHECK_ERRNO (ctx, fp2 != NULL, NULL);
file = PyFile_FromFile (fp2, "<PGA_file>", "w", NULL);
}
#endif
ERR_CHECK (ctx, file, NULL);
pyfp = Py_BuildValue ("L", (long long) fp);
ERR_CHECK (ctx, pyfp, NULL);
retval = PyObject_SetAttrString (self, "_fp", pyfp);
ERR_CHECK (ctx, retval >= 0, NULL);
return file;
}
/*
* Low-level gene print function
* Note: We do a hack here and store both, the original FILE *fp and the
* generated python file object into member variables _fp and _file,
* respectively. These are reused in the print_gene function (and the
* called print_string python method). This avoids garbage collection
* and/or memory leak issues with files and FILE * variables. There is
* no way to temporarily create a FILE * and avoiding the unterlying
* file descriptor being closed in C. The previous version used dup2 to
* duplicate the file descriptor but this is non-portable. The issue is
* further complicated by the fact that Python3 (as opposed to Python2)
* uses file descriptors not FILE* for generating a file object.
*/
static void print_gene (PGAContext *ctx, FILE *fp, int p, int pop)
{
PyObject *self = NULL, *file = NULL, *r = NULL;
int retval = -1;
ERR_CHECK_X_OCCURRED (ctx);
self = get_self (ctx);
ERR_CHECK_X (ctx, self);
fflush (fp);
file = get_file_from_fp (ctx, self, fp);
ERR_CHECK_X (ctx, file);
r = PyObject_CallMethod (self, "print_string", "Oii", file, p, pop);
ERR_CHECK_X (ctx, r);
Py_CLEAR (r);
/* Flush file */
r = PyObject_CallMethod (file, "flush", "");
ERR_CHECK_X (ctx, r);
Py_CLEAR (r);
/* File is set to not close unterlying fd but close anyway */
r = PyObject_CallMethod (file, "close", "");
ERR_CHECK_X (ctx, r);
Py_CLEAR (r);
/* Now remove self._fp */
retval = PyObject_DelAttrString (self, "_fp");
ERR_CHECK_X (ctx, retval == 0);
errout:
Py_CLEAR (file);
Py_CLEAR (r);
Py_CLEAR (self);
}
/******************
* Serialization
******************/
static void *serialize_object = NULL;
static void *serialize_inner = NULL;
static PyObject *pickle_module = NULL;
/*
* Used only for user defined data type.
* This implementation relies on a serialization to be immediately used
* and freed afterwards.
*/
static size_t serialize (PGAContext *ctx, int p, int pop, void **ser)
{
PGAIndividual *ind = PGAGetIndividual (ctx, p, pop);
Py_ssize_t serial_size = 0;
ERR_CHECK_X_OCCURRED (ctx);
ERR_CHECK_X (ctx, ind->chrom != NULL);
ERR_CHECK_X (ctx, serialize_object == NULL);
ERR_CHECK_X (ctx, serialize_inner == NULL);
if (pickle_module == NULL) {
pickle_module = PyImport_ImportModule ("pickle");
}