def parse_compound(cls, expr, db_atom): """ Parse compound expressions (based on some atomic expressions defined in db_atom) Compound expressions follow the syntax either '#expr' if expr is an atomic expression '$(expr_0,..,expr_n)' where $ is an operator (#, *, **, +) acting on expr_0 to _n e.g. expr = '**(#a,*(#c,+(#d,#e)))' with db = {'a':xx,'c':yy,'d':qq,'e':zz} """ if (not (ut.is_str(expr))): raise SystemError('prse_atom: atom arg should be a string') op, list_sub_expr = cls._split_op_args(expr) if (op == '#'): res = db_atom[list_sub_expr] elif (op in cls._PARSING_DICO_OP): parsed_sub = [ cls.parse_compound(sub, db_atom) for sub in list_sub_expr ] res = cls._apply_operator(op, parsed_sub) else: raise SystemError('operator {0} not recognized'.format(op)) return res
def save_plot_best_func(list_name, save_fig): if(ut.is_str(save_fig)): plt.close() for n in list_name: plot_one_best_func(rawres[n]) plt.legend(list_name) plt.savefig(save_fig) plt.close()
def plot_pop_adiab(model, **args_pop_adiab): """ Plot pop adiab where each population_t is dispatched on one of the three subplot #TODO: better plots """ if (hasattr(model, 'pop_adiab')): limit_legend = args_pop_adiab.get('lim_legend', 10) limit_enlevels = args_pop_adiab.get('lim_enlevels', np.inf) pop_adiab = model.adiab_pop #txn t = model.adiab_t en = model.adiab_en #txn cf = model.adiab_cf # txcf nb_levels = min(pop_adiab.shape[1], limit_enlevels) en_0 = en[:, 0] #[0,0] control function f, axarr = plt.subplots(2, 2, sharex=True) axarr[0, 0].plot(t, cf, label='f(t)') for i in range(nb_levels): pop_tmp = pop_adiab[:, i] max_tmp = np.max(pop_tmp) if (i <= limit_legend): lbl_tmp = str(i) else: lbl_tmp = None if (max_tmp > 0.1): axarr[0, 1].plot(t, pop_tmp, label=lbl_tmp) elif (max_tmp > 0.01): axarr[1, 1].plot(t, pop_tmp, label=lbl_tmp) axarr[1, 0].plot(t, en[:, i] - en_0, label=lbl_tmp) ax_tmp = axarr[0, 1] ax_tmp.legend(fontsize='x-small') ax_tmp.set_title('main pop') ax_tmp.set(xlabel='t', ylabel='%') ax_tmp = axarr[1, 1] ax_tmp.legend(fontsize='x-small') ax_tmp.set_title('sec pop') ax_tmp.set(xlabel='t', ylabel='%') ax_tmp = axarr[0, 0] ax_tmp.legend() ax_tmp.set_title('control') ax_tmp.set(xlabel='t', ylabel='cf') ax_tmp = axarr[1, 0] ax_tmp.set_title('instantaneous ein') ax_tmp.set(xlabel='t', ylabel='E') save_fig = args_pop_adiab.get('save_fig') if (ut.is_str(save_fig)): f.savefig(save_fig) else: logger.warning( "pcModel_qspin.plot_pop_adiab: no pop_adiab found.. Generate it first" )
def _read_configs(cls, config_object, list_output = True): """ Allow for different type of configs to be passed (<dic>, <list<dic>>, <str>, <list<str>>) """ if(ut.is_dico(config_object)): configs = [config_object] if(list_output) else config_object elif(ut.is_list(config_object)): configs = [cls._read_configs(conf, list_output = False) for conf in config_object] elif(ut.is_str(config_object)): configs = ut.file_to_dico(config_object) if(list_output): configs = [configs] else: raise NotImplementedError() return configs
def _init_params_NM(self, **args_optim): """Methods: + 'zero' for each params 0 <(nb_params) np.array> + 'uniform', 'normal', 'lhs' <(n_bparams+1, n_params ) np.array> + 'nmguess_guess_step0_stepNon0': <(n_params+1, n_params ) np.array> Init produce N+1 vertices arround a guess (adapted fm Matlab routine) guess[0] = guess, guess[i] = guess + e * n_i, with e= step0/stepNon0 (dep on value of guess for a particular element) and n_i is one basis unit vector) e.g. nmguess_[3,0,1]_0.5_1 >> [[3,0,1], [4, 0, 1], [3,0.5,1], [3,0,2]] """ init_obj = args_optim['init_obj'] nb_params = args_optim['nb_params'] if(ut.is_str(init_obj)): args = init_obj.split("_") if(args[0] == 'zero'): init_args = np.zeros_like(nb_params) elif(args[0] in ['uniform','normal', 'lhs']): dim = [nb_params + 1, nb_params] init_args = self.rdm_gen.gen_rdmnb_from_string(init_obj, dim) elif(args[0] == 'nmguess'): assert (len(args)==4), 'nmguess, not the right format' guess, step0, stepNon0 = args[1], args[2], args[3] init_args = np.zeros_like([nb_params + 1, nb_params]) init_args[0, :] = guess for i in range(nb_params): perturb = np.zeros(nb_params) if(guess[i] == 0): perturb[i] = step0 else: perturb[i] = stepNon0 init_args[(i+1), :] = init_args[0,:] + perturb return init_args print(init_args) elif init_obj is None: print('params set up to zero-vect') init_args = np.zeros(nb_params) else: init_args = np.array(init_obj) return init_args
def plot_pop_adiab(model, **args_pop_adiab): """ Plot pop adiab where each population_t is dispatched on one of the three subplot #TODO: better plots """ col_list = [ 'b', 'g', 'r', 'c', 'm', 'k', 'C0', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9' ] * 10 if (hasattr(model, 'pop_adiab')): limit_legend = args_pop_adiab.get('lim_legend', 15) limit_enlevels = args_pop_adiab.get('lim_enlevels', np.inf) pop_adiab = model.adiab_pop #txn t = model.adiab_t en = model.adiab_en #txn cf = model.adiab_cf # txcf nb_levels = min(pop_adiab.shape[1], limit_enlevels) #[0,0] control function f, axarr = plt.subplots(2, 2, sharex=True) axarr[0, 0].plot(t, cf, label='f') #r"$\Gamma(t)$") for i in range(nb_levels): col = col_list[i] pop_tmp = pop_adiab[:, i] max_tmp = np.max(pop_tmp) if (i <= limit_legend): lbl_tmp = str(i) else: lbl_tmp = None if (max_tmp > 0.1): axarr[0, 1].plot(t, pop_tmp, label=lbl_tmp, color=col) elif (max_tmp > 0.01): axarr[1, 1].plot(t, pop_tmp, label=lbl_tmp, color=col) if (i < 10): axarr[1, 0].plot(t, en[:, i] - en[:, 0], label=lbl_tmp, color=col) ax_tmp = axarr[0, 1] ax_tmp.legend(fontsize='x-small') ax_tmp.set_title('Population', fontsize=8) ax_tmp.set(xlabel='t') ax_tmp = axarr[1, 1] ax_tmp.legend(fontsize='x-small') ax_tmp.set(xlabel='t') ax_tmp = axarr[0, 0] ax_tmp.legend() ax_tmp.set(xlabel='t', ylabel='cf') ax_tmp = axarr[1, 0] ax_tmp.set(xlabel='t', ylabel='E') #r"$E_i - E_0$" save_fig = args_pop_adiab.get('save_fig') if (ut.is_str(save_fig)): f.savefig(save_fig) else: print( "pcModel_qspin.plot_pop_adiab: no pop_adiab found.. Generate it first" )
def parse_atom(cls, atom): """ parse atomic expression simply append """ if (not (ut.is_str(atom))): raise SystemError('prse_atom: atom arg should be a string') res = 'self.build_atom_func(' + atom + ')' return res
def _build_control(self, model_dico): """ if the control_object is a string evaluate it if not do nothing""" control = model_dico.get('control_obj', None) if(ut.is_str(control)): model_dico['control_obj'] = type(self)._build_control_from_string(control, None, model_dico)
def _build_constraints(self, constraint_obj, **xargs): # Creation of constraints if constraint_obj is not None: if ut.is_str(constraint_obj): components = constraint_obj.split('_') if(components[0] == 'step'): limit = float(components[1]) logger.info("use of constraints: step with step value {0}".format(limit)) nb_params = xargs['nb_params'] cst = [{'name':str(i), 'constraint': 'abs(x[:,{0}]-x[:,{1}])-{2}'.format(i-1, i, limit)} for i in range(1, nb_params)] if(len(components) >= 3): xref = float(components[2]) cst += [{'name':'0', 'constraint':'abs(x[:,0]-{0})-{1}'.format(xref, limit)}] if(len(components) >= 4): xref = float(components[3]) cst += [{'name':str(nb_params), 'constraint':'abs(x[:,-1]-{0})-{1}'.format(xref, limit)}] elif(components[0] == 'smooth'): # quite costly to compute model = xargs['model'] func = model.control_fun[0].clone() if model.n_controls > 1: logger.warning('smoothness constraints have just been computed on the first control function') limit = float(components[1]) time = model.t_array.copy() time[0] = time[0] - 1e-6 time[-1] = time[-1] + 1e-6 logger.info("use of constraints: smoothness is capped to {0}".format(limit)) def compute_smoothness(x, func, limit): func.theta = x return func.smoothness(time) - limit def smooth_constr(x): return np.array([compute_smoothness(xx, func, limit) for xx in x]) cst = [{'name':'smooth', 'constraint':smooth_constr}] elif(components[0] == 'smoothlin'): limit = float(components[1]) if(len(components) == 4): xinit = float(components[2]) xfinal = float(components[3]) def smoothlin_constr(x): res = np.sum(np.square(np.diff(x)), axis =1) + np.square(x[:,0] -xinit) + np.square(x[:,-1] -xfinal) return res / (x.shape[1] + 1) -limit else: def smoothlin_constr(x): return np.sum(np.square(np.diff(x)), axis = 1) / (x.shape[1] -1) -limit logger.info("use of constraints: smoothness linear is capped to {0}".format(limit)) cst = [{'name':'smooth', 'constraint':smoothlin_constr}] else: logger.error("Constraints for BO {} is not recognized".format(components[0])) else: logger.error("Constraints for BO {} is not recognized".format(constraint_obj)) else: cst = None return cst