ucar.ma2.Range Java Examples

The following examples show how to use ucar.ma2.Range. 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: CoordAxisHelper.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
Optional<CoverageCoordAxisBuilder> subsetContaining(double want) {
  int index = findCoordElement(want, false); // not bounded, may not be valid index
  if (index < 0 || index >= axis.getNcoords())
    return Optional.empty(String.format("value %f not in axis %s", want, axis.getName()));

  double val = axis.getCoordMidpoint(index);

  CoverageCoordAxisBuilder builder = new CoverageCoordAxisBuilder(axis);
  builder.subset(1, val, val, 0.0, makeValues(index));
  try {
    builder.setRange(new Range(index, index));
  } catch (InvalidRangeException e) {
    throw new RuntimeException(e); // cant happen
  }
  return Optional.of(builder);
}
 
Example #2
Source File: FmrcDataset.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private Array read(TimeInventory.Instance timeInstance, String fullNameEsc, List<Range> innerSection,
    HashMap<String, NetcdfDataset> openFilesRead) throws IOException, InvalidRangeException {
  NetcdfFile ncfile = open(timeInstance.getDatasetLocation(), openFilesRead);
  if (ncfile == null)
    return null; // file might be deleted ??

  Variable v = ncfile.findVariable(fullNameEsc);
  if (v == null)
    return null; // v could be missing, return missing data i think

  // assume time is first dimension LOOK: out of-order; ensemble; section different ??
  Range timeRange = new Range(timeInstance.getDatasetIndex(), timeInstance.getDatasetIndex());
  Section.Builder sb = Section.builder().appendRanges(innerSection);
  sb.insertRange(0, timeRange);
  return v.read(sb.build());
}
 
Example #3
Source File: LayoutTiled.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Constructor.
 *
 * @param chunkIterator iterator over all available data chunks
 * @param chunkSize all chunks assumed to be the same size
 * @param elemSize size of an element in bytes.
 * @param wantSection the wanted section of data, contains a List of Range objects. Must be complete
 */
public LayoutTiled(DataChunkIterator chunkIterator, int[] chunkSize, int elemSize, Section wantSection) {
  this.chunkIterator = chunkIterator;
  this.chunkSize = chunkSize;
  this.elemSize = elemSize;
  this.want = wantSection;
  if (this.want.isVariableLength()) {
    // remove the varlen
    List<Range> newrange = new ArrayList<>(this.want.getRanges());
    newrange.remove(newrange.size() - 1);
    this.want = new Section(newrange);
  }

  this.totalNelems = this.want.computeSize();
  this.totalNelemsDone = 0;
}
 
Example #4
Source File: TestSectionFillValue.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testExplicitFillValue() throws Exception {
  String filename = TestDir.cdmLocalTestDataDir + "standardVar.nc";
  try (NetcdfDataset ncfile = NetcdfDatasets.openDataset(filename)) {
    VariableDS v = (VariableDS) ncfile.findVariable("t3");
    Assert.assertNotNull("t3", v);
    Assert.assertTrue(v.hasFillValue());
    Assert.assertNotNull(v.findAttribute("_FillValue"));

    int rank = v.getRank();
    List<Range> ranges = new ArrayList<>();
    ranges.add(null);
    for (int i = 1; i < rank; i++) {
      ranges.add(new Range(0, 1));
    }

    VariableDS v_section = (VariableDS) v.section(ranges);
    Assert.assertNotNull(v_section.findAttribute("_FillValue"));
    System.out.println(v_section.findAttribute("_FillValue"));
    Assert.assertTrue(v_section.hasFillValue());
  }
}
 
