Java Code Examples for ucar.ma2.DataType#getType()

The following examples show how to use ucar.ma2.DataType#getType() . 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: RowParser.java    From tablestore-examples with Apache License 2.0 6 votes vote down vote up
public static GridDataSetMeta parseMetaFromRow(Row row) {
    String uniqueKey = row.getPrimaryKey().getPrimaryKeyColumn(GRID_DATA_SET_ID_PK_NAME).getValue().asString();
    DataType dataType = DataType.getType(row.getColumn(DATA_TYPE_COL_NAME).get(0).getValue().asString());
    List<String> variables = Arrays.asList(row.getColumn(VARIABLE_LIST_COL_NAME).get(0).getValue().asString().split(","));
    int tSize = (int) row.getColumn(T_SIZE_COL_NAME).get(0).getValue().asLong();
    int zSize = (int) row.getColumn(Z_SIZE_COL_NAME).get(0).getValue().asLong();
    int xSize = (int) row.getColumn(X_SIZE_COL_NAME).get(0).getValue().asLong();
    int ySize = (int) row.getColumn(Y_SIZE_COL_NAME).get(0).getValue().asLong();

    StoreOptions.StoreType storeType = StoreOptions.StoreType.valueOf(
            row.getColumn(STORE_TYPE_COL_NAME).get(0).getValue().asString());
    StoreOptions storeOptions = new StoreOptions(storeType);
    if (storeType.equals(StoreOptions.StoreType.SLICE)) {
        storeOptions.setxSplitCount((int) row.getColumn(X_SPLIT_COUNT_COL_NAME).get(0).getValue().asLong());
        storeOptions.setySplitCount((int) row.getColumn(Y_SPLIT_COUNT_COL_NAME).get(0).getValue().asLong());
    }
    Map<String, Object> attributes = new HashMap<String, Object>();
    for (Column column : row.getColumns()) {
        if (!column.getName().startsWith("_")) {
            attributes.put(column.getName(), ValueUtil.toObject(column.getValue()));
        }
    }
    GridDataSetMeta meta = new GridDataSetMeta(uniqueKey, dataType, variables, tSize, zSize, xSize, ySize, storeOptions);
    meta.setAttributes(attributes);
    return meta;
}
 
Example 2
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 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: 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 5
Source File: Attribute.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Create a scalar numeric-valued Attribute, possibly unsigned.
 *
 * @param name name of Attribute
 * @param val value of Attribute
 * @param isUnsigned if value is unsigned, used only for integer types.
 */
public Attribute(String name, Number val, boolean isUnsigned) {
  super(name);
  if (name == null)
    throw new IllegalArgumentException("Trying to set name to null on " + this);

  int[] shape = new int[1];
  shape[0] = 1;
  DataType dt = DataType.getType(val.getClass(), isUnsigned);
  this.dataType = dt;
  Array vala = Array.factory(dt, shape);
  Index ima = vala.getIndex();
  vala.setObject(ima.set0(0), val);
  setValues(vala); // make private
  setImmutable();
}
 
Example 6
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 7
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;

  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 8
Source File: NcMLReader.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Read an NcML enumTypedef element.
 *
 * @param g put enumTypedef into this group
 * @param refg parent Group in referenced dataset
 * @param etdElem ncml enumTypedef element
 */
private void readEnumTypedef(Group g, Group refg, Element etdElem) {
  String name = etdElem.getAttributeValue("name");
  if (name == null) {
    errlog.format("NcML enumTypedef name is required (%s)%n", etdElem);
    return;
  }
  String typeS = etdElem.getAttributeValue("type");
  DataType baseType = (typeS == null) ? DataType.ENUM1 : DataType.getType(typeS);

  Map<Integer, String> map = new HashMap<>(100);
  for (Element e : etdElem.getChildren("enum", ncNS)) {
    String key = e.getAttributeValue("key");
    String value = e.getTextNormalize();
    if (key == null) {
      errlog.format("NcML enumTypedef enum key attribute is required (%s)%n", e);
      continue;
    }
    if (value == null) {
      errlog.format("NcML enumTypedef enum value is required (%s)%n", e);
      continue;
    }
    try {
      int keyi = Integer.parseInt(key);
      map.put(keyi, value);
    } catch (Exception e2) {
      errlog.format("NcML enumTypedef enum key attribute not an integer (%s)%n", e);
    }
  }

  EnumTypedef td = new EnumTypedef(name, map, baseType);
  g.addEnumeration(td);
}
 
