diff --git a/docs/conf.py b/docs/conf.py index 1fe1168..2158df7 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -15,7 +15,7 @@ import os import sys sys.path.insert(0, os.path.abspath('..')) -print os.path.abspath('..') +print(os.path.abspath('..')) import matplotlib matplotlib.use('Agg') diff --git a/lumopt/__init__.py b/lumopt/__init__.py index 33ca77f..d8bfe31 100644 --- a/lumopt/__init__.py +++ b/lumopt/__init__.py @@ -1,12 +1,31 @@ -import inspect, os -import pathlib +import os, sys, platform -here=os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # script directory -here=pathlib.Path(here) -root=pathlib.Path(*here.parts[:-1]) -CONFIG={} -#CONFIG['fdtd_path']="/Applications/Lumerical/FDTD Solutions/FDTD Solutions.app/Contents/API/Python" -CONFIG['root']=str(root.absolute()) -print 'CONFIGURATION FILE {}'.format(CONFIG) +# add lumopt.py to system path +lumopt_dir_name = os.path.dirname(__file__) +parent_dir_name = os.path.dirname(lumopt_dir_name) +if parent_dir_name not in sys.path: + sys.path.append(parent_dir_name) -## Geeze this seems awefully complicated, is there no other way to do it better?? +# look for lumapi.py in system path +python_api_path = '' +for dir_name in sys.path: + if os.path.isfile(os.path.join(dir_name, 'lumapi.py')): + python_api_path = dir_name; break +# if search comes out empty, look in the default install path +if not python_api_path: + current_platform = platform.system() + default_api_path = '' + if current_platform == 'Windows': + default_api_path = '/Program Files/Lumerical/FDTD/api/python' + elif current_platform == 'Darwin': + default_api_path = '/Applications/Lumerical/FDTD/FDTD.app/Contents/MacOS/' + elif current_platform == 'Linux': + default_api_path = '/opt/lumerical/FDTD/bin' + default_api_path = os.path.normpath(default_api_path) + if os.path.isfile(os.path.join(default_api_path, 'lumapi.py')): + sys.path.append(default_api_path) + python_api_path = default_api_path + +# save paths for subsequent file access +CONFIG = {'root' : parent_dir_name, 'lumapi' : python_api_path} +print('CONFIGURATION FILE {}'.format(CONFIG)) diff --git a/lumopt/figures_of_merit/modematch.py b/lumopt/figures_of_merit/modematch.py index 29074ed..9e43a41 100644 --- a/lumopt/figures_of_merit/modematch.py +++ b/lumopt/figures_of_merit/modematch.py @@ -2,7 +2,7 @@ import numpy as np from lumopt import CONFIG import sys -from fom import fom +from lumopt.figures_of_merit.fom import fom from lumopt.utilities.fields import Fields @@ -72,11 +72,10 @@ def get_mode(self, sim, plot=False): def put_monitors(self,simulation): ''' Make sure the field monitor is looking at the right wavelength''' - script="select('{}');" \ - "set('override global monitor settings',1);" \ - "set('frequency points',1);" \ - "set('wavelength center',{});".format(self.monitor_name,self.wavelengths[0]) - + script = ( "select('{}');" + + "set('override global monitor settings',1);" + + "set('frequency points',1);" + + "set('wavelength center',{});" ).format(self.monitor_name,self.wavelengths[0]) simulation.fdtd.eval(script) @@ -162,4 +161,4 @@ def add_adjoint_sources(self, sim): # finite_difference_gradients = opt.calculate_finite_differences_gradients(n_derivatives=n_derivatives, dx=5e-9, # central=True, print_res=True) # - # print finite_difference_gradients \ No newline at end of file + # print finite_difference_gradients diff --git a/lumopt/geometries/continuous_epsilon.py b/lumopt/geometries/continuous_epsilon.py index 8a357f8..90825bc 100644 --- a/lumopt/geometries/continuous_epsilon.py +++ b/lumopt/geometries/continuous_epsilon.py @@ -1,3 +1,4 @@ +import sys from geometry import Geometry from lumopt.utilities.materials import Material import lumapi @@ -31,21 +32,21 @@ def add_geo(self,sim,params=None): fdtd.putv('y_geo',self.y) fdtd.putv('z_geo',np.array([self.z-self.depth/2,self.z+self.depth/2])) - script='addimport;' \ - 'temp=zeros(length(x_geo),length(y_geo),2);' \ - 'temp(:,:,1)=eps_geo;' \ - 'temp(:,:,2)=eps_geo;' \ - 'importnk2(sqrt(temp),x_geo,y_geo,z_geo);' \ - 'set("detail",1);' + script = ( 'addimport;' + + 'temp=zeros(length(x_geo),length(y_geo),2);' + + 'temp(:,:,1)=eps_geo;' + + 'temp(:,:,2)=eps_geo;' + + 'importnk2(sqrt(temp),x_geo,y_geo,z_geo);' + + 'set("detail",1);' ) if self.addmesh: - mesh_script='addmesh;' \ - 'set("x min",{});' \ - 'set("x max",{});' \ - 'set("y min",{});' \ - 'set("y max",{});' \ - 'set("dx",{});' \ - 'set("dy",{});'.format(np.amin(self.x),np.amax(self.x),np.amin(self.y),np.amax(self.y),self.x[1]-self.x[0],self.y[1]-self.y[0]) + mesh_script = ( 'addmesh;' + + 'set("x min",{});' + + 'set("x max",{});' + + 'set("y min",{});' + + 'set("y max",{});' + + 'set("dx",{});' + + 'set("dy",{});').format(np.amin(self.x),np.amax(self.x),np.amin(self.y),np.amax(self.y),self.x[1]-self.x[0],self.y[1]-self.y[0]) fdtd.eval(mesh_script) fdtd.eval(script) @@ -57,9 +58,9 @@ def calculate_gradients(self, gradient_fields, wavelength,real=True): for x in self.x: for y in self.y:#,y in zip(xx.reshape(-1),yy.reshape(-1)): derivs.append(gradient_fields.integrate_square(center=(x,y),box=(dx,dy),z=self.z,wl=wavelength,real=real)) - print '.', - print '' - print 'Done' + sys.stdout.write('.'); sys.stdout.flush() + print('') + print('Done') return derivs def initialize(self,wavelengths,opt): @@ -138,21 +139,21 @@ def add_geo(self,sim,params=None): fdtd.putv('y_geo',self.y) fdtd.putv('z_geo',[self.z-self.depth/2,self.z+self.depth/2]) - script='addimport;' \ - 'temp=zeros(length(x_geo),length(y_geo),2);' \ - 'temp(:,:,1)=eps_geo;' \ - 'temp(:,:,2)=eps_geo;' \ - 'importnk2(sqrt(temp),x_geo,y_geo,z_geo);' \ - 'set("detail",1);' + script = ( 'addimport;' + + 'temp=zeros(length(x_geo),length(y_geo),2);' + + 'temp(:,:,1)=eps_geo;' + + 'temp(:,:,2)=eps_geo;' + + 'importnk2(sqrt(temp),x_geo,y_geo,z_geo);' + + 'set("detail",1);' ) if self.addmesh: - mesh_script='addmesh;' \ - 'set("x min",{});' \ - 'set("x max",{});' \ - 'set("y min",{});' \ - 'set("y max",{});' \ - 'set("dx",{});' \ - 'set("dy",{});'.format(np.amin(self.x),np.amax(self.x),np.amin(self.y),np.amax(self.y),self.x[1]-self.x[0],self.y[1]-self.y[0]) + mesh_script = ( 'addmesh;' + + 'set("x min",{});' + + 'set("x max",{});' + + 'set("y min",{});' + + 'set("y max",{});' + + 'set("dx",{});' + + 'set("dy",{});' ).format(np.amin(self.x),np.amax(self.x),np.amin(self.y),np.amax(self.y),self.x[1]-self.x[0],self.y[1]-self.y[0]) fdtd.eval(mesh_script) fdtd.eval(script) @@ -192,8 +193,8 @@ def get_eps_derivatives(self): d_eps = self.func(d_params)[0] eps_derivatives.append((d_eps - current_eps)/self.dx) - """eps_derivatives are the derivatives for the output of self.func . We need - the derivatives on the points of the Yee Cell though since nternally, FDTD interpolate + """eps_derivatives are the derivatives for the output of self.func . We need + the derivatives on the points of the Yee Cell though since nternally, FDTD interpolate eps onto the Yee Grid. Here I assume that the mesh dimensions are constant in the area so things are easier to calculate""" @@ -243,44 +244,44 @@ def add_geo(self,sim,params=None): fdtd.putv('y_geo',self.y) fdtd.putv('z_geo',self.z) - script='addimport;' \ - 'importnk2(sqrt(eps_geo),x_geo,y_geo,z_geo);' \ - 'set("detail",1);' + script = ( 'addimport;' + + 'importnk2(sqrt(eps_geo),x_geo,y_geo,z_geo);' + + 'set("detail",1);' ) if self.addmesh: - mesh_script='addmesh;' \ - 'set("x min",{});' \ - 'set("x max",{});' \ - 'set("y min",{});' \ - 'set("y max",{});' \ - 'set("z min",{});' \ - 'set("z max",{});' \ - 'set("dx",{});' \ - 'set("dy",{});' \ - 'set("dz",{});'.format(np.amin(self.x),np.amax(self.x), - np.amin(self.y),np.amax(self.y), - np.amin(self.z),np.amax(self.z), - self.x[1]-self.x[0],self.y[1]-self.y[0], - self.z[1]-self.z[0]) - - monitor_script = 'select("opt_fields");' \ - 'set("x min",{});' \ - 'set("x max",{});' \ - 'set("y min",{});' \ - 'set("y max",{});' \ - 'set("z min",{});' \ - 'set("z max",{});'.format(np.amin(self.x), np.amax(self.x), - np.amin(self.y), np.amax(self.y), - np.amin(self.z), np.amax(self.z)) - index_script = 'select("opt_fields_index");' \ - 'set("x min",{});' \ - 'set("x max",{});' \ - 'set("y min",{});' \ - 'set("y max",{});' \ - 'set("z min",{});' \ - 'set("z max",{});'.format(np.amin(self.x), np.amax(self.x), - np.amin(self.y), np.amax(self.y), - np.amin(self.z), np.amax(self.z)) + mesh_script = ( 'addmesh;' + + 'set("x min",{});' + + 'set("x max",{});' + + 'set("y min",{});' + + 'set("y max",{});' + + 'set("z min",{});' + + 'set("z max",{});' + + 'set("dx",{});' + + 'set("dy",{});' + + 'set("dz",{});' ).format(np.amin(self.x),np.amax(self.x), + np.amin(self.y),np.amax(self.y), + np.amin(self.z),np.amax(self.z), + self.x[1]-self.x[0],self.y[1]-self.y[0], + self.z[1]-self.z[0]) + + monitor_script = ( 'select("opt_fields");' + + 'set("x min",{});' + + 'set("x max",{});' + + 'set("y min",{});' + + 'set("y max",{});' + + 'set("z min",{});' + + 'set("z max",{});' ).format(np.amin(self.x), np.amax(self.x), + np.amin(self.y), np.amax(self.y), + np.amin(self.z), np.amax(self.z)) + index_script = ( 'select("opt_fields_index");' + + 'set("x min",{});' + + 'set("x max",{});' + + 'set("y min",{});' + + 'set("y max",{});' + + 'set("z min",{});' + + 'set("z max",{});' ).format(np.amin(self.x), np.amax(self.x), + np.amin(self.y), np.amax(self.y), + np.amin(self.z), np.amax(self.z)) fdtd.eval(mesh_script+monitor_script+index_script) fdtd.eval(script) @@ -368,45 +369,45 @@ def add_geo(self,sim,params=None): fdtd.putv('y_geo',self.y) fdtd.putv('z_geo',self.z) - script='addimport;' \ - 'importnk2(sqrt(eps_geo),x_geo,y_geo,z_geo);' \ - 'set("data offset in yee cell",1);' \ - 'set("detail",1);' + script = ( 'addimport;' + + 'importnk2(sqrt(eps_geo),x_geo,y_geo,z_geo);' + + 'set("data offset in yee cell",1);' + + 'set("detail",1);' ) if self.addmesh: - mesh_script='addmesh;' \ - 'set("x min",{});' \ - 'set("x max",{});' \ - 'set("y min",{});' \ - 'set("y max",{});' \ - 'set("z min",{});' \ - 'set("z max",{});' \ - 'set("dx",{});' \ - 'set("dy",{});' \ - 'set("dz",{});'.format(np.amin(self.x),np.amax(self.x), - np.amin(self.y),np.amax(self.y), - np.amin(self.z),np.amax(self.z), - self.x[1]-self.x[0],self.y[1]-self.y[0], - self.z[1]-self.z[0]) - - monitor_script = 'select("opt_fields");' \ - 'set("x min",{});' \ - 'set("x max",{});' \ - 'set("y min",{});' \ - 'set("y max",{});' \ - 'set("z min",{});' \ - 'set("z max",{});'.format(np.amin(self.x), np.amax(self.x), - np.amin(self.y), np.amax(self.y), - np.amin(self.z), np.amax(self.z)) - index_script = 'select("opt_fields_index");' \ - 'set("x min",{});' \ - 'set("x max",{});' \ - 'set("y min",{});' \ - 'set("y max",{});' \ - 'set("z min",{});' \ - 'set("z max",{});'.format(np.amin(self.x), np.amax(self.x), - np.amin(self.y), np.amax(self.y), - np.amin(self.z), np.amax(self.z)) + mesh_script = ( 'addmesh;' + + 'set("x min",{});' + + 'set("x max",{});' + + 'set("y min",{});' + + 'set("y max",{});' + + 'set("z min",{});' + + 'set("z max",{});' + + 'set("dx",{});' + + 'set("dy",{});' + + 'set("dz",{});' ).format(np.amin(self.x),np.amax(self.x), + np.amin(self.y),np.amax(self.y), + np.amin(self.z),np.amax(self.z), + self.x[1]-self.x[0],self.y[1]-self.y[0], + self.z[1]-self.z[0]) + + monitor_script = ( 'select("opt_fields");' + + 'set("x min",{});' + + 'set("x max",{});' + + 'set("y min",{});' + + 'set("y max",{});' + + 'set("z min",{});' + + 'set("z max",{});' ).format(np.amin(self.x), np.amax(self.x), + np.amin(self.y), np.amax(self.y), + np.amin(self.z), np.amax(self.z)) + index_script = ( 'select("opt_fields_index");' + + 'set("x min",{});' + + 'set("x max",{});' + + 'set("y min",{});' + + 'set("y max",{});' + + 'set("z min",{});' + + 'set("z max",{});' ).format(np.amin(self.x), np.amax(self.x), + np.amin(self.y), np.amax(self.y), + np.amin(self.z), np.amax(self.z)) fdtd.eval(mesh_script+monitor_script+index_script) fdtd.eval(script) @@ -493,45 +494,45 @@ def add_geo(self,sim,params=None): fdtd.putv('y_geo',self.y) fdtd.putv('z_geo',self.z) - script='addimport;' \ - 'importnk2(sqrt(eps_geo),x_geo,y_geo,z_geo);' \ - 'set("data offset in yee cell",1);' \ - 'set("detail",1);' + script = ( 'addimport;' + + 'importnk2(sqrt(eps_geo),x_geo,y_geo,z_geo);' + + 'set("data offset in yee cell",1);' + + 'set("detail",1);' ) if self.addmesh: - mesh_script='addmesh;' \ - 'set("x min",{});' \ - 'set("x max",{});' \ - 'set("y min",{});' \ - 'set("y max",{});' \ - 'set("z min",{});' \ - 'set("z max",{});' \ - 'set("dx",{});' \ - 'set("dy",{});' \ - 'set("dz",{});'.format(np.amin(self.x),np.amax(self.x), - np.amin(self.y),np.amax(self.y), - np.amin(self.z),np.amax(self.z), - self.x[1]-self.x[0],self.y[1]-self.y[0], - self.z[1]-self.z[0]) - - monitor_script = 'select("opt_fields");' \ - 'set("x min",{});' \ - 'set("x max",{});' \ - 'set("y min",{});' \ - 'set("y max",{});' \ - 'set("z min",{});' \ - 'set("z max",{});'.format(np.amin(self.x), np.amax(self.x), - np.amin(self.y), np.amax(self.y), - np.amin(self.z), np.amax(self.z)) - index_script = 'select("opt_fields_index");' \ - 'set("x min",{});' \ - 'set("x max",{});' \ - 'set("y min",{});' \ - 'set("y max",{});' \ - 'set("z min",{});' \ - 'set("z max",{});'.format(np.amin(self.x), np.amax(self.x), - np.amin(self.y), np.amax(self.y), - np.amin(self.z), np.amax(self.z)) + mesh_script = ( 'addmesh;' + + 'set("x min",{});' + + 'set("x max",{});' + + 'set("y min",{});' + + 'set("y max",{});' + + 'set("z min",{});' + + 'set("z max",{});' + + 'set("dx",{});' + + 'set("dy",{});' + + 'set("dz",{});' ).format(np.amin(self.x),np.amax(self.x), + np.amin(self.y),np.amax(self.y), + np.amin(self.z),np.amax(self.z), + self.x[1]-self.x[0],self.y[1]-self.y[0], + self.z[1]-self.z[0]) + + monitor_script = ( 'select("opt_fields");' + + 'set("x min",{});' + + 'set("x max",{});' + + 'set("y min",{});' + + 'set("y max",{});' + + 'set("z min",{});' + + 'set("z max",{});' ).format(np.amin(self.x), np.amax(self.x), + np.amin(self.y), np.amax(self.y), + np.amin(self.z), np.amax(self.z)) + index_script = ( 'select("opt_fields_index");' + + 'set("x min",{});' + + 'set("x max",{});' + + 'set("y min",{});' + + 'set("y max",{});' + + 'set("z min",{});' + + 'set("z max",{});' ).format(np.amin(self.x), np.amax(self.x), + np.amin(self.y), np.amax(self.y), + np.amin(self.z), np.amax(self.z)) fdtd.eval(mesh_script+monitor_script+index_script) fdtd.eval(script) @@ -581,4 +582,4 @@ def add_geo(self,sim,params=None): y_geo=opt.geometry.y - print 'ha' \ No newline at end of file + print('ha') diff --git a/lumopt/geometries/geometry.py b/lumopt/geometries/geometry.py index 7772997..0bf2b59 100644 --- a/lumopt/geometries/geometry.py +++ b/lumopt/geometries/geometry.py @@ -104,7 +104,7 @@ def get_d_eps_d_params(self,dx): current_eps=self.get_eps()[0] current_params=self.get_current_params() d_epses=[] - print 'Getting d eps' + print('Getting d eps') for i,param in enumerate(current_params): d_params = current_params.copy() d_params[i] = param + dx @@ -119,7 +119,7 @@ def get_d_eps_d_params_update(self,dx): current_eps, x, y, z, sim = self.get_eps(return_sim=True) current_params=self.get_current_params() d_epses=[] - print 'Getting d eps' + print('Getting d eps') for i,param in enumerate(current_params): d_params = current_params.copy() d_params[i] = param + dx diff --git a/lumopt/geometries/polygon.py b/lumopt/geometries/polygon.py index 3f44984..63f9880 100644 --- a/lumopt/geometries/polygon.py +++ b/lumopt/geometries/polygon.py @@ -1,4 +1,4 @@ -from geometry import Geometry +from lumopt.geometries.geometry import Geometry import numpy as np from lumopt.utilities.edge import Edge import scipy @@ -74,8 +74,8 @@ def calculate_gradients(self,gradient_fields,wavelength,real=True): gradient_pairs_edges=[] for edge in self.edges: gradient_pairs_edges.append(edge.derivative(gradient_fields,wavelength,n_points=self.edge_precision,real=real)) - print '.', - print '' + print('.') + print('') #the gradients returned for an edge derivative are the gradients with respect to moving each end point perpendicular to that edge #This is not exactly what we are looking for here, since we want the derivative w/ respect to moving each point #in the x or y direction, so coming up is a lot of projections... @@ -127,21 +127,21 @@ def add_geo(self, sim, params=None): points = np.reshape(params, (-1, 2)) fdtd.putv('vertices', points) - script = "addpoly;" \ - "set('name','polygon_{0}');" \ - "set('z',{1});" \ - "set('x',0);" \ - "set('y',0);" \ - "set('z span',{2});" \ - "set('vertices',vertices);" \ - "{3}".format(self.hash, self.z, self.depth, self.eps_in.set_script()) + script = ("addpoly;" + + "set('name','polygon_{0}');" + + "set('z',{1});" + + "set('x',0);" + + "set('y',0);" + + "set('z span',{2});" + + "set('vertices',vertices);" + + "{3}").format(self.hash, self.z, self.depth, self.eps_in.set_script()) fdtd.eval(script) def update_geo_in_sim(self,sim,params): points = np.reshape(params, (-1, 2)) sim.fdtd.putv('vertices', points) - script = "select('polygon_{0}');" \ - "set('vertices',vertices);".format(self.hash) + script = ("select('polygon_{0}');" + + "set('vertices',vertices);").format(self.hash) sim.fdtd.eval(script) def plot(self,ax): @@ -256,17 +256,17 @@ def add_poly_script(self,points,only_update=False): #vertices_string=format(matlab.double(points.tolist())).replace('],[','];[') vertices_string=np.array2string(points,max_line_width=10e10,floatmode='unique',separator=',').replace(',\n',';') if not only_update: - script = "addpoly;" \ - "set('name','polygon_{0}');".format(self.hash) + script = ( "addpoly;" + + "set('name','polygon_{0}');" ).format(self.hash) else: script = "select('polygon_{0}');".format(self.hash) - script=script+ "set('z',{1});" \ - "set('x',0);" \ - "set('y',0);" \ - "set('z span',{2});" \ - "set('vertices',{3});" \ - "{4}".format(self.hash, self.z, self.depth,vertices_string, self.eps_in.set_script()) + script += ( "set('z',{1});" + + "set('x',0);" + + "set('y',0);" + + "set('z span',{2});" + + "set('vertices',{3});" + + "{4}" ).format(self.hash, self.z, self.depth,vertices_string, self.eps_in.set_script()) return script def add_geo(self, sim, params=None,eval=True,only_update=False): diff --git a/lumopt/lumerical_methods/lumerical_scripts.py b/lumopt/lumerical_methods/lumerical_scripts.py index 4ae4d9d..c0202ec 100644 --- a/lumopt/lumerical_methods/lumerical_scripts.py +++ b/lumopt/lumerical_methods/lumerical_scripts.py @@ -12,29 +12,29 @@ def get_source_power(fdtd, wl=1550e-9): def add_point_monitor(fdtd,monitor_name,position): '''This script adds a point monitor in a simulation''' - script = "addpower;" \ - "set('name','{}');" \ - "set('monitor type','Point');" \ - "set('x',{});" \ - "set('y',{});" \ - "set('z',{});".format(monitor_name,position[0],position[1],position[2]) + script = ( "addpower;" + + "set('name','{}');" + + "set('monitor type','Point');" + + "set('x',{});" + + "set('y',{});" + + "set('z',{});" ).format(monitor_name,position[0],position[1],position[2]) fdtd.eval(script) def add_point_monitor_script(monitor_name,position): '''This script adds a point monitor in a simulation''' - script = "addpower;" \ - "set('name','{}');" \ - "set('monitor type','Point');" \ - "set('x',{});" \ - "set('y',{});" \ - "set('z',{});".format(monitor_name,position[0],position[1],position[2]) + script = ( "addpower;" + + "set('name','{}');" + + "set('monitor type','Point');" + + "set('x',{});" + + "set('y',{});" + + "set('z',{});" ).format(monitor_name,position[0],position[1],position[2]) return script def remove_interpolation_on_monitor(fdtd,monitor_name='opt_fields'): ''' Removes the interpolation from the monitor (not to be used lightly!)''' - script="select({});" \ - "set('spatial interpolation','none');".format(monitor_name) + script = ( "select({});" + + "set('spatial interpolation','none');" ).format(monitor_name) fdtd.eval(script) return @@ -46,16 +46,16 @@ def get_fields_no_interp(fdtd, monitor_name, get_eps=False, get_D=False, get_H=F It returns a Field object''' #print 'getting raw fields for {}'.format(monitor_name) # script="m='{}';".format(monitor_name) - # script+="x = getdata(m,'x');"\ - # "y = getdata(m,'y');"\ - # "z = getdata(m,'z');"\ - # "f = getdata(m,'f');"\ - # "delta_x = getdata(m,'delta_x');"\ - # "delta_y = getdata(m,'delta_y');"\ - # "if (getdata(m,'dimension')==2){ delta_z=0; } else { delta_z=getdata(m,'delta_z');}"\ - # "Ex = getdata(m, 'Ex');" \ - # "Ey = getdata(m, 'Ey');"\ - # "Ez = getdata(m, 'Ez');" + # script += ( "x = getdata(m,'x');" + # + "y = getdata(m,'y');" + # + "z = getdata(m,'z');" + # + "f = getdata(m,'f');" + # + "delta_x = getdata(m,'delta_x');" + # + "delta_y = getdata(m,'delta_y');" + # + "if (getdata(m,'dimension')==2){ delta_z=0; } else { delta_z=getdata(m,'delta_z');}" + # + "Ex = getdata(m, 'Ex');" + # + "Ey = getdata(m, 'Ey');" + # + "Ez = getdata(m, 'Ez');" # lumapi.evalScript(handle, script) # fields_x = lumapi.getVar(handle, "x") # fields_y = lumapi.getVar(handle, "y") @@ -73,12 +73,12 @@ def get_fields_no_interp(fdtd, monitor_name, get_eps=False, get_D=False, get_H=F # fields_lambda=c/fields_f # if get_eps: - script="index_x=getdata('{0}','index_x');" \ - "index_y=getdata('{0}','index_y');" \ - "index_z=getdata('{0}','index_z');" \ - "eps_x=index_x^2;" \ - "eps_y=index_y^2;" \ - "eps_z=index_z^2;".format(monitor_name+ '_index') + script = ( "index_x=getdata('{0}','index_x');" + + "index_y=getdata('{0}','index_y');" + + "index_z=getdata('{0}','index_z');" + + "eps_x=index_x^2;" + + "eps_y=index_y^2;" + + "eps_z=index_z^2;" ).format(monitor_name+ '_index') fdtd.eval(script) fields_eps_x = fdtd.getv("eps_x") fields_eps_y = fdtd.getv("eps_y") @@ -134,10 +134,10 @@ def get_fields(fdtd, monitor_name, get_eps=False, get_D=False, get_H=False,noint return get_fields_interp(fdtd, monitor_name, get_eps, get_D, get_H) def get_eps_from_sim(fdtd): - script='select("FDTD");' \ - 'set("simulation time",0.1e-15);' \ - 'save("eps_extract");' \ - 'run;' + script = ( 'select("FDTD");' + + 'set("simulation time",0.1e-15);' + + 'save("eps_extract");' + + 'run;' ) fdtd.eval(script) # lumapi.evalScript(handle, "eps=getresult('{}','eps');".format('opt_fields' + '_index')) # #lumapi.evalScript(handle, "eps=getresult('{}','eps');".format('opt_fields' + '_D_index')) @@ -150,15 +150,15 @@ def get_eps_from_sim(fdtd): # y=lumapi.getVar(handle,'y') # z=lumapi.getVar(handle,'z') - script = "index_x=getdata('{0}','index_x');" \ - "index_y=getdata('{0}','index_y');" \ - "index_z=getdata('{0}','index_z');" \ - "eps_x=index_x^2;" \ - "eps_y=index_y^2;" \ - "eps_z=index_z^2;" \ - "x = getdata('{0}','x');"\ - "y = getdata('{0}','y');"\ - "z = getdata('{0}','z');".format('opt_fields' + '_index') + script = ( "index_x=getdata('{0}','index_x');" + + "index_y=getdata('{0}','index_y');" + + "index_z=getdata('{0}','index_z');" + + "eps_x=index_x^2;" + + "eps_y=index_y^2;" + + "eps_z=index_z^2;" + + "x = getdata('{0}','x');" + + "y = getdata('{0}','y');" + + "z = getdata('{0}','z');").format('opt_fields' + '_index') fdtd.eval(script) fields_eps_x = fdtd.getv("eps_x") fields_eps_y = fdtd.getv("eps_y") @@ -212,14 +212,16 @@ def make_fields_dataset(fdtd,fields,prefactor): fdtd.eval('EM.addattribute("E", E*prefactor);') fdtd.eval('EM.addattribute("H", H*prefactor);') # Optional -def copy_properties(fdtd,origin,destination,properties= ['x', 'y', 'z', 'x_span', 'y_span', 'z_span']): +def copy_properties(fdtd, origin, destination, properties = ['x', 'y', 'z', 'x_span', 'y_span', 'z_span']): + origin = origin if 'model::' in origin else 'model::' + origin orig = fdtd.getObjectById(origin) + destination = destination if 'model::' in destination else 'model::' + destination dest = fdtd.getObjectById(destination) for thing in properties: try: dest.__setattr__(thing.replace(' ','_'), orig.__getattr__(thing.replace(' ','_'))) except: - print 'Could not copy {} from {} to {} '.format(thing,origin,destination) + print('Could not copy {} from {} to {} '.format(thing, origin, destination)) def set_injection_axis(fdtd,source_name): src = fdtd.getObjectById(source_name) @@ -281,18 +283,17 @@ def add_dipole_script(x, y, z, wavelength, dipole, name_suffix='', magnetic=Fals if not amplitude==0: lumerical_script = "adddipole;" if magnetic: lumerical_script += "set('dipole type','Magnetic dipole');" - lumerical_script += "set('name','{8}');" \ - "set('x',{0});" \ - "set('y',{1});" \ - "set('z',{2});" \ - "set('theta',{3});" \ - "set('phi',{4});" \ - "set('phase',{5});" \ - "set('center wavelength',{6});" \ - "set ('wavelength span',0);" \ - "baseAmp=get('base amplitude');" \ - "set('amplitude',{7}/baseAmp);".format(x, y, z, theta, phi, phase_deg, wavelength, - amplitude, dir + name_suffix) + lumerical_script += ( "set('name','{8}');" + + "set('x',{0});" + + "set('y',{1});" + + "set('z',{2});" + + "set('theta',{3});" + + "set('phi',{4});" + + "set('phase',{5});" + + "set('center wavelength',{6});" + + "set ('wavelength span',0);" + + "baseAmp=get('base amplitude');" + + "set('amplitude',{7}/baseAmp);" ).format(x, y, z, theta, phi, phase_deg, wavelength, amplitude, dir + name_suffix) script+=lumerical_script diff --git a/lumopt/optimization.py b/lumopt/optimization.py index ec5ddf7..017077b 100644 --- a/lumopt/optimization.py +++ b/lumopt/optimization.py @@ -1,5 +1,4 @@ -from lumopt.lumerical_methods.lumerical_scripts import add_D_monitors_to_fields_monitors, \ - remove_interpolation_on_monitor, add_index_to_fields_monitors, set_spatial_interp +from lumopt.lumerical_methods.lumerical_scripts import add_D_monitors_to_fields_monitors, remove_interpolation_on_monitor, add_index_to_fields_monitors, set_spatial_interp from lumopt.utilities.simulation import Simulation from lumopt.utilities.gradients import Gradient_fields from time import sleep @@ -245,7 +244,7 @@ def run_forward_solves(self, plotfields=False): ''' if self.verbose: - print 'Running Forward Solves' + print('Running Forward Solves') # create the simulation forward_sim = self.make_sim() @@ -271,7 +270,7 @@ def run_adjoint_solves(self, plotfields=False): Generates the adjoint simulations, runs them and extacts the adjoint fields ''' if self.verbose: - print 'Running adjoint Solves' + print('Running adjoint Solves') adjoint_sim = self.make_sim() @@ -290,7 +289,7 @@ def make_adjoint_solves(self, sleep_time=1000): Generates the adjoint simulations, moslty for testing ''' if self.verbose: - print 'Running adjoint Solves' + print('Running adjoint Solves') adjoint_sim = self.make_sim() @@ -338,7 +337,7 @@ def calculate_finite_differences_gradients_2(self, n_derivatives=range(4, 6), dx self.run_forward_solves() self.run_adjoint_solves() adjoint_gradients=self.calculate_gradients(real=False) - print "Adjoint gradients= {}".format(adjoint_gradients) + print("Adjoint gradients= {}".format(adjoint_gradients)) current_fom = self.fomHist[-1] current_eps = deepcopy(self.forward_fields.eps.copy()) current_E = deepcopy(self.forward_fields.E) @@ -360,17 +359,17 @@ def calculate_finite_differences_gradients_2(self, n_derivatives=range(4, 6), dx plt.pcolormesh(np.real(d_eps[:, :, 0, 0, 2]).transpose()) plt.show() recalculated_adjoint_deriv = trapz3D(np.sum(sparse_pert_E*d_eps,axis=-1)[:,:,:,0],self.forward_fields.x,self.forward_fields.y,self.forward_fields.z) - print 'recalculated adjoint gradients={}'.format(recalculated_adjoint_deriv) + print('recalculated adjoint gradients={}'.format(recalculated_adjoint_deriv)) recalculated_adjoint_derivs.append(recalculated_adjoint_deriv) else: - print 'central not supported on this on yet' + print('central not supported on this on yet') if print_res: print('Derivative n {}={}'.format(i, deriv)) self.geometry.update_geometry(params) if print_res: - print finite_differences_gradients - print recalculated_adjoint_derivs + print(finite_differences_gradients) + print(recalculated_adjoint_derivs) return finite_differences_gradients, recalculated_adjoint_derivs,adjoint_gradients @@ -435,7 +434,7 @@ def calculate_finite_differences_gradients(self, n_derivatives=range(4,6), dx=3e self.geometry.update_geometry(params) if print_res: - print finite_differences_gradients + print(finite_differences_gradients) return finite_differences_gradients @@ -444,7 +443,7 @@ def calculate_gradients(self,real=True): '''Uses the forward and adjoint fields to calculate the derivatives to the optimization parameters Assumes the forward and adjoint solves have been run''' if self.verbose: - print 'Calculating Gradients' + print('Calculating Gradients') # Create the gradient fields self.gradient_fields = Gradient_fields(forward_fields=self.forward_fields, adjoint_fields=self.adjoint_fields) @@ -470,7 +469,7 @@ def get_caller(num): return inspect.stack()[num] # 1 is get_caller's caller calling_file= os.path.abspath(inspect.getfile(get_caller(3)[0])) except: - print 'Couldnt copy python setupfile' + print('Couldnt copy python setupfile') directories = os.listdir(os.getcwd()) @@ -480,7 +479,7 @@ def get_caller(num): old = - 1 if old == 25: - print 'Too many optimization folders in {}'.format(os.getcwd()) + print('Too many optimization folders in {}'.format(os.getcwd())) raise ValueError new_dir_name = 'opts_{}'.format(old + 1) @@ -521,4 +520,4 @@ def get_caller(num): opt = Optimization(base_script=base_script, fom=fom, geometry=geometry, optimizer=optimizer) - opt.run() \ No newline at end of file + opt.run() diff --git a/lumopt/optimizers/generic_optimizers.py b/lumopt/optimizers/generic_optimizers.py index 63f079e..fb5398c 100644 --- a/lumopt/optimizers/generic_optimizers.py +++ b/lumopt/optimizers/generic_optimizers.py @@ -301,7 +301,7 @@ def callable_jac_local(params): def run(self,verbose=True): print('Running Scipy Optimizer') - print 'bounds= {}'.format(self.bounds) - print 'start= {}'.format(self.start_point) + print('bounds= {}'.format(self.bounds)) + print('start= {}'.format(self.start_point)) res= sci.minimize(fun=self.callable_fom,x0=self.start_point,jac=self.callable_jac,bounds=self.bounds,callback=self.callback,options={'maxiter':self.max_iter,'disp':True,'gtol':self.pgtol},method=self.method) - return res \ No newline at end of file + return res diff --git a/lumopt/utilities/fields.py b/lumopt/utilities/fields.py index 7666e5e..c67081b 100644 --- a/lumopt/utilities/fields.py +++ b/lumopt/utilities/fields.py @@ -150,7 +150,7 @@ def calculate_overlap(self,other_field,remove_E=False,remove_H=False): '''Calculates the mode overlap with another field. This assumes this mode has been normalized''' if not self.normalized: self.normalize_power() - print 'Normalized the mode being modematched to' + print('Normalized the mode being modematched to') if not (len(self.x)==len(other_field.x) and len(self.y)==len(other_field.y) and len(self.z)==len(other_field.z) and len(self.wl)==len(other_field.wl)): raise ValueError('Fields are not on same grid, (or not the same amount of wavelengths Modematch does not support this (write a method!!)') diff --git a/lumopt/utilities/load_lumerical_scripts.py b/lumopt/utilities/load_lumerical_scripts.py index 3bf61cd..093bb12 100644 --- a/lumopt/utilities/load_lumerical_scripts.py +++ b/lumopt/utilities/load_lumerical_scripts.py @@ -7,7 +7,7 @@ def load_from_lsf(script_file_name): :return: ''' - with open(script_file_name, 'rb') as text_file: + with open(script_file_name, 'r') as text_file: lines = [line.strip().split('#',1)[0] for line in text_file.readlines()] script="" diff --git a/lumopt/utilities/materials.py b/lumopt/utilities/materials.py index b26dd10..c86691a 100644 --- a/lumopt/utilities/materials.py +++ b/lumopt/utilities/materials.py @@ -85,5 +85,5 @@ def get_eps(self,wl): if __name__=='__main__': test=Material() test.initialize() - print test.permittivities - print test.get_eps(1550e-9) \ No newline at end of file + print(test.permittivities) + print(test.get_eps(1550e-9)) diff --git a/lumopt/utilities/plotter.py b/lumopt/utilities/plotter.py index c5f6ff3..7d07e8c 100644 --- a/lumopt/utilities/plotter.py +++ b/lumopt/utilities/plotter.py @@ -45,13 +45,13 @@ def update(self,optimization): try: optimization.optimizations[0].gradient_fields.plot_eps(self.ax[1,0]) except: - print "can't plot geometry" + print("can't plot geometry") try: optimization.optimizations[0].gradient_fields.plot(self.fig,self.ax[1,1],self.ax[1,2]) except: - print "can't plot gradient fields" + print("can't plot gradient fields") # optimization.optimizations[0].geometry.plot(self.ax[1,0]) - print 'plot updated' + print('plot updated') plt.tight_layout() self.fig.canvas.draw() self.fig.canvas.flush_events() diff --git a/lumopt/utilities/scipy_wrappers.py b/lumopt/utilities/scipy_wrappers.py index a271ba5..821ed9e 100644 --- a/lumopt/utilities/scipy_wrappers.py +++ b/lumopt/utilities/scipy_wrappers.py @@ -143,28 +143,28 @@ def demo_interpolator(): points = (np.array([3, 4]), np.array([1, 2]),np.array([5])) vals = np.array([10,11,12,13]).reshape(2,2,1) - print vals.shape + print(vals.shape) wi=wrapped_GridInterpolator(points,vals) - print wi((3.5,1.5,5)) - print wi((3.5, 1, 5)) - print wi([(3.5,1.5,5),(3.5,1,5)]) + print(wi((3.5,1.5,5))) + print(wi((3.5, 1, 5))) + print(wi([(3.5,1.5,5),(3.5,1,5)])) points=(np.array([1]),np.array([2])) vals=np.array([5]).reshape(1,1) wi = wrapped_GridInterpolator(points, vals) - print wi((1, 2)) + print(wi((1, 2))) ti=RegularGridInterpolator(points,vals) try: - print ti((3.5,1.5,5)) + print(ti((3.5,1.5,5))) except: - print 'It didnt work for the regular interpolator!' + print('It didnt work for the regular interpolator!') if __name__=='__main__': demo_interpolator() import os - print os.getcwd() - print dblsimps(lambda x, y:x * y, 0, 10, -2, 2,points_per_dimension=3) \ No newline at end of file + print(os.getcwd()) + print(dblsimps(lambda x, y:x * y, 0, 10, -2, 2,points_per_dimension=3))