Example #5
Source File: TestGridSubset.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
@Ignore("Does this file exist in a shared location?")
public void testAaron() throws Exception {
  // different scale/offset in aggregation
  try (GridDataset dataset = GridDataset.open("G:/work/braekel/dataset.ncml")) {
    GridDatatype grid = null;
    for (GridDatatype thisGrid : dataset.getGrids()) {
      if (thisGrid.getName().equals("cref")) {
        grid = thisGrid;
      }
    }
    List<Range> ranges = new ArrayList<Range>();
    ranges.add(new Range(0, 0));
    ranges.add(new Range(0, 0));
    ranges.add(new Range(638, 638));
    ranges.add(new Range(3750, 4622));

    Array arr = grid.getVariable().read(ranges);
    Index index = arr.getIndex();
    index.set(new int[] {0, 0, 0, 834});
    logger.debug("index {} value {}", index.currentElement(), arr.getDouble(index));
  }
}
 
Example #6
Source File: OpendapServlet.java    From tds with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
long computeArraySize(SDArray da) throws Exception {
  assert (da.getContainerVar() instanceof DPrimitive);
  BaseType base = da.getPrimitiveVector().getTemplate();
  DataType dtype = DODSNetcdfFile.convertToNCType(base, false);
  int elemSize = dtype.getSize();
  int n = da.numDimensions();
  List<Range> ranges = new ArrayList<>(n);
  long size = 0;
  for (int i = 0; i < n; i++) {
    ranges.add(new Range(da.getStart(i), da.getStop(i), da.getStride(i)));
  }
  Section s = new Section(ranges);
  size += s.computeSize() * elemSize;

  return size;
}
 
Example #7
Source File: CDMUtil.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Test a List<Range> against a List<DapDimension>
 * to see if the range list represents the whole
 * set of dimensions within the specified indices.
 *
 * @param rangelist the set of ucar.ma2.Range
 * @param dimset the set of DapDimensions
 * @param start start looking here
 * @param stop stop looking here
 * @result true if rangelist is whole; false otherwise.
 */

public static boolean isWhole(List<Range> rangelist, List<DapDimension> dimset, int start, int stop)
    throws dap4.core.util.DapException {
  int rsize = (rangelist == null ? 0 : rangelist.size());
  if (rsize != dimset.size())
    throw new dap4.core.util.DapException("range/dimset rank mismatch");
  if (rsize == 0)
    return true;
  if (start < 0 || stop < start || stop > rsize)
    throw new dap4.core.util.DapException("Invalid start/stop indices");

  for (int i = start; i < stop; i++) {
    Range r = rangelist.get(i);
    DapDimension d = dimset.get(i);
    if (r.stride() != 1 || r.first() != 0 || r.length() != d.getSize())
      return false;
  }
  return true;
}
 
Example #8
Source File: TestGridSubsetCoordinateSystem.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testGridDomain() throws Exception {
  System.err.printf("%nOpen %s grid='%s'%n", filename, gridName);
  Grib.setDebugFlags(new DebugFlagsImpl("Grib/indexOnly"));
  try (GridDataset dataset = GridDataset.open(filename)) {
    GeoGrid grid = dataset.findGridByName(gridName);
    GridCoordSystem gcs = grid.getCoordinateSystem();
    System.err.printf("%s%n", gcs);
    testDomain("original grid", grid.getDimensions(), gcs.getCoordinateAxes());

    GridDatatype gridSubset = grid.makeSubset(null, null, new Range(0, 0), null, null, null);
    GridCoordSystem gcsSubset = gridSubset.getCoordinateSystem();
    System.err.printf("%s%n", gcsSubset);
    testDomain("subset grid", gridSubset.getDimensions(), gcsSubset.getCoordinateAxes());

  } finally {
    Grib.setDebugFlags(new DebugFlagsImpl(""));
  }
}
 
Example #9
Source File: N3iospWriter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void fillRecordVariables(int recStart, int recEnd) throws IOException, InvalidRangeException {
  // do each record completely, should be a bit more efficient

  for (int i = recStart; i < recEnd; i++) { // do one record at a time
    Range r = new Range(i, i);

    // run through each variable
    for (Variable v : ncfile.getVariables()) {
      if (!v.isUnlimited() || (v instanceof Structure))
        continue;
      Section.Builder recordSection = Section.builder().appendRanges(v.getRanges());
      recordSection.setRange(0, r);
      writeData(v, recordSection.build(), makeConstantArray(v));
    }
  }
}
 
