Skip to content

Jupyter-Notebook

About the Notebook API

The Notebook API is a new feature in the v0.12.0 release of SpectraFit with major focus on working with Jupyter Notebooks.

The Notebook API is a work in progress and is subject to change.

Jupyter Notebook plugin for SpectraFit.

DataFrameDisplay

Class for displaying a dataframe in different ways.

Source code in spectrafit/plugins/notebook.py
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
class DataFrameDisplay:
    """Class for displaying a dataframe in different ways."""

    def df_display(self, df: pd.DataFrame, mode: Optional[str] = None) -> None:
        """Call the DataframeDisplay class.

        !!! info "About `df_display`"

            This function is used to display a dataframe in two different ways.

            1. Regular display mode:
                1. Via `IPython.display` for regular sliced displaying of the dataframe
                   in the notebook.
                2. Via `IPython.display` as Markdown for regular displaying of the
                    complete dataframe in the notebook.
            2. Interactive display mode:
                1. Via `itables` for interactive displaying of the dataframe in the
                    notebook, which allows for sorting, filtering, and jumping. For
                    more information see [itables](https://github.com/mwouts/itables).
                2. Via `dtale` for interactive displaying of the dataframe in the
                    notebook, which allows advanced data analysis of the dataframe in
                    an external window. For more information see
                    [dtale](https://github.com/man-group/dtale).

        Args:
            df (pd.DataFrame): Dataframe to display.
            mode (str, Optional): Display mode. Defaults to None.

        Raises:
            ValueError: Raises ValueError if mode of displaying is not supported.
        """
        if mode == "regular":
            self.regular_display(df=df)
        elif mode == "markdown":
            self.markdown_display(df=df)
        elif mode == "interactive":
            self.interactive_display(df=df)
        elif mode == "dtale":
            self.dtale_display(df=df)
        elif mode is not None:
            raise ValueError(
                f"Invalid mode: {mode}. "
                "Valid modes are: regular, interactive, dtale, markdown."
            )

    @staticmethod
    def regular_display(df: pd.DataFrame) -> None:
        """Display the dataframe in a regular way.

        Args:
            df (pd.DataFrame): Dataframe to display.
        """
        display(df)

    @staticmethod
    def interactive_display(df: pd.DataFrame) -> None:
        """Display the dataframe in an interactive way.

        Args:
            df (pd.DataFrame): Dataframe to display.
        """
        itables_show(df)

    @staticmethod
    def dtale_display(df: pd.DataFrame) -> None:
        """Display the dataframe in a dtale way.

        Args:
            df (pd.DataFrame): Dataframe to display.
        """
        dtale_show(df)

    @staticmethod
    def markdown_display(df: pd.DataFrame) -> None:
        """Display the dataframe in a markdown way.

        Args:
            df (pd.DataFrame): Dataframe to display.
        """
        display_markdown(df.to_markdown(), raw=True)

df_display(df, mode=None)

Call the DataframeDisplay class.

About df_display

This function is used to display a dataframe in two different ways.

  1. Regular display mode:
    1. Via IPython.display for regular sliced displaying of the dataframe in the notebook.
    2. Via IPython.display as Markdown for regular displaying of the complete dataframe in the notebook.
  2. Interactive display mode:
    1. Via itables for interactive displaying of the dataframe in the notebook, which allows for sorting, filtering, and jumping. For more information see itables.
    2. Via dtale for interactive displaying of the dataframe in the notebook, which allows advanced data analysis of the dataframe in an external window. For more information see dtale.

Parameters:

Name Type Description Default
df pd.DataFrame

Dataframe to display.

required
mode str, Optional

Display mode. Defaults to None.

None

Raises:

Type Description
ValueError

Raises ValueError if mode of displaying is not supported.

Source code in spectrafit/plugins/notebook.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
def df_display(self, df: pd.DataFrame, mode: Optional[str] = None) -> None:
    """Call the DataframeDisplay class.

    !!! info "About `df_display`"

        This function is used to display a dataframe in two different ways.

        1. Regular display mode:
            1. Via `IPython.display` for regular sliced displaying of the dataframe
               in the notebook.
            2. Via `IPython.display` as Markdown for regular displaying of the
                complete dataframe in the notebook.
        2. Interactive display mode:
            1. Via `itables` for interactive displaying of the dataframe in the
                notebook, which allows for sorting, filtering, and jumping. For
                more information see [itables](https://github.com/mwouts/itables).
            2. Via `dtale` for interactive displaying of the dataframe in the
                notebook, which allows advanced data analysis of the dataframe in
                an external window. For more information see
                [dtale](https://github.com/man-group/dtale).

    Args:
        df (pd.DataFrame): Dataframe to display.
        mode (str, Optional): Display mode. Defaults to None.

    Raises:
        ValueError: Raises ValueError if mode of displaying is not supported.
    """
    if mode == "regular":
        self.regular_display(df=df)
    elif mode == "markdown":
        self.markdown_display(df=df)
    elif mode == "interactive":
        self.interactive_display(df=df)
    elif mode == "dtale":
        self.dtale_display(df=df)
    elif mode is not None:
        raise ValueError(
            f"Invalid mode: {mode}. "
            "Valid modes are: regular, interactive, dtale, markdown."
        )

dtale_display(df) staticmethod

Display the dataframe in a dtale way.

Parameters:

Name Type Description Default
df pd.DataFrame

Dataframe to display.

required
Source code in spectrafit/plugins/notebook.py
111
112
113
114
115
116
117
118
@staticmethod
def dtale_display(df: pd.DataFrame) -> None:
    """Display the dataframe in a dtale way.

    Args:
        df (pd.DataFrame): Dataframe to display.
    """
    dtale_show(df)

interactive_display(df) staticmethod

Display the dataframe in an interactive way.

Parameters:

Name Type Description Default
df pd.DataFrame

Dataframe to display.

required
Source code in spectrafit/plugins/notebook.py
102
103
104
105
106
107
108
109
@staticmethod
def interactive_display(df: pd.DataFrame) -> None:
    """Display the dataframe in an interactive way.

    Args:
        df (pd.DataFrame): Dataframe to display.
    """
    itables_show(df)

markdown_display(df) staticmethod

Display the dataframe in a markdown way.

Parameters:

Name Type Description Default
df pd.DataFrame

Dataframe to display.

required
Source code in spectrafit/plugins/notebook.py
120
121
122
123
124
125
126
127
@staticmethod
def markdown_display(df: pd.DataFrame) -> None:
    """Display the dataframe in a markdown way.

    Args:
        df (pd.DataFrame): Dataframe to display.
    """
    display_markdown(df.to_markdown(), raw=True)

regular_display(df) staticmethod

Display the dataframe in a regular way.

Parameters:

Name Type Description Default
df pd.DataFrame

Dataframe to display.

required
Source code in spectrafit/plugins/notebook.py
 93
 94
 95
 96
 97
 98
 99
100
@staticmethod
def regular_display(df: pd.DataFrame) -> None:
    """Display the dataframe in a regular way.

    Args:
        df (pd.DataFrame): Dataframe to display.
    """
    display(df)

DataFramePlot

Class to plot a dataframe.

