Java Code Examples for ucar.nc2.Variable#getDimensions()

The following examples show how to use ucar.nc2.Variable#getDimensions() . 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
/**
 * Test a List<Range> against the CDM variable's dimensions
 * to see if the range list is whole
 * wrt the dimensions
 *
 * @param rangelist the set of ucar.ma2.Range
 * @param var the cdm var
 * @result true if rangelist is whole wrt slices; false otherwise.
 */
public static boolean isWhole(List<Range> rangelist, Variable var) throws dap4.core.util.DapException {
  List<Dimension> dimset = var.getDimensions();
  if (rangelist.size() != dimset.size())
    return false;
  for (int i = 0; i < rangelist.size(); i++) {
    Range r = rangelist.get(i);
    Dimension dim = dimset.get(i);
    if (r.stride() != 1 || r.first() != 0 || r.length() != dim.getLength())
      return false;
  }
  return true;
}
 
Example 2
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 3
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 4
public VariableBean(Variable vs) {
  this.vs = vs;

  setName(vs.getShortName());
  setDescription(vs.getDescription());
  setUnits(vs.getUnitsString());
  setDataType(vs.getDataType().toString());

  // collect dimensions
  Formatter lens = new Formatter();
  Formatter names = new Formatter();
  lens.format("(");
  List<Dimension> dims = vs.getDimensions();
  for (int j = 0; j < dims.size(); j++) {
    Dimension dim = dims.get(j);
    if (j > 0) {
      lens.format(",");
      names.format(",");
    }
    String name = dim.isShared() ? dim.getShortName() : "anon";
    names.format("%s", name);
    lens.format("%d", dim.getLength());
  }
  lens.format(")");
  setDimensions(names.toString());
  setShape(lens.toString());
}
 
Example 5
public VariableBean(Variable vs) {
  this.vs = vs;
  // vs = (v instanceof VariableEnhanced) ? (VariableEnhanced) v : new VariableStandardized( v);

  setName(vs.getShortName());
  setDescription(vs.getDescription());
  setUnits(vs.getUnitsString());
  setDataType(vs.getDataType().toString());

  // Attribute csAtt = vs.findAttribute("_coordSystems");
  // if (csAtt != null)
  // setCoordSys( csAtt.getStringValue());

  // collect dimensions
  StringBuilder lens = new StringBuilder();
  StringBuilder names = new StringBuilder();
  List dims = vs.getDimensions();
  for (int j = 0; j < dims.size(); j++) {
    ucar.nc2.Dimension dim = (ucar.nc2.Dimension) dims.get(j);
    if (j > 0) {
      lens.append(",");
      names.append(",");
    }
    String name = dim.isShared() ? dim.getShortName() : "anon";
    names.append(name);
    lens.append(dim.getLength());
  }
  setDimensions(names.toString());
  setShape(lens.toString());
}
 
Example 6
/**
 * Creates and returns an IGeometryInfo object for the given variable in the given netcdfFile.
 * If no geometry info available, then returns null.
 *
 * @param variable
 * @param netcdfFile
 * @return geometryInfo or null.
 */
