Data Model
About the Data Model
The Data Model API is a new feature in the v0.12.0 release of SpectraFit
with major focus on:
- Data Validation
- Settings Management
The Data Model API is a work in progress and is subject to change. It is realized by using the pydantic library.
Data Model API¶
Command Line Interface¶
Reference model for the API of the command line interface.
CMDModelAPI
¶
Bases: BaseModel
Model for the model command line argument.
Source code in spectrafit/api/cmd_model.py
class CMDModelAPI(BaseModel):
"""Model for the model command line argument."""
infile: str
outfile: str = Field(default="spectrafit_results")
input: str = Field(default="fitting_input.toml")
oversampling: bool = DataPreProcessingAPI().oversampling
energy_start: Optional[float] = DataPreProcessingAPI().energy_start
energy_stop: Optional[float] = DataPreProcessingAPI().energy_stop
smooth: Optional[int] = DataPreProcessingAPI().smooth
shift: Optional[float] = DataPreProcessingAPI().shift
column: List[Union[int, str]] = DataPreProcessingAPI().column
separator: str = "\t"
decimal: str = "."
header: Optional[int] = None
comment: Optional[str] = None
global_: int = Field(GlobalFittingAPI().global_)
autopeak: Union[AutopeakAPI, bool, Any] = False
noplot: bool = False
version: bool = False
verbose: int = Field(default=0, ge=0, le=2)
description: Optional[DescriptionAPI] = Field(DescriptionAPI())
DescriptionAPI
¶
Bases: BaseModel
Model for the description command line argument.
Source code in spectrafit/api/cmd_model.py
class DescriptionAPI(BaseModel):
"""Model for the description command line argument."""
project_name: str = Field(
default="FittingProject",
alias="projectName",
description="Name of the project",
)
project_details: str = Field(
default=f"Fitting Project via SpectraFit v{__version__}",
alias="projectDetails",
description="Project details",
)
keywords: List[str] = Field(
default=["spectra"], description="Keywords for the project"
)
authors: List[str] = Field(
default=["authors"], description="Authors of the project"
)
references: List[str] = Field(
default=["https://github.com/Anselmoo/spectrafit"],
alias="refs",
description="References for the project",
)
metadata: Optional[Union[Dict[Any, Any], List[Any]]] = Field(
default=None, description="Metadata for the project"
)
license: str = "BSD-3-Clause"
version: str = __version__
host_info: str = sha256(f"{getuser()}@{gethostname()}".encode()).hexdigest()
timestamp: str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
id_: str = Field(
default=str(uuid4()), alias="id", description="Unique ID of the project"
)
@field_validator("references")
@classmethod
def check_references(cls, v: List[str]) -> Optional[List[str]]:
"""Check if the list of references have valid URLs."""
return [str(HttpUrl(url)) for url in v]
check_references(v)
classmethod
¶
Check if the list of references have valid URLs.
Models and Components¶
Reference model for the API of the models distributions.
AmplitudeAPI
¶
Bases: BaseModel
Definition of the amplitude of the models distributions.
Source code in spectrafit/api/models_model.py
class AmplitudeAPI(BaseModel):
"""Definition of the amplitude of the models distributions."""
max: Optional[float] = Field(default=None, description="Maximum amplitude.")
min: Optional[int] = Field(default=None, description="Minimum amplitude.")
vary: bool = Field(default=True, description="Vary the amplitude.")
value: Optional[float] = Field(default=None, description="Initial Amplitude value.")
expr: Optional[str] = Field(default=None, description=__description__)
AtanAPI
¶
Bases: BaseModel
Definition of the Step of the models distributions.
Source code in spectrafit/api/models_model.py
CGaussianAPI
¶
Bases: BaseModel
Definition of the cumulative Gaussian of the models distributions.
Source code in spectrafit/api/models_model.py
CLorentzianAPI
¶
Bases: BaseModel
Definition of the cumulative Lorentzian of the models distributions.
Source code in spectrafit/api/models_model.py
CVoigtAPI
¶
Bases: BaseModel
Definition of the cumulative Voigt of the models distributions.
Source code in spectrafit/api/models_model.py
CenterAPI
¶
Bases: BaseModel
Definition of the center of the models distributions.
Source code in spectrafit/api/models_model.py
class CenterAPI(BaseModel):
"""Definition of the center of the models distributions."""
max: Optional[float] = Field(default=None, description="Maximum center.")
min: Optional[int] = Field(default=None, description="Minimum center.")
vary: bool = Field(default=True, description="Vary the center.")
value: Optional[float] = Field(default=None, description="Initial Center value.")
expr: Optional[str] = Field(default=None, description=__description__)
CoefficientAPI
¶
Bases: BaseModel
Definition of the Coefficient of the models distributions.
Source code in spectrafit/api/models_model.py
class CoefficientAPI(BaseModel):
"""Definition of the Coefficient of the models distributions."""
max: Optional[float] = Field(default=None, description="Maximum coefficient.")
min: Optional[int] = Field(default=None, description="Minimum coefficient.")
vary: bool = Field(default=True, description="Vary the coefficient.")
value: Optional[float] = Field(
default=None, description="Initial coefficient value."
)
expr: Optional[str] = Field(default=None, description=__description__)
ConfIntervalAPI
¶
Bases: BaseModel
Definition of Confidence Interval Function.
Source code in spectrafit/api/models_model.py
class ConfIntervalAPI(BaseModel):
"""Definition of Confidence Interval Function."""
p_names: Optional[List[str]] = Field(
default=None, description="List of parameters names."
)
trace: bool = Field(
default=True, description="Trace of the confidence interfall matrix."
)
maxiter: int = Field(
default=200,
gt=1,
le=2000,
description="Maximum number of iteration",
)
verbose: bool = Field(
default=False, description="Print information about the fit process."
)
prob_func: Optional[Callable[[float], float]] = Field(
default=None, description="Probing function."
)
ConstantAPI
¶
DecayAPI
¶
Bases: BaseModel
Definition of the Decay of the Exponential of the models distributions.
Source code in spectrafit/api/models_model.py
class DecayAPI(BaseModel):
"""Definition of the Decay of the Exponential of the models distributions."""
max: Optional[float] = Field(default=None, description="Maximum decay rate.")
min: Optional[int] = Field(default=None, description="Minimum decay rate.")
vary: bool = Field(default=True, description="Vary the decay rate.")
value: Optional[float] = Field(
default=None, description="Initial decay rate value."
)
expr: Optional[str] = Field(default=None, description=__description__)
DistributionModelAPI
¶
Bases: BaseModel
Definition of the models distributions.
Source code in spectrafit/api/models_model.py
class DistributionModelAPI(BaseModel):
"""Definition of the models distributions."""
gaussian: GaussianAPI = GaussianAPI()
lorentzian: LorentzianAPI = LorentzianAPI()
voigt: VoigtAPI = VoigtAPI()
pseudovoigt: PseudovoigtAPI = PseudovoigtAPI()
exponential: ExponentialAPI = ExponentialAPI()
power: PowerAPI = PowerAPI()
linear: LinearAPI = LinearAPI()
constant: ConstantAPI = ConstantAPI()
erf: ErfAPI = ErfAPI()
heaviside: HeavisideAPI = HeavisideAPI()
atan: AtanAPI = AtanAPI()
log: LogAPI = LogAPI()
cgaussian: CGaussianAPI = CGaussianAPI()
clorentzian: CLorentzianAPI = CLorentzianAPI()
cvoigt: CVoigtAPI = CVoigtAPI()
polynom2: Polynomia2API = Polynomia2API()
polynom3: Polynomia3API = Polynomia3API()
pearson1: Pearson1API = Pearson1API()
pearson2: Pearson2API = Pearson2API()
pearson3: Pearson3API = Pearson3API()
pearson4: Pearson4API = Pearson4API()
ErfAPI
¶
Bases: BaseModel
Definition of the Step of the models distributions.
Source code in spectrafit/api/models_model.py
ExponentAPI
¶
Bases: BaseModel
Definition of the Exponent of the Linear of the models distributions.
Source code in spectrafit/api/models_model.py
class ExponentAPI(BaseModel):
"""Definition of the Exponent of the Linear of the models distributions."""
max: Optional[float] = Field(default=None, description="Maximum exponent.")
min: Optional[int] = Field(default=None, description="Minimum exponent.")
vary: bool = Field(default=True, description="Vary the exponent.")
value: Optional[float] = Field(default=None, description="Initial exponent value.")
expr: Optional[str] = Field(default=None, description=__description__)
ExponentialAPI
¶
Bases: BaseModel
Definition of the Exponential of the models distributions.
Source code in spectrafit/api/models_model.py
FwhmgAPI
¶
Bases: BaseModel
Definition of the FWHM Gaussian of the models distributions.
Source code in spectrafit/api/models_model.py
class FwhmgAPI(BaseModel):
"""Definition of the FWHM Gaussian of the models distributions."""
max: Optional[float] = Field(
default=None,
description="Maximum Full Width Half Maximum of the Gaussian Distribution.",
)
min: Optional[int] = Field(
default=None,
description="Minimum Full Width Half Maximum of the Gaussian Distribution.",
)
vary: bool = Field(
default=True,
description="Vary the Full Width Half Maximum of the Gaussian Distribution.",
)
value: Optional[float] = Field(
default=None,
description="Initial Full Width Half Maximum of "
"the Gaussian Distribution value.",
)
expr: Optional[str] = Field(default=None, description=__description__)
FwhmlAPI
¶
Bases: BaseModel
Definition of the FWHM Lorentzian of the models distributions.
Source code in spectrafit/api/models_model.py
class FwhmlAPI(BaseModel):
"""Definition of the FWHM Lorentzian of the models distributions."""
max: Optional[float] = Field(
default=None,
description="Maximum Full Width Half Maximum of the Lorentzian Distribution.",
)
min: Optional[int] = Field(
default=None,
description="Minimum Full Width Half Maximum of the Lorentzian Distribution.",
)
vary: bool = Field(
default=True,
description="Vary the Full Width Half Maximum of the Lorentzian Distribution.",
)
value: Optional[float] = Field(
default=None,
description="Initial Full Width Half Maximum of "
"the Lorentzian Distribution value.",
)
expr: Optional[str] = Field(default=None, description=__description__)
FwhmvAPI
¶
Bases: BaseModel
Definition of the FWHM Voigt of the models distributions.
Source code in spectrafit/api/models_model.py
class FwhmvAPI(BaseModel):
"""Definition of the FWHM Voigt of the models distributions."""
max: Optional[float] = Field(
default=None,
description="Maximum Full Width Half Maximum of the Voigt Distribution.",
)
min: Optional[int] = Field(
default=None,
description="Minimum Full Width Half Maximum of the Voigt Distribution.",
)
vary: bool = Field(
default=True,
description="Vary the Full Width Half Maximum of the Voigt Distribution.",
)
value: Optional[float] = Field(
default=None,
description="Initial Full Width Half Maximum of the Voigt Distribution value.",
)
expr: Optional[str] = Field(default=None, description=__description__)
GammaAPI
¶
Bases: BaseModel
Definition of the Gamma of the Voigt of the models distributions.
Source code in spectrafit/api/models_model.py
class GammaAPI(BaseModel):
"""Definition of the Gamma of the Voigt of the models distributions."""
max: Optional[float] = Field(default=None, description="Maximum gamma.")
min: Optional[int] = Field(default=None, description="Minimum gamma.")
vary: bool = Field(default=True, description="Vary the gamma.")
value: Optional[float] = Field(default=None, description="Initial Gamma value.")
expr: Optional[str] = Field(default=None, description=__description__)
GaussianAPI
¶
Bases: BaseModel
Definition of the Gaussian of the models distributions.
Source code in spectrafit/api/models_model.py
HeavisideAPI
¶
Bases: BaseModel
Definition of the Step of the models distributions.
Source code in spectrafit/api/models_model.py
InterceptAPI
¶
Bases: BaseModel
Definition of the Intercept of the Linear of the models distributions.
Source code in spectrafit/api/models_model.py
class InterceptAPI(BaseModel):
"""Definition of the Intercept of the Linear of the models distributions."""
max: Optional[float] = Field(default=None, description="Maximum intercept.")
min: Optional[int] = Field(default=None, description="Minimum intercept.")
vary: bool = Field(default=True, description="Vary the intercept.")
value: Optional[float] = Field(default=None, description="Initial intercept value.")
expr: Optional[str] = Field(default=None, description=__description__)
KurtosisAPI
¶
Bases: BaseModel
Definition of the kurtosis of the models distributions.
Source code in spectrafit/api/models_model.py
class KurtosisAPI(BaseModel):
"""Definition of the kurtosis of the models distributions."""
max: Optional[float] = Field(default=None, description="Maximum kurtosis.")
min: Optional[int] = Field(default=None, description="Minimum kurtosis.")
vary: bool = Field(default=True, description="Vary the kurtosis.")
value: Optional[float] = Field(default=None, description="Initial kurtosis value.")
expr: Optional[str] = Field(default=None, description=__description__)
LinearAPI
¶
LogAPI
¶
Bases: BaseModel
Definition of the Step of the models distributions.
Source code in spectrafit/api/models_model.py
LorentzianAPI
¶
Bases: BaseModel
Definition of the Lorentzian of the models distributions.
Source code in spectrafit/api/models_model.py
Pearson1API
¶
Bases: BaseModel
Definition of the pearson type I of the models distributions.
Source code in spectrafit/api/models_model.py
Pearson2API
¶
Bases: BaseModel
Definition of the pearson type II of the models distributions.
Source code in spectrafit/api/models_model.py
Pearson3API
¶
Bases: BaseModel
Definition of the pearson type III of the models distributions.
Source code in spectrafit/api/models_model.py
Pearson4API
¶
Bases: BaseModel
Definition of the pearson type IV of the models distributions.
Source code in spectrafit/api/models_model.py
class Pearson4API(BaseModel):
"""Definition of the pearson type IV of the models distributions."""
amplitude: AmplitudeAPI = AmplitudeAPI()
center: CenterAPI = CenterAPI()
sigma: SigmaAPI = SigmaAPI()
exponent: ExponentAPI = ExponentAPI()
skewness: SkewnessAPI = SkewnessAPI()
kurtosis: KurtosisAPI = KurtosisAPI()
Polynomia2API
¶
Bases: BaseModel
Definition of the second order polynomial of the models distributions.
Source code in spectrafit/api/models_model.py
Polynomia3API
¶
Bases: BaseModel
Definition of the third order polynomial of the models distributions.
Source code in spectrafit/api/models_model.py
class Polynomia3API(BaseModel):
"""Definition of the third order polynomial of the models distributions."""
coefficient0: CoefficientAPI = CoefficientAPI()
coefficient1: CoefficientAPI = CoefficientAPI()
coefficient2: CoefficientAPI = CoefficientAPI()
coefficient3: CoefficientAPI = CoefficientAPI()
PowerAPI
¶
Bases: BaseModel
Definition of the Power of the models distributions.
Source code in spectrafit/api/models_model.py
PseudovoigtAPI
¶
Bases: BaseModel
Definition of the Pseudovoigt of the models distributions.
Source code in spectrafit/api/models_model.py
SigmaAPI
¶
Bases: BaseModel
Definition of the Sigma of the models distributions.
Source code in spectrafit/api/models_model.py
class SigmaAPI(BaseModel):
"""Definition of the Sigma of the models distributions."""
max: Optional[float] = Field(default=None, description="Maximum sigma.")
min: Optional[int] = Field(default=None, description="Minimum sigma.")
vary: bool = Field(default=True, description="Vary the sigma.")
value: Optional[float] = Field(default=None, description="Initial sigma value.")
expr: Optional[str] = Field(default=None, description=__description__)
SkewnessAPI
¶
Bases: BaseModel
Definition of the skewness of the models distributions.
Source code in spectrafit/api/models_model.py
class SkewnessAPI(BaseModel):
"""Definition of the skewness of the models distributions."""
max: Optional[float] = Field(default=None, description="Maximum skewness.")
min: Optional[int] = Field(default=None, description="Minimum skewness.")
vary: bool = Field(default=True, description="Vary the skewness.")
value: Optional[float] = Field(default=None, description="Initial skewness value.")
expr: Optional[str] = Field(default=None, description=__description__)
SlopeAPI
¶
Bases: BaseModel
Definition of the Slope of the Linear of the models distributions.
Source code in spectrafit/api/models_model.py
class SlopeAPI(BaseModel):
"""Definition of the Slope of the Linear of the models distributions."""
max: Optional[float] = Field(default=None, description="Maximum slope.")
min: Optional[int] = Field(default=None, description="Minimum slope.")
vary: bool = Field(default=True, description="Vary the slope.")
value: Optional[float] = Field(default=None, description="Inital slope value.")
expr: Optional[str] = Field(default=None, description=__description__)
VoigtAPI
¶
Juptyer Notebook¶
Reference model for the API of the Jupyter Notebook interface.
ColorAPI
¶
Bases: BaseModel
Definition of the colors of the plotly figure.
Source code in spectrafit/api/notebook_model.py
class ColorAPI(BaseModel):
"""Definition of the colors of the plotly figure."""
intensity: str = Field(
default=PlotlyColors[0], description="Color of the spectrum-intensity."
)
residual: str = Field(
default=PlotlyColors[1], description="Color of the residuals."
)
fit: str = Field(default=PlotlyColors[5], description="Color of the fit.")
components: str = Field(
default=PlotlyColors[6], description="Color of the components, mainly peaks."
)
bars: List[str] = Field(
default=[i for j in zip(Teal_r, Purp_r) for i in j],
description="Color of the bar plot of the metrics.",
)
lines: List[str] = Field(
default=Burg, description="Color of the lines of the plot."
)
paper: str = Field(default="white", description="Color of the paper.")
plot: str = Field(default="white", description="Color of the plot.")
color: str = Field(default="black", description="Color of the text.")
grid: str = Field(default="lightgrey", description="Color of the grid.")
line: str = Field(default="black", description="Color of the bottom and side line.")
zero_line: str = Field(default="grey", description="Color of the zero line.")
ticks: str = Field(default="black", description="Color of the ticks.")
font: str = Field(default="black", description="Font color of the plot.")
@field_validator(
"paper",
"layout",
"grid",
"line",
"zero_line",
"ticks",
"font",
check_fields=False,
)
@classmethod
def transparent_rgb(cls, v: str) -> str:
"""Convert string to transparent RGB color.
Args:
v (str): One of the key-words of the validator decorator.
Returns:
str: Translate the word `transparent` to the rgb value `rgba(0,0,0,0)`.
"""
return "rgba(0,0,0,0)" if "transparent" in v.lower() else v
transparent_rgb(v)
classmethod
¶
Convert string to transparent RGB color.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
v | str | One of the key-words of the validator decorator. | required |
Returns:
Name | Type | Description |
---|---|---|
str | str | Translate the word |
Source code in spectrafit/api/notebook_model.py
@field_validator(
"paper",
"layout",
"grid",
"line",
"zero_line",
"ticks",
"font",
check_fields=False,
)
@classmethod
def transparent_rgb(cls, v: str) -> str:
"""Convert string to transparent RGB color.
Args:
v (str): One of the key-words of the validator decorator.
Returns:
str: Translate the word `transparent` to the rgb value `rgba(0,0,0,0)`.
"""
return "rgba(0,0,0,0)" if "transparent" in v.lower() else v
FnameAPI
¶
Bases: BaseModel
Definition of the file name.
Source code in spectrafit/api/notebook_model.py
class FnameAPI(BaseModel):
"""Definition of the file name."""
fname: str = Field(..., description="Name of the file to save.")
suffix: str = Field(..., description="Suffix of the file to save.")
prefix: Optional[str] = Field(
default=None, description="Prefix of the file to save."
)
folder: Optional[str] = Field(default=None, description="Folder to save the file.")
FontAPI
¶
Bases: BaseModel
Definition of the used font of the plotly figure.
Source code in spectrafit/api/notebook_model.py
class FontAPI(BaseModel):
"""Definition of the used font of the plotly figure."""
family: str = Field(
default="Open Sans, monospace", description="Font family of the plot."
)
size: int = Field(default=12, description="Font size of the plot.")
color: str = Field(default="black", description="Font color of the plot.")
GridAPI
¶
Bases: BaseModel
Definition of the grid of the plotly figure.
Source code in spectrafit/api/notebook_model.py
LegendAPI
¶
Bases: BaseModel
Definition of the legend of the plotly figure.
Source code in spectrafit/api/notebook_model.py
class LegendAPI(BaseModel):
"""Definition of the legend of the plotly figure."""
orientation: str = Field(default="h", description="Orientation of the legend.")
yanchor: str = Field(default="bottom", description="Y anchor of the legend.")
y: float = Field(default=1.02, description="Y position of the legend.")
xanchor: str = Field(default="right", description="X anchor of the legend.")
x: float = Field(default=1, description="X position of the legend.")
MetricAPI
¶
Bases: BaseModel
Definition of the residual plot (Y-Axis) of the plotly figure.
Source code in spectrafit/api/notebook_model.py
class MetricAPI(BaseModel):
"""Definition of the residual plot (Y-Axis) of the plotly figure."""
name_0: str = Field(
default="Metrics", description="Name of the first metrics-axis of the plot."
)
unit_0: Optional[str] = Field(
default="a.u.", description="Name of the first metrics-axis units of the plot."
)
name_1: str = Field(
default="Metrics", description="Name of the second metrics-axis of the plot."
)
unit_1: Optional[str] = Field(
default="a.u.", description="Name of the second metrics-axis units of the plot."
)
PlotAPI
¶
Bases: BaseModel
Definition of the plotly figure.
Source code in spectrafit/api/notebook_model.py
class PlotAPI(BaseModel):
"""Definition of the plotly figure."""
x: str = Field(..., description="Name of the x column to plot.")
y: Union[str, List[str]] = Field(
..., description="List of the names of the y columns to plot."
)
title: Optional[str] = Field(None, description="Title of the plot.")
xaxis_title: XAxisAPI = XAxisAPI()
yaxis_title: YAxisAPI = YAxisAPI()
residual_title: ResidualAPI = ResidualAPI()
metric_title: MetricAPI = MetricAPI()
run_title: RunAPI = RunAPI()
legend_title: str = Field(default="Spectra", description="Title of the legend.")
show_legend: bool = Field(default=True, description="Show legend.")
legend: LegendAPI = LegendAPI()
font: FontAPI = FontAPI()
minor_ticks: bool = Field(default=True, description="Show minor ticks.")
color: ColorAPI = ColorAPI()
grid: GridAPI = GridAPI()
size: Tuple[int, Tuple[int, int]] = Field(
default=(800, (600, 300)), description="Size of the fit- and metric-plot."
)
ResidualAPI
¶
Bases: BaseModel
Definition of the residual plot (Y-Axis) of the plotly figure.
Source code in spectrafit/api/notebook_model.py
class ResidualAPI(BaseModel):
"""Definition of the residual plot (Y-Axis) of the plotly figure."""
name: str = Field(
default="Residuals", description="Name of the residual-axis of the plot."
)
unit: Optional[str] = Field(
default="a.u.", description="Name of the residual-axis units of the plot."
)
RunAPI
¶
Bases: BaseModel
Definition of the residual plot (Y-Axis) of the plotly figure.
Source code in spectrafit/api/notebook_model.py
XAxisAPI
¶
Bases: BaseModel
Defintion of the X-Axis of the plotly figure.
Source code in spectrafit/api/notebook_model.py
YAxisAPI
¶
Bases: BaseModel
Defintion of the Y-Axis of the plotly figure.
Source code in spectrafit/api/notebook_model.py
Report Design¶
Reference model for the API of the Jupyter Notebook report.
CreditsAPI
¶
Bases: BaseModel
Credits API model.
Source code in spectrafit/api/report_model.py
class CreditsAPI(BaseModel):
"""Credits API model."""
dtale: str = f"dtale v{dtale_version}"
emcee: str = f"emcee v{emcee_version}"
itables: str = f"itables v{itables_version}"
lmfit: str = f"lmfit v{lmfit_version}"
numdifftools: str = f"numdifftools v{numdifftools_version}"
numpy: str = f"numpy v{numpy_version}"
pandas: str = f"pandas v{pandas_version}"
plotly: str = f"plotly v{plotly_version}"
pydantic: str = f"pydantic v{pydantic_version}"
scipy: str = f"scipy v{scipy_version}"
sklearn: str = f"sklearn v{sklearn_version}"
statsmodels: str = f"statsmodels v{statsmodels_version}"
FitMethodAPI
¶
Bases: BaseModel
Fit method API model.
Source code in spectrafit/api/report_model.py
class FitMethodAPI(BaseModel):
"""Fit method API model."""
global_fitting: Union[bool, int] = Field(
default=False,
description="Fitting in the global fashion",
)
confidence_interval: Union[bool, Dict[str, Any]] = Field(
...,
description="Settings for the confidence interval calculation",
)
configurations: Dict[str, Any] = Field(
..., description="Settings for the fitting configuration"
)
settings_solver_models: Dict[str, Any] = Field(
...,
description="Settings for the solver models including minimizer and optimizer",
)
InputAPI
¶
Bases: BaseModel
Input API for the report endpoint.
Source code in spectrafit/api/report_model.py
class InputAPI(BaseModel):
"""Input API for the report endpoint."""
description: DescriptionAPI = DescriptionAPI()
credits: CreditsAPI = CreditsAPI()
initial_model: List[Dict[str, Dict[str, Dict[str, Any]]]] = Field(
..., description="Initial model for the fit"
)
method: FitMethodAPI = Field(
..., description="Fitting method with optional including of confidence interval"
)
pre_processing: DataPreProcessingAPI = Field(..., description="Data pre-processing")
OutputAPI
¶
Bases: BaseModel
Output API for the report endpoint.
Source code in spectrafit/api/report_model.py
class OutputAPI(BaseModel):
"""Output API for the report endpoint."""
df_org: Dict[Hashable, Any] = Field(
...,
description="DataFrame of the original data via 'records' orient",
)
df_fit: Dict[Hashable, Any] = Field(
...,
description="DataFrame of the fitted data via 'records' orient",
)
df_pre: Dict[Hashable, Any] = Field(
default={},
description="DataFrame of the pre-processed data via 'records' orient",
)
model_config = ConfigDict(arbitrary_types_allowed=True)
ReportAPI
¶
Bases: BaseModel
Definition of the report model.
Source code in spectrafit/api/report_model.py
SolverAPI
¶
Bases: BaseModel
Solver API for the report endpoint.
Source code in spectrafit/api/report_model.py
class SolverAPI(BaseModel):
"""Solver API for the report endpoint."""
goodness_of_fit: Dict[str, float] = Field(..., description="Goodness of fit")
regression_metrics: Dict[str, List[Any]] = Field(
..., description="Regression metrics"
)
descriptive_statistic: Dict[str, List[Any]] = Field(
..., description="Descriptive statistic"
)
linear_correlation: Dict[str, List[Any]] = Field(
..., description="Linear correlation"
)
component_correlation: Dict[str, Dict[str, Any]] = Field(
default={},
description="Linear correlation of each attribute of components. if possible",
)
confidence_interval: Dict[str, Any] = Field(
default={}, description="Confidence interval, if possible"
)
covariance_matrix: Dict[str, Dict[str, Any]] = Field(
default={}, description="Covariance matrix, if possible"
)
variables: Dict[str, Dict[str, Any]] = Field(
...,
description="Variables with their initial, optimized and optional error values",
)
errorbars: Dict[str, Any] = Field(
default={},
description="Error bar comment if values reach initial value or boundary",
)
computational: Dict[str, Any] = Field(
...,
description="Computational information like number of function evaluations",
)
Tools and Utilities¶
Reference model for the API of the SpectraFit tools.
AutopeakAPI
¶
Bases: BaseModel
Definition of the auto detection of peak command line argument.
The auto detection of peaks is performed by the SpectraFit tools. Here is listed the set of parameters that are used to control the auto detection of peaks according to the following scipy.signal.find_peaks
-module; source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.find_peaks.html
Source code in spectrafit/api/tools_model.py
class AutopeakAPI(BaseModel):
"""Definition of the auto detection of peak command line argument.
The auto detection of peaks is performed by the SpectraFit tools. Here is listed the
set of parameters that are used to control the auto detection of peaks according to
the following `scipy.signal.find_peaks` -module; source:
[https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.find_peaks.html](
https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.find_peaks.html
)
"""
modeltype: Optional[str] = None
height: Optional[List[float]] = None
threshold: Optional[List[float]] = None
distance: Optional[int] = None
prominence: Optional[List[float]] = None
width: Optional[List[float]] = None
wlen: Optional[int] = None
rel_height: Optional[float] = None
plateau_size: Optional[float] = None
model_config = ConfigDict(extra="forbid", validate_assignment=True)
ColumnNamesAPI
¶
Bases: BaseModel
Definition of the column names of the exported model.
Source code in spectrafit/api/tools_model.py
DataPreProcessingAPI
¶
Bases: BaseModel
Definition of the data preprocessing command line argument.
Source code in spectrafit/api/tools_model.py
class DataPreProcessingAPI(BaseModel):
"""Definition of the data preprocessing command line argument."""
oversampling: bool = Field(
default=False,
description="Oversampling the spectra by using factor of 5; default to False.",
)
energy_start: Optional[float] = Field(
default=None,
description="Start energy of the spectra; default to None.",
)
energy_stop: Optional[float] = Field(
default=None,
description="Stop energy of the spectra; default to None.",
)
smooth: int = Field(
default=0,
ge=0,
description="Smoothing level of the spectra; default to 0.",
)
shift: float = Field(
default=0,
description="Shift the energy axis; default to 0.",
)
column: List[Union[int, str]] = Field(
min_length=1,
default=[0, 1],
description="Column of the data.",
)
GeneralSolverModelsAPI
¶
Bases: BaseModel
Definition of the general solver of SpectraFit.
GeneralSolver
The General Solver combines the settings for lmfit
by adding the global fitting settings.
Source code in spectrafit/api/tools_model.py
class GeneralSolverModelsAPI(BaseModel):
"""Definition of the general solver of SpectraFit.
!!! note "GeneralSolver"
The General Solver combines the settings for `lmfit` by adding the global
fitting settings.
"""
global_: int = GlobalFittingAPI().global_
minimizer: Dict[str, Any] = SolverModelsAPI().minimizer
optimizer: Dict[str, Any] = SolverModelsAPI().optimizer
GlobalFittingAPI
¶
SolverModelsAPI
¶
Bases: BaseModel
Definition of the solver of SpectraFit.
Source code in spectrafit/api/tools_model.py
class SolverModelsAPI(BaseModel):
"""Definition of the solver of SpectraFit."""
minimizer: Dict[str, Any] = Field(
default={"nan_policy": "propagate", "calc_covar": True},
description="Minimizer options",
)
optimizer: Dict[str, Any] = Field(
default={"max_nfev": None, "method": "leastsq"},
description="Optimzer options",
)
File Model API¶
Definition of the data file model.
DataFileAPI
¶
Bases: BaseModel
Definition of a data file.
Source code in spectrafit/api/file_model.py
class DataFileAPI(BaseModel):
"""Definition of a data file."""
skiprows: Optional[int] = Field(
default=None,
description="Number of lines to skip at the beginning of the file.",
)
skipfooter: int = Field(
...,
description="Number of lines to skip at the end of the file.",
)
delimiter: str = Field(
...,
description="Delimiter to use.",
)
comment: Optional[str] = Field(
default=None,
description="Comment marker to use.",
)
names: Optional[Callable[[Path, str], Optional[List[str]]]] = Field(
default=None,
description="Column names can be provided by list of strings or a function",
)
header: Optional[Union[int, List[str]]] = Field(
default=None,
description="Column headers to use.",
)
file_suffixes: List[str] = Field(
...,
description="File suffixes to use.",
)
@field_validator("delimiter")
@classmethod
def check_delimiter(cls, v: str) -> Optional[str]:
"""Check if the delimiter is valid."""
if v in {" ", "\t", ",", ";", "|", r"\s+"}:
return v
raise ValueError(f" {v} is not a valid delimiter.")
@field_validator("comment")
@classmethod
def check_comment(cls, v: str) -> Optional[str]:
"""Check if the comment marker is valid."""
if v is None or v in {"#", "%"}:
return v
raise ValueError(f" {v} is not a valid comment marker.")
PPTX Model API¶
PPTXModel class for SpectraFit API.
DescriptionAPI
¶
Field169API
¶
Bases: BaseModel
Field169 class for PPTXData input.
About the field 16:9
The field 16:9
of the elements in the powerpoint presentation defines the structure of the powerpoint presentation with the elements of the header, left subtitle and right subtitle for the ratio of 16:9
with pixel width and height of 1280 and 720 respectively.
Source code in spectrafit/api/pptx_model.py
class Field169API(BaseModel):
"""Field169 class for PPTXData input.
!!! info "About the field `16:9`"
The field `16:9` of the elements in the powerpoint presentation defines the
structure of the powerpoint presentation with the elements of the header,
left subtitle and right subtitle for the ratio of `16:9` with pixel width
and height of __1280__ and __720__ respectively.
"""
ratio: PPTXRatioAPI
structure: PPTXStructureAPI
Field169HDRAPI
¶
Bases: BaseModel
Field169HDRAPI class for PPTXData input.
About the field 16:9 High Definition Resolution (HDR)
The field 16:9
of the elements in the powerpoint presentation defines the structure of the powerpoint presentation with the elements of the header, left subtitle and right subtitle for the ratio of 16:9
with pixel width and height of 1920 and 1080 respectively.
Source code in spectrafit/api/pptx_model.py
class Field169HDRAPI(BaseModel):
"""Field169HDRAPI class for PPTXData input.
!!! info "About the field `16:9 High Definition Resolution (HDR)`"
The field `16:9` of the elements in the powerpoint presentation defines the
structure of the powerpoint presentation with the elements of the header,
left subtitle and right subtitle for the ratio of `16:9` with pixel width
and height of __1920__ and __1080__ respectively.
"""
ratio: PPTXRatioAPI
structure: PPTXStructureAPI
Field43API
¶
Bases: BaseModel
Field43 class for PPTXData input.
About the field 4:3
The field 4:3
of the elements in the powerpoint presentation defines the structure of the powerpoint presentation with the elements of the header, left subtitle and right subtitle for the ratio of 4:3
with pixel width and height of 960 and 720 respectively.
Source code in spectrafit/api/pptx_model.py
class Field43API(BaseModel):
"""Field43 class for PPTXData input.
!!! info "About the field `4:3`"
The field `4:3` of the elements in the powerpoint presentation defines the
structure of the powerpoint presentation with the elements of the header,
left subtitle and right subtitle for the ratio of `4:3` with pixel width
and height of __960__ and __720__ respectively.
"""
ratio: PPTXRatioAPI
structure: PPTXStructureAPI
GoodnessOfFitAPI
¶
Bases: BaseModel
GoodnessOfFit class.
Source code in spectrafit/api/pptx_model.py
InputAPI
¶
MethodAPI
¶
OutputAPI
¶
PPTXBasicTitleAPI
¶
Bases: BaseModel
PPTXBasicTitle class for PPTXData input.
About the basic title
The basic title of the elements in the powerpoint presentation defines the structure of the powerpoint presentation with the elements of the header, left subtitle and right subtitle for the ratio of 16:9
and 4:3
.
Source code in spectrafit/api/pptx_model.py
class PPTXBasicTitleAPI(BaseModel):
"""PPTXBasicTitle class for PPTXData input.
!!! info "About the basic title"
The basic title of the elements in the powerpoint presentation defines the
structure of the powerpoint presentation with the elements of the header,
left subtitle and right subtitle for the ratio of `16:9` and `4:3`.
"""
sub_title_left: str = "Plot: Fitted and Experimental Spectra"
sub_title_right: str = "Tables: Metrics and Variables"
figure_description: str = (
"Figure 1: Fitted and Experimental Spectra with the Residuals"
)
table_1_description: str = "Table 1: Goodness of Fit"
table_2_description: str = "Table 2: Regression Metrics"
table_3_description: str = "Table 3: Variables"
credit_logo: Path = (
Path(str(pkg_resources.get_distribution("spectrafit").location))
/ "spectrafit/plugins/img/SpectraFit.png"
)
credit_description: str = f"SpectraFit: v{__version__}"
PPTXDataAPI
¶
Bases: BaseModel
PPTXData class for SpectraFit API.
Source code in spectrafit/api/pptx_model.py
Config
¶
PPTXDescriptionAPI
¶
Bases: BaseModel
Description class for PPTXData input.
About the description
The description of the elements in the powerpoint presentation. This includes the text of the description for figure, table and textbox.
Source code in spectrafit/api/pptx_model.py
class PPTXDescriptionAPI(BaseModel):
"""Description class for PPTXData input.
!!! info "About the description"
The description of the elements in the powerpoint presentation. This
includes the text of the description for figure, table and textbox.
"""
model_config = ConfigDict(validate_assignment=True, arbitrary_types_allowed=True)
position: PPTXPositionAPI
text: str
font_size: Pt = Field(default_factory=lambda: Pt(8))
PPTXFigureAPI
¶
Bases: BaseModel
Figure class for PPTXData input.
About the figure
The figure of the elements in the powerpoint presentation, which is connected to the PPTXDescriptionAPI
to provide both the figure and the description at the same time. This includes the position of the figure and the description of the figure. The figure can be either a png
or jpg
file and the description is a str
.
Source code in spectrafit/api/pptx_model.py
class PPTXFigureAPI(BaseModel):
"""Figure class for PPTXData input.
!!! info "About the figure"
The figure of the elements in the powerpoint presentation, which is connected
to the `PPTXDescriptionAPI` to provide both the figure and the description at
the same time. This includes the position of the figure and the description
of the figure. The figure can be either a `png` or `jpg` file and the
description is a `str`.
"""
position: PPTXPositionAPI
description: PPTXDescriptionAPI
fname: Path
PPTXHeaderAPI
¶
PPTXLayoutAPI
¶
PPTXLayout class for PPTXData input.
Attributes:
Name | Type | Description |
---|---|---|
pptx_formats | Dict[str, List[Union[Field169API, Field169HDRAPI, Field43API]]] | The formats of the powerpoint presentation. This includes the ratio of |
Source code in spectrafit/api/pptx_model.py
class PPTXLayoutAPI:
"""PPTXLayout class for PPTXData input.
Attributes:
pptx_formats (Dict[str, List[Union[Field169API, Field169HDRAPI, Field43API]]]):
The formats of the powerpoint presentation. This includes the ratio of
`16:9` and `4:3` with pixel width and height of __1280__ and __720__
respectively for `16:9` and __960__ and __720__ respectively for `4:3`.
"""
pptx_formats: Dict[
str, Tuple[Type[Union[Field169API, Field169HDRAPI, Field43API]], Dict[str, int]]
] = {
"16:9": (Field169API, {"width": 1280, "height": 720}),
"16:9HDR": (Field169HDRAPI, {"width": 1920, "height": 1080}),
"4:3": (Field43API, {"width": 960, "height": 720}),
}
def __init__(self, format: str, data: PPTXDataAPI) -> None:
"""Initialize the PPTXLayout class.
Args:
format (str): The format of the powerpoint presentation.
data (PPTXDataAPI): The data of the powerpoint presentation.
"""
self._format = format
self.tmp_fname = self.tmp_plot(pd.DataFrame(data.output.df_fit))
self.title = data.input.description.project_name
self.df_gof = pd.DataFrame({k: [v] for k, v in data.solver.goodness_of_fit})
self.df_regression = pd.DataFrame(**data.solver.regression_metrics.model_dump())
self.df_variables = pd.DataFrame.from_dict(
data.solver.variables, orient="index"
)
def tmp_plot(self, df_fit: pd.DataFrame) -> Path:
"""Create a temporary plot.
Args:
df_fit (pd.DataFrame): The DataFrame containing the fit results.
Returns:
Path: The path to the temporary plot.
"""
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
PlotSpectra(
df=df_fit,
args={},
).plot_local_spectra()
tmp_fname = Path(tmp.name)
plt.savefig(tmp_fname, dpi=300, bbox_inches="tight")
return tmp_fname
def create_ratio(self) -> PPTXRatioAPI:
"""Create the ratio of the powerpoint presentation.
Returns:
PPTXRatioAPI: The ratio of the powerpoint presentation.
"""
return PPTXRatioAPI(
width=Pt(self.pptx_formats[self._format][1]["width"]),
height=Pt(self.pptx_formats[self._format][1]["height"]),
)
def create_header(self) -> PPTXHeaderAPI:
"""Create the header of the powerpoint presentation.
Returns:
PPTXHeaderAPI: The header of the powerpoint presentation.
"""
return PPTXHeaderAPI(
position=PPTXPositionAPI(
left=Pt(0),
top=Pt(0),
width=Pt(self.pptx_formats[self._format][1]["width"]),
height=Pt(self.pptx_formats[self._format][1]["height"] // 5),
),
text=self.title,
)
def create_sub_title_left(self) -> PPTXSubTitleLeftAPI:
"""Create the left subtitle of the powerpoint presentation.
Returns:
PPTXSubTitleLeftAPI: The left subtitle of the powerpoint presentation.
"""
return PPTXSubTitleLeftAPI(
position=PPTXPositionAPI(
left=Pt(0),
top=Pt(self.pptx_formats[self._format][1]["height"] // 5),
width=Pt(self.pptx_formats[self._format][1]["width"] // 2),
height=Pt(self.pptx_formats[self._format][1]["height"] // 10),
),
text=PPTXBasicTitleAPI().sub_title_left,
figure=PPTXFigureAPI(
position=PPTXPositionAPI(
left=Pt(0),
top=Pt(
self.pptx_formats[self._format][1]["height"] // 5
+ self.pptx_formats[self._format][1]["height"] // 10
),
width=Pt(self.pptx_formats[self._format][1]["width"] // 2),
height=Pt(3 * self.pptx_formats[self._format][1]["height"] // 5),
),
description=PPTXDescriptionAPI(
position=PPTXPositionAPI(
left=Pt(0),
top=Pt(
self.pptx_formats[self._format][1]["height"] // 10
+ 4 * self.pptx_formats[self._format][1]["height"] // 5
),
width=Pt(self.pptx_formats[self._format][1]["width"] // 2),
height=Pt(18),
),
text=PPTXBasicTitleAPI().figure_description,
),
fname=self.tmp_fname,
),
)
def create_sub_title_right(self) -> PPTXSubTitleRightAPI:
"""Create the right subtitle of the powerpoint presentation.
Returns:
PPTXSubTitleRightAPI: The right subtitle of the powerpoint presentation.
"""
return PPTXSubTitleRightAPI(
position=PPTXPositionAPI(
left=Pt(self.pptx_formats[self._format][1]["width"] // 2),
top=Pt(self.pptx_formats[self._format][1]["height"] // 5),
width=Pt(self.pptx_formats[self._format][1]["width"] // 2),
height=Pt(self.pptx_formats[self._format][1]["height"] // 10),
),
text=PPTXBasicTitleAPI().sub_title_right,
table_1=self.create_table_1(),
table_2=self.create_table_2(),
table_3=self.create_table_3(),
credit=self.create_credit(),
)
def create_table_1(self) -> PPTXTableAPI:
"""Create the table 1 of the powerpoint presentation.
Returns:
PPTXTableAPI: The table 1 of the powerpoint presentation.
"""
_basic_block = (
self.pptx_formats[self._format][1]["height"] // 5
+ self.pptx_formats[self._format][1]["height"] // 10
)
return PPTXTableAPI(
position=PPTXPositionAPI(
left=Pt(self.pptx_formats[self._format][1]["width"] // 2),
top=Pt(_basic_block + 20),
width=Pt(self.pptx_formats[self._format][1]["width"] // 2),
height=Pt(self.pptx_formats[self._format][1]["height"] // 6),
),
description=PPTXDescriptionAPI(
position=PPTXPositionAPI(
left=Pt(self.pptx_formats[self._format][1]["width"] // 2),
top=Pt(_basic_block),
width=Pt(self.pptx_formats[self._format][1]["width"] // 2),
height=Pt(18),
),
text=PPTXBasicTitleAPI().table_1_description,
),
df=self.df_gof,
transpose=False,
index_hidden=True,
)
def create_table_2(self) -> PPTXTableAPI:
"""Create the table 2 of the powerpoint presentation.
Returns:
PPTXTableAPI: The table 2 of the powerpoint presentation.
"""
_basic_block = (
self.pptx_formats[self._format][1]["height"] // 5
+ self.pptx_formats[self._format][1]["height"] // 10
+ self.pptx_formats[self._format][1]["height"] // 6
)
return PPTXTableAPI(
position=PPTXPositionAPI(
left=Pt(self.pptx_formats[self._format][1]["width"] // 2),
top=Pt(_basic_block + 40),
width=Pt(self.pptx_formats[self._format][1]["width"] // 2),
height=Pt(self.pptx_formats[self._format][1]["height"] // 6),
),
description=PPTXDescriptionAPI(
position=PPTXPositionAPI(
left=Pt(self.pptx_formats[self._format][1]["width"] // 2),
top=Pt(_basic_block + 20),
width=Pt(self.pptx_formats[self._format][1]["width"] // 2),
height=Pt(18),
),
text=PPTXBasicTitleAPI().table_2_description,
),
df=self.df_regression,
transpose=True,
index_hidden=True,
)
def create_table_3(self) -> PPTXTableAPI:
"""Create the table 3 of the powerpoint presentation.
Returns:
PPTXTableAPI: The table 3 of the powerpoint presentation.
"""
_basic_block = (
self.pptx_formats[self._format][1]["height"] // 5
+ self.pptx_formats[self._format][1]["height"] // 10
+ self.pptx_formats[self._format][1]["height"] // 3
)
return PPTXTableAPI(
position=PPTXPositionAPI(
left=Pt(self.pptx_formats[self._format][1]["width"] // 2),
top=Pt(_basic_block + 60),
width=Pt(self.pptx_formats[self._format][1]["width"] // 2),
height=Pt(self.pptx_formats[self._format][1]["height"] // 6),
),
description=PPTXDescriptionAPI(
position=PPTXPositionAPI(
left=Pt(self.pptx_formats[self._format][1]["width"] // 2),
top=Pt(_basic_block + 40),
width=Pt(self.pptx_formats[self._format][1]["width"] // 2),
height=Pt(18),
),
text=PPTXBasicTitleAPI().table_3_description,
),
df=self.df_variables,
transpose=True,
index_hidden=False,
)
def create_credit(self) -> PPTXFigureAPI:
"""Create the credit of the powerpoint presentation.
Returns:
PPTXFigureAPI: The credit of the powerpoint presentation.
"""
return PPTXFigureAPI(
position=PPTXPositionAPI(
left=Pt(self.pptx_formats[self._format][1]["width"] - 40),
top=Pt(self.pptx_formats[self._format][1]["height"] - 40),
width=Pt(40),
height=Pt(40),
),
description=PPTXDescriptionAPI(
position=PPTXPositionAPI(
left=Pt(self.pptx_formats[self._format][1]["width"] - 200),
top=Pt(self.pptx_formats[self._format][1]["height"] - 40),
width=Pt(200),
height=Pt(14),
),
text=PPTXBasicTitleAPI().credit_description,
),
fname=PPTXBasicTitleAPI().credit_logo,
)
def get_pptx_layout(self) -> Union[Field169API, Field169HDRAPI, Field43API]:
"""Get the powerpoint presentation layout.
Returns:
Union[Field169API, Field169HDRAPI, Field43API]: The powerpoint presentation
layout.
"""
return self.pptx_formats[self._format][0](
ratio=self.create_ratio(),
structure=PPTXStructureAPI(
header=self.create_header(),
sub_title_left=self.create_sub_title_left(),
sub_title_right=self.create_sub_title_right(),
),
)
__init__(format, data)
¶
Initialize the PPTXLayout class.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
format | str | The format of the powerpoint presentation. | required |
data | PPTXDataAPI | The data of the powerpoint presentation. | required |
Source code in spectrafit/api/pptx_model.py
def __init__(self, format: str, data: PPTXDataAPI) -> None:
"""Initialize the PPTXLayout class.
Args:
format (str): The format of the powerpoint presentation.
data (PPTXDataAPI): The data of the powerpoint presentation.
"""
self._format = format
self.tmp_fname = self.tmp_plot(pd.DataFrame(data.output.df_fit))
self.title = data.input.description.project_name
self.df_gof = pd.DataFrame({k: [v] for k, v in data.solver.goodness_of_fit})
self.df_regression = pd.DataFrame(**data.solver.regression_metrics.model_dump())
self.df_variables = pd.DataFrame.from_dict(
data.solver.variables, orient="index"
)
create_credit()
¶
Create the credit of the powerpoint presentation.
Returns:
Name | Type | Description |
---|---|---|
PPTXFigureAPI | PPTXFigureAPI | The credit of the powerpoint presentation. |
Source code in spectrafit/api/pptx_model.py
def create_credit(self) -> PPTXFigureAPI:
"""Create the credit of the powerpoint presentation.
Returns:
PPTXFigureAPI: The credit of the powerpoint presentation.
"""
return PPTXFigureAPI(
position=PPTXPositionAPI(
left=Pt(self.pptx_formats[self._format][1]["width"] - 40),
top=Pt(self.pptx_formats[self._format][1]["height"] - 40),
width=Pt(40),
height=Pt(40),
),
description=PPTXDescriptionAPI(
position=PPTXPositionAPI(
left=Pt(self.pptx_formats[self._format][1]["width"] - 200),
top=Pt(self.pptx_formats[self._format][1]["height"] - 40),
width=Pt(200),
height=Pt(14),
),
text=PPTXBasicTitleAPI().credit_description,
),
fname=PPTXBasicTitleAPI().credit_logo,
)
create_header()
¶
Create the header of the powerpoint presentation.
Returns:
Name | Type | Description |
---|---|---|
PPTXHeaderAPI | PPTXHeaderAPI | The header of the powerpoint presentation. |
Source code in spectrafit/api/pptx_model.py
def create_header(self) -> PPTXHeaderAPI:
"""Create the header of the powerpoint presentation.
Returns:
PPTXHeaderAPI: The header of the powerpoint presentation.
"""
return PPTXHeaderAPI(
position=PPTXPositionAPI(
left=Pt(0),
top=Pt(0),
width=Pt(self.pptx_formats[self._format][1]["width"]),
height=Pt(self.pptx_formats[self._format][1]["height"] // 5),
),
text=self.title,
)
create_ratio()
¶
Create the ratio of the powerpoint presentation.
Returns:
Name | Type | Description |
---|---|---|
PPTXRatioAPI | PPTXRatioAPI | The ratio of the powerpoint presentation. |
Source code in spectrafit/api/pptx_model.py
def create_ratio(self) -> PPTXRatioAPI:
"""Create the ratio of the powerpoint presentation.
Returns:
PPTXRatioAPI: The ratio of the powerpoint presentation.
"""
return PPTXRatioAPI(
width=Pt(self.pptx_formats[self._format][1]["width"]),
height=Pt(self.pptx_formats[self._format][1]["height"]),
)
create_sub_title_left()
¶
Create the left subtitle of the powerpoint presentation.
Returns:
Name | Type | Description |
---|---|---|
PPTXSubTitleLeftAPI | PPTXSubTitleLeftAPI | The left subtitle of the powerpoint presentation. |
Source code in spectrafit/api/pptx_model.py
def create_sub_title_left(self) -> PPTXSubTitleLeftAPI:
"""Create the left subtitle of the powerpoint presentation.
Returns:
PPTXSubTitleLeftAPI: The left subtitle of the powerpoint presentation.
"""
return PPTXSubTitleLeftAPI(
position=PPTXPositionAPI(
left=Pt(0),
top=Pt(self.pptx_formats[self._format][1]["height"] // 5),
width=Pt(self.pptx_formats[self._format][1]["width"] // 2),
height=Pt(self.pptx_formats[self._format][1]["height"] // 10),
),
text=PPTXBasicTitleAPI().sub_title_left,
figure=PPTXFigureAPI(
position=PPTXPositionAPI(
left=Pt(0),
top=Pt(
self.pptx_formats[self._format][1]["height"] // 5
+ self.pptx_formats[self._format][1]["height"] // 10
),
width=Pt(self.pptx_formats[self._format][1]["width"] // 2),
height=Pt(3 * self.pptx_formats[self._format][1]["height"] // 5),
),
description=PPTXDescriptionAPI(
position=PPTXPositionAPI(
left=Pt(0),
top=Pt(
self.pptx_formats[self._format][1]["height"] // 10
+ 4 * self.pptx_formats[self._format][1]["height"] // 5
),
width=Pt(self.pptx_formats[self._format][1]["width"] // 2),
height=Pt(18),
),
text=PPTXBasicTitleAPI().figure_description,
),
fname=self.tmp_fname,
),
)
create_sub_title_right()
¶
Create the right subtitle of the powerpoint presentation.
Returns:
Name | Type | Description |
---|---|---|
PPTXSubTitleRightAPI | PPTXSubTitleRightAPI | The right subtitle of the powerpoint presentation. |
Source code in spectrafit/api/pptx_model.py
def create_sub_title_right(self) -> PPTXSubTitleRightAPI:
"""Create the right subtitle of the powerpoint presentation.
Returns:
PPTXSubTitleRightAPI: The right subtitle of the powerpoint presentation.
"""
return PPTXSubTitleRightAPI(
position=PPTXPositionAPI(
left=Pt(self.pptx_formats[self._format][1]["width"] // 2),
top=Pt(self.pptx_formats[self._format][1]["height"] // 5),
width=Pt(self.pptx_formats[self._format][1]["width"] // 2),
height=Pt(self.pptx_formats[self._format][1]["height"] // 10),
),
text=PPTXBasicTitleAPI().sub_title_right,
table_1=self.create_table_1(),
table_2=self.create_table_2(),
table_3=self.create_table_3(),
credit=self.create_credit(),
)
create_table_1()
¶
Create the table 1 of the powerpoint presentation.
Returns:
Name | Type | Description |
---|---|---|
PPTXTableAPI | PPTXTableAPI | The table 1 of the powerpoint presentation. |
Source code in spectrafit/api/pptx_model.py
def create_table_1(self) -> PPTXTableAPI:
"""Create the table 1 of the powerpoint presentation.
Returns:
PPTXTableAPI: The table 1 of the powerpoint presentation.
"""
_basic_block = (
self.pptx_formats[self._format][1]["height"] // 5
+ self.pptx_formats[self._format][1]["height"] // 10
)
return PPTXTableAPI(
position=PPTXPositionAPI(
left=Pt(self.pptx_formats[self._format][1]["width"] // 2),
top=Pt(_basic_block + 20),
width=Pt(self.pptx_formats[self._format][1]["width"] // 2),
height=Pt(self.pptx_formats[self._format][1]["height"] // 6),
),
description=PPTXDescriptionAPI(
position=PPTXPositionAPI(
left=Pt(self.pptx_formats[self._format][1]["width"] // 2),
top=Pt(_basic_block),
width=Pt(self.pptx_formats[self._format][1]["width"] // 2),
height=Pt(18),
),
text=PPTXBasicTitleAPI().table_1_description,
),
df=self.df_gof,
transpose=False,
index_hidden=True,
)
create_table_2()
¶
Create the table 2 of the powerpoint presentation.
Returns:
Name | Type | Description |
---|---|---|
PPTXTableAPI | PPTXTableAPI | The table 2 of the powerpoint presentation. |
Source code in spectrafit/api/pptx_model.py
def create_table_2(self) -> PPTXTableAPI:
"""Create the table 2 of the powerpoint presentation.
Returns:
PPTXTableAPI: The table 2 of the powerpoint presentation.
"""
_basic_block = (
self.pptx_formats[self._format][1]["height"] // 5
+ self.pptx_formats[self._format][1]["height"] // 10
+ self.pptx_formats[self._format][1]["height"] // 6
)
return PPTXTableAPI(
position=PPTXPositionAPI(
left=Pt(self.pptx_formats[self._format][1]["width"] // 2),
top=Pt(_basic_block + 40),
width=Pt(self.pptx_formats[self._format][1]["width"] // 2),
height=Pt(self.pptx_formats[self._format][1]["height"] // 6),
),
description=PPTXDescriptionAPI(
position=PPTXPositionAPI(
left=Pt(self.pptx_formats[self._format][1]["width"] // 2),
top=Pt(_basic_block + 20),
width=Pt(self.pptx_formats[self._format][1]["width"] // 2),
height=Pt(18),
),
text=PPTXBasicTitleAPI().table_2_description,
),
df=self.df_regression,
transpose=True,
index_hidden=True,
)
create_table_3()
¶
Create the table 3 of the powerpoint presentation.
Returns:
Name | Type | Description |
---|---|---|
PPTXTableAPI | PPTXTableAPI | The table 3 of the powerpoint presentation. |
Source code in spectrafit/api/pptx_model.py
def create_table_3(self) -> PPTXTableAPI:
"""Create the table 3 of the powerpoint presentation.
Returns:
PPTXTableAPI: The table 3 of the powerpoint presentation.
"""
_basic_block = (
self.pptx_formats[self._format][1]["height"] // 5
+ self.pptx_formats[self._format][1]["height"] // 10
+ self.pptx_formats[self._format][1]["height"] // 3
)
return PPTXTableAPI(
position=PPTXPositionAPI(
left=Pt(self.pptx_formats[self._format][1]["width"] // 2),
top=Pt(_basic_block + 60),
width=Pt(self.pptx_formats[self._format][1]["width"] // 2),
height=Pt(self.pptx_formats[self._format][1]["height"] // 6),
),
description=PPTXDescriptionAPI(
position=PPTXPositionAPI(
left=Pt(self.pptx_formats[self._format][1]["width"] // 2),
top=Pt(_basic_block + 40),
width=Pt(self.pptx_formats[self._format][1]["width"] // 2),
height=Pt(18),
),
text=PPTXBasicTitleAPI().table_3_description,
),
df=self.df_variables,
transpose=True,
index_hidden=False,
)
get_pptx_layout()
¶
Get the powerpoint presentation layout.
Returns:
Type | Description |
---|---|
Union[Field169API, Field169HDRAPI, Field43API] | Union[Field169API, Field169HDRAPI, Field43API]: The powerpoint presentation layout. |
Source code in spectrafit/api/pptx_model.py
def get_pptx_layout(self) -> Union[Field169API, Field169HDRAPI, Field43API]:
"""Get the powerpoint presentation layout.
Returns:
Union[Field169API, Field169HDRAPI, Field43API]: The powerpoint presentation
layout.
"""
return self.pptx_formats[self._format][0](
ratio=self.create_ratio(),
structure=PPTXStructureAPI(
header=self.create_header(),
sub_title_left=self.create_sub_title_left(),
sub_title_right=self.create_sub_title_right(),
),
)
tmp_plot(df_fit)
¶
Create a temporary plot.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df_fit | DataFrame | The DataFrame containing the fit results. | required |
Returns:
Name | Type | Description |
---|---|---|
Path | Path | The path to the temporary plot. |
Source code in spectrafit/api/pptx_model.py
def tmp_plot(self, df_fit: pd.DataFrame) -> Path:
"""Create a temporary plot.
Args:
df_fit (pd.DataFrame): The DataFrame containing the fit results.
Returns:
Path: The path to the temporary plot.
"""
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
PlotSpectra(
df=df_fit,
args={},
).plot_local_spectra()
tmp_fname = Path(tmp.name)
plt.savefig(tmp_fname, dpi=300, bbox_inches="tight")
return tmp_fname
PPTXPositionAPI
¶
Bases: BaseModel
Position class for PPTXData input.
About the position
The position of the elements in the powerpoint presentation. This includes the top, left, width and height of the elements for figure, table and textbox. All the values are in pixels.
Source code in spectrafit/api/pptx_model.py
class PPTXPositionAPI(BaseModel):
"""Position class for PPTXData input.
!!! info "About the position"
The position of the elements in the powerpoint presentation. This includes
the top, left, width and height of the elements for figure, table and
textbox. All the values are in pixels.
"""
model_config = ConfigDict(validate_assignment=True, arbitrary_types_allowed=True)
left: Pt
top: Pt
width: Pt
height: Pt
PPTXRatioAPI
¶
Bases: BaseModel
Ratio class for PPTXData input.
About the ratio
The ratio of the powerpoint presentation. This includes the width and height of the powerpoint presentation. The ratio is either 16:9
or 4:3
. The default ratio is 16:9
and the default width and height are 1920
and 1080
respectively. The width and height are in pixels.
Source code in spectrafit/api/pptx_model.py
class PPTXRatioAPI(BaseModel, arbitrary_types_allowed=True):
"""Ratio class for PPTXData input.
!!! info "About the ratio"
The ratio of the powerpoint presentation. This includes the width and height
of the powerpoint presentation. The ratio is either `16:9` or `4:3`. The
default ratio is `16:9` and the default width and height are `1920` and
`1080` respectively. The width and height are in pixels.
"""
model_config = ConfigDict(validate_assignment=True, arbitrary_types_allowed=True)
width: Pt
height: Pt
PPTXStructureAPI
¶
PPTXSubTitleLeftAPI
¶
Bases: BaseModel
SubTitle_1 class for PPTXData input.
About the left subtitle
The left subtitle of the elements in the powerpoint presentation defines the first column of the powerpoint presentation with the elements of the subtitle, the figure and the description of the figure. This includes the position of the subtitle, the text of the subtitle, the figure and the description of the figure.
Source code in spectrafit/api/pptx_model.py
class PPTXSubTitleLeftAPI(BaseModel):
"""SubTitle_1 class for PPTXData input.
!!! info "About the left subtitle"
The left subtitle of the elements in the powerpoint presentation defines the
first column of the powerpoint presentation with the elements of the subtitle,
the figure and the description of the figure. This includes the position of
the subtitle, the text of the subtitle, the figure and the description of the
figure.
"""
index: int = 1
position: PPTXPositionAPI
text: str
figure: PPTXFigureAPI
PPTXSubTitleRightAPI
¶
Bases: BaseModel
SubTitle_2 class for PPTXData input.
About the right subtitle
The right subtitle of the elements in the powerpoint presentation defines the second column of the powerpoint presentation with the elements of the subtitle, the tables and their descriptions. The tables are divided into three tables for goodness_of_fit
, regression_metrics
and variables
. This includes the position of the subtitle, the text of the subtitle, the tables and their descriptions. Finally, the credit of the figure is also included in the right subtitle.
Source code in spectrafit/api/pptx_model.py
class PPTXSubTitleRightAPI(BaseModel):
"""SubTitle_2 class for PPTXData input.
!!! info "About the right subtitle"
The right subtitle of the elements in the powerpoint presentation defines the
second column of the powerpoint presentation with the elements of the subtitle,
the tables and their descriptions. The tables are divided into three tables for
`goodness_of_fit`, `regression_metrics` and `variables`. This includes the
position of the subtitle, the text of the subtitle, the tables and their
descriptions. Finally, the credit of the figure is also included in the
right subtitle.
"""
index: int = 2
position: PPTXPositionAPI
text: str
table_1: PPTXTableAPI
table_2: PPTXTableAPI
table_3: PPTXTableAPI
credit: PPTXFigureAPI
PPTXTableAPI
¶
Bases: BaseModel
Table class for PPTXData input.
About the table
The table of the elements in the powerpoint presentation, which is connected to the PPTXDescriptionAPI
to provide both the table and the description at the same time. This includes the position of the table and the description of the table. The table is a pandas.DataFrame
and the description is a str
.
Source code in spectrafit/api/pptx_model.py
class PPTXTableAPI(BaseModel):
"""Table class for PPTXData input.
!!! info "About the table"
The table of the elements in the powerpoint presentation, which is connected
to the `PPTXDescriptionAPI` to provide both the table and the description at
the same time. This includes the position of the table and the description
of the table. The table is a `pandas.DataFrame` and the description is a
`str`.
"""
model_config = ConfigDict(validate_assignment=True, arbitrary_types_allowed=True)
df: pd.DataFrame
transpose: bool
index_hidden: bool
position: PPTXPositionAPI
description: PPTXDescriptionAPI
RegressionMetricsAPI
¶
Bases: BaseModel
RegressionMetrics class.
Source code in spectrafit/api/pptx_model.py
class RegressionMetricsAPI(BaseModel):
"""RegressionMetrics class."""
index: List[str]
columns: List[int]
data: List[List[float]]
@field_validator("index")
@classmethod
def short_metrics(cls, v: List[str]) -> List[str]:
"""Shorten the metrics names.
Args:
v (List[str]): The metrics names.
Returns:
List[str]: The shortened metrics names.
"""
pattern = r"(?<!\d)[a-zA-Z0-9]{2,}(?!\d)"
abbreviations: Dict[str, str] = {}
for metric in v:
abbreviation = "".join(re.findall(pattern, metric)).lower()[:2]
while abbreviation in abbreviations.values() or len(abbreviation) < 2:
abbreviation = "".join(re.findall(pattern, metric)).lower()[
: len(abbreviation) + 1
]
abbreviations[metric] = abbreviation
return list(abbreviations.values())
short_metrics(v)
classmethod
¶
Shorten the metrics names.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
v | List[str] | The metrics names. | required |
Returns:
Type | Description |
---|---|
List[str] | List[str]: The shortened metrics names. |
Source code in spectrafit/api/pptx_model.py
@field_validator("index")
@classmethod
def short_metrics(cls, v: List[str]) -> List[str]:
"""Shorten the metrics names.
Args:
v (List[str]): The metrics names.
Returns:
List[str]: The shortened metrics names.
"""
pattern = r"(?<!\d)[a-zA-Z0-9]{2,}(?!\d)"
abbreviations: Dict[str, str] = {}
for metric in v:
abbreviation = "".join(re.findall(pattern, metric)).lower()[:2]
while abbreviation in abbreviations.values() or len(abbreviation) < 2:
abbreviation = "".join(re.findall(pattern, metric)).lower()[
: len(abbreviation) + 1
]
abbreviations[metric] = abbreviation
return list(abbreviations.values())
SolverAPI
¶
Bases: BaseModel
Solver class for getting the metrics of the fit for PPTXData output.
Source code in spectrafit/api/pptx_model.py
class SolverAPI(BaseModel):
"""Solver class for getting the metrics of the fit for PPTXData output."""
goodness_of_fit: GoodnessOfFitAPI
regression_metrics: RegressionMetricsAPI
variables: Dict[str, Dict[str, float]]
@field_validator("variables")
@classmethod
def short_variables(
cls, v: Dict[str, Dict[str, float]]
) -> Dict[str, Dict[str, float]]:
"""Shorten the variables names.
Args:
v (Dict[str, Dict[str, float]]): The variables names.
Returns:
Dict[str, Dict[str, float]]: The shortened variables names.
"""
new_dict = {}
for key, value in v.items():
new_key = "".join([part[:2] for part in key.split("_")])
new_value = {}
for sub_key, sub_value in value.items():
new_sub_key = sub_key.replace("_value", "")
new_value[new_sub_key] = sub_value
new_dict[new_key] = new_value
return new_dict
short_variables(v)
classmethod
¶
Shorten the variables names.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
v | Dict[str, Dict[str, float]] | The variables names. | required |
Returns:
Type | Description |
---|---|
Dict[str, Dict[str, float]] | Dict[str, Dict[str, float]]: The shortened variables names. |
Source code in spectrafit/api/pptx_model.py
@field_validator("variables")
@classmethod
def short_variables(
cls, v: Dict[str, Dict[str, float]]
) -> Dict[str, Dict[str, float]]:
"""Shorten the variables names.
Args:
v (Dict[str, Dict[str, float]]): The variables names.
Returns:
Dict[str, Dict[str, float]]: The shortened variables names.
"""
new_dict = {}
for key, value in v.items():
new_key = "".join([part[:2] for part in key.split("_")])
new_value = {}
for sub_key, sub_value in value.items():
new_sub_key = sub_key.replace("_value", "")
new_value[new_sub_key] = sub_value
new_dict[new_key] = new_value
return new_dict