Source code in spectrafit/plugins/notebook.py
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
class DataFramePlot:
    """Class to plot a dataframe."""

    def plot_2dataframes(
        self,
        args_plot: PlotAPI,
        df_1: pd.DataFrame,
        df_2: Optional[pd.DataFrame] = None,
    ) -> None:
        """Plot of two dataframes.

        !!! info "About the plot"

            The plot is a combination of two plots. The first plot is the
            can be the residual plot of a fit or the _modified_ data. The second
            plot can be the fit or the original data.

        !!! missing "`line_dash_map`"

            Currently, the `line_dash_map` is not working, and the dash is not
            plotted. Most likely, this is related to the fact that the columns
            are not labeled in the dataframe.

        Args:
            args_plot (PlotAPI): PlotAPI object for the settings of the plot.
            df_1 (pd.DataFrame): First dataframe to plot, which will generate
                 automatically a fit plot with residual plot. The ratio is 70% to 20%
                 with 10% space in between.
            df_2 (Optional[pd.DataFrame], optional): Second optional dataframe to
                 plot for comparsion. In this case, the ratio will between first
                 and second plot will be same. Defaults to None.
        """
        if df_2 is None:
            _fig1 = px.line(
                df_1,
                x=ColumnNamesAPI().energy,
                y=ColumnNamesAPI().residual,
                color_discrete_sequence=[args_plot.color.residual],
            )
            _y = df_1.columns.drop([ColumnNamesAPI().energy, ColumnNamesAPI().residual])
            _fig2 = px.line(
                df_1,
                x=ColumnNamesAPI().energy,
                y=_y,
                color_discrete_map={
                    ColumnNamesAPI().intensity: args_plot.color.intensity,
                    ColumnNamesAPI().fit: args_plot.color.fit,
                    **{
                        key: args_plot.color.components
                        for key in _y.drop(
                            [ColumnNamesAPI().intensity, ColumnNamesAPI().fit]
                        )
                    },
                },
                line_dash_map={
                    ColumnNamesAPI().intensity: "solid",
                    ColumnNamesAPI().fit: "longdash",
                    **{
                        key: "dash"
                        for key in _y.drop(
                            [ColumnNamesAPI().intensity, ColumnNamesAPI().fit]
                        )
                    },
                },
            )
        else:
            _fig1 = px.line(df_1, x=args_plot.x, y=args_plot.y)
            _fig2 = px.line(df_2, x=args_plot.x, y=args_plot.y)

        fig = make_subplots(
            rows=2, cols=1, shared_xaxes=True, shared_yaxes=True, vertical_spacing=0.05
        )

        for _spec_1 in _fig1["data"]:
            fig.append_trace(_spec_1, row=1, col=1)
        for _spec_2 in _fig2["data"]:
            fig.append_trace(_spec_2, row=2, col=1)
        height = args_plot.size[1][0]
        self.update_layout_axes(fig, args_plot, height)
        xaxis_title = self.title_text(
            name=args_plot.xaxis_title.name, unit=args_plot.xaxis_title.unit
        )
        yaxis_title = self.title_text(
            name=args_plot.yaxis_title.name, unit=args_plot.yaxis_title.unit
        )

        fig.update_xaxes(title_text=xaxis_title, row=1, col=1)
        fig.update_xaxes(title_text=xaxis_title, row=2, col=1)
        if df_2 is None:
            residual_title = self.title_text(
                name=args_plot.residual_title.name, unit=args_plot.residual_title.unit
            )
            fig["layout"]["yaxis1"].update(domain=[0.8, 1])
            fig["layout"]["yaxis2"].update(domain=[0, 0.7])
            fig.update_yaxes(title_text=residual_title, row=1, col=1)
        else:
            fig.update_yaxes(title_text=yaxis_title, row=1, col=1)
        fig.update_yaxes(title_text=yaxis_title, row=2, col=1)
        fig.show()

    def plot_dataframe(self, args_plot: PlotAPI, df: pd.DataFrame) -> None:
        """Plot the dataframe according to the PlotAPI arguments.

        Args:
            args_plot (PlotAPI): PlotAPI object for the settings of the plot.
            df (pd.DataFrame): Dataframe to plot.
        """
        fig = px.line(df, x=args_plot.x, y=args_plot.y)
        height = args_plot.size[1][0]
        self.update_layout_axes(fig, args_plot, height)
        fig.update_xaxes(
            title_text=self.title_text(
                name=args_plot.xaxis_title.name, unit=args_plot.xaxis_title.unit
            )
        )
        fig.update_yaxes(
            title_text=self.title_text(
                name=args_plot.yaxis_title.name, unit=args_plot.yaxis_title.unit
            )
        )
        fig.show()

    def plot_global_fit(self, args_plot: PlotAPI, df: pd.DataFrame) -> None:
        """Plot the global dataframe according to the PlotAPI arguments.

        Args:
            args_plot (PlotAPI): PlotAPI object for the settings of the plot.
            df (pd.DataFrame): Dataframe to plot.
        """
        for i in range(
            1,
            sum(1 for _col in df.columns if _col.startswith(ColumnNamesAPI().fit)) + 1,
        ):
            _col = [col for col in df.columns if col.endswith(str(i))]
            _col.append(ColumnNamesAPI().energy)
            _df = df[_col]
            _df = _df.rename(
                columns={
                    f"{ColumnNamesAPI().intensity}_{i}": ColumnNamesAPI().intensity,
                    f"{ColumnNamesAPI().fit}_{i}": ColumnNamesAPI().fit,
                    f"{ColumnNamesAPI().residual}_{i}": ColumnNamesAPI().residual,
                }
            )
            self.plot_2dataframes(args_plot, _df)

    def plot_metric(
        self,
        args_plot: PlotAPI,
        df_metric: pd.DataFrame,
        bar_criteria: Union[str, List[str]],
        line_criteria: Union[str, List[str]],
    ) -> None:
        """Plot the metric according to the PlotAPI arguments.

        Args:
            args_plot (PlotAPI): PlotAPI object for the settings of the plot.
            df_metric (pd.DataFrame): Metric dataframe to plot.
            bar_criteria (Union[str, List[str]]): String or list of criteria to plot as
                 bars.
            line_criteria (Union[str, List[str]]): String or l of criteria to plot as
                 lines.
        """
        fig = make_subplots(specs=[[{"secondary_y": True}]])
        _fig_bar = px.bar(
            df_metric,
            y=bar_criteria,
            color_discrete_sequence=args_plot.color.bars,
        )
        _fig_line = px.line(
            df_metric,
            y=line_criteria,
            color_discrete_sequence=args_plot.color.lines,
        )
        _fig_line.update_traces(mode="lines+markers", yaxis="y2")
        fig.add_traces(_fig_bar.data + _fig_line.data)
        fig.update_layout(xaxis_type="category")
        height = args_plot.size[1][1]
        self.update_layout_axes(fig, args_plot, height)
        fig.update_xaxes(
            title_text=self.title_text(
                name=args_plot.run_title.name, unit=args_plot.run_title.unit
            )
        )
        fig.update_yaxes(
            title_text=self.title_text(
                name=args_plot.metric_title.name_0, unit=args_plot.metric_title.unit_0
            ),
            secondary_y=False,
        )
        fig.update_yaxes(
            title_text=self.title_text(
                name=args_plot.metric_title.name_1, unit=args_plot.metric_title.unit_1
            ),
            secondary_y=True,
        )
        fig.show()

    def update_layout_axes(
        self, fig: Figure, args_plot: PlotAPI, height: int
    ) -> Figure:
        """Update the layout of the plot.

        Args:
            fig (Figure): Figure to update.
            args_plot (PlotAPI): PlotAPI object for the settings of the plot.
            height (int): Height of the plot.

        Returns:
            Figure: Updated figure.
        """
        fig.update_layout(
            title=args_plot.title,
            legend_title=args_plot.legend_title,
            legend=args_plot.legend.dict(),
            font=args_plot.font.dict(),
            showlegend=args_plot.show_legend,
            width=args_plot.size[0],
            height=height,
            paper_bgcolor=args_plot.color.paper,
            plot_bgcolor=args_plot.color.plot,
        )

        fig.update_xaxes(
            minor=self.get_minor(args_plot=args_plot),
            gridcolor=args_plot.color.grid,
            linecolor=args_plot.color.line,
            zerolinecolor=args_plot.color.zero_line,
            color=args_plot.color.color,
        )

        fig.update_yaxes(
            minor=self.get_minor(args_plot=args_plot),
            gridcolor=args_plot.color.grid,
            linecolor=args_plot.color.line,
            zerolinecolor=args_plot.color.zero_line,
            color=args_plot.color.color,
        )
        return fig

    @staticmethod
    def title_text(name: str, unit: Optional[str] = None) -> str:
        """Return the title text.

        Args:
            name (str): Name of the variable.
            unit (Optional[str], optional): Unit of the variable. Defaults to None.

        Returns:
            str: Title text.
        """
        return name if unit is None else f"{name} [{unit}]"

    def get_minor(self, args_plot: PlotAPI) -> Dict[str, Union[str, bool]]:
        """Get the minor axis arguments.

        Args:
            args_plot (PlotAPI): PlotAPI object for the settings of the plot.

        Returns:
            Dict[str, Union[str, bool]]: Dictionary with the minor axis arguments.
        """
        return dict(
            tickcolor=args_plot.color.ticks,
            showgrid=args_plot.grid.show,
            ticks=args_plot.grid.ticks,
            griddash=args_plot.grid.dash,
        )

get_minor(args_plot)

Get the minor axis arguments.

Parameters:

Name Type Description Default
args_plot PlotAPI

PlotAPI object for the settings of the plot.

required

Returns:

Type Description
Dict[str, Union[str, bool]]

Dict[str, Union[str, bool]]: Dictionary with the minor axis arguments.

Source code in spectrafit/plugins/notebook.py
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
def get_minor(self, args_plot: PlotAPI) -> Dict[str, Union[str, bool]]:
    """Get the minor axis arguments.

    Args:
        args_plot (PlotAPI): PlotAPI object for the settings of the plot.

    Returns:
        Dict[str, Union[str, bool]]: Dictionary with the minor axis arguments.
    """
    return dict(
        tickcolor=args_plot.color.ticks,
        showgrid=args_plot.grid.show,
        ticks=args_plot.grid.ticks,
        griddash=args_plot.grid.dash,
    )

plot_2dataframes(args_plot, df_1, df_2=None)

Plot of two dataframes.

About the plot

The plot is a combination of two plots. The first plot is the can be the residual plot of a fit or the modified data. The second plot can be the fit or the original data.

line_dash_map

Currently, the line_dash_map is not working, and the dash is not plotted. Most likely, this is related to the fact that the columns are not labeled in the dataframe.

Parameters:

Name Type Description Default
args_plot PlotAPI

PlotAPI object for the settings of the plot.

required
df_1 pd.DataFrame

First dataframe to plot, which will generate automatically a fit plot with residual plot. The ratio is 70% to 20% with 10% space in between.

required
df_2 Optional[pd.DataFrame]

Second optional dataframe to plot for comparsion. In this case, the ratio will between first and second plot will be same. Defaults to None.

None
Source code in spectrafit/plugins/notebook.py
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
def plot_2dataframes(
    self,
    args_plot: PlotAPI,
    df_1: pd.DataFrame,
    df_2: Optional[pd.DataFrame] = None,
) -> None:
    """Plot of two dataframes.

    !!! info "About the plot"

        The plot is a combination of two plots. The first plot is the
        can be the residual plot of a fit or the _modified_ data. The second
        plot can be the fit or the original data.

    !!! missing "`line_dash_map`"

        Currently, the `line_dash_map` is not working, and the dash is not
        plotted. Most likely, this is related to the fact that the columns
        are not labeled in the dataframe.

    Args:
        args_plot (PlotAPI): PlotAPI object for the settings of the plot.
        df_1 (pd.DataFrame): First dataframe to plot, which will generate
             automatically a fit plot with residual plot. The ratio is 70% to 20%
             with 10% space in between.
        df_2 (Optional[pd.DataFrame], optional): Second optional dataframe to
             plot for comparsion. In this case, the ratio will between first
             and second plot will be same. Defaults to None.
    """
    if df_2 is None:
        _fig1 = px.line(
            df_1,
            x=ColumnNamesAPI().energy,
            y=ColumnNamesAPI().residual,
            color_discrete_sequence=[args_plot.color.residual],
        )
        _y = df_1.columns.drop([ColumnNamesAPI().energy, ColumnNamesAPI().residual])
        _fig2 = px.line(
            df_1,
            x=ColumnNamesAPI().energy,
            y=_y,
            color_discrete_map={
                ColumnNamesAPI().intensity: args_plot.color.intensity,
                ColumnNamesAPI().fit: args_plot.color.fit,
                **{
                    key: args_plot.color.components
                    for key in _y.drop(
                        [ColumnNamesAPI().intensity, ColumnNamesAPI().fit]
                    )
                },
            },
            line_dash_map={
                ColumnNamesAPI().intensity: "solid",
                ColumnNamesAPI().fit: "longdash",
                **{
                    key: "dash"
                    for key in _y.drop(
                        [ColumnNamesAPI().intensity, ColumnNamesAPI().fit]
                    )
                },
            },
        )
    else:
        _fig1 = px.line(df_1, x=args_plot.x, y=args_plot.y)
        _fig2 = px.line(df_2, x=args_plot.x, y=args_plot.y)

    fig = make_subplots(
        rows=2, cols=1, shared_xaxes=True, shared_yaxes=True, vertical_spacing=0.05
    )

    for _spec_1 in _fig1["data"]:
        fig.append_trace(_spec_1, row=1, col=1)
    for _spec_2 in _fig2["data"]:
        fig.append_trace(_spec_2, row=2, col=1)
    height = args_plot.size[1][0]
    self.update_layout_axes(fig, args_plot, height)
    xaxis_title = self.title_text(
        name=args_plot.xaxis_title.name, unit=args_plot.xaxis_title.unit
    )
    yaxis_title = self.title_text(
        name=args_plot.yaxis_title.name, unit=args_plot.yaxis_title.unit
    )

    fig.update_xaxes(title_text=xaxis_title, row=1, col=1)
    fig.update_xaxes(title_text=xaxis_title, row=2, col=1)
    if df_2 is None:
        residual_title = self.title_text(
            name=args_plot.residual_title.name, unit=args_plot.residual_title.unit
        )
        fig["layout"]["yaxis1"].update(domain=[0.8, 1])
        fig["layout"]["yaxis2"].update(domain=[0, 0.7])
        fig.update_yaxes(title_text=residual_title, row=1, col=1)
    else:
        fig.update_yaxes(title_text=yaxis_title, row=1, col=1)
    fig.update_yaxes(title_text=yaxis_title, row=2, col=1)
    fig.show()

