ucar.nc2.time.Calendar Java Examples

The following examples show how to use ucar.nc2.time.Calendar. 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: GribIospBuilder.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void makeRuntimeCoordinate(Group.Builder g, CoordinateRuntime rtc) {
  int n = rtc.getSize();
  boolean isScalar = (n == 1); // this is the case of runtime[1]
  String tcName = rtc.getName();
  String dims = isScalar ? null : rtc.getName(); // null means scalar
  if (!isScalar) {
    g.addDimension(new Dimension(tcName, n));
  }

  Variable.Builder v = Variable.builder().setName(tcName).setDataType(DataType.DOUBLE).setParentGroupBuilder(g)
      .setDimensionsByName(dims);
  g.addVariable(v);
  v.addAttribute(new Attribute(CDM.UNITS, rtc.getUnit()));
  v.addAttribute(new Attribute(CF.STANDARD_NAME, CF.TIME_REFERENCE));
  v.addAttribute(new Attribute(CDM.LONG_NAME, Grib.GRIB_RUNTIME));
  v.addAttribute(new Attribute(CF.CALENDAR, Calendar.proleptic_gregorian.toString()));

  // lazy eval
  v.setSPobject(new Time2Dinfo(Time2DinfoType.reftime, null, rtc));
}
 
Example #2
Source File: DecoderWrapper.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the value of the attribute of the given name as a date, or {@code null} if none.
 *
 * @param  name  the name of the attribute to search, or {@code null}.
 * @return the attribute value, or {@code null} if none or unparsable or if the given name was null.
 */
@Override
public Date dateValue(final String name) {
    if (name != null) {
        for (final Group group : groups) {
            final Attribute attribute = findAttribute(group, name);
            if (attribute != null && attribute.isString()) {
                String value = Utils.nonEmpty(attribute.getStringValue());
                if (value != null) {
                    final CalendarDate date;
                    try {
                        date = CalendarDateFormatter.isoStringToCalendarDate(Calendar.proleptic_gregorian, value);
                    } catch (IllegalArgumentException e) {
                        listeners.warning(e);
                        continue;
                    }
                    return new Date(date.getMillis());
                }
            }
        }
    }
    return null;
}
 
Example #3
Source File: NcssParamsBean.java    From tds with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public boolean intersectsTime(CalendarDateRange have, Formatter errs) {
  if (have == null)
    return true;
  Calendar dataCal = have.getStart().getCalendar(); // use the same calendar as the dataset

  CalendarDateRange want = getCalendarDateRange(dataCal);
  if (want != null) {
    if (have.intersects(want)) {
      return true;
    } else {
      errs.format("Requested time range %s does not intersect actual time range %s", want, have);
      return false;
    }
  }

  CalendarDate wantTime = getRequestedDate(dataCal);
  if (wantTime == null)
    return true;
  if (!have.includes(wantTime)) {
    errs.format("Requested time %s does not intersect actual time range %s", wantTime, have);
    return false;
  }
  return true;
}
 
Example #4
Source File: GribIosp.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void makeTimeCoordinate1D(NetcdfFile ncfile, Group g, CoordinateTime coordTime) { // }, CoordinateRuntime
                                                                                          // runtime) {
  int ntimes = coordTime.getSize();
  String tcName = coordTime.getName();
  String dims = coordTime.getName();
  ncfile.addDimension(g, new Dimension(tcName, ntimes));
  Variable v = ncfile.addVariable(g, new Variable(ncfile, g, null, tcName, DataType.DOUBLE, dims));
  String units = coordTime.getTimeUdUnit();
  v.addAttribute(new Attribute(CDM.UNITS, units));
  v.addAttribute(new Attribute(CF.STANDARD_NAME, CF.TIME));
  v.addAttribute(new Attribute(CDM.LONG_NAME, Grib.GRIB_VALID_TIME));
  v.addAttribute(new Attribute(CF.CALENDAR, Calendar.proleptic_gregorian.toString()));

  double[] data = new double[ntimes];
  int count = 0;

  // coordinate values
  for (int val : coordTime.getOffsetSorted()) {
    data[count++] = val;
  }
  v.setCachedData(Array.factory(DataType.DOUBLE, new int[] {ntimes}, data));

  makeTimeAuxReference(ncfile, g, tcName, units, coordTime);
}
 
