Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 23 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -210,20 +210,42 @@ cmake --build fdtd/build -j
There is no packaging yet; run the code from the repository root or add `src/`
to `PYTHONPATH`.

## External material fragments

CaseMaker can merge an external material/mesh fragment produced by another
tool. The fragment contains one material, its `cell` elements, and the
matching associations:

```python
cm.setGridFromJSON("grid.json")
cm.addMaterialFragment("fragment.json")
```

The fragment grid must match the case grid. Material and element ids are
remapped to the next free ids in the case. CaseMaker does not run or inspect
the tool that produced the fragment; it only consumes the JSON file.

See [docs/fragments.md](docs/fragments.md) for the fragment format, grid
validation rules and a complete example.

## API overview

| Method | Purpose |
| --- | --- |
| `setGridFromVTK(path)` | Load grid origin, number of cells and steps from a VTK grid. |
| `setGridFromVTK(path)` / `setGridFromJSON(path)` | Load the grid. |
| `writeGridJSON(path)` | Write the current grid. |
| `addCellElementsFromVTK(path)` | Add staircased cell elements from QUAD/LINE VTK cells. |
| `addCellElementIntervals(intervals)` | Add a cell element from relative node intervals. |
| `addThinSlotElementsFromVTK(path)` | Add line or embedded-surface cell elements for a thin slot. |
| `addConformalVolumeFromVTK(path)` | Add a conformal volume/surface from TRIANGLE VTK cells. |
| `addCellElementBox(bbox)` | Add a cell element from an absolute-coordinate box. |
| `addNodeElement(position)` | Add a mesh node (used by point probes, etc.). |
| `addPECMaterial()` / `addMaterialAssociation(...)` | Define materials and associate them with elements. |
| `addMaterialFragment(path)` | Merge an external material/mesh/association fragment. |
| `addThinSlotMaterial(width)` | Define a `thinSlot` material (width in metres, matching the grid). |
| `addPlanewaveSource(...)` | Add a plane-wave source with an excitation file. |
| `addPointProbe(...)` / `addFarFieldProbe(...)` | Add point and far-field probes. |
| `addMovieProbe(...)` | Add a time/frequency movie probe for ParaView. |
| `exportCase(name)` | Write `<name>.fdtd.json`. |

## Tests
Expand Down
168 changes: 168 additions & 0 deletions docs/fragments.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
# External material fragments

CaseMaker can merge a material/mesh fragment produced by an external
preprocessing tool. CaseMaker only consumes the JSON file; it does not run,
import, or inspect the tool that produced it.

## Fragment format

The fragment has three top-level fields:

```json
{
"material": {
"id": 1,
"name": "plasma",
"type": "lorentz",
"epsInf": 1.0,
"omega1": 0.0,
"levels": [
{"omegaP": 27497.99, "gamma": 95598295.23,
"f_p_level": 0, "nu_c_level": 0}
]
},
"mesh": {
"grid": {
"numberOfCells": [128, 128, 128],
"origin": [-0.51516904, -1.09476239, -1.09476239],
"steps": {
"x": [0.0164875],
"y": [0.0150898],
"z": [0.0150898]
}
},
"elements": [
{
"id": 1,
"name": "fp_0_nu_0",
"type": "cell",
"intervals": [
[[24, 30, 64], [31, 31, 65]]
]
}
]
},
"materialAssociations": [
{"materialId": 1, "level": 0, "elementIds": [1]}
]
}
```

- `material` is the material definition. Level-based Lorentz materials use a
`levels` array; other existing material types use their normal fields.
- `mesh.elements` contains one `cell` element per material level. Each
element can contain many closed-open intervals.
- `mesh.grid.steps` may contain one value per axis or one value per cell.
- `materialAssociations[].level`, when present, is the zero-based index into
`material.levels`.

The fragment does not contain sources, probes, boundaries or the PEC body.
Those remain caseMaker inputs.

## Merging

```python
cm.setGridFromJSON("grid.json")
cm.addMaterialFragment("fragment.json")
```

`addMaterialFragment()`:

- validates that `material`, `mesh`, `materialAssociations`, `mesh.grid` and
`mesh.elements` are present;
- validates `numberOfCells` exactly and `origin`/`steps` within `1e-12`;
- adopts the fragment grid if the case has no grid yet;
- appends the material to `materials`;
- appends its elements to `mesh.elements`;
- rewrites `materialId` and `elementIds` to the next free ids;
- preserves each association’s `level` index.

