code: def test_fit_ml_model_with_h_mat():
      """Tests the output of `fit_ml_model` and function `get_h_mat` for different scenarios."""
  
      def helper_test_h_mat(
          const_val, remove_intercept, fit_algorithm, normalize_method
      ):
          # Does not require a seed since tests only check the correctness / consistency.
          n_total = 150
          X = np.random.rand(n_total, 3)
          X = np.concatenate(
              [const_val * np.ones((n_total, 1)), X], axis=1
          )
          beta = np.ones((X.shape[1], 1))
          y = (
              X @ beta
              + 1
              + np.random.normal(0, 1, n_total).reshape(-1, 1)
          )
          X_train = X[:100, :]
          y_train = y[:100, :]
  
          df = pd.DataFrame(
              np.concatenate([y_train, X_train], axis=1),
              columns=["y", "const", "a", "b", "c"],
          )
          model_formula_str = "y~const+a+b+c"
  
          uncertainty_dict = {
              "uncertainty_method": "simple_conditional_residuals",
              "params": {
                  "conditional_cols": [],
                  "quantiles": [0.025, 0.975],
                  "quantile_estimation_method": "normal_fit",
                  "sample_size_thresh": 5,
                  "small_sample_size_method": "std_quantiles",
                  "small_sample_size_quantile": 0.98,
              },
          }
  
          remove_intercept = remove_intercept
          model = fit_ml_model(
              df=df,
              model_formula_str=model_formula_str,
              fit_algorithm=fit_algorithm,
              fit_algorithm_params=None,
              uncertainty_dict=uncertainty_dict,
              normalize_method=normalize_method,
              regression_weight_col=None,
              remove_intercept=remove_intercept,
          )
  
          ml_model = model["ml_model"]
          # Prepares different versions of X matrix.
          X_mat = np.array(model["x_mat"])
          X_centered = X_mat - X_mat.mean(axis=0)
          y_centered = y_train - y.mean()
          ci_model = model["uncertainty_model"]
          L = ci_model["lu_d_sqrt"]
          p_effective = model["p_effective"]
          alpha = ml_model.alpha_ if fit_algorithm == "ridge" else 0
          # Calls `get_h_mat` with different X to compute H matrix.
          H = (
              get_h_mat(X_centered, alpha)
              if fit_algorithm == "ridge"
              else get_h_mat(X_mat, alpha)
          )
  
          if fit_algorithm == "linear":
              # Tests beta_hat.
              expected_beta_hat = np.array(ml_model.params).reshape(
                  -1, 1
              )  # No additional intercept.
              beta_hat = H @ y_train
              assert_equal(X_mat @ expected_beta_hat, X_mat @ beta_hat)
  
              # Tests the decomposition of the H matrix.
              assert np.linalg.norm(H @ H.T - L @ L.T) < 1e-8
  
              # Tests `p_effective`.
              assert_equal(p_effective, np.linalg.matrix_rank(X_mat))
  
              # Tests the values in `ci_model`.
              assert ci_model["n_train"] is not None
              assert ci_model["x_train_mean"] is None
              assert (ci_model["pi_se_scaler"] >= 1).all()
  
          if fit_algorithm == "ridge":
              # Tests beta hat.
              # Using `y_centered` or `y_train` should give the same result,
              # because `H @ (y_train - y_centered) = 0`.
              assert_equal(ml_model.coef_, (H @ y_centered).reshape(-1))
              assert_equal(ml_model.coef_, (H @ y_train).reshape(-1))
  
              # Tests intercept.
              beta_hat = H @ y_centered
              assert_equal(
                  ml_model.intercept_,
                  (y_train - X_mat @ beta_hat).mean(),
              )
  
              # Tests the decomposition of the H matrix.
              assert np.linalg.norm(H @ H.T - L @ L.T) < 1e-8
  
              # Tests `p_effective`.
              assert_equal(p_effective, np.trace(H @ X_centered) + 1)
  
              # Tests the values in `ci_model`.
              assert ci_model["n_train"] is not None
              assert ci_model["x_train_mean"] is not None
              assert (ci_model["pi_se_scaler"] >= 1).all()
  
      for const_val in [0, 1, 2]:
          for remove_intercept in [True, False]:
              for fit_algorithm in ["linear", "ridge"]:
                  for normalize_method in [
                      "zero_to_one",
                      "statistical",
                      "minus_half_to_half",
                      "zero_at_origin",
                  ]:
                      helper_test_h_mat(
                          const_val,
                          remove_intercept,
                          fit_algorithm,
                          normalize_method,
                      )
  
imports: import warnings
  import numpy
  import pandas
  import pytest
  import scipy
  from pandas.testing import assert_frame_equal
  from patsy import dmatrices
  from greykite.algo.common.ml_models import breakdown_regression_based_prediction
  from greykite.algo.common.ml_models import design_mat_from_formula
  from greykite.algo.common.ml_models import fit_ml_model
  from greykite.algo.common.ml_models import fit_ml_model_with_evaluation
  from greykite.algo.common.ml_models import fit_model_via_design_matrix
  from greykite.algo.common.ml_models import get_h_mat
  from greykite.algo.common.ml_models import get_intercept_col_from_design_mat
  from greykite.algo.common.ml_models import predict_ml
  from greykite.algo.common.ml_models import predict_ml_with_uncertainty
  from greykite.algo.uncertainty.conditional.conf_interval import predict_ci
  from greykite.common.constants import ERR_STD_COL
  from greykite.common.constants import QUANTILE_SUMMARY_COL
  from greykite.common.constants import TimeFeaturesEnum
  from greykite.common.evaluation import EvaluationMetricEnum
  from greykite.common.evaluation import calc_pred_err
  from greykite.common.features.timeseries_features import build_time_features_df
  from greykite.common.features.timeseries_features import fourier_series_multi_fcn
  from greykite.common.features.timeseries_features import get_fourier_col_name
  from greykite.common.python_utils import assert_equal
  from greykite.common.testing_utils import gen_sliced_df
label_desc: Use image node_id 28 for calling a global function with example usage: test_fit_ml_model_with_h_mat() without return types