ucar.nc2.Attribute Java Examples

The following examples show how to use ucar.nc2.Attribute. 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: CEDRICRadarConvention.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
protected void augmentDataset(CancelTask cancelTask) throws IOException {
  NcMLReaderNew.wrapNcMLresource(datasetBuilder, CoordSystemFactory.resourcesDir + "CEDRICRadar.ncml", cancelTask);

  VariableDS.Builder lat = (VariableDS.Builder) rootGroup.findVariableLocal("radar_latitude")
      .orElseThrow(() -> new IllegalStateException("Must have radar_latitude variable"));
  VariableDS.Builder lon = (VariableDS.Builder) rootGroup.findVariableLocal("radar_longitude")
      .orElseThrow(() -> new IllegalStateException("Must have radar_longitude variable"));
  float latv = (float) lat.orgVar.readScalarDouble();
  float lonv = (float) lon.orgVar.readScalarDouble();

  VariableDS.Builder pv = (VariableDS.Builder) rootGroup.findVariableLocal("Projection")
      .orElseThrow(() -> new IllegalStateException("Must have Projection variable"));
  pv.addAttribute(new Attribute("longitude_of_projection_origin", lonv));
  pv.addAttribute(new Attribute("latitude_of_projection_origin", latv));

  super.augmentDataset(cancelTask);
}
 
Example #2
Source File: CatalogExtractor.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void makeGrib1Vocabulary(List<GridDatatype> grids, PrintWriter out) {
  String stdName;
  out.println("\n<variables vocabulary='GRIB-1'>");
  for (GridDatatype grid : grids) {
    Attribute att = grid.findAttributeIgnoreCase("GRIB_param_number");
    stdName = (att != null) ? att.getNumericValue().toString() : null;

    out.print("  <variable name='");
    out.print(grid.getFullName());
    out.print("' vocabulary_name='");
    out.print(stdName != null ? stdName : "dunno");
    out.print("' units='");
    out.print(grid.getUnitsString());
    out.println("'/>");
  }
  out.println("</variables>");
}
 
Example #3
Source File: AggregationOuterDimension.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
protected Array read(DatasetOuterDimension dset, NetcdfFile ncfile) {
  Array data = getData(dset.getId());
  if (data != null)
    return data;

  Attribute att = ncfile.findGlobalAttribute(gattName);
  if (att == null)
    throw new IllegalArgumentException("Unknown attribute name= " + gattName);
  data = att.getValues();
  if (dtype == null)
    dtype = DataType.getType(data);

  if (dset.ncoord == 1) // LOOK ??
    putData(dset.getId(), data);
  else {
    // duplicate the value to each of the coordinates
    Array allData = Array.factory(dtype, new int[] {dset.ncoord});
    for (int i = 0; i < dset.ncoord; i++)
      Array.arraycopy(data, 0, allData, i, 1); // LOOK generalize to vectors ??
    putData(dset.getId(), allData);
    data = allData;
  }
  return data;
}
 
Example #4
Source File: IFPSConvention.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private Projection makeLCProjection(NetcdfDataset ds) {
  Attribute latLonOrigin = projVar.attributes().findAttributeIgnoreCase("latLonOrigin");
  if (latLonOrigin == null || latLonOrigin.isString())
    throw new IllegalStateException();
  double centralLon = latLonOrigin.getNumericValue(0).doubleValue();
  double centralLat = latLonOrigin.getNumericValue(1).doubleValue();

  double par1 = findAttributeDouble("stdParallelOne");
  double par2 = findAttributeDouble("stdParallelTwo");
  LambertConformal lc = new LambertConformal(centralLat, centralLon, par1, par2);

  // make Coordinate Transform Variable
  ProjectionCT ct = new ProjectionCT("lambertConformalProjection", "FGDC", lc);
  VariableDS ctVar = makeCoordinateTransformVariable(ds, ct);
  ctVar.addAttribute(new Attribute(_Coordinate.Axes, "xCoord yCoord"));
  ds.addVariable(null, ctVar);

  return lc;
}
 
