forked from Amber-MD/cpptraj
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNetcdfFile.cpp
More file actions
1806 lines (1734 loc) · 62.5 KB
/
NetcdfFile.cpp
File metadata and controls
1806 lines (1734 loc) · 62.5 KB
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
#include "NetcdfFile.h"
#ifdef BINTRAJ
#include <netcdf.h>
#include <cstring> // strlen
#include <cmath> // round
#ifdef HAS_HDF5
# include <limits> // for integer compression
#endif
#ifdef MPI
# include "ParallelNetcdf.h"
#endif
#include "CpptrajStdio.h"
#include "Constants.h"
#include "Version.h"
#include "Frame.h"
// DEFINES
#define NCENSEMBLE "ensemble"
#define NCFRAME "frame"
#define NCSPATIAL "spatial"
#define NCATOM "atom"
#define NCCELL_SPATIAL "cell_spatial"
#define NCCELL_LENGTHS "cell_lengths"
#define NCCELL_ANGULAR "cell_angular"
#define NCCELL_ANGLES "cell_angles"
#define NCCOORDS "coordinates"
#define NCVELO "velocities"
#define NCFRC "forces"
#define NCTEMPERATURE "temp0"
#define NCTIME "time"
#define NCLABEL "label"
#define NCLABELLEN 5
#define NCREMD_DIMENSION "remd_dimension"
#define NCREMD_DIMTYPE "remd_dimtype"
#define NCREMD_INDICES "remd_indices"
#define NCREMD_REPIDX "remd_repidx"
#define NCREMD_CRDIDX "remd_crdidx"
#define NCEPTOT "eptot"
#define NCBINS "bins"
#define NCREMDVALUES "remd_values"
#define NCCOMPPOS "compressedpos"
#define NCCOMPVEL "compressedvel"
#define NCCOMPFRC "compressedfrc"
#define NCICOMPFAC "icompressfac"
// CONSTRUCTOR
NetcdfFile::NetcdfFile() :
ncid_(-1),
ncframe_(-1),
TempVID_(-1),
coordVID_(-1),
velocityVID_(-1),
frcVID_(-1),
cellAngleVID_(-1),
cellLengthVID_(-1),
timeVID_(-1),
remd_dimension_(0),
indicesVID_(-1),
repidxVID_(-1),
crdidxVID_(-1),
ensembleSize_(0),
compressedPosVID_(-1),
compressedVelVID_(-1),
compressedFrcVID_(-1),
fchunkSize_(1),
ishuffle_(-1),
# ifdef HAS_HDF5
deflateLevels_((unsigned int)NVID, 0),
intCompressFac_((unsigned int)NVID, 0),
# endif
ncdebug_(0),
frameDID_(-1),
atomDID_(-1),
ncatom_(-1),
ncatom3_(-1),
spatialDID_(-1),
labelDID_(-1),
cell_spatialDID_(-1),
cell_angularDID_(-1),
spatialVID_(-1),
cell_spatialVID_(-1),
cell_angularVID_(-1),
RemdValuesVID_(-1)
{
start_[0] = 0;
start_[1] = 0;
start_[2] = 0;
count_[0] = 0;
count_[1] = 0;
count_[2] = 0;
}
/*
// NetcdfFile::GetNetcdfConventions()
NetcdfFile::NCTYPE NetcdfFile::GetNetcdfConventions(int ncidIn) {
NCTYPE nctype = NC_UNKNOWN;
std::string attrText = NC::GetAttrText(ncidIn, "Conventions");
if (attrText.empty()) {
// Check if this is an MDtraj h5 file
attrText = NC::GetAttrText(ncidIn, "conventions");
if (attrText.empty()) {
# ifdef HAS_HDF5
// Check if this is an MDAnalysis h5md file
bool is_h5md = false;
std::vector<std::string> GroupNames = NC::GetGroupNames( ncidIn );
if (!GroupNames.empty()) {
for (std::vector<std::string>::const_iterator it = GroupNames.begin();
it != GroupNames.end(); ++it)
{
if (*it == "h5md") {
mprintf("DEBUG: H5MD detected.\n");
is_h5md = true;
break;
}
}
}
if (!is_h5md)
mprinterr("Error: Could not get conventions from NetCDF file.\n");
# endif
return NC_UNKNOWN;
}
//mprintf("DEBUG: This appears to be an HDF5 h5 file.\n");
return NC_UNKNOWN;
}
// Identify the conventions string
for (int i = 0; i < (int)NC_UNKNOWN; i++) {
if (attrText.compare( ConventionsStr_[i] ) == 0) {
nctype = (NCTYPE)i;
break;
}
}
if (nctype == NC_UNKNOWN) {
mprinterr("Error: NetCDF file has unrecognized conventions \"%s\".\n",
attrText.c_str());
mprinterr("Error: Expected one of");
for (int i = 0; i < (int)NC_UNKNOWN; i++)
mprintf(" \"%s\"", ConventionsStr_[i]);
mprinterr("\n");
}
return nctype;
}
*/
// NetcdfFile::CheckConventionsVersion()
void NetcdfFile::CheckConventionsVersion() {
std::string attrText = NC::GetAttrText(ncid_, "ConventionVersion");
if ( attrText != "1.0")
mprintf("Warning: NetCDF file has ConventionVersion that is not 1.0 (%s)\n", attrText.c_str());
}
// -----------------------------------------------------------------------------
/** \return true if temperature VID is defined or a replica dimension is temperature.
*/
bool NetcdfFile::HasTemperatures() const {
if (TempVID_ != -1)
return true;
else if (!remValType_.empty()) {
for (int idx = 0; idx != remValType_.Ndims(); idx++)
if (remValType_.DimType(idx) == ReplicaDimArray::TEMPERATURE)
return true;
}
return false;
}
/** \return true if a replica dimension is pH. TODO put inside ReplicaDimArray
*/
bool NetcdfFile::Has_pH() const {
if (!remValType_.empty()) {
for (int idx = 0; idx != remValType_.Ndims(); idx++)
if (remValType_.DimType(idx) == ReplicaDimArray::PH)
return true;
}
return false;
}
/** \return true if a replica dimension is RedOx.
*/
bool NetcdfFile::HasRedOx() const {
if (!remValType_.empty()) {
for (int idx = 0; idx != remValType_.Ndims(); idx++)
if (remValType_.DimType(idx) == ReplicaDimArray::REDOX)
return true;
}
return false;
}
// NetcdfFile::SetupFrameDim()
/** Get the frame dimension ID and # of frames (ncframe). */
int NetcdfFile::SetupFrameDim() {
frameDID_ = NC::GetDimInfo( ncid_, NCFRAME, ncframe_ );
if (frameDID_==-1) return 1;
return 0;
}
/** Get the ensemble dimension ID and size. */
int NetcdfFile::SetupEnsembleDim() {
ensembleSize_ = 0;
ensembleDID_ = NC::GetDimInfo( ncid_, NCENSEMBLE, ensembleSize_ );
if (ensembleDID_ == -1) return 0;
return ensembleSize_;
}
// NetcdfFile::SetupCoordsVelo()
/** Setup ncatom, ncatom3, atomDID, coordVID, spatialDID, spatialVID,
* velocityVID, frcVID. Check units and spatial dimensions.
*/
int NetcdfFile::SetupCoordsVelo(bool useVelAsCoords, bool useFrcAsCoords) {
if (useVelAsCoords && useFrcAsCoords) {
mprinterr("Error: Cannot use both velocities and forces as coords - specify one only.\n");
return 1;
}
// Get spatial info
int spatial;
spatialDID_ = NC::GetDimInfo( ncid_, NCSPATIAL, spatial );
if (spatialDID_ == -1) return 1;
if (spatial != 3) {
mprinterr("Error: Expected 3 spatial dimensions, got %i\n",spatial);
return 1;
}
if ( NC::CheckErr(nc_inq_varid(ncid_, NCSPATIAL, &spatialVID_)) ) {
mprintf("Warning: Could not get spatial VID. File may not be Amber NetCDF compliant.\n");
mprintf("Warning: Assuming spatial variables are 'x', 'y', 'z'\n");
} else {
start_[0] = 0;
count_[0] = 3;
char xyz[3];
if (NC::CheckErr(nc_get_vara_text(ncid_, spatialVID_, start_, count_, xyz))) {
mprinterr("Error: Getting spatial variables.\n");
return 1;
}
if (xyz[0] != 'x' || xyz[1] != 'y' || xyz[2] != 'z') {
mprinterr("Error: NetCDF spatial variables are '%c', '%c', '%c', not 'x', 'y', 'z'\n",
xyz[0], xyz[1], xyz[2]);
return 1;
}
}
// Get atoms info
atomDID_ = NC::GetDimInfo( ncid_, NCATOM, ncatom_ );
if (atomDID_==-1) return 1;
ncatom3_ = ncatom_ * 3;
# ifdef HAS_HDF5
unsigned int needed_itmp_size = 0;
# endif
bool has_coordinates = false;
bool has_velocities = false;
bool has_forces = false;
// Get coord info
coordVID_ = -1;
if ( nc_inq_varid(ncid_, NCCOORDS, &coordVID_) == NC_NOERR ) {
if (ncdebug_ > 0) mprintf("\tNetCDF file has coordinates.\n");
std::string attrText = NC::GetAttrText(ncid_, coordVID_, "units");
if (attrText!="angstrom")
mprintf("Warning: NetCDF file has length units of %s - expected angstrom.\n",
attrText.c_str());
has_coordinates = true;
}
// Get compressed coord info
compressedPosVID_ = -1;
if ( nc_inq_varid(ncid_, NCCOMPPOS, &compressedPosVID_) == NC_NOERR ) {
if (ncdebug_ > 0) mprintf("\tNetCDF file has integer-compressed coordinates.\n");
# ifdef HAS_HDF5
// Get integer compression factor
if (NC::CheckErr(nc_get_att_double(ncid_, compressedPosVID_, NCICOMPFAC, (&intCompressFac_[0])+V_COORDS))) {
mprinterr("Error: Could not get integer compression factor attribute for COORDS.\n");
return 1;
}
mprintf("\tCoordinates are integer-compressed with factor: %g\n", intCompressFac_[V_COORDS]);
needed_itmp_size = Ncatom3();
has_coordinates = true;
# else /* HAS_HDF5 */
mprinterr("Error: Integer-compressed NetCDF trajectories requires cpptraj compiled with HDF5 support.\n");
return 1;
# endif /* HAS_HDF5 */
}
// Get velocity info
velocityVID_ = -1;
if ( nc_inq_varid(ncid_, NCVELO, &velocityVID_) == NC_NOERR ) {
if (ncdebug_>0) mprintf("\tNetCDF file has velocities.\n");
has_velocities = true;
}
// Get compressed velocity info
compressedVelVID_ = -1;
if ( nc_inq_varid(ncid_, NCCOMPVEL, &compressedVelVID_) == NC_NOERR ) {
if (ncdebug_ > 0) mprintf("\tNetCDF file has integer-compressed velocities.\n");
# ifdef HAS_HDF5
// Get integer compression factor
if (NC::CheckErr(nc_get_att_double(ncid_, compressedVelVID_, NCICOMPFAC, (&intCompressFac_[0])+V_VEL))) {
mprinterr("Error: Could not get integer compression factor attribute for VEL.\n");
return 1;
}
mprintf("\tVelocities are integer-compressed with factor: %g\n", intCompressFac_[V_VEL]);
needed_itmp_size = Ncatom3();
has_velocities = true;
# else /* HAS_HDF5 */
mprinterr("Error: Integer-compressed NetCDF trajectories requires cpptraj compiled with HDF5 support.\n");
return 1;
# endif /* HAS_HDF5 */
}
// Get force info
frcVID_ = -1;
if ( nc_inq_varid(ncid_, NCFRC, &frcVID_) == NC_NOERR ) {
if (ncdebug_>0) mprintf("\tNetCDF file has forces.\n");
has_forces = true;
}
// Get compressed force info
compressedFrcVID_ = -1;
if ( nc_inq_varid(ncid_, NCCOMPFRC, &compressedFrcVID_) == NC_NOERR ) {
if (ncdebug_ > 0) mprintf("\tNetCDF file has integer-compressed forces.\n");
# ifdef HAS_HDF5
// Get integer compression factor
if (NC::CheckErr(nc_get_att_double(ncid_, compressedFrcVID_, NCICOMPFAC, (&intCompressFac_[0])+V_FRC))) {
mprinterr("Error: Could not get integer compression factor attribute for FRC.\n");
return 1;
}
mprintf("\tForces are integer-compressed with factor: %g\n", intCompressFac_[V_FRC]);
needed_itmp_size = Ncatom3();
has_forces = true;
# else /* HAS_HDF5 */
mprinterr("Error: Integer-compressed NetCDF trajectories requires cpptraj compiled with HDF5 support.\n");
return 1;
# endif /* HAS_HDF5 */
}
# ifdef HAS_HDF5
// Allocate temporary space for integer array if needed
if (needed_itmp_size > 0)
itmp_.resize( needed_itmp_size );
# endif
// Return a error if no coords, velocities, or forces
if ( !has_coordinates && !has_velocities && !has_forces ) {
mprinterr("Error: NetCDF file has no coordinates, velocities, or forces.\n");
return 1;
}
// If using velocities/forces as coordinates, swap them now.
if (useVelAsCoords) {
if (velocityVID_ != -1) {
coordVID_ = velocityVID_;
velocityVID_ = -1;
# ifdef HAS_HDF5
} else if (compressedVelVID_ != -1) {
compressedPosVID_ = compressedVelVID_;
compressedVelVID_ = -1;
intCompressFac_[V_COORDS] = intCompressFac_[V_VEL];
# endif
} else {
mprinterr("Error: Cannot use velocities as coordinates; no velocities present.\n");
return 1;
}
mprintf("\tUsing velocities as coordinates.\n");
} else if (useFrcAsCoords) {
if (frcVID_ != -1) {
coordVID_ = frcVID_;
frcVID_ = -1;
# ifdef HAS_HDF5
} else if (compressedFrcVID_ != -1) {
compressedPosVID_ = compressedFrcVID_;
compressedFrcVID_ = -1;
intCompressFac_[V_COORDS] = intCompressFac_[V_FRC];
# endif
} else {
mprinterr("Error: Cannot use forces as coordinates; no forces present.\n");
return 1;
}
mprintf("\tUsing forces as coordinates.\n");
}
// Get overall replica and coordinate indices
crdidxVID_ = -1;
if ( nc_inq_varid(ncid_, NCREMD_REPIDX, &repidxVID_) == NC_NOERR ) {
if (ncdebug_>0) mprintf("\tNetCDF file has overall replica indices.\n");
if ( NC::CheckErr(nc_inq_varid(ncid_, NCREMD_CRDIDX, &crdidxVID_)) ) {
mprinterr("Error: Getting overall coordinate index variable ID.\n");
return 1;
}
} else
repidxVID_ = -1;
return 0;
}
// NetcdfFile::SetupTime()
/** Determine if Netcdf file contains time; set up timeVID and check units. */
int NetcdfFile::SetupTime() {
if ( nc_inq_varid(ncid_, NCTIME, &timeVID_) == NC_NOERR ) {
std::string attrText = NC::GetAttrText(ncid_, timeVID_, "units");
if (attrText!="picosecond")
mprintf("Warning: NetCDF file has time units of %s - expected picosecond.\n",
attrText.c_str());
// Check for time values which have NOT been filled, which was possible
// with netcdf trajectories created by older versions of ptraj/cpptraj.
if (ncframe_ > 0 && myType_ == NC::NC_AMBERTRAJ) {
float time;
start_[0] = 0; count_[0] = 1;
if (NC::CheckErr(nc_get_vara_float(ncid_, timeVID_, start_, count_, &time))) {
mprinterr("Error: Getting time value for NetCDF file.\n");
return -1;
}
if (time == NC_FILL_FLOAT) {
mprintf("Warning: NetCDF file time variable defined but empty. Disabling.\n");
timeVID_ = -1;
} else {
// If first 2 values are 0, this is another indication of a bad time variable.
if (ncframe_ > 1) {
float time1;
start_[0] = 1;
if (NC::CheckErr(nc_get_vara_float(ncid_, timeVID_, start_, count_, &time1))) {
mprinterr("Error: Getting second time value for NetCDF file.\n");
return -1;
}
if (time1 == 0 && time1 == time)
{
mprintf("Warning: NetCDF file time variable defined but all zero. Disabling.\n");
timeVID_ = -1;
}
}
}
}
return 0;
}
timeVID_=-1;
return 1;
}
// NetcdfFile::SetupTemperature()
/** Determine if Netcdf file contains temperature; set up temperature VID. */
void NetcdfFile::SetupTemperature() {
TempVID_ = -1;
if ( nc_inq_varid(ncid_, NCTEMPERATURE, &TempVID_) == NC_NOERR ) {
if (ncdebug_ > 0) mprintf("\tNetCDF file has replica temperatures.\n");
}
}
// NetcdfFile::SetupMultiD()
/** Determine if Netcdf file contains multi-D REMD info. If so set the
* number of replica dimensions (remd_dimension_) and figure out
* the dimension types (remdDim)
*/
int NetcdfFile::SetupMultiD() {
int dimensionDID;
remd_dimension_ = 0;
if ( nc_inq_dimid(ncid_, NCREMD_DIMENSION, &dimensionDID) == NC_NOERR)
{
// Although this is a second call to dimid, makes for easier code
if ( (dimensionDID = NC::GetDimInfo(ncid_, NCREMD_DIMENSION, remd_dimension_))==-1 )
return -1;
if (ncdebug_ > 0)
mprintf("\tNetCDF file has multi-D REMD info, %i dimensions.\n",remd_dimension_);
// Ensure valid # dimensions
if (remd_dimension_ < 1) {
if (ncdebug_ > 0)
mprintf("\tNumber of REMD dimensions is less than 1.\n");
remd_dimension_ = 0;
} else {
// Start and count for groupnum and dimtype, allocate mem
start_[0]=0;
start_[1]=0;
start_[2]=0;
count_[0]=remd_dimension_;
count_[1]=0;
count_[2]=0;
std::vector<int> remd_dimtype( remd_dimension_ );
// Get dimension types
int dimtypeVID;
if ( NC::CheckErr(nc_inq_varid(ncid_, NCREMD_DIMTYPE, &dimtypeVID)) ) {
mprinterr("Error: Getting dimension type variable ID for each dimension.\n");
return -1;
}
if ( NC::CheckErr(nc_get_vara_int(ncid_, dimtypeVID, start_, count_, &remd_dimtype[0])) ) {
mprinterr("Error: Getting dimension type in each dimension.\n");
return -1;
}
// Get VID for replica indices
if ( NC::CheckErr(nc_inq_varid(ncid_, NCREMD_INDICES, &indicesVID_)) ) {
mprinterr("Error: Getting replica indices variable ID.\n");
return -1;
}
// Store type of each dimension TODO should just have one netcdf coordinfo
remDimType_.clear();
for (int dim = 0; dim < remd_dimension_; ++dim)
remDimType_.AddRemdDimension( remd_dimtype[dim] );
}
}
// Get VID for replica values
if ( nc_inq_varid(ncid_, NCREMDVALUES, &RemdValuesVID_) == NC_NOERR ) {
if (ncdebug_ > 0) mprintf("\tNetCDF file has replica values.\n");
remValType_.clear();
if (remd_dimension_ > 0) {
remValType_ = remDimType_;
} else {
// Probably 1D
int ndims = 0;
if (NC::CheckErr(nc_inq_varndims(ncid_, RemdValuesVID_, &ndims))) {
mprinterr("Error: Checking number of dimensions for REMD_VALUES.\n");
return 1;
}
if (ndims < 2) {
mprintf("Warning: New style (Amber >= V18) remd values detected with < 2 dimensions.\n"
"Warning: Assuming temperature.\n");
remValType_.AddRemdDimension( ReplicaDimArray::TEMPERATURE );
} else {
mprinterr("Error: New style (Amber >= V18) remd values detected with > 1 dimension\n"
"Error: but no multi-D replica info present.\n");
return 1;
}
}
RemdValues_.assign( remValType_.Ndims(), 0 );
}
return 0;
}
// NetcdfFile::SetupBox()
/** \return 0 on success, 1 on error, -1 for no box coords. */
int NetcdfFile::SetupBox() {
nc_box_.SetNoBox();
if ( nc_inq_varid(ncid_, NCCELL_LENGTHS, &cellLengthVID_) == NC_NOERR ) {
if (NC::CheckErr( nc_inq_varid(ncid_, NCCELL_ANGLES, &cellAngleVID_) )) {
mprinterr("Error: Getting cell angles.\n");
return 1;
}
if (ncdebug_ > 0) mprintf("\tNetCDF Box information found.\n");
// If present, get box angles. These will be used to determine the box
// type in TrajectoryFile.
start_[0]=0;
start_[1]=0;
start_[2]=0;
start_[3]=0;
switch (myType_) {
case NC::NC_AMBERRESTART:
count_[0]=3;
count_[1]=0;
count_[2]=0;
break;
case NC::NC_AMBERTRAJ:
count_[0]=1;
count_[1]=3;
count_[2]=0;
break;
case NC::NC_AMBERENSEMBLE:
count_[0]=1; // NOTE: All ensemble members must have same box type
count_[1]=1; // TODO: Check all members?
count_[2]=3;
break;
default: return 1; // Sanity check
}
count_[3]=0;
double boxCrd[6]; /// XYZ ABG
if ( NC::CheckErr(nc_get_vara_double(ncid_, cellLengthVID_, start_, count_, boxCrd )) )
{
mprinterr("Error: Getting cell lengths.\n");
return 1;
}
if ( NC::CheckErr(nc_get_vara_double(ncid_, cellAngleVID_, start_, count_, boxCrd+3)) )
{
mprinterr("Error: Getting cell angles.\n");
return 1;
}
if (ncdebug_ > 0) mprintf("\tNetCDF Box: XYZ={%f %f %f} ABG={%f %f %f}\n",
boxCrd[0], boxCrd[1], boxCrd[2], boxCrd[3], boxCrd[4], boxCrd[5]);
if (nc_box_.SetupFromXyzAbg( boxCrd )) {
mprintf("Warning: NetCDF file unit cell variables appear to be empty; disabling box.\n");
cellLengthVID_ = -1;
cellAngleVID_ = -1;
nc_box_.SetNoBox();
return -1;
}
return 0;
}
// No box information
return -1;
}
/** Read REMD related values. */
int NetcdfFile::ReadRemdValues(Frame& frm) {
// FIXME assuming start_ is set
count_[0] = 1; // 1 frame
if ( repidxVID_ != -1)
nc_get_vara_int(ncid_, repidxVID_, start_, count_, frm.repidxPtr());
if ( crdidxVID_ != -1)
nc_get_vara_int(ncid_, crdidxVID_, start_, count_, frm.crdidxPtr());
if ( RemdValuesVID_ != -1 ) {
count_[1] = remd_dimension_; // # dimensions
if ( NC::CheckErr(nc_get_vara_double(ncid_, RemdValuesVID_, start_, count_, &RemdValues_[0])) )
{
mprinterr("Error: Getting replica values\n");
return 1;
}
for (int idx = 0; idx != remValType_.Ndims(); ++idx)
{
if (remValType_.DimType(idx) == ReplicaDimArray::TEMPERATURE) {
frm.SetTemperature( RemdValues_[idx] );
//mprintf("DEBUG: T= %g\n", frm.Temperature());
} else if (remValType_.DimType(idx) == ReplicaDimArray::PH) {
frm.Set_pH( RemdValues_[idx] );
//mprintf("DEBUG: pH= %g\n", frm.pH());
} else if (remValType_.DimType(idx) == ReplicaDimArray::REDOX) {
frm.SetRedOx( RemdValues_[idx] );
//mprintf("DEBUG: RedOx= %g\n", frm.RedOx());
} else
mprinterr("Internal Error: NetcdfFile::ReadRemdValues(): Unhandled remd value read for dim %i (%s)\n", idx, ReplicaDimArray::dimType(remValType_.DimType(idx)));
}
}
return 0;
}
/** Set up a NetCDF file for reading. */
int NetcdfFile::NC_setupRead(std::string const& fname, NC::ConventionsType expectedType, int expectedNatoms,
bool useVelAsCoords, bool useFrcAsCoords, int debugIn)
{
ncdebug_ = debugIn;
// If file is open, close it.
if (ncid_ != -1) NC_close();
// Open read
if (NC_openRead( fname.c_str() ) != 0) {
mprinterr("Error: Could not open NetCDF file '%s' for read setup.\n", fname.c_str());
return 1;
}
// Sanity check
myType_ = NC::GetConventions(ncid_);
if ( myType_ != expectedType ) {
mprinterr("Error: NetCDF file conventions do not include \"%s\"\n",
NC::conventionsStr(expectedType));
return 1;
}
// This will warn if conventions are not 1.0
CheckConventionsVersion();
// Get the title
nctitle_ = NC::GetAttrText(ncid_, "title");
// Get frame info if necessary.
if (myType_ == NC::NC_AMBERTRAJ || myType_ == NC::NC_AMBERENSEMBLE) {
if (SetupFrameDim() != 0) return 1;
if (Ncframe() < 1) {
mprinterr("Error: NetCDF file has no frames.\n");
return 1;
}
// Get ensemble info if necessary
if (myType_ == NC::NC_AMBERENSEMBLE) {
if (SetupEnsembleDim() < 1) {
mprinterr("Error: Could not get ensemble dimension info.\n");
return 1;
}
}
}
// Setup atom-dimension-related variables.
if ( SetupCoordsVelo( useVelAsCoords, useFrcAsCoords ) != 0 ) return 1;
// Check that specified number of atoms matches expected number.
if (Ncatom() != expectedNatoms) {
mprinterr("Error: Number of atoms in NetCDF file (%i) does not match number\n"
"Error: in associated topology (%i)!\n", Ncatom(), expectedNatoms);
return 1;
}
// Setup Time - FIXME: Allowed to fail silently
SetupTime();
// Box info
if (SetupBox() == 1) // 1 indicates an error
return 1;
// Replica Temperatures - FIXME: Allowed to fail silently
SetupTemperature();
// Replica Dimensions
if ( SetupMultiD() == -1 ) return 1;
// NOTE: TO BE ADDED
// labelDID;
//int cell_spatialDID, cell_angularDID;
//int spatialVID, cell_spatialVID, cell_angularVID;
if (ncdebug_ > 1) NC::Debug(ncid_);
NC_close();
return 0;
}
/** \return Coordinate info corresponding to current setup. */
CoordinateInfo NetcdfFile::NC_coordInfo() const {
// TODO the 'false' is for step info. Enable this in the future when time
// is present.
return CoordinateInfo( ensembleSize_, remDimType_, nc_box_,
HasCoords(), HasVelocities(), HasForces(),
HasTemperatures(), Has_pH(), HasRedOx(),
HasTimes(), false, (repidxVID_ != -1), (crdidxVID_ != -1),
(RemdValuesVID_ != -1) );
}
// NetcdfFile::NC_openRead()
int NetcdfFile::NC_openRead(std::string const& Name) {
if (Name.empty()) return 1;
if ( NC::CheckErr( nc_open( Name.c_str(), NC_NOWRITE, &ncid_ ) ) )
return 1;
return 0;
}
// NetcdfFile::NC_close()
void NetcdfFile::NC_close() {
if (ncid_ == -1) return;
bool err = NC::CheckErr( nc_close(ncid_) );
if (ncdebug_ > 0 && !err)
mprintf("Successfully closed ncid %i\n",ncid_);
ncid_ = -1;
}
// =============================================================================
// NetcdfFile::NC_openWrite()
int NetcdfFile::NC_openWrite(std::string const& Name) {
if (Name.empty()) return 1;
if ( NC::CheckErr( nc_open( Name.c_str(), NC_WRITE, &ncid_ ) ) )
return 1;
return 0;
}
// NetcdfFile::NC_createReservoir()
int NetcdfFile::NC_createReservoir(bool hasBins, double reservoirT, int iseed,
int& eptotVID, int& binsVID)
{
int dimensionID[1];
dimensionID[0] = frameDID_;
if (ncid_ == -1 || dimensionID[0] == -1) return 1;
// Place file back in define mode
if ( NC::CheckErr( nc_redef( ncid_ ) ) ) return 1;
// Define eptot, bins, temp0
if ( NC::CheckErr( nc_def_var(ncid_, NCEPTOT, NC_DOUBLE, 1, dimensionID, &eptotVID)) ) {
mprinterr("Error: defining eptot variable ID.\n");
return 1;
}
if (hasBins) {
if ( NC::CheckErr( nc_def_var(ncid_, NCBINS, NC_INT, 1, dimensionID, &binsVID)) ) {
mprinterr("Error: defining bins variable ID.\n");
return 1;
}
} else
binsVID = -1;
if (NC_defineTemperature(dimensionID, 0)) return 1;
// Random seed, make global
if ( NC::CheckErr( nc_put_att_int(ncid_, NC_GLOBAL, "iseed", NC_INT, 1, &iseed) ) ) {
mprinterr("Error: setting random seed attribute.\n");
return 1;
}
// End definitions
if (NC::CheckErr(nc_enddef(ncid_))) {
mprinterr("NetCDF error on ending definitions.");
return 1;
}
// Write temperature
if (NC::CheckErr(nc_put_var_double(ncid_,TempVID_,&reservoirT)) ) {
mprinterr("Error: Writing reservoir temperature.\n");
return 1;
}
return 0;
}
/** Set remDimDID appropriate for given type. */
void NetcdfFile::SetRemDimDID(int remDimDID, int* dimensionID) const {
switch (myType_) {
case NC::NC_AMBERENSEMBLE:
dimensionID[0] = frameDID_;
dimensionID[1] = ensembleDID_;
dimensionID[2] = remDimDID;
break;
case NC::NC_AMBERTRAJ:
dimensionID[0] = frameDID_;
dimensionID[1] = remDimDID;
break;
case NC::NC_AMBERRESTART:
dimensionID[0] = remDimDID;
break;
default:
mprinterr("Internal Error: SetRemDimDID(): Unrecognized type.\n");
}
}
/** Variable ID descriptions. */
const char* NetcdfFile::vidDesc_[NVID] = {
"coordinates", // V_COORDS
"velocities", // V_VEL
"forces", // V_FRC
"temp0", // V_TEMP
"cell_lengths", // V_BOXL
"cell_angles", // V_BOXA
"time", // V_TIME
"remd_indices", // V_IND
"remd_repidx", // V_RIDX
"remd_crdidx", // V_CIDX
"remd_values" // V_REMDVALS
};
/** Dimension ID descriptions. */
const char* NetcdfFile::didDesc_[NDID] = {
"frame", // D_FRAME
"atom", // D_ATOM
"spatial" // D_SPATIAL
};
// -----------------------------------------------------------------------------
// This section contains HDF5-related functionality
/** Set variable compression level (and integer shuffle) if supported. */
int NetcdfFile::NC_setDeflate(VidType vtype, int varid, int ishuffleIn) const
{
# ifdef HAS_HDF5
if (deflateLevels_[vtype] > 0) {
if (ncdebug_ > 0)
mprintf("DEBUG: Setting deflate level for '%s' to %i (ishuffle=%i)\n",
vidDesc_[vtype], deflateLevels_[vtype], ishuffleIn);
if ( NC::CheckErr( nc_def_var_deflate(ncid_, varid, ishuffleIn, 1, deflateLevels_[vtype]) ) ) {
mprinterr("Error: Setting compression for '%s' variable.\n", vidDesc_[vtype]);
return 1;
}
}
# else
mprintf("Warning: Setting NetCDF variable compression requires compiling with HDF5 support.\n");
# endif
return 0;
}
/** Set variable compression level with integer shuffle off. */
int NetcdfFile::NC_setDeflate(VidType vtype, int varid) const {
return NC_setDeflate(vtype, varid, 0);
}
/** Increase frame chunk size for variable if supported. */
int NetcdfFile::NC_setFrameChunkSize(VidType vtype, int varid) const
{
# ifdef HAS_HDF5
if (fchunkSize_ > 1) {
// Get number of dimensions
int ndims = 0;
if ( NC::CheckErr( nc_inq_varndims(ncid_, varid, &ndims) ) ) {
mprinterr("Error: getting # dims for '%s' variable.\n", vidDesc_[vtype]);
return 1;
}
if (ndims < 1) {
mprintf("Warning: NC_setFrameChunkSize: Variable '%s' has no dimensions.\n",
vidDesc_[vtype]);
return 0;
}
// Get dimension IDs
std::vector<int> dimids(ndims);
if ( NC::CheckErr( nc_inq_var(ncid_, varid, 0, 0, 0, &dimids[0], 0) ) ) {
mprinterr("Error: getting dimension IDs for '%s' variable.\n", vidDesc_[vtype]);
return 1;
}
// Allocate space for chunk sizes
std::vector<size_t> chunkSizes( ndims );
// Set frame chunk size
int err = NC_setVarDimChunkSizes(vtype, varid, fchunkSize_, dimids, frameDID_, chunkSizes);
return err;
}
# else
mprintf("Warning: Setting NetCDF frame chunk size requires compiling with HDF5 support.\n");
# endif
return 0;
}
# ifdef HAS_HDF5
/** Set desired compression level for specified variable if supported. */
int NetcdfFile::setDesiredCompression(VidType vtype, int deflateLevelIn) {
if (ncdebug_ > 0)
mprintf("DEBUG: Setting desired compression for VIDTYPE %s to %i\n", vidDesc_[vtype], deflateLevelIn);
deflateLevels_[vtype] = deflateLevelIn;
return 0;
}
/** Set desired compression level for all variables if supported. */
int NetcdfFile::SetupCompression(int deflateLevelIn, int icompressIn, int ishuffleIn) {
mprintf("\tSetting NetCDF variable compression level to %i\n", deflateLevelIn);
int err = 0;
// Integer compression implies compression
int local_deflateLevel = deflateLevelIn;
if (local_deflateLevel == 0 && icompressIn > 0) {
local_deflateLevel = 1;
}
for (int i = 0; i != (int)NVID; i++)
err += setDesiredCompression( (VidType)i, local_deflateLevel );
// Integer compression
ishuffle_ = 0;
if (icompressIn > 0) {
mprintf("\tSetting NetCDF integer compression for supported variables to %i\n", icompressIn);
// Warn about low precision powers
if (icompressIn < 4) {
mprintf("Warning: Using extremely low precision for integer compression.\n"
"Warning: Energy error will be on the order of 1E-%i kcal/mol/atom\n", icompressIn);
mprintf("Warning: Consider using integer power >= 4.\n");
} else
mprintf("Warning: Using lossy compression.\n"
"Warning: Energy error will be on the order of 1E-%i kcal/mol/atom\n", icompressIn);
// Calculate integer compression factors for supported variables
err += (calcCompressFactor( intCompressFac_[V_COORDS], icompressIn, "coordinates" ));
err += (calcCompressFactor( intCompressFac_[V_VEL], icompressIn, "velocities" ));
err += (calcCompressFactor( intCompressFac_[V_FRC], icompressIn, "forces" ));
// Report ishuffle status
ishuffle_ = ishuffleIn;
if (ishuffle_ == 0)
mprintf("\tInteger shuffle is off.\n");
else
mprintf("\tInteger shuffle is on.\n");
}
return err;
}
/* Set desired frame chunk size if supported. */
int NetcdfFile::SetFrameChunkSize(int fchunkSizeIn) {
mprintf("\tSetting frame chunk size to %i\n", fchunkSizeIn);
fchunkSize_ = fchunkSizeIn;
return 0;
}
/** If target dimID is -1 multiply existing chunk sizes for variable
* by chunkFac. Otherwise multiple chunk size matching target dimID
* only.
*/
int NetcdfFile::NC_setVarDimChunkSizes(VidType vtype, int varid, int chunkFac,
std::vector<int> const& dimids, int tgtDimId,
std::vector<size_t>& chunkSizes)
const
{
// Sanity checks.
if (dimids.empty() || chunkSizes.empty()) {
mprinterr("Internal Error: NC_setVarDimChunkSizes called with empty arrays.\n");
return 1;
}
// Get chunk sizes and storage type
int storagep = 0;
if ( NC::CheckErr( nc_inq_var_chunking(ncid_, varid, &storagep, &chunkSizes[0]) ) ) {
mprinterr("Error: getting existing chunk sizes for '%s' variable.\n", vidDesc_[vtype]);
return 1;
}
if (storagep != NC_CHUNKED) {
mprinterr("Internal Error: NC_setVarDimChunkSizes called for VID that is not chunked '%s'\n",
vidDesc_[vtype]);
return 1;
}
// Loop over dimension chunk sizes
for (unsigned int dim = 0; dim != dimids.size(); dim++) {
if (tgtDimId == -1 || tgtDimId == dimids[dim]) {
mprintf("DEBUG: '%s' dim %u chunk size = %zu new size= %zu\n",
vidDesc_[vtype], dim, chunkSizes[dim], chunkSizes[dim]*(size_t)chunkFac);
// Set new chunk size
chunkSizes[dim] *= chunkFac;
}
}
if ( NC::CheckErr( nc_def_var_chunking(ncid_, varid, NC_CHUNKED, &chunkSizes[0]) ) ) {
mprinterr("Error: Setting chunk sizes for '%s' variable.\n", vidDesc_[vtype]);
return 1;
}
return 0;
}
/** Set compressedFac to given power of 10 (min 1). */
int NetcdfFile::calcCompressFactor(double& compressedFac, int power, const char* desc) const {
compressedFac = 0;
if (power < 1) {
mprinterr("Internal Error: calcCompressFactor called with power of 10 < 1\n");
return 1;
}
compressedFac = 10.0;
for (int i = 1; i < power; i++)
compressedFac *= 10.0;
if (ncdebug_ > 0)
mprintf("\tIf present, will convert %s to integer using factor: x%g\n", desc, compressedFac);
return 0;
}
/** Write atom-based array using integer quantization and compression. */
int NetcdfFile::NC_writeIntCompressed(const double* xyz, int vid, double compressedFacIn)
{
// Convert to integer
static const long int maxval = (long int)std::numeric_limits<int>::max();
for (int idx = 0; idx != Ncatom3(); idx++)
{
// Multiply by compression factor and round to the nearest integer
long int ii = (long int)(round(xyz[idx] * compressedFacIn));
// Try some overflow protection
//long int ii = (long int)(frmOut[idx] * compressedFac_);
if (ii > maxval || ii < -maxval) {
mprinterr("Error: Value %i frame %i (%g) is too large to convert to int.\n",
idx+1, ncframe_+1, xyz[idx]);
mprinterr("Error: A smaller integer compression factor must be used.\n");
return 1;
}
itmp_[idx] = (int)ii;
//itmp_[idx] = (int)(frmOut[idx] * compressedFac_);
}
//mprintf("DEBUG: atom 0 xyz={ %20.10f %20.10f %20.10f } ixyz= { %20i %20i %20i }\n",
// frmOut[0], frmOut[1], frmOut[2], itmp_[0], itmp_[1], itmp_[2]);
// Write array
start_[0] = Ncframe();
start_[1] = 0;
start_[2] = 0;
count_[0] = 1;
count_[1] = Ncatom();
count_[2] = 3;
if (NC::CheckErr(nc_put_vara_int(ncid_, vid, start_, count_, &itmp_[0]))) {
mprinterr("Error: NetCDF writing compressed values frame %i\n", Ncframe()+1);
return 1;
}
return 0;
}