public static IArrayGeometryInfo createGeometryInfo(Variable variable, NetcdfFile netcdfFile) {

	Variable latitudeVariable = findLatitudeVariableForVariable(variable, netcdfFile);
	Variable longitudeVariable = findLongitudeVariableForVariable(variable, netcdfFile);
	//currently only 2D grids are supported.
	if (latitudeVariable == null || longitudeVariable == null) {//if data does not depend on space.
		return null;
	}

	//if 2D grid.
	IQuantityInfo latitudeQuantityInfo = new QuantityInfo(LATITUDE_STANDARD_NAME, latitudeVariable.getUnitsString());
	IQuantityInfo longitudeQuantityInfo = new QuantityInfo(LONGITUDE_STANDARD_NAME, longitudeVariable.getUnitsString());
	List<Dimension> latitudeVariableDimensions = latitudeVariable.getDimensions();
	int[] latitudeValueIndices = new int[latitudeVariableDimensions.size()];
	for (int n = 0; n < latitudeValueIndices.length; n++) {
		latitudeValueIndices[n] = variable.findDimensionIndex(latitudeVariableDimensions.get(n).getShortName());
	}
	List<Dimension> longitudeVariableDimensions = longitudeVariable.getDimensions();
	int[] longitudeValueIndices = new int[longitudeVariableDimensions.size()];
	for (int n = 0; n < longitudeValueIndices.length; n++) {
		longitudeValueIndices[n] = variable.findDimensionIndex(longitudeVariableDimensions.get(n).getShortName());
	}
	IArray latitudeArray = (IArray) readData(latitudeVariable);
	IArray longitudeArray = (IArray) readData(longitudeVariable);
       //the latitude and longitude coordinates are stored in the same order as in the netcdf file.
	ArrayGeometryInfo geometryInfo = new ArrayGeometryInfo(latitudeArray, latitudeValueIndices,
			latitudeQuantityInfo, longitudeArray, longitudeValueIndices, longitudeQuantityInfo,null,null,null);
	return geometryInfo;
}
 
Example 7
public static int getLatitudeDimensionIndexForVariable(Variable variable, NetcdfFile netcdfFile) {
	Variable latitudeVariable = NetcdfUtils.findLatitudeVariableForVariable(variable, netcdfFile);
	if (latitudeVariable == null) {
		return -1;
	}

	List<Dimension> latitudeVariableDimensions = latitudeVariable.getDimensions();
	return variable.findDimensionIndex(latitudeVariableDimensions.get(0).getShortName());
}
 
Example 8
static List<Dimension> filterDimensions(List<String> variables, NetcdfFile netcdfFile) {
    final List<Dimension> filteredDimensions = new ArrayList<Dimension>();

    for (String variableName : variables) {
        final Variable variable = netcdfFile.findVariable(variableName);
        for (Dimension dimension : variable.getDimensions()) {
            if (!filteredDimensions.contains(dimension)) {
                filteredDimensions.add(dimension);
            }
        }
    }

    return filteredDimensions;
}
 
Example 9
/**
 * Gets the subset string to be used in NetCDFFile.read given a variable and some indicies.
 * useful for subsetting timeseries
 * 
 * 
 * @param var variable to subset
 * @param beginInd beginning index (inclusive)
 * @param endInd end index (exclusive)
 * @param id The SimpleGeometryID to index
 * @return subset string
 */
public static String getSubsetString(Variable var, int beginInd, int endInd, int id) {
  if (var == null)
    return null;

  String subStr = "";

  List<Dimension> dimList = var.getDimensions();

  // Enforce two dimension arrays
  if (dimList.size() > 2 || dimList.size() < 1) {
    return null;
  }

  for (int i = 0; i < dimList.size(); i++) {

    Dimension dim = dimList.get(i);
    if (dim == null)
      continue;

    // If not CF Time then select only that ID
    if (!CF.TIME.equalsIgnoreCase(dim.getShortName()) && !CF.TIME.equalsIgnoreCase(dim.getFullNameEscaped())) {
      subStr += id;
    }

    // Otherwise subset based on time
    else {

      if (beginInd < 0 || endInd < 0)
        subStr += ":";
      else
        subStr += (beginInd + ":" + endInd);
    }

    if (i < dimList.size() - 1) {
      subStr += ",";
    }
  }

  return subStr;
}
 