Example #5
Source File: AggregationOuter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
protected Array read(AggDatasetOuter dset, NetcdfFile ncfile) {
  Array data = getData(dset.getId());
  if (data != null)
    return data;

  List<Object> vals = new ArrayList<>();
  for (String gattName : gattNames) {
    Attribute att = ncfile.findGlobalAttribute(gattName);
    if (att == null)
      throw new IllegalArgumentException("Unknown attribute name= " + gattName);
    vals.add(att.getValue(0));
  }

  Formatter f = new Formatter();
  f.format(format, vals.toArray());
  String result = f.toString();

  Array allData = Array.factory(dtype, new int[] {dset.ncoord});
  for (int i = 0; i < dset.ncoord; i++)
    allData.setObject(i, result);
  putData(dset.getId(), allData);
  return allData;
}
 
Example #6
Source File: CF1Convention.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void correctGoes16(Attribute productionLocation, Attribute icdVersion, Builder<?> gridMappingVar) {
  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.getAttributeContainer().findAttributeIgnoreCase(incorrect);
        if (attr != null) {
          Array vals = attr.getValues();
          if (vals != null) {
            gridMappingVar.getAttributeContainer().replace(attr, correct);
            log.debug("Renamed {} attribute {} to {}", gridMappingVar, incorrect, correct);
          }
        }
      });
    }
  }
}
 
Example #7
Source File: FeatureDatasetCapabilitiesWriter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
VariableSimpleAdapter(Element velem) {
  name = velem.getAttributeValue("name");
  String type = velem.getAttributeValue("type");
  dt = DataType.getType(type);

  atts = new ArrayList<>();
  List<Element> attElems = velem.getChildren("attribute");
  for (Element attElem : attElems) {
    String attName = attElem.getAttributeValue("name");
    ucar.ma2.Array values = NcMLReader.readAttributeValues(attElem);
    atts.add(new Attribute(attName, values));
  }

  for (Attribute att : atts) {
    if (att.getShortName().equals(CDM.UNITS))
      units = att.getStringValue();
    if (att.getShortName().equals(CDM.LONG_NAME))
      desc = att.getStringValue();
    if ((desc == null) && att.getShortName().equals("description"))
      desc = att.getStringValue();
    if ((desc == null) && att.getShortName().equals("standard_name"))
      desc = att.getStringValue();
  }
}
 
Example #8
Source File: MetadataExtractorAcdd.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void addSource(boolean isCreator, String sourceName, String urlName, String emailName) {
  Attribute att = ncfile.get(sourceName);
  if (att != null) {
    String sourceValue = att.getStringValue();

    Attribute urlAtt = ncfile.get(urlName);
    String url = (urlAtt == null) ? null : urlAtt.getStringValue();

    Attribute emailAtt = ncfile.get(emailName);
    String email = (emailAtt == null) ? null : emailAtt.getStringValue();

    ThreddsMetadata.Vocab name = new ThreddsMetadata.Vocab(sourceValue, null);
    ThreddsMetadata.Source src = new ThreddsMetadata.Source(name, url, email);

    if (isCreator)
      tmi.addCreator(src);
    else
      tmi.addPublisher(src);
  }
}
 
Example #9
Source File: TestWriteMiscProblems.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testFileHandleReleaseAfterHeaderWriteFailure() throws IOException {
  String filename = tempFolder.newFile().getAbsolutePath();

  NetcdfFormatWriter.Builder writerb = NetcdfFormatWriter.createNewNetcdf3(filename);
  Attribute invalidNc3Attr = Attribute.builder().setName("will_fail").setNumericValue(1, true).build();
  writerb.addAttribute(invalidNc3Attr);

  try (NetcdfFormatWriter writer = writerb.build()) {
    // this call *should* trigger a runtime exception (IllegalArgumentException)
  } catch (IllegalArgumentException iae) {
    // if we throw a runtime error during writerb.build(), we ended up in a state
    // where the underlying RAF was not closed because the code would encounter the same issue and
    // throw another runtime error. If a user was trying to handle the runtime error, this could end
    // up causing a file handle leak.
    // this test makes sure we are able to close the file.
    File fileToDelete = new File(filename);
    assertThat(fileToDelete.exists()).isTrue();
    // if the file handle has not been released, the file delete will fail
    // assertThat(fileToDelete.delete()).isTrue();
    // still want the IllegalArgumentException to happen, we'd just like to make sure the file handle is released
    throw iae;
  }
}
 
