sem: structural equation models (semopy, lavaan)

The user guide of this module: sem.

apatools.sem.sem(data, formula, method=None, solver='SLSQP', bootstrap=None, se_robust=True, return_model=False, seed=13, engine='semopy', lavaan_args=None, rscript=None)[source]

Fit a structural equation model with semopy.

The model is specified in lavaan-like syntax, fitted with semopy.Model, optionally bias-corrected by a bootstrap, and returned as a parameter table together with the fit statistics. Pass both to sem_report() or sem_plot().

Parameters:
  • data (pandas.DataFrame) – Observed variables (one row per observation, columns named as in formula).

  • formula (str) – Model description in semopy syntax: =~ measurement part (latent =~ indicators), ~ structural part (regressions), ~~ (co)variances. Example: "eta1 =~ y1 + y2 + y3"; use one line per equation for several.

  • method (str, optional) – Estimator. engine="semopy" (objective function passed to semopy.Model.fit(obj=...)): "MLW" (Wishart maximum likelihood, the default), "ULS", "GLS", "FIML", "DWLS" or "WLS". engine="lavaan": the same names are translated ("MLW" and "FIML" to ML, the latter with missing="fiml") and any lavaan estimator can be given ("ML", the default, "MLR", "WLSMV", …).

  • solver (str, default "SLSQP") – Name of the scipy optimizer used to minimize the objective (engine="semopy" only).

  • bootstrap (int or falsy, optional) – engine="semopy" (default 100): if truthy, semopy.bias_correction(model, n=bootstrap, resample_mean=True) is applied after fitting. This replaces the parameter estimates by bias-corrected ones; use 0 to keep the plain estimates and to save time. engine="lavaan" (default 0): if truthy, lavaan computes bootstrap standard errors and p-values from that many resamples (the estimates themselves are not changed).

  • se_robust (bool, default True) – Report Huber-White robust standard errors (model.inspect(se_robust=...); with lavaan se="robust.huber.white", only for the ML estimator).

  • return_model (bool, default False) – Also return the fitted model: the semopy.Model, or for engine="lavaan" a LavaanFit (lavaan’s own parameter tables and fit measures, its version and warnings).

  • seed (int, default 13) – Seed for numpy’s global random generator (np.random.seed), which makes the bootstrap and the optimizer’s starting values reproducible. The global state is changed as a side effect. With lavaan it seeds R (set.seed).

  • engine ({"semopy", "lavaan"}, default "semopy") – "semopy" fits the model in Python. "lavaan" fits it with the R package lavaan (Rosseel, 2012) in an Rscript subprocess and returns the same tables, so that sem_report() and sem_plot() work with both. It needs R with the package lavaan (install.packages("lavaan")) and no further Python package.

  • lavaan_args (dict, optional) – Further arguments of lavaan::sem for engine="lavaan", for example {"std.lv": True, "ordered": ["x1", "x2"], "missing": "fiml"} (they override the arguments derived from method, se_robust and bootstrap).

  • rscript (str, optional) – Path of Rscript (engine="lavaan"); by default the environment variable APATOOLS_RSCRIPT, the PATH and the usual install locations are searched.

Returns:

  • stats (pandas.DataFrame) – (The columns are the same for both engines.) One row per model parameter with semopy’s inspect columns in lower case (lval, op, rval, estimate, std_err, z-value, p-value), the standardized estimate est_std and its standard error se_std, z-value z_std and p-value p_std (delta method, as in lavaan’s standardizedSolution(); the loadings that are fixed to 1 in the unstandardized solution have no p-value but do have a p_std). Entries semopy reports as "-" are converted to NaN. op is "~" for regressions and measurement paths (semopy does not distinguish them), "~~" for (co)variances. stats.attrs["latent"] is the sorted list of latent variables, which sem_plot() uses to draw latent variables as circles.

  • metrics (pandas.DataFrame) – Single column value, indexed by N (rows in data) followed by semopy’s fit statistics (DoF, chi2, chi2 p-value, CFI, GFI, AGFI, NFI, TLI, RMSEA, AIC, BIC, LogLik, …).

  • model (semopy.Model) – The fitted model; only if return_model is True.

