Java Code Examples for ucar.ma2.Array

The following examples show how to use ucar.ma2.Array. These examples are extracted from open source projects. 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
/**
 * Constructor
 *
 * @param ncfile the target NetcdfDataset
 * @param dsp the compiled D4 databuffer
 */

public DataToCDM(DapNetcdfFile ncfile, DSP dsp, NodeMap nodemap) throws DapException {
  this.ncfile = ncfile;
  this.dsp = dsp;
  this.dmr = dsp.getDMR();
  this.nodemap = nodemap;
  this.cdmroot = ncfile.getRootGroup();
  arraymap = new HashMap<Variable, Array>();
  // Add endianness attribute to the group
  /*
   * ByteOrder remoteorder = ncfile.getDSP().getOrder();
   * String endianness = null;
   * if(remoteorder != null) {
   * if(remoteorder == ByteOrder.BIG_ENDIAN)
   * endianness = "big";
   * else if(remoteorder == ByteOrder.BIG_ENDIAN)
   * endianness = "little";
   * }
   * if(endianness != null) {
   * Attribute aendian = new Attribute(DapUtil.ENDIANATTRNAME, endianness);
   * this.cdmroot.addAttribute(aendian);
   * }
   */
}
 
Example 2
public static void showData(Grib2RecordBean bean1, Formatter f) {
  float[] data;
  try {
    data = bean1.readData();
  } catch (Exception e) {
    StringWriter sw = new StringWriter(5000);
    e.printStackTrace(new PrintWriter(sw));
    f.format("Exception %s", sw.toString());
    return;
  }
  Grib2Gds gds = bean1.gr.getGDS();

  int[] shape = {gds.getNy(), gds.getNx()};
  Array arr = Array.factory(DataType.FLOAT, shape, data);
  f.format("%s", Ncdump.printArray(arr));
}
 
Example 3
/**
 * Create an array of structures. WARNING: the underlying CDM code
 * (esp. NetcdfDataset) apparently does not support nested
 * structure arrays; so this code may throw an exception.
 *
 * @return A CDMArrayStructure for the databuffer for this struct.
 * @throws DapException
 */
protected CDMArrayStructure createStructure(DataCursor data) throws DapException {
  CDMArrayStructure arraystruct = new CDMArrayStructure(this.cdmroot, data);
  DapVariable var = (DapVariable) data.getTemplate();
  DapStructure struct = (DapStructure) var.getBaseType();
  int nmembers = struct.getFields().size();
  List<DapDimension> dimset = var.getDimensions();
  Odometer odom = Odometer.factory(DapUtil.dimsetToSlices(dimset));
  while (odom.hasNext()) {
    Index index = odom.next();
    long offset = index.index();
    DataCursor[] cursors = (DataCursor[]) data.read(index);
    DataCursor ithelement = cursors[0];
    for (int f = 0; f < nmembers; f++) {
      DataCursor dc = (DataCursor) ithelement.readField(f);
      Array afield = createVar(dc);
      arraystruct.add(offset, f, afield);
    }
  }
  return arraystruct;
}
 
Example 4
@Test
public void testNegDataSize() throws IOException, InvalidRangeException {
  Grib.setDebugFlags(new DebugFlagsImpl("Grib/debugGbxIndexOnly"));

  String endpoint = "D:/work/rdavm/ds084.3/ds084.3.ncx4";
  String covName = "v-component_of_wind_potential_vorticity_surface";
  try (FeatureDatasetCoverage fdc = CoverageDatasetFactory.open(endpoint)) {
    Assert.assertNotNull(endpoint, fdc);
    CoverageCollection cc = fdc.findCoverageDataset(FeatureType.GRID);
    Assert.assertNotNull(FeatureType.FMRC.toString(), cc);
    Coverage cov = cc.findCoverage(covName);
    Assert.assertNotNull(covName, cov);

    SubsetParams subset = new SubsetParams().setTimePresent();
    GeoReferencedArray geo = cov.readData(subset);
    Array data = geo.getData();
    System.out.printf(" read data from %s shape = %s%n", cov.getName(), Arrays.toString(data.getShape()));
  }

  Grib.setDebugFlags(new DebugFlagsImpl(""));
}
 
