diff --git a/examples/asc_test/master.py b/examples/asc_test/master.py index af5d878cfef39356282c2953f3523503d952f4ba..de2019588cf5bea43c0ad1b686a93cad351c35f3 100644 --- a/examples/asc_test/master.py +++ b/examples/asc_test/master.py @@ -1,3 +1,8 @@ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + from pykat import finesse from pykat.commands import * import copy @@ -7,87 +12,87 @@ import scipy.optimize def main(): - print """ - -------------------------------------------------------------- - Example file for using PyKat to automate Finesse simulations - Finesse: http://www.gwoptics.org/finesse - PyKat: http://www.gwoptics.org/pykat - - The file runs through the various Finesse simulations - to generate the Finesse results reported in the document: - `Comparing Finesse simulations, analytical solutions and OSCAR - simulations of Fabry-Perot alignment signals', LIGO-T1300345, - freely available online: http://arxiv.org/abs/1401.5727 - - This file is part of a collection; it outputs the results - shown the document's sections 3 and 4 and saves temporary - data and a new Finesse input file to be read by master2.py. - - Andreas Freise 16.01.2014 - -------------------------------------------------------------- - """ - - # for debugging we might need to see the temporay file: - kat = finesse.kat(tempdir=".",tempname="test") - kat.verbose = False - kat.loadKatFile('asc_base.kat') - kat.maxtem=3 - Lambda=1064.0e-9 - result = {} - - # defining variables as global for debugging - #global kat - #global out - #global result - - print "--------------------------------------------------------" - print " 1. tunes ETM position to find resonance" - kat.ETM.phi=resonance(kat) - - print "--------------------------------------------------------" - print " 2. print sideband and carrier powers/amplitudes" - powers(kat) - - print "--------------------------------------------------------" - print " 3. determine the optimal phase for the PDH signal" - (result['p_phase'], result['q_phase']) = pd_phase(kat) - - # setting demodulation phase - code_det = """ - pd1 PDrefl_p 9M 0 nWFS1 - scale 2 PDrefl_p - pd1 PDrefl_q 9M 90 nWFS1 - scale 2 PDrefl_q - """ - kat.parseKatCode(code_det) - kat.PDrefl_p.phi1=result['p_phase'] - kat.PDrefl_q.phi1=result['q_phase'] - - print "--------------------------------------------------------" - print " 4. adding a 0.1nm offset to ETM and compute PDH signal" - result['phi_tuned']=float(kat.ETM.phi) - result['phi_detuned'] = result['phi_tuned'] + 0.1/1064.0*360 - - kat.ETM.phi=result['phi_detuned'] - print " new ETM phi tuning = %g " % kat.ETM.phi - - (result['pd_p'], result['pd_q']) = pd_signal(kat) - print " PDH inphase = %e " % result['pd_p'] - print " PDH quadrtature = %e " % result['pd_q'] - - print "--------------------------------------------------------" - print " Saving results in temp. files to be read by master2.py" - tmpkatfile = "asc_base2.kat" - tmpresultfile = "myshelf1.dat" - print " kat object saved in: {0}".format(tmpkatfile) - print " current results saved in: {0}".format(tmpresultfile) - # first the current kat file - kat.saveScript(tmpkatfile) - # now the result variables: - tmpfile = shelve.open(tmpresultfile) - tmpfile['result']=result - tmpfile.close() - + print(""" + -------------------------------------------------------------- + Example file for using PyKat to automate Finesse simulations + Finesse: http://www.gwoptics.org/finesse + PyKat: http://www.gwoptics.org/pykat + + The file runs through the various Finesse simulations + to generate the Finesse results reported in the document: + `Comparing Finesse simulations, analytical solutions and OSCAR + simulations of Fabry-Perot alignment signals', LIGO-T1300345, + freely available online: http://arxiv.org/abs/1401.5727 + + This file is part of a collection; it outputs the results + shown the document's sections 3 and 4 and saves temporary + data and a new Finesse input file to be read by master2.py. + + Andreas Freise 16.01.2014 + -------------------------------------------------------------- + """) + + # for debugging we might need to see the temporay file: + kat = finesse.kat(tempdir=".",tempname="test") + kat.verbose = False + kat.loadKatFile('asc_base.kat') + kat.maxtem=3 + Lambda=1064.0e-9 + result = {} + + # defining variables as global for debugging + #global kat + #global out + #global result + + print("--------------------------------------------------------") + print(" 1. tunes ETM position to find resonance") + kat.ETM.phi=resonance(kat) + + print("--------------------------------------------------------") + print(" 2. print sideband and carrier powers/amplitudes") + powers(kat) + + print("--------------------------------------------------------") + print(" 3. determine the optimal phase for the PDH signal") + (result['p_phase'], result['q_phase']) = pd_phase(kat) + + # setting demodulation phase + code_det = """ + pd1 PDrefl_p 9M 0 nWFS1 + scale 2 PDrefl_p + pd1 PDrefl_q 9M 90 nWFS1 + scale 2 PDrefl_q + """ + kat.parseKatCode(code_det) + kat.PDrefl_p.phi1=result['p_phase'] + kat.PDrefl_q.phi1=result['q_phase'] + + print("--------------------------------------------------------") + print(" 4. adding a 0.1nm offset to ETM and compute PDH signal") + result['phi_tuned']=float(kat.ETM.phi) + result['phi_detuned'] = result['phi_tuned'] + 0.1/1064.0*360 + + kat.ETM.phi=result['phi_detuned'] + print(" new ETM phi tuning = %g " % kat.ETM.phi) + + (result['pd_p'], result['pd_q']) = pd_signal(kat) + print(" PDH inphase = %e " % result['pd_p']) + print(" PDH quadrtature = %e " % result['pd_q']) + + print("--------------------------------------------------------") + print(" Saving results in temp. files to be read by master2.py") + tmpkatfile = "asc_base2.kat" + tmpresultfile = "myshelf1.dat" + print(" kat object saved in: {0}".format(tmpkatfile)) + print(" current results saved in: {0}".format(tmpresultfile)) + # first the current kat file + kat.saveScript(tmpkatfile) + # now the result variables: + tmpfile = shelve.open(tmpresultfile, flag="c") + tmpfile[str('result')]=result + tmpfile.close() + #--------------------------------------------------------------------------- def pd_signal(tmpkat): @@ -102,106 +107,108 @@ def pd_signal(tmpkat): kat.noxaxis = True #global out out = kat.run() - print " Cavity power: {0:.6f}W".format(out.y[0,2]) + print(" Cavity power: {0:.6f}W".format(out.y[0,2])) return (out.y[0,0], out.y[0,1]) def pd_phase(tmpkat): - kat = copy.deepcopy(tmpkat) - - code_det = """ - pd1 PDrefl_q 9M 90 nWFS1 - """ - - kat.parseKatCode(code_det) - kat.noxaxis= True - - # function for root finding - def PD_q_test(x): - kat.PDrefl_q.phi1=x - out = kat.run() - print '\r root finding: function value %g ' % out.y, - sys.stdout.flush() - return out.y - - # do root finding - xtol=1e-8 - (result, info)=scipy.optimize.bisect(PD_q_test,80.0,100.0, xtol=xtol, maxiter=500, full_output=True) - - print "" - if info.converged: - p_phase=result-90.0 - q_phase=result - print " Root has been found:" - print " p_phase %8f" % (p_phase) - print " q_phase %8f" % (q_phase) - print " (%d iterations, %g tolerance)" % (info.iterations, xtol) - return (p_phase, q_phase) - else: - raise Exception("Root has not been found") - + kat = copy.deepcopy(tmpkat) + + code_det = """ + pd1 PDrefl_q 9M 90 nWFS1 + """ + + kat.parseKatCode(code_det) + kat.noxaxis= True + + # function for root finding + def PD_q_test(x): + kat.PDrefl_q.phi1=x + out = kat.run() + print('\r root finding: function value %g ' % out.y, end=' ') + sys.stdout.flush() + return out.y + + # do root finding + xtol=1e-8 + (result, info)=scipy.optimize.bisect(PD_q_test,80.0,100.0, xtol=xtol, maxiter=500, full_output=True) + + print("") + if info.converged: + p_phase=result-90.0 + q_phase=result + print(" Root has been found:") + print(" p_phase %8f" % (p_phase)) + print(" q_phase %8f" % (q_phase)) + print(" (%d iterations, %g tolerance)" % (info.iterations, xtol)) + return (p_phase, q_phase) + else: + raise Exception("Root has not been found") + def powers(tmpkat): - kat = copy.deepcopy(tmpkat) - - code1 = """ - ad EOM_up 9M nEOM1 - ad EOM_low -9M nEOM1 - pd cav_pow nITM2 - ad cav_c 0 nITM2 - ad WFS1_u 9M nWFS1 - ad WFS1_l -9M nWFS1 - ad WFS1_c 0 nWFS1 - ad WFS2_u 9M nWFS2 - ad WFS2_l -9M nWFS2 - ad WFS2_c 0 nWFS2 - noxaxis - """ + kat = copy.deepcopy(tmpkat) + + code1 = """ + ad EOM_up 9M nEOM1 + ad EOM_low -9M nEOM1 + pd cav_pow nITM2 + ad cav_c 0 nITM2 + ad WFS1_u 9M nWFS1 + ad WFS1_l -9M nWFS1 + ad WFS1_c 0 nWFS1 + ad WFS2_u 9M nWFS2 + ad WFS2_l -9M nWFS2 + ad WFS2_c 0 nWFS2 + noxaxis + """ - kat.parseKatCode(code1) + kat.parseKatCode(code1) - out = kat.run() + global out + out = kat.run() + + code1 = code1.split("\n") + for i in range(len(out.y)): + print(" %8s: %.4e" % (out.ylabels[i], out.y[0,i])) - code1 = code1.split("\n") - for i in range(len(out.y)): - print " %8s: %.4e" % (out.ylabels[i], out.y[0,i]) - def resonance(tmpkat): - kat = copy.deepcopy(tmpkat) - - code1 = """ - ad carr2 0 nITM1* - ad carr3 0 nITM2 - yaxis deg - """ - kat.parseKatCode(code1) - kat.noxaxis = True - - # function for root finding - def carrier_resonance(x): - kat.ETM.phi=x - out = kat.run() - phase = (out.y[0,0]-out.y[0,1]-90)%360-180 - print '\r root finding: function value %g ' % phase , - sys.stdout.flush() - return phase - - # do root finding - xtol=1e-8 - (result, info)=scipy.optimize.bisect(carrier_resonance,0.0,40.0, xtol=xtol, maxiter=500, full_output=True) - - print "" - if info.converged: - print " Root has been found:" - print " ETM phi %8f" % (result) - print " (%d iterations, %g tolerance)" % (info.iterations, xtol) - return result - else: - raise Exception(" Root has not been found") - + kat = copy.deepcopy(tmpkat) + + code1 = """ + ad carr2 0 nITM1* + ad carr3 0 nITM2 + yaxis deg + """ + kat.parseKatCode(code1) + kat.noxaxis = True + + # function for root finding + def carrier_resonance(x): + kat.ETM.phi=x + global out + out = kat.run() + phase = (out.y[0,0]-out.y[0,1]-90)%360-180 + print('\r root finding: function value %g ' % phase, end=' ') + sys.stdout.flush() + return phase + + # do root finding + xtol=1e-8 + (result, info)=scipy.optimize.bisect(carrier_resonance,0.0,40.0, xtol=xtol, maxiter=500, full_output=True) + + print("") + if info.converged: + print(" Root has been found:") + print(" ETM phi %8f" % (result)) + print(" (%d iterations, %g tolerance)" % (info.iterations, xtol)) + return result + else: + raise Exception(" Root has not been found") + if __name__ == '__main__': - main() + main() diff --git a/examples/asc_test/master1.py b/examples/asc_test/master1.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/examples/asc_test/master1py b/examples/asc_test/master1py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/examples/asc_test/master2.py b/examples/asc_test/master2.py index ec4fb5e7e730b822e2eba38a3aa1b5d11346c39c..9f28f9eab7b2922090c4eaf2362edc923a9a09b7 100644 --- a/examples/asc_test/master2.py +++ b/examples/asc_test/master2.py @@ -1,3 +1,8 @@ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + from pykat import finesse from pykat.commands import * import pylab as pl @@ -10,343 +15,344 @@ import sys def main(): - print """ - -------------------------------------------------------------- - Example file for using PyKat to automate Finesse simulations - Finesse: http://www.gwoptics.org/finesse - PyKat: http://www.gwoptics.org/pykat - - The file runs through the various Finesse simulations - to generate the Finesse results reported in the document: - `Comparing Finesse simulations, analytical solutions and OSCAR - simulations of Fabry-Perot alignment signals', LIGO-T1300345, - freely available online: http://arxiv.org/abs/1401.5727 - - This file is part of a collection; it outputs the results - shown the document's sections 5 and 6 and saves temporary - data and a new Finesse input file to be read by master3.py, - and master4.py. - - Andreas Freise 16.01.2014 - -------------------------------------------------------------- - """ - - # shall we clear the workspace? - # %reset -f - - # making these global during testing and debugging - #global kat - #global out - - kat = finesse.kat(tempdir=".",tempname="test") - kat.verbose = False - - tmpresultfile = 'myshelf1.dat' - - # loading data saved by master.py - kat.loadKatFile('asc_base2.kat') - try: - tmpfile = shelve.open(tmpresultfile) - result=tmpfile['result'] - tmpfile.close() - except: raise Exception("Could not open temprary results file {0}".format(tmpresultfile)) - - # overwriting some variables - kat.maxtem=3 - Lambda=1064.0e-9 - - # disable PDH photo diode as we won't need it for most of this - kat.PDrefl_p.enabled = False - kat.PDrefl_q.enabled = False - - # simulating a tuned cavity - kat.ETM.phi=result['phi_tuned'] - - print "--------------------------------------------------------" - print " 5. checking wavefronts for ITM/ETM tilt of 0.1nrad" - tilt(kat) - - print "--------------------------------------------------------" - print " 6. compute beam tilt from beam propogation" - gravity_tilt(kat) - - print "--------------------------------------------------------" - print " 7. compute optimal demodulation phase of WFS1 and WFS2" - - # adding wave front sensors to global kat object, will need them later - # on as well. - - code_WFS1 = """ - pd1 WFS1_I 9M 0 nWFS1 - pdtype WFS1_I y-split - pd1 WFS1_Q 9M 90 nWFS1 - pdtype WFS1_Q y-split - scale 2 WFS1_I % compensate the 0.5 gain of the demodulation - scale 2 WFS1_Q % compensate the 0.5 gain of the demodulation - """ - code_WFS2 = """ - pd1 WFS2_I 9M 0 nWFS2 - pdtype WFS2_I y-split - pd1 WFS2_Q 9M 90 nWFS2 - pdtype WFS2_Q y-split - scale 2 WFS2_I % compensate the 0.5 gain of the demodulation - scale 2 WFS2_Q % compensate the 0.5 gain of the demodulation - """ - kat.parseKatCode(code_WFS1) - kat.parseKatCode(code_WFS2) - - (WFS1_phase, WFS2_phase) = asc_phases(kat) - kat.WFS1_I.phi1=WFS1_phase - kat.WFS1_Q.phi1=WFS1_phase+90.0 - kat.WFS2_I.phi1=WFS2_phase - kat.WFS2_Q.phi1=WFS2_phase+90.0 - result['WFS1_phase']=WFS1_phase - result['WFS2_phase']=WFS2_phase - - print "--------------------------------------------------------" - print " 8. compute ASC signal matrix at WFS1 and WFS2" - signal = asc_signal(kat) - - print "--------------------------------------------------------" - print " Saving results in temp. files to be read by master3.py" - # re-enable PDH photo diode for savinf - kat.PDrefl_p.enabled = True - kat.PDrefl_q.enabled = True - - tmpkatfile = "asc_base3.kat" - tmpresultfile = "myshelf2.dat" - print " kat object saved in: {0}".format(tmpkatfile) - print " current results saved in: {0}".format(tmpresultfile) - # first the current kat file - kat.saveScript(tmpkatfile) - # now the result variables: - tmpfile = shelve.open(tmpresultfile) - tmpfile['result']=result - tmpfile.close() + print(""" + -------------------------------------------------------------- + Example file for using PyKat to automate Finesse simulations + Finesse: http://www.gwoptics.org/finesse + PyKat: http://www.gwoptics.org/pykat + + The file runs through the various Finesse simulations + to generate the Finesse results reported in the document: + `Comparing Finesse simulations, analytical solutions and OSCAR + simulations of Fabry-Perot alignment signals', LIGO-T1300345, + freely available online: http://arxiv.org/abs/1401.5727 + + This file is part of a collection; it outputs the results + shown the document's sections 5 and 6 and saves temporary + data and a new Finesse input file to be read by master3.py, + and master4.py. + + Andreas Freise 16.01.2014 + -------------------------------------------------------------- + """) + + # shall we clear the workspace? + # %reset -f + + # making these global during testing and debugging + #global kat + #global out + + kat = finesse.kat(tempdir=".",tempname="test") + kat.verbose = False + + tmpresultfile = "myshelf1.dat" + + # loading data saved by master.py + kat.loadKatFile('asc_base2.kat') + try: + tmpfile = shelve.open(tmpresultfile, flag="c") + result=tmpfile[str('result')] + tmpfile.close() + except: raise Exception("Could not open temprary results file {0}".format(tmpresultfile)) + + # overwriting some variables + kat.maxtem=3 + Lambda=1064.0e-9 + + # disable PDH photo diode as we won't need it for most of this + kat.PDrefl_p.enabled = False + kat.PDrefl_q.enabled = False + + # simulating a tuned cavity + kat.ETM.phi=result['phi_tuned'] + + print("--------------------------------------------------------") + print(" 5. checking wavefronts for ITM/ETM tilt of 0.1nrad") + tilt(kat) + + print("--------------------------------------------------------") + print(" 6. compute beam tilt from beam propogation") + gravity_tilt(kat) + + print("--------------------------------------------------------") + print(" 7. compute optimal demodulation phase of WFS1 and WFS2") + + # adding wave front sensors to global kat object, will need them later + # on as well. + + code_WFS1 = """ + pd1 WFS1_I 9M 0 nWFS1 + pdtype WFS1_I y-split + pd1 WFS1_Q 9M 90 nWFS1 + pdtype WFS1_Q y-split + scale 2 WFS1_I % compensate the 0.5 gain of the demodulation + scale 2 WFS1_Q % compensate the 0.5 gain of the demodulation + """ + code_WFS2 = """ + pd1 WFS2_I 9M 0 nWFS2 + pdtype WFS2_I y-split + pd1 WFS2_Q 9M 90 nWFS2 + pdtype WFS2_Q y-split + scale 2 WFS2_I % compensate the 0.5 gain of the demodulation + scale 2 WFS2_Q % compensate the 0.5 gain of the demodulation + """ + kat.parseKatCode(code_WFS1) + kat.parseKatCode(code_WFS2) + + (WFS1_phase, WFS2_phase) = asc_phases(kat) + kat.WFS1_I.phi1=WFS1_phase + kat.WFS1_Q.phi1=WFS1_phase+90.0 + kat.WFS2_I.phi1=WFS2_phase + kat.WFS2_Q.phi1=WFS2_phase+90.0 + result['WFS1_phase']=WFS1_phase + result['WFS2_phase']=WFS2_phase + + print("--------------------------------------------------------") + print(" 8. compute ASC signal matrix at WFS1 and WFS2") + signal = asc_signal(kat) + + print("--------------------------------------------------------") + print(" Saving results in temp. files to be read by master3.py") + # re-enable PDH photo diode for savinf + kat.PDrefl_p.enabled = True + kat.PDrefl_q.enabled = True + + tmpkatfile = "asc_base3.kat" + tmpresultfile = "myshelf2.dat" + print(" kat object saved in: {0}".format(tmpkatfile)) + print(" current results saved in: {0}".format(tmpresultfile)) + # first the current kat file + kat.saveScript(tmpkatfile) + # now the result variables: + tmpfile = shelve.open(tmpresultfile) + tmpfile[str('result')]=result + tmpfile.close() #----------------------------------------------------------------------------------- def asc_signal(tmpkat): - kat = copy.deepcopy(tmpkat) - - code_lock = """ - set err PDrefl_p re - lock z $err 900 1p - put* ETM phi $z - noplot z - """ - - kat.parseKatCode(code_lock) - # need to re-enable the photo diode for lock - kat.PDrefl_p.enabled = True - - kat.parseKatCode('yaxis abs') - kat.noxaxis = True - kat.maxtem=1 - - signal=np.zeros((2, 2)) - kat.ITM.ybeta=1e-10 - kat.ETM.ybeta=0.0 - out = kat.run() - signal[0,0] = out["WFS1_I"] - signal[1,0] = out["WFS2_I"] - - - kat.ITM.ybeta=0.0 - kat.ETM.ybeta=-1e-10 - out = kat.run() - signal[0,1] = out["WFS1_I"] - signal[1,1] = out["WFS2_I"] - signal = signal *1e10 - sensors=('WFS1', 'WFS2') - mirrors=('ITM', 'ETM') - print " ASC Matrix:" - for i in range(2): - print " ", sensors[i], " ", - for j in range(2): - print "%12.10g" % signal[i,j], - print mirrors[i] - return signal - - + kat = copy.deepcopy(tmpkat) + + code_lock = """ + set err PDrefl_p re + lock z $err 900 1p + put* ETM phi $z + noplot z + """ + + kat.parseKatCode(code_lock) + # need to re-enable the photo diode for lock + kat.PDrefl_p.enabled = True + + kat.parseKatCode('yaxis abs') + kat.noxaxis = True + kat.maxtem=1 + + signal=np.zeros((2, 2)) + kat.ITM.ybeta=1e-10 + kat.ETM.ybeta=0.0 + out = kat.run() + signal[0,0] = out["WFS1_I"] + signal[1,0] = out["WFS2_I"] + + + kat.ITM.ybeta=0.0 + kat.ETM.ybeta=-1e-10 + out = kat.run() + signal[0,1] = out["WFS1_I"] + signal[1,1] = out["WFS2_I"] + signal = signal *1e10 + sensors=('WFS1', 'WFS2') + mirrors=('ITM', 'ETM') + print(" ASC Matrix:") + for i in range(2): + print(" ", sensors[i], " ", end=' ') + for j in range(2): + print("%12.10g" % signal[i,j], end=' ') + print(mirrors[i]) + return signal + + def asc_phases(tmpkat): - kat = copy.deepcopy(tmpkat) - - kat.parseKatCode('yaxis abs') - kat.noxaxis = True - kat.maxtem=1 - - def demod_phase1(x): - kat.WFS1_I.phi1=x[0] - out = kat.run() - signal = out["WFS1_I"] - print '\r minimising: function value %g ' % signal , - sys.stdout.flush() - return -1*abs(signal) - - def demod_phase2(x): - kat.WFS2_I.phi1=x[0] - out = kat.run() - signal = out["WFS2_I"] - print '\r minimising: function value %g ' % signal , - sys.stdout.flush() - return -1*abs(signal) - - kat.ITM.ybeta=1e-10 - kat.ETM.ybeta=0.0 - res = fmin(demod_phase1, [0.0], xtol=1e-8, disp=False) - WFS1_phase = res[0] - print "" - print " WFS1 demod phase : %.10g deg" % WFS1_phase - - kat.ITM.ybeta=0.0 - kat.ETM.ybeta=-1e-10 - res = fmin(demod_phase2, [0.0], xtol=1e-8, disp=False) - WFS2_phase = res[0] - print "" - print " WFS2 demod phase : %.10g deg" % WFS2_phase - return(WFS1_phase, WFS2_phase) - + kat = copy.deepcopy(tmpkat) + + kat.parseKatCode('yaxis abs') + kat.noxaxis = True + kat.maxtem=1 + + def demod_phase1(x): + kat.WFS1_I.phi1=x[0] + out = kat.run() + signal = out["WFS1_I"] + print('\r minimising: function value %g ' % signal, end=' ') + sys.stdout.flush() + return -1*abs(signal) + + def demod_phase2(x): + kat.WFS2_I.phi1=x[0] + out = kat.run() + signal = out["WFS2_I"] + print('\r minimising: function value %g ' % signal, end=' ') + sys.stdout.flush() + return -1*abs(signal) + + kat.ITM.ybeta=1e-10 + kat.ETM.ybeta=0.0 + res = fmin(demod_phase1, [0.0], xtol=1e-8, disp=False) + WFS1_phase = res[0] + print("") + print(" WFS1 demod phase : %.10g deg" % WFS1_phase) + + kat.ITM.ybeta=0.0 + kat.ETM.ybeta=-1e-10 + res = fmin(demod_phase2, [0.0], xtol=1e-8, disp=False) + WFS2_phase = res[0] + print("") + print(" WFS2 demod phase : %.10g deg" % WFS2_phase) + return(WFS1_phase, WFS2_phase) + def gravity_tilt(tmpkat): - kat = copy.deepcopy(tmpkat) - - def compute_gravity_tilt(tmpkat): - kat = copy.deepcopy(tmpkat) - out = kat.run() - - y1 = out["b1"] - y2 = out["b1_1k"] - # shift of beam center on detector 1 (as m/w0y) - x1 = np.sum(out.x*y1)/np.sum(y1) - # shift of beam center on detector 2 (as m/w0y) - x2 = np.sum(out.x*y2)/np.sum(y2) - # calibrate this in meter by mutliplying with w0y - # and compute the angle geometrically - w0=out["w0y"][0] - detector_distance = 1000.0 - tilt=w0*(x2-x1)/detector_distance - print " Wavefront tilt : %g nrad" % tilt - - code_WFS1 = """ - beam b1 nWFS1 - beam b1_1k nL1_in - bp w0y y w0 nWFS1 - """ - - code_WFS2 = """ - m md 0 1 0 nWFS2 nWFS2b - s sd 1k nWFS2b nWFS2c - beam b1 nWFS2* - beam b1_1k nWFS2c - bp w0y y w0 nWFS2 - """ - - code_xaxis= """ - xaxis b1 y lin -40 40 800 - put b1_1k y $x1 - yaxis abs - """ - print " WFS1:" - print " ITM ybeta 0.1nm" - kat.parseKatCode(code_WFS1) - kat.parseKatCode(code_xaxis) - kat.spo1.L=1000.0 - kat.ITM.ybeta=1e-10 - kat.ETM.ybeta=0.0 - compute_gravity_tilt(kat) - print " ETM ybeta -0.1nm" - kat.ITM.ybeta=0.0 - kat.ETM.ybeta=-1e-10 - compute_gravity_tilt(kat) - - print " WFS2:" - print " ITM ybeta 0.1nm" - kat = copy.deepcopy(tmpkat) - kat.parseKatCode(code_WFS2) - kat.parseKatCode(code_xaxis) - kat.spo1.L=1.0e-9 - kat.ITM.ybeta=1e-10 - kat.ETM.ybeta=0.0 - compute_gravity_tilt(kat) - print " ETM ybeta -0.1nm" - kat.ITM.ybeta=0.0 - kat.ETM.ybeta=-1e-10 - compute_gravity_tilt(kat) - - + kat = copy.deepcopy(tmpkat) + + def compute_gravity_tilt(tmpkat): + kat = copy.deepcopy(tmpkat) + out = kat.run() + + y1 = out["b1"] + y2 = out["b1_1k"] + # shift of beam center on detector 1 (as m/w0y) + x1 = np.sum(out.x*y1)/np.sum(y1) + # shift of beam center on detector 2 (as m/w0y) + x2 = np.sum(out.x*y2)/np.sum(y2) + # calibrate this in meter by mutliplying with w0y + # and compute the angle geometrically + w0=out["w0y"][0] + detector_distance = 1000.0 + tilt=w0*(x2-x1)/detector_distance + print(" Wavefront tilt : %g nrad" % tilt) + + code_WFS1 = """ + beam b1 nWFS1 + beam b1_1k nL1_in + bp w0y y w0 nWFS1 + """ + + code_WFS2 = """ + m md 0 1 0 nWFS2 nWFS2b + s sd 1k nWFS2b nWFS2c + beam b1 nWFS2* + beam b1_1k nWFS2c + bp w0y y w0 nWFS2 + """ + + code_xaxis= """ + xaxis b1 y lin -40 40 800 + put b1_1k y $x1 + yaxis abs + """ + print(" WFS1:") + print(" ITM ybeta 0.1nm") + kat.parseKatCode(code_WFS1) + kat.parseKatCode(code_xaxis) + kat.spo1.L=1000.0 + kat.ITM.ybeta=1e-10 + kat.ETM.ybeta=0.0 + compute_gravity_tilt(kat) + print(" ETM ybeta -0.1nm") + kat.ITM.ybeta=0.0 + kat.ETM.ybeta=-1e-10 + compute_gravity_tilt(kat) + + print(" WFS2:") + print(" ITM ybeta 0.1nm") + kat = copy.deepcopy(tmpkat) + kat.parseKatCode(code_WFS2) + kat.parseKatCode(code_xaxis) + kat.spo1.L=1.0e-9 + kat.ITM.ybeta=1e-10 + kat.ETM.ybeta=0.0 + compute_gravity_tilt(kat) + print(" ETM ybeta -0.1nm") + kat.ITM.ybeta=0.0 + kat.ETM.ybeta=-1e-10 + compute_gravity_tilt(kat) + + def tilt(tmpkat): - kat = copy.deepcopy(tmpkat) - - def compute_tilt(tmpkat): - kat = copy.deepcopy(tmpkat) - global out - out = kat.run() - - # compute data x range in meters - beamsize = out["w0y"][0] - xrange = beamsize*(out.x.max()-out.x.min()) - stepsize=xrange/(len(out.x)-1) - print " Beamsize %e m" % beamsize - print " Measurement range: %e m, stepszie: %e m" % (xrange, stepsize) - # compute difference in angle between wavefront of carrier and sidebands - diff_l = (out["PDrefl_low"]-out["PDrefl_car"])/stepsize - diff_u = (out["PDrefl_up"]-out["PDrefl_car"])/stepsize - tilt_l = diff_l[1:-1]-diff_l[0:-2] - tilt_u = diff_u[1:-1]-diff_u[0:-2] - print " Tilt (upper - car), mean: %e m/deg, stddev %e m/deg" % (np.mean(tilt_u), np.std(tilt_u)) - print " Tilt (lower - car), mean: %e m/deg, stddev %e m/deg" % (np.mean(tilt_l), np.std(tilt_l)) - return (np.mean(tilt_l), np.mean(tilt_u)) - - code_WFS1 = """ - beam PDrefl_car 0 nWFS1 - beam PDrefl_up 9M nWFS1 - beam PDrefl_low -9M nWFS1 - bp w0y y w0 nWFS1 - """ - - code_WFS2 = """ - beam PDrefl_car 0 nWFS2 - beam PDrefl_up 9M nWFS2 - beam PDrefl_low -9M nWFS2 - bp w0y y w0 nWFS2 - """ - code_comm = """ - xaxis PDrefl_car y lin -1 1 100 - put PDrefl_up y $x1 - put PDrefl_low y $x1 - yaxis abs:deg - """ - - print " WFS1:" - print " ITM ybeta 0.1nm" - kat.parseKatCode(code_comm) - kat.parseKatCode(code_WFS1) - kat.ITM.ybeta=1e-10 - kat.ETM.ybeta=0.0 - (a1, a2) = compute_tilt(kat) - - print " ETM ybeta -0.1nm" - kat.ITM.ybeta=0.0 - kat.ETM.ybeta=-1e-10 - (a3, a4) = compute_tilt(kat) - - print " WFS2:" - print " ITM ybeta 0.1nm" - kat = copy.deepcopy(tmpkat) - kat.parseKatCode(code_comm) - kat.parseKatCode(code_WFS2) - kat.ITM.ybeta=1e-10 - kat.ETM.ybeta=0.0 - (a5, a6) = compute_tilt(kat) - - print " ETM ybeta -0.1nm" - kat.ITM.ybeta=0.0 - kat.ETM.ybeta=-1e-10 - (a6, a7) = compute_tilt(kat) - - return - + kat = copy.deepcopy(tmpkat) + + def compute_tilt(tmpkat): + global kat + kat = copy.deepcopy(tmpkat) + global out + out = kat.run() + + # compute data x range in meters + beamsize = out["w0y"][0].real + xrange = beamsize*(out.x.max()-out.x.min()) + stepsize=xrange/(len(out.x)-1) + print(" Beamsize %e m" % beamsize) + print(" Measurement range: %e m, stepszie: %e m" % (xrange, stepsize)) + # compute difference in angle between wavefront of carrier and sidebands + diff_l = (out["PDrefl_low"].real-out["PDrefl_car"].real)/stepsize + diff_u = (out["PDrefl_up"].real-out["PDrefl_car"].real)/stepsize + tilt_l = diff_l[1:-1]-diff_l[0:-2] + tilt_u = diff_u[1:-1]-diff_u[0:-2] + print(" Tilt (upper - car), mean: %e m/deg, stddev %e m/deg" % (np.mean(tilt_u), np.std(tilt_u))) + print(" Tilt (lower - car), mean: %e m/deg, stddev %e m/deg" % (np.mean(tilt_l), np.std(tilt_l))) + return (np.mean(tilt_l), np.mean(tilt_u)) + + code_WFS1 = """ + beam PDrefl_car 0 nWFS1 + beam PDrefl_up 9M nWFS1 + beam PDrefl_low -9M nWFS1 + bp w0y y w0 nWFS1 + """ + + code_WFS2 = """ + beam PDrefl_car 0 nWFS2 + beam PDrefl_up 9M nWFS2 + beam PDrefl_low -9M nWFS2 + bp w0y y w0 nWFS2 + """ + code_comm = """ + xaxis PDrefl_car y lin -1 1 100 + put PDrefl_up y $x1 + put PDrefl_low y $x1 + yaxis abs:deg + """ + + print(" WFS1:") + print(" ITM ybeta 0.1nm") + kat.parseKatCode(code_comm) + kat.parseKatCode(code_WFS1) + kat.ITM.ybeta=1e-10 + kat.ETM.ybeta=0.0 + (a1, a2) = compute_tilt(kat) + + print(" ETM ybeta -0.1nm") + kat.ITM.ybeta=0.0 + kat.ETM.ybeta=-1e-10 + (a3, a4) = compute_tilt(kat) + + print(" WFS2:") + print(" ITM ybeta 0.1nm") + kat = copy.deepcopy(tmpkat) + kat.parseKatCode(code_comm) + kat.parseKatCode(code_WFS2) + kat.ITM.ybeta=1e-10 + kat.ETM.ybeta=0.0 + (a5, a6) = compute_tilt(kat) + + print(" ETM ybeta -0.1nm") + kat.ITM.ybeta=0.0 + kat.ETM.ybeta=-1e-10 + (a6, a7) = compute_tilt(kat) + + return + if __name__ == '__main__': - main() + main() diff --git a/examples/asc_test/master3.py b/examples/asc_test/master3.py index fac597ec5f85c380aba2446d30542dd1648686f2..e17826854389be086d54e1c2d598df30cfe32d80 100644 --- a/examples/asc_test/master3.py +++ b/examples/asc_test/master3.py @@ -1,3 +1,8 @@ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + from pykat import finesse from pykat.commands import * import numpy as np @@ -8,7 +13,7 @@ import shutil def main(): - print """ + print(""" -------------------------------------------------------------- Example file for using PyKat to automate Finesse simulations Finesse: http://www.gwoptics.org/finesse @@ -26,7 +31,7 @@ def main(): Andreas Freise 16.01.2014 -------------------------------------------------------------- - """ + """) # shall we clear the workspace? # %reset -f @@ -44,7 +49,7 @@ def main(): kat.loadKatFile('asc_base3.kat') try: tmpfile = shelve.open(tmpresultfile) - result=tmpfile['result'] + result=tmpfile[str('result')] tmpfile.close() except: raise Exception("Could not open temprary results file {0}".format(tmpresultfile)) @@ -52,12 +57,12 @@ def main(): kat.WFS1_Q.enables = False kat.WFS2_Q.enables = False - print "--------------------------------------------------------" - print " 9. ASC signals for large misalignments (ITM)" + print("--------------------------------------------------------") + print(" 9. ASC signals for large misalignments (ITM)") asc_large(kat, 'ITM') - print "--------------------------------------------------------" - print " 10. ASC signals for large misalignments (ETM)" + print("--------------------------------------------------------") + print(" 10. ASC signals for large misalignments (ETM)") asc_large(kat, 'ETM') @@ -90,17 +95,17 @@ def asc_large(tmpkat, mir_name): for tem in maxtems: done_maxtems.append(tem) - print " Calculating maxtem = %d " % tem + print(" Calculating maxtem = %d " % tem) kat.maxtem = tem out[str(tem)] = kat.run(printout=0,printerr=1) import os.path if os.path.isfile(tmpfilename): shutil.copyfile(tmpfilename, backupname) - print " current results saved in: {0}".format(tmpfilename) + print(" current results saved in: {0}".format(tmpfilename)) tmpfile = shelve.open(tmpfilename) - tmpfile['out']=out - tmpfile['maxtems']=done_maxtems + tmpfile[str('out')]=out + tmpfile[str('maxtems')]=done_maxtems tmpfile.close() diff --git a/examples/asc_test/master3_plot.py b/examples/asc_test/master3_plot.py index 6f64ce987a473e36d3005111e4969ef833d23e18..b3f73a94d05f79f1c3425c276fe269f9d3823073 100644 --- a/examples/asc_test/master3_plot.py +++ b/examples/asc_test/master3_plot.py @@ -1,3 +1,8 @@ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + from pykat import finesse from pykat.commands import * import pylab as pl @@ -16,7 +21,7 @@ def printPDF(self, filename): pdfp.close() def main(): - print """ + print(""" -------------------------------------------------------------- Example file for using PyKat to automate Finesse simulations Finesse: http://www.gwoptics.org/finesse @@ -26,7 +31,7 @@ def main(): Andreas Freise 16.01.2014 -------------------------------------------------------------- - """ + """) # shall we clear the workspace? # %reset -f @@ -38,8 +43,8 @@ def main(): #global out #global result - print "--------------------------------------------------------" - print " Plotting ASC signals for large misalignments" + print("--------------------------------------------------------") + print(" Plotting ASC signals for large misalignments") asc_large('ITM') asc_large('ETM') @@ -57,8 +62,8 @@ def asc_large(mir_name): try: tmpfile = shelve.open(tmpfilename) - out=tmpfile['out'] - maxtems=tmpfile['maxtems'] + out=tmpfile[str('out')] + maxtems=tmpfile[str('maxtems')] tmpfile.close() except: raise Exception("Could not open temprary results file {0}".format(tmpfilename)) diff --git a/examples/asc_test/master4.py b/examples/asc_test/master4.py index 9ec50ac7052e7676c17087357c8473a17f39beff..2db0e7644df93538cd31ef5b048e1eb8acf66ae3 100644 --- a/examples/asc_test/master4.py +++ b/examples/asc_test/master4.py @@ -1,6 +1,11 @@ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + from pykat import finesse from pykat.commands import * -from pykat.optics.gaussian_beams import gauss_param +from pykat.optics.gaussian_beams import beam_param import pylab as pl import scipy @@ -19,7 +24,7 @@ def set_thermal_lens(kat, f): def main(): - print """ + print(""" -------------------------------------------------------------- Example file for using PyKat to automate Finesse simulations Finesse: http://www.gwoptics.org/finesse @@ -37,7 +42,7 @@ def main(): Andreas Freise 16.01.2014 -------------------------------------------------------------- - """ + """) # shall we clear the workspace? # %reset -f @@ -55,7 +60,7 @@ def main(): kat.loadKatFile('asc_base3.kat') try: tmpfile = shelve.open(tmpresultfile) - result=tmpfile['result'] + result=tmpfile[str('result')] tmpfile.close() except: raise Exception("Could not open temprary results file {0}".format(tmpresultfile)) @@ -69,9 +74,10 @@ def main(): kat.ETM.phi=result['phi_tuned'] - print "--------------------------------------------------------" - print " 11. Do beam tracing to measure beam parameters" + print("--------------------------------------------------------") + print(" 11. Do beam tracing to measure beam parameters") # get beam parameters at nodes: "npsl", "nITM1", "nWFS1", "nWFS2", "npo2" + global beam1, beam2, beam3 beam1 = get_qs(kat,1e13) beam2 = get_qs(kat,50e3) beam3 = get_qs(kat,5e3) @@ -80,7 +86,6 @@ def main(): kat.psl.npsl.node.setGauss(kat.psl, beam1[0]) kat.parseKatCode("startnode npsl") - global beam1, beam2, beam3 # if we use bs-based cavity we try to set good beam # parameter for reflected beam, first by @@ -88,32 +93,32 @@ def main(): x1=0.70 x2=0.30 if "ITM_TL_r" in kat._kat__components: - beam50 = gauss_param(z=(x1*beam1[1].z+x2*beam2[1].z), w0=(x1*beam1[1].w0+x2*beam2[1].w0)) - beam5 = gauss_param(z=(x1*beam1[1].z+x2*beam3[1].z), w0=(x1*beam1[1].w0+x2*beam3[1].w0)) + beam50 = beam_param(z=(x1*beam1[1].z+x2*beam2[1].z), w0=(x1*beam1[1].w0+x2*beam2[1].w0)) + beam5 = beam_param(z=(x1*beam1[1].z+x2*beam3[1].z), w0=(x1*beam1[1].w0+x2*beam3[1].w0)) node_text = "at ITM->nITM1r" t_comp=kat.ITM t_node=kat.ITM.nITM1r else: - beam50 = gauss_param(z=(x1*beam1[4].z+x2*beam2[4].z), w0=(x1*beam1[4].w0+x2*beam2[4].w0)) - beam5 = gauss_param(z=(x1*beam1[4].z+x2*beam3[4].z), w0=(x1*beam1[4].w0+x2*beam3[4].w0)) + beam50 = beam_param(z=(x1*beam1[4].z+x2*beam2[4].z), w0=(x1*beam1[4].w0+x2*beam2[4].w0)) + beam5 = beam_param(z=(x1*beam1[4].z+x2*beam3[4].z), w0=(x1*beam1[4].w0+x2*beam3[4].w0)) node_text = "at s2->npo2" t_comp=kat.s2 t_node=kat.s2.npo2 kat = set_thermal_lens(kat,50e3) - print "--------------------------------------------------------" - print " 12. computing beam tilt with thermal lens (f={0})".format(kat.ITM_TL.f) + print("--------------------------------------------------------") + print(" 12. computing beam tilt with thermal lens (f={0})".format(kat.ITM_TL.f)) - print " Setting compromise beam parameter {0}: w0={1}, z={2}".format(node_text, beam50.w0, beam50.z) + print(" Setting compromise beam parameter {0}: w0={1}, z={2}".format(node_text, beam50.w0, beam50.z)) t_node.node.setGauss(t_comp, beam50) kat.maxtem=8 - print " Calculating maxtem = %d " % kat.maxtem + print(" Calculating maxtem = %d " % kat.maxtem) tmp = gravity_tilt(kat) kat = set_thermal_lens(kat,5e3) - print "--------------------------------------------------------" - print " 13. computing beam tilt with thermal lens (f={0})".format(kat.ITM_TL.f) - print " Setting compromise beam parameter {0}: w0={1}, z={2}".format(node_text, beam5.w0, beam5.z) + print("--------------------------------------------------------") + print(" 13. computing beam tilt with thermal lens (f={0})".format(kat.ITM_TL.f)) + print(" Setting compromise beam parameter {0}: w0={1}, z={2}".format(node_text, beam5.w0, beam5.z)) t_node.node.setGauss(t_comp, beam5) #maxtems = [1, 3, 5, 9, 11, 13, 15, 19, 23, 25, 27, 29] maxtems = [1, 3, 5, 7] @@ -124,16 +129,16 @@ def main(): kat.WFS2_I.enabled = True kat = set_thermal_lens(kat,50e3) - print "--------------------------------------------------------" - print " 12. computing alignment signal with thermal lens (f={0})".format(kat.ITM_TL.f) + print("--------------------------------------------------------") + print(" 12. computing alignment signal with thermal lens (f={0})".format(kat.ITM_TL.f)) t_node.node.setGauss(t_comp, beam50) #maxtems = [1, 3, 5, 9, 11, 13, 15, 17, 19] maxtems = [1, 3, 5, 7] converge_asc(kat, maxtems, 'asc_signals_50.txt') kat = set_thermal_lens(kat,5e3) - print "--------------------------------------------------------" - print " 13. computing alignment signal with thermal lens (f={0})".format(kat.ITM_TL.f) + print("--------------------------------------------------------") + print(" 13. computing alignment signal with thermal lens (f={0})".format(kat.ITM_TL.f)) t_node.node.setGauss(t_comp, beam5) #maxtems = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31] maxtems = [1, 3, 5, 7] @@ -146,12 +151,12 @@ def converge_asc(tmpkat, maxtems, filename): savedata = np.zeros([len(maxtems),5]) for idx, tem in enumerate(maxtems): savedata[idx,0]=tem - print " Calculating maxtem = %d " % tem + print(" Calculating maxtem = %d " % tem) kat.maxtem = tem tmp = asc_signal(kat) savedata[idx,1:5]=tmp.reshape([1,4]) - print " Saving results in file: {0}".format(filename) - np.savetxt(filename, savedata[0:idx+1,:], fmt='%.18e', delimiter=' ') + print(" Saving results in file: {0}".format(filename)) + np.savetxt(filename, savedata[0:idx+1,:], fmt=b'%.18e', delimiter=' ') def converge_tilt(tmpkat, maxtems): kat = copy.deepcopy(tmpkat) @@ -159,12 +164,12 @@ def converge_tilt(tmpkat, maxtems): filename = "thermal_gravity.txt" for idx, tem in enumerate(maxtems): savedata[idx,0]=tem - print " Calculating maxtem = %d " % tem + print(" Calculating maxtem = %d " % tem) kat.maxtem = tem tmp = gravity_tilt(kat) savedata[idx,1:5]=tmp - print " Saving results in file: {0}".format(filename) - np.savetxt(filename, savedata[0:idx+1,:], fmt='%.18e', delimiter=' ') + print(" Saving results in file: {0}".format(filename)) + np.savetxt(filename, savedata[0:idx+1,:], fmt=b'%.18e', delimiter=' ') def get_qs(tmpkat,f): kat = copy.deepcopy(tmpkat) @@ -181,18 +186,10 @@ def get_qs(tmpkat,f): def beam_size(tmpkat, f, beam0): kat = copy.deepcopy(tmpkat) - print "setting q param ---------------" kat.psl.npsl.node.setGauss(kat.psl, beam0) - print kat.psl.npsl.node.q - #kat.parseKatCode("startnode npsl") - print "".join(kat.generateKatScript()) - # add thermal lens and propagate input beam to ITM kat = set_thermal_lens(kat, f) - global out - print "".join(kat.generateKatScript()) - out = kat.run(printout=0,printerr=0) # computing beam size at ITM @@ -201,7 +198,7 @@ def get_qs(tmpkat,f): from pykat.optics.ABCD import apply, mirror_refl abcd = mirror_refl(1,-2500) q_out = apply(abcd,q_in,1,1) - beam1 = gauss_param(q=q_out) + beam1 = beam_param(q=q_out) kat.removeLine("startnode") kat.psl.npsl.node.removeGauss() if "ITM_TL_r" in kat._kat__components: @@ -214,18 +211,18 @@ def get_qs(tmpkat,f): # computing beam size at WFS1 and WFS2 q2 = out['w2'] - beam2 = gauss_param(q=q2) + beam2 = beam_param(q=q2) q3 = out['w3'] - beam3 = gauss_param(q=q3) + beam3 = beam_param(q=q3) # computing beam size at pick off q4 = out['w4'] - beam4 = gauss_param(q=q4) - print " Input mode beam size with thermal lens f={0}".format(f) - print " - ITM w={0:.6}cm (w0={1}, z={2})".format(100.0*beam1.w,beam1.w0, beam1.z) - print " - WFS1 w={0:.6}cm (w0={1}, z={2})".format(100.0*beam2.w,beam2.w0, beam2.z) - print " - WFS2 w={0:.6}cm (w0={1}, z={2})".format(100.0*beam3.w,beam3.w0, beam3.z) - print " - npo2 w={0:.6}cm (w0={1}, z={2})".format(100.0*beam4.w,beam4.w0, beam4.z) + beam4 = beam_param(q=q4) + print(" Input mode beam size with thermal lens f={0}".format(f)) + print(" - ITM w={0:.6}cm (w0={1}, z={2})".format(100.0*beam1.w,beam1.w0, beam1.z)) + print(" - WFS1 w={0:.6}cm (w0={1}, z={2})".format(100.0*beam2.w,beam2.w0, beam2.z)) + print(" - WFS2 w={0:.6}cm (w0={1}, z={2})".format(100.0*beam3.w,beam3.w0, beam3.z)) + print(" - npo2 w={0:.6}cm (w0={1}, z={2})".format(100.0*beam4.w,beam4.w0, beam4.z)) #raw_input("Press enter to continue") return [beam1, beam2, beam3, beam4] @@ -236,7 +233,7 @@ def get_qs(tmpkat,f): # beam at laser when matched to cold cavity # (note the sign flip of the real part to change direction of gauss param) q0 = -1.0*out['w0'].conjugate() - beam0 = gauss_param(q=q0) + beam0 = beam_param(q=q0) # compute beam sizes when tracing this beam back through the system (beam1,beam2,beam3, beam4)=beam_size(kat,f,beam0) @@ -271,12 +268,12 @@ def asc_signal(tmpkat): signal = signal *1e10 sensors=('WFS1', 'WFS2') mirrors=('ITM', 'ETM') - print " ASC Matrix:" + print(" ASC Matrix:") for i in range(2): - print " ", sensors[i], " ", + print(" ", sensors[i], " ", end=' ') for j in range(2): - print "%12.10g" % signal[i,j], - print mirrors[i] + print("%12.10g" % signal[i,j], end=' ') + print(mirrors[i]) return signal def gravity_tilt(tmpkat): @@ -339,10 +336,10 @@ def gravity_tilt(tmpkat): kat.ITM.ybeta=0.0 kat.ETM.ybeta=-1e-10 t4=compute_gravity_tilt(kat) - print " WFS1 ITM {0:.4} nrad".format(t1*1e9) - print " WFS2 ITM {0:.4} nrad".format(t3*1e9) - print " WFS1 ETM {0:.4} nrad".format(t2*1e9) - print " WFS2 ETM {0:.4} nrad".format(t4*1e9) + print(" WFS1 ITM {0:.4} nrad".format(t1*1e9)) + print(" WFS2 ITM {0:.4} nrad".format(t3*1e9)) + print(" WFS1 ETM {0:.4} nrad".format(t2*1e9)) + print(" WFS2 ETM {0:.4} nrad".format(t4*1e9)) return [t1,t2,t3,t4] if __name__ == '__main__': diff --git a/examples/asc_test/master4_plot.py b/examples/asc_test/master4_plot.py index a65e393a1b562a5c4db882297dbc20ffe704a323..e4daa5c32638fe36c9a3eaaa9d2661672ee175af 100644 --- a/examples/asc_test/master4_plot.py +++ b/examples/asc_test/master4_plot.py @@ -1,3 +1,8 @@ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + from pykat import finesse from pykat.commands import * import pylab as pl @@ -15,7 +20,7 @@ def printPDF(self, filename): pdfp.close() def main(): - print """ + print(""" -------------------------------------------------------------- Example file for using PyKat to automate Finesse simulations Finesse: http://www.gwoptics.org/finesse @@ -25,25 +30,28 @@ def main(): Andreas Freise 16.01.2014 -------------------------------------------------------------- - """ + """) # shall we clear the workspace? # %reset -f # maybe close all plot windows? # close('all') - print "--------------------------------------------------------" - print " Plotting beam tilt with thermal lens " + print("--------------------------------------------------------") + print(" Plotting beam tilt with thermal lens ") gravity_tilt() - print "--------------------------------------------------------" - print " Plotting WFS signal with thermal lens " + print("--------------------------------------------------------") + print(" Plotting WFS signal with thermal lens ") asc_signal('asc_signals_5.txt', (0.3,0.15)) asc_signal('asc_signals_50.txt', (0.3,0.15)) def asc_signal(filename,loc): xscale = 1.0 yscale = 1.0 + global data + global cols + global lw data=np.loadtxt(filename) # extracting only nonzero rows data = data[~np.all(data == 0, axis=1)] @@ -55,9 +63,6 @@ def asc_signal(filename,loc): lw=np.ones(rows+1)*3 lw[-2]=2 lw[-1]=1 - global data - global cols - global lw for i in [0,2,1,3]: pl.scatter(data[:,0],yscale*data[:,i+1],s=80,facecolors='none', edgecolors=color_cycle[i], label=labels[i]+"={0:.4} W/rad".format(data[-1,i+1]*yscale)) pl.plot(data[:,0],yscale*data[:,i+1],'-',color=color_cycle[i], linewidth=1) @@ -77,6 +82,9 @@ def asc_signal(filename,loc): def gravity_tilt(): xscale = 1.0 yscale = 1.0e9 + global data + global cols + global lw data=np.loadtxt("thermal_gravity.txt") # extracting only nonzero rows data = data[~np.all(data == 0, axis=1)] @@ -88,9 +96,6 @@ def gravity_tilt(): lw=np.ones(rows+1)*3 lw[-2]=2 lw[-1]=1 - global data - global cols - global lw for i in [0,2,1,3]: pl.scatter(data[:,0],yscale*data[:,i+1],s=80,facecolors='none', edgecolors=color_cycle[i], label=labels[i]+"={0:.4} nrad".format(data[-1,i+1]*yscale)) pl.plot(data[:,0],yscale*data[:,i+1],'-',color=color_cycle[i], linewidth=1) diff --git a/examples/asc_test/master5.py b/examples/asc_test/master5.py index 1996b947612cd48389ccceef515c47e6052165ca..bb1e445658e8d931b90327469e207caa2d464930 100644 --- a/examples/asc_test/master5.py +++ b/examples/asc_test/master5.py @@ -1,6 +1,11 @@ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + from pykat import finesse from pykat.commands import * -from pykat.optics.gaussian_beams import gauss_param +from pykat.optics.gaussian_beams import beam_param import pylab as pl import scipy @@ -10,379 +15,379 @@ import shelve import copy import sys +# making python2 and python3 compatible +try: + input = raw_input +except NameError: + pass def main(): - print """ - -------------------------------------------------------------- - Example file for using PyKat to automate Finesse simulations - Finesse: http://www.gwoptics.org/finesse - PyKat: https://pypi.python.org/pypi/PyKat/ - - The file runs through the various pykat files which are used - to generate the Finesse results reported in the document: - `Comparing Finesse simulations, analytical solutions and OSCAR - simulations of Fabry-Perot alignment signals', LIGO-T1300345 - - This file is part of a collection. Run this after master2.py - - Andreas Freise 06.12.2013 - -------------------------------------------------------------- - """ - - # shall we clear the workspace? - # %reset -f - - # making these global during testing and debugging - global kat - global out - - kat = finesse.kat(tempdir=".",tempname="test") - kat.verbose = False - - tmpresultfile = 'myshelf2.dat' - - # loading data saved by master.py - kat.loadKatFile('asc_base3.kat') - try: - tmpfile = shelve.open(tmpresultfile) - result=tmpfile['result'] - tmpfile.close() - except: raise Exception("Could not open temprary results file {0}".format(tmpresultfile)) - - - # overwriting some variables - kat.maxtem=3 - Lambda=1064.0e-9 - - # this does not work yet due to the scale command - kat.PDrefl_p.enabled = False - kat.PDrefl_q.enabled = False - kat.WFS1_I.enabled = False - kat.WFS1_Q.enabled = False - kat.WFS2_I.enabled = False - kat.WFS2_Q.enabled = False - - kat.ETM.phi=result['phi_tuned'] - - - (beam1, beam2, beam3) = get_qs(kat) - """ - print " Measured beam parameter:" - print " - At front of ITM (no thermal lens) q={0}".format(beam1.q) - print " (eqals w0={0}, z={1})".format(beam1.w0, beam1.z) - print " - At pick of mirror 'po' (50k lens) q={0}".format(beam2.q) - print " (eqals w0={0}, z={1})".format(beam2.w0, beam2.z) - print " - At pick of mirror 'po' (5k lens) q={0}".format(beam3.q) - print " (eqals w0={0}, z={1})".format(beam3.w0, beam3.z) - #print " Setting these now view Gauss command and adding thermal lens" - """ - kat.ITM.nITM1.node.setGauss(kat.ITM,beam1) - - print "--------------------------------------------------------" - print " 11. computing beam sizes with thermal lens" - #beam_size(kat, beam2, beam3) - - kat.ITM_TL.f=50e3 - kat.maxtem = 8 - print "--------------------------------------------------------" - print " 11. computing beam tilt with thermal lens (f={0}, maxtem={1})".format(kat.ITM_TL.f, kat.maxtem) - #gravity_tilt(kat) - - kat.ITM_TL.f=5e3 - kat.maxtem = 23 - - print "--------------------------------------------------------" - print " 12. computing beam tilt with thermal lens (f={0}, maxtem={1})".format(kat.ITM_TL.f, kat.maxtem) - #gravity_tilt(kat) - - - print "--------------------------------------------------------" - print " 12. compute beam center with thermal lens" - - - - - print "--------------------------------------------------------" - print " Saving results in temp. files to be read by master6.py" - tmpkatfile = "asc_base4.kat" - tmpresultfile = "myshelf3.dat" - print " kat object saved in: {0}".format(tmpkatfile) - print " current results saved in: {0}".format(tmpresultfile) - # first the current kat file - kat.saveScript(tmpkatfile) - # now the result variables: - tmpfile = shelve.open(tmpresultfile) - tmpfile['result']=result - tmpfile.close() + print(""" + -------------------------------------------------------------- + Example file for using PyKat to automate Finesse simulations + Finesse: http://www.gwoptics.org/finesse + PyKat: https://pypi.python.org/pypi/PyKat/ + + The file runs through the various pykat files which are used + to generate the Finesse results reported in the document: + `Comparing Finesse simulations, analytical solutions and OSCAR + simulations of Fabry-Perot alignment signals', LIGO-T1300345 + + This file is part of a collection. Run this after master2.py + + Andreas Freise 06.12.2013 + -------------------------------------------------------------- + """) + + # shall we clear the workspace? + # %reset -f + + # making these global during testing and debugging + global kat + global out + + kat = finesse.kat(tempdir=".",tempname="test") + kat.verbose = False + + tmpresultfile = 'myshelf2.dat' + + # loading data saved by master.py + kat.loadKatFile('asc_base3.kat') + try: + tmpfile = shelve.open(tmpresultfile) + result=tmpfile[str('result')] + tmpfile.close() + except: raise Exception("Could not open temprary results file {0}".format(tmpresultfile)) + + + # overwriting some variables + kat.maxtem=3 + Lambda=1064.0e-9 + + # this does not work yet due to the scale command + kat.PDrefl_p.enabled = False + kat.PDrefl_q.enabled = False + kat.WFS1_I.enabled = False + kat.WFS1_Q.enabled = False + kat.WFS2_I.enabled = False + kat.WFS2_Q.enabled = False + + kat.ETM.phi=result['phi_tuned'] + + (beam1, beam2, beam3) = get_qs(kat) + """ + print " Measured beam parameter:" + print " - At front of ITM (no thermal lens) q={0}".format(beam1.q) + print " (eqals w0={0}, z={1})".format(beam1.w0, beam1.z) + print " - At pick of mirror 'po' (50k lens) q={0}".format(beam2.q) + print " (eqals w0={0}, z={1})".format(beam2.w0, beam2.z) + print " - At pick of mirror 'po' (5k lens) q={0}".format(beam3.q) + print " (eqals w0={0}, z={1})".format(beam3.w0, beam3.z) + #print " Setting these now view Gauss command and adding thermal lens" + """ + kat.ITM.nITM1.node.setGauss(kat.ITM,beam1) + + print("--------------------------------------------------------") + print(" 11. computing beam sizes with thermal lens") + #beam_size(kat, beam2, beam3) + + kat.ITM_TL.f=50e3 + kat.maxtem = 8 + print("--------------------------------------------------------") + print(" 11. computing beam tilt with thermal lens (f={0}, maxtem={1})".format(kat.ITM_TL.f, kat.maxtem)) + #gravity_tilt(kat) + + kat.ITM_TL.f=5e3 + kat.maxtem = 23 + + print("--------------------------------------------------------") + print(" 12. computing beam tilt with thermal lens (f={0}, maxtem={1})".format(kat.ITM_TL.f, kat.maxtem)) + #gravity_tilt(kat) + + + print("--------------------------------------------------------") + print(" 12. compute beam center with thermal lens") + + + + + print("--------------------------------------------------------") + print(" Saving results in temp. files to be read by master6.py") + tmpkatfile = "asc_base4.kat" + tmpresultfile = "myshelf3.dat" + print(" kat object saved in: {0}".format(tmpkatfile)) + print(" current results saved in: {0}".format(tmpresultfile)) + # first the current kat file + kat.saveScript(tmpkatfile) + # now the result variables: + tmpfile = shelve.open(tmpresultfile) + tmpfile[str('result')]=result + tmpfile.close() #----------------------------------------------------------------------------------- def get_qs(tmpkat): - kat = copy.deepcopy(tmpkat) - nodename0="npsl" - nodename1="nITM1" - nodename2="nWFS1" - nodename3="nWFS2" - # measure beam parameter for the 'cold beam' i.e. the laser beam - # matched to the cavity without any thermal lens - code_bp = "bp w0 y q {0}\nbp w1 y q {1}\nbp w2 y q {2}\nbp w3 y q {3}".format(nodename0,nodename1,nodename2,nodename3) - - kat.parseKatCode(code_bp) - kat.parseKatCode('yaxis re:im') - kat.noxaxis = True - kat.maxtem=0 - - def beam_size(tmpkat, f): - kat = copy.deepcopy(tmpkat) - # 1. run finesse with input laser mode matched to cavity (no thermal lens) - out = kat.run(printout=0,printerr=0) - - # beam at laser when matched to cold cavity - # (note the sign flip of the real part to change direction of gauss param) - q0 = -1.0*out['w0'].conjugate() - beam0 = gauss_param(q=q0) - kat.psl.npsl.node.setGauss(kat.psl, beam0) - kat.parseKatCode("startnode npsl") - - # add thermal lens and propagate input beam to ITM - kat.ITM_TL.f=f - if "ITM_TL_r" in kat._kat__components: - kat.ITM_TL_r.f=f - out = kat.run(printout=0,printerr=0) - - # computing beam size at ITM - # and then we reflect of ITM, an set it as new startnode - q_in = out['w1'] - from pykat.optics.ABCD import apply, mirror_refl - abcd = mirror_refl(1,-2500) - q_out = apply(abcd,q_in,1,1) - beam1 = gauss_param(q=q_out) - kat.removeLine("startnode") - kat.psl.npsl.node.removeGauss() - if "ITM_TL_r" in kat._kat__components: - kat.ITM.nITM1r.node.setGauss(kat.ITM, beam1) - kat.parseKatCode("startnode nITM1r") - else: - kat.ITM.nITM1.node.setGauss(kat.ITM, beam1) - kat.parseKatCode("startnode nITM1") - out = kat.run(printout=0,printerr=0) - - # computing beam size at WFS1 and WFS2 - q2 = out['w2'] - beam2 = gauss_param(q=q2) - q3 = out['w3'] - beam3 = gauss_param(q=q3) - print " Sideband (input mode) beam size with thermal lens f={0}".format(f) - print " - WFS1 w={0:.6}cm".format(100.0*beam2.w) - print " (w0={0}, z={1})".format(beam2.w0, beam2.z) - print " - WFS2 w={0:.6}cm".format(100.0*beam3.w) - print " (w0={0}, z={1})".format(beam3.w0, beam3.z) - raw_input("Press enter to continue") - - return(beam1, beam2, beam3) - - f=50e3 - beam_size(kat,f) - - f=5e3 - (beam1,beam2,beam3)=beam_size(kat,f) - - - return (beam1, beam2,beam3) + kat = copy.deepcopy(tmpkat) + nodename0="npsl" + nodename1="nITM1" + nodename2="nWFS1" + nodename3="nWFS2" + # measure beam parameter for the 'cold beam' i.e. the laser beam + # matched to the cavity without any thermal lens + code_bp = "bp w0 y q {0}\nbp w1 y q {1}\nbp w2 y q {2}\nbp w3 y q {3}".format(nodename0,nodename1,nodename2,nodename3) + + kat.parseKatCode(code_bp) + kat.parseKatCode('yaxis re:im') + kat.noxaxis = True + kat.maxtem=0 + + def beam_size(tmpkat, f): + kat = copy.deepcopy(tmpkat) + # 1. run finesse with input laser mode matched to cavity (no thermal lens) + out = kat.run(printout=0,printerr=0) + + # beam at laser when matched to cold cavity + # (note the sign flip of the real part to change direction of gauss param) + q0 = -1.0*out['w0'].conjugate() + beam0 = beam_param(q=q0) + kat.psl.npsl.node.setGauss(kat.psl, beam0) + kat.parseKatCode("startnode npsl") + + # add thermal lens and propagate input beam to ITM + kat.ITM_TL.f=f + if "ITM_TL_r" in kat._kat__components: + kat.ITM_TL_r.f=f + out = kat.run(printout=0,printerr=0) + + # computing beam size at ITM + # and then we reflect of ITM, an set it as new startnode + q_in = out['w1'] + from pykat.optics.ABCD import apply, mirror_refl + abcd = mirror_refl(1,-2500) + q_out = apply(abcd,q_in,1,1) + beam1 = beam_param(q=q_out) + kat.removeLine("startnode") + kat.psl.npsl.node.removeGauss() + if "ITM_TL_r" in kat._kat__components: + kat.ITM.nITM1r.node.setGauss(kat.ITM, beam1) + kat.parseKatCode("startnode nITM1r") + else: + kat.ITM.nITM1.node.setGauss(kat.ITM, beam1) + kat.parseKatCode("startnode nITM1") + out = kat.run(printout=0,printerr=0) + + # computing beam size at WFS1 and WFS2 + q2 = out['w2'] + beam2 = beam_param(q=q2) + q3 = out['w3'] + beam3 = beam_param(q=q3) + print(" Sideband (input mode) beam size with thermal lens f={0}".format(f)) + print(" - WFS1 w={0:.6}cm".format(100.0*beam2.w)) + print(" (w0={0}, z={1})".format(beam2.w0, beam2.z)) + print(" - WFS2 w={0:.6}cm".format(100.0*beam3.w)) + print(" (w0={0}, z={1})".format(beam3.w0, beam3.z)) + input("Press enter to continue") + return(beam1, beam2, beam3) + + f=50e3 + beam_size(kat,f) + f=5e3 + (beam1,beam2,beam3)=beam_size(kat,f) + return (beam1, beam2,beam3) def asc_signal(tmpkat): - kat = copy.deepcopy(tmpkat) - - code_lock = """ - set err PDrefl_p re - lock z $err 900 1p - put* ETM phi $z - noplot z - """ - - kat.parseKatCode(code_lock) - kat.parseKatCode('yaxis abs') - kat.noxaxis = True - kat.maxtem=1 - - signal=np.zeros((2, 2)) - kat.ITM.ybeta=1e-10 - kat.ETM.ybeta=0.0 - out = kat.run(printout=0,printerr=0) - WFS1_idx=out.ylabels.index("WFS1_I") - WFS2_idx=out.ylabels.index("WFS2_I") - signal[0,0] = out.y[WFS1_idx] - signal[1,0] = out.y[WFS2_idx] - - kat.ITM.ybeta=0.0 - kat.ETM.ybeta=-1e-10 - out = kat.run(printout=0,printerr=0) - signal[0,1] = out.y[WFS1_idx] - signal[1,1] = out.y[WFS2_idx] - signal = signal *1e10 - sensors=('WFS1', 'WFS2') - mirrors=('ITM', 'ETM') - print " ASC Matrix:" - for i in range(2): - print " ", sensors[i], " ", - for j in range(2): - print "%12.10g" % signal[i,j], - print mirrors[i] - return signal - - + kat = copy.deepcopy(tmpkat) + + code_lock = """ + set err PDrefl_p re + lock z $err 900 1p + put* ETM phi $z + noplot z + """ + + kat.parseKatCode(code_lock) + kat.parseKatCode('yaxis abs') + kat.noxaxis = True + kat.maxtem=1 + + signal=np.zeros((2, 2)) + kat.ITM.ybeta=1e-10 + kat.ETM.ybeta=0.0 + out = kat.run(printout=0,printerr=0) + WFS1_idx=out.ylabels.index("WFS1_I") + WFS2_idx=out.ylabels.index("WFS2_I") + signal[0,0] = out.y[WFS1_idx] + signal[1,0] = out.y[WFS2_idx] + + kat.ITM.ybeta=0.0 + kat.ETM.ybeta=-1e-10 + out = kat.run(printout=0,printerr=0) + signal[0,1] = out.y[WFS1_idx] + signal[1,1] = out.y[WFS2_idx] + signal = signal *1e10 + sensors=('WFS1', 'WFS2') + mirrors=('ITM', 'ETM') + print(" ASC Matrix:") + for i in range(2): + print(" ", sensors[i], " ", end=' ') + for j in range(2): + print("%12.10g" % signal[i,j], end=' ') + print(mirrors[i]) + return signal + + def asc_phases(tmpkat): - kat = copy.deepcopy(tmpkat) - - kat.parseKatCode('yaxis abs') - kat.noxaxis = True - kat.maxtem=1 - - def demod_phase1(x): - kat.WFS1_I.phi[0]=x - out = kat.run(printout=0,printerr=0) - WFS1_idx=out.ylabels.index("WFS1_I") - signal = out.y[WFS1_idx] - print '\r minimising: function value %g ' % signal , - sys.stdout.flush() - return -1*abs(signal) - - def demod_phase2(x): - kat.WFS2_I.phi[0]=x - out = kat.run(printout=0,printerr=0) - WFS2_idx=out.ylabels.index("WFS2_I") - signal = out.y[WFS2_idx] - print '\r minimising: function value %g ' % signal , - sys.stdout.flush() - return -1*abs(signal) - - kat.ITM.ybeta=1e-10 - kat.ETM.ybeta=0.0 - res = minimize_scalar(demod_phase1, method='brent') - WFS1_phase = res.x - print "" - print " WFS1 demod phase : %.10g deg" % WFS1_phase - - kat.ITM.ybeta=0.0 - kat.ETM.ybeta=-1e-10 - res = minimize_scalar(demod_phase2, method='brent') - WFS2_phase = res.x - print "" - print " WFS2 demod phase : %.10g deg" % WFS2_phase - return(WFS1_phase, WFS2_phase) - + kat = copy.deepcopy(tmpkat) + + kat.parseKatCode('yaxis abs') + kat.noxaxis = True + kat.maxtem=1 + + def demod_phase1(x): + kat.WFS1_I.phi[0]=x + out = kat.run(printout=0,printerr=0) + WFS1_idx=out.ylabels.index("WFS1_I") + signal = out.y[WFS1_idx] + print('\r minimising: function value %g ' % signal, end=' ') + sys.stdout.flush() + return -1*abs(signal) + + def demod_phase2(x): + kat.WFS2_I.phi[0]=x + out = kat.run(printout=0,printerr=0) + WFS2_idx=out.ylabels.index("WFS2_I") + signal = out.y[WFS2_idx] + print('\r minimising: function value %g ' % signal, end=' ') + sys.stdout.flush() + return -1*abs(signal) + + kat.ITM.ybeta=1e-10 + kat.ETM.ybeta=0.0 + res = minimize_scalar(demod_phase1, method='brent') + WFS1_phase = res.x + print("") + print(" WFS1 demod phase : %.10g deg" % WFS1_phase) + + kat.ITM.ybeta=0.0 + kat.ETM.ybeta=-1e-10 + res = minimize_scalar(demod_phase2, method='brent') + WFS2_phase = res.x + print("") + print(" WFS2 demod phase : %.10g deg" % WFS2_phase) + return(WFS1_phase, WFS2_phase) + def gravity_tilt(tmpkat): - kat = copy.deepcopy(tmpkat) - - def compute_gravity_tilt(tmpkat): - kat = copy.deepcopy(tmpkat) - out = kat.run(printout=0,printerr=0) - - y1 = out["b1"] - y2 = out["b1_1k"] - # shift of beam center on detector 1 (as m/w0y) - x1 = np.sum(out.x*y1)/np.sum(y1) - # shift of beam center on detector 2 (as m/w0y) - x2 = np.sum(out.x*y2)/np.sum(y2) - # calibrate this in meter by mutliplying with w0y - # and compute the angle geometrically - w0=out["w0y"][0] - detector_distance = 1000.0 - tilt=w0*(x2-x1)/detector_distance - print " Wavefront tilt : %g nrad" % tilt - - code_WFS1 = """ - beam b1 nWFS1 - beam b1_1k nL1_in - bp w0y y w0 nWFS1 - """ - - code_WFS2 = """ - m md 0 1 0 nWFS2 nWFS2b - s sd 1k nWFS2b nWFS2c - beam b1 nWFS2* - beam b1_1k nWFS2c - bp w0y y w0 nWFS2 - """ - - code_xaxis= """ - xaxis b1 y lin -40 40 800 - put b1_1k y $x1 - yaxis abs - """ - print " WFS1:" - print " ITM ybeta 0.1nm" - kat.parseKatCode(code_WFS1) - kat.parseKatCode(code_xaxis) - kat.spo1.L=1000.0 - kat.ITM.ybeta=1e-10 - kat.ETM.ybeta=0.0 - compute_gravity_tilt(kat) - print " ETM ybeta -0.1nm" - kat.ITM.ybeta=0.0 - kat.ETM.ybeta=-1e-10 - compute_gravity_tilt(kat) - - print " WFS1:" - print " ITM ybeta 0.1nm" - kat = copy.deepcopy(tmpkat) - kat.parseKatCode(code_WFS2) - kat.parseKatCode(code_xaxis) - kat.spo1.L=1.0e-9 - kat.ITM.ybeta=1e-10 - kat.ETM.ybeta=0.0 - compute_gravity_tilt(kat) - print " ETM ybeta -0.1nm" - kat.ITM.ybeta=0.0 - kat.ETM.ybeta=-1e-10 - compute_gravity_tilt(kat) + kat = copy.deepcopy(tmpkat) + + def compute_gravity_tilt(tmpkat): + kat = copy.deepcopy(tmpkat) + out = kat.run(printout=0,printerr=0) + + y1 = out["b1"] + y2 = out["b1_1k"] + # shift of beam center on detector 1 (as m/w0y) + x1 = np.sum(out.x*y1)/np.sum(y1) + # shift of beam center on detector 2 (as m/w0y) + x2 = np.sum(out.x*y2)/np.sum(y2) + # calibrate this in meter by mutliplying with w0y + # and compute the angle geometrically + w0=out["w0y"][0] + detector_distance = 1000.0 + tilt=w0*(x2-x1)/detector_distance + print(" Wavefront tilt : %g nrad" % tilt) + + code_WFS1 = """ + beam b1 nWFS1 + beam b1_1k nL1_in + bp w0y y w0 nWFS1 + """ + + code_WFS2 = """ + m md 0 1 0 nWFS2 nWFS2b + s sd 1k nWFS2b nWFS2c + beam b1 nWFS2* + beam b1_1k nWFS2c + bp w0y y w0 nWFS2 + """ + + code_xaxis= """ + xaxis b1 y lin -40 40 800 + put b1_1k y $x1 + yaxis abs + """ + print(" WFS1:") + print(" ITM ybeta 0.1nm") + kat.parseKatCode(code_WFS1) + kat.parseKatCode(code_xaxis) + kat.spo1.L=1000.0 + kat.ITM.ybeta=1e-10 + kat.ETM.ybeta=0.0 + compute_gravity_tilt(kat) + print(" ETM ybeta -0.1nm") + kat.ITM.ybeta=0.0 + kat.ETM.ybeta=-1e-10 + compute_gravity_tilt(kat) + + print(" WFS1:") + print(" ITM ybeta 0.1nm") + kat = copy.deepcopy(tmpkat) + kat.parseKatCode(code_WFS2) + kat.parseKatCode(code_xaxis) + kat.spo1.L=1.0e-9 + kat.ITM.ybeta=1e-10 + kat.ETM.ybeta=0.0 + compute_gravity_tilt(kat) + print(" ETM ybeta -0.1nm") + kat.ITM.ybeta=0.0 + kat.ETM.ybeta=-1e-10 + compute_gravity_tilt(kat) def beam_size(tmpkat, beam2, beam3): - kat = copy.deepcopy(tmpkat) - - global out - code_bps = """ - bp wWFS1 y w nWFS1 - bp wWFS2 y w nWFS2 - """ - kat.parseKatCode(code_bps) - kat.maxtem = 0 - kat.ITM.R=1.0 - kat.ITM.T=0.0 - - kat.noxaxis = True - kat.ITM_TL.f=50e3 - if "ITM_TL_r" in kat._kat__components: - kat.ITM_TL_r.f=50e3 - - kat.po.nWFS1.node.setGauss(kat.po,beam2) - - out = kat.run(printout=0,printerr=0) - - WFS1_idx=out.ylabels.index("wWFS1") - WFS2_idx=out.ylabels.index("wWFS2") - - - y1 = out.y[WFS1_idx] - y2 = out.y[WFS2_idx] - print " Beam size with thermal lens f={0}".format(kat.ITM_TL.f) - print " WFS1: {0}cm".format(y1*100.0) - print " WFS2: {0}cm".format(y2*100.0) - - kat.ITM_TL.f=5e3 - if "ITM_TL_r" in kat._kat__components: - kat.ITM_TL_r.f=5e3 - kat.po.nWFS1.node.setGauss(kat.po,beam3) - out = kat.run(printout=0,printerr=0) - y1 = out.y[WFS1_idx] - y2 = out.y[WFS2_idx] - print " Beam size with thermal lens f={0}".format(kat.ITM_TL.f) - print " WFS1: {0}cm".format(y1*100.0) - print " WFS2: {0}cm".format(y2*100.0) - - + kat = copy.deepcopy(tmpkat) + + global out + code_bps = """ + bp wWFS1 y w nWFS1 + bp wWFS2 y w nWFS2 + """ + kat.parseKatCode(code_bps) + kat.maxtem = 0 + kat.ITM.R=1.0 + kat.ITM.T=0.0 + + kat.noxaxis = True + kat.ITM_TL.f=50e3 + if "ITM_TL_r" in kat._kat__components: + kat.ITM_TL_r.f=50e3 + + kat.po.nWFS1.node.setGauss(kat.po,beam2) + + out = kat.run(printout=0,printerr=0) + + WFS1_idx=out.ylabels.index("wWFS1") + WFS2_idx=out.ylabels.index("wWFS2") + + + y1 = out.y[WFS1_idx] + y2 = out.y[WFS2_idx] + print(" Beam size with thermal lens f={0}".format(kat.ITM_TL.f)) + print(" WFS1: {0}cm".format(y1*100.0)) + print(" WFS2: {0}cm".format(y2*100.0)) + + kat.ITM_TL.f=5e3 + if "ITM_TL_r" in kat._kat__components: + kat.ITM_TL_r.f=5e3 + kat.po.nWFS1.node.setGauss(kat.po,beam3) + out = kat.run(printout=0,printerr=0) + y1 = out.y[WFS1_idx] + y2 = out.y[WFS2_idx] + print(" Beam size with thermal lens f={0}".format(kat.ITM_TL.f)) + print(" WFS1: {0}cm".format(y1*100.0)) + print(" WFS2: {0}cm".format(y2*100.0)) + + if __name__ == '__main__': - main() + main() diff --git a/pykat/SIfloat.py b/pykat/SIfloat.py index cac016f0623c82601cb7b6c072cb0e3c5b56b010..aa65c9ec2313f68deb721d7508182e61368c5937 100644 --- a/pykat/SIfloat.py +++ b/pykat/SIfloat.py @@ -1,3 +1,8 @@ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + import os import re import pykat.exceptions as pkex diff --git a/pykat/__init__.py b/pykat/__init__.py index 9b14f735d2213da106e9b1cd22c2b5be53a8cd38..4dda77b69059678d5f39a95c805adca1d778d013 100644 --- a/pykat/__init__.py +++ b/pykat/__init__.py @@ -7,10 +7,10 @@ import pykat.exceptions as pkex NoGUIException = pkex.BasePyKatException("No PyQt4 module was found so cannot open a GUI") -import finesse -import components -import detectors -import commands +import pykat.finesse as finesse +import pykat.components as components +import pykat.detectors as detectors +import pykat.commands as commands from pykat.optics.gaussian_beams import beam_param diff --git a/pykat/colours.py b/pykat/colours.py index cc65b2f77c41b757c5de407ecd8b7f8ca6315b86..94291cd35ad1ff93bbaac365fe6ca089161ecea6 100644 --- a/pykat/colours.py +++ b/pykat/colours.py @@ -4,6 +4,10 @@ Created on Mon Jan 28 10:43:18 2013 @author: Daniel """ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals class colours: HEADER = '\033[95m' @@ -19,4 +23,4 @@ class colours: self.OKGREEN = '' self.WARNING = '' self.FAIL = '' - self.ENDC = '' \ No newline at end of file + self.ENDC = '' diff --git a/pykat/commands.py b/pykat/commands.py index 6f0f1c89dfb111a55d78e3efcda25923b305dc4a..65c4b891dc540d1d049317be052eea2e4b86f87a 100644 --- a/pykat/commands.py +++ b/pykat/commands.py @@ -4,11 +4,19 @@ Created on Mon Jan 28 11:58:09 2013 @author: Daniel """ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + import numpy from numpy import min,max -import exceptions -from components import * -from structs import * +import pykat.external.six as six +if six.PY2: + import exceptions +from pykat.components import * +from pykat.structs import * + from pykat.param import Param, putter import pykat.exceptions as pkex from collections import namedtuple @@ -145,7 +153,7 @@ class xaxis(Command): scale = Scale.linear elif scale == "log": scale = Scale.logarithmic - elif isinstance(scale, str): + elif isinstance(scale, six.string_types): # else we have a string but not a recognisable one raise pkex.BasePyKatException("scale argument '{0}' is not valid, must be 'lin' or 'log'".format(scale)) @@ -159,12 +167,12 @@ class xaxis(Command): self.limits = numpy.array(SIfloat(limits)).astype(float) - if steps <= 0 : + if int(steps) <= 0 : raise pkex.BasePyKatException("steps value should be > 0") self.steps = int(steps) - if isinstance(param, str): + if isinstance(param, six.string_types): self.__param = param if comp == None: raise pkex.BasePyKatException("If parameter is set with a string, the comp argument must set the component name") diff --git a/pykat/components.py b/pykat/components.py index 7931e3a1ce3ef0af153e7e00c82163ea6fc0fd8c..f21bb74135a79552a5af42d92bf3990479ab6907 100644 --- a/pykat/components.py +++ b/pykat/components.py @@ -4,7 +4,18 @@ Created on Mon Jan 28 11:10:01 2013 @author: Daniel """ -import exceptions +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + +from pykat import USE_GUI, NoGUIException + +import pykat.external.six as six + +if six.PY2: + import exceptions + import pykat.exceptions as pkex import pykat from pykat.node_network import * @@ -198,7 +209,7 @@ class Component(object): del self._params[:] self.__removed = True - + def __deepcopy__(self, memo): cls = self.__class__ result = cls.__new__(cls) @@ -211,7 +222,7 @@ class Component(object): p._updateOwner(result) return result - + class AbstractMirrorComponent(Component): __metaclass__ = abc.ABCMeta diff --git a/pykat/detectors.py b/pykat/detectors.py index 1726b30f8b97f59ed27f9e002c06dac41c95179d..acca83ca2b6f3231bd78e0f4d9129e207c4f3c79 100644 --- a/pykat/detectors.py +++ b/pykat/detectors.py @@ -4,14 +4,24 @@ Created on Fri Feb 01 0split()9:09:10 2013 @author: Daniel """ -import exceptions +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + +import pykat.external.six as six +if six.PY2: + import exceptions + import abc from pykat.node_network import * from pykat.param import Param from pykat.SIfloat import SIfloat -import collections +import pykat.external.six as six import pykat.exceptions as pkex + +import collections import warnings import copy @@ -60,7 +70,7 @@ class BaseDetector(object) : self._alternate_beam.append(False) self._requested_nodes.append(n) - elif isinstance(nodes, str): + elif isinstance(nodes, six.string_types): # if we don't have a collection if nodes[-1]=='*': self._alternate_beam.append(True) @@ -146,7 +156,7 @@ class BaseDetector(object) : def _getScaleCmds(self, rtn): if self.scale != None: - if isinstance(self.scale, str): + if isinstance(self.scale, six.string_types): rtn.append("scale {1} {0}".format(self.name, self.scale)) elif isinstance(self.scale, (list, tuple)): for s in self.scale: @@ -372,9 +382,10 @@ class pd(Detector1): fs = [self.__f1, self.__f2, self.__f3, self.__f4, self.__f5] ps = [self.__phi1, self.__phi2, self.__phi3, self.__phi4, self.__phi5] - + for i in range(num_demods): f = 'f{0}'.format(i+1) + #print("i {0} fs {1} f {2} keys {3}".format(i,len(fs),f, kwargs.keys())) if f in kwargs: fs[i].value = kwargs[f] @@ -434,7 +445,7 @@ class pd(Detector1): # check if we are setting no phase that this is only on the last # demodulation phase. raise pkex.BasePyKatException("Only last demodulation phase can be set to None") - elif isinstance(value, str) and not isinstance(value,float) and value.lower() != "max": + elif isinstance(value, six.string_types) and not isinstance(value,float) and value.lower() != "max": raise pkex.BasePyKatException("Demodulation phase can only be set to a 'max' or a number (or None if the last demodulation phase)") setattr(self, '_'+ self.__class__.__name__ +'__phi' + num, value) @@ -878,4 +889,4 @@ class qhd(Detector2): for p in self._params: rtn.extend(p.getFinesseText()) - return rtn \ No newline at end of file + return rtn diff --git a/pykat/exceptions.py b/pykat/exceptions.py index c1f620be084d1e200c3f0c14a8edafc77e565ccf..1382809d9777529702e0030a1e9e78e30eba5fce 100644 --- a/pykat/exceptions.py +++ b/pykat/exceptions.py @@ -1,4 +1,11 @@ -import exceptions +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + +import pykat.external.six as six +if six.PY2: + import exceptions import os class BasePyKatException(Exception): diff --git a/pykat/finesse.py b/pykat/finesse.py index 573fcccac792797e1c5f997fe247ccc84fdd69a3..1e64096dcf5b494573051ce8bb24e01f4f76af34 100644 --- a/pykat/finesse.py +++ b/pykat/finesse.py @@ -23,6 +23,11 @@ Contact at ddb@star.sr.bham.ac.uk @author: Daniel Brown """ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + import sys import os import subprocess @@ -41,6 +46,23 @@ import collections import re import copy + +try: + # Python 2 + from itertools import izip_longest +except ImportError: + # Python 3 + from itertools import zip_longest as izip_longest +""" +try: + from future_builtins import zip_longest +except ImportError: # not 2.6+ or is 3.x + try: + from itertools import izip_longest as zip_longest # < 2.5 or 3.x + except ImportError: + print("boom") + pass +""" from collections import namedtuple, OrderedDict from pykat.node_network import NodeNetwork @@ -50,6 +72,8 @@ from pykat.commands import Command, xaxis from pykat.SIfloat import * from pykat.param import Param, AttrParam +import pykat.external.six as six + import pykat.exceptions as pkex from pykat import USE_GUI, NoGUIException @@ -92,7 +116,7 @@ def f__lkat_process(callback, cmd, kwargs): callback(lkat, **kwargs) except Exception as ex: - print "Exception caught in python: ", ex.message + print ("Exception caught in python: ", ex.message) finally: # This should always be called no matter what lkat._pykat_finish(0) @@ -507,7 +531,7 @@ class kat(object): @staticmethod def logo(): - print """ ..- + print (""" ..- PyKat {0:7} _ '( \\`.|\\.__...-\"\"""-_." ) ..+-----.._ / ' ` .-' @@ -515,7 +539,7 @@ class kat(object): ( '::;;+;;: `-"' =" /,`"" `) / L. \\`:::a:f c_/ n_' ..`--...___`. . , - `^-....____: +. {1}\n""".format(pykat.__version__, pykat_web) + `^-....____: +. {1}\n""".format(pykat.__version__, pykat_web)) def loadKatFile(self, katfile, blocks=None): commands=open(katfile).read() @@ -723,7 +747,7 @@ class kat(object): self.deriv_h = float(v[1]) elif(first == "gnuterm" or first == "pyterm"): if self.verbose: - print "Ignoring Gnuplot/Python terminal command '{0}'".format(line) + print ("Ignoring Gnuplot/Python terminal command '{0}'".format(line)) elif(first == "fsig"): after_process.append(line) elif(first == "noplot"): @@ -731,22 +755,22 @@ class kat(object): self.__blocks[self.__currentTag].contents.append(line) else: if self.verbose: - print "Parsing `{0}` into pykat object not implemented yet, added as extra line.".format(line) + print ("Parsing `{0}` into pykat object not implemented yet, added as extra line.".format(line)) obj = line # manually add the line to the block contents self.__blocks[self.__currentTag].contents.append(line) - if obj != None and not isinstance(obj, str): + if obj != None and not isinstance(obj, six.string_types): if self.hasNamedObject(obj.name): getattr(self, obj.name).remove() - print "Removed existing object '{0}' of type {1} to add line '{2}'".format(obj.name, obj.__class__, line) + print ("Removed existing object '{0}' of type {1} to add line '{2}'".format(obj.name, obj.__class__, line)) self.add(obj) except: - print "--------------------------------------------------------" - print "Error parsing line: " + line - print "--------------------------------------------------------" + print ("--------------------------------------------------------") + print ("Error parsing line: " + line) + print ("--------------------------------------------------------") raise @@ -810,7 +834,8 @@ class kat(object): raise pkex.BasePyKatException("Attr command '{0}' must specify both parameter and value pairs".format(line)) # convert split list to key value pairs - kv = dict(itertools.izip_longest(*[iter(v[2:])] * 2, fillvalue=None)) + #kv = dict(itertools.izip_longest(*[iter(v[2:])] * 2, fillvalue=None)) + kv = dict(izip_longest(*[iter(v[2:])] * 2, fillvalue=None)) comp.parseAttributes(kv) @@ -871,7 +896,7 @@ class kat(object): katfile.close() except pkex.BasePyKatException as ex: - print ex + print (ex) def getProcess(self, callback, **kwargs): @@ -924,8 +949,8 @@ class kat(object): if not (os.path.isfile(kat_exec) and os.access(kat_exec, os.X_OK)): raise pkex.MissingFinesse() - if self.verbose: print "--------------------------------------------------------------" - if self.verbose: print "Running kat - Started at " + str(start) + if self.verbose: print ("--------------------------------------------------------------") + if self.verbose: print ("Running kat - Started at " + str(start)) if hasattr(self, "x2axis") and self.noxaxis == False: r = katRun2D() @@ -976,53 +1001,65 @@ class kat(object): err = "" #if self.verbose: print "Finesse output:" - for line in iter(p.stderr.readline, ""): + for aline in iter(p.stderr.readline, b""): + if six.PY2: + line = unicode(aline, "utf-8") + else: + line = aline if len(line) > 0: # remove any ANSI commands - ansi = re.compile(r'\x1b[^m]*m') - line = ansi.sub('', line) + #ansi = re.compile(r'\x1b[^m]*m') + #line = ansi.sub('', line) + line = re.sub(br'\x1b[^m]*m', '', line, re.UNICODE) # warnings and errors start with an asterisk # so if verbose show them - if line.lstrip().startswith('*PROG*'): + if line.lstrip().startswith(b'*PROG*'): line = line[8:-1] - vals = line.split("-",1) + vals = line.split(b"-",1) action = vals[0].strip() prc = vals[1].strip()[:] if printerr == 1: - sys.stdout.write("\r{0} {1}".format(action, prc)) - elif line.lstrip().startswith('*'): - if self.verbose: sys.stdout.write(line) - elif line.rstrip().endswith('%'): + if six.PY2: + sys.stdout.write("\r{0} {1}".format(action, prc)) + else: + sys.stdout.write("\r{0} {1}".format(str(action, 'utf-8'), str(prc, 'utf-8'))) + elif line.lstrip().startswith(b'*'): + if self.verbose: + if six.PY2: + sys.stdout.write(line) + else: + sys.stdout.write(line) # todo fix this if needed + elif line.rstrip().endswith(b'%'): vals = line.split("-") action = vals[0].strip() prc = vals[1].strip()[:] if printerr == 1: - sys.stdout.write("\r{0} {1}".format(action, prc)) + sys.stdout.write("\r{0} {1}".format(action, str(prc))) else: - err += line + err += str(line) [out,errpipe] = p.communicate() if printout == 1: - print out + print (out) else: - if printerr == 1: print "" + if printerr == 1: print ("") # get the version number - ix = out.find('build ') + 6 - ix2 = out.find(')',ix) + ix = out.find(b'build ') + 6 + ix2 = out.find(b')',ix) r.katVersion = out[ix:ix2] r.runDateTime = datetime.datetime.now() # If Finesse returned an error, just print that and exit! if p.returncode != 0: - print err + print (err) sys.exit(1) self.__prevrunfilename = katfile.name @@ -1042,20 +1079,21 @@ class kat(object): os.rename(outfile, newoutfile) - if self.verbose: print "\nOutput data saved to '{0}'".format(newoutfile) + if self.verbose: print ("\nOutput data saved to '{0}'".format(newoutfile)) if hasattr(self, "x2axis") and self.noxaxis == False: [r.x,r.y,r.z,hdr] = self.readOutFile(outfile) r.xlabel = hdr[0] r.ylabel = hdr[1] - r.zlabels = map(str.strip, hdr[2:]) - + r.zlabels = [s.strip() for s in hdr[2:]] + #r.zlabels = map(str.strip, hdr[2:]) else: [r.x,r.y,hdr] = self.readOutFile(outfile) r.xlabel = hdr[0] - r.ylabels = map(str.strip, hdr[1:]) + r.ylabels = [s.strip() for s in hdr[1:]] + #r.ylabels = map(str.strip, hdr[1:]) // replaced 090415 adf if save_kat: if kat_name == None: @@ -1069,17 +1107,17 @@ class kat(object): os.rename(katfile.name, newkatfile) - if self.verbose: print "Kat file saved to '{0}'".format(newkatfile) + if self.verbose: print ("Kat file saved to '{0}'".format(newkatfile)) if self.trace != None and self.trace > 0: - #print "{0}".format(out) + #print ("{0}".format(out)) #if self.trace & 1: #search = out.find(' --- highest order of TEM modes') #if search > -1: - #print "Trace 1: {0}".format(out[search:]) + #print ("Trace 1: {0}".format(out[search:])) # for now, just try to print the trace block in full - print out[out.find(' ---') :] + print (out[out.find(' ---') :]) katfile.close() perfData = [] @@ -1096,10 +1134,10 @@ class kat(object): return r except pkex.FinesseRunError as fe: - print fe + print (fe) finally: - if self.verbose: print "" - if self.verbose: print "Finished in " + str(datetime.datetime.now()-start) + if self.verbose: print ("") + if self.verbose: print ("Finished in " + str(datetime.datetime.now()-start)) def remove(self, obj): if not isinstance(obj, pykat.finesse.Signals) and not (obj.name in self.__components or obj.name in self.__detectors or obj.name in self.__commands or obj in self.signals.targets): @@ -1139,7 +1177,7 @@ class kat(object): del nodes #import gc - #print gc.get_referrers(obj) + #print (gc.get_referrers(obj)) def getMatrices(self): @@ -1150,7 +1188,7 @@ class kat(object): self.noxaxis = True self.printmatrix = True - print "".join(self.generateKatScript()) + print ("".join(self.generateKatScript())) self.verbose = True self.run(printout=1) self.printmatrix = None @@ -1222,7 +1260,7 @@ class kat(object): obj._on_kat_add(self) except pkex.BasePyKatException as ex: - print ex + print (ex) def readOutFile(self, filename): @@ -1271,9 +1309,9 @@ class kat(object): for key in self.__blocks: objs = self.__blocks[key].contents for obj in objs: - if isinstance(obj, str): + if isinstance(obj, six.string_types): if fragment in obj: - print " ** removing line '{0}'".format(obj) + print (" ** removing line '{0}'".format(obj)) objs.remove(obj) def addLine(self, line, block=NO_BLOCK) : @@ -1284,13 +1322,32 @@ class kat(object): pykat object that create similar commands so becareful. """ self.__blocks[block].contents.append(line) + + def printExtraLines(self): + """ + This prints all the Finesse commands that have not been parsed + into pykat objects. This should be used for reference only. To + add or remove extra lines use the addLine and removeLine methods. + """ + found = False + + for key in self.__blocks: + objs = self.__blocks[key].contents + for obj in objs: + if isinstance(obj, six.string_types): + print(obj) + found = True + + if not found: + print("No extra lines were found") + def generateKatScript(self) : """ Generates the kat file which can then be run """ def writeBlock(): for obj in objs: - if isinstance(obj, str): + if isinstance(obj, six.string_types): out.append(obj + '\n') elif isinstance(obj, Component) or isinstance(obj, Detector) or isinstance(obj, Command): @@ -1364,7 +1421,7 @@ class kat(object): out.append("vacuum {0}\n".format(" ".join(objs))) - elif isinstance(self.vacuum, str): + elif isinstance(self.vacuum, six.string_types): out.append("vacuum {0}\n".format(self.vacuum)) else: pkex.BasePyKatException("Couldn't understand vacuum input list") @@ -1537,7 +1594,7 @@ class kat(object): name = com.__class__.__name__ - print getattr(self.__class__, name) + print (getattr(self.__class__, name)) delattr(self.__class__, name) delattr(self, '__com_' + name) @@ -1596,8 +1653,9 @@ class kat(object): line = " ".join(line.split()) # add to a list all the positions of any inline comment markers i = [line.find('#'), line.find('\\')] - i = filter(lambda a: a != -1, i) - + #i = filter(lambda a: a != -1, i) + i = [a for a in i if a != -1] + if len(i) == 0: commands.append(line) else: diff --git a/pykat/node_network.py b/pykat/node_network.py index d35f45f7723130e0cc8502145049304833ca86f7..550290e662dfcedb4378ead9002e538facb0a544 100644 --- a/pykat/node_network.py +++ b/pykat/node_network.py @@ -4,6 +4,10 @@ Created on Sun Jan 27 10:02:41 2013 @author: Daniel """ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals from pykat import USE_GUI, NoGUIException @@ -11,6 +15,7 @@ if USE_GUI: import pykat.gui.graphics import pykat.exceptions as pkex +import pykat.external.six as six from pykat.components import Component, NodeGaussSetter from pykat.detectors import BaseDetector as Detector @@ -72,10 +77,10 @@ class NodeNetwork(object): connected to it have changed. """ - if isinstance(node_old, str): + if isinstance(node_old, six.string_types): node_old = self.__kat.nodes[node_old] - if isinstance(node_new, str): + if isinstance(node_new, six.string_types): node_new = self.__kat.nodes[node_new] if isinstance(node_old, NodeGaussSetter): @@ -209,7 +214,7 @@ class NodeNetwork(object): """ - if isinstance(node, str): + if isinstance(node, six.string_types): node = self.__kat.nodes[node] if isinstance(node, NodeGaussSetter): @@ -350,7 +355,7 @@ class NodeNetwork(object): return False elif isinstance(currcomp, pykat.components.isolator): - print "isol" + print ("isol") elif isinstance(currcomp, pykat.components.laser): # if we are at a laser then we can't go any further # and it isn;t this node as we checked before @@ -397,13 +402,13 @@ class NodeNetwork(object): of the components it finds between them. """ - if isinstance(from_node, str): + if isinstance(from_node, six.string_types): from_node = self.__kat.nodes[from_node] if isinstance(from_node, NodeGaussSetter): from_node = from_node.node - if isinstance(to_node, str): + if isinstance(to_node, six.string_types): to_node = self.__kat.nodes[to_node] if isinstance(to_node, NodeGaussSetter): diff --git a/pykat/param.py b/pykat/param.py index a5bb11dee3400392edea62544d8d6c85cea6c2da..9670f0c0417e61049f788f60c1fa60cd5886e12f 100644 --- a/pykat/param.py +++ b/pykat/param.py @@ -1,3 +1,8 @@ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + import abc import pykat.exceptions as pkex import weakref @@ -87,7 +92,7 @@ class Param(putable, putter): putter.__init__(self, var_name, isPutter) putable.__init__(self, owner.name, name, isPutable) - + def _updateOwner(self, newOwner): """ This updates the internal weak reference to link a parameter to who owns it. @@ -159,7 +164,7 @@ class Param(putable, putter): #if this param can be put somewhere we need to check if it is if self.isPutable: for a in self.putees: - print "Removing put from {0} {1} to {2} {3}".format(self.owner.name, self.name, a.owner.name, a.name) + print ("Removing put from {0} {1} to {2} {3}".format(self.owner.name, self.name, a.owner.name, a.name)) a._putter = None self.put_count -= 1 @@ -169,7 +174,7 @@ class Param(putable, putter): # check if we have anything being put to us if self.isPutter: if self._putter != None: - print "Removing put from {0} {1} to {2} {3}".format(self._putter.owner.name, self._putter.name, self.owner.name, self.name) + print ("Removing put from {0} {1} to {2} {3}".format(self._putter.owner.name, self._putter.name, self.owner.name, self.name)) self._putter.put_count -= 1 self._putter.putees.remove(self) self._putter = None diff --git a/pykat/plotting.py b/pykat/plotting.py index 10e6cc1a7ba9a1662c2743962778d1fe06e56bcf..7abd88cfdc0eeb6ef4a60a561b08202b21bb9ebf 100644 --- a/pykat/plotting.py +++ b/pykat/plotting.py @@ -4,6 +4,10 @@ Created on Sat Feb 02 10:35:04 2013 @author: Daniel """ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals import numpy as np import matplotlib @@ -80,4 +84,4 @@ class pp(): # for Palatino and other serif fonts use: #font = {'family':'serif','serif':['Palatino']} SCREEN_TITLE = True # show title on screen? - PRINT_TITLE = False # show title in saved file? \ No newline at end of file + PRINT_TITLE = False # show title in saved file? diff --git a/pykat/profiling.py b/pykat/profiling.py index c6302a2f3d9e8b857fd30ce9f5c96083af92bdf2..4d1a7b9fdc9ae9a6fc761634ea7813a95b411bff 100644 --- a/pykat/profiling.py +++ b/pykat/profiling.py @@ -1,3 +1,8 @@ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + import numpy as np import pylab as pl @@ -24,4 +29,4 @@ def plotReducedPerformanceData(perfdata, ordered=False): pl.xlabel("Time [s]") pl.title("Timing data for FINESSE") - return labels, times, fig \ No newline at end of file + return labels, times, fig diff --git a/pykat/structs.py b/pykat/structs.py index d8838afbf36f703861cf719d2926e953707e75bd..90c5fb844fa656bd4ad7e59bcc4caed3c0b213ce 100644 --- a/pykat/structs.py +++ b/pykat/structs.py @@ -4,7 +4,11 @@ Created on Mon Jan 28 12:00:29 2013 @author: Daniel """ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals class Scale: linear = 'lin' - logarithmic = 'log' \ No newline at end of file + logarithmic = 'log'