class_docstr: Local volatility model for smile modeling.
  
  Local volatility (LV) model specifies that the dynamics of an asset is
  governed by the following stochastic differential equation:
  
  ```None
    dS(t) / S(t) =  mu(t, S(t)) dt + sigma(t, S(t)) * dW(t)
  ```
  where `mu(t, S(t))` is the drift and `sigma(t, S(t))` is the instantaneous
  volatility. The local volatility function `sigma(t, S(t))` is state dependent
  and is computed by calibrating against a given implied volatility surface
  `sigma_iv(T, K)` using the Dupire's formula [1]:
  
  ```
  sigma(T,K)^2 = 2 * (dC(T,K)/dT + (r - q)K dC(T,K)/dK + qC(T,K)) /
                     (K^2 d2C(T,K)/dK2)
  ```
  where the derivatives above are the partial derivatives. The LV model provides
  a flexible framework to model any (arbitrage free) volatility surface.
  
  #### Example: Simulation of local volatility process.
  
  ```python
  import numpy as np
  import tensorflow.compat.v2 as tf
  import tf_quant_finance as tff
  
  dtype = tf.float64
  dim = 2
  year = dim * [[2021, 2022]]
  month = dim * [[1, 1]]
  day = dim * [[1, 1]]
  expiries = tff.datetime.dates_from_year_month_day(year, month, day)
  valuation_date = [(2020, 1, 1)]
  expiry_times = tff.datetime.daycount_actual_365_fixed(
      start_date=valuation_date, end_date=expiries, dtype=dtype)
  strikes = dim * [[[0.1, 0.9, 1.0, 1.1, 3], [0.1, 0.9, 1.0, 1.1, 3]]]
  iv = dim * [[[0.135, 0.13, 0.1, 0.11, 0.13],
               [0.135, 0.13, 0.1, 0.11, 0.13]]]
  spot = dim * [1.0]
  risk_free_rate = [0.02]
  r = tf.convert_to_tensor(risk_free_rate, dtype=dtype)
  df = lambda t: tf.math.exp(-r * t)
  
  lv = tff.models.LocalVolatilityModel.from_market_data(
      dim, val_date, expiries, strikes, iv, spot, df, [0.0], dtype=dtype)
  num_samples = 10000
  paths = lv.sample_paths(
      [1.0, 1.5, 2.0],
      num_samples=num_samples,
      initial_state=spot,
      time_step=0.1,
      random_type=tff.math.random.RandomType.STATELESS_ANTITHETIC,
      seed=[1, 2])
  # paths.shape = (10000, 3, 2)
  
  #### References:
    [1]: Iain J. Clark. Foreign exchange option pricing - A Practitioner's
    guide. Chapter 5, Section 5.3.2. 2011.
docstr: Initializes the Local volatility model.
  
  If `precompute_iv` is True and `times_grid` and `spot_grid` are supplied, an
  interpolated version that pre-computes spline coefficients is used.
  
  Args:
    dim: A Python scalar which corresponds to the number of underlying assets
      comprising the model.
    risk_free_rate: One of the following: (a) An optional real `Tensor` of
      shape compatible with `[dim]` specifying the (continuously compounded)
      risk free interest rate. (b) A python callable accepting one real
      `Tensor` argument time t returning a `Tensor` of shape compatible with
      `[dim]`. If the underlying is an FX rate, then use this input to specify
      the domestic interest rate.
      Default value: `None` in which case the input is set to Zero.
    dividend_yield: A real `Tensor` of shape compatible with `spot_price`
      specifying the (continuously compounded) dividend yield. If the
      underlying is an FX rate, then use this input to specify the foreign
      interest rate.
      Default value: `None` in which case the input is set to Zero.
    local_volatility_fn: A Python callable which returns instantaneous
      volatility as a function of state and time. The function must accept a
      scalar `Tensor` corresponding to time 't' and a real `Tensor` of shape
      `[num_samples, dim]` corresponding to the underlying price (S) as inputs
      and return a real `Tensor` of shape `[num_samples, dim]` containing the
      local volatility computed at (S,t).
    corr_matrix: A `Tensor` of shape `[dim, dim]` and the same `dtype` as
      `risk_free_rate`. Corresponds to the instantaneous correlation between
      the underlying assets.
    times_grid: A `Tensor` of shape `[num_time_samples]`. The grid on which to
      do interpolation over time. Must be jointly specified with `spot_grid`.
      Default value: `None`.
    spot_grid: A `Tensor` of shape `[num_spot_samples]`. The grid on which to
      do interpolation over spots. Must be jointly specified with
      `times_grid`.
      Default value: `None`.
    precompute_iv: A bool. Whether or not to precompute implied volatility
      spline coefficients when using Dupire. If True, then `times_grid` and
      `spot_grid` must be supplied.
      Default value: False.
    dtype: The default dtype to use when converting values to `Tensor`s.
      Default value: `None` which means that default dtypes inferred by
        TensorFlow are used.
    name: Python string. The name to give to the ops created by this class.
      Default value: `None` which maps to the default name
        `local_volatility_model`.
  
  Raises:
    ValueError: If `precompute_iv` is True, but grids are not supplied.
docstr_tok: ["Initializes","the","Local","volatility","model",".","If","`","precompute_iv","`","is","True","and","`","times_grid","`","and","`","spot_grid","`","are","supplied",",","an","interpolated","version","that","pre-computes","spline","coefficients","is","used",".","Args",":","dim",":","A","Python","scalar","which","corresponds","to","the","number","of","underlying","assets","comprising","the","model",".","risk_free_rate",":","One","of","the","following",":","(","a",")","An","optional","real","`","Tensor","`","of","shape","compatible","with","`","[","dim","]","`","specifying","the","(","continuously","compounded",")","risk","free","interest","rate",".","(","b",")","A","python","callable","accepting","one","real","`","Tensor","`","argument","time","t","returning","a","`","Tensor","`","of","shape","compatible","with","`","[","dim","]","`",".","If","the","underlying","is","an","FX","rate",",","then","use","this","input","to","specify","the","domestic","interest","rate",".","Default","value",":","`","None","`","in","which","case","the","input","is","set","to","Zero",".","dividend_yield",":","A","real","`","Tensor","`","of","shape","compatible","with","`","spot_price","`","specifying","the","(","continuously","compounded",")","dividend","yield",".","If","the","underlying","is","an","FX","rate",",","then","use","this","input","to","specify","the","foreign","interest","rate",".","Default","value",":","`","None","`","in","which","case","the","input","is","set","to","Zero",".","local_volatility_fn",":","A","Python","callable","which","returns","instantaneous","volatility","as","a","function","of","state","and","time",".","The","function","must","accept","a","scalar","`","Tensor","`","corresponding","to","time","'t","'","and","a","real","`","Tensor","`","of","shape","`","[","num_samples",",","dim","]","`","corresponding","to","the","underlying","price","(","S",")","as","inputs","and","return","a","real","`","Tensor","`","of","shape","`","[","num_samples",",","dim","]","`","containing","the","local","volatility","computed","at","(","S",",","t",")",".","corr_matrix",":","A","`","Tensor","`","of","shape","`","[","dim",",","dim","]","`","and","the","same","`","dtype","`","as","`","risk_free_rate","`",".","Corresponds","to","the","instantaneous","correlation","between","the","underlying","assets",".","times_grid",":","A","`","Tensor","`","of","shape","`","[","num_time_samples","]","`",".","The","grid","on","which","to","do","interpolation","over","time",".","Must","be","jointly","specified","with","`","spot_grid","`",".","Default","value",":","`","None","`",".","spot_grid",":","A","`","Tensor","`","of","shape","`","[","num_spot_samples","]","`",".","The","grid","on","which","to","do","interpolation","over","spots",".","Must","be","jointly","specified","with","`","times_grid","`",".","Default","value",":","`","None","`",".","precompute_iv",":","A","bool",".","Whether","or","not","to","precompute","implied","volatility","spline","coefficients","when","using","Dupire",".","If","True",",","then","`","times_grid","`","and","`","spot_grid","`","must","be","supplied",".","Default","value",":","False",".","dtype",":","The","default","dtype","to","use","when","converting","values","to","`","Tensor","`","s",".","Default","value",":","`","None","`","which","means","that","default","dtypes","inferred","by","TensorFlow","are","used",".","name",":","Python","string",".","The","name","to","give","to","the","ops","created","by","this","class",".","Default","value",":","`","None","`","which","maps","to","the","default","name","`","local_volatility_model","`",".","Raises",":","ValueError",":","If","`","precompute_iv","`","is","True",",","but","grids","are","not","supplied","."]
code: def __init__(
      self,
      dim: int,
      risk_free_rate: Optional[
          Union[types.RealTensor, Optional[types.RealTensor]]
      ] = None,
      dividend_yield: Optional[
          Union[types.RealTensor, Optional[types.RealTensor]]
      ] = None,
      local_volatility_fn: Optional[
          Callable[..., types.RealTensor]
      ] = None,
      corr_matrix: Optional[types.RealTensor] = None,
      times_grid: Optional[types.RealTensor] = None,
      spot_grid: Optional[types.RealTensor] = None,
      precompute_iv: Optional[bool] = False,
      dtype: Optional[tf.DType] = None,
      name: Optional[str] = None,
  ):
      """Initializes the Local volatility model.
  
      If `precompute_iv` is True and `times_grid` and `spot_grid` are supplied, an
      interpolated version that pre-computes spline coefficients is used.
  
      Args:
        dim: A Python scalar which corresponds to the number of underlying assets
          comprising the model.
        risk_free_rate: One of the following: (a) An optional real `Tensor` of
          shape compatible with `[dim]` specifying the (continuously compounded)
          risk free interest rate. (b) A python callable accepting one real
          `Tensor` argument time t returning a `Tensor` of shape compatible with
          `[dim]`. If the underlying is an FX rate, then use this input to specify
          the domestic interest rate.
          Default value: `None` in which case the input is set to Zero.
        dividend_yield: A real `Tensor` of shape compatible with `spot_price`
          specifying the (continuously compounded) dividend yield. If the
          underlying is an FX rate, then use this input to specify the foreign
          interest rate.
          Default value: `None` in which case the input is set to Zero.
        local_volatility_fn: A Python callable which returns instantaneous
          volatility as a function of state and time. The function must accept a
          scalar `Tensor` corresponding to time 't' and a real `Tensor` of shape
          `[num_samples, dim]` corresponding to the underlying price (S) as inputs
          and return a real `Tensor` of shape `[num_samples, dim]` containing the
          local volatility computed at (S,t).
        corr_matrix: A `Tensor` of shape `[dim, dim]` and the same `dtype` as
          `risk_free_rate`. Corresponds to the instantaneous correlation between
          the underlying assets.
        times_grid: A `Tensor` of shape `[num_time_samples]`. The grid on which to
          do interpolation over time. Must be jointly specified with `spot_grid`.
          Default value: `None`.
        spot_grid: A `Tensor` of shape `[num_spot_samples]`. The grid on which to
          do interpolation over spots. Must be jointly specified with
          `times_grid`.
          Default value: `None`.
        precompute_iv: A bool. Whether or not to precompute implied volatility
          spline coefficients when using Dupire. If True, then `times_grid` and
          `spot_grid` must be supplied.
          Default value: False.
        dtype: The default dtype to use when converting values to `Tensor`s.
          Default value: `None` which means that default dtypes inferred by
            TensorFlow are used.
        name: Python string. The name to give to the ops created by this class.
          Default value: `None` which maps to the default name
            `local_volatility_model`.
  
      Raises:
        ValueError: If `precompute_iv` is True, but grids are not supplied.
      """
      self._name = name or "local_volatility_model"
      self._times_grid = None
      self._local_volatility_fn = local_volatility_fn
      # Mark that we're using the interpolated version.
      self._precompute_iv = precompute_iv
      if precompute_iv:
          if times_grid is None or spot_grid is None:
              raise ValueError(
                  "When `precompute_iv` is True, both `times_grid` and `spot_grid` "
                  "must be supplied"
              )
          self._times_grid = times_grid
  
      with tf.name_scope(self._name):
          self._dtype = dtype
          risk_free_rate = (
              [0.0] if risk_free_rate is None else risk_free_rate
          )
          dividend_yield = (
              [0.0] if dividend_yield is None else dividend_yield
          )
  
          self._domestic_rate = _convert_to_tensor_fn(
              risk_free_rate, dtype, "risk_free_rate"
          )
          self._foreign_rate = _convert_to_tensor_fn(
              dividend_yield, dtype, "dividend_yield"
          )
  
          corr_matrix = corr_matrix or tf.eye(
              dim, dim, dtype=self._dtype
          )
          self._rho = tf.convert_to_tensor(
              corr_matrix, dtype=self._dtype, name="rho"
          )
          self._sqrt_rho = tf.linalg.cholesky(self._rho)
  
          # TODO(b/173286140): Simulate using X(t)=log(S(t))
          def _vol_fn(t, log_spot):
              """Volatility function of LV model."""
              lv = self._local_volatility_fn(t, tf.math.exp(log_spot))
              lv = tf.expand_dims(lv, axis=-1)
              return lv * self._sqrt_rho
  
          # Drift function
          def _drift_fn(t, log_spot):
              """Drift function of LV model."""
              domestic_rate = self._domestic_rate(t)
              foreign_rate = self._foreign_rate(t)
              lv = self._local_volatility_fn(t, tf.math.exp(log_spot))
              return domestic_rate - foreign_rate - lv * lv / 2
  
          super(LocalVolatilityModel, self).__init__(
              dim, _drift_fn, _vol_fn, dtype, name
          )
  
imports: import functools
  from typing import Any, Callable, List, Optional, Union
  import tensorflow.compat.v2
  from tf_quant_finance import black_scholes
  from tf_quant_finance import datetime
  from tf_quant_finance import math
  from tf_quant_finance import types
  from tf_quant_finance.experimental.pricing_platform.framework.market_data import volatility_surface
  from tf_quant_finance.math import interpolation
  from tf_quant_finance.math import piecewise
  from tf_quant_finance.math import random
  from tf_quant_finance.models import generic_ito_process
label_desc: Use image node_id 1 to create a new LocalVolatilityModel object from inherited base classes: generic_ito_process with example: obj = LocalVolatilityModel(dim, risk_free_rate, dividend_yield, local_volatility_fn, corr_matrix, times_grid, spot_grid, precompute_iv, dtype, name)