ucar.ma2.Index Java Examples

The following examples show how to use ucar.ma2.Index. 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: Attribute.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Create a scalar numeric-valued Attribute, possibly unsigned.
 *
 * @param name name of Attribute
 * @param val value of Attribute
 * @param isUnsigned if value is unsigned, used only for integer types.
 */
public Attribute(String name, Number val, boolean isUnsigned) {
  super(name);
  if (name == null)
    throw new IllegalArgumentException("Trying to set name to null on " + this);

  int[] shape = new int[1];
  shape[0] = 1;
  DataType dt = DataType.getType(val.getClass(), isUnsigned);
  this.dataType = dt;
  Array vala = Array.factory(dt, shape);
  Index ima = vala.getIndex();
  vala.setObject(ima.set0(0), val);
  setValues(vala); // make private
  setImmutable();
}
 
Example #2
Source File: Structure.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Use this when this is a one dimensional array of Structures, or you are doing the index calculation yourself for
 * a multidimension array. This will read only the ith structure, and return the data as a StructureData object.
 * 
 * @param index index into 1D array
 * @return ith StructureData
 * @throws java.io.IOException on read error
 * @throws ucar.ma2.InvalidRangeException if index out of range
 */
public StructureData readStructure(int index) throws IOException, ucar.ma2.InvalidRangeException {
  Section.Builder sb = Section.builder();

  if (getRank() == 1) {
    sb.appendRange(index, index);

  } else if (getRank() > 1) {
    Index ii = Index.factory(shape); // convert to nD index
    ii.setCurrentCounter(index);
    int[] origin = ii.getCurrentCounter();
    for (int anOrigin : origin)
      sb.appendRange(anOrigin, anOrigin);
  }

  Array dataArray = read(sb.build());
  ArrayStructure data = (ArrayStructure) dataArray;
  return data.getStructureData(0);
}
 
Example #3
Source File: AtmosSigma.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Get the 1D vertical coordinate array for this time step and point
 * 
 * (needds test!!!)
 * 
 * @param timeIndex the time index. Ignored if !isTimeDependent().
 * @param xIndex the x index
 * @param yIndex the y index
 * @return vertical coordinate array
 * @throws java.io.IOException problem reading data
 * @throws ucar.ma2.InvalidRangeException _more_
 */
public D1 getCoordinateArray1D(int timeIndex, int xIndex, int yIndex) throws IOException, InvalidRangeException {

  Array ps = readArray(psVar, timeIndex);
  Index psIndex = ps.getIndex();
  int nz = sigma.length;
  ArrayDouble.D1 result = new ArrayDouble.D1(nz);

  double psVal = ps.getDouble(psIndex.set(yIndex, xIndex));
  for (int z = 0; z < nz; z++) {
    result.set(z, ptop + sigma[z] * (psVal - ptop));
  }

  return result;

}
 
Example #4
Source File: AtmosSigma.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Get the 3D vertical coordinate array for this time step.
 *
 * @param timeIndex the time index. Ignored if !isTimeDependent().
 * @return vertical coordinate array
 * @throws IOException problem reading data
 * @throws InvalidRangeException _more_
 */
public ArrayDouble.D3 getCoordinateArray(int timeIndex) throws IOException, InvalidRangeException {
  Array ps = readArray(psVar, timeIndex);
  Index psIndex = ps.getIndex();

  int nz = sigma.length;
  int[] shape2D = ps.getShape();
  int ny = shape2D[0];
  int nx = shape2D[1];

  ArrayDouble.D3 result = new ArrayDouble.D3(nz, ny, nx);

  for (int y = 0; y < ny; y++) {
    for (int x = 0; x < nx; x++) {
      double psVal = ps.getDouble(psIndex.set(y, x));
      for (int z = 0; z < nz; z++) {
        result.set(z, y, x, ptop + sigma[z] * (psVal - ptop));
      }
    }
  }

  return result;
}
 