Notes

Commonly used fit indices are CFI (Bentler, 1990), TLI (Tucker & Lewis, 1973) and RMSEA (Steiger & Lind, 1980; Browne & Cudeck, 1993). Hu and Bentler (1999) suggest CFI/TLI of about .95 or higher and RMSEA of about .06 or lower as indicators of good fit; these are rules of thumb, not tests. Robust standard errors follow the sandwich estimator of White (1980).

Requires the optional dependency semopy (pip install "apatools[sem]").

References

Igolkina, A. A., & Meshcheryakov, G. (2020). semopy: A Python package for structural equation modeling. Structural Equation Modeling: A Multidisciplinary Journal, 27(6), 952-963. https://doi.org/10.1080/10705511.2019.1704289

Bentler, P. M. (1990). Comparative fit indexes in structural models. Psychological Bulletin, 107(2), 238-246. https://doi.org/10.1037/0033-2909.107.2.238

Tucker, L. R., & Lewis, C. (1973). A reliability coefficient for maximum likelihood factor analysis. Psychometrika, 38(1), 1-10. https://doi.org/10.1007/bf02291170

Steiger, J. H., & Lind, J. C. (1980, May). Statistically based tests for the number of common factors [Paper presentation]. Annual meeting of the Psychometric Society, Iowa City, IA.

Browne, M. W., & Cudeck, R. (1993). Alternative ways of assessing model fit. In K. A. Bollen & J. S. Long (Eds.), Testing structural equation models. Sage.

Hu, L., & Bentler, P. M. (1999). Cutoff criteria for fit indexes in covariance structure analysis: Conventional criteria versus new alternatives. Structural Equation Modeling: A Multidisciplinary Journal, 6(1), 1-55. https://doi.org/10.1080/10705519909540118

White, H. (1980). A heteroskedasticity-consistent covariance matrix estimator and a direct test for heteroskedasticity. Econometrica, 48(4), 817-838. https://doi.org/10.2307/1912934

Examples

>>> stats, metrics = sem(df, "eta =~ y1 + y2 + y3", bootstrap=0)
>>> sem_report(stats, metrics)
apatools.sem.sem_report(stats, metrics, format_pval=True, add_stars=False, decimal=3)[source]

Format the output of sem() for reporting.

Parameters:
  • stats (pandas.DataFrame) – Parameter table returned by sem() (not modified; a copy is returned).

  • metrics (pandas.DataFrame) – Fit statistics returned by sem(). Must contain N, DoF, chi2 and chi2 p-value; the other statistics are looked up by name.

  • format_pval (bool or callable, default True) – Replace the p-value column by APA-formatted strings without the p prefix and without spaces (".009", "<.001", see apatools.format.format_p()). A callable receives one p-value; False keeps the numbers. When formatting, missing p-values become empty strings.

  • add_stars (bool or callable, default False) – Add a sig column with significance markers (apatools.format.get_stars() if True, or the callable). Stars are computed from the unformatted p-values.

  • decimal (int, default 3) – Number of decimals for the table and the fit summary; falsy skips rounding of the table.

Returns:

pandas.DataFrame – Copy of stats with formatted p-values, the optional sig column, rounded numbers and a new column model that is empty except for the first row, which holds the fit summary, e.g. "χ²(48, N = 500) = 303.8, p < .001, CFI = .9, TLI = .86, ..., RMSEA = 0.1". In it, CFI, GFI, AGFI, NFI and TLI are written without leading zero (APA style for values bounded by 1); the remaining statistics (RMSEA, AIC, BIC, LogLik, …) are reported as returned by semopy, rounded to decimal. Trailing zeros are not kept, since values are rounded as floats.

Notes

Because the fit summary is stored in the first row of stats, the table is meant for display or export (e.g. to a spreadsheet), not for further numerical work.

apatools.sem.sem_plot(stats, save_to_file=None, plot_covs=True, std_ests=True, show_stars=False, format_pval=True, format_fig='png', engine='semopy', return_fig=True, decimal=3, dpi=600, seed=13, **kwargs)[source]