Example #10
Source File: Cinrad2Record.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void readData1(RandomAccessFile raf, int datatype, Range gateRange, IndexIterator ii) throws IOException {
  long offset = message_offset;
  offset += MESSAGE_HEADER_SIZE; // offset is from "start of digital radar data message header"
  offset += getDataOffset(datatype);
  raf.seek(offset);
  if (logger.isDebugEnabled()) {
    logger.debug("  read recno " + recno + " at offset " + offset + " count= " + getGateCount(datatype));
    logger.debug(
        "   offset: reflect= " + reflect_offset + " velocity= " + velocity_offset + " spWidth= " + spectWidth_offset);
  }

  int dataCount = getGateCount(datatype);
  short[] data = new short[dataCount];
  raf.readShort(data, 0, dataCount);

  for (int idx : gateRange) {
    if (idx >= dataCount)
      ii.setShortNext((short) -32768);
    else
      ii.setShortNext(data[idx]);
  }

}
 
Example #11
Source File: AggDatasetOuter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Get the desired Range, reletive to this Dataset, if no overlap, return null.
 * <p>
 * wantStart, wantStop are the indices in the aggregated dataset, wantStart <= i < wantEnd.
 * if this overlaps, set the Range required for the nested dataset.
 * note this should handle strides ok.
 *
 * @param totalRange desired range, reletive to aggregated dimension.
 * @return desired Range or null if theres nothing wanted from this datase.
 * @throws InvalidRangeException if invalid range request
 */
protected Range getNestedJoinRange(Range totalRange) throws InvalidRangeException {
  int wantStart = totalRange.first();
  int wantStop = totalRange.last() + 1; // Range has last inclusive, we use last exclusive

  // see if this dataset is needed
  if (!isNeeded(wantStart, wantStop))
    return null;

  int firstInInterval = totalRange.getFirstInInterval(aggStart);
  if ((firstInInterval < 0) || (firstInInterval >= aggEnd))
    return null;

  int start = Math.max(firstInInterval, wantStart) - aggStart;
  int stop = Math.min(aggEnd, wantStop) - aggStart;

  return new Range(start, stop - 1, totalRange.stride()); // Range has last inclusive
}
 
Example #12
Source File: Ray.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Read data from this ray.
 *
 * @param raf read from this file
 * @param abbrev which data type we want
 * @param gateRange handles the possible subset of data to return
 * @param ii put the data here
 */
public void readData(RandomAccessFile raf, String abbrev, Range gateRange, IndexIterator ii) throws IOException {
  long offset = rayOffset;
  offset += (getDataOffset(abbrev) * 2 - 2);
  raf.seek(offset);
  byte[] b2 = new byte[2];
  int dataCount = getGateCount(abbrev);
  byte[] data = new byte[dataCount * 2];
  raf.readFully(data);

  for (int gateIdx : gateRange) {
    if (gateIdx >= dataCount)
      ii.setShortNext(uf_header2.missing);
    else {
      b2[0] = data[gateIdx * 2];
      b2[1] = data[gateIdx * 2 + 1];
      short value = getShort(b2, 0);

      ii.setShortNext(value);
    }
  }

}
 
Example #13
Source File: GradsBinaryGridServiceProvider.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Read the data for the variable
 *
 * @param v2 Variable to read
 * @param section section infomation
 * @return Array of data
 * @throws IOException problem reading from file
 * @throws InvalidRangeException invalid Range
 */
