Use Async Execution
This tutorial runs a batched solve and two independent solves from one active
asyncio event loop. An event loop runs asynchronous operations. Each
solve uses asynchronous=True and returns a coroutine,
which the event loop waits for.
Run the tutorial from the tutorial root:
python execution_runtime/async/run.py
Use asyncio.run(main()) only in a script entry point. In a notebook or an
async service, await main() from the existing event loop instead.
Python File
"""Use JCMsuite from a running asyncio event loop."""
import asyncio
import jcmsuite
async def main() -> None:
"""Run one batch and two independent solves in an active event loop.
In notebooks or async services, import the function and call:
`await main()`
(do not create a new event loop with `asyncio.run` there).
"""
batch_result = await jcmsuite.solve(
"mie2D.jcmp",
keys=[{"radius": 0.30}, {"radius": 0.4}],
asynchronous=True,
)
print(batch_result)
solve_a = jcmsuite.solve(
"mie2D.jcmp",
keys={"radius": 0.3},
asynchronous=True,
)
solve_b = jcmsuite.solve(
"mie2D.jcmp",
keys={"radius": 0.4},
asynchronous=True,
)
result_a, result_b = await asyncio.gather(solve_a, solve_b)
print(result_a)
print(result_b)
if __name__ == "__main__":
asyncio.run(main())
Project Files
layout.jcmt
Layout2D {
UnitOfLength = 1e-6
MeshOptions {
MaximumSideLength = 0.1
}
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.jcm
# material properties for the surroundings (air)
Material {
DomainId = 1
RelPermittivity = 1.0
RelPermeability = 1.0
}
# material properties the glass rod
Material {
DomainId = 2
RelPermittivity = 2.3104 # 1.52^2
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
}
}
PostProcess {
FourierTransform {
FieldBagPath = "./mie2D_results/fieldbag.jcm"
OutputFileName = "./mie2D_results/fc.jcm"
NormalDirection = Y
Rotation = X:Z:-Y
Format = JCM
}
}
# 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.jcm
SourceBag {
Source {
ElectricFieldStrength {
PlaneWave {
K = [1.14239732857811e7 0.0 0.0]
Amplitude = [0 0 1]
}
}
}
}