Esempio n. 1
0
def create_test_model(input_workspaces,
                      function_name,
                      parameters,
                      output_workspace_names=None,
                      logs=None,
                      global_parameters=None):
    """
    Create a list of fits with time series logs on the workspaces
    :param input_workspaces: See create_test_fits
    :param function_name: See create_test_fits
    :param parameters: See create_test_fits
    :param logs: A list of (name, (values...), (name, (values...)))
    :param global_parameters: An optional list of tied parameters
    :return: A list of Fits with workspaces/logs attached
    """
    fits = create_test_fits(input_workspaces, function_name, parameters,
                            output_workspace_names, global_parameters)
    logs = logs if logs is not None else []
    for fit, workspace_name in zip(fits, input_workspaces):
        add_logs(workspace_name, logs)

    fitting_context = TFAsymmetryFittingContext()
    for fit in fits:
        fitting_context.add_fit(fit)
    return fitting_context, ResultsTabModel(fitting_context, ResultsContext())
Esempio n. 2
0
def setup_context(freq=False):
    loaded_data = MuonLoadData()
    loaded_data.get_main_field_direction = mock.MagicMock(return_value='transverse')
    data_context = MuonDataContext(load_data=loaded_data)
    gui_context = MuonGuiContext()
    group_context = MuonGroupPairContext(data_context.check_group_contains_valid_detectors)
    corrections_context = CorrectionsContext(loaded_data)
    phase_table_context = PhaseTableContext()
    freq_context = FrequencyContext()
    plot_panes_context = PlotPanesContext()

    if freq:
        return FrequencyDomainAnalysisContext(muon_data_context=data_context,
                                              muon_group_context=group_context,
                                              muon_gui_context=gui_context,
                                              muon_phase_context=phase_table_context,
                                              corrections_context=corrections_context,
                                              fitting_context=BasicFittingContext(allow_double_pulse_fitting=True),
                                              frequency_context=freq_context,
                                              plot_panes_context=plot_panes_context)
    else:
        return DataAnalysisContext(muon_data_context=data_context,
                                   muon_group_context=group_context,
                                   muon_gui_context=gui_context,
                                   corrections_context=corrections_context,
                                   muon_phase_context=phase_table_context,
                                   fitting_context=TFAsymmetryFittingContext(allow_double_pulse_fitting=True),
                                   results_context=ResultsContext(),
                                   model_fitting_context=ModelFittingContext(),
                                   plot_panes_context=plot_panes_context)
Esempio n. 3
0
    def test_create_results_table_raises_error_if_number_params_different(
            self):
        parameters = OrderedDict([('Height', (100, 0.1)),
                                  ('Cost function value', (1.5, 0))])
        fits_func1 = create_test_fits(('ws1', ), 'func1', parameters)

        parameters = OrderedDict([('Height', (100, 0.1)), ('A0', (1, 0.001)),
                                  ('Cost function value', (1.5, 0))])
        fits_func2 = create_test_fits(('ws2', ), 'func2', parameters)

        fitting_context = TFAsymmetryFittingContext()
        fitting_context.fit_list = fits_func1 + fits_func2
        model = ResultsTabModel(fitting_context, ResultsContext())

        selected_results = [('ws1', 0), ('ws2', 1)]
        self.assertRaises(IndexError, model.create_results_table, [],
                          selected_results)
Esempio n. 4
0
    def test_create_results_table_with_mixed_global_non_global_raises_error(
            self):
        parameters = OrderedDict([('f0.Height', (100, 0.1)),
                                  ('f1.Height', (90, 0.001)),
                                  ('Cost function value', (1.5, 0))])
        fits_func1 = create_test_fits(('ws1', ), 'func1', parameters)
        fits_globals = create_test_fits(('ws2', ),
                                        'func1',
                                        parameters,
                                        global_parameters=['Height'])

        fitting_context = TFAsymmetryFittingContext()
        fitting_context.fit_list = fits_func1 + fits_globals
        model = ResultsTabModel(fitting_context, ResultsContext())

        selected_results = [('ws1', 0), ('ws2', 1)]
        self.assertRaises(IndexError, model.create_results_table, [],
                          selected_results)