Example 10
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 11
private void writeVars(List<Variable> vars, boolean largeFile, Formatter fout) throws IOException {
  int n = vars.size();
  if (n == 0) {
    raf.writeInt(0);
    raf.writeInt(0);
  } else {
    raf.writeInt(MAGIC_VAR);
    raf.writeInt(n);
  }

  for (Variable var : vars) {
    writeString(var.getShortName());

    // dimensions
    long vsize = var.getDataType().getSize(); // works for all netcdf-3 data types
    List<Dimension> dims = var.getDimensions();
    raf.writeInt(dims.size());
    for (Dimension dim : dims) {
      int dimIndex = findDimensionIndex(ncfile, dim);
      raf.writeInt(dimIndex);

      if (!dim.isUnlimited())
        vsize *= dim.getLength();
    }
    long unpaddedVsize = vsize;
    vsize += padding(vsize);

    // variable attributes
    long varAttsPos = raf.getFilePointer();
    writeAtts(var.attributes(), fout);

    // data type, variable size, beginning file position
    DataType dtype = var.getDataType();
    int type = getType(dtype);
    raf.writeInt(type);

    int vsizeWrite = (vsize < MAX_UNSIGNED_INT) ? (int) vsize : -1;
    raf.writeInt(vsizeWrite);
    long pos = raf.getFilePointer();
    if (largeFile)
      raf.writeLong(0); // come back to this later
    else
      raf.writeInt(0); // come back to this later

    // From nc3 file format specification
    // (https://www.unidata.ucar.edu/software/netcdf/docs/netcdf.html#NetCDF-Classic-Format):
    // Note on padding: In the special case of only a single record variable of character,
    // byte, or short type, no padding is used between data values.
    // 2/15/2011: we will continue to write the (incorrect) padded vsize into the header, but we will use the unpadded
    // size to read/write
    if (uvars.size() == 1 && uvars.get(0) == var) {
      if ((dtype == DataType.CHAR) || (dtype == DataType.BYTE) || (dtype == DataType.SHORT)) {
        vsize = unpaddedVsize;
      }
    }
    var.setSPobject(new N3headerNew.Vinfo(var.getShortName(), vsize, pos, var.isUnlimited(), varAttsPos));
  }
}
 
Example 12
public Element makeVariableElement(Variable var, boolean showValues) {
  boolean isStructure = var instanceof Structure;

  Element varElem = new Element("variable", namespace);
  varElem.setAttribute("name", var.getShortName());

  StringBuilder buff = new StringBuilder();
  List dims = var.getDimensions();
  for (int i = 0; i < dims.size(); i++) {
    Dimension dim = (Dimension) dims.get(i);
    if (i > 0)
      buff.append(" ");
    if (dim.isShared())
      buff.append(dim.getShortName());
    else if (dim.isVariableLength())
      buff.append("*");
    else
      buff.append(dim.getLength());
  }
  // if (buff.length() > 0)
  varElem.setAttribute("shape", buff.toString());

  DataType dt = var.getDataType();
  if (dt != null) {
    varElem.setAttribute("type", dt.toString());
    if (dt.isEnum())
      varElem.setAttribute("typedef", var.getEnumTypedef().getShortName());
  }


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

  if (isStructure) {
    Structure s = (Structure) var;
    for (Variable variable : s.getVariables()) {
      varElem.addContent(makeVariableElement(variable, showValues));
    }
  } else if (showValues) {
    try {
      varElem.addContent(makeValuesElement(var, true));
    } catch (IOException e) {
      String message = String.format("Couldn't read values for %s. Omitting <values> element.%n\t%s",
          var.getFullName(), e.getMessage());
      log.warn(message);
    }
  }

  return varElem;
}
 
