-
Notifications
You must be signed in to change notification settings - Fork 37
/
niomodule.c
7863 lines (7022 loc) · 213 KB
/
niomodule.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
/*******************************************************
* $Id: niomodule.c 16535 2016-06-17 23:24:19Z dbrown $
*******************************************************/
/*
* Objects representing NIO files and variables.
*
* David I. Brown
* Adapted from netcdfmodule.c which was
* Written by Konrad Hinsen
* last revision: 1998-3-14
*/
#ifndef PYNIO
#define PYNIO
#endif
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include "netcdf.h"
#include "Python.h"
#include "structmember.h"
#include "nio.h"
#include <numpy/arrayobject.h>
#include <sys/stat.h>
#include <unistd.h>
#include <limits.h>
/* Py_ssize_t for old Pythons */
/* This code is as recommended by: */
/* http://www.python.org/dev/peps/pep-0353/#conversion-guidelines */
#if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN)
typedef int Py_ssize_t;
#define PY_SSIZE_T_MAX INT_MAX
#define PY_SSIZE_T_MIN INT_MIN
#endif
#define _NIO_MODULE
#include "niomodule.h"
static PyObject* get_NioError(void);
static PyObject* get_NioFileType(void);
static PyObject* get_NioVariableType(void);
static PyObject* get_Niomodule(void);
static char* get_errbuf(void);
/* Converts unicode, bytes, or str to UTF8 unicode object.
* The ob argument can be unicode, bytes, or str;
*
* A new reference will always be returned.
* */
static PyObject* pystr_to_utf8(PyObject *ob) {
PyObject *bytes, *result;
int del_bytes = 0;
#if PY_MAJOR_VERSION >= 3
Py_ssize_t bytelen;
char *bytedata = NULL;
if (PyUnicode_Check(ob)) {
bytes = PyUnicode_AsUTF8String(ob);
del_bytes = 1;
}
else if (PyBytes_Check(ob)) {
bytes = ob;
del_bytes = 0;
} else {
del_bytes = 0;
PyErr_SetString(PyExc_ValueError, "argument is not a string type");
return NULL;
}
if (bytes) {
bytelen = PyBytes_Size(bytes);
bytedata = PyBytes_AsString(bytes);
result = PyUnicode_DecodeUTF8(bytedata, bytelen, "strict");
} else {
PyErr_SetString(PyExc_MemoryError, "creation of bytes failed");
return NULL;
}
#else
del_bytes = 0;
if (PyUnicode_Check(ob)) {
bytes = PyUnicode_AsUTF8String(ob);
} else if (PyString_Check(ob)) {
/* Make a copy of the string so that a new reference is returned */
bytes = PyString_FromString(PyString_AsString(ob));
} else {
PyErr_SetString(PyExc_ValueError, "argument is not a string type");
return NULL;
}
if (bytes) {
result = bytes;
} else {
PyErr_SetString(PyExc_MemoryError, "creation of bytes failed");
return NULL;
}
#endif
if (del_bytes) {
Py_XDECREF(bytes);
}
return result;
}
/* This will convert a Unicode/PyString to a UTF8 char* string.
*
* The resulting string must be free'd by the user.
*/
static char* as_utf8_char_and_size(PyObject *ob, Py_ssize_t *size) {
char *result;
char *tempstr;
Py_ssize_t local_size;
PyObject *pystr = NULL;
#if PY_MAJOR_VERSION >= 3
tempstr = (char*) PyUnicode_AsUTF8AndSize(ob, &local_size);
#else
/* First, need to convert the object to UTF8 unicode/string object */
if (PyUnicode_Check(ob) || PyString_Check(ob)) {
pystr = pystr_to_utf8(ob);
} else {
PyErr_SetString(PyExc_ValueError, "argument is not a string type");
return NULL;
}
if (pystr) {
tempstr = PyString_AsString(pystr);
local_size = strlen(tempstr);
} else {
if (size) {
*size = 0;
}
PyErr_SetString(PyExc_ValueError, "creation of string failed");
return NULL;
}
#endif
/* create a copy of tempstr */
result = calloc(local_size + 1, sizeof(char));
if (result) {
strcpy(result, tempstr);
} else {
result = (char*) PyErr_NoMemory();
}
if (size) {
*size = local_size;
}
if (pystr) {
Py_XDECREF(pystr);
}
return result;
}
static char* as_utf8_char(PyObject *ob) {
return as_utf8_char_and_size(ob, NULL);
}
/* Converts a char* to a python string
*
* A new reference is always returned.
*/
static PyObject* char_to_pystr(const char *s, Py_ssize_t len) {
PyObject *result = NULL;
#if PY_MAJOR_VERSION >= 3
result = PyUnicode_DecodeUTF8(s, len, "strict");
#else
result = PyString_FromStringAndSize(s, len);
#endif
return result;
}
static int is_string_type(PyObject *ob) {
int result;
#if PY_MAJOR_VERSION >= 3
result = PyUnicode_Check(ob) || PyBytes_Check(ob);
#else
result = PyUnicode_Check(ob) || PyString_Check(ob);
#endif
return result;
}
static PyObject* pystr_from_format(const char *format, ...) {
PyObject* result = NULL;
va_list arglist;
va_start(arglist, format);
#if PY_MAJOR_VERSION >= 3
PyObject *temp = PyUnicode_FromFormatV(format, arglist);
result = pystr_to_utf8(temp);
Py_XDECREF(temp);
#else
result = PyString_FromFormatV(format, arglist);
#endif
va_end(arglist);
return result;
}
static int dict_setitemstring(PyObject *d, const char *key, PyObject *val) {
PyObject *key_obj = char_to_pystr(key, strlen(key));
int success = 0;
success = PyDict_SetItem(d, key_obj, val);
Py_XDECREF(key_obj);
return success;
}
/* all doc strings defined within the C interface */
/* Nio.open_file.__doc__ */
static char *open_file_doc =
"\n\
Open a file containing data in a supported format for reading and/or writing.\
\n\n\
f = Nio.open_file(filepath, mode='r',options=None, history='')\n\n\
filepath -- path of file with data in a supported format. The path must end\n\
with an extension indicating the expected format of the file, whether or not\n\
it is part of the actual file name. Valid extensions include:\n\
.nc, .cdf, .netcdf, .nc3, .nc4, -- NetCDF\n\
.gr, .grb, .grib, .gr1, .grb1, .grib1, .gr2, .grb2, .grib2, -- GRIB\n\
.hd, .hdf -- HDF\n\
.he2, .he4, .hdfeos -- HDFEOS\n\
.he5, .hdfeos5 -- HDFEOS5\n\
.shp, .mif, .gmt, .rt1 -- shapefiles, other formats supported by GDAL OGR\n\
.ccm -- CCM history files\n\
Extensions are handled case-insensitvely, i.e.: .grib, .GRIB, and .Grib all\n\
indicate a GRIB file.\n\
mode -- access mode (optional):\n\
'r' -- open an existing file for reading\n\
'w','r+','rw','a' -- open an existing file for modification\n\
'c' -- create a new file open for writing\n\
options -- instance of NioOptions class used to specify format-specific\n\
options\n\
history -- a string specifying text to be appended to the file\'s global\n\
attribute. The attribute is created if it does not exist. Only valid\n\
if the file is open for writing\n\n\
Returns an NioFile object.\n\
";
/* Nio.options.__doc__ */
static char *options_doc =
"\n\
Return an NioOptions object for specifying format-specific options.\n\n\
opt = Nio.options()\n\
Assign 'opt' as the third (optional) argument to Nio.open_file.\n\
print opt.__doc__ to see valid options.\n\
";
/*
* opt = Nio.options()
* opt.__doc__
*/
static char *option_class_doc =
"\n\
NioOptions object\n\n\
Set options by assigning attributes to this object and then passing the\n\
object as an optional argument to Nio.open_file:\n\
opt.OptionName = value\n\
All option names and string option values are handled case-insensitively.\n\
\n\
Generic options:\n\
MaskedArrayMode -- Specify MaskedArray bahavior (string):\n\
'MaskedIfFillAtt' -- Return a masked array iff file variable has a\n\
_FillValue or a missing_value attribute (default).\n\
'MaskedNever' -- Never return a masked array for any variable.\n\
'MaskedAlways' -- Return a masked array for all variables.\n\
'MaskedIfFillAttAndValue' -- Return a masked array iff file variable has a\n\
_FillValue or a missing_value attribute and the returned data array\n\
actually contains 1 or more fill values.\n\
'MaskedExplicit' -- Only mask values specified explicitly using options\n\
'ExplicitFillValues, MaskBelowValue, and/or MaskAboveValue;\n\
ignore fill value attributes associated with the variable.\n\
ExplicitFillValues -- A scalar value or a sequence of values to be masked in the\n\
return array. The first value becomes the fill_value attribute of the MaskedArray.\n\
Setting this option causes MaskedArrayMode to be set to 'MaskedExplicit'.\n\
MaskBelowValue -- A scalar value all values less than which are masked. However, if\n\
MaskAboveValue is less than MaskBelowValue, a range of of values become masked.\n\
Setting this option causes MaskedArrayMode to be set to 'MaskedExplicit'.\n\
MaskAboveValue -- A scalar value all values greater than which are masked. However, if\n\
MaskBelowValue is greater than MaskAboveValue, a range of of values become masked.\n\
Setting this option causes MaskedArrayMode to be set to 'MaskedExplicit'.\n\
UseAxisAttribute -- A boolean option that if set True when using extended subscripting,\n\
and if coordinate variables have the CF-compliant 'axis' attribute, expects the\n\
short names ('T','Z','Y' or 'X') instead of the actual coordinate names in the\n\
subscript specification.\n\
\n\
NetCDF file options:\n\
Format -- Specify the format of newly created files (string):\n\
'Classic' -- (default) standard file (generally file size < 2GB)\n\
'LargeFile' or '64BitOffset' -- (fixed-size variables or record\n\
elements of unlimited dimension variables each up to 4GB)\n\
'NetCDF4Classic' -- Classic mode NetCDF 4 file (uses HDF 5 as the\n\
underlying format but is restricted to features of the classic\n\
NetCDF data model).\n\
'NetCDF4' -- NetCDF 4 file (uses HDF 5 as the underlying format).\n\
CompressionLevel -- Specify the level of data compression on a scale\n\
of 0 - 9 (ignored unless Format is set to 'NetCDF4Classic' or 'NetCDF4').\n\
HeaderReserveSpace -- Reserve <int-value> extra bytes in the header\n\
of a file open for writing. Used to subsequently add dimensions,\n\
attributes, and variables to existing files efficiently.\n\
MissingToFillValue -- If set True (the default), create a virtual\n\
'_FillValue' attribute only for variables that have a\n\
'missing_value' but no '_FillValue'.\n\
PreFill -- If set True (the default), fill all elements of newly\n\
defined variables with a fill value. If set False, elements are\n\
undefined until data is written.\n\
SafeMode -- Close the file after each individual operation on the file.\n\
\n\
GRIB files options\n\
DefaultNCEPTable -- (GRIB 1 only) Specify the table to use in certain\n\
ambiguous cases:\n\
'Operational' -- (default) Use the NCEP operational parameter table\n\
'Reanalysis' -- Use the NCEP reanalysis parameter table\n\
InitialTimeCoordinateType -- Specify the type of the coordinate\n\
associated with initial_time (as opposed to forecast_time)\n\
dimensions:\n\
'Numeric' -- (default) use CF-compliant numeric coordinates\n\
'String' -- use date strings as the coordinates\n\
SingleElementDimensions -- Specify that dimensional types with only a\n\
single representative element be treated as full-fledged dimensions.\n\
'None' -- (default) no single element dimensions are created\n\
'All' -- all possible single element dimensions are created.\n\
The names of individual dimension types may be specified individually:\n\
'Initial_time', 'Forecast_time', 'Level', 'Ensemble', or 'Probability'.\n\
ThinnedGridInterpolation -- Specify the type of interpolation for\n\
thinned (GRIB 'quasi-regular') grids:\n\
'Cubic' -- (cubic) use cubic interpolation\n\
'Linear' -- use linear interpolation\n\n\
";
static char *niofile_type_doc =
"\n\
NioFile object\n\n\
Given:\n\
f = Nio.open_file(filepath, mode='r', options=None, history='',format='')\n\
\n\
To see summary of file contents, including all attributes:\n\
print f\n\
Assign global attributes to writable files or groups using:\n\
f.global_att = global_att_value\n\
Attributes:\n\
name -- the name of the file or group\n\
dimensions -- dictionary of dimension lengths with dimension name keys\n\
variables -- dictionary of variable objects with variable name keys\n\
attributes -- dictionary of global file or group attributes with attribute name keys\n\
(the following are applicable for advanced formats NetCDF4 and HDF5 only)\n\
groups -- dictionary of groups with group name keys\n\
ud_types -- dictionary of user-defined data type definitions with data type name keys\n\
chunk_dimensions -- dictionary of chunking dimension sizes with dimension name keys\n\
parent -- reference to the parent group, parent file for the root group, or None for a file\n\
path -- the path of a group relative to the root group ('/'), or the file path for a file\n\
Methods:\n\
close(history='') -- close the file\n\
create_dimension(name, length) -- create a dimension in the file\n\
create_variable(name, type, dimensions) -- create a variable in the file\n\
unlimited(dimension_name) -- returns True if dimension_name refers to an unlimited dimension; False otherwise\n\
(the following are applicable for advanced formats NetCDF4 and HDF5 only)\n\
create_group(name) -- create a group in the file or group.\n\
create_vlen(name,type,dimensions) -- create a variable length array variable in the file or group.\n\
create_compound(name,type,dimensions) -- create a compound variable with the given type and dimensions.\n\
create_compound_type(name, type) -- create a user-defined compound type; with member names, sizes\n\
and types as defined in the type sequence argument.\n\
";
/* NioFile object method doc strings */
/*
* f = Nio.open_file(..)
* f.close.__doc__
* f.create_dimension.__doc__
* f.create_chunk_dimension.__doc__
* f.create_variable.__doc__
* f.create_group.__doc__
*/
static char *close_doc =
"\n\
Close a file, ensuring all modifications are up-to-date if open for writing.\
\n\n\
f.close([history])\n\
history -- optional string appended to the global 'history' attribute\n\
before closing a writable file. The attribute is created if it does not\n\
already exist.\n\
Read or write access attempts on the file object after closing\n\
raise an exception.\n\
";
static char *create_dimension_doc =
"\nCreate a new dimension with the given name and length in a writable file.\n\n\
f.create_dimension(name,length)\n\
name -- a string specifying the dimension name.\n\
length -- a positive integer specifying the dimension length. If set to\n\
None or 0, specifies the unlimited dimension.\n";
static char *create_chunk_dimension_doc =
"\nCreate a chunking size for a dimension that has been defined but not yet used in a writable file.\n\
The size must be no larger than the dimension size; once set it cannot be changed.\n\
f.create_chunk_dimension(name,length)\n\
name -- a string specifying the dimension name.\n\
length -- a positive integer specifying the dimension length. If set to\n\
None or 0, it will be reset to 1.\n";
static char *create_variable_doc =
"\n\
Create a new variable with given name, type, and dimensions in a writable file.\
\n\n\
f.create_variable(name,type,dimensions)\n\
name -- a string specifying the variable name.\n\
type -- a type identifier. The following are currently supported:\n\
'd' -- 64 bit real\n\
'f' -- 32 bit real\n\
'l' -- 32 bit integer\n\
'L' -- 32 bit unsigned integer\n\
'q' -- 64 bit integer\n\
'Q' -- 64 bit unsigned integer\n\
'h' -- 16 bit integer\n\
'H' -- 16 bit unsigned integer\n\
'b' -- 8 bit integer\n\
'B' -- 8 bit unsigned integer\n\
'S1','c' -- character\n\
dimensions -- a tuple of dimension names (strings), previously defined\n\
";
static char *create_group_doc =
"\n\
Create a new group with given name in a writable file.\
\n\n\
f.create_group(name)\n\
name -- a string specifying the group name.\n\
";
static char *create_vlen_doc =
"\n\
Create a new variable length array variable with given name in a writable file.\
\n\n\
f.create_vlen(name,type,dimensions)\n\
name -- a string specifying the vlen variable name.\n\
type -- the variable type.\n\
dimensions -- the dimensions of the vlen variable.\n\
";
static char *create_compound_type_doc =
"\n\
Create a new compound variable type with given name in a writable file.\
\n\n\
f.create_compound_type(name,type)\n\
name -- a string specifying the compound type name.\n\
type -- a sequence containing the name, type, and number of elements for each member of the compound type\n\
";
static char *create_compound_doc =
"\n\
Create a new compound variable with given name in a writable file.\
\n\n\
f.create_compound(name,type,dimensions)\n\
name -- a string specifying the compound variable name.\n\
type -- the variable type.\n\
dimensions -- the dimensions of the compound variable.\n\
";
static char *unlimited_doc =
"\n\
Returns True or False depending on whether the named dimension is unlimited.\n\n\
f.unlimited(name)\n\
name -- a string specifying the dimension name to be queried for the unlimited property.\n\
";
static char *niovariable_type_doc =
"\n\
NioVariable object\n\n\
Given \n\
v = f.variables['varname']\n\
Get summary of variable contents using:\n\
print v\n\
Assign variable attributes for writable files using, e.g:\n\
v.units = 'meters'\n\
Get or assign variable values using slicing syntax:\n\
val = v[:]\n\
assigns all elements of variable to 'val', retaining dimensionality;\n\
val = v[0,:]\n\
assigns one element of the first dimension and all elements of the remaining dimensions.\n\
Attributes:\n\
rank -- a scalar value indicating the number of dimensions\n\
shape -- a tuple containing the number of elements in each dimension\n\
dimensions -- a tuple containing the dimensions names in order\n\
attributes -- a dictionary of variable attributes with attribute name keys\n\
size -- a scalar value indicating the size in bytes of the variable\n\
name -- the name of the variable\n\
parent -- reference to the group or file to which the variable belongs\n\
path -- the path of the variable relative to the root group ('/')\n\
Methods:\n\
assign_value(value) -- assign a value to a variable in the file.\n\
get_value() -- retrieve the value of a variable in the file.\n\
typecode() -- return a character code representing the variable's type.\n\
set_option(option,value) -- set certain options.\n\
";
/* NioVariable object method doc strings */
/*
* v = f.variables['varname']
* v.assign_value.__doc__
* v.get_value.__doc__
* v.typecode.__doc__
*/
static char *assign_value_doc =
"\n\
Assign a value to a variable in the file.\n\n\
v = f.variables['varname']\n\
v.assign_value(value)\n\
value - a NumPy array or a Python sequence of values that are coercible\n\
to the type of variable 'v'.\n\
This method is the only way to assign a scalar value. There is no way to\n\
indicate a slice. For array variables direct assignment using slicing\n\
syntax is more flexible.\n\
";
static char *get_value_doc =
"\n\
Retrieve the value of a variable in the file.\n\n\
v = f.variables['varname']\n\
val = v.get_value()\n\
'val' is returned as a NumPy array.\n\
This method is the only way to retrieve the scalar value from a file.\n\
There is no way to indicate a slice. For array variables direct assignment\n\
using slicing syntax is more flexible.\n\
";
static char *typecode_doc =
"\n\
Return a character code representing the variable's type.\n\n\
v = f.variables['varname']\n\
t = v.typecode()\n\
Return variable 't' will be one of the following:\n\
'd' -- 64 bit real\n\
'f' -- 32 bit real\n\
'i' -- 32 bit integer\n\
'I' -- 32 bit unsigned integer\n\
'l' -- 32 or 64 bit integer (platform dependent)\n\
'L' -- 32 or 64 bit unsigned integer (platform dependent)\n\
'q' -- 64 bit integer\n\
'Q' -- 64 bit unsigned integer\n\
'h' -- 16 bit integer\n\
'H' -- 16 bit unsigned integer\n\
'b' -- 8 bit integer\n\
'B' -- 8 bit unsigned integer\n\
'S1', 'c' -- character\n\
'S' -- string\n\
'v' -- Vlen\n\
'x' -- Cmpound\n\
";
static void
NioVariableObject_dealloc(NioVariableObject *self);
static void
NioFileObject_dealloc(NioFileObject *self);
/*
* global used in NclMultiDValData
*/
short NCLnoPrintElem = 0;
size_t NCLtotalVariables = 0;
size_t NCLtotalGroups = 0;
static int nio_file_init(NioFileObject *self);
static NioFileObject* nio_read_group(NioFileObject* file,
NclFileGrpNode *grpnode);
static NioFileObject* nio_create_group(NioFileObject* file, NrmQuark gname);
static NioVariableObject* nio_read_advanced_variable(NioFileObject* file,
NclFileVarNode* varnode, int id);
static NioVariableObject *nio_variable_new(NioFileObject *file, char *name,
int id, int type, int ndims, NrmQuark *qdims, int nattrs);
void _convertObj2COMPOUND(PyObject* pyobj, obj* listids,
NclFileCompoundRecord *comprec, ng_size_t n_dims, ng_size_t curdim,
ng_usize_t* counter);
#if PY_MAJOR_VERSION < 3
static char err_buf[256];
static PyObject *Niomodule; /* the Nio Module object */
/* Error object and error messages for nio-specific errors */
static PyObject *NIOError;
#endif
static char *nio_errors[] = { "No Error", /* 0 */
"Not a NIO id", "Too many NIO files open", "NIO file exists && NC_NOCLOBBER",
"Invalid Argument", "Write to read only",
"Operation not allowed in data mode",
"Operation not allowed in define mode", "Coordinates out of Domain",
"MAX_NC_DIMS exceeded", "String match to name in use",
"Attribute not found", "MAX_NC_ATTRS exceeded", "Not a NIO data type",
"Invalid dimension id", "NC_UNLIMITED in the wrong index",
"MAX_NC_VARS exceeded", "Variable not found",
"Action prohibited on NC_GLOBAL varid", "Not an NIO supported file",
"In Fortran, string too short", "MAX_NC_NAME exceeded",
"NC_UNLIMITED size already in use", /* 22 */
"Memory allocation error", "attempt to set read-only attributes",
"invalid mode specification", "", "", "", "", "", "", "XDR error" /* 32 */
};
static void nio_seterror(int nio_ncerr) {
if (nio_ncerr != 0) {
char *error = "Unknown error";
if (nio_ncerr > 0 && nio_ncerr <= 32) {
error = nio_errors[nio_ncerr];
}
PyErr_SetString(get_NioError(), error);
}
}
/*
* Python equivalents to NIO data types
*
* Attention: the following specification may not be fully portable.
* The comments indicate the correct NIO specification. The assignment
* of Python types assumes that 'short' is 16-bit and 'int' is 32-bit.
*/
#if 0
int data_types[] =
{ -1, /* not used */
NPY_BYTE, /* signed 8-bit int */
NPY_CHAR, /* 8-bit character */
NPY_SHORT, /* 16-bit signed int */
NPY_INT, /* 32-bit signed int */
NPY_FLOAT, /* 32-bit IEEE float */
NPY_DOUBLE /* 64-bit IEEE float */
};
#endif
int data_type(NclBasicDataTypes ntype) {
switch (ntype) {
case NCL_short:
return NPY_SHORT;
case NCL_ushort:
return NPY_USHORT;
case NCL_int:
return NPY_INT; /* netcdf 3.x has only a long type */
case NCL_uint:
return NPY_UINT; /* netcdf 3.x has only a long type */
case NCL_long:
return NPY_LONG;
case NCL_ulong:
return NPY_ULONG;
case NCL_int64:
return NPY_LONGLONG;
case NCL_uint64:
return NPY_ULONGLONG;
case NCL_float:
return NPY_FLOAT;
case NCL_double:
return NPY_DOUBLE;
case NCL_byte:
return NPY_BYTE;
case NCL_ubyte:
return NPY_UBYTE;
case NCL_char:
return NPY_CHAR;
case NCL_logical:
return NPY_BOOL;
case NCL_string:
return NPY_STRING;
/* case NCL_vlen:
return NPY_VLEN;
case NCL_compound:
return NPY_COMPOUND;
case NCL_enum:
return NPY_ENUM;
case NCL_opaque:
return NPY_OPAQUE;
case NCL_reference:
return NPY_REFERENCE;
case NCL_list:
return NPY_LIST;
case NCL_listarray:
return NPY_LISTARRAY;
*/
case NCL_vlen:
case NCL_compound:
case NCL_enum:
case NCL_opaque:
case NCL_reference:
case NCL_list:
case NCL_listarray:
return NPY_OBJECT;
default:
return NPY_NOTYPE;
}
return NPY_NOTYPE;
}
/* Utility functions */
static void define_mode(NioFileObject *file, int define_flag) {
if (file->define != define_flag) {
#if 0
if (file->define)
ncendef(file->id);
else
ncredef(file->id);
#endif
file->define = define_flag;
}
}
static char *
typecode(int type) {
static char buf[3];
memset(buf, 0, 3);
switch (type) {
case NPY_BOOL:
buf[0] = NPY_BOOLLTR;
break;
case NPY_BYTE:
buf[0] = NPY_BYTELTR;
break;
case NPY_UBYTE:
buf[0] = NPY_UBYTELTR;
break;
case NPY_SHORT:
buf[0] = NPY_SHORTLTR;
break;
case NPY_USHORT:
buf[0] = NPY_USHORTLTR;
break;
case NPY_INT:
buf[0] = NPY_INTLTR;
break;
case NPY_UINT:
buf[0] = NPY_UINTLTR;
break;
case NPY_LONG:
buf[0] = NPY_LONGLTR;
break;
case NPY_ULONG:
buf[0] = NPY_ULONGLTR;
break;
case NPY_LONGLONG:
buf[0] = NPY_LONGLONGLTR;
break;
case NPY_ULONGLONG:
buf[0] = NPY_ULONGLONGLTR;
break;
case NPY_FLOAT:
buf[0] = NPY_FLOATLTR;
break;
case NPY_DOUBLE:
buf[0] = NPY_DOUBLELTR;
break;
case NPY_STRING:
buf[0] = NPY_STRINGLTR;
break;
#if 0
case NPY_CHAR:
buf[0] = NPY_STRINGLTR;
break;
#else
case NPY_CHAR:
buf[0] = NPY_CHARLTR;
break;
#endif
case NPY_VLEN:
buf[0] = NPY_VLENLTR;
break;
case NPY_COMPOUND:
buf[0] = NPY_COMPOUNDLTR;
break;
case NPY_ENUM:
buf[0] = NPY_ENUMLTR;
break;
case NPY_OPAQUE:
buf[0] = NPY_OPAQUELTR;
break;
case NPY_LIST:
buf[0] = NPY_LISTLTR;
break;
case NPY_LISTARRAY:
buf[0] = NPY_LISTARRAYLTR;
break;
case NPY_REFERENCE:
buf[0] = NPY_REFERENCELTR;
break;
default:
buf[0] = ' ';
break;
}
return &buf[0];
}
static NrmQuark nio_type_from_code(int code) {
NrmQuark type;
switch ((char) code) {
case 'c':
type = NrmStringToQuark("character");
break;
case 'S':
type = NrmStringToQuark("string");
break;
case '1':
case 'b':
type = NrmStringToQuark("byte");
break;
case 'B':
type = NrmStringToQuark("ubyte");
break;
case 'h':
type = NrmStringToQuark("short");
break;
case 'H':
type = NrmStringToQuark("ushort");
break;
case 'i':
type = NrmStringToQuark("integer");
break;
case 'I':
type = NrmStringToQuark("uint");
break;
case 'l':
type = NrmStringToQuark("long");
break;
case 'L':
type = NrmStringToQuark("ulong");
break;
case 'q':
type = NrmStringToQuark("int64");
break;
case 'Q':
type = NrmStringToQuark("uint64");
break;
case 'f':
type = NrmStringToQuark("float");
break;
case 'd':
type = NrmStringToQuark("double");
break;
case '?':
type = NrmStringToQuark("logical");
break;
case 'v':
type = NrmStringToQuark("list");
break;
case 'x':
type = NrmStringToQuark("compound");
break;
case 'O':
type = NrmStringToQuark("object");
break;
default:
type = NrmNULLQUARK;
}
return type;
}
static void collect_attributes(void *fileid, int varid, PyObject *attributes,
int nattrs) {
NclFile file = (NclFile) fileid;
NclFileAttInfoList *att_list = NULL;
NclFAttRec *att;
NclFVarRec *fvar = NULL;
char *name;
npy_intp length;
int py_type;
int i;
if (varid > -1) {
att_list = file->file.var_att_info[varid];
fvar = file->file.var_info[varid];
}
for (i = 0; i < nattrs; i++) {
NclMultiDValData md;
if (varid < 0) {
att = file->file.file_atts[i];
name = NrmQuarkToString(att->att_name_quark);
md = _NclFileReadAtt(file, att->att_name_quark, NULL);
} else if (!(att_list && fvar)) {
PyErr_SetString(get_NioError(),
"internal attribute or file variable error");
return;
} else {
att = att_list->the_att;
name = NrmQuarkToString(att->att_name_quark);
md = _NclFileReadVarAtt(file, fvar->var_name_quark,
att->att_name_quark, NULL);
att_list = att_list->next;
}
if (att->data_type == NCL_string) {
PyObject *string = NULL;
char *satt = NrmQuarkToString(*((NrmQuark *) md->multidval.val));
if (satt != NULL) {
string = char_to_pystr(satt, strlen(satt));
} else {
string = char_to_pystr("", strlen(""));
}
if (string != NULL) {
dict_setitemstring(attributes, name, string);
Py_DECREF(string);
}
} else {
PyObject *array;
length = (npy_intp) md->multidval.totalelements;
py_type = data_type(att->data_type);
/* following three if clauses are temporary until these types are actually supported */
if (py_type == NPY_REFERENCE) {
py_type = NPY_LONG;
}
if (py_type == NPY_COMPOUND) {
py_type = NPY_LONG;
}
if (py_type == NPY_ENUM) {
py_type = NPY_LONG;
}
array = PyArray_SimpleNew(1, &length, py_type);
if (array != NULL) {
memcpy(PyArray_BYTES((PyArrayObject *) array),
md->multidval.val,
(size_t) length * md->multidval.type->type_class.size);
array = PyArray_Return((PyArrayObject *) array);
if (array != NULL) {
dict_setitemstring(attributes, name, array);
Py_DECREF(array);
}
}
}
}
}
static int set_attribute(NioFileObject *file, int varid, PyObject *attributes,
char *name, PyObject *value) {
NclFile nfile = (NclFile) file->id;
NhlErrorTypes ret;
NclMultiDValData md = NULL;
PyArrayObject *array = NULL;
if (!value || value == Py_None) {
/* delete attribute */
if (varid == NC_GLOBAL) {
ret = _NclFileDeleteAtt(nfile, NrmStringToQuark(name));
} else {
ret = _NclFileDeleteVarAtt(nfile,
nfile->file.var_info[varid]->var_name_quark,
NrmStringToQuark(name));
}
PyObject_DelItemString(attributes, name);
return 0;
}
if (is_string_type(value)) {
ng_size_t len_dims = 1;
NrmQuark *qval = malloc(sizeof(NrmQuark));
char* utf8 = as_utf8_char(value);
qval[0] = NrmStringToQuark(utf8);
free(utf8);
md = _NclCreateMultiDVal(NULL, NULL, Ncl_MultiDValData, 0, (void*) qval,
NULL, 1, &len_dims, TEMPORARY, NULL,
(NclTypeClass) nclTypestringClass);
} else {
ng_size_t dim_sizes = 1;
int n_dims;
NrmQuark qtype;
int pyarray_type = NPY_NOTYPE;
PyArrayObject *tmparray = (PyArrayObject *) PyDict_GetItemString(
attributes, name);
if (tmparray != NULL) {
pyarray_type = PyArray_TYPE(tmparray);