Example 5
/**
 * Do not call this directly, use Variable.read() !!
 * Ranges must be filled (no nulls)
 */
protected Array readData(Variable v, Section ranges) throws IOException, InvalidRangeException {
  long start = 0;
  if (showRequest) {
    log.info("Data request for variable: {} section {}...", v.getFullName(), ranges);
    start = System.currentTimeMillis();
  }

  /*
   * if (unlocked) {
   * String info = cache.getInfo(this);
   * throw new IllegalStateException("File is unlocked - cannot use\n" + info);
   * }
   */

  if (iosp == null) {
    throw new IOException("iosp is null, perhaps file has been closed. Trying to read variable " + v.getFullName());
  }
  Array result = iosp.readData(v, ranges);

  if (showRequest) {
    long took = System.currentTimeMillis() - start;
    log.info(" ...took= {} msecs", took);
  }
  return result;
}
 
Example 6
private Array convertToDegrees(Variable.Builder<?> vb) {
  VariableDS.Builder<?> vds = (VariableDS.Builder<?>) vb;
  Variable v = vds.orgVar;
  Array data;
  try {
    data = v.read();
    data = data.reduce();
  } catch (IOException ioe) {
    throw new RuntimeException("data read failed on " + v.getFullName() + "=" + ioe.getMessage());
  }
  IndexIterator ii = data.getIndexIterator();
  while (ii.hasNext()) {
    ii.setDoubleCurrent(Math.toDegrees(ii.getDoubleNext()));
  }
  return data;
}
 
Example 7
/**
 * 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 8
/**
 * Add coordinate system variable
 *
 * @param ncfile netCDF file
 * @param name name of the variable
 * @param dims dimensions
 */
private void addCoordSystemVariable(NetcdfFile ncfile, String name, String dims) {
  Variable v = new Variable(ncfile, g, null, name);
  v.setDataType(DataType.CHAR);
  v.setDimensions(""); // scalar
  Array dataArray = Array.factory(DataType.CHAR, new int[0], new char[] {'0'});
  v.setCachedData(dataArray, false);
  v.addAttribute(new Attribute(_Coordinate.Axes, dims));
  if (isLatLon())
    v.addAttribute(new Attribute(_Coordinate.Transforms, "")); // to make sure its identified as a Coordinate System
                                                               // Variable
  else
    v.addAttribute(new Attribute(_Coordinate.Transforms, getGridName()));
  addGDSparams(v);
  ncfile.addVariable(g, v);
}
 
Example 9
protected Array read(Variable mainv, CancelTask cancelTask) throws IOException {
  NetcdfFile ncd = null;
  try {
    ncd = acquireFile(cancelTask);
    if ((cancelTask != null) && cancelTask.isCancel())
      return null;

    Variable v = findVariable(ncd, mainv);
    if (debugRead)
      System.out.printf("Agg.read %s from %s in %s%n", mainv.getNameAndDimensions(), v.getNameAndDimensions(),
          getLocation());
    return v.read();

  } finally {
    close(ncd);
  }
}
 
Example 10
Source Project: netcdf-java   Source File: TestNids.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void testNidsReadNVW() throws IOException {
  NetcdfFile ncfile = null;
  Variable v = null;
  Array a = null;
  try {
    System.out.println("**** Open " + vadWindProfileFile);
    ncfile = NetcdfFile.open(vadWindProfileFile);
  } catch (java.io.IOException e) {
    System.out.println(" fail = " + e);
    e.printStackTrace();
    assert (false);
  }

  assert (null != ncfile.findVariable("textStruct_code8"));
  assert (null != ncfile.findVariable("textStruct_code8").getDimension(0));

  v = ncfile.findVariable("unlinkedVectorStruct");
  testReadDataAsShort((Structure) v, "iValue");

  v = ncfile.findVariable("VADWindSpeed");
  testReadData(v);

  v = ncfile.findVariable("TabMessagePage");
  testReadData(v);
  ncfile.close();
}
 