Esempio n. 5
0
    def test_that_when_new_fit_is_performed_function_name_is_set_to_lastest_fit_name(
            self):
        parameters = OrderedDict([('Height', (100, 0.1)),
                                  ('Cost function value', (1.5, 0))])
        fits_func1 = create_test_fits(('ws1', ), 'func1', parameters)

        parameters = OrderedDict([('Height', (100, 0.1)), ('A0', (1, 0.001)),
                                  ('Cost function value', (1.5, 0))])
        fits_func2 = create_test_fits(('ws2', ), 'func2', parameters)

        fitting_context = TFAsymmetryFittingContext()
        fits = fits_func1 + fits_func2
        for fit in fits:
            fitting_context.add_fit(fit)
        model = ResultsTabModel(fitting_context, ResultsContext())

        model.on_new_fit_performed()

        self.assertEqual(model.selected_fit_function(), 'func2')
Esempio n. 6
0
    def test_create_results_table_with_logs_missing_from_some_workspaces_raises(
            self):
        workspace = WorkspaceFactory.create("Workspace2D",
                                            NVectors=3,
                                            YLength=5,
                                            XLength=5)

        parameters = OrderedDict([('f0.Height', (100, 0.1))])
        logs = [('log1', (1., 2.)), ('log2', (3., 4.)), ('log3', (4., 5.)),
                ('log4', (5., 6.))]
        fits_logs1 = create_test_fits(
            ('ws1', ),
            'func1',
            parameters,
            output_workspace_names=[
                StaticWorkspaceWrapper('test-ws1-ws', workspace)
            ])
        add_logs(fits_logs1[0].input_workspaces[0], logs[:2])

        fits_logs2 = create_test_fits(
            ('ws2', ),
            'func1',
            parameters,
            output_workspace_names=[
                StaticWorkspaceWrapper('test-ws2-ws', workspace)
            ])
        add_logs(fits_logs2[0].input_workspaces[0], logs[2:])

        fitting_context = TFAsymmetryFittingContext()
        fitting_context.fit_list = fits_logs1 + fits_logs2
        model = ResultsTabModel(fitting_context, ResultsContext())

        selected_results = [('ws1', 0), ('ws2', 1)]
        selected_logs = ['log1', 'log3']
        self.assertRaises(IndexError, model.create_results_table,
                          selected_logs, selected_results)
Esempio n. 7
0
def setup_context_for_tests(parent_object):
    parent_object.loaded_data = MuonLoadData()
    parent_object.loaded_data.get_main_field_direction = mock.MagicMock(return_value='transverse')
    parent_object.data_context = MuonDataContext(load_data=parent_object.loaded_data)
    parent_object.gui_context = MuonGuiContext()
    parent_object.group_context = MuonGroupPairContext(parent_object.data_context.check_group_contains_valid_detectors)
    parent_object.corrections_context = CorrectionsContext(parent_object.loaded_data)
    parent_object.phase_table_context = PhaseTableContext()
    parent_object.fitting_context = TFAsymmetryFittingContext(allow_double_pulse_fitting=True)
    parent_object.results_context = ResultsContext()
    parent_object.plot_panes_context = PlotPanesContext()
    parent_object.model_fitting_context = ModelFittingContext()
    parent_object.context = DataAnalysisContext(muon_data_context=parent_object.data_context,
                                                muon_group_context=parent_object.group_context,
                                                muon_gui_context=parent_object.gui_context,
                                                muon_phase_context=parent_object.phase_table_context,
                                                corrections_context=parent_object.corrections_context,
                                                fitting_context=parent_object.fitting_context,
                                                results_context=parent_object.results_context,
                                                model_fitting_context=parent_object.model_fitting_context,
                                                plot_panes_context=parent_object.plot_panes_context)
Esempio n. 8
0
 def test_model_returns_no_log_selection_if_no_fits_present(self):
     model = ResultsTabModel(TFAsymmetryFittingContext(), ResultsContext())
     self.assertEqual(0, len(model.log_selection({})))
