def minimize(self): # Compass requires an initial point if self.x0 is None: self.x0 = self.domain.l + self.domain._range / 2 res = minimizeCompass(self.f, bounds=self.domain.bounds, x0=self.x0, niter=self.config.niter, deltatol=self.config.deltatol, deltainit=self.config.deltainit, scaling=self.domain.range, redfactor=self.config.redfactor, errorcontrol=False, funcNinit=30, alpha=0.05, paired=False) x0 = res['x'] res = minimizeCompass(self.f, bounds=self.domain.bounds, x0=x0, niter=self.config.niter, deltatol=self.config.deltatol, deltainit=2*self.config.deltatol, scaling=self.domain.range, redfactor=self.config.redfactor, errorcontrol=True, funcNinit=30, alpha=0.05, paired=False)
def noisy_opt(): bounds = [[params[i][1], params[i][2]] for i in range(len(params))] x0 = np.array([params[i][3] for i in range(len(params))]) res = minimizeCompass(obj_func_one, bounds=bounds, x0=x0, deltatol=0.1, paired=False) print(res)
def optimize(stim_name_list, pin_score_dict): score_mat = np.concatenate(tuple( [pin_score_dict[n] for n in stim_name_list]), axis=0) optimizer_len = np.shape(score_mat)[0] bound = [[0, 100] for _ in range(optimizer_len)] initial_guess = np.array( [np.random.random_sample() * 100 for _ in range(optimizer_len)]) obj = construct_objective(score_mat) print("starting min compas") return minimizeCompass(obj, bounds=bound, x0=initial_guess, deltainit=1000, deltatol=0.001, paired=False)
def optimizer_prediction(number_of_layers, material, filename): ''' Optimizes the prediction of the TBR by changing the enrichment fractions and the TBR values and returns the best enrichment configuration for the highest TBR. ''' bounds=() x0=[] for k in range(number_of_layers): bounds=bounds+((0,1),) x0.append(0.5) bounds = bounds + ((0,2),) print(bounds) x0.append(1.2) print(x0) result = minimizeCompass(find_prediction, bounds=bounds, x0=x0, deltatol=0.01, paired=True, disp=False) args=[{'number_of_layers' : number_of_layers,'material' : material, 'filename' : filename}] print(result) print(1/result.fun)
def simulate(material, first_wall): results = [] bounds = () x0 = [] with open( 'results/result_noisyopt_' + str(material) + '_' + str(first_wall) + '.json', 'w') as file_object: json.dump([], file_object, indent=2) for number_of_layers in [1, 2, 3, 4]: with open('results/result_noisyopt_' + str(material) + '_' + str(first_wall) + '.json') as file_object: results = json.load(file_object) bounds = bounds + ((0, 1), ) print(bounds) x0.append(0.5) print(x0) result = minimizeCompass(find_tbr, bounds=bounds, x0=x0, deltatol=0.01, paired=True, disp=False) args = [{'material': material, 'first_wall': first_wall}] print(result) print(1 / result.fun) json_output = { "max_tbr": 1 / result.fun, "best_enrichment": list(result.x), "number_of_layers": len(result.x), "breeder_material_name": args[0]['material'], "include_first_wall": args[0]['first_wall'] } print('json_output', json_output) results.append(json_output) with open( 'results/result_noisyopt_' + str(material) + '_' + str(first_wall) + '.json', 'w') as file_object: json.dump(results, file_object, indent=2)
def optimize(stim_name_list, subset_list=None, min_bound=0, max_bound=100): if isinstance(stim_name_list, str): # Single stim optimization. stim_name_list = [stim_name_list] else: # Multi stim optimization. # Already a list, nothing to be done to stim_name_list. pass score_mat = np.concatenate(tuple( [pin_score_dict[n] for n in stim_name_list]), axis=0) print("SCORE MAT NAN PATCH") score_mat = np.where( np.isnan(score_mat), np.ma.array(score_mat, mask=np.isnan(score_mat)).max(axis=0), score_mat) # print("SCORE MAT CLIP") # score_mat = np.clip(score_mat,0, 100) # Use only a subset of the data points if provided. # Otherwise, use all of the data points still. if subset_list is not None: score_mat = np.take(score_mat, subset_list, 1) optimizer_len = np.shape(score_mat)[0] bound = [[min_bound, max_bound] for _ in range(optimizer_len)] np.random.seed(0) initial_guess = np.array( [np.random.random_sample() * 100 for _ in range(optimizer_len)]) obj = construct_objective(score_mat) return minimizeCompass(obj, bounds=bound, x0=initial_guess, deltainit=100, deltatol=0.01, paired=False), score_mat, obj
def optimize(stim_name_list, pin_score_dict, collapsed_sensitivity_dict): score_mat = np.concatenate(tuple( [pin_score_dict[n] for n in stim_name_list]), axis=0) sensitivity_mat = np.concatenate(tuple( [collapsed_sensitivity_dict[n] for n in stim_name_list]), axis=0) optimizer_len = np.shape(score_mat)[0] bound = [[0, 100] for _ in range(optimizer_len)] initial_guess = np.array( [np.random.random_sample() * 100 for _ in range(optimizer_len)]) obj = construct_objective(score_mat, sensitivity_mat, param_select_vec=[9], obj_comb_vec=[1, 1]) return minimizeCompass(obj, bounds=bound, x0=initial_guess, deltainit=1000, deltatol=1, paired=False)
ubMatrix = UpperBounds bRangeMatrix = ubMatrix - lbMatrix x0 = lbMatrix + np.random.rand(1, nVars) * bRangeMatrix # print(x0[0]) # obj_sim = Simulator(ObjectiveFcn(x0[0],nVars,currentStock,currentOrder)) # minimizeCompass(obj_sim.simulate, [0, 0], method='BFGS', callback=obj_sim.callback, options={"disp": True}) res = None while res is None: try: # connect res = minimizeCompass( ObjectiveFcn, x0=x0[0], deltatol=0.1, paired=False, args=[nVars, currentStock, currentOrder], errorcontrol=False) except: print( "\nAn unexcpected error occured. Program will terminate.\nPlease try running again..." ) time.sleep(2) sys.exit() # print(f"Number of calls to Simulator instance {obj_sim.num_calls}") pos = res.x iterationsList.append(res.nit)
logfile_name = start_time.strftime('test_noisyopt_results' + '%Y%m%d_%H%M%S') print("Log file: %s" % logfile_name) logfile = open(logfile_name, "w") log(logfile, 'Optimization method: noisyopt', stdout=False) log(logfile, "0-dB crossing\trmse\t\tExec Time") if args.func == 'quad_func': bnds = [(-1, 1)] x0 = [1.0] save = True res = minimizeCompass(quad_func, x0, args=(save, save), bounds=bnds, deltainit=deltainit, funcNinit=funcNinit, paired=False, feps=feps, disp=False) x = np.linspace(-1, 1, 100) for i in x: y.append(quad_func(i, False)) elif args.func == 'cavity_step_rmse': bnds = [(10000, 70000)] x0 = [10000] res = minimizeCompass(cavity_step_rmse, x0, args=(args.time, args.time),
# This is a minimal usage example for the optimization routines # see also http://noisyopt.readthedocs.io/en/latest/tutorial.html import numpy as np from noisyopt import minimizeCompass, minimizeSPSA # definition of noisy function to be optimized def obj(x): return (x**2).sum() + 0.1 * np.random.randn() bounds = [[-3.0, 3.0], [0.5, 5.0]] x0 = np.array([-2.0, 2.0]) res = minimizeCompass(obj, bounds=bounds, x0=x0, deltatol=0.1, paired=False) print(res) res = minimizeSPSA(obj, bounds=bounds, x0=x0, niter=1000, paired=False) print(res)
print(Y) #readLog() ##We are doing nothing here for now ##converting polar displacemt to polarization for computing error ##Not required for now ; comparing the polar displacements with DFT polar displacements #Y[6]=Y[6]*CbyV/((Y[0]+1)*(Y[1]+1)*(Y[2]+1)) #Y[7]=Y[7]*CbyV/((Y[0]+1)*(Y[1]+1)*(Y[2]+1)) #Y[8]=Y[8]*CbyV/((Y[0]+1)*(Y[1]+1)*(Y[2]+1)) ##script to compute error totalError = 0 for i in [0, 1, 2, 8]: totalError = totalError + ((Y[i] - Y0[i]) / (Y0[i]))**2 IT = IT + 1 return (totalError) #paramWrite(pInitFName,p0) ##note required, defined n the function itself #fopt.Bounds(lB, uB, keep_feasible=False) #fopt = optimize.minimize(Fun,p0,method='L-BFGS-B') fopt = minimizeCompass(Fun, bounds=pBounds, x0=p0, deltatol=0.1, paired=False) #fopt.Bounds(lB, uB, keep_feasible=False) #printing print("###################################################################") print("Minimum function value =", fopt.fun) print("Minimum function value at x =", fopt.x) print("Number of iterations done =", IT) #print(xopt) print("###################################################################") # In[ ]:
def test_minimizeCompass(): deltatol = 1e-3 ## basic testing without stochasticity def quadratic(x): return (x**2).sum() res = noisyopt.minimizeCompass(quadratic, np.asarray([0.5, 1.0]), deltatol=deltatol, errorcontrol=False) npt.assert_allclose(res.x, [0.0, 0.0], atol=deltatol) npt.assert_equal(res.free, [False, False]) # test with callback def callback(x): assert len(x) == 2 res = noisyopt.minimizeCompass(quadratic, np.asarray([0.5, 1.0]), deltatol=deltatol, errorcontrol=False, callback=callback) # test with scaling res = noisyopt.minimizeCompass(quadratic, np.asarray([0.5, 1.0]), deltatol=deltatol, scaling=np.array([0.1, 1.0]), errorcontrol=False) npt.assert_allclose(res.x, [0.0, 0.0], atol=deltatol) # test with output res = noisyopt.minimizeCompass(quadratic, np.asarray([0.5, 1.0]), deltatol=deltatol, errorcontrol=False, disp=True) npt.assert_allclose(res.x, [0.0, 0.0], atol=deltatol) npt.assert_equal(res.free, [False, False]) res = noisyopt.minimizeCompass(quadratic, np.asarray([2.5, -3.2]), deltatol=deltatol, errorcontrol=False) npt.assert_allclose(res.x, [0.0, 0.0], atol=deltatol) npt.assert_equal(res.free, [False, False]) res = noisyopt.minimizeCompass(quadratic, np.asarray([2.5, -3.2, 0.9, 10.0, -0.3]), deltatol=deltatol, errorcontrol=False) npt.assert_allclose(res.x, np.zeros(5), atol=deltatol) npt.assert_equal(res.free, [False, False, False, False, False]) ## test bound handling res = noisyopt.minimizeCompass(quadratic, np.asarray([0.5, 0.5]), bounds=np.asarray([[0, 1], [0, 1]]), deltatol=deltatol, errorcontrol=False) npt.assert_allclose(res.x, [0.0, 0.0], atol=deltatol) npt.assert_equal(res.free, [False, False]) res = noisyopt.minimizeCompass(quadratic, np.asarray([0.8, 0.8]), bounds=np.asarray([[0.5, 1], [0.5, 1]]), deltatol=deltatol, errorcontrol=False) npt.assert_allclose(res.x, [0.5, 0.5], atol=deltatol) npt.assert_equal(res.free, [False, False]) ## test args passing def quadratic_factor(x, factor): return factor * (x**2).sum() res = noisyopt.minimizeCompass(quadratic_factor, np.asarray([0.5, 1.0]), paired=False, args=(1.0, )) npt.assert_allclose(res.x, [0.0, 0.0], atol=deltatol) ## test determination of unconstrained variables def quadratic_except_last(x): return (x[:-1]**2).sum() res = noisyopt.minimizeCompass(quadratic_except_last, np.asarray([0.5, 1.0]), errorcontrol=False) npt.assert_approx_equal(res.x[0], 0.0) npt.assert_equal(res.free, [False, True]) ## test errorcontrol for stochastic function def stochastic_quadratic(x, seed=None): prng = np.random if seed is None else np.random.RandomState(seed) return (x**2).sum() + prng.randn(1) + 0.5 * np.random.randn(1) deltatol = 0.5 # test unpaired res = noisyopt.minimizeCompass(stochastic_quadratic, np.array([4.55, 3.0]), deltainit=2.0, deltatol=deltatol, errorcontrol=True, paired=False) npt.assert_allclose(res.x, [0.0, 0.0], atol=deltatol) npt.assert_equal(res.free, [False, False]) # test paired res = noisyopt.minimizeCompass(stochastic_quadratic, np.array([4.55, 3.0]), deltainit=2.0, deltatol=deltatol, errorcontrol=True, paired=True) npt.assert_allclose(res.x, [0.0, 0.0], atol=deltatol) npt.assert_equal(res.free, [False, False])
### noisyopt start objcount = 0 def obj(x): global objcount objcount += 1 #if objcount%1000==0: # print(objcount) a = x[0] b = x[1] c = x[2] d = x[3] lib.c_assignAndRun(a, b, c, d) return getCurEnergy() #return getCurMoment() #start_time = time.time() #print(obj([12,6])) #print("--- %s seconds ---" % (time.time() - start_time)) lib.c_setNumConfigs(100) res = minimizeCompass(obj, x0=snx0, deltatol=1, paired=False) print(objcount) print(res.success) print(snx0) print(res.x) np.savetxt(resfile, np.vstack((snx0, res.x)))
xx = np.eye(2**n_qubits) def Los2(Theta): return sum( np.linalg.norm(func(Theta, xx[i]) - xx[i]) for i in range(2**n_qubits - 1)) def Los3(test): return Los2([0, 0, test, 0, 0, 0]) res = minimizeCompass(Los3, x0=[1], bounds=[[-np.pi, np.pi]], deltatol=0.1, paired=False) a = { "00": func([0, 0, 0, 0, 0, 0], [1, 0, 0, 0])[0], "01": func([0, 0, 0, 0, 0, 0], [0, 1, 0, 0])[1], "10": func([0, 0, 0, 0, 0, 0], [0, 0, 1, 0])[2], "11": func([0, 0, 0, 0, 0, 0], [0, 0, 0, 1])[3], } b = { "00": func([0, 0, -0.5, 0, 0, 0], [1, 0, 0, 0])[0], "01": func([0, 0, -0.5, 0, 0, 0], [0, 1, 0, 0])[1], "10": func([0, 0, -0.5, 0, 0, 0], [0, 0, 1, 0])[2], "11": func([0, 0, -0.5, 0, 0, 0], [0, 0, 0, 1])[3], }
def test_minimizeCompass(): deltatol = 1e-3 ## basic testing without stochasticity def quadratic(x): return (x**2).sum() res = noisyopt.minimizeCompass(quadratic, np.asarray([0.5, 1.0]), deltatol=deltatol, errorcontrol=False) npt.assert_allclose(res.x, [0.0, 0.0], atol=deltatol) npt.assert_equal(res.free, [False, False]) # test with callback def callback(x): assert len(x) == 2 res = noisyopt.minimizeCompass(quadratic, np.asarray([0.5, 1.0]), deltatol=deltatol, errorcontrol=False, callback=callback) # test with scaling res = noisyopt.minimizeCompass(quadratic, np.asarray([0.5, 1.0]), deltatol=deltatol, scaling=np.array([0.1, 1.0]), errorcontrol=False) npt.assert_allclose(res.x, [0.0, 0.0], atol=deltatol) # test with output res = noisyopt.minimizeCompass(quadratic, np.asarray([0.5, 1.0]), deltatol=deltatol, errorcontrol=False, disp=True) npt.assert_allclose(res.x, [0.0, 0.0], atol=deltatol) npt.assert_equal(res.free, [False, False]) res = noisyopt.minimizeCompass(quadratic, np.asarray([2.5, -3.2]), deltatol=deltatol, errorcontrol=False) npt.assert_allclose(res.x, [0.0, 0.0], atol=deltatol) npt.assert_equal(res.free, [False, False]) res = noisyopt.minimizeCompass(quadratic, np.asarray([2.5, -3.2, 0.9, 10.0, -0.3]), deltatol=deltatol, errorcontrol=False) npt.assert_allclose(res.x, np.zeros(5), atol=deltatol) npt.assert_equal(res.free, [False, False, False, False, False]) ## test bound handling res = noisyopt.minimizeCompass(quadratic, np.asarray([0.5, 0.5]), bounds=np.asarray([[0, 1], [0, 1]]), deltatol=deltatol, errorcontrol=False) npt.assert_allclose(res.x, [0.0, 0.0], atol=deltatol) npt.assert_equal(res.free, [False, False]) res = noisyopt.minimizeCompass(quadratic, np.asarray([0.8, 0.8]), bounds=np.asarray([[0.5, 1], [0.5, 1]]), deltatol=deltatol, errorcontrol=False) npt.assert_allclose(res.x, [0.5, 0.5], atol=deltatol) npt.assert_equal(res.free, [False, False]) ## test args passing def quadratic_factor(x, factor): return factor*(x**2).sum() res = noisyopt.minimizeCompass(quadratic_factor, np.asarray([0.5, 1.0]), paired=False, args=(1.0,)) npt.assert_allclose(res.x, [0.0, 0.0], atol=deltatol) ## test determination of unconstrained variables def quadratic_except_last(x): return (x[:-1]**2).sum() res = noisyopt.minimizeCompass(quadratic_except_last, np.asarray([0.5, 1.0]), errorcontrol=False) npt.assert_approx_equal(res.x[0], 0.0) npt.assert_equal(res.free, [False, True]) ## test errorcontrol for stochastic function def stochastic_quadratic(x, seed=None): prng = np.random if seed is None else np.random.RandomState(seed) return (x**2).sum() + prng.randn(1) + 0.5*np.random.randn(1) deltatol = 0.5 # test unpaired res = noisyopt.minimizeCompass(stochastic_quadratic, np.array([4.55, 3.0]), deltainit=2.0, deltatol=deltatol, errorcontrol=True, paired=False) npt.assert_allclose(res.x, [0.0, 0.0], atol=deltatol) npt.assert_equal(res.free, [False, False]) # test paired res = noisyopt.minimizeCompass(stochastic_quadratic, np.array([4.55, 3.0]), deltainit=2.0, deltatol=deltatol, errorcontrol=True, paired=True) npt.assert_allclose(res.x, [0.0, 0.0], atol=deltatol) npt.assert_equal(res.free, [False, False])
# This is a minimal usage example for the optimization routines # see also http://noisyopt.readthedocs.io/en/latest/tutorial.html import numpy as np from noisyopt import minimizeCompass, minimizeSPSA # definition of noisy function to be optimized def obj(x): return (x**2).sum() + 0.1*np.random.randn() bounds = [[-3.0, 3.0], [0.5, 5.0]] x0 = np.array([-2.0, 2.0]) res = minimizeCompass(obj, bounds=bounds, x0=x0, deltatol=0.1, paired=False) print(res) res = minimizeSPSA(obj, bounds=bounds, x0=x0, niter=1000, paired=False) print(res)