from tklib.tkutils import terminate, pint, pfloat, getarg, getintarg, getfloatarg, pconv_by_type, str2val
from tklib.tkutils import format_strlist, sort_lists, is_exist, is_file, is_dir, val2str


from tklib.tkparams import tkParams
from tklib.tksci.tkFit_mxy_flex import tkFit_mxy, save_data, add_history, minimize_func_cachable, _global
save_data, add_history
from tklib.tksci.tkoptimize_direct import particle_swarm_optimization, genetic_algorithm
from tklib.tksci.tkoptimize_direct import simulated_annealing, replica_exchange_monte_carlo
from tklib.tksci.tkmlr import tkMLData, tkMLR


class tkFit_mxy_minimize(tkFit_mxy):
    def __init__(self, **args):
        super().__init__(**args)

    def _callback_simple(self, pk, run = True, savefig_path = None, use_so = False, print_level = 1):
        if self.stop_flag: return False

        fmin = self.minimize_func(pk, print_level)
        print(f"callback: iter={self.iter}: pk={pk}  fmin={fmin}")

        self.iter += 1

        if fmin < self.tol:
            if print_level:
                print(f"Warning: fmin=[{fmin}] reaches tol={self.tol:.4g}.")
            self.stop_flag = True
            return False

        return True