Example 11
/**
 * 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 12
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 13
@Test
public void testNonOrthMRUTC() throws IOException, InvalidRangeException {
  Grib.setDebugFlags(new DebugFlagsImpl("Grib/debugGbxIndexOnly"));

  String endpoint = "D:/work/rdavm/ds277.6/monthly/ds277.6.ncx4";
  String ccName = "ds277.6#MRUTC-LatLon_418X360-4p83S-179p50W";
  String covName = "Salinity_depth_below_sea_Average";
  try (FeatureDatasetCoverage fdc = CoverageDatasetFactory.open(endpoint)) {
    Assert.assertNotNull(endpoint, fdc);
    CoverageCollection cc = fdc.findCoverageDataset(ccName);
    Assert.assertNotNull(ccName, cc);
    Coverage cov = cc.findCoverage(covName);
    Assert.assertNotNull(covName, cov);

    SubsetParams subset = new SubsetParams().setTimePresent();
    GeoReferencedArray geo = cov.readData(subset);
    Array data = geo.getData();
    System.out.printf(" read data from %s shape = %s%n", cov.getName(), Arrays.toString(data.getShape()));
  }

  Grib.setDebugFlags(new DebugFlagsImpl(""));
}
 
Example 14
/**
 * 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 15
Source Project: tds   Source File: TestRdaProblems.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testBadSize() throws IOException, InvalidRangeException {

  String covName = "Geopotential_height_isobaric";
  Catalog cat = TdsLocalCatalog.open("catalog/rdaTest/ds084.3/catalog.xml");
  Assert.assertNotNull(cat);
  Dataset ds = cat.findDatasetByID("rdaTest/ds084.3/TwoD");

  DataFactory fac = new DataFactory();
  try (DataFactory.Result result = fac.openFeatureDataset(ds, null)) {
    Assert.assertFalse(result.errLog.toString(), result.fatalError);
    Assert.assertNotNull(result.featureDataset);
    Assert.assertEquals(FeatureDatasetCoverage.class, result.featureDataset.getClass());

    FeatureDatasetCoverage fdc = (FeatureDatasetCoverage) result.featureDataset;
    CoverageCollection cc = fdc.findCoverageDataset(FeatureType.FMRC);
    Assert.assertNotNull(FeatureType.FMRC.toString(), cc);
    Coverage cov = cc.findCoverage(covName);
    Assert.assertNotNull(covName, cov);

    SubsetParams subset = new SubsetParams().setTimePresent();
    GeoReferencedArray geo = cov.readData(subset);
    Array data = geo.getData();
    System.out.printf(" read data from %s shape = %s%n", cov.getName(), Arrays.toString(data.getShape()));
  }
}
 
Example 16
@Test
public void testMicrosoftBlobS3() throws IOException {
  // https://nexradsa.blob.core.windows.net/nexrad-l2/1997/07/07/KHPX/KHPX19970707_000827.gz
  String host = "nexradsa.blob.core.windows.net";
  String bucket = "nexrad-l2";
  String key = "1991/07/20/KTLX/KTLX19910720_160529.gz";
  String s3Uri = "cdms3://" + host + "/" + bucket + "?" + key;
  try (NetcdfFile ncfile = NetcdfFiles.open(s3Uri)) {

    assertThat(ncfile.findDimension("scanR")).isNotNull();
    assertThat(ncfile.findDimension("gateR")).isNotNull();
    assertThat(ncfile.findDimension("radialR")).isNotNull();

    Variable reflectivity = ncfile.findVariable("Reflectivity");
    Assert.assertNotNull(reflectivity);

    // read array
    Array array = reflectivity.read();

    assertThat(array.getRank()).isEqualTo(3);

    assertThat(array.getShape()).isEqualTo(new int[] {1, 366, 460});
  }
}
 
Example 17
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 18
/**
 * 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 19
@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 20
protected Array convertEnums(Map<Integer, String> map, DataType dataType, Array values) {
  Array result = Array.factory(DataType.STRING, values.getShape());
  IndexIterator ii = result.getIndexIterator();
  values.resetLocalIterator();
  while (values.hasNext()) {
    int ival;
    if (dataType == DataType.ENUM1)
      ival = (int) DataType.unsignedByteToShort(values.nextByte());
    else if (dataType == DataType.ENUM2)
      ival = DataType.unsignedShortToInt(values.nextShort());
    else
      ival = values.nextInt();
    String sval = map.get(ival);
    if (sval == null)
      sval = "Unknown enum value=" + ival;
    ii.setObjectNext(sval);
  }
  return result;
}
 
Example 21
/**
 * Get the maximum radial distance, in km.
 */
