ucar.nc2.NetcdfFileWriter Java Examples

The following examples show how to use ucar.nc2.NetcdfFileWriter. 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: NetcdfUtils.java    From OpenDA with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static Dimension createTimeVariable(NetcdfFileWriter netcdfFileWriter, ITimeInfo timeInfo, int[] uniqueTimeVariableCount, Map<ITimeInfo, Dimension> timeInfoTimeDimensionMap) {
	Dimension timeDimension = timeInfoTimeDimensionMap.get(timeInfo);

	if (timeDimension == null) {//if timeVariable with correct times not yet present.
		//create time dimension and variable.
		//for each unique timeDimension use a unique numbered variable name, like e.g.
		//time, time2, time3, etc.
		uniqueTimeVariableCount[0]++;
		String postfix = uniqueTimeVariableCount[0] <= 1 ? "" : String.valueOf(uniqueTimeVariableCount[0]);
		String timeVariableName = TIME_VARIABLE_NAME + postfix;
		int timeCount = timeInfo.getTimes().length;
		timeDimension = createTimeVariable(netcdfFileWriter, timeVariableName, timeCount, NetcdfUtils.createTimeUnitString());

		//put timeDimension in map so that it can be re-used later by other variables in the same file.
		timeInfoTimeDimensionMap.put(timeInfo, timeDimension);
	}

	return timeDimension;
}
 
Example #2
Source File: NetcdfUtils.java    From OpenDA with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Write values for all grid variables that are present.
 *
 * @param netcdfFileWriter
 * @param geometryGridVariablePropertiesMap
 * @throws Exception
 */
public static void writeGridVariablesValues(NetcdfFileWriter netcdfFileWriter,
		Map<IGeometryInfo, GridVariableProperties> geometryGridVariablePropertiesMap) throws Exception {

	//this currently only writes YX1DVariables and only for ArrayGeometryInfo.
	for (Map.Entry<IGeometryInfo, GridVariableProperties> entry : geometryGridVariablePropertiesMap.entrySet()) {
		IGeometryInfo geometryInfo = entry.getKey();
		GridVariableProperties gridVariableProperties = entry.getValue();

		//write y and x variable values (if present).
		String y1DVariableName = gridVariableProperties.getY1DVariableName();
		String x1DVariableName = gridVariableProperties.getX1DVariableName();
		if (y1DVariableName != null && x1DVariableName != null && geometryInfo instanceof ArrayGeometryInfo) {
			writeYX1DVariableValues(netcdfFileWriter, (ArrayGeometryInfo) geometryInfo, y1DVariableName, x1DVariableName);
		}

		//write z variable values (if present).
		String zVariableName = gridVariableProperties.getZVariableName();
		if (zVariableName != null && geometryInfo instanceof LayeredIrregularGridGeometryInfo) {
			writeZVariableValues(netcdfFileWriter, (LayeredIrregularGridGeometryInfo) geometryInfo, zVariableName);
		}
	}
}
 
Example #3
Source File: NetcdfUtils.java    From OpenDA with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Writes all metadata variables for the given maps to the given netcdfFile, i.e. times and spatial coordinates.
 */
public static void writeMetadata(NetcdfFileWriter netcdfFileWriter, Map<ITimeInfo, Dimension> timeInfoTimeDimensionMap,
								 Map<IGeometryInfo, GridVariableProperties> geometryInfoGridVariablePropertiesMap,
								 String stationNameVarName,
								 List<String> stationIdList, List<Integer> ensembleMemberIndexList) throws Exception {

	//write time variable values.
	NetcdfUtils.writeTimeVariablesValues(netcdfFileWriter, timeInfoTimeDimensionMap);

	//write geometry variable values.
	NetcdfUtils.writeGridVariablesValues(netcdfFileWriter, geometryInfoGridVariablePropertiesMap);

	//write station_id if available.
	NetcdfUtils.writeStationIdVariableValues(netcdfFileWriter, stationNameVarName, stationIdList);

	//write realization variable values.
	NetcdfUtils.writeRealizationVariableValues(netcdfFileWriter, ensembleMemberIndexList);
}
 