Example 9
Source File: AggregationOuter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected void promoteGlobalAttributes(AggDatasetOuter typicalDataset) throws IOException {

    for (CacheVar cv : cacheList) {
      if (!(cv instanceof PromoteVar))
        continue;
      PromoteVar pv = (PromoteVar) cv;

      Array data = pv.read(typicalDataset);
      if (data == null)
        throw new IOException("cant read " + typicalDataset);

      pv.dtype = DataType.getType(data);
      VariableDS.Builder promotedVar = VariableDS.builder().setName(pv.varName).setDataType(pv.dtype)
          .setParentGroupBuilder(ncDataset.rootGroup).setDimensionsByName(dimName);
      /*
       * if (data.getSize() > 1) { // LOOK case of non-scalar global attribute not dealt with
       * Dimension outer = ncDataset.getRootGroup().findDimension(dimName);
       * Dimension inner = new Dimension("", (int) data.getSize(), false); //anonymous
       * List<Dimension> dims = new ArrayList<Dimension>(2);
       * dims.add(outer);
       * dims.add(inner);
       * promotedVar.setDimensions(dims);
       * }
       */

      ncDataset.rootGroup.addVariable(promotedVar);
      promotedVar.setProxyReader(this);
      promotedVar.setSPobject(pv);
    }
  }
 
Example 10
Source File: NcMLReaderNew.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private StructureDS.Builder readStructureNew(Group.Builder groupBuilder, Element varElem) {
  String name = varElem.getAttributeValue("name");
  String type = varElem.getAttributeValue("type");
  DataType dtype = DataType.getType(type);

  // list of dimension names
  String dimNames = varElem.getAttributeValue("shape");
  if (dimNames == null) {
    dimNames = ""; // deprecated, prefer explicit ""
  }
  List<Dimension> varDims = groupBuilder.makeDimensionsList(dimNames);

  StructureDS.Builder structBuilder;
  if (dtype == DataType.STRUCTURE) {
    structBuilder = StructureDS.builder().setName(name).addDimensions(varDims);
  } else {
    structBuilder = SequenceDS.builder().setName(name);
  }

  java.util.List<Element> varList = varElem.getChildren("variable", ncNS);
  for (Element vElem : varList) {
    readMemberVariable(groupBuilder, structBuilder, null, vElem);
  }

  // look for attributes
  java.util.List<Element> attList = varElem.getChildren("attribute", ncNS);
  for (Element attElem : attList) {
    readAtt(structBuilder.getAttributeContainer(), null, attElem);
  }

  return structBuilder;
}
 
Example 11
Source File: NcMLReaderNew.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Read an NcML enumTypedef element.
 *
 * @param g put enumTypedef into this group
 * @param etdElem ncml enumTypedef element
 */
private void readEnumTypedef(Group.Builder g, Element etdElem) {
  String name = etdElem.getAttributeValue("name");
  if (name == null) {
    errlog.format("NcML enumTypedef name is required (%s)%n", etdElem);
    return;
  }
  String typeS = etdElem.getAttributeValue("type");
  DataType baseType = (typeS == null) ? DataType.ENUM1 : DataType.getType(typeS);

  Map<Integer, String> map = new HashMap<>(100);
  for (Element e : etdElem.getChildren("enum", ncNS)) {
    String key = e.getAttributeValue("key");
    String value = e.getTextNormalize();
    if (key == null) {
      errlog.format("NcML enumTypedef enum key attribute is required (%s)%n", e);
      continue;
    }
    if (value == null) {
      errlog.format("NcML enumTypedef enum value is required (%s)%n", e);
      continue;
    }
    try {
      int keyi = Integer.parseInt(key);
      map.put(keyi, value);
    } catch (Exception e2) {
      errlog.format("NcML enumTypedef enum key attribute not an integer (%s)%n", e);
    }
  }

  EnumTypedef td = new EnumTypedef(name, map, baseType);
  g.addEnumTypedef(td);
}
 