The fragment is not modified.

## Grid export

`setGridFromJSON(path)` loads a grid file, `writeGridJSON(path)` writes the
current case grid, and the grid can also come from tessellator through
`setGridFromVTK()`.

## Supporting caseMaker helpers

Two helpers are useful when assembling a case around a fragment:

- `addCellElementIntervals(intervals, name=None)` adds a `cell` element
directly from closed-open relative node intervals. This is used for TFSF
and NTFF boxes, movie slices, or any geometry already expressed as grid
intervals.
- `addMovieProbe(elementId, name, field="electric",
component="magnitude", domain=None)` adds a ParaView movie probe. The
referenced element must be one cell region with one interval.

## PEC body

The fragment is geometry-agnostic. Supply the PEC body separately, for
example from tessellator:

```python
body = cm.addCellElementsFromVTK(
"body_pec_surface.vtk", name="body_pec")
pec = cm.addPECMaterial()
cm.addMaterialAssociation(pec, [body])
```

Overlaps between fragment elements and PEC are resolved by fdtd material
priority; PEC wins.

## Example

```python
from caseMaker import CaseMaker

cm = CaseMaker()
cm.setGridFromJSON("grid.json")
cm.setNumberOfTimeSteps(3300)
cm.setTimeStep(2.390423293775277e-11)
cm.setAllBoundaries("pml")

tfsf = cm.addCellElementIntervals(
[[[16, 16, 16], [112, 112, 112]]], name="tfsf_box")
ntff = cm.addCellElementIntervals(
[[[8, 8, 8], [120, 120, 120]]], name="ntff_box")

body = cm.addCellElementsFromVTK(
"body_pec_surface.vtk", name="body_pec")
pec = cm.addPECMaterial()
cm.addMaterialAssociation(pec, [body])

cm.addMaterialFragment("fragment.json")

cm.addPlanewaveSource(
tfsf, "gauss.exc",
{"theta": 1.5707963267948966, "phi": 0.0},
{"theta": 0.0, "phi": 0.0})
cm.addFarFieldProbe(
ntff, "backscatter",
{"initial": 90.0, "final": 90.0, "step": 1.0},
{"initial": 180.0, "final": 180.0, "step": 1.0},
{"type": "frequency", "initialFrequency": 0.2e9,
"finalFrequency": 1.5e9, "numberOfFrequencies": 141,
"frequencySpacing": "linear"})

cm.exportCase("case")
```

## Tests

`test/test_fragments.py` covers:

- grid round-trip and validation;
- fragment ID remapping and level preservation;
- malformed and unknown associations;
- `addCellElementIntervals` and `addMovieProbe`;
- a small end-to-end case that is passed to `semba-fdtd -n -1` when the
solver is available.

Run with:

```shell
python3 -m pytest test/test_fragments.py
```
149 changes: 149 additions & 0 deletions src/caseMaker.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,120 @@ def setAllBoundaries(self, boundary_type):
}
}

def setGridFromJSON(self, path_to_grid):
with open(path_to_grid, 'r') as f:
grid = json.load(f)
self.input.setdefault('mesh', {})['grid'] = grid

def writeGridJSON(self, path_to_grid):
if 'mesh' not in self.input or 'grid' not in self.input['mesh']:
raise ValueError("No grid has been defined.")
with open(path_to_grid, 'w') as f:
json.dump(self.input['mesh']['grid'], f, indent=2)
return path_to_grid

@staticmethod
def _expandedSteps(steps, count):
values = [float(value) for value in steps]
if len(values) == 1:
values = values * count
if len(values) != count:
raise ValueError(
"Grid steps length must be 1 or numberOfCells.")
return values

def _validateGrid(self, fragment_grid):
if 'mesh' not in self.input or 'grid' not in self.input['mesh']:
self.input.setdefault('mesh', {})['grid'] = fragment_grid
return