plot_dataframe(args_plot, df)

Plot the dataframe according to the PlotAPI arguments.

Parameters:

Name Type Description Default
args_plot PlotAPI

PlotAPI object for the settings of the plot.

required
df pd.DataFrame

Dataframe to plot.

required
Source code in spectrafit/plugins/notebook.py
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
def plot_dataframe(self, args_plot: PlotAPI, df: pd.DataFrame) -> None:
    """Plot the dataframe according to the PlotAPI arguments.

    Args:
        args_plot (PlotAPI): PlotAPI object for the settings of the plot.
        df (pd.DataFrame): Dataframe to plot.
    """
    fig = px.line(df, x=args_plot.x, y=args_plot.y)
    height = args_plot.size[1][0]
    self.update_layout_axes(fig, args_plot, height)
    fig.update_xaxes(
        title_text=self.title_text(
            name=args_plot.xaxis_title.name, unit=args_plot.xaxis_title.unit
        )
    )
    fig.update_yaxes(
        title_text=self.title_text(
            name=args_plot.yaxis_title.name, unit=args_plot.yaxis_title.unit
        )
    )
    fig.show()

plot_global_fit(args_plot, df)

Plot the global dataframe according to the PlotAPI arguments.

Parameters:

Name Type Description Default
args_plot PlotAPI

PlotAPI object for the settings of the plot.

required
df pd.DataFrame

Dataframe to plot.

required
Source code in spectrafit/plugins/notebook.py
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
def plot_global_fit(self, args_plot: PlotAPI, df: pd.DataFrame) -> None:
    """Plot the global dataframe according to the PlotAPI arguments.

    Args:
        args_plot (PlotAPI): PlotAPI object for the settings of the plot.
        df (pd.DataFrame): Dataframe to plot.
    """
    for i in range(
        1,
        sum(1 for _col in df.columns if _col.startswith(ColumnNamesAPI().fit)) + 1,
    ):
        _col = [col for col in df.columns if col.endswith(str(i))]
        _col.append(ColumnNamesAPI().energy)
        _df = df[_col]
        _df = _df.rename(
            columns={
                f"{ColumnNamesAPI().intensity}_{i}": ColumnNamesAPI().intensity,
                f"{ColumnNamesAPI().fit}_{i}": ColumnNamesAPI().fit,
                f"{ColumnNamesAPI().residual}_{i}": ColumnNamesAPI().residual,
            }
        )
        self.plot_2dataframes(args_plot, _df)

plot_metric(args_plot, df_metric, bar_criteria, line_criteria)

Plot the metric according to the PlotAPI arguments.

Parameters:

Name Type Description Default
args_plot PlotAPI

PlotAPI object for the settings of the plot.

required
df_metric pd.DataFrame

Metric dataframe to plot.

required
bar_criteria Union[str, List[str]]

String or list of criteria to plot as bars.

required
line_criteria Union[str, List[str]]

String or l of criteria to plot as lines.

required
Source code in spectrafit/plugins/notebook.py
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
def plot_metric(
    self,
    args_plot: PlotAPI,
    df_metric: pd.DataFrame,
    bar_criteria: Union[str, List[str]],
    line_criteria: Union[str, List[str]],
) -> None:
    """Plot the metric according to the PlotAPI arguments.

    Args:
        args_plot (PlotAPI): PlotAPI object for the settings of the plot.
        df_metric (pd.DataFrame): Metric dataframe to plot.
        bar_criteria (Union[str, List[str]]): String or list of criteria to plot as
             bars.
        line_criteria (Union[str, List[str]]): String or l of criteria to plot as
             lines.
    """
    fig = make_subplots(specs=[[{"secondary_y": True}]])
    _fig_bar = px.bar(
        df_metric,
        y=bar_criteria,
        color_discrete_sequence=args_plot.color.bars,
    )
    _fig_line = px.line(
        df_metric,
        y=line_criteria,
        color_discrete_sequence=args_plot.color.lines,
    )
    _fig_line.update_traces(mode="lines+markers", yaxis="y2")
    fig.add_traces(_fig_bar.data + _fig_line.data)
    fig.update_layout(xaxis_type="category")
    height = args_plot.size[1][1]
    self.update_layout_axes(fig, args_plot, height)
    fig.update_xaxes(
        title_text=self.title_text(
            name=args_plot.run_title.name, unit=args_plot.run_title.unit
        )
    )
    fig.update_yaxes(
        title_text=self.title_text(
            name=args_plot.metric_title.name_0, unit=args_plot.metric_title.unit_0
        ),
        secondary_y=False,
    )
    fig.update_yaxes(
        title_text=self.title_text(
            name=args_plot.metric_title.name_1, unit=args_plot.metric_title.unit_1
        ),
        secondary_y=True,
    )
    fig.show()

title_text(name, unit=None) staticmethod

Return the title text.

Parameters:

Name Type Description Default
name str

Name of the variable.

required
unit Optional[str]

Unit of the variable. Defaults to None.

None

Returns:

Name Type Description
str str

Title text.

Source code in spectrafit/plugins/notebook.py
369
370
371
372
373
374
375
376
377
378
379
380
@staticmethod
def title_text(name: str, unit: Optional[str] = None) -> str:
    """Return the title text.

    Args:
        name (str): Name of the variable.
        unit (Optional[str], optional): Unit of the variable. Defaults to None.

    Returns:
        str: Title text.
    """
    return name if unit is None else f"{name} [{unit}]"

update_layout_axes(fig, args_plot, height)

Update the layout of the plot.

Parameters:

Name Type Description Default
fig Figure

Figure to update.

required
args_plot PlotAPI

PlotAPI object for the settings of the plot.

required
height int

Height of the plot.

required

Returns:

Name Type Description
Figure Figure

Updated figure.

Source code in spectrafit/plugins/notebook.py
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
def update_layout_axes(
    self, fig: Figure, args_plot: PlotAPI, height: int
) -> Figure:
    """Update the layout of the plot.

    Args:
        fig (Figure): Figure to update.
        args_plot (PlotAPI): PlotAPI object for the settings of the plot.
        height (int): Height of the plot.

    Returns:
        Figure: Updated figure.
    """
    fig.update_layout(
        title=args_plot.title,
        legend_title=args_plot.legend_title,
        legend=args_plot.legend.dict(),
        font=args_plot.font.dict(),
        showlegend=args_plot.show_legend,
        width=args_plot.size[0],
        height=height,
        paper_bgcolor=args_plot.color.paper,
        plot_bgcolor=args_plot.color.plot,
    )

    fig.update_xaxes(
        minor=self.get_minor(args_plot=args_plot),
        gridcolor=args_plot.color.grid,
        linecolor=args_plot.color.line,
        zerolinecolor=args_plot.color.zero_line,
        color=args_plot.color.color,
    )

    fig.update_yaxes(
        minor=self.get_minor(args_plot=args_plot),
        gridcolor=args_plot.color.grid,
        linecolor=args_plot.color.line,
        zerolinecolor=args_plot.color.zero_line,
        color=args_plot.color.color,
    )
    return fig

ExportReport

Bases: SolverResults

Class for exporting results as toml.

Source code in spectrafit/plugins/notebook.py
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
class ExportReport(SolverResults):
    """Class for exporting results as toml."""

    def __init__(
        self,
        description: DescriptionAPI,
        initial_model: List[Dict[str, Dict[str, Dict[str, Any]]]],
        pre_processing: DataPreProcessingAPI,
        fname: FnameAPI,
        args_out: Dict[str, Any],
        df_org: pd.DataFrame,
        df_fit: pd.DataFrame,
        df_pre: pd.DataFrame = pd.DataFrame(),
    ) -> None:
        """Initialize the ExportReport class.

        Args:
            description (DescriptionAPI): Description of the fit project.
            initial_model (List[Dict[str, Dict[str, Dict[str, Any]]]]): Initial model
                 for the fit.
            pre_processing (DataPreProcessingAPI): Data pre-processing settings.
            fname (FnameAPI): Filename of the fit project including the path, prefix,
                 and suffix.
            args_out (Dict[str, Any]): Dictionary of SpectraFit settings and results.
            df_org (pd.DataFrame): Dataframe of the original data for performing
                 the fit.
            df_fit (pd.DataFrame): Dataframe of the final fit data.
            df_pre (Optional[pd.DataFrame], optional): Dataframe of the pre-processed.
                 Defaults to pd.DataFrame().
        """
        super().__init__(args_out=args_out)
        self.description = description
        self.initial_model = initial_model
        self.pre_processing = pre_processing
        self.fname = fname

        self.df_org = df_org.to_dict(orient="list")
        self.df_fit = df_fit.to_dict(orient="list")
        self.df_pre = df_pre.to_dict(orient="list")

    @property
    def make_input_contribution(self) -> InputAPI:
        """Make input contribution of the report.

        Returns:
            InputAPI: Input contribution of the report as class.
        """
        return InputAPI(
            description=self.description,
            initial_model=self.initial_model,
            pre_processing=self.pre_processing,
            method=FitMethodAPI(
                global_fitting=self.settings_global_fitting,
                confidence_interval=self.settings_conf_interval,
                configurations=self.settings_configurations,
            ),
        )

    @property
    def make_solver_contribution(self) -> SolverAPI:
        """Make solver contribution of the report.

        Returns:
            SolverAPI: Solver contribution of the report as class.
        """
        return SolverAPI(
            goodness_of_fit=self.get_gof,
            regression_metrics=self.get_regression_metrics,
            descriptive_statistic=self.get_descriptive_statistic,
            linear_correlation=self.get_linear_correlation,
            component_correlation=self.get_component_correlation,
            confidence_interval=self.get_confidence_interval,
            covariance_matrix=self.get_covariance_matrix,
            variables=self.get_variables,
            errorbars=self.get_errorbars,
        )

    @property
    def make_output_contribution(self) -> OutputAPI:
        """Make output contribution of the report.

        Returns:
            OutputAPI: Output contribution of the report as class.
        """
        return OutputAPI(df_org=self.df_org, df_fit=self.df_fit, df_pre=self.df_pre)

    def __call__(self) -> Dict[str, Any]:
        """Get the complete report as dictionary.

        Returns:
            Dict[str, Any]: Report as dictionary by using the `.dict()` option of
                 pydantic. `None` is excluded.
        """
        return ReportAPI(
            input=self.make_input_contribution,
            solver=self.make_solver_contribution,
            output=self.make_output_contribution,
        ).dict(exclude_none=True)

make_input_contribution: InputAPI property

Make input contribution of the report.

Returns:

Name Type Description
InputAPI InputAPI

Input contribution of the report as class.

make_output_contribution: OutputAPI property

Make output contribution of the report.

Returns:

Name Type Description
OutputAPI OutputAPI

Output contribution of the report as class.

