Java Code Examples for ucar.nc2.Attribute

The following examples show how to use ucar.nc2.Attribute. 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
@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 2
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 3
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 4
@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 5
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 6
Source Project: netcdf-java   Source File: NcStream.java    License: 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 7
@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 8
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
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 10
@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 11
@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 12
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 13
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 14
@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 15
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 16
Source Project: OpenDA   Source File: NetcdfUtils.java    License: 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 17
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 18
@Override
public Attribute findAttributeIgnoreCase(String name) {
  for (Attribute att : atts) {
    if (att.getShortName().equalsIgnoreCase(name))
      return att;
  }
  return null;
}
 
Example 19
Source Project: netcdf-java   Source File: NcStream.java    License: 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 20
Source Project: netcdf-java   Source File: NcStream.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static Builder encodeVar(Variable var, int sizeToCache) throws IOException {
  Builder builder = NcStreamProto.Variable.newBuilder();
  builder.setName(var.getShortName());
  builder.setDataType(convertDataType(var.getDataType()));
  if (var.getDataType().isEnum()) {
    EnumTypedef enumType = var.getEnumTypedef();
    if (enumType != null)
      builder.setEnumType(enumType.getShortName());
  }

  for (Dimension dim : var.getDimensions()) {
    builder.addShape(encodeDim(dim));
  }

  for (Attribute att : var.attributes()) {
    builder.addAtts(encodeAtt(att));
  }

  // put small amounts of data in header "immediate mode"
  if (var.isCaching() && var.getDataType().isNumeric()) {
    if (var.isCoordinateVariable() || var.getSize() * var.getElementSize() < sizeToCache) {
      Array data = var.read();
      ByteBuffer bb = data.getDataAsByteBuffer();
      builder.setData(ByteString.copyFrom(bb.array()));
    }
  }

  return builder;
}
 
Example 21
@Override
public void addGlobalAttributes(AttributeContainer result) {
  String val = cust.getGeneratingProcessTypeName(getGenProcessType());
  if (val != null)
    result.addAttribute(new Attribute("Type_of_generating_process", val));
  val = cust.getGeneratingProcessName(getGenProcessId());
  if (val != null)
    result.addAttribute(
        new Attribute("Analysis_or_forecast_generating_process_identifier_defined_by_originating_centre", val));
  val = cust.getGeneratingProcessName(getBackProcessId());
  if (val != null)
    result.addAttribute(new Attribute("Background_generating_process_identifier_defined_by_originating_centre", val));
  result.addAttribute(new Attribute(CDM.FILE_FORMAT, DataFormatType.GRIB2.getDescription()));
}
 
Example 22
private double findAttributeDouble(NetcdfDataset ds, String attname) {
  Attribute att = ds.findGlobalAttributeIgnoreCase(attname);
  if (att == null) {
    parseInfo.format("ERROR cant find attribute= %s%n", attname);
    return Double.NaN;
  }
  return att.getNumericValue().doubleValue();
}
 
Example 23
@Test
public void testAxisAttrCombineSame() {
  Attribute attr1 = new Attribute(_Coordinate.Axes, "abe bec cid dave");
  Attribute attr2 = new Attribute(_Coordinate.Axes, "abe bec cid dave");
  Attribute attr3 = combineAxesAttrs(attr1, attr2);

  assertEquals(attr3.getStringValue(), (attr1.getStringValue()));
  assertEquals(attr3.getStringValue(), attr2.getStringValue());
}
 
Example 24
WriterCFProfileCollection(String fileOut, AttributeContainer globalAtts, List<VariableSimpleIF> dataVars,
    CalendarDateUnit timeUnit, String altUnits, CFPointWriterConfig config) throws IOException {
  super(fileOut, globalAtts, dataVars, timeUnit, altUnits, config);
  writerb.addAttribute(
      new Attribute(CF.DSG_REPRESENTATION, "Contiguous ragged array representation of profiles, H.3.4"));
  writerb.addAttribute(new Attribute(CF.FEATURE_TYPE, CF.FeatureType.profile.name()));
}
 