Example 13
private void readNetCdfVariables() {

		for (Variable variable : this.netcdfFile.getVariables()) {

			if (Arrays.asList(keyVariables).contains(variable.getShortName())) {

				Variable timeVariable = NetcdfUtils.findTimeVariableForVariable(variable, this.netcdfFile);
				if (timeVariable == null) {
					throw new RuntimeException("NetcdfD3dMapDataObject: no time axis for " + variable.getShortName() + ", file: " + netcdfFile.getLocation());
				}
				this.timeDimensionIndex = variable.findDimensionIndex(timeVariable.getShortName());
				timeDependentVars.put(variable.getShortName(), variable);

				// if this is the first time dependent variable: read the times
				if (timesInNetcdfFile == null) {
					ucar.ma2.Array timesArray;
					try {
						timesArray = timeVariable.read();
					} catch (IOException e) {
						throw new RuntimeException("NetcdfD3dMapDataObject could not read time variable " + timeVariable.getShortName() +
								"from netcdf file " + netcdfFile.getLocation());
					}
					timesInNetcdfFile = (double[]) timesArray.get1DJavaArray(double.class);
				}

				// get the number of spatial dimensions
				// one of the dimensions was for time
				List<Dimension> dimensions = variable.getDimensions();
				int nonTimeDimensions = dimensions.size() - 1;
				if (nonTimeDimensions != 4 && variable.getShortName().equalsIgnoreCase("R1")) {
					throw new RuntimeException("NetcdfD3dMapDataObject: #dims for R1 should be four, file: " + netcdfFile.getLocation());
				}

				int layerCount = 0;
				for (int i = 0; i < dimensions.size(); i++) {
					Dimension dimension = dimensions.get(i);
					if (variable.getShortName().equalsIgnoreCase("R1")){
						if (dimension.getShortName().equalsIgnoreCase("LSTSCI")) {
							lstsciDimensionIndex = i;
							if (dimension.getLength() != 1) {
								throw new RuntimeException("NetcdfD3dMapDataObject: #R1 != 1 is not supported (temp. or salinity), file: "
									+ netcdfFile.getLocation());
							}
						}
					}
					if (!variable.getShortName().equalsIgnoreCase("S1")) {
						if (dimension.getShortName().equalsIgnoreCase("KMAXOUT_RESTR")) {
							if (variable.getShortName().equalsIgnoreCase("R1")) {
								kmaxOutRestrDimensionIndex = i;
							} else if (variable.getShortName().equalsIgnoreCase("U1") || variable.getShortName().equalsIgnoreCase("V1")) {
								kmaxOutRestrDimensionIndexVelocity = i;
							}
							if (dimension.getLength() < 0) {
								throw new RuntimeException("NetcdfD3dMapDataObject: could not read number of layers, file: "
									+ netcdfFile.getLocation());
							}
							layerCount = dimension.getLength();
						}
					}

				}

				if (lstsciDimensionIndex == 0 || kmaxOutRestrDimensionIndex == 0 || kmaxOutRestrDimensionIndexVelocity == 0) {
					throw new RuntimeException("NetcdfD3dMapDataObject: dims not available, file: "
						+ netcdfFile.getLocation());
				}

				ITimeInfo timeInfo = NetcdfUtils.createTimeInfo(variable, this.netcdfFile, timeInfoCache);
				// for memory reasons, for the time being we only keep the last time step in the exchange time
				// so adjust the time info
				double[] times = timeInfo.getTimes();
				timeInfo = new TimeInfo(new double[]{times[times.length-1]});

				// Extracting geometry information only once
				if (this.xCoords == null | this.yCoords == null | this.zCoords == null) {
					Variable variableX = this.netcdfFile.findVariable("XZ");
					Variable variableY = this.netcdfFile.findVariable("YZ");
					Variable variableZ = this.netcdfFile.findVariable("ZK_LYR");

					int[] originXY = createOrigin(variableX);
					int[] sizeArrayXY = variableX.getShape();
					int[] originZ = createOrigin(variableZ);
					int[] sizeArrayZ = variableZ.getShape();

					this.xCoords = NetcdfUtils.readSelectedData(variableX, originXY, sizeArrayXY, -1);
					this.yCoords = NetcdfUtils.readSelectedData(variableY, originXY, sizeArrayXY, -1);
					this.zCoords = NetcdfUtils.readSelectedData(variableZ, originZ, sizeArrayZ, -1);
				}

				IGeometryInfo geometryInfo;
				if (variable.getShortName().equalsIgnoreCase("S1")) {
					geometryInfo = new NetcdfD3dMapExchangeItemGeometryInfo(this.xCoords, this.yCoords, null);
				} else {
					geometryInfo = new NetcdfD3dMapExchangeItemGeometryInfo(this.xCoords, this.yCoords, this.zCoords);
				}
				IExchangeItem exchangeItem = new NetcdfD3dMapExchangeItem(variable.getShortName(), this, timeInfo, geometryInfo);
				this.exchangeItems.put(exchangeItem.getId(), exchangeItem);

			}
		}
	}
 
