From 6c9a39bd4d38f9bae78bf2c1598893d690a1de03 Mon Sep 17 00:00:00 2001
From: Andreas Freise <adf@star.bham.ac.uk>
Date: Fri, 10 Apr 2015 23:04:48 +0100
Subject: [PATCH] conversion done, examples run in python2.7 and python3.4 !

---
 examples/asc_test/master.py       |  4 +--
 examples/asc_test/master2.py      |  8 ++---
 examples/asc_test/master3.py      |  6 ++--
 examples/asc_test/master3_plot.py |  4 +--
 examples/asc_test/master4.py      | 24 ++++++-------
 examples/asc_test/master4_plot.py | 12 +++----
 examples/asc_test/master5.py      | 21 ++++++-----
 pykat/__init__.py                 |  8 ++---
 pykat/commands.py                 |  2 +-
 pykat/finesse.py                  | 59 +++++++++++++++++++++++--------
 10 files changed, 91 insertions(+), 57 deletions(-)

diff --git a/examples/asc_test/master.py b/examples/asc_test/master.py
index d6d492a..de20195 100644
--- a/examples/asc_test/master.py
+++ b/examples/asc_test/master.py
@@ -89,8 +89,8 @@ def main():
 	# first the current kat file
 	kat.saveScript(tmpkatfile)
 	# now the result variables:
-	tmpfile = shelve.open(tmpresultfile)
-	tmpfile[b'result']=result
+	tmpfile = shelve.open(tmpresultfile, flag="c")
+	tmpfile[str('result')]=result
 	tmpfile.close()
 	
 #---------------------------------------------------------------------------
diff --git a/examples/asc_test/master2.py b/examples/asc_test/master2.py
index f8ac90b..9f28f9e 100644
--- a/examples/asc_test/master2.py
+++ b/examples/asc_test/master2.py
@@ -46,13 +46,13 @@ def main():
 	kat = finesse.kat(tempdir=".",tempname="test")
 	kat.verbose = False
 	
-	tmpresultfile = 'myshelf1.dat'
+	tmpresultfile = "myshelf1.dat"
 	
 	# loading data saved by master.py
 	kat.loadKatFile('asc_base2.kat')
 	try:
-		tmpfile = shelve.open(tmpresultfile)
-		result=tmpfile[b'result']
+		tmpfile = shelve.open(tmpresultfile, flag="c")
+		result=tmpfile[str('result')]
 		tmpfile.close()
 	except: raise Exception("Could not open temprary results file {0}".format(tmpresultfile))
 		
@@ -126,7 +126,7 @@ def main():
 	kat.saveScript(tmpkatfile)
 	# now the result variables:
 	tmpfile = shelve.open(tmpresultfile)
-	tmpfile[b'result']=result
+	tmpfile[str('result')]=result
 	tmpfile.close()
 
 
diff --git a/examples/asc_test/master3.py b/examples/asc_test/master3.py
index 4fddda3..e178268 100644
--- a/examples/asc_test/master3.py
+++ b/examples/asc_test/master3.py
@@ -49,7 +49,7 @@ def main():
     kat.loadKatFile('asc_base3.kat')
     try:
         tmpfile = shelve.open(tmpresultfile)
-        result=tmpfile[b'result']
+        result=tmpfile[str('result')]
         tmpfile.close()
     except: raise Exception("Could not open temprary results file {0}".format(tmpresultfile))
 
@@ -104,8 +104,8 @@ def asc_large(tmpkat, mir_name):
 
         print(" current results saved in: {0}".format(tmpfilename))
         tmpfile = shelve.open(tmpfilename)
