Java Code Examples for ucar.ma2.Array#getSize()

The following examples show how to use ucar.ma2.Array#getSize() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestSequence.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void testSequence() {
  String url = "http://tsds.net/tsds/test/Scalar";
  try {
    NetcdfDataset ds = NetcdfDatasets.openDataset(url);
    System.out.println(ds);
    Structure struct = (Structure) ds.findVariable("TimeSeries");
    Variable var = struct.findVariable("time");
    Array arr = var.read();
    int n = (int) arr.getSize();
    int i;
    for (i = 0; arr.hasNext() && i < n; i++)
      System.out.println(arr.nextDouble());
    if (i != n) {
      System.err.println("short sequence");
      System.exit(1);
    }
  } catch (Exception e) {
    e.printStackTrace();
  }
}
 
Example 2
Source File: TimeGrid.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/** testing */
public static void main(String arg[]) throws IOException {
  // String defaultFilename = "R:/testdata2/motherlode/grid/NAM_Alaska_45km_conduit_20060801_0000.grib1";
  String defaultFilename = "R:/testdata/grid/grib/grib2/test/NAM_CONUS_12km_20060305_1200.grib2";
  String filename = (arg.length > 0) ? arg[0] : defaultFilename;
  try {
    long start = System.currentTimeMillis();
    GridDataset gridDs = GridDataset.open(filename);
    GeoGrid gg = gridDs.findGridByName("Temperature");
    long took = System.currentTimeMillis() - start;
    System.out.println("open took = " + took + " msecs");

    start = System.currentTimeMillis();
    Array data = gg.readVolumeData(0);
    took = System.currentTimeMillis() - start;
    float size = (float) data.getSize() * gg.getDataType().getSize() / (1000 * 1000);
    System.out.println(size + " Mbytes, took = " + took + " msecs");

  } catch (Exception ioe) {
    ioe.printStackTrace();
  }


  System.in.read();
}
 
Example 3
Source File: StationData.java    From MeteoInfo with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Constructor
 *
 * @param a Array data
 * @param x Array x
 * @param y Array y
 * @param missingv Missing value
 */
public StationData(Array a, Array x, Array y, Number missingv) {
    int n = (int) a.getSize();
    this.missingValue = missingv.doubleValue();
    stations = new ArrayList<>();
    dataExtent = new Extent();
    data = new double[n][3];
    for (int i = 0; i < n; i++) {
        stations.add("s_" + String.valueOf(i + 1));
        data[i][0] = x.getDouble(i);
        data[i][1] = y.getDouble(i);
        data[i][2] = a.getDouble(i);
        if (Double.isNaN(data[i][2]))
            data[i][2] = missingv.doubleValue();
        //this.addData("s_" + String.valueOf(i + 1), x.getDouble(i), y.getDouble(i), a.getDouble(i));
    }
}
 
Example 4
Source File: Hdf5NewDataTable.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void showVlen(Formatter f, VarBean bean) {
  if (!bean.v.isVariableLength()) {
    f.format("Variable %s must be variable length", bean.v.getFullName());
    return;
  }

  try {
    int countRows = 0;
    long countElems = 0;
    Array result = bean.v.read();
    f.format("class = %s%n", result.getClass().getName());
    while (result.hasNext()) {
      Array line = (Array) result.next();
      countRows++;
      long size = line.getSize();
      countElems += size;
      f.format("  row %d size=%d%n", countRows, size);
    }
    float avg = (countRows == 0) ? 0 : ((float) countElems) / countRows;
    f.format("%n  nrows = %d totalElems=%d avg=%f%n", countRows, countElems, avg);
  } catch (IOException e) {
    e.printStackTrace(); // To change body of catch statement use File | Settings | File Templates.
  }
}
 
