code: def power_divergence(
      X, Y, Z, data, boolean=True, lambda_="cressie-read", **kwargs
  ):
      """
      Computes the Cressie-Read power divergence statistic [1]. The null hypothesis
      for the test is X is independent of Y given Z. A lot of the frequency comparision
      based statistics (eg. chi-square, G-test etc) belong to power divergence family,
      and are special cases of this test.
  
      Parameters
      ----------
      X: int, string, hashable object
          A variable name contained in the data set
  
      Y: int, string, hashable object
          A variable name contained in the data set, different from X
  
      Z: list, array-like
          A list of variable names contained in the data set, different from X and Y.
          This is the separating set that (potentially) makes X and Y independent.
          Default: []
  
      data: pandas.DataFrame
          The dataset on which to test the independence condition.
  
      lambda_: float or string
          The lambda parameter for the power_divergence statistic. Some values of
          lambda_ results in other well known tests:
              "pearson"             1          "Chi-squared test"
              "log-likelihood"      0          "G-test or log-likelihood"
              "freeman-tuckey"     -1/2        "Freeman-Tuckey Statistic"
              "mod-log-likelihood"  -1         "Modified Log-likelihood"
              "neyman"              -2         "Neyman's statistic"
              "cressie-read"        2/3        "The value recommended in the paper[1]"
  
      boolean: bool
          If boolean=True, an additional argument `significance_level` must
              be specified. If p_value of the test is greater than equal to
              `significance_level`, returns True. Otherwise returns False.
  
          If boolean=False, returns the chi2 and p_value of the test.
  
      Returns
      -------
      CI Test Results: tuple or bool
          If boolean = False, Returns a tuple (chi, p_value, dof). `chi` is the
          chi-squared test statistic. The `p_value` for the test, i.e. the
          probability of observing the computed chi-square statistic (or an even
          higher value), given the null hypothesis that X \u27C2 Y | Zs is True.
          If boolean = True, returns True if the p_value of the test is greater
          than `significance_level` else returns False.
  
      References
      ----------
      [1] Cressie, Noel, and Timothy RC Read. "Multinomial goodness‐of‐fit tests." Journal of the Royal Statistical Society: Series B (Methodological) 46.3 (1984): 440-464.
  
      Examples
      --------
      >>> import pandas as pd
      >>> import numpy as np
      >>> data = pd.DataFrame(np.random.randint(0, 2, size=(50000, 4)), columns=list('ABCD'))
      >>> data['E'] = data['A'] + data['B'] + data['C']
      >>> chi_square(X='A', Y='C', Z=[], data=data, boolean=True, significance_level=0.05)
      True
      >>> chi_square(X='A', Y='B', Z=['D'], data=data, boolean=True, significance_level=0.05)
      True
      >>> chi_square(X='A', Y='B', Z=['D', 'E'], data=data, boolean=True, significance_level=0.05)
      False
      """
  
      # Step 1: Check if the arguments are valid and type conversions.
      if hasattr(Z, "__iter__"):
          Z = list(Z)
      else:
          raise (f"Z must be an iterable. Got object type: {type(Z)}")
  
      if (X in Z) or (Y in Z):
          raise ValueError(
              f"The variables X or Y can't be in Z. Found {X if X in Z else Y} in Z."
          )
  
      # Step 2: Do a simple contingency test if there are no conditional variables.
      if len(Z) == 0:
          chi, p_value, dof, expected = stats.chi2_contingency(
              data.groupby([X, Y]).size().unstack(Y, fill_value=0),
              lambda_=lambda_,
          )
  
      # Step 3: If there are conditionals variables, iterate over unique states and do
      #         the contingency test.
      else:
          chi = 0
          dof = 0
          for z_state, df in data.groupby(Z):
              try:
                  c, _, d, _ = stats.chi2_contingency(
                      df.groupby([X, Y])
                      .size()
                      .unstack(Y, fill_value=0),
                      lambda_=lambda_,
                  )
                  chi += c
                  dof += d
              except ValueError:
                  # If one of the values is 0 in the 2x2 table.
                  if isinstance(z_state, str):
                      logger.info(
                          f"Skipping the test {X} \u27C2 {Y} | {Z[0]}={z_state}. Not enough samples"
                      )
                  else:
                      z_str = ", ".join(
                          [
                              f"{var}={state}"
                              for var, state in zip(Z, z_state)
                          ]
                      )
                      logger.info(
                          f"Skipping the test {X} \u27C2 {Y} | {z_str}. Not enough samples"
                      )
          p_value = 1 - stats.chi2.cdf(chi, df=dof)
  
      # Step 4: Return the values
      if boolean:
          return p_value >= kwargs["significance_level"]
      else:
          return chi, p_value, dof
  
file_path: pgmpy/pgmpy/estimators/CITests.py
imports: import numpy
  import pandas
  from scipy import stats
  from pgmpy.independencies import IndependenceAssertion
  from pgmpy.global_vars import logger
label_desc: Use image node_id 9 for calling a global function with example usage: power_divergence(X, Y, Z, data, boolean, lambda_) and returns: unknown, chi,  p_value,  dof