class_docstr: Linear Mixed Effects Model
  
  Parameters
  ----------
  endog : 1d array_like
      The dependent variable
  exog : 2d array_like
      A matrix of covariates used to determine the
      mean structure (the "fixed effects" covariates).
  groups : 1d array_like
      A vector of labels determining the groups -- data from
      different groups are independent
  exog_re : 2d array_like
      A matrix of covariates used to determine the variance and
      covariance structure (the "random effects" covariates).  If
      None, defaults to a random intercept for each group.
  exog_vc : VCSpec instance or dict-like (deprecated)
      A VCSPec instance defines the structure of the variance
      components in the model.  Alternatively, see notes below
      for a dictionary-based format.  The dictionary format is
      deprecated and may be removed at some point in the future.
  use_sqrt : bool
      If True, optimization is carried out using the lower
      triangle of the square root of the random effects
      covariance matrix, otherwise it is carried out using the
      lower triangle of the random effects covariance matrix.
  missing : str
      The approach to missing data handling
  
  Notes
  -----
  If `exog_vc` is not a `VCSpec` instance, then it must be a
  dictionary of dictionaries.  Specifically, `exog_vc[a][g]` is a
  matrix whose columns are linearly combined using independent
  random coefficients.  This random term then contributes to the
  variance structure of the data for group `g`.  The random
  coefficients all have mean zero, and have the same variance.  The
  matrix must be `m x k`, where `m` is the number of observations in
  group `g`.  The number of columns may differ among the top-level
  groups.
  
  The covariates in `exog`, `exog_re` and `exog_vc` may (but need
  not) partially or wholly overlap.
  
  `use_sqrt` should almost always be set to True.  The main use case
  for use_sqrt=False is when complicated patterns of fixed values in
  the covariance structure are set (using the `free` argument to
  `fit`) that cannot be expressed in terms of the Cholesky factor L.
  
  Examples
  --------
  A basic mixed model with fixed effects for the columns of
  ``exog`` and a random intercept for each distinct value of
  ``group``:
  
  >>> model = sm.MixedLM(endog, exog, groups)
  >>> result = model.fit()
  
  A mixed model with fixed effects for the columns of ``exog`` and
  correlated random coefficients for the columns of ``exog_re``:
  
  >>> model = sm.MixedLM(endog, exog, groups, exog_re=exog_re)
  >>> result = model.fit()
  
  A mixed model with fixed effects for the columns of ``exog`` and
  independent random coefficients for the columns of ``exog_re``:
  
  >>> free = MixedLMParams.from_components(
                   fe_params=np.ones(exog.shape[1]),
                   cov_re=np.eye(exog_re.shape[1]))
  >>> model = sm.MixedLM(endog, exog, groups, exog_re=exog_re)
  >>> result = model.fit(free=free)
  
  A different way to specify independent random coefficients for the
  columns of ``exog_re``.  In this example ``groups`` must be a
  Pandas Series with compatible indexing with ``exog_re``, and
  ``exog_re`` has two columns.
  
  >>> g = pd.groupby(groups, by=groups).groups
  >>> vc = {}
  >>> vc['1'] = {k : exog_re.loc[g[k], 0] for k in g}
  >>> vc['2'] = {k : exog_re.loc[g[k], 1] for k in g}
  >>> model = sm.MixedLM(endog, exog, groups, vcomp=vc)
  >>> result = model.fit()
