"""
Test the fits-module by loading a dumped rtfits result and performing
all actions again

"""

import unittest
import numpy as np
import cloudpickle
import matplotlib.pyplot as plt
import copy
import os

class TestDUMPS(unittest.TestCase):
    def setUp(self):
        self.sig0_dB_path = os.path.dirname(__file__) + os.sep + "sig0_dB.dump"
        self.sig0_linear_path = os.path.dirname(__file__) + os.sep + "sig0_linear.dump"

    def load_data(self, path):
        with open(path, 'rb') as file:
            fit = cloudpickle.load(file)
        return fit


#        self.assertTrue(
#            err < errdict[key],
#            msg='derived error' + str(err) + 'too high for ' + str(key))

    def test_rtplots(self):

        for path, msg in zip([self.sig0_dB_path, self.sig0_linear_path],
                             ['dB', 'linear']):

            print(f'testing plotfunctions for {msg} fit')
            fit = self.load_data(path)
            fitset = {
                'ftol': 1e-3,
                'gtol': 1e-3,
                'xtol': 1e-3,
                'max_nfev': 1,
                'method': 'trf',
                'tr_solver': 'lsmr',
                'x_scale': 'jac'}
            fit.fitset = fitset

            # call performfit to re-initialize _fnevals functions
            # (they might have been removed if symeninge has been used)
            fit.performfit()

            # get list of available plot-methods
            method_list = [func for func in dir(fit.plot) if
                           callable(getattr(fit.plot, func)) and not func.startswith("__")]

            for function_name in method_list:
                print(f'... {function_name}')
                f = fit.plot.__getattribute__(function_name)()
                if function_name == 'printsig0analysis':
                    plt.close(f[0])
                elif function_name == 'analyzemodel':
                    plt.close(f[0])
                else:
                    plt.close(f)

    def test_performfit(self):
        # settings with whome the fit has been performed
        fitset = {
            'ftol': 1e-3,
            'gtol': 1e-3,
            'xtol': 1e-3,
            'max_nfev': 50,
            'method': 'trf',
            'tr_solver': 'lsmr',
            'x_scale': 'jac'}
        for path, msg in zip([self.sig0_dB_path, self.sig0_linear_path],
                             ['dB', 'linear']):

            print(f'testing plotfunctions for {msg} fit')
            fit = self.load_data(path)
            fit.fitset = fitset
            old_results = copy.deepcopy(fit.res_dict)
            print('testing performfit')
            fit.performfit()

            for key, val in old_results.items():
                self.assertTrue(np.allclose(np.repeat(*fit.res_dict[key]), val, atol=1e-4, rtol=1e-4),
                                msg=f'fitted values for {msg} fit of {key} ' +
                                     f'differ by {np.mean(np.repeat(*fit.res_dict[key]) - val)}')



if __name__ == "__main__":
    unittest.main()
@@ -944,38 +944,42 @@
 th)%0A            
-fitset
+lsq_kwargs
  = %7B%0A           
@@ -1208,31 +1208,39 @@
     fit.
-fitset = fitset
+lsq_kwargs = lsq_kwargs
 %0A%0A      
@@ -2094,22 +2094,26 @@
         
-fitset
+lsq_kwargs
  = %7B%0A   
@@ -2546,23 +2546,31 @@
 fit.
-fitset = fitset
+lsq_kwargs = lsq_kwargs
 %0A   

fix of (fitset->lsq_kwargs) change in test_fit_dumps