public Array readData(Variable v2, Section section) throws IOException, InvalidRangeException {

  Array dataArray = Array.factory(DataType.FLOAT, section.getShape());
  GradsVariable gradsVar = findVar(v2);
  if (gradsVar == null)
    throw new IOException();

  // Canonical ordering is ens, time, level, lat, lon
  int rangeIdx = 0;
  Range ensRange = (gradsDDF.getEnsembleDimension() != null) ? section.getRange(rangeIdx++) : new Range(0, 0);
  Range timeRange = (section.getRank() > 2) ? section.getRange(rangeIdx++) : new Range(0, 0);
  Range levRange = (gradsVar.getNumLevels() > 0) ? section.getRange(rangeIdx++) : new Range(0, 0);
  Range yRange = section.getRange(rangeIdx++);
  Range xRange = section.getRange(rangeIdx);

  IndexIterator ii = dataArray.getIndexIterator();

  for (int ensIdx : ensRange)
    for (int timeIdx : timeRange)
      for (int levelIdx : levRange)
        readXY(v2, ensIdx, timeIdx, levelIdx, yRange, xRange, ii);

  return dataArray;
}
 
Example #14
Source File: Structure.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void readNextGeneralRank() throws IOException {

      try {
        Section.Builder sb = Section.builder().appendRanges(shape);
        sb.setRange(0, new Range(outerCount, outerCount));

        as = (ArrayStructure) read(sb.build());

        if (NetcdfFile.debugStructureIterator)
          System.out.println("readNext inner=" + outerCount + " total=" + outerCount);

        outerCount++;

      } catch (InvalidRangeException e) {
        log.error("Structure.Iterator.readNext() ", e);
        throw new IllegalStateException("Structure.Iterator.readNext() ", e);
      } // cant happen

      readStart += as.getSize();
      readCount = 0;
    }
 
Example #15
Source File: AggregationOuterDimension.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Get the desired Range, reletive to this Dataset, if no overlap, return null.
 * <p>
 * wantStart, wantStop are the indices in the aggregated dataset, wantStart <= i < wantEnd.
 * if this overlaps, set the Range required for the nested dataset.
 * note this should handle strides ok.
 *
 * @param totalRange desired range, reletive to aggregated dimension.
 * @return desired Range or null if theres nothing wanted from this datase.
 * @throws InvalidRangeException if invalid range request
 */
protected Range getNestedJoinRange(Range totalRange) throws InvalidRangeException {
  int wantStart = totalRange.first();
  int wantStop = totalRange.last() + 1; // Range has last inclusive, we use last exclusive

  // see if this dataset is needed
  if (!isNeeded(wantStart, wantStop))
    return null;

  int firstInInterval = totalRange.getFirstInInterval(aggStart);
  if ((firstInInterval < 0) || (firstInInterval >= aggEnd))
    return null;

  int start = Math.max(firstInInterval, wantStart) - aggStart;
  int stop = Math.min(aggEnd, wantStop) - aggStart;

  return new Range(start, stop - 1, totalRange.stride()); // Range has last inclusive
}
 
Example #16
Source File: Aggregation.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Read a section of the local Variable.
 *
 * @param mainv aggregated Variable
 * @param cancelTask let user cancel
 * @param section reletive to the local Variable
 * @return the complete Array for mainv
 * @throws IOException on I/O error
 * @throws InvalidRangeException on section error
 */
protected Array read(Variable mainv, CancelTask cancelTask, List<Range> section)
    throws IOException, InvalidRangeException {
  NetcdfFile ncd = null;
  try {
    ncd = acquireFile(cancelTask);
    if ((cancelTask != null) && cancelTask.isCancel())
      return null;

    Variable v = findVariable(ncd, mainv);
    if (debugRead) {
      Section want = new Section(section);
      System.out.printf("Agg.read(%s) %s from %s in %s%n", want, mainv.getNameAndDimensions(),
          v.getNameAndDimensions(), getLocation());
    }

    return v.read(section);

  } finally {
    close(ncd);
  }
}
 
Example #17
Source File: NcStream.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Nonnull
public static Section decodeSection(NcStreamProto.Section proto) {
  Section.Builder section = Section.builder();

  for (ucar.nc2.stream.NcStreamProto.Range pr : proto.getRangeList()) {
    try {
      long stride = pr.getStride();
      if (stride == 0)
        stride = 1; // default in protobuf2 was 1, but protobuf3 is 0, luckily 0 is illegal
      if (pr.getSize() == 0)
        section.appendRange(Range.EMPTY); // used for scalars LOOK really used ??
      else {
        // this.last = first + (this.length-1) * stride;
        section.appendRange((int) pr.getStart(), (int) (pr.getStart() + (pr.getSize() - 1) * stride), (int) stride);
      }

    } catch (InvalidRangeException e) {
      throw new RuntimeException("Bad Section in ncstream", e);
    }
  }
  return section.build();
}
 
