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

The following examples show how to use ucar.ma2.Array#getDouble() . 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: 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 2
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 3
Source File: CurvilinearGridPointMappingTest.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Test GridCoordSystem.getLatLon()
 *
 * @throws IOException if ...
 * @throws InvalidRangeException if ...
 */
@Test
public void checkGridCoordSystem_getLatLon() throws IOException, InvalidRangeException {
  int[] origin = new int[] {j, i};
  int[] shape = new int[] {1, 1};

  NetcdfFile ncf = NetcdfFiles.open(datasetLocation);
  Variable latVar = ncf.findVariable("lat");
  Array latArray = latVar.read(origin, shape);
  Variable lonVar = ncf.findVariable("lon");
  Array lonArray = lonVar.read(origin, shape);

  double latVal = latArray.getDouble(latArray.getIndex());
  double lonVal = lonArray.getDouble(lonArray.getIndex());

  GridDataset gd = GridDataset.open(datasetLocation);
  GeoGrid gg = gd.findGridByName("hs");
  GridCoordSystem gridCoordSys = gg.getCoordinateSystem();
  // gridCoordSys.getXHorizAxis().;
  // gridCoordSys.getYHorizAxis();
  LatLonPoint llPnt = gridCoordSys.getLatLon(170, 62);

  Assert.assertEquals(lat, llPnt.getLatitude(), 0.001);
  Assert.assertEquals(lon, llPnt.getLongitude(), 0.001);
}
 
Example 4
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 5
Source File: GridAsPointDataset.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public Point readData(GridDatatype grid, CalendarDate date, double zCoord, double lat, double lon)
    throws java.io.IOException {
  GridCoordSystem gcs = grid.getCoordinateSystem();

  int tidx = -1;
  // Date may be null if the grid does not have time axis
  if (date != null)
    tidx = findTimeIndexForCalendarDate(gcs, date);

  CoordinateAxis1D zAxis = gcs.getVerticalAxis();
  int zidx = zAxis.findCoordElement(zCoord);

  int[] xy = gcs.findXYindexFromLatLon(lat, lon, null);

  Array data = grid.readDataSlice(tidx, zidx, xy[1], xy[0]);

  // use actual grid midpoint
  LatLonPoint latlon = gcs.getLatLon(xy[0], xy[1]);

  Point p = new Point();
  p.lat = latlon.getLatitude();
  p.lon = latlon.getLongitude();
  p.z = zAxis.getCoordValue(zidx);
  p.dataValue = data.getDouble(data.getIndex());
  return p;
}
 
Example 6
Source File: GridAsPointDataset.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public Point readData(GridDatatype grid, CalendarDate date, double lat, double lon) throws java.io.IOException {
  GridCoordSystem gcs = grid.getCoordinateSystem();

  int tidx = -1;
  // Date may be null if the grid does not have time axis
  if (date != null)
    tidx = findTimeIndexForCalendarDate(gcs, date);

  int[] xy = gcs.findXYindexFromLatLon(lat, lon, null);

  Array data = grid.readDataSlice(tidx, -1, xy[1], xy[0]);

  // use actual grid midpoint
  LatLonPoint latlon = gcs.getLatLon(xy[0], xy[1]);

  Point p = new Point();
  p.lat = latlon.getLatitude();
  p.lon = latlon.getLongitude();
  p.dataValue = data.getDouble(data.getIndex());
  return p;
}
 
Example 7
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 8
Source File: GridAsPointDataset.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Reads data for the given point (earthlocation) and if bounded is true returns data for the closest point within the
 * grid, for points outside of the grid
 * 
 * @param grid read data from here
 * @param date at this time
 * @param location EarthLocation, if altitude is NaN assume that is 2D point
 * @param bounded if bounded, location must be in grid cell; otherwise get nearest grid point to location
 * @return the location and data value
 * @throws java.io.IOException on bad stuff
 */