Example #5
Source File: GribIospBuilder.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void makeTimeAuxReference(Group.Builder g, String timeName, String units, CoordinateTimeAbstract time) {
  if (time.getTime2runtime() == null) {
    return;
  }
  String tcName = "ref" + timeName;
  Variable.Builder v = Variable.builder().setName(tcName).setDataType(DataType.DOUBLE).setParentGroupBuilder(g)
      .setDimensionsByName(timeName);
  g.addVariable(v);
  v.addAttribute(new Attribute(CF.STANDARD_NAME, CF.TIME_REFERENCE));
  v.addAttribute(new Attribute(CDM.LONG_NAME, Grib.GRIB_RUNTIME));
  v.addAttribute(new Attribute(CF.CALENDAR, Calendar.proleptic_gregorian.toString()));
  v.addAttribute(new Attribute(CDM.UNITS, units));

  // lazy evaluation
  v.setSPobject(new Time2Dinfo(Time2DinfoType.timeAuxRef, null, time));
}
 
Example #6
Source File: GribIospBuilder.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void makeTimeCoordinate1D(Group.Builder g, CoordinateTime coordTime) { // }, CoordinateRuntime
  // runtime) {
  int ntimes = coordTime.getSize();
  String tcName = coordTime.getName();
  String dims = coordTime.getName();
  g.addDimension(new Dimension(tcName, ntimes));
  Variable.Builder v = Variable.builder().setName(tcName).setDataType(DataType.DOUBLE).setParentGroupBuilder(g)
      .setDimensionsByName(dims);
  g.addVariable(v);
  String units = coordTime.getTimeUdUnit();
  v.addAttribute(new Attribute(CDM.UNITS, units));
  v.addAttribute(new Attribute(CF.STANDARD_NAME, CF.TIME));
  v.addAttribute(new Attribute(CDM.LONG_NAME, Grib.GRIB_VALID_TIME));
  v.addAttribute(new Attribute(CF.CALENDAR, Calendar.proleptic_gregorian.toString()));

  double[] data = new double[ntimes];
  int count = 0;

  // coordinate values
  for (int val : coordTime.getOffsetSorted()) {
    data[count++] = val;
  }
  v.setCachedData(Array.factory(DataType.DOUBLE, new int[] {ntimes}, data), false);

  makeTimeAuxReference(g, tcName, units, coordTime);
}
 
Example #7
Source File: AggregationOuter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private boolean calendarsEquivalent(Calendar a, Calendar b) {
  boolean equivalent = false;
  if (a != null) {
    // calendar from new file must not be null
    if (b != null) {
      // is calendar from new file the same as the first file in the aggregation?
      equivalent = b.equals(a);
    }
  } else {
    // if calendar attribute is missing from the first file in the aggregation,
    // it must be missing from the new file in order for the calendars to be
    // considered "equivalent"
    equivalent = b == null;
  }
  return equivalent;
}
 
Example #8
Source File: CoordinateAxis.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public ucar.nc2.time.Calendar getCalendarFromAttribute() {
  String cal = attributes.findAttributeString(CF.CALENDAR, null);
  if (cal == null) { // default for CF and COARDS
    Attribute convention = (ncd == null) ? null : ncd.getRootGroup().findAttribute(CDM.CONVENTIONS);
    if (convention != null && convention.isString()) {
      String hasName = convention.getStringValue();
      int version = CF1Convention.getVersion(hasName);
      if (version >= 0) {
        return Calendar.gregorian;
        // if (version < 7 ) return Calendar.gregorian;
        // if (version >= 7 ) return Calendar.proleptic_gregorian; //
      }
      if (COARDSConvention.isMine(hasName))
        return Calendar.gregorian;
    }
  }
  return ucar.nc2.time.Calendar.get(cal);
}
 
Example #9
Source File: AggregationOuterDimension.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private boolean calendarsEquivalent(Calendar a, Calendar b) {
  boolean equivalent = false;
  if (a != null) {
    // calendar from new file must not be null
    if (b != null) {
      // is calendar from new file the same as the first file in the aggregation?
      equivalent = b.equals(a);
    }
  } else {
    // if calendar attribute is missing from the first file in the aggregation,
    // it must be missing from the new file in order for the calendars to be
    // considered "equivalent"
    equivalent = b != null ? false : true;
  }
  return equivalent;
}
 
