Skip to content

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:

  1. Data Validation
  2. 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
Python
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
Python
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.

Source code in spectrafit/api/cmd_model.py
Python
@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]

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
Python
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
Python
class AtanAPI(BaseModel):
    """Definition of the Step of the models distributions."""

    amplitude: AmplitudeAPI = AmplitudeAPI()
    center: CenterAPI = CenterAPI()
    sigma: SigmaAPI = SigmaAPI()

CGaussianAPI

Bases: BaseModel

Definition of the cumulative Gaussian of the models distributions.

Source code in spectrafit/api/models_model.py
Python
class CGaussianAPI(BaseModel):
    """Definition of the cumulative Gaussian of the models distributions."""

    amplitude: AmplitudeAPI = AmplitudeAPI()
    center: CenterAPI = CenterAPI()
    fwhmg: FwhmgAPI = FwhmgAPI()

CLorentzianAPI

Bases: BaseModel

Definition of the cumulative Lorentzian of the models distributions.

Source code in spectrafit/api/models_model.py
Python
class CLorentzianAPI(BaseModel):
    """Definition of the cumulative Lorentzian of the models distributions."""

    amplitude: AmplitudeAPI = AmplitudeAPI()
    center: CenterAPI = CenterAPI()
    fwhml: FwhmlAPI = FwhmlAPI()

CVoigtAPI

Bases: BaseModel

Definition of the cumulative Voigt of the models distributions.

Source code in spectrafit/api/models_model.py
Python
class CVoigtAPI(BaseModel):
    """Definition of the cumulative Voigt of the models distributions."""

    center: CenterAPI = CenterAPI()
    fwhmv: FwhmvAPI = FwhmvAPI()
    gamma: GammaAPI = GammaAPI()

CenterAPI

Bases: BaseModel

Definition of the center of the models distributions.

Source code in spectrafit/api/models_model.py
Python
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__)

ConfIntervalAPI

Bases: BaseModel

Definition of Confidence Interval Function.

Source code in spectrafit/api/models_model.py
Python
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

Bases: BaseModel

Definition of the Constant of the models distributions.

Source code in spectrafit/api/models_model.py
Python
class ConstantAPI(BaseModel):
    """Definition of the Constant of the models distributions."""

    amplitude: AmplitudeAPI = AmplitudeAPI()

DecayAPI

Bases: BaseModel

Definition of the Decay of the Exponential of the models distributions.

Source code in spectrafit/api/models_model.py
Python
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
Python
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()

ErfAPI

Bases: BaseModel

Definition of the Step of the models distributions.

Source code in spectrafit/api/models_model.py
Python
class ErfAPI(BaseModel):
    """Definition of the Step of the models distributions."""

    amplitude: AmplitudeAPI = AmplitudeAPI()
    center: CenterAPI = CenterAPI()
    sigma: SigmaAPI = SigmaAPI()

ExponentAPI

Bases: BaseModel

Definition of the Exponent of the Linear of the models distributions.

Source code in spectrafit/api/models_model.py
Python
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
Python
class ExponentialAPI(BaseModel):
    """Definition of the Exponential of the models distributions."""

    amplitude: AmplitudeAPI = AmplitudeAPI()
    decay: DecayAPI = DecayAPI()
    intercept: InterceptAPI = InterceptAPI()

FwhmgAPI

Bases: BaseModel

Definition of the FWHM Gaussian of the models distributions.

Source code in spectrafit/api/models_model.py
Python
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
Python
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
Python
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
Python
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
Python
class GaussianAPI(BaseModel):
    """Definition of the Gaussian of the models distributions."""

    amplitude: AmplitudeAPI = AmplitudeAPI()
    center: CenterAPI = CenterAPI()
    fwhmg: FwhmgAPI = FwhmgAPI()

HeavisideAPI

Bases: BaseModel

Definition of the Step of the models distributions.

Source code in spectrafit/api/models_model.py
Python
class HeavisideAPI(BaseModel):
    """Definition of the Step of the models distributions."""

    amplitude: AmplitudeAPI = AmplitudeAPI()
    center: CenterAPI = CenterAPI()
    sigma: SigmaAPI = SigmaAPI()

InterceptAPI

Bases: BaseModel

Definition of the Intercept of the Linear of the models distributions.

Source code in spectrafit/api/models_model.py
Python
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__)

LinearAPI

Bases: BaseModel

Definition of the Linear of the models distributions.

Source code in spectrafit/api/models_model.py
Python
class LinearAPI(BaseModel):
    """Definition of the Linear of the models distributions."""

    slope: SlopeAPI = SlopeAPI()
    intercept: InterceptAPI = InterceptAPI()

LogAPI

Bases: BaseModel

Definition of the Step of the models distributions.

Source code in spectrafit/api/models_model.py
Python
class LogAPI(BaseModel):
    """Definition of the Step of the models distributions."""

    amplitude: AmplitudeAPI = AmplitudeAPI()
    center: CenterAPI = CenterAPI()
    sigma: SigmaAPI = SigmaAPI()

LorentzianAPI

Bases: BaseModel

Definition of the Lorentzian of the models distributions.

Source code in spectrafit/api/models_model.py
Python
class LorentzianAPI(BaseModel):
    """Definition of the Lorentzian of the models distributions."""

    amplitude: AmplitudeAPI = AmplitudeAPI()
    center: CenterAPI = CenterAPI()
    fwhml: FwhmlAPI = FwhmlAPI()

PowerAPI

Bases: BaseModel

Definition of the Power of the models distributions.