public double getMaximumRadial() {
  if (maxRadial == 0.0) {
    try {
      Array radialData = getRadialAxisDataCached();
      maxRadial = MAMath.getMaximum(radialData);

      String units = getRadialAxis().getUnitsString();
      SimpleUnit radialUnit = SimpleUnit.factory(units);
      maxRadial = radialUnit.convertTo(maxRadial, SimpleUnit.kmUnit); // convert to km

    } catch (IOException | IllegalArgumentException e) {
      e.printStackTrace();
    }
  }
  return maxRadial;
}
 
Example 22
@Test
public void testUnsigned() throws IOException {
  try (NetcdfFile ncfile = NetcdfDatasets.openDataset(TestDir.cdmLocalTestDataDir + "testUnsignedByte.ncml")) {
    Variable v = ncfile.findVariable("bvar");
    Assert.assertNotNull(v);
    Assert.assertEquals(DataType.FLOAT, v.getDataType()); // has float scale_factor

    boolean hasSigned = false;
    Array data = v.read();
    while (data.hasNext()) {
      float b = data.nextFloat();
      if (b < 0)
        hasSigned = true;
    }
    Assert.assertTrue(!hasSigned);
  }
}
 
Example 23
private void showNew(String fileLocation) throws IOException {

    try (NetcdfDataset withBuilder = NetcdfDatasets.openDataset(fileLocation)) {
      Variable v = withBuilder.findVariable("catchments_x");
      Array data = v.read();
      System.out.printf("data = %s%n", data);
    }
  }
 
Example 24
private void correctGoes16(Attribute productionLocation, Attribute icdVersion, Variable gridMappingVar) {
  // Files with these global attributes might need corrected
  // :ICD_version = "GROUND SEGMENT (GS) TO ADVANCED WEATHER INTERACTIVE PROCESSING SYSTEM (AWIPS) INTERFACE CONTROL
  // DOCUMENT (ICD) Revision B" ;
  // :production_location = "WCDAS" ;
  String prodLoc = productionLocation.getStringValue();
  String icdVer = icdVersion.getStringValue();
  if (prodLoc != null && icdVer != null) {
    prodLoc = prodLoc.toLowerCase().trim();
    icdVer = icdVer.toLowerCase().trim();
    boolean mightNeedCorrected = prodLoc.contains("wcdas");
    mightNeedCorrected = mightNeedCorrected && icdVer.contains("ground segment");
    mightNeedCorrected = mightNeedCorrected && icdVer.contains("awips");
    if (mightNeedCorrected) {
      Map<String, String> possibleCorrections =
          ImmutableMap.of("semi_minor", CF.SEMI_MINOR_AXIS, "semi_major", CF.SEMI_MAJOR_AXIS);
      possibleCorrections.forEach((incorrect, correct) -> {
        Attribute attr = gridMappingVar.findAttributeIgnoreCase(incorrect);
        if (attr != null) {
          Array vals = attr.getValues();
          if (vals != null) {
            gridMappingVar.addAttribute(new Attribute(correct, vals));
            gridMappingVar.remove(attr);
            log.debug("Renamed {} attribute {} to {}", gridMappingVar, incorrect, correct);
          }
        }
      });
    }
  }
}
 
