def findMin(self, x, y, numIters = 100): meanfunc = self.model.meanfunc covfunc = self.model.covfunc likfunc = self.model.likfunc inffunc = self.model.inffunc hypInArray = self._convert_to_array() try: opt = simplex(self._nlml, hypInArray, maxiter=numIters, disp=False, full_output=True) optimalHyp = deepcopy(opt[0]) funcValue = opt[1] warnFlag = opt[4] if warnFlag == 1: self.logger.warning("Maximum number of function evaluations made") elif warnFlag == 2: self.logger.warning("Maximum number of iterations exceeded.") except: self.errorCounter += 1 if not self.searchConfig: raise Exception("Can not learn hyperparamters using Nelder-Mead.") self.trailsCounter += 1 if self.searchConfig: searchRange = self.searchConfig.meanRange + self.searchConfig.covRange + self.searchConfig.likRange if not (self.searchConfig.num_restarts or self.searchConfig.min_threshold): raise Exception('Specify at least one of the stop conditions') while True: self.trailsCounter += 1 # increase counter for i in range(hypInArray.shape[0]): # random init of hyp hypInArray[i] = np.random.uniform(low=searchRange[i][0], high=searchRange[i][1]) # value this time is better than optiaml min value try: thisopt = simplex(self._nlml, hypInArray, maxiter=numIters, disp=False, full_output=True) if thisopt[1] < funcValue: funcValue = thisopt[1] optimalHyp = thisopt[0] except: self.errorCounter += 1 if self.searchConfig.num_restarts and self.errorCounter > old_div(self.searchConfig.num_restarts, 2): self.logger.warning("[Simplex] %d out of %d trails failed during optimization", self.errorCounter, self.trailsCounter) raise Exception("Over half of the trails failed for Nelder-Mead") if self.searchConfig.num_restarts and self.trailsCounter > self.searchConfig.num_restarts-1: # if exceed num_restarts self.logger.warning("[Simplex] %d out of %d trails failed during optimization", self.errorCounter, self.trailsCounter) return optimalHyp, funcValue if self.searchConfig.min_threshold and funcValue <= self.searchConfig.min_threshold: # reach provided mininal self.logger.warning("[Simplex] %d out of %d trails failed during optimization", self.errorCounter, self.trailsCounter) return optimalHyp, funcValue return optimalHyp, funcValue
def simplex_fit(x, y, fitFunction, p0=None, y_sigmas=None): """Optimizes fit parameters using assuming least-square using simplex algo. Returns array with fit parameters and the sum of the deviations squared (fit quality)""" yNominal = np.array(y) yError = [0.0001 for i in y] # assuming 1 if no stdDev is given if isinstance(y[0], uncertainties.UFloat): yNominal = [i.nominal_value for i in y] yError = [i.std_dev for i in y] if y_sigmas is not None: yError = y_sigmas fitParameterCount = len(inspect.getargspec(fitFunction).args) - 1 if p0 is None: p0 = [0 for i in range(fitParameterCount) ] # starting from 0 if no initial guess is given squareErrorForFitFunction = lambda params, xData, yData, error: squareError( fitFunction, fitParameterCount, params, xData, yData, error) fitParams = simplex(squareErrorForFitFunction, p0, args=(x, y, yError), disp=True, full_output=0, maxfun=1000000, maxiter=1000000) fitQual = fitQuality(x, y, lambda xIn: fitFunction(xIn, *fitParams)) return [fitParams, fitQual]
def orientate_octahedra(S0, O, x0, y0, z0, n1, n2, n3, n1p, n2p, n3p): xinit = [0, 0, 0, 0, 0, 0] opt = simplex(func2, xinit, args=(S0, O, x0, y0, z0, n1, n2, n3, n1p, n2p, n3p), full_output=0) return opt
def get_rotation_angles(Sub1, n1, n2, Sub2, n3, n4, R): x0 = [0, 0, 0, 0, 0, 0] opt = simplex(func, x0, args=(Sub1, n1, n2, Sub2, n3, n4, R), full_output=0) return opt
def turn_alkyl(xo, yo, zo, xab, yab, zab): xinit = [0, 0, 0] opt = simplex(func3, xinit, args=(xo, yo, zo, xab, yab, zab), full_output=0) return opt
def turn_methyl(ux, uy, uz, x0, y0, z0, xc, yc, zc, lcc): xinit = [0, 0, 0] opt = simplex(func4, xinit, args=(ux, uy, uz, x0, y0, z0, xc, yc, zc, lcc), full_output=0) return opt
def simplex(self): """ NUMERICAL RECIPES: https://www.google.com/url?q=https://drive.google.com/file/d/1K6tg_um1G-5X-5hdgwKb8vKyBD5oz4vX/view?usp%3Dsharing&sa=D&ust=1606856195190000&usg=AFQjCNH2Sc8A5HVZrZb72T-DrPM2-1kRtQ """ from scipy.optimize import fmin as simplex self.param = simplex(self.error, 5 * [5], xtol=1e-50, ftol=1e-50, maxfun=1e6) print(self.param) self.fit = lambda x: func(x, *self.param) self._measureGoodness()
def go_simplex(func,xdata,ydata,lb,ub,errors=None): params = -999. ; chi2n = -999. # Check that the degrees of freedom is larger than 1 dof = len(xdata)-len(lb) if (dof<=1): sys.exit('HOD_FIT.py: The degrees of freedom should be >1') # Get random initial values within the boundaries given p1 = random.rand(len(lb)) p1 = lb + p1*(ub-lb) params = simplex(f_chi2,p1,args=(xdata,ydata,errors,func),full_output=0) model = func(xdata,*params) chi2n = chi2(ydata,model,errors)/dof return params,chi2n
def optimize(x, y, fitFunction, p0=None): """Optimizes fit parameters using assuming least-square using simplex algo. Returns array with fit parameters and the sum of the deviations squared (fit quality)""" yNominal = np.array(y) yError = [0.0001 for i in y] # assuming 1 if no stdDev is given if isinstance(y[0], uncertainties.UFloat): yNominal = [i.nominal_value for i in y] yError = [i.std_dev for i in y] fitParameterCount = len(inspect.getargspec(fitFunction).args) - 1 if p0 is None: p0 = [0 for i in range(fitParameterCount)] # starting from 0 if no initial guess is given squareErrorForFitFunction = lambda params, xData, yData, error: squareError(fitFunction, fitParameterCount, params, xData, yData, error) fitParams = simplex(squareErrorForFitFunction, p0, args=(x, y, yError), disp=True, full_output=0, maxfun=1000000) fitQual = fitQuality(x, y, lambda xIn: fitFunction(xIn, *fitParams)) return [fitParams, fitQual]
def scatter(residuals_np, s_peculiar_vel_np, s_appmagTBmax_np, InitialGuess=0.15): """ Function to compute the intrinsic scatter from the Hubble residuals by minimizing the -2*log(Likelihood) function in Eq. (6) of Blondin et al 2011. :param residuals_np : numpy array of Hubble residuals. :type residuals_np : ndarray. :param s_peculiar_vel_np : numpy array of peculiar-velocity uncertainties. :type s_peculiar_vel_np : ndarray. :param s_appmagTBmax_np : numpy array of apparent magnitude at t_Bmax uncertainties. :type s_appmagTBmax_np : ndarray. :param InitialGuess : Initial guess about the value of the intrinsic scatter. Default value = 0.15. :type InitialGuess : float. """ int_scatter = simplex(neg2lnLikelihood, InitialGuess, args=(residuals_np, s_peculiar_vel_np, s_appmagTBmax_np)) return int_scatter[0]
def scale_sky(sky_spec, sci_spec): """ Fit the 1D sky spectrum to the 1D science spectrum allowing different families of OH lines to be scaled differently and the continuum to be scaled separately. This module is code hijacked from the OSIRIS data redcution pipeline. """ sky, sky_hdr = pyfits.getdata(sky_spec, header=True) sci, sci_hdr = pyfits.getdata(sci_spec, header=True) # Make a wavelength array for the sky object. sky_lambda = np.arange(len(sky), dtype=float) sky_lambda -= sky_hdr['CRPIX1'] - 1 sky_lambda *= sky_hdr['CRDELT1'] sky_lambda += sky_hdr['CRVAL1'] # Full width in pixels of unresolved emission line line_half_width = 2 npixw = 2 * line_half_width # Median filter the sky to get an estimate of the continuum. # Remove this continuum. backgnd = filters.median(sky, size=10 * line_half_width, mode='nearest') sky2 = sky - backgnd for ii in range(len(l_boundary) - 1): lr = np.where((sky_lambda >= l_boundary[ii]) & (sky_lambda < l_boundary[ii + 1]))[0] if len(lr) == 0: continue sky_lr = sky[lr] sky2_lr = sky2[lr] sci_lr = sci[lr] lam_lr = sky_lamda[lr] sky_median = np.median(sky2_lr) sky_stddev = np.std(sky2) w_skylines = np.where(sky2_lr > (10 * sky_median) + sky_stddev)[0] if len(w_skylines) > 0: # Make a mask for where line regions are and for where the # continuum is. line_mask = np.zeros(len(lr), dtype=float) line_mask[w_skylines] = 10.0 # Convolve the mask with a "resolution-width" window. window = np.ones(npixw) line_mask = np.convolve(line_mask, window, mode='same') line_regions = line_mask > 0 line_count = line_regions.sum() if (line_count >= 3) and ((len(line_regions) - line_count) >= 3): # Remove the continuum from the science and object f_sci = interp1d(lam_lr[~line_regions], sci_lr[~line_regions]) f_obj = inpterp1d(lam_lr[~line_regions], sky2[~line_regions]) sci_no_cont = sci_lr[line_regions] - f_sci([lam_lr]) out = simplex(fit_sky, init, args=(sci, sky))
def scale_sky(sky_spec, sci_spec): """ Fit the 1D sky spectrum to the 1D science spectrum allowing different families of OH lines to be scaled differently and the continuum to be scaled separately. This module is code hijacked from the OSIRIS data redcution pipeline. """ sky, sky_hdr = pyfits.getdata(sky_spec, header=True) sci, sci_hdr = pyfits.getdata(sci_spec, header=True) # Make a wavelength array for the sky object. sky_lambda = np.arange(len(sky), dtype=float) sky_lambda -= sky_hdr['CRPIX1'] - 1 sky_lambda *= sky_hdr['CRDELT1'] sky_lambda += sky_hdr['CRVAL1'] # Full width in pixels of unresolved emission line line_half_width = 2 npixw = 2 * line_half_width # Median filter the sky to get an estimate of the continuum. # Remove this continuum. backgnd = filters.median(sky, size=10*line_half_width, mode='nearest') sky2 = sky - backgnd for ii in range(len(l_boundary)-1): lr = np.where((sky_lambda >= l_boundary[ii]) & (sky_lambda < l_boundary[ii+1]))[0] if len(lr) == 0: continue sky_lr = sky[lr] sky2_lr = sky2[lr] sci_lr = sci[lr] lam_lr = sky_lamda[lr] sky_median = np.median(sky2_lr) sky_stddev = np.std(sky2) w_skylines = np.where(sky2_lr > (10 * sky_median) + sky_stddev)[0] if len(w_skylines) > 0: # Make a mask for where line regions are and for where the # continuum is. line_mask = np.zeros(len(lr), dtype=float) line_mask[w_skylines] = 10.0 # Convolve the mask with a "resolution-width" window. window = np.ones(npixw) line_mask = np.convolve(line_mask, window, mode='same') line_regions = line_mask > 0 line_count = line_regions.sum() if (line_count >= 3) and ((len(line_regions) - line_count) >= 3): # Remove the continuum from the science and object f_sci = interp1d(lam_lr[~line_regions], sci_lr[~line_regions]) f_obj = inpterp1d(lam_lr[~line_regions], sky2[~line_regions]) sci_no_cont = sci_lr[line_regions] - f_sci([lam_lr]) out = simplex(fit_sky, init, args=(sci, sky))
print fof(56.9) plt.tight_layout() #plt.savefig('atlas5.png', dpi=200) plt.show() if 1: C3 = 19.79 #km2s2 DEC = 56.917 # deg lus = ext_LUS('mb') lus.set_boiloff(0.002) lus.set_time(4) lus.compute_stack_mass() lus.hit_from_incl(fof(DEC)) #lus.print_info() pl = simplex(c3, 37000, args=(lus, C3))[0] print "2x MB-60 ext-LUS:", round(pl, -2) lus2 = ext_LUS('rl') lus2.set_boiloff(0.002) lus2.set_time(4) lus2.compute_stack_mass() lus2.hit_from_incl(fof(DEC)) #lus.print_info() pl = simplex(c3, 37000, args=(lus2, C3))[0] print "2x RL-10 ext-LUS:", round(pl, -2)
def all_the_rest(lus, offset, loiter, save = 0): lus.set_launch_date(offset) lus.set_time(offset+loiter) lus.print_info() print "Launching numerical simualtion..." C3_target = allc3req[offset+loiter] ext_LUS_payload = simplex(c3, 27000, args=(lus, C3_target))[0] print " Payload: {0} kg @ [{1}off, {2}loi] ".format(round(ext_LUS_payload,2), offset, loiter) # Get parking orbit parameters __, __, pery, apo, transorb_period, br_time_1, br_time_2 = c3(ext_LUS_payload, lus, target_C3 = C3_target, rich_return = 1) # Plot generation print "\nDeploying C3@{0}% boiloff rate chart...".format(100*lus.Boiloff) # C3 plot data generation. allc3 = [] newt = [] for day in range(loiter+1): lus.set_time(offset+day) allc3.append(c3(ext_LUS_payload, lus)) newt.append(day+offset) # Chart name. name = "C3 @ [{0}%/d boiloff rate, {1}-day loiter time]".format(lus.Boiloff*100, loiter) # ext_LUS C3 curve annotation text at start. anno2_text = r"$Diff:\ {0} \ km^{{2}}s^{{-2}}$".format(round(allc3[0]-allc3req[offset], 2)) # ext_LUS C3 curve annotation text at end. anno3_text = r"$Diff:\ {0} \ km^{{2}}s^{{-2}}$".format(round(allc3[loiter]-allc3req[offset+loiter], 2)) # Additional information. anno4_text = ("Payload: {0} kg \n".format(round(ext_LUS_payload,-2)) +"Engines: {0}\n".format(lus.Engines) +"Initial T/W: {0}\n".format(round(lus.Thrust/lus.Stack_mass, 3)) +"Burns: {0} s + {1} s\n".format(round(br_time_1,2), round(br_time_2,2)) +"Parking orbit: {0} x {1} km\n".format(round(pery/1000,1), round(apo/1000,1)) +"Orbital period: {0} hour".format(round(transorb_period,2)) ) # Name of chart file. filename = ("C3-{0}-[{1}, {2}]-".format(lus.Boiloff, offset, loiter) +"{0}kg-{1}-{1}kg_add".format(round(ext_LUS_payload,2), lus.Engines, lus.Stage_additions) ) # Creating plot. plt.figure(figsize=(7.5, 4.5), dpi=180) # (11, 8) 80dpi dla full, (7.5, 4.5) 180dpi dla small # Plot ext_LUS C3 plt.plot([swp_time(i) for i in newt], allc3, label="Instantaneous C3") # Plot required C3 plt.plot([swp_time(i) for i in alltc3req], allc3req, label='Required C3') # Plot reentry speed barrier line plt.plot([swp_time(20)]*2, [38, 44], color='red', linewidth=1.5, linestyle="--") # Annotate reentry speed barrier line plt.annotate(r'Capsule Ventry barrier', xy=(swp_time(20), 43.2), xycoords='data', xytext=(-150, +20), textcoords='offset points', fontsize=12, bbox=dict(facecolor='white', edgecolor='None', alpha=0.65), arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2") ) # Annotate ext_LUS C3 curve at start plt.annotate(anno2_text, xy=(swp_time(newt[0]), allc3[0]), xycoords='data', xytext=(swp_time(8.5), 41.5), textcoords='data', fontsize=12, bbox=dict(facecolor='white', edgecolor='None', alpha=0.65), arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.1") ) # Annotate ext_LUS C3 curve at end plt.annotate(anno3_text, xy=(swp_time(newt[loiter]), allc3[loiter] ), xycoords='data', xytext=(swp_time(15), 41.0), textcoords='data', fontsize=12, bbox=dict(facecolor='white', edgecolor='None', alpha=0.65), arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.1") ) # Put additional information in place plt.text(swp_time(0.6), 38.2, anno4_text, style='italic', fontsize=10, bbox={'facecolor':'white', 'alpha':0.5, 'pad':10} ) # Add labels, tittle, legend #plt.xlabel('Date') plt.ylabel('C3 [$km^2s^{-2}$]') #plt.title(name) plt.legend(loc='upper left', prop={'size':12}) # Axis and grid modyfications rc('xtick', labelsize=8) plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) plt.gca().xaxis.set_major_locator(mdates.AutoDateLocator(minticks=6, maxticks=10)) plt.gca().xaxis.set_minor_locator(mdates.DayLocator()) plt.gcf().autofmt_xdate() plt.gca().yaxis.set_major_locator(plt.MultipleLocator(1.0)) #plt.gca().yaxis.set_minor_locator(plt.MultipleLocator(0.1) plt.gca().xaxis.grid(True,'minor') #plt.gca().yaxis.grid(True,'minor') plt.gca().xaxis.grid(True,'major', linewidth=1) plt.gca().yaxis.grid(True,'major', linewidth=1) plt.tight_layout() if save: plt.savefig(filename+'.png', dpi=200) plt.show()
return numpy.exp(-residual*residual/2.0) # Create data. X = [] Y = [] for x in range(-5, 6, 1): X.append(x) Y.append(math.exp(-x*x/2.0)) # Add Gaussian noise to data. Y = Y + numpy.random.normal(0.0, 0.1, len(Y)) import scipy.optimize as optimization guess = [1.0, 2.0] print optimization.curve_fit(func4curve_fit, X, Y, guess) def func4Simplex(params, X, Y): mu = params[0] sigma = params[1] chi2 = 0.0 for n in range(len(X)): residual = Y[n] - func4curve_fit(X[n], mu, sigma) chi2 = chi2 + residual*residual return chi2 from scipy.optimize import fmin as simplex print simplex(func4Simplex, guess, args=(X, Y))
def __call__(self, indiv): from numpy import arange, average, arrays, zeros from scipy.optimize import fmin as simplex # from scipy.optimize import fmin_powell as simplex from ...ce import leave_many_out, leave_one_out assert len(self._mlclasses) - self._fixed == len(indiv.genes),\ "Individual is of incorrect size.\n" self.nfun = 0 def callable_loo(x): from math import sqrt, log as ln, fabs, exp if self.nfun > EvalFitPairs.max_nfuncs: raise StopIteration if fabs(x[0]) > EvalFitPairs.max_pow: raise ValueError if fabs(x[1]) > EvalFitPairs.max_pow: raise ValueError self.nfun += 1 self.fitter.alpha = x[0] self.fitter.tcoef = 100*exp(x[1]) errors = leave_one_out(self.fitter) npreds, nstr = errors.shape prediction = errors[ arange(errors.shape[0]), arange(errors.shape[0]) ] return sqrt(average(prediction*prediction)) def callable_lmo(x): from math import sqrt, log as ln, fabs, exp if self.nfun > EvalFitPairs.max_nfuncs: raise StopIteration if fabs(x[0]) > EvalFitPairs.max_pow: raise ValueError if fabs(x[1]) > EvalFitPairs.max_pow: raise ValueError self.nfun += 1 self.fitter.alpha = x[0] self.fitter.tcoef = 100*exp(x[1]) errors = leave_many_out(self.fitter, self._sets) npred, prediction = 0, 0e0 for i in xrange(errors.shape[0]): for j in xrange(errors.shape[1]): if j not in self._sets[i]: continue prediction += errors[i,j] * errors[i,j] npred += 1 return sqrt(prediction / float(npred)) which_callable = callable_lmo if len(self._sets) == 0: which_callable = callable_loo # creates pair values. pairs = [ self.pairs[0] ] while pairs[-1] < self.pairs[1]: pairs.append( pairs[-1] + self.pairs[2] ) if pairs[-1] != self.pairs[1]: pairs.append( self.pairs[1] ) x0 = array([1.1,1.0]) minvals = None for p in pairs: onoffs = zeros((len(self._mlclasses),), dtype=bool) for i, index in enumerate(self._pairindex[:-1]): nbpairs = min(i+p, self._pairindex[index+1]) onoffs[i:nbpairs] = True onoffs[self._pairindex[-1]:self._fixed] = True onoffs[self._fixed:] = indiv.genes self.fitter.extinguish_cluster(onoffs, mask=True) # x0, fopt, dummy, dummy, dummy, dummy = \ fopt, iter, = 0,0 try: x0, fopt, iter, dummy, dummy = \ simplex(which_callable, x0, ftol=0.1, xtol=0.1, full_output=True, disp=False, maxfun=20, maxiter=20) except StopIteration: fopt = 1e12; x0 = array([1.1,1.0]) except ValueError: fopt = 1e12; x0 = array([1.1,1.0]) if minvals is None or minvals[0] > fopt: minvals = (fopt, iter) return minvals[0]
# Define the objective function to be minimised by Simplex. # params ... array holding the values of the fit parameters. # X ... array holding x-positions of observed data. # Y ... array holding y-values of observed data. # Err ... array holding errors of observed data. def func(params, X, Y, Err): # extract current values of fit parameters from input array a = params[0] b = params[1] c = params[2] # compute chi-square chi2 = 0.0 for n in range(len(X)): x = X[n] # The function y(x)=a+b*x+c*x^2 is a polynomial # in this example. y = a + b*x + c*x*x chi2 = chi2 + (Y[n] - y)*(Y[n] - y)/(Err[n]*Err[n]) return chi2 xdata = [0.0,1.0,2.0,3.0,4.0,5.0] ydata = [0.1,0.9,2.2,2.8,3.9,5.1] sigma = [1.0,1.0,1.0,1.0,1.0,1.0] #Initial guess. x0 = [0.0, 0.0, 0.0] # Apply downhill Simplex algorithm. print simplex(func, x0, args=(xdata, ydata, sigma), full_output=0)
def solve_branch_cut(weights, values, max_w): values = np.asarray(values) best_solution = None best_value = -np.inf subproblems = deque([(np.asarray(weights).reshape(1, 3), np.asarray(max_w).reshape(1, 1))]) nodes_opened = 0 while subproblems: A_parent, b_parent = subproblems.popleft() nodes_opened += 1 # if nodes_opened % 5 == 0: # print(nodes_opened) # Solve relaxed subproblem res = simplex(-values, A_parent, b_parent) if not res.success: if res.status == 1: print("Iteration limit reached... mby cycles?") elif res.status == 2: continue # Infeasible subproblem else: print( "Subproblem appears to be unbounded... mby bad initial problem?" ) # Filter relaxed solution for zeros res.x[np.isclose(res.x, 0)] = 0 # Check if subspace's relaxed optimal value is above current best value if -res.fun <= best_value: continue # skip branching on this subproblem # Find basic fractional elements fracts = [] for i in range(len(res.x)): if not res.x[i].is_integer(): fracts.append(i) # Check if solution is in integer space if not fracts: best_solution = res.x.astype('int') best_value = int(-res.fun) continue # Select a fractional element to branch from branch_i = fracts[0] # Create new constrains down = np.floor(res.x[branch_i]) constrain_1 = np.zeros((1, len(values))) constrain_1[0, branch_i] = 1 A_child_1 = np.concatenate([A_parent, constrain_1]) b_child_1 = np.concatenate([b_parent, np.array([[down]])]) subproblems.append((A_child_1, b_child_1)) up = np.ceil(res.x[branch_i]) constrain_2 = np.zeros((1, len(values))) constrain_2[0, branch_i] = -1 A_child_2 = np.concatenate([A_parent, constrain_2]) b_child_2 = np.concatenate([b_parent, np.array([[-up]])]) subproblems.append((A_child_2, b_child_2)) return best_solution, best_value, nodes_opened
def read_atom_locations(path, file, n0, n1, n2, n3, n4, n5, ax, f1): x, y, z = [], [], [] xi, yi, zi = [], [], [] label = [] f = open(path + file, "r") data = f.readlines() for line in data: words = line.split() label.append(words[0]) xi.append(words[1]) yi.append(words[2]) zi.append(words[3]) f.close() xmi, ymi, zmi = [], [], [] xm, ym, zm = [], [], [] labelm = [] f = open(path + "methyl.xyz", "r") data = f.readlines() for line in data: words = line.split() labelm.append(words[0]) xmi.append(words[1]) ymi.append(words[2]) zmi.append(words[3]) f.close() S0 = define_central_octa(xi, yi, zi, n0, n1, n2, n3, n4, n5) #Rotate into conveniant orientation : (at_3-at_4 axis) = (001) ux = float(S0[3][0]) - float(S0[4][0]) uy = float(S0[3][1]) - float(S0[4][1]) uz = float(S0[3][2]) - float(S0[4][2]) norm = np.sqrt(ux * ux + uy * uy + uz * uz) ux = ux / norm uy = uy / norm uz = uz / norm G = barycenter(S0) xinit = [0, 0, 0] opt = simplex(func3, xinit, args=(0, 0, 1, ux, uy, uz), full_output=0) # Rotate & move the atoms of the residu without any terminating CH3 fragments for i in range(len(xi)): vect1 = [[float(xi[i]) - float(G[0])], [float(yi[i]) - float(G[1])], [float(zi[i]) - float(G[2])]] vect2 = move3(opt[0], opt[1], opt[2], vect1) x.append(vect2[0]) y.append(vect2[1]) z.append(vect2[2]) for i in range(54): ax.scatter(float(x[i]), float(y[i]), float(z[i]), c='blue', s=30) f = open("./" + "monomer_0.xyz", "w") for i in range(len(x)): line = label[i] + " " + str(float(x[i])) + " " + str(float( y[i])) + " " + str(float(z[i])) + "\n" f1.write(line) f.write(line) f.close() # Operate the same displacement for the terminating CH3 fragments for i in range(len(xmi)): vect1 = [[float(xmi[i]) - float(G[0])], [float(ymi[i]) - float(G[1])], [float(zmi[i]) - float(G[2])]] vect2 = move3(opt[0], opt[1], opt[2], vect1) xm.append(vect2[0]) ym.append(vect2[1]) zm.append(vect2[2]) # Do the same for the central octahedra S = [] S = define_central_octa(x, y, z, n0, n1, n2, n3, n4, n5) return S, label, x, y, z, labelm, xm, ym, zm
def pload(C3_target, lus = lusrl): return simplex(c3, 27000, args=(lus, C3_target))[0]
def findMin(self, x, y, numIters=100): meanfunc = self.model.meanfunc covfunc = self.model.covfunc likfunc = self.model.likfunc inffunc = self.model.inffunc hypInArray = self._convert_to_array() try: opt = simplex(self._nlml, hypInArray, maxiter=numIters, disp=False, full_output=True) optimalHyp = deepcopy(opt[0]) funcValue = opt[1] warnFlag = opt[4] if warnFlag == 1: self.logger.warning( "Maximum number of function evaluations made") elif warnFlag == 2: self.logger.warning("Maximum number of iterations exceeded.") except: self.errorCounter += 1 if not self.searchConfig: raise Exception( "Can not learn hyperparamters using Nelder-Mead.") self.trailsCounter += 1 if self.searchConfig: searchRange = self.searchConfig.meanRange + self.searchConfig.covRange + self.searchConfig.likRange if not (self.searchConfig.num_restarts or self.searchConfig.min_threshold): raise Exception('Specify at least one of the stop conditions') while True: self.trailsCounter += 1 # increase counter for i in range(hypInArray.shape[0]): # random init of hyp hypInArray[i] = np.random.uniform(low=searchRange[i][0], high=searchRange[i][1]) # value this time is better than optiaml min value try: thisopt = simplex(self._nlml, hypInArray, maxiter=numIters, disp=False, full_output=True) if thisopt[1] < funcValue: funcValue = thisopt[1] optimalHyp = thisopt[0] except: self.errorCounter += 1 if self.searchConfig.num_restarts and self.errorCounter > old_div( self.searchConfig.num_restarts, 2): self.logger.warning( "[Simplex] %d out of %d trails failed during optimization", self.errorCounter, self.trailsCounter) raise Exception( "Over half of the trails failed for Nelder-Mead") if self.searchConfig.num_restarts and self.trailsCounter > self.searchConfig.num_restarts - 1: # if exceed num_restarts self.logger.warning( "[Simplex] %d out of %d trails failed during optimization", self.errorCounter, self.trailsCounter) return optimalHyp, funcValue if self.searchConfig.min_threshold and funcValue <= self.searchConfig.min_threshold: # reach provided mininal self.logger.warning( "[Simplex] %d out of %d trails failed during optimization", self.errorCounter, self.trailsCounter) return optimalHyp, funcValue return optimalHyp, funcValue
from scipy.optimize import fmin as simplex def func(params, X, Y): # extract current values of fit parameters from input array a = params[0] b = params[1] c = params[2] # compute chi-square chi2 = 0.0 for n in range(len(X)): x = X[n] # The function y(x) is a polynomial in this example. y = a + b*x + c*x*x chi2 = chi2 + (Y[n] - y)*(Y[n] - y) return chi2 xdata = [0.0,1.0,2.0,3.0,4.0,5.0] ydata = [0.1,0.9,2.2,2.8,3.9,5.1] sigma = [1.0,1.0,1.0,1.0,1.0,1.0] #Initial guess. x0 = [0.0, 0.0, 0.0] # Apply downhill Simplex algorithm. print simplex(func, x0, args=(xdata, ydata), xtol=0.0001, ftol=0.0001, maxiter=None, full_output=0)
####################################################################### # Branch & Cut Solution # ####################################################################### best_solution = None opt_value = -np.inf subproblems = deque([(A, b)]) nodes_opened = 0 while subproblems: A_parent, b_parent = subproblems.popleft() nodes_opened += 1 # Solve relaxed subproblem res = simplex(-profit, A_parent, b_parent) if not res.success: if res.status == 1: print("Iteration limit reached... mby cycles?") elif res.status == 2: continue # Infeasible subproblem else: print("Subproblem appears to be unbounded... mby bad initial problem?") # Filter relaxed solution for zeros res.x[np.isclose(res.x, 0)] = 0 # Check if subspace's relaxed optimal value is above current best value if -res.fun <= opt_value: continue # skip branching on this subproblem # Find basic fractional elements