Example #10
Source File: TestWriteMiscProblems.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testWriteBigString() throws IOException {
  String filename = tempFolder.newFile().getAbsolutePath();
  NetcdfFormatWriter.Builder writerb = NetcdfFormatWriter.createNewNetcdf3(filename);
  int len = 120000;
  ArrayChar.D1 arrayCharD1 = new ArrayChar.D1(len);
  for (int i = 0; i < len; i++)
    arrayCharD1.set(i, '1');
  writerb.addAttribute(new Attribute("tooLongChar", arrayCharD1));

  char[] carray = new char[len];
  for (int i = 0; i < len; i++)
    carray[i] = '2';
  String val = new String(carray);
  writerb.addAttribute(new Attribute("tooLongString", val));

  try (NetcdfFormatWriter ncfile = writerb.build()) {
  }
}
 
Example #11
Source File: CFPointObWriter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void main(String args[]) throws IOException {

    List<PointObVar> dataVars = new ArrayList<PointObVar>();
    dataVars.add(new PointObVar("test1", "units1", "desc1", DataType.CHAR, 4));
    dataVars.add(new PointObVar("test2", "units2", "desc3", DataType.CHAR, 4));

    // public CFPointObWriter(DataOutputStream stream, List<Attribute> globalAtts, String altUnits, List<PointObVar>
    // dataVars) throws IOException {

    FileOutputStream fos = new FileOutputStream("C:/temp/test.out");
    DataOutputStream out = new DataOutputStream(new BufferedOutputStream(fos, 10000));

    CFPointObWriter writer = new CFPointObWriter(out, new ArrayList<Attribute>(), "meters", dataVars, 1);

    double[] dvals = new double[0];
    String[] svals = new String[] {"valu", "value"};
    writer.addPoint(1.0, 2.0, 3.0, new Date(), dvals, svals);
    writer.finish();

  }
 
Example #12
Source File: BufrFeatureDatasetFactory.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private BufrStationCollection(String name) {
  super(name, null, null);

  // need the center id to match the standard fields
  Attribute centerAtt = netcdfDataset.findGlobalAttribute(BufrIosp2.centerId);
  int center = (centerAtt == null) ? 0 : centerAtt.getNumericValue().intValue();
  this.extract = new StandardFields.StandardFieldsFromStructure(center, obs);

  try {
    this.timeUnit = bufrDateUnits;
  } catch (Exception e) {
    e.printStackTrace(); // cant happen
  }

  this.altUnits = "m"; // LOOK fake units
}
 
Example #13
Source File: FeatureDatasetCapabilitiesWriter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
VariableSimpleAdapter(Element velem) {
  name = velem.getAttributeValue("name");
  String type = velem.getAttributeValue("type");
  dt = DataType.getType(type);

  atts = new ArrayList<>();
  List<Element> attElems = velem.getChildren("attribute");
  for (Element attElem : attElems) {
    String attName = attElem.getAttributeValue("name");
    ucar.ma2.Array values = NcMLReader.readAttributeValues(attElem);
    atts.add(new Attribute(attName, values));
  }

  for (Attribute att : atts) {
    if (att.getShortName().equals(CDM.UNITS))
      units = att.getStringValue();
    if (att.getShortName().equals(CDM.LONG_NAME))
      desc = att.getStringValue();
    if ((desc == null) && att.getShortName().equals("description"))
      desc = att.getStringValue();
    if ((desc == null) && att.getShortName().equals("standard_name"))
      desc = att.getStringValue();
  }
}
 