Example #18
Source File: CoordAxisHelper.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Nonnull
private CoverageCoordAxisBuilder subsetValuesClosest(double[] want) {
  int closest_index = findCoordElement(want, true); // bounded, always valid index

  CoverageCoordAxisBuilder builder = new CoverageCoordAxisBuilder(axis);

  if (axis.spacing == CoverageCoordAxis.Spacing.regularInterval) {
    double val1 = axis.getCoordEdge1(closest_index);
    double val2 = axis.getCoordEdge2(closest_index);
    builder.subset(1, val1, val2, val2 - val1, null);
  } else {
    builder.subset(1, 0, 0, 0.0, makeValues(closest_index));
  }

  try {
    builder.setRange(new Range(closest_index, closest_index));
  } catch (InvalidRangeException e) {
    throw new RuntimeException(e); // cant happen
  }
  return builder;
}
 
Example #19
Source File: CoordAxisHelper.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Nonnull
private CoverageCoordAxisBuilder subsetValuesClosest(double want) {
  int closest_index = findCoordElement(want, true); // bounded, always valid index
  CoverageCoordAxisBuilder builder = new CoverageCoordAxisBuilder(axis);

  if (axis.spacing == CoverageCoordAxis.Spacing.regularPoint) {
    double val = axis.getCoordMidpoint(closest_index);
    builder.subset(1, val, val, 0.0, null);

  } else if (axis.spacing == CoverageCoordAxis.Spacing.regularInterval) {
    double val1 = axis.getCoordEdge1(closest_index);
    double val2 = axis.getCoordEdge2(closest_index);
    builder.subset(1, val1, val2, val2 - val1, null);

  } else {
    builder.subset(1, 0, 0, 0.0, makeValues(closest_index));
  }

  try {
    builder.setRange(new Range(closest_index, closest_index));
  } catch (InvalidRangeException e) {
    throw new RuntimeException(e); // cant happen
  }
  return builder;
}
 
Example #20
Source File: AggDataset.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Read a section of the local Variable.
 *
 * @param mainv aggregated Variable
 * @param cancelTask let user cancel
 * @param section reletive to the local Variable
 * @return the complete Array for mainv
 * @throws IOException on I/O error
 * @throws InvalidRangeException on section error
 */
protected Array read(Variable mainv, CancelTask cancelTask, List<Range> section)
    throws IOException, InvalidRangeException {
  NetcdfFile ncd = null;
  try {
    ncd = acquireFile(cancelTask);
    if ((cancelTask != null) && cancelTask.isCancel())
      return null;

    Variable v = findVariable(ncd, mainv);
    if (debugRead) {
      Section want = new Section(section);
      System.out.printf("Agg.read(%s) %s from %s in %s%n", want, mainv.getNameAndDimensions(),
          v.getNameAndDimensions(), getLocation());
    }

    return v.read(section);

  } finally {
    close(ncd);
  }
}
 
Example #21
Source File: Cinrad2Record.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Read data from this record.
 * 
 * @param raf read from this file
 * @param datatype which data type we want
 * @param gateRange handles the possible subset of data to return
 * @param ii put the data here
 */
public void readData(RandomAccessFile raf, int datatype, Range gateRange, IndexIterator ii) throws IOException {
  long offset = message_offset;
  offset += MESSAGE_HEADER_SIZE; // offset is from "start of digital radar data message header"
  offset += getDataOffset(datatype);
  raf.seek(offset);
  if (logger.isDebugEnabled()) {
    logger.debug("  read recno " + recno + " at offset " + offset + " count= " + getGateCount(datatype));
    logger.debug(
        "   offset: reflect= " + reflect_offset + " velocity= " + velocity_offset + " spWidth= " + spectWidth_offset);
  }

  int dataCount = getGateCount(datatype);
  byte[] data = new byte[dataCount];
  raf.readFully(data);

  for (int gateIdx : gateRange) {
    if (gateIdx >= dataCount)
      ii.setByteNext(MISSING_DATA);
    else
      ii.setByteNext(data[gateIdx]);
  }

}
 
