This repository has been archived by the owner on Sep 1, 2022. It is now read-only.
/
Variable.java
1823 lines (1603 loc) · 60.7 KB
/
Variable.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 1998-2018 John Caron and University Corporation for Atmospheric Research/Unidata
* See LICENSE for license information.
*/
package ucar.nc2;
import ucar.ma2.*;
import ucar.nc2.constants.CDM;
import ucar.nc2.constants.CF;
import ucar.nc2.iosp.IospHelper;
import ucar.nc2.util.CancelTask;
import ucar.nc2.util.Indent;
import ucar.nc2.util.rc.RC;
import java.io.OutputStream;
import java.util.*;
import java.io.IOException;
import java.nio.channels.WritableByteChannel;
/**
* A Variable is a logical container for data. It has a dataType, a set of Dimensions that define its array shape,
* and optionally a set of Attributes.
* <p/>
* The data is a multidimensional array of primitive types, Strings, or Structures.
* Data access is done through the read() methods, which return a memory resident Array.
* <p> Immutable if setImmutable() was called.
*
* @author caron
* @see ucar.ma2.Array
* @see ucar.ma2.DataType
*/
public class Variable extends CDMNode implements VariableIF, ProxyReader, AttributeContainer {
/**
* Globally permit or prohibit caching. For use during testing and debugging.
* <p>
* A {@code true} value for this field does not indicate whether a Variable
* {@link #isCaching() is caching}, only that it's <i>permitted</i> to cache.
*/
static public boolean permitCaching = true;
static public int defaultSizeToCache = 4000; // bytes cache any variable whose size() < defaultSizeToCache
static public int defaultCoordsSizeToCache = 40 * 1000; // bytes cache coordinate variable whose size() < defaultSizeToCache
static protected boolean debugCaching = false;
static private org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(Variable.class);
static public String getDAPName(String name, Variable context) {
if (RC.getUseGroups()) {
// leave off leading '/' for root entries
Group xg = context.getParentGroup();
if (!xg.isRoot()) {
// Get the list of parent groups
List<Group> path = Group.collectPath(xg);
Formatter dapname = new Formatter();
for (int i = 1; i < path.size(); i++) { // start at 1 to skip root group
Group g = path.get(i);
dapname.format("/%s", g.getShortName());
}
dapname.format("/%s", name);
name = dapname.toString();
}
}
return name;
}
static public String getDAPName(Variable v) {
return Variable.getDAPName(v.getShortName(), v);
}
//////////////////////////////////////////////////
// Instance data and methods
protected NetcdfFile ncfile; // physical container for this Variable; where the I/O happens. may be null if Variable is self contained.
protected int[] shape = new int[0];
protected Section shapeAsSection; // derived from the shape, immutable; used for every read, deferred creation
protected DataType dataType;
protected int elementSize;
protected List<Dimension> dimensions = new ArrayList<>(5);
protected AttributeContainerHelper attributes;
protected boolean isVariableLength = false;
protected boolean isMetadata = false;
protected Cache cache = new Cache(); // cache cannot be null
protected int sizeToCache = -1; // bytes
protected ProxyReader proxyReader = this;
/**
* Get the data type of the Variable.
*/
public DataType getDataType() {
return dataType;
}
/**
* Get the shape: length of Variable in each dimension.
* A scalar (rank 0) will have an int[0] shape.
*
* @return int array whose length is the rank of this Variable
* and whose values equal the length of that Dimension.
*/
public int[] getShape() {
int[] result = new int[shape.length]; // optimization over clone()
System.arraycopy(shape, 0, result, 0, shape.length);
return result;
}
// if scalar, return int[1], else return getShape()
public int[] getShapeNotScalar() {
if (isScalar())
return new int[]{1};
return getShape();
}
/**
* Get the size of the ith dimension
*
* @param index which dimension
* @return size of the ith dimension
*/
public int getShape(int index) {
return shape[index];
}
/**
* Get the total number of elements in the Variable.
* If this is an unlimited Variable, will use the current number of elements.
* If this is a Sequence, will return 1.
* If variable length, will skip vlen dimensions
*
* @return total number of elements in the Variable.
*/
public long getSize() {
long size = 1;
for (int aShape : shape) {
if (aShape >= 0)
size *= aShape;
}
return size;
}
/**
* Get the number of bytes for one element of this Variable.
* For Variables of primitive type, this is equal to getDataType().getSize().
* Variables of String type dont know their size, so what they return is undefined.
* Variables of Structure type return the total number of bytes for all the members of
* one Structure, plus possibly some extra padding, depending on the underlying format.
* Variables of Sequence type return the number of bytes of one element.
*
* @return total number of bytes for the Variable
*/
public int getElementSize() {
return elementSize;
}
/**
* Get the number of dimensions of the Variable.
*
* @return the rank
*/
public int getRank() {
return shape.length;
}
/**
* Get the parent group.
*
* @return group of this variable; if null return rootgroup
*/
public Group getParentGroup() {
Group g = super.getParentGroup();
if (g == null) {
g = ncfile.getRootGroup();
super.setParentGroup(g);
}
assert g != null;
return g;
}
/**
* Is this variable metadata?. True if its values need to be included explicitly in NcML output.
*
* @return true if Variable values need to be included in NcML
*/
public boolean isMetadata() {
return isMetadata;
}
/**
* Whether this is a scalar Variable (rank == 0).
*
* @return true if Variable has rank 0
*/
public boolean isScalar() {
return getRank() == 0;
}
/**
* Does this variable have a variable length dimension?
* If so, it has as one of its dimensions Dimension.VLEN.
*
* @return true if Variable has a variable length dimension?
*/
public boolean isVariableLength() {
return isVariableLength;
}
/**
* Can this variable's size grow?.
* This is equivalent to saying at least one of its dimensions is unlimited.
*
* @return boolean true iff this variable can grow
*/
public boolean isUnlimited() {
for (Dimension d : dimensions) {
if (d.isUnlimited()) return true;
}
return false;
}
/**
* Get the list of dimensions used by this variable.
* The most slowly varying (leftmost for Java and C programmers) dimension is first.
* For scalar variables, the list is empty.
*
* @return List<Dimension>, immutable
*/
public java.util.List<Dimension> getDimensions() {
return dimensions;
}
/**
* Get the ith dimension.
*
* @param i index of the dimension.
* @return requested Dimension, or null if i is out of bounds.
*/
public Dimension getDimension(int i) {
if ((i < 0) || (i >= getRank())) return null;
return dimensions.get(i);
}
/**
* Get the list of Dimension names, space delineated.
*
* @return Dimension names, space delineated
*/
public String getDimensionsString() {
return Dimension.makeDimensionsString(dimensions);
}
/**
* Find the index of the named Dimension in this Variable.
*
* @param name the name of the dimension
* @return the index of the named Dimension, or -1 if not found.
*/
public int findDimensionIndex(String name) {
for (int i = 0; i < dimensions.size(); i++) {
Dimension d = dimensions.get(i);
if (name.equals(d.getShortName()))
return i;
}
return -1;
}
/**
* Get the description of the Variable.
* Default is to use CDM.LONG_NAME attribute value. If not exist, look for "description", "title", or
* "standard_name" attribute value (in that order).
*
* @return description, or null if not found.
*/
public String getDescription() {
String desc = null;
Attribute att = findAttributeIgnoreCase(CDM.LONG_NAME);
if ((att != null) && att.isString())
desc = att.getStringValue();
if (desc == null) {
att = findAttributeIgnoreCase("description");
if ((att != null) && att.isString())
desc = att.getStringValue();
}
if (desc == null) {
att = findAttributeIgnoreCase(CDM.TITLE);
if ((att != null) && att.isString())
desc = att.getStringValue();
}
if (desc == null) {
att = findAttributeIgnoreCase(CF.STANDARD_NAME);
if ((att != null) && att.isString())
desc = att.getStringValue();
}
return desc;
}
/**
* Get the Unit String for the Variable.
* Looks for the CDM.UNITS attribute value
*
* @return unit string, or null if not found.
*/
public String getUnitsString() {
String units = null;
Attribute att = findAttribute(CDM.UNITS);
if (att == null) att = findAttributeIgnoreCase(CDM.UNITS);
if ((att != null) && att.isString()) {
units = att.getStringValue();
if (units != null) units = units.trim();
}
return units;
}
/**
* Get shape as an List of Range objects.
* The List is immutable.
*
* @return List of Ranges, one for each Dimension.
*/
public List<Range> getRanges() {
return getShapeAsSection().getRanges();
}
/**
* Get shape as a Section object.
*
* @return Section containing List<Range>, one for each Dimension.
*/
public Section getShapeAsSection() {
if (shapeAsSection == null) {
try {
List<Range> list = new ArrayList<>();
for (Dimension d : dimensions) {
int len = d.getLength();
if (len > 0)
list.add(new Range(d.getShortName(), 0, len - 1));
else if (len == 0)
list.add( Range.EMPTY); // LOOK empty not named
else {
assert d.isVariableLength();
list.add( Range.VLEN); // LOOK vlen not named
}
}
shapeAsSection = new Section(list).makeImmutable();
} catch (InvalidRangeException e) {
log.error("Bad shape in variable " + getFullName(), e);
throw new IllegalStateException(e.getMessage());
}
}
return shapeAsSection;
}
public ProxyReader getProxyReader() {
return proxyReader;
}
public void setProxyReader(ProxyReader proxyReader) {
this.proxyReader = proxyReader;
}
/**
* Create a new Variable that is a logical subsection of this Variable.
* No data is read until a read method is called on it.
*
* @param ranges List of type ucar.ma2.Range, with size equal to getRank().
* Each Range corresponds to a Dimension, and specifies the section of data to read in that Dimension.
* A Range object may be null, which means use the entire dimension.
* @return a new Variable which is a logical section of this Variable.
* @throws InvalidRangeException
*/
public Variable section(List<Range> ranges) throws InvalidRangeException {
return section(new Section(ranges, shape).makeImmutable());
}
/**
* Create a new Variable that is a logical subsection of this Variable.
* No data is read until a read method is called on it.
*
* @param subsection Section of this variable.
* Each Range in the section corresponds to a Dimension, and specifies the section of data to read in that Dimension.
* A Range object may be null, which means use the entire dimension.
* @return a new Variable which is a logical section of this Variable.
* @throws InvalidRangeException if section not compatible with shape
*/
public Variable section(Section subsection) throws InvalidRangeException {
subsection = Section.fill(subsection, shape);
// create a copy of this variable with a proxy reader
Variable sectionV = copy(); // subclasses must override
sectionV.setProxyReader(new SectionReader(this, subsection));
sectionV.shape = subsection.getShape();
sectionV.createNewCache(); // dont share the cache
sectionV.setCaching(false); // dont cache
// replace dimensions if needed !! LOOK not shared
sectionV.dimensions = new ArrayList<>();
for (int i = 0; i < getRank(); i++) {
Dimension oldD = getDimension(i);
Dimension newD = (oldD.getLength() == sectionV.shape[i]) ? oldD : new Dimension(oldD.getShortName(), sectionV.shape[i], false);
newD.setUnlimited(oldD.isUnlimited());
sectionV.dimensions.add(newD);
}
sectionV.resetShape();
return sectionV;
}
/**
* Create a new Variable that is a logical slice of this Variable, by
* fixing the specified dimension at the specified index value. This reduces rank by 1.
* No data is read until a read method is called on it.
*
* @param dim which dimension to fix
* @param value at what index value
* @return a new Variable which is a logical slice of this Variable.
* @throws InvalidRangeException if dimension or value is illegal
*/
public Variable slice(int dim, int value) throws InvalidRangeException {
if ((dim < 0) || (dim >= shape.length))
throw new InvalidRangeException("Slice dim invalid= " + dim);
// ok to make slice of record dimension with length 0
boolean recordSliceOk = false;
if ((dim == 0) && (value == 0)) {
Dimension d = getDimension(0);
recordSliceOk = d.isUnlimited();
}
// otherwise check slice in range
if (!recordSliceOk) {
if ((value < 0) || (value >= shape[dim]))
throw new InvalidRangeException("Slice value invalid= " + value + " for dimension " + dim);
}
// create a copy of this variable with a proxy reader
Variable sliceV = copy(); // subclasses must override
Section slice = new Section(getShapeAsSection());
slice.replaceRange(dim, new Range(value, value)).makeImmutable();
sliceV.setProxyReader(new SliceReader(this, dim, slice));
sliceV.createNewCache(); // dont share the cache
sliceV.setCaching(false); // dont cache
// remove that dimension - reduce rank
sliceV.dimensions.remove(dim);
sliceV.resetShape();
return sliceV;
}
/**
* Create a new Variable that is a logical view of this Variable, by
* eliminating the specified dimension(s) of length 1.
* No data is read until a read method is called on it.
*
* @param dims list of dimensions of length 1 to reduce
* @return a new Variable which is a logical slice of this Variable.
* @throws InvalidRangeException if dimension or value is illegal
*/
public Variable reduce(List<Dimension> dims) throws InvalidRangeException {
List<Integer> dimIdx = new ArrayList<>(dims.size());
for (Dimension d : dims) {
assert dimensions.contains(d);
assert d.getLength() == 1;
dimIdx.add(dimensions.indexOf(d));
}
// create a copy of this variable with a proxy reader
Variable sliceV = copy(); // subclasses must override
sliceV.setProxyReader(new ReduceReader(this, dimIdx));
sliceV.createNewCache(); // dont share the cache
sliceV.setCaching(false); // dont cache
// remove dimension(s) - reduce rank
for (Dimension d : dims) sliceV.dimensions.remove(d);
sliceV.resetShape();
return sliceV;
}
protected Variable copy() {
return new Variable(this);
}
public NetcdfFile getNetcdfFile() {
return ncfile;
}
//////////////////////////////////////////////////////////////////////////////
/**
* Lookup the enum string for this value.
* Can only be called on enum types, where dataType.isEnum() is true.
*
* @param val the integer value of this enum
* @return the String value
*/
public String lookupEnumString(int val) {
if (!dataType.isEnum())
throw new UnsupportedOperationException("Can only call Variable.lookupEnumVal() on enum types");
return enumTypedef.lookupEnumString(val);
}
private EnumTypedef enumTypedef;
/**
* Public by accident.
*
* @param enumTypedef set the EnumTypedef, only use if getDataType.isEnum()
*/
public void setEnumTypedef(EnumTypedef enumTypedef) {
if (immutable) throw new IllegalStateException("Cant modify");
if (!dataType.isEnum())
throw new UnsupportedOperationException("Can only call Variable.setEnumTypedef() on enum types");
this.enumTypedef = enumTypedef;
}
/**
* Get the EnumTypedef, only use if getDataType.isEnum()
*
* @return enumTypedef or null if !getDataType.isEnum()
*/
public EnumTypedef getEnumTypedef() {
return enumTypedef;
}
//////////////////////////////////////////////////////////////////////////////
// IO
// implementation notes to subclassers
// all other calls use them, so override only these:
// _read()
// _read(Section section)
// _readNestedData(Section section, boolean flatten)
/**
* Read a section of the data for this Variable and return a memory resident Array.
* The Array has the same element type as the Variable, and the requested shape.
* Note that this does not do rank reduction, so the returned Array has the same rank
* as the Variable. Use Array.reduce() for rank reduction.
* <p/>
* <code>assert(origin[ii] + shape[ii]*stride[ii] <= Variable.shape[ii]); </code>
* <p/>
*
* @param origin int array specifying the starting index. If null, assume all zeroes.
* @param shape int array specifying the extents in each dimension.
* This becomes the shape of the returned Array.
* @return the requested data in a memory-resident Array
*/
public Array read(int[] origin, int[] shape) throws IOException, InvalidRangeException {
if ((origin == null) && (shape == null))
return read();
if (origin == null)
return read(new Section(shape));
if (shape == null)
return read(new Section(origin, this.shape));
return read(new Section(origin, shape));
}
/**
* Read data section specified by a "section selector", and return a memory resident Array. Uses
* Fortran 90 array section syntax.
*
* @param sectionSpec specification string, eg "1:2,10,:,1:100:10". May optionally have ().
* @return the requested data in a memory-resident Array
* @see ucar.ma2.Section for sectionSpec syntax
*/
public Array read(String sectionSpec) throws IOException, InvalidRangeException {
return read(new Section(sectionSpec));
}
/**
* Read a section of the data for this Variable from the netcdf file and return a memory resident Array.
*
* @param ranges list of Range specifying the section of data to read.
* @return the requested data in a memory-resident Array
* @throws IOException if error
* @throws InvalidRangeException if ranges is invalid
* @see #read(Section)
*/
public Array read(List<Range> ranges) throws IOException, InvalidRangeException {
if (null == ranges)
return _read();
return read(new Section(ranges));
}
/**
* Read a section of the data for this Variable from the netcdf file and return a memory resident Array.
* The Array has the same element type as the Variable, and the requested shape.
* Note that this does not do rank reduction, so the returned Array has the same rank
* as the Variable. Use Array.reduce() for rank reduction.
* <p/>
* If the Variable is a member of an array of Structures, this returns only the variable's data
* in the first Structure, so that the Array shape is the same as the Variable.
* To read the data in all structures, use ncfile.readSectionSpec().
* <p/>
* Note this only allows you to specify a subset of this variable.
* If the variable is nested in a array of structures and you want to subset that, use
* NetcdfFile.read(String sectionSpec, boolean flatten);
*
* @param section list of Range specifying the section of data to read.
* Must be null or same rank as variable.
* If list is null, assume all data.
* Each Range corresponds to a Dimension. If the Range object is null, it means use the entire dimension.
* @return the requested data in a memory-resident Array
* @throws IOException if error
* @throws InvalidRangeException if section is invalid
*/
public Array read(ucar.ma2.Section section) throws java.io.IOException, ucar.ma2.InvalidRangeException {
return (section == null) ? _read() : _read(Section.fill(section, shape));
}
/**
* Read all the data for this Variable and return a memory resident Array.
* The Array has the same element type and shape as the Variable.
* <p/>
* If the Variable is a member of an array of Structures, this returns only the variable's data
* in the first Structure, so that the Array shape is the same as the Variable.
* To read the data in all structures, use ncfile.readSection().
*
* @return the requested data in a memory-resident Array.
*/
public Array read() throws IOException {
return _read();
}
/**
* *********************************************************************
*/
// scalar reading
/**
* Get the value as a byte for a scalar Variable. May also be one-dimensional of length 1.
*
* @throws IOException if theres an IO Error
* @throws UnsupportedOperationException if not a scalar Variable or one-dimensional of length 1.
* @throws ForbiddenConversionException if data type not convertible to byte
*/
public byte readScalarByte() throws IOException {
Array data = getScalarData();
return data.getByte(Index.scalarIndexImmutable);
}
/**
* Get the value as a short for a scalar Variable. May also be one-dimensional of length 1.
*
* @throws IOException if theres an IO Error
* @throws UnsupportedOperationException if not a scalar Variable or one-dimensional of length 1.
* @throws ForbiddenConversionException if data type not convertible to short
*/
public short readScalarShort() throws IOException {
Array data = getScalarData();
return data.getShort(Index.scalarIndexImmutable);
}
/**
* Get the value as a int for a scalar Variable. May also be one-dimensional of length 1.
*
* @throws IOException if theres an IO Error
* @throws UnsupportedOperationException if not a scalar Variable or one-dimensional of length 1.
* @throws ForbiddenConversionException if data type not convertible to int
*/
public int readScalarInt() throws IOException {
Array data = getScalarData();
return data.getInt(Index.scalarIndexImmutable);
}
/**
* Get the value as a long for a scalar Variable. May also be one-dimensional of length 1.
*
* @throws IOException if theres an IO Error
* @throws UnsupportedOperationException if not a scalar Variable
* @throws ForbiddenConversionException if data type not convertible to long
*/
public long readScalarLong() throws IOException {
Array data = getScalarData();
return data.getLong(Index.scalarIndexImmutable);
}
/**
* Get the value as a float for a scalar Variable. May also be one-dimensional of length 1.
*
* @throws IOException if theres an IO Error
* @throws UnsupportedOperationException if not a scalar Variable or one-dimensional of length 1.
* @throws ForbiddenConversionException if data type not convertible to float
*/
public float readScalarFloat() throws IOException {
Array data = getScalarData();
return data.getFloat(Index.scalarIndexImmutable);
}
/**
* Get the value as a double for a scalar Variable. May also be one-dimensional of length 1.
*
* @throws IOException if theres an IO Error
* @throws UnsupportedOperationException if not a scalar Variable or one-dimensional of length 1.
* @throws ForbiddenConversionException if data type not convertible to double
*/
public double readScalarDouble() throws IOException {
Array data = getScalarData();
return data.getDouble(Index.scalarIndexImmutable);
}
/**
* Get the value as a String for a scalar Variable. May also be one-dimensional of length 1.
* May also be one-dimensional of type CHAR, which wil be turned into a scalar String.
*
* @throws IOException if theres an IO Error
* @throws UnsupportedOperationException if not a scalar or one-dimensional.
* @throws ClassCastException if data type not DataType.STRING or DataType.CHAR.
*/
public String readScalarString() throws IOException {
Array data = getScalarData();
if (dataType == DataType.STRING)
return (String) data.getObject(Index.scalarIndexImmutable);
else if (dataType == DataType.CHAR) {
ArrayChar dataC = (ArrayChar) data;
return dataC.getString();
} else
throw new IllegalArgumentException("readScalarString not STRING or CHAR " + getFullName());
}
protected Array getScalarData() throws IOException {
Array scalarData = (cache.data != null) ? cache.data : read();
scalarData = scalarData.reduce();
if ((scalarData.getRank() == 0) || ((scalarData.getRank() == 1) && dataType == DataType.CHAR))
return scalarData;
throw new java.lang.UnsupportedOperationException("not a scalar variable =" + this);
}
///////////////
// internal reads: all other calls go through these.
// subclasses must override, so that NetcdfDataset wrapping will work.
// non-structure-member Variables.
protected Array _read() throws IOException {
// caching overrides the proxyReader
// check if already cached
if (cache.data != null) {
if (debugCaching) System.out.println("got data from cache " + getFullName());
return cache.data.copy();
}
Array data = proxyReader.reallyRead(this, null);
// optionally cache it
if (isCaching()) {
setCachedData(data);
if (debugCaching) System.out.println("cache " + getFullName());
return cache.data.copy(); // dont let users get their nasty hands on cached data
} else {
return data;
}
}
/**
* public by accident, do not call directly.
*
* @return Array
* @throws IOException on error
*/
@Override
public Array reallyRead(Variable client, CancelTask cancelTask) throws IOException {
if (isMemberOfStructure()) { // LOOK should be UnsupportedOperationException ??
List<String> memList = new ArrayList<>();
memList.add(this.getShortName());
Structure s = getParentStructure().select(memList);
ArrayStructure as = (ArrayStructure) s.read();
return as.extractMemberArray(as.findMember(getShortName()));
}
try {
return ncfile.readData(this, getShapeAsSection());
} catch (InvalidRangeException e) {
e.printStackTrace();
throw new IOException(e.getMessage()); // cant happen haha
}
}
// section of non-structure-member Variable
// assume filled, validated Section
protected Array _read(Section section) throws IOException, InvalidRangeException {
// check if its really a full read
if ((null == section) || section.computeSize() == getSize())
return _read();
// full read was cached
if (isCaching()) {
if (cache.data == null) {
setCachedData(_read()); // read and cache entire array
if (debugCaching) System.out.println("cache " + getFullName());
}
if (debugCaching) System.out.println("got data from cache " + getFullName());
return cache.data.sectionNoReduce(section.getRanges()).copy(); // subset it, return copy
}
return proxyReader.reallyRead(this, section, null);
}
/**
* public by accident, do not call directly.
*
* @return Array
* @throws IOException on error
*/
@Override
public Array reallyRead(Variable client, Section section, CancelTask cancelTask) throws IOException, InvalidRangeException {
if (isMemberOfStructure()) {
throw new UnsupportedOperationException("Cannot directly read section of Member Variable=" + getFullName());
}
// read just this section
return ncfile.readData(this, section);
}
/* structure-member Variable; section has a Range for each array in the parent
// stuctures(s) and for the Variable.
private Array _readMemberData(List<Range> section, boolean flatten) throws IOException, InvalidRangeException {
/*Variable useVar = (ioVar != null) ? ioVar : this;
NetcdfFile useFile = (ncfileIO != null) ? ncfileIO : ncfile;
return useFile.readMemberData(useVar, section, flatten);
} */
public long readToByteChannel(Section section, WritableByteChannel wbc) throws IOException, InvalidRangeException {
if ((ncfile == null) || hasCachedData())
return IospHelper.copyToByteChannel(read(section), wbc);
return ncfile.readToByteChannel(this, section, wbc);
}
public long readToStream(Section section, OutputStream out) throws IOException, InvalidRangeException {
if ((ncfile == null) || hasCachedData())
return IospHelper.copyToOutputStream(read(section), out);
return ncfile.readToOutputStream(this, section, out);
}
/*******************************************/
/* nicely formatted string representation */
/**
* Get the display name plus the dimensions, eg 'float name(dim1, dim2)'
*
* @return display name plus the dimensions
*/
public String getNameAndDimensions() {
Formatter buf = new Formatter();
getNameAndDimensions(buf, true, false);
return buf.toString();
}
/**
* Get the display name plus the dimensions, eg 'float name(dim1, dim2)'
*
* @param strict strictly comply with ncgen syntax, with name escaping. otherwise, get extra info, no escaping
* @return display name plus the dimensions
*/
public String getNameAndDimensions(boolean strict) {
Formatter buf = new Formatter();
getNameAndDimensions(buf, false, strict);
return buf.toString();
}
/**
* Get the display name plus the dimensions, eg 'name(dim1, dim2)'
*
* @param buf add info to this StringBuilder
*/
public void getNameAndDimensions(StringBuilder buf) {
getNameAndDimensions(buf, true, false);
}
/**
* Get the display name plus the dimensions, eg 'name(dim1, dim2)'
*
* @param buf add info to this StringBuffer
* @deprecated use getNameAndDimensions(StringBuilder buf)
*/
public void getNameAndDimensions(StringBuffer buf) {
Formatter proxy = new Formatter();
getNameAndDimensions(proxy, true, false);
buf.append(proxy.toString());
}
/**
* Add display name plus the dimensions to the StringBuffer
*
* @param buf add info to this
* @param useFullName use full name else short name. strict = true implies short name
* @param strict strictly comply with ncgen syntax, with name escaping. otherwise, get extra info, no escaping
*/
public void getNameAndDimensions(StringBuilder buf, boolean useFullName, boolean strict) {
Formatter proxy = new Formatter();
getNameAndDimensions(proxy, useFullName, strict);
buf.append(proxy.toString());
}
/**
* Add display name plus the dimensions to the StringBuffer
*
* @param buf add info to this
* @param useFullName use full name else short name. strict = true implies short name
* @param strict strictly comply with ncgen syntax, with name escaping. otherwise, get extra info, no escaping
*/
public void getNameAndDimensions(Formatter buf, boolean useFullName, boolean strict) {
useFullName = useFullName && !strict;
String name = useFullName ? getFullName() : getShortName();
if (strict) name = NetcdfFile.makeValidCDLName(getShortName());
buf.format("%s", name);
if (shape != null) {
if (getRank() > 0) buf.format("(");
for (int i = 0; i < dimensions.size(); i++) {
Dimension myd = dimensions.get(i);
String dimName = myd.getShortName();
if ((dimName != null) && strict)
dimName = NetcdfFile.makeValidCDLName(dimName);
if (i != 0) buf.format(", ");
if (myd.isVariableLength()) {
buf.format("*");
} else if (myd.isShared()) {
if (!strict)
buf.format("%s=%d", dimName, myd.getLength());
else
buf.format("%s", dimName);
} else {
if (dimName != null) {
buf.format("%s=", dimName);
}
buf.format("%d", myd.getLength());
}
}
if (getRank() > 0) buf.format(")");
}
}
/**
* CDL representation of Variable, not strict.
*/
public String toString() {
return writeCDL(false, false);
}
/**
* CDL representation of a Variable.
*
* @param useFullName use full name, else use short name
* @param strict strictly comply with ncgen syntax
* @return CDL representation of the Variable.
*/
public String writeCDL(boolean useFullName, boolean strict) {
Formatter buf = new Formatter();
writeCDL(buf, new Indent(2), useFullName, strict);
return buf.toString();
}
protected void writeCDL(Formatter buf, Indent indent, boolean useFullName, boolean strict) {
buf.format("%s", indent);
if (dataType == null)
buf.format("Unknown");
else if (dataType.isEnum()) {
if (enumTypedef == null)
buf.format("enum UNKNOWN");
else
buf.format("enum %s", NetcdfFile.makeValidCDLName(enumTypedef.getShortName()));
} else
buf.format("%s", dataType.toString());
//if (isVariableLength) buf.append("(*)"); // LOOK
buf.format(" ");
getNameAndDimensions(buf, useFullName, strict);
buf.format(";");
if (!strict) buf.format(extraInfo());
buf.format("%n");
indent.incr();
for (Attribute att : getAttributes()) {
if(Attribute.isspecial(att)) continue;
buf.format("%s", indent);
att.writeCDL(buf, strict, getShortName());
buf.format(";");
if (!strict && (att.getDataType() != DataType.STRING))
buf.format(" // %s", att.getDataType());
buf.format("%n");
}
indent.decr();
}
/**