forked from tskit-dev/msprime
-
Notifications
You must be signed in to change notification settings - Fork 2
/
_msprimemodule.c
9082 lines (8375 loc) · 264 KB
/
_msprimemodule.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) 2014-2018 University of Oxford
**
** This file is part of msprime.
**
** msprime 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 3 of the License, or
** (at your option) any later version.
**
** msprime 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 msprime. If not, see <http://www.gnu.org/licenses/>.
*/
#define PY_SSIZE_T_CLEAN
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <Python.h>
#include <structmember.h>
#ifdef HAVE_NUMPY
#include <numpy/arrayobject.h>
#endif
#include <float.h>
#include <hdf5.h>
#include <gsl/gsl_version.h>
#include <gsl/gsl_math.h>
#include "msprime.h"
#if PY_MAJOR_VERSION >= 3
#define IS_PY3K
#endif
#define MODULE_DOC \
"Low level interface for msprime"
#define SET_COLS 0
#define APPEND_COLS 1
static PyObject *MsprimeInputError;
static PyObject *MsprimeLibraryError;
typedef struct {
PyObject_HEAD
unsigned long seed;
gsl_rng* rng;
} RandomGenerator;
typedef struct {
PyObject_HEAD
mutgen_t *mutgen;
RandomGenerator *random_generator;
} MutationGenerator;
/* The XTable classes each have 'lock' attribute, which is used to
* raise an error if a Python thread attempts to access a table
* while another Python thread is operating on it. Because tables
* allocate memory dynamically, we cannot gaurantee safety otherwise.
* The locks are set before the GIL is released and unset afterwards.
* Because C code executed here represents atomic Python operations
* (while the GIL is held), this should be safe */
typedef struct {
PyObject_HEAD
bool locked;
node_table_t *node_table;
} NodeTable;
typedef struct {
PyObject_HEAD
bool locked;
edge_table_t *edge_table;
} EdgeTable;
typedef struct {
PyObject_HEAD
bool locked;
site_table_t *site_table;
} SiteTable;
typedef struct {
PyObject_HEAD
bool locked;
mutation_table_t *mutation_table;
} MutationTable;
typedef struct {
PyObject_HEAD
bool locked;
migration_table_t *migration_table;
} MigrationTable;
typedef struct {
PyObject_HEAD
bool locked;
provenance_table_t *provenance_table;
} ProvenanceTable;
typedef struct {
PyObject_HEAD
msp_t *sim;
RandomGenerator *random_generator;
} Simulator;
typedef struct {
PyObject_HEAD
recomb_map_t *recomb_map;
} RecombinationMap;
typedef struct {
PyObject_HEAD
tree_sequence_t *tree_sequence;
} TreeSequence;
typedef struct {
PyObject_HEAD
TreeSequence *tree_sequence;
sparse_tree_t *sparse_tree;
} SparseTree;
typedef struct {
PyObject_HEAD
SparseTree *sparse_tree;
int first;
} SparseTreeIterator;
typedef struct {
PyObject_HEAD
TreeSequence *tree_sequence;
tree_diff_iterator_t *tree_diff_iterator;
} TreeDiffIterator;
typedef struct {
PyObject_HEAD
SparseTree *sparse_tree;
node_list_t *head;
node_list_t *tail;
node_list_t *next;
} SampleListIterator;
typedef struct {
PyObject_HEAD
TreeSequence *tree_sequence;
vcf_converter_t *vcf_converter;
} VcfConverter;
typedef struct {
PyObject_HEAD
TreeSequence *tree_sequence;
hapgen_t *haplotype_generator;
} HaplotypeGenerator;
typedef struct {
PyObject_HEAD
TreeSequence *tree_sequence;
vargen_t *variant_generator;
} VariantGenerator;
typedef struct {
PyObject_HEAD
TreeSequence *tree_sequence;
ld_calc_t *ld_calc;
} LdCalculator;
static void
handle_library_error(int err)
{
if (err == MSP_ERR_OUT_OF_BOUNDS) {
PyErr_SetString(PyExc_IndexError, msp_strerror(err));
} else{
PyErr_SetString(MsprimeLibraryError, msp_strerror(err));
}
}
static void
handle_input_error(int err)
{
PyErr_SetString(MsprimeInputError, msp_strerror(err));
}
static int
parse_sample_ids(PyObject *py_samples, tree_sequence_t *ts, size_t *num_samples,
node_id_t **samples)
{
int ret = -1;
PyObject *item;
size_t j;
Py_ssize_t num_samples_local;
node_id_t *samples_local = NULL;
num_samples_local = PyList_Size(py_samples);
if (num_samples_local < 2) {
PyErr_SetString(PyExc_ValueError, "Must provide at least 2 samples");
goto out;
}
samples_local = PyMem_Malloc(num_samples_local * sizeof(node_id_t));
if (samples_local == NULL) {
PyErr_NoMemory();
goto out;
}
for (j = 0; j < num_samples_local; j++) {
item = PyList_GetItem(py_samples, j);
if (!PyNumber_Check(item)) {
PyErr_SetString(PyExc_TypeError, "sample id must be a number");
goto out;
}
samples_local[j] = (node_id_t) PyLong_AsLong(item);
if (samples_local[j] < 0 || samples_local[j] >= tree_sequence_get_num_nodes(ts)) {
PyErr_SetString(PyExc_ValueError, "node ID out of bounds");
goto out;
}
if (! tree_sequence_is_sample(ts, samples_local[j])) {
PyErr_SetString(PyExc_ValueError, "Specified node is not a sample");
goto out;
}
}
*num_samples = (size_t) num_samples_local;
*samples = samples_local;
samples_local = NULL;
ret = 0;
out:
if (samples_local != NULL) {
PyMem_Free(samples_local);
}
return ret;
}
static int
parse_samples(PyObject *py_samples, Py_ssize_t *num_samples, sample_t **samples)
{
int ret = -1;
long tmp_long;
Py_ssize_t j, n;
PyObject *sample, *value;
sample_t *ret_samples = NULL;
n = PyList_Size(py_samples);
ret_samples = PyMem_Malloc(n * sizeof(sample_t));
if (ret_samples == NULL) {
PyErr_NoMemory();
goto out;
}
for (j = 0; j < n; j++) {
sample = PyList_GetItem(py_samples, j);
if (!PyTuple_Check(sample)) {
PyErr_SetString(PyExc_TypeError, "not a tuple");
goto out;
}
if (PyTuple_Size(sample) != 2) {
PyErr_SetString(PyExc_ValueError,
"sample must be (population,time) tuple");
goto out;
}
value = PyTuple_GetItem(sample, 0);
if (!PyNumber_Check(value)) {
PyErr_Format(PyExc_TypeError, "'population' is not number");
goto out;
}
tmp_long = PyLong_AsLong(value);
if (tmp_long < 0) {
PyErr_SetString(PyExc_ValueError, "negative population IDs not valid");
goto out;
}
ret_samples[j].population_id = (population_id_t) tmp_long;
value = PyTuple_GetItem(sample, 1);
if (!PyNumber_Check(value)) {
PyErr_Format(PyExc_TypeError, "'time' is not number");
goto out;
}
ret_samples[j].time = PyFloat_AsDouble(value);
if (ret_samples[j].time < 0) {
PyErr_SetString(PyExc_ValueError, "negative times not valid");
goto out;
}
}
*samples = ret_samples;
*num_samples = n;
ret = 0;
ret_samples = NULL;
out:
if (ret_samples != NULL) {
PyMem_Free(ret_samples);
}
return ret;
}
/*
* Retrieves the PyObject* corresponding the specified key in the
* specified dictionary.
*/
static PyObject *
get_dict_value(PyObject *dict, const char *key_str)
{
PyObject *ret = NULL;
PyObject *key = Py_BuildValue("s", key_str);
if (key == NULL) {
goto out;
}
if (!PyDict_Contains(dict, key)) {
PyErr_Format(PyExc_ValueError, "'%s' not specified", key_str);
goto out;
}
ret = PyDict_GetItem(dict, key);
assert(ret != NULL);
out:
Py_DECREF(key);
return ret;
}
/*
* Retrieves a number value with the specified key from the specified
* dictionary.
*/
static PyObject *
get_dict_number(PyObject *dict, const char *key_str)
{
PyObject *ret = NULL;
PyObject *value;
value = get_dict_value(dict, key_str);
if (value == NULL) {
goto out;
}
if (!PyNumber_Check(value)) {
PyErr_Format(PyExc_TypeError, "'%s' is not number", key_str);
goto out;
}
ret = value;
out:
return ret;
}
static PyObject *
convert_integer_list(size_t *list, size_t size)
{
PyObject *ret = NULL;
PyObject *l = NULL;
PyObject *py_int = NULL;
size_t j;
l = PyList_New(size);
if (l == NULL) {
goto out;
}
for (j = 0; j < size; j++) {
py_int = Py_BuildValue("n", (Py_ssize_t) list[j]);
if (py_int == NULL) {
Py_DECREF(l);
goto out;
}
PyList_SET_ITEM(l, j, py_int);
}
ret = l;
out:
return ret;
}
static PyObject *
convert_node_id_list(node_id_t *children, size_t num_children)
{
PyObject *ret = NULL;
PyObject *t;
PyObject *py_int;
size_t j;
t = PyTuple_New(num_children);
if (t == NULL) {
goto out;
}
for (j = 0; j < num_children; j++) {
py_int = Py_BuildValue("i", (int) children[j]);
if (py_int == NULL) {
Py_DECREF(children);
goto out;
}
PyTuple_SET_ITEM(t, j, py_int);
}
ret = t;
out:
return ret;
}
static PyObject *
convert_float_list(double *list, size_t size)
{
PyObject *ret = NULL;
PyObject *l = NULL;
PyObject *py_float = NULL;
size_t j;
l = PyList_New(size);
if (l == NULL) {
goto out;
}
for (j = 0; j < size; j++) {
py_float = Py_BuildValue("d", list[j]);
if (py_float == NULL) {
Py_DECREF(l);
goto out;
}
PyList_SET_ITEM(l, j, py_float);
}
ret = l;
out:
return ret;
}
static PyObject *
make_metadata(const char *metadata, Py_ssize_t length)
{
const char *m = metadata == NULL? "": metadata;
return PyBytes_FromStringAndSize(m, length);
}
static PyObject *
make_mutation(mutation_t *mutation)
{
PyObject *ret = NULL;
PyObject* metadata = NULL;
metadata = make_metadata(mutation->metadata, (Py_ssize_t) mutation->metadata_length);
if (metadata == NULL) {
goto out;
}
ret = Py_BuildValue("iis#iO", mutation->site, mutation->node, mutation->derived_state,
(Py_ssize_t) mutation->derived_state_length, mutation->parent,
metadata);
out:
Py_XDECREF(metadata);
return ret;
}
static PyObject *
make_mutation_id_list(mutation_t *mutations, size_t length)
{
PyObject *ret = NULL;
PyObject *t;
PyObject *item;
size_t j;
t = PyTuple_New(length);
if (t == NULL) {
goto out;
}
for (j = 0; j < length; j++) {
item = Py_BuildValue("i", mutations[j].id);
if (item == NULL) {
Py_DECREF(t);
goto out;
}
PyTuple_SET_ITEM(t, j, item);
}
ret = t;
out:
return ret;
}
static PyObject *
make_provenance(provenance_t *provenance)
{
PyObject *ret = NULL;
ret = Py_BuildValue("s#s#",
provenance->timestamp, (Py_ssize_t) provenance->timestamp_length,
provenance->record, (Py_ssize_t) provenance->record_length);
return ret;
}
static PyObject *
make_node(node_t *r)
{
PyObject *ret = NULL;
PyObject* metadata = make_metadata(r->metadata, (Py_ssize_t) r->metadata_length);
if (metadata == NULL) {
goto out;
}
ret = Py_BuildValue("IdiO",
(unsigned int) r->flags, r->time, (int) r->population, metadata);
out:
Py_XDECREF(metadata);
return ret;
}
static PyObject *
make_edge(edge_t *edge)
{
return Py_BuildValue("ddii",
edge->left, edge->right, (int) edge->parent, (int) edge->child);
}
static PyObject *
make_migration(migration_t *r)
{
int source = r->source == MSP_NULL_POPULATION_ID ? -1: r->source;
int dest = r->dest == MSP_NULL_POPULATION_ID ? -1: r->dest;
PyObject *ret = NULL;
ret = Py_BuildValue("ddiiid",
r->left, r->right, (int) r->node, source, dest, r->time);
return ret;
}
static PyObject *
make_site(site_t *site)
{
PyObject *ret = NULL;
PyObject *mutations = NULL;
PyObject* metadata = NULL;
metadata = make_metadata(site->metadata, (Py_ssize_t) site->metadata_length);
if (metadata == NULL) {
goto out;
}
mutations = make_mutation_id_list(site->mutations, site->mutations_length);
if (mutations == NULL) {
goto out;
}
/* TODO should reorder this tuple, as it's not very logical. */
ret = Py_BuildValue("ds#OnO", site->position, site->ancestral_state,
(Py_ssize_t) site->ancestral_state_length, mutations,
(Py_ssize_t) site->id, metadata);
out:
Py_XDECREF(mutations);
Py_XDECREF(metadata);
return ret;
}
#ifdef HAVE_NUMPY
static PyObject *
make_alleles(variant_t *variant)
{
PyObject *ret = NULL;
PyObject *item, *t;
size_t j;
t = PyTuple_New(variant->num_alleles);
if (t == NULL) {
goto out;
}
for (j = 0; j < variant->num_alleles; j++) {
item = Py_BuildValue("s#", variant->alleles[j], variant->allele_lengths[j]);
if (item == NULL) {
Py_DECREF(t);
goto out;
}
PyTuple_SET_ITEM(t, j, item);
}
ret = t;
out:
return ret;
}
static PyObject *
make_variant(variant_t *variant, size_t num_samples)
{
PyObject *ret = NULL;
npy_intp dims = num_samples;
PyObject *alleles = make_alleles(variant);
PyArrayObject *genotypes = (PyArrayObject *) PyArray_SimpleNew(1, &dims, NPY_UINT8);
/* TODO update this to account for 16 bit variants when we provide the
* high-level interface. */
if (genotypes == NULL || alleles == NULL) {
goto out;
}
memcpy(PyArray_DATA(genotypes), variant->genotypes.u8, num_samples * sizeof(uint8_t));
ret = Py_BuildValue("iOO", variant->site->id, genotypes, alleles);
out:
Py_XDECREF(genotypes);
Py_XDECREF(alleles);
return ret;
}
#endif
static PyObject *
convert_sites(site_t *sites, size_t num_sites)
{
PyObject *ret = NULL;
PyObject *l = NULL;
PyObject *py_site = NULL;
size_t j;
l = PyList_New(num_sites);
if (l == NULL) {
goto out;
}
for (j = 0; j < num_sites; j++) {
py_site = make_site(&sites[j]);
if (py_site == NULL) {
Py_DECREF(l);
goto out;
}
PyList_SET_ITEM(l, j, py_site);
}
ret = l;
out:
return ret;
}
/*===================================================================
* RandomGenerator
*===================================================================
*/
static int
RandomGenerator_check_state(RandomGenerator *self)
{
int ret = 0;
if (self->rng == NULL) {
PyErr_SetString(PyExc_SystemError, "RandomGenerator not initialised");
ret = -1;
}
return ret;
}
static void
RandomGenerator_dealloc(RandomGenerator* self)
{
if (self->rng != NULL) {
gsl_rng_free(self->rng);
self->rng = NULL;
}
Py_TYPE(self)->tp_free((PyObject*)self);
}
static int
RandomGenerator_init(RandomGenerator *self, PyObject *args, PyObject *kwds)
{
int ret = -1;
static char *kwlist[] = {"seed", NULL};
unsigned long long seed = 0;
self->rng = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "K", kwlist, &seed)) {
goto out;
}
if (seed == 0 || seed >= (1ULL<<32)) {
PyErr_Format(PyExc_ValueError,
"seeds must be greater than 0 and less than 2^32");
goto out;
}
self->seed = seed;
self->rng = gsl_rng_alloc(gsl_rng_default);
gsl_rng_set(self->rng, self->seed);
ret = 0;
out:
return ret;
}
static PyObject *
RandomGenerator_get_seed(RandomGenerator *self)
{
PyObject *ret = NULL;
if (RandomGenerator_check_state(self) != 0) {
goto out;
}
ret = Py_BuildValue("k", self->seed);
out:
return ret;
}
static PyMemberDef RandomGenerator_members[] = {
{NULL} /* Sentinel */
};
static PyMethodDef RandomGenerator_methods[] = {
{"get_seed", (PyCFunction) RandomGenerator_get_seed,
METH_NOARGS, "Returns the random seed for this generator."},
{NULL} /* Sentinel */
};
static PyTypeObject RandomGeneratorType = {
PyVarObject_HEAD_INIT(NULL, 0)
"_msprime.RandomGenerator", /* tp_name */
sizeof(RandomGenerator), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)RandomGenerator_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
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 */
"RandomGenerator objects", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
RandomGenerator_methods, /* tp_methods */
RandomGenerator_members, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)RandomGenerator_init, /* tp_init */
};
/*===================================================================
* General table code.
*===================================================================
*/
#ifdef HAVE_NUMPY
static PyObject *
table_get_column_array(size_t num_rows, void *data, int npy_type,
size_t element_size)
{
PyObject *ret = NULL;
PyArrayObject *array;
npy_intp dims = (npy_intp) num_rows;
array = (PyArrayObject *) PyArray_EMPTY(1, &dims, npy_type, 0);
if (array == NULL) {
goto out;
}
memcpy(PyArray_DATA(array), data, num_rows * element_size);
ret = (PyObject *) array;
out:
return ret;
}
static PyArrayObject *
table_read_column_array(PyObject *input, int npy_type, size_t *num_rows, bool check_num_rows)
{
PyArrayObject *ret = NULL;
PyArrayObject *array = NULL;
npy_intp *shape;
array = (PyArrayObject *) PyArray_FROM_OTF(input, npy_type, NPY_ARRAY_IN_ARRAY);
if (array == NULL) {
goto out;
}
if (PyArray_NDIM(array) != 1) {
PyErr_SetString(PyExc_ValueError, "Dim != 1");
goto out;
}
shape = PyArray_DIMS(array);
if (check_num_rows) {
if (*num_rows != shape[0]) {
PyErr_SetString(PyExc_ValueError, "Input array dimensions must be equal.");
goto out;
}
} else {
*num_rows = shape[0];
}
ret = array;
out:
if (ret == NULL) {
Py_XDECREF(array);
}
return ret;
}
static PyArrayObject *
table_read_offset_array(PyObject *input, size_t *num_rows, size_t length, bool check_num_rows)
{
PyArrayObject *ret = NULL;
PyArrayObject *array = NULL;
npy_intp *shape;
array = (PyArrayObject *) PyArray_FROM_OTF(input, NPY_UINT32, NPY_ARRAY_IN_ARRAY);
if (array == NULL) {
goto out;
}
if (PyArray_NDIM(array) != 1) {
PyErr_SetString(PyExc_ValueError, "Dim != 1");
goto out;
}
shape = PyArray_DIMS(array);
if (! check_num_rows) {
*num_rows = shape[0];
if (*num_rows == 0) {
PyErr_SetString(PyExc_ValueError,
"Offset arrays must have at least one element");
goto out;
}
*num_rows -= 1;
}
if (shape[0] != *num_rows + 1) {
PyErr_SetString(PyExc_ValueError, "offset columns must have n + 1 rows.");
goto out;
}
ret = array;
out:
if (ret == NULL) {
Py_XDECREF(array);
}
return ret;
}
#endif
/*===================================================================
* NodeTable
*===================================================================
*/
static int
NodeTable_check_state(NodeTable *self)
{
int ret = -1;
if (self->node_table == NULL) {
PyErr_SetString(PyExc_SystemError, "NodeTable not initialised");
goto out;
}
if (self->locked) {
PyErr_SetString(PyExc_RuntimeError, "NodeTable in use by other thread.");
goto out;
}
ret = 0;
out:
return ret;
}
static void
NodeTable_dealloc(NodeTable* self)
{
if (self->node_table != NULL) {
node_table_free(self->node_table);
PyMem_Free(self->node_table);
self->node_table = NULL;
}
Py_TYPE(self)->tp_free((PyObject*)self);
}
static int
NodeTable_init(NodeTable *self, PyObject *args, PyObject *kwds)
{
int ret = -1;
int err;
static char *kwlist[] = {"max_rows_increment", NULL};
Py_ssize_t max_rows_increment = 0;
Py_ssize_t max_metadata_length_increment = 0;
self->node_table = NULL;
self->locked = false;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|n", kwlist,
&max_rows_increment)) {
goto out;
}
if (max_rows_increment < 0) {
PyErr_SetString(PyExc_ValueError, "max_rows_increment must be positive");
goto out;
}
self->node_table = PyMem_Malloc(sizeof(node_table_t));
if (self->node_table == NULL) {
PyErr_NoMemory();
goto out;
}
err = node_table_alloc(self->node_table, (size_t) max_rows_increment,
(size_t) max_metadata_length_increment);
if (err != 0) {
handle_library_error(err);
goto out;
}
ret = 0;
out:
return ret;
}
static PyObject *
NodeTable_add_row(NodeTable *self, PyObject *args, PyObject *kwds)
{
PyObject *ret = NULL;
int err;
unsigned int flags = 0;
double time = 0;
int population = -1;
PyObject *py_metadata = Py_None;
char *metadata = "";
Py_ssize_t metadata_length = 0;
static char *kwlist[] = {"flags", "time", "population", "metadata", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|idiO", kwlist,
&flags, &time, &population, &py_metadata)) {
goto out;
}
if (NodeTable_check_state(self) != 0) {
goto out;
}
if (py_metadata != Py_None) {
if (PyBytes_AsStringAndSize(py_metadata, &metadata, &metadata_length) < 0) {
goto out;
}
}
err = node_table_add_row(self->node_table, (uint32_t) flags, time,
(population_id_t) population, metadata, metadata_length);
if (err < 0) {
handle_library_error(err);
goto out;
}
ret = Py_BuildValue("i", err);
out:
return ret;
}
static PyObject *
NodeTable_get_row(NodeTable *self, PyObject *args)
{
PyObject *ret = NULL;
Py_ssize_t num_rows, row_id;
node_t node;
if (NodeTable_check_state(self) != 0) {
goto out;
}
if (!PyArg_ParseTuple(args, "n", &row_id)) {
goto out;
}
num_rows = (Py_ssize_t) self->node_table->num_rows;
if (row_id < 0 || row_id >= num_rows) {
PyErr_SetString(PyExc_IndexError, "row index out of bounds");
goto out;
}
node.time = self->node_table->time[row_id];
node.flags = self->node_table->flags[row_id];
node.population = self->node_table->population[row_id];
node.metadata = self->node_table->metadata
+ self->node_table->metadata_offset[row_id];
node.metadata_length = self->node_table->metadata_offset[row_id + 1]
- self->node_table->metadata_offset[row_id];
ret = make_node(&node);
out:
return ret;
}
#ifdef HAVE_NUMPY
static PyObject *
NodeTable_set_or_append_columns(NodeTable *self, PyObject *args, PyObject *kwds,
int method)
{
PyObject *ret = NULL;
int err;
size_t num_rows, metadata_length;
char *metadata_data = NULL;
uint32_t *metadata_offset_data = NULL;
void *population_data = NULL;
PyObject *time_input = NULL;
PyArrayObject *time_array = NULL;
PyObject *flags_input = NULL;
PyArrayObject *flags_array = NULL;
PyObject *population_input = Py_None;
PyArrayObject *population_array = NULL;
PyObject *metadata_input = Py_None;
PyArrayObject *metadata_array = NULL;
PyObject *metadata_offset_input = Py_None;
PyArrayObject *metadata_offset_array = NULL;
static char *kwlist[] = {"flags", "time", "population", "metadata", "metadata_offset", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|OOO", kwlist,
&flags_input, &time_input, &population_input, &metadata_input,
&metadata_offset_input)) {
goto out;
}
if (NodeTable_check_state(self) != 0) {
goto out;
}
flags_array = table_read_column_array(flags_input, NPY_UINT32, &num_rows, false);
if (flags_array == NULL) {
goto out;
}
time_array = table_read_column_array(time_input, NPY_FLOAT64, &num_rows, true);
if (time_array == NULL) {
goto out;
}
if (population_input != Py_None) {
population_array = table_read_column_array(population_input, NPY_INT32,
&num_rows, true);
if (population_array == NULL) {
goto out;
}
population_data = PyArray_DATA(population_array);