make_solver_contribution: SolverAPI property

Make solver contribution of the report.

Returns:

Name Type Description
SolverAPI SolverAPI

Solver contribution of the report as class.

__call__()

Get the complete report as dictionary.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Report as dictionary by using the .dict() option of pydantic. None is excluded.

Source code in spectrafit/plugins/notebook.py
709
710
711
712
713
714
715
716
717
718
719
720
def __call__(self) -> Dict[str, Any]:
    """Get the complete report as dictionary.

    Returns:
        Dict[str, Any]: Report as dictionary by using the `.dict()` option of
             pydantic. `None` is excluded.
    """
    return ReportAPI(
        input=self.make_input_contribution,
        solver=self.make_solver_contribution,
        output=self.make_output_contribution,
    ).dict(exclude_none=True)

__init__(description, initial_model, pre_processing, fname, args_out, df_org, df_fit, df_pre=pd.DataFrame())

Initialize the ExportReport class.

Parameters:

Name Type Description Default
description DescriptionAPI

Description of the fit project.

required
initial_model List[Dict[str, Dict[str, Dict[str, Any]]]]

Initial model for the fit.

required
pre_processing DataPreProcessingAPI

Data pre-processing settings.

required
fname FnameAPI

Filename of the fit project including the path, prefix, and suffix.

required
args_out Dict[str, Any]

Dictionary of SpectraFit settings and results.

required
df_org pd.DataFrame

Dataframe of the original data for performing the fit.

required
df_fit pd.DataFrame

Dataframe of the final fit data.

required
df_pre Optional[pd.DataFrame]

Dataframe of the pre-processed. Defaults to pd.DataFrame().

pd.DataFrame()
Source code in spectrafit/plugins/notebook.py
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
def __init__(
    self,
    description: DescriptionAPI,
    initial_model: List[Dict[str, Dict[str, Dict[str, Any]]]],
    pre_processing: DataPreProcessingAPI,
    fname: FnameAPI,
    args_out: Dict[str, Any],
    df_org: pd.DataFrame,
    df_fit: pd.DataFrame,
    df_pre: pd.DataFrame = pd.DataFrame(),
) -> None:
    """Initialize the ExportReport class.

    Args:
        description (DescriptionAPI): Description of the fit project.
        initial_model (List[Dict[str, Dict[str, Dict[str, Any]]]]): Initial model
             for the fit.
        pre_processing (DataPreProcessingAPI): Data pre-processing settings.
        fname (FnameAPI): Filename of the fit project including the path, prefix,
             and suffix.
        args_out (Dict[str, Any]): Dictionary of SpectraFit settings and results.
        df_org (pd.DataFrame): Dataframe of the original data for performing
             the fit.
        df_fit (pd.DataFrame): Dataframe of the final fit data.
        df_pre (Optional[pd.DataFrame], optional): Dataframe of the pre-processed.
             Defaults to pd.DataFrame().
    """
    super().__init__(args_out=args_out)
    self.description = description
    self.initial_model = initial_model
    self.pre_processing = pre_processing
    self.fname = fname

    self.df_org = df_org.to_dict(orient="list")
    self.df_fit = df_fit.to_dict(orient="list")
    self.df_pre = df_pre.to_dict(orient="list")

ExportResults

Class for exporting results as csv.

Source code in spectrafit/plugins/notebook.py
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
class ExportResults:
    """Class for exporting results as csv."""

    def export_df(self, df: pd.DataFrame, args: FnameAPI) -> None:
        """Export the dataframe as csv.

        Args:
            df (pd.DataFrame): Dataframe to export.
            args (FnameAPI): Arguments for the file export including the path, prefix,
                 and suffix.
        """
        df.to_csv(
            self.fname2path(
                fname=args.fname,
                prefix=args.prefix,
                suffix=args.suffix,
                folder=args.folder,
            ),
            index=False,
        )

    def export_report(self, report: Dict[Any, Any], args: FnameAPI) -> None:
        """Export the results as toml file.

        Args:
            report (Dict[Any, Any]): Results as dictionary to export.
            args (FnameAPI): Arguments for the file export including the path, prefix,
                 and suffix.
        """
        with open(
            self.fname2path(
                fname=args.fname,
                prefix=args.prefix,
                suffix=args.suffix,
                folder=args.folder,
            ),
            "wb+",
        ) as f:
            tomli_w.dump(report, f)

    @staticmethod
    def fname2path(
        fname: str,
        suffix: str,
        prefix: Optional[str] = None,
        folder: Optional[str] = None,
    ) -> Path:
        """Translate string to Path object.

        Args:
            fname (str): Filename
            suffix (str): Name of the suffix of the file.
            prefix (Optional[str], optional): Name of the prefix of the file. Defaults
                 to None.
            folder (Optional[str], optional): Folder, where it will be saved.
                 This folders will be created, if not exist. Defaults to None.

        Returns:
            Path: Path object of the file.
        """
        if prefix:
            fname = f"{prefix}_{fname}"
        _fname = Path(fname).with_suffix(f".{suffix}")
        if folder:
            Path(folder).mkdir(parents=True, exist_ok=True)
            _fname = Path(folder) / _fname
        return _fname

export_df(df, args)

Export the dataframe as csv.

Parameters:

Name Type Description Default
df pd.DataFrame

Dataframe to export.

required
args FnameAPI

Arguments for the file export including the path, prefix, and suffix.

required
Source code in spectrafit/plugins/notebook.py
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
def export_df(self, df: pd.DataFrame, args: FnameAPI) -> None:
    """Export the dataframe as csv.

    Args:
        df (pd.DataFrame): Dataframe to export.
        args (FnameAPI): Arguments for the file export including the path, prefix,
             and suffix.
    """
    df.to_csv(
        self.fname2path(
            fname=args.fname,
            prefix=args.prefix,
            suffix=args.suffix,
            folder=args.folder,
        ),
        index=False,
    )

export_report(report, args)

Export the results as toml file.

Parameters:

Name Type Description Default
report Dict[Any, Any]

Results as dictionary to export.

required
args FnameAPI

Arguments for the file export including the path, prefix, and suffix.

required
Source code in spectrafit/plugins/notebook.py
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
def export_report(self, report: Dict[Any, Any], args: FnameAPI) -> None:
    """Export the results as toml file.

    Args:
        report (Dict[Any, Any]): Results as dictionary to export.
        args (FnameAPI): Arguments for the file export including the path, prefix,
             and suffix.
    """
    with open(
        self.fname2path(
            fname=args.fname,
            prefix=args.prefix,
            suffix=args.suffix,
            folder=args.folder,
        ),
        "wb+",
    ) as f:
        tomli_w.dump(report, f)

fname2path(fname, suffix, prefix=None, folder=None) staticmethod

Translate string to Path object.

Parameters:

Name Type Description Default
fname str

Filename

required
suffix str

Name of the suffix of the file.

required
prefix Optional[str]

Name of the prefix of the file. Defaults to None.

None
folder Optional[str]

Folder, where it will be saved. This folders will be created, if not exist. Defaults to None.

None

Returns:

Name Type Description
Path Path

Path object of the file.

Source code in spectrafit/plugins/notebook.py
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
@staticmethod
def fname2path(
    fname: str,
    suffix: str,
    prefix: Optional[str] = None,
    folder: Optional[str] = None,
) -> Path:
    """Translate string to Path object.

    Args:
        fname (str): Filename
        suffix (str): Name of the suffix of the file.
        prefix (Optional[str], optional): Name of the prefix of the file. Defaults
             to None.
        folder (Optional[str], optional): Folder, where it will be saved.
             This folders will be created, if not exist. Defaults to None.

    Returns:
        Path: Path object of the file.
    """
    if prefix:
        fname = f"{prefix}_{fname}"
    _fname = Path(fname).with_suffix(f".{suffix}")
    if folder:
        Path(folder).mkdir(parents=True, exist_ok=True)
        _fname = Path(folder) / _fname
    return _fname

SolverResults

Class for storing the results of the solver.

Source code in spectrafit/plugins/notebook.py
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
class SolverResults:
    """Class for storing the results of the solver."""

    def __init__(self, args_out: Dict[str, Any]) -> None:
        """Initialize the SolverResults class.

        Args:
            args_out (Dict[str, Any]): Dictionary of SpectraFit settings and results.
        """
        self.args_out = args_out

    @property
    def settings_global_fitting(self) -> Union[bool, int]:
        """Global fitting settings.

        Returns:
            Union[bool, int]: Global fitting settings.
        """
        return self.args_out["global_"]

    @property
    def settings_configurations(self) -> Dict[str, Any]:
        """Configure settings.

        Returns:
            Dict[str, Any]: Configuration settings.
        """
        return self.args_out["fit_insights"]["configurations"]

    @property
    def get_gof(self) -> Dict[str, float]:
        """Get the goodness of fit values.

        Returns:
            Dict[str, float]: Goodness of fit values as dictionary.
        """
        return self.args_out["fit_insights"]["statistics"]

    @property
    def get_variables(self) -> Dict[str, Dict[str, float]]:
        """Get the variables of the fit.

        Returns:
            Dict[str, Dict[str, float]]: Variables of the fit.
        """
        return self.args_out["fit_insights"]["variables"]

    @property
    def get_errorbars(self) -> Dict[str, float]:
        """Get the comments about the error bars of fit values.

        Returns:
            Dict[str, float]: Comments about the error bars as dictionary or dataframe.
        """
        return self.args_out["fit_insights"]["errorbars"]

    @property
    def get_component_correlation(self) -> Dict[str, Any]:
        """Get the linear correlation of the components.

        Returns:
            Dict[str, Any]: Linear correlation of the components as dictionary.
        """
        return self.args_out["fit_insights"]["correlations"]

    @property
    def get_covariance_matrix(self) -> Dict[str, Any]:
        """Get the covariance matrix.

        Returns:
            Dict[str, Any]: Covariance matrix as dictionary.
        """
        return self.args_out["fit_insights"]["covariance_matrix"]

    @property
    def get_regression_metrics(self) -> Dict[str, Any]:
        """Get the regression metrics.

        Returns:
            Dict[str, Any]: Regression metrics as dictionary.
        """
        return self.args_out["regression_metrics"]

    @property
    def get_descriptive_statistic(self) -> Dict[str, Any]:
        """Get the descriptive statistic.

        Returns:
            Dict[str, Any]: Descriptive statistic as dictionary of the spectra, fit, and
                 components as dictionary.
        """
        return self.args_out["descriptive_statistic"]

    @property
    def get_linear_correlation(self) -> Dict[str, Any]:
        """Get the linear correlation.

        Returns:
            Dict[str, Any]: Linear correlation of the spectra, fit, and components
                 as dictionary.
        """
        return self.args_out["linear_correlation"]

    @property
    def settings_conf_interval(self) -> Union[bool, Dict[str, Any]]:
        """Confidence interval settings.

        Returns:
            Union[bool, Dict[str, Any]]: Confidence interval settings.
        """
        if isinstance(self.args_out["conf_interval"], dict):
            self.args_out["conf_interval"] = {
                key: value if value is not None else {}
                for key, value in self.args_out["conf_interval"].items()
            }
        return self.args_out["conf_interval"]

    @property
    def get_confidence_interval(self) -> Dict[Any, Any]:
        """Get the confidence interval.

        Returns:
            Dict[Any, Any]: Confidence interval as dictionary with or without the
                    confidence interval results.
        """
        if self.args_out["conf_interval"] is False:
            return {}
        return self.args_out["confidence_interval"]

    @property
    def get_current_metric(self) -> pd.DataFrame:
        """Get the current metric.

        !!! note "About the regression metrics"

            For using the regression metrics, the `regression_metrics` must be averaged
            to merge the results of the different configurations together with the
            `goodness_of_fit` and `variables` results.

        Returns:
            pd.DataFrame: Current metric based on `regression_metrics` and
            `goodness_of_fit` as dataframe.
        """
        gof = {key: [value] for key, value in self.get_gof.items()}
        reg = {
            key: [np.average(val)]
            for key, val in zip(
                self.get_regression_metrics["index"],
                self.get_regression_metrics["data"],
            )
        }
        metric = {**gof, **reg}
        return pd.DataFrame(metric)

