def test_year_month_day_to_ordinal(self):
     date_tuples = test_data.test_dates
     expected = np.array(
         [datetime.date(y, m, d).toordinal() for y, m, d in date_tuples],
         dtype=np.int32)
     dates_np = np.array(date_tuples)
     years, months, days = dates_np[:, 0], dates_np[:, 1], dates_np[:, 2]
     actual = date_utils.year_month_day_to_ordinal(years, months, days)
     self.assertAllEqual(expected, actual)
Ejemplo n.º 2
0
  def from_year_month_day_tensors(cls,
                                  years,
                                  months,
                                  days,
                                  validate=True):
    """Creates DateTensor from tensors of years, months and days.

    Args:
      years: Tensor of int32 type. Elements should be positive.
      months: Tensor of int32 type of same shape as `year`. Elements should be
        in range `[1, 12]`.
      days: Tensor of int32 type of same shape as `year`. Elements should be in
        range `[1, 31]` and represent valid dates together with corresponding
        elements of `month` and `year` Tensors.
      validate: Whether to validate the dates.

    Returns:
      DateTensor object.

    Example:
    ```python
    years = tf.constant([2015, 2017], dtype=tf.int32)
    months = tf.constant([4, 12], dtype=tf.int32)
    days = tf.constant([15, 30], dtype=tf.int32)
    date_tensor = DateTensor.from_year_month_day_tensors(years, months, days)
    ```
    """
    years = tf.convert_to_tensor(years, tf.int32)
    months = tf.convert_to_tensor(months, tf.int32)
    days = tf.convert_to_tensor(days, tf.int32)

    control_deps = []
    if validate:
      control_deps.append(tf.debugging.assert_positive(years))
      control_deps.append(
          tf.debugging.assert_greater_equal(months, Month.JANUARY.value))
      control_deps.append(
          tf.debugging.assert_less_equal(months, Month.DECEMBER.value))
      control_deps.append(tf.debugging.assert_positive(days))
      is_leap = date_utils.is_leap_year(years)
      days_in_months = tf.constant(_days_in_months, tf.int32)
      max_days = tf.gather(days_in_months,
                           months + 12 * tf.dtypes.cast(is_leap, np.int32))
      control_deps.append(tf.debugging.assert_less_equal(days, max_days))
      with tf.compat.v1.control_dependencies(control_deps):
        # Ensure years, months, days themselves are under control_deps.
        years = tf.identity(years)
        months = tf.identity(months)
        days = tf.identity(days)

    with tf.compat.v1.control_dependencies(control_deps):
      ordinals = date_utils.year_month_day_to_ordinal(years, months, days)
      return DateTensor(ordinals, years, months, days)