Loops
Use loops in template Python blocks to create repeated JCM input text. This page creates a staggered hexagonal array of glass rods. The project keys control the rod radius, lattice spacing, and rod counts.
Loops reduce repeated JCM input text when a project contains many similar
objects. One for loop can generate one JCM block for each rod. Nested loops
can generate two-dimensional arrays. Project keys can control the number of
loop iterations, so one template can create multiple geometry sizes.
Define The Geometry
The lattice uses these grid vectors:
where is the lattice spacing. The template uses the grid vectors to place
each rod and to calculate the width and height of the computational domain.
Staggered hexagonal array of glass rods.
The script defines a rod radius of , a lattice spacing
of
, and rod counts of
:
keys = {
"radius": 0.3,
"a": 1.0,
"n_rods": [3, 3],
"n_air": 1.0,
"n_glass": 1.52,
"lambda_0": 0.550, # in um
"polarization": 45, # in degree
}
The first and third columns contain three rods. The staggered second column contains two rods. The template therefore creates eight rods.
Continue Loops Across Template Blocks
Start a Python loop in a <? block. Close the block with ?> before the JCM
text that the loop must repeat. Open another <? block at the same indentation
level to continue or close the loop.
For example, this template creates one Circle block for each value in
rod_indices:
<?
for rod_index in keys["rod_indices"]:
keys["rod_index"] = rod_index
?>
Circle {
Name = "Rod %(rod_index)d"
}
<?
?>
Warning
Close every Python loop in a later <? ... ?> block. Indent the first ?>
tag at the same level as the statements in the active loop body. In the example,
the first ?> has four spaces before it. The final ?> closes the for loop.
The complete layout.jcmt template follows. The first Python block calculates
the grid vectors and the computational-domain dimensions. The static Layout2D
text defines the domain and its transparent boundary. The second Python block
starts the nested loops that generate the rod geometry:
<?
# compute grid vectors for hexagonal grid
grid_vector_1 = np.array([0.0, keys["a"]])
grid_vector_2 = np.array(
[np.sin(np.deg2rad(60)), np.cos(np.deg2rad(60))]
) * keys["a"]
# compute computational domain enclosing all scatterer
max_x = (keys["n_rods"][0] - 1) * grid_vector_2[0]
max_y = (keys["n_rods"][1] - 1) * grid_vector_1[1]
keys["computational_domain_X"] = max_x + 2 * keys["radius"] + 2
keys["computational_domain_Y"] = max_y + 2 * keys["radius"] + 2
?>
Layout2D {
UnitOfLength = 1e-6
MeshOptions {
MaximumSideLength = 0.1
CurvilinearDegree = 2
}
Objects {
# Computational domain
Parallelogram {
Name = "ComputationalDomain"
DomainId = 1
Priority = ComputationalDomain
Width = %(computational_domain_X)e
Height = %(computational_domain_Y)e
Boundary {
Class = Transparent
}
}
<?
index = 0
center_array = np.array([max_x / 2, max_y / 2])
for i_x in range(keys["n_rods"][0]):
column_start = np.array(
[i_x * grid_vector_2[0], (i_x % 2) * grid_vector_2[1]]
)
for i_y in range(keys["n_rods"][1] - (i_x % 2)):
index += 1
keys["center"] = column_start + i_y * grid_vector_1 - center_array
keys["rod_index"] = index
# important to have the code snippet closing on the same level as the code!
?>
# Scatterer (rod)
Circle {
Name = "Rod %(rod_index)e"
DomainId = 2
Priority = 1
Radius = %(radius)e
GlobalPosition = %(center)e
}
<? # closes for loops
?>
}
}
The opening Python block sets grid_vector_1, grid_vector_2, max_x, and
max_y. The block also sets the computational_domain_X and
computational_domain_Y project keys that define the Parallelogram size.
The nested loops calculate each rod centre. Each loop iteration sets the
center and rod_index project keys. The indented ?> tag transfers control
to the JCM Circle block, which uses those project keys. The final Python block
closes both loops.
Run The Project
from matplotlib import pyplot as plt
import jcmsuite
# Set problem parameter
keys = {
"radius": 0.3,
"a": 1.0,
"n_rods": [3, 3],
"n_air": 1.0,
"n_glass": 1.52,
"lambda_0": 0.550, # in um
"polarization": 45, # in degree
}
# Solve the Project
results = jcmsuite.solve("mie2D.jcmp", keys=keys)
# Access the results of the first postprocess and export it to a dictionary
scattering_postprocess = results.postprocesses[0]
scattering_export = scattering_postprocess.to_dict()
cross_section = scattering_export["ElectromagneticFieldEnergyFlux"][0][0].real
print(f"scattering cross section: {cross_section}")
# Access the field export of the second postprocess
field_export = results.postprocesses[1].fields
# Select the first field intensity and export it to an xarray Dataset
xarray_export = field_export.intensity.select(0).to_xarray()
xx = xarray_export["X"]
yy = xarray_export["Y"]
intensity = xarray_export["field"]
plt.pcolor(xx, yy, intensity, shading="auto")
plt.show()
solve renders the template project support files and returns a
SolveResult. The script exports the first postprocess data as a dictionary and
prints the exterior energy flux. The script selects the first exported field
from the second postprocess and displays its intensity.
Field intensity around the rod array.
The script requires JCMsuite, an available license, and matplotlib.
Inspect The Geometry
Run run_geo.py before a solve to inspect the rendered rod array. The script
uses the radius, lattice spacing, and rod counts from its project keys. JCMgeo
creates grid.jcm and JCMview opens the grid. The script does not run the
electromagnetic solve.
import jcmsuite
keys = {
"radius": 0.3,
"a": 1.0,
"n_rods": [3, 3],
}
# Create the mesh and view it
results = jcmsuite.geo(".", keys=keys, show=True)
JCMview requires a graphical environment.
Project Files
run.py
from matplotlib import pyplot as plt
import jcmsuite
# Set problem parameter
keys = {
"radius": 0.3,
"a": 1.0,
"n_rods": [3, 3],
"n_air": 1.0,
"n_glass": 1.52,
"lambda_0": 0.550, # in um
"polarization": 45, # in degree
}
# Solve the Project
results = jcmsuite.solve("mie2D.jcmp", keys=keys)
# Access the results of the first postprocess and export it to a dictionary
scattering_postprocess = results.postprocesses[0]
scattering_export = scattering_postprocess.to_dict()
cross_section = scattering_export["ElectromagneticFieldEnergyFlux"][0][0].real
print(f"scattering cross section: {cross_section}")
# Access the field export of the second postprocess
field_export = results.postprocesses[1].fields
# Select the first field intensity and export it to an xarray Dataset
xarray_export = field_export.intensity.select(0).to_xarray()
xx = xarray_export["X"]
yy = xarray_export["Y"]
intensity = xarray_export["field"]
plt.pcolor(xx, yy, intensity, shading="auto")
plt.show()
run_geo.py
import jcmsuite
keys = {
"radius": 0.3,
"a": 1.0,
"n_rods": [3, 3],
}
# Create the mesh and view it
results = jcmsuite.geo(".", keys=keys, show=True)
layout.jcmt
<?
# compute grid vectors for hexagonal grid
grid_vector_1 = np.array([0.0, keys["a"]])
grid_vector_2 = np.array(
[np.sin(np.deg2rad(60)), np.cos(np.deg2rad(60))]
) * keys["a"]
# compute computational domain enclosing all scatterer
max_x = (keys["n_rods"][0] - 1) * grid_vector_2[0]
max_y = (keys["n_rods"][1] - 1) * grid_vector_1[1]
keys["computational_domain_X"] = max_x + 2 * keys["radius"] + 2
keys["computational_domain_Y"] = max_y + 2 * keys["radius"] + 2
?>
Layout2D {
UnitOfLength = 1e-6
MeshOptions {
MaximumSideLength = 0.1
CurvilinearDegree = 2
}
Objects {
# Computational domain
Parallelogram {
Name = "ComputationalDomain"
DomainId = 1
Priority = ComputationalDomain
Width = %(computational_domain_X)e
Height = %(computational_domain_Y)e
Boundary {
Class = Transparent
}
}
<?
index = 0
center_array = np.array([max_x / 2, max_y / 2])
for i_x in range(keys["n_rods"][0]):
column_start = np.array(
[i_x * grid_vector_2[0], (i_x % 2) * grid_vector_2[1]]
)
for i_y in range(keys["n_rods"][1] - (i_x % 2)):
index += 1
keys["center"] = column_start + i_y * grid_vector_1 - center_array
keys["rod_index"] = index
# important to have the code snippet closing on the same level as the code!
?>
# Scatterer (rod)
Circle {
Name = "Rod %(rod_index)e"
DomainId = 2
Priority = 1
Radius = %(radius)e
GlobalPosition = %(center)e
}
<? # closes for loops
?>
}
}
materials.jcmt
<?
# compute rel. permittivity of glass from refractive index
keys["permittivity_air"] = keys["n_air"]**2
?>
# material properties for the surroundings (air)
Material {
DomainId = 1
RelPermittivity = %(permittivity_air)e
RelPermeability = 1.0
}
<?
# compute rel. permittivity of glass from refractive index
keys["permittivity_glass"] = keys["n_glass"]**2
?>
# material properties the glass rod
Material {
DomainId = 2
RelPermittivity = %(permittivity_glass)e
RelPermeability = 1.0
}
mie2D.jcmp
Project {
InfoLevel = 3
Electromagnetics {
TimeHarmonic {
Scattering {
FieldComponents = Electric
Accuracy {
FiniteElementDegree = 3
Refinement {
MaxNumberSteps = 0
PreRefinements = 0
}
}
}
}
}
}
# computes the energy flux of the scattered field into the exterior domain
PostProcess {
FluxIntegration {
FieldBagPath = "./mie2D_results/fieldbag.jcm"
OutputFileName = "./mie2D_results/energyflux_scattered.jcm"
OutputQuantity = ElectromagneticFieldEnergyFlux
InterfaceType = ExteriorDomain
}
}
# exports computed field on cartesian grid
PostProcess {
ExportFields {
FieldBagPath = "./mie2D_results/fieldbag.jcm"
OutputFileName = "./mie2D_results/fieldbag_cartesian.jcm"
Cartesian {
NGridPointsX = 200
NGridPointsY = 200
}
}
}
sources.jcmt
<?
# numpy does not have to be imported, is imported by default
from math import pi, sin, cos
# compute k-vector and e-vector
lambda_0 = keys["lambda_0"]*1e-6 # initially in um!
keys["k_illum"] = [2*pi/lambda_0*keys["n_air"], 0, 0]
pol_rad = np.deg2rad(keys["polarization"])
keys["e_illum"] = [0, sin(pol_rad), cos(pol_rad)]
?>
SourceBag {
Source {
ElectricFieldStrength {
PlaneWave {
K = %(k_illum)e
Amplitude = %(e_illum)e
}
}
}
}
Next Step
Continue to Parallel Parameter Scan to run the radius scan with a local daemon resource.