Example 12
Source File: Attribute.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public Builder setNumericValue(Number val, boolean isUnsigned) {
  int[] shape = {1};
  DataType dt = DataType.getType(val.getClass(), isUnsigned);
  setDataType(dt);
  Array vala = Array.factory(dt, shape);
  Index ima = vala.getIndex();
  vala.setObject(ima.set0(0), val);
  setValues(vala);
  return this;
}
 
Example 13
Source File: Attribute.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Construct attribute with list of String or Number values.
 * The list determines the attribute type
 * 
 * @param name name of attribute
 * @param values list of values. must be String or Number, must all be the same type, and have at least 1 member
 * @param isUnsigned if the data type is unsigned.
 */
public Attribute(String name, List values, boolean isUnsigned) {
  this(name);
  if (values == null || values.isEmpty())
    throw new IllegalArgumentException("Cannot determine attribute's type");
  Class c = values.get(0).getClass();
  this.dataType = DataType.getType(c, isUnsigned);
  setValues(values); // make private
  setImmutable();
}
 
Example 14
Source File: AggregationOuterDimension.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected void promoteGlobalAttributes(DatasetOuterDimension typicalDataset) throws IOException {

    for (CacheVar cv : cacheList) {
      if (!(cv instanceof PromoteVar))
        continue;
      PromoteVar pv = (PromoteVar) cv;

      Array data = pv.read(typicalDataset);
      if (data == null)
        throw new IOException("cant read " + typicalDataset);

      pv.dtype = DataType.getType(data);
      VariableDS promotedVar = new VariableDS(ncDataset, null, null, pv.varName, pv.dtype, dimName, null, null);
      /*
       * if (data.getSize() > 1) { // LOOK case of non-scalar global attribute not delat with
       * Dimension outer = ncDataset.getRootGroup().findDimension(dimName);
       * Dimension inner = new Dimension("", (int) data.getSize(), false); //anonymous
       * List<Dimension> dims = new ArrayList<Dimension>(2);
       * dims.add(outer);
       * dims.add(inner);
       * promotedVar.setDimensions(dims);
       * }
       */

      ncDataset.addVariable(null, promotedVar);
      promotedVar.setProxyReader(this);
      promotedVar.setSPobject(pv);
    }
  }
 
Example 15
Source File: NcMLReaderNew.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Read the NcML variable element, and nested elements.
 *
 * @param groupBuilder put dimension into this group
 * @param refGroup parent Group in referenced dataset, may be null
 * @param varElem ncml variable element
 */
private void readVariable(Group.Builder groupBuilder, @Nullable Group refGroup, Element varElem) {
  String name = varElem.getAttributeValue("name");
  if (name == null) {
    errlog.format("NcML Variable name is required (%s)%n", varElem);
    return;
  }
  String nameInFile = Optional.ofNullable(varElem.getAttributeValue("orgName")).orElse(name);

  DataType dtype = null;
  String typeS = varElem.getAttributeValue("type");
  if (typeS != null) {
    dtype = DataType.getType(typeS);
  }

  // see if it already exists
  Variable refv = (refGroup == null) ? null : refGroup.findVariableLocal(nameInFile);
  Optional<Variable.Builder<?>> addedFromAgg = groupBuilder.findVariableLocal(nameInFile);
  if (refv == null && !addedFromAgg.isPresent()) { // new
    if (dtype == null) {
      errlog.format("NcML Variable dtype is required for new variable (%s)%n", name);
      return;
    }
    if (dtype == DataType.STRUCTURE || dtype == DataType.SEQUENCE) {
      groupBuilder.addVariable(readStructureNew(groupBuilder, varElem));
    } else {
      groupBuilder.addVariable(readVariableNew(groupBuilder, dtype, varElem));
    }
    return;
  }

  // refv exists
  if (refv != null) {
    if (dtype == null) {
      dtype = refv.getDataType();
    }
    if (dtype == DataType.STRUCTURE || dtype == DataType.SEQUENCE) {
      readStructureExisting(groupBuilder, null, dtype, (Structure) refv, varElem)
          .ifPresent(groupBuilder::addVariable);
    } else {
      readVariableExisting(groupBuilder, null, dtype, refv, varElem).ifPresent(groupBuilder::addVariable);
    }
    return;
  }

  // refv does not exist, but addedFromAgg may be present
  DataType finalDtype = dtype;
  addedFromAgg.ifPresent(agg -> {
    if (agg instanceof VariableDS.Builder<?>) {
      VariableDS.Builder<?> aggDs = (VariableDS.Builder<?>) agg;
      aggDs.setOriginalName(nameInFile);
    }
    DataType reallyFinalDtype = finalDtype != null ? finalDtype : agg.dataType;
    augmentVariableNew(agg, reallyFinalDtype, varElem);
  });
}
 
