Skip to content

Commit

Permalink
Fixed platform specific code parsing errors.
Browse files Browse the repository at this point in the history
  • Loading branch information
Roberto committed Dec 14, 2018
1 parent b7cf1ae commit 81ab810
Show file tree
Hide file tree
Showing 14 changed files with 293 additions and 274 deletions.
2 changes: 1 addition & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')

Expand Down
39 changes: 29 additions & 10 deletions lumopt/__init__.py
Original file line number Diff line number Diff line change
@@ -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))
13 changes: 6 additions & 7 deletions lumopt/figures_of_merit/modematch.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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
# print finite_difference_gradients
285 changes: 143 additions & 142 deletions lumopt/geometries/continuous_epsilon.py

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions lumopt/geometries/geometry.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
42 changes: 21 additions & 21 deletions lumopt/geometries/polygon.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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...
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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):
Expand Down
115 changes: 58 additions & 57 deletions lumopt/lumerical_methods/lumerical_scripts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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")
Expand All @@ -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")
Expand Down Expand Up @@ -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'))
Expand All @@ -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")
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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

Expand Down
Loading

0 comments on commit 81ab810

Please sign in to comment.