Example #10
Source File: CatalogBuilder.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected DateRange readTimeCoverage(Element tElem) {
  if (tElem == null) {
    return null;
  }

  Calendar calendar = readCalendar(tElem.getAttributeValue("calendar"));
  DateType start = readDate(tElem.getChild("start", Catalog.defNS), calendar);
  DateType end = readDate(tElem.getChild("end", Catalog.defNS), calendar);

  TimeDuration duration = readDuration(tElem.getChild("duration", Catalog.defNS));
  TimeDuration resolution = readDuration(tElem.getChild("resolution", Catalog.defNS));

  try {
    return new DateRange(start, end, duration, resolution);
  } catch (java.lang.IllegalArgumentException e) {
    errlog.format(" ** warning: TimeCoverage error ='%s'%n", e.getMessage());
    logger.debug(" ** warning: TimeCoverage error ='{}'", e.getMessage());
    return null;
  }
}
 
Example #11
Source File: CdmrfReader.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static Calendar convertCalendar(CdmrFeatureProto.Calendar type) {
  switch (type) {
    case gregorian:
      return Calendar.gregorian;
    case proleptic_gregorian:
      return Calendar.proleptic_gregorian;
    case noleap:
      return Calendar.noleap;
    case all_leap:
      return Calendar.all_leap;
    case uniform30day:
      return Calendar.uniform30day;
    case julian:
      return Calendar.julian;
    case none:
      return Calendar.none;
  }
  throw new IllegalStateException("illegal data type " + type);
}
 
Example #12
Source File: CdmrfWriter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static CdmrFeatureProto.Calendar convertCalendar(Calendar type) {
  switch (type) {
    case gregorian:
      return CdmrFeatureProto.Calendar.gregorian;
    case proleptic_gregorian:
      return CdmrFeatureProto.Calendar.proleptic_gregorian;
    case noleap:
      return CdmrFeatureProto.Calendar.noleap;
    case all_leap:
      return CdmrFeatureProto.Calendar.all_leap;
    case uniform30day:
      return CdmrFeatureProto.Calendar.uniform30day;
    case julian:
      return CdmrFeatureProto.Calendar.julian;
    case none:
      return CdmrFeatureProto.Calendar.none;
  }
  throw new IllegalStateException("illegal data type " + type);
}
 
Example #13
Source File: CatalogBuilder.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected DateType makeDateType(String text, String format, String type, Calendar calendar) {
  if (text == null) {
    return null;
  }
  try {
    return new DateType(text, format, type, calendar);
  } catch (java.text.ParseException e) {
    errlog.format(" ** Parse error: Bad date format = '%s'%n", text);
    return null;
  }
}
 
Example #14
Source File: DefaultDateRangeTest.java    From tds with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void shouldGetPresent() throws ParseException {
  CalendarDateRange range = requestParams.makeCalendarDateRange(Calendar.getDefault());
  System.out.printf("range=%s%n", range);
  System.out.printf(" duration: expected=%d actual=%d%n", durationInSeconds, range.getDurationInSecs());
  // assertEquals(durationInSeconds, range.getDurationInSecs() );
  // long duration =Math.abs( durationInSeconds - range.getDurationInSecs() );
  assertTrue(Math.abs(durationInSeconds - range.getDurationInSecs()) < 100);
}
 
