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_gridand :func:to_gridconvert between :class:~fdatools.core.FDataand plain sampled arrays, in either the fdatools layout(n_points, n_curves)or the machine-learning layout(n_curves, n_points). - SciPy -- :func:
to_scipyand :func:from_scipyconvert spline curves to and from :class:scipy.interpolate.BSplineexactly (same knots, same coefficients). - scikit-fda -- :func:
to_skfdaand :func:from_skfdaconvert to and fromFDataBasis(exactly, for B-spline, Fourier, monomial and constant bases) andFDataGrid. - Panel econometrics (linearmodels, statsmodels, pandas) --
:func:
from_panelsmooths a(entity, time)MultiIndex panel into one curve per entity, and :func:to_panelwrites curves back in that layout. - Any linear estimator -- :func:
functional_designbuilds the design matrix of a scalar-on-function modely_i = a + z_i'g + int x_i(t) beta(t) dt + e_i. Fit it withstatsmodels.OLS/WLS/GLM/QuantReg,linearmodelsPanelOLS/IV2SLS, or scikit-learn, then map the estimated parameters and their covariance back tobeta(t)with :meth:FunctionalDesign.betaand :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 |
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, |
shape
property
¶
shape: tuple[int, int]
Shape of :attr:matrix.
Returns:
| Type | Description |
|---|---|
tuple of int
|
|
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: |
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: |
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 ( |
required |
functional
|
FData or mapping of str to FData
|
New curves, as in :meth: |
required |
scalar
|
mapping of str to array_like
|
New scalar covariates, as in :meth: |
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: |
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 |
ValueError
|
If |
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 ( |
required |
cov
|
array_like or DataFrame
|
Their covariance (statsmodels |
required |
name
|
str
|
Which functional covariate. Optional when there is only one. |
None
|
t
|
array_like
|
Evaluation points. Defaults to |
None
|
level
|
float
|
Coverage. Default |
0.95
|
n_points
|
int
|
Grid size used when |
_DEFAULT_POINTS
|
df
|
float
|
Residual degrees of freedom (statsmodels |
None
|
simultaneous
|
bool
|
Return a simultaneous (sup-t) band instead of a pointwise one.
Default |
False
|
seed
|
int or None
|
Seed of the simulation behind a simultaneous band. Default |
0
|
Returns:
| Type | Description |
|---|---|
t, estimate, lower, upper : ndarray
|
Evaluation points and the band. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
t
|
array_like
|
The |
None
|
basis
|
Basis
|
Expansion basis. Defaults to the default of
:func: |
None
|
lam
|
float or str
|
Smoothing parameter, as in :func: |
'gcv'
|
curve_axis
|
(0, 1)
|
Which axis of |
0
|
Returns:
| Type | Description |
|---|---|
FData
|
The fitted curves. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
None
|
n_points
|
int
|
Grid size used when |
_DEFAULT_POINTS
|
deriv
|
int
|
Derivative order to evaluate. Default |
0
|
curve_axis
|
(0, 1)
|
Axis of the returned values that indexes the curves: |
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: |
required |
extrapolate
|
bool
|
Passed to SciPy. Default |
False
|
Returns:
| Type | Description |
|---|---|
BSpline
|
A vector-valued spline: |
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: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the knot vector is not clamped, or |
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
|
None
|
n_points
|
int
|
Grid size used when |
_DEFAULT_POINTS
|
Returns:
| Type | Description |
|---|---|
FDataBasis or FDataGrid
|
An exact |
Raises:
| Type | Description |
|---|---|
ImportError
|
If scikit-fda is not installed. |
ValueError
|
If |
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 |
None
|
lam
|
float or str
|
Smoothing parameter for the grid path. Default |
'gcv'
|
Returns:
| Type | Description |
|---|---|
FData
|
Exact for |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
TypeError
|
If |
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 |
None
|
basis
|
Basis
|
Expansion basis. Defaults to a cubic B-spline on the observed time
range (see :func: |
None
|
lam
|
float or str
|
Smoothing parameter, as in :func: |
'gcv'
|
Returns:
| Type | Description |
|---|---|
PanelCurves
|
The curves and their entity labels. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the index is not a two-level MultiIndex, |
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 |
None
|
entities
|
sequence
|
One label per curve. Defaults to |
None
|
names
|
tuple of str
|
Names of the two index levels. Default |
('entity', 'time')
|
value
|
str
|
Name of the value column. Default |
'value'
|
n_points
|
int
|
Grid size used when |
_DEFAULT_POINTS
|
deriv
|
int
|
Derivative order to evaluate. Default |
0
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One column, indexed by a two-level MultiIndex sorted by entity then time. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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, |
required |
scalar
|
mapping of str to array_like
|
Scalar covariates, |
None
|
beta_basis
|
Basis, FData or a mapping of str to them
|
Explicit coefficient functions per covariate: a :class: |
None
|
n_basis
|
int
|
Size of the default B-spline basis for |
7
|
method
|
('basis', 'fpca')
|
How covariates without an explicit |
"basis"
|
n_components
|
int
|
Number of principal components for |
4
|
intercept
|
bool
|
Prepend a column of ones named |
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 |
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]')