Source code in spectrafit/api/models_model.py
Python
class PowerAPI(BaseModel):
    """Definition of the Power of the models distributions."""

    amplitude: AmplitudeAPI = AmplitudeAPI()
    exponent: ExponentAPI = ExponentAPI()
    intercept: InterceptAPI = InterceptAPI()

PseudovoigtAPI

Bases: BaseModel

Definition of the Pseudovoigt of the models distributions.

Source code in spectrafit/api/models_model.py
Python
class PseudovoigtAPI(BaseModel):
    """Definition of the Pseudovoigt of the models distributions."""

    amplitude: AmplitudeAPI = AmplitudeAPI()
    center: CenterAPI = CenterAPI()
    fwhmg: FwhmgAPI = FwhmgAPI()
    fwhml: FwhmlAPI = FwhmlAPI()

SigmaAPI

Bases: BaseModel

Definition of the Sigma of the models distributions.

Source code in spectrafit/api/models_model.py
Python
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__)

SlopeAPI

Bases: BaseModel

Definition of the Slope of the Linear of the models distributions.

Source code in spectrafit/api/models_model.py
Python
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

Bases: BaseModel

Definition of the Voigt of the models distributions.

Source code in spectrafit/api/models_model.py
Python
class VoigtAPI(BaseModel):
    """Definition of the Voigt of the models distributions."""

    center: CenterAPI = CenterAPI()
    fwhmv: FwhmvAPI = FwhmvAPI()
    gamma: GammaAPI = GammaAPI()

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
Python
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 transparent to the rgb value rgba(0,0,0,0).

Source code in spectrafit/api/notebook_model.py
Python
@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
Python
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
Python
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
Python
class GridAPI(BaseModel):
    """Definition of the grid of the plotly figure."""

    show: bool = Field(default=True, description="Show grid lines.")
    ticks: str = Field(default="outside", description="Show grid ticks.")
    dash: str = Field(default="dot", description="Show grid dashes.")

LegendAPI

Bases: BaseModel

Definition of the legend of the plotly figure.

Source code in spectrafit/api/notebook_model.py
Python
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
Python
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
Python
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
Python
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
Python
class RunAPI(BaseModel):
    """Definition of the residual plot (Y-Axis) of the plotly figure."""

    name: str = Field(default="Run", description="Name of the Run-axis of the plot.")
    unit: Optional[str] = Field(
        default="#", description="Name of the run-axis units of the plot."
    )

XAxisAPI

Bases: BaseModel

Defintion of the X-Axis of the plotly figure.

Source code in spectrafit/api/notebook_model.py
Python
class XAxisAPI(BaseModel):
    """Defintion of the X-Axis of the plotly figure."""

    name: str = Field(default="Energy", description="Name of the x-axis of the plot.")
    unit: Optional[str] = Field(
        default="eV", description="Name of the x-axis units of the plot."
    )

YAxisAPI

Bases: BaseModel

Defintion of the Y-Axis of the plotly figure.

Source code in spectrafit/api/notebook_model.py
Python
class YAxisAPI(BaseModel):
    """Defintion of the Y-Axis of the plotly figure."""

    name: str = Field(
        default="Intensity", description="Name of the y-axis of the plot."
    )
    unit: Optional[str] = Field(
        default="a.u.", description="Name of the y-axis units of the plot."
    )

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
Python
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
Python
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
Python
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
Python
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
Python
class ReportAPI(BaseModel):
    """Definition of the report model."""

    input: InputAPI = Field(
        ...,
        description="Input data for the report.",
    )
    solver: SolverAPI = Field(
        ...,
        description="Solver data for the report.",
    )
    output: OutputAPI = Field(
        ...,
        description="Output data for the report.",
    )

SolverAPI

Bases: BaseModel

Solver API for the report endpoint.

Source code in spectrafit/api/report_model.py
Python
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",
    )

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
Python
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
Python
class ColumnNamesAPI(BaseModel):
    """Definition of the column names of the exported model."""

    energy: str = "energy"
    intensity: str = "intensity"
    residual: str = "residual"
    fit: str = "fit"

DataPreProcessingAPI

Bases: BaseModel

Definition of the data preprocessing command line argument.

Source code in spectrafit/api/tools_model.py
Python
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,
        dtypes=float,
        description="Start energy of the spectra; default to None.",
    )
    energy_stop: Optional[float] = Field(
        default=None,
        dtypes=float,
        description="Stop energy of the spectra; default to None.",
    )
    smooth: int = Field(
        default=0,
        ge=0,
        dtypes=int,
        description="Smoothing level of the spectra; default to 0.",
    )
    shift: float = Field(
        default=0,
        dtypes=float,
        description="Shift the energy axis; default to 0.",
    )
    column: List[Union[int, str]] = Field(
        min_length=1,
        default=[0, 1],
        dtypes=[int, str],
        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
Python
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

Bases: BaseModel

Definition of the global fitting routine.

Source code in spectrafit/api/tools_model.py
Python
class GlobalFittingAPI(BaseModel):
    """Definition of the global fitting routine."""

    global_: int = Field(default=0, ge=0, le=2, description="Global fitting routine.")

SolverModelsAPI

Bases: BaseModel

Definition of the solver of SpectraFit.

Source code in spectrafit/api/tools_model.py
Python
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": 1000, "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
Python
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.")

check_comment(v) classmethod

Check if the comment marker is valid.

Source code in spectrafit/api/file_model.py
Python
@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.")

check_delimiter(v) classmethod

Check if the delimiter is valid.

Source code in spectrafit/api/file_model.py
Python
@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.")