Example #15
Source File: DsgSubsetWriterTest.java    From tds with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void setupClass() throws URISyntaxException {
  // The WaterML marshaller usually initializes wml2:generationDate and om:resultTime to "now". This is a problem,
  // because those values will always differ from the fixed values we have in our expectedResultResource files.
  // So, to facilitate testing, we're going to fix the values that the marshaller emits.
  MarshallingUtil.fixedGenerationDate = CalendarDate.of(Calendar.gregorian, 1970, 1, 1, 0, 0, 0);
  MarshallingUtil.fixedResultTime = CalendarDate.of(Calendar.gregorian, 1970, 1, 1, 0, 0, 0);

  ncssDiskCache = new NcssDiskCache(DiskCache2.getDefault().getRootDirectory());

  subsetParamsAll = new SubsetParams();
  subsetParamsAll.setVariables(Arrays.asList("pr", "tas"));

  subsetParamsPoint = new SubsetParams();
  subsetParamsPoint.setVariables(Arrays.asList("pr"));
  subsetParamsPoint.setTime(CalendarDate.parseISOformat(null, "1970-01-01 02:00:00Z"));
  // Full extension is (40.0, -100.0) to (68.0, -58.0).
  LatLonRect bbox = new LatLonRect(LatLonPoint.create(40.0, -100.0), LatLonPoint.create(53.0, -58.0));
  subsetParamsPoint.setLatLonBoundingBox(bbox);

  subsetParamsStation1 = new SubsetParams();
  subsetParamsStation1.setVariables(Arrays.asList("tas"));
  CalendarDate start = CalendarDate.parseISOformat(null, "1970-01-05T00:00:00Z");
  CalendarDate end = CalendarDate.parseISOformat(null, "1970-02-05T00:00:00Z");
  subsetParamsStation1.setTimeRange(CalendarDateRange.of(start, end));
  subsetParamsStation1.setStations(Arrays.asList("AAA", "CCC"));

  subsetParamsStation2 = new SubsetParams();
  subsetParamsStation2.setVariables(Arrays.asList("pr", "tas"));
  // The nearest will be "1970-01-21 00:00:00Z"
  subsetParamsStation2.setTime(CalendarDate.parseISOformat(null, "1970-01-21 01:00:00Z"));
}
 
Example #16
Source File: NcssPointParamsBean.java    From tds with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public SubsetParams makeSubset() {

    SubsetParams subset = new SubsetParams();

    // vars
    subset.set(SubsetParams.variables, var);

    // horiz
    if (stns != null)
      subset.set(SubsetParams.stations, stns);
    else if (hasLatLonBB())
      subset.set(SubsetParams.latlonBB, getLatLonBoundingBox());
    else if (hasLatLonPoint())
      subset.set(SubsetParams.latlonPoint, LatLonPoint.create(getLatitude(), getLongitude()));

    // time
    CalendarDate date = getRequestedDate(Calendar.getDefault());
    CalendarDateRange dateRange = getCalendarDateRange(Calendar.getDefault());
    if (isAllTimes()) {
      subset.set(SubsetParams.timeAll, true);

    } else if (date != null) {
      subset.set(SubsetParams.time, date);

    } else if (dateRange != null) {
      subset.set(SubsetParams.timeRange, dateRange);

    } else {
      subset.set(SubsetParams.timePresent, true);
    }

    if (timeWindow != null) {
      CalendarPeriod period = CalendarPeriod.of(timeWindow);
      subset.set(SubsetParams.timeWindow, period);
    }

    return subset;
  }
 
Example #17
Source File: NcssGridParamsBean.java    From tds with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public CalendarDate getRuntimeDate(Calendar cal) {
  if (runtimeDate == null)
    return null;
  if (cal.equals(Calendar.getDefault()))
    return runtimeDate;

  // otherwise must reparse
  if (getTime().equalsIgnoreCase("present")) {
    return CalendarDate.present(cal);
  }

  return CalendarDateFormatter.isoStringToCalendarDate(cal, getRuntime());
}
 
Example #18
Source File: CatalogBuilder.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected Calendar readCalendar(String calendarAttribValue) {
  if (calendarAttribValue == null) {
    return Calendar.getDefault();
  }

  Calendar calendar = Calendar.get(calendarAttribValue);
  if (calendar == null) {
    errlog.format(" ** Parse error: Bad calendar name = '%s'%n", calendarAttribValue);
    logger.debug(" ** Parse error: Bad calendar name = '{}}'", calendarAttribValue);
    return Calendar.getDefault();
  }

  return calendar;
}
 
Example #19
Source File: NcssParamsBean.java    From tds with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public CalendarDate getRequestedDate(Calendar cal) {
  if (date == null)
    return null;
  if (cal.equals(Calendar.getDefault()))
    return date;

  // otherwise must reparse
  return CalendarDateFormatter.isoStringToCalendarDate(cal, getTime());
}
 