grid = self.input['mesh']['grid']
fragment_counts = [int(value) for value in fragment_grid['numberOfCells']]
counts = [int(value) for value in grid['numberOfCells']]
if fragment_counts != counts:
raise ValueError(
"Fragment grid numberOfCells does not match the case grid.")
if not np.allclose(grid['origin'], fragment_grid['origin'],
rtol=0.0, atol=1.0e-12):
raise ValueError(
"Fragment grid origin does not match the case grid.")
for axis, count in zip(('x', 'y', 'z'), counts):
case_steps = self._expandedSteps(grid['steps'][axis], count)
fragment_steps = self._expandedSteps(
fragment_grid['steps'][axis], count)
if not np.allclose(case_steps, fragment_steps,
rtol=0.0, atol=1.0e-12):
raise ValueError(
"Fragment grid steps do not match the case grid "
"in axis {}.".format(axis))

def addMaterialFragment(self, path_to_fragment):
'''Merge a material/mesh/materialAssociations fragment.

The fragment is geometry-agnostic: it contains one material with a
levels array, one cell element per level, and one association per
level. IDs are remapped to the next free ids in this case.
'''
with open(path_to_fragment, 'r') as f:
fragment = json.load(f)

for key in ('material', 'mesh', 'materialAssociations'):
if key not in fragment:
raise ValueError(
"Material fragment is missing '{}'.".format(key))
if 'grid' not in fragment['mesh'] or \
'elements' not in fragment['mesh']:
raise ValueError(
"Material fragment mesh must contain 'grid' and 'elements'.")

self._validateGrid(fragment['mesh']['grid'])

self.input.setdefault('materials', [])
self.input.setdefault('mesh', {})
self.input['mesh'].setdefault('elements', [])
self.input.setdefault('materialAssociations', [])

material = dict(fragment['material'])
old_material_id = material.get('id', 1)
new_material_id = len(self.input['materials']) + 1
material['id'] = new_material_id
self.input['materials'].append(material)

element_offset = len(self.input['mesh']['elements'])
element_map = {}
for index, element in enumerate(fragment['mesh']['elements'],
start=1):
old_element_id = element.get('id', index)
new_element_id = element_offset + index
element = dict(element)
element['id'] = new_element_id
self.input['mesh']['elements'].append(element)
element_map[old_element_id] = new_element_id

for association in fragment['materialAssociations']:
association_material = association.get(
'materialId', old_material_id)
if association_material != old_material_id:
raise ValueError(
"Material fragment association references an unknown "
"material.")
element_ids = []
for element_id in association.get('elementIds', []):
if element_id not in element_map:
raise ValueError(
"Material fragment association references an unknown "
"element.")
element_ids.append(element_map[element_id])
merged = {
'materialId': new_material_id,
'elementIds': element_ids,
}
if 'level' in association:
merged['level'] = association['level']
self.input['materialAssociations'].append(merged)

return new_material_id

def addConformalVolumeFromVTK(self, path_to_vtk, subtype="volume", name=None):
if subtype not in ("volume", "surface"):
raise ValueError("subtype must be 'volume' or 'surface'.")
Expand Down Expand Up @@ -176,6 +290,25 @@ def addCellElementBox(self, boundingBox):

return id

def addCellElementIntervals(self, intervals, name=None):
'''Adds a cell element from closed-open relative node intervals.'''
if 'mesh' not in self.input:
self.input['mesh'] = {}
if 'elements' not in self.input['mesh']:
self.input['mesh']['elements'] = []
elements = self.input['mesh']['elements']

id = len(elements) + 1
element = {
"id": id,
"type": "cell",
"intervals": intervals,
}
if name is not None:
element["name"] = name
elements.append(element)
return id

def addNodeElement(self, position):
''' position is assumed to be in absolute coordinates.'''
if isinstance(position, list):
Expand Down Expand Up @@ -305,6 +438,22 @@ def addFarFieldProbe(self, elementId, name, theta, phi, domain):
"domain": domain
})

def addMovieProbe(self, elementId, name, field="electric",
component="magnitude", domain=None):
if 'probes' not in self.input:
self.input['probes'] = []

probe = {
"name": name,
"type": "movie",
"field": field,
"component": component,
"elementIds": [elementId],
}
if domain is not None:
probe["domain"] = domain
self.input['probes'].append(probe)

def exportCase(self, case_name):
with open(case_name + '.fdtd.json', 'w') as f:
json.dump(self.input, f)
Expand Down
Loading
Loading