Example #5
Source File: ADASConvention.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void makeCoordAxis(String axisName) throws IOException {
  String name = axisName + "_stag";
  if (!rootGroup.findVariableLocal(name).isPresent()) {
    return;
  }
  VariableDS.Builder stagV = (VariableDS.Builder) rootGroup.findVariableLocal(name).get();
  Array data_stag = stagV.orgVar.read();
  int n = (int) data_stag.getSize() - 1;
  DataType dt = DataType.getType(data_stag);
  Array data = Array.factory(dt, new int[] {n});
  Index stagIndex = data_stag.getIndex();
  Index dataIndex = data.getIndex();
  for (int i = 0; i < n; i++) {
    double val = data_stag.getDouble(stagIndex.set(i)) + data_stag.getDouble(stagIndex.set(i + 1));
    data.setDouble(dataIndex.set(i), 0.5 * val);
  }

  DataType dtype = DataType.getType(data);
  String units = stagV.getAttributeContainer().findAttributeString(CDM.UNITS, "m");
  CoordinateAxis.Builder cb = CoordinateAxis1D.builder().setName(axisName).setDataType(dtype)
      .setParentGroupBuilder(rootGroup).setDimensionsByName(axisName).setUnits(units)
      .setDesc("synthesized non-staggered " + axisName + " coordinate");
  cb.setCachedData(data, true);
  datasetBuilder.replaceCoordinateAxis(rootGroup, cb);
}
 
Example #6
Source File: GeotiffWriter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private double geoShiftGetXstart(Array lon, double inc) {
  Index ilon = lon.getIndex();
  int[] lonShape = lon.getShape();
  IndexIterator lonIter = lon.getIndexIterator();
  double xlon;

  LatLonPoint p0 = LatLonPoint.create(0, lon.getFloat(ilon.set(0)));
  LatLonPoint pN = LatLonPoint.create(0, lon.getFloat(ilon.set(lonShape[0] - 1)));

  xlon = p0.getLongitude();
  while (lonIter.hasNext()) {
    float l = lonIter.getFloatNext();
    LatLonPoint pn = LatLonPoint.create(0, l);
    if (pn.getLongitude() < xlon) {
      xlon = pn.getLongitude();
    }
  }

  if (p0.getLongitude() == pN.getLongitude()) {
    xlon = xlon - inc;
  }

  return xlon;
}
 
Example #7
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 #8
Source File: TestAggFmrc.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testDataValues() throws IOException {
  Array valuesScan = varScan.read();
  Array valuesExplicit = varExplicit.read();
  List<int[]> idxs = new ArrayList<>();
  idxs.add(new int[] {0, 0, 0, 0, 0});
  idxs.add(new int[] {2, 20, 5, 38, 44});
  idxs.add(new int[] {1, 10, 3, 19, 22});

  Index idx = Index.factory(valuesScan.getShape());

  for (int[] loc : idxs) {
    idx.set(loc);
    float a = valuesScan.getFloat(idx);
    float b = valuesExplicit.getFloat(idx);
    Assert.assertEquals(a, b, 0);
  }
}
 
Example #9
Source File: CDMArrayAtomic.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Get the array element at a specific dap4 index as a float
 * converting as needed.
 *
 * @param idx of element to get
 * @return value at <code>index</code> cast to float if necessary.
 */
protected float getFloat(dap4.core.util.Index idx) {
  assert data.getScheme() == Scheme.ATOMIC;
  try {
    Object value = data.read(idx);
    value = Convert.convert(DapType.FLOAT32, this.basetype, value);
    return (Float) java.lang.reflect.Array.get(value, 0);
  } catch (IOException ioe) {
    throw new IndexOutOfBoundsException(ioe.getMessage());
  }
}
 
Example #10
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 #11
Source File: CDMArrayAtomic.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Get the array element at a specific dap4 index as a long
 *
 * @param idx of element to get
 * @return value at <code>index</code> cast to long if necessary.
 */
protected long getLong(dap4.core.util.Index idx) {
  assert data.getScheme() == Scheme.ATOMIC;
  try {
    Object value = data.read(idx);
    value = Convert.convert(DapType.INT64, this.basetype, value);
    return (Long) java.lang.reflect.Array.get(value, 0);
  } catch (IOException ioe) {
    throw new IndexOutOfBoundsException(ioe.getMessage());
  }
}
 
Example #12
Source File: CDMArrayAtomic.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Get the array element at a specific dap4 index as a integer
 *
 * @param idx of element to get
 * @return value at <code>index</code> cast to integer if necessary.
 */
protected int getInt(dap4.core.util.Index idx) {
  assert data.getScheme() == Scheme.ATOMIC;
  try {
    Object value = data.read(idx);
    value = Convert.convert(DapType.INT32, this.basetype, value);
    return (Integer) java.lang.reflect.Array.get(value, 0);
  } catch (IOException ioe) {
    throw new IndexOutOfBoundsException(ioe.getMessage());
  }
}
 
