Python Code Snippets
This page extends Keyword Substitution with Python blocks in template project support files. The blocks calculate material and source values from project keys before JCMsuite runs the project.
Define Project Keys
The project keys define the rod radius, the refractive indices, the vacuum wavelength, and the polarization angle:
keys = {
"radius": 0.3,
"n_air": 1.0,
"n_glass": 1.52,
"lambda_0": 0.550, # in um
"polarization": 45, # in degree
}
The radius is . The refractive indices are
and
. The source has a vacuum wavelength of
and a polarization angle of
.
The template calculates the incident field as:
where .
Use Python Blocks
A Python block starts with <? and ends with ?>. The template evaluates the block as
Python code. The block can read and update project keys. numpy is imported by default.
Text outside the block remains JCM input text.
The materials.jcmt template calculates the relative permittivity of air and glass from
the refractive indices. The template then substitutes the calculated values into the
Material sections:
<?
# 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
}
The sources.jcmt template converts the vacuum wavelength to metres. The template
calculates the wave vector and the polarization vector. The Source section then uses the
calculated project keys:
<?
# 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
}
}
}
}
Run The Project
from matplotlib import pyplot as plt
import jcmsuite
# Set problem parameter
keys = {
"radius": 0.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 intensity of the second postprocess and export it to an xarray Dataset
field_export = results.postprocesses[1].fields
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 each template project support file and returns a
SolveResult. The
script exports the first postprocess data with
to_dict() and prints the exterior energy
flux. The script selects the first exported field from the second postprocess and displays
its intensity.
Project Files
run.py
from matplotlib import pyplot as plt
import jcmsuite
# Set problem parameter
keys = {
"radius": 0.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 intensity of the second postprocess and export it to an xarray Dataset
field_export = results.postprocesses[1].fields
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()
layout.jcmt
Layout2D {
UnitOfLength = 1e-6
MeshOptions {
MaximumSideLength = 0.1
CurvilinearDegree = 2
}
Objects {
# Computational domain
Parallelogram {
Name = "ComputationalDomain"
DomainId = 1
Priority = ComputationalDomain
Width = 4
Height = 4
Boundary {
Class = Transparent
}
}
# Scatterer (rod)
Circle {
Name = "Rod"
DomainId = 2
Priority = 1
Radius = %(radius)e
RefineAll = 4
}
}
}
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 Loops to generate repeated JCM input text from a Python block.