Example #20
Source File: NcssParamsBean.java    From tds with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public CalendarDateRange makeCalendarDateRange(Calendar cal) {
  try {
    // this handles "present"
    DateRange dr = new DateRange(new DateType(time_start, null, null, cal), new DateType(time_end, null, null, cal),
        new TimeDuration(time_duration), null);
    return CalendarDateRange.of(dr.getStart().getCalendarDate(), dr.getEnd().getCalendarDate());
  } catch (ParseException pe) {
    return null; // ??
  }
}
 
Example #21
Source File: NcssParamsBean.java    From tds with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public CalendarDateRange getCalendarDateRange(Calendar cal) {
  if (dateRange == null)
    return null;
  if (cal.equals(Calendar.getDefault()))
    return dateRange;

  // otherwise must reparse
  return makeCalendarDateRange(cal);
}
 
Example #22
Source File: GribIosp.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void makeTimeAuxReference(NetcdfFile ncfile, Group g, String timeName, String units,
    CoordinateTimeAbstract time) {
  if (time.getTime2runtime() == null) {
    return;
  }
  String tcName = "ref" + timeName;
  Variable v = ncfile.addVariable(g, new Variable(ncfile, g, null, tcName, DataType.DOUBLE, timeName));
  v.addAttribute(new Attribute(CF.STANDARD_NAME, CF.TIME_REFERENCE));
  v.addAttribute(new Attribute(CDM.LONG_NAME, Grib.GRIB_RUNTIME));
  v.addAttribute(new Attribute(CF.CALENDAR, Calendar.proleptic_gregorian.toString()));
  v.addAttribute(new Attribute(CDM.UNITS, units));

  // lazy evaluation
  v.setSPobject(new Time2Dinfo(Time2DinfoType.timeAuxRef, null, time));
}
 
Example #23
Source File: CatalogBuilder.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected DateType readDate(Element elem, Calendar calendar) {
  if (elem == null) {
    return null;
  }
  String format = elem.getAttributeValue("format");
  String type = elem.getAttributeValue("type");
  return makeDateType(elem.getText(), format, type, calendar);
}
 
Example #24
Source File: GribIosp.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void makeTimeCoordinate2D(NetcdfFile ncfile, Group g, CoordinateTime2D time2D,
    GribCollectionImmutable.Type gctype) {
  CoordinateRuntime runtime = time2D.getRuntimeCoordinate();

  int ntimes = time2D.getNtimes();
  String tcName = time2D.getName();
  String timeDimName = make2dValidTimeDimensionName(tcName);
  String dims = runtime.getName() + " " + timeDimName;
  int dimLength = ntimes;

  ncfile.addDimension(g, new Dimension(timeDimName, dimLength));
  Variable v = ncfile.addVariable(g, new Variable(ncfile, g, null, tcName, DataType.DOUBLE, dims));
  String units = runtime.getUnit(); // + " since " + runtime.getFirstDate();
  v.addAttribute(new Attribute(CDM.UNITS, units));
  v.addAttribute(new Attribute(CF.STANDARD_NAME, CF.TIME));
  v.addAttribute(new Attribute(CDM.LONG_NAME, Grib.GRIB_VALID_TIME));
  v.addAttribute(new Attribute(CF.CALENDAR, Calendar.proleptic_gregorian.toString()));
  if (!tcName.equalsIgnoreCase(timeDimName)) {
    // explicitly set the axis type as Time
    v.addAttribute(new Attribute(_Coordinate.AxisType, AxisType.Time.toString()));
  }

  // the data is not generated until asked for to save space
  if (!time2D.isTimeInterval()) {
    v.setSPobject(new Time2Dinfo(Time2DinfoType.off, time2D, null));
  } else {
    v.setSPobject(new Time2Dinfo(Time2DinfoType.intv, time2D, null));
    // bounds for intervals
    String bounds_name = timeDimName + "_bounds";
    Variable bounds = ncfile.addVariable(g, new Variable(ncfile, g, null, bounds_name, DataType.DOUBLE, dims + " 2"));
    v.addAttribute(new Attribute(CF.BOUNDS, bounds_name));
    bounds.addAttribute(new Attribute(CDM.UNITS, units));
    bounds.addAttribute(new Attribute(CDM.LONG_NAME, "bounds for " + tcName));
    bounds.setSPobject(new Time2Dinfo(Time2DinfoType.bounds, time2D, null));
  }

}
 