Plot a SEM path diagram from the stats table returned by sem().

Latent variables are drawn as circles, observed variables as boxes, regressions and measurement paths as arrows from predictor/indicator to outcome/latent and covariances as dashed double-headed arrows. Edges are labelled with the estimate and, below it, the formatted p-value (or stars). The drawing is done by one of two engines that show the same diagram:

  • "semopy" (default): the diagram of semopy.semplot drawn by Graphviz (semopy_plot()); needs the Graphviz executables.

  • "networkx": a pure Python drawing with networkx and matplotlib (networkx_plot()); needs no external program and also supports dpi.

  • "lavaan": drawn by the R package semPlot (semPlot::semPaths), the usual plotter of lavaan models, in an Rscript subprocess; works with the tables of both sem engines. Needs R with the packages lavaan and semPlot; returns an RFigure (displays in Jupyter, .save(path)).

Parameters:
  • stats (pandas.DataFrame) – Parameter table from sem().

  • save_to_file (str, optional) – Write the figure to this path. The file type follows format_fig for the "semopy" engine; for "networkx" it follows the extension of the path (format_fig if the path has none).

  • plot_covs (bool, default True) – Draw covariances between different variables (dashed, double-headed arrows).

  • std_ests (bool, default True) – Show standardized estimates (est_std) instead of raw estimate.

  • show_stars (bool or callable, default False) – Show significance stars instead of p-values (apatools.format.get_stars() if True, or a callable).

  • format_pval (bool or callable, default True) – Format p-values as e.g. "p=.009" / "p<.001" (apatools.format.format_p()); a callable receives one p-value. Ignored if show_stars is set. False prints the raw numbers.

  • format_fig (str, default "png") – Output format ("png", "svg", "pdf", …), see save_to_file.

  • engine ({"semopy", "networkx", "lavaan"}, default "semopy") – Drawing engine. Any other value raises NotImplementedError.

  • return_fig (bool, default True) – Return the figure object; if False the function returns None (the figure is still written to save_to_file, and a matplotlib figure is closed).

  • decimal (int, default 3) – Rounding of the estimates.

  • dpi (int, default 600) – Resolution of the saved figure; used by the "networkx" engine only (the "semopy" engine accepts it but ignores it).

  • seed (int, default 13) – Seed for numpy’s global random generator.

  • **kwargs – Passed through to the engine function: layout for both engines (a Graphviz layout program such as "dot" / "neato" for "semopy", see semopy_plot(); "layered", "spring", "kamada_kawai", "circular" for "networkx"; "tree", "tree2", "circle", "circle2", "spring" for "lavaan"), figsize and fontsize for "networkx", see networkx_plot(), and rotation, width, height, fontsize and rscript for "lavaan".

Returns:

graphviz.Digraph, matplotlib.figure.Figure, RFigure or None – "semopy": the Graphviz graph (displays inline in Jupyter). "networkx": the matplotlib figure. "lavaan": the figure drawn by R. None if return_fig is False.

Notes

The "semopy" engine needs the graphviz Python package and the Graphviz executables (dot) on the system PATH (on Windows, add the Graphviz bin folder to PATH): pip install "apatools[graphviz]". The "networkx" engine needs networkx and matplotlib: pip install "apatools[networkx]". The "lavaan" engine needs R with the packages lavaan and semPlot (install.packages(c("lavaan", "semPlot"))).

apatools.sem.semopy_plot(stats, save_to_file, plot_covs=True, std_ests=True, plot_ests=True, layout='dot', latshape='circle', show_stars=False, format_pval=True, format_fig='png', decimal=3, seed=13, **kwargs)[source]

Draw a SEM diagram adapted from semopy.semplot (the "semopy" engine of sem_plot()).

Builds a Graphviz graph from the parameter table and renders it once (to a temporary directory that is removed afterwards) so that errors in the Graphviz installation surface immediately and save_to_file can be written. Edges with the intercept pseudo-variable "1" are skipped, and variance (self-covariance) rows are not drawn.