Example #13
Source File: CDMArrayAtomic.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Get the array element at a specific dap4 index as a short
 *
 * @param idx of element to get
 * @return value at <code>index</code> cast to short if necessary.
 */
protected short getShort(dap4.core.util.Index idx) {
  assert data.getScheme() == Scheme.ATOMIC;
  try {
    Object value = data.read(idx);
    value = Convert.convert(DapType.INT16, this.basetype, value);
    return (Short) java.lang.reflect.Array.get(value, 0);
  } catch (IOException ioe) {
    throw new IndexOutOfBoundsException(ioe.getMessage());
  }
}
 
Example #14
Source File: CDMArrayAtomic.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Get the array element at a specific dap4 index as a byte
 *
 * @param idx of element to get
 * @return value at <code>index</code> cast to byte if necessary.
 */
protected byte getByte(dap4.core.util.Index idx) {
  assert data.getScheme() == Scheme.ATOMIC;
  try {
    Object value = data.read(idx);
    value = Convert.convert(DapType.INT8, this.basetype, value);
    return (Byte) java.lang.reflect.Array.get(value, 0);
  } catch (IOException ioe) {
    throw new IndexOutOfBoundsException(ioe.getMessage());
  }
}
 
Example #15
Source File: CDMArrayAtomic.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Get the array element at a specific dap4 index as a char
 *
 * @param idx of element to get
 * @return value at <code>index</code> cast to char if necessary.
 */
protected char getChar(dap4.core.util.Index idx) {
  assert data.getScheme() == Scheme.ATOMIC;
  try {
    Object value = data.read(idx);
    value = Convert.convert(DapType.CHAR, this.basetype, value);
    return (Character) java.lang.reflect.Array.get(value, 0);
  } catch (IOException ioe) {
    throw new IndexOutOfBoundsException(ioe.getMessage());
  }
}
 
Example #16
Source File: CDMArrayAtomic.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Get the array element at a specific dap4 index as a boolean
 *
 * @param idx of element to get
 * @return value at <code>index</code> cast to char if necessary.
 */
protected boolean getBoolean(dap4.core.util.Index idx) {
  assert data.getScheme() == Scheme.ATOMIC;
  try {
    Object value = data.read(idx);
    value = Convert.convert(DapType.INT64, this.basetype, value);
    return ((Long) java.lang.reflect.Array.get(value, 0)) != 0;
  } catch (IOException ioe) {
    throw new IndexOutOfBoundsException(ioe.getMessage());
  }
}
 
Example #17
Source File: CDMArrayAtomic.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Get the array element at a specific dap4 index as an Object
 *
 * @param idx of element to get
 * @return value at <code>index</code> cast to Object if necessary.
 */
protected Object getObject(dap4.core.util.Index idx) {
  assert data.getScheme() == Scheme.ATOMIC;
  try {
    Object value = data.read(idx);
    value = java.lang.reflect.Array.get(value, 0);
    return value;
  } catch (IOException ioe) {
    throw new IndexOutOfBoundsException(ioe.getMessage());
  }
}
 
Example #18
Source File: GeotiffWriter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void dump(Array data, int col) {
  int[] shape = data.getShape();
  Index ima = data.getIndex();

  for (int j = 0; j < shape[0]; j++) {
    float dd = data.getFloat(ima.set(j, col));
    System.out.println(j + " value= " + dd);
  }
}
 
Example #19
Source File: Attribute.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public Builder setNumericValue(Number val, boolean isUnsigned) {
  int[] shape = {1};
  DataType dt = DataType.getType(val.getClass(), isUnsigned);
  setDataType(dt);
  Array vala = Array.factory(dt, shape);
  Index ima = vala.getIndex();
  vala.setObject(ima.set0(0), val);
  setValues(vala);
  return this;
}
 
Example #20
Source File: NetcdfCopier.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private Array convertDataToChar(Variable newVar, Array oldData) {
  ArrayChar newData = (ArrayChar) Array.factory(DataType.CHAR, newVar.getShape());
  Index ima = newData.getIndex();
  IndexIterator ii = oldData.getIndexIterator();
  while (ii.hasNext()) {
    String s = (String) ii.getObjectNext();
    int[] c = ii.getCurrentCounter();
    for (int i = 0; i < c.length; i++) {
      ima.setDim(i, c[i]);
    }
    newData.setString(ima, s);
  }
  return newData;
}
 
