Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sourcery refactored master branch #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 19 additions & 14 deletions examples/goos/bend90/bend90.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,38 +109,43 @@ def make_objective(eps: goos.Shape, stage: str, sim_3d: bool):
pml_thickness = [400, 400, 400, 400, 0, 0]

sim = maxwell.fdfd_simulation(
name="sim_{}".format(stage),
name=f"sim_{stage}",
wavelength=1550,
eps=eps,
solver_info=solver_info,
sources=[
maxwell.WaveguideModeSource(center=[-1400, 0, 0],
extents=[0, 2500, 1000],
normal=[1, 0, 0],
mode_num=0,
power=1)
maxwell.WaveguideModeSource(
center=[-1400, 0, 0],
extents=[0, 2500, 1000],
normal=[1, 0, 0],
mode_num=0,
power=1,
)
Comment on lines -112 to +123
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function make_objective refactored with the following changes:

],
simulation_space=maxwell.SimulationSpace(
mesh=maxwell.UniformMesh(dx=40),
sim_region=goos.Box3d(
center=[0, 0, 0],
extents=[4000, 4000, sim_z_extent],
),
pml_thickness=pml_thickness),
pml_thickness=pml_thickness,
),
background=goos.material.Material(index=1.0),
outputs=[
maxwell.Epsilon(name="eps"),
maxwell.ElectricField(name="field"),
maxwell.WaveguideModeOverlap(name="overlap",
center=[0, 1400, 0],
extents=[2500, 0, 1000],
normal=[0, 1, 0],
mode_num=0,
power=1),
maxwell.WaveguideModeOverlap(
name="overlap",
center=[0, 1400, 0],
extents=[2500, 0, 1000],
normal=[0, 1, 0],
mode_num=0,
power=1,
),
],
)

obj = goos.rename(-goos.abs(sim["overlap"]), name="obj_{}".format(stage))
obj = goos.rename(-goos.abs(sim["overlap"]), name=f"obj_{stage}")
return obj, sim


Expand Down
35 changes: 19 additions & 16 deletions examples/goos/grating_1d/grating_1d.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,47 +204,52 @@ def make_objective(eps: goos.Shape, stage: str, params: Options):
2000 + pml_thick * 2)

sim = maxwell.fdfd_simulation(
name="sim_{}".format(stage),
name=f"sim_{stage}",
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function make_objective refactored with the following changes:

wavelength=params.wlen,
eps=eps,
solver=solver,
sources=[
maxwell.GaussianSource(
w0=params.beam_width / 2,
center=[
params.coupler_len / 2, 0,
params.wg_thickness / 2 + params.beam_dist
params.coupler_len / 2,
0,
params.wg_thickness / 2 + params.beam_dist,
],
extents=[params.beam_extents, 0, 0],
normal=[0, 0, -1],
power=1,
theta=np.deg2rad(params.source_angle_deg),
psi=np.pi / 2,
polarization_angle=0,
normalize_by_sim=True)
normalize_by_sim=True,
)
],
simulation_space=maxwell.SimulationSpace(
mesh=maxwell.UniformMesh(dx=params.dx),
sim_region=goos.Box3d(
center=[(sim_left_x + sim_right_x) / 2, 0, sim_z_center],
extents=[sim_right_x - sim_left_x, 0, sim_z_extent],
),
pml_thickness=[pml_thick, pml_thick, 0, 0, pml_thick, pml_thick]),
pml_thickness=[pml_thick, pml_thick, 0, 0, pml_thick, pml_thick],
),
background=goos.material.Material(index=params.eps_bg),
outputs=[
maxwell.Epsilon(name="eps"),
maxwell.ElectricField(name="field"),
maxwell.WaveguideModeOverlap(name="overlap",
center=[-params.wg_len / 2, 0, 0],
extents=[0, 1000, 2000],
normal=[-1, 0, 0],
mode_num=0,
power=1),
maxwell.WaveguideModeOverlap(
name="overlap",
center=[-params.wg_len / 2, 0, 0],
extents=[0, 1000, 2000],
normal=[-1, 0, 0],
mode_num=0,
power=1,
),
],
)

obj = (1 - goos.abs(sim["overlap"]))**2
obj = goos.rename(obj, name="obj_{}".format(stage))
obj = goos.rename(obj, name=f"obj_{stage}")
return obj, sim


