Skip to content

Interoperability

fdatools.interop: lossless bridges to NumPy, SciPy (scipy.interpolate.BSpline) and scikit-fda; (entity, time) panels for linearmodels and statsmodels; and design matrices that let any linear estimator (OLS, WLS, GLM, quantile regression, IV, panel fixed effects) fit a scalar-on-function model. See the econometrics tutorial.

Bridges between fdatools and the wider scientific and econometric Python stack.

Functional data rarely starts or ends inside one library. This module moves curves in and out of fdatools without loss wherever the mathematics allows it, and turns functional covariates into ordinary design matrices that any linear estimator can fit:

  • NumPy -- :func:from_grid and :func:to_grid convert between :class:~fdatools.core.FData and plain sampled arrays, in either the fdatools layout (n_points, n_curves) or the machine-learning layout (n_curves, n_points).
  • SciPy -- :func:to_scipy and :func:from_scipy convert spline curves to and from :class:scipy.interpolate.BSpline exactly (same knots, same coefficients).
  • scikit-fda -- :func:to_skfda and :func:from_skfda convert to and from FDataBasis (exactly, for B-spline, Fourier, monomial and constant bases) and FDataGrid.
  • Panel econometrics (linearmodels, statsmodels, pandas) -- :func:from_panel smooths a (entity, time) MultiIndex panel into one curve per entity, and :func:to_panel writes curves back in that layout.
  • Any linear estimator -- :func:functional_design builds the design matrix of a scalar-on-function model y_i = a + z_i'g + int x_i(t) beta(t) dt + e_i. Fit it with statsmodels.OLS/WLS/GLM/QuantReg, linearmodels PanelOLS/IV2SLS, or scikit-learn, then map the estimated parameters and their covariance back to beta(t) with :meth:FunctionalDesign.beta and :meth:FunctionalDesign.band.

scipy is a core dependency; pandas (the pandas extra) and scikit-fda are imported lazily, only by the functions that need them.

PanelCurves dataclass

PanelCurves(fd: FData, entities: list[Any])

Curves smoothed from a panel, one per entity.

Attributes:

Name Type Description
fd FData

One curve per entity, in the order of :attr:entities.

entities list

Entity labels, in first-seen order.

FunctionalDesign dataclass

FunctionalDesign(
    matrix: NDArray[float64],
    columns: tuple[str, ...],
    _blocks: tuple[_Block, ...],
    _scalars: tuple[str, ...] = (),
    _intercept: bool = True,
)

Design matrix of a scalar-on-function linear model.

Expanding each coefficient function, beta(t) = sum_k b_k theta_k(t), turns int x_i(t) beta(t) dt into z_i' b with z_ik = int x_i(t) theta_k(t) dt. Any linear estimator fitted to :attr:matrix therefore estimates b, and its covariance matrix gives standard errors of beta(t). The functions theta_k are a basis (method="basis") or the covariate's principal components (method="fpca", functional principal component regression).

Build one with :func:functional_design; build the matching matrix for new observations with :meth:transform.

Attributes:

Name Type Description
matrix (ndarray, shape(n, n_columns))

The intercept (when requested), the scalar covariates, then the functional blocks.

columns tuple of str

Column labels, "name[k]" for functional blocks ("name[pc1]", ... for principal components).

shape property

shape: tuple[int, int]

Shape of :attr:matrix.

Returns:

Type Description
tuple of int

(n_observations, n_columns).

Examples:

>>> import numpy as np
>>> import fdatools as fdt
>>> from fdatools.interop import functional_design
>>> x = fdt.FData(np.eye(6), fdt.BSpline(n_basis=6))
>>> functional_design({"x": x}, n_basis=4).shape
(6, 5)

functional_names property

functional_names: tuple[str, ...]

Names of the functional covariates.

Returns:

Type Description
tuple of str

In design order.

Examples:

>>> import numpy as np
>>> import fdatools as fdt
>>> from fdatools.interop import functional_design
>>> x = fdt.FData(np.eye(6), fdt.BSpline(n_basis=6))
>>> functional_design({"temp": x}, n_basis=4).functional_names
('temp',)

to_frame