Parameters:
  • stats (pandas.DataFrame) – Parameter table from sem(). Latent variables are read from stats.attrs["latent"]; without it every right-hand-side variable is drawn as latent (circle).

  • save_to_file (str or None) – Path where the rendered figure is copied to; None only returns the graph.

  • plot_covs (bool, optional) – Draw covariances as dashed double-headed edges. Default True.

  • std_ests (bool, optional) – Plot standardized (est_std) instead of raw (estimate) estimates. Default True.

  • plot_ests (bool, optional) – Label edges with estimates and p-values. Default True.

  • layout (str, optional) – Graphviz layout program ("dot", "neato", "fdp", …). Default ‘dot’.

  • latshape (str, optional) – Graphviz node shape for latent variables. Default ‘circle’.

  • show_stars (bool or callable, optional) – Append significance stars to the labels instead of p-values (apatools.format.get_stars() if True, or the callable).

  • format_pval (bool or callable, optional) – Format p-values in labels as "p=.009" (see apatools.format.format_p(); ignored when show_stars is set); a callable receives one p-value.

  • format_fig (str, optional) – Graphviz output format. Default ‘png’.

  • decimal (int, optional) – Rounding of estimates. Default 3.

  • seed (int, optional) – Seed for numpy’s global random generator. Default 13.

  • **kwargs – Accepted and ignored (lets sem_plot() forward its extra options).

Returns:

graphviz.Digraph – The graph, which can be displayed or re-rendered with other options.

Raises:
  • ImportError – If the graphviz Python package is not installed.

  • graphviz.ExecutableNotFound – If the Graphviz executables are not on the PATH.

apatools.sem.networkx_plot(stats, save_to_file=None, plot_covs=True, std_ests=True, plot_ests=True, layout='layered', show_stars=False, format_pval=True, format_fig='png', decimal=3, dpi=600, seed=13, figsize=None, fontsize=10, **kwargs)[source]

Draw a SEM path diagram with networkx and matplotlib (the "networkx" engine of sem_plot()).

The same diagram as semopy_plot() (circles for latent and boxes for observed variables, arrows from predictor / indicator to outcome / latent, dashed double-headed arrows for covariances, edge labels with the estimate and the p-value or stars) but drawn in Python: no Graphviz executable is needed, the output is a matplotlib figure and the resolution can be set with dpi. Edges with the intercept pseudo-variable "1" and variances are not drawn.

Parameters:
  • stats (pandas.DataFrame) – Parameter table from sem() (latent variables are read from stats.attrs["latent"], as in semopy_plot()).

  • save_to_file (str or None) – Write the figure to this path (dpi resolution, cropped to the diagram). The file type follows the extension; format_fig is used if the path has none.

  • plot_covs – As in sem_plot() / semopy_plot().

  • std_ests – As in sem_plot() / semopy_plot().

  • plot_ests – As in sem_plot() / semopy_plot().

  • show_stars – As in sem_plot() / semopy_plot().

  • format_pval – As in sem_plot() / semopy_plot().

  • decimal – As in sem_plot() / semopy_plot().

  • layout ({"layered", "spring", "kamada_kawai", "circular"}, default "layered") – "layered": predictors on the left, outcomes on the right (latent variables between their causes and their indicators), ordered to reduce crossing edges; deterministic. The others are generic networkx layouts ("spring" is seeded with seed).

  • format_fig (str, default "png") – File type if save_to_file has no extension.

  • dpi (int, default 600) – Resolution of the saved file.

  • seed (int, default 13) – Seed for numpy’s global random generator and for the "spring" layout.

  • figsize (tuple of float, optional) – Figure size in inches; by default it follows the size of the diagram.

  • fontsize (float, default 10) – Font size of the variable names (edge labels are one point smaller).

  • **kwargs – Accepted and ignored (lets sem_plot() forward its extra options).

Returns:

matplotlib.figure.Figure – The figure (created with pyplot: show it with plt.show() or close it with plt.close(fig)).

Raises:
  • ImportError – If networkx or matplotlib is not installed (pip install "apatools[networkx]").

  • ValueError – For an unknown layout.