public Point readData(GridDatatype grid, CalendarDate date, EarthLocation location, boolean bounded)
    throws java.io.IOException {
  if (!bounded) {
    if (Double.isNaN(location.getAltitude())) {
      return readData(grid, date, location.getLatitude(), location.getLongitude());
    } else {
      return readData(grid, date, location.getAltitude(), location.getLatitude(), location.getLongitude());
    }
  }

  // Bounded --> Read closest data
  GridCoordSystem gcs = grid.getCoordinateSystem();
  int tidx = findTimeIndexForCalendarDate(gcs, date);
  int[] xy = gcs.findXYindexFromLatLonBounded(location.getLatitude(), location.getLongitude(), null);

  LatLonPoint latlon = gcs.getLatLon(xy[0], xy[1]);
  Point p = new Point();
  p.lat = latlon.getLatitude();
  p.lon = latlon.getLongitude();

  int zidx = -1;
  if (!Double.isNaN(location.getAltitude())) {
    CoordinateAxis1D zAxis = gcs.getVerticalAxis();
    zidx = zAxis.findCoordElement(location.getAltitude());
    p.z = zAxis.getCoordValue(zidx);
  }

  Array data = grid.readDataSlice(tidx, zidx, xy[1], xy[0]);
  p.dataValue = data.getDouble(data.getIndex());

  return p;
}
 
Example 9
Source File: AWIPSConvention.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private CoordinateAxis makeTimeCoordAxisFromReference(NetcdfDataset ds, Variable timeVar, Array vals) {
  Variable refVar = ds.findVariable("reftime");
  if (refVar == null)
    return null;
  double refValue;
  try {
    Array refArray = refVar.read();
    refValue = refArray.getDouble(refArray.getIndex()); // get the first value
  } catch (IOException ioe) {
    return null;
  }
  if (refValue == N3iosp.NC_FILL_DOUBLE)
    return null;

  // construct the values array - make it a double to be safe
  Array dvals = Array.factory(DataType.DOUBLE, vals.getShape());
  IndexIterator diter = dvals.getIndexIterator();
  IndexIterator iiter = vals.getIndexIterator();
  while (iiter.hasNext())
    diter.setDoubleNext(iiter.getDoubleNext() + refValue); // add reftime to each of the values

  String units = ds.findAttValueIgnoreCase(refVar, CDM.UNITS, "seconds since 1970-1-1 00:00:00");
  units = normalize(units);
  String desc = "synthesized time coordinate from reftime, valtimeMINUSreftime";
  CoordinateAxis1D timeCoord = new CoordinateAxis1D(ds, null, "timeCoord", DataType.DOUBLE, "record", units, desc);

  timeCoord.setCachedData(dvals, true);

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

  return timeCoord;
}
 
Example 10
Source File: AWIPSConvention.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nullable
private CoordinateAxis.Builder makeTimeCoordAxisFromReference(Array vals) {
  if (!rootGroup.findVariableLocal("reftime").isPresent())
    return null;
  VariableDS.Builder refVar = (VariableDS.Builder) rootGroup.findVariableLocal("reftime").get();

  double refValue;
  try {
    Array refArray = refVar.orgVar.read();
    refValue = refArray.getDouble(refArray.getIndex()); // get the first value
  } catch (IOException ioe) {
    return null;
  }
  if (refValue == N3iosp.NC_FILL_DOUBLE) // why?
    return null;

  // construct the values array - make it a double to be safe
  Array dvals = Array.factory(DataType.DOUBLE, vals.getShape());
  IndexIterator diter = dvals.getIndexIterator();
  IndexIterator iiter = vals.getIndexIterator();
  while (iiter.hasNext())
    diter.setDoubleNext(iiter.getDoubleNext() + refValue); // add reftime to each of the values

  String name = "timeCoord";
  String units = refVar.getAttributeContainer().findAttributeString(CDM.UNITS, "seconds since 1970-1-1 00:00:00");
  units = normalize(units);
  String desc = "synthesized time coordinate from reftime, valtimeMINUSreftime";
  CoordinateAxis1D.Builder timeCoord =
      CoordinateAxis1D.builder().setName(name).setDataType(DataType.DOUBLE).setParentGroupBuilder(rootGroup)
          .setDimensionsByName("record").setUnits(units).setDesc(desc).setCachedData(dvals, true);

  parseInfo.format("Created Time Coordinate Axis From reftime Variable%n");
  return timeCoord;
}
 
Example 11
Source File: TestCurvilinearGridPointMapping.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Test CoverageCoordSys.HorizCoordSys.getLatLon()
 *
 * @throws IOException if ...
 * @throws InvalidRangeException if ...
 */