Example #21
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 #22
Source File: TestH5.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@org.junit.Test
public void testOffsetCompactLayout() throws IOException {
  try (NetcdfFile ncfile = TestH5.openH5("matlab_cols.mat")) {

    Variable v = ncfile.findVariable("b");
    System.out.printf("%s%n", v);

    Array data = v.read();
    logger.debug("{}", Ncdump.printArray(data, "offset data", null));
    Index ii = data.getIndex();
    assert (data.getDouble(ii.set(3, 2)) == 12.0);

  }
}
 
Example #23
Source File: TestH5.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@org.junit.Test
public void testSuperblockIsOffset() throws IOException {
  try (NetcdfFile ncfile = TestH5.openH5("superblockIsOffsetNPP.h5")) {

    Variable v = ncfile.findVariable("BeamTime");
    System.out.printf("%s%n", v);

    Array data = v.read();
    logger.debug("{}", Ncdump.printArray(data, "offset data", null));
    Index ii = data.getIndex();
    assert (data.getLong(ii.set(11, 93)) == 1718796166693743L);

  }
}
 
Example #24
Source File: TestCoverageSubsetTime.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test // 1 runtime, 1 time (Time2DCoordSys case 1b)
public void test1Runtime1Time() throws IOException, InvalidRangeException {
  String endpoint = TestDir.cdmUnitTestDir + "gribCollections/gfs_2p5deg/gfs_2p5deg.ncx4";
  String covName = "Total_ozone_entire_atmosphere_single_layer";

  logger.debug("test1Runtime1Time Dataset {} coverage {}", endpoint, covName);

  try (FeatureDatasetCoverage cc = CoverageDatasetFactory.open(endpoint)) {
    Assert.assertNotNull(endpoint, cc);
    CoverageCollection gcs = cc.findCoverageDataset(FeatureType.FMRC);
    Assert.assertNotNull("gcs", gcs);
    Coverage cover = gcs.findCoverage(covName);
    Assert.assertNotNull(covName, cover);

    SubsetParams params = new SubsetParams();
    CalendarDate runtime = CalendarDate.parseISOformat(null, "2015-03-01T06:00:00Z");
    params.set(SubsetParams.runtime, runtime);
    CalendarDate time = CalendarDate.parseISOformat(null, "2015-03-01T12:00:00Z");
    params.set(SubsetParams.time, time);
    logger.debug("  subset {}", params);

    GeoReferencedArray geo = cover.readData(params);
    testGeoArray(geo, runtime, time, null);

    Array data = geo.getData();
    Index ai = data.getIndex();
    float testValue = data.getFloat(ai.set(0, 0, 1, 0));
    Assert2.assertNearlyEquals(371.5, testValue);
  }
}
 
Example #25
Source File: CDMArrayAtomic.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Get the array element at a specific dap4 index as a double
 *
 * @param idx of element to get
 * @return value at <code>index</code> cast to double if necessary.
 */
protected double getDouble(dap4.core.util.Index idx) {
  assert data.getScheme() == Scheme.ATOMIC;
  try {
    Object value = data.read(idx);
    value = Convert.convert(DapType.FLOAT64, this.basetype, value);
    return (Double) java.lang.reflect.Array.get(value, 0);
  } catch (IOException ioe) {
    throw new IndexOutOfBoundsException(ioe.getMessage());
  }
}
 
Example #26
Source File: TestCoverageSubsetTime.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test // 1 runtime, 1 time (Time2DCoordSys case 1b)
public void test1Runtime1TimeInterval() throws IOException, InvalidRangeException {
  String endpoint = TestDir.cdmUnitTestDir + "gribCollections/gfs_2p5deg/gfs_2p5deg.ncx4";
  String covName = "Momentum_flux_u-component_surface_Mixed_intervals_Average";

  logger.debug("test1Runtime1TimeInterval Dataset {} coverage {}", endpoint, covName);

  try (FeatureDatasetCoverage cc = CoverageDatasetFactory.open(endpoint)) {
    Assert.assertNotNull(endpoint, cc);
    CoverageCollection gcs = cc.findCoverageDataset(FeatureType.FMRC);
    Assert.assertNotNull("gcs", gcs);
    Coverage cover = gcs.findCoverage(covName);
    Assert.assertNotNull(covName, cover);

    SubsetParams params = new SubsetParams();
    CalendarDate runtime = CalendarDate.parseISOformat(null, "2015-03-01T06:00:00Z");
    params.set(SubsetParams.runtime, runtime);
    CalendarDate time = CalendarDate.parseISOformat(null, "2015-03-01T11:00:00Z"); // (6,12), (12,18)
    params.set(SubsetParams.time, time);
    logger.debug("  subset {}", params);

    GeoReferencedArray geo = cover.readData(params);
    testGeoArray(geo, runtime, time, null);

    Array data = geo.getData();
    Index ai = data.getIndex();
    float testValue = data.getFloat(ai.set(0, 0, 2, 2));
    Assert2.assertNearlyEquals(0.073f, testValue);
  }
}
 
