def justtwiss(): ######################### global dictionary system('madx < job.ORM.madx > scum') x = twiss('twiss.orbit.dat') y = twiss('twiss.all.dat') return x, y
def getTunes(options,fileslist): ''' Reads in the driven tunes from the file with dpp=0 Reads in the model tunes from the twiss model (twiss.dat) Appends the attributes to options. :param options: options from parse_args :param fileslist: dictionary of files, dpp used as key :raise ValueError: If fileslist[0] does not exist ''' if fileslist[0][0][-3:]=='.gz': fname=fileslist[0][0][:-3] end='.gz' else: fname=fileslist[0][0] end='' tw_x=twiss(fname+'_linx'+end) tw_y=twiss(fname+'_liny'+end) tw=twiss(get_twissfile(options)) qdx,qdy=tw_x.TUNEX[0],tw_y.TUNEY[0] qx,qy=tw.Q1%1,tw.Q2%1 setattr(options,"qx",qx) setattr(options,"qy",qy) setattr(options,"qdx",qdx) setattr(options,"qdy",qdy)
def twissVec(deltafamilies): #print deltafamilies writeparams(deltafamilies) system('madx < job.iterate.madx > scum');md=model('twiss.dat') dir='/afs/cern.ch/user/g/grumolo/scratch1/acd.data/results/' x=twiss(dir+'x.out');y=twiss(dir+'y.out') #-- read results and make model phadv blah=muXY(md,x,y) return numpy.concatenate([blah[0],blah[1],[md['Q1']],[md['Q2']]])
def twissVec(deltafamilies): # print deltafamilies writeparams(deltafamilies) system("madx < job.iterate.madx > scum") md = model("twiss.dat") dir = "/afs/cern.ch/user/g/grumolo/scratch1/acd.data/results/" x = twiss(dir + "x.out") y = twiss(dir + "y.out") # -- read results and make model phadv blah = muXY(md, x, y) return numpy.concatenate([blah[0], blah[1], [md["Q1"]], [md["Q2"]]])
def phasesubtract(prex,prey,nit,options,maccel,mpath): global dictionary print mpath twissfile=mpath+"/twiss.corrected.dat" print "Where to read the twiss file "+twissfile MADTwiss1=twiss(twissfile,dictionary) [phase1x,phase1y]=GetPhases(prex,prey,MADTwiss1) fmodel=options.OPT+'/twiss.dat' MADTwiss0=twiss(fmodel,dictionary) [phase0x,phase0y]=GetPhases(prex,prey,MADTwiss0) fpresentx=mpath+'/getphasex.0'+str(nit)+'.out' fpresenty=mpath+'/getphasey.0'+str(nit)+'.out' faftx=open(fpresentx,'w') tunex=prex.Q1-(MADTwiss1.Q1 %1)+(MADTwiss0.Q1 %1) if tunex>0.5: tunex=tunex-1.0 tuney=prey.Q2-(MADTwiss1.Q2 %1)+(MADTwiss0.Q2 %1) if tuney>0.5: tuney=tuney-1.0 faftx.write('@ Q1 %le '+str(tunex)+'\n') faftx.write('* NAME NAME2 S PHASEX STDPHX PHXMDL\n') faftx.write('$ %s %s %le %le %le %le\n') fafty=open(fpresenty,'w') fafty.write('@ Q2 %le '+str(tuney)+'\n') fafty.write('* NAME NAME2 S PHASEY STDPHY PHYMDL\n') fafty.write('$ %s %s %le %le %le %le\n') for i in prex.NAME: i2=prex.NAME2[prex.indx[i]] try: phasex=prex.PHASEX[prex.indx[i]]-(phase1x[i]-phase0x[i]) faftx.write('"'+i+'" '+'"'+i2+'" '+str(MADTwiss0.S[MADTwiss0.indx[i]])+' '+str(phasex)+' '+str(prex.STDPHX[prex.indx[i]])+' '+str(phase0x[i])+'\n') except: 0.0 faftx.close() system('cp '+fpresentx+' '+mpath+'/getphasex.out.copy') for i in prey.NAME: i2=prey.NAME2[prey.indx[i]] #print i, MADTwiss0.S[MADTwiss0.indx[i]], prex.POS1[prex.indx[i]] try: phasey=prey.PHASEY[prey.indx[i]]-(phase1y[i]-phase0y[i]) #print 'phase difference',(phase1y[i]-phase0y[i]) #print (phase1[i][1]-phase0[i][1]) fafty.write('"'+i+'" '+'"'+i2+'" '+str(MADTwiss0.S[MADTwiss0.indx[i]])+' '+str(phasey)+' '+str(prey.STDPHY[prey.indx[i]])+' '+str(phase0y[i])+'\n') except: 0.0 fafty.close() system('cp '+fpresenty+' '+mpath+'/getphasey.out.copy')
def justtwiss(): ######################### global dictionary system('madx < job.twiss.madx > scum') #x=twiss('twiss.dat',dictionary) x=twiss('twiss.orbit.dat') return x
def __init__(self, order=1): #--- DBDP= (1/beta)*(dbeta/dp) self.order=order;self.DPDB={};nm=_findFile() DPP=[];QXY=[];xdat=[];ydat=[];VAR={};SC={}; print '#- Poly Fit, Order:',self.order for k in nm: aa=twiss(k);iter=0; DPP.append(aa.DPP); try: QXY.append(aa.Q1) except: QXY.append(aa.Q2) for j in aa.NAME: #-- make dict, dpp vs amp try: dPP=aa.DPP except: dPP=0.0 if j not in VAR: VAR[j]=[];SC[j]=aa.S[aa.indx[j]] VAR[j].append([dPP,aa.AMPX[iter]]);iter+=1 #--- fit dpp vs amp and norm by amp for k in VAR.iteritems(): k1=npy.array(k[1]) if len(k1)>2: coeff=_polyFit(k1[:,0],k1[:,1],self.order) err=_stDev(coeff, k1[:,0], k1[:,1]) self.DPDB[k[0]]=SC[k[0]],coeff[1]/coeff[0],err print SC[k[0]],coeff[1]/coeff[0],err #else: print k[0],'not fitted' #-- calculate tune & chroms if len(DPP)>1: coeff=_polyFit(DPP,QXY,self.order)
def justtwiss(deltafamilies): ######################### print deltafamilies writeparams(deltafamilies) system('madx < job.iterate.madx > scum') x = twiss('twiss.dat') return x
def justtwiss(deltafamilies): ######################### print deltafamilies writeparams(deltafamilies) system("madx < job.iterate.madx > scum") x = twiss("twiss.dat") return x
def justtwiss(deltafamilies): ######################### print deltafamilies writeparams(deltafamilies) system('madx < job.iterate.madx > scum') x=twiss('twiss.dat') return x
def justtwiss(): ######################### global dictionary system('madx < job.twiss.madx > scum') #x=twiss('twiss.dat',dictionary) x = twiss('twiss.orbit.dat') return x
def justtwiss(deltafamilies): ######################### print deltafamilies writeparams(deltafamilies) system("madx < job.iterate_couple.madx > scum") x = twiss("twiss_couple.dat") print x.Q1, x.Q2 return x
def justtwiss(deltafamilies): ######################### global dictionary print deltafamilies writeparams(deltafamilies) system('madx < sls_f6cwo.RM.madx > scum') x=twiss('twiss.dat',dictionary) return x
def justtwiss(file): ######################### # print deltafamilies #writeparams(deltafamilies) #system('madx < job.iterate.madx > scum') x = twiss(file) x.Cmatrix() return x
def model(file): mdB = twiss(file) mdlB = {} for k in range(len(mdB.NAME)): mdlB[mdB.NAME[k]] = [mdB.MUX[k], mdB.MUY[k]] mdlB["Q1"] = mdB.Q1 mdlB["Q2"] = mdB.Q2 return mdlB
def Cminus(f): a = twiss(f) a.Cmatrix() abs_f1001 = np.sqrt((a.F1001R) * (a.F1001R) + (a.F1001I) * (a.F1001I)) abs_f1010 = np.sqrt((a.F1010R) * (a.F1010R) + (a.F1010I) * (a.F1010I)) Cm = 1 - 1 / (1 + 4 * ((abs_f1001) * (abs_f1001) - (abs_f1010) * (abs_f1010))) return Cm
def justtwiss(deltafamilies): ######################### print deltafamilies writeparams(deltafamilies) system('madx < job.iterate_temp.madx > scum') x=twiss('twiss_temp.dat') print x.Q1, x.Q2 return x
def justtwiss(file): ######################### # print deltafamilies #writeparams(deltafamilies) #system('madx < job.iterate.madx > scum') x=twiss(file) x.Cmatrix() return x
def justtwiss(deltafamilies): ######################### print deltafamilies writeparams(deltafamilies) system('madx < job.coupling.madx > scum') system('pythonafs twiss_converter_for_coupling.py twiss.couple.dat.org') x=twiss('twiss.couple.rm.dat') #x.Cmatrix() return x
def justtwiss(deltafamilies): ######################### print deltafamilies writeparams(deltafamilies) system('madx < job.couplingb2.madx > scum') system('pythonafs twiss_converter_for_coupling.py twiss.couple.dat.org') x=twiss('twiss.couple.rm.dat') #x.Cmatrix() return x
def justtwiss(deltafamilies): ######################### print deltafamilies writeparams(deltafamilies) system('madx < job.iterate_couple.madx > scum') x = twiss('twiss_couple.dat') print x.Q1, x.Q2 x.Cmatrix() return x
def justtwiss(deltafamilies): ######################### global dictionary print deltafamilies writeparams(deltafamilies) system("madx < job.iterate.madx > scum") x = twiss("twiss.dat", dictionary) x.Cmatrix() return x
def justtwiss(deltafamilies): ######################### global dictionary print deltafamilies writeparams(deltafamilies) system('madx < job.iterate_couple.madx > scum') x=twiss('twiss_couple.dat', dictionary) x.Cmatrix() return x
def justtwiss(deltafamilies): ######################### global dictionary print deltafamilies writeparams(deltafamilies) system('madx < job.iterate.madx > scum') x=twiss('twiss.dat', dictionary) x.Cmatrix() return x
def loadtwiss_beta(varandpath): (var, path) = varandpath # print "Reading twiss." + var x = 0 try: x = metaclass.twiss(path + "/twiss." + var) os.remove(path + "/twiss." + var) except IOError as e: print e return [] return var, x
def readtables(self, path, ext): self.twissfilesx = [] self.twissfilesy = [] files = os.listdir(path) for i in files: if ext in i: print "Twiss file found : " + path + "/" + i tempx = twiss(path + "/" + i) tempy = twiss(path + "/" + i) self.twissfilesx.append(tempx) self.twissfilesy.append(tempx) print "Number of twiss files found in directory " + str( len(self.twissfiles))
def readtables(self,path,ext): self.twissfilesx=[] self.twissfilesy=[] files=os.listdir(path) for i in files: if ext in i: print "Twiss file found : "+path+"/"+i tempx=twiss(path+"/"+i) tempy=twiss(path+"/"+i) self.twissfilesx.append(tempx) self.twissfilesy.append(tempx) print "Number of twiss files found in directory "+str(len(self.twissfiles))
def dispsubtract(predx,nit,options,maccel,mpath,fmodel): global dictionary twissfile=mpath+"/twiss.corrected.dat" MADTwiss1=twiss(twissfile,dictionary) MADTwiss0=twiss(fmodel,dictionary) fpresentDx=mpath+'/getNDx.0'+str(nit)+'.out' faftdx=open(fpresentDx,'w') faftdx.write('* NAME S NDX STDNDX NDXMDL\n') faftdx.write('$ %s %le %le %le %le\n') for i in predx.NAME: #try: sDX=predx.NDX[predx.indx[i]]-(MADTwiss1.DX[predx.indx[i]]/sqrt(MADTwiss1.BETX[predx.indx[i]])-MADTwiss0.DX[predx.indx[i]]/sqrt(MADTwiss0.BETX[predx.indx[i]])) faftdx.write('"'+i+'" '+str(MADTwiss0.S[MADTwiss0.indx[i]])+' '+str(sDX)+' '+str(predx.STDNDX[predx.indx[i]])+' '+str(predx.NDXMDL[predx.indx[i]])+'\n') #except: # 0.0 faftdx.close() system('cp '+fpresentDx+' '+mpath+'/getNDx.out.copy')
def loadtwiss_coup(varandpath): var, path = varandpath # print "Reading twiss." + var x = 0 try: x = metaclass.twiss(path + "/twiss." + var) x.Cmatrix() os.remove(path + "/twiss." + var) except IOError as e: print e return [] return var, x
def fromTFStoDF(file): import metaclass as metaclass a = metaclass.twiss(file) aux = [] aux1 = [] for i in dir(a): if not i[0] == '_': if type(getattr(a, i)) is float: #print(i + ":"+ str(type(getattr(a,i)))) aux.append(i) aux1.append(getattr(a, i)) if type(getattr(a, i)) is str: #print(i + ":"+ str(type(getattr(a,i)))) aux.append(i) aux1.append(getattr(a, i)) myList = [] myColumns = [] for i in a.keys: myContainer = getattr(a, i) if len(myContainer) == 0: print("The column " + i + ' is empty.') else: myColumns.append(i) myList.append(myContainer) optics = pnd.DataFrame(np.transpose(myList), index=a.S, columns=myColumns) for i in optics.columns: aux3 = optics.iloc[0][i] if type(aux3) is str: aux3 = str.replace(aux3, '+', '') aux3 = str.replace(aux3, '-', '') aux3 = str.replace(aux3, '.', '') aux3 = str.replace(aux3, 'e', '') aux3 = str.replace(aux3, 'E', '') if aux3.isdigit(): optics[i] = optics[i].apply(np.double) aux.append('FILE_NAME') aux1.append(os.path.abspath(file)) aux.append('TABLE') aux1.append(optics) globalDF = pnd.DataFrame([aux1], columns=aux) return globalDF
def callandrunmadx(beam,plane,path,bsource,freetune,driventune,madx): maindir=os.path.dirname(path) acpath=maindir+"/ACDIPOLE.core/" if not os.path.exists(acpath): os.mkdir(acpath) if plane=="H": tunes=open(acpath+'/tunes'+beam+'_H.sh','w') shtunes=acpath+'/tunes'+beam+'_H.sh' madxpath=bsource+'/MODEL/'+beam+'/AC.Dipole/twiss.'+beam+'.hac.mask' madxpro='twiss.'+beam+'.hac.madx' print madxpath #if not os.path.exists(acpath+'/twiss.'+beam+'.hac.madx'): #os.system('cp '+madxpath+' '+acpath) else: tunes=open(acpath+'/tunes'+beam+'_V.sh','w') shtunes=acpath+'/tunes'+beam+'_V.sh' madxpath=bsource+'/MODEL/'+beam+'/AC.Dipole/twiss.'+beam+'.vac.mask' madxpro='twiss.'+beam+'.vac.madx' #if not os.path.exists(acpath+'/twiss.'+beam+'.vac.madx'): #os.system('cp '+madxpath+' '+acpath) print >> tunes,'sed -e \'s/%Q/\''+str(freetune)+'\'/g\' \\' print >> tunes,' -e \'s/%D/\''+str(driventune)+'\'/g\' \\' print >> tunes,' -e \'s/%PATH/\''+'\"'+str(acpath.replace('/','\/'))+'\"'+'\'/g\' \\' if plane=="H": print >> tunes,'<',madxpath,'> ',acpath+'/twiss.'+beam+'.hac.madx' else: print >> tunes,'<',madxpath,'> ',acpath+'/twiss.'+beam+'.vac.madx' tunes.close() print 'chmod 777 '+shtunes os.system('chmod 777 '+shtunes) os.system(shtunes) print "Triggering madx job" print madx+'<'+acpath os.system(madx+'<'+acpath+'/'+madxpro) if plane=="H": twissfile=acpath+"/twiss."+beam+".hac.dat" else: twissfile=acpath+"/twiss."+beam+".vac.dat" twissac=twiss(twissfile) return twissac
def justtwiss(deltafamilies,magnet): ######################### global dictionary print deltafamilies writeparams(deltafamilies,magnet) if(magnet=="Q"): system('madx < job.iterateQ.madx > scum') elif(magnet=='S'): system('madx < job.iterateS.madx > scum') x=twiss('twiss_Response.dat') x.Cmatrix() return x
def justtwiss(deltafamilies, magnet): ######################### global dictionary print deltafamilies writeparams(deltafamilies, magnet) if (magnet == "Q"): system('madx < job.iterateQ.madx > scum') elif (magnet == 'S'): system('madx < job.iterateS.madx > scum') x = twiss('twiss_Response.dat') x.Cmatrix() return x
def write_QuadRamp_files(target_file, twissfile, pattern, ptc_source_table): comm = orbit_mpi.mpi_comm.MPI_COMM_WORLD rank = orbit_mpi.MPI_Comm_rank(comm) if not rank: t = metaclass.twiss(twissfile) q_i = [i for i, n in enumerate(t.NAME) if pattern in n] with open(target_file, 'w') as fid: fid.write('SET ORBIT RAMPING \n') for i in q_i: fid.write(' ramp\n %s\t"%s"\t%1.9f \n' % (t.NAME[i], ptc_source_table, (t.K1L[i] / t.L[i]) / (t.K1L[q_i[0]] / t.L[q_i[0]]))) fid.write('return') orbit_mpi.MPI_Barrier(comm)
def callandrunmadx(beam, plane, path, bsource, freetune, driventune, madx): maindir = os.path.dirname(path) acpath = maindir + "/ACDIPOLE.core/" if not os.path.exists(acpath): os.mkdir(acpath) if plane == "H": tunes = open(acpath + '/tunes' + beam + '_H.sh', 'w') shtunes = acpath + '/tunes' + beam + '_H.sh' madxpath = bsource + '/MODEL/' + beam + '/AC.Dipole/twiss.' + beam + '.hac.mask' madxpro = 'twiss.' + beam + '.hac.madx' print madxpath #if not os.path.exists(acpath+'/twiss.'+beam+'.hac.madx'): #os.system('cp '+madxpath+' '+acpath) else: tunes = open(acpath + '/tunes' + beam + '_V.sh', 'w') shtunes = acpath + '/tunes' + beam + '_V.sh' madxpath = bsource + '/MODEL/' + beam + '/AC.Dipole/twiss.' + beam + '.vac.mask' madxpro = 'twiss.' + beam + '.vac.madx' #if not os.path.exists(acpath+'/twiss.'+beam+'.vac.madx'): #os.system('cp '+madxpath+' '+acpath) print >> tunes, 'sed -e \'s/%Q/\'' + str(freetune) + '\'/g\' \\' print >> tunes, ' -e \'s/%D/\'' + str(driventune) + '\'/g\' \\' print >> tunes, ' -e \'s/%PATH/\'' + '\"' + str( acpath.replace('/', '\/')) + '\"' + '\'/g\' \\' if plane == "H": print >> tunes, '<', madxpath, '> ', acpath + '/twiss.' + beam + '.hac.madx' else: print >> tunes, '<', madxpath, '> ', acpath + '/twiss.' + beam + '.vac.madx' tunes.close() print 'chmod 777 ' + shtunes os.system('chmod 777 ' + shtunes) os.system(shtunes) print "Triggering madx job" print madx + '<' + acpath os.system(madx + '<' + acpath + '/' + madxpro) if plane == "H": twissfile = acpath + "/twiss." + beam + ".hac.dat" else: twissfile = acpath + "/twiss." + beam + ".vac.dat" twissac = twiss(twissfile) return twissac
def loadtwiss_chrom_coup(varandpathanddpp): var, path, dpp = varandpathanddpp # print "Reading twiss.dp+." + var xp = 0 xm = 0 try: xp = metaclass.twiss(path + "/twiss.dp+." + var) xp.Cmatrix() # print "Reading twiss.dp-." + var xm = metaclass.twiss(path + "/twiss.dp-." + var) xm.Cmatrix() except IOError as e: print e return [] # Initializing and Calculating chromatic coupling for every BPM xp.Cf1001r = [] xp.Cf1001i = [] xp.Cf1010r = [] xp.Cf1010i = [] for j in range(len(xp.NAME)): vvv = (xp.F1001R[j] - xm.F1001R[j]) / (2 * dpp) xp.Cf1001r.append(vvv) vvv = (xp.F1001I[j] - xm.F1001I[j]) / (2 * dpp) xp.Cf1001i.append(vvv) vvv = (xp.F1001R[j] - xm.F1001R[j]) / (2 * dpp) xp.Cf1010r.append(vvv) vvv = (xp.F1010I[j] - xm.F1010I[j]) / (2 * dpp) xp.Cf1010i.append(vvv) os.remove(path + "/twiss.dp+." + var) os.remove(path + "/twiss.dp-." + var) return var, xp
def dispsubtract(predx, nit, options, maccel, mpath): global dictionary twissfile = mpath + "/twiss.corrected.dat" MADTwiss1 = twiss(twissfile, dictionary) fmodel = options.OPT + "/twiss.dat" MADTwiss0 = twiss(fmodel, dictionary) fpresentDx = mpath + "/getNDx.0" + str(nit) + ".out" faftdx = open(fpresentDx, "w") faftdx.write("* NAME S NDX STDNDX NDXMDL\n") faftdx.write("$ %s %le %le %le %le\n") for i in predx.NAME: # try: sDX = predx.NDX[predx.indx[i]] - ( MADTwiss1.DX[predx.indx[i]] / sqrt(MADTwiss1.BETX[predx.indx[i]]) - MADTwiss0.DX[predx.indx[i]] / sqrt(MADTwiss0.BETX[predx.indx[i]]) ) faftdx.write( '"' + i + '" ' + str(MADTwiss0.S[MADTwiss0.indx[i]]) + " " + str(sDX) + " " + str(predx.STDNDX[predx.indx[i]]) + " " + str(predx.NDXMDL[predx.indx[i]]) + "\n" ) # except: # 0.0 faftdx.close() system("cp " + fpresentDx + " " + mpath + "/getNDx.out.copy")
def plotOptics(sx,px,sy,py,modelFile): import pylab; phm=[]; phx=[]; phy=[] a=twiss(modelFile);Q1=a.Q1%1.0; Q2=a.Q2%1.0 phm.append([a.MUX[0],a.MUY[0]]); phx.append((Q1-(px[-1]-px[0]))/2) phy.append((-Q2+(py[-1]-py[0]))/2) for j in range(1,len(a.MUX)): phm.append([a.MUX[j]-a.MUX[j-1], a.MUY[j]-a.MUY[j-1]]) for j in range(1,len(px)): phx.append(mod(px[j]-px[j-1],1)) for j in range(1,len(py)): phy.append(mod(py[j]-py[j-1],1)) phm=array(phm) pylab.subplot(2,1,1); pylab.scatter(sx,phx);pylab.plot(a.S,phm[:,0]); pylab.subplot(2,1,2); pylab.scatter(sy,phy);pylab.plot(a.S,phm[:,1]); pylab.show()
def calcHist(fileName,attr_name,nbins=70): a=twiss(fileName) if default==0: if npy.isreal(a.__dict__[attr_name]): indx,frq=npy.histogram(a.__dict__[attr_name],bins=nbins) if default==1: if a.__dict__[attr_name].typecode()=='d': hits=Histogram(a.__dict__[attr_name],nbins) indx=hits[:,0];frq=hits[:,1] ave=npy.average(a.__dict__[attr_name]) if default==0: stdev=npy.std(a.__dict__[attr_name]) if default==1: stdev=std(a.__dict__[attr_name]) else: print "data is not real" f=open(path+'/HIST.tfs','w') f.write('@ NAME %0'+str(len(attr_name))+'s "'+attr_name+'"\n') f.write('@ '+attr_name+'AVE %le '+str(ave)+'\n') f.write('@ '+attr_name+'STD %le '+str(ave)+'\n') f.write("*"+'%5s %5s' % ("INDX", "FREQ")+"\n") f.write("$"+'%5s %5s' % ("%le", "%le")+"\n") for j in range(len(indx)): f.write('%5s %5s' % (indx[j], frq[j])+"\n") f.close()
def main(accel): ''' :Parameters: 'accel': string Indicates the used accelerator 'names_dict': dict: string --> float <description> :Return: int 0 if execution was successful otherwise !=0 ''' ## Never use exec() or execFile() ## If you have to use try/catch then catch specific exceptions but never all try: twiss_file = metaclass.twiss("I_do_not_exist.dat") except IOError: traceback.print_exc() return 1 print twiss_file print accel return 0
tan(phasetune)) + pi * (phasetune - pi) + pi * driventune return phasedriven def getlambda(drivetune, tune): up = sin(pi * (drivetune - tune)) down = sin(pi * (drivetune + tune)) lambdad = up / down return lambdad # reading files phasex = twiss(options.path + '/getphasex.out') Qx = phasex.Q1 Qy = phasex.Q2 phasey = twiss(options.path + '/getphasey.out') phasext = twiss(options.path + '/getphasetotx.out') phaseyt = twiss(options.path + '/getphasetoty.out') betax = twiss(options.path + '/getbetax.out') betay = twiss(options.path + '/getbetay.out') ampbetax = twiss(options.path + '/getampbetax.out') ampbetay = twiss(options.path + '/getampbetay.out') model = twiss(options.bb + '/MODEL/' + options.accel + '/nominal.opt/twiss_ac.dat') allfiles = [phasex, phasey, phasext, phaseyt, betax, betay, ampbetax, ampbetay] # main part
from metaclass import twiss twissno=twiss('twiss_elements.dat') twissac=twiss('twiss_elements_ac.dat') filefile=open("acdipole.tfs","w") betaxIP1=twissno.BETX[twissno.indx['IP1']]-twissac.BETX[twissac.indx ['IP1']] betayIP1=twissno.BETY[twissno.indx['IP1']]-twissac.BETY[twissac.indx['IP1']] betaxIP2=twissno.BETX[twissno.indx['IP2']]-twissac.BETX[twissac.indx['IP2']] betayIP2=twissno.BETY[twissno.indx['IP2']]-twissac.BETY[twissac.indx['IP2']] betaxIP5=twissno.BETX[twissno.indx['IP5']]-twissac.BETX[twissac.indx['IP5']] betayIP5=twissno.BETY[twissno.indx['IP5']]-twissac.BETY[twissac.indx['IP5']] betaxIP8=twissno.BETX[twissno.indx['IP8']]-twissac.BETX[twissac.indx['IP8']] betayIP8=twissno.BETY[twissno.indx['IP8']]-twissac.BETY[twissac.indx['IP8']] print >> filefile,"* NAME DBETX DBETY" print >> filefile,"$ %s %le %le" print >> filefile,"IP1",betaxIP1,betayIP1 print >> filefile,"IP2",betaxIP2,betayIP2 print >> filefile,"IP5",betaxIP5,betayIP5 print >> filefile,"IP8",betaxIP8,betayIP8 filefile.close()
if "MDH" in name: return 1 else: return 0 def checkphaseandbeta(x, k, l): #print x.BETX[k]/x.BETX[l], abs(x.MUX[k]-x.MUX[l]) if (0.95 < x.BETX[k] / x.BETX[l] < 1.05) and (0.47 < abs(x.MUX[k] - x.MUX[l]) < 0.57): return 1 else: return 0 a = twiss('67ph.opt/twiss.tfs') pairs = [] corr1 = [] corr2 = [] corrs = [] vars = {} for i in range(len(a.NAME)): if iscorr(a.NAME[i]): corrs.append(i) vars[a.NAME[i]] = "" vcount = 0 for i in range(len(corrs) - 3):
import metaclass as mtc import numpy as np fname = 'twiss.out' ob = mtc.twiss(fname) import matplotlib.pyplot as pl pl.close('all') sp1 = pl.subplot(3, 1, 1) pl.plot(ob.S, 0.5 * np.float_(np.sign(ob.K0L)), '.g') pl.plot(ob.S, -0.5 * np.float_(np.sign(ob.K0L)), '.g') pl.plot(ob.S, np.float_(np.sign(ob.K1L)), '.b') sp1.set_ylim(-1.2, 1.2) sp2 = pl.subplot(3, 1, 2, sharex=sp1) pl.plot(ob.S, ob.BETX, '-b') pl.plot(ob.S, ob.BETY, '-r') sp3 = pl.subplot(3, 1, 3, sharex=sp1) pl.plot(ob.S, ob.DX, '.-') for sp in [sp1, sp2, sp3]: sp.grid('on') pl.show()
errorcuts=options.errorcut.split(",") errorcutC=float(errorcuts[0]) errorcutD=float(errorcuts[1]) #modelcut=float(options.modelcut) #errorcut=float(options.errorcut) cut= float(options.cut) #print "Model, error and SVD cuts:", modelcut, errorcut, cut print "Starting loading Full Response optics" FullResponse=pickle.load(open(accelpath+'/Coupling/FullResponse_couple','r')) print "Loading ended" couple=twiss(options.path+'/getcouple.out') weights=options.Dy.split(',') if weights[4]=="1": dispy=twiss(options.path+'/getDy.out') else: dispy=[] execfile(accelpath+'/Coupling/AllLists_couple.py') print accelpath+'/Coupling/AllLists_couple.py' listvar=options.var.split(",") print listvar varslist=[] for var in listvar: exec('variable='+var+'()')
else: beta_real = real.BETY[real.indx[bpm]] alfa_real = real.ALFY[real.indx[bpm]] beta_model = model.BETY[model.indx[bpm]] alfa_model = model.ALFY[model.indx[bpm]] beta = (beta_real - beta_model) / beta_model alfa = alfa_real - alfa_model phase = 0 data[bpm] = [bpm, s, beta, alfa, phase] return [bpms, data] # reading files phasex = twiss(options.path + '/getphasex.out') drivetunex = phasex.Q1 drivetuney = phasex.Q2 phasey = twiss(options.path + '/getphasey.out') #phasext=twiss(options.path+'/getphaserx.out') #phaseyt=twiss(options.path+'/getphasery.out') betax = twiss(options.path + '/getbetax.out') betay = twiss(options.path + '/getbetay.out') ampbetax = twiss(options.path + '/getampbetax.out') ampbetay = twiss(options.path + '/getampbetay.out') #model=twiss(options.bb+'/MODEL/'+options.accel+'/nominal.opt/twiss_ac.dat') allfiles = [phasex, phasey, betax, betay, ampbetax, ampbetay] # writing files betaxac = open(options.output + '/getbetax_acfree.out', 'w')
metavar="PATH", default="./", dest="path") parser.add_option("-n", "--nbpms", help="Number of BPMs", metavar="NBPMS", default=16, dest="nbpms") (options, args) = parser.parse_args() datafilename = options.path + options.file print 'ORM file = ', datafilename ORMmeas = twiss(datafilename) nbpms = options.nbpms ncorrs = len(ORMmeas.s) / nbpms print(' ncorrs = ', ncorrs) plt.figure(1) for i in range(ncorrs): plt.subplot(211) startidx = i * nbpms stopidx = (i + 1) * nbpms - 1 plt.plot(ORMmeas.s[startidx:stopidx], ORMmeas.MX[startidx:stopidx]) plt.subplot(212)
def correctpy(options, args): print "Selected accelerator:", options.ACCEL print "Path to measurements:", options.path betapath = options.rpath print "Path to Repository:", betapath accelpath=betapath+'/MODEL/'+options.ACCEL+'/'+options.OPT+'/' accelpath2=betapath+'/MODEL/'+options.ACCEL2+'/'+options.OPT+'/' print "Path to Accelerator model", accelpath print "Selected algorithm:", options.TECH if options.TECH=="MICADO": ncorr=int(options.ncorr) print "Number of Correctors Used:", options.ncorr else: if options.ACCEL=="SPS": MinStr =0.0 else: MinStr = float(options.MinStr) print "Minimum corrector strength", MinStr j=int(options.JustOneBeam) ##### implementing cuts for modelcut=float(options.modelcut.split(",")[0]) errorcut=float(options.errorcut.split(",")[0]) modelcutdx=float(options.modelcut.split(",")[1]) errorcutdx=float(options.errorcut.split(",")[1]) cut= float(options.cut) print "Model, error and SVD cuts:", modelcut, errorcut, cut print "Starting loading Full Response optics" FullResponse=pickle.load(open(accelpath+'/FullResponse.Numeric','r')) if j==1: FullResponse2=pickle.load(open(accelpath2+'/FullResponse.Numeric','r')) print "Loading ended" x=twiss(options.path+'/getphasex.out') y=twiss(options.path+'/getphasey.out') if j==1: x2=twiss(options.path2+'/getphasex.out') y2=twiss(options.path2+'/getphasey.out') try: if options.WGT.split(",")[4]=='1': dx=twiss(options.path+'/getNDx.out') # changed by Glenn Vanbavinckhove (26/02/09) else: dx=[] if j==1 and options.WGT.split(",")[4]=='1': dx2=twiss(options.path2+'/getNDx.out') else: dx2=[] except: print "WARNING: No good dispersion or inexistent file getDx" print "WARNING: Correction will not take into account NDx" dx=[] dx2=[] execfile(accelpath+'/AllLists.py') if j==1: execfile(accelpath2+'/AllLists.py') # extra depdency to be able to handle to different magnets group listvar=options.var.split(",") varslist=[] for var in listvar: #exec('variable='+var+'()') #varslist=varslist+variable varslist=varslist+eval(var+'()') intqx=int(FullResponse['0'].Q1) intqy=int(FullResponse['0'].Q2) if j==1: intqx2=int(FullResponse2['0'].Q1) intqy2=int(FullResponse2['0'].Q2) print "Integer part of tunes: ", intqx, intqy # remember to add integer part of the tunes to exp data!!! if x.Q1 > 0.0: x.Q1=x.Q1+intqx else: x.Q1=x.Q1+intqx+1.0 if y.Q2 > 0.0: y.Q2=y.Q2+intqy else: y.Q2=y.Q2+intqy+1.0 if j==1: if x2.Q1 > 0.0: x2.Q1=x2.Q1+intqx2 else: x2.Q1=x2.Q1+intqx2+1.0 if y2.Q2 > 0.0: y2.Q2=y2.Q2+intqy2 else: y2.Q2=y2.Q2+intqy2+1.0 if j==0: print "Experiment tunes: ", x.Q1, y.Q2 if j==1: print "Experiment tunes: ", x.Q1, y.Q2, x2.Q1, y2.Q2 variables=varslist phasexlist=MakePairs(x, FullResponse['0'], modelcut=modelcut, errorcut=errorcut) phaseylist=MakePairs(y, FullResponse['0'], modelcut=modelcut, errorcut=errorcut) betaxlist=[] betaylist=betaxlist displist=MakeList(dx, FullResponse['0']) if j==1: phasexlist2=MakePairs(x2, FullResponse2['0'], modelcut=modelcut, errorcut=errorcut) phaseylist2=MakePairs(y2, FullResponse2['0'], modelcut=modelcut, errorcut=errorcut) betaxlist2=[] betaylist2=betaxlist2 displist2=MakeList(dx2, FullResponse2['0']) print "Input ready" wei=[] for i in range(0,6): wei.append(int(options.WGT.split(",")[i]))#wei=[1,1,1,1,1,10] # Weights of phasex phasey betax betay disp and tunes print "weight=",wei if j==0: beat_inp=beat_input(varslist, phasexlist, phaseylist, betaxlist, betaylist, displist, wei) sensitivity_matrix=beat_inp.computeSensitivityMatrix(FullResponse) if j==1: beat_inp=beat_input2(varslist, phasexlist, phaseylist, betaxlist, betaylist, displist, phasexlist2, phaseylist2, betaxlist2, betaylist2, displist2, wei) sensitivity_matrix=beat_inp.computeSensitivityMatrix2(FullResponse,FullResponse2) if options.TECH=="SVD": if j==0: [deltas, varslist ] = correctbeatEXP(x,y,dx, beat_inp, cut=cut, app=0, path=options.path) if j==1: [deltas, varslist ] = correctbeatEXP2(x,x2,y,y2,dx,dx2, beat_inp, cut=cut, app=0, path=options.path) if 1: #All accelerators iteration=0 # Let's remove too low useless correctors while (len(filter(lambda x: abs(x)< MinStr, deltas))>0): iteration=1+iteration il=len(varslist) varslist_t=[] for i in range(0,il): if (abs(deltas[i]) > MinStr): varslist_t.append(varslist[i]) varslist=varslist_t if len(varslist)==0: print "You want to correct with too high cut on the corrector strength" sys.exit() if j==0: beat_inp=beat_input(varslist, phasexlist, phaseylist, betaxlist, betaylist, displist, wei) sensitivity_matrix=beat_inp.computeSensitivityMatrix(FullResponse) [deltas, varslist ] = correctbeatEXP(x,y,dx, beat_inp, cut=cut, app=0, path=options.path) if j==1: beat_inp=beat_input2(varslist, phasexlist, phaseylist, betaxlist, betaylist, displist, phasexlist2, phaseylist2, betaxlist2, betaylist2, displist2, wei) sensitivity_matrix=beat_inp.computeSensitivityMatrix2(FullResponse,FullResponse2) [deltas, varslist ] = correctbeatEXP2(x,x2,y,y2,dx,dx2, beat_inp, cut=cut, app=0, path=options.path) print "Initial correctors:", il, ". Current: ",len(varslist), ". Removed for being lower than:", MinStr, "Iteration:", iteration print deltas if options.TECH=="MICADO": bNCorrNumeric(x,y,dx,beat_inp, cut=cut,ncorr=ncorr,app=0,path=options.path) if options.ACCEL=="SPS": b=twiss(options.path+"/changeparameters.tfs") execfile(accelpath+'/Bumps.py') # LOADS corrs execfile(accelpath+'/BumpsYASP.py') # LOADS corrsYASP #Output for YASP... f=open(options.path+"/changeparameters.yasp", "w") #Output for Knob... g=open(options.path+"/changeparameters.knob", "w") f.write("#PLANE H\n") f.write("#UNIT RAD\n") g.write("* NAME DELTA \n") g.write("$ %s %le \n") plane = 'H' beam = '1' for corr in corrsYASP: print >>f, "#SETTING", corr, corrsYASP[corr] for corr in corrs: print >>g, "K"+corr, corrs[corr] f.close() g.close() if "LHC" in options.ACCEL: #.knob should always exist to be sent to LSA! system("cp "+options.path+"/changeparameters.tfs "+options.path+"/changeparameters.knob") # madx table b=twiss(options.path+"/changeparameters.tfs") mad=open(options.path+"/changeparameters.madx", "w") names=b.NAME delta=b.DELTA for i in range(len(names)): if cmp(delta[i],0)==1: mad.write(names[i]+" = "+names[i]+" + "+str(delta[i])+";\n"); else: mad.write(names[i]+" = "+names[i]+" "+str(delta[i])+";\n"); mad.write("return;"); mad.close() return 0
print "dCalH = ", calCH print "dCalV = ", calCV print "xCal = ", calX print "yCal = ", calY incrQ = 0.0001 # increment by which variable parameters will be changed FullResponse['incrQ'] = incrQ #Store this info for future use for vq in varQ: # loop over quads for strength; for dummy quad k0, loop over BPM calib writeparams(vq, incrQ) MADtwiss = justtwiss() d = 0 for vc in varCH: var = vq + '-' + vc orbit(varU, vc, MADtwiss) FullResponse[var] = twiss('twiss.resp.dat') print var d = d + 1 d = 0 for vc in varCV: var = vq + '-' + vc orbit(varU, vc, MADtwiss) FullResponse[var] = twiss('twiss.resp.dat') print var d = d + 1 pickle.dump(FullResponse, open('FullResponse', 'w'), -1)
from metaclass import twiss twissno = twiss('twiss_elements.dat') twissac = twiss('twiss_elements_ac.dat') filefile = open("acdipole.tfs", "w") betaxIP1 = twissno.BETX[twissno.indx['IP1']] - twissac.BETX[ twissac.indx['IP1']] betayIP1 = twissno.BETY[twissno.indx['IP1']] - twissac.BETY[ twissac.indx['IP1']] betaxIP2 = twissno.BETX[twissno.indx['IP2']] - twissac.BETX[ twissac.indx['IP2']] betayIP2 = twissno.BETY[twissno.indx['IP2']] - twissac.BETY[ twissac.indx['IP2']] betaxIP5 = twissno.BETX[twissno.indx['IP5']] - twissac.BETX[ twissac.indx['IP5']] betayIP5 = twissno.BETY[twissno.indx['IP5']] - twissac.BETY[ twissac.indx['IP5']] betaxIP8 = twissno.BETX[twissno.indx['IP8']] - twissac.BETX[ twissac.indx['IP8']] betayIP8 = twissno.BETY[twissno.indx['IP8']] - twissac.BETY[ twissac.indx['IP8']] print >> filefile, "* NAME DBETX DBETY" print >> filefile, "$ %s %le %le" print >> filefile, "IP1", betaxIP1, betayIP1
print >> f, "twiss, deltap= " + str( dpp) + ",file=\"" + path + "/twiss.dp+.0\";" print >> f, "twiss, deltap=-" + str( dpp) + ",file=\"" + path + "/twiss.dp-.0\";" f.close() print "Runing MADX" shell_command('/afs/cern.ch/group/si/slap/bin/madx < ' + path + '/job.iterate.madx') varsforloop = variables + ['0'] for i in range(0, len(varsforloop)): #Loop over variables var = varsforloop[i] print "Reading twiss.dp+." + var xp = twiss(path + "/twiss.dp+." + var) xp.Cmatrix() print "Reading twiss.dp-." + var xm = twiss(path + "/twiss.dp-." + var) xm.Cmatrix() # Initializing and Calculating chromatic coupling for every BPM xp.Cf1001r = [] xp.Cf1001i = [] xp.Cf1010r = [] xp.Cf1010i = [] for j in range(len(xp.NAME)): vvv = (xp.F1001R[j] - xm.F1001R[j]) / (2 * dpp) xp.Cf1001r.append(vvv) vvv = (xp.F1001I[j] - xm.F1001I[j]) / (2 * dpp)
print str_temp, str_temp.shape #----------------------------------------- IP ----------------------------------------------------- zero_for_conc = np.zeros(19) if str_temp.shape[0] != 1203: tt = np.concatenate((str_temp, zero_for_conc), axis=0) print "tt" str_temp = tt print str_temp #np.savetxt("file.txt",str_tempo, fmt='%.18e') #-------------------------- Get the RDT from twiss file ------------------------------------------ tab = twiss("twiss_coupling.twiss") tab.Cmatrix() #-------------------------- Assemble the rdt list to correct ------------------------------------- difference = np.array([tab.F1001R, tab.F1001I]) addit = np.array([tab.F1010R, tab.F1010I]) sol = np.concatenate((difference.flatten(), addit.flatten()), axis=0) print sol #----------------------------- Compute the solution -------------------------------------------- print "solve system" matrdt = np.genfromtxt( "/afs/cern.ch/work/s/saumon/__response_matrix/coupling_v205_10mm/rdt_arc_sy_ip_response_matrix_v205_10mm.txt", delimiter=",",
######################### def justtwiss(): ######################### global dictionary system('madx < job.twiss.madx > scum') #x=twiss('twiss.dat',dictionary) x = twiss('twiss.orbit.dat') return x ################### Main #execfile('mydictionary.py') twBPM = twiss('twiss.bpm.dat') bpms = twBPM.NAME execfile('AllLists.py') FullResponse = {} #Initialize FullResponse varQ = MQX() #Define variables varC = CorPartial() delta1 = zeros(len(varQ) * len(varC)) * 1.0 #Zero^th of the variables qc = 10 ic = 0.0001 incr = ones(len(varQ) * len(varC)) * ic #increment of variables FullResponse['qc'] = qc FullResponse['incr'] = incr #Store this info for future use
rmsphix = sqrt(sum((dphixa - dphixb)**2) / len(dphixa)) rmsphiy = sqrt(sum((dphiya - dphiyb)**2) / len(dphiya)) peakphix = max(abs(dphixa - dphixb)) peakphiy = max(abs(dphiya - dphiyb)) return array([ rmsx, rmsy, peakx, peaky, rmsphix, rmsphiy, peakphix, peakphiy, avebx, aveby, avebxr, avebyr, avedxbx, avedxbxr, avedx, avedxr, ndxbeat ]) #R=transpose(pickle.load(open('sensitivity_matrix','r'))) #zerovector=array(pickle.load(open('zerovector','r'))) #print R #print len(R), len(R[0]), len(variables) y = twiss('twiss.dat') beatbefore = [] beatafter = [] seedstart = 0 seedend = 1 sigmaphase = 0.25 / 360. for seed in range(seedstart, seedend): delta = zeros(210) * 1.0 # writeparams(delta) # writeseed(seed) # system('madx < job.err4example.madx > scum ') x = twiss('twiss.4G.dat') #dphix=[] #dphiy=[] #dphixb=[] #dphiyb=[]
FullResponse['delta1'] = delta1 #" " " #FullResponse['0']=justtwiss(delta1) #Response to Zero, base , nominal #Set-up the madx file for f = open('iter.madx', 'w') for i in range(0, len(delta1)): #Loop over variables delta = array(delta1) delta[i] = delta[i] + incr[i] var = variables[i] print >> f, var, "=", var, "+(", delta[i], ");" print >> f, "twiss, file=twiss." + var + ";" # print >>f, "system, \"gzip twiss."+var+" \";" print >> f, var, "=", var, "-(", delta[i], ");" print >> f, "twiss, file=twiss.0 ;" f.close() system('madx < job.iterate_couple.madx') for i in range(0, len(delta1)): #Loop over variables delta = array(delta1) delta[i] = delta[i] + incr[i] var = variables[i] print "Reading twiss." + var FullResponse[var] = twiss("twiss." + var) #os.system('rm twiss.'+var) FullResponse['0'] = twiss('twiss.0') #Response to Zero, base , nominal pickle.dump(FullResponse, open('FullResponse_couple.Numeric', 'w'), -1)
from metaclass import twiss import sys model = twiss('quad.tfs') bpminstall = open('bpms_install.madx', 'w') bpmseq = open('bpms_seqedit.madx', 'w') bpmptc = open('bpms_ptc.madx', 'w') names = model.NAME stot = model.S # phase advances ph = [] # pos phx = 0 phy = 0 summ = 0 for i in range(len(names) - 1): name1 = names[i] name2 = names[i + 1] s = stot[i] phx = (model.MUX[i + 1] - model.MUX[i] + phx) % 1 phy = (model.MUY[i + 1] - model.MUY[i] + phy) % 1 #print model.MUX[i+1]-model.MUX[i],model.NAME[i],model.NAME[i+1],model.S[i],model.S[i+1] #print "phx ",phx
f=open('iter.madx','w') for i in range(0,len(delta1)) : #Loop over variables delta=array(delta1) delta[i]=delta[i]+incr[i] var=variables[i] print >>f, var,"=", var, "+(",delta[i],");" print >>f, "twiss, file=twiss."+var+";" # print >>f, "system, \"gzip twiss."+var+" \";" print >>f, var,"=", var, "-(",delta[i],");" print >>f, "twiss, file=twiss.0 ;" f.close() system('madx < job.iterate.madx') for i in range(0,len(delta1)) : #Loop over variables delta=array(delta1) delta[i]=delta[i]+incr[i] var=variables[i] print "Reading twiss."+var FullResponse[var]=twiss("twiss."+var) #os.system('rm twiss.'+var) FullResponse['0']=twiss('twiss.0') #Response to Zero, base , nominal pickle.dump(FullResponse,open('FullResponse.Numeric','w'),-1)