Example 16
Source File: NcMLReaderNew.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void readMemberVariable(Group.Builder groupBuilder, StructureDS.Builder<?> parentStructure,
    @Nullable Structure refParentStructure, Element varElem) {
  String name = varElem.getAttributeValue("name");
  if (name == null) {
    errlog.format("NcML Variable name is required (%s)%n", varElem);
    return;
  }
  String nameInFile = Optional.ofNullable(varElem.getAttributeValue("orgName")).orElse(name);

  DataType dtype = null;
  String typeS = varElem.getAttributeValue("type");
  if (typeS != null) {
    dtype = DataType.getType(typeS);
  }

  // see if it already exists
  Variable refv = (refParentStructure == null) ? null : refParentStructure.findVariable(nameInFile);
  if (refv == null) { // new
    if (dtype == null) {
      errlog.format("NcML Variable dtype is required for new (nested) variable (%s)%n", name);
      return;
    }
    if (dtype == DataType.STRUCTURE || dtype == DataType.SEQUENCE) {
      parentStructure.addMemberVariable(readStructureNew(groupBuilder, varElem));
    } else {
      parentStructure.addMemberVariable(readVariableNew(groupBuilder, dtype, varElem));
    }
    return;
  }

  // refv exists
  if (dtype == null) {
    dtype = refv.getDataType();
  }

  if (dtype == DataType.STRUCTURE || dtype == DataType.SEQUENCE) {
    readStructureExisting(groupBuilder, parentStructure, dtype, (Structure) refv, varElem)
        .ifPresent(parentStructure::addMemberVariable);
  } else {
    readVariableExisting(groupBuilder, parentStructure, dtype, refv, varElem)
        .ifPresent(parentStructure::addMemberVariable);
  }
}
 
Example 17
Source File: NcMLReaderNew.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Parse the values element
 *
 * @param s JDOM element to parse
 * @return Array with parsed values
 * @throws IllegalArgumentException if string values not parsable to specified data type
 */
private static ucar.ma2.Array readAttributeValues(Element s) throws IllegalArgumentException {
  String valString = s.getAttributeValue("value");

  // can also be element text
  if (valString == null) {
    valString = s.getTextNormalize();
  }

  // no value specified hmm technically this is not illegal !!
  if (valString == null) {
    throw new IllegalArgumentException("No value specified");
  }

  String type = s.getAttributeValue("type");
  DataType dtype = (type == null) ? DataType.STRING : DataType.getType(type);
  if (dtype == DataType.CHAR) {
    dtype = DataType.STRING;
  }

  // backwards compatibility with deprecated isUnsigned attribute
  String unS = s.getAttributeValue("isUnsigned");
  boolean isUnsignedSet = "true".equalsIgnoreCase(unS);
  if (isUnsignedSet && dtype.isIntegral() && !dtype.isUnsigned()) {
    dtype = dtype.withSignedness(DataType.Signedness.UNSIGNED);
  }

  String sep = s.getAttributeValue("separator");
  if ((sep == null) && (dtype == DataType.STRING)) {
    List<String> list = new ArrayList<>();
    list.add(valString);
    return Array.makeArray(dtype, list);
  }

  if (sep == null) {
    sep = " "; // default whitespace separated
  }

  List<String> stringValues = new ArrayList<>();
  StringTokenizer tokn = new StringTokenizer(valString, sep);
  while (tokn.hasMoreTokens()) {
    stringValues.add(tokn.nextToken());
  }

  return Array.makeArray(dtype, stringValues);
}
 
