PDielec.GUI.FitterTab
#
FitterTab module.
Module Contents#
Classes#
Initialize the main FitterTab with its components and connect signals to slots. |
Functions#
|
Calculate the cross-correlation between the experimental spectrum and a calculated spectrum, with an applied scaling factor. |
|
Calculate the root mean square error (RMSE) between a renormalised experimental spectrum and calculated spectrum after applying a scaling factor. |
|
Find the delimiter used in a CSV file. |
|
Test to see if element is a float. |
|
Read an experimental file. |
|
Resample the experimental spectrum to match calculated frequencies and optionally apply baseline removal. |
- class PDielec.GUI.FitterTab.FitterTab(parent, debug=False)[source]#
Bases:
qtpy.QtWidgets.QWidget
Initialize the main FitterTab with its components and connect signals to slots.
A class for managing and displaying a spectroscopic fitting interface within a QWidget. This constructor sets up the UI for a spectral analysis widget, initializing all the GUI components such as buttons, combo boxes, spin boxes, and plotting canvases. It also sets up the initial state for various attributes related to the spectral analysis settings and data.
Parameters#
- parentQWidget
The parent widget.
- debugbool, optional
Flag to indicate whether debugging messages should be printed, by default False.
Attributes#
- parentQWidget
The parent QWidget within which this FitterTab is contained.
- debugbool, optional
A flag to activate debug mode which provides additional output for development and troubleshooting. Defaults to False.
Notes#
This class is designed to provide a user interface for spectral fitting tasks, allowing for adjustments of various fitting parameters and visualization of fitting results. It leverages Qt widgets for the graphical user interface components and matplotlib for plotting.
The class initializes with customizable settings related to spectral fitting including file names, fitting types, iterations, scaling factors, and baseline correction options. It supports reading experimental data from .xlsx or .csv files, setting fitting parameters through a dynamically generated form, and presenting the fitting results graphically with options to adjust the view.
Methods#
- __init__(self, parent, debug=False)
Constructor to initialize the spectroscopic fitting interface with the given parent and debug settings.
- on_iterations_sb_changed(self)
Handle changes to the number of iterations spinbox value.
- on_independent_yaxes_cb_changed(self, value)
Handle changes to the independent y-axes checkbox state.
- on_optimise_frequency_scaling_cb_changed(self, value)
Handle changes to the optimise frequency scaling checkbox state.
- on_spectrum_scaling_cb_changed(self, value)
Handle changes to the spectrum scaling checkbox state.
- on_hpfilter_lambda_sb_changed(self, value)
Handle changes to the HP filter lambda spinbox value.
- on_spectrum_scaling_factor_sb_changed(self, value)
Handle changes to the spectrum scaling factor spinbox value.
- on_baseline_cb_changed(self, value)
Handle changes to the baseline correction checkbox state.
- on_spectral_difference_threshold_sb_changed(self, value)
Handle changes to the spectral difference threshold spinbox value.
- on_frequency_scaling_factor_sb_changed(self, value)
Handle changes to the frequency scaling factor spinbox value.
- replotButton1Clicked(self)
Handle the event when the first replot button is clicked.
- replotButton2Clicked(self)
Handle the event when the second replot button with frequency shift is clicked.
- plot(self, experiment, xs, ys, legends, label)
Plots the fitting results with optional experiment data overlay.
- fittingButtonClicked(self)
Initiates the fitting process when the fitting button is clicked.
- optimiseFit(self)
Optimises the fitting parameters.
- optimiseFunction(self, variables)
Function to be optimised during the fitting process.
- redraw_sigmas_tw(self)
Redraws the table widget for sigma values based on current settings.
- on_fitting_type_cb_activated(self, index)
Handle changes to the fitting type combo box selection.
- on_scenario_cb_activated(self, index)
Handle selection changes in the scenario combo box.
- on_spectrafile_le_return(self)
Handle actions to take when the spectra file line edit has a return event.
- on_spectrafile_le_changed(self, text)
Handle changes to the spectra file line edit text.
- on_sigmas_tw_itemChanged(self, item)
Responds to item changes in the sigmas table widget.
- print_settings(self)
Prints the current settings to the debugger.
- replot(self)
Handle the replotting of spectra.
- refresh(self, force=False)
Refreshes the interface based on current settings and data.
- requestRefresh(self)
Requests a refresh of the interface.
- fittingButtonClicked()[source]#
Handle the click event on the fitting button.
This method toggles the fitting process on and off. When clicked, it changes the button’s text accordingly to reflect the current state - either “Perform fitting” or “Interrupt fitting”. It also triggers re-plotting and refreshes the UI. If the fitting process starts, it performs optimization and then resets the button’s state to allow a new fitting process.
Parameters#
None
Returns#
None
- on_baseline_cb_changed(value)[source]#
Handle the change event of the baseline checkbox.
This method is called when the baseline checkbox state changes. It updates the setting for baseline removal and marks refresh as required.
Parameters#
- valuestr
The new value or state of the baseline checkbox. The actual data type and use of this parameter depend on the specific implementation and could vary.
Returns#
None
- on_fitting_type_cb_activated(index)[source]#
Handle the activation of a fitting type option.
This method updates the current settings to reflect the selected fitting type based on the provided index. It also marks the state as requiring a refresh.
Parameters#
- indexint
The index of the selected fitting type in the fitting type definitions list.
Returns#
None
- on_frequency_scaling_factor_sb_changed(value)[source]#
Handle changes in the frequency scaling factor setting.
This function changes the frequency scaling factor setting. It updates the setting with the new value and marks a refresh as necessary. It also handles conversion errors gracefully.
Parameters#
- valuestr
The new value for the frequency scaling factor setting. The function attempts to convert this to a float.
Returns#
None
Notes#
The self.refreshRequired flag is set to True regardless of whether the conversion succeeds.
- on_hpfilter_lambda_sb_changed(value)[source]#
Handle changes to the high-pass filter lambda scrollbar value.
Parameters#
- valuestr
The new value from the high-pass filter lambda scrollbar, intended to be converted to float.
Returns#
None
- on_independent_yaxes_cb_changed(value)[source]#
Handle the change of state for the independent Y-axes checkbox.
Parameters#
- valuebool
The new state of the checkbox. The actual value might not be used in the function but represents the change.
Returns#
None
Notes#
This function is triggered upon the change of the ‘independent_yaxes_cb’ checkbox state. It updates the settings dictionary with the new state of the ‘Independent y-axes’ option and sets the ‘refreshRequired’ flag to True, indicating that a refresh is needed to reflect the changes in the UI or data visualization.
- on_iterations_sb_changed()[source]#
Handle changes in the iterations spin box value.
This method is called when the iterations spin box value is changed. It updates the ‘Number of iterations’ setting with the new value and flags that a refresh is required.
Parameters#
None
Returns#
None
- on_optimise_frequency_scaling_cb_changed(value)[source]#
Handle changes in the frequency scaling optimization option.
This method updates the ‘Optimise frequency scaling’ setting based on the state of a checkbox and marks that a refresh is required based on the new setting.
Parameters#
- valuebool
The value or state that triggered the change. This parameter is logged but not directly used to set the ‘Optimise frequency scaling’ option.
Returns#
None
- on_scenario_cb_activated(index)[source]#
Handle scenario combobox activation.
This function is triggered when a scenario combobox option is selected. It logs the activation with the selected index, marks that a refresh is required, and updates the settings to reflect the new scenario.
Parameters#
- indexint
The index of the activated scenario.
Returns#
None
- on_sigmas_tw_itemChanged(item)[source]#
Handle item changed event in a table widget for sigma values.
This method updates mode fitting status and sigma values based on changes in a table widget, redraws the table widget, and refreshes output based on the modifications. It also handles error for invalid numeric input for sigma values.
Parameters#
- itemQTableWidgetItem
The table widget item that has been changed.
Returns#
None
Side Effects#
Updates internal data structures storing mode fitting statuses and sigma values.
Triggers UI update methods to reflect changes in the table widget and other dependent UI components.
Blocks and unblocks signals from the table widget to prevent recursive item change events during updates.
Processes all pending events for the application to ensure UI updates are immediately applied.
- on_spectrafile_le_changed(text)[source]#
Handle changes to the spectra file input field.
This method is triggered when the text of the spectrum file input field changes. It updates the ‘Experimental file name’ setting with the new text, marks the current experimental file as unread, and indicates that a refresh is required.
Parameters#
- textstr
The new text from the spectra file input field. Not directly used after method update.
Returns#
None
Notes#
The actual text used in processing is fetched directly from the spectrafile_le attribute, not from the text argument.
- on_spectrafile_le_return()[source]#
Handle file selection for experimental spectra.
This method is executed when an action associated with the spectrafile_le widget is performed. It prompts the user to select a file if the currently specified file does not exist or cannot be found. It updates the application’s settings with the new file name, if a file is selected.
Parameters#
None
Returns#
None
Notes#
The method first checks if the file specified in the spectrafile_le widget exists. If it does not, a file dialog is opened for the user to select a file. If a file is selected, the method updates the application’s settings and the text of the spectrafile_le widget to reflect the new file name. Additionally, it sets a flag indicating that a refresh is required and that the experimental file needs to be read again. Finally, it triggers the last button pressed action.
This method utilizes os.path.isfile to check file existence, QFileDialog for file selection.
- on_spectral_difference_threshold_sb_changed(value)[source]#
Handle changes in spectral difference threshold setting.
This function is called when the ‘Spectral difference threshold’ setting is changed. It updates the setting value, converting it to a float, and sets a flag indicating that a refresh is required.
Parameters#
- valuestr
The new value for the ‘Spectral difference threshold’ setting. The function attempts to convert this to a float.
Returns#
None
- on_spectrum_scaling_cb_changed(value)[source]#
Handle the change event of the spectrum scaling checkbox.
This method is triggered whenever the spectrum scaling checkbox’s state changes. It updates the settings to reflect the current state of the checkbox and flags that a refresh is required.
Parameters#
- valuebool
The new value of the spectrum scaling checkbox. The specific type and significance can vary depending on the implementation details of the checkbox and its handlers.
Returns#
None
- on_spectrum_scaling_factor_sb_changed(value)[source]#
Handle the change in spectrum scaling factor.
Parameters#
- valuestr
The new value for the spectrum scaling factor. Expected to be convertible to float.
Returns#
None
Notes#
This function attempts to update the ‘Spectrum scaling factor’ setting with the new value after converting it to float. If the conversion fails, a message is printed indicating the failure.
- optimiseFit()[source]#
Optimise the fit based on the initial and adjusted sigmas and potential frequency scaling.
Instructions for determining the best fitting parameters for the model are conducted within the constraints of predefined modes. The function iterates to minimize the discrepancy between modeled and experimental data. It employs the Nelder-Mead optimization method for solving the problem.
Parameters#
None
Returns#
- list or OptimizeResult
The final optimization point as a list if no sigma has been selected for optimisation, or as an OptimizeResult object returned by scipy.optimize.minimize. The return type depends on whether the optimization process is executed.
Notes#
The function uses several attributes of the class instance it belongs to: - modes_fitted to determine which modes are fitted. - sigmas_cm1 as initial sigma points for optimization. - settings to check if frequency scaling should be optimised and to determine the number of iterations for the optimization. - optimiseFunction as the function to be minimized.
It modifies the functionCalls attribute by setting it to 0 at the beginning and uses fit_list to store the indexes of modes that are being fitted.
- optimiseFunction(variables)[source]#
Optimise the fitting function based on given variables.
This method adjusts internal settings based on an array of variables to optimise the fitting function according to the predefined criteria (e.g., minimize cross-correlation or spectral difference). It updates GUI components and recalculates the function value based on the new configuration.
Parameters#
- variableslist or array-like
The variables used for optimization. This could include sigma values for each element to be fitted and optionally a scaling factor for frequency scaling, depending on the configuration.
Returns#
- float
The function value after optimization, which is either the negative cross-correlation or the root mean square error (RMSE), based on the fitting type setting.
Notes#
calculationInProgress is a boolean attribute of the object that indicates whether a calculation can proceed.
Manipulates GUI components such as fittingButton and elements within notebook.settingsTab, thus requires the GUI to be in a responsive state.
Uses global debugger object for logging progress and results.
The method updates the internal state of the object, such as the functionCalls counter and sigma values for elements being fitted.
Raises#
- Exception
If the calculation is not in progress (indicated by calculationInProgress being False), it immediately returns a predefined extremely negative value (e.g., -9.9e+99).
- plot(experiment, xs, ys, legends, label)[source]#
Plot experimental and calculated data on the same or separate y-axes.
This method plots provided experimental and calculated data sets using Matplotlib. It supports plotting data with independent y-axes and applying frequency shift and scaling to the x-axis. The plot appearance, including color mapping, line width, and labels, is customizable.
Parameters#
- experimentarray_like
The experimental data to be plotted. If empty, no experimental data is plotted.
- xslist of array_like
A list containing the x-axis data for each data set.
- yslist of array_like
A list containing the y-axis data for each data set to be plotted alongside the x data.
- legendslist of str
A list containing the labels for each data set.
- labelstr
The label for the plot, typically used as a part of y-axis label.
Returns#
None
Raises#
- ValueError
If xs, ys, and legends lists do not have the same length.
- print_settings()[source]#
Print the settings attributes of the instance.
Parameters#
None
Returns#
None
Prints the key and value of each setting in the instance’s settings attribute, with the help of the debugger print method.
- redraw_sigmas_tw()[source]#
Redraw the table widget for sigmas.
This method updates the table widget sigmas_tw used for displaying sigma, frequency, and intensity information. It checks if the data lists (sigmas_cm1, frequencies_cm1, and intensities) are non-empty and then proceeds to populate the table. Each row in the table corresponds to a unique sigma, frequency, and intensity value. The method also handles item selection and editing properties based on the state of modes_selected and modes_fitted attributes.
Parameters#
None
Returns#
None
Notes#
sigmas_cm1, frequencies_cm1, and intensities are lists that store sigma, frequency, and intensity data, respectively.
modes_selected and modes_fitted are lists that store boolean values indicating whether a mode is selected and whether it is fitted, respectively.
- refresh(force=False)[source]#
Refresh the state of the application based on user-defined conditions and settings.
Parameters#
- forcebool, optional
If True, the refresh proceeds regardless of whether it is deemed necessary based on the internal state. Defaults to False.
Returns#
None
Notes#
The refresh process involves several key steps including checking if a refresh is required, updating plotting data from settings, reading an experimental file, setting GUI components based on notebook scenarios, and recalculating spectra. If the refresh is aborted either due to being unnecessary or because there are no frequencies, it returns early. Additionally, if force is True, it ignores the check for whether a refresh is required and proceeds with the refresh.
After updating relevant class attributes and GUI components, the function recalculates cross-correlation, root-mean-square error (RMSE) between experimental and calculated spectra, and updates the display with these metrics.
- replot()[source]#
Replots the experimental spectrum along with calculated frequencies and spectra.
This method will initially check if there is a resampled experimental spectrum. If such a spectrum exists, the spectrum is resampled. Subsequently, it calls the plot method with the updated data along with other related information such as legends and labels.
Parameters#
None
Returns#
None
- replotButton1Clicked()[source]#
Handle the click event on the replot button.
This method is triggered when the replot button is clicked. It sets up the necessary flags for the replot operation and invokes the refresh method to update the plot.
Parameters#
None
Returns#
None
Notes#
This method modifies the instance attributes to reflect that a replot is required without a frequency shift, and it bookmarks the last button pressed as ‘replotButton1Clicked’. It also calls the self.refresh method to initiate the replotting process.
- replotButton2Clicked()[source]#
Handle the event when the second replot button is clicked.
This method updates various attributes to indicate that a refresh of the plot is required, specifically with a frequency shift. It records that this button was the last one pressed and then initiates the refresh process.
Parameters#
None
Returns#
None
- PDielec.GUI.FitterTab.calculateCrossCorrelation(xaxis, calculated_spectrum, experimental_spectrum, scaling_factor=1.0, debug=False)[source]#
Calculate the cross-correlation between the experimental spectrum and a calculated spectrum, with an applied scaling factor.
The calculated and experimental spectra share the same frequencies (xaxis). If a scaling factor is applied, the calculated spectrum x-axis is rescaled according to the scaling factor.
Parameters#
- xaxis1d array of floats
An array frequencies valid for both the calculated and experimental spectra
- calculated_spectrum1d array of floats
The calculated spectrum
- experimental_spectrum1d array of floats
The experimental spectrum
- scaling_factorfloat, optional
The factor by which the x-axis of the calculated spectrum is scaled, default is 1.0
- debugboolean, optional
Set to true for debugging information
Returns#
- tuple
A tuple containing: - lag: The lag at which the maximum correlation occurs. - max_corr: The maximum correlation value. - center_corr: The correlation value at the center (zero lag).
Notes#
The calculated spectrum’s x-axis is rescaled according to the scaling_factor. The correlation is performed on the normalized (zero-mean unit-variance) spectra. Interpolation of the calculated spectrum onto the experimental spectrum’s x-axis is performed using cubic interpolation.
- PDielec.GUI.FitterTab.calculateSpectralDifference(xaxis, calculated_spectrum, experimental_spectrum, spectral_threshold=0.05, scaling_factor=1.0, debug=False)[source]#
Calculate the root mean square error (RMSE) between a renormalised experimental spectrum and calculated spectrum after applying a scaling factor.
Parameters#
- xaxis1d array of floats
An array frequencies valid for both the calculated and experimental spectra
- calculated_spectrum1d array of floats
The calculated spectrum
- experimental_spectrum1d array of floats
The experimental spectrum
- scaling_factorfloat, optional
The factor by which the x-axis of the calculated spectrum is scaled, default is 1.0
- spectral_thresholdfloat,optional
Only signals greater than the threshold are considered in the difference calculation. Default is 0.05
- debugboolean, optional
Set to true for debugging information
Returns#
- float
The root mean square error between the resampled experimental spectrum and the scaled calculated spectrum.
Notes#
This method modifies the spectra by scaling, normalization, and thresholding before calculating the RMSE.
If the resampled experimental spectrum is empty, the method returns 0.0 immediately.
Uses cubic interpolation for scaling the calculated spectrum.
Normalization is performed based on the maximum value in the experimental spectrum.
- PDielec.GUI.FitterTab.find_delimiter(filename)[source]#
Find the delimiter used in a CSV file.
Parameters#
- filenamestr
The path to the file for which the delimiter is to be determined.
Returns#
- str
The detected delimiter character.
Notes#
This function uses the csv.Sniffer class to deduce the delimiter of the given file by analyzing the first 5000 bytes of the file.
- PDielec.GUI.FitterTab.is_float(element)[source]#
Test to see if element is a float.
Parameters#
- elementstr
A string to be analysed to see if it is a float
Returns#
- bool
True if the element is a float, False otherwise.
- PDielec.GUI.FitterTab.read_experimental_file(file_name, frequency_column=1, spectrum_column=2, sheet_name=None, debug=False)[source]#
Read an experimental file.
Parameters#
- file_namestr
An xlsx or a csv file containing the experimental spectrum
- frequency_columnint
The frequency column in the spread sheet, default is 1. The first column in a sheet is column 1
- spectrum_columnint
The spectrum column in the spread sheet, default is 2. The first column in a sheet is column 1
- sheet_namestr
The name of the spreadsheet to be used to extract the frequency and spectrum, default is None
- debugboolean
True if debug information is needed, default is False
Returns#
- experimental_frequenciesan array of floats
The experimental frequencies in cm-1
- experimental_spectruman array of floats
The experimental spectrum
Errors#
If any errors occur, such as a file not existing, empty arrays/lists are returned, :w
- PDielec.GUI.FitterTab.resample_experimental_spectrum(calculated_frequencies, experimental_frequencies, experimental_spectrum, baseline_removal='False', HPFilter_lambda=7.0, debug=False)[source]#
Resample the experimental spectrum to match calculated frequencies and optionally apply baseline removal.
This method modifies the experimental spectrum to align with the calculated frequencies. It pads the spectrum at both ends with zeros outside the calculated frequencies range, then uses cubic interpolation over the whole range. If ‘baseline_removal’ is enabled, applies the Hodrick-Prescott filter for baseline removal on the resampled spectrum.
Parameters#
- calculated_frequenciesarray of floats
The frequencies the caculated spectrum is tabulated
- experimental_frequenciesarray of floats
The frequencies the experimental spectrum is tabulated
- experimental_spectrumarray of floats
The experimental spectrum
- baseline_removalboolean
Optional switches on baseline removal using a Hodrick-Prescott filter, default is False
- HPFilter_lambdafloat
The value of lambda in in the Hodrick-Prescott filter, default value is 7.0
- debugboolean
Optional switches on some debug information, default is False
Returns#
- None
Modifies the instance’s resampled_experimental_spectrum in place.