Differentiate Numeric Postprocess Results Twice

Second derivatives are not limited to Cartesian field exports. This example builds a scalar objective from Fourier data, differentiates it twice, and inspects second derivatives in Fourier and scattering results.

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.

You need PyTorch, pandas, and a configured JCMsuite runtime with a solver license. All project files are in the example folder. Run from the repository root:

python demos/documentation_tutorials/derivatives/torch/second_order_postprocess/run.py
"""Differentiate numeric postprocess values and inspect their solver pairs."""

import torch

import jcmsuite
from jcmsuite.torch import RealDerivative

permittivity = torch.tensor(1.967, dtype=torch.float64, requires_grad=True)
result = jcmsuite.torch.solve(
    "project.jcmp",
    keys={"permittivity": permittivity, "line_permittivity": 1.4},
    key_derivative_map={"permittivity": RealDerivative("permittivity_real")},
    temporary=True,
)

# The Fourier result is structured numeric data.
fourier = result.postprocesses[0]
electric_field = fourier.to_dict()["ElectricFieldStrength"][0]
loss = electric_field.abs().square().sum()
gradient = torch.autograd.grad(loss, permittivity, create_graph=True)[0]
curvature = torch.autograd.grad(gradient, permittivity, retain_graph=True)[0]
print("Fourier objective:", loss.item())
print("First derivative:", gradient.item())
print("Second derivative:", curvature.item())

first = fourier.derivatives["permittivity"].real
sensitivity = first.to_dict()["ElectricFieldStrength"][0]
sensitivity_gradient = torch.autograd.grad(sensitivity.sum(), permittivity)[0]
print("Sensitivity-objective gradient:", sensitivity_gradient)
second = first.derivatives["permittivity"].to_dict()
print("Second solver derivative:", second["ElectricFieldStrength"])

# Numeric scattering tables use the same nested selection and keep quantity names.
scattering = result.postprocesses[1]
pair = scattering.derivatives["permittivity"].derivatives["permittivity"]
print("Scattering second derivative quantities:", list(pair.real.to_dict()))
ordinary = result.untorch().postprocesses[1]
ordinary_first = ordinary.derivatives["permittivity_real"]
ordinary_pair = ordinary_first.derivatives["permittivity_real"]
print("Ordinary table export:\n", ordinary_pair.to_df().head())

What To Notice

The Fourier objective is approximately 0.1589, its first derivative 0.1423, and its second derivative -0.0796. The script also differentiates an objective built directly from first-sensitivity values.

Derivative lookup uses the bound project key permittivity. Select .real before exporting a sensitivity with complex output quantities. Nested lookup then gives the selected second solver derivative, without another solve.

Torch exports use dictionaries containing tensors. To get a pandas table, the script returns to ordinary results with result.untorch() and selects the solver labels. Coordinate metadata and quantity names remain in the export.

The project requests Order = 2. The numbers demonstrate material derivatives on a fixed geometry; they are not convergence or accuracy assertions. A second-derivative inspection is detached, and third-order solver derivatives are not supported.

Project Files

project.jcmp
Project {
  Derivatives {
    Order = 2
  }
  InfoLevel = 1
  Electromagnetics {
    TimeHarmonic {
      Scattering {
        FieldComponents = Electric
        Accuracy {
          FiniteElementDegree = 3
          Precision = 0.001
        }
      }
    }
  }
}
PostProcess {
  FourierTransform {
    FieldBagPath = "project_results/fieldbag.jcm"
    OutputFileName = "project_results/fc.jcm"
    NormalDirection = Y
    Rotation = X:Z:-Y
    Format = JCM
  }
}
PostProcess {
  ScatteringMatrix {
    Format = JCM
    InputFileName = "project_results/fc.jcm"
    OutputFileName = "project_results/sm.jcm"
  }
}
materials.jcmt
DerivativeParameter {
  Name = "line_permittivity"
  TreeEntry = "Material_2/RelPermittivity"
}
DerivativeParameter {
  Name = "permittivity_real"
  TreeEntry {
    Path = "Material_3/RelPermittivity"
    Scaling = (1, 0)
  }
}
DerivativeParameter {
  Name = "permittivity_imag"
  TreeEntry {
    Path = "Material_3/RelPermittivity"
    Scaling = (0, 1)
  }
}
Material {
  Name = "Material_1"
  DomainId = 1
  RelPermittivity = 1
  RelPermeability = 1
}
Material {
  Name = "Material_2"
  DomainId = 2
  RelPermittivity = %(line_permittivity)g
  RelPermeability = 1
}
Material {
  Name = "Material_3"
  DomainId = 3
  RelPermittivity = %(permittivity)g
  RelPermeability = 1
}
layout.jcm
Layout2D {
  Name = "Line"
  UnitOfLength = 1e-9
  MeshOptions {
    MinimumMeshAngle = 25
    SnapTolerance = 1e-6
    MaximumSideLength = 10
  }
  Objects {
    Parallelogram {
      Name = "ComputationalDomain"
      DomainId = 1
      Priority = ComputationalDomain
      Width = 90
      Height = 100
      Boundary {
        Number = [1 3]
        Class = TransparentBoundary
      }
      Boundary {
        Number = [2 4]
        Class = Periodic
      }
    }
    Parallelogram {
      Name = "Substrate"
      DomainId = 3
      Width = 90
      Height = 20
      Port = South
      Alignment {
        Parent {
          Domain = "ComputationalDomain"
          Port = South
        }
        Orientation = Parallel
      }
    }
    Trapezoid {
      Name = "Line"
      DomainId = 2
      Priority = 4
      Height = 55
      Width = 31
      InnerAngles = [88 88]
      Port = South
      Alignment {
        Parent {
          Domain = "Substrate"
          Port = North
        }
        Orientation = AntiParallel
      }
      CornerRounding {
        Point = [3 4]
        Radius = 8
        NPoints = 5
      }
    }
  }
}
sources.jcm
SourceBag {
  Source {
    ElectricFieldStrength {
      PlaneWave {
        3DTo2D = yes
        Incidence = FromAbove
        SP = [1 0]
        Lambda0 = 3.65e-07
        ThetaPhi = [65, 45]
      }
    }
  }
}
SourceBag {
  Source {
    ElectricFieldStrength {
      PlaneWave {
        3DTo2D = yes
        Incidence = FromAbove
        SP = [0 1]
        Lambda0 = 3.65e-07
        ThetaPhi = [65, 45]
      }
    }
  }
}