class_docstr_tok: ["Linear","Mixed","Effects","Model","Parameters","--","--","--","--","--","endog",":","1d","array_like","The","dependent","variable","exog",":","2d","array_like","A","matrix","of","covariates","used","to","determine","the","mean","structure","(","the","``","fixed","effects","''","covariates",")",".","groups",":","1d","array_like","A","vector","of","labels","determining","the","groups","--","data","from","different","groups","are","independent","exog_re",":","2d","array_like","A","matrix","of","covariates","used","to","determine","the","variance","and","covariance","structure","(","the","``","random","effects","''","covariates",")",".","If","None",",","defaults","to","a","random","intercept","for","each","group",".","exog_vc",":","VCSpec","instance","or","dict-like","(","deprecated",")","A","VCSPec","instance","defines","the","structure","of","the","variance","components","in","the","model",".","Alternatively",",","see","notes","below","for","a","dictionary-based","format",".","The","dictionary","format","is","deprecated","and","may","be","removed","at","some","point","in","the","future",".","use_sqrt",":","bool","If","True",",","optimization","is","carried","out","using","the","lower","triangle","of","the","square","root","of","the","random","effects","covariance","matrix",",","otherwise","it","is","carried","out","using","the","lower","triangle","of","the","random","effects","covariance","matrix",".","missing",":","str","The","approach","to","missing","data","handling","Notes","--","--","-","If","`","exog_vc","`","is","not","a","`","VCSpec","`","instance",",","then","it","must","be","a","dictionary","of","dictionaries",".","Specifically",",","`","exog_vc","[","a","]","[","g","]","`","is","a","matrix","whose","columns","are","linearly","combined","using","independent","random","coefficients",".","This","random","term","then","contributes","to","the","variance","structure","of","the","data","for","group","`","g","`",".","The","random","coefficients","all","have","mean","zero",",","and","have","the","same","variance",".","The","matrix","must","be","`","m","x","k","`",",","where","`","m","`","is","the","number","of","observations","in","group","`","g","`",".","The","number","of","columns","may","differ","among","the","top-level","groups",".","The","covariates","in","`","exog","`",",","`","exog_re","`","and","`","exog_vc","`","may","(","but","need","not",")","partially","or","wholly","overlap",".","`","use_sqrt","`","should","almost","always","be","set","to","True",".","The","main","use","case","for","use_sqrt=False","is","when","complicated","patterns","of","fixed","values","in","the","covariance","structure","are","set","(","using","the","`","free","`","argument","to","`","fit","`",")","that","can","not","be","expressed","in","terms","of","the","Cholesky","factor","L.","Examples","--","--","--","--","A","basic","mixed","model","with","fixed","effects","for","the","columns","of","``","exog","``","and","a","random","intercept","for","each","distinct","value","of","``","group","``",":",">",">",">","model","=","sm.MixedLM","(","endog",",","exog",",","groups",")",">",">",">","result","=","model.fit","(",")","A","mixed","model","with","fixed","effects","for","the","columns","of","``","exog","``","and","correlated","random","coefficients","for","the","columns","of","``","exog_re","``",":",">",">",">","model","=","sm.MixedLM","(","endog",",","exog",",","groups",",","exog_re=exog_re",")",">",">",">","result","=","model.fit","(",")","A","mixed","model","with","fixed","effects","for","the","columns","of","``","exog","``","and","independent","random","coefficients","for","the","columns","of","``","exog_re","``",":",">",">",">","free","=","MixedLMParams.from_components","(","fe_params=np.ones","(","exog.shape","[","1","]",")",",","cov_re=np.eye","(","exog_re.shape","[","1","]",")",")",">",">",">","model","=","sm.MixedLM","(","endog",",","exog",",","groups",",","exog_re=exog_re",")",">",">",">","result","=","model.fit","(","free=free",")","A","different","way","to","specify","independent","random","coefficients","for","the","columns","of","``","exog_re","``",".","In","this","example","``","groups","``","must","be","a","Pandas","Series","with","compatible","indexing","with","``","exog_re","``",",","and","``","exog_re","``","has","two","columns",".",">",">",">","g","=","pd.groupby","(","groups",",","by=groups",")",".groups",">",">",">","vc","=","{","}",">",">",">","vc","[","'","1","'","]","=","{","k",":","exog_re.loc","[","g","[","k","]",",","0","]","for","k","in","g","}",">",">",">","vc","[","'","2","'","]","=","{","k",":","exog_re.loc","[","g","[","k","]",",","1","]","for","k","in","g","}",">",">",">","model","=","sm.MixedLM","(","endog",",","exog",",","groups",",","vcomp=vc",")",">",">",">","result","=","model.fit","(",")"]
docstr: Create a Model from a formula and dataframe.
  
  Parameters
  ----------
  formula : str or generic Formula object
      The formula specifying the model
  data : array_like
      The data for the model. See Notes.
  re_formula : str
      A one-sided formula defining the variance structure of the
      model.  The default gives a random intercept for each
      group.
  vc_formula : dict-like
      Formulas describing variance components.  `vc_formula[vc]` is
      the formula for the component with variance parameter named
      `vc`.  The formula is processed into a matrix, and the columns
      of this matrix are linearly combined with independent random
      coefficients having mean zero and a common variance.
  subset : array_like
      An array-like object of booleans, integers, or index
      values that indicate the subset of df to use in the
      model. Assumes df is a `pandas.DataFrame`
  missing : str
      Either 'none' or 'drop'
  args : extra arguments
      These are passed to the model
  kwargs : extra keyword arguments
      These are passed to the model with one exception. The
      ``eval_env`` keyword is passed to patsy. It can be either a
      :class:`patsy:patsy.EvalEnvironment` object or an integer
      indicating the depth of the namespace to use. For example, the
      default ``eval_env=0`` uses the calling namespace. If you wish
      to use a "clean" environment set ``eval_env=-1``.
  
  Returns
  -------
  model : Model instance
  
  Notes
  -----
  `data` must define __getitem__ with the keys in the formula
  terms args and kwargs are passed on to the model
  instantiation. E.g., a numpy structured or rec array, a
  dictionary, or a pandas DataFrame.
  
  If the variance component is intended to produce random
  intercepts for disjoint subsets of a group, specified by
  string labels or a categorical data value, always use '0 +' in
  the formula so that no overall intercept is included.
  
  If the variance components specify random slopes and you do
  not also want a random group-level intercept in the model,
  then use '0 +' in the formula to exclude the intercept.
  
  The variance components formulas are processed separately for
  each group.  If a variable is categorical the results will not
  be affected by whether the group labels are distinct or
  re-used over the top-level groups.
  
  Examples
  --------
  Suppose we have data from an educational study with students
  nested in classrooms nested in schools.  The students take a
  test, and we want to relate the test scores to the students'
  ages, while accounting for the effects of classrooms and
  schools.  The school will be the top-level group, and the
  classroom is a nested group that is specified as a variance
  component.  Note that the schools may have different number of
  classrooms, and the classroom labels may (but need not be)
  different across the schools.
  
  >>> vc = {'classroom': '0 + C(classroom)'}
  >>> MixedLM.from_formula('test_score ~ age', vc_formula=vc,                                   re_formula='1', groups='school', data=data)
  
  Now suppose we also have a previous test score called
  'pretest'.  If we want the relationship between pretest
  scores and the current test to vary by classroom, we can
  specify a random slope for the pretest score
  
  >>> vc = {'classroom': '0 + C(classroom)', 'pretest': '0 + pretest'}
  >>> MixedLM.from_formula('test_score ~ age + pretest', vc_formula=vc,                                   re_formula='1', groups='school', data=data)
  
  The following model is almost equivalent to the previous one,
  but here the classroom random intercept and pretest slope may
  be correlated.
  
  >>> vc = {'classroom': '0 + C(classroom)'}
  >>> MixedLM.from_formula('test_score ~ age + pretest', vc_formula=vc,                                   re_formula='1 + pretest', groups='school',                                   data=data)