to_frame(index: Any = None) -> pd.DataFrame

Return :attr:matrix as a labelled :class:pandas.DataFrame.

Labelled columns make statsmodels and linearmodels summaries readable and let :meth:beta pick parameters by name.

Parameters:

Name Type Description Default
index array_like

Row index, e.g. the entity-time MultiIndex of a panel.

None

Returns:

Type Description
DataFrame

The design matrix.

Examples:

>>> import numpy as np
>>> import fdatools as fdt
>>> from fdatools.interop import functional_design
>>> x = fdt.FData(np.eye(6), fdt.BSpline(n_basis=6))
>>> list(functional_design({"x": x}, n_basis=2).to_frame().columns)
['const', 'x[0]', 'x[1]']

transform

transform(
    functional: Mapping[str, FData] | FData,
    scalar: Mapping[str, Any] | None = None,
) -> NDArray[np.float64]

Build the design matrix for new observations, column for column.

The same coefficient functions and the same centring are used, so design.transform(x_new) @ params predicts from a model fitted on :attr:matrix.

Parameters:

Name Type Description Default
functional FData or mapping of str to FData

New curves for every functional covariate (a bare :class:FData when the design has exactly one). They may use any basis on the same domain.

required
scalar mapping of str to array_like

New values for every scalar covariate of the design.

None

Returns:

Type Description
(ndarray, shape(n_new, n_columns))

The new design matrix, with :attr:columns as its columns.

Raises:

Type Description
ValueError

If a covariate is missing or the covariates disagree on the number of observations.

Examples:

>>> import numpy as np
>>> import fdatools as fdt
>>> from fdatools.interop import functional_design
>>> x = fdt.FData(np.random.default_rng(0).standard_normal((8, 30)), fdt.BSpline(n_basis=8))
>>> design = functional_design(x, n_basis=4)
>>> bool(np.allclose(design.transform(x), design.matrix))
True

predict

predict(
    params: Any,
    functional: Mapping[str, FData] | FData,
    scalar: Mapping[str, Any] | None = None,
) -> NDArray[np.float64]

Return the linear predictor transform(functional, scalar) @ params.

For a GLM this is the linear predictor (apply the inverse link for the mean); for OLS it is the prediction itself.

Parameters:

Name Type Description Default
params array_like or Series

Estimated parameters (result.params).

required
functional FData or mapping of str to FData

New curves, as in :meth:transform.

required
scalar mapping of str to array_like

New scalar covariates, as in :meth:transform.

None

Returns:

Type Description
(ndarray, shape(n_new))

The linear predictor.

Examples:

>>> import numpy as np
>>> import fdatools as fdt
>>> from fdatools.interop import functional_design
>>> x = fdt.FData(np.random.default_rng(0).standard_normal((8, 30)), fdt.BSpline(n_basis=8))
>>> design = functional_design(x, n_basis=4)
>>> design.predict(np.ones(5), x[:3]).shape
(3,)

beta

beta(params: Any, name: str | None = None) -> FData

Map estimated parameters back to a coefficient function beta(t).

Parameters:

Name Type Description Default
params array_like or Series

The estimator's parameters for :attr:matrix (e.g. statsmodels' result.params). A labelled Series is matched by column name, so extra or reordered entries are fine.

required
name str

Which functional covariate. Optional when there is only one.

None

Returns:

Type Description
FData

One curve, in the basis of that covariate's coefficient functions.

Raises:

Type Description
KeyError

If name is not a functional covariate.

ValueError

If params has the wrong length, or name is needed.

Examples:

>>> import numpy as np
>>> import fdatools as fdt
>>> from fdatools.interop import functional_design
>>> rng = np.random.default_rng(0)
>>> x = fdt.FData(rng.standard_normal((8, 40)), fdt.BSpline(n_basis=8))
>>> design = functional_design({"x": x}, n_basis=5)
>>> y = design.matrix @ np.arange(6.0)
>>> params, *_ = np.linalg.lstsq(design.matrix, y, rcond=None)
>>> design.beta(params).basis.n_basis
5

band

