Java Code Examples for ucar.nc2.NetcdfFileWriter

The following examples show how to use ucar.nc2.NetcdfFileWriter. 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
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 2
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 3
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 4
@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 5
@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 6
Source Project: OpenDA   Source File: NetcdfUtils.java    License: 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 7
Source Project: OpenDA   Source File: NetcdfUtils.java    License: 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 8
Source Project: OpenDA   Source File: NetcdfUtils.java    License: 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 9
Source Project: OpenDA   Source File: NetcdfUtils.java    License: 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 10
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 11
Source Project: OpenDA   Source File: NetcdfUtils.java    License: 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 12
Source Project: OpenDA   Source File: NetcdfUtils.java    License: 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 13
Source Project: OpenDA   Source File: NetcdfUtils.java    License: 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 14
Source Project: OpenDA   Source File: NetcdfUtils.java    License: 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 15
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 16
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 17
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 18
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 19
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);
  }
}
 
Example 20
public static NetcdfFileFormat convertToNetcdfFileFormat(NetcdfFileWriter.Version version) {
  switch (version) {
    case netcdf3:
      return NetcdfFileFormat.NETCDF3;
    case netcdf4:
      return NetcdfFileFormat.NETCDF4;
    case netcdf4_classic:
      return NetcdfFileFormat.NETCDF4_CLASSIC;
    case netcdf3c64:
      return NetcdfFileFormat.NETCDF3_64BIT_OFFSET;
    default:
      throw new IllegalStateException("Unsupported version: " + version);
  }
}
 
Example 21
private NetcdfFile openJni(String location) throws IOException {
  Nc4Iosp iosp = new Nc4Iosp(NetcdfFileWriter.Version.netcdf4);
  NetcdfFile ncfile = new NetcdfFileSubclass(iosp, location);
  RandomAccessFile raf = new RandomAccessFile(location, "r");
  iosp.open(raf, ncfile, null);
  return ncfile;
}
 
Example 22
private NetcdfFile openJni(String location) throws IOException {
  Nc4Iosp iosp = new Nc4Iosp(NetcdfFileWriter.Version.netcdf4);
  NetcdfFile ncfile = new NetcdfFileSubclass(iosp, location);
  RandomAccessFile raf = new RandomAccessFile(location, "r");
  iosp.open(raf, ncfile, null);
  return ncfile;
}
 
Example 23
@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 24
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 25
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 26
Source Project: OpenDA   Source File: NetcdfUtils.java    License: 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 27
Source Project: OpenDA   Source File: NetcdfUtils.java    License: 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 28
Source Project: OpenDA   Source File: NetcdfUtils.java    License: 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 29
Source Project: OpenDA   Source File: NetcdfUtils.java    License: 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 30
Source Project: OpenDA   Source File: NetcdfUtils.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void createDataVariables(NetcdfFileWriter netcdfFileWriter, List<IExchangeItem> exchangeItems, Map<String, Map<Integer, IExchangeItem>> ensembleExchangeItems,
		Dimension realizationDimension, Dimension stationDimension, Map<ITimeInfo, Dimension> timeInfoTimeDimensionMap, Map<IGeometryInfo, GridVariableProperties> geometryInfoGridVariablePropertiesMap) {

	//non-ensemble exchange items.
	int[] uniqueTimeVariableCount = new int[]{0};
	createDataVariables(netcdfFileWriter, exchangeItems, null, stationDimension, timeInfoTimeDimensionMap, geometryInfoGridVariablePropertiesMap, uniqueTimeVariableCount);

	//ensemble exchange items.
	if (ensembleExchangeItems != null) {
		for (Map<Integer, IExchangeItem> ensemble : ensembleExchangeItems.values()) {
			Collection<IExchangeItem> items = ensemble.values();
			createDataVariables(netcdfFileWriter, items, realizationDimension, stationDimension, timeInfoTimeDimensionMap, geometryInfoGridVariablePropertiesMap, uniqueTimeVariableCount);
		}
	}
}