Example 14
/**
 * Searches all the variables that the given variable depends on,
 * and returns the first variable that is a valid time variable.
 * If cannot find a valid time variable, then returns null.
 *
 * @param variable
 * @param netcdfFile
 * @return timeVariable or null.
 */
public static Variable findTimeVariableForVariable(Variable variable, NetcdfFile netcdfFile) {
	List<Dimension> dimensions = variable.getDimensions();
	for (Dimension dimension : dimensions) {
		Variable dimensionVariable = netcdfFile.findVariable(dimension.getShortName());
		if (dimensionVariable == null || !dimensionVariable.isCoordinateVariable()) {
			continue;
		}

		if(isTimeVariable(dimensionVariable)) {
			return dimensionVariable;
		}
	}

	//search auxiliary coordinate variables.
	//according to the CF-convention (see http://cf-pcmdi.llnl.gov/documents/cf-conventions/1.5/cf-conventions.html#coordinate-system):
	//"An application that is trying to find the latitude coordinate of a variable should always look first to see
	//if any of the variable's dimensions correspond to a latitude coordinate variable. If the latitude coordinate
	//is not found this way, then the auxiliary coordinate variables listed by the coordinates attribute should
	//be checked. Note that it is permissible, but optional, to list coordinate variables as well as auxiliary
	//coordinate variables in the coordinates attribute. The axis attribute is not allowed for auxiliary coordinate
	//variables. Auxiliary coordinate variables which lie on the horizontal surface can be identified as such by their
	//dimensions being horizontal. Horizontal dimensions are those whose coordinate variables have an axis attribute
	//of X or Y, or a units attribute indicating latitude and longitude (see Chapter 4, Coordinate Types ).
	String coordinates = getAttributeStringValue(variable, COORDINATES_ATTRIBUTE_NAME);
	if (coordinates != null) {
		String[] strings = coordinates.split("\\s+");
		for (String auxiliaryCoordinateVariableName : strings) {
			Variable auxiliaryCoordinateVariable = netcdfFile.findVariable(auxiliaryCoordinateVariableName);
			if (auxiliaryCoordinateVariable == null) {
				continue;
			}

			if (isTimeVariable(auxiliaryCoordinateVariable)) {
				return auxiliaryCoordinateVariable;
			}
		}
	}

	return null;
}
 
Example 15
/**
 * Searches all the variables that the given variable depends on,
 * and returns the first variable that is a valid latitude variable.
 * If cannot find a valid latitude variable, then returns null.
 *
 * @param variable
 * @param netcdfFile
 * @return latitudeVariable or null.
 */