band(
    params: Any,
    cov: Any,
    name: str | None = None,
    t: Any = None,
    *,
    level: float = 0.95,
    n_points: int = _DEFAULT_POINTS,
    df: float | None = None,
    simultaneous: bool = False,
    seed: int | None = 0,
) -> tuple[
    NDArray[np.float64],
    NDArray[np.float64],
    NDArray[np.float64],
    NDArray[np.float64],
]

Return a pointwise or simultaneous confidence band for beta(t).

Var beta(t) = theta(t)' V theta(t), with V the estimator's covariance of the block's parameters, so the band honours whatever covariance the estimator computed -- classical, HC/HAC-robust, clustered or bootstrapped.

A simultaneous band covers the whole curve at once with probability level. Its critical value is the level quantile of the sup-t statistic max_t |beta*(t) - beta(t)| / se(t), simulated from the estimated sampling distribution of the parameters (the "sup-t" band of Montiel Olea and Plagborg-Møller, 2019). It is wider than the pointwise band.

Parameters:

Name Type Description Default
params array_like or Series

Estimated parameters (result.params).

required
cov array_like or DataFrame

Their covariance (statsmodels result.cov_params(), linearmodels result.cov).

required
name str

Which functional covariate. Optional when there is only one.

None
t array_like

Evaluation points. Defaults to n_points points across the domain. A simultaneous band covers these points.

None
level float

Coverage. Default 0.95.

0.95
n_points int

Grid size used when t is not given. Default 101.

_DEFAULT_POINTS
df float

Residual degrees of freedom (statsmodels result.df_resid). Uses Student-t instead of normal critical values, which matters in small samples. Default None (normal).

None
simultaneous bool

Return a simultaneous (sup-t) band instead of a pointwise one. Default False.

False
seed int or None

Seed of the simulation behind a simultaneous band. Default 0, so repeated calls return the same band.

0

Returns:

Type Description
t, estimate, lower, upper : ndarray

Evaluation points and the band.

Raises:

Type Description
ValueError

If level is not in (0, 1), df is not positive, or the shapes disagree.

Examples:

>>> import numpy as np
>>> import fdatools as fdt
>>> from fdatools.interop import functional_design
>>> x = fdt.FData(np.random.default_rng(0).standard_normal((8, 40)), fdt.BSpline(n_basis=8))
>>> design = functional_design({"x": x}, n_basis=4)
>>> t, est, lo, hi = design.band(np.ones(5), np.eye(5), n_points=11)
>>> _, _, slo, shi = design.band(np.ones(5), np.eye(5), n_points=11, simultaneous=True)
>>> bool(np.all(shi - slo >= hi - lo))
True

from_grid

from_grid(
    values: Any,
    t: Any = None,
    *,
    basis: Basis | None = None,
    lam: float | str = "gcv",
    curve_axis: int = 1,
) -> FData

Turn curves sampled on a common grid into an :class:~fdatools.core.FData.

A thin, NumPy-friendly front end to :func:~fdatools.smoothing.smooth.

Parameters:

Name Type Description Default
values array_like

Sampled curves, shape (n_points,), (n_points, n_curves) (the fdatools layout, curve_axis=1) or (n_curves, n_points) (the scikit-learn / pandas-wide layout, curve_axis=0). A third axis holds variables.

required
t array_like

The n_points sampling points. Defaults to 0, 1, ..., n_points - 1.

None
basis Basis

Expansion basis. Defaults to the default of :func:~fdatools.smoothing.smooth.

None
lam float or str

Smoothing parameter, as in :func:~fdatools.smoothing.smooth. The default "gcv" chooses it by generalised cross-validation; 0.0 gives plain least squares.

'gcv'
curve_axis (0, 1)

Which axis of values indexes the curves. Default 1.

0

Returns:

Type Description
FData

The fitted curves.

Raises:

Type Description
ValueError

If curve_axis is not 0 or 1, or t does not match the number of points.

Examples:

>>> import numpy as np
>>> import fdatools as fdt
>>> from fdatools.interop import from_grid
>>> t = np.linspace(0.0, 1.0, 50)
>>> X = np.sin(2 * np.pi * np.outer(np.arange(1, 4), t))  # 3 curves, one per row
>>> fd = from_grid(X, t, basis=fdt.BSpline(n_basis=15), lam=0.0, curve_axis=0)
>>> fd.n_curves
3