Esempio n. 9
0
    def test_updating_model_selected_fit_function(self):
        model = ResultsTabModel(TFAsymmetryFittingContext(), ResultsContext())
        new_selection = 'func2'
        model.set_selected_fit_function(new_selection)

        self.assertEqual(model.selected_fit_function(), new_selection)
Esempio n. 10
0
    def test_default_model_has_no_selected_function_without_fits(self):
        model = ResultsTabModel(TFAsymmetryFittingContext(), ResultsContext())

        self.assertTrue(model.selected_fit_function() is None)
Esempio n. 11
0
    def test_updating_model_results_table_name(self):
        table_name = 'table_name'
        model = ResultsTabModel(TFAsymmetryFittingContext(), ResultsContext())
        model.set_results_table_name(table_name)

        self.assertEqual(model.results_table_name(), table_name)
Esempio n. 12
0
 def test_default_model_has_results_table_name(self):
     model = ResultsTabModel(TFAsymmetryFittingContext(), ResultsContext())
     self.assertEqual(model.results_table_name(), DEFAULT_TABLE_NAME)
Esempio n. 13
0
    def __init__(self, parent=None, window_flags=None):
        super(MuonAnalysisGui, self).__init__(parent)
        if window_flags:
            self.setWindowFlags(window_flags)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.setObjectName("MuonAnalysis2")
        self.current_tab = ''

        try:
            check_facility()
        except AttributeError as error:
            self.warning_popup(error.args[0])
        # load the feature flags
        feature_dict = load_features()

        # initialise the data storing classes of the interface
        self.loaded_data = MuonLoadData()
        self.data_context = MuonDataContext('Muon Data', self.loaded_data)
        self.gui_context = MuonGuiContext()
        self.group_pair_context = MuonGroupPairContext(
            self.data_context.check_group_contains_valid_detectors)
        self.corrections_context = CorrectionsContext(self.loaded_data)
        self.phase_context = PhaseTableContext()
        self.fitting_context = TFAsymmetryFittingContext(
            allow_double_pulse_fitting=True)
        self.results_context = ResultsContext()
        self.model_fitting_context = ModelFittingContext(
            allow_double_pulse_fitting=False)
        self.plot_panes_context = PlotPanesContext()
        self.context = DataAnalysisContext(
            muon_data_context=self.data_context,
            muon_gui_context=self.gui_context,
            muon_group_context=self.group_pair_context,
            corrections_context=self.corrections_context,
            fitting_context=self.fitting_context,
            results_context=self.results_context,
            model_fitting_context=self.model_fitting_context,
            muon_phase_context=self.phase_context,
            plot_panes_context=self.plot_panes_context)

        # create the Dockable plot widget
        self.fitting_tab = FittingTabWidget(self.context, self)
        self.plot_widget = MuonAnalysisPlotWidget(self.context, parent=self)
        self.dockable_plot_widget_window = PlottingDockWidget(
            parent=self, plotting_widget=self.plot_widget.view)
        self.dockable_plot_widget_window.setMinimumWidth(800)

        # Add dock widget to main Muon analysis window
        self.addDockWidget(QtCore.Qt.RightDockWidgetArea,
                           self.dockable_plot_widget_window)
        # Need this line to stop the bug where the dock window snaps back to its original size after resizing.
        # 0 argument is arbitrary and has no effect on fit widget size
        # This is a qt bug reported at (https://bugreports.qt.io/browse/QTBUG-65592)
        if QT_VERSION >= LooseVersion("5.6"):
            self.resizeDocks({self.dockable_plot_widget_window}, {1},
                             QtCore.Qt.Horizontal)

        # set up other widgets
        self.load_widget = LoadWidget(self.loaded_data, self.context, self)
        self.home_tab = HomeTabWidget(self.context, self)
        self.grouping_tab_widget = GroupingTabWidget(self.context, parent)
        self.corrections_tab = CorrectionsTabWidget(self.context, self)
        self.phase_tab = PhaseTabWidget(self.context, self)
        self.seq_fitting_tab = SeqFittingTabWidget(
            self.context, self.fitting_tab.fitting_tab_model, self)
        self.results_tab = ResultsTabWidget(self.context.fitting_context,
                                            self.context, self)

        self.add_model_analysis = AddModelAnalysis(self, feature_dict)
        self.add_raw_plots = AddRawPlots(self, feature_dict)
        self.add_fitting = AddFitting(self, feature_dict)
        setup_group_ws = AddGroupingWorkspaces(self, feature_dict)

        self.setup_tabs()
        self.plot_widget.insert_plot_panes()

        self.help_widget = HelpWidget("Muon Analysis 2")

        central_widget = QtWidgets.QWidget()
        vertical_layout = QtWidgets.QVBoxLayout()
        vertical_layout.addWidget(self.load_widget.load_widget_view)
        vertical_layout.addWidget(self.tabs)
        vertical_layout.addWidget(self.help_widget.view)
        central_widget.setLayout(vertical_layout)
        central_widget.setSizePolicy(
            QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum,
                                  QtWidgets.QSizePolicy.Maximum))
        self.setCentralWidget(central_widget)
        self.setWindowTitle(self.context.window_title)

        self.disable_notifier = GenericObservable()
        self.disable_observer = GenericObserver(
            self.disable_notifier.notify_subscribers)
        self.enable_notifier = GenericObservable()
        self.enable_observer = GenericObserver(
            self.enable_notifier.notify_subscribers)

        self.setup_load_observers()

        self.setup_gui_variable_observers()

        self.setup_grouping_changed_observers()

        self.setup_corrections_changed_observers()

        self.setup_instrument_changed_notifier()

        self.setup_group_calculation_enable_notifier()

        self.setup_group_calculation_disabler_notifier()

        self.setup_on_load_enabler()

        self.setup_on_load_disabler()

        self.setup_phase_quad_changed_notifier()

        self.setup_phase_table_changed_notifier()

        self.setup_fitting_notifier()

        self.setup_counts_calculation_finished_notifier()

        self.setup_asymmetry_pair_and_diff_calculations_finished_notifier()

        self.context.data_context.message_notifier.add_subscriber(
            self.grouping_tab_widget.group_tab_presenter.message_observer)

        self.setup_disable_notifier()

        self.setup_enable_notifier()

        self.add_model_analysis.add_observers_to_feature(self)
        self.add_model_analysis.set_feature_observables(self)

        self.add_raw_plots.add_observers_to_feature(self)
        setup_group_ws.add_observers_to_feature(self)