Expand Down Expand Up @@ -273,12 +278,10 @@ def visualize(folder: str, step: int):

plt.figure()
plt.subplot(1, 2, 1)
plt.imshow(
np.abs(data["monitor_data"]["sim_{}.eps".format(stage)][1].squeeze()))
plt.imshow(np.abs(data["monitor_data"][f"sim_{stage}.eps"][1].squeeze()))
plt.colorbar()
plt.subplot(1, 2, 2)
plt.imshow(
np.abs(data["monitor_data"]["sim_{}.field".format(stage)][1].squeeze()))
plt.imshow(np.abs(data["monitor_data"][f"sim_{stage}.field"][1].squeeze()))
Comment on lines -276 to +284
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function visualize refactored with the following changes:

plt.colorbar()
plt.show()

Expand Down
3 changes: 1 addition & 2 deletions examples/goos/optplan_examples/simple_opt.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,7 @@ def main(save_folder: str):
# More efficient to call `eval_nodes` when evaluating multiple nodes
# at the same time.
x_val, y_val, obj_val = plan.eval_nodes([x, y, obj])
print("x: {}, y: {}, obj: {}".format(x_val.array, y_val.array,
obj_val.array))
print(f"x: {x_val.array}, y: {y_val.array}, obj: {obj_val.array}")
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function main refactored with the following changes:



if __name__ == "__main__":
Expand Down
3 changes: 1 addition & 2 deletions examples/goos/optplan_examples/simple_opt_reloaded.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,7 @@ def main(save_folder: str, checkpoint_file: str):

# Show that we have retrieved the values.
x_val, y_val, obj_val = plan.eval_nodes([x, y, obj])
print("x: {}, y: {}, obj: {}".format(x_val.array, y_val.array,
obj_val.array))
print(f"x: {x_val.array}, y: {y_val.array}, obj: {obj_val.array}")
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function main refactored with the following changes:



if __name__ == "__main__":
Expand Down
114 changes: 62 additions & 52 deletions examples/invdes/grating_coupler/grating.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,8 @@ def create_objective(
)
# Append to monitor list for each wavelength
monitor_list.append(
optplan.FieldMonitor(name="mon_eps_" + str(wlen), function=epsilon))
optplan.FieldMonitor(name=f"mon_eps_{str(wlen)}", function=epsilon)
)
Comment on lines -310 to +311
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function create_objective refactored with the following changes:


# Add a Gaussian source that is angled at 10 degrees.
sim = optplan.FdfdSimulation(
Expand All @@ -329,11 +330,12 @@ def create_objective(
)
monitor_list.append(
optplan.FieldMonitor(
name="mon_field_" + str(wlen),
name=f"mon_field_{str(wlen)}",
function=sim,
normal=[0, 1, 0],
center=[0, 0, 0],
))
)
)

wg_overlap = optplan.WaveguideModeOverlap(
center=[-grating_len / 2 - 1000, 0, wg_thickness / 2],
Expand All @@ -346,7 +348,9 @@ def create_objective(
optplan.Overlap(simulation=sim, overlap=wg_overlap))**2
monitor_list.append(
optplan.SimpleMonitor(
name="mon_power_" + str(wlen), function=power))
name=f"mon_power_{str(wlen)}", function=power
)
)

if not MINIMIZE_BACKREFLECTION:
# Spins minimizes the objective function, so to make `power` maximized,
Expand All @@ -373,7 +377,9 @@ def create_objective(
optplan.Overlap(simulation=refl_sim, overlap=wg_overlap))**2
monitor_list.append(
optplan.SimpleMonitor(
name="mon_refl_power_" + str(wlen), function=refl_power))
name=f"mon_refl_power_{str(wlen)}", function=refl_power
)
)

