au.gov.amsa.util.netcdf.NetCdfWriter Maven / Gradle / Ivy
package au.gov.amsa.util.netcdf;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import com.github.davidmoten.guavamini.Lists;
import com.github.davidmoten.guavamini.Preconditions;
import ucar.ma2.Array;
import ucar.ma2.DataType;
import ucar.ma2.InvalidRangeException;
import ucar.nc2.Attribute;
import ucar.nc2.Dimension;
import ucar.nc2.NetcdfFileWriter;
import ucar.nc2.NetcdfFileWriter.Version;
import ucar.nc2.Variable;
public class NetCdfWriter implements AutoCloseable {
private final NetcdfFileWriter f;
private final Map, List>> map = new HashMap<>();
public NetCdfWriter(File file, String version) {
try {
f = NetcdfFileWriter.createNew(Version.netcdf3, file.getPath());
// add version attribute
f.addGroupAttribute(null, new Attribute("version", version));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public NetcdfFileWriter writer() {
return f;
}
public NetCdfWriter addAttribute(String name, String value) {
f.addGroupAttribute(null, new Attribute(name, value));
return this;
}
public VarBuilder addVariable(String shortName, Class cls) {
return new VarBuilder(this, shortName, cls);
}
public Var addVariable(String shortName, Optional longName,
Optional units, Optional encoding, Class cls, int numRecords) {
Preconditions.checkNotNull(shortName);
Preconditions.checkNotNull(longName);
Preconditions.checkNotNull(units);
Preconditions.checkNotNull(encoding);
Preconditions.checkNotNull(cls);
Dimension dimension = f.addDimension(null, shortName, numRecords);
Variable variable = f.addVariable(null, shortName, toDataType(cls),
Arrays.asList(dimension));
if (longName.isPresent())
variable.addAttribute(new Attribute("long_name", longName.get()));
if (units.isPresent())
variable.addAttribute(new Attribute("units", units.get()));
if (encoding.isPresent())
variable.addAttribute(new Attribute("encoding", encoding.get()));
return new Var(this, variable, cls);
}
public NetCdfWriter add(Var variable, T value) {
@SuppressWarnings("unchecked")
List
© 2015 - 2025 Weber Informatics LLC | Privacy Policy