-        tmpfile[b'out']=out
-        tmpfile[b'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 373a8ae..b3f73a9 100644
--- a/examples/asc_test/master3_plot.py
+++ b/examples/asc_test/master3_plot.py
@@ -62,8 +62,8 @@ def asc_large(mir_name):
 
     try:
         tmpfile = shelve.open(tmpfilename)
-        out=tmpfile[b'out']
-        maxtems=tmpfile[b'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 b7a56d8..2db0e76 100644
--- a/examples/asc_test/master4.py
+++ b/examples/asc_test/master4.py
@@ -5,7 +5,7 @@ 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
@@ -60,7 +60,7 @@ def main():
     kat.loadKatFile('asc_base3.kat')
     try:
         tmpfile = shelve.open(tmpresultfile)
-        result=tmpfile[b'result']
+        result=tmpfile[str('result')]
         tmpfile.close()
     except: raise Exception("Could not open temprary results file {0}".format(tmpresultfile))
     
@@ -77,6 +77,7 @@ def main():
     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)
@@ -85,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
@@ -93,14 +93,14 @@ 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
@@ -198,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:
@@ -211,13 +211,13 @@ 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)    
+        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))
@@ -233,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)
     
diff --git a/examples/asc_test/master4_plot.py b/examples/asc_test/master4_plot.py
index a10dcfd..e4daa5c 100644
--- a/examples/asc_test/master4_plot.py
+++ b/examples/asc_test/master4_plot.py
@@ -49,6 +49,9 @@ def main():
 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)]
@@ -60,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)
@@ -82,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)]
@@ -93,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 1ba6c2b..bb1e445 100644
--- a/examples/asc_test/master5.py
+++ b/examples/asc_test/master5.py
@@ -5,7 +5,7 @@ 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
@@ -15,6 +15,11 @@ import shelve
 import copy
 import sys
 
+# making python2 and python3 compatible
+try:
+   input = raw_input
+except NameError:
+   pass
 
 def main():
 
@@ -51,7 +56,7 @@ def main():
 	kat.loadKatFile('asc_base3.kat')
 	try:
 		tmpfile = shelve.open(tmpresultfile)
-		result=tmpfile[b'result']
+		result=tmpfile[str('result')]
 		tmpfile.close()
 	except: raise Exception("Could not open temprary results file {0}".format(tmpresultfile))
 
@@ -117,7 +122,7 @@ def main():
 	kat.saveScript(tmpkatfile)
 	# now the result variables:
 	tmpfile = shelve.open(tmpresultfile)
-	tmpfile[b'result']=result
+	tmpfile[str('result')]=result
 	tmpfile.close()
 
 
@@ -146,7 +151,7 @@ def get_qs(tmpkat):
 		# 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)
 		kat.psl.npsl.node.setGauss(kat.psl, beam0)
 		kat.parseKatCode("startnode npsl")
 
@@ -162,7 +167,7 @@ def get_qs(tmpkat):
 		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:
@@ -175,15 +180,15 @@ def get_qs(tmpkat):
 
 		# 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)	 
 		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")
+		input("Press enter to continue")
 		return(beam1, beam2, beam3)
 		
 	f=50e3
diff --git a/pykat/__init__.py b/pykat/__init__.py
index 9b14f73..4dda77b 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/commands.py b/pykat/commands.py
index 9458b5f..65c4b89 100644
--- a/pykat/commands.py
+++ b/pykat/commands.py
@@ -167,7 +167,7 @@ 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)
diff --git a/pykat/finesse.py b/pykat/finesse.py
index 62792ae..1e64096 100644
--- a/pykat/finesse.py
+++ b/pykat/finesse.py
@@ -46,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
@@ -817,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)
                     
@@ -984,35 +1002,45 @@ class kat(object):
             
             #if self.verbose: print "Finesse output:"            
             for aline in iter(p.stderr.readline, b""):
-                line = unicode(aline, "utf-8")
+                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)
-                    line = re.sub(r'\x1b[^m]*m', '', line, re.UNICODE)
+                    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()
@@ -1023,8 +1051,8 @@ class kat(object):
                 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()
@@ -1625,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:
-- 
GitLab