Example 18
Source File: IFPSConvention.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void createTimeCoordinate(VariableDS.Builder<?> ncVar) {
  // Time coordinate is stored in the attribute validTimes
  // One caveat is that the times have two bounds an upper and a lower

  // get the times values
  Attribute timesAtt = ncVar.getAttributeContainer().findAttribute("validTimes");
  if (timesAtt == null)
    return;
  Array timesArray = timesAtt.getValues();

  // get every other one LOOK this is awkward
  try {
    int n = (int) timesArray.getSize();
    List<Range> list = new ArrayList<>();
    list.add(new Range(0, n - 1, 2));
    timesArray = timesArray.section(list);
  } catch (InvalidRangeException e) {
    throw new IllegalStateException(e);
  }

  // make sure it matches the dimension
  DataType dtype = DataType.getType(timesArray);
  int nTimesAtt = (int) timesArray.getSize();

  // create a special dimension and coordinate variable
  Dimension dimTime = ncVar.orgVar.getDimension(0);
  int nTimesDim = dimTime.getLength();
  if (nTimesDim != nTimesAtt) {
    parseInfo.format(" **error ntimes in attribute (%d) doesnt match dimension length (%d) for variable %s%n",
        nTimesAtt, nTimesDim, ncVar.getFullName());
    return;
  }

  // add the dimension
  String dimName = ncVar.shortName + "_timeCoord";
  Dimension newDim = new Dimension(dimName, nTimesDim);
  rootGroup.addDimension(newDim);

  // add the coordinate variable
  String units = "seconds since 1970-1-1 00:00:00";
  String desc = "time coordinate for " + ncVar.shortName;

  CoordinateAxis1D.Builder timeCoord = CoordinateAxis1D.builder().setName(dimName).setDataType(dtype)
      .setParentGroupBuilder(rootGroup).setDimensionsByName(dimName).setUnits(units).setDesc(desc);
  timeCoord.setCachedData(timesArray, true);
  timeCoord.addAttribute(new Attribute(_Coordinate.AxisType, AxisType.Time.toString()));
  datasetBuilder.replaceCoordinateAxis(rootGroup, timeCoord);

  parseInfo.format(" added coordinate variable %s%n", dimName);

  // now make the original variable use the new dimension
  ArrayList<Dimension> newDims = new ArrayList<>(ncVar.getDimensions());
  newDims.set(0, newDim);
  ncVar.setDimensions(newDims);

  // better to explicitly set the coordinate system
  ncVar.addAttribute(new Attribute(_Coordinate.Axes, dimName + " yCoord xCoord"));

  // fix the attributes
  Attribute att = ncVar.getAttributeContainer().findAttribute("fillValue");
  if (att != null)
    ncVar.addAttribute(new Attribute(CDM.FILL_VALUE, att.getNumericValue()));
  att = ncVar.getAttributeContainer().findAttribute("descriptiveName");
  if (null != att)
    ncVar.addAttribute(new Attribute(CDM.LONG_NAME, att.getStringValue()));
}
 