private static Variable findLatitudeVariableForVariable(Variable variable, NetcdfFile netcdfFile) {
	//search coordinate variables.
	List<Dimension> dimensions = variable.getDimensions();
	for (Dimension dimension : dimensions) {
		Variable dimensionVariable = netcdfFile.findVariable(dimension.getShortName());
		if (dimensionVariable == null || !dimensionVariable.isCoordinateVariable()) {
			continue;
		}

		if (isLatitudeVariable(dimensionVariable)) {
			return dimensionVariable;
		}
	}

	//search auxiliary coordinate variables.
	//according to the CF-convention (see http://cf-pcmdi.llnl.gov/documents/cf-conventions/1.5/cf-conventions.html#coordinate-system):
	//"An application that is trying to find the latitude coordinate of a variable should always look first to see
	//if any of the variable's dimensions correspond to a latitude coordinate variable. If the latitude coordinate
	//is not found this way, then the auxiliary coordinate variables listed by the coordinates attribute should
	//be checked. Note that it is permissible, but optional, to list coordinate variables as well as auxiliary
	//coordinate variables in the coordinates attribute. The axis attribute is not allowed for auxiliary coordinate
	//variables. Auxiliary coordinate variables which lie on the horizontal surface can be identified as such by their
	//dimensions being horizontal. Horizontal dimensions are those whose coordinate variables have an axis attribute
	//of X or Y, or a units attribute indicating latitude and longitude (see Chapter 4, Coordinate Types ).
	String coordinates = getAttributeStringValue(variable, COORDINATES_ATTRIBUTE_NAME);
	if (coordinates != null) {
		String[] strings = coordinates.split("\\s+");
		for (String auxiliaryCoordinateVariableName : strings) {
			Variable auxiliaryCoordinateVariable = netcdfFile.findVariable(auxiliaryCoordinateVariableName);
			if (auxiliaryCoordinateVariable == null) {
				continue;
			}

			if (isLatitudeVariable(auxiliaryCoordinateVariable)) {
				return auxiliaryCoordinateVariable;
			}
		}
	}

	return null;
}
 
Example 16
/**
 * Searches all the variables that the given variable depends on,
 * and returns the first variable that is a valid longitude variable.
 * If cannot find a valid longitude variable, then returns null.
 *
 * @param variable
 * @param netcdfFile
 * @return longitudeVariable or null.
 */
private static Variable findLongitudeVariableForVariable(Variable variable, NetcdfFile netcdfFile) {
	//search coordinate variables.
	List<Dimension> dimensions = variable.getDimensions();
	for (Dimension dimension : dimensions) {
		Variable dimensionVariable = netcdfFile.findVariable(dimension.getShortName());
		if (dimensionVariable == null || !dimensionVariable.isCoordinateVariable()) {
			continue;
		}

		if (isLongitudeVariable(dimensionVariable)) {
			return dimensionVariable;
		}
	}

	//search auxiliary coordinate variables.
	//according to the CF-convention (see http://cf-pcmdi.llnl.gov/documents/cf-conventions/1.5/cf-conventions.html#coordinate-system):
	//"An application that is trying to find the latitude coordinate of a variable should always look first to see
	//if any of the variable's dimensions correspond to a latitude coordinate variable. If the latitude coordinate
	//is not found this way, then the auxiliary coordinate variables listed by the coordinates attribute should
	//be checked. Note that it is permissible, but optional, to list coordinate variables as well as auxiliary
	//coordinate variables in the coordinates attribute. The axis attribute is not allowed for auxiliary coordinate
	//variables. Auxiliary coordinate variables which lie on the horizontal surface can be identified as such by their
	//dimensions being horizontal. Horizontal dimensions are those whose coordinate variables have an axis attribute
	//of X or Y, or a units attribute indicating latitude and longitude (see Chapter 4, Coordinate Types ).
	String coordinates = getAttributeStringValue(variable, COORDINATES_ATTRIBUTE_NAME);
	if (coordinates != null) {
		String[] strings = coordinates.split("\\s+");
		for (String auxiliaryCoordinateVariableName : strings) {
			Variable auxiliaryCoordinateVariable = netcdfFile.findVariable(auxiliaryCoordinateVariableName);
			if (auxiliaryCoordinateVariable == null) {
				continue;
			}

			if (isLongitudeVariable(auxiliaryCoordinateVariable)) {
				return auxiliaryCoordinateVariable;
			}
		}
	}

	return null;
}