Example #14
Source File: NetcdfUtils.java    From OpenDA with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Creates a time dimension and variable.
 *
 * @param dataFile
 * @param timeCount      if timeCount is -1, then creates an unlimited timeDimension
 * @param timeUnitString
 * @return timeDimension
 */
public static Dimension createTimeVariable(NetcdfFileWriter dataFile, String timeVariableName, int timeCount, String timeUnitString) {
	//create time dimension.
	Dimension timeDimension;
	if (timeCount == -1 || timeCount == 0) {
		timeDimension = dataFile.addUnlimitedDimension(timeVariableName);
	} else {
		timeDimension = dataFile.addDimension(null,timeVariableName, timeCount);
	}

	//create time variable.
	Variable myVar = dataFile.addVariable(null,timeVariableName, ucar.ma2.DataType.DOUBLE, Arrays.asList(timeDimension) );
	dataFile.addVariableAttribute(myVar, new Attribute (STANDARD_NAME_ATTRIBUTE_NAME, TIME_VARIABLE_NAME) );
	dataFile.addVariableAttribute(myVar, new Attribute(LONG_NAME_ATTRIBUTE_NAME, TIME_VARIABLE_NAME));
	dataFile.addVariableAttribute(myVar, new Attribute(UNITS_ATTRIBUTE_NAME, timeUnitString));
	//use default calendar.
	dataFile.addVariableAttribute(myVar, new Attribute(CALENDAR_ATTRIBUTE_NAME, DEFAULT_CALENDAR_ATTRIBUTE_VALUE));
	dataFile.addVariableAttribute(myVar, new Attribute(AXIS_ATTRIBUTE_NAME, T_AXIS));
	return timeDimension;
}
 
Example #15
Source File: NcStream.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static NcStreamProto.Structure.Builder encodeStructure(Structure s) throws IOException {
  NcStreamProto.Structure.Builder builder = NcStreamProto.Structure.newBuilder();
  builder.setName(s.getShortName());
  builder.setDataType(convertDataType(s.getDataType()));

  for (Dimension dim : s.getDimensions())
    builder.addShape(encodeDim(dim));

  for (Attribute att : s.attributes())
    builder.addAtts(encodeAtt(att));

  for (Variable v : s.getVariables()) {
    if (v instanceof Structure)
      builder.addStructs(NcStream.encodeStructure((Structure) v));
    else
      builder.addVars(NcStream.encodeVar(v, -1));
  }

  return builder;
}
 
Example #16
Source File: CFGridCoverageWriter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void addLatLon2D(CoverageCollection subsetDataset, Group.Builder group) {
  HorizCoordSys horizCoordSys = subsetDataset.getHorizCoordSys();
  CoverageCoordAxis1D xAxis = horizCoordSys.getXAxis();
  CoverageCoordAxis1D yAxis = horizCoordSys.getYAxis();

  Dimension xDim = group.findDimension(xAxis.getName())
      .orElseThrow(() -> new IllegalStateException("We should've added X dimension in addDimensions()."));
  Dimension yDim = group.findDimension(yAxis.getName())
      .orElseThrow(() -> new IllegalStateException("We should've added Y dimension in addDimensions()."));

  List<Dimension> dims = Arrays.asList(yDim, xDim);

  Variable.Builder latVar = Variable.builder().setName("lat").setDataType(DataType.DOUBLE).setDimensions(dims);
  latVar.addAttribute(new Attribute(CDM.UNITS, CDM.LAT_UNITS));
  latVar.addAttribute(new Attribute(CF.STANDARD_NAME, CF.LATITUDE));
  latVar.addAttribute(new Attribute(CDM.LONG_NAME, "latitude coordinate"));
  latVar.addAttribute(new Attribute(_Coordinate.AxisType, AxisType.Lat.toString()));
  group.addVariable(latVar);

  Variable.Builder lonVar = Variable.builder().setName("lon").setDataType(DataType.DOUBLE).setDimensions(dims);
  lonVar.addAttribute(new Attribute(CDM.UNITS, CDM.LON_UNITS));
  lonVar.addAttribute(new Attribute(CF.STANDARD_NAME, CF.LONGITUDE));
  lonVar.addAttribute(new Attribute(CDM.LONG_NAME, "longitude coordinate"));
  lonVar.addAttribute(new Attribute(_Coordinate.AxisType, AxisType.Lon.toString()));
  group.addVariable(lonVar);
}
 