get_component_correlation: Dict[str, Any] property

Get the linear correlation of the components.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Linear correlation of the components as dictionary.

get_confidence_interval: Dict[Any, Any] property

Get the confidence interval.

Returns:

Type Description
Dict[Any, Any]

Dict[Any, Any]: Confidence interval as dictionary with or without the confidence interval results.

get_covariance_matrix: Dict[str, Any] property

Get the covariance matrix.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Covariance matrix as dictionary.

get_current_metric: pd.DataFrame property

Get the current metric.

About the regression metrics

For using the regression metrics, the regression_metrics must be averaged to merge the results of the different configurations together with the goodness_of_fit and variables results.

Returns:

Type Description
pd.DataFrame

pd.DataFrame: Current metric based on regression_metrics and

pd.DataFrame

goodness_of_fit as dataframe.

get_descriptive_statistic: Dict[str, Any] property

Get the descriptive statistic.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Descriptive statistic as dictionary of the spectra, fit, and components as dictionary.

get_errorbars: Dict[str, float] property

Get the comments about the error bars of fit values.

Returns:

Type Description
Dict[str, float]

Dict[str, float]: Comments about the error bars as dictionary or dataframe.

get_gof: Dict[str, float] property

Get the goodness of fit values.

Returns:

Type Description
Dict[str, float]

Dict[str, float]: Goodness of fit values as dictionary.

get_linear_correlation: Dict[str, Any] property

Get the linear correlation.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Linear correlation of the spectra, fit, and components as dictionary.

get_regression_metrics: Dict[str, Any] property

Get the regression metrics.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Regression metrics as dictionary.

get_variables: Dict[str, Dict[str, float]] property

Get the variables of the fit.

Returns:

Type Description
Dict[str, Dict[str, float]]

Dict[str, Dict[str, float]]: Variables of the fit.

settings_conf_interval: Union[bool, Dict[str, Any]] property

Confidence interval settings.

Returns:

Type Description
Union[bool, Dict[str, Any]]

Union[bool, Dict[str, Any]]: Confidence interval settings.

settings_configurations: Dict[str, Any] property

Configure settings.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Configuration settings.

settings_global_fitting: Union[bool, int] property

Global fitting settings.

Returns:

Type Description
Union[bool, int]

Union[bool, int]: Global fitting settings.

__init__(args_out)

Initialize the SolverResults class.

Parameters:

Name Type Description Default
args_out Dict[str, Any]

Dictionary of SpectraFit settings and results.

required
Source code in spectrafit/plugins/notebook.py
471
472
473
474
475
476
477
def __init__(self, args_out: Dict[str, Any]) -> None:
    """Initialize the SolverResults class.

    Args:
        args_out (Dict[str, Any]): Dictionary of SpectraFit settings and results.
    """
    self.args_out = args_out

SpectraFitNotebook

Bases: DataFramePlot, DataFrameDisplay, ExportResults

Jupyter Notebook plugin for SpectraFit.