Example #22
Source File: N3iospNew.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private long readRecordData(ucar.nc2.Structure s, Section section, WritableByteChannel out)
    throws java.io.IOException {
  long count = 0;

  /*
   * RegularIndexer index = new RegularIndexer( s.getShape(), recsize, recStart, section, recsize);
   * while (index.hasNext()) {
   * Indexer.Chunk chunk = index.next();
   * count += raf.readBytes( out, chunk.getFilePos(), chunk.getNelems() * s.getElementSize());
   * }
   */

  // LOOK this is the OTW layout based on netcdf-3
  // not sure this works but should give an idea of timing
  Range recordRange = section.getRange(0);
  /*
   * int stride = recordRange.stride();
   * if (stride == 1) {
   * int first = recordRange.first();
   * int n = recordRange.length();
   * if (false) System.out.println(" read record " + first+" "+ n * header.recsize+" bytes ");
   * return raf.readToByteChannel(out, header.recStart + first * header.recsize, n * header.recsize);
   *
   * } else {
   */

  for (int recnum : recordRange) {
    if (debugRecord)
      System.out.println(" read record " + recnum);
    raf.seek(header.recStart + recnum * header.recsize); // where the record starts
    count += raf.readToByteChannel(out, header.recStart + recnum * header.recsize, header.recsize);
  }
  // }

  return count;
}
 
Example #23
Source File: ReduceReader.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Array reallyRead(Variable client, Section section, CancelTask cancelTask)
    throws IOException, InvalidRangeException {
  Section.Builder orgSection = Section.builder().appendRanges(section.getRanges());
  for (int dim : dims) {
    orgSection.insertRange(dim, Range.ONE); // lowest first
  }

  Array data = orgClient._read(orgSection.build());
  for (int i = dims.size() - 1; i >= 0; i--)
    data = data.reduce(dims.get(i)); // highest first

  return data;
}
 
Example #24
Source File: N3iospWriter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void writeData(Variable v2, Section section, Array values) throws java.io.IOException, InvalidRangeException {
  N3headerNew.Vinfo vinfo = (N3headerNew.Vinfo) v2.getSPobject();
  DataType dataType = v2.getDataType();

  if (v2.isUnlimited()) {
    Range firstRange = section.getRange(0);
    setNumrecs(firstRange.last() + 1);
  }

  if (v2 instanceof Structure) {
    if (!(values instanceof ArrayStructure))
      throw new IllegalArgumentException("writeData for Structure: data must be ArrayStructure");

    if (v2.getRank() == 0)
      throw new IllegalArgumentException("writeData for Structure: must have rank > 0");

    Dimension d = v2.getDimension(0);
    if (!d.isUnlimited())
      throw new IllegalArgumentException("writeData for Structure: must have unlimited dimension");

    writeRecordData((Structure) v2, section, (ArrayStructure) values);

  } else {
    Layout layout = (!v2.isUnlimited()) ? new LayoutRegular(vinfo.begin, v2.getElementSize(), v2.getShape(), section)
        : new LayoutRegularSegmented(vinfo.begin, v2.getElementSize(), header.recsize, v2.getShape(), section);
    writeData(values, layout, dataType);
  }
}
 
Example #25
Source File: NcStream.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static NcStreamProto.Section encodeSection(Section section) {
  NcStreamProto.Section.Builder sbuilder = NcStreamProto.Section.newBuilder();
  for (Range r : section.getRanges()) {
    NcStreamProto.Range.Builder rbuilder = NcStreamProto.Range.newBuilder();
    rbuilder.setStart(r.first());
    rbuilder.setSize(r.length());
    rbuilder.setStride(r.stride());
    sbuilder.addRange(rbuilder);
  }
  return sbuilder.build();
}
 
