forked from jhamman/DHSVM
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FileIONetCDF.c
executable file
·851 lines (737 loc) · 30.5 KB
/
FileIONetCDF.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
/*
* SUMMARY: FileIONetCDF.c - Functions for NetCDF IO
* USAGE: Part of DHSVM
*
* AUTHOR: Bart Nijssen
* ORG: University of Washington, Department of Civil Engineering
* E-MAIL: [email protected]
* ORIG-DATE: Apr-96
* DESCRIPTION: Functions for binary IO
* DESCRIP-END.
* FUNCTIONS: CreateMapFileNetCDF()
* Read2DMatrixNetCDF()
* Write2DMatrixNetCDF()
* SizeOfNumberType()
*
* Modified was made to Read2DMatrix by Ning (2013)
Comment :First, make sure that the input NETCDF file to Read2DMatrix
is in 3 dimensions. In this case, the 1st dimention should be time,
the 2nd is y (lat), and 3rd is x (lon).
Using the command 'ncdump -in.nc', we can see that the
descending/ascending order in which the NetCDF file uses to stores
coordinates. The order is important b/c it decides in which order
the NetCDF files is read out and stored in a 2D matrix.
Simply put, in the input netcdf file, if the first variable value
corresponds to the smallest x and y, which is the lower left corner
in the spatial sense, then it shouldn't be assigned to
Matrix[0][0] which is in the upper left corner. Instead it should be
stored in lower left corner.
So the Read2DMatrix function is changed so that it reads x and y
in .nc input file, and output a flag that will be used as an indicator
of whethe or not the matrix should be reversed.
Note that this program now handles two cases: 1) .nc generated
from gdal tool, in which x and y are both in an ascending order;
2) .nc generated from arcmap, in which x is in an ascending and y in an
descedning order, and no reverse needs to be made in this case. Just be
aware that a time dimention has to be added to arc generated .nc file.
(check the tutorial for instructions).
The matrix will be reversed in the 1st case in the program that calls
Read2DMATRIX (Ning, Feb 2013)
*/
#ifdef HAVE_NETCDF
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <netcdf.h>
#include <time.h>
#include "settings.h"
#include "data.h"
#include "fifoNetCDF.h"
#include "fileio.h"
#include "functions.h"
#include "settings.h"
#include "DHSVMerror.h"
#include "sizeofnt.h"
static void nc_check_err(const int ncstatus, const int line, const char *file);
static int GenerateHistory(int argc, char **argv, char *History);
static int ncUpdateGlobalHistory(int argc, char **argv, int ncid);
#ifdef TEST_FILEIONETCDF
char commandline[] = "Testing the NetCDF file format";
#else
extern char commandline[];
#endif
/*******************************************************************************
Function name: CreateMapFileNetCDF()
Purpose : Open and close a new file. If the file already exists it
will be overwritten.
Required :
FileName - Name of the new file
FileLabel - String describing file contents
Map - structure with information about spatial extent of model area
Returns : void
Modifies :
Comments : NetCDF defines all the dimensions in the file before the file
can be written to. By default it creates the entire file
during when nc_endef() is called and fills all positions with
_FillValue. This behavior is turned off here to speed up the
initialization process by or'ing the NC_NOFILL flag into
the mode parameter of nc_create()
*******************************************************************************/
void CreateMapFileNetCDF(char *FileName, ...)
{
const char *Routine = "CreateMapFileNetCDF";
va_list ap;
MAPSIZE *Map = NULL; /* pointer to structure with map info */
char *FileLabel; /* File label */
double *Array;
double missing_value[1];
char *ptrstr[1];
int x;
int y;
int varideast;
int varidnorth;
int varidtime;
int ncstatus;
int ncid;
int dimids[3]; /* time, north, east */
/****************************************************************************/
/* HANDLE VARIABLE ARGUMENT LIST */
/****************************************************************************/
va_start(ap, FileName);
FileLabel = va_arg(ap, char *);
Map = va_arg(ap, MAPSIZE *);
/* Go ahead and clobber any existing file */
ncstatus = nc_create(FileName, NC_CLOBBER | NC_NOFILL, &ncid);
nc_check_err(ncstatus, __LINE__, __FILE__);
/****************************************************************************/
/* DEFINE MODE */
/****************************************************************************/
ncstatus = nc_def_dim(ncid, TIME_DIM, NC_UNLIMITED, &dimids[0]);
nc_check_err(ncstatus, __LINE__, __FILE__);
ncstatus = nc_def_dim(ncid, Y_DIM, Map->NY, &dimids[1]);
nc_check_err(ncstatus, __LINE__, __FILE__);
ncstatus = nc_def_dim(ncid, X_DIM, Map->NX, &dimids[2]);
nc_check_err(ncstatus, __LINE__, __FILE__);
/* Define dimension variables and their attributes */
/* time */
ncstatus = nc_def_var(ncid, TIME_DIM, NC_DOUBLE, 1, &dimids[0], &varidtime);
nc_check_err(ncstatus, __LINE__, __FILE__);
ncstatus = nc_put_att_text(ncid, varidtime, ATT_NAME, strlen(TIME_DIM),
TIME_DIM);
nc_check_err(ncstatus, __LINE__, __FILE__);
ncstatus = nc_put_att_text(ncid, varidtime, ATT_LONGNAME, strlen(TIME_DIM),
TIME_DIM);
nc_check_err(ncstatus, __LINE__, __FILE__);
ncstatus = nc_put_att_text(ncid, varidtime, ATT_UNITS, strlen("index"),
"index");
nc_check_err(ncstatus, __LINE__, __FILE__);
/* ncstatus = nc_put_att_text(ncid, varidtime, ATT_FORMAT, strlen("%g"), "%g"); */
/* nc_check_err(ncstatus, __LINE__, __FILE__); */
/* northing */
ncstatus = nc_def_var(ncid, Y_DIM, NC_DOUBLE, 1, &dimids[1], &varidnorth);
nc_check_err(ncstatus, __LINE__, __FILE__);
ncstatus = nc_put_att_text(ncid, varidnorth, ATT_NAME, strlen(Y_DIM), Y_DIM);
nc_check_err(ncstatus, __LINE__, __FILE__);
ncstatus =
nc_put_att_text(ncid, varidnorth, ATT_LONGNAME, strlen("Northing"),
"Northing");
nc_check_err(ncstatus, __LINE__, __FILE__);
ncstatus = nc_put_att_text(ncid, varidnorth, ATT_UNITS, strlen("m"), "m");
nc_check_err(ncstatus, __LINE__, __FILE__);
/* ncstatus = nc_put_att_text(ncid, varidnorth, ATT_FORMAT, strlen("%g"), "%g"); */
/* nc_check_err(ncstatus, __LINE__, __FILE__); */
/* easting */
ncstatus = nc_def_var(ncid, X_DIM, NC_DOUBLE, 1, &dimids[2], &varideast);
nc_check_err(ncstatus, __LINE__, __FILE__);
ncstatus = nc_put_att_text(ncid, varideast, ATT_NAME, strlen(X_DIM), X_DIM);
nc_check_err(ncstatus, __LINE__, __FILE__);
ncstatus = nc_put_att_text(ncid, varideast, ATT_LONGNAME, strlen("Easting"),
"Easting");
nc_check_err(ncstatus, __LINE__, __FILE__);
ncstatus = nc_put_att_text(ncid, varideast, ATT_UNITS, strlen("m"), "m");
nc_check_err(ncstatus, __LINE__, __FILE__);
/* ncstatus = nc_put_att_text(ncid, varideast, ATT_FORMAT, strlen("%g"), "%g"); */
/* nc_check_err(ncstatus, __LINE__, __FILE__); */
/* Update the history attribute */
ptrstr[0] = commandline;
ncstatus = ncUpdateGlobalHistory(1, ptrstr, ncid);
nc_check_err(ncstatus, __LINE__, __FILE__);
/* Insert the file label and other global attributes */
ncstatus = nc_put_att_text(ncid, NC_GLOBAL, ATT_COMMENT, strlen(FileLabel),
FileLabel);
nc_check_err(ncstatus, __LINE__, __FILE__);
missing_value[0] = NA;
ncstatus = nc_put_att_double(ncid, NC_GLOBAL, ATT_MISSINGVALUE, NC_DOUBLE, 1,
missing_value);
nc_check_err(ncstatus, __LINE__, __FILE__);
/* exit the define mode */
ncstatus = nc_enddef(ncid);
nc_check_err(ncstatus, __LINE__, __FILE__);
/****************************************************************************/
/* WRITE X AND Y DIMENSIONS TO THE OUTPUT FILE */
/****************************************************************************/
Array = (double *) calloc(Map->NX, sizeof(double));
if (Array == NULL)
ReportError((char *) Routine, 1);
for (x = 0; x < Map->NX; x++)
Array[x] = Map->Xorig + x * Map->DX;
ncstatus = nc_put_var_double(ncid, varideast, Array);
nc_check_err(ncstatus, __LINE__, __FILE__);
free(Array);
Array = (double *) calloc(Map->NY, sizeof(double));
if (Array == NULL)
ReportError((char *) Routine, 1);
for (y = 0; y < Map->NY; y++)
Array[y] = Map->Yorig - y * Map->DY;
ncstatus = nc_put_var_double(ncid, varidnorth, Array);
nc_check_err(ncstatus, __LINE__, __FILE__);
free(Array);
ncstatus = nc_close(ncid);
nc_check_err(ncstatus, __LINE__, __FILE__);
}
/*******************************************************************************
Function name: Read2DMatrixNetCDF()
Purpose : Function to read a 2D array from a file.
Required :
FileName - name of input file
Matrix - address of array data into
NumberType - code for number type (taken from HDF, see comments at the
beginning of InitFileIO.c for more detail)
NY - Number of rows
NX - Number of columns
NDataSet - number of the dataset to read, i.e. the first matrix in a
file is number 0, etc. (this is not used for the NetCDF file,
since we can retrieve the variable by name).
VarName - Name of variable to retrieve
Returns : Number of elements read
Modifies : Matrix
Comments : NOTE that we cannot modify anything other than the returned
Matrix, because we have to stay compatible with Read2DMatrixBin
*******************************************************************************/
int Read2DMatrixNetCDF(char *FileName, void *Matrix, int NumberType, int NY,
int NX, int NDataSet, ...)
{
const char *Routine = "Read2DMatrixNetCDF";
char Str[BUFSIZE + 1];
char dimname[NC_MAX_NAME + 1];
char *VarName;
int dimids[3];
int ndims;
int ncid;
int ncstatus;
nc_type TempNumberType;
int varid;
size_t index;
double time;
int timid;
size_t count[3];
size_t start[3] = { 0, 0, 0 };
size_t dimlen;
size_t timelen;
va_list ap;
double *Ycoord;
double *Xcoord; /* lat, lon variables */
int LatisAsc, LonisAsc, flag; /* flag */
int lon_varid, lat_varid;
count[0] = 1;
count[1] = NY;
count[2] = NX;
/****************************************************************************/
/* GO THROUGH VARIABLE ARGUMENT LIST */
/****************************************************************************/
va_start(ap, NDataSet);
VarName = va_arg(ap, char *);
index = va_arg(ap, int);
/****************************************************************************/
/* QUERY NETDCF FILE */
/****************************************************************************/
ncstatus = nc_open(FileName, NC_NOWRITE, &ncid);
nc_check_err(ncstatus, __LINE__, __FILE__);
/* check whether the variable exists and get its parameters */
ncstatus = nc_inq_varid(ncid, VarName, &varid);
nc_check_err(ncstatus, __LINE__, __FILE__);
ncstatus = nc_inq_var(ncid, varid, 0, &TempNumberType, &ndims, dimids, NULL);
nc_check_err(ncstatus, __LINE__, __FILE__);
if (TempNumberType != NumberType) {
sprintf(Str, "%s: nc_type for %s is different than expected.\n",
FileName, VarName);
ReportWarning(Str, 58);
}
/* make sure that the x and y dimensions have the correct sizes */
ncstatus = nc_inq_dim(ncid, dimids[1], dimname, &dimlen);
nc_check_err(ncstatus, __LINE__, __FILE__);
ncstatus = nc_inq_varid(ncid, dimname, &lat_varid);
nc_check_err(ncstatus, __LINE__, __FILE__);
if (dimlen != NY)
ReportError(VarName, 59);
Ycoord = (double *) calloc(dimlen, sizeof(double));
if (Ycoord == NULL)
ReportError((char *) Routine, 1);
/* Read the latitude coordinate variable data. */
ncstatus = nc_get_var_double(ncid, lat_varid, Ycoord);
nc_check_err(ncstatus, __LINE__, __FILE__);
/* A quick check if the lat, long are in a ascending order.
If so, matrix must be flipped so the first value in the matrix will be
assigned to the lower left corner cell that has lowest X (lon) & Y (lat) value.
(see more comments in the header of this C file). */
LatisAsc = 1;
if( Ycoord[0] > Ycoord[NY - 1] )
LatisAsc = 0;
ncstatus = nc_inq_dim(ncid, dimids[2], dimname, &dimlen);
nc_check_err(ncstatus, __LINE__, __FILE__);
ncstatus = nc_inq_varid(ncid, dimname, &lon_varid);
nc_check_err(ncstatus, __LINE__, __FILE__);
if (dimlen != NX)
ReportError(VarName, 60);
Xcoord = (double *) calloc(NX, sizeof(double));
if (Xcoord == NULL)
ReportError((char *) Routine, 1);
/* Read the latitude coordinate variable data. */
ncstatus = nc_get_var_double(ncid, lon_varid, Xcoord);
nc_check_err(ncstatus, __LINE__, __FILE__);
LonisAsc = 1;
if( Xcoord[0] > Xcoord[NX - 1] )
LonisAsc = 0;
if (LonisAsc == 0){
printf("The current program does not handle the cases when longitude or X \
values in the .nc input in an descending order. You can either change the input \
.nc file format outside of this program. or you can easily modify this program to \
fit your needs. \n");
ReportError("Improper NetCDF input files", 58);
}
if ((LatisAsc == 0) & (LonisAsc == 1))
flag = 0;
if ((LatisAsc == 1) & (LonisAsc == 1))
flag = 1;
/* see whether the time dimension needs to be updated (the assumption is that
the same index value refers to the same moment in time. Since currently we
make separate files for separate variables this is OK) */
ncstatus = nc_inq_dimlen(ncid, dimids[0], &timelen);
nc_check_err(ncstatus, __LINE__, __FILE__);
if (timelen < index + 1) { /* need to add one to time */
ncstatus = nc_inq_varid(ncid, TIME_DIM, &timid);
nc_check_err(ncstatus, __LINE__, __FILE__);
time = (double) index;
ncstatus = nc_put_var1_double(ncid, timid, &index, &time);
nc_check_err(ncstatus, __LINE__, __FILE__);
}
start[0] = index;
/****************************************************************************/
/* READ VARIABLE */
/****************************************************************************/
switch (NumberType) {
case NC_BYTE:
ncstatus = nc_get_vara_uchar(ncid, varid, start, count, Matrix);
break;
case NC_CHAR:
ncstatus = nc_get_vara_text(ncid, varid, start, count, Matrix);
break;
case NC_SHORT:
ncstatus = nc_get_vara_short(ncid, varid, start, count, Matrix);
break;
case NC_INT:
ncstatus = nc_get_vara_int(ncid, varid, start, count, Matrix);
break;
/* 8 bit integer not yet implemented in NetCDF 3.4, but anticipated in
future versions */
/* case NC_LONG: */
/* ncstatus = nc_put_vara_long(ncid, varid, start, count, Matrix); */
/* break; */
case NC_FLOAT:
ncstatus = nc_get_vara_float(ncid, varid, start, count, Matrix);
break;
case NC_DOUBLE:
ncstatus = nc_get_vara_double(ncid, varid, start, count, Matrix);
break;
default:
ReportError((char *) Routine, 40);
break;
}
nc_check_err(ncstatus, __LINE__, __FILE__);
/****************************************************************************/
/* CLEAN UP */
/****************************************************************************/
ncstatus = nc_close(ncid);
nc_check_err(ncstatus, __LINE__, __FILE__);
return flag;
}
/*******************************************************************************
Function name: Write2DMatrixNetCDF()
Purpose : Function to write a 2D array to a file. Data is appended to
the end of the file.
Required :
FileName - name of output file
Matrix - address of array containing matrix elements
NumberType - code for number type (taken from HDF, see comments at the
beginning of InitFileIO.c for more detail)
NY - Number of rows
NX - Number of columns
Returns : Number of elements written
Modifies :
Comments :
*******************************************************************************/
int Write2DMatrixNetCDF(char *FileName, void *Matrix, int NumberType, int NY,
int NX, ...)
{
const char *Routine = "Write2DMatrixNetCDF";
double time;
int dimids[3]; /* time, north, east */
size_t index; /* index of the time slice being dumped */
int ncid;
int ncstatus;
int timid;
int varid;
size_t count[3];
size_t start[3] = { 0, 0, 0 };
size_t timelen;
va_list ap;
MAPDUMP *DMap;
count[0] = 1;
count[1] = NY;
count[2] = NX;
/****************************************************************************/
/* GO THROUGH VARIABLE ARGUMENT LIST */
/****************************************************************************/
va_start(ap, NX);
DMap = va_arg(ap, MAPDUMP *);
index = va_arg(ap, int);
/****************************************************************************/
/* QUERY NETDCF FILE */
/****************************************************************************/
ncstatus = nc_open(FileName, NC_WRITE, &ncid);
nc_check_err(ncstatus, __LINE__, __FILE__);
/* get dimension ID's */
nc_inq_dimid(ncid, TIME_DIM, &(dimids[0]));
nc_check_err(ncstatus, __LINE__, __FILE__);
nc_inq_dimid(ncid, Y_DIM, &(dimids[1]));
nc_check_err(ncstatus, __LINE__, __FILE__);
nc_inq_dimid(ncid, X_DIM, &(dimids[2]));
nc_check_err(ncstatus, __LINE__, __FILE__);
/* see whether variable has been defined; if not defined, define it now */
ncstatus = nc_inq_varid(ncid, DMap->Name, &varid);
if (ncstatus == NC_ENOTVAR) { /* Variable not defined */
ncstatus = nc_redef(ncid);
nc_check_err(ncstatus, __LINE__, __FILE__);
ncstatus = nc_def_var(ncid, DMap->Name, DMap->NumberType, 3, dimids,
&varid);
nc_check_err(ncstatus, __LINE__, __FILE__);
/* write variable attributes */
ncstatus = nc_put_att_text(ncid, varid, ATT_NAME, strlen(DMap->Name),
DMap->Name);
nc_check_err(ncstatus, __LINE__, __FILE__);
ncstatus = nc_put_att_text(ncid, varid, ATT_LONGNAME,
strlen(DMap->LongName), DMap->LongName);
nc_check_err(ncstatus, __LINE__, __FILE__);
ncstatus = nc_put_att_text(ncid, varid, ATT_UNITS, strlen(DMap->Units),
DMap->Units);
nc_check_err(ncstatus, __LINE__, __FILE__);
ncstatus = nc_put_att_text(ncid, varid, ATT_FORMAT, strlen(DMap->Format),
DMap->Format);
nc_check_err(ncstatus, __LINE__, __FILE__);
ncstatus = nc_enddef(ncid);
nc_check_err(ncstatus, __LINE__, __FILE__);
}
else /* Variable defined */
nc_check_err(ncstatus, __LINE__, __FILE__);
/* see whether the time dimension needs to be updated (the assumption is that
the same index value refers to the same moment in time. Since currently we
make separate files for separate variables this is OK) */
ncstatus = nc_inq_dimlen(ncid, dimids[0], &timelen);
nc_check_err(ncstatus, __LINE__, __FILE__);
if (timelen < index + 1) { /* need to add one to time */
ncstatus = nc_inq_varid(ncid, TIME_DIM, &timid);
nc_check_err(ncstatus, __LINE__, __FILE__);
time = (double) index;
ncstatus = nc_put_var1_double(ncid, timid, &index, &time);
nc_check_err(ncstatus, __LINE__, __FILE__);
}
start[0] = index;
/****************************************************************************/
/* WRITE VARIABLE */
/****************************************************************************/
switch (NumberType) {
case NC_BYTE:
ncstatus = nc_put_vara_uchar(ncid, varid, start, count, Matrix);
break;
case NC_CHAR:
ncstatus = nc_put_vara_text(ncid, varid, start, count, Matrix);
break;
case NC_SHORT:
ncstatus = nc_put_vara_short(ncid, varid, start, count, Matrix);
break;
case NC_INT:
ncstatus = nc_put_vara_int(ncid, varid, start, count, Matrix);
break;
/* 8 bit integer not yet implemented in NetCDF 3.4, but anticipated in
future versions */
/* case NC_LONG: */
/* ncstatus = nc_put_vara_long(ncid, varid, start, count, Matrix); */
/* break; */
case NC_FLOAT:
ncstatus = nc_put_vara_float(ncid, varid, start, count, Matrix);
break;
case NC_DOUBLE:
ncstatus = nc_put_vara_double(ncid, varid, start, count, Matrix);
break;
default:
ReportError((char *) Routine, 40);
break;
}
nc_check_err(ncstatus, __LINE__, __FILE__);
/****************************************************************************/
/* CLEAN UP */
/****************************************************************************/
ncstatus = nc_close(ncid);
nc_check_err(ncstatus, __LINE__, __FILE__);
return NY * NX;
}
/*******************************************************************************
Function name: nc_check_err()
Purpose : Check status returned by NetCDF functions.
Required : int ncstatus - error status returned by NetCDF functions
Returns : void
Modifies : void
Comments :
*******************************************************************************/
static void nc_check_err(const int ncstatus, const int line, const char *file)
{
char str[BUFSIZE + 1];
if (ncstatus != NC_NOERR) {
sprintf(str, "%s, line: %d -- %s", file, line, nc_strerror(ncstatus));
ReportError((char *) str, 57);
}
}
/*******************************************************************************
Function name: GenerateHistory
Purpose : Generate a string documenting when and by whom a change was
made to the NetCDF file
Required : int argc - number of strings
char **argv - pointer to array of strings
char *History - history string
Returns : 0
Modifies : History string
Comments : Originally part of another series of programs for NetCDF. In
that case the command-line arguments were recorded in the
history.
*******************************************************************************/
static int GenerateHistory(int argc, char **argv, char *History)
{
int i;
char TimeStr[BUFSIZ];
time_t timer;
/* Get date and time in local time */
time(&timer);
strftime(TimeStr, (size_t) BUFSIZ, "%b %d, %Y %X %z", localtime(&timer));
strcpy(History, TimeStr);
/* add user name */
sprintf(History, "%s by %s:", History, getenv("LOGNAME"));
/* add command-line arguments */
for (i = 0; i < argc; i++)
sprintf(History, "%s %s", History, argv[i]);
return 0;
}
/*******************************************************************************
Function name: ncUpdateGlobalHistory
Purpose : Update the global history attribute or create one if it does
not exist.
Required : int argc - number of strings
char **argv - pointer to array of strings
int ncid - NetCDF file id
Returns : status (NC_NOERR if successful)
Modifies : History attribute
Comments : File has to be in define mode before calling ths function.
Originally part of another series of programs for NetCDF. In
that case the command-line arguments were recorded in the
history.
*******************************************************************************/
static int ncUpdateGlobalHistory(int argc, char **argv, int ncid)
{
char update[BUFSIZ + 1]; /* update string */
char *strOldHistory = NULL; /* pointer to old history string */
char *strNewHistory = NULL; /* pointer to new and improved history string */
int status = 0; /* return status */
size_t length; /* string length */
/* Create an update string */
GenerateHistory(argc, argv, update);
/* Query the NetCDF file to see if a history attribute is already present
The assumption here is that there is only one global history attribute,
and that the attribute name is all in lower case. The file is supposed to
be in define mode */
status = nc_inq_att(ncid, NC_GLOBAL, ATT_HISTORY, NULL, &length);
if (status == NC_ENOTATT) { /* no history attibrute present */
status = nc_put_att_text(ncid, NC_GLOBAL, ATT_HISTORY, strlen(update),
update);
nc_check_err(status, __LINE__, __FILE__);
}
else if (status == NC_NOERR) { /* history attribute present */
strOldHistory = calloc(length + 1, sizeof(char));
if (strOldHistory == NULL)
return 1;
status = nc_get_att_text(ncid, NC_GLOBAL, ATT_HISTORY, strOldHistory);
nc_check_err(status, __LINE__, __FILE__);
/* the NetCDF text is normally stored without the C string
terminator '\0'. So check whether it is present at the end
of the string, if not, append one. */
if (strOldHistory[length - 1] != '\0')
strOldHistory[length] = '\0';
/* place the newest string at the beginning */
strNewHistory = calloc(length + strlen(update) + 2, sizeof(char));
if (strNewHistory == NULL)
return 1;
sprintf(strNewHistory, "%s\n%s", update, strOldHistory);
status = nc_put_att_text(ncid, NC_GLOBAL, ATT_HISTORY,
strlen(strNewHistory), strNewHistory);
nc_check_err(status, __LINE__, __FILE__);
if (strOldHistory != NULL)
free(strOldHistory);
if (strNewHistory != NULL)
free(strNewHistory);
}
else
nc_check_err(status, __LINE__, __FILE__);
return status;
}
/*******************************************************************************
Test main. Compile by typing:
gcc -Wall -g -o test_netcdf -DTEST_FILEIONETCDF FileIONetCDF.c ReportError.c Files.c SizeOfNT.c VarID.c -lnetcdf
then run the program by typing test_netcdf
*******************************************************************************/
#ifdef TEST_FILEIONETCDF
int main(void)
{
char FileLabel[BUFSIZE + 1];
char *cReadArray;
char *cWriteArray;
float *ReadArray;
float *WriteArray;
int eflag = 0;
int i;
MAPSIZE Map;
MAPDUMP cDMap;
MAPDUMP DMap;
/****************************************************************************/
/* INITIALIZATION */
/****************************************************************************/
/* Fill the Map structure */
strcpy(Map.System, "Coordinate system");
Map.Xorig = 100.;
Map.Yorig = 100.;
Map.X = 0;
Map.Y = 0;
Map.NX = 4;
Map.NY = 6;
Map.DX = 5.;
Map.DY = 5.;
Map.DXY = 7.07;
Map.OffsetX = 0;
Map.OffsetY = 0;
/* Write floats */
DMap.ID = 404; /* Snow water equivalent */
DMap.Layer = 0;
DMap.Resolution = MAP_OUTPUT; /* Full resolution maps */
DMap.N = 2; /* Dump for two timesteps */
DMap.MinVal = 0; /* Not used for resolution MAP_OUTPUT */
DMap.MaxVal = 2; /* Not used for resolution MAP_OUTPUT */
strcpy(DMap.FileName, "test_netcdf_out.nc");
DMap.DumpDate = (DATE *) calloc(DMap.N, sizeof(DATE));
if (DMap.DumpDate == NULL)
ReportError("Testing NetCDF", 1);
DMap.DumpDate[0].Year = 1999;
DMap.DumpDate[0].Month = 12;
DMap.DumpDate[0].Day = 31;
DMap.DumpDate[0].JDay = 365;
DMap.DumpDate[0].Hour = 23;
DMap.DumpDate[1].Year = 2000;
DMap.DumpDate[1].Month = 1;
DMap.DumpDate[1].Day = 1;
DMap.DumpDate[1].JDay = 1;
DMap.DumpDate[1].Hour = 0;
MakeVarAttr(&DMap, FileLabel);
CreateMapFileNetCDF(DMap.FileName, FileLabel, &Map);
WriteArray = (float *) calloc(Map.NX * Map.NY, sizeof(float));
if (WriteArray == NULL)
ReportError("Testing NetCDF", 1);
for (i = 0; i < Map.NX * Map.NY; i++)
WriteArray[i] = (float) i;
Write2DMatrixNetCDF(DMap.FileName, (void *) WriteArray, DMap.NumberType,
Map.NY, Map.NX, &DMap, 0);
for (i = 0; i < Map.NX * Map.NY; i++)
WriteArray[i] = (float) i + Map.NX * Map.NY;
Write2DMatrixNetCDF(DMap.FileName, (void *) WriteArray, DMap.NumberType,
Map.NY, Map.NX, &DMap, 1);
for (i = 0; i < Map.NX * Map.NY; i++)
WriteArray[i] = (float) i + 2 * Map.NX * Map.NY;
Write2DMatrixNetCDF(DMap.FileName, (void *) WriteArray, DMap.NumberType,
Map.NY, Map.NX, &DMap, 0);
/* Write bytes */
cDMap.ID = 401; /* Snow water equivalent */
cDMap.Layer = 0;
cDMap.Resolution = MAP_OUTPUT; /* Full resolution maps */
cDMap.N = 2; /* Dump for two timesteps */
cDMap.MinVal = 0; /* Not used for resolution MAP_OUTPUT */
cDMap.MaxVal = 2; /* Not used for resolution MAP_OUTPUT */
strcpy(cDMap.FileName, "test_netcdf_out.nc");
cDMap.DumpDate = (DATE *) calloc(cDMap.N, sizeof(DATE));
if (cDMap.DumpDate == NULL)
ReportError("Testing NetCDF", 1);
cDMap.DumpDate[0].Year = 1999;
cDMap.DumpDate[0].Month = 12;
cDMap.DumpDate[0].Day = 31;
cDMap.DumpDate[0].JDay = 365;
cDMap.DumpDate[0].Hour = 23;
cDMap.DumpDate[1].Year = 2000;
cDMap.DumpDate[1].Month = 1;
cDMap.DumpDate[1].Day = 1;
cDMap.DumpDate[1].JDay = 1;
cDMap.DumpDate[1].Hour = 0;
MakeVarAttr(&cDMap, FileLabel);
cWriteArray = (char *) calloc(Map.NX * Map.NY, sizeof(char));
if (cWriteArray == NULL)
ReportError("Testing NetCDF", 1);
for (i = 0; i < Map.NX * Map.NY; i++)
cWriteArray[i] = (char) i;
Write2DMatrixNetCDF(cDMap.FileName, (void *) cWriteArray, cDMap.NumberType,
Map.NY, Map.NX, &cDMap, 0);
/* Try reading the datasets just written and make sure they make sense */
ReadArray = (float *) calloc(Map.NX * Map.NY, sizeof(float));
if (ReadArray == NULL)
ReportError("Testing NetCDF", 1);
cReadArray = (char *) calloc(Map.NX * Map.NY, sizeof(char));
if (cReadArray == NULL)
ReportError("Testing NetCDF", 1);
printf("Reading %s from %s ...\n", DMap.Name, DMap.FileName);
Read2DMatrixNetCDF(DMap.FileName, (void *) ReadArray, DMap.NumberType,
Map.NY, Map.NX, 0, DMap.Name);
printf("... read succesfull\n\n");
for (i = 0; i < Map.NX * Map.NY; i++) {
if (WriteArray[i] - ReadArray[i] != 0)
break;
}
if (i != Map.NX * Map.NY) {
eflag++;
fprintf(stderr, "Comparison failed for element %d\n", i);
fprintf(stderr, "Written value %f : Read value %f\n",
WriteArray[i], ReadArray[i]);
}
printf("Reading %s from %s ...\n", cDMap.Name, cDMap.FileName);
Read2DMatrixNetCDF(cDMap.FileName, (void *) cReadArray, cDMap.NumberType,
Map.NY, Map.NX, 0, cDMap.Name);
printf("... read succesfull\n\n");
for (i = 0; i < Map.NX * Map.NY; i++) {
if (cWriteArray[i] - cReadArray[i] != 0)
break;
}
if (i != Map.NX * Map.NY) {
eflag++;
fprintf(stderr, "Comparison failed for element %d\n", i);
fprintf(stderr, "Written value %d : Read value %d\n",
cWriteArray[i], cReadArray[i]);
}
if (eflag == 0)
printf("Test successful\n");
return EXIT_SUCCESS;
}
#endif
#endif