docstr_tok: ["Create","a","Model","from","a","formula","and","dataframe",".","Parameters","--","--","--","--","--","formula",":","str","or","generic","Formula","object","The","formula","specifying","the","model","data",":","array_like","The","data","for","the","model",".","See","Notes",".","re_formula",":","str","A","one-sided","formula","defining","the","variance","structure","of","the","model",".","The","default","gives","a","random","intercept","for","each","group",".","vc_formula",":","dict-like","Formulas","describing","variance","components",".","`","vc_formula","[","vc","]","`","is","the","formula","for","the","component","with","variance","parameter","named","`","vc","`",".","The","formula","is","processed","into","a","matrix",",","and","the","columns","of","this","matrix","are","linearly","combined","with","independent","random","coefficients","having","mean","zero","and","a","common","variance",".","subset",":","array_like","An","array-like","object","of","booleans",",","integers",",","or","index","values","that","indicate","the","subset","of","df","to","use","in","the","model",".","Assumes","df","is","a","`","pandas.DataFrame","`","missing",":","str","Either","'none","'","or","'drop'","args",":","extra","arguments","These","are","passed","to","the","model","kwargs",":","extra","keyword","arguments","These","are","passed","to","the","model","with","one","exception",".","The","``","eval_env","``","keyword","is","passed","to","patsy",".","It","can","be","either","a",":","class",":","`","patsy",":","patsy.EvalEnvironment","`","object","or","an","integer","indicating","the","depth","of","the","namespace","to","use",".","For","example",",","the","default","``","eval_env=0","``","uses","the","calling","namespace",".","If","you","wish","to","use","a","``","clean","''","environment","set","``","eval_env=-1","``",".","Returns","--","--","--","-","model",":","Model","instance","Notes","--","--","-","`","data","`","must","define","__getitem__","with","the","keys","in","the","formula","terms","args","and","kwargs","are","passed","on","to","the","model","instantiation",".","E.g.",",","a","numpy","structured","or","rec","array",",","a","dictionary",",","or","a","pandas","DataFrame",".","If","the","variance","component","is","intended","to","produce","random","intercepts","for","disjoint","subsets","of","a","group",",","specified","by","string","labels","or","a","categorical","data","value",",","always","use","'","0","+","'","in","the","formula","so","that","no","overall","intercept","is","included",".","If","the","variance","components","specify","random","slopes","and","you","do","not","also","want","a","random","group-level","intercept","in","the","model",",","then","use","'","0","+","'","in","the","formula","to","exclude","the","intercept",".","The","variance","components","formulas","are","processed","separately","for","each","group",".","If","a","variable","is","categorical","the","results","will","not","be","affected","by","whether","the","group","labels","are","distinct","or","re-used","over","the","top-level","groups",".","Examples","--","--","--","--","Suppose","we","have","data","from","an","educational","study","with","students","nested","in","classrooms","nested","in","schools",".","The","students","take","a","test",",","and","we","want","to","relate","the","test","scores","to","the","students'","ages",",","while","accounting","for","the","effects","of","classrooms","and","schools",".","The","school","will","be","the","top-level","group",",","and","the","classroom","is","a","nested","group","that","is","specified","as","a","variance","component",".","Note","that","the","schools","may","have","different","number","of","classrooms",",","and","the","classroom","labels","may","(","but","need","not","be",")","different","across","the","schools",".",">",">",">","vc","=","{","'classroom","'",":","'","0","+","C","(","classroom",")","'","}",">",">",">","MixedLM.from_formula","(","'test_score","~","age","'",",","vc_formula=vc",",","re_formula=","'","1","'",",","groups='school","'",",","data=data",")","Now","suppose","we","also","have","a","previous","test","score","called","'pretest","'",".","If","we","want","the","relationship","between","pretest","scores","and","the","current","test","to","vary","by","classroom",",","we","can","specify","a","random","slope","for","the","pretest","score",">",">",">","vc","=","{","'classroom","'",":","'","0","+","C","(","classroom",")","'",",","'pretest","'",":","'","0","+","pretest","'","}",">",">",">","MixedLM.from_formula","(","'test_score","~","age","+","pretest","'",",","vc_formula=vc",",","re_formula=","'","1","'",",","groups='school","'",",","data=data",")","The","following","model","is","almost","equivalent","to","the","previous","one",",","but","here","the","classroom","random","intercept","and","pretest","slope","may","be","correlated",".",">",">",">","vc","=","{","'classroom","'",":","'","0","+","C","(","classroom",")","'","}",">",">",">","MixedLM.from_formula","(","'test_score","~","age","+","pretest","'",",","vc_formula=vc",",","re_formula=","'","1","+","pretest","'",",","groups='school","'",",","data=data",")"]
code: def from_formula(
      cls,
      formula,
      data,
      re_formula=None,
      vc_formula=None,
      subset=None,
      use_sparse=False,
      missing="none",
      *args,
      **kwargs,
  ):
      """
          Create a Model from a formula and dataframe.
  
          Parameters
          ----------
          formula : str or generic Formula object
              The formula specifying the model
          data : array_like
              The data for the model. See Notes.
          re_formula : str
              A one-sided formula defining the variance structure of the
              model.  The default gives a random intercept for each
              group.
          vc_formula : dict-like
              Formulas describing variance components.  `vc_formula[vc]` is
              the formula for the component with variance parameter named
              `vc`.  The formula is processed into a matrix, and the columns
              of this matrix are linearly combined with independent random
              coefficients having mean zero and a common variance.
          subset : array_like
              An array-like object of booleans, integers, or index
              values that indicate the subset of df to use in the
              model. Assumes df is a `pandas.DataFrame`
          missing : str
              Either 'none' or 'drop'
          args : extra arguments
              These are passed to the model
          kwargs : extra keyword arguments
              These are passed to the model with one exception. The
              ``eval_env`` keyword is passed to patsy. It can be either a
              :class:`patsy:patsy.EvalEnvironment` object or an integer
              indicating the depth of the namespace to use. For example, the
              default ``eval_env=0`` uses the calling namespace. If you wish
              to use a "clean" environment set ``eval_env=-1``.
  
          Returns
          -------
          model : Model instance
  
          Notes
          -----
          `data` must define __getitem__ with the keys in the formula
          terms args and kwargs are passed on to the model
          instantiation. E.g., a numpy structured or rec array, a
          dictionary, or a pandas DataFrame.
  
          If the variance component is intended to produce random
          intercepts for disjoint subsets of a group, specified by
          string labels or a categorical data value, always use '0 +' in
          the formula so that no overall intercept is included.
  
          If the variance components specify random slopes and you do
          not also want a random group-level intercept in the model,
          then use '0 +' in the formula to exclude the intercept.
  
          The variance components formulas are processed separately for
          each group.  If a variable is categorical the results will not
          be affected by whether the group labels are distinct or
          re-used over the top-level groups.
  
          Examples
          --------
          Suppose we have data from an educational study with students
          nested in classrooms nested in schools.  The students take a
          test, and we want to relate the test scores to the students'
          ages, while accounting for the effects of classrooms and
          schools.  The school will be the top-level group, and the
          classroom is a nested group that is specified as a variance
          component.  Note that the schools may have different number of
          classrooms, and the classroom labels may (but need not be)
          different across the schools.
  
          >>> vc = {'classroom': '0 + C(classroom)'}
          >>> MixedLM.from_formula('test_score ~ age', vc_formula=vc, \
                                    re_formula='1', groups='school', data=data)
  
          Now suppose we also have a previous test score called
          'pretest'.  If we want the relationship between pretest
          scores and the current test to vary by classroom, we can
          specify a random slope for the pretest score
  
          >>> vc = {'classroom': '0 + C(classroom)', 'pretest': '0 + pretest'}
          >>> MixedLM.from_formula('test_score ~ age + pretest', vc_formula=vc, \
                                    re_formula='1', groups='school', data=data)
  
          The following model is almost equivalent to the previous one,
          but here the classroom random intercept and pretest slope may
          be correlated.
  
          >>> vc = {'classroom': '0 + C(classroom)'}
          >>> MixedLM.from_formula('test_score ~ age + pretest', vc_formula=vc, \
                                    re_formula='1 + pretest', groups='school', \
                                    data=data)
          """
  
      if "groups" not in kwargs.keys():
          raise AttributeError(
              "'groups' is a required keyword argument "
              + "in MixedLM.from_formula"
          )
      groups = kwargs["groups"]
  
      # If `groups` is a variable name, retrieve the data for the
      # groups variable.
      group_name = "Group"
      if isinstance(groups, str):
          group_name = groups
          groups = np.asarray(data[groups])
      else:
          groups = np.asarray(groups)
      del kwargs["groups"]
  
      # Bypass all upstream missing data handling to properly handle
      # variance components
      if missing == "drop":
          data, groups = _handle_missing(
              data, groups, formula, re_formula, vc_formula
          )
          missing = "none"
  
      if re_formula is not None:
          if re_formula.strip() == "1":
              # Work around Patsy bug, fixed by 0.3.
              exog_re = np.ones((data.shape[0], 1))
              exog_re_names = [group_name]
          else:
              eval_env = kwargs.get("eval_env", None)
              if eval_env is None:
                  eval_env = 1
              elif eval_env == -1:
                  from patsy import EvalEnvironment
  
                  eval_env = EvalEnvironment({})
              exog_re = patsy.dmatrix(
                  re_formula, data, eval_env=eval_env
              )
              exog_re_names = exog_re.design_info.column_names
              exog_re_names = [
                  x.replace("Intercept", group_name)
                  for x in exog_re_names
              ]
              exog_re = np.asarray(exog_re)
          if exog_re.ndim == 1:
              exog_re = exog_re[:, None]
      else:
          exog_re = None
          if vc_formula is None:
              exog_re_names = [group_name]
          else:
              exog_re_names = []
  
      if vc_formula is not None:
          eval_env = kwargs.get("eval_env", None)
          if eval_env is None:
              eval_env = 1
          elif eval_env == -1:
              from patsy import EvalEnvironment
  
              eval_env = EvalEnvironment({})
  
          vc_mats = []
          vc_colnames = []
          vc_names = []
          gb = data.groupby(groups)
          kylist = sorted(gb.groups.keys())
          vcf = sorted(vc_formula.keys())
          for vc_name in vcf:
              md = patsy.ModelDesc.from_formula(vc_formula[vc_name])
              vc_names.append(vc_name)
              evc_mats, evc_colnames = [], []
              for group_ix, group in enumerate(kylist):
                  ii = gb.groups[group]
                  mat = patsy.dmatrix(
                      md,
                      data.loc[ii, :],
                      eval_env=eval_env,
                      return_type="dataframe",
                  )
                  evc_colnames.append(mat.columns.tolist())
                  if use_sparse:
                      evc_mats.append(sparse.csr_matrix(mat))
                  else:
                      evc_mats.append(np.asarray(mat))
              vc_mats.append(evc_mats)
              vc_colnames.append(evc_colnames)
          exog_vc = VCSpec(vc_names, vc_colnames, vc_mats)
      else:
          exog_vc = VCSpec([], [], [])
  
      kwargs["subset"] = None
      kwargs["exog_re"] = exog_re
      kwargs["exog_vc"] = exog_vc
      kwargs["groups"] = groups
      mod = super().from_formula(formula, data, *args, **kwargs)
  
      # expand re names to account for pairs of RE
      (
          param_names,
          exog_re_names,
          exog_re_names_full,
      ) = mod._make_param_names(exog_re_names)
  
      mod.data.param_names = param_names
      mod.data.exog_re_names = exog_re_names
      mod.data.exog_re_names_full = exog_re_names_full
  
      if vc_formula is not None:
          mod.data.vcomp_names = mod.exog_vc.names
  
      return mod
  
imports: import warnings
  import numpy
  import pandas
  import patsy
  from scipy import sparse
  from scipy.stats.distributions import norm
  from statsmodels.base._penalties import Penalty
  import statsmodels.base.model
  from statsmodels.tools import data
  from statsmodels.tools.decorators import cache_readonly
  from statsmodels.tools.sm_exceptions import ConvergenceWarning
label_desc: Use image node_id 3 for calling the MixedLM obj's underlying member method code with example usage: obj.from_formula(cls, formula, data, re_formula, vc_formula, subset, use_sparse, missing) and returns: mod