Example 25
private void createNewVariables(VariableDS.Builder ncVar, List<Dimension> newDims, Dimension levelDim)
    throws InvalidRangeException {

  ArrayList<Dimension> dims = new ArrayList<>(ncVar.orgVar.getDimensions());
  int newDimIndex = dims.indexOf(levelDim);

  int[] origin = new int[ncVar.getRank()];
  int[] shape = ncVar.orgVar.getShape();
  int count = 0;
  for (Dimension dim : newDims) {
    origin[newDimIndex] = count;
    shape[newDimIndex] = dim.getLength();
    Variable varSection = ncVar.orgVar.section(new Section(origin, shape));

    String name = ncVar.shortName + "-" + dim.getShortName();
    VariableDS.Builder varNew =
        VariableDS.builder().setName(name).setOriginalVariable(varSection).setDataType(ncVar.dataType);
    dims.set(newDimIndex, dim);
    varNew.addDimensions(dims);
    varNew.addAttributes(ncVar.getAttributeContainer());

    // synthesize long name
    String long_name = ncVar.getAttributeContainer().findAttributeString(CDM.LONG_NAME, ncVar.shortName);
    long_name = long_name + "-" + dim.getShortName();
    varNew.getAttributeContainer().addAttribute(new Attribute(CDM.LONG_NAME, long_name));

    rootGroup.addVariable(varNew);
    parseInfo.format("Created New Variable as section = %s%n", name);
    count += dim.getLength();
  }
}
 
Example 26
@Override
public List<Attribute> getGlobalAttributes() {
  if (globalAttributes == null) {
    if (pfc instanceof CompositePointCollection)
      globalAttributes = ((CompositePointCollection) pfc).getGlobalAttributes();
    else if (pfc instanceof CompositeStationCollection)
      globalAttributes = ((CompositeStationCollection) pfc).getGlobalAttributes();
  }

  return globalAttributes;
}
 
Example 27
public void setVocabularyId(Attribute id) {
  if (id == null)
    return;
  StringBuilder sbuff = new StringBuilder();
  for (int i = 0; i < id.getLength(); i++) {
    if (i > 0)
      sbuff.append(",");
    sbuff.append(id.getNumericValue(i));
  }
  this.id = sbuff.toString();
}
 
Example 28
private CoverageCoordAxis makeRuntimeAuxCoord(CoordinateTime2D time2D, int ntimes) {
  CoordinateRuntime runtimeU = time2D.getRuntimeCoordinate();
  List<Double> runOffsets = runtimeU.getOffsetsInTimeUnits();

  double[] values = new double[ntimes];
  int count = 0;
  for (int run = 0; run < time2D.getNruns(); run++) {
    CoordinateTimeAbstract timeCoord = time2D.getTimeCoordinate(run);
    for (int time = 0; time < timeCoord.getNCoords(); time++)
      values[count++] = runOffsets.get(run);
  }

  boolean isScalar = (time2D.getNruns() == 1); // this is the case of runtime[1]
  CoverageCoordAxis.DependenceType dependence =
      isScalar ? CoverageCoordAxis.DependenceType.scalar : CoverageCoordAxis.DependenceType.dependent;
  String refName = "ref" + time2D.getName();

  AttributeContainerMutable atts = new AttributeContainerMutable(time2D.getName());
  atts.addAttribute(new Attribute(CDM.UNITS, time2D.getTimeUdUnit()));
  atts.addAttribute(new Attribute(CF.STANDARD_NAME, CF.TIME_REFERENCE));
  atts.addAttribute(new Attribute(CDM.LONG_NAME, Grib.GRIB_RUNTIME));
  atts.addAttribute(new Attribute(CF.CALENDAR, ucar.nc2.time.Calendar.proleptic_gregorian.toString()));

  CoverageCoordAxisBuilder builder = new CoverageCoordAxisBuilder(refName, time2D.getTimeUdUnit(), Grib.GRIB_RUNTIME,
      DataType.DOUBLE, AxisType.RunTime, atts, dependence, time2D.getName(), null, ntimes, 0, 0, 0, values, this);
  builder.setSpacingFromValues(false);

  return new CoverageCoordAxis1D(builder);
}
 
Example 29
public T setDesc(String desc) {
  this.desc = desc;
  if (desc != null) {
    addAttribute(new Attribute(CDM.LONG_NAME, desc));
  }
  return self();
}
 
Example 30
private void addGlobalAtts(AttributeContainer atts) {
  writerb.addAttribute(new Attribute(CDM.CONVENTIONS, isExtendedModel ? CDM.CF_EXTENDED : "CF-1.6"));
  writerb.addAttribute(new Attribute(CDM.HISTORY, "Written by CFPointWriter"));
  for (Attribute att : atts) {
    if (!reservedGlobalAtts.contains(att.getShortName()))
      writerb.addAttribute(att);
  }
}