# Lint as: python3
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Douglas ADI method for solving multidimensional parabolic PDEs."""

import numpy as np
import tensorflow.compat.v2 as tf
from tf_quant_finance.math.pde.steppers.multidim_parabolic_equation_stepper import multidim_parabolic_equation_step


def douglas_adi_step(theta=0.5):
  """Creates a stepper function with Crank-Nicolson time marching scheme.

  Douglas ADI scheme is the simplest time marching scheme for solving parabolic
  PDEs with multiple spatial dimensions. The time step consists of several
  substeps: the first one is fully explicit, and the following `N` steps are
  implicit with respect to contributions of one of the `N` axes (hence "ADI" -
  alternating direction implicit). See `douglas_adi_scheme` below for more
  details.

  Args:
    theta: positive Number. `theta = 0` corresponds to fully explicit scheme.
    The larger `theta` the stronger are the corrections by the implicit
    substeps. The recommended value is `theta = 0.5`, because the scheme is
    second order accurate in that case, unless mixed second derivative terms are
    present in the PDE.
  Returns:
    Callable to be used in finite-difference PDE solvers (see fd_solvers.py).
  """
  def _step_fn(
      time,
      next_time,
      coord_grid,
      value_grid,
      boundary_conditions,
      second_order_coeff_fn,
      first_order_coeff_fn,
      zeroth_order_coeff_fn,