to_grid

to_grid(
    fd: FData,
    t: Any = None,
    *,
    n_points: int = _DEFAULT_POINTS,
    deriv: int = 0,
    curve_axis: int = 1,
) -> tuple[NDArray[np.float64], NDArray[np.float64]]

Sample curves on a grid and return plain NumPy arrays.

Parameters:

Name Type Description Default
fd FData

The curves.

required
t array_like

Evaluation points. Defaults to n_points equally spaced points across the domain.

None
n_points int

Grid size used when t is not given. Default 101.

_DEFAULT_POINTS
deriv int

Derivative order to evaluate. Default 0.

0
curve_axis (0, 1)

Axis of the returned values that indexes the curves: 1 gives (n_points, n_curves), 0 gives (n_curves, n_points), the layout scikit-learn and statsmodels expect for a feature matrix.

0

Returns:

Name Type Description
t ndarray

The evaluation points.

values ndarray

The sampled curves.

Examples:

>>> import numpy as np
>>> import fdatools as fdt
>>> from fdatools.interop import to_grid
>>> fd = fdt.FData(np.eye(5), fdt.BSpline(n_basis=5))
>>> t, X = to_grid(fd, n_points=11, curve_axis=0)
>>> X.shape
(5, 11)

to_scipy

to_scipy(
    fd: FData, *, extrapolate: bool = False
) -> ScipyBSpline

Convert spline curves to one :class:scipy.interpolate.BSpline, exactly.

The knots and coefficients are carried over unchanged, so the SciPy object evaluates, differentiates (.derivative()) and integrates (.integrate()) to the same function, to rounding.

Parameters:

Name Type Description Default
fd FData

Curves in a :class:~fdatools.basis.BSpline or :class:~fdatools.basis.Polygonal basis.

required
extrapolate bool

Passed to SciPy. Default False: outside the domain the spline returns NaN, matching the fact that fdatools curves have a domain.

False

Returns:

Type Description
BSpline

A vector-valued spline: spl(t) has shape (len(t), n_curves) (or (len(t), n_curves, n_vars)), like fd(t).

Raises:

Type Description
TypeError

If the basis is not a spline basis.

Examples:

>>> import numpy as np
>>> import fdatools as fdt
>>> from fdatools.interop import to_scipy
>>> fd = fdt.FData(np.arange(12.0).reshape(6, 2), fdt.BSpline(n_basis=6))
>>> spl = to_scipy(fd)
>>> t = np.array([0.1, 0.7])
>>> bool(np.allclose(spl(t), fd(t)))
True

from_scipy

from_scipy(spline: Any) -> FData

Convert a clamped :class:scipy.interpolate.BSpline to an :class:~fdatools.core.FData.

Accepts the output of make_interp_spline, make_lsq_spline, make_smoothing_spline, splrep (as a BSpline) and friends, as long as the knot vector is clamped -- both end knots repeated k + 1 times -- which is what those constructors produce by default.

Parameters:

Name Type Description Default
spline BSpline

The spline. A coefficient array with trailing axes becomes several curves (second axis) and variables (third axis).

required

Returns:

Type Description
FData

The same function in a :class:~fdatools.basis.BSpline basis.

Raises:

Type Description
ValueError

If the knot vector is not clamped, or spline.axis is not 0.

Examples:

>>> import numpy as np
>>> from scipy.interpolate import make_interp_spline
>>> from fdatools.interop import from_scipy
>>> x = np.linspace(0.0, 1.0, 9)
>>> spl = make_interp_spline(x, np.cos(x), k=3)
>>> fd = from_scipy(spl)
>>> bool(np.allclose(fd(x)[:, 0], np.cos(x)))
True

to_skfda

to_skfda(
    fd: FData,
    t: Any = None,
    *,
    n_points: int = _DEFAULT_POINTS,
) -> Any

Convert curves to a scikit-fda object.

Parameters:

Name Type Description Default
fd FData

The curves, with no variable axis.

required
t array_like