# We now have two sub-objectives: Maximize transmission and minimize
# back-reflection, so we must an objective that defines the appropriate
Expand Down Expand Up @@ -423,14 +429,11 @@ def create_transformations(
Returns:
A list of transformations.
"""
# Setup empty transformation list.
trans_list = []

# First do continuous relaxation optimization.
cont_param = optplan.PixelParametrization(
simulation_space=sim_space,
init_method=optplan.UniformInitializer(min_val=0, max_val=1))
trans_list.append(
trans_list = [
Comment on lines -426 to +436
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function create_transformations refactored with the following changes:

This removes the following comments ( why? ):

# Discrete optimization.
# Setup empty transformation list.

optplan.Transformation(
name="opt_cont",
parametrization=cont_param,
Expand All @@ -440,12 +443,14 @@ def create_transformations(
monitor_lists=optplan.ScipyOptimizerMonitorList(
callback_monitors=monitors,
start_monitors=monitors,
end_monitors=monitors),
end_monitors=monitors,
),
optimization_options=optplan.ScipyOptimizerOptions(
maxiter=cont_iters),
maxiter=cont_iters
),
),
))

)
]
# If true, do another round of continous optimization with a discreteness bias.
if DISCRETENESS_PENALTY:
# Define parameters necessary to normaize discrete penalty term
Expand Down Expand Up @@ -496,37 +501,41 @@ def create_transformations(
# room later on.
disc_param = optplan.GratingParametrization(
simulation_space=sim_space, inverted=True)
trans_list.append(
optplan.Transformation(
name="cont_to_disc",
parametrization=disc_param,
transformation=optplan.GratingEdgeFitTransformation(
parametrization=cont_param,
min_feature=cont_to_disc_factor * min_feature)))

# Discrete optimization.
trans_list.append(
optplan.Transformation(
name="opt_disc",
parametrization=disc_param,
transformation=optplan.ScipyOptimizerTransformation(
optimizer="SLSQP",
objective=obj,
constraints_ineq=[
optplan.GratingFeatureConstraint(
min_feature_size=min_feature,
simulation_space=sim_space,
boundary_constraint_scale=1.0,
)
],
monitor_lists=optplan.ScipyOptimizerMonitorList(
callback_monitors=monitors,
start_monitors=monitors,
end_monitors=monitors),
optimization_options=optplan.ScipyOptimizerOptions(
maxiter=disc_iters),
trans_list.extend(
(
optplan.Transformation(
name="cont_to_disc",
parametrization=disc_param,
transformation=optplan.GratingEdgeFitTransformation(
parametrization=cont_param,
min_feature=cont_to_disc_factor * min_feature,
),
),
))
optplan.Transformation(
name="opt_disc",
parametrization=disc_param,
transformation=optplan.ScipyOptimizerTransformation(
optimizer="SLSQP",
objective=obj,
constraints_ineq=[
optplan.GratingFeatureConstraint(
min_feature_size=min_feature,
simulation_space=sim_space,
boundary_constraint_scale=1.0,
)
],
monitor_lists=optplan.ScipyOptimizerMonitorList(
callback_monitors=monitors,
start_monitors=monitors,
end_monitors=monitors,
),
optimization_options=optplan.ScipyOptimizerOptions(
maxiter=disc_iters
),
),
),
)
)
return trans_list


Expand Down Expand Up @@ -561,7 +570,7 @@ def view_opt_quick(save_folder: str) -> None:
log_data = pickle.load(fp)
for key, data in log_data["monitor_data"].items():
if np.isscalar(data):
print("{}: {}".format(key, data.squeeze()))
print(f"{key}: {data.squeeze()}")
Comment on lines -564 to +573
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function view_opt_quick refactored with the following changes:



def resume_opt(save_folder: str) -> None:
Expand Down Expand Up @@ -609,14 +618,15 @@ def gen_gds(save_folder: str, grating_len: float, wg_width: float) -> None:
coords = np.insert(coords, 0, 0, axis=0)
coords = np.insert(coords, -1, grating_len, axis=0)

# `coords` now contains the location of the grating edges. Now draw a
# series of rectangles to represent the grating.
grating_poly = []
for i in range(0, len(coords), 2):
grating_poly.append(
((coords[i], -wg_width / 2), (coords[i], wg_width / 2),
(coords[i + 1], wg_width / 2), (coords[i + 1], -wg_width / 2)))

grating_poly = [
(
(coords[i], -wg_width / 2),
(coords[i], wg_width / 2),
(coords[i + 1], wg_width / 2),
(coords[i + 1], -wg_width / 2),
)
for i in range(0, len(coords), 2)
]
Comment on lines -612 to +629
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function gen_gds refactored with the following changes:

This removes the following comments ( why? ):

# series of rectangles to represent the grating.
# `coords` now contains the location of the grating edges. Now draw a

# Save the grating to `grating.gds`.
grating = gdspy.Cell("GRATING", exclude_from_current=True)
grating.add(gdspy.PolygonSet(grating_poly, 100))
Expand Down
Loading