@Test
public void checkGridCoordSystem_getLatLon() throws IOException, InvalidRangeException {
  int[] origin = new int[] {j, i};
  int[] shape = new int[] {1, 1};

  NetcdfFile ncf = NetcdfFiles.open(datasetLocation);
  Variable latVar = ncf.findVariable("lat");
  Array latArray = latVar.read(origin, shape);
  Variable lonVar = ncf.findVariable("lon");
  Array lonArray = lonVar.read(origin, shape);

  double latVal = latArray.getDouble(0);
  double lonVal = lonArray.getDouble(0);
  logger.debug("{}, {}", latVal, lonVal);

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

    CoverageCoordSys gridCoordSys = cover.getCoordSys();
    Assert.assertNotNull("CoverageCoordSys", gridCoordSys);
    HorizCoordSys hcs = gridCoordSys.getHorizCoordSys();
    Assert.assertNotNull("HorizCoordSys", hcs);

    LatLonPoint llPnt = hcs.getLatLon(j, i);
    Assert2.assertNearlyEquals(lat, llPnt.getLatitude());
    Assert2.assertNearlyEquals(lon, llPnt.getLongitude());
  }
}
 
Example 12
Source File: XYSeriesData.java    From MeteoInfo with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Set X data
 * @param value X data 
 */
public void setXdata(Array value){
    this.xdata = new double[(int)value.getSize()];
    double v;
    for (int i = 0; i < xdata.length; i++){
        v = value.getDouble(i);
        if (Double.isNaN(v))
            xdata[i] = this.missingValue;
        else
            xdata[i] = v;
    }
}
 
Example 13
Source File: XYSeriesData.java    From MeteoInfo with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Set Y data
 * @param value Y data 
 */
public void setYdata(Array value){
    this.ydata = new double[(int)value.getSize()];
    double v;
    for (int i = 0; i < ydata.length; i++){
        v = value.getDouble(i);
        if (Double.isNaN(v))
            ydata[i] = this.missingValue;
        else
            ydata[i] = v;
    }
}
 
Example 14
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 15
Source File: PolylineErrorShape.java    From MeteoInfo with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Set Y error data
 * @param value Y error data 
 */
public void setYerror(Array value){
    this.yerror = new double[(int)value.getSize()];
    double v;
    for (int i = 0; i < yerror.length; i++){
        v = value.getDouble(i);
        yerror[i] = v;
    }
}
 
Example 16
Source File: NetCDFReadTask.java    From mzmine2 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, 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,
      null, dataPoints, spectrumType, polarity, scanDefinition, null);

  return buildingScan;

}
 
Example 17
Source File: TestSinglePointGds.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void checkVal(Variable variable, double expectedValue, double tol) throws IOException {
  Array array = variable.read();
  assertThat(array.getSize()).isEqualTo(1);
  double val = array.getDouble(0);
  assertThat(val).isWithin(tol).of(expectedValue);
}
 
Example 18
Source File: WRFEta.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 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
 */
public ArrayDouble.D3 getCoordinateArray(int timeIndex) throws IOException {
  ArrayDouble.D3 array;

  Array pertArray = getTimeSlice(pertVar, timeIndex);
  Array baseArray = getTimeSlice(baseVar, timeIndex);

  // ADD: use MAMath?
  // ADD: use IndexIterator from getIndexIteratorFast?
  int[] shape = pertArray.getShape();
  // ADD: assert that rank = 3
  // ADD: assert that both arrays are same shape
  int ni = shape[0];
  int nj = shape[1];
  int nk = shape[2];

  array = new ArrayDouble.D3(ni, nj, nk);
  Index index = array.getIndex();

  for (int i = 0; i < ni; i++) {
    for (int j = 0; j < nj; j++) {
      for (int k = 0; k < nk; k++) {
        index.set(i, j, k);
        double d = pertArray.getDouble(index) + baseArray.getDouble(index);
        if (isZStag) {
          d = d / 9.81; // convert geopotential to height
        }
        array.setDouble(index, d);
      }
    }
  }

  if (isXStag) {
    array = addStagger(array, 2); // assuming x dim index is 2
  }
  if (isYStag) {
    array = addStagger(array, 1); // assuming y dim index is 1
  }

  return array;
}
 
Example 19
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;

}
 
Example 20
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;
    }
  };
}