Example #17
Source File: WRFConvention.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Nullable
private CoordinateAxis.Builder makeLonCoordAxis(String axisName, Dimension dim) {
  if (dim == null)
    return null;
  double dx = 4 * findAttributeDouble("DX");
  int nx = dim.getLength();
  double startx = centerX - dx * (nx - 1) / 2;

  CoordinateAxis.Builder v = CoordinateAxis1D.builder().setName(axisName).setDataType(DataType.DOUBLE)
      .setDimensionsByName(dim.getShortName()).setUnits("degrees_east").setDesc("synthesized longitude coordinate");
  v.setAutoGen(startx, dx);
  v.setAxisType(AxisType.Lon);
  v.addAttribute(new Attribute(_Coordinate.AxisType, "Lon"));
  if (!axisName.equals(dim.getShortName()))
    v.addAttribute(new Attribute(_Coordinate.AliasForDimension, dim.getShortName()));

  return v;
}
 
Example #18
Source File: GridDatasetInfo.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private Element writeAxis(CoordinateAxis axis) {
  NcmlWriter ncmlWriter = new NcmlWriter();

  Element varElem = new Element("axis");
  varElem.setAttribute("name", axis.getFullName());
  varElem.setAttribute("shape", getShapeString(axis.getShape())); // axis.getDimensionsString());

  DataType dt = axis.getDataType();
  varElem.setAttribute("type", dt.toString());

  AxisType axisType = axis.getAxisType();
  if (null != axisType)
    varElem.setAttribute("axisType", axisType.toString());

  // attributes
  for (Attribute att : axis.attributes()) {
    varElem.addContent(ncmlWriter.makeAttributeElement(att));
  }

  if (axis.getRank() == 1) {
    try {
      Element values = ncmlWriter.makeValuesElement(axis, true);
      varElem.addContent(values);
    } catch (IOException e) {
      String message = String.format("Couldn't read values for %s. Omitting <values> element.", axis.getFullName());
      logger.warn(message, e);
    }
  }

  return varElem;
}
 
Example #19
Source File: IFPSConvention.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public boolean isMine(NetcdfFile ncfile) {
  // check that file has a latitude and longitude variable, and that latitude has an attribute called
  // projectionType
  boolean geoVarsCheck;
  Variable v = ncfile.findVariable("latitude");
  if (null != ncfile.findVariable("longitude") && (null != v)) {
    geoVarsCheck = (null != v.findAttributeString("projectionType", null));
  } else {
    // bail early
    return false;
  }

  // check that there is a global attribute called fileFormatVersion, and that it has one
  // of two known values
  boolean fileFormatCheck;
  Attribute ff = ncfile.findGlobalAttributeIgnoreCase("fileFormatVersion");
  if (ff != null) {
    String ffValue = ff.getStringValue();
    // two possible values (as of now)
    fileFormatCheck = (ffValue.equalsIgnoreCase("20030117") || ffValue.equalsIgnoreCase("20010816"));
  } else {
    // bail
    return false;
  }

  // both must be true
  return (geoVarsCheck && fileFormatCheck);
}
 
Example #20
Source File: CompositePointCollection.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** @deprecated use attributes() */
@Deprecated
public List<Attribute> getGlobalAttributes() {
  if (globalAttributes == null)
    readMetadata();
  return ImmutableList.copyOf(globalAttributes);
}
 