Example 5
Source File: Table.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void init() {
  if (startVarName == null) { // read numRecords when startVar is not known LOOK this should be deffered
    try {
      Variable v = ds.findVariable(numRecordsVarName);
      Array numRecords = v.read();
      int n = (int) numRecords.getSize();

      // construct the start variable
      this.numRecords = new int[n];
      this.startIndex = new int[n];
      int i = 0;
      int count = 0;
      while (numRecords.hasNext()) {
        this.startIndex[i] = count;
        this.numRecords[i] = numRecords.nextInt();
        count += this.numRecords[i];
        i++;
      }
      isInit = true;
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
}
 
Example 6
Source File: SigmetIOServiceProvider.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Read data from a top level Variable and send data to a WritableByteChannel.
 *
 * @param v2 Variable
 * @param section wanted section of data of Variable. The section list is a list
 *        of ucar.ma2.Range which define the requested data subset.
 * @param channel WritableByteChannel object - channel that can write bytes.
 * @return the number of bytes written, possibly zero.
 */
public long readToByteChannel11(ucar.nc2.Variable v2, Section section, WritableByteChannel channel)
    throws java.io.IOException {
  Array data = readData(v2, section);
  float[] ftdata = new float[(int) data.getSize()];
  byte[] bytedata = new byte[(int) data.getSize() * 4];
  IndexIterator iter = data.getIndexIterator();
  int i = 0;
  ByteBuffer buffer = ByteBuffer.allocateDirect(bytedata.length);
  while (iter.hasNext()) {
    ftdata[i] = iter.getFloatNext();
    bytedata[i] = new Float(ftdata[i]).byteValue();
    buffer.put(bytedata[i]);
    i++;
  }
  buffer = ByteBuffer.wrap(bytedata);
  // write the bytes to the channel
  int count = channel.write(buffer);
  // check if all bytes where written
  if (buffer.hasRemaining()) {
    // if not all bytes were written, move the unwritten bytes to the beginning and
    // set position just after the last unwritten byte
    buffer.compact();
  } else {
    buffer.clear();
  }
  return (long) count;
}
 
Example 7
Source File: PolylineErrorShape.java    From MeteoInfo with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Set X error data
 * @param value X error data 
 */
public void setXerror(Array value){
    this.xerror = new double[(int)value.getSize()];
    double v;
    for (int i = 0; i < xerror.length; i++){
        v = value.getDouble(i);
        xerror[i] = v;
    }
}
 
Example 8
Source File: TimeRecords2.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
static private void readColumns(NetcdfFile ncfile) throws IOException {
  long start = System.currentTimeMillis();
  long total = 0;
  for (Variable variable : ncfile.getVariables()) {
    Array data = variable.read();
    total += data.getSize();
  }
  double took = (System.currentTimeMillis() - start) * .001;
  System.out.println("   nvars = " + ncfile.getVariables().size());
  System.out.println(" readCols took=" + took + " secs (" + total + ")");
}
 
Example 9
Source File: Ncdump.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static void printStringArray(Formatter out, Array ma, Indent indent, CancelTask ct) {
  if (ct != null && ct.isCancel())
    return;

  int rank = ma.getRank();
  Index ima = ma.getIndex();

  if (rank == 0) {
    out.format("  \"%s\"", ma.getObject(ima));
    return;
  }

  if (rank == 1) {
    boolean first = true;
    for (int i = 0; i < ma.getSize(); i++) {
      if (!first)
        out.format(", ");
      out.format("  \"%s\"", ma.getObject(ima.set(i)));
      first = false;
    }
    return;
  }

  int[] dims = ma.getShape();
  int last = dims[0];

  out.format("%n%s{", indent);
  indent.incr();
  for (int ii = 0; ii < last; ii++) {
    ArrayObject slice = (ArrayObject) ma.slice(0, ii);
    if (ii > 0)
      out.format(",");
    printStringArray(out, slice, indent, ct);
  }
  indent.decr();
  out.format("%n%s}", indent);
}
 
Example 10
Source File: NetcdfCopier.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void copyAll(NetcdfFormatWriter ncwriter, Variable oldVar, Variable newVar) throws IOException {
  Array data = oldVar.read();
  try {
    if (!extended && oldVar.getDataType() == DataType.STRING) {
      data = convertDataToChar(newVar, data);
    }
    if (data.getSize() > 0) { // zero when record dimension = 0
      ncwriter.write(newVar, data);
    }

  } catch (InvalidRangeException e) {
    e.printStackTrace();
    throw new IOException(e.getMessage() + " for Variable " + oldVar.getFullName());
  }
}
 
Example 11
Source File: H5iospNew.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
Array convertReference(Array refArray) throws IOException {
  int nelems = (int) refArray.getSize();
  Index ima = refArray.getIndex();
  String[] result = new String[nelems];
  for (int i = 0; i < nelems; i++) {
    long reference = refArray.getLong(ima.set(i));
    String name = header.getDataObjectName(reference);
    result[i] = name != null ? name : Long.toString(reference);
    if (debugVlen)
      System.out.printf(" convertReference 0x%x to %s %n", reference, result[i]);
  }
  return Array.factory(DataType.STRING, new int[] {nelems}, result);
}
 
Example 12
Source File: NetcdfDataset.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Set the data values from a list of Strings.
 *
 * @param v for this variable
 * @param values list of Strings
 * @throws IllegalArgumentException if values array not correct size, or values wont parse to the correct type
 * @deprecated use Variable.setValues()
 */
@Deprecated
public void setValues(Variable v, List<String> values) throws IllegalArgumentException {
  Array data = Array.makeArray(v.getDataType(), values);

  if (data.getSize() != v.getSize())
    throw new IllegalArgumentException("Incorrect number of values specified for the Variable " + v.getFullName()
        + " needed= " + v.getSize() + " given=" + data.getSize());

  if (v.getRank() != 1) // dont have to reshape for rank 1
    data = data.reshape(v.getShape());

  v.setCachedData(data, true);
}
 
Example 13
Source File: CoverageAsPoint.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
TimeseriesIterator() {
  varIters = new ArrayList<>();
  for (VarData vd : varData) {
    Array data = vd.array.getData();
    if (debug)
      System.out.printf("%s shape=%s%n", vd.cov.getName(), Arrays.toString(data.getShape()));
    varIters.add(new VarIter(vd.cov, vd.array, data.getIndexIterator()));
    nvalues = (int) data.getSize();

    if (timeAxis == null) { // assume they are all the same (!)
      CoverageCoordSys csys = vd.array.getCoordSysForData();
      timeAxis = (CoverageCoordAxis1D) csys.getTimeAxis(); // LOOK may not be right
    }
  }
}
 
Example 14
Source File: LCMSNetCDFParser.java    From act with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Iterator<LCMSSpectrum> getIterator(String inputFile)
    throws ParserConfigurationException, IOException, XMLStreamException {

  final NetcdfFile netcdfFile = NetcdfFile.open(inputFile);

  // Assumption: all referenced Variables will always exist in the NetcdfFfile.

  // Assumption: these arrays will have the same length.
  final Array mzValues = netcdfFile.findVariable(MASS_VALUES).read();
  final Array intensityValues = netcdfFile.findVariable(INTENSITY_VALUES).read();
  assert(mzValues.getSize() == intensityValues.getSize());
  // Assumption: the mz/intensity values are always floats.
  assert(mzValues.getDataType() == DataType.FLOAT &&
      intensityValues.getDataType() == DataType.FLOAT);

  // Assumption: all of these variables' arrays will have the same lengths.
  final Array scanTimeArray = netcdfFile.findVariable(SCAN_TIME).read();
  final Array scanPointsStartArray = netcdfFile.findVariable(SCAN_POINTS_START).read();
  final Array scanPointsCountArray = netcdfFile.findVariable(SCAN_POINTS_COUNT).read();
  final Array totalIntensityArray = netcdfFile.findVariable(TOTAL_INTENSITY).read();
  assert(scanTimeArray.getSize() == scanPointsStartArray.getSize() &&
      scanPointsStartArray.getSize() == scanPointsCountArray.getSize() &&
      scanPointsCountArray.getSize() == totalIntensityArray.getSize());
  // Assumption: the following four columns always have these types.
  assert(scanTimeArray.getDataType() == DataType.DOUBLE &&
      scanPointsStartArray.getDataType() == DataType.INT &&
      scanPointsCountArray.getDataType() == DataType.INT &&
      totalIntensityArray.getDataType() == DataType.DOUBLE);

  final long size = scanTimeArray.getSize();

  return new Iterator<LCMSSpectrum>() {
    private int i = 0;
    @Override
    public boolean hasNext() {
      return this.i < size;
    }

    @Override
    public LCMSSpectrum next() {
      int pointCount = scanPointsCountArray.getInt(i);
      List<Pair<Double, Double>> mzIntPairs = new ArrayList<>(pointCount);

      int pointsStart = scanPointsStartArray.getInt(i);
      int pointsEnd = pointsStart + pointCount;
      for (int p = pointsStart; p < pointsEnd; p++) {
        Double mz = Float.valueOf(mzValues.getFloat(p)).doubleValue();
        Double intensity = Float.valueOf(intensityValues.getFloat(p)).doubleValue();
        mzIntPairs.add(Pair.of(mz, intensity));
      }

      LCMSSpectrum s = new LCMSSpectrum(i, scanTimeArray.getDouble(i), "s", mzIntPairs,
          null, null, null, i, totalIntensityArray.getDouble(i));

      // Don't forget to advance the counter!
      this.i++;

      // Close the file if we're done with all the array contents.
      if (i >= size) {
        try {
          netcdfFile.close();
        } catch (IOException e) {
          throw new RuntimeException(e); // TODO: can we do better?
        }
      }

      return s;
    }
  };
}
 
Example 15
Source File: FmrcDataset.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public Array reallyRead(Variable mainv, Section section, CancelTask cancelTask)
    throws IOException, InvalidRangeException {
  Vstate1D vstate = (Vstate1D) mainv.getSPobject();

  // read the original type - if its been promoted to a new type, the conversion happens after this read
  DataType dtype = (mainv instanceof VariableDS) ? ((VariableDS) mainv).getOriginalDataType() : mainv.getDataType();

  Array allData = Array.factory(dtype, section.getShape());
  int destPos = 0;

  // assumes the first dimension is time: LOOK: what about ensemble ??
  List<Range> ranges = section.getRanges();
  Range timeRange = ranges.get(0);
  List<Range> innerSection = ranges.subList(1, ranges.size());

  // keep track of open files - must be local variable for thread safety
  HashMap<String, NetcdfDataset> openFilesRead = new HashMap<>();

  try {

    // iterate over the desired forecast times
    for (int timeIdx : timeRange) {
      Array result = null;

      // find the inventory for this grid, runtime, and hour
      TimeInventory.Instance timeInv = vstate.timeInv.getInstance(vstate.gridLite, timeIdx);
      if (timeInv == null) {
        if (logger.isDebugEnabled())
          logger.debug("Missing Inventory timeInx=" + timeIdx + " for " + mainv.getFullName() + " in "
              + state.lite.collectionName);
        // vstate.timeInv.getInstance(vstate.gridLite, timeIdx); // allow debugger
      } else if (timeInv.getDatasetLocation() != null) {
        if (debugRead)
          System.out.printf("HIT %s%n", timeInv);
        result = read(timeInv, mainv.getFullNameEscaped(), innerSection, openFilesRead); // may return null
        result = MAMath.convert(result, dtype); // just in case it need to be converted
      }

      // may have missing data
      if (result == null) {
        int[] shape = new Section(innerSection).getShape();
        result = ((VariableDS) mainv).getMissingDataArray(shape); // fill with missing values
        if (debugRead)
          System.out.printf("MISS %d ", timeIdx);
      }

      if (debugRead)
        System.out.printf("%d reallyRead %s %d bytes start at %d total size is %d%n", timeIdx, mainv.getFullName(),
            result.getSize(), destPos, allData.getSize());

      Array.arraycopy(result, 0, allData, destPos, (int) result.getSize());
      destPos += result.getSize();
    }
    return allData;

  } finally {
    // close any files used during this operation
    closeAll(openFilesRead);
  }
}
 
Example 16
Source File: IFPSConvention.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void createTimeCoordinate(VariableDS.Builder<?> ncVar) {
  // Time coordinate is stored in the attribute validTimes
  // One caveat is that the times have two bounds an upper and a lower

  // get the times values
  Attribute timesAtt = ncVar.getAttributeContainer().findAttribute("validTimes");
  if (timesAtt == null)
    return;
  Array timesArray = timesAtt.getValues();

  // get every other one LOOK this is awkward
  try {
    int n = (int) timesArray.getSize();
    List<Range> list = new ArrayList<>();
    list.add(new Range(0, n - 1, 2));
    timesArray = timesArray.section(list);
  } catch (InvalidRangeException e) {
    throw new IllegalStateException(e);
  }

  // make sure it matches the dimension
  DataType dtype = DataType.getType(timesArray);
  int nTimesAtt = (int) timesArray.getSize();

  // create a special dimension and coordinate variable
  Dimension dimTime = ncVar.orgVar.getDimension(0);
  int nTimesDim = dimTime.getLength();
  if (nTimesDim != nTimesAtt) {
    parseInfo.format(" **error ntimes in attribute (%d) doesnt match dimension length (%d) for variable %s%n",
        nTimesAtt, nTimesDim, ncVar.getFullName());
    return;
  }

  // add the dimension
  String dimName = ncVar.shortName + "_timeCoord";
  Dimension newDim = new Dimension(dimName, nTimesDim);
  rootGroup.addDimension(newDim);

  // add the coordinate variable
  String units = "seconds since 1970-1-1 00:00:00";
  String desc = "time coordinate for " + ncVar.shortName;

  CoordinateAxis1D.Builder timeCoord = CoordinateAxis1D.builder().setName(dimName).setDataType(dtype)
      .setParentGroupBuilder(rootGroup).setDimensionsByName(dimName).setUnits(units).setDesc(desc);
  timeCoord.setCachedData(timesArray, true);
  timeCoord.addAttribute(new Attribute(_Coordinate.AxisType, AxisType.Time.toString()));
  datasetBuilder.replaceCoordinateAxis(rootGroup, timeCoord);

  parseInfo.format(" added coordinate variable %s%n", dimName);

  // now make the original variable use the new dimension
  ArrayList<Dimension> newDims = new ArrayList<>(ncVar.getDimensions());
  newDims.set(0, newDim);
  ncVar.setDimensions(newDims);

  // better to explicitly set the coordinate system
  ncVar.addAttribute(new Attribute(_Coordinate.Axes, dimName + " yCoord xCoord"));

  // fix the attributes
  Attribute att = ncVar.getAttributeContainer().findAttribute("fillValue");
  if (att != null)
    ncVar.addAttribute(new Attribute(CDM.FILL_VALUE, att.getNumericValue()));
  att = ncVar.getAttributeContainer().findAttribute("descriptiveName");
  if (null != att)
    ncVar.addAttribute(new Attribute(CDM.LONG_NAME, att.getStringValue()));
}
 
Example 17
Source File: AWIPSConvention.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private CoordinateAxis.Builder makeTimeCoordAxis() {
  VariableDS.Builder timeVar = (VariableDS.Builder) rootGroup.findVariableLocal("valtimeMINUSreftime")
      .orElseThrow(() -> new RuntimeException("must have varible 'valtimeMINUSreftime'"));

  Dimension recordDim =
      rootGroup.findDimension("record").orElseThrow(() -> new RuntimeException("must have dimension 'record'"));

  Array vals;
  try {
    vals = timeVar.orgVar.read();
  } catch (IOException ioe) {
    return null;
  }

  // it seems that the record dimension does not always match valtimeMINUSreftime dimension!!
  // HAHAHAHAHAHAHAHA !
  int recLen = recordDim.getLength();
  int valLen = (int) vals.getSize();
  if (recLen != valLen) {
    try {
      vals = vals.sectionNoReduce(new int[] {0}, new int[] {recordDim.getLength()}, null);
      parseInfo.format(" corrected the TimeCoordAxis length%n");
    } catch (InvalidRangeException e) {
      parseInfo.format("makeTimeCoordAxis InvalidRangeException%n");
    }
  }

  // create the units out of the filename if possible
  String units = makeTimeUnitFromFilename(datasetBuilder.location);
  if (units == null) // ok that didnt work, try something else
    return makeTimeCoordAxisFromReference(vals);

  // create the coord axis
  String name = "timeCoord";
  String desc = "synthesized time coordinate from valtimeMINUSreftime and filename YYYYMMDD_HHMM";
  CoordinateAxis1D.Builder timeCoord =
      CoordinateAxis1D.builder().setName(name).setDataType(DataType.INT).setParentGroupBuilder(rootGroup)
          .setDimensionsByName("record").setUnits(units).setDesc(desc).setCachedData(vals, true);

  parseInfo.format("Created Time Coordinate Axis = %s%n", name);
  return timeCoord;
}
 
Example 18
Source File: NetcdfCopier.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Copies data from {@code oldVar} to {@code newVar}. The writes are done in a series of chunks no larger than
 * {@code maxChunkSize}
 * bytes.
 *
 * @param oldVar a variable from the original file to copy data from.
 * @param newVar a variable from the original file to copy data from.
 * @param maxChunkSize the size, <b>in bytes</b>, of the largest chunk to write.
 * @param cancel allow user to cancel, may be null.
 * @throws IOException if an I/O error occurs.
 */
private void copySome(NetcdfFormatWriter ncwriter, Variable oldVar, Variable newVar, long maxChunkSize,
    CancelTask cancel) throws IOException {
  long maxChunkElems = maxChunkSize / oldVar.getElementSize();
  long byteWriteTotal = 0;

  ChunkingIndex index = new ChunkingIndex(oldVar.getShape());
  while (index.currentElement() < index.getSize()) {
    try {
      int[] chunkOrigin = index.getCurrentCounter();
      int[] chunkShape = index.computeChunkShape(maxChunkElems);

      cancel.setProgress(
          "Reading chunk " + new Section(chunkOrigin, chunkShape) + " from variable: " + oldVar.getShortName(), -1);

      Array data = oldVar.read(chunkOrigin, chunkShape);
      if (!getOutputFormat().isNetdf4format() && oldVar.getDataType() == DataType.STRING) {
        data = convertDataToChar(newVar, data);
      }

      if (data.getSize() > 0) { // zero when record dimension = 0
        cancel.setProgress(
            "Writing chunk " + new Section(chunkOrigin, chunkShape) + " from variable: " + oldVar.getShortName(), -1);

        ncwriter.write(newVar, chunkOrigin, data);
        if (debugWrite) {
          System.out.println(" write " + data.getSize() + " bytes at " + new Section(chunkOrigin, chunkShape));
        }

        byteWriteTotal += data.getSize();
      }

      index.setCurrentCounter(index.currentElement() + (int) Index.computeSize(chunkShape));
      if (cancel.isCancel()) {
        return;
      }

    } catch (InvalidRangeException e) {
      e.printStackTrace();
      throw new IOException(e.getMessage());
    }
  }
}
 
Example 19
Source File: IFPSConvention.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void createTimeCoordinate(NetcdfDataset ds, Variable ncVar) {
  // Time coordinate is stored in the attribute validTimes
  // One caveat is that the times have two bounds an upper and a lower

  // get the times values
  Attribute timesAtt = ncVar.findAttribute("validTimes");
  if (timesAtt == null)
    return;
  Array timesArray = timesAtt.getValues();

  // get every other one LOOK this is awkward
  try {
    int n = (int) timesArray.getSize();
    List<Range> list = new ArrayList<>();
    list.add(new Range(0, n - 1, 2));
    timesArray = timesArray.section(list);
  } catch (InvalidRangeException e) {
    throw new IllegalStateException(e);
  }

  // make sure it matches the dimension
  DataType dtype = DataType.getType(timesArray);
  int nTimesAtt = (int) timesArray.getSize();

  // create a special dimension and coordinate variable
  Dimension dimTime = ncVar.getDimension(0);
  int nTimesDim = dimTime.getLength();
  if (nTimesDim != nTimesAtt) {
    parseInfo.format(" **error ntimes in attribute (%d) doesnt match dimension length (%d) for variable %s%n",
        nTimesAtt, nTimesDim, ncVar.getFullName());
    return;
  }

  // add the dimension
  String dimName = ncVar.getFullName() + "_timeCoord";
  Dimension newDim = new Dimension(dimName, nTimesDim);
  ds.addDimension(null, newDim);

  // add the coordinate variable
  String units = "seconds since 1970-1-1 00:00:00";
  String desc = "time coordinate for " + ncVar.getFullName();

  CoordinateAxis1D timeCoord = new CoordinateAxis1D(ds, null, dimName, dtype, dimName, units, desc);
  timeCoord.setCachedData(timesArray, true);
  timeCoord.addAttribute(new Attribute(_Coordinate.AxisType, AxisType.Time.toString()));
  ds.addCoordinateAxis(timeCoord);

  parseInfo.format(" added coordinate variable %s%n", dimName);

  // now make the original variable use the new dimension
  List<Dimension> dimsList = new ArrayList(ncVar.getDimensions());
  dimsList.set(0, newDim);
  ncVar.setDimensions(dimsList);

  // better to explicitly set the coordinate system
  ncVar.addAttribute(new Attribute(_Coordinate.Axes, dimName + " yCoord xCoord"));

  // fix the attributes
  Attribute att = ncVar.findAttribute("fillValue");
  if (att != null)
    ncVar.addAttribute(new Attribute(CDM.FILL_VALUE, att.getNumericValue()));
  att = ncVar.findAttribute("descriptiveName");
  if (null != att)
    ncVar.addAttribute(new Attribute(CDM.LONG_NAME, att.getStringValue()));

  // ncVar.enhance();
}
 
Example 20
Source File: AWIPSConvention.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private CoordinateAxis makeTimeCoordAxis(NetcdfDataset ds) {
  Variable timeVar = ds.findVariable("valtimeMINUSreftime");
  Dimension recordDim = ds.findDimension("record");
  Array vals;

  try {
    vals = timeVar.read();
  } catch (IOException ioe) {
    return null;
  }

  // it seems that the record dimension does not always match valtimeMINUSreftime dimension!!
  // HAHAHAHAHAHAHAHA !
  int recLen = recordDim.getLength();
  int valLen = (int) vals.getSize();
  if (recLen != valLen) {
    try {
      vals = vals.sectionNoReduce(new int[] {0}, new int[] {recordDim.getLength()}, null);
      parseInfo.format(" corrected the TimeCoordAxis length%n");
    } catch (InvalidRangeException e) {
      parseInfo.format("makeTimeCoordAxis InvalidRangeException%n");
    }
  }

  // create the units out of the filename if possible
  String units = makeTimeUnitFromFilename(ds.getLocation());
  if (units == null) // ok that didnt work, try something else
    return makeTimeCoordAxisFromReference(ds, timeVar, vals);

  // create the coord axis
  String desc = "synthesized time coordinate from valtimeMINUSreftime and filename YYYYMMDD_HHMM";
  CoordinateAxis1D timeCoord = new CoordinateAxis1D(ds, null, "timeCoord", DataType.INT, "record", units, desc);

  timeCoord.setCachedData(vals, true);

  parseInfo.format("Created Time Coordinate Axis = ");
  timeCoord.getNameAndDimensions(parseInfo, true, false);
  parseInfo.format("%n");

  return timeCoord;
}