Esempio n. 14
0
    def test_that_allow_double_pulse_fitting_is_set_to_false_by_default(self):
        self.assertFalse(self.fitting_context.allow_double_pulse_fitting)

        self.fitting_context = TFAsymmetryFittingContext(
            allow_double_pulse_fitting=True)
        self.assertTrue(self.fitting_context.allow_double_pulse_fitting)
Esempio n. 15
0
 def setUp(self):
     self.fitting_context = TFAsymmetryFittingContext()
Esempio n. 16
0
class TFAsymmetryFittingContextTest(unittest.TestCase):
    def setUp(self):
        self.fitting_context = TFAsymmetryFittingContext()

    def test_that_allow_double_pulse_fitting_is_set_to_false_by_default(self):
        self.assertFalse(self.fitting_context.allow_double_pulse_fitting)

        self.fitting_context = TFAsymmetryFittingContext(
            allow_double_pulse_fitting=True)
        self.assertTrue(self.fitting_context.allow_double_pulse_fitting)

    def test_that_the_context_has_been_instantiated_with_empty_fit_data(self):
        self.assertEqual(self.fitting_context.dataset_names, [])
        self.assertEqual(self.fitting_context.current_dataset_index, None)
        self.assertEqual(self.fitting_context.start_xs, [])
        self.assertEqual(self.fitting_context.end_xs, [])
        self.assertEqual(self.fitting_context.single_fit_functions, [])
        self.assertEqual(self.fitting_context.dataset_indices_for_undo, [])
        self.assertEqual(self.fitting_context.single_fit_functions_for_undo,
                         [])
        self.assertEqual(self.fitting_context.fit_statuses_for_undo, [])
        self.assertEqual(self.fitting_context.chi_squared_for_undo, [])
        self.assertEqual(self.fitting_context.fit_statuses, [])
        self.assertEqual(self.fitting_context.chi_squared, [])
        self.assertEqual(self.fitting_context.plot_guess, False)
        self.assertEqual(self.fitting_context.guess_workspace_name, None)
        self.assertEqual(self.fitting_context.function_name, "")
        self.assertTrue(self.fitting_context.function_name_auto_update)
        self.assertEqual(self.fitting_context.minimizer, "")
        self.assertEqual(self.fitting_context.evaluation_type, "")
        self.assertTrue(self.fitting_context.fit_to_raw)

        self.assertEqual(self.fitting_context.simultaneous_fit_function, None)
        self.assertEqual(
            self.fitting_context.simultaneous_fit_functions_for_undo, [])
        self.assertEqual(self.fitting_context.normalisations_for_undo, [])
        self.assertEqual(self.fitting_context.normalisations_fixed_for_undo,
                         [])

        self.assertTrue(not self.fitting_context.simultaneous_fitting_mode)
        self.assertEqual(self.fitting_context.simultaneous_fit_by, "")
        self.assertEqual(self.fitting_context.simultaneous_fit_by_specifier,
                         "")
        self.assertEqual(self.fitting_context.global_parameters, [])

        self.assertTrue(not self.fitting_context.tf_asymmetry_mode)
        self.assertEqual(self.fitting_context.tf_asymmetry_single_functions,
                         [])
        self.assertEqual(
            self.fitting_context.tf_asymmetry_simultaneous_function, None)

    def test_that_clear_will_clear_the_undo_data_and_active_fits_list(self):
        self.fitting_context.active_fit_history = [mock.Mock(), mock.Mock()]
        self.fitting_context.dataset_indices_for_undo = [0, 1]
        self.fitting_context.single_fit_functions_for_undo = [
            mock.Mock(), mock.Mock()
        ]
        self.fitting_context.fit_statuses_for_undo = ["Success", "Fail"]
        self.fitting_context.chi_squared_for_undo = [2.2, 3.3]

        self.fitting_context.simultaneous_fit_functions_for_undo = [
            mock.Mock(), mock.Mock()
        ]
        self.fitting_context.normalisations_for_undo = [1.0, 2.0]
        self.fitting_context.normalisations_fixed_for_undo = [True, False]

        self.assertEqual(len(self.fitting_context.active_fit_history), 2)
        self.assertEqual(len(self.fitting_context.all_latest_fits()), 2)
        self.assertEqual(len(self.fitting_context.dataset_indices_for_undo), 2)
        self.assertEqual(
            len(self.fitting_context.single_fit_functions_for_undo), 2)
        self.assertEqual(len(self.fitting_context.fit_statuses_for_undo), 2)
        self.assertEqual(len(self.fitting_context.chi_squared_for_undo), 2)
        self.assertEqual(
            len(self.fitting_context.simultaneous_fit_functions_for_undo), 2)
        self.assertEqual(len(self.fitting_context.normalisations_for_undo), 2)
        self.assertEqual(
            len(self.fitting_context.normalisations_fixed_for_undo), 2)

        self.fitting_context.clear()

        self.assertEqual(self.fitting_context.active_fit_history, [])
        self.assertEqual(self.fitting_context.all_latest_fits(), [])
        self.assertEqual(self.fitting_context.dataset_indices_for_undo, [])
        self.assertEqual(self.fitting_context.single_fit_functions_for_undo,
                         [])
        self.assertEqual(self.fitting_context.fit_statuses_for_undo, [])
        self.assertEqual(self.fitting_context.chi_squared_for_undo, [])
        self.assertEqual(
            self.fitting_context.simultaneous_fit_functions_for_undo, [])
        self.assertEqual(self.fitting_context.normalisations_for_undo, [])
        self.assertEqual(self.fitting_context.normalisations_fixed_for_undo,
                         [])

    def test_that_all_latest_fits_will_return_the_two_most_recent_unique_fits(
            self):
        output_ws = WorkspaceFactory.create("Workspace2D",
                                            NVectors=3,
                                            YLength=5,
                                            XLength=5)
        table_workspace = WorkspaceFactory.createTable()

        output_ws_wrap1 = StaticWorkspaceWrapper("Output1", output_ws)
        parameter_ws_wrap1 = StaticWorkspaceWrapper("Parameter1",
                                                    table_workspace)
        covariance_ws_wrap1 = StaticWorkspaceWrapper("Covariance1",
                                                     table_workspace)
        output_ws_wrap2 = StaticWorkspaceWrapper("Output2", output_ws)
        parameter_ws_wrap2 = StaticWorkspaceWrapper("Parameter2",
                                                    table_workspace)
        covariance_ws_wrap2 = StaticWorkspaceWrapper("Covariance2",
                                                     table_workspace)

        fit1 = FitInformation(["Input1"], "GausOsc", [output_ws_wrap1],
                              parameter_ws_wrap1, covariance_ws_wrap1)
        fit2 = FitInformation(["Input2"], "GausOsc", [output_ws_wrap2],
                              parameter_ws_wrap2, covariance_ws_wrap2)
        fit3 = FitInformation(["Input1"], "GausOsc", [output_ws_wrap1],
                              parameter_ws_wrap1, covariance_ws_wrap1)

        self.fitting_context.tf_asymmetry_mode = True
        self.fitting_context.simultaneous_fitting_mode = True
        self.fitting_context.active_fit_history = [fit1, fit2, fit3]

        self.assertEqual(self.fitting_context.active_fit_history[0], fit1)
        self.assertEqual(self.fitting_context.active_fit_history[1], fit2)
        self.assertEqual(self.fitting_context.active_fit_history[2], fit3)

        self.assertEqual(self.fitting_context.all_latest_fits()[0], fit2)
        self.assertEqual(self.fitting_context.all_latest_fits()[1], fit3)

        self.fitting_context.tf_asymmetry_mode = False
        self.assertEqual(self.fitting_context.active_fit_history, [])
        self.assertEqual(self.fitting_context.all_latest_fits()[0], fit2)
        self.assertEqual(self.fitting_context.all_latest_fits()[1], fit3)

    def test_remove_workspace_by_name_will_remove_a_fit_containing_a_specific_parameter_workspace(
            self):
        output_ws = WorkspaceFactory.create("Workspace2D",
                                            NVectors=3,
                                            YLength=5,
                                            XLength=5)
        table_workspace = WorkspaceFactory.createTable()

        output_ws_wrap1 = StaticWorkspaceWrapper("Output1", output_ws)
        parameter_ws_wrap1 = StaticWorkspaceWrapper("Parameter1",
                                                    table_workspace)
        covariance_ws_wrap1 = StaticWorkspaceWrapper("Covariance1",
                                                     table_workspace)
        output_ws_wrap2 = StaticWorkspaceWrapper("Output2", output_ws)
        parameter_ws_wrap2 = StaticWorkspaceWrapper("Parameter2",
                                                    table_workspace)
        covariance_ws_wrap2 = StaticWorkspaceWrapper("Covariance2",
                                                     table_workspace)

        fit1 = FitInformation(["Input1"], "GausOsc", [output_ws_wrap1],
                              parameter_ws_wrap1, covariance_ws_wrap1)
        fit2 = FitInformation(["Input2"], "GausOsc", [output_ws_wrap2],
                              parameter_ws_wrap2, covariance_ws_wrap2)

        self.fitting_context.tf_asymmetry_mode = True
        self.fitting_context.simultaneous_fitting_mode = True
        self.fitting_context.active_fit_history = [fit1, fit2]

        self.fitting_context.remove_workspace_by_name("Parameter1")

        self.assertEqual(self.fitting_context.active_fit_history[0], fit2)
        self.assertEqual(self.fitting_context.all_latest_fits()[0], fit2)