Example #21
Source File: NcStream.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static Attribute decodeAtt(NcStreamProto.Attribute attp) {
  // BARF LOOK
  DataType dtOld = decodeAttributeType(attp.getType());
  DataType dtNew = convertDataType(attp.getDataType());
  DataType dtUse;
  if (dtNew != DataType.CHAR)
    dtUse = dtNew;
  else if (dtOld != DataType.STRING)
    dtUse = dtOld;
  else if (attp.getSdataCount() > 0)
    dtUse = DataType.STRING;
  else
    dtUse = DataType.CHAR;

  int len = attp.getLen();
  if (len == 0) // deal with empty attribute
    return Attribute.builder(attp.getName()).setDataType(dtUse).build();

  if (dtUse == DataType.STRING) {
    int lenp = attp.getSdataCount();
    if (lenp != len)
      System.out.println("HEY lenp != len");
    if (lenp == 1)
      return new Attribute(attp.getName(), attp.getSdata(0));
    else {
      Array data = Array.factory(dtUse, new int[] {lenp});
      for (int i = 0; i < lenp; i++)
        data.setObject(i, attp.getSdata(i));
      return new Attribute(attp.getName(), data);
    }
  } else {
    ByteString bs = attp.getData();
    ByteBuffer bb = ByteBuffer.wrap(bs.toByteArray());
    // if null, then use int[]{bb.limit()}
    return new Attribute(attp.getName(), Array.factory(dtUse, (int[]) null, bb));
  }
}
 
Example #22
Source File: CdmrfReader.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
CoverageTransform decodeCoordTransform(CdmrFeatureProto.CoordTransform proto) {

    String name = proto.getName();
    AttributeContainerMutable atts = new AttributeContainerMutable(name);
    for (ucar.nc2.stream.NcStreamProto.Attribute patt : proto.getParamsList())
      atts.addAttribute(NcStream.decodeAtt(patt));

    return new CoverageTransform(name, atts, proto.getIsHoriz());
  }
 
Example #23
Source File: GDVConvention.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected void augmentDataset(CancelTask cancelTask) throws IOException {
  projCT = makeProjectionCT();
  if (projCT != null) {
    VariableDS.Builder vb = makeCoordinateTransformVariable(projCT);
    rootGroup.addVariable(vb);

    String xname = findCoordinateName(AxisType.GeoX);
    String yname = findCoordinateName(AxisType.GeoY);
    if (xname != null && yname != null)
      vb.addAttribute(new Attribute(_Coordinate.Axes, xname + " " + yname));
  }
}
 
Example #24
Source File: AWIPSConvention.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void createNewVariables(NetcdfDataset ds, Variable ncVar, List<Dimension> newDims, Dimension levelDim)
    throws InvalidRangeException {

  List<Dimension> dims = ncVar.getDimensions();
  int newDimIndex = dims.indexOf(levelDim);
  // String shapeS = ncVar.getShapeS();

  int[] origin = new int[ncVar.getRank()];
  int[] shape = ncVar.getShape();
  int count = 0;
  for (Dimension dim : newDims) {
    String name = ncVar.getShortName() + "-" + dim.getShortName();

    origin[newDimIndex] = count;
    shape[newDimIndex] = dim.getLength();

    Variable varNew = ncVar.section(new Section(origin, shape));
    varNew.setName(name);
    varNew.setDimension(newDimIndex, dim);

    // synthesize long name
    String long_name = ds.findAttValueIgnoreCase(ncVar, CDM.LONG_NAME, ncVar.getShortName());
    long_name = long_name + "-" + dim.getShortName();
    ds.addVariableAttribute(varNew, new Attribute(CDM.LONG_NAME, long_name));

    ds.addVariable(null, varNew);

    parseInfo.format("Created New Variable as section = ");
    varNew.getNameAndDimensions(parseInfo, true, false);
    parseInfo.format("%n");

    count += dim.getLength();
  }
}
 