Example #4
Source File: NetcdfUtils.java    From OpenDA with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Write values for all time variables that are present.
 *
 * @param netcdfFileWriter
 * @param timeInfoTimeDimensionMap
 * @throws Exception
 */
public static void writeTimeVariablesValues(NetcdfFileWriter netcdfFileWriter,
		Map<ITimeInfo, Dimension> timeInfoTimeDimensionMap) throws Exception {

	for (Map.Entry<ITimeInfo, Dimension> entry : timeInfoTimeDimensionMap.entrySet()) {
		ITimeInfo timeInfo = entry.getKey();
		Dimension timeDimension = entry.getValue();

		Variable timeVariable = netcdfFileWriter.findVariable(timeDimension.getShortName());
		String timeUnitString = timeVariable.findAttribute(UNITS_ATTRIBUTE_NAME).getStringValue();
		DateUnit dateUnit = new DateUnit(timeUnitString);

		double[] times = timeInfo.getTimes();
		ArrayDouble.D1 timesArray = new ArrayDouble.D1(times.length);
		for (int n = 0; n < times.length; n++) {
			double newTime = dateUnit.makeValue(new Date(Time.mjdToMillies(times[n])));
			timesArray.set(n, newTime);
		}

		netcdfFileWriter.write(timeVariable, timesArray);
	}
}
 
Example #5
Source File: TestGridClose.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void alterExistingFile(String url) throws IOException {
  NetcdfFileWriter file = null;
  try {
    file = NetcdfFileWriter.openExisting(url);
    file.setRedefineMode(true);
    // Group rootGroup = file.getRootGroup();
    // Group headerDataGroup = new Group(file, rootGroup, "header_data");
    // file.addGroup(rootGroup, headerDataGroup);
    file.addVariable(null, newVarName, DataType.FLOAT, "z y x");
  } finally {
    if (file != null) {
      file.setRedefineMode(false);
      file.flush();
      file.close();
    }
  }
}
 
Example #6
Source File: NetcdfUtils.java    From OpenDA with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static void createDataVariables(NetcdfFileWriter netcdfFileWriter, Collection<IExchangeItem> exchangeItems, Dimension realizationDimension, Dimension stationDimension,
		Map<ITimeInfo, Dimension> timeInfoTimeDimensionMap, Map<IGeometryInfo, GridVariableProperties> geometryInfoGridVariablePropertiesMap, int[] uniqueTimeVariableCount) {

	for (IExchangeItem item : exchangeItems) {
		String variableName = getVariableName(item);
		if (netcdfFileWriter.findVariable(variableName) != null) {//if variable already exists.
			//if the variable already exists, we do not need to add it again. This can happen for scalar time series.
			continue;
		}

		//if variable does not exist yet.
		//create time coordinate variable, if not present yet.
		//assume that all exchangeItems for a given parameter have identical time records. TODO validate this. AK
		Dimension timeDimension = null;
		ITimeInfo timeInfo = item.getTimeInfo();
		if (timeInfo != null && timeInfo.getTimes() != null) {//if variable depends on time.
			timeDimension = createTimeVariable(netcdfFileWriter, timeInfo, uniqueTimeVariableCount, timeInfoTimeDimensionMap);
		}
		NetcdfUtils.createDataVariable(netcdfFileWriter, item, timeDimension, realizationDimension, stationDimension, geometryInfoGridVariablePropertiesMap);
	}
}
 
Example #7
Source File: NetcdfOutputChooser.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void setOutputFilename(String filename) {
  if (filename == null)
    filename = "test";
  String location = filename;
  if (location.startsWith("file:"))
    location = location.substring(5);
  int pos = location.lastIndexOf(".");
  if (pos > 0)
    location = location.substring(0, pos);

  // change suffix
  NetcdfFileWriter.Version version = (NetcdfFileWriter.Version) netcdfVersion.getSelectedItem();
  String suffix = (version == null) ? ".nc" : version.getSuffix();
  if (filename.endsWith(".nc") && suffix.equals(".nc"))
    suffix = ".sub.nc";
  location += suffix;

  outputFilename.setText(location);
}
 