Example 25
Source Project: netcdf-java   Source File: TestH5.java    License: 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 26
Source Project: netcdf-java   Source File: CDMDSP.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected DapAttribute buildattribute(Attribute cdmattr) throws DapException {
  DapType attrtype = CDMTypeFcns.cdmtype2daptype(cdmattr.getDataType());
  EnumTypedef cdmenum = cdmattr.getEnumType();
  boolean enumfillvalue = (cdmattr.getShortName().equals(FILLVALUE) && cdmenum != null);
  DapEnumeration dapenum = null;

  // We need to handle _FillValue specially if the
  // the variable is enum typed.
  if (enumfillvalue) {
    cdmenum = findMatchingEnum(cdmenum);
    // Make sure the cdm attribute has type enumx
    if (!cdmenum.getBaseType().isEnum())
      throw new DapException("CDM _FillValue attribute type is not enumX");
    // Modify the attr
    cdmattr.setEnumType(cdmenum);
    // Now, map to a DapEnumeration
    dapenum = (DapEnumeration) this.nodemap.get(cdmenum);
    if (dapenum == null)
      throw new DapException("Illegal CDM variable attribute type: " + cdmenum);
    attrtype = dapenum;
  }
  if (attrtype == null)
    throw new DapException("DapFile: illegal CDM variable attribute type: " + cdmattr.getDataType());
  DapAttribute dapattr = (DapAttribute) dmrfactory.newAttribute(cdmattr.getShortName(), attrtype);
  recordNode(cdmattr, dapattr);
  // Transfer the values
  Array values = cdmattr.getValues();
  if (!validatecdmtype(cdmattr.getDataType(), values.getElementType()))
    throw new DapException("Attr type versus attribute data mismatch: " + values.getElementType());
  IndexIterator iter = values.getIndexIterator();
  String[] valuelist = null;
  Object vec = CDMTypeFcns.createVector(cdmattr.getDataType(), values.getSize());
  for (int i = 0; iter.hasNext(); i++) {
    java.lang.reflect.Array.set(vec, i, iter.next());
  }
  valuelist = (String[]) Convert.convert(DapType.STRING, attrtype, vec);
  dapattr.setValues(valuelist);
  return dapattr;
}
 
Example 27
@Test
public void testEcmwfExtendedComplexData2() throws IOException {
  final String testfile = "../grib/src/test/data/complex_packing2.grib1";
  try (NetcdfFile nc = NetcdfFiles.open(testfile)) {

    Variable var = nc.findVariable("Snowfall_surface");
    Array data = var.read();

    float first = data.getFloat(0);

    Assert.assertEquals(.326607, first, 1e-6);
  }
}
 
Example 28
Source Project: netcdf-java   Source File: HdfEos.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 *
 */
private static String getStructMetadata(Group eosGroup) throws IOException {
  StringBuilder sbuff = null;
  String structMetadata = null;

  int n = 0;
  while (true) {
    Variable structMetadataVar = eosGroup.findVariableLocal("StructMetadata." + n);
    if (structMetadataVar == null) {
      break;
    }
    if ((structMetadata != null) && (sbuff == null)) { // more than 1 StructMetadata
      sbuff = new StringBuilder(64000);
      sbuff.append(structMetadata);
    }

    // read and parse the ODL
    Array A = structMetadataVar.read();
    if (A instanceof ArrayChar.D1) {
      ArrayChar ca = (ArrayChar) A;
      structMetadata = ca.getString(); // common case only StructMetadata.0, avoid extra copy
    } else if (A instanceof ArrayObject.D0) {
      ArrayObject ao = (ArrayObject) A;
      structMetadata = (String) ao.getObject(0);
    } else {
      log.error("Unsupported array type {} for StructMetadata", A.getElementType());
    }

    if (sbuff != null) {
      sbuff.append(structMetadata);
    }
    n++;
  }
  return (sbuff != null) ? sbuff.toString() : structMetadata;
}
 
Example 29
@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 30
/**
 * Read data from a top level Variable and return a memory resident Array.
 *
 * @param v2 Variable. It may have FLOAT/INTEGER data type.
 * @param section wanted section of data of Variable. The section list is a list
 *        of ucar.ma2.Range which define the requested data subset.
 * @return Array of data which will be read from Variable through this call.
 */
public Array readData1(ucar.nc2.Variable v2, Section section) throws IOException, InvalidRangeException {
  // doData(raf, ncfile, varList);
  int[] sh = section.getShape();
  Array temp = Array.factory(v2.getDataType(), sh);
  long pos0 = 0;
  // Suppose that the data has LayoutRegular
  LayoutRegular index = new LayoutRegular(pos0, v2.getElementSize(), v2.getShape(), section);
  if (v2.getShortName().startsWith("time") | v2.getShortName().startsWith("numGates")) {
    temp = readIntData(index, v2);
  } else {
    temp = readFloatData(index, v2);
  }
  return temp;
}