def analyzeData(self,gd): """ Analysis of the BasicGraphData() instance with data. Returns the error value. """ if(gd.getNumbOfPoints() == 0): return 0. y_max = gd.getMaxY() y_min = gd.getMinY() amp0 = (y_max - y_min)/2.0 amp_step = 0.05*amp0 phase_step = 3.0 self.param_arr[0] = (y_max + y_min)/2.0 for i_h in range(self.n_harm+1): param_local_arr = self.param_arr[0:2*i_h+1] #print "debug i_h=",i_h," =====start ==== param_arr=",param_local_arr variables = ArrayList() delta_hint = InitialDelta() var = Variable("base",param_local_arr[0], - Double.MAX_VALUE, Double.MAX_VALUE) variables.add(var) delta_hint.addInitialDelta(var,amp_step) for i_fit in range(i_h): var = Variable("amp"+str(i_fit),param_local_arr[2*i_fit+1], - Double.MAX_VALUE, Double.MAX_VALUE) variables.add(var) delta_hint.addInitialDelta(var,amp_step) var = Variable("phase"+str(i_fit),param_local_arr[2*i_fit+2], - Double.MAX_VALUE, Double.MAX_VALUE) variables.add(var) delta_hint.addInitialDelta(var,phase_step) scorer = HarmScorer(gd,variables) self.harm_func = scorer.getHarmFunc() if(i_h == 0): scorer.copyFromExternalParams(self.param_arr) (amp,shift) = scorer.getNextHarm_Amp_Shift() #print "debug zero harm (amp,shift)=",(amp,shift) self.param_arr[2*i_h+1] = amp self.param_arr[2*i_h+2] = shift #print "debug i_h=",i_h," =====final ==== param_arr=", self.param_arr continue maxSolutionStopper = SolveStopperFactory.maxEvaluationsStopper((i_h+1)*self.n_iter) solver = Solver(SimplexSearchAlgorithm(),maxSolutionStopper) problem = ProblemFactory.getInverseSquareMinimizerProblem(variables,scorer,0.0001) problem.addHint(delta_hint) solver.solve(problem) #------- get results trial = solver.getScoreBoard().getBestSolution() err2 = scorer.score(trial,variables) scorer.copyToExternalParams(self.param_arr) #print "debug i_h=",i_h," =====final err2=",math.sqrt(err2),"==== param_arr=", self.param_arr if(i_h != self.n_harm): (amp,shift) = scorer.getNextHarm_Amp_Shift() #print "debug last step (amp,shift)=",(amp,shift) self.param_arr[2*i_h+1] = amp self.param_arr[2*i_h+2] = shift #print "debug i_h=",i_h," ===== last step==== param_arr=", self.param_arr return math.sqrt(err2)
def fit(self): if(self.active_cav_wrapper == null): return variables = ArrayList() delta_hint = InitialDelta() #----- variable eKin_in var = Variable("eKin_in",self.eKin_in, - Double.MAX_VALUE, Double.MAX_VALUE) variables.add(var) delta_hint.addInitialDelta(var,0.3) #----- variable cavity amplitude var = Variable("cav_amp",self.cav_amp, - Double.MAX_VALUE, Double.MAX_VALUE) variables.add(var) delta_hint.addInitialDelta(var,self.cav_amp*0.01) #----- variable cavity phase offset var = Variable("phase_offset",self.cav_phase_shift, - Double.MAX_VALUE, Double.MAX_VALUE) variables.add(var) delta_hint.addInitialDelta(var,1.0) #-------- solve the fitting problem scorer = CavAmpPhaseScorer(self,variables) maxSolutionStopper = SolveStopperFactory.maxEvaluationsStopper(120) self.solver = Solver(SimplexSearchAlgorithm(),maxSolutionStopper) problem = ProblemFactory.getInverseSquareMinimizerProblem(variables,scorer,0.0001) problem.addHint(delta_hint) self.solver.solve(problem) #------- get results trial = self.solver.getScoreBoard().getBestSolution() err2 = scorer.score(trial,variables) [self.eKin_in,self.cav_amp,self.cav_phase_shift] = scorer .getTrialParams(trial) self.active_cav_wrapper.eKin_in = self.eKin_in self.active_cav_wrapper.designPhase = makePhaseNear(self.active_cav_wrapper.livePhase - self.cav_phase_shift,0.) self.active_cav_wrapper.eKin_err = math.sqrt(err2) cav_phase = self.active_cav_wrapper.livePhase self.active_cav_wrapper.eKin_out = self.getModelEnergyOut(self.eKin_in,self.cav_amp,cav_phase,self.cav_phase_shift) #print "debug cav=",self.active_cav_wrapper.alias," shift=",self.cav_phase_shift," amp=",self.cav_amp," err2=", math.sqrt(err2)," ekinOut=", self.active_cav_wrapper.eKin_out #----- this defenition of the avg. gap phase will be replaced by another with self.model_eKin_in self.active_cav_wrapper.avg_gap_phase = self.getAvgGapPhase() self.active_cav_wrapper.designAmp = self.cav_amp self.solver = null #----make theory graph plot x_arr = [] y_arr = [] for i in range(self.scan_gd.getNumbOfPoints()): phase = self.scan_gd.getX(i) y = self.scan_gd.getY(i) x_arr.append(phase) y_arr.append(y) self.active_cav_wrapper.eKinOutPlotTh.addPoint(x_arr,y_arr)
diff2) return diff2 def getDCH_Field_Arr_for_Trial(self, trial): #------ return dch field array for the trial point field_arr = [] for dch_ind in range(self.variables.size()): var = self.variables.get(dch_ind) field = trial.getTrialPoint().getValue(var) field_arr.append(field) return field_arr #---- Initial step in parameters. During optimization #---- these steps will be reduced inside the optimizer. delta_hint = InitialDelta() #---- optimizing variabes variables = ArrayList() field_max = 0.012 field_min = -0.012 field_step = (field_max - field_min) / 30 for dch_ind in range(len(dchs)): dch = dchs[dch_ind] field = dch.getField() var = Variable(dch.getId(), field, field_min, field_max) variables.add(var) delta_hint.addInitialDelta(var, field_step)
def run(self): tr_twiss_analysis_controller = self.linac_wizard_document.tr_twiss_analysis_controller transverse_twiss_fitting_controller = tr_twiss_analysis_controller.transverse_twiss_fitting_controller init_and_fit_params_controller = transverse_twiss_fitting_controller.init_and_fit_params_controller initial_twiss_params_holder = transverse_twiss_fitting_controller.initial_twiss_params_holder final_twiss_params_holder = init_and_fit_params_controller.final_twiss_params_holder nIterations = int(init_and_fit_params_controller.fit_iter_text.getValue()) #print "debug Twiss_Fitter start to run! Iter=",nIterations (alphaX, betaX, emittX) = initial_twiss_params_holder.getParams(0) (alphaY, betaY, emittY) = initial_twiss_params_holder.getParams(1) (alphaZ, betaZ, emittZ) = initial_twiss_params_holder.getParams(2) twiss_arr = [] twiss_arr.append(Twiss(alphaX, betaX, emittX)) twiss_arr.append(Twiss(alphaY, betaY, emittY)) twiss_arr.append(Twiss(alphaZ, betaZ, emittZ)) (alphaXStep, betaXStep, emittXStep) = initial_twiss_params_holder.getParamsStep(0) (alphaYStep, betaYStep, emittYStep) = initial_twiss_params_holder.getParamsStep(1) (alphaZStep, betaZStep, emittZStep) = initial_twiss_params_holder.getParamsStep(2) variables = ArrayList() variables.add(Variable("alphaX", alphaX, - Double.MAX_VALUE, Double.MAX_VALUE)) variables.add(Variable("betaX", betaX, - Double.MAX_VALUE, Double.MAX_VALUE)) variables.add(Variable("emittX", emittX, - Double.MAX_VALUE, Double.MAX_VALUE)) variables.add(Variable("alphaY", alphaY, - Double.MAX_VALUE, Double.MAX_VALUE)) variables.add(Variable("betaY", betaY, - Double.MAX_VALUE, Double.MAX_VALUE)) variables.add(Variable("emittY", emittY, - Double.MAX_VALUE, Double.MAX_VALUE)) variables.add(Variable("alphaZ", alphaZ, - Double.MAX_VALUE, Double.MAX_VALUE)) variables.add(Variable("betaZ", betaZ, - Double.MAX_VALUE, Double.MAX_VALUE)) variables.add(Variable("emittZ", emittZ, - Double.MAX_VALUE, Double.MAX_VALUE)) delta_hint = InitialDelta() variables_fit = ArrayList() #---------- X if(alphaXStep != 0.): variables_fit.add(variables.get(0)) delta_hint.addInitialDelta(variables.get(0), alphaXStep) if(betaXStep != 0.): variables_fit.add(variables.get(1)) delta_hint.addInitialDelta(variables.get(1), betaXStep) if(emittXStep != 0.): variables_fit.add(variables.get(2)) delta_hint.addInitialDelta(variables.get(2), emittXStep) #---------- Y if(alphaYStep != 0.): variables_fit.add(variables.get(3)) delta_hint.addInitialDelta(variables.get(3), alphaYStep) if(betaYStep != 0.): variables_fit.add(variables.get(4)) delta_hint.addInitialDelta(variables.get(4), betaYStep) if(emittYStep != 0.): variables_fit.add(variables.get(5)) delta_hint.addInitialDelta(variables.get(5), emittYStep) #---------- Z if(alphaZStep != 0.): variables_fit.add(variables.get(6)) delta_hint.addInitialDelta(variables.get(6), alphaZStep) if(betaZStep != 0.): variables_fit.add(variables.get(7)) delta_hint.addInitialDelta(variables.get(7), betaZStep) if(emittZStep != 0.): variables_fit.add(variables.get(8)) delta_hint.addInitialDelta(variables.get(8), emittZStep) #------- fitting process with solver if(variables_fit.isEmpty()): return scorer = AccScoreCalculator(self.linac_wizard_document,variables,twiss_arr) maxSolutionStopper = SolveStopperFactory.maxEvaluationsStopper(nIterations) solver = Solver(SimplexSearchAlgorithm(),maxSolutionStopper) self.solver = solver problem = ProblemFactory.getInverseSquareMinimizerProblem(variables_fit,scorer,0.001) problem.addHint(delta_hint) solver.solve(problem) #------- get results trial = solver.getScoreBoard().getBestSolution() scorer.trialToTwiss(trial) twiss_arr = scorer.getTwissArr() (alphaX, betaX, emittX) = (twiss_arr[0].getAlpha(),twiss_arr[0].getBeta(),twiss_arr[0].getEmittance()) (alphaY, betaY, emittY) = (twiss_arr[1].getAlpha(),twiss_arr[1].getBeta(),twiss_arr[1].getEmittance()) (alphaZ, betaZ, emittZ) = (twiss_arr[2].getAlpha(),twiss_arr[2].getBeta(),twiss_arr[2].getEmittance()) final_twiss_params_holder.setParams(0,alphaX, betaX, emittX) final_twiss_params_holder.setParams(1,alphaY, betaY, emittY) final_twiss_params_holder.setParams(2,alphaZ, betaZ, emittZ) init_and_fit_params_controller.finalTwiss_table.getModel().fireTableDataChanged() init_and_fit_params_controller.fit_iter_left_text.setValue(0.) scorer.setUpLastNode(false) scorer.calculateDiff2()
self.count = 0 def score(self,trial,variables): self.count += 1 var = self.variables.get(0) x = trial.getTrialPoint().getValue(var) return self.func(x) def fun_to_opt(x): return (x-3)*(x-3)+1 variables = ArrayList() xvar = Variable( "x", 0.0, -25.0, 25.0 ) variables.add(xvar) scorer = MyScorer(variables,fun_to_opt) n_iterations = 50 maxSolutionStopper = SolveStopperFactory.maxEvaluationsStopper(n_iterations) # solver = Solver(SimplexSearchAlgorithm(),maxSolutionStopper) solver = Solver(RandomSearch(),maxSolutionStopper) problem = ProblemFactory.getInverseSquareMinimizerProblem(variables,scorer,0.00001) delta_hint = InitialDelta() problem.addHint(delta_hint) solver.solve(problem) trial = solver.getScoreBoard().getBestSolution() result = trial.getTrialPoint().getValue(xvar) print 'Result is', result
def actionPerformed(self,e): if(plotActionListener.getAccCalc() == None): textArea.setText("Can not do anything! Calculate the existing orbit first!") return accCalc = plotActionListener.getAccCalc() #accCalc.track1() # Flatten the horizontal orbit problem = Problem() objective = MinimizingObjective( 0.05 ) problem.addObjective( objective ) hint = InitialDelta() problem.addHint( hint ) orbCorrH = OrbitCorr( accCalc,accNodeForCorr,dcorrsH,"DCH", problem, hint ) evaluator = ScoringEvaluator( orbCorrH, problem.getVariables(), objective ) problem.setEvaluator( evaluator ) solver = Solver( SolveStopperFactory.maxEvaluationsStopper(1000) ) # solver = Solver() # solver.setScorer(orbCorrH) # solver.setVariables(orbCorrH.getProxiesV()) # stopper = SolveStopperFactory.maxIterationStopper(1000) # solver.setStopper(stopper) # solver.solve() textArea.append("====== orbit correction ===== \n") textArea.append( "Orbit H score before = %6.4f \n"%orbCorrH.raw_score() ) solver.solve( problem ) scoreboard = solver.getScoreBoard() best_solution = scoreboard.getBestSolution() #print scoreboard # apply the best solution to the model so the variable proxies represent the optimal values problem.evaluate( best_solution ) textArea.append( "Orbit H score after = %6.4f \n"%orbCorrH.raw_score() ) #orbCorrH.printCorrectors() #print solver.getScoreboard().toString() #accCalc.track1() # Flatten the vertical orbit problem = Problem() objective = MinimizingObjective( 0.05 ) problem.addObjective( objective ) hint = InitialDelta() problem.addHint( hint ) orbCorrV = OrbitCorr( accCalc,accNodeForCorr,dcorrsV,"DCV", problem, hint ) evaluator = ScoringEvaluator( orbCorrV, problem.getVariables(), objective ) problem.setEvaluator( evaluator ) solver = Solver( SolveStopperFactory.maxEvaluationsStopper(1000) ) # solver = Solver() # solver.setScorer(orbCorrV) # solver.setVariables(orbCorrV.getProxiesV()) # stopper = SolveStopperFactory.maxIterationStopper(1000) # solver.setStopper(stopper) textArea.append("-------------------\n") textArea.append("Orbit V score before = %6.4f \n"%orbCorrV.raw_score()) solver.solve( problem ) scoreboard = solver.getScoreBoard() best_solution = scoreboard.getBestSolution() #print scoreboard # apply the best solution to the model so the variable proxies represent the optimal values problem.evaluate( best_solution ) textArea.append( "Orbit V score after = %6.4f \n"%orbCorrV.raw_score() ) #orbCorrV.printCorrectors() #print solver.getScoreboard().toString() #============PLOTTING======================= plotx = FunctionGraphsJPanel() ploty = FunctionGraphsJPanel() #---------------------------------- orbX = BasicGraphData() orbY = BasicGraphData() orbX.setDrawLinesOn(true) orbX.setGraphColor(Color.RED) orbY.setDrawLinesOn(true) orbY.setGraphColor(Color.RED) for accNode in accCalc.getAccNodesQuads(): quad = accNode.getNode() s = accNode.getPosS() x = orbCorrH.getTrajDic()[quad] y = orbCorrV.getTrajDic()[quad] orbX.addPoint(s,x) orbY.addPoint(s,y) plotx.addGraphData(orbX) ploty.addGraphData(orbY) plotx.setName("HORIZONTAL (Red-Model Only)") ploty.setName("VERTICAL (Red-Model Only)") plotsAfterPanel.removeAll() plotsAfterPanel.add(plotx) plotsAfterPanel.add(ploty) #---------------------------------- orbCorrH.applyCorrections() orbCorrV.applyCorrections()
def actionPerformed(self,e): self.problem = Problem() objective = MinimizingObjective( 0.05 ) self.problem.addObjective( objective ) hint = InitialDelta( 0.5 ) self.problem.addHint( hint ) x0_var = Variable( "x0", 0.0, -10.0, 10.0 ) hint.addInitialDelta( x0_var, 0.5 ) self.problem.addVariable( x0_var ) self.x0_Proxy = self.problem.getValueReference( x0_var ) xp0_var = Variable( "xp0", 0.0, -10.0, 10.0 ) hint.addInitialDelta( xp0_var, 0.5 ) self.problem.addVariable( xp0_var ) self.xp0_Proxy = self.problem.getValueReference( xp0_var ) y0_var = Variable( "y0", 0.0, -10.0, 10.0 ) hint.addInitialDelta( y0_var, 0.5 ) self.problem.addVariable( y0_var ) self.y0_Proxy = self.problem.getValueReference( y0_var ) yp0_var = Variable( "yp0", 0.0, -10.0, 10.0 ) hint.addInitialDelta( yp0_var, 0.5 ) self.problem.addVariable( yp0_var ) self.yp0_Proxy = self.problem.getValueReference( yp0_var ) variable_proxies = Vector() variable_proxies.add( self.x0_Proxy ) variable_proxies.add( self.xp0_Proxy ) variable_proxies.add( self.y0_Proxy ) variable_proxies.add( self.yp0_Proxy ) self.accCalc = AccCalculator(accSeq , nodes, offSetsFileName, variable_proxies ) accCalc = self.accCalc evaluator = ScoringEvaluator( self.accCalc, self.problem.getVariables(), objective ) self.problem.setEvaluator( evaluator ) textArea.setText(null) plotsBeforePanel.removeAll() #find initial conditions solver = Solver( SolveStopperFactory.maxEvaluationsStopper( 2500 ) ) res = "Score= %6.4f maxDiff= %6.3f \n"%(accCalc.raw_score(),accCalc.getMaxDiff()) textArea.append(res) textArea.append("===after CCL entrance coord. fit ===\n") solver.solve( self.problem ) scoreboard = solver.getScoreBoard() best_solution = scoreboard.getBestSolution() # print best_solution # apply the best solution to the model so the variable proxies represent the optimal values self.problem.evaluate( best_solution ) res = "Score= %6.4f maxDiff= %6.3f \n"%(accCalc.raw_score(),accCalc.getMaxDiff()) textArea.append(res) textArea.append("=== CCL entrance coordinates ===\n") # x0 = best_solution.getTrialPoint().getValue( x0_var ) # xp0 = best_solution.getTrialPoint().getValue( xp0_var ) # y0 = best_solution.getTrialPoint().getValue( y0_var ) # yp0 = best_solution.getTrialPoint().getValue( yp0_var ) x0 = self.x0_Proxy.getValue() xp0 = self.xp0_Proxy.getValue() y0 = self.y0_Proxy.getValue() yp0 = self.yp0_Proxy.getValue() textArea.append("x0 [mm] = %6.3f \n"%x0) textArea.append("xp0[mrad]= %6.3f \n"%xp0) textArea.append("y0 [mm] = %6.3f \n"%y0) textArea.append("yp0[mrad]= %6.3f \n"%yp0) #plot graphs plotx = FunctionGraphsJPanel() ploty = FunctionGraphsJPanel() orbX = BasicGraphData() orbY = BasicGraphData() orbX.setDrawLinesOn(true) orbX.setGraphColor(Color.RED) orbY.setDrawLinesOn(true) orbY.setGraphColor(Color.RED) for accNode in accCalc.getAccNodesQuads(): s = accNode.getPosS() x = accNode.getPosX() y = accNode.getPosY() orbX.addPoint(s,x) orbY.addPoint(s,y) for accNode in accCalc.getAccNodesBPMs(): s = accNode.getPosS() x = accNode.getPosX() y = accNode.getPosY() orbX.addPoint(s,x) orbY.addPoint(s,y) plotx.addGraphData(orbX) ploty.addGraphData(orbY) #add BPMs points bpmX = BasicGraphData() bpmY = BasicGraphData() bpmX.setDrawLinesOn(false) bpmY.setDrawLinesOn(false) bpmX.setGraphColor(Color.BLACK) bpmY.setGraphColor(Color.BLACK) for accNode in accCalc.getAccNodesBPMs(): s = accNode.getPosS() x = accNode.getPosExperX() y = accNode.getPosExperY() bpmX.addPoint(s,x) bpmY.addPoint(s,y) plotx.addGraphData(bpmX) ploty.addGraphData(bpmY) plotx.setName("HORIZONTAL (Red-Model Black-BPMs)") ploty.setName("VERTICAL (Red-Model Black-BPMs)") plotsBeforePanel.add(plotx) plotsBeforePanel.add(ploty)