Grid used when the basis has no scikit-fda counterpart. Defaults to n_points points across the domain.

None
n_points int

Grid size used when t is not given. Default 101.

_DEFAULT_POINTS

Returns:

Type Description
FDataBasis or FDataGrid

An exact FDataBasis for B-spline, polygonal, Fourier, monomial (consecutive exponents from 0) and constant bases; otherwise the curves sampled on t as an FDataGrid.

Raises:

Type Description
ImportError

If scikit-fda is not installed.

ValueError

If fd carries a variable axis.

Examples:

>>> import numpy as np
>>> import fdatools as fdt
>>> from fdatools.interop import to_skfda
>>> fd = fdt.FData(np.eye(5), fdt.BSpline(n_basis=5))
>>> to_skfda(fd).n_samples
5

from_skfda

from_skfda(
    obj: Any,
    *,
    basis: Basis | None = None,
    lam: float | str = "gcv",
) -> FData

Convert a scikit-fda FDataBasis or FDataGrid to an :class:~fdatools.core.FData.

Parameters:

Name Type Description Default
obj FDataBasis or FDataGrid

One-dimensional-domain, scalar-valued functional data.

required
basis Basis

Target basis for an FDataGrid (or for an FDataBasis whose basis has no exact fdatools counterpart). Defaults to the default of :func:~fdatools.smoothing.smooth.

None
lam float or str

Smoothing parameter for the grid path. Default "gcv".

'gcv'

Returns:

Type Description
FData

Exact for FDataBasis on B-spline, Fourier, monomial and constant bases; otherwise a penalised fit to the sampled values.

Raises:

Type Description
ValueError

If obj has a multidimensional domain or codomain.

TypeError

If obj is neither an FDataBasis nor an FDataGrid.

Examples:

>>> import numpy as np
>>> from skfda import FDataGrid
>>> from fdatools.interop import from_skfda
>>> grid = FDataGrid(np.random.rand(3, 20), np.linspace(0, 1, 20))
>>> from_skfda(grid).n_curves
3

from_panel

from_panel(
    data: Any,
    value: str | None = None,
    *,
    basis: Basis | None = None,
    lam: float | str = "gcv",
) -> PanelCurves

Smooth a (entity, time) panel into one curve per entity.

The input layout is the one used by linearmodels.PanelOLS and statsmodels panel tools: a two-level :class:pandas.MultiIndex with the entity first and a numeric time second. Balanced panels share one grid; unbalanced panels (missing periods, NaNs) are fitted per entity.

Parameters:

Name Type Description Default
data Series or DataFrame

The panel. Rows with a missing value are dropped.

required
value str

Column to smooth when data is a DataFrame. Required unless it has exactly one column.

None
basis Basis

Expansion basis. Defaults to a cubic B-spline on the observed time range (see :func:~fdatools.smoothing.smooth).

None
lam float or str

Smoothing parameter, as in :func:~fdatools.smoothing.smooth.

'gcv'

Returns:

Type Description
PanelCurves

The curves and their entity labels.

Raises:

Type Description
ValueError

If the index is not a two-level MultiIndex, value is ambiguous or missing, or the times are not numeric.

Examples:

>>> import numpy as np
>>> import pandas as pd
>>> import fdatools as fdt
>>> from fdatools.interop import from_panel
>>> idx = pd.MultiIndex.from_product([["a", "b"], np.arange(10.0)], names=["firm", "year"])
>>> s = pd.Series(np.tile(np.linspace(0, 1, 10), 2), index=idx)
>>> panel = from_panel(s, basis=fdt.BSpline(domain=(0.0, 9.0), n_basis=5), lam=0.0)
>>> panel.entities, panel.fd.n_curves
(['a', 'b'], 2)

to_panel

to_panel(
    fd: FData,
    t: Any = None,
    *,
    entities: Sequence[Any] | None = None,
    names: tuple[str, str] = ("entity", "time"),
    value: str = "value",
    n_points: int = _DEFAULT_POINTS,
    deriv: int = 0,
) -> pd.DataFrame

Evaluate curves on t and return an (entity, time) panel DataFrame.

The result plugs straight into linearmodels.PanelOLS / RandomEffects or a statsmodels formula with entity effects.