Source code in spectrafit/plugins/notebook.py
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
class SpectraFitNotebook(DataFramePlot, DataFrameDisplay, ExportResults):
    """Jupyter Notebook plugin for SpectraFit."""

    args: Dict[str, Any]
    global_: Union[bool, int] = False
    autopeak: bool = False
    df_fit: pd.DataFrame
    df_pre: pd.DataFrame = pd.DataFrame()
    df_metric: pd.DataFrame = pd.DataFrame()
    df_peaks: pd.DataFrame = pd.DataFrame()
    initial_model: List[Dict[str, Dict[str, Dict[str, Any]]]]

    def __init__(
        self,
        df: pd.DataFrame,
        x_column: str,
        y_column: Union[str, List[str]],
        oversampling: bool = False,
        smooth: int = 0,
        shift: float = 0,
        energy_start: Optional[float] = None,
        energy_stop: Optional[float] = None,
        title: Optional[str] = None,
        xaxis_title: XAxisAPI = XAxisAPI(name="Energy", unit="eV"),
        yaxis_title: YAxisAPI = YAxisAPI(name="Intensity", unit="a.u."),
        residual_title: ResidualAPI = ResidualAPI(name="Residual", unit="a.u."),
        metric_title: MetricAPI = MetricAPI(
            name_0="Metrics", unit_0="a.u.", name_1="Metrics", unit_1="a.u."
        ),
        run_title: RunAPI = RunAPI(name="Run", unit="#"),
        legend_title: str = "Spectra",
        show_legend: bool = True,
        legend: LegendAPI = LegendAPI(
            orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1
        ),
        font: FontAPI = FontAPI(family="Open Sans, monospace", size=12, color="black"),
        minor_ticks: bool = True,
        color: ColorAPI = ColorAPI(),
        grid: GridAPI = GridAPI(),
        size: Tuple[int, Tuple[int, int]] = (800, (600, 300)),
        fname: str = "results",
        folder: Optional[str] = None,
        description: DescriptionAPI = DescriptionAPI(),
    ) -> None:
        """Initialize the SpectraFitNotebook class.

        !!! info "About `Pydantic`-Definition"

            For being consistent with the `SpectraFit` class, the `SpectraFitNotebook`
            class refers to the `Pydantic`-Definition of the `SpectraFit` class.
            Currently, the following definitions are used:

            - `XAxisAPI`: Definition of the x-axis including units
            - `YAxisAPI`: Definition of the y-axis including units
            - `ResidualAPI`: Definition of the residual including units
            - `LegendAPI`: Definition of the legend according to `Plotly`
            - `FontAPI`: Definition of the font according to `Plotly`, which can be
                replaced by _built-in_ definitions
            - `ColorAPI`: Definition of the colors according to `Plotly`, which can be
                replace by _built-in_ definitions
            - `GridAPI`: Definition of the grid according to `Plotly`
            - `DescriptionAPI`: Definition of the description of the fit project

            All classes can be replaced by the corresponding `dict`-definition.

            ```python
            LegendAPI(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1)
            ```

            can be also

            ```python
            dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1)
            ```

        Args:
            df (pd.DataFrame): Dataframe with the data to fit.
            x_column (str): Name of the x column.
            y_column (Union[str, List[str]]): Name of the y column(s).
            oversampling (bool, optional): Activate the oversampling options.
                 Defaults to False.
            smooth (int, optional): Activate the smoothing functions setting an
                 `int>0`. Defaults to 0.
            shift (float, optional): Apply shift to the x-column. Defaults to 0.
            energy_start (Optional[float], optional): Energy start. Defaults to None.
            energy_stop (Optional[float], optional): Energy stop. Defaults to None.
            title (Optional[str], optional): Plot title. Defaults to None.
            xaxis_title (XAxisAPI, optional): X-Axis title. Defaults to XAxisAPI().
            yaxis_title (YAxisAPI, optional): Y-Axis title. Defaults to YAxisAPI().
            residual_title (ResidualAPI, optional): Residual title. Defaults to
                 ResidualAPI().
            metric_title (MetricAPI, optional): Metric title for both axes, bar and
                 line plot. Defaults to MetricAPI().
            run_title (RunAPI, optional): Run title. Defaults to RunAPI().
            legend_title (str, optional): Legend title. Defaults to "Spectra".
            show_legend (bool, optional): Show legend. Defaults to True.
            legend (LegendAPI, optional): Legend options. Defaults to LegendAPI().
            font (FontAPI, optional): Font options. Defaults to FontAPI().
            minor_ticks (bool, optional): Show minor ticks. Defaults to True.
            color (ColorAPI, optional): Color options. Defaults to ColorAPI().
            grid (GridAPI, optional): Grid options. Defaults to GridAPI().
            size (Tuple[int, Tuple[int, int]] , optional): Size of the fit- and metric-
                 plot. First width defines the fit, the second the metrics.
                 Defaults to (800, (600,300)).
            fname (str, optional): Filename of the export. Defaults to "results".
            folder (Optional[str], optional): Folder of the export. Defaults to None.
            description (DescriptionAPI, optional): Description of the data. Defaults
                 to DescriptionAPI()..


        Raises:
            ValueError: If the dataframe only contains one column.
        """
        self.x_column = x_column
        self.y_column = y_column

        if df.shape[1] < 2:
            raise ValueError("The dataframe must have 2 or more columns.")

        if isinstance(self.y_column, list):
            self.global_ = 1
            self.df = df[[self.x_column, *self.y_column]]
        else:
            self.df = df[[self.x_column, self.y_column]]
        self.df_org = self.df.copy()

        self.args_pre = DataPreProcessingAPI(
            oversampling=oversampling,
            energy_start=energy_start,
            energy_stop=energy_stop,
            smooth=smooth,
            shift=shift,
            column=list(self.df.columns),
        )
        self.args_desc = description

        self.args_plot = PlotAPI(
            x=self.x_column,
            y=self.y_column,
            title=title,
            xaxis_title=xaxis_title,
            yaxis_title=yaxis_title,
            residual_title=residual_title,
            metric_title=metric_title,
            run_title=run_title,
            legend_title=legend_title,
            show_legend=show_legend,
            legend=legend,
            font=font,
            minor_ticks=minor_ticks,
            color=color,
            grid=grid,
            size=size,
        )
        self.export_args_df = FnameAPI(fname=fname, folder=folder, suffix="csv")
        self.export_args_out = FnameAPI(fname=fname, folder=folder, suffix="lock")

        self.args_solver: Dict[str, Any] = {}
        self.pre_statistic: Dict[str, Any] = {}

    @property
    def pre_process(self) -> None:
        """Pre-processing class."""
        self.df, _pre_statistic = PreProcessing(df=self.df, args=self.args_pre.dict())()
        self.pre_statistic = _pre_statistic["data_statistic"]
        self.df_pre = self.df.copy()

    @property
    def return_pre_statistic(self) -> Dict[str, Any]:
        """Return the pre-processing statistic."""
        return self.pre_statistic

    @property
    def return_df_org(self) -> pd.DataFrame:
        """Return the original dataframe."""
        return self.df_org

    @property
    def return_df_pre(self) -> Union[pd.DataFrame, None]:
        """Return the pre-processed dataframe."""
        return self.df_pre

    @property
    def return_df(self) -> pd.DataFrame:
        """Return the dataframe."""
        return self.df

    @property
    def return_df_fit(self) -> pd.DataFrame:
        """Return the fit dataframe."""
        return self.df_fit

    @property
    def export_df_act(self) -> None:
        """Export the dataframe."""
        self.export_args_df.prefix = "act"
        self.export_df(df=self.df, args=self.export_args_df)

    @property
    def export_df_fit(self) -> None:
        """Export the dataframe."""
        self.export_args_df.prefix = "fit"
        self.export_df(df=self.df_fit, args=self.export_args_df)

    @property
    def export_df_org(self) -> None:
        """Export the dataframe."""
        self.export_args_df.prefix = "org"
        self.export_df(df=self.df_org, args=self.export_args_df)

    @property
    def export_df_pre(self) -> None:
        """Export the dataframe."""
        if self.df_pre.empty is False:
            self.export_args_df.prefix = "pre"
            self.export_df(df=self.df_pre, args=self.export_args_df)

    @property
    def export_df_metric(self) -> None:
        """Export the dataframe."""
        if self.df_metric.empty is False:
            self.export_args_df.prefix = "metric"
            self.export_df(df=self.df_metric, args=self.export_args_df)

    @property
    def plot_original_df(self) -> None:
        """Plot the original spectra."""
        self.plot_dataframe(args_plot=self.args_plot, df=self.df_org)

    @property
    def plot_current_df(self) -> None:
        """Plot the current spectra."""
        self.plot_dataframe(args_plot=self.args_plot, df=self.df)

    @property
    def plot_preprocessed_df(self) -> None:
        """Plot the current processed spectra."""
        self.plot_2dataframes(
            args_plot=self.args_plot, df_1=self.df_pre, df_2=self.df_org
        )

    def plot_fit_df(self) -> None:
        """Plot the fit."""
        if self.global_ == 1:
            self.plot_global_fit(args_plot=self.args_plot, df=self.df_fit)
        else:
            self.plot_2dataframes(args_plot=self.args_plot, df_1=self.df_fit)

    def plot_current_metric(
        self,
        bar_criteria: Optional[Union[str, List[str]]] = None,
        line_criteria: Optional[Union[str, List[str]]] = None,
    ) -> None:
        """Plot the current metric.

        Args:
            bar_criteria (Optional[Union[str, List[str]]], optional): Criteria for the
                    bar plot. Defaults to None.
            line_criteria (Optional[Union[str, List[str]]], optional): Criteria for
                    the line plot. Defaults to None.
        """
        if bar_criteria is None:
            bar_criteria = [
                "akaike_information",
                "bayesian_information",
            ]

        if line_criteria is None:
            line_criteria = [
                "mean_squared_error",
            ]

        self.plot_metric(
            args_plot=self.args_plot,
            df_metric=self.df_metric,
            bar_criteria=bar_criteria,
            line_criteria=line_criteria,
        )

    @property
    def generate_report(self) -> None:
        """Generate the SpectraFit report of the final fit."""
        self.export_report(
            report=ExportReport(
                description=self.args_desc,
                initial_model=self.initial_model,
                pre_processing=self.args_pre,
                fname=self.export_args_out,
                args_out=self.args,
                df_org=self.df_org,
                df_pre=self.df_pre,
                df_fit=self.df_fit,
            )(),
            args=self.export_args_out,
        )

    def solver_model(
        self,
        initial_model: List[Dict[str, Dict[str, Dict[str, Any]]]],
        show_plot: bool = True,
        show_metric: bool = True,
        show_df: bool = False,
        show_peaks: bool = False,
        conf_interval: Union[bool, Dict[str, Any]] = False,
        bar_criteria: Optional[Union[str, List[str]]] = None,
        line_criteria: Optional[Union[str, List[str]]] = None,
    ) -> None:
        """Solves the fit problem based on the proposed model.

        Args:
            initial_model (List[Dict[str, Dict[str, Dict[str, Any]]]]): List of
                 dictionary with the initial model and its fitting parameters and
                 options for the components.
            show_plot (bool, optional): Show current fit results as plot.
                 Defaults to True.
            show_metric (bool, optional): Show the metric of the fit. Defaults to True.
            show_df (bool, optional): Show current fit results as dataframe. Defaults
                 to False.
            show_peaks (bool, optional): Show the peaks of fit. Defaults to False.
            conf_interval (Union[bool,Dict[str, Any]], optional): Bool or dictionary for
                 the parameter with the parameter for calculating the confidence
                 interval. Using `conf_interval=False` turns of the calculation of
                 the confidence interval and accelerate its. Defaults to False.
            bar_criteria (Optional[Union[str, List[str]]], optional): Criteria for the
                bar plot. It is recommended to use attributes from `goodness of fit`
                module. Defaults to None.
            line_criteria (Optional[Union[str, List[str]]], optional): Criteria for
                the line plot. It is recommended to use attributes from
                `regression metric` module. Defaults to None.

        !!! info: "About criteria"

            The criteria for the bar and line plot are defined as a list of strings.
            The supported keywords are defined by the built-in metrics for
            `goodness of fit` and `regression` and can be checked in [documentation](
                https://anselmoo.github.io/spectrafit/doc/statistics/
            ).

        """
        self.initial_model = initial_model

        if isinstance(conf_interval, bool):
            conf_interval = ConfIntervalAPI().dict() if conf_interval is True else False
        elif isinstance(conf_interval, dict):
            conf_interval = ConfIntervalAPI(**conf_interval).dict(exclude_none=True)

        self.df_fit, self.args = PostProcessing(
            self.df,
            {
                "global_": self.global_,
                "conf_interval": conf_interval,
            },
            *SolverModels(
                df=self.df,
                args={
                    "global_": self.global_,
                    "column": list(self.df.columns),
                    "autopeak": self.autopeak,
                    **list2dict(peak_list=self.initial_model),
                },
            )(),
        )()
        self.update_metric()
        self.update_peaks()
        if show_plot:
            self.plot_fit_df()

        if show_metric:
            self.plot_current_metric(
                bar_criteria=bar_criteria, line_criteria=line_criteria
            )

        if show_df:
            self.interactive_display(df=self.df_fit)

        if show_peaks:
            self.interactive_display(df=self.df_peaks)

    def update_peaks(self) -> None:
        """Update the peaks dataframe as multi-column dataframe.

        The multi-column dataframe is used for the interactive display of the
        peaks with initial, current (model), and best fit values.
        """
        tuples = []
        _list = []
        for key_1, _dict in self.args["fit_insights"]["variables"].items():
            tuples.extend([(key_1, key_2) for key_2, val in _dict.items()])
            _list.extend([val for _, val in _dict.items()])

        self.df_peaks = pd.concat(
            [
                self.df_peaks,
                pd.DataFrame(
                    pd.Series(
                        _list,
                        index=pd.MultiIndex.from_tuples(
                            tuples, names=["component", "parameter"]
                        ),
                    )
                ).T,
            ],
            ignore_index=True,
        )

    def update_metric(self) -> None:
        """Update the metric dataframe."""
        self.df_metric = pd.concat(
            [self.df_metric, SolverResults(self.args).get_current_metric],
            ignore_index=True,
        )

    def display_fit_df(self, mode: Optional[str] = "regular") -> None:
        """Display the fit dataframe.

        Args:
            mode (str, optional): Display mode. Defaults to "regular".
        """
        self.df_display(df=self.df_fit, mode=mode)

    def display_preprocessed_df(self, mode: Optional[str] = "regular") -> None:
        """Display the preprocessed dataframe.

        Args:
            mode (str, optional): Display mode. Defaults to "regular".
        """
        self.df_display(df=self.df_pre, mode=mode)

    def display_original_df(self, mode: Optional[str] = "regular") -> None:
        """Display the original dataframe.

        Args:
            mode (str, optional): Display mode. Defaults to "regular".
        """
        self.df_display(df=self.df_org, mode=mode)

    def display_current_df(self, mode: Optional[str] = "regular") -> None:
        """Display the current dataframe.

        Args:
            mode (str, optional): Display mode. Defaults to "regular".
        """
        self.df_display(df=self.df, mode=mode)

export_df_act: None property

Export the dataframe.

export_df_fit: None property

Export the dataframe.

export_df_metric: None property

Export the dataframe.

export_df_org: None property

Export the dataframe.

export_df_pre: None property

Export the dataframe.

generate_report: None property

Generate the SpectraFit report of the final fit.

plot_current_df: None property

Plot the current spectra.

plot_original_df: None property

Plot the original spectra.

plot_preprocessed_df: None property

Plot the current processed spectra.

pre_process: None property

Pre-processing class.

return_df: pd.DataFrame property

Return the dataframe.

return_df_fit: pd.DataFrame property

Return the fit dataframe.

return_df_org: pd.DataFrame property

Return the original dataframe.

return_df_pre: Union[pd.DataFrame, None] property

Return the pre-processed dataframe.

return_pre_statistic: Dict[str, Any] property

Return the pre-processing statistic.

__init__(df, x_column, y_column, oversampling=False, smooth=0, shift=0, energy_start=None, energy_stop=None, title=None, xaxis_title=XAxisAPI(name='Energy', unit='eV'), yaxis_title=YAxisAPI(name='Intensity', unit='a.u.'), residual_title=ResidualAPI(name='Residual', unit='a.u.'), metric_title=MetricAPI(name_0='Metrics', unit_0='a.u.', name_1='Metrics', unit_1='a.u.'), run_title=RunAPI(name='Run', unit='#'), legend_title='Spectra', show_legend=True, legend=LegendAPI(orientation='h', yanchor='bottom', y=1.02, xanchor='right', x=1), font=FontAPI(family='Open Sans, monospace', size=12, color='black'), minor_ticks=True, color=ColorAPI(), grid=GridAPI(), size=(800, (600, 300)), fname='results', folder=None, description=DescriptionAPI())

Initialize the SpectraFitNotebook class.

About Pydantic-Definition

For being consistent with the SpectraFit class, the SpectraFitNotebook class refers to the Pydantic-Definition of the SpectraFit class. Currently, the following definitions are used:

  • XAxisAPI: Definition of the x-axis including units
  • YAxisAPI: Definition of the y-axis including units
  • ResidualAPI: Definition of the residual including units
  • LegendAPI: Definition of the legend according to Plotly
  • FontAPI: Definition of the font according to Plotly, which can be replaced by built-in definitions
  • ColorAPI: Definition of the colors according to Plotly, which can be replace by built-in definitions
  • GridAPI: Definition of the grid according to Plotly
  • DescriptionAPI: Definition of the description of the fit project