Example #8
Source File: StationSubsetWriterNetcdf.java    From tds with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public StationSubsetWriterNetcdf(FeatureDatasetPoint fdPoint, SubsetParams ncssParams, NcssDiskCache ncssDiskCache,
    OutputStream out, NetcdfFileWriter.Version version) throws NcssException, IOException {
  super(fdPoint, ncssParams);

  this.ncssDiskCache = ncssDiskCache;
  this.out = out;
  this.version = version;

  this.netcdfResult = ncssDiskCache.getDiskCache().createUniqueFile("ncss-station", ".nc");
  List<Attribute> attribs = new ArrayList<>();
  attribs.add(new Attribute(CDM.TITLE, "Extracted data from TDS Feature Collection " + fdPoint.getLocation()));

  // get the timeUnit and altUnit from the first FeatureCollection
  assert fdPoint.getPointFeatureCollectionList().size() > 0;
  DsgFeatureCollection fc = fdPoint.getPointFeatureCollectionList().get(0);
  CalendarDateUnit timeUnit = fc.getTimeUnit();
  String altUnit = fc.getAltUnits();

  this.cfWriter = new WriterCFStationCollection(netcdfResult.getAbsolutePath(), attribs, wantedVariables, timeUnit,
      altUnit, new CFPointWriterConfig(version));
}
 