Example #26
Source File: CoordAxisHelper.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nonnull
private CoverageCoordAxisBuilder subsetValuesLatest() {
  int last = axis.getNcoords() - 1;
  double val = axis.getCoordMidpoint(last);

  CoverageCoordAxisBuilder builder = new CoverageCoordAxisBuilder(axis);
  builder.subset(1, val, val, 0.0, makeValues(last));
  try {
    builder.setRange(new Range(last, last));
  } catch (InvalidRangeException e) {
    throw new RuntimeException(e); // cant happen
  }
  return builder;
}
 
Example #27
Source File: CdmrGridController.java    From tds with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@RequestMapping(value = "/**", method = RequestMethod.GET, params = "req=coord")
public void handleCoordRequest(HttpServletRequest request, HttpServletResponse response, @RequestParam String var,
    OutputStream out) throws IOException, BindException, InvalidRangeException {

  if (!allowedServices.isAllowed(StandardService.cdmrFeatureGrid))
    throw new ServiceNotAllowed(StandardService.cdmrFeatureGrid.toString());

  String datasetPath = TdsPathUtils.extractPath(request, StandardService.cdmrFeatureGrid.getBase());

  try (CoverageCollection gridCoverageDataset =
      TdsRequestedDataset.getCoverageCollection(request, response, datasetPath)) {
    if (gridCoverageDataset == null)
      return;

    response.setContentType(ContentType.binary.getContentHeader());
    response.setHeader("Content-Description", "ncstream");

    String[] coordNames = var.split(",");
    for (String coordName : coordNames) {
      CoverageCoordAxis coord = gridCoverageDataset.findCoordAxis(coordName);
      double[] values;
      if (!coord.isRegular())
        values = coord.getValues();
      else {
        values = new double[coord.getNcoords()];
        for (int i = 0; i < values.length; i++)
          values[i] = coord.getStartValue() + i * coord.getResolution();
      }
      sendCoordData(coord.getName(), new Section(new Range(values.length)), Array.makeFromJavaArray(values), out);
    }
    out.flush();

  } catch (Throwable t) {
    throw new RuntimeException("CdmrGridController on dataset " + datasetPath, t);
  }
}
 
Example #28
Source File: CDMUtil.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Convert a list of ucar.ma2.Range to a list of Slice
 * More or less the inverst of create CDMRanges
 *
 * @param rangelist the set of ucar.ma2.Range
 * @result the equivalent list of Slice
 */
public static List<Slice> createSlices(List<Range> rangelist) throws dap4.core.util.DapException {
  List<Slice> slices = new ArrayList<Slice>(rangelist.size());
  for (int i = 0; i < rangelist.size(); i++) {
    Range r = rangelist.get(i);
    // r does not store last
    int stride = r.stride();
    int first = r.first();
    int n = r.length();
    int stop = first + (n * stride);
    Slice cer = new Slice(first, stop - 1, stride);
    slices.add(cer);
  }
  return slices;
}
 
Example #29
Source File: N3iospWriter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void writeRecordData(ucar.nc2.Structure s, Section section, ArrayStructure structureArray)
    throws java.io.IOException, ucar.ma2.InvalidRangeException {
  int countSrcRecnum = 0;
  Range recordRange = section.getRange(0);
  for (int recnum : recordRange) {
    StructureData sdata = structureArray.getStructureData(countSrcRecnum);
    writeRecordData(s, recnum, sdata);
    countSrcRecnum++;
  }
}
 
Example #30
Source File: DataTable.java    From MeteoInfo with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Get data rows
 *
 * @param range Range
 * @return DataRowCollection The data rows
 */
public DataRowCollection getRows(Range range) {
    DataRowCollection r = new DataRowCollection();
    for (int i = range.first(); i < range.last(); i++){
        r.add(this.rows.get(i));
    }
    return r;
}