All classes can be replaced by the corresponding dict-definition.

LegendAPI(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1)

can be also

dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1)

Parameters:

Name Type Description Default
df pd.DataFrame

Dataframe with the data to fit.

required
x_column str

Name of the x column.

required
y_column Union[str, List[str]]

Name of the y column(s).

required
oversampling bool

Activate the oversampling options. Defaults to False.

False
smooth int

Activate the smoothing functions setting an int>0. Defaults to 0.

0
shift float

Apply shift to the x-column. Defaults to 0.

0
energy_start Optional[float]

Energy start. Defaults to None.

None
energy_stop Optional[float]

Energy stop. Defaults to None.

None
title Optional[str]

Plot title. Defaults to None.

None
xaxis_title XAxisAPI

X-Axis title. Defaults to XAxisAPI().

XAxisAPI(name='Energy', unit='eV')
yaxis_title YAxisAPI

Y-Axis title. Defaults to YAxisAPI().

YAxisAPI(name='Intensity', unit='a.u.')
residual_title ResidualAPI

Residual title. Defaults to ResidualAPI().

ResidualAPI(name='Residual', unit='a.u.')
metric_title MetricAPI

Metric title for both axes, bar and line plot. Defaults to MetricAPI().

MetricAPI(name_0='Metrics', unit_0='a.u.', name_1='Metrics', unit_1='a.u.')
run_title RunAPI

Run title. Defaults to RunAPI().

RunAPI(name='Run', unit='#')
legend_title str

Legend title. Defaults to "Spectra".

'Spectra'
show_legend bool

Show legend. Defaults to True.

True
legend LegendAPI

Legend options. Defaults to LegendAPI().

LegendAPI(orientation='h', yanchor='bottom', y=1.02, xanchor='right', x=1)
font FontAPI

Font options. Defaults to FontAPI().

FontAPI(family='Open Sans, monospace', size=12, color='black')
minor_ticks bool

Show minor ticks. Defaults to True.

True
color ColorAPI

Color options. Defaults to ColorAPI().

ColorAPI()
grid GridAPI

Grid options. Defaults to GridAPI().

GridAPI()
size Tuple[int, Tuple[int, int]]

Size of the fit- and metric- plot. First width defines the fit, the second the metrics. Defaults to (800, (600,300)).

(800, (600, 300))
fname str

Filename of the export. Defaults to "results".

'results'
folder Optional[str]

Folder of the export. Defaults to None.

None
description DescriptionAPI

Description of the data. Defaults to DescriptionAPI()..

DescriptionAPI()

Raises:

Type Description
ValueError

If the dataframe only contains one column.

Source code in spectrafit/plugins/notebook.py
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
def __init__(
    self,
    df: pd.DataFrame,
    x_column: str,
    y_column: Union[str, List[str]],
    oversampling: bool = False,
    smooth: int = 0,
    shift: float = 0,
    energy_start: Optional[float] = None,
    energy_stop: Optional[float] = None,
    title: Optional[str] = None,
    xaxis_title: XAxisAPI = XAxisAPI(name="Energy", unit="eV"),
    yaxis_title: YAxisAPI = YAxisAPI(name="Intensity", unit="a.u."),
    residual_title: ResidualAPI = ResidualAPI(name="Residual", unit="a.u."),
    metric_title: MetricAPI = MetricAPI(
        name_0="Metrics", unit_0="a.u.", name_1="Metrics", unit_1="a.u."
    ),
    run_title: RunAPI = RunAPI(name="Run", unit="#"),
    legend_title: str = "Spectra",
    show_legend: bool = True,
    legend: LegendAPI = LegendAPI(
        orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1
    ),
    font: FontAPI = FontAPI(family="Open Sans, monospace", size=12, color="black"),
    minor_ticks: bool = True,
    color: ColorAPI = ColorAPI(),
    grid: GridAPI = GridAPI(),
    size: Tuple[int, Tuple[int, int]] = (800, (600, 300)),
    fname: str = "results",
    folder: Optional[str] = None,
    description: DescriptionAPI = DescriptionAPI(),
) -> None:
    """Initialize the SpectraFitNotebook class.

    !!! info "About `Pydantic`-Definition"

        For being consistent with the `SpectraFit` class, the `SpectraFitNotebook`
        class refers to the `Pydantic`-Definition of the `SpectraFit` class.
        Currently, the following definitions are used:

        - `XAxisAPI`: Definition of the x-axis including units
        - `YAxisAPI`: Definition of the y-axis including units
        - `ResidualAPI`: Definition of the residual including units
        - `LegendAPI`: Definition of the legend according to `Plotly`
        - `FontAPI`: Definition of the font according to `Plotly`, which can be
            replaced by _built-in_ definitions
        - `ColorAPI`: Definition of the colors according to `Plotly`, which can be
            replace by _built-in_ definitions
        - `GridAPI`: Definition of the grid according to `Plotly`
        - `DescriptionAPI`: Definition of the description of the fit project

        All classes can be replaced by the corresponding `dict`-definition.

        ```python
        LegendAPI(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1)
        ```

        can be also

        ```python
        dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1)
        ```

    Args:
        df (pd.DataFrame): Dataframe with the data to fit.
        x_column (str): Name of the x column.
        y_column (Union[str, List[str]]): Name of the y column(s).
        oversampling (bool, optional): Activate the oversampling options.
             Defaults to False.
        smooth (int, optional): Activate the smoothing functions setting an
             `int>0`. Defaults to 0.
        shift (float, optional): Apply shift to the x-column. Defaults to 0.
        energy_start (Optional[float], optional): Energy start. Defaults to None.
        energy_stop (Optional[float], optional): Energy stop. Defaults to None.
        title (Optional[str], optional): Plot title. Defaults to None.
        xaxis_title (XAxisAPI, optional): X-Axis title. Defaults to XAxisAPI().
        yaxis_title (YAxisAPI, optional): Y-Axis title. Defaults to YAxisAPI().
        residual_title (ResidualAPI, optional): Residual title. Defaults to
             ResidualAPI().
        metric_title (MetricAPI, optional): Metric title for both axes, bar and
             line plot. Defaults to MetricAPI().
        run_title (RunAPI, optional): Run title. Defaults to RunAPI().
        legend_title (str, optional): Legend title. Defaults to "Spectra".
        show_legend (bool, optional): Show legend. Defaults to True.
        legend (LegendAPI, optional): Legend options. Defaults to LegendAPI().
        font (FontAPI, optional): Font options. Defaults to FontAPI().
        minor_ticks (bool, optional): Show minor ticks. Defaults to True.
        color (ColorAPI, optional): Color options. Defaults to ColorAPI().
        grid (GridAPI, optional): Grid options. Defaults to GridAPI().
        size (Tuple[int, Tuple[int, int]] , optional): Size of the fit- and metric-
             plot. First width defines the fit, the second the metrics.
             Defaults to (800, (600,300)).
        fname (str, optional): Filename of the export. Defaults to "results".
        folder (Optional[str], optional): Folder of the export. Defaults to None.
        description (DescriptionAPI, optional): Description of the data. Defaults
             to DescriptionAPI()..


    Raises:
        ValueError: If the dataframe only contains one column.
    """
    self.x_column = x_column
    self.y_column = y_column

    if df.shape[1] < 2:
        raise ValueError("The dataframe must have 2 or more columns.")

    if isinstance(self.y_column, list):
        self.global_ = 1
        self.df = df[[self.x_column, *self.y_column]]
    else:
        self.df = df[[self.x_column, self.y_column]]
    self.df_org = self.df.copy()

    self.args_pre = DataPreProcessingAPI(
        oversampling=oversampling,
        energy_start=energy_start,
        energy_stop=energy_stop,
        smooth=smooth,
        shift=shift,
        column=list(self.df.columns),
    )
    self.args_desc = description

    self.args_plot = PlotAPI(
        x=self.x_column,
        y=self.y_column,
        title=title,
        xaxis_title=xaxis_title,
        yaxis_title=yaxis_title,
        residual_title=residual_title,
        metric_title=metric_title,
        run_title=run_title,
        legend_title=legend_title,
        show_legend=show_legend,
        legend=legend,
        font=font,
        minor_ticks=minor_ticks,
        color=color,
        grid=grid,
        size=size,
    )
    self.export_args_df = FnameAPI(fname=fname, folder=folder, suffix="csv")
    self.export_args_out = FnameAPI(fname=fname, folder=folder, suffix="lock")

    self.args_solver: Dict[str, Any] = {}
    self.pre_statistic: Dict[str, Any] = {}

display_current_df(mode='regular')

Display the current dataframe.

Parameters:

Name Type Description Default
mode str

Display mode. Defaults to "regular".

'regular'
Source code in spectrafit/plugins/notebook.py
1159
1160
1161
1162
1163
1164
1165
def display_current_df(self, mode: Optional[str] = "regular") -> None:
    """Display the current dataframe.

    Args:
        mode (str, optional): Display mode. Defaults to "regular".
    """
    self.df_display(df=self.df, mode=mode)

display_fit_df(mode='regular')

Display the fit dataframe.

Parameters:

Name Type Description Default
mode str

Display mode. Defaults to "regular".

'regular'
Source code in spectrafit/plugins/notebook.py
1135
1136
1137
1138
1139
1140
1141
def display_fit_df(self, mode: Optional[str] = "regular") -> None:
    """Display the fit dataframe.

    Args:
        mode (str, optional): Display mode. Defaults to "regular".
    """
    self.df_display(df=self.df_fit, mode=mode)

display_original_df(mode='regular')

Display the original dataframe.

Parameters:

Name Type Description Default
mode str

Display mode. Defaults to "regular".

'regular'
Source code in spectrafit/plugins/notebook.py
1151
1152
1153
1154
1155
1156
1157
def display_original_df(self, mode: Optional[str] = "regular") -> None:
    """Display the original dataframe.

    Args:
        mode (str, optional): Display mode. Defaults to "regular".
    """
    self.df_display(df=self.df_org, mode=mode)

display_preprocessed_df(mode='regular')

Display the preprocessed dataframe.

Parameters:

Name Type Description Default
mode str

Display mode. Defaults to "regular".

'regular'
Source code in spectrafit/plugins/notebook.py
1143
1144
1145
1146
1147
1148
1149
def display_preprocessed_df(self, mode: Optional[str] = "regular") -> None:
    """Display the preprocessed dataframe.

    Args:
        mode (str, optional): Display mode. Defaults to "regular".
    """
    self.df_display(df=self.df_pre, mode=mode)

plot_current_metric(bar_criteria=None, line_criteria=None)

Plot the current metric.

Parameters:

Name Type Description Default
bar_criteria Optional[Union[str, List[str]]]

Criteria for the bar plot. Defaults to None.