Example #27
Source File: TestCoverageSubsetTime.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test // 1 runtime, 1 time (Time2DCoordSys case 1b)
public void test1Runtime1TimeIntervalEdge() throws IOException, InvalidRangeException {
  String endpoint = TestDir.cdmUnitTestDir + "gribCollections/gfs_2p5deg/gfs_2p5deg.ncx4";
  String covName = "Momentum_flux_u-component_surface_Mixed_intervals_Average";

  logger.debug("test1Runtime1TimeInterval Dataset {} coverage {}", endpoint, covName);

  try (FeatureDatasetCoverage cc = CoverageDatasetFactory.open(endpoint)) {
    Assert.assertNotNull(endpoint, cc);
    CoverageCollection gcs = cc.findCoverageDataset(FeatureType.FMRC);
    Assert.assertNotNull("gcs", gcs);
    Coverage cover = gcs.findCoverage(covName);
    Assert.assertNotNull(covName, cover);

    SubsetParams params = new SubsetParams();
    CalendarDate runtime = CalendarDate.parseISOformat(null, "2015-03-01T00:00:00Z");
    params.set(SubsetParams.runtime, runtime);
    CalendarDate time = CalendarDate.parseISOformat(null, "2015-03-06T19:30:00Z"); // (6,12), (12,18)
    params.set(SubsetParams.time, time);
    logger.debug("  subset {}", params);

    GeoReferencedArray geo = cover.readData(params);
    testGeoArray(geo, runtime, time, null);

    Array data = geo.getData();
    Index ai = data.getIndex();
    float testValue = data.getFloat(ai.set(0, 0, 3, 0));
    Assert2.assertNearlyEquals(0.244f, testValue);
  }
}
 
Example #28
Source File: TestNcMLValues.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Before
public void setUp() {
  ncml = "<?xml version='1.0' encoding='UTF-8'?>\n" // leavit
      + "<netcdf xmlns='http://www.unidata.ucar.edu/namespaces/netcdf/ncml-2.2'>\n" // leavit
      + "   <dimension name='intDim' length='3' />\n" // leavit
      + "   <variable name='singleWs' type='int' shape='intDim'>\n" // leavit
      + "     <attribute name='description' value='Test Single White Space With Default Separator' />\n" // leavit
      + "     <values>0 1 2</values>\n" // leavit
      + "   </variable>\n" // leavit
      + "   <variable name='multiWs' type='int' shape='intDim'>\n" // leavit
      + "     <attribute name='description' value='Test Multi-length White Spaces With Default Separator' />\n" // leavit
      + "     <values>0    1  2</values>\n" // leavit
      + "   </variable>\n" // leavit
      + "   <variable name='tabs' type='int' shape='intDim'>\n" // leavit
      + "     <attribute name='description' value='Test Tab Spaces With Default Separator' />\n" // leavit
      + "     <values>0\t1\t2</values>\n" // leavit
      + "   </variable>\n" // leavit
      + "   <variable name='mixedTabSpace' type='int' shape='intDim'>\n" // leavit
      + "     <attribute name='description' value='Test Mixed Tab/Single-Space Spaces With Default Separator' />\n" // leavit
      + "     <values>0\t1 2</values>\n" // leavit
      + "   </variable>\n" // leavit
      + "   <variable name='mixedTabSpaces' type='int' shape='intDim'>\n" // leavit
      + "     <attribute name='description' value='Test Mixed Tab/Multi-Space Spaces With Default Separator' />\n" // leavit
      + "     <values>0\t1    2</values>\n" // leavit
      + "   </variable>\n" // leavit
      + "   <variable name='mixedSpace' type='int' shape='intDim'>\n" // leavit
      + "     <attribute name='description' value='Test Mixed Spaces With Default Separator' />\n" // leavit
      + "     <values>0\t  1\t    2</values>\n" // leavit
      + "   </variable>\n" // leavit
      + "   <variable name='customSep' type='int' shape='intDim'>\n" // leavit
      + "     <attribute name='description' value='Test Custom Separator' />\n" // leavit
      + "     <values separator='-'>0-1-2</values>\n" // leavit
      + "   </variable>\n" // leavit
      + "</netcdf>"; // leavit

  expectedIntLength = 3;
  expectedIntShape = new int[] {expectedIntLength};
  expectedIntValues = new ArrayInt(expectedIntShape, false);
  intVarNames =
      new String[] {"singleWs", "multiWs", "tabs", "mixedTabSpace", "mixedTabSpaces", "mixedSpace", "customSep"};
  Index idx = expectedIntValues.getIndex();
  for (int i = 0; i < expectedIntLength; i++) {
    expectedIntValues.set(idx, i);
    idx.incr();
  }

  try {
    ncfile = NcMLReaderNew.readNcML(new StringReader(ncml), null, null).build();
  } catch (IOException e) {
    System.out.println("IO error = " + e);
    e.printStackTrace();
  }

}
 