Parameters:

Name Type Description Default
fd FData

The curves, with no variable axis.

required
t array_like

Evaluation times. Defaults to n_points points across the domain.

None
entities sequence

One label per curve. Defaults to 0, 1, ..., n_curves - 1.

None
names tuple of str

Names of the two index levels. Default ("entity", "time").

('entity', 'time')
value str

Name of the value column. Default "value".

'value'
n_points int

Grid size used when t is not given. Default 101.

_DEFAULT_POINTS
deriv int

Derivative order to evaluate. Default 0.

0

Returns:

Type Description
DataFrame

One column, indexed by a two-level MultiIndex sorted by entity then time.

Raises:

Type Description
ValueError

If entities has the wrong length, or fd carries a variable axis.

Examples:

>>> import numpy as np
>>> import fdatools as fdt
>>> from fdatools.interop import to_panel
>>> fd = fdt.FData(np.eye(4)[:, :2], fdt.BSpline(n_basis=4))
>>> to_panel(fd, np.array([0.0, 1.0]), entities=["a", "b"]).shape
(4, 1)

functional_design

functional_design(
    functional: Mapping[str, FData] | FData,
    scalar: Mapping[str, Any] | None = None,
    *,
    beta_basis: Mapping[str, Basis | FData]
    | Basis
    | FData
    | None = None,
    n_basis: int = 7,
    method: str = "basis",
    n_components: int = 4,
    intercept: bool = True,
) -> FunctionalDesign

Build the design matrix of a scalar-on-function model for any estimator.

The model is y_i = a + sum_s g_s w_is + sum_f int x_if(t) beta_f(t) dt + e_i. Fit y on :attr:FunctionalDesign.matrix with the estimator of your choice -- OLS, WLS, GLM (logit, Poisson), quantile regression, IV/2SLS, panel fixed effects -- and recover beta_f(t) with :meth:FunctionalDesign.beta, its band with :meth:FunctionalDesign.band and predictions for new curves with :meth:FunctionalDesign.predict.

With method="basis" and an ordinary least-squares fit the coefficient functions equal those of :func:~fdatools.regression.fregress with lam=0 and the same bases. method="fpca" is functional principal component regression: beta_f is expanded in the first n_components principal components of x_f, which regularises by truncation and keeps the columns uncorrelated.

Parameters:

Name Type Description Default
functional FData or mapping of str to FData

The functional covariates, n curves each. A bare :class:FData is named "x".

required
scalar mapping of str to array_like

Scalar covariates, n values each, placed after the intercept.

None
beta_basis Basis, FData or a mapping of str to them

Explicit coefficient functions per covariate: a :class:Basis, or an :class:FData whose curves are the functions (for example the harmonics of an :class:~fdatools.decomposition.FPCA you fitted yourself). Covariates without one follow method.

None
n_basis int

Size of the default B-spline basis for method="basis" (cubic, or of order n_basis when fewer than four functions are asked for). Default 7. Keep it small: an unpenalised fit needs n well above the total column count.

7
method ('basis', 'fpca')

How covariates without an explicit beta_basis are expanded. Default "basis".

"basis"
n_components int

Number of principal components for method="fpca". Default 4.

4
intercept bool

Prepend a column of ones named "const". Default True; set it to False for fixed-effects estimators that absorb the constant.

True

Returns:

Type Description
FunctionalDesign

The matrix, its column labels and what is needed to map parameters back to functions and to build the matrix for new observations.

Raises:

Type Description
ValueError

If method is unknown, the covariates disagree on the number of observations, a functional covariate carries a variable axis, or the column names collide.

Examples:

>>> import numpy as np
>>> import fdatools as fdt
>>> from fdatools.interop import functional_design
>>> growth = fdt.datasets.load_growth()
>>> height = fdt.smooth(growth.hgtf, growth.age, basis=fdt.BSpline((1.0, 18.0), 12)).fd
>>> functional_design({"height": height}, n_basis=5).shape
(54, 6)
>>> functional_design({"height": height}, method="fpca", n_components=3).columns
('const', 'height[pc1]', 'height[pc2]', 'height[pc3]')