Example 19
Source File: IFPSConvention.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void createTimeCoordinate(NetcdfDataset ds, Variable ncVar) {
  // Time coordinate is stored in the attribute validTimes
  // One caveat is that the times have two bounds an upper and a lower

  // get the times values
  Attribute timesAtt = ncVar.findAttribute("validTimes");
  if (timesAtt == null)
    return;
  Array timesArray = timesAtt.getValues();

  // get every other one LOOK this is awkward
  try {
    int n = (int) timesArray.getSize();
    List<Range> list = new ArrayList<>();
    list.add(new Range(0, n - 1, 2));
    timesArray = timesArray.section(list);
  } catch (InvalidRangeException e) {
    throw new IllegalStateException(e);
  }

  // make sure it matches the dimension
  DataType dtype = DataType.getType(timesArray);
  int nTimesAtt = (int) timesArray.getSize();

  // create a special dimension and coordinate variable
  Dimension dimTime = ncVar.getDimension(0);
  int nTimesDim = dimTime.getLength();
  if (nTimesDim != nTimesAtt) {
    parseInfo.format(" **error ntimes in attribute (%d) doesnt match dimension length (%d) for variable %s%n",
        nTimesAtt, nTimesDim, ncVar.getFullName());
    return;
  }

  // add the dimension
  String dimName = ncVar.getFullName() + "_timeCoord";
  Dimension newDim = new Dimension(dimName, nTimesDim);
  ds.addDimension(null, newDim);

  // add the coordinate variable
  String units = "seconds since 1970-1-1 00:00:00";
  String desc = "time coordinate for " + ncVar.getFullName();

  CoordinateAxis1D timeCoord = new CoordinateAxis1D(ds, null, dimName, dtype, dimName, units, desc);
  timeCoord.setCachedData(timesArray, true);
  timeCoord.addAttribute(new Attribute(_Coordinate.AxisType, AxisType.Time.toString()));
  ds.addCoordinateAxis(timeCoord);

  parseInfo.format(" added coordinate variable %s%n", dimName);

  // now make the original variable use the new dimension
  List<Dimension> dimsList = new ArrayList(ncVar.getDimensions());
  dimsList.set(0, newDim);
  ncVar.setDimensions(dimsList);

  // better to explicitly set the coordinate system
  ncVar.addAttribute(new Attribute(_Coordinate.Axes, dimName + " yCoord xCoord"));

  // fix the attributes
  Attribute att = ncVar.findAttribute("fillValue");
  if (att != null)
    ncVar.addAttribute(new Attribute(CDM.FILL_VALUE, att.getNumericValue()));
  att = ncVar.findAttribute("descriptiveName");
  if (null != att)
    ncVar.addAttribute(new Attribute(CDM.LONG_NAME, att.getStringValue()));

  // ncVar.enhance();
}
 
Example 20
Source File: NcMLReader.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Parse the values element
 *
 * @param s JDOM element to parse
 * @return Array with parsed values
 * @throws IllegalArgumentException if string values not parsable to specified data type
 */
public static ucar.ma2.Array readAttributeValues(Element s) throws IllegalArgumentException {
  String valString = s.getAttributeValue("value");

  // can also be element text
  if (valString == null) {
    valString = s.getTextNormalize();
  }

  // no value specified hmm technically this is not illegal !!
  if (valString == null)
    throw new IllegalArgumentException("No value specified");

  String type = s.getAttributeValue("type");
  DataType dtype = (type == null) ? DataType.STRING : DataType.getType(type);
  if (dtype == DataType.CHAR)
    dtype = DataType.STRING;

  // backwards compatibility with deprecated isUnsigned attribute
  String unS = s.getAttributeValue("isUnsigned");
  boolean isUnsignedSet = "true".equalsIgnoreCase(unS);
  if (isUnsignedSet && dtype.isIntegral() && !dtype.isUnsigned()) {
    dtype = dtype.withSignedness(DataType.Signedness.UNSIGNED);
  }

  String sep = s.getAttributeValue("separator");
  if ((sep == null) && (dtype == DataType.STRING)) {
    List<String> list = new ArrayList<>();
    list.add(valString);
    return Array.makeArray(dtype, list);
  }

  if (sep == null)
    sep = " "; // default whitespace separated

  List<String> stringValues = new ArrayList<>();
  StringTokenizer tokn = new StringTokenizer(valString, sep);
  while (tokn.hasMoreTokens())
    stringValues.add(tokn.nextToken());

  return Array.makeArray(dtype, stringValues);
}