Example #29
Source File: CDMArrayAtomic.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public double getDouble(ucar.ma2.Index cdmidx) {
  return getDouble(CDMUtil.cdmIndexToIndex(cdmidx));
}
 
Example #30
Source File: NetCDFReadTask.java    From mzmine3 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Reads one scan from the file. Requires that general information has already been read.
 */
private Scan readNextScan() throws IOException {

  // Get scan starting position and length
  int[] scanStartPosition = new int[1];
  int[] scanLength = new int[1];
  Integer[] startAndLength = scansIndex.get(scanNum);

  // End of file
  if (startAndLength == null) {
    return null;
  }
  scanStartPosition[0] = startAndLength[0];
  scanLength[0] = startAndLength[1];

  // Get retention time of the scan
  Double retentionTime = scansRetentionTimes.get(scanNum);
  if (retentionTime == null) {
    logger.severe("Could not find retention time for scan " + scanNum);
    throw (new IOException("Could not find retention time for scan " + scanNum));
  }

  // An empty scan needs special attention..
  if (scanLength[0] == 0) {
    scanNum++;

    return new SimpleScan(null, scanNum, 1, retentionTime.doubleValue(), 0.0,
            0, 0, null, new DataPoint[0], MassSpectrumType.CENTROIDED,
            PolarityType.UNKNOWN, "", null);
  }

  // Is there any way how to extract polarity from netcdf?
  PolarityType polarity = PolarityType.UNKNOWN;

  // Is there any way how to extract scan definition from netcdf?
  String scanDefinition = "";

  // Read mass and intensity values
  Array massValueArray;
  Array intensityValueArray;
  try {
    massValueArray = massValueVariable.read(scanStartPosition, scanLength);
    intensityValueArray = intensityValueVariable.read(scanStartPosition, scanLength);
  } catch (Exception e) {
    logger.log(Level.SEVERE, "Could not read from variables mass_values and/or intensity_values.",
        e);
    throw (new IOException("Could not read from variables mass_values and/or intensity_values."));
  }

  Index massValuesIndex = massValueArray.getIndex();
  Index intensityValuesIndex = intensityValueArray.getIndex();

  int arrayLength = massValueArray.getShape()[0];

  DataPoint dataPoints[] = new DataPoint[arrayLength];

  for (int j = 0; j < arrayLength; j++) {
    Index massIndex0 = massValuesIndex.set0(j);
    Index intensityIndex0 = intensityValuesIndex.set0(j);

    double mz = massValueArray.getDouble(massIndex0) * massValueScaleFactor;
    double intensity = intensityValueArray.getDouble(intensityIndex0) * intensityValueScaleFactor;
    dataPoints[j] = new SimpleDataPoint(mz, intensity);

  }

  scanNum++;

  // Auto-detect whether this scan is centroided
  MassSpectrumType spectrumType = ScanUtils.detectSpectrumType(dataPoints);

  SimpleScan buildingScan = new SimpleScan(null, scanNum, 1, retentionTime.doubleValue(),
          0.0, 0,0,null,dataPoints, spectrumType, polarity,
          scanDefinition, null);

  return buildingScan;

}