def KG(z, evls, pnts, gp, kernel, NSAMPS=30, DEG=3, sampling=False): # Find initial minimum value from GP model min_val = 1e100 X_sample = pnts Y_sample = evls #for x0 in [np.random.uniform(XL, XU, size=DIM) for oo in range(20)]: x0 = np.random.uniform(XL, XU, size=DIM) res = mini(gp, x0=x0, bounds=[(XL, XU) for ss in range(DIM)]) #, method='Nelder-Mead') #res = mini(expected_improvement, x0=x0[0], bounds=[(XL, XU) for ss in range(DIM)], args=(X_sample, Y_sample, gp))#, callback=callb) # if res.fun < min_val: min_val = res.fun min_x = res.x # estimate min(f^{n+1}) with MC simulation MEAN = 0 points = np.atleast_2d(np.append(X_sample, z)).T m, s = gp(z, return_std=True) distribution = cp.J(cp.Normal(0, s)) samples = distribution.sample(NSAMPS, rule='Halton') PCEevals = [] for pp in range(NSAMPS): # construct future GP, using z as the next point evals = np.append(evls, m + samples[pp]) #evals = np.append(evls, m + np.random.normal(0, s)) gpnxt = GaussianProcessRegressor(kernel=kernel, n_restarts_optimizer=35, random_state=98765, normalize_y=True) gpnxt.fit(points, evals) # convinience function def gpf_next(x, return_std=False): alph, astd = gpnxt.predict(np.atleast_2d(x), return_std=True) alph = alph[0] if return_std: return (alph, astd) else: return alph res = mini(gpf_next, x0=x0, bounds=[(XL, XU) for ss in range(DIM)]) min_next_val = res.fun min_next_x = res.x #print('+++++++++ ', res.fun) #MEAN += min_next_val PCEevals.append(min_next_val) if not sampling: polynomial_expansion = cp.orth_ttr(DEG, distribution) foo_approx = cp.fit_regression(polynomial_expansion, samples, PCEevals) MEAN = cp.E(foo_approx, distribution) else: MEAN = np.mean(PCEevals) #print(PCEevals, '...', MEAN) #hey #MEAN /= NSAMPS return min_val - MEAN
def lin_fit(time, flux, flux_err): a0 = flux[0] b0 = (flux[-1] - flux[0]) / (time[-1] - time[0]) X0 = [a0, b0] result = mini(fit_lin, X0, args=(time, flux, flux_err)) for i in range(10): result = mini(fit_lin, result.x, args=(time, flux, flux_err)) lin_model = result.x[0] + result.x[1] * time return lin_model, result.x, result.fun
def flux_model(param): res = mini(prob,param,method='Nelder-Mead',tol=1e-18) tau = res.x[1] #1400. #res.x[1] #1400. #res.x[1] b = res.x[0] #9.2/tau #res.x[0] #7.5*10**(-15)/tau #res.x[0] sigma_tot = res.x[2] #0.01 #res.x[2] #1.3*10**(-16) #res.x[2] model = np.zeros((2000,len(flux1))) flux_test = flux1[0] for j in range(len(model[:,0])): model[j,0] = flux1[0] #flux_model = [flux1[0]] #print j for i in range(len(flux1)-1): #print i, model[j,i] dt = (time1[i+1]-time1[i]) epsilon = np.random.normal(0,1,1) dX1 = (flux1[i+1])#*(-1) + model[j,0] change = dX(tau,sigma_tot,dt,b,epsilon,dX1) #flux1[i+1] - flux1[i] #print change,flux1[i+1] model[j,i+1] = change + flux1[i] #model[j,i] # - flux_test) model2 = [] time_model = [] std = [] for i in range(len(model[0,:])): model2.append(np.mean(model[:,i])) std.append(np.std(model[:,i])) time_model.append(time1[i]) flux_model = np.array((time_model,model2,std,res.x)) return flux_model
def best_fit_LC_solve_qlp(phase, flux, rp, a, t0=0., inc=90., ecc=0., w=90., ld="quadratic", u=[0.1, 0.3]): phase = np.array(phase, dtype='float64') res = mini(fit_phasefolded, [rp, a, inc, ecc, w, u[0], u[1]], args=(phase, flux, np.zeros(len(flux)) + np.std(flux))) for i in range(20): if res.success == False: res = mini(fit_phasefolded, res.x, args=(phase, flux, np.zeros(len(flux)) + np.std(flux))) else: res = res #print(res.success) # t0_best = res.x[0] rp_best = res.x[0] a_best = res.x[1] inc_best = res.x[2] ecc_best = res.x[3] w_best = res.x[4] u1_best, u2_best = res.x[5], res.x[6] flux_best = lc_model(phase, rp_best, a_best, t0=0., per=1., inc=inc_best, ecc=ecc_best, w=w_best, limb_dark="quadratic", u=[u1_best, u2_best]) return flux_best, res.x, res.fun
def poly_fit(time, flux, flux_err): a0 = flux[0] b0 = -10 c0 = 4 d0 = 5 X0 = [a0, b0, c0, d0] result = mini(fit, X0, args=(time, flux, flux_err)) for i in range(10): result = mini(fit, result.x, args=(time, flux, flux_err)) # print result.x poly_model = result.x[ 0] + result.x[1] * time + result.x[2] * time**2 + result.x[3] * time**3 return poly_model, result.x, result.fun
def test_minimize(): with variable_scope() as vm: m = Variable("R_m", value=2.1) vm.set_bound({"R_m": (None, 3)}) def f(): return m() * m() from scipy.optimize import minimize as mini ret = vm.minimize( f, method=lambda g, x: mini(g, x, jac=True, method="L-BFGS-B")) print(ret) assert abs(m().numpy()) < 1e-6
args = parser.parse_args() if args.fit == "sec": data = np.loadtxt(args.fn) phase, flux, err = data[:, 0], data[:, 1], data[:, 2] t0, per, rp, a, inc, e, w, fp = args.epoc, args.period, args.rad, args.smaxis, args.inclination, args.ecc, args.omega, args.flux phase_fit = np.array(phase, dtype=float) bounds = Bounds(([28., 85., 0.53]), ([33., 90., 0.54])) res = mini(fit_secondary, [a, inc, e], args=(phase_fit, flux, err), bounds=bounds) print("Minimization success is: {} with $\chi^2$={:.2f}".format( res.success, res.fun)) print("a = {:.4f}; inc = {:.4f}; ecc = {:.4f}".format( res.x[0], res.x[1], res.x[2])) # print("inc = {:.4f}; ecc = {:.4f}; w = {:.4f}; u = [{:.4f}, {:.4f}]".format(res.x[3], res.x[4], res.x[5], res.x[6], res.x[7])) pm = bm.TransitParams() pm.t0 = t0 pm.per = 1. pm.rp = rp pm.a = res.x[0] pm.inc = res.x[1]
def understand(x, y): print("learning structure") return mini(loss, [0.25 for i in range(4)], args=(x, y)).x
#%% PROGRAMA # Configuraciones para ejecutar algoritmo de optimización restricciones = [{ 'type': 'eq', 'fun': restriccion1 }, { 'type': 'ineq', 'fun': restriccion2 }] limites = (limitesX0, limitesX1) # Ejecución de optimización solucion = mini(f, semilla, method='SLSQP', bounds=limites, constraints=restricciones) #%% IMPRESIÓN DE RESULTADOS print() print('Resultado de ejecución:') print(solucion) print() print('Solución:') print('X1 = {:.4f}'.format(solucion.x[0])) print('X2 = {:.4f}'.format(solucion.x[1])) print('Función evaluada en solución: {:.4f}'.format(solucion.fun))
def SMaxTuning(self): # #----------------------------------------------- INPUT = self.TRNG_DATA NOISE_SIG = self.SYSTEM_PARAMS['SMAX_TUNE']['smax_noise_sigma'] W_DECAY = self.SYSTEM_PARAMS['SMAX_TUNE']['smax_weight_decay'] MAX_TUNE_EPS = self.SYSTEM_PARAMS['SMAX_TUNE']['smax_tune_epochs'] NUM_CLASSES = self.SYSTEM_PARAMS['STACK']['num_classes'] SYSPARM = [] SHAPES = [] for LAY in self.GenLayers(): W = LAY['WIN'] SHAPES.append(W.shape) SYSPARM.append(W.flatten()) if LAY.has_key('BIN'): B = LAY['BIN'] SHAPES.append(B.shape) SYSPARM.append(B.flatten()) SYSPARM = np.concatenate(SYSPARM) if self.SYSTEM_PARAMS['SMAX_TUNE']['use_batcher']: if self.BATCHER is None: self.BATCHER = Batcher() NUM_BATCHES = self.SYSTEM_PARAMS['BATCHER']['num_batches'] BATCHES, BAT_LABS = self.BATCHER.GetBatches(INPUT, self.RANDO) DisplayItems('Finetune BATCH SMax', self.SYSTEM_PARAMS['SMAX_TUNE'], num_classes=NUM_CLASSES, verbose=self.CHECKS['verbose'], Elapsed_Global_Time=time.clock() - self.TIMER) T = lambda x: TrainStackedSAEBatchAlgo(x, NUM_CLASSES, SHAPES, W_DECAY, NOISE_SIG, NUM_BATCHES, BATCHES, BAT_LABS) else: if self.SYSTEM_PARAMS['STACK']['use_generic_labels'] or not self.CHECKS['labels_loaded']: self.LoadLabels('generic', num_classes=NUM_CLASSES, num_labs=INPUT.shape[0]) LABS = self.TRNG_LABS DisplayItems('Finetune Online SMax', self.SYSTEM_PARAMS['SMAX_TUNE'], num_classes=NUM_CLASSES, Elapsed_Global_Time=time.clock() - self.TIMER, verbose=self.CHECKS['verbose']) print "{0} | {1} | {2} << {3}".format('COST','AVGACT', 'KLD','ERR') T = lambda x: TrainStackedSAEAlgo(x, NUM_CLASSES, SHAPES, W_DECAY, NOISE_SIG, INPUT, LABS) options_ = {'maxiter' : MAX_TUNE_EPS, 'gtol' : 1e-9 , 'disp' : self.CHECKS['verbose']} RES = mini(T, SYSPARM, method='L-BFGS-B', jac=True, options=options_) FLATWnB = RES.x NEW_SLI = [] for wb, lay in zip(self.GenRebuilt(FLATWnB, SHAPES),self.StackLayerInfo['LAYER']): LAY_DICT = {} LAY_DICT.update(lay) WIN,BIN = wb if BIN != []: LAY_DICT.update({'WIN':WIN, 'BIN':BIN}) else: LAY_DICT.update({'WIN':WIN}) NEW_SLI.append(LAY_DICT) self.StackLayerInfo['LAYER'] = [nu_sli for nu_sli in NEW_SLI]
parser.add_argument('-fp', '--flux', type=float, default=1.) args = parser.parse_args() t0, per, rp, a, inc, ecc, w, fp = args.epoc, args.period, args.rad, args.smaxis, args.inclination, args.ecc, args.omega, args.flux if args.fit == 'full': data_full = np.loadtxt(args.fn) time_full, flux_full = data_full[:, 0] - data_full[:, 0].min(), data_full[:, 3] bw = args.binwidth / 1440 #put bin width into units of days time_bin, flux_bin, err_bin = lc_bin(time_full, flux_full, bw) bounds_full = Bounds(([t0-0.1, per-0.05, rp-0.3, a-5, 85., 0., 0., 0., 0.]), ([t0+0.1, per+0.05, rp+0.3, a+5, 90., 1.0, 90., 1.0, 1.0])) res = mini(fold_fit, [t0, per, rp, a, 89., 0., 90., 0.3, 0.2], args=(time_bin, flux_bin, err_bin), bounds=bounds_full) print(res.x, res.fun) print(res.success) pm = bm.TransitParams() pm.t0 = 0.25 pm.per = 1. pm.rp = res.x[2] pm.a = res.x[3] pm.inc = res.x[4] pm.ecc = res.x[5] pm.w = res.x[6] u1, u2 = res.x[7], res.x[8] pm.u = [u1, u2]
from scipy.optimize import minimize as mini def fun(x): return 1000-x[0]**2-2*x[1]**2-x[2]**2-x[0]*x[1]-x[0]*x[2] bnds = ((0, 5), (0, 5), (0, 5)) cons = ({'type': 'eq', 'fun': lambda x: 8*x[0]+14*x[1]+7*x[2]-56}, {'type': 'eq', 'fun': lambda x: x[0]**2+x[1]**2+x[2]**2-25}) res = mini(fun, [0, 0, 0], method='SLSQP', bounds=bnds, constraints=cons) # Nelder-Mead,Powell,CG,BFGS,Newton-CG,Anneal,L-BFGS-B,TNC,COBYLA,SLSQP,dogleg,turst-ncg,custom -a callable object print(res.success) print(res.x) print(res.fun)
data1 = np.loadtxt(args.fn1) phase_bin1, flux_bin1, err_bin1 = data1[:, 0], data1[:, 1], data1[:, 2] data2 = np.loadtxt(args.fn2) phase_bin2, flux_bin2, err_bin2 = data2[:, 0], data2[:, 1], data2[:, 2] t0, rp, a = args.epoc, args.rad, args.smaxis phase_fit1 = np.array(phase_bin1, dtype=float) phase_fit2 = np.array(phase_bin2, dtype=float) bounds = Bounds(([0.01, 0.01, 5., 85., 0.5, 0., 0., 0., 0., 0.]), ([1., 1., 30., 90., 0.9, 360., 1., 1., 1., 1.])) res = mini(fit, [rp, rp, a, 89., 0.7, 90., 0.3, 0.2, 0.3, 0.2], args=(phase_fit1, flux_bin1, err_bin1, phase_fit2, flux_bin2, err_bin2), bounds=bounds) print(res.fun, res.success) print(res.x) pm = bm.TransitParams() pm2 = bm.TransitParams() pm.t0 = 0. pm2.t0 = t0 pm.per = pm2.per = 1. pm.rp = res.x[0] pm2.rp = res.x[1] pm.a = pm2.a = res.x[2] pm.inc = pm2.inc = res.x[3] pm.ecc = pm2.ecc = res.x[4]
def best_params_find(X0, x, y, yerr): result = mini(chi_squared, X0, args=(x, y, yerr)) for i in range(10): result = mini(chi_squared, result.x, args=(x, y, yerr)) return result.x, result.fun
def best_fit_LC_solve(phase, flux, per, rp, a, t0=0., inc=89., ecc=0., w=90., ld="quadratic", u=[0.1, 0.3]): bins = [p * per * 24 * 60 // 10 for p in phase] length = np.int(max(bins) - min(bins)) print(length) p_bin = np.zeros(length) f_bin = np.zeros(length) e_bin = np.zeros(length) sigma = np.std(flux) for i in range(length): # if len(np.where(bins == i + min(bins))[0]) == 1: # p_bin[i] = phase[i] # f_bin[i] = flux[i] # e_bin[i] = sigma if len(np.where(bins == i + min(bins))[0]) > 0: p_bin[i] = np.mean(phase[np.where(bins == i + min(bins))[0]]) f_bin[i] = np.mean(flux[np.where(bins == i + min(bins))[0]]) e_bin[i] = sem(flux[np.where(bins == i + min(bins))[0]]) else: p_bin[i] = -1000 f_bin[i] = -1000 e_bin[i] = -1000 p_bin = np.delete(p_bin, np.where(p_bin < -900)) f_bin = np.delete(f_bin, np.where(f_bin < -900)) e_bin = np.delete(e_bin, np.where(e_bin < -900)) print(np.where(np.isnan(e_bin))) res = mini(fit_phasefolded, [rp, a, inc, ecc, w, u[0], u[1]], args=(p_bin, f_bin, e_bin)) for i in range(20): if res.success == False: res = mini(fit_phasefolded, res.x, args=(p_bin, f_bin, e_bin)) else: res = res # print(res.success) # t0_best = res.x[0] rp_best = res.x[0] a_best = res.x[1] inc_best = res.x[2] ecc_best = res.x[3] w_best = res.x[4] u1_best, u2_best = res.x[5], res.x[6] flux_best = lc_model(p_bin, rp_best, a_best, t0=0., per=1., inc=inc_best, ecc=ecc_best, w=w_best, limb_dark="quadratic", u=[u1_best, u2_best]) return flux_best, p_bin, f_bin, e_bin, res.x, res.fun
timestrategy=TS, BCs=BC, dt=truedt, convstrategy=cs, diffstrategy=ds) errs.append(np.sqrt((u[:, -1] - trueu[0::2**(ii + 2), -1])**2)) #y_2.append(np.max(np.abs(u[:, -1] - trueu[0::2 **( ii + 2 ), -1]))) #y_2.append(np.sum(np.abs((u[:, -1] - trueu[0::2 **( ii + 2 ), -1])) / nx)) y_2.append( np.sqrt(np.sum((u[:, -1] - trueu[0::2**(ii + 2), -1])**2) / nx)) dxs = np.array(dxs) def fitness(a): return 1e25 * np.sum((np.exp(a) * dxs[0] - y_2[0])**2) a = mini(fitness, 4).x def fitness(a): return 1e29 * np.sum((np.exp(a) * dxs[0]**2 - y_2[0])**2) b = mini(fitness, 4).x def fitness(a): return 1e29 * np.sum((np.exp(a) * dxs[0]**4 - y_2[0])**2) c = mini(fitness, 4).x plt.plot(dxs, y_2, marker='*', label='convergence', markersize=10) plt.plot(dxs, np.exp(c) * dxs**4, c='k', label=r'$\Delta X^4$', ls='--') plt.plot(dxs, np.exp(b) * dxs**2, c='k', label=r'$\Delta X^2$', ls='-.') plt.plot(dxs, np.exp(a) * dxs, c='k', label=r'$\Delta X$', ls=':')
"confs.append(lambda x: -10000 * (1e3 - x[{}]) if 1e3 - x[{}]<0 else 0)" .format(i, i)) for j in range(i + 1, nturbs): exec( "confs.append(lambda x: -10000 * np.sqrt((x[:nturbs][{}] - x[:nturbs][{}])**2 + (x[nturbs:][{}] - x[nturbs:][{}])**2) if (np.sqrt((x[:nturbs][{}] - x[:nturbs][{}])**2 + (x[nturbs:][{}] - x[nturbs:][{}])**2) < 2 * D) else 0)" .format(i, j, i, j, i, j, i, j)) cons = tuple([{'type': 'ineq', 'fun': confs[i]} for i in range(len(confs))]) #cons = cons + ({'type': 'ineq', 'fun': bounds},) ii = 0 best = 0 while True: miniout = mini(fitness, x0, bounds=[[0, 1e3] for _ in range(2 * nturbs)], constraints=cons, method="COBYLA", options={ 'rhobeg': 200, 'maxiter': 20000 }) #miniout = mini(fitness, x0, bounds=[[0, 1e3] for _ in range(2 * nturbs)], constraints =cons, method="COBYLA", options={'rhobeg':400}) xopt = miniout.x #xopt = mini(fitness, x0, bounds=[[0, 1e3] for _ in range(2 * nturbs)], constraints =cons, method="COBYLA", options={'maxiter':200000}).x #xopt = mini(fitness, x0, bounds=[[0, 1e3] for _ in range(2 * nturbs)], constraints =cons, method="SLSQP", options={'maxiter':200000}).x #xopt = mini(fitness, x0, bounds=[[0, 1e3] for _ in range(2 * nturbs)], constraints = ({'type': 'eq', 'fun': spacing}), method="SLSQP", options={'maxiter':200000}).x #xopt = mini(fitness, x0, bounds=[[0, 1e3] for _ in range(2 * nturbs)], constraints = ({'type': 'ineq', 'fun': spacing}), method="TNC").x #xopt = mini(fitness, x0, bounds=[[0, 1e3] for _ in range(2 * nturbs)], constraints = ({'type': 'ineq', 'fun': spacing}, {'type': 'ineq', 'fun': bounds}), method="COBYLA").x print spacing(xopt), bounds(xopt), ','.join([str(s) for s in xopt]) print '--' # txopt = xopt[:nturbs] # tyopt = xopt[nturbs:]
def MFKG(z, lfpoints, lfevals, hfpoints, hfevals, kernel, OPTIMIZE=True): # construct initial GP gp1 = GaussianProcessRegressor(kernel=kernel, n_restarts_optimizer=35, random_state=98765, normalize_y=True) gpd = GaussianProcessRegressor(kernel=kernel, n_restarts_optimizer=35, random_state=98765, normalize_y=True) gp1.fit(np.atleast_2d(lfpoints).T, lfevals) gpd.fit(np.atleast_2d(hfpoints).T, hfevals) def gp(x, return_std=False): return (np.array(gp1.predict(x, return_std=return_std)) + np.array(gpd.predict(x, return_std=return_std))) # Find initial minimum value from GP model min_val = 1e100 X_sample = pnts Y_sample = evls #for x0 in [np.random.uniform(XL, XU, size=DIM) for oo in range(20)]: res = mini(gp, x0=x0, bounds=[(0, 3) for ss in range(DIM)], method='Nelder-Mead') #res = mini(expected_improvement, x0=x0[0], bounds=[(XL, XU) for ss in range(DIM)], args=(X_sample, Y_sample, gp))#, callback=callb) # if res.fun < min_val: min_val = res.fun min_x = res.x # estimate min(f^{n+1}) with MC simulation MEAN = 0 NSAMPS = 20 for pp in range(NSAMPS): # construct future GP points = np.atleast_2d(np.append(X_sample, z)).T m, s = gp(z, return_std=True) evals = np.append(evls, m + np.random.normal(0, s)) gpnxt = GaussianProcessRegressor(kernel=kernel, n_restarts_optimizer=35, random_state=98765, normalize_y=True) gpnxt.fit(points, evals) # convinience function def gpf_next(x, return_std=False): alph, astd = gpnxt.predict(np.atleast_2d(x), return_std=True) alph = alph[0] if return_std: return (alph, astd) else: return alph # search for minimum in future GP min_next_val = 99999 #for x0 in [np.random.uniform(XL, XU, size=DIM) for oo in range(10)]: res = mini(gpf_next, x0=x0, bounds=[(XL, XU) for ss in range(DIM)]) #res = mini(expected_improvement, x0=x0, bounds=[(XL, XU) for ss in range(DIM)], args=(np.array(points), np.array(evals), gpf_next)) #res = mini(gpf_next, x0=x0, bounds=[(0, 3) for ss in range(DIM)], args=(X_sample, Y_sample, gpf_next)) #print('--> ', res.fun, res.fun[0] < min_next_val) # if res.fun < min_next_val: min_next_val = res.fun min_next_x = res.x MEAN += min_next_val MEAN /= NSAMPS return min_val - MEAN
def cost(label_arr, model_arr): # inputs are nb.array([]) # sum over training set c = -(1. - label_arr)*np.log(1. - model_arr) - label_arr*np.log(model_arr) return np.sum(c)/len(c) def model_1d(model_vec, df): # Calculate model output z = model_vec[0] + model_vec[1] * df.x return sigmoid(z) def model_cost(model_vec, df, model): # model_vec is python vector # df is data frame with column x and column label # model is a functionto calculate model output return cost(df.label, model(model_vec, df)) from scipy.optimize import minimize as mini res_1d = mini(model_cost, x0=[0.1,0.1], args=(df_1d, model_1d)) print (res_1d) # 预测 #df_pred_1d = pd.DataFrame.from_dict({"x": np.linspace(-3,3,99)}) #df_pred_1d["y"] = model_1d(res_1d.x, df_pred_1d) #df_pred_1d.head() #print classifier.decision_function()
label="Power") plt.xlabel('Turbine') ax.set_ylabel('Speed') ax2.set_ylabel('Power (kW)') ax.legend() ax2.legend(loc="upper right", bbox_to_anchor=[.97, .92]) plt.xlabel("Turbine Number") plt.title("power is %f kW" % (-1 * power(a))) plt.savefig('speed.pdf') plt.clf() #def con1(a): return np.sum(np.abs(a[a>.3333])) #def con2(a): return np.sum(np.abs(a[a<0])) #astar = mini(power, a, constraints=[{'type': 'ineq', 'fun': con1}, {'type': 'ineq', 'fun': con2}], method='COBYLA').x astar = mini(power, a, bounds=[(0, .3333) for _ in range(nturbs)], method='COBYLA').x f, ax = plt.subplots() ax2 = ax.twinx() ax.plot(range(nturbs), uwake(astar), c='k', label="Wind Speed") ax2.plot(range(nturbs), 4 * a * (1 - a)**2 * .5 * uwake(astar)**3 * rho, c='k', ls='--', label='Power') ax.get_yaxis().get_major_formatter().set_scientific(False) ax.get_yaxis().get_major_formatter().set_useOffset(False) ax2.get_yaxis().get_major_formatter().set_scientific(False) ax2.get_yaxis().get_major_formatter().set_useOffset(False) plt.draw()
def nonlinear_least_squares(motor_func, pStart, grid, data, approx_model): # ----------------------------------------------------------------- # Computes the least-squares-parameter for a model function. # N - number of data points # M - number of parameters # ----------------------------------------------------------------- # input: # motor_func func handle to model function of the motor # pStart [Mx1] An initial guess for the parameter vector # grid [Nx3] A vector with points at which some measurement # data exists. The values are # grid = [uDesired, q, dq] # data [Nx1] The measured data at the grid points # approx_model {dict} a description of the model # ----------------------------------------------------------------- # return: # L func handle to residual function # dL_dp func handle to residual function derivate # p [Mx1] the optimized parameter # err_final float the sum of the squared error at all gridpoints # success bool the return state of the nonlinear solver # ----------------------------------------------------------------- u, _ = motor_func(grid, approx_model, pStart) def L(pStart): # calculate u_ist u_ist, _ = motor_func(grid, approx_model, pStart) # initial loss loss = 0 # compute loss function for x in range(len(data)): lho = data[x - 1] - u_ist[x - 1] loss += 0.5 * np.linalg.norm(lho)**2 return loss def dL_dp(pStart): # calculate u_ist u_ist, _ = motor_func(grid, approx_model, pStart) # initial loss loss = 0 # compute loss function for x in range(len(data)): lho = data[x - 1] - u_ist[x - 1] loss += -lho return loss # use scipy to minimize results = mini(L, x0=pStart, method='SLSQP', tol=0.00001, options={'maxiter': 1000}) # results = mini(dL_dp, x0=pStart, method='SLSQP', tol=0.00001, options={'maxiter': 1000}) # record result p = results.x.reshape((-1, 1)) success = results.success err_final = L(p) return L, dL_dp, p, err_final, success
def lc_fit(fn, period, t0): ''' Function to fit a batman model to an input lc datafile to find the best fit system parameters ''' #Load time and flux data for the object DATA = np.loadtxt(fn) time, flux, err = DATA[:, 0], DATA[:, 3], DATA[:, 4] phase = ((time - t0)/period)%1 #Convert time values in to phases phase = np.array([p-1 if p > 0.8 else p for p in phase], dtype=float) p_fit = phase[phase < 0.2] #Crop phase and flux arrays to only contain values f_fit = flux[phase < 0.2] #in range (-0.2 , 0.2) e_fit = err[phase < 0.2] params = [0.05, 10., 90.] #Input parameters [rp, a, inc] for minimization bnds = Bounds(([0., 0., 60.]), ([1., 100., 90.])) #Parameter upper, lower bounds res = mini(lc_min, params, args=(p_fit, f_fit, e_fit), bounds=bnds) #perform minimization rp_best, a_best, inc_best = res.x[0], res.x[1], res.x[2] #Best fit parameters print('Best fit parameters: rp={:.4f}; a={:.4f}; inc={:.4f}'.format(rp_best, a_best, inc_best)) print('Minimization success: {}; chi2={:.4f}'.format(res.success, res.fun)) #Produce a best fit model using the minimization results pm_best = bm.TransitParams() pm_best.t0 = 0. #Time of transit centre pm_best.per = 1. #Orbital period = 1 as phase folded pm_best.rp = rp_best #Ratio of planet to stellar radius pm_best.a = a_best #Semi-major axis (units of stellar radius) pm_best.inc = inc_best #Orbital Inclination [deg] pm_best.ecc = 0. #Orbital eccentricity (fix circular orbits) pm_best.w = 90. #Longitude of periastron [deg] (unimportant as circular orbits) pm_best.u = [0.67, 0.3] #Stellar LD coefficients pm_best.limb_dark="quadratic" #LD model p_best = np.linspace(-0.1, 0.1, 10000) m_best = bm.TransitModel(pm_best, p_best) f_best = m_best.light_curve(pm_best) p1 = p_best[np.where(f_best < 1)[0][0]] #Phase of first contact p4 = p_best[np.where(f_best < 1)[0][-1]] #Phase of final contact t_dur = (p4 - p1) * period *24 #Transit duration [hours] t_depth = (1 - f_best.min()) * 100 #Transit depth [percent] #Produce binned data set for plotting bw = 10 / (1440*period) #Bin width - 10 mins in units of phase p_bin, f_bin, e_bin = lc_bin(p_fit, f_fit, bw) #Produce plot of data and best fit model LC plt.figure() plt.plot(p_fit, f_fit, marker='o', color='gray', linestyle='none', markersize=1) plt.plot(p_bin, f_bin, 'ro', markersize=3) plt.plot(p_best, f_best, 'g--') plt.xlabel('Phase') plt.ylabel('Flux') plt.title('Depth: {:.4f}%; Duration: {:4f} hours; (Rp/Rs): {:.4f}'.format(t_depth, t_dur, rp_best)) # plt.savefig("Plot save location") plt.show() return p_best, f_best, p_fit, f_fit, rp_best, a_best, inc_best, t_dur, t_depth
from scipy.optimize import minimize as mini import random def fun(x): s = 0 for i in range(0, len(x) - 1): #[0:2] s += 100 * (x[i + 1] - x[i])**2 + (1 - x[i]**2) return s bnds = ([(-30, 30)] * 3) #len(x)=3 res = mini(fun, [random.randint(-30, 30)] * 3, method='SLSQP', bounds=bnds) # Nelder-Mead,Powell,CG,BFGS,Newton-CG,Anneal,L-BFGS-B,TNC,COBYLA,SLSQP,dogleg,turst-ncg,custom -a callable object print(res.success) print(res.x) print(res.fun)
promedioDemanda = (s0 // tiempoTotal) x0 = np.random.rand(tiempoTotal) * promedioDemanda xPromedio = np.full(tiempoTotal, promedioDemanda) # Configuraciones para ejecutar algoritmo de optimización # Restricciones restricciones = [{'type': 'ineq', 'fun': restriccionInventario}] # Límites limiteInferior = 0 limiteSuperior = A / B limites = [(limiteInferior, limiteSuperior) for i in range(tiempoTotal)] # Ejecución de optimización soluciones = mini(ingreso, x0, method='SLSQP', bounds=limites, constraints=restricciones) ingresoTotal = -ingreso(soluciones.x) * factorEscala #%% IMPRESIÓN DE RESULTADOS # Arreglo de tiempo (N° Hora) print() print('Arreglo de Tiempo:') print(arregloTiempo) print() # Arreglo semilla de demanda: print('Arreglo Semilla de Demanda:') print(x0)