Example #9
Source File: StationSubsetWriterNetcdf.java    From tds with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public HttpHeaders getHttpHeaders(String datasetPath, boolean isStream) {
  HttpHeaders httpHeaders = new HttpHeaders();

  String fileName = TdsPathUtils.getFileNameForResponse(datasetPath, version);
  String url = ncssDiskCache.getServletCachePath() + fileName;

  if (version == NetcdfFileWriter.Version.netcdf3) {
    httpHeaders.set(ContentType.HEADER, ContentType.netcdf.getContentHeader());
  } else if (version == NetcdfFileWriter.Version.netcdf4 || version == NetcdfFileWriter.Version.netcdf4_classic) {
    httpHeaders.set(ContentType.HEADER, ContentType.netcdf.getContentHeader());
  }

  httpHeaders.set("Content-Location", url);
  httpHeaders.set("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

  return httpHeaders;
}
 
Example #10
Source File: PointSubsetWriterNetcdf.java    From tds with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public HttpHeaders getHttpHeaders(String datasetPath, boolean isStream) {
  HttpHeaders httpHeaders = new HttpHeaders();

  String fileName = TdsPathUtils.getFileNameForResponse(datasetPath, version);
  String url = ncssDiskCache.getServletCachePath() + fileName;

  if (version == NetcdfFileWriter.Version.netcdf3) {
    httpHeaders.set(ContentType.HEADER, ContentType.netcdf.getContentHeader());
  } else if (version == NetcdfFileWriter.Version.netcdf4 || version == NetcdfFileWriter.Version.netcdf4_classic) {
    httpHeaders.set(ContentType.HEADER, ContentType.netcdf.getContentHeader());
  }

  httpHeaders.set("Content-Location", url);
  httpHeaders.set("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

  return httpHeaders;
}
 
Example #11
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 #12
Source File: NetcdfUtils.java    From OpenDA with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static void writeDataForVariableForSingleTimeSingleLocationSingleRealization(NetcdfFileWriter netcdfFileWriter, Variable variable,
		int timeIndex, int realizationDimensionIndex, int realizationIndex, int stationDimensionIndex, int stationIndex, double[] values) {
	int[] origin = createOrigin(variable);
	int[] sizeArray = variable.getShape();

	//here assume that timeDimensionIndex is 0.
	int timeDimensionIndex = 0;
	//select only the given time, station and realization.
	origin[timeDimensionIndex] = timeIndex;
	sizeArray[timeDimensionIndex] = 1;
	origin[realizationDimensionIndex] = realizationIndex;
	sizeArray[realizationDimensionIndex] = 1;
	origin[stationDimensionIndex] = stationIndex;
	sizeArray[stationDimensionIndex] = 1;

	writeSelectedData(netcdfFileWriter, variable, origin, sizeArray, values);
}
 
Example #13
Source File: NetcdfUtils.java    From OpenDA with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Creates metadata and data variables for the given exchangeItems and/or ensembleExchangeItems in the given netcdfFile, if not present yet.
 * Each exchangeItem stores a scalar timeseries for a single location (and a single ensemble member).
 * All exchangeItems must use the same ensemble member indices.
 */
public static void createMetadataAndDataVariablesForScalars(NetcdfFileWriter netcdfFileWriter,
															List<IExchangeItem> exchangeItems, Map<String, Map<Integer, IExchangeItem>> ensembleExchangeItems, Map<ITimeInfo, Dimension> timeInfoTimeDimensionMap, String stationNameVarName,
															String stationDimensionVarName,
															int stationCount, int ensembleMemberCount) {

	//create stations variable.
	Dimension stationDimension = createStationsVariable(netcdfFileWriter, stationNameVarName, stationDimensionVarName, stationCount);

	//create realization variable.
	Dimension realizationDimension = null;
	if (ensembleMemberCount > 0) {
		realizationDimension = createRealizationVariable(netcdfFileWriter, ensembleMemberCount);
	}

	//create data variables.
	NetcdfUtils.createDataVariables(netcdfFileWriter, exchangeItems, ensembleExchangeItems, realizationDimension, stationDimension, timeInfoTimeDimensionMap, null);
}
 
Example #14
Source File: NetcdfUtils.java    From OpenDA with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Creates metadata for the given exchangeItem in the given netcdfFile, if not present yet.
 */
public static void createMetadataAndDataVariablesForGrids(NetcdfFileWriter netcdfFileWriter, List<IExchangeItem> exchangeItems, Map<ITimeInfo, Dimension> timeInfoTimeDimensionMap,
		Map<IGeometryInfo, GridVariableProperties> geometryInfoGridVariablePropertiesMap) {

	int[] uniqueTimeVariableCount = new int[]{0};
	int[] uniqueGeometryCount = new int[]{0};
	for (IExchangeItem exchangeItem : exchangeItems) {
		//create time coordinate variable, if not present yet.
		Dimension timeDimension = null;
		ITimeInfo timeInfo = exchangeItem.getTimeInfo();
		if (timeInfo != null && timeInfo.getTimes() != null) {//if variable depends on time.
			timeDimension = createTimeVariable(netcdfFileWriter, timeInfo, uniqueTimeVariableCount, timeInfoTimeDimensionMap);
		}

		//create spatial coordinate variables, if not present yet.
		//this only adds spatial dimensions, this does not add spatial variables with coordinates,
		//because the coordinates are usually not available in exchangeItems that come from models.
		if (!GeometryUtils.isScalar(exchangeItem.getGeometryInfo())) {//if grid.
			createGridVariables(netcdfFileWriter, exchangeItem.getGeometryInfo(), uniqueGeometryCount, geometryInfoGridVariablePropertiesMap);
		}

		//create data variable.
		createDataVariable(netcdfFileWriter, exchangeItem, timeDimension, null, null, geometryInfoGridVariablePropertiesMap);
	}
}
 
Example #15
Source File: TestGrib2Netcdf.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public int doAct(String filename) throws IOException {

      TestGrib2Netcdf writer = new TestGrib2Netcdf();
      for (int level = 1; level < 8; level++) {
        total += writer.writeNetcdf(filename, NetcdfFileWriter.Version.netcdf4, Nc4Chunking.Strategy.grib, level, true);
        total +=
            writer.writeNetcdf(filename, NetcdfFileWriter.Version.netcdf4, Nc4Chunking.Strategy.grib, level, false);
        fw.flush();
      }

      fw.flush();

      return 1;
    }
 
Example #16
Source File: NetcdfUtils.java    From OpenDA with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * For each unique geometryInfo in the given geometryInfos creates unique grid variables in the given netcdfFile
 * and stores the properties of the created grid variables in the returned geometryGridVariablePropertiesMap.
 * These properties are used later in the method NetcdfUtils.createDataVariables.
 *
 * @param netcdfFileWriter
 * @param geometryInfos
 * @return geometryGridVariablePropertiesMap
 */
public static Map<IGeometryInfo, GridVariableProperties> createGridVariables(NetcdfFileWriter netcdfFileWriter, IGeometryInfo[] geometryInfos) {
	Map<IGeometryInfo, GridVariableProperties> geometryGridVariablePropertiesMap = new LinkedHashMap<>();

	int[] uniqueGeometryCount = new int[]{0};
	for (IGeometryInfo geometryInfo : geometryInfos) {
		if (geometryInfo == null || geometryInfo instanceof PointGeometryInfo) {//if scalar.
			continue;
		}

		createGridVariables(netcdfFileWriter, geometryInfo, uniqueGeometryCount, geometryGridVariablePropertiesMap);
	}

	return geometryGridVariablePropertiesMap;
}
 
Example #17
Source File: TestCFPointWriterMisc.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
@Category(NeedsCdmUnitTest.class)
public void testPointProblem() throws IOException {
  String filename = TestDir.cdmUnitTestDir + "ft/point/netcdf/Surface_Buoy_20090921_0000.nc";
  TestCFPointWriter.writeDataset(filename, FeatureType.POINT,
      new CFPointWriterConfig(NetcdfFileWriter.Version.netcdf3), false, tempFolder.newFile());
}
 
Example #18
Source File: NetcdfUtils.java    From OpenDA with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void writeZVariableValues(NetcdfFileWriter netcdfFileWriter, LayeredIrregularGridGeometryInfo geometryInfo, String zVariableName) throws Exception {
	IVector zCoordinates = geometryInfo.getZCoordinates();
	ArrayDouble.D1 zArray = new ArrayDouble.D1(zCoordinates.getSize());
	for (int n = 0; n < zArray.getSize(); n++) {
		zArray.set(n, zCoordinates.getValue(n));
	}
	Variable myZVar = netcdfFileWriter.findVariable(zVariableName);
	netcdfFileWriter.write(myZVar, zArray);
}
 
Example #19
Source File: RewriteGrid.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
double rewrite(String filenameIn, String filenameOut, NetcdfFileWriter.Version version,
    Nc4Chunking.Strategy chunkerType, int deflateLevel, boolean shuffle, Formatter fw) throws IOException {

  ucar.nc2.dt.GridDataset gds = ucar.nc2.dt.grid.GridDataset.open(filenameIn);
  Nc4Chunking chunking = (version == NetcdfFileWriter.Version.netcdf3) ? null
      : Nc4ChunkingStrategy.factory(chunkerType, deflateLevel, shuffle);
  NetcdfFileWriter writer = NetcdfFileWriter.createNew(version, filenameOut, chunking);

  long start = System.currentTimeMillis();

  long totalBytes;
  try {
    totalBytes = CFGridWriter2.writeFile(gds, null, null, null, 1, null, null, 1, true, writer);
  } catch (Throwable e) {
    e.printStackTrace();
    return 0;
  }

  File fin = new File(filenameIn);
  double lenIn = (double) fin.length();
  lenIn /= 1000 * 1000;

  File fout = new File(filenameOut);
  double lenOut = (double) fout.length();
  lenOut /= 1000 * 1000;

  System.out.format("   %10.3f: %s%n", lenOut / lenIn, fout.getCanonicalPath());
  double took = (System.currentTimeMillis() - start) / 1000.0;
  System.out.format("   that took: %f secs%n", took);

  if (fw != null)
    fw.format("%s,%10.3f, %s,%s, %d, %10.3f,%10.3f,%d%n", fin.getName(), lenIn,
        (chunkerType != null) ? chunkerType : "nc3", shuffle ? "shuffle" : "", deflateLevel, lenOut, lenOut / lenIn,
        totalBytes);

  return lenOut;
}
 
Example #20
Source File: NetcdfUtils.java    From OpenDA with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void addGlobalAttributes(NetcdfFileWriter netcdfFileWriter) {
	netcdfFileWriter.addGroupAttribute(null,new Attribute("title", "Netcdf data"));
	netcdfFileWriter.addGroupAttribute(null,new Attribute("institution", "Deltares"));
	netcdfFileWriter.addGroupAttribute(null,new Attribute("source", "written by OpenDA"));
	netcdfFileWriter.addGroupAttribute(null,new Attribute("history", "Created at " + new Date(System.currentTimeMillis()) ));
	netcdfFileWriter.addGroupAttribute(null,new Attribute("references", "http://www.openda.org"));
	netcdfFileWriter.addGroupAttribute(null,new Attribute("Conventions", "CF-1.6"));
}
 
Example #21
Source File: CFGridWriter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public long makeFile(String location, ucar.nc2.dt.GridDataset gds, List<String> gridList, ProjectionRect llbb,
    int horizStride, Range zRange, CalendarDateRange dateRange, int stride_time, boolean addLatLon,
    NetcdfFileWriter.Version version) throws IOException, InvalidRangeException {

  return makeOrTestSize(location, gds, gridList, llbb, horizStride, zRange, dateRange, stride_time, addLatLon, false,
      version);
}
 
Example #22
Source File: CFGridWriter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public long makeFile(String location, ucar.nc2.dt.GridDataset gds, List<String> gridList, ProjectionRect projRect,
    int horizStride, Range zRange, CalendarDateRange dateRange, int stride_time, boolean addLatLon)
    throws IOException, InvalidRangeException {

  return makeOrTestSize(location, gds, gridList, projRect, horizStride, zRange, dateRange, stride_time, addLatLon,
      false, NetcdfFileWriter.Version.netcdf3);
}
 
Example #23
Source File: CFGridWriter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public long makeFile(String location, ucar.nc2.dt.GridDataset gds, List<String> gridList, LatLonRect llbb,
    int horizStride, Range zRange, CalendarDateRange dateRange, int stride_time, boolean addLatLon,
    NetcdfFileWriter.Version version) throws IOException, InvalidRangeException {

  return makeOrTestSize(location, gds, gridList, llbb, horizStride, zRange, dateRange, stride_time, addLatLon, false,
      version);
}
 
Example #24
Source File: NetcdfUtils.java    From OpenDA with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void writeDataForVariableForSingleTime(NetcdfFileWriter netcdfFileWriter, Variable variable, int timeDimensionIndex, int timeIndex, double[] values) {
	int[] origin = createOrigin(variable);
	int[] sizeArray = variable.getShape();

	//select only the given time.
	origin[timeDimensionIndex] = timeIndex;
	sizeArray[timeDimensionIndex] = 1;

	writeSelectedData(netcdfFileWriter, variable, origin, sizeArray, values);
}
 
Example #25
Source File: NetcdfUtils.java    From OpenDA with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void writeDataForVariableForSingleTimeSingleLocation(NetcdfFileWriter netcdfFileWriter, Variable variable, int timeIndex, int stationDimensionIndex, int stationIndex, double[] values) {
	int[] origin = createOrigin(variable);
	int[] sizeArray = variable.getShape();

	//here assume that timeDimensionIndex is 0.
	int timeDimensionIndex = 0;
	//select only the given time and station.
	origin[timeDimensionIndex] = timeIndex;
	sizeArray[timeDimensionIndex] = 1;
	origin[stationDimensionIndex] = stationIndex;
	sizeArray[stationDimensionIndex] = 1;

	writeSelectedData(netcdfFileWriter, variable, origin, sizeArray, values);
}
 
Example #26
Source File: CFGridWriter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public long makeFile(String location, ucar.nc2.dt.GridDataset gds, List<String> gridList, LatLonRect llbb,
    int horizStride, Range zRange, CalendarDateRange dateRange, int stride_time, boolean addLatLon)
    throws IOException, InvalidRangeException {

  return makeOrTestSize(location, gds, gridList, llbb, horizStride, zRange, dateRange, stride_time, addLatLon, false,
      NetcdfFileWriter.Version.netcdf3);
}
 
Example #27
Source File: NetcdfUtils.java    From OpenDA with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void writeSelectedData(NetcdfFileWriter netcdfFileWriter, Variable variable, int[] origin, int[] sizeArray, double[] values) {
	//replace NaN values with missing value for variable.
	double missingValue = getMissingValueDouble(variable);
	if (!Double.isNaN(missingValue)) {
		double[] newValues = new double[values.length];
		System.arraycopy(values, 0, newValues, 0, values.length);
		for (int n = 0; n < newValues.length; n++) {
			if (Double.isNaN(newValues[n])) {
				newValues[n] = missingValue;
			}
		}
		values = newValues;
	} else {//if missingValue is Double.NaN, then NaN values in values array are already equal to missingValue.
		//do nothing.
	}

	//prepare array for writing.
	ucar.ma2.Array array = ucar.ma2.Array.factory(DataType.DOUBLE, sizeArray, values);

	//write data.
	try {
		netcdfFileWriter.write(variable, origin, array);
	} catch (IOException | InvalidRangeException e) {
		throw new RuntimeException("Error while writing data to netcdf variable '" + variable.getShortName()
				+ "' in netcdf file " + netcdfFileWriter.getNetcdfFile().getLocation() + ". Message was: " + e.getMessage(), e);
	}
}
 
Example #28
Source File: NetcdfUtils.java    From OpenDA with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Add variable for station_id.
 */
public static Dimension createStationsVariable(NetcdfFileWriter netcdfFileWriter, String stationNameVarName, String stationDimensionVarName, int stationCount) {
	Dimension stationDimension = netcdfFileWriter.addDimension(null,stationDimensionVarName, stationCount);
	Dimension charDimension = netcdfFileWriter.addDimension(null,CHAR_LEN_ID, CHARLENGTH_ID);
	ArrayList<Dimension> dimensions = new ArrayList<Dimension>();
	dimensions.add(stationDimension);
	dimensions.add(charDimension);

	Variable myVar = netcdfFileWriter.addVariable(null, stationNameVarName, DataType.CHAR, dimensions);
	netcdfFileWriter.addVariableAttribute( myVar, new Attribute( LONG_NAME_ATTRIBUTE_NAME, "station identification code"));
	netcdfFileWriter.addVariableAttribute( myVar, new Attribute(CF_ROLE_ATTRIBUTE_NAME, NetcdfUtils.TIME_SERIES_ID_CF_ROLE));

	return stationDimension;
}
 
Example #29
Source File: NetcdfUtils.java    From OpenDA with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Creates a realization dimension and variable.
 */
public static Dimension createRealizationVariable(NetcdfFileWriter netcdfFileWriter, int ensembleMemberCount) {
	//See http://cf-pcmdi.llnl.gov/documents/cf-standard-names/standard-name-table/18/cf-standard-name-table.html
	//standard name "realization":
	//Realization is used to label a dimension that can be thought of as a statistical sample,
	//e.g., labelling members of a model ensemble.
	//See http://www.clivar.org/sites/default/files/imported/organization/wgsip/chfp/CHFP_metadata.pdf
	//and http://www.ppt2txt.com/r/zd0ebf25/
	//int realization(realization) ;
	//realization:data_type = "int" ;
	//realization:units = "1" ;
	//realization:standard_name = "realization" ;
	//realization:long_name = "Number of the simulation in the ensemble" ;
	//float physical_field(time, realization, level, latitude, longitude) ;

	//create realization dimension.
	Dimension realizationDimension = netcdfFileWriter.addDimension(null, REALIZATION_VARIABLE_NAME, ensembleMemberCount);

	//create realization variable.
	ArrayList<Dimension> realizationDimensionList = new ArrayList<>();
	realizationDimensionList.add(realizationDimension);
	Variable myVar = netcdfFileWriter.addVariable(null, REALIZATION_VARIABLE_NAME, DataType.INT, realizationDimensionList);
	netcdfFileWriter.addVariableAttribute(myVar, new Attribute(STANDARD_NAME_ATTRIBUTE_NAME, REALIZATION_VARIABLE_NAME));
	netcdfFileWriter.addVariableAttribute(myVar, new Attribute(LONG_NAME_ATTRIBUTE_NAME, "Index of an ensemble member within an ensemble"));
	netcdfFileWriter.addVariableAttribute(myVar, new Attribute(UNITS_ATTRIBUTE_NAME, "1"));

	return realizationDimension;
}
 
Example #30
Source File: NetcdfFormatWriter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static NetcdfFileWriter.Version convertToNetcdfFileWriterVersion(NetcdfFileFormat format) {
  switch (format) {
    case NETCDF3:
      return NetcdfFileWriter.Version.netcdf3;
    case NETCDF4:
      return NetcdfFileWriter.Version.netcdf4;
    case NETCDF4_CLASSIC:
      return NetcdfFileWriter.Version.netcdf4_classic;
    case NETCDF3_64BIT_OFFSET:
      return NetcdfFileWriter.Version.netcdf3c64;
    default:
      throw new IllegalStateException("Unsupported format: " + format);
  }
}