Bind Alternative Shape Derivatives

Experimental feature

The jcmsuite.torch integration is experimental. Its API and behavior can change in future releases. Do not depend on its current interface for production workflows without testing each package update.

This tutorial uses inline derivative vectors in a Layout3D template to describe the bottom radius, top radius, and cylinder height as three shape derivatives. The matching DerivativeParameter sections declare their names and order. The Torch solve binds each differentiable Project Key to one of those names.

Unlike a layout that lists TreeEntry paths in each DerivativeParameter, this form places each derivative vector next to the geometry value. For example, Circle/Radius = %(radius_bottom)g<1.0, 0.0, 0.0> assigns the first derivative component to the bottom radius. The top-layer thickness uses -1.0 for the height component so the top of the computational domain remains fixed.

The solve reads the energy flux and uses torch.autograd.grad to report its derivatives with respect to all three shape parameters. It requires a JCMsuite runtime that supports first-order shape derivatives for Scattering projects.

Run it from demos/documentation_tutorials:

python derivatives/torch/alternative_jcm_derivatives/run.py
"""Compute Torch gradients for tensorial shape derivatives."""

import torch

import jcmsuite
from jcmsuite.torch import RealDerivative

radius_bottom = torch.tensor(1.0, dtype=torch.float64, requires_grad=True)
radius_top = torch.tensor(1.0, dtype=torch.float64, requires_grad=True)
height = torch.tensor(1.5, dtype=torch.float64, requires_grad=True)

results = jcmsuite.torch.solve(
    "project.jcmp",
    keys={
        "radius_bottom": radius_bottom,
        "radius_top": radius_top,
        "height": height,
    },
    temporary=True,
    key_derivative_map={
        "radius_bottom": RealDerivative("RadiusBottom"),
        "radius_top": RealDerivative("RadiusTop"),
        "height": RealDerivative("Height"),
    },
)

flux = results.postprocesses[0].to_dict()["ElectromagneticFieldEnergyFlux"][0][0].real
gradients = torch.autograd.grad(flux, (radius_bottom, radius_top, height))

print(f"Energy flux: {flux.item()}")
print(f"Gradient with respect to bottom radius: {gradients[0].item()}")
print(f"Gradient with respect to top radius: {gradients[1].item()}")
print(f"Gradient with respect to cylinder height: {gradients[2].item()}")

Project Files

layout.jcmt
DerivativeParameter {
  Name = "RadiusBottom"
}
DerivativeParameter {
  Name = "RadiusTop"
}
DerivativeParameter {
  Name = "Height"
}

Layout3D {
  UnitOfLength = 1e-06
  MeshOptions {
    MaximumSideLength = 1.3
  }
  Extrusion {
    Objects {
      Polygon {
        Name = "ComputationalDomain/Background"
        DomainId = 1
        Priority = -1
        Points = [-2 -2, 2 -2, 2 2, -2 2]
        Boundary {
          Class = Periodic
        }
      }
      Circle {
        Name = "Circle"
        DomainId = 2
        Radius = 1
        MeshOptions {
          BoundaryMeshConstraint = .3
        }
      }
    }
    MultiLayer {
      AlignmentZ {
        GlobalZ = -1.1
      }
      LayerInterface {
        BoundaryClass = Transparent
      }
      Layer {
        Thickness = 1.0
        DomainId = 1
      }
      LayerInterface {
        Name = "InterfaceBottom"
        GeometryValues = [
          Circle/Radius = %(radius_bottom)g<1.0, 0.0, 0.0>
        ]
      }
      Layer {
        Name = "CylinderLayer"
        Thickness = %(height)g<0.0, 0.0, 1.0>
        DomainIdMapping = [1 2, 2 3]
      }
      LayerInterface {
        Name = "InterfaceTop"
        GeometryValues = [
          Circle/Radius = %(radius_top)g<0.0, 1.0, 0.0>
        ]
      }
      Layer {
        Name = "TopLayer"
        Thickness = 2.0<0.0, 0.0, -1.0>
        DomainIdMapping = [1 2]
      }
      LayerInterface {
        BoundaryClass = Transparent
      }
    }
  }
}
materials.jcmt
Material {
  Name = "Material_1"
  DomainId = 1
  RelPermittivity = 1
  RelPermeability = 1.0
}
Material {
  Name = "Material_2"
  DomainId = 2
  RelPermittivity = 1.4
  RelPermeability = 1.0
}
Material {
  Name = "Material_3"
  DomainId = 3
  RelPermittivity = 2.0
  RelPermeability = 1.0
}
project.jcmp
Project {
  Derivatives {
    Order = 1
  }
  InfoLevel = 10
  Electromagnetics {
    TimeHarmonic {
      Scattering {
        FieldComponents = Electric
        Accuracy {
          FiniteElementDegree = 2
          Precision = 0.01
        }
      }
    }
  }
}
PostProcess {
  FluxIntegration {
    OutputQuantity = ElectromagneticFieldEnergyFlux
    FieldBagPath = "project_results/fieldbag.jcm"
    OutputFileName = "project_results/flux.jcm"
    InterfaceType = ExteriorDomain
  }
}
sources.jcm
SourceBag {
  Source {
    ElectricFieldStrength {
      PlaneWave {
        Incidence = FromAbove
        SP = [1 0]
        Lambda0 = 1.0e-06
        ThetaPhi = [0, 0]
      }
    }
  }
}