Example #25
Source File: GribIosp.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void makeRuntimeCoordinate(NetcdfFile ncfile, Group g, CoordinateRuntime rtc) {
  int n = rtc.getSize();
  boolean isScalar = (n == 1); // this is the case of runtime[1]
  String tcName = rtc.getName();
  String dims = isScalar ? null : rtc.getName(); // null means scalar
  if (!isScalar) {
    ncfile.addDimension(g, new Dimension(tcName, n));
  }

  Variable v = ncfile.addVariable(g, new Variable(ncfile, g, null, tcName, DataType.DOUBLE, dims));
  v.addAttribute(new Attribute(CDM.UNITS, rtc.getUnit()));
  v.addAttribute(new Attribute(CF.STANDARD_NAME, CF.TIME_REFERENCE));
  v.addAttribute(new Attribute(CDM.LONG_NAME, Grib.GRIB_RUNTIME));
  v.addAttribute(new Attribute(CF.CALENDAR, Calendar.proleptic_gregorian.toString()));

  /*
   * String vsName = tcName + "_ISO";
   * Variable vs = ncfile.addVariable(g, new Variable(ncfile, g, null, vsName, DataType.STRING, dims));
   * vs.addAttribute(new Attribute(CDM.UNITS, "ISO8601"));
   * v.addAttribute(new Attribute(CDM.LONG_NAME, "GRIB reference time"));
   * v.addAttribute(new Attribute(CF.CALENDAR, Calendar.proleptic_gregorian.toString()));
   * 
   * // coordinate values
   * String[] dataS = new String[n];
   * int count = 0;
   * for (CalendarDate val : rtc.getRuntimesSorted()) {
   * dataS[count++] = val.toString();
   * }
   * vs.setCachedData(Array.factory(DataType.STRING, isScalar ? new int[0] : new int[]{n}, dataS));
   */

  // lazy eval
  v.setSPobject(new Time2Dinfo(Time2DinfoType.reftime, null, rtc));
}
 
Example #26
Source File: GribIospBuilder.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void makeTimeCoordinate2D(Group.Builder g, CoordinateTime2D time2D, GribCollectionImmutable.Type gctype) {
  CoordinateRuntime runtime = time2D.getRuntimeCoordinate();

  int ntimes = time2D.getNtimes();
  String tcName = time2D.getName();
  String timeDimName = make2dValidTimeDimensionName(tcName);
  String dims = runtime.getName() + " " + timeDimName;
  int dimLength = ntimes;

  g.addDimension(new Dimension(timeDimName, dimLength));
  Variable.Builder v = Variable.builder().setName(tcName).setDataType(DataType.DOUBLE).setParentGroupBuilder(g)
      .setDimensionsByName(dims);
  g.addVariable(v);
  String units = runtime.getUnit(); // + " since " + runtime.getFirstDate();
  v.addAttribute(new Attribute(CDM.UNITS, units));
  v.addAttribute(new Attribute(CF.STANDARD_NAME, CF.TIME));
  v.addAttribute(new Attribute(CDM.LONG_NAME, Grib.GRIB_VALID_TIME));
  v.addAttribute(new Attribute(CF.CALENDAR, Calendar.proleptic_gregorian.toString()));
  if (!tcName.equalsIgnoreCase(timeDimName)) {
    // explicitly set the axis type as Time
    v.addAttribute(new Attribute(_Coordinate.AxisType, AxisType.Time.toString()));
  }

  // the data is not generated until asked for to save space
  if (!time2D.isTimeInterval()) {
    v.setSPobject(new Time2Dinfo(Time2DinfoType.off, time2D, null));
  } else {
    v.setSPobject(new Time2Dinfo(Time2DinfoType.intv, time2D, null));
    // bounds for intervals
    String bounds_name = timeDimName + "_bounds";
    Variable.Builder bounds = Variable.builder().setName(bounds_name).setDataType(DataType.DOUBLE)
        .setParentGroupBuilder(g).setDimensionsByName(dims + " 2");
    g.addVariable(bounds);
    v.addAttribute(new Attribute(CF.BOUNDS, bounds_name));
    bounds.addAttribute(new Attribute(CDM.UNITS, units));
    bounds.addAttribute(new Attribute(CDM.LONG_NAME, "bounds for " + tcName));
    bounds.setSPobject(new Time2Dinfo(Time2DinfoType.bounds, time2D, null));
  }

}
 