None
line_criteria Optional[Union[str, List[str]]]

Criteria for the line plot. Defaults to None.

None
Source code in spectrafit/plugins/notebook.py
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
def plot_current_metric(
    self,
    bar_criteria: Optional[Union[str, List[str]]] = None,
    line_criteria: Optional[Union[str, List[str]]] = None,
) -> None:
    """Plot the current metric.

    Args:
        bar_criteria (Optional[Union[str, List[str]]], optional): Criteria for the
                bar plot. Defaults to None.
        line_criteria (Optional[Union[str, List[str]]], optional): Criteria for
                the line plot. Defaults to None.
    """
    if bar_criteria is None:
        bar_criteria = [
            "akaike_information",
            "bayesian_information",
        ]

    if line_criteria is None:
        line_criteria = [
            "mean_squared_error",
        ]

    self.plot_metric(
        args_plot=self.args_plot,
        df_metric=self.df_metric,
        bar_criteria=bar_criteria,
        line_criteria=line_criteria,
    )

plot_fit_df()

Plot the fit.

Source code in spectrafit/plugins/notebook.py
964
965
966
967
968
969
def plot_fit_df(self) -> None:
    """Plot the fit."""
    if self.global_ == 1:
        self.plot_global_fit(args_plot=self.args_plot, df=self.df_fit)
    else:
        self.plot_2dataframes(args_plot=self.args_plot, df_1=self.df_fit)

solver_model(initial_model, show_plot=True, show_metric=True, show_df=False, show_peaks=False, conf_interval=False, bar_criteria=None, line_criteria=None)

Solves the fit problem based on the proposed model.

Parameters:

Name Type Description Default
initial_model List[Dict[str, Dict[str, Dict[str, Any]]]]

List of dictionary with the initial model and its fitting parameters and options for the components.

required
show_plot bool

Show current fit results as plot. Defaults to True.

True
show_metric bool

Show the metric of the fit. Defaults to True.

True
show_df bool

Show current fit results as dataframe. Defaults to False.

False
show_peaks bool

Show the peaks of fit. Defaults to False.

False
conf_interval Union[bool, Dict[str, Any]]

Bool or dictionary for the parameter with the parameter for calculating the confidence interval. Using conf_interval=False turns of the calculation of the confidence interval and accelerate its. Defaults to False.

False
bar_criteria Optional[Union[str, List[str]]]

Criteria for the bar plot. It is recommended to use attributes from goodness of fit module. Defaults to None.

None
line_criteria Optional[Union[str, List[str]]]

Criteria for the line plot. It is recommended to use attributes from regression metric module. Defaults to None.

None

!!! info: "About criteria"

The criteria for the bar and line plot are defined as a list of strings.
The supported keywords are defined by the built-in metrics for
`goodness of fit` and `regression` and can be checked in [documentation](
    https://anselmoo.github.io/spectrafit/doc/statistics/
).
Source code in spectrafit/plugins/notebook.py
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
def solver_model(
    self,
    initial_model: List[Dict[str, Dict[str, Dict[str, Any]]]],
    show_plot: bool = True,
    show_metric: bool = True,
    show_df: bool = False,
    show_peaks: bool = False,
    conf_interval: Union[bool, Dict[str, Any]] = False,
    bar_criteria: Optional[Union[str, List[str]]] = None,
    line_criteria: Optional[Union[str, List[str]]] = None,
) -> None:
    """Solves the fit problem based on the proposed model.

    Args:
        initial_model (List[Dict[str, Dict[str, Dict[str, Any]]]]): List of
             dictionary with the initial model and its fitting parameters and
             options for the components.
        show_plot (bool, optional): Show current fit results as plot.
             Defaults to True.
        show_metric (bool, optional): Show the metric of the fit. Defaults to True.
        show_df (bool, optional): Show current fit results as dataframe. Defaults
             to False.
        show_peaks (bool, optional): Show the peaks of fit. Defaults to False.
        conf_interval (Union[bool,Dict[str, Any]], optional): Bool or dictionary for
             the parameter with the parameter for calculating the confidence
             interval. Using `conf_interval=False` turns of the calculation of
             the confidence interval and accelerate its. Defaults to False.
        bar_criteria (Optional[Union[str, List[str]]], optional): Criteria for the
            bar plot. It is recommended to use attributes from `goodness of fit`
            module. Defaults to None.
        line_criteria (Optional[Union[str, List[str]]], optional): Criteria for
            the line plot. It is recommended to use attributes from
            `regression metric` module. Defaults to None.

    !!! info: "About criteria"

        The criteria for the bar and line plot are defined as a list of strings.
        The supported keywords are defined by the built-in metrics for
        `goodness of fit` and `regression` and can be checked in [documentation](
            https://anselmoo.github.io/spectrafit/doc/statistics/
        ).

    """
    self.initial_model = initial_model

    if isinstance(conf_interval, bool):
        conf_interval = ConfIntervalAPI().dict() if conf_interval is True else False
    elif isinstance(conf_interval, dict):
        conf_interval = ConfIntervalAPI(**conf_interval).dict(exclude_none=True)

    self.df_fit, self.args = PostProcessing(
        self.df,
        {
            "global_": self.global_,
            "conf_interval": conf_interval,
        },
        *SolverModels(
            df=self.df,
            args={
                "global_": self.global_,
                "column": list(self.df.columns),
                "autopeak": self.autopeak,
                **list2dict(peak_list=self.initial_model),
            },
        )(),
    )()
    self.update_metric()
    self.update_peaks()
    if show_plot:
        self.plot_fit_df()

    if show_metric:
        self.plot_current_metric(
            bar_criteria=bar_criteria, line_criteria=line_criteria
        )

    if show_df:
        self.interactive_display(df=self.df_fit)

    if show_peaks:
        self.interactive_display(df=self.df_peaks)

update_metric()

Update the metric dataframe.

Source code in spectrafit/plugins/notebook.py
1128
1129
1130
1131
1132
1133
def update_metric(self) -> None:
    """Update the metric dataframe."""
    self.df_metric = pd.concat(
        [self.df_metric, SolverResults(self.args).get_current_metric],
        ignore_index=True,
    )

update_peaks()

Update the peaks dataframe as multi-column dataframe.

The multi-column dataframe is used for the interactive display of the peaks with initial, current (model), and best fit values.

Source code in spectrafit/plugins/notebook.py
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
def update_peaks(self) -> None:
    """Update the peaks dataframe as multi-column dataframe.

    The multi-column dataframe is used for the interactive display of the
    peaks with initial, current (model), and best fit values.
    """
    tuples = []
    _list = []
    for key_1, _dict in self.args["fit_insights"]["variables"].items():
        tuples.extend([(key_1, key_2) for key_2, val in _dict.items()])
        _list.extend([val for _, val in _dict.items()])

    self.df_peaks = pd.concat(
        [
            self.df_peaks,
            pd.DataFrame(
                pd.Series(
                    _list,
                    index=pd.MultiIndex.from_tuples(
                        tuples, names=["component", "parameter"]
                    ),
                )
            ).T,
        ],
        ignore_index=True,
    )

Color Scheme

For changing the color scheme of the plots, additional color schemes can be added to the spectrafit.plugins.notebook module. The color schemes are defined as a pydantic BaseSettings class with the following attributes:

Color Schemas for the Plots in Jupyter Notebooks.

DraculaColor

Bases: BaseModel

Dracula color schema for SpectraFit.

Dracula Color

The Dracula Color is a color schema is used for the dark mode of the SpectraFit application. This color schema is used in the following way:

  • Background #282a36 → paper, plot
  • Current Line #44475a → not used
  • Foreground #f8f8f2 → color, grid, ticks, font
  • Comment #6272a4 → line
  • Cyan #8be9fd → zero_line
  • Green #50fa7b → fit
  • Orange #ffb86c → not used
  • Pink #ff79c6 → components
  • Purple #bd93f9 → intensity
  • Red #ff5555 → residual
  • Yellow #f1fa8c → not used
Source code in spectrafit/plugins/color_schemas.py
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class DraculaColor(BaseModel, allow_mutation=False):
    """Dracula color schema for SpectraFit.

    !!! info "Dracula Color"

        The [Dracula Color](https://draculatheme.com/contribute) is a color schema is
        used for the dark mode of the `SpectraFit` application. This color schema is
        used in the following way:

        * Background    #282a36 &rarr; **paper**, **plot**
        * Current Line	#44475a &rarr; _not used_
        * Foreground	#f8f8f2 &rarr; **color**, **grid**, **ticks**,  **font**
        * Comment	#6272a4 &rarr; **line**
        * Cyan	#8be9fd &rarr; **zero_line**
        * Green	#50fa7b &rarr; **fit**
        * Orange	#ffb86c &rarr; _not used_
        * Pink	#ff79c6 &rarr; **components**
        * Purple	#bd93f9 &rarr; **intensity**
        * Red	#ff5555 &rarr; **residual**
        * Yellow	#f1fa8c &rarr; _not used_

    """

    intensity: str = "#bd93f9"
    residual: str = "#ff5555"
    fit: str = "#50fa7b"
    bars: List[str] = ["#803C62", "#FFC4E6", "#FF79C6", "#806273", "#CC609D"]
    lines: List[str] = ["#805C36", "#FFDCB8", "#FFB86C", "#806E5C", "#CC9356"]
    components: str = "#ff79c6"
    paper: str = "#282a36"
    plot: str = "#282a36"
    color: str = "#f8f8f2"
    grid: str = "#f8f8f2"
    line: str = "#6272a4"
    zero_line: str = "#8be9fd"
    ticks: str = "#f8f8f2"
    font: str = "#f8f8f2"

DraculaFont

Bases: BaseModel

Dracula font schema for SpectraFit.

Dracula Font

The Dracula Font is a font schema is used for the dark mode of the SpectraFit application. This font schema is used in the following way:

  • Font Family "Fira Code" → family
  • Font Size 12 → size
  • Font Color dracula white → color

See also: https://github.com/tonsky/FiraCode

Source code in spectrafit/plugins/color_schemas.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class DraculaFont(BaseModel, allow_mutation=False):
    """Dracula font schema for SpectraFit.

    !!! info "Dracula Font"

        The [Dracula Font](https://draculatheme.com/contribute) is a font schema is
        used for the dark mode of the `SpectraFit` application. This font schema is
        used in the following way:

        * Font Family	"Fira Code" &rarr; **family**
        * Font Size	12 &rarr; **size**
        * Font Color dracula white &rarr; **color**

        See also: https://github.com/tonsky/FiraCode
    """

    family: str = "Fira Code"
    size: int = 12
    color: str = "#f8f8f2"

Running SpectraFit in the builtin Jupyter-Notebook

For running SpectraFit in the builtin Jupyter-Notebook, the following command can be used:

spectrafit-jupyter

And next, the SpectraFitNotebook class can be used for fitting the data:

from spectrafit.plugins.notebook import SpectraFitNotebook