Example #25
Source File: WriterCFPointAbstract.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void addDataVariablesClassic(Dimension recordDim, StructureData stnData, HashSet<String> varSet,
    String coordVars) {
  addDimensionsClassic(dataVars);

  for (StructureMembers.Member m : stnData.getMembers()) {
    VariableSimpleIF oldVar = findDataVar(m.getName());
    if (oldVar == null)
      continue;

    List<Dimension> dims = makeDimensionList(oldVar.getDimensions());
    dims.add(0, recordDim);

    Variable.Builder newVar;
    if (oldVar.getDataType() == DataType.STRING && !isExtendedModel) {
      // What should the string length be ??
      String name = oldVar.getShortName();
      Dimension strlen = new Dimension(name + "_strlen", defaultStringLength);
      newVar = Variable.builder().setName(name).setDataType(DataType.CHAR).setDimensions(dims).addDimension(strlen);
      writerb.getRootGroup().addDimensionIfNotExists(strlen);
    } else {
      newVar =
          Variable.builder().setName(oldVar.getShortName()).setDataType(oldVar.getDataType()).setDimensions(dims);
    }

    if (writerb.getRootGroup().replaceVariable(newVar)) {
      logger.warn("Variable was already added =" + oldVar.getShortName());
    }

    for (Attribute att : oldVar.attributes()) {
      String attName = att.getShortName();
      if (!reservedVariableAtts.contains(attName) && !attName.startsWith("_Coordinate"))
        newVar.addAttribute(att);
    }
    newVar.addAttribute(new Attribute(CF.COORDINATES, coordVars));
    varSet.add(oldVar.getShortName());
  }

}
 
Example #26
Source File: CoverageDatasetCapabilities.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private Element writeCoordTransform(CoverageTransform ct) {
  Element ctElem = new Element("coordTransform");
  ctElem.setAttribute("name", ct.getName());
  ctElem.setAttribute("transformType", ct.isHoriz() ? "Projection" : "Vertical");
  for (Attribute param : ct.attributes()) {
    Element pElem = ncmlWriter.makeAttributeElement(param);
    pElem.setName("parameter");
    ctElem.addContent(pElem);
  }
  return ctElem;
}
 
Example #27
Source File: MetadataExtractorAcdd.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void addDate(String dateType) {
  Attribute att = ncfile.get(dateType);
  if (att != null) {
    String dateValue = att.getStringValue();

    try {
      tmi.addDate(new DateType(dateValue, null, dateType));
    } catch (Exception e) {
      log.warn("MetadataExtractorAcdd Cant Parse {} date '{}' for {} message= {}", dateType, dateValue,
          ds.getFullName(), e.getMessage());
    }
  }
}
 
Example #28
Source File: HdfEosOmiConvention.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private CoordinateAxis.Builder makeLatCoordAxis(Group.Builder g2, int n, String dimName) {
  CoordinateAxis.Builder v = CoordinateAxis1D.builder().setName("lat").setDataType(DataType.FLOAT)
      .setParentGroupBuilder(g2).setDimensionsByName(dimName).setUnits(CDM.LAT_UNITS).setDesc("latitude");

  double incr = 180.0 / n;
  v.setAutoGen(-90.0 + 0.5 * incr, incr);
  v.addAttribute(new Attribute(_Coordinate.AxisType, AxisType.Lat.toString()));
  return v;
}
 
Example #29
Source File: AWIPSConvention.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
double findAttributeDouble(String attname) {
  Attribute att = rootGroup.getAttributeContainer().findAttributeIgnoreCase(attname);
  if (att == null || att.isString()) {
    parseInfo.format("ERROR cant find numeric attribute= %s%n", attname);
    return Double.NaN;
  }
  return att.getNumericValue().doubleValue();
}
 
Example #30
Source File: NetcdfUtils.java    From OpenDA with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @param variable
 * @return value from the add_offset attribute for the given variable.
 */
public static double getOffSetDouble(Variable variable) {
       Attribute attribute = variable.findAttribute(ADD_OFFSET_ATTRIBUTE_NAME);
       if (attribute != null) {
           return attribute.getNumericValue().doubleValue();
       } else {
           return 0;
       }
}