Example #27
Source File: CdmrfWriter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
CdmrFeatureProto.CalendarDateRange.Builder encodeDateRange(CalendarDateRange dateRange) {
  CdmrFeatureProto.CalendarDateRange.Builder builder = CdmrFeatureProto.CalendarDateRange.newBuilder();

  builder.setStart(dateRange.getStart().getMillis());
  builder.setEnd(dateRange.getEnd().getMillis());
  Calendar cal = dateRange.getStart().getCalendar();
  builder.setCalendar(convertCalendar(cal));
  return builder;
}
 
Example #28
Source File: CoordinateAxisTimeHelper.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public CoordinateAxisTimeHelper(Calendar calendar, String unitString) {
  this.calendar = calendar;
  if (unitString == null) {
    this.dateUnit = null;
    return;
  }
  this.dateUnit = CalendarDateUnit.withCalendar(calendar, unitString); // this will throw exception on failure
}
 
Example #29
Source File: TimeCoord.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
double getValueInHours(Calendar cal, DateUnit unit, double value) {
  // CalendarDate d = unit.makeCalendarDate(value);
  // double secs = unit.getTimeUnit().getValueInSeconds(value);
  // CalendarDate d = CalendarDate.of(cal, unit.getDateOrigin().getTime() + (long)(1000*secs));

  CalendarDateUnit dateUnit = CalendarDateUnit.withCalendar(cal, unit.getUnitsString()); // this will throw exception
                                                                                         // on failure
  CalendarDate d = dateUnit.makeCalendarDate(value);
  return FmrcInv.getOffsetInHours(runDate, d);
}
 
Example #30
Source File: RecordDatasetHelper.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Constructor.
 *
 * @param ncfile the netccdf file
 * @param typedDataVariables list of data variables; all record variables will be added to this list, except . You
 *        can remove extra
 * @param obsTimeVName observation time variable name (required)
 * @param nomTimeVName nominal time variable name (may be null)
 * @throws IllegalArgumentException if ncfile has no unlimited dimension and recDimName is null.
 */
public RecordDatasetHelper(NetcdfDataset ncfile, String obsTimeVName, String nomTimeVName,
    List<VariableSimpleIF> typedDataVariables, String recDimName, Formatter errBuffer) {
  this.ncfile = ncfile;
  this.obsTimeVName = obsTimeVName;
  this.nomTimeVName = nomTimeVName;
  this.errs = errBuffer;

  // check if we already have a structure vs if we have to add it.

  if (this.ncfile.hasUnlimitedDimension()) {
    this.ncfile.sendIospMessage(NetcdfFile.IOSP_MESSAGE_ADD_RECORD_STRUCTURE);
    this.recordVar = (StructureDS) this.ncfile.getRootGroup().findVariableLocal("record");
    this.obsDim = ncfile.getUnlimitedDimension();

  } else {
    if (recDimName == null)
      throw new IllegalArgumentException("File <" + this.ncfile.getLocation()
          + "> has no unlimited dimension, specify psuedo record dimension with observationDimension global attribute.");
    this.obsDim = this.ncfile.getRootGroup().findDimension(recDimName);
    this.recordVar = new StructurePseudoDS(this.ncfile, null, "record", null, obsDim);
  }

  // create member variables
  List<Variable> recordMembers = ncfile.getVariables();
  for (Variable v : recordMembers) {
    if (v == recordVar)
      continue;
    if (v.isScalar())
      continue;
    if (v.getDimension(0) == this.obsDim)
      typedDataVariables.add(v);
  }

  // need the time units
  Variable timeVar = ncfile.findVariable(obsTimeVName);
  String timeUnitString = ncfile.findAttValueIgnoreCase(timeVar, CDM.UNITS, "seconds since 1970-01-01");
  Calendar cal = TimeHelper.getCalendarFromAttribute(timeVar);

  try {
    timeUnit = CalendarDateUnit.withCalendar(cal, timeUnitString);

  } catch (Exception e) {
    if (null != errs)
      errs.format("Error on string = %s == %s%n", timeUnitString, e.getMessage());
    timeUnit = CalendarDateUnit.unixDateUnit;
  }
}