From 61e8ee5c472a52b718fd2337c3b838b1b867a701 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Thu, 26 Nov 2026 15:18:31 +0100 Subject: [PATCH 1/6] M0.101: the createPatchDicts from the description (gaps row 4, 2 of 6) --- ROADMAP.md | 3 +- crates/engine/src/cmd/mesh_snappy.rs | 10 +- crates/engine/src/cmd/workflow.rs | 69 ++- crates/engine/src/tests.rs | 207 ++++++- crates/model/src/coupling.rs | 25 +- crates/model/src/coupling_tests.rs | 8 +- crates/model/src/create_patch.rs | 626 +++++++++++++++++++++ crates/model/src/create_patch_tests.rs | 445 +++++++++++++++ crates/model/src/description.rs | 260 ++++++++- crates/model/src/description_edit.rs | 58 +- crates/model/src/description_edit_tests.rs | 42 +- crates/model/src/description_tests.rs | 105 +++- crates/model/src/lib.rs | 1 + crates/model/tests/coupling.rs | 60 +- crates/ui-egui/src/forms.rs | 58 +- crates/ui-egui/src/results.rs | 18 +- crates/ui-egui/src/workflowcard.rs | 19 +- crates/validate/src/description.rs | 90 +++ docs/common-workflow.md | 2 +- docs/gaps.md | 2 +- docs/user-guide/checks.md | 1 + docs/user-guide/command-line.md | 6 +- docs/user-guide/workflow.md | 96 +++- 23 files changed, 2142 insertions(+), 69 deletions(-) create mode 100644 crates/model/src/create_patch.rs create mode 100644 crates/model/src/create_patch_tests.rs diff --git a/ROADMAP.md b/ROADMAP.md index 16bf9bc..281c051 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,6 +1,6 @@ # umcfGui roadmap -**Stage:** M0 — foundation. *Last updated: 2026-11-24.* +**Stage:** M0 — foundation. *Last updated: 2026-11-26.* | Area | State | |---|---| @@ -124,3 +124,4 @@ Ranked work list: [`docs/gaps.md`](docs/gaps.md). - 2026-11-24 — M0.98 a background mesh kept between regions (gaps row 6, 4 of 4 parts; the row is closed): a region's mesh can start with `background ` instead of `blockMesh` (`model::workflow::RootStep::Background`), as the `windAroundBuildings` tutorials mesh the vegetation from the air's background. `Allprepare` keeps what that region's `blockMesh` made in `constant/polyMesh.background.`, marked as its own (`.umcfgui-kept`; one there without the mark stops it, nothing removed), copies it into `constant/polyMesh` for each region meshed from it and removes it after the last (`Allclean` removes a marked one); a region it can't be kept from (not listed before it, not built by steps of its own starting with `blockMesh`) is refused by `workflow.scripts` and named by the case check (`workflow.blocks`), with blocks of its own its mesh doesn't read. The script reader takes the kept copy back where the mesh it was kept from is moved to its region with `mv` (the generated scripts; any `constant/polyMesh.*` directory, as the tutorials' `polyMesh.bckp`), and lists a copy no region is meshed from or one removed before it is used. The case check (`workflow.snappy`) also checks a region's inside point against the blocks as they are now. `mesh.snappy` takes `background` (a region, or `null` for its own `blockMesh` again) and checks the inside point and the surfaces against that region's blocks; the *Snappy mesh* card has *Background from*, offering the regions it can start from, and previews and checks their blocks. - 2026-11-24 — M0.99 a script's words bounded (review of M0.98): a word longer than 64 KiB once expanded is cut there and marked unresolved (a long literal was kept whole), and a script's reading stops after 64 MiB of expanded words (`script::MAX_EXPANDED`, each word charged 64 bytes more, as it is expanded), so neither a command of many long words nor a loop repeating long or empty ones builds steps without end; the prefixes before a command (`time`, `nohup`, …) are taken off at once. - 2026-11-24 — M0.100 each region's `changeDictionaryDict` from the description (gaps row 4, 1 of 6 parts): `workflow.dictionaries` (*Write the dictionaries*, a form) writes it for every region whose steps run `changeDictionary`, from the patches' roles and partners (`model::coupling`): a wall with a partner `mappedWall`, an open side `mapped` (`mappedPatch` in OpenFOAM-8), the vegetation's canopy the air's cells (`mappedInternal`; OpenFOAM-8 `mappedWall` with `sampleMode nearestCell`), OpenFOAM-12's `neighbourRegion`/`neighbourPatch` or OpenFOAM-8's `sampleRegion`/`samplePatch`, a fluid's and a solid's patches paired by `method nearest`; generated with a checksum, one edited by hand written over only with `replace`. Refused for a partner without a role, and for a name that isn't a plain OpenFOAM word or a region's that can't be a directory on every system. The case check `workflow.change-dictionary` says a missing, stale or differing one, by the keys each version reads, and a sample mode or method the version hasn't. `workflow.import` gives a vegetation patch mapped to its twin whose role isn't told the role `coupled` (a `mappedWall`) or `sky` (`mapped`, `mappedPatch`). The 15 dictionaries of the three 3×3 cases (OpenFOAM-8 and -12) are generated as the cases' own map them; on the street canyon with vegetation `Allprepare` makes the same meshes (OpenFOAM-8 byte for byte, OpenFOAM-12 with `method nearest` added) and `Allrun` the same fields. +- 2026-11-26 — M0.101 the `createPatchDict`s from the description (gaps row 4, 2 of 6 parts): a patch's `from` in `system/umcfWorkflow` names the patches `createPatch` makes it of (`( defaultFaces )`; a quoted name is a pattern, `( "region1_to_.*" )`), and its `type` the type where its role doesn't give it (the street canyons' plain `buildings` wall). `workflow.dictionaries` writes `system//createPatchDict` for a region whose steps run `createPatch`, and `system/createPatchDict` for the regions meshed with it in `constant/polyMesh` (which must make the same patches), each patch typed by its own type, else `wall` for a wall's role, the canopy and every solid's patch, else `patch`; `pointSync false;` for OpenFOAM-8. `workflow.import` reads `from` and `type` from the case's `createPatchDict`s (a source as written: quoted, a pattern), `workflow.dictionaries` leaves a case's own that holds what the description can't as it is, noted, even with `replace`, `workflow.patch` (*Describe a patch*: *Made of*, *Type*) edits them, and the case check `workflow.create-patch` says a dictionary missing, stale or making the patches otherwise (`model::create_patch`). The 16 `createPatchDict`s of the four 3×3 cases are generated as the cases' own make them; on the street canyon with vegetation `Allprepare` with the generated ones makes the same meshes, byte for byte, in OpenFOAM-8 and -12. diff --git a/crates/engine/src/cmd/mesh_snappy.rs b/crates/engine/src/cmd/mesh_snappy.rs index 5bcbe21..bbd68f1 100644 --- a/crates/engine/src/cmd/mesh_snappy.rs +++ b/crates/engine/src/cmd/mesh_snappy.rs @@ -771,9 +771,13 @@ fn snappy(s: &mut Session, p: &Value) -> Result { for (name, role) in &roles { match with.patches.iter_mut().find(|q| q.name == *name) { Some(q) => q.role = *role, - None => { - with.patches.push(umcf_model::description::PatchDesc { name: name.clone(), role: *role, partner: None }) - } + None => with.patches.push(umcf_model::description::PatchDesc { + name: name.clone(), + role: *role, + partner: None, + from: Vec::new(), + kind: None, + }), } } let type_of = blocks::type_lookup(&with); diff --git a/crates/engine/src/cmd/workflow.rs b/crates/engine/src/cmd/workflow.rs index 1fa7bca..b2dd43b 100644 --- a/crates/engine/src/cmd/workflow.rs +++ b/crates/engine/src/cmd/workflow.rs @@ -115,7 +115,7 @@ pub(super) const IMPORT: CommandSpec = CommandSpec { label: "Write workflow description", menu: "Case/Write workflow description", shortcut: None, - params: "replace: true to write over the case's system/umcfWorkflow (its comments and hand edits are not kept). Writes the workflow description from the case: its scripts (Allprepare, Allrun) read into the workflow, the region kinds, each patch's role and partner as its mesh and velocity condition tell, each solid's materials as its constant//transportProperties lists them (buildingMaterials), and the components the case's files switch on (a fluid's grassProperties whose grassModel isn't none and grass isn't off, a limitTemperature entry in the file a fluid's limit is read from (OpenFOAM-12: system/fvConstraints, else system/fvOptions, else constant/fvOptions; OpenFOAM-8: constant/fvOptions, else system/fvOptions), blending on in controlDict), and the settings its files have (deltaT, endTime, writeInterval, the fluids' RAS model, the temperature limit's bounds, blendingCoeffs: a macro, or fluids that differ, noted and left out), each region's grid of blocks read from the blockMeshDict its mesh reads, when that is one (all its blocks one cell each of a grid of stations along x, y and z, each span's cells and grading the same in every block; a dictionary that isn't one, with curved edges, a block over several cells, a scale, an #include or a $macro, is left out with a note; each patch whose type there isn't the one its role (or no role: patch) gives kept in the blocks' types; a region without a mesh given the patches its blocks name, without a role; the dictionary isn't written: mesh.block writes it from the blocks), each region's snappy entry read from the snappyHexMeshDict its snappyHexMesh step reads (its STL surfaces that cut or refine by distance, with the solids of the _ patches each made in the mesh, boxes refining the cells inside, feature levels, layers, the inside point, the expansion ratio and the first layer's thickness; the inside point as the case's version takes it (OpenFOAM-12: insidePoints of one point, insidePoint, locationInMesh; OpenFOAM-8: locationInMesh); what the entry can't hold noted and left out: other geometry, a surface or box it would refuse (the others kept), a scaled surface, a surface making a faceZone or cellZone (its refinement alone kept), layer sizes other than the entry's, an expansion below 1, a patch type other than its role's (each _ patch against its own), patchInfo beyond its type (inGroups), singleRegionName false, an expansionRatio that isn't a number, a name given to more than one surface or box, layers given to a surface by a _ patch's name, levels per solid, surfaces and layers named by a pattern, a patch's own layer settings, outside points, an #include or $macro not followed, macros; several inside points give no entry; the dictionary isn't written: mesh.snappy with replace writes it from the entry), and the material library from the solids' materials (each model's first material whose coefficients are numbers or dictionaries of them; a model whose materials differ noted once, a material with a macro or directive among its coefficients noted and left out). What it couldn't tell (a patch without a role, a region the scripts don't mesh, a step that doesn't fit, a material or its model given by a macro, a material listed more than once) is listed in notes. case.save writes it. A system/umcfWorkflow that is a symbolic link is not written over.", + params: "replace: true to write over the case's system/umcfWorkflow (its comments and hand edits are not kept). Writes the workflow description from the case: its scripts (Allprepare, Allrun) read into the workflow, the region kinds, each patch's role and partner as its mesh and velocity condition tell, each solid's materials as its constant//transportProperties lists them (buildingMaterials), and the components the case's files switch on (a fluid's grassProperties whose grassModel isn't none and grass isn't off, a limitTemperature entry in the file a fluid's limit is read from (OpenFOAM-12: system/fvConstraints, else system/fvOptions, else constant/fvOptions; OpenFOAM-8: constant/fvOptions, else system/fvOptions), blending on in controlDict), and the settings its files have (deltaT, endTime, writeInterval, the fluids' RAS model, the temperature limit's bounds, blendingCoeffs: a macro, or fluids that differ, noted and left out), each region's grid of blocks read from the blockMeshDict its mesh reads, when that is one (all its blocks one cell each of a grid of stations along x, y and z, each span's cells and grading the same in every block; a dictionary that isn't one, with curved edges, a block over several cells, a scale, an #include or a $macro, is left out with a note; each patch whose type there isn't the one its role (or no role: patch) gives kept in the blocks' types; a region without a mesh given the patches its blocks name, without a role; the dictionary isn't written: mesh.block writes it from the blocks), each region's snappy entry read from the snappyHexMeshDict its snappyHexMesh step reads (its STL surfaces that cut or refine by distance, with the solids of the _ patches each made in the mesh, boxes refining the cells inside, feature levels, layers, the inside point, the expansion ratio and the first layer's thickness; the inside point as the case's version takes it (OpenFOAM-12: insidePoints of one point, insidePoint, locationInMesh; OpenFOAM-8: locationInMesh); what the entry can't hold noted and left out: other geometry, a surface or box it would refuse (the others kept), a scaled surface, a surface making a faceZone or cellZone (its refinement alone kept), layer sizes other than the entry's, an expansion below 1, a patch type other than its role's (each _ patch against its own), patchInfo beyond its type (inGroups), singleRegionName false, an expansionRatio that isn't a number, a name given to more than one surface or box, layers given to a surface by a _ patch's name, levels per solid, surfaces and layers named by a pattern, a patch's own layer settings, outside points, an #include or $macro not followed, macros; several inside points give no entry; the dictionary isn't written: mesh.snappy with replace writes it from the entry), and the material library from the solids' materials (each model's first material whose coefficients are numbers or dictionaries of them; a model whose materials differ noted once, a material with a macro or directive among its coefficients noted and left out). What it couldn't tell (a patch without a role, a region the scripts don't mesh, a step that doesn't fit, a material or its model given by a macro, a material listed more than once) is listed in notes. case.save writes it. A system/umcfWorkflow that is a symbolic link is not written over. Also reads, from the createPatchDict each region's createPatch reads (its own when its steps run createPatch, else system/createPatchDict when its mesh does), the patches made of others (constructFrom patches) into their from, as written (a quoted source a pattern), and their type where the role wouldn't give it; a name given twice is made of both items' sources; an item made of a face set, part of which a macro or directive gives, with a patchInfo that isn't a plain type's dictionary, other keys, a key given twice, or sources with a quote, backslash or space inside is noted and left out (20 notes a dictionary for each region reading it, then a count).", enabled: needs_case, run: import, journal: true, @@ -220,7 +220,7 @@ pub(super) const PATCH: CommandSpec = CommandSpec { label: "Describe a patch", menu: "Case/Workflow/Describe a patch", shortcut: None, - params: "region, patch: the region of system/umcfWorkflow and its patch (a patch the region doesn't list is added); role: inlet, outlet, side, top, ground, coupled, canopy, interior, bottom or sky (null takes it away); partner: {\"region\", \"patch\"} it is coupled to (null takes it away); name: a new name for the patch (the partners that named it follow, and the region's blocks: sides, single faces, patches without faces, types; refused while the region's blocks entry doesn't read whole, or when the blocks name a patch of the new name, or to or from defaultFaces while the region has blocks: the faces left to blockMesh). At least one of them. Edits the description only, entry by entry: its comments and layout stay. The case's own files (the mesh, fields, dictionaries) follow once they are written from it; patch.set renames a patch in the case.", + params: "region, patch: the region of system/umcfWorkflow and its patch (a patch the region doesn't list is added); role: inlet, outlet, side, top, ground, coupled, canopy, interior, bottom or sky (null takes it away); partner: {\"region\", \"patch\"} it is coupled to (null takes it away); from: the patches createPatch makes it of, a list of names and patterns as createPatch reads them (a name that isn't a plain word is quoted for it, a pattern: \"region1_to_.*\"; one given quoted stays so, \"\\\"region.1\\\"\" a regular expression; none with a quote, backslash or space inside; null takes them away), which workflow.dictionaries writes into the createPatchDict its mesh or steps read; type: the type createPatch makes it of where its role doesn't give it (wall for a plain wall without a partner; read only with from, refused without; null takes it away; not a mapped type, which changeDictionary gives from the role and partner); name: a new name for the patch (refused while another patch of the region is made of it, from; the partners that named it follow, and the region's blocks: sides, single faces, patches without faces, types; refused while the region's blocks entry doesn't read whole, or when the blocks name a patch of the new name, or to or from defaultFaces while the region has blocks: the faces left to blockMesh). At least one of them. Edits the description only, entry by entry: its comments and layout stay. The case's own files (the mesh, fields, dictionaries) follow once they are written from it; patch.set renames a patch in the case.", enabled: needs_case, run: patch, journal: true, @@ -230,7 +230,7 @@ pub(super) const PATCH: CommandSpec = CommandSpec { /// `workflow.patch`: a patch's role, partner and name. fn patch(s: &mut Session, p: &Value) -> Result { - let p = Params::new(PATCH.id, p, &["region", "patch", "role", "partner", "name"])?; + let p = Params::new(PATCH.id, p, &["region", "patch", "role", "partner", "from", "type", "name"])?; let region = p.required_str("region")?; let patch = p.required_str("patch")?; let mut edit = PatchEdit::default(); @@ -262,6 +262,24 @@ fn patch(s: &mut Session, p: &Value) -> Result { } } } + match p.value("from") { + None => {} + Some(Value::Null) => edit.from = Some(Vec::new()), + Some(Value::Array(items)) if !items.is_empty() => { + let names: Option> = items.iter().map(|v| v.as_str().map(str::to_string)).collect(); + match names { + Some(names) => edit.from = Some(names), + None => return Err(Error::Params(format!("{}: from is a list of patch names, or null", PATCH.id))), + } + } + Some(_) => return Err(Error::Params(format!("{}: from is a list of patch names, or null", PATCH.id))), + } + match p.value("type") { + None => {} + Some(Value::Null) => edit.kind = Some(None), + Some(Value::String(t)) => edit.kind = Some(Some(t.clone())), + Some(_) => return Err(Error::Params(format!("{}: type is a patch type, or null", PATCH.id))), + } edit.rename = p.str("name")?.map(str::to_string); let o = s.opened_mut()?; let r = o.case.describe_patch(region, patch, &edit)?; @@ -760,7 +778,7 @@ pub(super) const DICTIONARIES: CommandSpec = CommandSpec { label: "Write the dictionaries", menu: "Case/Workflow/Write the dictionaries", shortcut: None, - params: "region: one region (default: every region). replace: true to write over a dictionary edited by hand or not written by umcfGui (case.save keeps a backup of each). Writes, from system/umcfWorkflow and for its OpenFOAM version (the case's when it names none), each region's system//changeDictionaryDict whose steps run changeDictionary: every patch with a partner, mappedWall to it when its role is a wall's (ground, coupled, interior, bottom) and mapped (mappedPatch in OpenFOAM-8) when it is an open side's (inlet, outlet, side, top, sky), with neighbourRegion and neighbourPatch (OpenFOAM-8: sampleMode nearestPatchFace, sampleRegion, samplePatch) and a uniform offset of (0 0 0); a fluid's and a solid's patches paired by method nearest (OpenFOAM-12), a vegetation patch and its twin without; the vegetation region's canopy mapped to the air's cells (mappedInternal, offsetMode normal, distance 0; OpenFOAM-8: mappedWall, sampleMode nearestCell), the air being the fluid region its other patches are coupled to, else the radiation's lai region, else the only fluid region. Patches without a partner are left as the mesh makes them. Generated, with a checksum: one written by umcfGui and unchanged since is written over without replace. Refused, writing none: a description with problems (workflow.show lists them), a patch with a partner but no role, a partner region the description doesn't have, a canopy with a partner or with no air to map to, a region, patch or partner name that isn't a plain OpenFOAM word (they are written unquoted), a region's name that can't be a directory on every system (., .., a colon, a dot at its end, a Windows device's name), a region named that the description doesn't have or whose steps don't run changeDictionary, a dictionary there that doesn't load (or a directory: mend or remove it), one that is a symbolic link or the same file as another dictionary, and, without replace, one there that differs and wasn't written by umcfGui. The outcome lists what was written, written over by hand edits, and left as it was, and notes a region with coupled patches whose steps don't run changeDictionary. case.save writes them; edit.undo takes them back.", + params: "region: one region (default: every region). replace: true to write over a dictionary edited by hand or not written by umcfGui (case.save keeps a backup of each). Writes, from system/umcfWorkflow and for its OpenFOAM version (the case's when it names none), each region's system//changeDictionaryDict whose steps run changeDictionary: every patch with a partner, mappedWall to it when its role is a wall's (ground, coupled, interior, bottom) and mapped (mappedPatch in OpenFOAM-8) when it is an open side's (inlet, outlet, side, top, sky), with neighbourRegion and neighbourPatch (OpenFOAM-8: sampleMode nearestPatchFace, sampleRegion, samplePatch) and a uniform offset of (0 0 0); a fluid's and a solid's patches paired by method nearest (OpenFOAM-12), a vegetation patch and its twin without; the vegetation region's canopy mapped to the air's cells (mappedInternal, offsetMode normal, distance 0; OpenFOAM-8: mappedWall, sampleMode nearestCell), the air being the fluid region its other patches are coupled to, else the radiation's lai region, else the only fluid region. Patches without a partner are left as the mesh makes them. Generated, with a checksum: one written by umcfGui and unchanged since is written over without replace. Refused, writing none: a description with problems (workflow.show lists them), a patch with a partner but no role, a partner region the description doesn't have, a canopy with a partner or with no air to map to, a region, patch or partner name that isn't a plain OpenFOAM word (they are written unquoted), a region's name that can't be a directory on every system (., .., a colon, a dot at its end, a Windows device's name), a region named that the description doesn't have, a dictionary there that doesn't load (or a directory: mend or remove it), one that is a symbolic link or the same file as another dictionary, and, without replace, one there that differs and wasn't written by umcfGui. Also writes each createPatchDict the mesh or steps read: system//createPatchDict for a region whose steps run createPatch, system/createPatchDict for the regions meshed with createPatch in constant/polyMesh (one for them all: they must make the same patches); each patch made of others (from) as { name; patchInfo { type; } constructFrom patches; patches ( … ); }, the sources as the description has them (a quoted one a pattern), its type the patch's own (type), else wall for a wall's role (ground, coupled, interior, bottom), the canopy and every solid's patch, else patch; pointSync false for OpenFOAM-8. Refused, too: a patch made by createPatch with neither a role nor a type, or in a region whose mesh and steps run no createPatch, a region running createPatch both in and after its mesh with patches to make, and regions sharing system/createPatchDict that make other patches. The case's own createPatchDict that holds what the description can't (a patch it doesn't make or gives twice, one made of a face set or of sources it can't hold, patchInfo entries besides the type or other keys of an item, a key given twice in an item or its patchInfo, a value from a macro or directive, a patches list that can't be read whole, another entry at its top, OpenFOAM-8's pointSync not off) is left as it is even with replace, noted with what would be lost; the others are written. With region, that region's dictionaries (and the shared createPatchDict when its mesh runs createPatch); a region whose mesh and steps run neither changeDictionary nor createPatch is refused. The outcome lists what was written, written over by hand edits, and left as it was, and notes a region with coupled patches whose steps don't run changeDictionary. case.save writes them; edit.undo takes them back.", enabled: needs_case, run: dictionaries, journal: true, @@ -770,7 +788,7 @@ pub(super) const DICTIONARIES: CommandSpec = CommandSpec { /// `workflow.dictionaries`: the dictionaries generated from the description. fn dictionaries(s: &mut Session, p: &Value) -> Result { - use umcf_model::coupling; + use umcf_model::{coupling, create_patch}; let p = Params::new(DICTIONARIES.id, p, &["region", "replace"])?; let replace = p.bool("replace")?.unwrap_or(false); let only = p.str("region")?.map(str::to_string); @@ -796,9 +814,9 @@ fn dictionaries(s: &mut Session, p: &Value) -> Result { if let Some(name) = &only { match d.region(name) { None => return Err(Error::Failed(format!("region {name} isn't in {PATH}"))), - Some(r) if !coupling::runs(r) => { + Some(r) if !coupling::runs(r) && !create_patch::runs(r) && !create_patch::runs_root(r) => { return Err(Error::Failed(format!( - "the steps of region {name} in {PATH} don't run changeDictionary: it has no dictionary to write" + "the mesh and steps of region {name} in {PATH} run neither changeDictionary nor createPatch: it has no dictionary to write" ))); } Some(_) => {} @@ -820,6 +838,28 @@ fn dictionaries(s: &mut Session, p: &Value) -> Result { .map_err(|e| Error::Failed(format!("{}: {e}: no dictionary is written", DICTIONARIES.id)))?; texts.push((coupling::dict_path(&r.name), text)); } + // The createPatchDicts: a region's own, and the one of every region meshed with createPatch + // in constant/polyMesh, written when one of them is asked for. + let targets = create_patch::targets(&d, only.as_deref()) + .map_err(|e| Error::Failed(format!("{}: {e}: no dictionary is written", DICTIONARIES.id)))?; + for t in &targets { + // The case's own holding what the description can't: never written over, even with + // replace (it would be lost), but left as it is, noted (the others are written). + if let Some(doc) = o.case.dict(&t.path) + && !umcf_model::blocks::untouched(&doc.to_string()) + { + let kept = create_patch::kept(&doc.root, &t.made, version); + if !kept.is_empty() { + notes.push(format!( + "{} holds what {PATH} doesn't ({}): left as it is, as written over it would be lost: give the patches their from (and type) with workflow.patch, or mend the file by hand", + t.path, + create_patch::summary(&kept) + )); + continue; + } + } + texts.push((t.path.clone(), create_patch::dict(t, version))); + } let limit = o.case.options().dict_bytes; // What is there now: the same, one umcfGui wrote (written over), or another (by hand). let mut written = Vec::new(); @@ -875,8 +915,9 @@ fn dictionaries(s: &mut Session, p: &Value) -> Result { })?; } let changed: Vec<&String> = written.iter().chain(&by_hand).collect(); - let message = if texts.is_empty() { - format!("no region's steps in {PATH} run changeDictionary: no dictionary to write") + let left = notes.iter().filter(|n| n.contains("left as it is, as written over")).count(); + let message = if texts.is_empty() && left == 0 { + format!("no region's mesh or steps in {PATH} run changeDictionary or createPatch: no dictionary to write") } else if changed.is_empty() { format!("the dictionaries are as {PATH} has them already, for {version}: nothing to write") } else { @@ -885,6 +926,14 @@ fn dictionaries(s: &mut Session, p: &Value) -> Result { changed.iter().map(|x| x.as_str()).collect::>().join(", ") ) }; + let message = if left > 0 { + format!( + "{message}; {} left as it is, holding what {PATH} doesn't (see the notes)", + count(left, "createPatchDict") + ) + } else { + message + }; Ok(Outcome::new( message, json!({ "version": version.to_string(), "written": written, "replaced": by_hand, "unchanged": same, "notes": notes }), @@ -983,6 +1032,8 @@ pub(crate) fn to_json(d: &Description) -> Value { "name": p.name, "role": p.role.map(description::Role::name), "partner": p.partner.as_ref().map(|(r, q)| json!({ "region": r, "patch": q })), + "from": p.from, + "type": p.kind, }) }) .collect(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ecb55d8..12ef1c1 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2143,11 +2143,14 @@ fn the_description_is_edited_entry_by_entry() { assert_eq!(out.message, "system/umcfWorkflow: patch top of region roofs is now outside"); assert_eq!( region(&mut s, "roofs")["patches"], - json!([{ "name": "outside", "role": "coupled", "partner": { "region": "air", "patch": "roofs" } }]) + json!([{ "name": "outside", "role": "coupled", "partner": { "region": "air", "patch": "roofs" }, "from": [], "type": null }]) ); s.execute("workflow.patch", &json!({ "region": "roofs", "patch": "outside", "role": null, "partner": null })) .unwrap(); - assert_eq!(region(&mut s, "roofs")["patches"], json!([{ "name": "outside", "role": null, "partner": null }])); + assert_eq!( + region(&mut s, "roofs")["patches"], + json!([{ "name": "outside", "role": null, "partner": null, "from": [], "type": null }]) + ); s.execute("workflow.material", &json!({ "region": "roofs", "material": "tiles", "remove": true })).unwrap(); assert_eq!(region(&mut s, "roofs")["materials"], json!([])); // Each is one edit in the history and the journal. @@ -4911,13 +4914,15 @@ fn each_regions_change_dictionary_is_written_from_its_patches_roles_and_partners s.execute("case.new", &canyon_params(&dir, version)).unwrap(); // Nothing to write while no region's steps run changeDictionary. let out = s.execute("workflow.dictionaries", &json!({})).unwrap(); - assert!(out.message.starts_with("no region's steps"), "{}", out.message); + assert!(out.message.starts_with("no region's mesh or steps"), "{}", out.message); // The canyon's coupling, as workflow.import reads it from a case. let (mut d, _) = s.case().unwrap().description().unwrap(); let patch = |name: &str, role: Role, partner: Option<(&str, &str)>| PatchDesc { name: name.into(), role: Some(role), partner: partner.map(|(r, p)| (r.into(), p.into())), + from: Vec::new(), + kind: None, }; for r in &mut d.regions { r.steps = vec![RegionStep::ChangeDictionary]; @@ -5125,7 +5130,7 @@ fn each_regions_change_dictionary_is_written_from_its_patches_roles_and_partners std::fs::write(dir.join("system/umcfWorkflow"), d.write()).unwrap(); s.execute("case.open", &json!({ "path": dir.to_str().unwrap() })).unwrap(); let e = s.execute("workflow.dictionaries", &json!({"region": "street"})).unwrap_err().to_string(); - assert!(e.contains("the steps of region street in system/umcfWorkflow don't run changeDictionary"), "{e}"); + assert!(e.contains("the mesh and steps of region street in system/umcfWorkflow run neither changeDictionary nor createPatch"), "{e}"); let out = s.execute("workflow.dictionaries", &json!({"replace": true})).unwrap(); assert!( out.data["notes"][0] @@ -5138,3 +5143,197 @@ fn each_regions_change_dictionary_is_written_from_its_patches_roles_and_partners let _ = std::fs::remove_dir_all(&dir); } } + +#[test] +fn each_create_patch_dict_is_written_from_the_patches_made_of_others() { + use umcf_model::workflow::RegionStep; + for version in [8, 12] { + let dir = std::env::temp_dir().join(format!("umcf-engine-{}-create-patch-{version}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut s = Session::with_backup(".umcfgui/backup/test"); + s.execute("case.new", &canyon_params(&dir, version)).unwrap(); + // The air's buildings made of blockMesh's defaultFaces after its mesh, the street's sides + // too; the other regions run no createPatch. + let (mut d, _) = s.case().unwrap().description().unwrap(); + for r in &mut d.regions { + r.steps = match r.name.as_str() { + "air" | "street" => vec![RegionStep::CreatePatch], + _ => Vec::new(), + }; + } + std::fs::write(dir.join("system/umcfWorkflow"), d.write()).unwrap(); + s.execute("case.open", &json!({ "path": dir.to_str().unwrap(), "discard": true })).unwrap(); + let out = s + .execute( + "workflow.patch", + &json!({"region": "air", "patch": "buildings", "role": "coupled", "from": ["defaultFaces"]}), + ) + .unwrap(); + assert_eq!(out.message, "system/umcfWorkflow: patch buildings of region air added"); + let air = + out.data["description"]["regions"].as_array().unwrap().iter().find(|r| r["name"] == "air").unwrap().clone(); + let buildings = air["patches"].as_array().unwrap().iter().find(|p| p["name"] == "buildings").unwrap().clone(); + assert_eq!(buildings["from"], json!(["defaultFaces"])); + s.execute( + "workflow.patch", + &json!({"region": "street", "patch": "sides", "role": "side", "from": ["defaultFaces", "region1_to_.*"]}), + ) + .unwrap(); + let desc = s.case().unwrap().dict("system/umcfWorkflow").unwrap().to_string(); + assert!(desc.contains("sides { role side; from ( defaultFaces \"region1_to_.*\" ); }"), "{desc}"); + // A type of its own, over the role's; a mapped one refused. + s.execute("workflow.patch", &json!({"region": "street", "patch": "sides", "type": "symmetryPlane"})).unwrap(); + let e = s + .execute("workflow.patch", &json!({"region": "street", "patch": "sides", "type": "mappedWall"})) + .unwrap_err(); + assert!(e.to_string().contains("type mappedWall needs entries of its own"), "{e}"); + let out = s.execute("workflow.patch", &json!({"region": "street", "patch": "sides", "type": null})).unwrap(); + let street = out.data["description"]["regions"] + .as_array() + .unwrap() + .iter() + .find(|r| r["name"] == "street") + .unwrap() + .clone(); + let sides = street["patches"].as_array().unwrap().iter().find(|p| p["name"] == "sides").unwrap().clone(); + assert_eq!(sides["type"], Value::Null); + // A type only with from. + let e = s.execute("workflow.patch", &json!({"region": "air", "patch": "inlet", "type": "wall"})).unwrap_err(); + assert!(e.to_string().contains("a type is read only for a patch createPatch makes (from)"), "{e}"); + s.execute("workflow.patch", &json!({"region": "street", "patch": "sides", "type": "wall"})).unwrap(); + let e = s.execute("workflow.patch", &json!({"region": "street", "patch": "sides", "from": null})).unwrap_err(); + assert!(e.to_string().contains("give from too, or take the type away (null)"), "{e}"); + s.execute("workflow.patch", &json!({"region": "street", "patch": "sides", "type": null})).unwrap(); + // Refused: a source with a quote, an empty list. + let e = + s.execute("workflow.patch", &json!({"region": "street", "patch": "sides", "from": ["a\"b"]})).unwrap_err(); + assert!(e.to_string().contains("is neither a plain OpenFOAM name nor a pattern"), "{e}"); + let e = s.execute("workflow.patch", &json!({"region": "street", "patch": "sides", "from": []})).unwrap_err(); + assert!(e.to_string().contains("from is a list of patch names, or null"), "{e}"); + let said = |s: &mut Session| -> Vec { + let check = s.execute("case.check", &Value::Null).unwrap(); + check.data["diagnostics"] + .as_array() + .unwrap() + .iter() + .filter(|d| d["code"] == "workflow.create-patch") + .map(|d| format!("{}: {}", d["path"].as_str().unwrap_or(""), d["message"].as_str().unwrap_or(""))) + .collect() + }; + assert_eq!( + said(&mut s), + [ + "system/air/createPatchDict: not there, and createPatch reads it: workflow.dictionaries writes it from the patches of region air", + "system/street/createPatchDict: not there, and createPatch reads it: workflow.dictionaries writes it from the patches of region street", + ] + ); + let out = s.execute("workflow.dictionaries", &json!({})).unwrap(); + assert_eq!( + out.data["written"], + json!(["system/air/createPatchDict", "system/street/createPatchDict"]), + "{}", + out.data + ); + assert_eq!(said(&mut s), Vec::::new()); + let air = s.case().unwrap().dict("system/air/createPatchDict").unwrap().to_string(); + assert!(umcf_model::blocks::untouched(&air), "{air}"); + assert!( + air.contains("name buildings;") && air.contains("patches ( defaultFaces );"), + "{air}" + ); + assert_eq!(air.contains("pointSync false;"), version == 8, "{air}"); + let street = s.case().unwrap().dict("system/street/createPatchDict").unwrap().to_string(); + assert!( + street.contains("type wall;") && street.contains("( defaultFaces \"region1_to_.*\" )"), + "{street}" + ); + // One region only: its dictionary. + let out = s.execute("workflow.dictionaries", &json!({"region": "street"})).unwrap(); + assert_eq!(out.data["unchanged"], json!(["system/street/createPatchDict"]), "{}", out.data); + // Edited by hand: said, kept without replace, written with it. + s.execute("case.save", &json!({})).unwrap(); + let hand = dir.join("system/air/createPatchDict"); + std::fs::write( + &hand, + "FoamFile { class dictionary; object createPatchDict; }\npointSync false;\npatches ( { name buildings; patchInfo { type wall; } constructFrom patches; patches ( other ); } );\n", + ) + .unwrap(); + s.execute("case.open", &json!({ "path": dir.to_str().unwrap(), "discard": true })).unwrap(); + let hand_said = said(&mut s); + assert_eq!(hand_said.len(), 1, "{hand_said:?}"); + assert!( + hand_said[0].starts_with( + "system/air/createPatchDict: the case's own makes the patches otherwise than the description of region air does (patch buildings is made of ( other ) there, the description makes it of ( defaultFaces ))" + ), + "{hand_said:?}" + ); + let e = s.execute("workflow.dictionaries", &json!({})).unwrap_err().to_string(); + assert!(e.contains("system/air/createPatchDict was edited by hand"), "{e}"); + let out = s.execute("workflow.dictionaries", &json!({"replace": true})).unwrap(); + assert_eq!(out.data["replaced"], json!(["system/air/createPatchDict"]), "{}", out.data); + assert_eq!(said(&mut s), Vec::::new()); + // One making what the description doesn't hold: never written over, even with replace. + s.execute("case.save", &json!({})).unwrap(); + std::fs::write( + &hand, + "FoamFile { class dictionary; object createPatchDict; }\npointSync false;\npatches ( { name buildings; patchInfo { type wall; } constructFrom patches; patches ( defaultFaces ); } { name cyc; patchInfo { type cyclic; neighbourPatch cyc2; } constructFrom patches; patches ( a ); } );\n", + ) + .unwrap(); + s.execute("case.open", &json!({ "path": dir.to_str().unwrap(), "discard": true })).unwrap(); + let before = std::fs::read_to_string(&hand).unwrap(); + let out = s.execute("workflow.dictionaries", &json!({"replace": true})).unwrap(); + assert!(out.message.contains("1 createPatchDict left as it is"), "{}", out.message); + assert!( + out.data["notes"].as_array().unwrap().iter().any(|n| n.as_str().unwrap().contains( + "system/air/createPatchDict holds what system/umcfWorkflow doesn't (patch cyc): left as it is" + )), + "{}", + out.data + ); + s.execute("case.save", &json!({})).unwrap(); + assert_eq!(std::fs::read_to_string(&hand).unwrap(), before); + let kept_said = said(&mut s); + assert!( + kept_said[0].contains( + "(patch cyc is made there, the description doesn't make it (from)): it holds what the description can't" + ), + "{kept_said:?}" + ); + let fresh = umcf_model::create_patch::dict( + &umcf_model::create_patch::targets(&s.case().unwrap().description().unwrap().0, Some("air")).unwrap()[0], + if version == 8 { umcf_core::OfVersion::V8 } else { umcf_core::OfVersion::V12 }, + ); + // The same patches, but more the description can't hold: said, though nothing differs. + std::fs::write(&hand, format!("{fresh}\nwriteCyclicMatch true;\n")).unwrap(); + s.execute("case.open", &json!({ "path": dir.to_str().unwrap(), "discard": true })).unwrap(); + let more = said(&mut s); + assert!( + more.len() == 1 && more[0].contains("makes the patches as the description of region air does, but holds what it can't (its writeCyclicMatch)"), + "{more:?}" + ); + std::fs::write(&hand, fresh).unwrap(); + s.execute("case.open", &json!({ "path": dir.to_str().unwrap(), "discard": true })).unwrap(); + assert_eq!(said(&mut s), Vec::::new()); + // Taken away: written over (umcfGui's own) with nothing to make. + s.execute("workflow.patch", &json!({"region": "air", "patch": "buildings", "from": null})).unwrap(); + assert!(said(&mut s)[0].starts_with("system/air/createPatchDict: written by umcfGui otherwise")); + let out = s.execute("workflow.dictionaries", &json!({})).unwrap(); + assert_eq!(out.data["written"], json!(["system/air/createPatchDict"]), "{}", out.data); + assert!(s.case().unwrap().dict("system/air/createPatchDict").unwrap().to_string().contains("patches\n(\n);")); + // A patch made of others in a region that runs no createPatch: refused, said. + s.execute( + "workflow.patch", + &json!({"region": "vegetation", "patch": "air_to_vegetation", "role": "canopy", "from": ["x"]}), + ) + .unwrap(); + let e = s.execute("workflow.dictionaries", &json!({})).unwrap_err().to_string(); + assert!(e.contains("patch air_to_vegetation of region vegetation is made by createPatch (from), but the region's mesh and steps don't run createPatch"), "{e}"); + assert!( + said(&mut s)[0] + .starts_with("system/umcfWorkflow: the createPatchDicts can't be written from the description") + ); + let e = s.execute("workflow.dictionaries", &json!({"region": "vegetation"})).unwrap_err().to_string(); + assert!(e.contains("run neither changeDictionary nor createPatch"), "{e}"); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/model/src/coupling.rs b/crates/model/src/coupling.rs index 693aa2a..3bbdd51 100644 --- a/crates/model/src/coupling.rs +++ b/crates/model/src/coupling.rs @@ -69,15 +69,7 @@ pub fn entries(d: &Description, region: &str, version: OfVersion) -> Result Result`) for `what`'s sake: +/// a plain OpenFOAM word, not `.` or `..`, no `:`, not ending with `.`, not a name Windows keeps +/// for a device. +pub(crate) fn directory(n: &str, what: &str) -> Result<(), String> { + if !crate::description_edit::plain_name(n) { + return Err(format!("region `{n}` isn't a plain OpenFOAM word: rename it to write the {what}")); + } + if n.contains(':') || n.ends_with('.') || crate::new_case::windows_device(n) { + return Err(format!( + "region `{n}` can't be a directory on every system (a `:`, a `.` at its end, or a Windows device's name): rename it to write the {what}" + )); + } + Ok(()) +} + /// The fluid region a vegetation region's canopy maps to: the one its other patches are /// coupled to, else the one `calcLAI` runs on, else the case's only fluid region. fn canopy_air(d: &Description, r: &RegionDesc) -> Result { diff --git a/crates/model/src/coupling_tests.rs b/crates/model/src/coupling_tests.rs index ea2b05b..a77ca31 100644 --- a/crates/model/src/coupling_tests.rs +++ b/crates/model/src/coupling_tests.rs @@ -16,7 +16,13 @@ fn region(name: &str, kind: RegionKind, patches: Vec) -> RegionDesc { } fn patch(name: &str, role: Option, partner: Option<(&str, &str)>) -> PatchDesc { - PatchDesc { name: name.into(), role, partner: partner.map(|(r, p)| (r.into(), p.into())) } + PatchDesc { + name: name.into(), + role, + partner: partner.map(|(r, p)| (r.into(), p.into())), + from: Vec::new(), + kind: None, + } } fn canyon() -> Description { diff --git a/crates/model/src/create_patch.rs b/crates/model/src/create_patch.rs new file mode 100644 index 0000000..40ecf20 --- /dev/null +++ b/crates/model/src/create_patch.rs @@ -0,0 +1,626 @@ +//! The `createPatchDict`s, generated from `system/umcfWorkflow`: the patches `createPatch` makes +//! of others (`constructFrom patches`), each typed by its role, as the reference cases make +//! them (docs/common-workflow.md, *What the known cases do*): blockMesh's own `defaultFaces` +//! made into the buildings' walls (`buildings`, a solid's `sides`), the vegetation region's +//! `region1_to_` patch, which `splitMeshRegions` leaves, made into its canopy +//! (`air_to_vegetation`). +//! +//! A patch's `from` in the description names the patches it is made of, as the dictionary has +//! them: a bare name is one patch, a quoted one a pattern (`"region1_to_.*"`), as `createPatch` +//! reads them (a quoted name without a regular expression's characters is the patch it names). Two +//! dictionaries are read: +//! +//! - `system//createPatchDict`, by `createPatch -region ` (a step after the +//! mesh, `steps ( createPatch … )`); +//! - `system/createPatchDict`, by `createPatch` on `constant/polyMesh` (a step of the mesh, +//! `mesh ( blockMesh … createPatch … )`): one for every region meshed so, which therefore make +//! the same patches. +//! +//! The type is the patch's own `type` where it has one (a plain wall without a partner, as the +//! canyons' `buildings`, has no role that gives it), else `wall` for a wall's role (`ground`, +//! `coupled`, `interior`, `bottom`), the canopy and every solid's patch (the reference cases' +//! solids' `sides`), else `patch`; `changeDictionary` makes a coupled one and the canopy mapped +//! after. OpenFOAM-8 reads `pointSync`, OpenFOAM-12 doesn't: it is written +//! for OpenFOAM-8 only. + +use std::collections::{HashMap, HashSet}; +use std::fmt::Write as _; + +use umcf_core::OfVersion; +use umcf_foam_dict::{Dict, Item, Node, unquote}; + +use crate::RegionKind; +use crate::description::{Description, RegionDesc, Role}; +use crate::workflow::{MeshBuild, RegionStep, RootStep}; + +/// The `createPatchDict` of `createPatch` on `constant/polyMesh`. +pub const ROOT_PATH: &str = "system/createPatchDict"; + +/// A patch `createPatch` makes: its name, type and the patches it is made of. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Made { + pub patch: String, + pub kind: String, + /// As the description has them: a name that isn't a plain word is a pattern. + pub from: Vec, +} + +/// One `createPatchDict` the description's steps read: where, the regions whose `createPatch` +/// reads it, and the patches it makes. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Target { + pub path: String, + pub regions: Vec, + pub made: Vec, +} + +/// Where `region`'s own `createPatchDict` is (the same in OpenFOAM-8 and -12). +pub fn dict_path(region: &str) -> String { + format!("system/{region}/createPatchDict") +} + +/// Whether `region`'s steps after the mesh run `createPatch -region`. +pub fn runs(r: &RegionDesc) -> bool { + r.steps.iter().any(|s| matches!(s, RegionStep::CreatePatch)) +} + +/// Whether `region`'s mesh runs `createPatch` on `constant/polyMesh`. +pub fn runs_root(r: &RegionDesc) -> bool { + matches!(&r.mesh, Some(MeshBuild::Root(steps)) if steps.contains(&RootStep::CreatePatch)) +} + +/// The type `createPatch` makes a patch of `role` in a region of `kind` (without a `type` of its +/// own): `wall` for a wall's role, the canopy and every solid's patch, else `patch`. +pub fn role_type(kind: RegionKind, role: Role) -> &'static str { + match (kind, role) { + (RegionKind::Solid, _) | (_, Role::Ground | Role::Coupled | Role::Interior | Role::Bottom | Role::Canopy) => { + "wall" + } + _ => "patch", + } +} + +/// The patches `createPatch` makes in region `r`, from its patches' `from`; an error says why +/// they can't be written (neither a role nor a type, a name that isn't a plain OpenFOAM word). +fn made(r: &RegionDesc) -> Result, String> { + let mut out = Vec::new(); + for p in r.patches.iter().filter(|p| !p.from.is_empty()) { + if !crate::description_edit::plain_name(&p.name) { + return Err(format!( + "patch `{}` of region {} isn't a plain OpenFOAM word: rename it to write the createPatchDict", + p.name, r.name + )); + } + let Some(kind) = p.kind.clone().or_else(|| p.role.map(|role| role_type(r.kind, role).to_string())) else { + return Err(format!( + "patch {} of region {} is made by createPatch, but has neither a role nor a type, which gives its type: give it one", + p.name, r.name + )); + }; + out.push(Made { patch: p.name.clone(), kind, from: p.from.clone() }); + } + Ok(out) +} + +/// Every `createPatchDict` the description's steps read, with the patches each makes; with +/// `only`, those region `only`'s mesh and steps read (and the regions sharing +/// `system/createPatchDict` with it). An error says why one can't be written (also: a region +/// whose mesh and steps both run `createPatch` with patches to make, so which makes them isn't +/// told; regions meshed in `constant/polyMesh` whose patches made by `createPatch` differ, as +/// they read the same dictionary). +pub fn targets(d: &Description, only: Option<&str>) -> Result, String> { + let shared = only.and_then(|n| d.region(n)).is_some_and(runs_root); + let mut out = Vec::new(); + let mut root: Option = None; + for r in &d.regions { + let (own, at_root) = (runs(r), runs_root(r)); + if only.is_some_and(|n| n != r.name && !(shared && at_root)) { + continue; + } + if !own && !at_root { + if let Some(p) = r.patches.iter().find(|p| !p.from.is_empty()) { + return Err(format!( + "patch {} of region {} is made by createPatch (from), but the region's mesh and steps don't run createPatch", + p.name, r.name + )); + } + continue; + } + let made = made(r)?; + if own && at_root && !made.is_empty() { + return Err(format!( + "region {} runs createPatch both in its mesh (system/createPatchDict) and after it (system/{}/createPatchDict): which makes its patches isn't told: take one out", + r.name, r.name + )); + } + if own && only.is_none_or(|n| n == r.name) { + crate::coupling::directory(&r.name, "createPatchDict")?; + out.push(Target { path: dict_path(&r.name), regions: vec![r.name.clone()], made: made.clone() }); + } + if at_root { + match &mut root { + None => root = Some(Target { path: ROOT_PATH.to_string(), regions: vec![r.name.clone()], made }), + Some(t) => { + // As createPatch takes them: by patch, the sources their union. + let key = |m: &[Made]| { + let mut v: Vec<(String, String, Vec)> = + m.iter().map(|x| (x.patch.clone(), x.kind.clone(), source_set(&x.from))).collect(); + v.sort(); + v + }; + if key(&t.made) != key(&made) { + return Err(format!( + "regions {} and {} are meshed in constant/polyMesh with createPatch, which reads system/createPatchDict for both: the patches they make (from) must be the same", + t.regions[0], r.name + )); + } + t.regions.push(r.name.clone()); + } + } + } + } + out.extend(root); + Ok(out) +} + +/// The `createPatchDict` of `t` for `version`, generated ([`crate::blocks::stamped`]). +pub fn dict(t: &Target, version: OfVersion) -> String { + let location = t.path.rsplit_once('/').map_or("system", |(dir, _)| dir); + let mut s = format!( + "FoamFile\n{{\n version 2.0;\n format ascii;\n class dictionary;\n location \"{location}\";\n object createPatchDict;\n}}\n\n" + ); + if version == OfVersion::V8 { + s.push_str("pointSync false;\n\n"); + } + s.push_str("patches\n(\n"); + for m in &t.made { + let _ = write!( + s, + " {{\n name {};\n patchInfo\n {{\n type {};\n }}\n constructFrom patches;\n patches ( {} );\n }}\n", + m.patch, + m.kind, + m.from.join(" ") + ); + } + s.push_str(");\n\n// ************************************************************************* //\n"); + let whose = if t.regions.len() == 1 { "region" } else { "regions" }; + crate::blocks::stamped( + &format!( + "The patches createPatch makes of others in {whose} {} in system/umcfWorkflow (from), by role (docs/common-workflow.md).", + t.regions.join(", ") + ), + &s, + ) +} + +/// One item of a `createPatchDict`'s `patches`, as far as it is plain. +struct There { + name: Option, + construct: Option, + from: Option>, + kind: Option, + /// Keys of its `patchInfo` besides `type` (a cyclic's `neighbourPatch`, `inGroups`, …). + info: Vec, + /// Its `patchInfo` is there but isn't a dictionary. + info_odd: bool, + /// Its keys besides `name`, `patchInfo`, `constructFrom`, `patches` and `set`. + other: Vec, + /// No directive or macro in it: all it holds is seen. + told: bool, + /// A key given twice in it or its `patchInfo`, which OpenFOAM merges. + twice: bool, +} + +/// A name as a message shows it: at most 64 characters, then `…`. +pub(crate) fn cut(s: &str) -> String { + match s.char_indices().nth(64) { + Some((at, _)) => format!("{}…", s.get(..at).unwrap_or_default()), + None => s.to_string(), + } +} + +/// At most a few of `items`, each cut, then how many more: what a hostile file can't make long. +fn few(items: &[String]) -> String { + const FEW: usize = 5; + let shown: Vec = items.iter().take(FEW).map(|s| cut(s)).collect(); + match items.len().saturating_sub(FEW) { + 0 => shown.join(" "), + more => format!("{} … and {more} more", shown.join(" ")), + } +} + +/// What a macro or directive gives: not compared. +fn untold(t: &str) -> bool { + t.starts_with(['$', '#']) +} + +/// Whether `values` hold what a macro or directive gives (`$x`, `#calc`), at any depth. +fn holds_untold(values: &[Node]) -> bool { + let mut stack: Vec<&Node> = values.iter().collect(); + while let Some(n) = stack.pop() { + match n { + Node::Atom(t) if untold(&t.text) => return true, + Node::Atom(_) => {} + Node::List { items, .. } | Node::Dims { items, .. } => stack.extend(items), + Node::Dict { body, .. } => { + if body.items.iter().any(|i| !matches!(i, Item::Entry(_))) { + return true; + } + stack.extend(body.entries().flat_map(|e| e.value.iter())); + } + } + } + false +} + +/// Whether an item of `patches`, or its `patchInfo`, gives a key twice (OpenFOAM merges them). +pub(crate) fn keys_twice(d: &Dict) -> bool { + let twice = |x: &Dict| { + let mut keys = HashSet::new(); + x.entries().any(|e| !keys.insert(e.key())) + }; + twice(d) || d.entries().filter(|e| e.key() == "patchInfo").filter_map(|e| e.dict()).any(twice) +} + +/// Whether an item of `patches` is whole: no macro or directive anywhere in it (as an item or a +/// value), and its `patchInfo`, where there is one, a dictionary. +pub(crate) fn whole(d: &Dict) -> bool { + let info = d.get("patchInfo"); + !(d.items.iter().any(|i| !matches!(i, Item::Entry(_))) + || d.entries().any(|e| holds_untold(&e.value)) + || info.is_some_and(|e| e.dict().is_none())) +} + +/// The items of `root`'s `patches`, or what is wrong with the list (`None`: not told, a macro +/// or directive gives it). +fn items(root: &Dict) -> Result>, String> { + let directives = root.items.iter().any(|i| matches!(i, Item::Directive { .. } | Item::Macro { .. })); + let Some(list) = root.get("patches") else { + return if directives { + Ok(None) + } else { + Err("it has no patches list, without which createPatch stops".into()) + }; + }; + let items = match list.value.as_slice() { + [Node::List { items, .. }] => items, + [Node::Atom(t)] if untold(&t.text) => return Ok(None), + _ => return Err("its patches isn't a list of dictionaries".into()), + }; + let one = |d: &Dict, k: &str| match d.get(k).map(|e| e.value.as_slice()) { + Some([Node::Atom(t)]) => Some(unquote(&t.text).to_string()), + _ => None, + }; + let mut out = Vec::new(); + for n in items { + let Node::Dict { body: d, .. } = n else { + if let Node::Atom(t) = n + && untold(&t.text) + { + out.push(There { + name: None, + construct: None, + from: None, + kind: None, + info: Vec::new(), + info_odd: false, + other: Vec::new(), + told: false, + twice: false, + }); + continue; + } + return Err("its patches isn't a list of dictionaries".into()); + }; + let info_entry = d.get("patchInfo"); + let info_dict = info_entry.and_then(|e| e.dict()); + // Not a dictionary, nor what a macro gives (which is said as such). + let info_odd = info_entry.is_some_and(|e| e.dict().is_none() && !holds_untold(&e.value)); + let other: Vec = d + .entries() + .map(|e| e.key().to_string()) + .filter(|k| !matches!(k.as_str(), "name" | "patchInfo" | "constructFrom" | "patches" | "set")) + .collect(); + let told = whole(d); + let from = match d.get("patches").map(|e| e.value.as_slice()) { + Some([Node::List { items, .. }]) => items + .iter() + .map(|n| match n { + Node::Atom(t) => Some(t.text.clone()), + _ => None, + }) + .collect(), + _ => None, + }; + let kind = info_dict.and_then(|p| one(p, "type")); + let info = info_dict + .map(|p| p.entries().map(|e| e.key().to_string()).filter(|k| k != "type").collect()) + .unwrap_or_default(); + let twice = keys_twice(d); + out.push(There { + name: one(d, "name"), + construct: one(d, "constructFrom"), + from, + kind, + info, + info_odd, + other, + told, + twice, + }); + } + Ok(Some(out)) +} + +/// Whether OpenFOAM takes the quoted `inner` for a regular expression (`wordRe::compile` with +/// `DETECT`): one of `. * + ? ( ) | [ ]` (`regExp::meta`), or a character a word can't hold. +fn pattern(inner: &str) -> bool { + inner.chars().any(|c| { + matches!(c, '.' | '*' | '+' | '?' | '(' | ')' | '|' | '[' | ']' | '\'' | '/' | ';' | '{' | '}' | '$') + || c.is_whitespace() + }) +} + +/// How a source compares: a quoted one OpenFOAM doesn't take for a pattern is the name it holds, +/// as `createPatch` matches it; else as written. +pub(crate) fn normal(t: &str) -> String { + match t.strip_prefix('"').and_then(|r| r.strip_suffix('"')) { + Some(inner) if t.len() >= 2 && !pattern(inner) => inner.to_string(), + _ => t.to_string(), + } +} + +/// Sources as `createPatch` takes them: their union, in no order. +fn source_set(from: &[String]) -> Vec { + let mut v: Vec = from.iter().map(|f| normal(f)).collect(); + v.sort(); + v.dedup(); + v +} + +/// How a `createPatchDict` (`root`, the file's top level) differs from the patches `made`, for +/// `version`: a patch not made there, made of a set or of other patches (in any order: their +/// union), of what isn't a list of names, of another type, one made there the description +/// doesn't make, and the `patches` list or OpenFOAM-8's `pointSync` missing, which +/// `createPatch` stops without. A name or type quoted or not is the same, and so is a source +/// quoted that OpenFOAM doesn't take for a pattern; what a macro or directive gives isn't +/// compared (an item holding one is compared by its name only); a `patches` list that isn't one +/// of dictionaries is said so. +pub fn differences(root: &Dict, made: &[Made], version: OfVersion) -> Vec { + let mut out = Vec::new(); + let directives = root.items.iter().any(|i| matches!(i, Item::Directive { .. } | Item::Macro { .. })); + if version == OfVersion::V8 && root.get("pointSync").is_none() && !directives { + out.push("it has no pointSync, without which OpenFOAM-8's createPatch stops".to_string()); + } + let there = match items(root) { + Ok(Some(t)) => t, + Ok(None) => return out, + Err(e) => { + out.push(e); + return out; + } + }; + // By name: a name given twice is one patch of both items' sources (createPatch moves both + // items' faces into the first), compared whole only when both are. + let mut by_name: HashMap<&str, There> = HashMap::with_capacity(there.len()); + for t in &there { + let Some(n) = t.name.as_deref() else { continue }; + match by_name.get_mut(n) { + None => { + by_name.insert( + n, + There { + name: t.name.clone(), + construct: t.construct.clone(), + from: t.from.clone(), + kind: t.kind.clone(), + info: Vec::new(), + info_odd: false, + other: Vec::new(), + told: t.told, + twice: false, + }, + ); + } + Some(first) => { + first.told &= t.told && t.construct == first.construct; + match (&mut first.from, &t.from) { + (Some(a), Some(b)) => a.extend(b.iter().cloned()), + (a, _) => *a = None, + } + } + } + } + let unnamed = there.iter().any(|t| t.name.as_deref().is_none_or(untold)); + let names: HashSet<&str> = made.iter().map(|m| m.patch.as_str()).collect(); + for m in made { + let Some(t) = by_name.get(m.patch.as_str()) else { + if unnamed { + continue; + } + out.push(format!("patch {} isn't made there, the description makes it of ( {} )", m.patch, shown(&m.from))); + continue; + }; + if !t.told { + continue; + } + match t.construct.as_deref() { + Some("patches") => {} + Some(c) => { + out.push(format!( + "patch {} is made of a {} there, the description makes it of ( {} )", + m.patch, + cut(c), + shown(&m.from) + )); + continue; + } + None => { + out.push(format!("patch {} has no constructFrom there, which createPatch stops without", m.patch)); + continue; + } + } + match &t.from { + Some(from) if source_set(from) != source_set(&m.from) => out.push(format!( + "patch {} is made of ( {} ) there, the description makes it of ( {} )", + m.patch, + few(from), + shown(&m.from) + )), + Some(_) => {} + None => out.push(format!( + "patch {} is made of what isn't a list of names there, the description makes it of ( {} )", + m.patch, + shown(&m.from) + )), + } + if let Some(k) = &t.kind + && *k != m.kind + { + out.push(format!("patch {}: type is {} there, the description makes it {}", m.patch, cut(k), m.kind)); + } + } + let mut said: HashSet<&str> = HashSet::new(); + for t in &there { + if let Some(n) = &t.name + && !untold(n) + && !names.contains(n.as_str()) + && said.insert(n.as_str()) + { + out.push(format!("patch {} is made there, the description doesn't make it (from)", cut(n))); + } + } + out +} + +/// What a `createPatchDict` (`root`) holds that the description can't, so writing it over from +/// `made` for `version` would drop it: a patch made there the description doesn't make, an item +/// that can't be read whole (no plain name, a macro or directive in it), a patch given twice, one +/// made of a face set or of sources the description can't hold, a key given twice in an item or +/// its `patchInfo` (OpenFOAM merges them), the entries of a `patchInfo` besides its `type` and +/// other keys of an item, a `patches` list that can't be read, a top-level entry +/// besides `patches` (OpenFOAM-8's `pointSync` unless it is off, as written). Empty: the +/// description holds all of it. +pub fn kept(root: &Dict, made: &[Made], version: OfVersion) -> Vec { + let mut out = Vec::new(); + if root.items.iter().any(|i| matches!(i, Item::Directive { .. } | Item::Macro { .. })) { + out.push("a directive or macro at its top".to_string()); + } + if root.items.iter().any(|i| matches!(i, Item::Value(_))) { + out.push("a value without a key at its top".to_string()); + } + if root.entries().filter(|e| e.key() == "patches").count() > 1 { + out.push("its patches, given twice".to_string()); + } + for e in root.entries() { + match e.key() { + "FoamFile" | "patches" => {} + "pointSync" if version == OfVersion::V12 => {} + "pointSync" => { + let off = match e.value.as_slice() { + [Node::Atom(t)] => umcf_foam_dict::switch(&t.text) == Some(false), + _ => false, + }; + if !off { + out.push("its pointSync, which isn't off".to_string()); + } + } + k => out.push(format!("its {}", cut(k))), + } + } + let there = match items(root) { + Ok(Some(t)) => t, + Ok(None) => { + out.push("its patches given by a macro or directive".to_string()); + return out; + } + Err(_) => { + out.push("its patches list, which can't be read whole".to_string()); + return out; + } + }; + let names: HashSet<&str> = made.iter().map(|m| m.patch.as_str()).collect(); + let mut seen: HashSet<&str> = HashSet::with_capacity(there.len()); + for t in &there { + let Some(n) = t.name.as_deref().filter(|n| !untold(n)) else { + out.push("a patch without a plain name".to_string()); + continue; + }; + let sources_held = t.from.as_ref().is_some_and(|f| f.iter().all(|s| source_ok(s))); + let shown = cut(n); + let first = seen.insert(n); + if !names.contains(n) { + if first { + out.push(format!("patch {shown}")); + } + } else if !first { + out.push(format!("patch {shown}, given twice (one item of both, by hand)")); + } else if t.info_odd { + out.push(format!("patch {shown}'s patchInfo, which isn't a dictionary")); + } else if !t.told { + out.push(format!("patch {shown}'s macro or directive")); + } else if t.construct.as_deref() != Some("patches") { + out.push(format!("patch {shown}, made of a {}", cut(t.construct.as_deref().unwrap_or("what isn't said")))); + } else if !sources_held { + out.push(format!("patch {shown}'s sources")); + } else if t.twice { + out.push(format!("patch {shown}'s keys given twice (OpenFOAM merges them)")); + } else if !t.info.is_empty() { + out.push(format!("patch {shown}'s patchInfo {}", few(&t.info))); + } else if !t.other.is_empty() { + out.push(format!("patch {shown}'s {}", few(&t.other))); + } + // A cap on what a hostile file makes long. + if out.len() > 2 * MAX_KEPT { + out.truncate(MAX_KEPT); + out.push("and more".to_string()); + return out; + } + } + out +} + +/// What [`kept`] (or [`differences`]) lists, as a message gives it: the first, and how many more. +pub fn summary(items: &[String]) -> String { + match items { + [] => String::new(), + [one] => one.clone(), + [first, .., last] if last == "and more" => format!("{first}, and more"), + [first, rest @ ..] => format!("{first}, and {} more", rest.len()), + } +} + +/// The most of what [`kept`] lists, about. +const MAX_KEPT: usize = 20; + +/// A source given by name (`workflow.patch`) as the dictionaries write it: as given when quoted, +/// a plain word bare, anything else quoted (a pattern). +pub fn source_token(s: &str) -> String { + if s.starts_with('"') || crate::description_edit::plain_name(s) { s.to_string() } else { format!("\"{s}\"") } +} + +/// Whether `t` is a source the description holds: a plain word, or a quoted pattern without +/// quotes, backslashes, white space or control characters inside (which the dictionaries would +/// have to escape, and `createPatch` reads otherwise). +pub fn source_ok(t: &str) -> bool { + if crate::description_edit::plain_name(t) { + return true; + } + match t.strip_prefix('"').and_then(|r| r.strip_suffix('"')) { + Some(inner) => { + t.len() >= 2 + && !inner.is_empty() + && inner.len() <= 255 + && !inner.chars().any(|c| c.is_control() || c.is_whitespace() || matches!(c, '"' | '\\')) + } + None => false, + } +} + +fn shown(from: &[String]) -> String { + few(from) +} + +#[cfg(test)] +#[path = "create_patch_tests.rs"] +mod tests; diff --git a/crates/model/src/create_patch_tests.rs b/crates/model/src/create_patch_tests.rs new file mode 100644 index 0000000..76c3f71 --- /dev/null +++ b/crates/model/src/create_patch_tests.rs @@ -0,0 +1,445 @@ +use super::*; +use crate::description::PatchDesc; + +fn patch(name: &str, role: Option, from: &[&str]) -> PatchDesc { + PatchDesc { name: name.into(), role, partner: None, from: from.iter().map(|s| s.to_string()).collect(), kind: None } +} + +fn region( + name: &str, + kind: RegionKind, + mesh: Option, + steps: Vec, + patches: Vec, +) -> RegionDesc { + RegionDesc { + name: name.into(), + kind, + mesh, + steps, + patches, + materials: Vec::new(), + blocks: None, + mesh_box: None, + snappy: None, + } +} + +fn root_mesh() -> Option { + Some(MeshBuild::Root(vec![ + RootStep::BlockMesh("system/blockMeshDict".into()), + RootStep::CreatePatch, + RootStep::SnappyHexMesh("system/snappyHexMeshDict".into()), + ])) +} + +/// The 3×3 reference cases: the air and the vegetation meshed in constant/polyMesh with a +/// createPatch making the buildings' walls of blockMesh's defaultFaces, each solid its sides. +fn three() -> Description { + let buildings = |partner: bool| PatchDesc { + partner: partner.then(|| ("air".to_string(), "buildings".to_string())), + ..patch("buildings", Some(Role::Coupled), &["defaultFaces"]) + }; + Description { + regions: vec![ + region( + "air", + RegionKind::Fluid, + root_mesh(), + vec![RegionStep::ChangeDictionary], + vec![patch("west", Some(Role::Inlet), &[]), buildings(false)], + ), + region("vegetation", RegionKind::Vegetation, root_mesh(), vec![], vec![buildings(true)]), + region( + "street", + RegionKind::Solid, + Some(MeshBuild::Block), + vec![RegionStep::CreatePatch, RegionStep::ChangeDictionary], + vec![patch("street", Some(Role::Coupled), &[]), patch("sides", Some(Role::Side), &["defaultFaces"])], + ), + ], + ..Default::default() + } +} + +fn root(text: &str) -> umcf_foam_dict::Dict { + umcf_foam_dict::Document::parse(text).unwrap().root +} + +#[test] +fn the_patches_made_are_gathered_per_dictionary() { + let t = targets(&three(), None).unwrap(); + assert_eq!( + t, + [ + Target { + path: "system/street/createPatchDict".into(), + regions: vec!["street".into()], + made: vec![Made { patch: "sides".into(), kind: "wall".into(), from: vec!["defaultFaces".into()] }], + }, + Target { + path: ROOT_PATH.into(), + regions: vec!["air".into(), "vegetation".into()], + made: vec![Made { patch: "buildings".into(), kind: "wall".into(), from: vec!["defaultFaces".into()] }], + }, + ] + ); + // A region whose steps run createPatch with nothing to make: an empty list, as createPatch + // takes it. + let mut d = three(); + d.regions[2].patches[1].from.clear(); + let t = targets(&d, None).unwrap(); + assert_eq!(t[0].made, []); + assert!(dict(&t[0], OfVersion::V12).contains("patches\n(\n);")); + // Types by role: an open side's patch, a wall's and the canopy wall, a solid's always wall. + let d = Description { + regions: vec![ + region( + "vegetation", + RegionKind::Vegetation, + None, + vec![RegionStep::CreatePatch], + vec![ + patch("air_to_vegetation", Some(Role::Canopy), &["\"region1_to_.*\""]), + patch("sky", Some(Role::Sky), &["top"]), + patch("floor", Some(Role::Ground), &["bottom"]), + ], + ), + region( + "roofs", + RegionKind::Solid, + None, + vec![RegionStep::CreatePatch], + vec![patch("top", Some(Role::Top), &["a", "b"])], + ), + ], + ..Default::default() + }; + let t = targets(&d, None).unwrap(); + let kinds: Vec> = t.iter().map(|t| t.made.iter().map(|m| m.kind.as_str()).collect()).collect(); + assert_eq!(kinds, [vec!["wall", "patch", "wall"], vec!["wall"]]); +} + +#[test] +fn what_cant_be_written_is_refused() { + let refused = |f: &dyn Fn(&mut Description)| { + let mut d = three(); + f(&mut d); + targets(&d, None).unwrap_err() + }; + let e = refused(&|d| d.regions[2].patches[1].role = None); + assert!( + e.contains("patch sides of region street is made by createPatch, but has neither a role nor a type"), + "{e}" + ); + // A type of its own, with a role or without, is the type made. + for role in [None, Some(Role::Side)] { + let mut d = three(); + d.regions[2].patches[1].role = role; + d.regions[2].patches[1].kind = Some("symmetryPlane".into()); + assert_eq!(targets(&d, None).unwrap()[0].made[0].kind, "symmetryPlane"); + } + let e = refused(&|d| d.regions[2].steps.clear()); + assert!(e.contains("the region's mesh and steps don't run createPatch"), "{e}"); + let e = refused(&|d| d.regions[0].steps.push(RegionStep::CreatePatch)); + assert!(e.contains("region air runs createPatch both in its mesh"), "{e}"); + // The two regions meshed in constant/polyMesh read one dictionary: the same patches. + let e = refused(&|d| d.regions[1].patches[0].from = vec!["other".into()]); + assert!(e.contains("regions air and vegetation are meshed in constant/polyMesh with createPatch"), "{e}"); + let e = refused(&|d| d.regions[1].patches.clear()); + assert!(e.contains("the patches they make (from) must be the same"), "{e}"); + // The same sources in another order are the same, as createPatch takes their union. + let mut d = three(); + d.regions[0].patches[1].from = vec!["a".into(), "b".into()]; + d.regions[1].patches[0].from = vec!["b".into(), "a".into(), "a".into()]; + assert!(targets(&d, None).is_ok()); + let e = refused(&|d| d.regions[2].patches[1].name = "two words".into()); + assert!(e.contains("patch `two words` of region street isn't a plain OpenFOAM word"), "{e}"); + let e = refused(&|d| d.regions[2].name = "con".into()); + assert!(e.contains("region `con` can't be a directory on every system"), "{e}"); + // The same patches in another order are the same. + let mut d = three(); + d.regions[0].patches.push(patch("roofs", Some(Role::Coupled), &["x"])); + d.regions[1].patches.insert(0, patch("roofs", Some(Role::Coupled), &["x"])); + assert!(targets(&d, None).is_ok()); +} + +#[test] +fn the_dictionary_is_written_for_each_version() { + let t = targets(&three(), None).unwrap(); + let v12 = dict(&t[1], OfVersion::V12); + let v8 = dict(&t[1], OfVersion::V8); + assert!(crate::blocks::untouched(&v12) && crate::blocks::untouched(&v8)); + // OpenFOAM-8 stops without pointSync; OpenFOAM-12 doesn't read it. + assert!(!v12.contains("pointSync") && v8.contains("pointSync false;")); + assert!(v12.contains("location \"system\";") && v12.contains("regions air, vegetation")); + assert!(dict(&t[0], OfVersion::V12).contains("location \"system/street\";")); + for (text, v) in [(&v12, OfVersion::V12), (&v8, OfVersion::V8)] { + assert_eq!(differences(&root(text), &t[1].made, v), Vec::::new()); + } + assert!(v12.contains( + " name buildings;\n patchInfo\n {\n type wall;\n }\n constructFrom patches;\n patches ( defaultFaces );\n" + )); + // A pattern is written quoted, as createPatch reads one. + let mut d = three(); + d.regions[2].patches[1].from = vec!["\"region1_to_.*\"".into(), "air.roof".into()]; + let t = targets(&d, None).unwrap(); + assert!(dict(&t[0], OfVersion::V12).contains("patches ( \"region1_to_.*\" air.roof );")); +} + +#[test] +fn the_cases_own_is_compared_by_what_it_makes() { + let made = targets(&three(), None).unwrap().remove(1).made; + let diff = |text: &str, v| differences(&root(text), &made, v); + // As the reference cases have it (their `set f0;` unread, pointSync given in both versions). + let own = "pointSync false; patches ( { name buildings; patchInfo { type wall; } constructFrom patches; patches (defaultFaces); set f0; } );"; + assert_eq!(diff(own, OfVersion::V12), Vec::::new()); + assert_eq!(diff(own, OfVersion::V8), Vec::::new()); + assert_eq!( + diff(&own.replace("pointSync false; ", ""), OfVersion::V8), + ["it has no pointSync, without which OpenFOAM-8's createPatch stops"] + ); + // A quoted plain name is the same patch. + assert_eq!(diff(&own.replace("(defaultFaces)", "(\"defaultFaces\")"), OfVersion::V12), Vec::::new()); + assert_eq!( + diff(&own.replace("(defaultFaces)", "(defaultFaces other)"), OfVersion::V12), + ["patch buildings is made of ( defaultFaces other ) there, the description makes it of ( defaultFaces )"] + ); + assert_eq!( + diff(&own.replace("type wall", "type patch"), OfVersion::V12), + ["patch buildings: type is patch there, the description makes it wall"] + ); + assert_eq!( + diff(&own.replace("constructFrom patches", "constructFrom set"), OfVersion::V12), + ["patch buildings is made of a set there, the description makes it of ( defaultFaces )"] + ); + assert_eq!( + diff(&own.replace("constructFrom patches; ", ""), OfVersion::V12), + ["patch buildings has no constructFrom there, which createPatch stops without"] + ); + assert_eq!( + diff(&own.replace("name buildings", "name walls"), OfVersion::V12), + [ + "patch buildings isn't made there, the description makes it of ( defaultFaces )", + "patch walls is made there, the description doesn't make it (from)" + ] + ); + assert_eq!(diff("pointSync false;", OfVersion::V12), ["it has no patches list, without which createPatch stops"]); + assert_eq!(diff("patches ( defaultFaces );", OfVersion::V12), ["its patches isn't a list of dictionaries"]); + assert_eq!(diff("patches 3;", OfVersion::V12), ["its patches isn't a list of dictionaries"]); + // What a macro or directive gives isn't compared. + assert_eq!(diff("patches $list;", OfVersion::V12), Vec::::new()); + assert_eq!(diff(&own.replace("(defaultFaces)", "($faces)"), OfVersion::V12), Vec::::new()); + assert_eq!(diff(&own.replace("type wall", "type $t"), OfVersion::V12), Vec::::new()); + let included = "patches ( { #include \"made\" } );"; + assert_eq!(diff(included, OfVersion::V12), Vec::::new()); + // Nothing to make: an empty list is fine, none isn't. + assert_eq!(differences(&root("pointSync false; patches ( );"), &[], OfVersion::V8), Vec::::new()); + assert_eq!( + differences(&root("pointSync false;"), &[], OfVersion::V8), + ["it has no patches list, without which createPatch stops"] + ); +} + +#[test] +fn a_source_keeps_whether_it_is_a_pattern() { + let made = targets(&three(), None).unwrap().remove(1).made; + let own = "pointSync false; patches ( { name buildings; patchInfo { type wall; } constructFrom patches; patches (defaultFaces); } );"; + let diff = |text: &str| differences(&root(text), &made, OfVersion::V12); + // Quoted, a name with a regular expression's character is a pattern, not the name. + let mut regex = made.clone(); + regex[0].from = vec!["region.1".into()]; + let quoted = own.replace("(defaultFaces)", "(\"region.1\")"); + assert_eq!( + differences(&root("ed), ®ex, OfVersion::V12), + ["patch buildings is made of ( \"region.1\" ) there, the description makes it of ( region.1 )"] + ); + regex[0].from = vec!["\"region.1\"".into()]; + assert_eq!(differences(&root("ed), ®ex, OfVersion::V12), Vec::::new()); + // A quoted name or type is the same. + assert_eq!( + diff(&own.replace("name buildings", "name \"buildings\"").replace("type wall", "type \"wall\"")), + Vec::::new() + ); + // What the description holds: a bare word, or a quoted pattern without what would need escaping. + for ok in ["defaultFaces", "air.roof", "\"region1_to_.*\"", "\"a|b\""] { + assert!(source_ok(ok), "{ok}"); + } + for bad in ["", "\"\"", "\"a\\.b\"", "\"a b\"", "a*", "\"a\"b\"", "\"open"] { + assert!(!source_ok(bad), "{bad}"); + } + assert_eq!(source_token("region1_to_.*"), "\"region1_to_.*\""); + assert_eq!(source_token("defaultFaces"), "defaultFaces"); + assert_eq!(source_token("\"region.1\""), "\"region.1\""); +} + +#[test] +fn what_a_macro_or_directive_gives_isnt_compared() { + let made = targets(&three(), None).unwrap().remove(1).made; + let diff = |text: &str| differences(&root(text), &made, OfVersion::V8); + // At the top: pointSync and the list may come from it. + assert_eq!(diff("#include \"common\""), Vec::::new()); + assert_eq!( + diff( + "$common; patches ( { name buildings; patchInfo { type wall; } constructFrom patches; patches (defaultFaces); } );" + ), + Vec::::new() + ); + // In an item: compared by its name only. + assert_eq!(diff("pointSync false; patches ( { name buildings; #include \"rest\" } );"), Vec::::new()); + assert_eq!(diff("pointSync false; patches ( { name buildings; $rest; } );"), Vec::::new()); +} + +#[test] +fn what_the_description_cant_hold_is_kept() { + let made = targets(&three(), None).unwrap().remove(1).made; + let kept = |text: &str| kept(&root(text), &made, OfVersion::V8); + let own = "pointSync false; patches ( { name buildings; patchInfo { type wall; } constructFrom patches; patches (defaultFaces); } );"; + assert_eq!(kept(own), Vec::::new()); + // Made of a set: the description can't hold it. The reference cases' `set` beside patches, + // which createPatch doesn't read, is fine. + assert_eq!( + kept(&own.replace("constructFrom patches", "constructFrom set; set f0")), + ["patch buildings, made of a set"] + ); + assert_eq!(kept(&own.replace("(defaultFaces);", "(defaultFaces); set f0;")), Vec::::new()); + assert_eq!(kept(&own.replace("constructFrom patches; ", "")), ["patch buildings, made of a what isn't said"]); + assert_eq!(kept(&own.replace("(defaultFaces)", "(\"a b\")")), ["patch buildings's sources"]); + assert_eq!(kept(&own.replace("(defaultFaces);", "(defaultFaces); extra 1;")), ["patch buildings's extra"]); + assert_eq!( + kept(&own.replace("patchInfo { type wall; }", "patchInfo wall;")), + ["patch buildings's patchInfo, which isn't a dictionary"] + ); + // Given twice: one patch of both, which written once loses the shape. + let twice = own.replace( + "(defaultFaces); } );", + "(defaultFaces); } { name buildings; patchInfo { type wall; } constructFrom patches; patches (x); } );", + ); + assert_eq!(kept(&twice), ["patch buildings, given twice (one item of both, by hand)"]); + assert_eq!( + differences(&root(&twice), &made, OfVersion::V8), + ["patch buildings is made of ( defaultFaces x ) there, the description makes it of ( defaultFaces )"] + ); + let mut both = made.clone(); + both[0].from = vec!["x".into(), "defaultFaces".into()]; + assert_eq!(differences(&root(&twice), &both, OfVersion::V8), Vec::::new()); + // Other things at the top. + assert_eq!(kept(&format!("{own} 3")).len(), 1); + assert_eq!(kept(&format!("patches ( ); {own}")), ["its patches, given twice"]); + // Long lists are cut short. + let keys: String = (0..100).map(|i| format!("k{i} 1; ")).collect(); + let long = kept(&own.replace("type wall;", &format!("type wall; {keys}"))); + assert_eq!(long, ["patch buildings's patchInfo k0 k1 k2 k3 k4 … and 95 more"]); + let many: String = (0..1000).map(|i| format!("{{ name p{i}; constructFrom patches; patches (a); }} ")).collect(); + let many = kept(&format!("pointSync false; patches ( {many} );")); + assert_eq!(many.len(), 21); + assert_eq!(many.last().map(String::as_str), Some("and more")); + let more = own.replace( + "(defaultFaces); } );", + "(defaultFaces); } { name cyc; patchInfo { type cyclic; neighbourPatch cyc2; } constructFrom patches; patches (a); } );", + ); + assert_eq!(kept(&more), ["patch cyc"]); + assert_eq!( + kept(&own.replace("type wall;", "type wall; inGroups (walls);")), + ["patch buildings's patchInfo inGroups"] + ); + assert_eq!( + kept(&own.replace("name buildings;", "name buildings; $rest;")), + ["patch buildings's macro or directive"] + ); + assert_eq!(kept(&own.replace("name buildings;", "name $n;")), ["a patch without a plain name"]); + assert_eq!( + kept("#include \"made\""), + ["a directive or macro at its top", "its patches given by a macro or directive"] + ); + // A list that can't be read, a value from a macro, other entries at the top. + assert_eq!(kept("pointSync false; patches 1 ( { name cyc; } );"), ["its patches list, which can't be read whole"]); + assert_eq!(kept("pointSync false; patches ( cyc );"), ["its patches list, which can't be read whole"]); + assert_eq!( + kept(&own.replace("patchInfo { type wall; }", "patchInfo $wallInfo;")), + ["patch buildings's macro or directive"] + ); + assert_eq!(kept(&own.replace("type wall;", "type $t;")), ["patch buildings's macro or directive"]); + assert_eq!(kept(&own.replace("(defaultFaces)", "($faces)")), ["patch buildings's macro or directive"]); + assert_eq!(kept(&own.replace("pointSync false;", "pointSync true;")), ["its pointSync, which isn't off"]); + assert_eq!( + kept(&own.replace("pointSync false;", "pointSync off; writeCyclicMatch true;")), + ["its writeCyclicMatch"] + ); + // OpenFOAM-12 doesn't read pointSync: dropped, nothing is lost. + assert_eq!( + super::kept(&root(&own.replace("pointSync false;", "pointSync true;")), &made, OfVersion::V12), + Vec::::new() + ); +} + +#[test] +fn sources_are_a_union_and_quoted_names_follow_openfoam() { + let made = targets(&three(), None).unwrap().remove(1).made; + let mut two = made.clone(); + two[0].from = vec!["a".into(), "b".into()]; + let own = |from: &str| { + format!( + "patches ( {{ name buildings; patchInfo {{ type wall; }} constructFrom patches; patches ({from}); }} );" + ) + }; + let diff = |text: &str| differences(&root(text), &two, OfVersion::V12); + // createPatch takes their union: order and repeats don't matter. + assert_eq!(diff(&own("b a a")), Vec::::new()); + assert_eq!(diff(&own("a")), ["patch buildings is made of ( a ) there, the description makes it of ( a b )"]); + // Quoted: a name OpenFOAM doesn't take for a pattern is the name. + assert_eq!(diff(&own("\"a\" b")), Vec::::new()); + assert_eq!(diff(&own("\"a*\" b")).len(), 1); + assert_eq!( + diff("patches ( { name buildings; patchInfo { type wall; } constructFrom patches; patches a; } );"), + ["patch buildings is made of what isn't a list of names there, the description makes it of ( a b )"] + ); + // constructFrom quoted is the word. + assert_eq!(diff(&own("a b").replace("constructFrom patches", "constructFrom \"patches\"")), Vec::::new()); +} + +#[test] +fn one_region_is_written_without_the_others() { + let mut d = three(); + // The air and the vegetation share system/createPatchDict but make other patches. + d.regions[1].patches[0].from = vec!["other".into()]; + assert!(targets(&d, None).is_err()); + assert!(targets(&d, Some("air")).is_err()); + let t = targets(&d, Some("street")).unwrap(); + assert_eq!(t.len(), 1); + assert_eq!(t[0].path, "system/street/createPatchDict"); + // A region running createPatch both in and after its mesh, with nothing to make: both read. + let mut d = three(); + d.regions[0].steps.push(RegionStep::CreatePatch); + d.regions[0].patches[1].from.clear(); + d.regions[1].patches[0].from.clear(); + let paths: Vec = targets(&d, None).unwrap().into_iter().map(|t| t.path).collect(); + assert_eq!(paths, ["system/air/createPatchDict", "system/street/createPatchDict", ROOT_PATH]); +} + +#[test] +fn keys_given_twice_are_kept_and_summaries_count() { + let made = targets(&three(), None).unwrap().remove(1).made; + let own = "pointSync false; patches ( { name buildings; patchInfo { type wall; } constructFrom patches; patches (defaultFaces); } );"; + // OpenFOAM merges a sub-dictionary given twice: what the first holds would be lost. + let twice = own.replace("patchInfo { type wall; }", "patchInfo { inGroups (g); } patchInfo { type wall; }"); + assert_eq!( + kept(&root(&twice), &made, OfVersion::V8), + ["patch buildings's keys given twice (OpenFOAM merges them)"] + ); + let twice = own.replace("type wall;", "type wall; type wall;"); + assert_eq!( + kept(&root(&twice), &made, OfVersion::V8), + ["patch buildings's keys given twice (OpenFOAM merges them)"] + ); + // A patch the description doesn't make, given twice, is said once. + let other = own.replace("(defaultFaces); } );", "(defaultFaces); } { name x; constructFrom patches; patches (a); } { name x; constructFrom patches; patches (b); } );"); + assert_eq!( + differences(&root(&other), &made, OfVersion::V8), + ["patch x is made there, the description doesn't make it (from)"] + ); + assert_eq!(summary(&[]), ""); + assert_eq!(summary(&["a".into()]), "a"); + assert_eq!(summary(&["a".into(), "b".into(), "c".into()]), "a, and 2 more"); + assert_eq!(summary(&["a".into(), "b".into(), "and more".into()]), "a, and more"); +} diff --git a/crates/model/src/description.rs b/crates/model/src/description.rs index 0126823..76bae70 100644 --- a/crates/model/src/description.rs +++ b/crates/model/src/description.rs @@ -123,6 +123,13 @@ pub struct PatchDesc { pub role: Option, /// The region and patch it is coupled to. pub partner: Option<(String, String)>, + /// The patches `createPatch` makes it of (`constructFrom patches`), in its region's + /// `createPatchDict`; a name that isn't a plain word is a pattern. Empty: not made by + /// `createPatch`. + pub from: Vec, + /// Its type where the role doesn't give it (`type`), for `createPatch` to make it of: a + /// plain wall without a partner (the canyons' `buildings`), or a patch without a role. + pub kind: Option, } /// A solid's material: the cell zone of its name is built of it @@ -256,7 +263,7 @@ impl Description { if role.is_none() { notes.push(format!("region {name}, patch {}: no role could be told ({})", p.name, p.kind)); } - patches.push(PatchDesc { name: p.name.clone(), role, partner }); + patches.push(PatchDesc { name: p.name.clone(), role, partner, from: Vec::new(), kind: None }); } let mut materials = Vec::new(); if region.kind == RegionKind::Solid { @@ -311,10 +318,19 @@ impl Description { { for n in g.patch_names() { if !patches.iter().any(|p| p.name == n) { - patches.push(PatchDesc { name: n.to_string(), role: None, partner: None }); + patches.push(PatchDesc { + name: n.to_string(), + role: None, + partner: None, + from: Vec::new(), + kind: None, + }); } } } + if let Some(m) = mesh { + import_created(case, name, region.kind, m, &mut patches, &mut notes); + } regions.push(RegionDesc { name: name.to_string(), kind: region.kind, @@ -496,6 +512,12 @@ impl Description { if let Some((region, patch)) = &p.partner { let _ = write!(body, " partner ( {} {} );", word(region), word(patch)); } + if !p.from.is_empty() { + let _ = write!(body, " from ( {} );", p.from.join(" ")); + } + if let Some(t) = &p.kind { + let _ = write!(body, " type {};", word(t)); + } let _ = writeln!(s, " {:<15} {{{body} }}", word(&p.name)); } s.push_str(" }\n"); @@ -943,7 +965,7 @@ fn read_region( } match p.dict() { Some(b) => r.patches.push(read_patch(&pname, b, &pat, problem)), - None => problem(&pat, "is a dictionary: { role …; [partner ( region patch );] }".into()), + None => problem(&pat, "is a dictionary: { role …; [partner ( region patch );] [from ( patch … );] [type …;] }".into()), } } } @@ -1059,8 +1081,11 @@ fn read_split( Some(Split { of, zone, dict }) } +/// What a patch's `from` is, said when it isn't. +const FROM_IS: &str = "is ( patch … ): names, or quoted patterns without quotes, backslashes or spaces inside"; + fn read_patch(name: &str, body: &umcf_foam_dict::Dict, at: &str, problem: &mut impl FnMut(&str, String)) -> PatchDesc { - let mut p = PatchDesc { name: name.to_string(), role: None, partner: None }; + let mut p = PatchDesc { name: name.to_string(), role: None, partner: None, from: Vec::new(), kind: None }; let mut seen = HashSet::new(); for e in body.entries() { let here = format!("{at}/{}", e.key()); @@ -1082,9 +1107,38 @@ fn read_patch(name: &str, body: &umcf_foam_dict::Dict, at: &str, problem: &mut i }, _ => problem(&here, "is ( region patch )".into()), }, + "type" => match single(e) { + Some(t) if crate::description_edit::plain_name(&t) && !crate::blocks::needs_own_entries(&t) => { + p.kind = Some(t) + } + Some(t) if crate::description_edit::plain_name(&t) => problem( + &here, + format!( + "{t} needs entries of its own (neighbourPatch, …): give it with changeDictionary (role and partner)" + ), + ), + _ => problem(&here, "is a patch type (one plain word)".into()), + }, + "from" => match list(e) { + Some(items) if !items.is_empty() => { + let names: Option> = items + .iter() + .map(|n| atom(n).filter(|t| crate::create_patch::source_ok(t)).map(str::to_string)) + .collect(); + match names { + Some(names) => p.from = names, + None => problem(&here, FROM_IS.into()), + } + } + _ => problem(&here, FROM_IS.into()), + }, _ => problem(&here, "is not a key of a patch".into()), } } + if p.kind.is_some() && p.from.is_empty() { + problem(&format!("{at}/type"), "is read only with from (the patches createPatch makes it of)".into()); + p.kind = None; + } p } @@ -1451,6 +1505,204 @@ fn air_roles(case: &Case) -> Vec<(String, Role)> { out } +/// The patches the `createPatchDict` region `name`'s `createPatch` reads makes of others +/// (`constructFrom patches`): their `from`, a patch the list doesn't have added (its role not +/// told), and the type it is made of where the role wouldn't give it (`type`). The region's own dictionary when its steps run `createPatch`, else +/// `system/createPatchDict` when its mesh does. What can't be told (a face set, a macro) is noted. +fn import_created( + case: &Case, + name: &str, + kind: RegionKind, + mesh: &crate::workflow::RegionMesh, + patches: &mut Vec, + notes: &mut Vec, +) { + let own = mesh.steps.contains(&RegionStep::CreatePatch); + let at_root = matches!(&mesh.build, MeshBuild::Root(s) if s.contains(&RootStep::CreatePatch)); + if own && at_root { + notes.push(format!( + "region {name}: createPatch runs both in its mesh and after it: only system/{name}/createPatchDict is read, and workflow.dictionaries writes neither while the region has patches to make, until one is taken out" + )); + } + let path = match (own, at_root) { + (true, _) => crate::create_patch::dict_path(name), + (false, true) => crate::create_patch::ROOT_PATH.to_string(), + (false, false) => return, + }; + let Some(doc) = case.dict(&path) else { + notes.push(format!("region {name}: createPatch runs, but {path} isn't there or doesn't load")); + return; + }; + let items = match doc.root.get("patches").map(|e| e.value.as_slice()) { + Some([Node::List { items, .. }]) => items, + _ => { + notes.push(format!("region {name}: {path} has no plain patches list: what createPatch makes isn't told")); + return; + } + }; + let one = |d: &umcf_foam_dict::Dict, k: &str| match d.get(k).map(|e| e.value.as_slice()) { + Some([Node::Atom(t)]) => Some(t.text.clone()), + _ => None, + }; + // The patches by name, as items are many (a hostile file); a few notes, then a count. + let mut at: HashMap = patches.iter().enumerate().map(|(i, p)| (p.name.clone(), i)).collect(); + // A name given twice is one patch of both items' sources, as createPatch makes it. + let mut imported: HashMap> = HashMap::new(); + let mut noted = 0usize; + let mut note = |notes: &mut Vec, m: String| { + noted += 1; + if noted <= MAX_CREATE_NOTES { + notes.push(m); + } + }; + for n in items { + let Node::Dict { body, .. } = n else { + note(notes, format!("region {name}: an item of the patches of {path} isn't a dictionary: left out")); + continue; + }; + let plain = |t: &String| !t.starts_with(['$', '#']); + let Some(patch) = one(body, "name").filter(plain).map(|t| unescaped(&t)) else { + note(notes, format!("region {name}: a patch of {path} has no plain name: left out")); + continue; + }; + if crate::create_patch::keys_twice(body) { + note( + notes, + format!( + "region {name}, patch {patch}: {path} gives a key of it twice, which OpenFOAM merges: left out" + ), + ); + continue; + } + // A patchInfo that isn't a dictionary (nor a macro's), and keys createPatch doesn't + // read that the description can't hold. + if let Some(e) = body.get("patchInfo") + && e.dict().is_none() + && !matches!(e.value.as_slice(), [Node::Atom(t)] if t.text.starts_with(['$', '#'])) + { + note( + notes, + format!("region {name}, patch {patch}: {path} gives its patchInfo, which isn't a dictionary: left out"), + ); + continue; + } + if let Some(k) = body + .entries() + .map(|e| e.key()) + .find(|k| !matches!(*k, "name" | "patchInfo" | "constructFrom" | "patches" | "set")) + { + note( + notes, + format!( + "region {name}, patch {patch}: {path} gives it {}, which the description doesn't hold: left out", + crate::create_patch::cut(k) + ), + ); + continue; + } + if !crate::create_patch::whole(body) { + note( + notes, + format!("region {name}, patch {patch}: {path} gives part of it by a macro or directive: left out"), + ); + continue; + } + match one(body, "constructFrom").map(|t| unescaped(&t)).as_deref() { + Some("patches") => {} + Some(c) => { + note( + notes, + format!( + "region {name}, patch {patch}: {path} makes it of a {c}, which the description doesn't hold: left out" + ), + ); + continue; + } + None => { + note(notes, format!("region {name}, patch {patch}: {path} gives no plain constructFrom: left out")); + continue; + } + } + let from: Option> = match body.get("patches").map(|e| e.value.as_slice()) { + Some([Node::List { items, .. }]) => items + .iter() + .map(|n| atom(n).filter(|t| crate::create_patch::source_ok(t)).map(str::to_string)) + .collect(), + _ => None, + }; + let Some(from) = from.filter(|f| !f.is_empty()) else { + note( + notes, + format!( + "region {name}, patch {patch}: the patches {path} makes it of aren't a plain list of names and quoted patterns (without quotes, backslashes or spaces inside): left out" + ), + ); + continue; + }; + // Its type, kept where the role wouldn't give it (none, or another); a patchInfo holding + // more (a cyclic's or mapped patch's entries) isn't the description's. + let info = body.get("patchInfo").and_then(Entry::dict); + let given = info.and_then(|i| one(i, "type")).map(|t| unescaped(&t)); + let more = info.is_some_and(|i| { + i.entries().any(|e| e.key() != "type") + || i.items.iter().any(|x| !matches!(x, umcf_foam_dict::Item::Entry(_))) + }); + if more + || given + .as_deref() + .is_some_and(|t| !crate::description_edit::plain_name(t) || crate::blocks::needs_own_entries(t)) + { + note( + notes, + format!( + "region {name}, patch {patch}: {path} gives its patchInfo more than a plain type the description holds (a mapped or cyclic type, its entries): left out" + ), + ); + continue; + } + let own = |role: Option| { + given.clone().filter(|t| role.is_none_or(|r| crate::create_patch::role_type(kind, r) != t.as_str())) + }; + match at.get(&patch).and_then(|i| patches.get_mut(*i)) { + Some(p) if imported.contains_key(&patch) => { + let seen = imported.entry(patch).or_default(); + for f in from { + if seen.insert(f.clone()) { + p.from.push(f); + } + } + } + Some(p) => { + let mut seen = HashSet::new(); + let from: Vec = from.into_iter().filter(|f| seen.insert(f.clone())).collect(); + imported.insert(patch.clone(), seen); + p.from = from; + p.kind = own(p.role); + } + None => { + let kind = own(None); + note( + notes, + format!( + "region {name}, patch {patch}: made by createPatch, its role isn't told (the mesh doesn't have it)" + ), + ); + at.insert(patch.clone(), patches.len()); + let mut seen = HashSet::new(); + let from: Vec = from.into_iter().filter(|f| seen.insert(f.clone())).collect(); + imported.insert(patch.clone(), seen); + patches.push(PatchDesc { name: patch, role: None, partner: None, from, kind }); + } + } + } + if noted > MAX_CREATE_NOTES { + notes.push(format!("region {name}: {path}: and {} more notes like these", noted - MAX_CREATE_NOTES)); + } +} + +/// The most notes [`import_created`] gives for one dictionary before it counts the rest. +const MAX_CREATE_NOTES: usize = 20; + /// A patch's role and partner, as far as the mesh and the velocity condition (`u`) tell. fn infer( case: &Case, diff --git a/crates/model/src/description_edit.rs b/crates/model/src/description_edit.rs index 73b6a29..98d76b1 100644 --- a/crates/model/src/description_edit.rs +++ b/crates/model/src/description_edit.rs @@ -18,6 +18,11 @@ pub struct PatchEdit { pub partner: Option>, /// A new name; the partners that name the patch follow it. pub rename: Option, + /// The patches `createPatch` makes it of (names, or patterns); `Some(vec![])` takes them + /// away. + pub from: Option>, + /// Its type where the role doesn't give it; `Some(None)` takes it away. + pub kind: Option>, } /// What an edit did, besides the change itself. @@ -260,8 +265,43 @@ impl Case { if let Some(to) = &edit.rename { name("new name", to)?; } + let from: Option> = + edit.from.as_ref().map(|f| f.iter().map(|s| crate::create_patch::source_token(s)).collect()); + for f in from.iter().flatten() { + if !crate::create_patch::source_ok(f) { + return Err(refuse(format!( + "from `{f}` is neither a plain OpenFOAM name nor a pattern without quotes, backslashes or spaces inside" + ))); + } + } + if let Some(Some(t)) = &edit.kind { + name("type", t)?; + if crate::blocks::needs_own_entries(t) { + return Err(refuse(format!( + "type {t} needs entries of its own (neighbourPatch, …): changeDictionary gives it from the role and partner" + ))); + } + } if edit == &PatchEdit::default() { - return Err(refuse("nothing to change: give a role, a partner or a new name".into())); + return Err(refuse( + "nothing to change: give a role, a partner, the patches it is made of, a type or a new name".into(), + )); + } + // A type is read only with from: neither left without the other. + // (Not told while the description doesn't read: the edit then sees what is there.) + if (edit.from.is_some() || edit.kind.is_some()) + && let Some((d, _)) = self.description() + { + let now = d.region(region).and_then(|r| r.patches.iter().find(|p| p.name == patch).cloned()); + let from = + edit.from.as_ref().map_or_else(|| now.as_ref().is_some_and(|p| !p.from.is_empty()), |f| !f.is_empty()); + let kind = + edit.kind.as_ref().map_or_else(|| now.as_ref().is_some_and(|p| p.kind.is_some()), Option::is_some); + if kind && !from { + return Err(refuse(format!( + "patch {patch} of region {region}: a type is read only for a patch createPatch makes (from): give from too, or take the type away (null)" + ))); + } } let doc = self.editable()?; if !once(doc, &["regions", region])? { @@ -272,6 +312,8 @@ impl Case { if there { once(doc, &[&base[..], &["role"]].concat())?; once(doc, &[&base[..], &["partner"]].concat())?; + once(doc, &[&base[..], &["from"]].concat())?; + once(doc, &[&base[..], &["type"]].concat())?; unended(doc, &base)?; } else if edit.rename.is_some() { return Err(refuse(format!("patch {patch} of region {region} is not in {PATH}: nothing to rename"))); @@ -307,6 +349,18 @@ impl Case { "region {region}'s blocks name a patch {to} already: renaming {patch} to it would make the two one" ))); } + // Nor one another patch is made of (by name): its from would name what isn't there. + if let Some(by) = self.description().and_then(|(d, _)| { + d.region(region)? + .patches + .iter() + .find(|q| q.from.iter().any(|f| crate::create_patch::normal(f) == patch)) + .map(|q| q.name.clone()) + }) { + return Err(refuse(format!( + "patch {by} of region {region} is made of {patch} (from): renaming {patch} would leave it made of what isn't there; change its from first" + ))); + } for (r, p, pr, pp) in partners(doc) { // Its own partner, when this call sets it, is the one given. let own = r == region && p == patch; @@ -321,6 +375,8 @@ impl Case { let changes: Vec<(&str, Option)> = [ edit.role.map(|r| ("role", r.map(|r| r.name().to_string()))), edit.partner.as_ref().map(|p| ("partner", p.as_ref().map(|(r, q)| format!("( {r} {q} )")))), + from.as_ref().map(|f| ("from", (!f.is_empty()).then(|| format!("( {} )", f.join(" "))))), + edit.kind.as_ref().map(|t| ("type", t.clone())), ] .into_iter() .flatten() diff --git a/crates/model/src/description_edit_tests.rs b/crates/model/src/description_edit_tests.rs index 2d1f96d..2800d0e 100644 --- a/crates/model/src/description_edit_tests.rs +++ b/crates/model/src/description_edit_tests.rs @@ -60,6 +60,8 @@ fn a_patch_is_added_and_partnered() { role: Some(Some(Role::Coupled)), partner: Some(Some(("street".into(), "roof".into()))), rename: None, + from: None, + kind: None, }; assert!(c.describe_patch("air", "roof", &edit).unwrap().added); let p = read(&c).region("air").unwrap().patches.iter().find(|p| p.name == "roof").cloned().unwrap(); @@ -211,8 +213,13 @@ fn a_patch_laid_out_by_hand_keeps_its_comments() { ); assert!(text.contains("// the wind comes from here")); c.put_description(&fs, &text, false).unwrap(); - let edit = - PatchEdit { role: Some(Some(Role::Side)), partner: Some(Some(("air".into(), "east".into()))), rename: None }; + let edit = PatchEdit { + role: Some(Some(Role::Side)), + partner: Some(Some(("air".into(), "east".into()))), + rename: None, + from: None, + kind: None, + }; c.describe_patch("air", "west", &edit).unwrap(); let after = text_of(&c); assert!(after.contains(" // the wind comes from here\n role side;\n partner ( air east );\n"), "{after}"); @@ -356,8 +363,13 @@ fn a_self_coupled_patch_renamed_with_a_new_partner_keeps_it() { let (_, mut c) = described(); let selfish = PatchEdit { partner: Some(Some(("air".into(), "odd".into()))), ..PatchEdit::default() }; c.describe_patch("air", "odd", &selfish).unwrap(); - let edit = - PatchEdit { rename: Some("even".into()), partner: Some(Some(("street".into(), "x".into()))), role: None }; + let edit = PatchEdit { + rename: Some("even".into()), + partner: Some(Some(("street".into(), "x".into()))), + role: None, + from: None, + kind: None, + }; let r = c.describe_patch("air", "odd", &edit).unwrap(); assert!(!r.followed.contains(&"air/even".to_string()), "{r:?}"); let p = read(&c).region("air").unwrap().patches.iter().find(|p| p.name == "even").cloned().unwrap(); @@ -365,7 +377,7 @@ fn a_self_coupled_patch_renamed_with_a_new_partner_keeps_it() { // Coupled to itself again, then renamed with its partner taken away: none. let selfish = PatchEdit { partner: Some(Some(("air".into(), "even".into()))), ..PatchEdit::default() }; c.describe_patch("air", "even", &selfish).unwrap(); - let edit = PatchEdit { rename: Some("third".into()), partner: Some(None), role: None }; + let edit = PatchEdit { rename: Some("third".into()), partner: Some(None), role: None, from: None, kind: None }; c.describe_patch("air", "even", &edit).unwrap(); let p = read(&c).region("air").unwrap().patches.iter().find(|p| p.name == "third").cloned().unwrap(); assert_eq!(p.partner, None); @@ -537,3 +549,23 @@ fn a_snappy_surface_changes_alone() { assert!(after.contains("/* to come */"), "{after}"); assert_eq!(read(&c).region(®ion).unwrap().snappy.as_ref(), Some(&sn)); } + +#[test] +fn a_patch_another_is_made_of_isnt_renamed() { + let (fs, mut c) = described(); + let edit = |from: Option>, rename: Option<&str>| PatchEdit { + role: None, + partner: None, + rename: rename.map(str::to_string), + from, + kind: None, + }; + c.describe_patch("air", "buildings", &edit(Some(vec!["odd".into()]), None)).unwrap(); + let e = c.describe_patch("air", "odd", &edit(None, Some("even"))).unwrap_err().to_string(); + assert!(e.contains("patch buildings of region air is made of odd (from): renaming odd would leave it"), "{e}"); + // Quoted without a pattern's characters, it names the patch too. + c.describe_patch("air", "buildings", &edit(Some(vec!["\"odd\"".into()]), None)).unwrap(); + let e = c.describe_patch("air", "odd", &edit(None, Some("even"))).unwrap_err().to_string(); + assert!(e.contains("is made of odd (from)"), "{e}"); + let _ = fs; +} diff --git a/crates/model/src/description_tests.rs b/crates/model/src/description_tests.rs index 88d6347..6a50521 100644 --- a/crates/model/src/description_tests.rs +++ b/crates/model/src/description_tests.rs @@ -221,7 +221,13 @@ fn written_and_read_back_it_is_the_same() { RootStep::CreatePatch, RootStep::SnappyHexMesh("system/snappyHexMeshDict.street".into()), ])); - r.patches.push(PatchDesc { name: "with space".into(), role: Some(Role::Interior), partner: None }); + r.patches.push(PatchDesc { + name: "with space".into(), + role: Some(Role::Interior), + partner: None, + from: Vec::new(), + kind: None, + }); } d.features = true; d.solver = None; @@ -245,6 +251,8 @@ fn odd_names_come_back_as_they_were() { name: odd.into(), role: Some(Role::Coupled), partner: Some((odd.into(), odd.into())), + from: vec!["\"region1_to_.*\"".into(), "defaultFaces".into()], + kind: Some("wall".into()), }], materials: vec![MaterialDesc { name: odd.into(), model: Some(odd.into()) }], blocks: None, @@ -339,6 +347,41 @@ fn problems_are_named_and_the_rest_is_read() { assert!(d.radiation.is_none()); } +#[test] +fn the_patches_a_patch_is_made_of_are_names_or_patterns() { + let text = format!( + "{}regions\n{{\n air\n {{\n kind fluid;\n mesh blocks;\n steps ( createPatch );\n patches {{ buildings {{ role coupled; from ( defaultFaces \"region1_to_.*\" ); }} w {{ from ( defaultFaces ); type wall; }} m {{ type mappedWall; }} l {{ type ( wall ); }} t {{ type wall; }} a {{ from ( ); }} b {{ from defaultFaces; }} c {{ from ( ( x ) ); }} d {{ from ( \"\" ); }} }}\n }}\n}}\n", + header("dictionary", "umcfWorkflow") + ); + let (d, problems) = Description::read(&Document::parse(&text).unwrap()); + let at: Vec<&str> = problems.iter().map(|p| p.at.as_str()).collect(); + assert_eq!( + at, + [ + "regions/air/patches/m/type", + "regions/air/patches/l/type", + "regions/air/patches/t/type", + "regions/air/patches/a/from", + "regions/air/patches/b/from", + "regions/air/patches/c/from", + "regions/air/patches/d/from" + ], + "{problems:#?}" + ); + assert!(problems[0].message.starts_with("mappedWall needs entries of its own"), "{problems:#?}"); + assert_eq!(problems[1].message, "is a patch type (one plain word)"); + assert_eq!(problems[2].message, "is read only with from (the patches createPatch makes it of)"); + assert!(problems[3..].iter().all(|p| p.message.starts_with("is ( patch … ): names, or quoted patterns"))); + let air = d.region("air").unwrap(); + assert_eq!(air.patches[0].from, ["defaultFaces", "\"region1_to_.*\""]); + assert_eq!(air.patches[1].from, ["defaultFaces"]); + assert_eq!(air.patches[1].kind.as_deref(), Some("wall")); + assert!(air.patches[2..].iter().all(|p| p.from.is_empty() && p.kind.is_none())); + assert!(d.write().contains("w { from ( defaultFaces ); type wall; }")); + // Written back as read: the pattern quoted. + assert!(d.write().contains("buildings { role coupled; from ( defaultFaces \"region1_to_.*\" ); }")); +} + #[test] fn radiation_values_that_are_not_one_name_are_problems() { let text = format!( @@ -982,3 +1025,63 @@ fn a_mesh_from_another_regions_background_is_written_read_back_and_found() { assert_eq!(d.region("vegetation").and_then(|r| r.mesh.clone()), None, "{mesh}"); } } + +#[test] +fn import_reads_what_create_patch_makes() { + let item = |name: &str, info: &str, rest: &str| format!("{{ name {name}; patchInfo {info}; {rest} }}"); + let made = + |name: &str, info: &str, from: &str| item(name, info, &format!("constructFrom patches; patches ({from});")); + let items = [ + // The ground's role gives wall: no type kept. Given twice: both items' sources. + made("ground", "{ type wall; }", "a"), + made("ground", "{ type wall; }", "b a"), + // A patch the mesh doesn't have: added without a role, its type kept. + made("buildings", "{ type wall; }", "defaultFaces"), + // The top's role gives patch: wall kept. + made("top", "{ type wall; }", "\"top_.*\""), + // Left out, noted. + item("setp", "{ type patch; }", "constructFrom set; set f0;"), + made("m", "$info", "x"), + made("pi", "wall", "x"), + made("cyc", "{ type cyclic; neighbourPatch c2; }", "x"), + made("bs", "{ type wall; }", "\"a b\""), + item("ex", "{ type wall; }", "constructFrom patches; patches (x); extra 1;"), + item("tw", "{ inGroups (g); } patchInfo { type wall; }", "constructFrom patches; patches (x);"), + "{ name $n; }".to_string(), + ]; + let dict = format!("{}patches ( {} );\n", header("dictionary", "createPatchDict"), items.join(" ")); + let c = Case::open(&canyon().with("system/air/createPatchDict", dict)).unwrap(); + let (d, notes) = Description::import(&c); + let air = d.region("air").unwrap(); + let get = |n: &str| air.patches.iter().find(|p| p.name == n).unwrap(); + assert_eq!( + (get("ground").from.clone(), get("ground").kind.clone()), + (vec!["a".to_string(), "b".to_string()], None) + ); + assert_eq!((get("buildings").role, get("buildings").kind.as_deref()), (None, Some("wall"))); + assert_eq!((get("top").from.clone(), get("top").kind.as_deref()), (vec!["\"top_.*\"".to_string()], Some("wall"))); + for n in ["setp", "m", "pi", "cyc", "bs", "ex", "tw"] { + assert!(air.patches.iter().all(|p| p.name != n || p.from.is_empty()), "{n}"); + } + let said = |s: &str| notes.iter().any(|n| n.contains(s)); + for s in [ + "patch setp: system/air/createPatchDict makes it of a set", + "patch m: system/air/createPatchDict gives part of it by a macro or directive", + "patch pi: system/air/createPatchDict gives its patchInfo, which isn't a dictionary", + "patch cyc: system/air/createPatchDict gives its patchInfo more than a plain type", + "patch bs: the patches system/air/createPatchDict makes it of aren't a plain list", + "patch ex: system/air/createPatchDict gives it extra", + "patch tw: system/air/createPatchDict gives a key of it twice", + "a patch of system/air/createPatchDict has no plain name", + "patch buildings: made by createPatch, its role isn't told", + ] { + assert!(said(s), "{s}: {notes:#?}"); + } + // Many left out: 20 notes, then a count. + let bad: Vec = (0..30).map(|i| made(&format!("m{i}"), "$info", "x")).collect(); + let dict = format!("{}patches ( {} );\n", header("dictionary", "createPatchDict"), bad.join(" ")); + let c = Case::open(&canyon().with("system/air/createPatchDict", dict)).unwrap(); + let (_, notes) = Description::import(&c); + assert_eq!(notes.iter().filter(|n| n.contains("by a macro or directive")).count(), 20); + assert!(notes.iter().any(|n| n.contains("and 10 more notes like these")), "{notes:#?}"); +} diff --git a/crates/model/src/lib.rs b/crates/model/src/lib.rs index 7d6edbd..d4cbc79 100644 --- a/crates/model/src/lib.rs +++ b/crates/model/src/lib.rs @@ -47,6 +47,7 @@ pub mod blocks; pub mod components; mod controls; pub mod coupling; +pub mod create_patch; pub mod description; pub mod description_edit; pub mod material_edit; diff --git a/crates/model/tests/coupling.rs b/crates/model/tests/coupling.rs index 33b8801..5d1ab87 100644 --- a/crates/model/tests/coupling.rs +++ b/crates/model/tests/coupling.rs @@ -1,4 +1,4 @@ -//! Each region's `changeDictionaryDict` generated from the description `workflow.import` reads +//! Each region's `changeDictionaryDict` (and each `createPatchDict`, below) generated from the description `workflow.import` reads //! from a real case (`umcf_model::coupling`), compared with the case's own, read only, from //! `UMCF_CASES` (`:`-separated case directories); skipped without it. //! @@ -66,3 +66,61 @@ fn the_cases_change_dictionaries_are_generated_from_their_descriptions() { eprintln!("{compared} changeDictionaryDicts compared"); assert!(compared > 0, "UMCF_CASES gives no case with a changeDictionaryDict"); } + +/// Each `createPatchDict` the description's meshes and steps read, generated from what +/// `workflow.import` reads of the case's own (`umcf_model::create_patch`), against the case's +/// own: every patch it makes of others, as it makes it (`create_patch::differences`, the same +/// patches, sources and types). A patch whose role the import can't tell (a case without a +/// mesh) leaves its case uncompared, noted; a run that compares none fails. +#[test] +fn the_cases_create_patch_dictionaries_are_generated_from_their_descriptions() { + use umcf_model::create_patch; + let Ok(cases) = std::env::var("UMCF_CASES") else { + eprintln!( + "SKIP the_cases_create_patch_dictionaries_are_generated_from_their_descriptions: set UMCF_CASES=:… to run it" + ); + return; + }; + let mut compared = 0; + for dir in cases.split(':').filter(|d| !d.is_empty()) { + let case = match umcf_model::Case::open_with(&umcf_core::DirFs::new(dir), umcf_model::OpenOptions::default()) { + Ok(c) => c, + Err(e) => panic!("{dir}: doesn't open: {e}"), + }; + let (desc, _) = Description::import(&case); + let Some(version) = desc.version.or(case.layout.version) else { + eprintln!("{dir}: its OpenFOAM version isn't told: not compared"); + continue; + }; + let targets = match create_patch::targets(&desc, None) { + Ok(t) => t, + Err(e) if e.contains("neither a role nor a type") => { + eprintln!("{dir}: {e}: not compared"); + continue; + } + Err(e) => panic!("{dir}: {e}"), + }; + for t in &targets { + let Some(own) = case.dict(&t.path) else { continue }; + assert_eq!( + create_patch::differences(&own.root, &t.made, version), + Vec::::new(), + "{dir}: {}", + t.path + ); + let text = create_patch::dict(t, version); + let doc = umcf_foam_dict::Document::parse(&text).unwrap(); + assert!(umcf_model::blocks::untouched(&text), "{dir}: {}", t.path); + assert_eq!( + create_patch::differences(&doc.root, &t.made, version), + Vec::::new(), + "{dir}: {}", + t.path + ); + eprintln!("{dir}: {}: {} patches as the case's", t.path, t.made.len()); + compared += 1; + } + } + eprintln!("{compared} createPatchDicts compared"); + assert!(compared > 0, "UMCF_CASES gives no case with a createPatchDict"); +} diff --git a/crates/ui-egui/src/forms.rs b/crates/ui-egui/src/forms.rs index af03ff5..1f991db 100644 --- a/crates/ui-egui/src/forms.rs +++ b/crates/ui-egui/src/forms.rs @@ -64,6 +64,9 @@ pub(crate) enum Kind { Role(&'static [&'static str]), /// A name typed or picked (as [`Kind::Pick`]), sent as [`Kind::Role`] is: a material's model. Model, + /// Names typed, apart by spaces (with the hint while empty), sent as a list only when changed + /// from what the form was filled with; emptied: `null`. The patches a patch is made of. + Words(&'static str), /// The region and patch a patch is coupled to (`{"region", "patch"}`), each typed or picked: /// sent only when changed, both emptied: `null`. Partner, @@ -279,6 +282,7 @@ fn sent_when_changed(kind: Kind) -> bool { | Kind::Sides(_) | Kind::Role(_) | Kind::Model + | Kind::Words(_) | Kind::Partner | Kind::Coefficients | Kind::SnappySurfaces @@ -454,6 +458,17 @@ pub(crate) fn grid_text(kind: Kind, v: &Value, start: &str) -> Option { Value::String(t) => Some(t.clone()), _ => None, }, + Kind::Words(_) => match v { + Value::Null => Some(String::new()), + Value::Array(items) => { + let words: Option> = items + .iter() + .map(|x| x.as_str().filter(|t| !t.is_empty() && !t.contains(char::is_whitespace))) + .collect(); + Some(words?.join(" ")) + } + _ => None, + }, Kind::RegionRows => { let rows: Option> = v .as_array()? @@ -909,6 +924,14 @@ fn grid_json(f: &Field, text: &str, was: &str) -> Result, String> } Ok(Some(if now.is_empty() { Value::Null } else { json!(now) })) } + Kind::Words(_) => { + let (now, then): (Vec<&str>, Vec<&str>) = + (text.split_whitespace().collect(), was.split_whitespace().collect()); + if now == then { + return Ok(None); + } + Ok(Some(if now.is_empty() { Value::Null } else { json!(now) })) + } Kind::Partner => { let (now, then) = (parts(text, 2), parts(was, 2)); let trim = |v: &[String]| v.iter().map(|x| x.trim().to_string()).collect::>(); @@ -1214,7 +1237,7 @@ static SPECS: &[Spec] = &[ }, Spec { id: "workflow.patch", - intro: "A patch of a region of system/umcfWorkflow: its role, its partner, or a new name (a patch the region doesn't list is added).", + intro: "A patch of a region of system/umcfWorkflow: its role, its partner, the patches createPatch makes it of and their type, or a new name (a patch the region doesn't list is added).", fields: &[ field("region", "Region", Kind::WorkflowRegion, "A region of system/umcfWorkflow"), field("patch", "Patch", Kind::Pick("a patch, or a new one"), "A patch of the region, or a new one"), @@ -1227,6 +1250,18 @@ static SPECS: &[Spec] = &[ "none: taken away", ), field("partner", "Coupled to", Kind::Partner, "The region and patch it is coupled to; neither: taken away"), + field( + "from", + "Made of", + Kind::Words("defaultFaces"), + "The patches createPatch makes it of, apart by spaces (one that isn't a plain name is a pattern); none: taken away", + ), + field( + "type", + "Type", + Kind::Model, + "The type createPatch makes it of where its role doesn't give one (wall); empty: taken away", + ), field( "name", "New name", @@ -1270,13 +1305,13 @@ static SPECS: &[Spec] = &[ }, Spec { id: "workflow.dictionaries", - intro: "Writes each region's changeDictionaryDict from the patches' roles and partners in system/umcfWorkflow (Save writes them).", + intro: "Writes each region's changeDictionaryDict from the patches' roles and partners in system/umcfWorkflow, and each createPatchDict from the patches made of others (Save writes them).", fields: &[ field( "region", "Region", Kind::WorkflowRegion, - "Left to choose: every region whose steps run changeDictionary", + "Left to choose: every region whose steps run changeDictionary, or whose mesh or steps run createPatch", ), field( "replace", @@ -2249,7 +2284,7 @@ pub(crate) fn show( v.join(&PARTS.to_string()) }; } - Kind::Text(hint) | Kind::Number(hint) | Kind::Count(hint) => { + Kind::Text(hint) | Kind::Number(hint) | Kind::Count(hint) | Kind::Words(hint) => { let edit = egui::TextEdit::singleline(text).desired_width(wide).hint_text(hint); ui.add(edit).labelled_by(label.id); } @@ -2866,6 +2901,21 @@ mod tests { assert_eq!(f.values["role"], "top"); f.fill(spec, &json!({"region": "air", "patch": "ground", "partner": ["street"]})).unwrap(); assert_eq!(f.params(spec).unwrap()["partner"], json!(["street"])); + // The patches it is made of: a list apart by spaces, sent when changed; emptied: null. + let mut f = FormState::default(); + f.fill(spec, &json!({"region": "air", "patch": "buildings", "from": ["defaultFaces", "region1_to_.*"]})) + .unwrap(); + assert_eq!(f.values["from"], "defaultFaces region1_to_.*"); + f.initial = f.values.clone(); + assert_eq!(f.params(spec).unwrap(), json!({"region": "air", "patch": "buildings"})); + f.values.insert("from", " defaultFaces region1_to_.* ".into()); + assert_eq!(f.params(spec).unwrap(), json!({"region": "air", "patch": "buildings"})); + f.values.insert("from", "defaultFaces other".into()); + assert_eq!(f.params(spec).unwrap()["from"], json!(["defaultFaces", "other"])); + f.values.insert("from", " ".into()); + assert_eq!(f.params(spec).unwrap()["from"], Value::Null); + f.fill(spec, &json!({"region": "air", "patch": "buildings", "from": null})).unwrap(); + assert_eq!(f.values["from"], ""); // A switch is sent either way; names ticked as a list. let spec = super::spec("workflow.component").unwrap(); let mut c = FormState::default(); diff --git a/crates/ui-egui/src/results.rs b/crates/ui-egui/src/results.rs index 71047a6..7a8fe41 100644 --- a/crates/ui-egui/src/results.rs +++ b/crates/ui-egui/src/results.rs @@ -194,7 +194,19 @@ pub fn lines(data: &Value) -> Vec<(Kind, String)> { .filter(|q| q.is_object()) .map(|q| format!(" → {}/{}", s(q, "region"), s(q, "patch"))) .unwrap_or_default(); - desc.push(Kind::Text, || format!(" {}: {role}{partner}", s(p, "name"))); + let from = p + .get("from") + .and_then(Value::as_array) + .filter(|f| !f.is_empty()) + .map(|f| { + format!( + ", made of {}", + some(f.iter().map(|x| x.as_str().unwrap_or_default().to_string())).join(" ") + ) + }) + .unwrap_or_default(); + let kind = p.get("type").and_then(Value::as_str).map(|t| format!(", type {t}")).unwrap_or_default(); + desc.push(Kind::Text, || format!(" {}: {role}{partner}{from}{kind}", s(p, "name"))); } if !materials.is_empty() { let names = some(materials.iter().map(|m| match m.get("model").and_then(Value::as_str) { @@ -232,7 +244,7 @@ mod tests { "patches": [ { "name": "inlet", "role": "inlet", "partner": null }, { "name": "ground", "role": "coupled", "partner": { "region": "street", "patch": "top" } }, - { "name": "odd", "role": null, "partner": null }, + { "name": "odd", "role": null, "partner": null, "from": ["defaultFaces", "region1_to_.*"], "type": "wall" }, ] }, { "name": "street", "kind": "solid", "mesh": [{ "step": "blockMesh", "dict": "blockMeshDict.street" }], "steps": [], "patches": [], @@ -264,7 +276,7 @@ mod tests { ), (Kind::Text, " inlet: inlet".to_string()), (Kind::Text, " ground: coupled → street/top".to_string()), - (Kind::Text, " odd: no role".to_string()), + (Kind::Text, " odd: no role, made of defaultFaces region1_to_.*, type wall".to_string()), (Kind::Text, "street (solid), mesh blockMesh(blockMeshDict.street)".to_string()), (Kind::Text, " materials: soil (Soil), plaster".to_string()), ] diff --git a/crates/ui-egui/src/workflowcard.rs b/crates/ui-egui/src/workflowcard.rs index ee56c46..8eaf7d5 100644 --- a/crates/ui-egui/src/workflowcard.rs +++ b/crates/ui-egui/src/workflowcard.rs @@ -1,9 +1,9 @@ //! The workflow description's cards (`workflow.region`, `workflow.patch`, `workflow.material`, //! `workflow.component`, `mesh.split`, `mesh.snappy`): each frame, the names their fields offer //! (the description's regions, a region's patches and materials, the material models of the -//! solver, the air's patches), and -//! what they describe filled in when it is chosen (a region's kind, a patch's role and partner, -//! a material's model, a region's snappy entry). +//! solver, the air's patches), and what they describe filled in when it is chosen (a region's +//! kind, a patch's role, partner and the patches it is made of, a material's model, a region's +//! snappy entry). use umcf_model::RegionKind; use umcf_model::description::Description; @@ -89,7 +89,15 @@ fn described( .filter(|(a, b)| !a.contains('|') && !b.contains('|')) .map(|(a, b)| format!("{a}|{b}")) .unwrap_or_default(); - Some(vec![("role", role), ("partner", partner)]) + // Sources with a space can't be shown apart by spaces: none shown. + let from = + if p.from.iter().any(|x| x.contains(char::is_whitespace)) { String::new() } else { p.from.join(" ") }; + Some(vec![ + ("role", role), + ("partner", partner), + ("from", from), + ("type", p.kind.clone().unwrap_or_default()), + ]) } "workflow.material" => { let m = r.materials.iter().find(|m| m.name == value("material"))?; @@ -178,7 +186,7 @@ fn merge_table(k: &str, value: &str, was: &str, now: &str) -> Option { fn card_fields(id: &str) -> &'static [&'static str] { match id { "workflow.region" => &["kind"], - "workflow.patch" => &["role", "partner"], + "workflow.patch" => &["role", "partner", "from", "type"], "workflow.material" => &["model"], "material.set" => &["coefficients"], "mesh.split" => &["of", "zone", "dict"], @@ -305,6 +313,7 @@ impl App { options.insert("patch", patches_of(d, ®ion)); let partner = f.values.get("partner").and_then(|p| p.split('|').next()).unwrap_or("").trim(); options.insert(PARTNER_PATCHES, patches_of(d, partner)); + options.insert("type", vec!["wall".to_string(), "patch".to_string()]); options.insert("partner", regions); } "mesh.split" => { diff --git a/crates/validate/src/description.rs b/crates/validate/src/description.rs index 33d0fe5..5b51970 100644 --- a/crates/validate/src/description.rs +++ b/crates/validate/src/description.rs @@ -17,6 +17,7 @@ const BLOCKS: &str = "workflow.blocks"; const SPLIT: &str = "workflow.split"; const SNAPPY: &str = "workflow.snappy"; const CHANGE: &str = "workflow.change-dictionary"; +const CREATE: &str = "workflow.create-patch"; pub(crate) fn check(case: &Case, out: &mut Vec) { let Some((d, problems)) = case.description() else { return }; @@ -145,6 +146,95 @@ pub(crate) fn check(case: &Case, out: &mut Vec) { } } features(case, &d, out); + if problems.is_empty() { + create_patch(case, &d, out); + } +} + +/// `workflow.create-patch`: each `createPatchDict` the description's meshes and steps read +/// (`createPatch -region`'s own, and `system/createPatchDict` of the regions meshed with +/// `createPatch` in `constant/polyMesh`), against what `workflow.dictionaries` writes from the +/// patches' `from` and roles ([`umcf_model::create_patch`]): one that can't be written, one +/// missing or that doesn't load, one umcfGui wrote that isn't what it writes now, and the +/// case's own where it makes the patches otherwise, as [`umcf_model::create_patch::differences`] +/// says. +fn create_patch(case: &Case, d: &Description, out: &mut Vec) { + use umcf_model::create_patch as cp; + let Some(version) = d.version.or(case.layout.version) else { return }; + let targets = match cp::targets(d, None) { + Ok(t) => t, + Err(e) => { + out.push(Diagnostic::new( + Level::Warning, + CREATE, + PATH, + format!("the createPatchDicts can't be written from the description: {e}"), + )); + return; + } + }; + for t in &targets { + let regions = t.regions.join(", "); + let whose = if t.regions.len() == 1 { "region" } else { "regions" }; + let message = match case.dict(&t.path) { + None if case.exists(&t.path) == Some(true) => { + "doesn't load as a dictionary (or is a directory): workflow.dictionaries can't write it until it is mended or removed".to_string() + } + None => format!("not there, and createPatch reads it: workflow.dictionaries writes it from the patches of {whose} {regions}"), + Some(doc) => { + let have = doc.to_string(); + if have == cp::dict(t, version) { + continue; + } + if blocks::untouched(&have) { + format!( + "written by umcfGui otherwise than it writes {whose} {regions}'s now (other patches made, roles, another OpenFOAM version, or an older umcfGui): workflow.dictionaries writes it again" + ) + } else { + let diff = cp::differences(&doc.root, &t.made, version); + let kept = cp::kept(&doc.root, &t.made, version); + let Some(first) = diff.first() else { + // The same patches, but more the description can't hold: said, as + // workflow.dictionaries leaves it as it is. + if !kept.is_empty() { + let mut diag = Diagnostic::new( + Level::Warning, + CREATE, + &t.path, + format!( + "the case's own makes the patches as the description of {whose} {regions} does, but holds what it can't ({}), which workflow.dictionaries leaves as it is: describe it (workflow.patch) or mend the file by hand", + cp::summary(&kept) + ), + ); + if let [only] = t.regions.as_slice() { + diag = diag.region(only); + } + out.push(diag); + } + continue; + }; + let more = match diff.len() { + 1 => String::new(), + n => format!(", and {} more", n - 1), + }; + // What the description can't hold isn't written over: said how to keep it. + let fix = if kept.is_empty() { + "workflow.dictionaries with replace writes it from the description (the one there is kept in the backup when the case is saved)" + } else { + "it holds what the description can't, which workflow.dictionaries doesn't write over: give the patches their from (and type) with workflow.patch, or mend the file by hand" + }; + format!( + "the case's own makes the patches otherwise than the description of {whose} {regions} does ({first}{more}): {fix}" + ) + } + } + }; + let mut diag = Diagnostic::new(Level::Warning, CREATE, &t.path, message); + if let [only] = t.regions.as_slice() { + diag = diag.region(only); + } + out.push(diag); + } } /// Whether the `snappyHexMeshDict` `root` holds what the entry `sn` of region `r` does, read diff --git a/docs/common-workflow.md b/docs/common-workflow.md index a83c0ee..8ae18d8 100644 --- a/docs/common-workflow.md +++ b/docs/common-workflow.md @@ -123,7 +123,7 @@ named by the description too: a solid's materials, the tree zone. | `system/umcfWorkflow` | the user, through umcfGui's commands or by hand | | Geometry: the STL surfaces, the blocks, refinement levels, layers, extrusion thicknesses | settings in `umcfWorkflow`, written into the meshing dictionaries | | A region's `blockMeshDict` (the one its `mesh` reads) | generated from its `blocks` by `mesh.block` ([the workflow](user-guide/workflow.md#blocks)) | -| `createPatchDict`, `changeDictionaryDict`, `topoSetDict` (or the `setSet` batch), `viewFactorsDict`, `setFieldsDict` | generated from `umcfWorkflow` (`changeDictionaryDict` so far: `workflow.dictionaries`) | +| `createPatchDict`, `changeDictionaryDict`, `topoSetDict` (or the `setSet` batch), `viewFactorsDict`, `setFieldsDict` | generated from `umcfWorkflow` (`changeDictionaryDict` and `createPatchDict` so far: `workflow.dictionaries`) | | `0.orig//`: the initial fields with an entry per patch, by role, and the tables there (`Tambient`, `wambient`, `cloudCover`, …) | the fields' entries generated for patches that have none, then set by the user and kept: `bc.set` sets a condition in the start time's field today, and will set it in `0.orig` too (see [the fields](#the-fields)); the tables from the site and weather data (row 9) or the user | | The materials' entries in `buildingMaterials` (`transportProperties` of each solid) | added with the material from a library of materials with their coefficients, then edited by the user | | `Allprepare`, `Allrun`, `Allclean` | generated, for the version in `umcfWorkflow` | diff --git a/docs/gaps.md b/docs/gaps.md index 8769a6e..60dbda4 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -13,7 +13,7 @@ be reset and made again. [What a case needs](case-requirements.md) is the specif | # | Gap | Why it matters | Where | |---|---|---|---| | 1 | Patches of an existing mesh, the rest: running `createPatch` on the prepared patches from umcfGui (with the runner, row 11). The meshing dictionaries follow once they are generated from `umcfWorkflow` (rows 4, 7 and 8); until then `patch.set` lists where the old name is still written. Retyping, regrouping and renaming (`patch.set`, a new name followed into the results of other times, the `processor*` directories and `boundaryData` on request) and new patches from faces picked, selected in a rectangle or painted with a brush, labels, a box or an STL surface (`patch.create`) are there, for the mesh as it is | A patch is split most directly where it is seen; until `createPatch` runs, the new patch can't be given conditions or looked at | `model`, `engine`, `ui-egui` | -| 4 | The dictionaries generated from `umcfWorkflow` by patch role and the coupling rules, the rest (each region's `changeDictionaryDict` is written by `workflow.dictionaries`): `createPatchDict`, `topoSetDict` (or the `setSet` batch), `viewFactorsDict`, and `0.orig//` with an entry per patch by role (inlet, outlet, side, top, ground, coupled, canopy, interior, bottom, sky), the cell zones named by it (materials, the tree zone), and each material's `buildingMaterials` entry from a library of materials; a generated dictionary marked as such and backed up before it replaces a hand edit, while an existing `0.orig` field is edited in place (only a missing one is made) | Coupling by hand touches a dozen files that must agree | `model`, `schema`, `engine` | +| 4 | The dictionaries generated from `umcfWorkflow` by patch role and the coupling rules, the rest (each region's `changeDictionaryDict` and the `createPatchDict`s are written by `workflow.dictionaries`): `topoSetDict` (or the `setSet` batch), `viewFactorsDict`, and `0.orig//` with an entry per patch by role (inlet, outlet, side, top, ground, coupled, canopy, interior, bottom, sky), the cell zones named by it (materials, the tree zone), and each material's `buildingMaterials` entry from a library of materials; a generated dictionary marked as such and backed up before it replaces a hand edit, while an existing `0.orig` field is edited in place (only a missing one is made) | Coupling by hand touches a dozen files that must agree | `model`, `schema`, `engine` | | 7 | Solids by extrusion in `umcfWorkflow`: layers (material, thickness, cells, grading) from a building surface or the ground, or from the snapped air patch for solids that meet the air face for face, written to the `extrudeMeshDict`s, the patch renames and the material cell zones; leaf area density from the tree surface (`topoSet`, `setFields`) | The STL chain's solids and trees are made this way | `model`, `engine` | | 8 | The scripts from `umcfWorkflow` (`Allprepare`, `Allrun`, `Allclean` for its version: written by `workflow.scripts`), the rest: the fields put in place after meshing (`0.orig` to `0`, `setFields`); the STL chain read into a `umcfWorkflow` (`extrudeMesh`, and the tutorials' moves between `constant/polyMesh` and the regions by copy rather than `mv`, after which their kept background is read too); a split region's fields put back after the split (`cp 0/vegetation.bckp/* 0/vegetation/`); and reset (`mesh.reset`), which puts the case back before meshing | After a change to the geometry or the patches the mesh is out of date | `model` (workflow), `validate`, `engine` | | 9 | Site, date and weather: latitude, longitude, time zone, start date and the mesh's north, from which the sun table (`sunPosVector`) and the irradiance (`IDN`, `Idif`) are computed, and the outdoor tables (`Tambient`, `wambient`, `cloudCover`, `LW`) read from a weather file; emissivity, albedo and view factor settings per patch | Radiation data can't be set in the case otherwise; the solver itself has no calendar | `model` (site, weather), `engine`, `ui-egui` | diff --git a/docs/user-guide/checks.md b/docs/user-guide/checks.md index eb5b25a..f19ecf6 100644 --- a/docs/user-guide/checks.md +++ b/docs/user-guide/checks.md @@ -243,6 +243,7 @@ OpenFOAM version. Each problem names the script and line. | `workflow.blocks` | Warning | A region's [blocks](workflow.md#blocks) in the description: the grid's problems (stations that don't increase, a span without cells or with a section blockMesh would give none, a `cyclic`, `nonConformal`, `mapped` or `processor` type in `types`, more than 10 000 names in a map, a dictionary too large to read back, a missing block outside the grid or listed twice, a whole layer missing, a face without a patch, a single face inside the mesh, too many blocks), a patch the region's `patches` don't list or whose role doesn't fit its side (the ground and top across the gravity of `constant//g`, else `constant/g`, else z up, said), blocks without a `mesh`, a region meshed from another's [background](workflow.md#background) that the scripts can't keep (that region not listed before it, not built by steps of its own starting with `blockMesh`, or a region named as the directory it is kept in) or that has blocks of its own its mesh doesn't read, or that doesn't list the patches of the background's blocks its mesh gets, a [box](workflow.md#box) without blocks, with a problem of its own (a surface name that isn't an STL file of `constant/triSurface`, a negative margin, a cell size not above 0) or around surfaces the case doesn't have, and a `blockMeshDict` that isn't there, doesn't load or isn't what the blocks make (edited by hand, written from other blocks, another patch type): `mesh.block` writes it, listing any type it changes and any patch it drops or adds, and refusing to change a wall or constraint type the call's `types` doesn't give, or to drop such a patch `dropPatches` doesn't name. The grid's problems: the first 20 of them all, then how many more; patches the description doesn't list, and patches whose role doesn't fit: 20 of each, then how many more | | `workflow.snappy` | Warning | A region's [snappy entry](workflow.md#snappy) in the description: its own problems (a cutting surface without a level, distances whose levels grow away from the surface, a feature level on a compressed surface, a box without a length, names given twice, …), a solid region, a mesh that doesn't run snappyHexMesh, a surface the case doesn't have, cutting surfaces' patches the description doesn't list or that another surface or the blocks make too (those of the region whose background its mesh starts from), an inside point outside those blocks, on their sides or in a missing block (the blocks may have changed since `mesh.snappy` checked it), features asked for while the workflow doesn't run `surfaceFeatures`, a `snappyHexMeshDict` that isn't what the entry writes (missing, doesn't load, written from another entry, or edited by hand so that it holds something else than the entry: one of the case's own that holds what the entry does, as `workflow.import` read the entry from it, with the patch types the roles give, is an Info, counting the parts of it the entry can't hold), and a `system/surfaceFeaturesDict` that is missing, doesn't load, was written from other entries, or is the case's own and doesn't list a surface asking for features. The surfaces themselves are checked by `mesh.snappy` | | `workflow.change-dictionary` | Warning | The `changeDictionaryDict` of a region whose steps run `changeDictionary`, against what [`workflow.dictionaries`](workflow.md#writing-the-dictionaries) writes from the patches' roles and partners: one that can't be written (a partner without a role, a partner region not described, a canopy with a partner or no air, a name that isn't a plain OpenFOAM word, or a region's that can't be a directory on every system), one missing or that doesn't load, one umcfGui wrote otherwise than it writes now (other roles or partners, another OpenFOAM version, or an older umcfGui), and the case's own where it differs, by the keys the version reads and only those given (`changeDictionary` merges a block into the mesh's patch, so a key left out keeps the mesh's value, not known before the mesh is made; a region or patch the version reads that is left out is said to be unconfirmed, in OpenFOAM-8 unless OpenFOAM-12's key stands in its place, said to be unread; a patch's block with a `~key`, which takes the key out of the mesh's patch, isn't compared, said so): a patch's type, or the region and patch it maps to (OpenFOAM-8 only `sampleRegion` and `samplePatch`, `neighbourRegion` or `neighbourPatch` in their place said to be unread; OpenFOAM-12 `neighbourRegion` and `neighbourPatch` where given, else the older two, which alone, the description's or not, are said to be unconfirmed, as OpenFOAM-12 reads the newer first and the mesh's patch keeps a newer one it has; OpenFOAM-12's `mappedInternal` reads no patch; OpenFOAM-8 stops on a patch other than `none` in a mode that samples none, `nearestCell`, `nearestOnlyCell` or `nearestFace`, with a `coupleGroup` too, and without a mode given the patch isn't compared; with a `coupleGroup`, OpenFOAM-8 compares the region and patch only when both are given (in `nearestCell` and `nearestOnlyCell` the region alone; `nearestFace` asks the group for a patch not given, refused), OpenFOAM-12 stops on a group given with either, and a partner named by the group alone isn't compared; OpenFOAM-12's `samePatch`, a switch (`true`, `yes`, `on` and the like) or a number other than 0, names the patch of the same name, refused with a patch named too (not compared then), and alone compared and, where it is the description's, said to be unconfirmed, as OpenFOAM-12 refuses it beside a `neighbourPatch`, which it writes on a mapped patch and the mesh's patch keeps, and one that isn't a switch (quoted, too) refused, the patch not compared then; a name that isn't a word, empty (`""`) or a dictionary, is said to be refused, for the keys the version reads, a group's too, and so is a type that is a dictionary), a sample mode OpenFOAM-8 hasn't or one sampling no patch against one sampling a patch, an OpenFOAM-12 `method` (or `sampleMode` read as it) it hasn't, a patch changed that the description doesn't map, a value in `boundary` (which `changeDictionary` adds to the mesh's `boundary` file), a `~patch` there, quoted or not (on which `changeDictionary` stops where the mesh has the patch, or, with a block for it after, writes the block in its place without its faces; neither compared); other methods and modes, the offsets and values given by a macro or directive aren't compared (nor, with an OpenFOAM-8 `sampleMode` from one, the `samplePatch`), a patch mapped only through a pattern or group is said not to be there, keys a patch's block brings in (`$common;`, `#include`) aren't seen, and of a patch given twice only the last is read (OpenFOAM merges them). The case's own that maps them as the description does is fine. Not checked while the description doesn't read whole | +| `workflow.create-patch` | Warning | Each `createPatchDict` the description's meshes and steps read (`system//createPatchDict` for `createPatch -region`, `system/createPatchDict` for the regions meshed with `createPatch` in `constant/polyMesh`), against what [`workflow.dictionaries`](workflow.md#the-createpatchdicts) writes from the patches made of others (`from`) and their roles or types: when they can't be written (a patch made with neither a role nor a type, or in a region running no `createPatch`, a region running it both in and after its mesh with patches to make, regions sharing `system/createPatchDict` that make other patches, a name that isn't a plain word), one missing or that doesn't load, one umcfGui wrote otherwise than it writes now, and the case's own where it makes the patches otherwise: a patch not made there, made of a set or of other patches, of another type, one made there the description doesn't make, the `patches` list or OpenFOAM-8's `pointSync` missing, which `createPatch` stops without. The sources are compared as their union, in any order; a name or type quoted or not is the same, and so is a source quoted that OpenFOAM doesn't take for a pattern; what a macro or directive gives isn't compared (an item holding one by its name only). Where the case's own holds what the description can't (a patch it doesn't make or gives twice, one made of a face set or of sources it can't hold, `patchInfo` entries besides the type or other keys of an item, a key given twice in an item or its `patchInfo`, a value from a macro or directive, a list that can't be read whole, another entry at its top, OpenFOAM-8's `pointSync` not off), it says so, even where it makes the same patches, and to describe them with `workflow.patch` or mend the file, as `workflow.dictionaries` leaves it as it is. Not checked while the description doesn't read whole | | `workflow.split` | Warning | A region [split](workflow.md#split) from another by a cell zone: from a region the description doesn't list, lists after it or doesn't build; a zone not named (no script splits it), or that its `topoSetDict` doesn't make, a `topoSetDict` that makes other zones too (they would be split off as well; no script splits it) or whose zones can't be told (`#include`, a macro), or a dictionary the case doesn't have; a zone or `region1` named as a region (the split's clean-up would remove that region's directories), a region named `region` and a number (as `splitMeshRegions` names the parts outside the zone) | ## Finite-volume constraints and pressure limits (OpenFOAM-12) diff --git a/docs/user-guide/command-line.md b/docs/user-guide/command-line.md index f1ab43c..90ca1e1 100644 --- a/docs/user-guide/command-line.md +++ b/docs/user-guide/command-line.md @@ -158,16 +158,16 @@ bad arguments. | `case.info` | The case: OpenFOAM version, kind, regions with their patch and field counts, `processor*` directories, unsaved files, what didn't read | | `case.check` | The [case check](checks.md) | | `workflow.show` | The [workflow description](workflow.md#the-workflow-description): `system/umcfWorkflow` as read, with its problems, or as `workflow.import` would write it when the case has none: `scripts` (`true` also returns the scripts `workflow.scripts` would write) | -| `workflow.import` | Writes `system/umcfWorkflow` from the case's scripts, meshes (blocks from a `blockMeshDict`, the snappy entry from a `snappyHexMeshDict`) and solids' materials, with notes on what it couldn't tell: `replace` (`true` writes over the case's own) | +| `workflow.import` | Writes `system/umcfWorkflow` from the case's scripts, meshes (blocks from a `blockMeshDict`, the snappy entry from a `snappyHexMeshDict`), `createPatchDict`s (each patch's `from` and `type`, [the createPatchDicts](workflow.md#the-createpatchdicts)) and solids' materials, with notes on what it couldn't tell: `replace` (`true` writes over the case's own) | | `region.add` | [Adds a region](new-case.md#adding-a-region) to the case: `region`, `kind` (`fluid`, `solid`, `vegetation`) required; `materials` (a solid's, `[{"name": "brick", "model": "Hamstad5Brick"}]`). Lists it where the case's version reads its regions and writes the settings of its kind; the files there are kept | | `material.set` | [Sets a material's coefficients](new-case.md#a-materials-coefficients) in its solid's `transportProperties`: `region`, `material`, `coefficients` (`{"rho": 1700, "wcap": 2, "mu": null}`), that material only | | `workflow.region` | [Edits the description](workflow.md#editing-the-description): `region`, and `kind` (`fluid`, `solid`, `vegetation`: adds it or gives it that kind) or `remove: true` | -| `workflow.patch` | Edits a patch of the description: `region`, `patch`, and any of `role` (`null` takes it away), `partner` (`{"region": "street", "patch": "top"}`, or `null`), `name` (renames it; the partners that named it follow) | +| `workflow.patch` | Edits a patch of the description: `region`, `patch`, and any of `role` (`null` takes it away), `partner` (`{"region": "street", "patch": "top"}`, or `null`), `from` (the patches `createPatch` makes it of, `["defaultFaces"]`, or `null`), `type` (its type where the role doesn't give it, or `null`), `name` (renames it; the partners that named it follow) | | `workflow.material` | Edits a solid's material in the description: `region`, `material`, and `model` (its `buildingMaterialModel`, or `null`) or `remove: true` | | `workflow.settings` | [Chooses settings](workflow.md#settings): any of `deltaT`, `endTime`, `writeInterval`, `turbulence`, `temperatureLimit` (`[min, max]`), `blending` (`{"dampingThickness": 60, "alphaCoeffU": 0.3, "alphaCoeffT": 0.3}`), `materials` (the library: `{"HamstadConcrete": {"rho": 1950, …}}`), `numerics` (per region kind: `{"fluid": {"SIMPLE": {"nNonOrthogonalCorrectors": 1}}}`), `from` (another case, read only), into the case's files and its description | | `workflow.component` | [Switches a component](workflow.md#components) on or off: `component` (`grass`, `temperatureLimit`, `blending`), `on` (`true`, `false`), `patches` (the grass's, of `air`), in the case's files and its description | | `workflow.scripts` | Writes `Allprepare`, `Allrun` and `Allclean` from the description, for its OpenFOAM version ([Writing the scripts](workflow.md#writing-the-scripts)): `replace` (`true` writes over scripts that differ) | -| `workflow.dictionaries` | Writes each region's `changeDictionaryDict` from the patches' roles and partners in the description, for its OpenFOAM version ([Writing the dictionaries](workflow.md#writing-the-dictionaries)): `region` (one region's only), `replace` (`true` writes over one edited by hand) | +| `workflow.dictionaries` | Writes each region's `changeDictionaryDict` from the patches' roles and partners in the description, and each `createPatchDict` from the patches made of others (`from`), for its OpenFOAM version ([Writing the dictionaries](workflow.md#writing-the-dictionaries)): `region` (one region's only), `replace` (`true` writes over one edited by hand) | | `geometry.import` | Copies an STL file into `constant/triSurface` ([Surfaces](surfaces.md#importing)): `path` (required), `name`, `replace`, `scale` | | `geometry.trees` | Writes [tree crowns](surfaces.md#tree-crowns) as one surface in `constant/triSurface`: the trees from `table` (a file of the case), `path` (a file outside it) or `trees` (`[{"x": 10, "y": 5, "z": 0, "diameter": 6, "height": 8}]`); `name` (default `trees.stl`), `solid` (default `trees`), `replace` | | `geometry.check` | The [surface checks](surfaces.md#checks): `file` (one surface of the case), `path` (a file anywhere, no case needed), or neither (every STL surface in `constant/triSurface`) | diff --git a/docs/user-guide/workflow.md b/docs/user-guide/workflow.md index 7704cf2..36b2af8 100644 --- a/docs/user-guide/workflow.md +++ b/docs/user-guide/workflow.md @@ -133,8 +133,9 @@ case's own scripts, read as above, without a description. `workflow.dictionaries` writes, from the [workflow description](#the-workflow-description) and for its OpenFOAM version, the dictionaries the scripts' steps read that carry only names and -types. So far that is each region's `system//changeDictionaryDict`, for a region whose -steps run `changeDictionary` (the others of [gaps](../gaps.md) row 4 follow). It types the +types. So far those are each region's `system//changeDictionaryDict`, for a region whose +steps run `changeDictionary`, and the `createPatchDict`s ([below](#the-createpatchdicts)) (the +others of [gaps](../gaps.md) row 4 follow). The `changeDictionaryDict` types the patches by their roles and points them at their partners, as the [coupling rules](../case-requirements.md#coupling-rules) say: @@ -221,11 +222,66 @@ umcf-cli run --case path/to/case --cmd 'workflow.import={}' \ With a dictionary there edited by hand, or the case's own, that isn't what it writes, the command names it and writes none; `{"replace":true}` writes them from the description (`case.save` keeps a backup of each). +### The createPatchDicts + +A patch `createPatch` makes of others has their names in its `from` +([the description](#the-workflow-description)): blockMesh's own `defaultFaces` made into the +buildings' walls (the 3×3 cases' `buildings` and their solids' `sides`, the street canyons' +`buildings`), or the patch `splitMeshRegions` leaves on the vegetation region made into its +canopy (`"region1_to_.*"`, a pattern). `workflow.dictionaries` writes, for each, the +`createPatchDict` its `createPatch` reads: + +- `system//createPatchDict` for a region whose steps run `createPatch` (`createPatch + -region`, after the mesh); +- `system/createPatchDict` for the regions whose mesh runs `createPatch` in `constant/polyMesh` + (`mesh ( blockMesh … createPatch … )`, the 3×3 cases' air and vegetation): one dictionary for + them all, so they must make the same patches. + +Each patch is `{ name …; patchInfo { type …; } constructFrom patches; patches ( … ); }`, its +sources as the description has them: a bare name one patch, a quoted one a pattern, as +`createPatch` reads them (`"region.1"` is a regular expression, `region.1` a name). Its type is the +patch's own `type` where it has one, else `wall` for a wall's role (`ground`, `coupled`, +`interior`, `bottom`), the canopy and every solid's patch, else `patch`; `changeDictionary` makes +a coupled one and the canopy mapped after. `pointSync false;` is written for OpenFOAM-8, which +stops without it (OpenFOAM-12 doesn't read it). A region whose steps run `createPatch` with no +patch to make gets an empty list. Refused, writing none: a patch made by `createPatch` with +neither a role nor a type, one in a region whose mesh and steps run no `createPatch`, a region +whose mesh and steps both run it with patches to make (which makes them isn't told), regions +meshed in `constant/polyMesh` that make different patches, a patch name that isn't a plain +OpenFOAM word, and a region's name that can't be a directory on every system. Generated, written +over and kept as the `changeDictionaryDict`s are (`replace`, `region`: that region's, and the +shared one when its mesh runs `createPatch`; a problem in another region's doesn't stop it, +unless the two share `system/createPatchDict`). The case's own that holds what the description +can't (a patch it doesn't make or makes in two items, one made of a face set or of sources it +can't hold, an entry of `patchInfo` besides its `type`, such as a cyclic's `neighbourPatch`, or +another key of the item, a key given twice in an item or its `patchInfo` (OpenFOAM merges them), +a value given by a macro or directive, a `patches` list that can't be +read whole, another entry at its top, OpenFOAM-8's `pointSync` that isn't off) isn't written over, +even with `replace`: it is left as it is and noted, naming what would be lost, for +`workflow.patch` to give the patches their `from` and `type`, or for the file to be mended by +hand; the other dictionaries are written. + +The case check (`workflow.create-patch`) says when one is missing, doesn't load, was written by +umcfGui otherwise than it writes now, or is the case's own and makes the patches otherwise: a +patch not made there, made of a set or of other patches, of another type, one made there that +the description doesn't make, and the `patches` list or OpenFOAM-8's `pointSync` missing, which +`createPatch` stops without; and the case's own that makes the patches as the description does +but holds what it can't (as above). The sources are compared as `createPatch` takes them, their +union in any order (of both items, for a patch given twice); a name or type quoted or not is the same, and so is a source quoted that OpenFOAM +doesn't take for a pattern (`"defaultFaces"`: one without `. * + ? ( ) | [ ]` or a character a +word can't hold); what a macro or directive gives isn't compared (an item holding one is +compared by its name only). Where the case's own makes +what the description can't hold, it says to give the patches their `from` with `workflow.patch` +rather than to write it over. When the dictionaries can't be written from the description, it +says why. + On the three 3×3 cases (OpenFOAM-8 and -12) the dictionaries written from the imported -description map every patch as the cases' own do. On the street canyon with vegetation -(`streetCanyon_CFDHAM_veg`), `Allprepare` run with them makes the same meshes as with the -tutorial's own: byte for byte in OpenFOAM-8; in OpenFOAM-12 with `method nearest` added to the -air's and solids' pairs, and `Allrun` then gives the same fields. +description map every patch as the cases' own do, and make the same patches of the same ones. +On the street canyon with vegetation (`streetCanyon_CFDHAM_veg`), `Allprepare` run with the +generated dictionaries makes the same meshes as with the tutorial's own: byte for byte in +OpenFOAM-8; in OpenFOAM-12 byte for byte with the generated `createPatchDict`s, and with the +generated `changeDictionaryDict`s with `method nearest` added to the air's and solids' pairs, +after which `Allrun` gives the same fields. ## The workflow description @@ -235,7 +291,7 @@ each patch with its role and partner, the radiation pre-processing and the solve first piece of [the common workflow](../common-workflow.md): the scripts are written from it (`workflow.scripts`, [above](#writing-the-scripts)), and so are the dictionaries that only carry names and types (`workflow.dictionaries`, [above](#writing-the-dictionaries); so far each -region's `changeDictionaryDict`). +region's `changeDictionaryDict` and the `createPatchDict`s). ```c++ version 12; @@ -297,6 +353,8 @@ settings | `steps` | after the mesh: `createPatch`, `changeDictionary`, `topoSet` (or `setSet "batch"` in OpenFOAM-8), `setFields` with the fields it restores from their backups first | | `role` | `inlet`, `outlet`, `side`, `top`, `ground`, `coupled`, `canopy`, `interior`, `bottom`, `sky` | | `partner` | the region and patch a coupled patch is mapped to | +| `from` | the patches `createPatch` makes the patch of, as its dictionary has them: a bare name one patch (`( defaultFaces )`), a quoted one a pattern (`( "region1_to_.*" )`), without quotes, backslashes or spaces inside; in the [`createPatchDict`](#the-createpatchdicts) its region's mesh or steps read. A patch another of its region is made of (by name) isn't renamed with `workflow.patch` (refused: change the `from` first) | +| `type` | the type `createPatch` makes it of where its role doesn't give it (`wall` for a plain wall without a partner, as the street canyons' `buildings`); read only with `from`; not a mapped type, which `changeDictionary` gives from the role and partner. | | `materials` | a solid region's materials, in the order of its `buildingMaterials`: each the name of the cell zone built of it, with its `model` (`buildingMaterialModel`); the coefficients stay in the region's `transportProperties` | | `radiation` | the region the view factors and solar ray tracing are computed on, and the one `calcLAI` runs on | | `settings` | the [settings](#settings) the case chose; one that isn't there is the default | @@ -329,7 +387,7 @@ directory, or over the size limit), or one the open case doesn't hold (written o nothing: the save would write the file it points to); with `replace` it writes over the case's own, whose comments and hand edits are not kept (`edit.undo` brings them back). In the desktop app, both commands show in the results card the problems and the import's notes first, then the settings -(version, radiation, components, solver), then the regions with their meshes, steps, patch roles and +(version, radiation, components, solver), then the regions with their meshes, steps, patch roles (with what a patch is made of and its type) and materials. The case check reads the file against the case (`workflow.description`): what can't be read in it, regions and patches the case doesn't have or it leaves out, other kinds, partners that aren't there, a @@ -337,6 +395,17 @@ solid's materials the case doesn't list (or lists with another model), a model t doesn't have for the case's version (one the case's file has too is the case check's to say), materials of the case it leaves out, and another OpenFOAM version. +The import reads the `createPatchDict` each region's `createPatch` reads (its own when its steps +run it, else `system/createPatchDict` when its mesh does): each patch made of others +(`constructFrom patches`) gets their names as its `from`, and its type as `type` where its role +wouldn't give that one (a patch the region doesn't have is added without a role). One made of a +face set, whose name or sources aren't plain (a pattern with a backslash, a quote or a space +inside), part of which a macro or directive gives, with other keys or a key given twice, or whose `patchInfo` isn't a +dictionary or holds more than a plain type (a mapped or cyclic patch's entries), is noted and +left out (the first 20 of a dictionary, +then a count, for each region reading it); a patch given in two items is made of both items' sources. A region whose mesh +and steps both run `createPatch` is noted: only its own dictionary is read. + ### Blocks @@ -1161,7 +1230,7 @@ its comments kept. | Command | What | |---|---| | `workflow.region` | `region` with `kind` (`fluid`, `solid` or `vegetation`) adds the region or gives it that kind (an empty `materials { }` goes when a solid becomes another kind); with `remove: true` it is taken out, and what still names it (coupled patches, regions meshed from its [background](#background), the radiation) is listed. A solid with materials stays one | -| `workflow.patch` | `region`, `patch` and any of `role`, `partner` (`{"region": "street", "patch": "top"}`) and `name`. `null` takes a role or partner away; a patch the region doesn't list is added. A new name is followed by the region's [blocks](#blocks) and the partners that named the patch (its own too, when it is coupled to itself, unless the same call sets or takes away its partner) | +| `workflow.patch` | `region`, `patch` and any of `role`, `partner` (`{"region": "street", "patch": "top"}`), `from` (`["defaultFaces"]`: names, and patterns, a name that isn't a plain word quoted for it, `"\"region.1\""` given quoted; none with a quote, backslash or space inside), `type` (not a mapped one; only with `from`, which isn't taken away while it is there) and `name`. `null` takes a role, partner, `from` or `type` away; a patch the region doesn't list is added. A new name is followed by the region's [blocks](#blocks) and the partners that named the patch (its own too, when it is coupled to itself, unless the same call sets or takes away its partner) | | `workflow.material` | `region` (a solid), `material` (the name of its cell zone) and `model` (its `buildingMaterialModel`, or `null`), or `remove: true` | ```sh @@ -1188,13 +1257,14 @@ materials, the partner region's patches, the solver's material models for the ca (the patch card starts on the description's first region, the material card on its first solid). Choosing what it describes fills in what the description says of it (a region's kind, a patch's -role and partner, a material's model; a name the description doesn't have keeps what was -typed for it, and clears what another's filled in), and only what is changed from that is sent: a role, partner or model emptied is taken +role, partner, *Made of* (its `from`, apart by spaces) and type, a material's model; a name the description doesn't have keeps what was +typed for it, and clears what another's filled in), and only what is changed from that is sent: a role, partner, *Made of*, type or model emptied is taken away (`null`). A region's kind is sent as chosen. After another command or an undo, what wasn't -typed follows the description. A patch is added with a role or a partner (a patch without either +typed follows the description. A patch is added with a role, a partner or *Made of* (a type only with *Made of*; a patch without any goes through *Edit as JSON*: `"role": null`, sent as given). *Back to the form* fills the form again from what the JSON names, as the description has it then, with the JSON over it; a value a field can't hold (a name that isn't text) is kept and sent as it is, for the command to refuse. *Write workflow description* and *Write the scripts* are forms of their *replace* checkbox; *Write the dictionaries* has the -region (left to choose: every region) and *replace*. +region (left to choose: every region whose steps run `changeDictionary`, or whose mesh or steps +run `createPatch`) and *replace*. From 21f0aa12b0b1c0493aec4121873a567a86196fef Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Fri, 27 Nov 2026 09:51:22 +0100 Subject: [PATCH 2/6] M0.101: createPatch's order, counted lists, switches and bounded checks (review) --- ROADMAP.md | 2 +- crates/engine/src/cmd/workflow.rs | 32 ++- crates/engine/src/tests.rs | 11 +- crates/model/src/create_patch.rs | 217 +++++++++++++++++++-- crates/model/src/create_patch_tests.rs | 169 +++++++++++++++- crates/model/src/description.rs | 94 +++++++-- crates/model/src/description_edit.rs | 13 +- crates/model/src/description_edit_tests.rs | 6 + crates/model/src/description_tests.rs | 36 ++++ crates/model/tests/coupling.rs | 5 +- crates/ui-egui/src/forms.rs | 2 +- crates/ui-egui/src/tests.rs | 12 ++ crates/ui-egui/src/workflowcard.rs | 5 +- crates/validate/src/description.rs | 5 +- docs/common-workflow.md | 4 +- docs/user-guide/checks.md | 2 +- docs/user-guide/command-line.md | 2 +- docs/user-guide/workflow.md | 37 ++-- 18 files changed, 589 insertions(+), 65 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 281c051..c3e0136 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -124,4 +124,4 @@ Ranked work list: [`docs/gaps.md`](docs/gaps.md). - 2026-11-24 — M0.98 a background mesh kept between regions (gaps row 6, 4 of 4 parts; the row is closed): a region's mesh can start with `background ` instead of `blockMesh` (`model::workflow::RootStep::Background`), as the `windAroundBuildings` tutorials mesh the vegetation from the air's background. `Allprepare` keeps what that region's `blockMesh` made in `constant/polyMesh.background.`, marked as its own (`.umcfgui-kept`; one there without the mark stops it, nothing removed), copies it into `constant/polyMesh` for each region meshed from it and removes it after the last (`Allclean` removes a marked one); a region it can't be kept from (not listed before it, not built by steps of its own starting with `blockMesh`) is refused by `workflow.scripts` and named by the case check (`workflow.blocks`), with blocks of its own its mesh doesn't read. The script reader takes the kept copy back where the mesh it was kept from is moved to its region with `mv` (the generated scripts; any `constant/polyMesh.*` directory, as the tutorials' `polyMesh.bckp`), and lists a copy no region is meshed from or one removed before it is used. The case check (`workflow.snappy`) also checks a region's inside point against the blocks as they are now. `mesh.snappy` takes `background` (a region, or `null` for its own `blockMesh` again) and checks the inside point and the surfaces against that region's blocks; the *Snappy mesh* card has *Background from*, offering the regions it can start from, and previews and checks their blocks. - 2026-11-24 — M0.99 a script's words bounded (review of M0.98): a word longer than 64 KiB once expanded is cut there and marked unresolved (a long literal was kept whole), and a script's reading stops after 64 MiB of expanded words (`script::MAX_EXPANDED`, each word charged 64 bytes more, as it is expanded), so neither a command of many long words nor a loop repeating long or empty ones builds steps without end; the prefixes before a command (`time`, `nohup`, …) are taken off at once. - 2026-11-24 — M0.100 each region's `changeDictionaryDict` from the description (gaps row 4, 1 of 6 parts): `workflow.dictionaries` (*Write the dictionaries*, a form) writes it for every region whose steps run `changeDictionary`, from the patches' roles and partners (`model::coupling`): a wall with a partner `mappedWall`, an open side `mapped` (`mappedPatch` in OpenFOAM-8), the vegetation's canopy the air's cells (`mappedInternal`; OpenFOAM-8 `mappedWall` with `sampleMode nearestCell`), OpenFOAM-12's `neighbourRegion`/`neighbourPatch` or OpenFOAM-8's `sampleRegion`/`samplePatch`, a fluid's and a solid's patches paired by `method nearest`; generated with a checksum, one edited by hand written over only with `replace`. Refused for a partner without a role, and for a name that isn't a plain OpenFOAM word or a region's that can't be a directory on every system. The case check `workflow.change-dictionary` says a missing, stale or differing one, by the keys each version reads, and a sample mode or method the version hasn't. `workflow.import` gives a vegetation patch mapped to its twin whose role isn't told the role `coupled` (a `mappedWall`) or `sky` (`mapped`, `mappedPatch`). The 15 dictionaries of the three 3×3 cases (OpenFOAM-8 and -12) are generated as the cases' own map them; on the street canyon with vegetation `Allprepare` makes the same meshes (OpenFOAM-8 byte for byte, OpenFOAM-12 with `method nearest` added) and `Allrun` the same fields. -- 2026-11-26 — M0.101 the `createPatchDict`s from the description (gaps row 4, 2 of 6 parts): a patch's `from` in `system/umcfWorkflow` names the patches `createPatch` makes it of (`( defaultFaces )`; a quoted name is a pattern, `( "region1_to_.*" )`), and its `type` the type where its role doesn't give it (the street canyons' plain `buildings` wall). `workflow.dictionaries` writes `system//createPatchDict` for a region whose steps run `createPatch`, and `system/createPatchDict` for the regions meshed with it in `constant/polyMesh` (which must make the same patches), each patch typed by its own type, else `wall` for a wall's role, the canopy and every solid's patch, else `patch`; `pointSync false;` for OpenFOAM-8. `workflow.import` reads `from` and `type` from the case's `createPatchDict`s (a source as written: quoted, a pattern), `workflow.dictionaries` leaves a case's own that holds what the description can't as it is, noted, even with `replace`, `workflow.patch` (*Describe a patch*: *Made of*, *Type*) edits them, and the case check `workflow.create-patch` says a dictionary missing, stale or making the patches otherwise (`model::create_patch`). The 16 `createPatchDict`s of the four 3×3 cases are generated as the cases' own make them; on the street canyon with vegetation `Allprepare` with the generated ones makes the same meshes, byte for byte, in OpenFOAM-8 and -12. +- 2026-11-26 — M0.101 the `createPatchDict`s from the description (gaps row 4, 2 of 6 parts): a patch's `from` in `system/umcfWorkflow` names the patches `createPatch` makes it of (`( defaultFaces )`; a quoted source is a pattern when it holds a regular expression's characters, `( "region1_to_.*" )`, else the name it holds, `"defaultFaces"` as `defaultFaces`), and its `type` the type over the one its role gives (the street canyons' plain `buildings` wall). `workflow.dictionaries` writes `system//createPatchDict` for a region whose steps run `createPatch`, and `system/createPatchDict` for the regions meshed with it in `constant/polyMesh` (which must make the same patches), each patch typed by its own type, else `wall` for a wall's role, the canopy and every solid's patch, else `patch`, in the order the region lists them (`createPatch` gives a face two patches take to the last; the import keeps the dictionary's); `pointSync false;` for OpenFOAM-8. `workflow.import` reads `from` and `type` from the case's `createPatchDict`s (a source as written: quoted, a pattern or the name it holds), `workflow.dictionaries` leaves a case's own that holds what the description can't as it is, noted, even with `replace`, `workflow.patch` (*Describe a patch*: *Made of*, *Type*) edits them, and the case check `workflow.create-patch` says a dictionary missing, stale or making the patches otherwise (`model::create_patch`). The 16 `createPatchDict`s of the four 3×3 cases are generated as the cases' own make them; on the street canyon with vegetation `Allprepare` with the generated ones makes the same meshes, byte for byte, in OpenFOAM-8 and -12. diff --git a/crates/engine/src/cmd/workflow.rs b/crates/engine/src/cmd/workflow.rs index b2dd43b..717dcc0 100644 --- a/crates/engine/src/cmd/workflow.rs +++ b/crates/engine/src/cmd/workflow.rs @@ -115,7 +115,7 @@ pub(super) const IMPORT: CommandSpec = CommandSpec { label: "Write workflow description", menu: "Case/Write workflow description", shortcut: None, - params: "replace: true to write over the case's system/umcfWorkflow (its comments and hand edits are not kept). Writes the workflow description from the case: its scripts (Allprepare, Allrun) read into the workflow, the region kinds, each patch's role and partner as its mesh and velocity condition tell, each solid's materials as its constant//transportProperties lists them (buildingMaterials), and the components the case's files switch on (a fluid's grassProperties whose grassModel isn't none and grass isn't off, a limitTemperature entry in the file a fluid's limit is read from (OpenFOAM-12: system/fvConstraints, else system/fvOptions, else constant/fvOptions; OpenFOAM-8: constant/fvOptions, else system/fvOptions), blending on in controlDict), and the settings its files have (deltaT, endTime, writeInterval, the fluids' RAS model, the temperature limit's bounds, blendingCoeffs: a macro, or fluids that differ, noted and left out), each region's grid of blocks read from the blockMeshDict its mesh reads, when that is one (all its blocks one cell each of a grid of stations along x, y and z, each span's cells and grading the same in every block; a dictionary that isn't one, with curved edges, a block over several cells, a scale, an #include or a $macro, is left out with a note; each patch whose type there isn't the one its role (or no role: patch) gives kept in the blocks' types; a region without a mesh given the patches its blocks name, without a role; the dictionary isn't written: mesh.block writes it from the blocks), each region's snappy entry read from the snappyHexMeshDict its snappyHexMesh step reads (its STL surfaces that cut or refine by distance, with the solids of the _ patches each made in the mesh, boxes refining the cells inside, feature levels, layers, the inside point, the expansion ratio and the first layer's thickness; the inside point as the case's version takes it (OpenFOAM-12: insidePoints of one point, insidePoint, locationInMesh; OpenFOAM-8: locationInMesh); what the entry can't hold noted and left out: other geometry, a surface or box it would refuse (the others kept), a scaled surface, a surface making a faceZone or cellZone (its refinement alone kept), layer sizes other than the entry's, an expansion below 1, a patch type other than its role's (each _ patch against its own), patchInfo beyond its type (inGroups), singleRegionName false, an expansionRatio that isn't a number, a name given to more than one surface or box, layers given to a surface by a _ patch's name, levels per solid, surfaces and layers named by a pattern, a patch's own layer settings, outside points, an #include or $macro not followed, macros; several inside points give no entry; the dictionary isn't written: mesh.snappy with replace writes it from the entry), and the material library from the solids' materials (each model's first material whose coefficients are numbers or dictionaries of them; a model whose materials differ noted once, a material with a macro or directive among its coefficients noted and left out). What it couldn't tell (a patch without a role, a region the scripts don't mesh, a step that doesn't fit, a material or its model given by a macro, a material listed more than once) is listed in notes. case.save writes it. A system/umcfWorkflow that is a symbolic link is not written over. Also reads, from the createPatchDict each region's createPatch reads (its own when its steps run createPatch, else system/createPatchDict when its mesh does), the patches made of others (constructFrom patches) into their from, as written (a quoted source a pattern), and their type where the role wouldn't give it; a name given twice is made of both items' sources; an item made of a face set, part of which a macro or directive gives, with a patchInfo that isn't a plain type's dictionary, other keys, a key given twice, or sources with a quote, backslash or space inside is noted and left out (20 notes a dictionary for each region reading it, then a count).", + params: "replace: true to write over the case's system/umcfWorkflow (its comments and hand edits are not kept). Writes the workflow description from the case: its scripts (Allprepare, Allrun) read into the workflow, the region kinds, each patch's role and partner as its mesh and velocity condition tell, each solid's materials as its constant//transportProperties lists them (buildingMaterials), and the components the case's files switch on (a fluid's grassProperties whose grassModel isn't none and grass isn't off, a limitTemperature entry in the file a fluid's limit is read from (OpenFOAM-12: system/fvConstraints, else system/fvOptions, else constant/fvOptions; OpenFOAM-8: constant/fvOptions, else system/fvOptions), blending on in controlDict), and the settings its files have (deltaT, endTime, writeInterval, the fluids' RAS model, the temperature limit's bounds, blendingCoeffs: a macro, or fluids that differ, noted and left out), each region's grid of blocks read from the blockMeshDict its mesh reads, when that is one (all its blocks one cell each of a grid of stations along x, y and z, each span's cells and grading the same in every block; a dictionary that isn't one, with curved edges, a block over several cells, a scale, an #include or a $macro, is left out with a note; each patch whose type there isn't the one its role (or no role: patch) gives kept in the blocks' types; a region without a mesh given the patches its blocks name, without a role; the dictionary isn't written: mesh.block writes it from the blocks), each region's snappy entry read from the snappyHexMeshDict its snappyHexMesh step reads (its STL surfaces that cut or refine by distance, with the solids of the _ patches each made in the mesh, boxes refining the cells inside, feature levels, layers, the inside point, the expansion ratio and the first layer's thickness; the inside point as the case's version takes it (OpenFOAM-12: insidePoints of one point, insidePoint, locationInMesh; OpenFOAM-8: locationInMesh); what the entry can't hold noted and left out: other geometry, a surface or box it would refuse (the others kept), a scaled surface, a surface making a faceZone or cellZone (its refinement alone kept), layer sizes other than the entry's, an expansion below 1, a patch type other than its role's (each _ patch against its own), patchInfo beyond its type (inGroups), singleRegionName false, an expansionRatio that isn't a number, a name given to more than one surface or box, layers given to a surface by a _ patch's name, levels per solid, surfaces and layers named by a pattern, a patch's own layer settings, outside points, an #include or $macro not followed, macros; several inside points give no entry; the dictionary isn't written: mesh.snappy with replace writes it from the entry), and the material library from the solids' materials (each model's first material whose coefficients are numbers or dictionaries of them; a model whose materials differ noted once, a material with a macro or directive among its coefficients noted and left out). What it couldn't tell (a patch without a role, a region the scripts don't mesh, a step that doesn't fit, a material or its model given by a macro, a material listed more than once) is listed in notes. case.save writes it. A system/umcfWorkflow that is a symbolic link is not written over. Also reads, from the createPatchDict each region's createPatch reads (its own when its steps run createPatch, else system/createPatchDict when its mesh does), the patches made of others (constructFrom patches) into their from, as written (a quoted source a pattern), and their type where the role wouldn't give it; a name given twice is made of both items' sources (noted when it comes again after a patch whose sources may overlap); the patches made keep the dictionary's order among the region's patches; an item made of a face set, part of which a macro or directive gives, with a patchInfo that isn't a plain type's dictionary, other keys, a key given twice, or sources with a quote, backslash, brace or space inside or a pattern that may not compile is noted and left out (20 notes a dictionary for each region reading it, then a count).", enabled: needs_case, run: import, journal: true, @@ -215,12 +215,15 @@ fn region(s: &mut Session, p: &Value) -> Result { edited(s, message, &report) } +/// The most patches a patch is made of (from), as workflow.patch takes them. +const MAX_FROM: usize = 64; + pub(super) const PATCH: CommandSpec = CommandSpec { id: "workflow.patch", label: "Describe a patch", menu: "Case/Workflow/Describe a patch", shortcut: None, - params: "region, patch: the region of system/umcfWorkflow and its patch (a patch the region doesn't list is added); role: inlet, outlet, side, top, ground, coupled, canopy, interior, bottom or sky (null takes it away); partner: {\"region\", \"patch\"} it is coupled to (null takes it away); from: the patches createPatch makes it of, a list of names and patterns as createPatch reads them (a name that isn't a plain word is quoted for it, a pattern: \"region1_to_.*\"; one given quoted stays so, \"\\\"region.1\\\"\" a regular expression; none with a quote, backslash or space inside; null takes them away), which workflow.dictionaries writes into the createPatchDict its mesh or steps read; type: the type createPatch makes it of where its role doesn't give it (wall for a plain wall without a partner; read only with from, refused without; null takes it away; not a mapped type, which changeDictionary gives from the role and partner); name: a new name for the patch (refused while another patch of the region is made of it, from; the partners that named it follow, and the region's blocks: sides, single faces, patches without faces, types; refused while the region's blocks entry doesn't read whole, or when the blocks name a patch of the new name, or to or from defaultFaces while the region has blocks: the faces left to blockMesh). At least one of them. Edits the description only, entry by entry: its comments and layout stay. The case's own files (the mesh, fields, dictionaries) follow once they are written from it; patch.set renames a patch in the case.", + params: "region, patch: the region of system/umcfWorkflow and its patch (a patch the region doesn't list is added); role: inlet, outlet, side, top, ground, coupled, canopy, interior, bottom or sky (null takes it away); partner: {\"region\", \"patch\"} it is coupled to (null takes it away); from: the patches createPatch makes it of, a list of names and patterns as createPatch reads them (a name that isn't a plain word is quoted for it, a pattern: \"region1_to_.*\"; one given quoted stays so, \"\\\"region.1\\\"\" a regular expression; none with a quote, backslash, brace or space inside, nor a pattern that may not compile (an unclosed bracket or group, a repeat with nothing before it, a group starting (? other than a leading (?i), OpenFOAM's case ignored; at most 64; null takes them away), which workflow.dictionaries writes into the createPatchDict its mesh or steps read; type: the type createPatch makes it of, over the one its role gives (wall for a plain wall without a partner; read only with from, refused without; null takes it away; not a mapped type, which changeDictionary gives from the role and partner); name: a new name for the patch (refused while another patch of the region is made of it, from; the partners that named it follow, and the region's blocks: sides, single faces, patches without faces, types; refused while the region's blocks entry doesn't read whole, or when the blocks name a patch of the new name, or to or from defaultFaces while the region has blocks: the faces left to blockMesh). At least one of them. Edits the description only, entry by entry: its comments and layout stay. The case's own files (the mesh, fields, dictionaries) follow once they are written from it; patch.set renames a patch in the case.", enabled: needs_case, run: patch, journal: true, @@ -265,6 +268,9 @@ fn patch(s: &mut Session, p: &Value) -> Result { match p.value("from") { None => {} Some(Value::Null) => edit.from = Some(Vec::new()), + Some(Value::Array(items)) if items.len() > MAX_FROM => { + return Err(Error::Params(format!("{}: from names more than {MAX_FROM} patches", PATCH.id))); + } Some(Value::Array(items)) if !items.is_empty() => { let names: Option> = items.iter().map(|v| v.as_str().map(str::to_string)).collect(); match names { @@ -778,7 +784,7 @@ pub(super) const DICTIONARIES: CommandSpec = CommandSpec { label: "Write the dictionaries", menu: "Case/Workflow/Write the dictionaries", shortcut: None, - params: "region: one region (default: every region). replace: true to write over a dictionary edited by hand or not written by umcfGui (case.save keeps a backup of each). Writes, from system/umcfWorkflow and for its OpenFOAM version (the case's when it names none), each region's system//changeDictionaryDict whose steps run changeDictionary: every patch with a partner, mappedWall to it when its role is a wall's (ground, coupled, interior, bottom) and mapped (mappedPatch in OpenFOAM-8) when it is an open side's (inlet, outlet, side, top, sky), with neighbourRegion and neighbourPatch (OpenFOAM-8: sampleMode nearestPatchFace, sampleRegion, samplePatch) and a uniform offset of (0 0 0); a fluid's and a solid's patches paired by method nearest (OpenFOAM-12), a vegetation patch and its twin without; the vegetation region's canopy mapped to the air's cells (mappedInternal, offsetMode normal, distance 0; OpenFOAM-8: mappedWall, sampleMode nearestCell), the air being the fluid region its other patches are coupled to, else the radiation's lai region, else the only fluid region. Patches without a partner are left as the mesh makes them. Generated, with a checksum: one written by umcfGui and unchanged since is written over without replace. Refused, writing none: a description with problems (workflow.show lists them), a patch with a partner but no role, a partner region the description doesn't have, a canopy with a partner or with no air to map to, a region, patch or partner name that isn't a plain OpenFOAM word (they are written unquoted), a region's name that can't be a directory on every system (., .., a colon, a dot at its end, a Windows device's name), a region named that the description doesn't have, a dictionary there that doesn't load (or a directory: mend or remove it), one that is a symbolic link or the same file as another dictionary, and, without replace, one there that differs and wasn't written by umcfGui. Also writes each createPatchDict the mesh or steps read: system//createPatchDict for a region whose steps run createPatch, system/createPatchDict for the regions meshed with createPatch in constant/polyMesh (one for them all: they must make the same patches); each patch made of others (from) as { name; patchInfo { type; } constructFrom patches; patches ( … ); }, the sources as the description has them (a quoted one a pattern), its type the patch's own (type), else wall for a wall's role (ground, coupled, interior, bottom), the canopy and every solid's patch, else patch; pointSync false for OpenFOAM-8. Refused, too: a patch made by createPatch with neither a role nor a type, or in a region whose mesh and steps run no createPatch, a region running createPatch both in and after its mesh with patches to make, and regions sharing system/createPatchDict that make other patches. The case's own createPatchDict that holds what the description can't (a patch it doesn't make or gives twice, one made of a face set or of sources it can't hold, patchInfo entries besides the type or other keys of an item, a key given twice in an item or its patchInfo, a value from a macro or directive, a patches list that can't be read whole, another entry at its top, OpenFOAM-8's pointSync not off) is left as it is even with replace, noted with what would be lost; the others are written. With region, that region's dictionaries (and the shared createPatchDict when its mesh runs createPatch); a region whose mesh and steps run neither changeDictionary nor createPatch is refused. The outcome lists what was written, written over by hand edits, and left as it was, and notes a region with coupled patches whose steps don't run changeDictionary. case.save writes them; edit.undo takes them back.", + params: "region: one region (default: every region). replace: true to write over a dictionary edited by hand or not written by umcfGui (case.save keeps a backup of each). Writes, from system/umcfWorkflow and for its OpenFOAM version (the case's when it names none), each region's system//changeDictionaryDict whose steps run changeDictionary: every patch with a partner, mappedWall to it when its role is a wall's (ground, coupled, interior, bottom) and mapped (mappedPatch in OpenFOAM-8) when it is an open side's (inlet, outlet, side, top, sky), with neighbourRegion and neighbourPatch (OpenFOAM-8: sampleMode nearestPatchFace, sampleRegion, samplePatch) and a uniform offset of (0 0 0); a fluid's and a solid's patches paired by method nearest (OpenFOAM-12), a vegetation patch and its twin without; the vegetation region's canopy mapped to the air's cells (mappedInternal, offsetMode normal, distance 0; OpenFOAM-8: mappedWall, sampleMode nearestCell), the air being the fluid region its other patches are coupled to, else the radiation's lai region, else the only fluid region. Patches without a partner are left as the mesh makes them. Generated, with a checksum: one written by umcfGui and unchanged since is written over without replace. Refused, writing none: a description with problems (workflow.show lists them), a patch with a partner but no role, a partner region the description doesn't have, a canopy with a partner or with no air to map to, a region, patch or partner name that isn't a plain OpenFOAM word (they are written unquoted), a region's name that can't be a directory on every system (., .., a colon, a dot at its end, a Windows device's name), a region named that the description doesn't have, a dictionary there that doesn't load (or a directory: mend or remove it), one that is a symbolic link or the same file as another dictionary, and, without replace, one there that differs and wasn't written by umcfGui. Also writes each createPatchDict the mesh or steps read: system//createPatchDict for a region whose steps run createPatch, system/createPatchDict for the regions meshed with createPatch in constant/polyMesh (one for them all: they must make the same patches); each patch made of others (from) as { name; patchInfo { type; } constructFrom patches; patches ( … ); }, the sources as the description has them (a quoted one a pattern), its type the patch's own (type), else wall for a wall's role (ground, coupled, interior, bottom), the canopy and every solid's patch, else patch; pointSync false for OpenFOAM-8. Refused, too: a patch made by createPatch with neither a role nor a type, or in a region whose mesh and steps run no createPatch, a region running createPatch both in and after its mesh with patches to make, and regions sharing system/createPatchDict that make other patches, or make them in another order where their sources may overlap (the order is the regions' patches', which is createPatch's: a face two patches take goes to the last). The case's own createPatchDict that holds what the description can't (a patch it doesn't make or gives twice, one made of a face set or of sources it can't hold, patchInfo entries besides the type or other keys of an item, a key given twice in an item or its patchInfo, a value from a macro or directive, a patches list that can't be read whole, another entry at its top or in its FoamFile header, OpenFOAM-8's pointSync not off) is left as it is even with replace, noted with what would be lost; the others are written. With region, that region's dictionaries (and the shared createPatchDict when its mesh runs createPatch); a region whose mesh and steps run neither changeDictionary nor createPatch is refused. The outcome lists what was written, written over by hand edits, unchanged, and left as it is (left: holding what the description can't), and notes a region with coupled patches whose steps don't run changeDictionary. case.save writes them; edit.undo takes them back.", enabled: needs_case, run: dictionaries, journal: true, @@ -842,6 +848,8 @@ fn dictionaries(s: &mut Session, p: &Value) -> Result { // in constant/polyMesh, written when one of them is asked for. let targets = create_patch::targets(&d, only.as_deref()) .map_err(|e| Error::Failed(format!("{}: {e}: no dictionary is written", DICTIONARIES.id)))?; + // The createPatchDicts left as they are (what they hold the description can't). + let mut left: Vec = Vec::new(); for t in &targets { // The case's own holding what the description can't: never written over, even with // replace (it would be lost), but left as it is, noted (the others are written). @@ -855,6 +863,7 @@ fn dictionaries(s: &mut Session, p: &Value) -> Result { t.path, create_patch::summary(&kept) )); + left.push(t.path.clone()); continue; } } @@ -915,9 +924,12 @@ fn dictionaries(s: &mut Session, p: &Value) -> Result { })?; } let changed: Vec<&String> = written.iter().chain(&by_hand).collect(); - let left = notes.iter().filter(|n| n.contains("left as it is, as written over")).count(); - let message = if texts.is_empty() && left == 0 { + let message = if texts.is_empty() && left.is_empty() { format!("no region's mesh or steps in {PATH} run changeDictionary or createPatch: no dictionary to write") + } else if texts.is_empty() { + "nothing written".to_string() + } else if changed.is_empty() && !left.is_empty() { + format!("the others are as {PATH} has them already, for {version}: nothing written") } else if changed.is_empty() { format!("the dictionaries are as {PATH} has them already, for {version}: nothing to write") } else { @@ -926,17 +938,17 @@ fn dictionaries(s: &mut Session, p: &Value) -> Result { changed.iter().map(|x| x.as_str()).collect::>().join(", ") ) }; - let message = if left > 0 { + let message = if left.is_empty() { + message + } else { format!( "{message}; {} left as it is, holding what {PATH} doesn't (see the notes)", - count(left, "createPatchDict") + count(left.len(), "createPatchDict") ) - } else { - message }; Ok(Outcome::new( message, - json!({ "version": version.to_string(), "written": written, "replaced": by_hand, "unchanged": same, "notes": notes }), + json!({ "version": version.to_string(), "written": written, "replaced": by_hand, "unchanged": same, "left": left, "notes": notes }), )) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 12ef1c1..4a7061b 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -5283,6 +5283,15 @@ fn each_create_patch_dict_is_written_from_the_patches_made_of_others() { let before = std::fs::read_to_string(&hand).unwrap(); let out = s.execute("workflow.dictionaries", &json!({"replace": true})).unwrap(); assert!(out.message.contains("1 createPatchDict left as it is"), "{}", out.message); + // Left as it is isn't the same as described already. + assert!(!out.message.starts_with("the dictionaries are as"), "{}", out.message); + assert_eq!(out.data["left"], json!(["system/air/createPatchDict"]), "{}", out.data); + let many: Vec = (0..65).map(|i| format!("p{i}")).collect(); + let e = s + .execute("workflow.patch", &json!({"region": "air", "patch": "buildings", "from": many})) + .unwrap_err() + .to_string(); + assert!(e.contains("from names more than 64 patches"), "{e}"); assert!( out.data["notes"].as_array().unwrap().iter().any(|n| n.as_str().unwrap().contains( "system/air/createPatchDict holds what system/umcfWorkflow doesn't (patch cyc): left as it is" @@ -5308,7 +5317,7 @@ fn each_create_patch_dict_is_written_from_the_patches_made_of_others() { s.execute("case.open", &json!({ "path": dir.to_str().unwrap(), "discard": true })).unwrap(); let more = said(&mut s); assert!( - more.len() == 1 && more[0].contains("makes the patches as the description of region air does, but holds what it can't (its writeCyclicMatch)"), + more.len() == 1 && more[0].contains("shows no difference from the patches the description of region air makes (what a macro or directive gives isn't compared), but holds what it can't (its writeCyclicMatch)"), "{more:?}" ); std::fs::write(&hand, fresh).unwrap(); diff --git a/crates/model/src/create_patch.rs b/crates/model/src/create_patch.rs index 40ecf20..19ae66e 100644 --- a/crates/model/src/create_patch.rs +++ b/crates/model/src/create_patch.rs @@ -154,6 +154,14 @@ pub fn targets(d: &Description, only: Option<&str>) -> Result, Strin t.regions[0], r.name )); } + let at: HashMap<&str, usize> = + made.iter().enumerate().map(|(i, m)| (m.patch.as_str(), i)).collect(); + if let Some((a, b)) = out_of_order(&t.made, &at) { + return Err(format!( + "regions {} and {} are meshed in constant/polyMesh with createPatch, which reads system/createPatchDict for both: they make {a} and {b}, whose sources may overlap, in another order (createPatch gives a face to the last that takes it): list them in the same order", + t.regions[0], r.name + )); + } t.regions.push(r.name.clone()); } } @@ -282,9 +290,12 @@ fn items(root: &Dict) -> Result>, String> { Err("it has no patches list, without which createPatch stops".into()) }; }; - let items = match list.value.as_slice() { - [Node::List { items, .. }] => items, - [Node::Atom(t)] if untold(&t.text) => return Ok(None), + let items = match (listed(&list.value), list.value.as_slice()) { + (Some(items), _) => items, + (None, [Node::Atom(t)]) if untold(&t.text) => return Ok(None), + (None, [Node::Atom(_), Node::List { .. }]) => { + return Err("its patches list's count isn't the number of its items, at which OpenFOAM stops".into()); + } _ => return Err("its patches isn't a list of dictionaries".into()), }; let one = |d: &Dict, k: &str| match d.get(k).map(|e| e.value.as_slice()) { @@ -322,15 +333,15 @@ fn items(root: &Dict) -> Result>, String> { .filter(|k| !matches!(k.as_str(), "name" | "patchInfo" | "constructFrom" | "patches" | "set")) .collect(); let told = whole(d); - let from = match d.get("patches").map(|e| e.value.as_slice()) { - Some([Node::List { items, .. }]) => items + let from = match d.get("patches").and_then(|e| listed(&e.value)) { + Some(items) => items .iter() .map(|n| match n { Node::Atom(t) => Some(t.text.clone()), _ => None, }) .collect(), - _ => None, + None => None, }; let kind = info_dict.and_then(|p| one(p, "type")); let info = info_dict @@ -378,6 +389,56 @@ fn source_set(from: &[String]) -> Vec { v } +/// The most patches made whose order is compared, two by two, and the most source lookups +/// that takes: what a hostile file can't make slow (a description has far fewer). +pub(crate) const MAX_ORDERED: usize = 256; +const ORDER_BUDGET: usize = 1 << 20; + +/// Two of `made` whose sources may take the same faces (a source both name, or a pattern in +/// either, which may match what the other names) and whose order `at` (a patch's place +/// elsewhere) has the other way round: `createPatch` gives a face to the last patch taking it, so +/// their order decides where the faces they share go. Patches `at` doesn't place aren't +/// compared; the first [`MAX_ORDERED`] are, within [`ORDER_BUDGET`] lookups. +fn out_of_order<'a>(made: &'a [Made], at: &HashMap<&str, usize>) -> Option<(&'a str, &'a str)> { + let placed: Vec<(&Made, usize, HashSet, bool)> = made + .iter() + .take(MAX_ORDERED) + .filter_map(|m| { + let p = at.get(m.patch.as_str())?; + let set: HashSet = m.from.iter().map(|f| normal(f)).collect(); + let pattern = set.iter().any(|s| s.starts_with('"')); + Some((m, *p, set, pattern)) + }) + .collect(); + let mut budget = ORDER_BUDGET; + for (i, (a, pa, sa, qa)) in placed.iter().enumerate() { + for (b, pb, sb, qb) in placed.iter().skip(i + 1) { + if pb >= pa { + continue; + } + if *qa || *qb { + return Some((&a.patch, &b.patch)); + } + let (small, big) = if sa.len() < sb.len() { (sa, sb) } else { (sb, sa) }; + budget = budget.checked_sub(small.len().max(1))?; + if small.iter().any(|f| big.contains(f)) { + return Some((&a.patch, &b.patch)); + } + } + } + None +} + +/// A list as OpenFOAM reads one: `( … )`, or with its count first (`2 ( … )`), the count the +/// items'. `None`: neither. +pub(crate) fn listed(values: &[Node]) -> Option<&[Node]> { + match values { + [Node::List { items, .. }] => Some(items), + [Node::Atom(n), Node::List { items, .. }] if n.text.parse::().ok() == Some(items.len()) => Some(items), + _ => None, + } +} + /// How a `createPatchDict` (`root`, the file's top level) differs from the patches `made`, for /// `version`: a patch not made there, made of a set or of other patches (in any order: their /// union), of what isn't a list of names, of another type, one made there the description @@ -389,8 +450,20 @@ fn source_set(from: &[String]) -> Vec { pub fn differences(root: &Dict, made: &[Made], version: OfVersion) -> Vec { let mut out = Vec::new(); let directives = root.items.iter().any(|i| matches!(i, Item::Directive { .. } | Item::Macro { .. })); - if version == OfVersion::V8 && root.get("pointSync").is_none() && !directives { - out.push("it has no pointSync, without which OpenFOAM-8's createPatch stops".to_string()); + if version == OfVersion::V8 { + match root.get("pointSync").map(|e| e.value.as_slice()) { + None if !directives => { + out.push("it has no pointSync, without which OpenFOAM-8's createPatch stops".to_string()); + } + None => {} + // A word or a number: a quoted string isn't a switch to OpenFOAM-8. + Some([Node::Atom(t)]) + if untold(&t.text) || (!t.text.starts_with('"') && umcf_foam_dict::switch(&t.text).is_some()) => {} + Some(v) if holds_untold(v) => {} + Some(_) => out.push( + "its pointSync isn't a switch (true or false), at which OpenFOAM-8's createPatch stops".to_string(), + ), + } } let there = match items(root) { Ok(Some(t)) => t, @@ -474,12 +547,32 @@ pub fn differences(root: &Dict, made: &[Made], version: OfVersion) -> Vec { + out.push(format!("patch {}: type is {} there, the description makes it {}", m.patch, cut(k), m.kind)); + } + Some(_) => {} + None => out.push(format!( + "patch {} has no type there (patchInfo), which createPatch needs for a new patch; the description makes it {}", + m.patch, m.kind + )), + } + } + // The order: where two patches' sources may overlap, the last takes the faces they share. + // A name given twice is compared by its first item and by its last. + let mut first_at: HashMap<&str, usize> = HashMap::with_capacity(there.len()); + let mut last_at: HashMap<&str, usize> = HashMap::with_capacity(there.len()); + for (i, t) in there.iter().enumerate() { + if let Some(n) = t.name.as_deref() { + first_at.entry(n).or_insert(i); + last_at.insert(n, i); } } + if let Some((a, b)) = out_of_order(made, &first_at).or_else(|| out_of_order(made, &last_at)) { + out.push(format!( + "patches {a} and {b}, whose sources may overlap, are made in the other order there, or one is given again around the other (createPatch gives a face to the last that takes it)" + )); + } let mut said: HashSet<&str> = HashSet::new(); for t in &there { if let Some(n) = &t.name @@ -514,11 +607,27 @@ pub fn kept(root: &Dict, made: &[Made], version: OfVersion) -> Vec { } for e in root.entries() { match e.key() { - "FoamFile" | "patches" => {} + "FoamFile" => match e.dict() { + Some(h) => { + for k in h.entries().map(|x| x.key()) { + if !matches!(k, "version" | "format" | "class" | "location" | "object") { + out.push(format!("its FoamFile {}", cut(k))); + if out.len() > 2 * MAX_KEPT { + break; + } + } + } + if h.items.iter().any(|i| !matches!(i, Item::Entry(_))) { + out.push("its FoamFile's macro or directive".to_string()); + } + } + None => out.push("its FoamFile, which isn't a dictionary".to_string()), + }, + "patches" => {} "pointSync" if version == OfVersion::V12 => {} "pointSync" => { let off = match e.value.as_slice() { - [Node::Atom(t)] => umcf_foam_dict::switch(&t.text) == Some(false), + [Node::Atom(t)] => !t.text.starts_with('"') && umcf_foam_dict::switch(&t.text) == Some(false), _ => false, }; if !off { @@ -527,6 +636,11 @@ pub fn kept(root: &Dict, made: &[Made], version: OfVersion) -> Vec { } k => out.push(format!("its {}", cut(k))), } + if out.len() > 2 * MAX_KEPT { + out.truncate(MAX_KEPT); + out.push("and more".to_string()); + return out; + } } let there = match items(root) { Ok(Some(t)) => t, @@ -611,12 +725,85 @@ pub fn source_ok(t: &str) -> bool { t.len() >= 2 && !inner.is_empty() && inner.len() <= 255 - && !inner.chars().any(|c| c.is_control() || c.is_whitespace() || matches!(c, '"' | '\\')) + && !inner.chars().any(|c| c.is_control() || c.is_whitespace() || matches!(c, '"' | '\\' | '{' | '}')) + && (!pattern(inner) || regex_ok(inner)) } None => false, } } +/// Whether `re` is a regular expression OpenFOAM compiles, as far as can be told without its +/// regex library (POSIX extended, `regcomp` with `REG_EXTENDED`, in OpenFOAM-8 and -12): brackets +/// closed and not empty, no bracket inside one, ranges upward, groups closed and not starting +/// `(?`, a repeat (`* + ?`) only after what it repeats. Stricter than both, never looser: +/// what may not compile is refused. +fn regex_ok(re: &str) -> bool { + // A leading `(?i)` is OpenFOAM's: case ignored, the rest compiled. + let re = match re.strip_prefix("(?i)") { + Some("") => return false, + Some(rest) => rest, + None => re, + }; + let mut depth = 0usize; + // Whether what came last can be repeated. + let mut atom = false; + let mut chars = re.chars().peekable(); + while let Some(c) = chars.next() { + match c { + '[' => { + if chars.peek() == Some(&'^') { + chars.next(); + } + let mut class: Vec = Vec::new(); + loop { + match chars.next() { + None | Some('[') => return false, + Some(']') => break, + Some(x) => class.push(x), + } + } + if class.is_empty() { + return false; + } + let mut i = 1; + while i + 1 < class.len() { + // Upward, and not chained (`a-c-e`, which POSIX leaves undefined). + if class.get(i) == Some(&'-') + && (class.get(i - 1) > class.get(i + 1) || class.get(i + 2) == Some(&'-')) + { + return false; + } + i += 1; + } + atom = true; + } + ']' => return false, + '(' => { + if chars.peek() == Some(&'?') { + return false; + } + depth += 1; + atom = false; + } + ')' => { + let Some(d) = depth.checked_sub(1) else { return false }; + depth = d; + atom = true; + } + '|' => atom = false, + '*' | '+' | '?' => { + if !atom { + return false; + } + atom = false; + } + '^' | '$' => atom = false, + _ => atom = true, + } + } + depth == 0 +} + fn shown(from: &[String]) -> String { few(from) } diff --git a/crates/model/src/create_patch_tests.rs b/crates/model/src/create_patch_tests.rs index 76c3f71..fff45df 100644 --- a/crates/model/src/create_patch_tests.rs +++ b/crates/model/src/create_patch_tests.rs @@ -353,7 +353,8 @@ fn what_the_description_cant_hold_is_kept() { ["a directive or macro at its top", "its patches given by a macro or directive"] ); // A list that can't be read, a value from a macro, other entries at the top. - assert_eq!(kept("pointSync false; patches 1 ( { name cyc; } );"), ["its patches list, which can't be read whole"]); + assert_eq!(kept("pointSync false; patches 2 ( { name cyc; } );"), ["its patches list, which can't be read whole"]); + assert_eq!(kept("pointSync false; patches 1 ( { name cyc; } );"), ["patch cyc"]); assert_eq!(kept("pointSync false; patches ( cyc );"), ["its patches list, which can't be read whole"]); assert_eq!( kept(&own.replace("patchInfo { type wall; }", "patchInfo $wallInfo;")), @@ -443,3 +444,169 @@ fn keys_given_twice_are_kept_and_summaries_count() { assert_eq!(summary(&["a".into(), "b".into(), "c".into()]), "a, and 2 more"); assert_eq!(summary(&["a".into(), "b".into(), "and more".into()]), "a, and more"); } + +#[test] +fn counted_lists_switches_and_missing_types_are_read_as_openfoam_does() { + let made = targets(&three(), None).unwrap().remove(1).made; + let diff = |text: &str, v| differences(&root(text), &made, v); + let own = "pointSync false; patches 1 ( { name buildings; patchInfo { type wall; } constructFrom patches; patches 1 (defaultFaces); } );"; + assert_eq!(diff(own, OfVersion::V8), Vec::::new()); + assert_eq!(kept(&root(own), &made, OfVersion::V8), Vec::::new()); + assert_eq!( + diff(&own.replace("patches 1 ( {", "patches 2 ( {"), OfVersion::V12), + ["its patches list's count isn't the number of its items, at which OpenFOAM stops"] + ); + assert_eq!( + diff(&own.replace("pointSync false", "pointSync banana"), OfVersion::V8), + ["its pointSync isn't a switch (true or false), at which OpenFOAM-8's createPatch stops"] + ); + assert_eq!(diff(&own.replace("pointSync false", "pointSync $sync"), OfVersion::V8), Vec::::new()); + // A quoted string isn't a switch to OpenFOAM-8, nor off. + let quoted = own.replace("pointSync false", "pointSync \"false\""); + assert_eq!( + diff("ed, OfVersion::V8), + ["its pointSync isn't a switch (true or false), at which OpenFOAM-8's createPatch stops"] + ); + assert_eq!(kept(&root("ed), &made, OfVersion::V8), ["its pointSync, which isn't off"]); + assert_eq!(diff(&own.replace("pointSync false", "pointSync banana"), OfVersion::V12), Vec::::new()); + assert_eq!( + diff(&own.replace("{ type wall; }", "{ }"), OfVersion::V12), + [ + "patch buildings has no type there (patchInfo), which createPatch needs for a new patch; the description makes it wall" + ] + ); +} + +#[test] +fn the_order_decides_where_shared_faces_go() { + let two = |names: [&str; 2]| { + let mut d = three(); + d.regions.truncate(2); + for r in &mut d.regions { + r.patches = names + .iter() + .map(|n| PatchDesc { kind: Some("wall".into()), ..patch(n, None, &["defaultFaces"]) }) + .collect(); + } + d + }; + assert!(targets(&two(["roof", "wall"]), None).is_ok()); + let mut d = two(["roof", "wall"]); + d.regions[1].patches.reverse(); + let e = targets(&d, None).unwrap_err(); + assert!(e.contains("they make roof and wall, whose sources may overlap, in another order"), "{e}"); + // Sources that can't overlap: any order. + let mut d = two(["roof", "wall"]); + for r in &mut d.regions { + r.patches[1].from = vec!["other".into()]; + } + d.regions[1].patches.reverse(); + assert!(targets(&d, None).is_ok()); + // The case's own in the other order: a difference, not what the description can't hold. + let made = targets(&two(["roof", "wall"]), None).unwrap().remove(0).made; + let item = + |n: &str| format!("{{ name {n}; patchInfo {{ type wall; }} constructFrom patches; patches (defaultFaces); }}"); + let other = format!("patches ( {} {} );", item("wall"), item("roof")); + assert_eq!( + differences(&root(&other), &made, OfVersion::V12), + [ + "patches roof and wall, whose sources may overlap, are made in the other order there, or one is given again around the other (createPatch gives a face to the last that takes it)" + ] + ); + assert_eq!(kept(&root(&other), &made, OfVersion::V12), Vec::::new()); + let same = format!("patches ( {} {} );", item("roof"), item("wall")); + assert_eq!(differences(&root(&same), &made, OfVersion::V12), Vec::::new()); + // A name given again after the other: its last item decides too. + let again = format!("patches ( {} {} {} );", item("roof"), item("wall"), item("roof")); + assert_eq!(differences(&root(&again), &made, OfVersion::V12).len(), 1); + // Many patches: compared two by two among the first few hundred only, quickly. + let many = |reversed: bool| { + let mut d = three(); + d.regions.truncate(2); + for (k, r) in d.regions.iter_mut().enumerate() { + r.patches = (0..20_000) + .map(|i| PatchDesc { kind: Some("wall".into()), ..patch(&format!("p{i}"), None, &[&format!("s{i}")]) }) + .collect(); + if reversed && k == 1 { + r.patches.reverse(); + } + } + d + }; + assert!(targets(&many(true), None).is_ok()); + assert!(targets(&many(false), None).is_ok()); + // Wide patches, the other order, no source shared: within a budget of lookups. + let wide = |reversed: bool| { + let mut d = three(); + d.regions.truncate(2); + for (k, r) in d.regions.iter_mut().enumerate() { + r.patches = (0..MAX_ORDERED) + .map(|i| { + let from: Vec = (0..2_000).map(|j| format!("s{i}_{j}")).collect(); + PatchDesc { kind: Some("wall".into()), from, ..patch(&format!("p{i}"), None, &[]) } + }) + .collect(); + if reversed && k == 1 { + r.patches.reverse(); + } + } + d + }; + assert!(targets(&wide(true), None).is_ok()); + // A shared source among the first: still found at that scale. + let mut d = wide(true); + for r in &mut d.regions { + for p in r.patches.iter_mut().filter(|p| p.name == "p0" || p.name == "p1") { + p.from.push("shared".into()); + } + } + assert!(targets(&d, None).unwrap_err().contains("p0 and p1"), "{:?}", targets(&d, None)); +} + +#[test] +fn a_header_of_its_own_is_kept_and_long_lists_are_capped() { + let made = targets(&three(), None).unwrap().remove(1).made; + let own = "FoamFile { version 2.0; format ascii; class dictionary; object createPatchDict; note \"mine\"; } patches ( { name buildings; patchInfo { type wall; } constructFrom patches; patches (defaultFaces); } );"; + assert_eq!(kept(&root(own), &made, OfVersion::V12), ["its FoamFile note"]); + let header: String = (0..1000).map(|i| format!("k{i} 1; ")).collect(); + let k = kept(&root(&format!("FoamFile {{ {header} }} patches ( );")), &[], OfVersion::V12); + assert_eq!(k.len(), MAX_KEPT + 1); + let many: String = (0..1000).map(|i| format!("k{i} 1; ")).collect(); + let k = kept(&root(&format!("{many} patches ( );")), &[], OfVersion::V12); + assert_eq!(k.len(), MAX_KEPT + 1); + assert_eq!(k.last().map(String::as_str), Some("and more")); +} + +#[test] +fn patterns_that_may_not_compile_are_refused() { + for ok in [ + "defaultFaces", + "\"defaultFaces\"", + "\"region1_to_.*\"", + "\"(a|b)_wall\"", + "\"[a-c]x+\"", + "\"wall.?\"", + "\"(?i)wall.*\"", + ] { + assert!(source_ok(ok), "{ok}"); + } + for bad in [ + "\"[\"", + "\"(a\"", + "\"a)\"", + "\"*a\"", + "\"a**\"", + "\"[]\"", + "\"[z-a]\"", + "\"(?:a)\"", + "\"a{2}\"", + "\"|*\"", + "\"(?i)\"", + "\"(?i)*\"", + "\"[a-c-e]\"", + ] { + assert!(!source_ok(bad), "{bad}"); + } + assert_eq!(source_token("["), "\"[\""); + assert!(!source_ok(&source_token("["))); +} diff --git a/crates/model/src/description.rs b/crates/model/src/description.rs index 76bae70..1d39590 100644 --- a/crates/model/src/description.rs +++ b/crates/model/src/description.rs @@ -127,7 +127,7 @@ pub struct PatchDesc { /// `createPatchDict`; a name that isn't a plain word is a pattern. Empty: not made by /// `createPatch`. pub from: Vec, - /// Its type where the role doesn't give it (`type`), for `createPatch` to make it of: a + /// Its type (`type`) for `createPatch` to make it of, over the one its role gives: a /// plain wall without a partner (the canyons' `buildings`), or a patch without a role. pub kind: Option, } @@ -1082,7 +1082,8 @@ fn read_split( } /// What a patch's `from` is, said when it isn't. -const FROM_IS: &str = "is ( patch … ): names, or quoted patterns without quotes, backslashes or spaces inside"; +const FROM_IS: &str = + "is ( patch … ): names, or quoted patterns OpenFOAM compiles, without quotes, backslashes, braces or spaces inside"; fn read_patch(name: &str, body: &umcf_foam_dict::Dict, at: &str, problem: &mut impl FnMut(&str, String)) -> PatchDesc { let mut p = PatchDesc { name: name.to_string(), role: None, partner: None, from: Vec::new(), kind: None }; @@ -1533,9 +1534,9 @@ fn import_created( notes.push(format!("region {name}: createPatch runs, but {path} isn't there or doesn't load")); return; }; - let items = match doc.root.get("patches").map(|e| e.value.as_slice()) { - Some([Node::List { items, .. }]) => items, - _ => { + let items = match doc.root.get("patches").and_then(|e| crate::create_patch::listed(&e.value)) { + Some(items) => items, + None => { notes.push(format!("region {name}: {path} has no plain patches list: what createPatch makes isn't told")); return; } @@ -1548,6 +1549,12 @@ fn import_created( let mut at: HashMap = patches.iter().enumerate().map(|(i, p)| (p.name.clone(), i)).collect(); // A name given twice is one patch of both items' sources, as createPatch makes it. let mut imported: HashMap> = HashMap::new(); + // The patches made, in the dictionary's order (createPatch's: the last to take a face has it). + let mut order: Vec = Vec::new(); + let mut order_at: HashMap = HashMap::new(); + let mut normals: HashMap, bool)> = HashMap::new(); + let mut again: HashSet = HashSet::new(); + let mut budget: usize = 1 << 20; let mut noted = 0usize; let mut note = |notes: &mut Vec, m: String| { noted += 1; @@ -1623,18 +1630,18 @@ fn import_created( continue; } } - let from: Option> = match body.get("patches").map(|e| e.value.as_slice()) { - Some([Node::List { items, .. }]) => items - .iter() - .map(|n| atom(n).filter(|t| crate::create_patch::source_ok(t)).map(str::to_string)) - .collect(), - _ => None, - }; + let from: Option> = + body.get("patches").and_then(|e| crate::create_patch::listed(&e.value)).and_then(|items| { + items + .iter() + .map(|n| atom(n).filter(|t| crate::create_patch::source_ok(t)).map(str::to_string)) + .collect() + }); let Some(from) = from.filter(|f| !f.is_empty()) else { note( notes, format!( - "region {name}, patch {patch}: the patches {path} makes it of aren't a plain list of names and quoted patterns (without quotes, backslashes or spaces inside): left out" + "region {name}, patch {patch}: the patches {path} makes it of aren't a plain list of names and quoted patterns OpenFOAM compiles (without quotes, backslashes, braces or spaces inside): left out" ), ); continue; @@ -1663,6 +1670,47 @@ fn import_created( let own = |role: Option| { given.clone().filter(|t| role.is_none_or(|r| crate::create_patch::role_type(kind, r) != t.as_str())) }; + // A name given again after others: its sources join the first item's place, which + // changes where faces it shares with those between go (the last to take a face has it). + // (Only the repeat's own sources: those of the first item go where they would anyway.) + // Bounded (a hostile file): the patches after its first item, a few hundred, by their + // sources as createPatch takes them, a budget of lookups for the whole dictionary; a + // patch noted once. + if let Some(first) = order_at.get(&patch) + && order.last() != Some(&patch) + && budget > 0 + && !again.contains(&patch) + { + let own: HashSet = from.iter().map(|f| crate::create_patch::normal(f)).collect(); + let own_pattern = own.iter().any(|f| f.starts_with('"')); + let between = order.iter().skip(first.saturating_add(1)).take(crate::create_patch::MAX_ORDERED); + let shared = between.filter_map(|n| normals.get(n).map(|s| (n, s))).find(|(_, (theirs, pattern))| { + let (small, big) = if theirs.len() < own.len() { (theirs, &own) } else { (&own, theirs) }; + budget = budget.saturating_sub(small.len().max(1)); + own_pattern || *pattern || small.iter().any(|f| big.contains(f)) + }); + if let Some((q, _)) = shared { + let q = q.clone(); + again.insert(patch.clone()); + note( + notes, + format!( + "region {name}, patch {patch}: {path} makes it again after {q}, whose sources may overlap: the description makes it of both items' sources in the first one's place, which may give the faces they share to {q} (workflow.dictionaries leaves the file as it is)" + ), + ); + } + } + if !imported.contains_key(&patch) { + order_at.insert(patch.clone(), order.len()); + order.push(patch.clone()); + } + // Its sources as createPatch takes them, and whether one is a pattern, for the above. + let entry = normals.entry(patch.clone()).or_default(); + for f in &from { + let n = crate::create_patch::normal(f); + entry.1 |= n.starts_with('"'); + entry.0.insert(n); + } match at.get(&patch).and_then(|i| patches.get_mut(*i)) { Some(p) if imported.contains_key(&patch) => { let seen = imported.entry(patch).or_default(); @@ -1698,6 +1746,26 @@ fn import_created( if noted > MAX_CREATE_NOTES { notes.push(format!("region {name}: {path}: and {} more notes like these", noted - MAX_CREATE_NOTES)); } + // The patches made take the places of those made, in the dictionary's order; the others + // keep the mesh's. + // (A name the mesh gives twice: the copy made of others only, the other left where it is.) + // In one pass (many patches in a hostile file). + let mut slotted: HashSet = HashSet::new(); + let mut rest: Vec> = Vec::with_capacity(patches.len()); + let mut made: HashMap = HashMap::new(); + for p in std::mem::take(patches) { + if imported.contains_key(&p.name) && !p.from.is_empty() && slotted.insert(p.name.clone()) { + rest.push(None); + made.insert(p.name.clone(), p); + } else { + rest.push(Some(p)); + } + } + let mut placed: Vec = order.iter().filter_map(|n| made.remove(n)).collect(); + placed.extend(made.into_values()); + let mut placed = placed.into_iter(); + patches.extend(rest.into_iter().filter_map(|p| p.or_else(|| placed.next()))); + patches.extend(placed); } /// The most notes [`import_created`] gives for one dictionary before it counts the rest. diff --git a/crates/model/src/description_edit.rs b/crates/model/src/description_edit.rs index 98d76b1..d1d2c6d 100644 --- a/crates/model/src/description_edit.rs +++ b/crates/model/src/description_edit.rs @@ -21,7 +21,7 @@ pub struct PatchEdit { /// The patches `createPatch` makes it of (names, or patterns); `Some(vec![])` takes them /// away. pub from: Option>, - /// Its type where the role doesn't give it; `Some(None)` takes it away. + /// Its type, over the one its role gives; `Some(None)` takes it away. pub kind: Option>, } @@ -270,7 +270,7 @@ impl Case { for f in from.iter().flatten() { if !crate::create_patch::source_ok(f) { return Err(refuse(format!( - "from `{f}` is neither a plain OpenFOAM name nor a pattern without quotes, backslashes or spaces inside" + "from `{f}` is neither a plain OpenFOAM name nor a pattern OpenFOAM compiles, without quotes, backslashes, braces or spaces inside" ))); } } @@ -354,7 +354,14 @@ impl Case { d.region(region)? .patches .iter() - .find(|q| q.from.iter().any(|f| crate::create_patch::normal(f) == patch)) + .find(|q| { + // The patch renamed is made of what this call gives it, where it gives it. + let from = match &from { + Some(given) if q.name == patch => given, + _ => &q.from, + }; + from.iter().any(|f| crate::create_patch::normal(f) == patch) + }) .map(|q| q.name.clone()) }) { return Err(refuse(format!( diff --git a/crates/model/src/description_edit_tests.rs b/crates/model/src/description_edit_tests.rs index 2800d0e..e6c127a 100644 --- a/crates/model/src/description_edit_tests.rs +++ b/crates/model/src/description_edit_tests.rs @@ -567,5 +567,11 @@ fn a_patch_another_is_made_of_isnt_renamed() { c.describe_patch("air", "buildings", &edit(Some(vec!["\"odd\"".into()]), None)).unwrap(); let e = c.describe_patch("air", "odd", &edit(None, Some("even"))).unwrap_err().to_string(); assert!(e.contains("is made of odd (from)"), "{e}"); + // The patch renamed is made of what the call gives it: of itself refused, of another not. + c.describe_patch("air", "buildings", &edit(Some(vec!["defaultFaces".into()]), None)).unwrap(); + let e = c.describe_patch("air", "odd", &edit(Some(vec!["odd".into()]), Some("even"))).unwrap_err().to_string(); + assert!(e.contains("patch odd of region air is made of odd (from)"), "{e}"); + c.describe_patch("air", "odd", &edit(Some(vec!["odd".into()]), None)).unwrap(); + c.describe_patch("air", "odd", &edit(Some(vec!["west".into()]), Some("even"))).unwrap(); let _ = fs; } diff --git a/crates/model/src/description_tests.rs b/crates/model/src/description_tests.rs index 6a50521..4e769ff 100644 --- a/crates/model/src/description_tests.rs +++ b/crates/model/src/description_tests.rs @@ -1085,3 +1085,39 @@ fn import_reads_what_create_patch_makes() { assert_eq!(notes.iter().filter(|n| n.contains("by a macro or directive")).count(), 20); assert!(notes.iter().any(|n| n.contains("and 10 more notes like these")), "{notes:#?}"); } + +#[test] +fn import_keeps_the_order_create_patch_makes_the_patches_in() { + let made = |name: &str, from: &str| { + format!("{{ name {name}; patchInfo {{ type wall; }} constructFrom patches; patches ({from}); }}") + }; + let order = |items: &[String]| { + let dict = + format!("{}patches {} ( {} );\n", header("dictionary", "createPatchDict"), items.len(), items.join(" ")); + let c = Case::open(&canyon().with("system/air/createPatchDict", dict)).unwrap(); + let (d, notes) = Description::import(&c); + let names: Vec = d.region("air").unwrap().patches.iter().map(|p| p.name.clone()).collect(); + let at = |n: &str| names.iter().position(|x| x == n).unwrap(); + (at("top") < at("ground"), names.len(), notes) + }; + let (top_first, n, notes) = order(&[made("top", "x"), made("ground", "x")]); + assert!(top_first, "{notes:#?}"); + let (top_first, m, _) = order(&[made("ground", "x"), made("top", "x")]); + assert!(!top_first); + assert_eq!(n, m); + // Given again after a patch whose sources may overlap: noted. + let (_, _, notes) = order(&[made("top", "x"), made("ground", "y"), made("top", "y")]); + assert!( + notes.iter().any(|n| n.contains("patch top: system/air/createPatchDict makes it again after ground")), + "{notes:#?}" + ); + // A hostile file: a patch of many sources, then many repeats after it: bounded, noted once. + let wide: Vec = (0..50_000).map(|i| format!("s{i}")).collect(); + let mut items = vec![made("top", "x"), made("ground", &wide.join(" "))]; + items.extend((0..5_000).map(|i| made("top", &format!("s{i}")))); + let (_, _, notes) = order(&items); + assert_eq!(notes.iter().filter(|n| n.contains("makes it again after ground")).count(), 1, "{notes:#?}"); + // Only the repeat's own sources count: the first item's go where they would anyway. + let (_, _, notes) = order(&[made("top", "x"), made("ground", "x"), made("top", "y")]); + assert!(notes.iter().all(|n| !n.contains("makes it again")), "{notes:#?}"); +} diff --git a/crates/model/tests/coupling.rs b/crates/model/tests/coupling.rs index 5d1ab87..49afffd 100644 --- a/crates/model/tests/coupling.rs +++ b/crates/model/tests/coupling.rs @@ -101,7 +101,10 @@ fn the_cases_create_patch_dictionaries_are_generated_from_their_descriptions() { Err(e) => panic!("{dir}: {e}"), }; for t in &targets { - let Some(own) = case.dict(&t.path) else { continue }; + let Some(own) = case.dict(&t.path) else { + assert_ne!(case.exists(&t.path), Some(true), "{dir}: {} is there but doesn't load", t.path); + continue; + }; assert_eq!( create_patch::differences(&own.root, &t.made, version), Vec::::new(), diff --git a/crates/ui-egui/src/forms.rs b/crates/ui-egui/src/forms.rs index 1f991db..e48bd77 100644 --- a/crates/ui-egui/src/forms.rs +++ b/crates/ui-egui/src/forms.rs @@ -1260,7 +1260,7 @@ static SPECS: &[Spec] = &[ "type", "Type", Kind::Model, - "The type createPatch makes it of where its role doesn't give one (wall); empty: taken away", + "The type createPatch makes it of, over the one its role gives (wall for a plain wall); empty: by its role", ), field( "name", diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index bad6c28..00c7d98 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -3475,6 +3475,18 @@ fn the_workflow_cards_fill_from_the_description() { form(&h).params(spec).unwrap(), json!({"region": "street", "patch": "street_to_air", "partner": {"region": "air", "patch": "top"}}) ); + // Sources only spaced otherwise than filled in are unchanged: they follow a command run + // meanwhile. + h.state_mut() + .act("workflow.patch", json!({"region": "street", "patch": "street_to_air", "from": ["defaultFaces"]})); + h.run(); + h.run(); + assert_eq!(form(&h).values["from"], "defaultFaces"); + set(&mut h, "from", " defaultFaces "); + h.state_mut().act("workflow.patch", json!({"region": "street", "patch": "street_to_air", "from": ["other"]})); + h.run(); + h.run(); + assert_eq!(form(&h).values["from"], "other"); // Leaving a patch the description has for a name it doesn't: what was filled in from it is // cleared, not carried over; what was typed (the partner) stays. set(&mut h, "patch", "street_to_air2"); diff --git a/crates/ui-egui/src/workflowcard.rs b/crates/ui-egui/src/workflowcard.rs index 8eaf7d5..66b401c 100644 --- a/crates/ui-egui/src/workflowcard.rs +++ b/crates/ui-egui/src/workflowcard.rs @@ -274,7 +274,10 @@ impl App { for (k, v) in now { let was = f.initial.get(k).cloned().unwrap_or_default(); let value = f.values.get(k).cloned().unwrap_or_default(); - if !f.extra.contains_key(k) && value == was { + // Sources apart by spaces: the same as filled in however they are spaced. + let unchanged = + if k == "from" { value.split_whitespace().eq(was.split_whitespace()) } else { value == was }; + if !f.extra.contains_key(k) && unchanged { f.values.insert(k, v.clone()); } else if !f.extra.contains_key(k) && let Some(merged) = merge_table(k, &value, &was, &v) diff --git a/crates/validate/src/description.rs b/crates/validate/src/description.rs index 5b51970..392b3ae 100644 --- a/crates/validate/src/description.rs +++ b/crates/validate/src/description.rs @@ -180,6 +180,9 @@ fn create_patch(case: &Case, d: &Description, out: &mut Vec) { None if case.exists(&t.path) == Some(true) => { "doesn't load as a dictionary (or is a directory): workflow.dictionaries can't write it until it is mended or removed".to_string() } + None if case.exists(&t.path).is_none() => { + "not loaded, and whether it is there isn't known (the case lists more files than are read): createPatch reads it".to_string() + } None => format!("not there, and createPatch reads it: workflow.dictionaries writes it from the patches of {whose} {regions}"), Some(doc) => { let have = doc.to_string(); @@ -202,7 +205,7 @@ fn create_patch(case: &Case, d: &Description, out: &mut Vec) { CREATE, &t.path, format!( - "the case's own makes the patches as the description of {whose} {regions} does, but holds what it can't ({}), which workflow.dictionaries leaves as it is: describe it (workflow.patch) or mend the file by hand", + "the case's own shows no difference from the patches the description of {whose} {regions} makes (what a macro or directive gives isn't compared), but holds what it can't ({}), which workflow.dictionaries leaves as it is: describe it (workflow.patch) or mend the file by hand", cp::summary(&kept) ), ); diff --git a/docs/common-workflow.md b/docs/common-workflow.md index 8ae18d8..2682602 100644 --- a/docs/common-workflow.md +++ b/docs/common-workflow.md @@ -134,7 +134,9 @@ umcfGui from the case workflow; edit the workflow, not this file.`), and is writ whenever the description changes. One edited by hand since it was generated is kept in the backup before it is replaced, and the change says which. A `blockMeshDict` carries a checksum in its header too: one edited since (or not written by umcfGui) is written over only when asked -(`replace`). The fields of `0.orig` are not generated files: +(`replace`). A `createPatchDict` holding what the description can't (a patch's `inGroups`, a +cyclic patch, a face set) isn't written over even with `replace`, as that would be lost: edit +it by hand, or move into the description what it holds. The fields of `0.orig` are not generated files: they are edited in place (below). ## The fields diff --git a/docs/user-guide/checks.md b/docs/user-guide/checks.md index f19ecf6..f44ae67 100644 --- a/docs/user-guide/checks.md +++ b/docs/user-guide/checks.md @@ -243,7 +243,7 @@ OpenFOAM version. Each problem names the script and line. | `workflow.blocks` | Warning | A region's [blocks](workflow.md#blocks) in the description: the grid's problems (stations that don't increase, a span without cells or with a section blockMesh would give none, a `cyclic`, `nonConformal`, `mapped` or `processor` type in `types`, more than 10 000 names in a map, a dictionary too large to read back, a missing block outside the grid or listed twice, a whole layer missing, a face without a patch, a single face inside the mesh, too many blocks), a patch the region's `patches` don't list or whose role doesn't fit its side (the ground and top across the gravity of `constant//g`, else `constant/g`, else z up, said), blocks without a `mesh`, a region meshed from another's [background](workflow.md#background) that the scripts can't keep (that region not listed before it, not built by steps of its own starting with `blockMesh`, or a region named as the directory it is kept in) or that has blocks of its own its mesh doesn't read, or that doesn't list the patches of the background's blocks its mesh gets, a [box](workflow.md#box) without blocks, with a problem of its own (a surface name that isn't an STL file of `constant/triSurface`, a negative margin, a cell size not above 0) or around surfaces the case doesn't have, and a `blockMeshDict` that isn't there, doesn't load or isn't what the blocks make (edited by hand, written from other blocks, another patch type): `mesh.block` writes it, listing any type it changes and any patch it drops or adds, and refusing to change a wall or constraint type the call's `types` doesn't give, or to drop such a patch `dropPatches` doesn't name. The grid's problems: the first 20 of them all, then how many more; patches the description doesn't list, and patches whose role doesn't fit: 20 of each, then how many more | | `workflow.snappy` | Warning | A region's [snappy entry](workflow.md#snappy) in the description: its own problems (a cutting surface without a level, distances whose levels grow away from the surface, a feature level on a compressed surface, a box without a length, names given twice, …), a solid region, a mesh that doesn't run snappyHexMesh, a surface the case doesn't have, cutting surfaces' patches the description doesn't list or that another surface or the blocks make too (those of the region whose background its mesh starts from), an inside point outside those blocks, on their sides or in a missing block (the blocks may have changed since `mesh.snappy` checked it), features asked for while the workflow doesn't run `surfaceFeatures`, a `snappyHexMeshDict` that isn't what the entry writes (missing, doesn't load, written from another entry, or edited by hand so that it holds something else than the entry: one of the case's own that holds what the entry does, as `workflow.import` read the entry from it, with the patch types the roles give, is an Info, counting the parts of it the entry can't hold), and a `system/surfaceFeaturesDict` that is missing, doesn't load, was written from other entries, or is the case's own and doesn't list a surface asking for features. The surfaces themselves are checked by `mesh.snappy` | | `workflow.change-dictionary` | Warning | The `changeDictionaryDict` of a region whose steps run `changeDictionary`, against what [`workflow.dictionaries`](workflow.md#writing-the-dictionaries) writes from the patches' roles and partners: one that can't be written (a partner without a role, a partner region not described, a canopy with a partner or no air, a name that isn't a plain OpenFOAM word, or a region's that can't be a directory on every system), one missing or that doesn't load, one umcfGui wrote otherwise than it writes now (other roles or partners, another OpenFOAM version, or an older umcfGui), and the case's own where it differs, by the keys the version reads and only those given (`changeDictionary` merges a block into the mesh's patch, so a key left out keeps the mesh's value, not known before the mesh is made; a region or patch the version reads that is left out is said to be unconfirmed, in OpenFOAM-8 unless OpenFOAM-12's key stands in its place, said to be unread; a patch's block with a `~key`, which takes the key out of the mesh's patch, isn't compared, said so): a patch's type, or the region and patch it maps to (OpenFOAM-8 only `sampleRegion` and `samplePatch`, `neighbourRegion` or `neighbourPatch` in their place said to be unread; OpenFOAM-12 `neighbourRegion` and `neighbourPatch` where given, else the older two, which alone, the description's or not, are said to be unconfirmed, as OpenFOAM-12 reads the newer first and the mesh's patch keeps a newer one it has; OpenFOAM-12's `mappedInternal` reads no patch; OpenFOAM-8 stops on a patch other than `none` in a mode that samples none, `nearestCell`, `nearestOnlyCell` or `nearestFace`, with a `coupleGroup` too, and without a mode given the patch isn't compared; with a `coupleGroup`, OpenFOAM-8 compares the region and patch only when both are given (in `nearestCell` and `nearestOnlyCell` the region alone; `nearestFace` asks the group for a patch not given, refused), OpenFOAM-12 stops on a group given with either, and a partner named by the group alone isn't compared; OpenFOAM-12's `samePatch`, a switch (`true`, `yes`, `on` and the like) or a number other than 0, names the patch of the same name, refused with a patch named too (not compared then), and alone compared and, where it is the description's, said to be unconfirmed, as OpenFOAM-12 refuses it beside a `neighbourPatch`, which it writes on a mapped patch and the mesh's patch keeps, and one that isn't a switch (quoted, too) refused, the patch not compared then; a name that isn't a word, empty (`""`) or a dictionary, is said to be refused, for the keys the version reads, a group's too, and so is a type that is a dictionary), a sample mode OpenFOAM-8 hasn't or one sampling no patch against one sampling a patch, an OpenFOAM-12 `method` (or `sampleMode` read as it) it hasn't, a patch changed that the description doesn't map, a value in `boundary` (which `changeDictionary` adds to the mesh's `boundary` file), a `~patch` there, quoted or not (on which `changeDictionary` stops where the mesh has the patch, or, with a block for it after, writes the block in its place without its faces; neither compared); other methods and modes, the offsets and values given by a macro or directive aren't compared (nor, with an OpenFOAM-8 `sampleMode` from one, the `samplePatch`), a patch mapped only through a pattern or group is said not to be there, keys a patch's block brings in (`$common;`, `#include`) aren't seen, and of a patch given twice only the last is read (OpenFOAM merges them). The case's own that maps them as the description does is fine. Not checked while the description doesn't read whole | -| `workflow.create-patch` | Warning | Each `createPatchDict` the description's meshes and steps read (`system//createPatchDict` for `createPatch -region`, `system/createPatchDict` for the regions meshed with `createPatch` in `constant/polyMesh`), against what [`workflow.dictionaries`](workflow.md#the-createpatchdicts) writes from the patches made of others (`from`) and their roles or types: when they can't be written (a patch made with neither a role nor a type, or in a region running no `createPatch`, a region running it both in and after its mesh with patches to make, regions sharing `system/createPatchDict` that make other patches, a name that isn't a plain word), one missing or that doesn't load, one umcfGui wrote otherwise than it writes now, and the case's own where it makes the patches otherwise: a patch not made there, made of a set or of other patches, of another type, one made there the description doesn't make, the `patches` list or OpenFOAM-8's `pointSync` missing, which `createPatch` stops without. The sources are compared as their union, in any order; a name or type quoted or not is the same, and so is a source quoted that OpenFOAM doesn't take for a pattern; what a macro or directive gives isn't compared (an item holding one by its name only). Where the case's own holds what the description can't (a patch it doesn't make or gives twice, one made of a face set or of sources it can't hold, `patchInfo` entries besides the type or other keys of an item, a key given twice in an item or its `patchInfo`, a value from a macro or directive, a list that can't be read whole, another entry at its top, OpenFOAM-8's `pointSync` not off), it says so, even where it makes the same patches, and to describe them with `workflow.patch` or mend the file, as `workflow.dictionaries` leaves it as it is. Not checked while the description doesn't read whole | +| `workflow.create-patch` | Warning | Each `createPatchDict` the description's meshes and steps read (`system//createPatchDict` for `createPatch -region`, `system/createPatchDict` for the regions meshed with `createPatch` in `constant/polyMesh`), against what [`workflow.dictionaries`](workflow.md#the-createpatchdicts) writes from the patches made of others (`from`) and their roles or types: when they can't be written (a patch made with neither a role nor a type, or in a region running no `createPatch`, a region running it both in and after its mesh with patches to make, regions sharing `system/createPatchDict` that make other patches, or make them in another order where their sources may overlap, a name that isn't a plain word), one missing or that doesn't load (or, where the case lists more files than are read, not loaded and not known to be there), one umcfGui wrote otherwise than it writes now, and the case's own where it makes the patches otherwise: a patch not made there, made of a set or of other patches, of another type or of none (`patchInfo` without a `type`), one made there the description doesn't make, two whose sources may overlap made in the other order (or one given again around the other: `createPatch` gives a face to the last patch that takes it), the `patches` list or OpenFOAM-8's `pointSync` missing, which `createPatch` stops without, a `pointSync` that isn't a switch (a word or a number, not a quoted string), a `patches` list whose count isn't its items'. The sources are compared as their union, in any order; a name or type quoted or not is the same, and so is a source quoted that OpenFOAM doesn't take for a pattern; what a macro or directive gives isn't compared (an item holding one by its name only). Where the case's own holds what the description can't (a patch it doesn't make or gives twice, one made of a face set or of sources it can't hold, `patchInfo` entries besides the type or other keys of an item, a key given twice in an item or its `patchInfo`, a value from a macro or directive, a list that can't be read whole, another entry at its top or in its `FoamFile` header, OpenFOAM-8's `pointSync` not off), it says so, also where it shows no difference (what a macro or directive gives isn't compared), and to describe them with `workflow.patch` or mend the file, as `workflow.dictionaries` leaves it as it is. Not checked while the description doesn't read whole | | `workflow.split` | Warning | A region [split](workflow.md#split) from another by a cell zone: from a region the description doesn't list, lists after it or doesn't build; a zone not named (no script splits it), or that its `topoSetDict` doesn't make, a `topoSetDict` that makes other zones too (they would be split off as well; no script splits it) or whose zones can't be told (`#include`, a macro), or a dictionary the case doesn't have; a zone or `region1` named as a region (the split's clean-up would remove that region's directories), a region named `region` and a number (as `splitMeshRegions` names the parts outside the zone) | ## Finite-volume constraints and pressure limits (OpenFOAM-12) diff --git a/docs/user-guide/command-line.md b/docs/user-guide/command-line.md index 90ca1e1..4123ef9 100644 --- a/docs/user-guide/command-line.md +++ b/docs/user-guide/command-line.md @@ -162,7 +162,7 @@ bad arguments. | `region.add` | [Adds a region](new-case.md#adding-a-region) to the case: `region`, `kind` (`fluid`, `solid`, `vegetation`) required; `materials` (a solid's, `[{"name": "brick", "model": "Hamstad5Brick"}]`). Lists it where the case's version reads its regions and writes the settings of its kind; the files there are kept | | `material.set` | [Sets a material's coefficients](new-case.md#a-materials-coefficients) in its solid's `transportProperties`: `region`, `material`, `coefficients` (`{"rho": 1700, "wcap": 2, "mu": null}`), that material only | | `workflow.region` | [Edits the description](workflow.md#editing-the-description): `region`, and `kind` (`fluid`, `solid`, `vegetation`: adds it or gives it that kind) or `remove: true` | -| `workflow.patch` | Edits a patch of the description: `region`, `patch`, and any of `role` (`null` takes it away), `partner` (`{"region": "street", "patch": "top"}`, or `null`), `from` (the patches `createPatch` makes it of, `["defaultFaces"]`, or `null`), `type` (its type where the role doesn't give it, or `null`), `name` (renames it; the partners that named it follow) | +| `workflow.patch` | Edits a patch of the description: `region`, `patch`, and any of `role` (`null` takes it away), `partner` (`{"region": "street", "patch": "top"}`, or `null`), `from` (the patches `createPatch` makes it of, `["defaultFaces"]`, or `null`), `type` (its type, over the one its role gives, or `null`), `name` (renames it; the partners that named it follow) | | `workflow.material` | Edits a solid's material in the description: `region`, `material`, and `model` (its `buildingMaterialModel`, or `null`) or `remove: true` | | `workflow.settings` | [Chooses settings](workflow.md#settings): any of `deltaT`, `endTime`, `writeInterval`, `turbulence`, `temperatureLimit` (`[min, max]`), `blending` (`{"dampingThickness": 60, "alphaCoeffU": 0.3, "alphaCoeffT": 0.3}`), `materials` (the library: `{"HamstadConcrete": {"rho": 1950, …}}`), `numerics` (per region kind: `{"fluid": {"SIMPLE": {"nNonOrthogonalCorrectors": 1}}}`), `from` (another case, read only), into the case's files and its description | | `workflow.component` | [Switches a component](workflow.md#components) on or off: `component` (`grass`, `temperatureLimit`, `blending`), `on` (`true`, `false`), `patches` (the grass's, of `air`), in the case's files and its description | diff --git a/docs/user-guide/workflow.md b/docs/user-guide/workflow.md index 36b2af8..24c5921 100644 --- a/docs/user-guide/workflow.md +++ b/docs/user-guide/workflow.md @@ -235,9 +235,11 @@ canopy (`"region1_to_.*"`, a pattern). `workflow.dictionaries` writes, for each, -region`, after the mesh); - `system/createPatchDict` for the regions whose mesh runs `createPatch` in `constant/polyMesh` (`mesh ( blockMesh … createPatch … )`, the 3×3 cases' air and vegetation): one dictionary for - them all, so they must make the same patches. + them all, so they must make the same patches, in the same order where their sources may + overlap. -Each patch is `{ name …; patchInfo { type …; } constructFrom patches; patches ( … ); }`, its +The patches are written in the order the region lists them, which is `createPatch`'s: a face two +patches' sources take goes to the last. Each patch is `{ name …; patchInfo { type …; } constructFrom patches; patches ( … ); }`, its sources as the description has them: a bare name one patch, a quoted one a pattern, as `createPatch` reads them (`"region.1"` is a regular expression, `region.1` a name). Its type is the patch's own `type` where it has one, else `wall` for a wall's role (`ground`, `coupled`, @@ -247,7 +249,8 @@ stops without it (OpenFOAM-12 doesn't read it). A region whose steps run `create patch to make gets an empty list. Refused, writing none: a patch made by `createPatch` with neither a role nor a type, one in a region whose mesh and steps run no `createPatch`, a region whose mesh and steps both run it with patches to make (which makes them isn't told), regions -meshed in `constant/polyMesh` that make different patches, a patch name that isn't a plain +meshed in `constant/polyMesh` that make different patches (or in another order, where their +sources may overlap), a patch name that isn't a plain OpenFOAM word, and a region's name that can't be a directory on every system. Generated, written over and kept as the `changeDictionaryDict`s are (`replace`, `region`: that region's, and the shared one when its mesh runs `createPatch`; a problem in another region's doesn't stop it, @@ -256,17 +259,19 @@ can't (a patch it doesn't make or makes in two items, one made of a face set or can't hold, an entry of `patchInfo` besides its `type`, such as a cyclic's `neighbourPatch`, or another key of the item, a key given twice in an item or its `patchInfo` (OpenFOAM merges them), a value given by a macro or directive, a `patches` list that can't be -read whole, another entry at its top, OpenFOAM-8's `pointSync` that isn't off) isn't written over, +read whole, another entry at its top or in its `FoamFile` header, OpenFOAM-8's `pointSync` that isn't off) isn't written over, even with `replace`: it is left as it is and noted, naming what would be lost, for `workflow.patch` to give the patches their `from` and `type`, or for the file to be mended by hand; the other dictionaries are written. The case check (`workflow.create-patch`) says when one is missing, doesn't load, was written by umcfGui otherwise than it writes now, or is the case's own and makes the patches otherwise: a -patch not made there, made of a set or of other patches, of another type, one made there that -the description doesn't make, and the `patches` list or OpenFOAM-8's `pointSync` missing, which -`createPatch` stops without; and the case's own that makes the patches as the description does -but holds what it can't (as above). The sources are compared as `createPatch` takes them, their +patch not made there, made of a set or of other patches, of another type or of none, one made +there that the description doesn't make, two whose sources may overlap made in the other order +(`createPatch` gives a face to the last patch that takes it), the `patches` list or OpenFOAM-8's +`pointSync` missing, which `createPatch` stops without, a `pointSync` that isn't a switch, and a +`patches` list whose count isn't its items'; and the case's own that shows no difference but +holds what it can't (as above). The sources are compared as `createPatch` takes them, their union in any order (of both items, for a patch given twice); a name or type quoted or not is the same, and so is a source quoted that OpenFOAM doesn't take for a pattern (`"defaultFaces"`: one without `. * + ? ( ) | [ ]` or a character a word can't hold); what a macro or directive gives isn't compared (an item holding one is @@ -353,8 +358,8 @@ settings | `steps` | after the mesh: `createPatch`, `changeDictionary`, `topoSet` (or `setSet "batch"` in OpenFOAM-8), `setFields` with the fields it restores from their backups first | | `role` | `inlet`, `outlet`, `side`, `top`, `ground`, `coupled`, `canopy`, `interior`, `bottom`, `sky` | | `partner` | the region and patch a coupled patch is mapped to | -| `from` | the patches `createPatch` makes the patch of, as its dictionary has them: a bare name one patch (`( defaultFaces )`), a quoted one a pattern (`( "region1_to_.*" )`), without quotes, backslashes or spaces inside; in the [`createPatchDict`](#the-createpatchdicts) its region's mesh or steps read. A patch another of its region is made of (by name) isn't renamed with `workflow.patch` (refused: change the `from` first) | -| `type` | the type `createPatch` makes it of where its role doesn't give it (`wall` for a plain wall without a partner, as the street canyons' `buildings`); read only with `from`; not a mapped type, which `changeDictionary` gives from the role and partner. | +| `from` | the patches `createPatch` makes the patch of, as its dictionary has them: a bare name one patch (`( defaultFaces )`), a quoted one a pattern (`( "region1_to_.*" )`), without quotes, backslashes, braces or spaces inside and a pattern OpenFOAM compiles; in the [`createPatchDict`](#the-createpatchdicts) its region's mesh or steps read. A patch another of its region is made of (by name) isn't renamed with `workflow.patch` (refused: change the `from` first) | +| `type` | the type `createPatch` makes it of, over the one its role gives (`wall` for a plain wall without a partner, as the street canyons' `buildings`); read only with `from`; not a mapped type, which `changeDictionary` gives from the role and partner. | | `materials` | a solid region's materials, in the order of its `buildingMaterials`: each the name of the cell zone built of it, with its `model` (`buildingMaterialModel`); the coefficients stay in the region's `transportProperties` | | `radiation` | the region the view factors and solar ray tracing are computed on, and the one `calcLAI` runs on | | `settings` | the [settings](#settings) the case chose; one that isn't there is the default | @@ -399,11 +404,15 @@ The import reads the `createPatchDict` each region's `createPatch` reads (its ow run it, else `system/createPatchDict` when its mesh does): each patch made of others (`constructFrom patches`) gets their names as its `from`, and its type as `type` where its role wouldn't give that one (a patch the region doesn't have is added without a role). One made of a -face set, whose name or sources aren't plain (a pattern with a backslash, a quote or a space -inside), part of which a macro or directive gives, with other keys or a key given twice, or whose `patchInfo` isn't a +face set, whose name or sources aren't plain (a pattern with a backslash, a quote, a brace or a +space inside, or one that may not compile), part of which a macro or directive gives, with other keys or a key given twice, or whose `patchInfo` isn't a dictionary or holds more than a plain type (a mapped or cyclic patch's entries), is noted and left out (the first 20 of a dictionary, -then a count, for each region reading it); a patch given in two items is made of both items' sources. A region whose mesh +then a count, for each region reading it); a patch given in two items is made of both items' sources (noted where +it comes again after a patch whose sources may overlap its own: the faces they share may then go +elsewhere, and `workflow.dictionaries` leaves the file as it is). The patches made keep the +dictionary's order among the region's patches (`createPatch` gives a face to the last patch that +takes it); the order of the patches in the description is the order the dictionary makes them in. A region whose mesh and steps both run `createPatch` is noted: only its own dictionary is read. @@ -1230,7 +1239,7 @@ its comments kept. | Command | What | |---|---| | `workflow.region` | `region` with `kind` (`fluid`, `solid` or `vegetation`) adds the region or gives it that kind (an empty `materials { }` goes when a solid becomes another kind); with `remove: true` it is taken out, and what still names it (coupled patches, regions meshed from its [background](#background), the radiation) is listed. A solid with materials stays one | -| `workflow.patch` | `region`, `patch` and any of `role`, `partner` (`{"region": "street", "patch": "top"}`), `from` (`["defaultFaces"]`: names, and patterns, a name that isn't a plain word quoted for it, `"\"region.1\""` given quoted; none with a quote, backslash or space inside), `type` (not a mapped one; only with `from`, which isn't taken away while it is there) and `name`. `null` takes a role, partner, `from` or `type` away; a patch the region doesn't list is added. A new name is followed by the region's [blocks](#blocks) and the partners that named the patch (its own too, when it is coupled to itself, unless the same call sets or takes away its partner) | +| `workflow.patch` | `region`, `patch` and any of `role`, `partner` (`{"region": "street", "patch": "top"}`), `from` (`["defaultFaces"]`: names, and patterns, a name that isn't a plain word quoted for it, `"\"region.1\""` given quoted; none with a quote, backslash, brace or space inside, nor a pattern that may not compile; at most 64), `type` (not a mapped one; only with `from`, which isn't taken away while it is there) and `name`. `null` takes a role, partner, `from` or `type` away; a patch the region doesn't list is added. A new name is followed by the region's [blocks](#blocks) and the partners that named the patch (its own too, when it is coupled to itself, unless the same call sets or takes away its partner) | | `workflow.material` | `region` (a solid), `material` (the name of its cell zone) and `model` (its `buildingMaterialModel`, or `null`), or `remove: true` | ```sh From ca722c8a18453bfe7460becd44a8ff9f418a9c3d Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Fri, 27 Nov 2026 13:44:32 +0100 Subject: [PATCH 3/6] M0.101: createPatch's order with patch groups, POSIX classes, no history step for nothing written (review) Any two patches createPatch makes may take the same faces (a name no patch has is a patch group), so the order is checked in one pass for every patch: regions sharing system/createPatchDict list them in the same order, the case check reports any other order or a name given again around another, and the import notes a name given again after another patch. Patterns accept POSIX classes inside brackets; an empty source list keeps the case's own file; workflow.dictionaries that writes nothing adds no undo step and keeps redo; workflow.show's help documents from and type; the patch card compares from by its names when the patch changes. --- ROADMAP.md | 2 +- crates/engine/src/cmd/workflow.rs | 14 +-- crates/engine/src/lib.rs | 14 ++- crates/engine/src/tests.rs | 8 ++ crates/model/src/create_patch.rs | 119 +++++++++++++------------ crates/model/src/create_patch_tests.rs | 85 +++++++++--------- crates/model/src/description.rs | 56 ++++-------- crates/model/src/description_tests.rs | 11 ++- crates/ui-egui/src/workflowcard.rs | 4 +- docs/user-guide/checks.md | 2 +- docs/user-guide/workflow.md | 16 ++-- 11 files changed, 173 insertions(+), 158 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index c3e0136..e0a2e9e 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -124,4 +124,4 @@ Ranked work list: [`docs/gaps.md`](docs/gaps.md). - 2026-11-24 — M0.98 a background mesh kept between regions (gaps row 6, 4 of 4 parts; the row is closed): a region's mesh can start with `background ` instead of `blockMesh` (`model::workflow::RootStep::Background`), as the `windAroundBuildings` tutorials mesh the vegetation from the air's background. `Allprepare` keeps what that region's `blockMesh` made in `constant/polyMesh.background.`, marked as its own (`.umcfgui-kept`; one there without the mark stops it, nothing removed), copies it into `constant/polyMesh` for each region meshed from it and removes it after the last (`Allclean` removes a marked one); a region it can't be kept from (not listed before it, not built by steps of its own starting with `blockMesh`) is refused by `workflow.scripts` and named by the case check (`workflow.blocks`), with blocks of its own its mesh doesn't read. The script reader takes the kept copy back where the mesh it was kept from is moved to its region with `mv` (the generated scripts; any `constant/polyMesh.*` directory, as the tutorials' `polyMesh.bckp`), and lists a copy no region is meshed from or one removed before it is used. The case check (`workflow.snappy`) also checks a region's inside point against the blocks as they are now. `mesh.snappy` takes `background` (a region, or `null` for its own `blockMesh` again) and checks the inside point and the surfaces against that region's blocks; the *Snappy mesh* card has *Background from*, offering the regions it can start from, and previews and checks their blocks. - 2026-11-24 — M0.99 a script's words bounded (review of M0.98): a word longer than 64 KiB once expanded is cut there and marked unresolved (a long literal was kept whole), and a script's reading stops after 64 MiB of expanded words (`script::MAX_EXPANDED`, each word charged 64 bytes more, as it is expanded), so neither a command of many long words nor a loop repeating long or empty ones builds steps without end; the prefixes before a command (`time`, `nohup`, …) are taken off at once. - 2026-11-24 — M0.100 each region's `changeDictionaryDict` from the description (gaps row 4, 1 of 6 parts): `workflow.dictionaries` (*Write the dictionaries*, a form) writes it for every region whose steps run `changeDictionary`, from the patches' roles and partners (`model::coupling`): a wall with a partner `mappedWall`, an open side `mapped` (`mappedPatch` in OpenFOAM-8), the vegetation's canopy the air's cells (`mappedInternal`; OpenFOAM-8 `mappedWall` with `sampleMode nearestCell`), OpenFOAM-12's `neighbourRegion`/`neighbourPatch` or OpenFOAM-8's `sampleRegion`/`samplePatch`, a fluid's and a solid's patches paired by `method nearest`; generated with a checksum, one edited by hand written over only with `replace`. Refused for a partner without a role, and for a name that isn't a plain OpenFOAM word or a region's that can't be a directory on every system. The case check `workflow.change-dictionary` says a missing, stale or differing one, by the keys each version reads, and a sample mode or method the version hasn't. `workflow.import` gives a vegetation patch mapped to its twin whose role isn't told the role `coupled` (a `mappedWall`) or `sky` (`mapped`, `mappedPatch`). The 15 dictionaries of the three 3×3 cases (OpenFOAM-8 and -12) are generated as the cases' own map them; on the street canyon with vegetation `Allprepare` makes the same meshes (OpenFOAM-8 byte for byte, OpenFOAM-12 with `method nearest` added) and `Allrun` the same fields. -- 2026-11-26 — M0.101 the `createPatchDict`s from the description (gaps row 4, 2 of 6 parts): a patch's `from` in `system/umcfWorkflow` names the patches `createPatch` makes it of (`( defaultFaces )`; a quoted source is a pattern when it holds a regular expression's characters, `( "region1_to_.*" )`, else the name it holds, `"defaultFaces"` as `defaultFaces`), and its `type` the type over the one its role gives (the street canyons' plain `buildings` wall). `workflow.dictionaries` writes `system//createPatchDict` for a region whose steps run `createPatch`, and `system/createPatchDict` for the regions meshed with it in `constant/polyMesh` (which must make the same patches), each patch typed by its own type, else `wall` for a wall's role, the canopy and every solid's patch, else `patch`, in the order the region lists them (`createPatch` gives a face two patches take to the last; the import keeps the dictionary's); `pointSync false;` for OpenFOAM-8. `workflow.import` reads `from` and `type` from the case's `createPatchDict`s (a source as written: quoted, a pattern or the name it holds), `workflow.dictionaries` leaves a case's own that holds what the description can't as it is, noted, even with `replace`, `workflow.patch` (*Describe a patch*: *Made of*, *Type*) edits them, and the case check `workflow.create-patch` says a dictionary missing, stale or making the patches otherwise (`model::create_patch`). The 16 `createPatchDict`s of the four 3×3 cases are generated as the cases' own make them; on the street canyon with vegetation `Allprepare` with the generated ones makes the same meshes, byte for byte, in OpenFOAM-8 and -12. +- 2026-11-26 — M0.101 the `createPatchDict`s from the description (gaps row 4, 2 of 6 parts): a patch's `from` in `system/umcfWorkflow` names the patches `createPatch` makes it of (`( defaultFaces )`; a quoted source is a pattern when it holds a regular expression's characters, `( "region1_to_.*" )`, else the name it holds, `"defaultFaces"` as `defaultFaces`), and its `type` the type over the one its role gives (the street canyons' plain `buildings` wall). `workflow.dictionaries` writes `system//createPatchDict` for a region whose steps run `createPatch`, and `system/createPatchDict` for the regions meshed with it in `constant/polyMesh` (which must make the same patches, in the same order: any two may take the same faces, through a pattern or a patch group), each patch typed by its own type, else `wall` for a wall's role, the canopy and every solid's patch, else `patch`, in the order the region lists them (`createPatch` gives a face two patches take to the last; the import keeps the dictionary's); `pointSync false;` for OpenFOAM-8. `workflow.import` reads `from` and `type` from the case's `createPatchDict`s (a source as written: quoted, a pattern or the name it holds), `workflow.dictionaries` leaves a case's own that holds what the description can't as it is, noted, even with `replace`, `workflow.patch` (*Describe a patch*: *Made of*, *Type*) edits them, and the case check `workflow.create-patch` says a dictionary missing, stale or making the patches otherwise (`model::create_patch`). The 16 `createPatchDict`s of the four 3×3 cases are generated as the cases' own make them; on the street canyon with vegetation `Allprepare` with the generated ones makes the same meshes, byte for byte, in OpenFOAM-8 and -12. diff --git a/crates/engine/src/cmd/workflow.rs b/crates/engine/src/cmd/workflow.rs index 717dcc0..da454fc 100644 --- a/crates/engine/src/cmd/workflow.rs +++ b/crates/engine/src/cmd/workflow.rs @@ -15,7 +15,7 @@ pub(super) const SHOW: CommandSpec = CommandSpec { label: "Workflow description", menu: "Case/Workflow description", shortcut: None, - params: "scripts: true to also return the scripts workflow.scripts would write from it (scripts, version; scriptsError when none can be: no system/umcfWorkflow of the case's own, a description with problems, no version, a name unsafe in a script, a region split by a cell zone that no script can split: its zone not known, a region named as the zone or the parts, its topoSetDict missing, making no such zone or others too, or whose zones can't be told, the region copied not built before it; a region meshed from another's background that the script can't keep: that region not built before it by steps of its own starting with blockMesh, or a region named as the directory it is kept in), without writing them. Returns the case's workflow description: system/umcfWorkflow as read (source \"file\", with the problems in it), or, when the case has none, as workflow.import would write it from the scripts and meshes (source \"scripts\", with what the import couldn't tell; \"unreadable\" when the file is there but isn't a dictionary, \"disk\" when it is on disk but not in the open case: written or undone since it was opened). Each region: kind (fluid, solid, vegetation), mesh (\"blocks\", the steps that build it in constant/polyMesh ({\"step\": \"blockMesh\" or \"snappyHexMesh\", \"dict\": its dictionary}, {\"step\": \"createPatch\"}, or first {\"step\": \"background\", \"of\": the region whose background mesh it starts from}), or for a region split from another region's mesh by a cell zone {\"from\": \"split\", \"of\": the region copied, \"zone\": the cell zone taken out or null, \"dict\": the topoSetDict that makes it}), blocks (its grid of blocks as mesh.block takes it, null when the description has none), box (the box its blocks are made from, as mesh.box takes it, or null), snappy (its surfaces, boxes and inside point as mesh.snappy takes them, or null), steps, patches with their role (inlet, outlet, side, top, ground, coupled, canopy, interior, bottom, sky) and partner, and a solid's materials (name: its cell zone; model: its buildingMaterialModel).", + params: "scripts: true to also return the scripts workflow.scripts would write from it (scripts, version; scriptsError when none can be: no system/umcfWorkflow of the case's own, a description with problems, no version, a name unsafe in a script, a region split by a cell zone that no script can split: its zone not known, a region named as the zone or the parts, its topoSetDict missing, making no such zone or others too, or whose zones can't be told, the region copied not built before it; a region meshed from another's background that the script can't keep: that region not built before it by steps of its own starting with blockMesh, or a region named as the directory it is kept in), without writing them. Returns the case's workflow description: system/umcfWorkflow as read (source \"file\", with the problems in it), or, when the case has none, as workflow.import would write it from the scripts and meshes (source \"scripts\", with what the import couldn't tell; \"unreadable\" when the file is there but isn't a dictionary, \"disk\" when it is on disk but not in the open case: written or undone since it was opened). Each region: kind (fluid, solid, vegetation), mesh (\"blocks\", the steps that build it in constant/polyMesh ({\"step\": \"blockMesh\" or \"snappyHexMesh\", \"dict\": its dictionary}, {\"step\": \"createPatch\"}, or first {\"step\": \"background\", \"of\": the region whose background mesh it starts from}), or for a region split from another region's mesh by a cell zone {\"from\": \"split\", \"of\": the region copied, \"zone\": the cell zone taken out or null, \"dict\": the topoSetDict that makes it}), blocks (its grid of blocks as mesh.block takes it, null when the description has none), box (the box its blocks are made from, as mesh.box takes it, or null), snappy (its surfaces, boxes and inside point as mesh.snappy takes them, or null), steps, patches with their role (inlet, outlet, side, top, ground, coupled, canopy, interior, bottom, sky), partner, from (the sources createPatch makes it of, as the description has them, a quoted one with its quotes; empty: not made by createPatch) and type (its own type, over the one its role gives; null: none, the role's), and a solid's materials (name: its cell zone; model: its buildingMaterialModel).", enabled: needs_case, run: show, journal: false, @@ -115,7 +115,7 @@ pub(super) const IMPORT: CommandSpec = CommandSpec { label: "Write workflow description", menu: "Case/Write workflow description", shortcut: None, - params: "replace: true to write over the case's system/umcfWorkflow (its comments and hand edits are not kept). Writes the workflow description from the case: its scripts (Allprepare, Allrun) read into the workflow, the region kinds, each patch's role and partner as its mesh and velocity condition tell, each solid's materials as its constant//transportProperties lists them (buildingMaterials), and the components the case's files switch on (a fluid's grassProperties whose grassModel isn't none and grass isn't off, a limitTemperature entry in the file a fluid's limit is read from (OpenFOAM-12: system/fvConstraints, else system/fvOptions, else constant/fvOptions; OpenFOAM-8: constant/fvOptions, else system/fvOptions), blending on in controlDict), and the settings its files have (deltaT, endTime, writeInterval, the fluids' RAS model, the temperature limit's bounds, blendingCoeffs: a macro, or fluids that differ, noted and left out), each region's grid of blocks read from the blockMeshDict its mesh reads, when that is one (all its blocks one cell each of a grid of stations along x, y and z, each span's cells and grading the same in every block; a dictionary that isn't one, with curved edges, a block over several cells, a scale, an #include or a $macro, is left out with a note; each patch whose type there isn't the one its role (or no role: patch) gives kept in the blocks' types; a region without a mesh given the patches its blocks name, without a role; the dictionary isn't written: mesh.block writes it from the blocks), each region's snappy entry read from the snappyHexMeshDict its snappyHexMesh step reads (its STL surfaces that cut or refine by distance, with the solids of the _ patches each made in the mesh, boxes refining the cells inside, feature levels, layers, the inside point, the expansion ratio and the first layer's thickness; the inside point as the case's version takes it (OpenFOAM-12: insidePoints of one point, insidePoint, locationInMesh; OpenFOAM-8: locationInMesh); what the entry can't hold noted and left out: other geometry, a surface or box it would refuse (the others kept), a scaled surface, a surface making a faceZone or cellZone (its refinement alone kept), layer sizes other than the entry's, an expansion below 1, a patch type other than its role's (each _ patch against its own), patchInfo beyond its type (inGroups), singleRegionName false, an expansionRatio that isn't a number, a name given to more than one surface or box, layers given to a surface by a _ patch's name, levels per solid, surfaces and layers named by a pattern, a patch's own layer settings, outside points, an #include or $macro not followed, macros; several inside points give no entry; the dictionary isn't written: mesh.snappy with replace writes it from the entry), and the material library from the solids' materials (each model's first material whose coefficients are numbers or dictionaries of them; a model whose materials differ noted once, a material with a macro or directive among its coefficients noted and left out). What it couldn't tell (a patch without a role, a region the scripts don't mesh, a step that doesn't fit, a material or its model given by a macro, a material listed more than once) is listed in notes. case.save writes it. A system/umcfWorkflow that is a symbolic link is not written over. Also reads, from the createPatchDict each region's createPatch reads (its own when its steps run createPatch, else system/createPatchDict when its mesh does), the patches made of others (constructFrom patches) into their from, as written (a quoted source a pattern), and their type where the role wouldn't give it; a name given twice is made of both items' sources (noted when it comes again after a patch whose sources may overlap); the patches made keep the dictionary's order among the region's patches; an item made of a face set, part of which a macro or directive gives, with a patchInfo that isn't a plain type's dictionary, other keys, a key given twice, or sources with a quote, backslash, brace or space inside or a pattern that may not compile is noted and left out (20 notes a dictionary for each region reading it, then a count).", + params: "replace: true to write over the case's system/umcfWorkflow (its comments and hand edits are not kept). Writes the workflow description from the case: its scripts (Allprepare, Allrun) read into the workflow, the region kinds, each patch's role and partner as its mesh and velocity condition tell, each solid's materials as its constant//transportProperties lists them (buildingMaterials), and the components the case's files switch on (a fluid's grassProperties whose grassModel isn't none and grass isn't off, a limitTemperature entry in the file a fluid's limit is read from (OpenFOAM-12: system/fvConstraints, else system/fvOptions, else constant/fvOptions; OpenFOAM-8: constant/fvOptions, else system/fvOptions), blending on in controlDict), and the settings its files have (deltaT, endTime, writeInterval, the fluids' RAS model, the temperature limit's bounds, blendingCoeffs: a macro, or fluids that differ, noted and left out), each region's grid of blocks read from the blockMeshDict its mesh reads, when that is one (all its blocks one cell each of a grid of stations along x, y and z, each span's cells and grading the same in every block; a dictionary that isn't one, with curved edges, a block over several cells, a scale, an #include or a $macro, is left out with a note; each patch whose type there isn't the one its role (or no role: patch) gives kept in the blocks' types; a region without a mesh given the patches its blocks name, without a role; the dictionary isn't written: mesh.block writes it from the blocks), each region's snappy entry read from the snappyHexMeshDict its snappyHexMesh step reads (its STL surfaces that cut or refine by distance, with the solids of the _ patches each made in the mesh, boxes refining the cells inside, feature levels, layers, the inside point, the expansion ratio and the first layer's thickness; the inside point as the case's version takes it (OpenFOAM-12: insidePoints of one point, insidePoint, locationInMesh; OpenFOAM-8: locationInMesh); what the entry can't hold noted and left out: other geometry, a surface or box it would refuse (the others kept), a scaled surface, a surface making a faceZone or cellZone (its refinement alone kept), layer sizes other than the entry's, an expansion below 1, a patch type other than its role's (each _ patch against its own), patchInfo beyond its type (inGroups), singleRegionName false, an expansionRatio that isn't a number, a name given to more than one surface or box, layers given to a surface by a _ patch's name, levels per solid, surfaces and layers named by a pattern, a patch's own layer settings, outside points, an #include or $macro not followed, macros; several inside points give no entry; the dictionary isn't written: mesh.snappy with replace writes it from the entry), and the material library from the solids' materials (each model's first material whose coefficients are numbers or dictionaries of them; a model whose materials differ noted once, a material with a macro or directive among its coefficients noted and left out). What it couldn't tell (a patch without a role, a region the scripts don't mesh, a step that doesn't fit, a material or its model given by a macro, a material listed more than once) is listed in notes. case.save writes it. A system/umcfWorkflow that is a symbolic link is not written over. Also reads, from the createPatchDict each region's createPatch reads (its own when its steps run createPatch, else system/createPatchDict when its mesh does), the patches made of others (constructFrom patches) into their from, as written (a quoted source a pattern), and their type where the role wouldn't give it; a name given twice is made of both items' sources (noted when it comes again after another patch: any two may take the same faces, through a shared source, a pattern or a patch group); the patches made keep the dictionary's order among the region's patches; an item made of a face set, part of which a macro or directive gives, with a patchInfo that isn't a plain type's dictionary, other keys, a key given twice, or sources with a quote, backslash, brace or space inside or a pattern that may not compile is noted and left out (20 notes a dictionary for each region reading it, then a count).", enabled: needs_case, run: import, journal: true, @@ -223,7 +223,7 @@ pub(super) const PATCH: CommandSpec = CommandSpec { label: "Describe a patch", menu: "Case/Workflow/Describe a patch", shortcut: None, - params: "region, patch: the region of system/umcfWorkflow and its patch (a patch the region doesn't list is added); role: inlet, outlet, side, top, ground, coupled, canopy, interior, bottom or sky (null takes it away); partner: {\"region\", \"patch\"} it is coupled to (null takes it away); from: the patches createPatch makes it of, a list of names and patterns as createPatch reads them (a name that isn't a plain word is quoted for it, a pattern: \"region1_to_.*\"; one given quoted stays so, \"\\\"region.1\\\"\" a regular expression; none with a quote, backslash, brace or space inside, nor a pattern that may not compile (an unclosed bracket or group, a repeat with nothing before it, a group starting (? other than a leading (?i), OpenFOAM's case ignored; at most 64; null takes them away), which workflow.dictionaries writes into the createPatchDict its mesh or steps read; type: the type createPatch makes it of, over the one its role gives (wall for a plain wall without a partner; read only with from, refused without; null takes it away; not a mapped type, which changeDictionary gives from the role and partner); name: a new name for the patch (refused while another patch of the region is made of it, from; the partners that named it follow, and the region's blocks: sides, single faces, patches without faces, types; refused while the region's blocks entry doesn't read whole, or when the blocks name a patch of the new name, or to or from defaultFaces while the region has blocks: the faces left to blockMesh). At least one of them. Edits the description only, entry by entry: its comments and layout stay. The case's own files (the mesh, fields, dictionaries) follow once they are written from it; patch.set renames a patch in the case.", + params: "region, patch: the region of system/umcfWorkflow and its patch (a patch the region doesn't list is added); role: inlet, outlet, side, top, ground, coupled, canopy, interior, bottom or sky (null takes it away); partner: {\"region\", \"patch\"} it is coupled to (null takes it away); from: the patches createPatch makes it of, a list of names and patterns as createPatch reads them (a name that isn't a plain word is quoted for it, a pattern: \"region1_to_.*\"; one given quoted stays so, \"\\\"region.1\\\"\" a regular expression; none with a quote, backslash, brace or space inside, nor a pattern that may not compile (an unclosed bracket or group, a bracket inside a bracket other than a POSIX class such as [:digit:], a repeat with nothing before it, a group starting (? other than a leading (?i), OpenFOAM's case ignored; at most 64; null takes them away), which workflow.dictionaries writes into the createPatchDict its mesh or steps read; type: the type createPatch makes it of, over the one its role gives (wall for a plain wall without a partner; read only with from, refused without; null takes it away; not a mapped type, which changeDictionary gives from the role and partner); name: a new name for the patch (refused while another patch of the region is made of it, from; the partners that named it follow, and the region's blocks: sides, single faces, patches without faces, types; refused while the region's blocks entry doesn't read whole, or when the blocks name a patch of the new name, or to or from defaultFaces while the region has blocks: the faces left to blockMesh). At least one of them. Edits the description only, entry by entry: its comments and layout stay. The case's own files (the mesh, fields, dictionaries) follow once they are written from it; patch.set renames a patch in the case.", enabled: needs_case, run: patch, journal: true, @@ -784,7 +784,7 @@ pub(super) const DICTIONARIES: CommandSpec = CommandSpec { label: "Write the dictionaries", menu: "Case/Workflow/Write the dictionaries", shortcut: None, - params: "region: one region (default: every region). replace: true to write over a dictionary edited by hand or not written by umcfGui (case.save keeps a backup of each). Writes, from system/umcfWorkflow and for its OpenFOAM version (the case's when it names none), each region's system//changeDictionaryDict whose steps run changeDictionary: every patch with a partner, mappedWall to it when its role is a wall's (ground, coupled, interior, bottom) and mapped (mappedPatch in OpenFOAM-8) when it is an open side's (inlet, outlet, side, top, sky), with neighbourRegion and neighbourPatch (OpenFOAM-8: sampleMode nearestPatchFace, sampleRegion, samplePatch) and a uniform offset of (0 0 0); a fluid's and a solid's patches paired by method nearest (OpenFOAM-12), a vegetation patch and its twin without; the vegetation region's canopy mapped to the air's cells (mappedInternal, offsetMode normal, distance 0; OpenFOAM-8: mappedWall, sampleMode nearestCell), the air being the fluid region its other patches are coupled to, else the radiation's lai region, else the only fluid region. Patches without a partner are left as the mesh makes them. Generated, with a checksum: one written by umcfGui and unchanged since is written over without replace. Refused, writing none: a description with problems (workflow.show lists them), a patch with a partner but no role, a partner region the description doesn't have, a canopy with a partner or with no air to map to, a region, patch or partner name that isn't a plain OpenFOAM word (they are written unquoted), a region's name that can't be a directory on every system (., .., a colon, a dot at its end, a Windows device's name), a region named that the description doesn't have, a dictionary there that doesn't load (or a directory: mend or remove it), one that is a symbolic link or the same file as another dictionary, and, without replace, one there that differs and wasn't written by umcfGui. Also writes each createPatchDict the mesh or steps read: system//createPatchDict for a region whose steps run createPatch, system/createPatchDict for the regions meshed with createPatch in constant/polyMesh (one for them all: they must make the same patches); each patch made of others (from) as { name; patchInfo { type; } constructFrom patches; patches ( … ); }, the sources as the description has them (a quoted one a pattern), its type the patch's own (type), else wall for a wall's role (ground, coupled, interior, bottom), the canopy and every solid's patch, else patch; pointSync false for OpenFOAM-8. Refused, too: a patch made by createPatch with neither a role nor a type, or in a region whose mesh and steps run no createPatch, a region running createPatch both in and after its mesh with patches to make, and regions sharing system/createPatchDict that make other patches, or make them in another order where their sources may overlap (the order is the regions' patches', which is createPatch's: a face two patches take goes to the last). The case's own createPatchDict that holds what the description can't (a patch it doesn't make or gives twice, one made of a face set or of sources it can't hold, patchInfo entries besides the type or other keys of an item, a key given twice in an item or its patchInfo, a value from a macro or directive, a patches list that can't be read whole, another entry at its top or in its FoamFile header, OpenFOAM-8's pointSync not off) is left as it is even with replace, noted with what would be lost; the others are written. With region, that region's dictionaries (and the shared createPatchDict when its mesh runs createPatch); a region whose mesh and steps run neither changeDictionary nor createPatch is refused. The outcome lists what was written, written over by hand edits, unchanged, and left as it is (left: holding what the description can't), and notes a region with coupled patches whose steps don't run changeDictionary. case.save writes them; edit.undo takes them back.", + params: "region: one region (default: every region). replace: true to write over a dictionary edited by hand or not written by umcfGui (case.save keeps a backup of each). Writes, from system/umcfWorkflow and for its OpenFOAM version (the case's when it names none), each region's system//changeDictionaryDict whose steps run changeDictionary: every patch with a partner, mappedWall to it when its role is a wall's (ground, coupled, interior, bottom) and mapped (mappedPatch in OpenFOAM-8) when it is an open side's (inlet, outlet, side, top, sky), with neighbourRegion and neighbourPatch (OpenFOAM-8: sampleMode nearestPatchFace, sampleRegion, samplePatch) and a uniform offset of (0 0 0); a fluid's and a solid's patches paired by method nearest (OpenFOAM-12), a vegetation patch and its twin without; the vegetation region's canopy mapped to the air's cells (mappedInternal, offsetMode normal, distance 0; OpenFOAM-8: mappedWall, sampleMode nearestCell), the air being the fluid region its other patches are coupled to, else the radiation's lai region, else the only fluid region. Patches without a partner are left as the mesh makes them. Generated, with a checksum: one written by umcfGui and unchanged since is written over without replace. Refused, writing none: a description with problems (workflow.show lists them), a patch with a partner but no role, a partner region the description doesn't have, a canopy with a partner or with no air to map to, a region, patch or partner name that isn't a plain OpenFOAM word (they are written unquoted), a region's name that can't be a directory on every system (., .., a colon, a dot at its end, a Windows device's name), a region named that the description doesn't have, a dictionary there that doesn't load (or a directory: mend or remove it), one that is a symbolic link or the same file as another dictionary, and, without replace, one there that differs and wasn't written by umcfGui. Also writes each createPatchDict the mesh or steps read: system//createPatchDict for a region whose steps run createPatch, system/createPatchDict for the regions meshed with createPatch in constant/polyMesh (one for them all: they must make the same patches); each patch made of others (from) as { name; patchInfo { type; } constructFrom patches; patches ( … ); }, the sources as the description has them (a quoted one a pattern), its type the patch's own (type), else wall for a wall's role (ground, coupled, interior, bottom), the canopy and every solid's patch, else patch; pointSync false for OpenFOAM-8. Refused, too: a patch made by createPatch with neither a role nor a type, or in a region whose mesh and steps run no createPatch, a region running createPatch both in and after its mesh with patches to make, and regions sharing system/createPatchDict that make other patches, or make them in another order (the order is the regions' patches', which is createPatch's: a face two patches take goes to the last, and any two may take the same faces, through a shared source, a pattern or a patch group). The case's own createPatchDict that holds what the description can't (a patch it doesn't make or gives twice, one made of a face set or of sources it can't hold, patchInfo entries besides the type or other keys of an item, a key given twice in an item or its patchInfo, a value from a macro or directive, a patches list that can't be read whole, another entry at its top or in its FoamFile header, OpenFOAM-8's pointSync not off) is left as it is even with replace, noted with what would be lost; the others are written. With region, that region's dictionaries (and the shared createPatchDict when its mesh runs createPatch); a region whose mesh and steps run neither changeDictionary nor createPatch is refused. The outcome lists what was written, written over by hand edits, unchanged, and left as it is (left: holding what the description can't), and notes a region with coupled patches whose steps don't run changeDictionary. case.save writes them; edit.undo takes them back (a run that writes nothing adds no step to the history and leaves what can be redone).", enabled: needs_case, run: dictionaries, journal: true, @@ -946,10 +946,12 @@ fn dictionaries(s: &mut Session, p: &Value) -> Result { count(left.len(), "createPatchDict") ) }; - Ok(Outcome::new( + let outcome = Outcome::new( message, json!({ "version": version.to_string(), "written": written, "replaced": by_hand, "unchanged": same, "left": left, "notes": notes }), - )) + ); + // Nothing written: no step in the history, and what can be redone stays. + Ok(if changed.is_empty() { outcome.unchanged() } else { outcome }) } /// The outcome of an edit: the message, and the description as it is now. diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index fdc0a81..c6c6e5a 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -85,11 +85,21 @@ impl std::fmt::Debug for CommandSpec { pub struct Outcome { pub message: String, pub data: Value, + /// Whether the case is as it was: an undoable command that changed nothing adds no step to + /// the history, and what can be redone stays. + pub unchanged: bool, } impl Outcome { pub fn new(message: impl Into, data: Value) -> Self { - Outcome { message: message.into(), data } + Outcome { message: message.into(), data, unchanged: false } + } + + /// The same, for a case left as it was ([`Outcome::unchanged`]). + #[must_use] + pub fn unchanged(mut self) -> Self { + self.unchanged = true; + self } } @@ -443,7 +453,7 @@ impl Session { } Ok(Ok(outcome)) => { self.prune_selection(); - if let Some(case) = before { + if let Some(case) = before.filter(|_| !outcome.unchanged) { let edit = Edit { command: spec.id, label: spec.label, detail: detail(params) }; self.undo.push(Step { case, edit }); if self.undo.len() > UNDO_DEPTH { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 4a7061b..2495dc4 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -5286,6 +5286,14 @@ fn each_create_patch_dict_is_written_from_the_patches_made_of_others() { // Left as it is isn't the same as described already. assert!(!out.message.starts_with("the dictionaries are as"), "{}", out.message); assert_eq!(out.data["left"], json!(["system/air/createPatchDict"]), "{}", out.data); + // Nothing written: no step in the history, what can be redone stays. + s.execute("workflow.patch", &json!({"region": "air", "patch": "extra", "role": "side"})).unwrap(); + s.execute("edit.undo", &Value::Null).unwrap(); + let undo = s.history().0.len(); + let again = s.execute("workflow.dictionaries", &json!({"region": "air", "replace": true})).unwrap(); + assert!(again.unchanged, "{}", again.message); + assert!(s.can_redo()); + assert_eq!(s.history().0.len(), undo); let many: Vec = (0..65).map(|i| format!("p{i}")).collect(); let e = s .execute("workflow.patch", &json!({"region": "air", "patch": "buildings", "from": many})) diff --git a/crates/model/src/create_patch.rs b/crates/model/src/create_patch.rs index 19ae66e..955e1a6 100644 --- a/crates/model/src/create_patch.rs +++ b/crates/model/src/create_patch.rs @@ -156,9 +156,9 @@ pub fn targets(d: &Description, only: Option<&str>) -> Result, Strin } let at: HashMap<&str, usize> = made.iter().enumerate().map(|(i, m)| (m.patch.as_str(), i)).collect(); - if let Some((a, b)) = out_of_order(&t.made, &at) { + if let Some((a, b)) = out_of_order(t.made.iter().map(|m| m.patch.as_str()), &at) { return Err(format!( - "regions {} and {} are meshed in constant/polyMesh with createPatch, which reads system/createPatchDict for both: they make {a} and {b}, whose sources may overlap, in another order (createPatch gives a face to the last that takes it): list them in the same order", + "regions {} and {} are meshed in constant/polyMesh with createPatch, which reads system/createPatchDict for both: they make {a} and {b} in another order (createPatch gives a face to the last that takes it, and any two may take the same faces: a source both name, a pattern, a patch group): list them in the same order", t.regions[0], r.name )); } @@ -389,42 +389,27 @@ fn source_set(from: &[String]) -> Vec { v } -/// The most patches made whose order is compared, two by two, and the most source lookups -/// that takes: what a hostile file can't make slow (a description has far fewer). -pub(crate) const MAX_ORDERED: usize = 256; -const ORDER_BUDGET: usize = 1 << 20; - -/// Two of `made` whose sources may take the same faces (a source both name, or a pattern in -/// either, which may match what the other names) and whose order `at` (a patch's place -/// elsewhere) has the other way round: `createPatch` gives a face to the last patch taking it, so -/// their order decides where the faces they share go. Patches `at` doesn't place aren't -/// compared; the first [`MAX_ORDERED`] are, within [`ORDER_BUDGET`] lookups. -fn out_of_order<'a>(made: &'a [Made], at: &HashMap<&str, usize>) -> Option<(&'a str, &'a str)> { - let placed: Vec<(&Made, usize, HashSet, bool)> = made - .iter() - .take(MAX_ORDERED) - .filter_map(|m| { - let p = at.get(m.patch.as_str())?; - let set: HashSet = m.from.iter().map(|f| normal(f)).collect(); - let pattern = set.iter().any(|s| s.starts_with('"')); - Some((m, *p, set, pattern)) - }) - .collect(); - let mut budget = ORDER_BUDGET; - for (i, (a, pa, sa, qa)) in placed.iter().enumerate() { - for (b, pb, sb, qb) in placed.iter().skip(i + 1) { - if pb >= pa { +/// Two patches of `seq` (the names of a dictionary's items, in its order) that `at` (a patch's +/// place elsewhere) has the other way round, or a name given again around another: the one +/// before, and the one after. `createPatch` gives a face to the last item that takes it, and any +/// two may take the same faces (a source both name, a pattern, a name that is a patch group, as +/// OpenFOAM takes a name no patch has), so their order decides where those faces go. Items `at` +/// doesn't place aren't compared (one the description doesn't make is a difference of its own, +/// and a name given again around it isn't seen as such); one given again right after itself is +/// one item. In one pass. +fn out_of_order<'a>(seq: impl IntoIterator, at: &HashMap<&str, usize>) -> Option<(&'a str, &'a str)> { + let mut last: Option<(&str, usize)> = None; + for n in seq { + let Some(&p) = at.get(n) else { continue }; + if let Some((m, q)) = last { + if m == n { continue; } - if *qa || *qb { - return Some((&a.patch, &b.patch)); - } - let (small, big) = if sa.len() < sb.len() { (sa, sb) } else { (sb, sa) }; - budget = budget.checked_sub(small.len().max(1))?; - if small.iter().any(|f| big.contains(f)) { - return Some((&a.patch, &b.patch)); + if p <= q { + return Some((m, n)); } } + last = Some((n, p)); } None } @@ -558,19 +543,12 @@ pub fn differences(root: &Dict, made: &[Made], version: OfVersion) -> Vec = HashMap::with_capacity(there.len()); - let mut last_at: HashMap<&str, usize> = HashMap::with_capacity(there.len()); - for (i, t) in there.iter().enumerate() { - if let Some(n) = t.name.as_deref() { - first_at.entry(n).or_insert(i); - last_at.insert(n, i); - } - } - if let Some((a, b)) = out_of_order(made, &first_at).or_else(|| out_of_order(made, &last_at)) { + // The order: any two may take the same faces, and the last takes them (a name given again + // around another is in both places). + let at: HashMap<&str, usize> = made.iter().enumerate().map(|(i, m)| (m.patch.as_str(), i)).collect(); + if let Some((a, b)) = out_of_order(there.iter().filter_map(|t| t.name.as_deref()), &at) { out.push(format!( - "patches {a} and {b}, whose sources may overlap, are made in the other order there, or one is given again around the other (createPatch gives a face to the last that takes it)" + "patches {a} and {b} are made in the other order there, or one is given again around the other (createPatch gives a face to the last that takes it, and any two may take the same faces: a source both name, a pattern, a patch group)" )); } let mut said: HashSet<&str> = HashSet::new(); @@ -660,7 +638,8 @@ pub fn kept(root: &Dict, made: &[Made], version: OfVersion) -> Vec { out.push("a patch without a plain name".to_string()); continue; }; - let sources_held = t.from.as_ref().is_some_and(|f| f.iter().all(|s| source_ok(s))); + // An empty list moves no faces, which the description can't say (an empty from makes none). + let sources_held = t.from.as_ref().is_some_and(|f| !f.is_empty() && f.iter().all(|s| source_ok(s))); let shown = cut(n); let first = seen.insert(n); if !names.contains(n) { @@ -732,9 +711,13 @@ pub fn source_ok(t: &str) -> bool { } } +/// The character classes POSIX names (`[[:digit:]]`), which every `regcomp` knows. +const POSIX_CLASSES: [&str; 12] = + ["alnum", "alpha", "blank", "cntrl", "digit", "graph", "lower", "print", "punct", "space", "upper", "xdigit"]; + /// Whether `re` is a regular expression OpenFOAM compiles, as far as can be told without its /// regex library (POSIX extended, `regcomp` with `REG_EXTENDED`, in OpenFOAM-8 and -12): brackets -/// closed and not empty, no bracket inside one, ranges upward, groups closed and not starting +/// closed and not empty, no bracket inside one but a POSIX class (`[:digit:]`), ranges upward, groups closed and not starting /// `(?`, a repeat (`* + ?`) only after what it repeats. Stricter than both, never looser: /// what may not compile is refused. fn regex_ok(re: &str) -> bool { @@ -754,12 +737,31 @@ fn regex_ok(re: &str) -> bool { if chars.peek() == Some(&'^') { chars.next(); } - let mut class: Vec = Vec::new(); + // Its members: a character, or a POSIX class (`[:digit:]`, None), which no range + // may end at. + let mut class: Vec> = Vec::new(); loop { match chars.next() { - None | Some('[') => return false, + None => return false, Some(']') => break, - Some(x) => class.push(x), + Some('[') => { + if chars.next() != Some(':') { + return false; + } + let mut name = String::new(); + loop { + match chars.next() { + Some(':') => break, + Some(x) if x.is_ascii_lowercase() && name.len() < 8 => name.push(x), + _ => return false, + } + } + if chars.next() != Some(']') || !POSIX_CLASSES.contains(&name.as_str()) { + return false; + } + class.push(None); + } + Some(x) => class.push(Some(x)), } } if class.is_empty() { @@ -767,11 +769,16 @@ fn regex_ok(re: &str) -> bool { } let mut i = 1; while i + 1 < class.len() { - // Upward, and not chained (`a-c-e`, which POSIX leaves undefined). - if class.get(i) == Some(&'-') - && (class.get(i - 1) > class.get(i + 1) || class.get(i + 2) == Some(&'-')) - { - return false; + // Upward, between characters, and not chained (`a-c-e`, which POSIX leaves + // undefined). + if class.get(i) == Some(&Some('-')) { + match (class.get(i - 1), class.get(i + 1)) { + (Some(Some(lo)), Some(Some(hi))) if lo <= hi => {} + _ => return false, + } + if class.get(i + 2) == Some(&Some('-')) { + return false; + } } i += 1; } diff --git a/crates/model/src/create_patch_tests.rs b/crates/model/src/create_patch_tests.rs index fff45df..7ac9387 100644 --- a/crates/model/src/create_patch_tests.rs +++ b/crates/model/src/create_patch_tests.rs @@ -157,11 +157,12 @@ fn what_cant_be_written_is_refused() { assert!(e.contains("patch `two words` of region street isn't a plain OpenFOAM word"), "{e}"); let e = refused(&|d| d.regions[2].name = "con".into()); assert!(e.contains("region `con` can't be a directory on every system"), "{e}"); - // The same patches in another order are the same. + // The same patches in another order: refused, as any two may take the same faces (a + // name may be a patch group). let mut d = three(); d.regions[0].patches.push(patch("roofs", Some(Role::Coupled), &["x"])); d.regions[1].patches.insert(0, patch("roofs", Some(Role::Coupled), &["x"])); - assert!(targets(&d, None).is_ok()); + assert!(targets(&d, None).unwrap_err().contains("in another order")); } #[test] @@ -494,14 +495,16 @@ fn the_order_decides_where_shared_faces_go() { let mut d = two(["roof", "wall"]); d.regions[1].patches.reverse(); let e = targets(&d, None).unwrap_err(); - assert!(e.contains("they make roof and wall, whose sources may overlap, in another order"), "{e}"); - // Sources that can't overlap: any order. + assert!(e.contains("they make roof and wall in another order"), "{e}"); + // Sources by other names: a name may be a patch group holding the other, so any order + // other than the same is refused too. let mut d = two(["roof", "wall"]); for r in &mut d.regions { - r.patches[1].from = vec!["other".into()]; + r.patches[1].from = vec!["facades".into()]; } - d.regions[1].patches.reverse(); assert!(targets(&d, None).is_ok()); + d.regions[1].patches.reverse(); + assert!(targets(&d, None).unwrap_err().contains("they make roof and wall in another order")); // The case's own in the other order: a difference, not what the description can't hold. let made = targets(&two(["roof", "wall"]), None).unwrap().remove(0).made; let item = @@ -510,57 +513,52 @@ fn the_order_decides_where_shared_faces_go() { assert_eq!( differences(&root(&other), &made, OfVersion::V12), [ - "patches roof and wall, whose sources may overlap, are made in the other order there, or one is given again around the other (createPatch gives a face to the last that takes it)" + "patches wall and roof are made in the other order there, or one is given again around the other (createPatch gives a face to the last that takes it, and any two may take the same faces: a source both name, a pattern, a patch group)" ] ); assert_eq!(kept(&root(&other), &made, OfVersion::V12), Vec::::new()); let same = format!("patches ( {} {} );", item("roof"), item("wall")); assert_eq!(differences(&root(&same), &made, OfVersion::V12), Vec::::new()); - // A name given again after the other: its last item decides too. + // A name given again right after itself: one item. + let twice = format!("patches ( {} {} {} );", item("roof"), item("roof"), item("wall")); + assert_eq!(differences(&root(&twice), &made, OfVersion::V12), Vec::::new()); + // A name given again around the other: the faces both take may go elsewhere, whatever the + // places of each name's first and last items. let again = format!("patches ( {} {} {} );", item("roof"), item("wall"), item("roof")); assert_eq!(differences(&root(&again), &made, OfVersion::V12).len(), 1); - // Many patches: compared two by two among the first few hundred only, quickly. - let many = |reversed: bool| { + let at = + |n: &str, s: &str| format!("{{ name {n}; patchInfo {{ type wall; }} constructFrom patches; patches ({s}); }}"); + let made = vec![ + Made { patch: "roof".into(), kind: "wall".into(), from: vec!["x".into(), "y".into()] }, + Made { patch: "wall".into(), kind: "wall".into(), from: vec!["y".into(), "z".into()] }, + ]; + let around = + format!("patches ( {} {} {} {} );", at("roof", "x"), at("wall", "y"), at("roof", "y"), at("wall", "z")); + let d = differences(&root(&around), &made, OfVersion::V12); + assert_eq!(d.len(), 1, "{d:?}"); + assert!(d[0].starts_with("patches wall and roof are made in the other order there"), "{d:?}"); + // An empty list moves no faces, which the description can't say: kept. + let empty = format!("patches ( {} {} );", at("roof", ""), at("wall", "y z")); + assert_eq!(kept(&root(&empty), &made, OfVersion::V12), ["patch roof's sources"]); + // Many patches, in one pass: the other order found wherever it is. + let many = |swap: Option<(usize, usize)>| { let mut d = three(); d.regions.truncate(2); for (k, r) in d.regions.iter_mut().enumerate() { r.patches = (0..20_000) .map(|i| PatchDesc { kind: Some("wall".into()), ..patch(&format!("p{i}"), None, &[&format!("s{i}")]) }) .collect(); - if reversed && k == 1 { - r.patches.reverse(); - } - } - d - }; - assert!(targets(&many(true), None).is_ok()); - assert!(targets(&many(false), None).is_ok()); - // Wide patches, the other order, no source shared: within a budget of lookups. - let wide = |reversed: bool| { - let mut d = three(); - d.regions.truncate(2); - for (k, r) in d.regions.iter_mut().enumerate() { - r.patches = (0..MAX_ORDERED) - .map(|i| { - let from: Vec = (0..2_000).map(|j| format!("s{i}_{j}")).collect(); - PatchDesc { kind: Some("wall".into()), from, ..patch(&format!("p{i}"), None, &[]) } - }) - .collect(); - if reversed && k == 1 { - r.patches.reverse(); + if let Some((i, j)) = swap + && k == 1 + { + r.patches.swap(i, j); } } d }; - assert!(targets(&wide(true), None).is_ok()); - // A shared source among the first: still found at that scale. - let mut d = wide(true); - for r in &mut d.regions { - for p in r.patches.iter_mut().filter(|p| p.name == "p0" || p.name == "p1") { - p.from.push("shared".into()); - } - } - assert!(targets(&d, None).unwrap_err().contains("p0 and p1"), "{:?}", targets(&d, None)); + assert!(targets(&many(None), None).is_ok()); + assert!(targets(&many(Some((300, 301))), None).unwrap_err().contains("they make p300 and p301 in another order")); + assert!(targets(&many(Some((0, 19_999))), None).is_err()); } #[test] @@ -587,6 +585,8 @@ fn patterns_that_may_not_compile_are_refused() { "\"[a-c]x+\"", "\"wall.?\"", "\"(?i)wall.*\"", + "\"wall[[:digit:]]+\"", + "\"[^[:space:]a-c]x\"", ] { assert!(source_ok(ok), "{ok}"); } @@ -604,6 +604,11 @@ fn patterns_that_may_not_compile_are_refused() { "\"(?i)\"", "\"(?i)*\"", "\"[a-c-e]\"", + "\"[[:digits:]]\"", + "\"[[:digit:]\"", + "\"[[:digit]]\"", + "\"[[=a=]]\"", + "\"[a-[:digit:]]\"", ] { assert!(!source_ok(bad), "{bad}"); } diff --git a/crates/model/src/description.rs b/crates/model/src/description.rs index 1d39590..b6b92bd 100644 --- a/crates/model/src/description.rs +++ b/crates/model/src/description.rs @@ -1551,10 +1551,9 @@ fn import_created( let mut imported: HashMap> = HashMap::new(); // The patches made, in the dictionary's order (createPatch's: the last to take a face has it). let mut order: Vec = Vec::new(); - let mut order_at: HashMap = HashMap::new(); - let mut normals: HashMap, bool)> = HashMap::new(); + // For a name given again after another: the name of the item before. + let mut last: Option = None; let mut again: HashSet = HashSet::new(); - let mut budget: usize = 1 << 20; let mut noted = 0usize; let mut note = |notes: &mut Vec, m: String| { noted += 1; @@ -1670,47 +1669,26 @@ fn import_created( let own = |role: Option| { given.clone().filter(|t| role.is_none_or(|r| crate::create_patch::role_type(kind, r) != t.as_str())) }; - // A name given again after others: its sources join the first item's place, which - // changes where faces it shares with those between go (the last to take a face has it). - // (Only the repeat's own sources: those of the first item go where they would anyway.) - // Bounded (a hostile file): the patches after its first item, a few hundred, by their - // sources as createPatch takes them, a budget of lookups for the whole dictionary; a - // patch noted once. - if let Some(first) = order_at.get(&patch) - && order.last() != Some(&patch) - && budget > 0 - && !again.contains(&patch) + // A name given again after another: its sources join the first item's place, which + // changes where the faces it shares with those between go (the last to take a face has + // it), and any two may take the same faces (a source both name, a pattern, a name that is + // a patch group). A patch noted once (a later repeat comes after this one); in one pass. + if let Some(q) = last.as_ref().filter(|q| imported.contains_key(&patch) && **q != patch) + && again.insert(patch.clone()) { - let own: HashSet = from.iter().map(|f| crate::create_patch::normal(f)).collect(); - let own_pattern = own.iter().any(|f| f.starts_with('"')); - let between = order.iter().skip(first.saturating_add(1)).take(crate::create_patch::MAX_ORDERED); - let shared = between.filter_map(|n| normals.get(n).map(|s| (n, s))).find(|(_, (theirs, pattern))| { - let (small, big) = if theirs.len() < own.len() { (theirs, &own) } else { (&own, theirs) }; - budget = budget.saturating_sub(small.len().max(1)); - own_pattern || *pattern || small.iter().any(|f| big.contains(f)) - }); - if let Some((q, _)) = shared { - let q = q.clone(); - again.insert(patch.clone()); - note( - notes, - format!( - "region {name}, patch {patch}: {path} makes it again after {q}, whose sources may overlap: the description makes it of both items' sources in the first one's place, which may give the faces they share to {q} (workflow.dictionaries leaves the file as it is)" - ), - ); - } + note( + notes, + format!( + "region {name}, patch {patch}: {path} makes it again after {q}: the description makes it of both items' sources in the first one's place, which may give faces they share to {q} (any two may take the same faces: a source both name, a pattern, a patch group; workflow.dictionaries leaves the file as it is)" + ), + ); + } + if last.as_ref() != Some(&patch) { + last = Some(patch.clone()); } if !imported.contains_key(&patch) { - order_at.insert(patch.clone(), order.len()); order.push(patch.clone()); } - // Its sources as createPatch takes them, and whether one is a pattern, for the above. - let entry = normals.entry(patch.clone()).or_default(); - for f in &from { - let n = crate::create_patch::normal(f); - entry.1 |= n.starts_with('"'); - entry.0.insert(n); - } match at.get(&patch).and_then(|i| patches.get_mut(*i)) { Some(p) if imported.contains_key(&patch) => { let seen = imported.entry(patch).or_default(); diff --git a/crates/model/src/description_tests.rs b/crates/model/src/description_tests.rs index 4e769ff..f3e03cd 100644 --- a/crates/model/src/description_tests.rs +++ b/crates/model/src/description_tests.rs @@ -1105,19 +1105,22 @@ fn import_keeps_the_order_create_patch_makes_the_patches_in() { let (top_first, m, _) = order(&[made("ground", "x"), made("top", "x")]); assert!(!top_first); assert_eq!(n, m); - // Given again after a patch whose sources may overlap: noted. + // Given again after another patch: noted (any two may take the same faces). let (_, _, notes) = order(&[made("top", "x"), made("ground", "y"), made("top", "y")]); assert!( notes.iter().any(|n| n.contains("patch top: system/air/createPatchDict makes it again after ground")), "{notes:#?}" ); - // A hostile file: a patch of many sources, then many repeats after it: bounded, noted once. + // A hostile file: a patch of many sources, then many repeats after it: noted once. let wide: Vec = (0..50_000).map(|i| format!("s{i}")).collect(); let mut items = vec![made("top", "x"), made("ground", &wide.join(" "))]; items.extend((0..5_000).map(|i| made("top", &format!("s{i}")))); let (_, _, notes) = order(&items); assert_eq!(notes.iter().filter(|n| n.contains("makes it again after ground")).count(), 1, "{notes:#?}"); - // Only the repeat's own sources count: the first item's go where they would anyway. - let (_, _, notes) = order(&[made("top", "x"), made("ground", "x"), made("top", "y")]); + // Sources by other names: one may be a patch group holding the other's, noted too. + let (_, _, notes) = order(&[made("top", "x"), made("ground", "facades"), made("top", "y")]); + assert!(notes.iter().any(|n| n.contains("makes it again after ground")), "{notes:#?}"); + // Given again right after itself: one item, nothing between. + let (_, _, notes) = order(&[made("top", "x"), made("top", "y"), made("ground", "x")]); assert!(notes.iter().all(|n| !n.contains("makes it again")), "{notes:#?}"); } diff --git a/crates/ui-egui/src/workflowcard.rs b/crates/ui-egui/src/workflowcard.rs index 66b401c..6ee808a 100644 --- a/crates/ui-egui/src/workflowcard.rs +++ b/crates/ui-egui/src/workflowcard.rs @@ -163,7 +163,9 @@ fn described( fn undescribed(f: &mut FormState, k: &'static str) { let was = f.initial.get(k).cloned().unwrap_or_default(); let value = f.values.get(k).cloned().unwrap_or_default(); - if value == was { + // Sources by their names: spacing alone isn't an edit (as when rebased). + let unchanged = if k == "from" { value.split_whitespace().eq(was.split_whitespace()) } else { value == was }; + if unchanged { f.values.insert(k, String::new()); } else if let Some(merged) = merge_table(k, &value, &was, "") { f.values.insert(k, merged); diff --git a/docs/user-guide/checks.md b/docs/user-guide/checks.md index f44ae67..36d1d1c 100644 --- a/docs/user-guide/checks.md +++ b/docs/user-guide/checks.md @@ -243,7 +243,7 @@ OpenFOAM version. Each problem names the script and line. | `workflow.blocks` | Warning | A region's [blocks](workflow.md#blocks) in the description: the grid's problems (stations that don't increase, a span without cells or with a section blockMesh would give none, a `cyclic`, `nonConformal`, `mapped` or `processor` type in `types`, more than 10 000 names in a map, a dictionary too large to read back, a missing block outside the grid or listed twice, a whole layer missing, a face without a patch, a single face inside the mesh, too many blocks), a patch the region's `patches` don't list or whose role doesn't fit its side (the ground and top across the gravity of `constant//g`, else `constant/g`, else z up, said), blocks without a `mesh`, a region meshed from another's [background](workflow.md#background) that the scripts can't keep (that region not listed before it, not built by steps of its own starting with `blockMesh`, or a region named as the directory it is kept in) or that has blocks of its own its mesh doesn't read, or that doesn't list the patches of the background's blocks its mesh gets, a [box](workflow.md#box) without blocks, with a problem of its own (a surface name that isn't an STL file of `constant/triSurface`, a negative margin, a cell size not above 0) or around surfaces the case doesn't have, and a `blockMeshDict` that isn't there, doesn't load or isn't what the blocks make (edited by hand, written from other blocks, another patch type): `mesh.block` writes it, listing any type it changes and any patch it drops or adds, and refusing to change a wall or constraint type the call's `types` doesn't give, or to drop such a patch `dropPatches` doesn't name. The grid's problems: the first 20 of them all, then how many more; patches the description doesn't list, and patches whose role doesn't fit: 20 of each, then how many more | | `workflow.snappy` | Warning | A region's [snappy entry](workflow.md#snappy) in the description: its own problems (a cutting surface without a level, distances whose levels grow away from the surface, a feature level on a compressed surface, a box without a length, names given twice, …), a solid region, a mesh that doesn't run snappyHexMesh, a surface the case doesn't have, cutting surfaces' patches the description doesn't list or that another surface or the blocks make too (those of the region whose background its mesh starts from), an inside point outside those blocks, on their sides or in a missing block (the blocks may have changed since `mesh.snappy` checked it), features asked for while the workflow doesn't run `surfaceFeatures`, a `snappyHexMeshDict` that isn't what the entry writes (missing, doesn't load, written from another entry, or edited by hand so that it holds something else than the entry: one of the case's own that holds what the entry does, as `workflow.import` read the entry from it, with the patch types the roles give, is an Info, counting the parts of it the entry can't hold), and a `system/surfaceFeaturesDict` that is missing, doesn't load, was written from other entries, or is the case's own and doesn't list a surface asking for features. The surfaces themselves are checked by `mesh.snappy` | | `workflow.change-dictionary` | Warning | The `changeDictionaryDict` of a region whose steps run `changeDictionary`, against what [`workflow.dictionaries`](workflow.md#writing-the-dictionaries) writes from the patches' roles and partners: one that can't be written (a partner without a role, a partner region not described, a canopy with a partner or no air, a name that isn't a plain OpenFOAM word, or a region's that can't be a directory on every system), one missing or that doesn't load, one umcfGui wrote otherwise than it writes now (other roles or partners, another OpenFOAM version, or an older umcfGui), and the case's own where it differs, by the keys the version reads and only those given (`changeDictionary` merges a block into the mesh's patch, so a key left out keeps the mesh's value, not known before the mesh is made; a region or patch the version reads that is left out is said to be unconfirmed, in OpenFOAM-8 unless OpenFOAM-12's key stands in its place, said to be unread; a patch's block with a `~key`, which takes the key out of the mesh's patch, isn't compared, said so): a patch's type, or the region and patch it maps to (OpenFOAM-8 only `sampleRegion` and `samplePatch`, `neighbourRegion` or `neighbourPatch` in their place said to be unread; OpenFOAM-12 `neighbourRegion` and `neighbourPatch` where given, else the older two, which alone, the description's or not, are said to be unconfirmed, as OpenFOAM-12 reads the newer first and the mesh's patch keeps a newer one it has; OpenFOAM-12's `mappedInternal` reads no patch; OpenFOAM-8 stops on a patch other than `none` in a mode that samples none, `nearestCell`, `nearestOnlyCell` or `nearestFace`, with a `coupleGroup` too, and without a mode given the patch isn't compared; with a `coupleGroup`, OpenFOAM-8 compares the region and patch only when both are given (in `nearestCell` and `nearestOnlyCell` the region alone; `nearestFace` asks the group for a patch not given, refused), OpenFOAM-12 stops on a group given with either, and a partner named by the group alone isn't compared; OpenFOAM-12's `samePatch`, a switch (`true`, `yes`, `on` and the like) or a number other than 0, names the patch of the same name, refused with a patch named too (not compared then), and alone compared and, where it is the description's, said to be unconfirmed, as OpenFOAM-12 refuses it beside a `neighbourPatch`, which it writes on a mapped patch and the mesh's patch keeps, and one that isn't a switch (quoted, too) refused, the patch not compared then; a name that isn't a word, empty (`""`) or a dictionary, is said to be refused, for the keys the version reads, a group's too, and so is a type that is a dictionary), a sample mode OpenFOAM-8 hasn't or one sampling no patch against one sampling a patch, an OpenFOAM-12 `method` (or `sampleMode` read as it) it hasn't, a patch changed that the description doesn't map, a value in `boundary` (which `changeDictionary` adds to the mesh's `boundary` file), a `~patch` there, quoted or not (on which `changeDictionary` stops where the mesh has the patch, or, with a block for it after, writes the block in its place without its faces; neither compared); other methods and modes, the offsets and values given by a macro or directive aren't compared (nor, with an OpenFOAM-8 `sampleMode` from one, the `samplePatch`), a patch mapped only through a pattern or group is said not to be there, keys a patch's block brings in (`$common;`, `#include`) aren't seen, and of a patch given twice only the last is read (OpenFOAM merges them). The case's own that maps them as the description does is fine. Not checked while the description doesn't read whole | -| `workflow.create-patch` | Warning | Each `createPatchDict` the description's meshes and steps read (`system//createPatchDict` for `createPatch -region`, `system/createPatchDict` for the regions meshed with `createPatch` in `constant/polyMesh`), against what [`workflow.dictionaries`](workflow.md#the-createpatchdicts) writes from the patches made of others (`from`) and their roles or types: when they can't be written (a patch made with neither a role nor a type, or in a region running no `createPatch`, a region running it both in and after its mesh with patches to make, regions sharing `system/createPatchDict` that make other patches, or make them in another order where their sources may overlap, a name that isn't a plain word), one missing or that doesn't load (or, where the case lists more files than are read, not loaded and not known to be there), one umcfGui wrote otherwise than it writes now, and the case's own where it makes the patches otherwise: a patch not made there, made of a set or of other patches, of another type or of none (`patchInfo` without a `type`), one made there the description doesn't make, two whose sources may overlap made in the other order (or one given again around the other: `createPatch` gives a face to the last patch that takes it), the `patches` list or OpenFOAM-8's `pointSync` missing, which `createPatch` stops without, a `pointSync` that isn't a switch (a word or a number, not a quoted string), a `patches` list whose count isn't its items'. The sources are compared as their union, in any order; a name or type quoted or not is the same, and so is a source quoted that OpenFOAM doesn't take for a pattern; what a macro or directive gives isn't compared (an item holding one by its name only). Where the case's own holds what the description can't (a patch it doesn't make or gives twice, one made of a face set or of sources it can't hold, `patchInfo` entries besides the type or other keys of an item, a key given twice in an item or its `patchInfo`, a value from a macro or directive, a list that can't be read whole, another entry at its top or in its `FoamFile` header, OpenFOAM-8's `pointSync` not off), it says so, also where it shows no difference (what a macro or directive gives isn't compared), and to describe them with `workflow.patch` or mend the file, as `workflow.dictionaries` leaves it as it is. Not checked while the description doesn't read whole | +| `workflow.create-patch` | Warning | Each `createPatchDict` the description's meshes and steps read (`system//createPatchDict` for `createPatch -region`, `system/createPatchDict` for the regions meshed with `createPatch` in `constant/polyMesh`), against what [`workflow.dictionaries`](workflow.md#the-createpatchdicts) writes from the patches made of others (`from`) and their roles or types: when they can't be written (a patch made with neither a role nor a type, or in a region running no `createPatch`, a region running it both in and after its mesh with patches to make, regions sharing `system/createPatchDict` that make other patches, or make them in another order, a name that isn't a plain word), one missing or that doesn't load (or, where the case lists more files than are read, not loaded and not known to be there), one umcfGui wrote otherwise than it writes now, and the case's own where it makes the patches otherwise: a patch not made there, made of a set or of other patches, of another type or of none (`patchInfo` without a `type`), one made there the description doesn't make, two made in the other order (or one given again around the other: `createPatch` gives a face to the last patch that takes it, and any two may take the same faces, through a shared source, a pattern or a patch group), the `patches` list or OpenFOAM-8's `pointSync` missing, which `createPatch` stops without, a `pointSync` that isn't a switch (a word or a number, not a quoted string), a `patches` list whose count isn't its items'. The sources are compared as their union, in any order; a name or type quoted or not is the same, and so is a source quoted that OpenFOAM doesn't take for a pattern; what a macro or directive gives isn't compared (an item holding one by its name only). Where the case's own holds what the description can't (a patch it doesn't make or gives twice, one made of a face set or of sources it can't hold, `patchInfo` entries besides the type or other keys of an item, a key given twice in an item or its `patchInfo`, a value from a macro or directive, a list that can't be read whole, another entry at its top or in its `FoamFile` header, OpenFOAM-8's `pointSync` not off), it says so, also where it shows no difference (what a macro or directive gives isn't compared), and to describe them with `workflow.patch` or mend the file, as `workflow.dictionaries` leaves it as it is. Not checked while the description doesn't read whole | | `workflow.split` | Warning | A region [split](workflow.md#split) from another by a cell zone: from a region the description doesn't list, lists after it or doesn't build; a zone not named (no script splits it), or that its `topoSetDict` doesn't make, a `topoSetDict` that makes other zones too (they would be split off as well; no script splits it) or whose zones can't be told (`#include`, a macro), or a dictionary the case doesn't have; a zone or `region1` named as a region (the split's clean-up would remove that region's directories), a region named `region` and a number (as `splitMeshRegions` names the parts outside the zone) | ## Finite-volume constraints and pressure limits (OpenFOAM-12) diff --git a/docs/user-guide/workflow.md b/docs/user-guide/workflow.md index 24c5921..c786906 100644 --- a/docs/user-guide/workflow.md +++ b/docs/user-guide/workflow.md @@ -163,7 +163,7 @@ patches by their roles and points them at their partners, as the - Generated, with a checksum: one umcfGui wrote and nobody changed since is written over as the description changes. One edited by hand or not written by umcfGui is written over only with `replace: true`; `case.save` keeps it in `.umcfgui/backup/` and `edit.undo` takes the write - back. One that doesn't load (or a directory there), a symbolic link and one that is the same + back (a run that writes nothing adds no step to the history and leaves what can be redone). One that doesn't load (or a directory there), a symbolic link and one that is the same file as another dictionary aren't written over, and nothing is written then. `region` writes one region's only; a region with coupled patches whose steps don't run `changeDictionary` is noted. @@ -235,8 +235,9 @@ canopy (`"region1_to_.*"`, a pattern). `workflow.dictionaries` writes, for each, -region`, after the mesh); - `system/createPatchDict` for the regions whose mesh runs `createPatch` in `constant/polyMesh` (`mesh ( blockMesh … createPatch … )`, the 3×3 cases' air and vegetation): one dictionary for - them all, so they must make the same patches, in the same order where their sources may - overlap. + them all, so they must make the same patches, in the same order (any two may take the same + faces: a source both name, a pattern, or a name that is a patch group, which OpenFOAM takes a + name no patch has for). The patches are written in the order the region lists them, which is `createPatch`'s: a face two patches' sources take goes to the last. Each patch is `{ name …; patchInfo { type …; } constructFrom patches; patches ( … ); }`, its @@ -249,8 +250,7 @@ stops without it (OpenFOAM-12 doesn't read it). A region whose steps run `create patch to make gets an empty list. Refused, writing none: a patch made by `createPatch` with neither a role nor a type, one in a region whose mesh and steps run no `createPatch`, a region whose mesh and steps both run it with patches to make (which makes them isn't told), regions -meshed in `constant/polyMesh` that make different patches (or in another order, where their -sources may overlap), a patch name that isn't a plain +meshed in `constant/polyMesh` that make different patches (or in another order), a patch name that isn't a plain OpenFOAM word, and a region's name that can't be a directory on every system. Generated, written over and kept as the `changeDictionaryDict`s are (`replace`, `region`: that region's, and the shared one when its mesh runs `createPatch`; a problem in another region's doesn't stop it, @@ -267,8 +267,8 @@ hand; the other dictionaries are written. The case check (`workflow.create-patch`) says when one is missing, doesn't load, was written by umcfGui otherwise than it writes now, or is the case's own and makes the patches otherwise: a patch not made there, made of a set or of other patches, of another type or of none, one made -there that the description doesn't make, two whose sources may overlap made in the other order -(`createPatch` gives a face to the last patch that takes it), the `patches` list or OpenFOAM-8's +there that the description doesn't make, two made in the other order, or one given again around another +(`createPatch` gives a face to the last patch that takes it, and any two may take the same faces), the `patches` list or OpenFOAM-8's `pointSync` missing, which `createPatch` stops without, a `pointSync` that isn't a switch, and a `patches` list whose count isn't its items'; and the case's own that shows no difference but holds what it can't (as above). The sources are compared as `createPatch` takes them, their @@ -409,7 +409,7 @@ space inside, or one that may not compile), part of which a macro or directive g dictionary or holds more than a plain type (a mapped or cyclic patch's entries), is noted and left out (the first 20 of a dictionary, then a count, for each region reading it); a patch given in two items is made of both items' sources (noted where -it comes again after a patch whose sources may overlap its own: the faces they share may then go +it comes again after another patch, whose faces may be the same, through a source both name, a pattern or a patch group: the faces they share may then go elsewhere, and `workflow.dictionaries` leaves the file as it is). The patches made keep the dictionary's order among the region's patches (`createPatch` gives a face to the last patch that takes it); the order of the patches in the description is the order the dictionary makes them in. A region whose mesh From 9f948a4f224b2f13e6105cf3068b6c7b02a36733 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Fri, 27 Nov 2026 14:29:41 +0100 Subject: [PATCH 4/6] M0.101: a hyphen ending a bracket is a character in a source pattern (review) [a-c-] is accepted as POSIX reads it (the range, then a hyphen); a chained range ([a-c-e], [a-c--]) is still refused. --- crates/model/src/create_patch.rs | 3 ++- crates/model/src/create_patch_tests.rs | 3 +++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/model/src/create_patch.rs b/crates/model/src/create_patch.rs index 955e1a6..c2ead28 100644 --- a/crates/model/src/create_patch.rs +++ b/crates/model/src/create_patch.rs @@ -776,7 +776,8 @@ fn regex_ok(re: &str) -> bool { (Some(Some(lo)), Some(Some(hi))) if lo <= hi => {} _ => return false, } - if class.get(i + 2) == Some(&Some('-')) { + // (A hyphen ending the bracket is a character: `[a-c-]`.) + if class.get(i + 2) == Some(&Some('-')) && class.get(i + 3).is_some() { return false; } } diff --git a/crates/model/src/create_patch_tests.rs b/crates/model/src/create_patch_tests.rs index 7ac9387..e98a9ab 100644 --- a/crates/model/src/create_patch_tests.rs +++ b/crates/model/src/create_patch_tests.rs @@ -587,6 +587,8 @@ fn patterns_that_may_not_compile_are_refused() { "\"(?i)wall.*\"", "\"wall[[:digit:]]+\"", "\"[^[:space:]a-c]x\"", + "\"wall[a-c-]\"", + "\"[^a-c-]\"", ] { assert!(source_ok(ok), "{ok}"); } @@ -604,6 +606,7 @@ fn patterns_that_may_not_compile_are_refused() { "\"(?i)\"", "\"(?i)*\"", "\"[a-c-e]\"", + "\"[a-c--]\"", "\"[[:digits:]]\"", "\"[[:digit:]\"", "\"[[:digit]]\"", From a05ed406b6de58f70b360fef821c0fabafa92d01 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Fri, 27 Nov 2026 20:09:05 +0100 Subject: [PATCH 5/6] M0.101: createPatch items read as OpenFOAM does, undo after a save said (review) The case check compares a quoted source as the name it holds only where the name reads the same bare (not "123"), reports a name made of patches and of a set or zone, made of a set or zone beside an item it can't read, an item without a constructFrom wherever it is, and one without a name; a FoamFile value given by a macro keeps the file as it is. The help and guide say that a dictionary a save created stays on disk after edit.undo, and that a run writing nothing stays in the journal. The workflow cards compare a field as the form sends it: from by its names, a partner by its parts, the others trimmed. --- crates/engine/src/cmd/workflow.rs | 2 +- crates/engine/src/lib.rs | 3 +- crates/engine/src/tests.rs | 3 + crates/model/src/create_patch.rs | 80 +++++++++++++++++++++---- crates/model/src/create_patch_tests.rs | 83 ++++++++++++++++++++++++++ crates/model/tests/coupling.rs | 6 +- crates/ui-egui/src/forms.rs | 2 +- crates/ui-egui/src/tests.rs | 17 +++++- crates/ui-egui/src/workflowcard.rs | 23 +++++-- docs/user-guide/checks.md | 2 +- docs/user-guide/workflow.md | 12 ++-- 11 files changed, 204 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/cmd/workflow.rs b/crates/engine/src/cmd/workflow.rs index da454fc..290988e 100644 --- a/crates/engine/src/cmd/workflow.rs +++ b/crates/engine/src/cmd/workflow.rs @@ -784,7 +784,7 @@ pub(super) const DICTIONARIES: CommandSpec = CommandSpec { label: "Write the dictionaries", menu: "Case/Workflow/Write the dictionaries", shortcut: None, - params: "region: one region (default: every region). replace: true to write over a dictionary edited by hand or not written by umcfGui (case.save keeps a backup of each). Writes, from system/umcfWorkflow and for its OpenFOAM version (the case's when it names none), each region's system//changeDictionaryDict whose steps run changeDictionary: every patch with a partner, mappedWall to it when its role is a wall's (ground, coupled, interior, bottom) and mapped (mappedPatch in OpenFOAM-8) when it is an open side's (inlet, outlet, side, top, sky), with neighbourRegion and neighbourPatch (OpenFOAM-8: sampleMode nearestPatchFace, sampleRegion, samplePatch) and a uniform offset of (0 0 0); a fluid's and a solid's patches paired by method nearest (OpenFOAM-12), a vegetation patch and its twin without; the vegetation region's canopy mapped to the air's cells (mappedInternal, offsetMode normal, distance 0; OpenFOAM-8: mappedWall, sampleMode nearestCell), the air being the fluid region its other patches are coupled to, else the radiation's lai region, else the only fluid region. Patches without a partner are left as the mesh makes them. Generated, with a checksum: one written by umcfGui and unchanged since is written over without replace. Refused, writing none: a description with problems (workflow.show lists them), a patch with a partner but no role, a partner region the description doesn't have, a canopy with a partner or with no air to map to, a region, patch or partner name that isn't a plain OpenFOAM word (they are written unquoted), a region's name that can't be a directory on every system (., .., a colon, a dot at its end, a Windows device's name), a region named that the description doesn't have, a dictionary there that doesn't load (or a directory: mend or remove it), one that is a symbolic link or the same file as another dictionary, and, without replace, one there that differs and wasn't written by umcfGui. Also writes each createPatchDict the mesh or steps read: system//createPatchDict for a region whose steps run createPatch, system/createPatchDict for the regions meshed with createPatch in constant/polyMesh (one for them all: they must make the same patches); each patch made of others (from) as { name; patchInfo { type; } constructFrom patches; patches ( … ); }, the sources as the description has them (a quoted one a pattern), its type the patch's own (type), else wall for a wall's role (ground, coupled, interior, bottom), the canopy and every solid's patch, else patch; pointSync false for OpenFOAM-8. Refused, too: a patch made by createPatch with neither a role nor a type, or in a region whose mesh and steps run no createPatch, a region running createPatch both in and after its mesh with patches to make, and regions sharing system/createPatchDict that make other patches, or make them in another order (the order is the regions' patches', which is createPatch's: a face two patches take goes to the last, and any two may take the same faces, through a shared source, a pattern or a patch group). The case's own createPatchDict that holds what the description can't (a patch it doesn't make or gives twice, one made of a face set or of sources it can't hold, patchInfo entries besides the type or other keys of an item, a key given twice in an item or its patchInfo, a value from a macro or directive, a patches list that can't be read whole, another entry at its top or in its FoamFile header, OpenFOAM-8's pointSync not off) is left as it is even with replace, noted with what would be lost; the others are written. With region, that region's dictionaries (and the shared createPatchDict when its mesh runs createPatch); a region whose mesh and steps run neither changeDictionary nor createPatch is refused. The outcome lists what was written, written over by hand edits, unchanged, and left as it is (left: holding what the description can't), and notes a region with coupled patches whose steps don't run changeDictionary. case.save writes them; edit.undo takes them back (a run that writes nothing adds no step to the history and leaves what can be redone).", + params: "region: one region (default: every region). replace: true to write over a dictionary edited by hand or not written by umcfGui (case.save keeps a backup of each). Writes, from system/umcfWorkflow and for its OpenFOAM version (the case's when it names none), each region's system//changeDictionaryDict whose steps run changeDictionary: every patch with a partner, mappedWall to it when its role is a wall's (ground, coupled, interior, bottom) and mapped (mappedPatch in OpenFOAM-8) when it is an open side's (inlet, outlet, side, top, sky), with neighbourRegion and neighbourPatch (OpenFOAM-8: sampleMode nearestPatchFace, sampleRegion, samplePatch) and a uniform offset of (0 0 0); a fluid's and a solid's patches paired by method nearest (OpenFOAM-12), a vegetation patch and its twin without; the vegetation region's canopy mapped to the air's cells (mappedInternal, offsetMode normal, distance 0; OpenFOAM-8: mappedWall, sampleMode nearestCell), the air being the fluid region its other patches are coupled to, else the radiation's lai region, else the only fluid region. Patches without a partner are left as the mesh makes them. Generated, with a checksum: one written by umcfGui and unchanged since is written over without replace. Refused, writing none: a description with problems (workflow.show lists them), a patch with a partner but no role, a partner region the description doesn't have, a canopy with a partner or with no air to map to, a region, patch or partner name that isn't a plain OpenFOAM word (they are written unquoted), a region's name that can't be a directory on every system (., .., a colon, a dot at its end, a Windows device's name), a region named that the description doesn't have, a dictionary there that doesn't load (or a directory: mend or remove it), one that is a symbolic link or the same file as another dictionary, and, without replace, one there that differs and wasn't written by umcfGui. Also writes each createPatchDict the mesh or steps read: system//createPatchDict for a region whose steps run createPatch, system/createPatchDict for the regions meshed with createPatch in constant/polyMesh (one for them all: they must make the same patches); each patch made of others (from) as { name; patchInfo { type; } constructFrom patches; patches ( … ); }, the sources as the description has them (a quoted one a pattern), its type the patch's own (type), else wall for a wall's role (ground, coupled, interior, bottom), the canopy and every solid's patch, else patch; pointSync false for OpenFOAM-8. Refused, too: a patch made by createPatch with neither a role nor a type, or in a region whose mesh and steps run no createPatch, a region running createPatch both in and after its mesh with patches to make, and regions sharing system/createPatchDict that make other patches, or make them in another order (the order is the regions' patches', which is createPatch's: a face two patches take goes to the last, and any two may take the same faces, through a shared source, a pattern or a patch group). The case's own createPatchDict that holds what the description can't (a patch it doesn't make or gives twice, one made of a face set or of sources it can't hold, patchInfo entries besides the type or other keys of an item, a key given twice in an item or its patchInfo, a value from a macro or directive (in its FoamFile header too), a patches list that can't be read whole, another entry at its top or in its FoamFile header, OpenFOAM-8's pointSync not off) is left as it is even with replace, noted with what would be lost; the others are written. With region, that region's dictionaries (and the shared createPatchDict when its mesh runs createPatch); a region whose mesh and steps run neither changeDictionary nor createPatch is refused. The outcome lists what was written, written over by hand edits, unchanged, and left as it is (left: holding what the description can't), and notes a region with coupled patches whose steps don't run changeDictionary. case.save writes them; edit.undo takes them back before case.save; after it, saving again brings back the file a save wrote over, but a dictionary a save created stays on disk (case.save removes no file): delete it by hand. A run that writes nothing adds no step to the history and leaves what can be redone (the journal keeps it).", enabled: needs_case, run: dictionaries, journal: true, diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index c6c6e5a..1c578cb 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -86,7 +86,8 @@ pub struct Outcome { pub message: String, pub data: Value, /// Whether the case is as it was: an undoable command that changed nothing adds no step to - /// the history, and what can be redone stays. + /// the history, and what can be redone stays (the journal keeps it: run on another case, it + /// may change that one). pub unchanged: bool, } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 2495dc4..7648384 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -5290,10 +5290,13 @@ fn each_create_patch_dict_is_written_from_the_patches_made_of_others() { s.execute("workflow.patch", &json!({"region": "air", "patch": "extra", "role": "side"})).unwrap(); s.execute("edit.undo", &Value::Null).unwrap(); let undo = s.history().0.len(); + let journal = s.journal().len(); let again = s.execute("workflow.dictionaries", &json!({"region": "air", "replace": true})).unwrap(); assert!(again.unchanged, "{}", again.message); assert!(s.can_redo()); assert_eq!(s.history().0.len(), undo); + // Kept in the journal: replayed on another case, it may write there. + assert_eq!(s.journal().len(), journal + 1); let many: Vec = (0..65).map(|i| format!("p{i}")).collect(); let e = s .execute("workflow.patch", &json!({"region": "air", "patch": "buildings", "from": many})) diff --git a/crates/model/src/create_patch.rs b/crates/model/src/create_patch.rs index c2ead28..608bde8 100644 --- a/crates/model/src/create_patch.rs +++ b/crates/model/src/create_patch.rs @@ -373,10 +373,17 @@ fn pattern(inner: &str) -> bool { } /// How a source compares: a quoted one OpenFOAM doesn't take for a pattern is the name it holds, -/// as `createPatch` matches it; else as written. +/// as `createPatch` matches it, unless the name written bare would be read otherwise (`123`, a +/// number, or starting with a sign or a dot); else as written. pub(crate) fn normal(t: &str) -> String { match t.strip_prefix('"').and_then(|r| r.strip_suffix('"')) { - Some(inner) if t.len() >= 2 && !pattern(inner) => inner.to_string(), + Some(inner) + if t.len() >= 2 + && !pattern(inner) + && !inner.starts_with(|c: char| c.is_ascii_digit() || matches!(c, '+' | '-' | '.')) => + { + inner.to_string() + } _ => t.to_string(), } } @@ -426,8 +433,9 @@ pub(crate) fn listed(values: &[Node]) -> Option<&[Node]> { /// How a `createPatchDict` (`root`, the file's top level) differs from the patches `made`, for /// `version`: a patch not made there, made of a set or of other patches (in any order: their -/// union), of what isn't a list of names, of another type, one made there the description -/// doesn't make, and the `patches` list or OpenFOAM-8's `pointSync` missing, which +/// union), of both (in two items), of what isn't a list of names, of another type, one made +/// there the description doesn't make, an item read whole without a name or a constructFrom, two patches in the +/// other order (or one given again around another), and the `patches` list or OpenFOAM-8's `pointSync` missing, which /// `createPatch` stops without. A name or type quoted or not is the same, and so is a source /// quoted that OpenFOAM doesn't take for a pattern; what a macro or directive gives isn't /// compared (an item holding one is compared by its name only); a `patches` list that isn't one @@ -461,8 +469,21 @@ pub fn differences(root: &Dict, made: &[Made], version: OfVersion) -> Vec = HashMap::with_capacity(there.len()); + // How a name's items read whole make it, in any order: one without a constructFrom (which + // stops createPatch), one of patches, and what else they are made of (the first by name, so + // the message doesn't depend on the order: a set, a zone): what that moves isn't the + // description's, whatever an item that can't be read whole holds. + let mut ways: HashMap<&str, (bool, bool, Option<&str>)> = HashMap::with_capacity(there.len()); for t in &there { let Some(n) = t.name.as_deref() else { continue }; + if t.told { + let w = ways.entry(n).or_default(); + match t.construct.as_deref() { + None => w.0 = true, + Some("patches") => w.1 = true, + Some(c) => w.2 = Some(w.2.map_or(c, |o: &str| o.min(c))), + } + } match by_name.get_mut(n) { None => { by_name.insert( @@ -481,7 +502,7 @@ pub fn differences(root: &Dict, made: &[Made], version: OfVersion) -> Vec { - first.told &= t.told && t.construct == first.construct; + first.told &= t.told; match (&mut first.from, &t.from) { (Some(a), Some(b)) => a.extend(b.iter().cloned()), (a, _) => *a = None, @@ -489,7 +510,12 @@ pub fn differences(root: &Dict, made: &[Made], version: OfVersion) -> Vec = made.iter().map(|m| m.patch.as_str()).collect(); for m in made { let Some(t) = by_name.get(m.patch.as_str()) else { @@ -499,6 +525,31 @@ pub fn differences(root: &Dict, made: &[Made], version: OfVersion) -> Vec { + out.push(format!( + "patch {} is made in two ways there (items of other patches and of a set or zone), the description makes it of ( {} )", + m.patch, + shown(&m.from) + )); + continue; + } + Some(c) => { + out.push(format!( + "patch {} is made of a {} there, the description makes it of ( {} )", + m.patch, + cut(c), + shown(&m.from) + )); + continue; + } + None => {} + } if !t.told { continue; } @@ -570,8 +621,9 @@ pub fn differences(root: &Dict, made: &[Made], version: OfVersion) -> Vec Vec { let mut out = Vec::new(); if root.items.iter().any(|i| matches!(i, Item::Directive { .. } | Item::Macro { .. })) { @@ -587,12 +639,16 @@ pub fn kept(root: &Dict, made: &[Made], version: OfVersion) -> Vec { match e.key() { "FoamFile" => match e.dict() { Some(h) => { - for k in h.entries().map(|x| x.key()) { + for x in h.entries() { + let k = x.key(); if !matches!(k, "version" | "format" | "class" | "location" | "object") { out.push(format!("its FoamFile {}", cut(k))); - if out.len() > 2 * MAX_KEPT { - break; - } + } else if holds_untold(&x.value) { + // Written over, the value would be lost. + out.push(format!("its FoamFile {k}, given by a macro or directive")); + } + if out.len() > 2 * MAX_KEPT { + break; } } if h.items.iter().any(|i| !matches!(i, Item::Entry(_))) { diff --git a/crates/model/src/create_patch_tests.rs b/crates/model/src/create_patch_tests.rs index e98a9ab..8e7d477 100644 --- a/crates/model/src/create_patch_tests.rs +++ b/crates/model/src/create_patch_tests.rs @@ -618,3 +618,86 @@ fn patterns_that_may_not_compile_are_refused() { assert_eq!(source_token("["), "\"[\""); assert!(!source_ok(&source_token("["))); } + +#[test] +fn numbers_mixed_items_missing_names_and_header_macros_are_seen() { + let made = |from: &str| vec![Made { patch: "roof".into(), kind: "wall".into(), from: vec![from.into()] }]; + let item = |s: &str| format!("{{ name roof; patchInfo {{ type wall; }} constructFrom patches; patches ({s}); }}"); + let diff = |text: &str, m: &[Made]| differences(&root(text), m, OfVersion::V12); + // A quoted name compares as the name, but not one read bare as a number. + assert_eq!(diff(&format!("patches ( {} );", item("west")), &made("\"west\"")), Vec::::new()); + assert_eq!(diff(&format!("patches ( {} );", item("123")), &made("\"123\"")).len(), 1); + assert_eq!(diff(&format!("patches ( {} );", item("\"123\"")), &made("\"123\"")), Vec::::new()); + assert_eq!(diff(&format!("patches ( {} );", item("-x")), &made("\"-x\"")).len(), 1); + assert_eq!(diff(&format!("patches ( {} );", item("\"-x\"")), &made("\"-x\"")), Vec::::new()); + // A name made of patches and of a set: a difference, not left uncompared. + let set = "{ name roof; patchInfo { type wall; } constructFrom set; set roofFaces; }"; + let d = diff(&format!("patches ( {} {set} );", item("west")), &made("west")); + assert_eq!( + d, + [ + "patch roof is made in two ways there (items of other patches and of a set or zone), the description makes it of ( west )" + ] + ); + // Two items of no patches, or one without a constructFrom: said as for one item. + let zone = "{ name roof; patchInfo { type wall; } constructFrom zone; zone z; }"; + assert_eq!( + diff(&format!("patches ( {set} {zone} );"), &made("west")), + ["patch roof is made of a set there, the description makes it of ( west )"] + ); + let bare = "{ name roof; patchInfo { type wall; } patches (west); }"; + assert_eq!( + diff(&format!("patches ( {bare} {} );", item("west")), &made("west")), + ["patch roof has no constructFrom there, which createPatch stops without"] + ); + let d = diff(&format!("patches ( {} {bare} );", item("west")), &made("west")); + assert_eq!(d, ["patch roof has no constructFrom there, which createPatch stops without"]); + // In any order: with a set too, and around an item a macro holds part of. + let untold = "{ name roof; $more constructFrom patches; patches (west); }"; + for items in [ + format!("{} {set} {bare}", item("west")), + format!("{} {bare} {set}", item("west")), + format!("{bare} {untold} {set}"), + ] { + let d = diff(&format!("patches ( {items} );"), &made("west")); + assert_eq!(d, ["patch roof has no constructFrom there, which createPatch stops without"], "{items}"); + } + // Of a set or a zone only: said whatever the order, and beside an item a macro holds part of. + for items in [format!("{set} {zone}"), format!("{zone} {set}"), format!("{untold} {set}")] { + assert_eq!( + diff(&format!("patches ( {items} );"), &made("west")), + ["patch roof is made of a set there, the description makes it of ( west )"], + "{items}" + ); + } + let two = "patch roof is made in two ways there (items of other patches and of a set or zone), the description makes it of ( west )"; + for items in [format!("{} {untold} {set}", item("west")), format!("{} {set} {untold}", item("west"))] { + assert_eq!(diff(&format!("patches ( {items} );"), &made("west")), [two], "{items}"); + } + // An item read whole without a name stops createPatch: said, and what isn't made is too. + let d = diff("patches ( { constructFrom patches; patches (west); } );", &made("west")); + assert_eq!( + d, + [ + "an item there has no name (a word), at which createPatch stops", + "patch roof isn't made there, the description makes it of ( west )" + ] + ); + // One whose name a macro may give: nothing said of what isn't made. + assert_eq!( + diff("patches ( { $named constructFrom patches; patches (west); } );", &made("west")), + Vec::::new() + ); + // A header value from a macro is kept; a literal one isn't. + let header = |loc: &str| { + format!( + "FoamFile {{ version 2.0; format ascii; class dictionary; location {loc}; object createPatchDict; }} patches ( {} );", + item("west") + ) + }; + assert_eq!( + kept(&root(&header("$caseLocation")), &made("west"), OfVersion::V12), + ["its FoamFile location, given by a macro or directive"] + ); + assert_eq!(kept(&root(&header("\"system\"")), &made("west"), OfVersion::V12), Vec::::new()); +} diff --git a/crates/model/tests/coupling.rs b/crates/model/tests/coupling.rs index 49afffd..5902c8a 100644 --- a/crates/model/tests/coupling.rs +++ b/crates/model/tests/coupling.rs @@ -70,8 +70,10 @@ fn the_cases_change_dictionaries_are_generated_from_their_descriptions() { /// Each `createPatchDict` the description's meshes and steps read, generated from what /// `workflow.import` reads of the case's own (`umcf_model::create_patch`), against the case's /// own: every patch it makes of others, as it makes it (`create_patch::differences`, the same -/// patches, sources and types). A patch whose role the import can't tell (a case without a -/// mesh) leaves its case uncompared, noted; a run that compares none fails. +/// patches, sources and types). Not compared, noted: a case whose OpenFOAM version isn't told, +/// and one with a patch made of others that has neither a role (a case without a mesh) nor a +/// type of its own; a target the case doesn't have is passed over (one there must load). A run +/// that compares none fails. #[test] fn the_cases_create_patch_dictionaries_are_generated_from_their_descriptions() { use umcf_model::create_patch; diff --git a/crates/ui-egui/src/forms.rs b/crates/ui-egui/src/forms.rs index e48bd77..35eb1ea 100644 --- a/crates/ui-egui/src/forms.rs +++ b/crates/ui-egui/src/forms.rs @@ -952,7 +952,7 @@ fn grid_json(f: &Field, text: &str, was: &str) -> Result, String> /// The text of a [`Kind::Numbers`] or [`Kind::Counts`] field: its parts, one per label. const PARTS: char = '|'; -fn parts(text: &str, n: usize) -> Vec { +pub(crate) fn parts(text: &str, n: usize) -> Vec { let mut v: Vec = text.split(PARTS).map(str::to_string).collect(); v.resize(n, String::new()); v diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 00c7d98..4ce25da 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -3487,10 +3487,25 @@ fn the_workflow_cards_fill_from_the_description() { h.run(); h.run(); assert_eq!(form(&h).values["from"], "other"); + // A type only trimmed otherwise (as the form sends it) is unchanged too. + h.state_mut().act("workflow.patch", json!({"region": "street", "patch": "street_to_air", "type": "wall"})); + h.run(); + h.run(); + assert_eq!(form(&h).values["type"], "wall"); + set(&mut h, "type", "wall "); + h.state_mut().act("workflow.patch", json!({"region": "street", "patch": "street_to_air", "type": "patch"})); + h.run(); + h.run(); + assert_eq!(form(&h).values["type"], "patch"); // Leaving a patch the description has for a name it doesn't: what was filled in from it is - // cleared, not carried over; what was typed (the partner) stays. + // cleared, not carried over (sources only spaced, a type only trimmed otherwise too); what + // was typed (the partner) stays. + set(&mut h, "from", " other "); + set(&mut h, "type", "patch "); set(&mut h, "patch", "street_to_air2"); h.run(); + assert_eq!(form(&h).values["from"], ""); + assert_eq!(form(&h).values["type"], ""); assert_eq!(form(&h).values["role"], ""); assert_eq!(form(&h).values["partner"], "air|top"); // A new patch's name being typed keeps the role chosen for it. diff --git a/crates/ui-egui/src/workflowcard.rs b/crates/ui-egui/src/workflowcard.rs index 6ee808a..1bcf5fb 100644 --- a/crates/ui-egui/src/workflowcard.rs +++ b/crates/ui-egui/src/workflowcard.rs @@ -157,14 +157,28 @@ fn described( } } +/// Whether field `k` holds the same in `value` as in `was`, as the form sends it: sources +/// (`from`) by their names however spaced, a partner (`region|patch`) by its parts trimmed, +/// the others trimmed. +fn same(k: &str, value: &str, was: &str) -> bool { + match k { + "from" => value.split_whitespace().eq(was.split_whitespace()), + "partner" => { + let trimmed = |v: &str| crate::forms::parts(v, 2).iter().map(|p| p.trim().to_string()).collect::>(); + trimmed(value) == trimmed(was) + } + _ => value.trim() == was.trim(), + } +} + /// A field `k` (not held as JSON) whose entry is gone (taken away, or another one chosen that /// doesn't have it): emptied as filled; a table typed in keeps only its rows typed over or added, /// to be sent as new. The caller resets `initial`. fn undescribed(f: &mut FormState, k: &'static str) { let was = f.initial.get(k).cloned().unwrap_or_default(); let value = f.values.get(k).cloned().unwrap_or_default(); - // Sources by their names: spacing alone isn't an edit (as when rebased). - let unchanged = if k == "from" { value.split_whitespace().eq(was.split_whitespace()) } else { value == was }; + // Spacing alone isn't an edit (as when rebased). + let unchanged = same(k, &value, &was); if unchanged { f.values.insert(k, String::new()); } else if let Some(merged) = merge_table(k, &value, &was, "") { @@ -276,9 +290,8 @@ impl App { for (k, v) in now { let was = f.initial.get(k).cloned().unwrap_or_default(); let value = f.values.get(k).cloned().unwrap_or_default(); - // Sources apart by spaces: the same as filled in however they are spaced. - let unchanged = - if k == "from" { value.split_whitespace().eq(was.split_whitespace()) } else { value == was }; + // Spacing alone isn't an edit: sources however they are spaced, the others trimmed. + let unchanged = same(k, &value, &was); if !f.extra.contains_key(k) && unchanged { f.values.insert(k, v.clone()); } else if !f.extra.contains_key(k) diff --git a/docs/user-guide/checks.md b/docs/user-guide/checks.md index 36d1d1c..ba3b93f 100644 --- a/docs/user-guide/checks.md +++ b/docs/user-guide/checks.md @@ -243,7 +243,7 @@ OpenFOAM version. Each problem names the script and line. | `workflow.blocks` | Warning | A region's [blocks](workflow.md#blocks) in the description: the grid's problems (stations that don't increase, a span without cells or with a section blockMesh would give none, a `cyclic`, `nonConformal`, `mapped` or `processor` type in `types`, more than 10 000 names in a map, a dictionary too large to read back, a missing block outside the grid or listed twice, a whole layer missing, a face without a patch, a single face inside the mesh, too many blocks), a patch the region's `patches` don't list or whose role doesn't fit its side (the ground and top across the gravity of `constant//g`, else `constant/g`, else z up, said), blocks without a `mesh`, a region meshed from another's [background](workflow.md#background) that the scripts can't keep (that region not listed before it, not built by steps of its own starting with `blockMesh`, or a region named as the directory it is kept in) or that has blocks of its own its mesh doesn't read, or that doesn't list the patches of the background's blocks its mesh gets, a [box](workflow.md#box) without blocks, with a problem of its own (a surface name that isn't an STL file of `constant/triSurface`, a negative margin, a cell size not above 0) or around surfaces the case doesn't have, and a `blockMeshDict` that isn't there, doesn't load or isn't what the blocks make (edited by hand, written from other blocks, another patch type): `mesh.block` writes it, listing any type it changes and any patch it drops or adds, and refusing to change a wall or constraint type the call's `types` doesn't give, or to drop such a patch `dropPatches` doesn't name. The grid's problems: the first 20 of them all, then how many more; patches the description doesn't list, and patches whose role doesn't fit: 20 of each, then how many more | | `workflow.snappy` | Warning | A region's [snappy entry](workflow.md#snappy) in the description: its own problems (a cutting surface without a level, distances whose levels grow away from the surface, a feature level on a compressed surface, a box without a length, names given twice, …), a solid region, a mesh that doesn't run snappyHexMesh, a surface the case doesn't have, cutting surfaces' patches the description doesn't list or that another surface or the blocks make too (those of the region whose background its mesh starts from), an inside point outside those blocks, on their sides or in a missing block (the blocks may have changed since `mesh.snappy` checked it), features asked for while the workflow doesn't run `surfaceFeatures`, a `snappyHexMeshDict` that isn't what the entry writes (missing, doesn't load, written from another entry, or edited by hand so that it holds something else than the entry: one of the case's own that holds what the entry does, as `workflow.import` read the entry from it, with the patch types the roles give, is an Info, counting the parts of it the entry can't hold), and a `system/surfaceFeaturesDict` that is missing, doesn't load, was written from other entries, or is the case's own and doesn't list a surface asking for features. The surfaces themselves are checked by `mesh.snappy` | | `workflow.change-dictionary` | Warning | The `changeDictionaryDict` of a region whose steps run `changeDictionary`, against what [`workflow.dictionaries`](workflow.md#writing-the-dictionaries) writes from the patches' roles and partners: one that can't be written (a partner without a role, a partner region not described, a canopy with a partner or no air, a name that isn't a plain OpenFOAM word, or a region's that can't be a directory on every system), one missing or that doesn't load, one umcfGui wrote otherwise than it writes now (other roles or partners, another OpenFOAM version, or an older umcfGui), and the case's own where it differs, by the keys the version reads and only those given (`changeDictionary` merges a block into the mesh's patch, so a key left out keeps the mesh's value, not known before the mesh is made; a region or patch the version reads that is left out is said to be unconfirmed, in OpenFOAM-8 unless OpenFOAM-12's key stands in its place, said to be unread; a patch's block with a `~key`, which takes the key out of the mesh's patch, isn't compared, said so): a patch's type, or the region and patch it maps to (OpenFOAM-8 only `sampleRegion` and `samplePatch`, `neighbourRegion` or `neighbourPatch` in their place said to be unread; OpenFOAM-12 `neighbourRegion` and `neighbourPatch` where given, else the older two, which alone, the description's or not, are said to be unconfirmed, as OpenFOAM-12 reads the newer first and the mesh's patch keeps a newer one it has; OpenFOAM-12's `mappedInternal` reads no patch; OpenFOAM-8 stops on a patch other than `none` in a mode that samples none, `nearestCell`, `nearestOnlyCell` or `nearestFace`, with a `coupleGroup` too, and without a mode given the patch isn't compared; with a `coupleGroup`, OpenFOAM-8 compares the region and patch only when both are given (in `nearestCell` and `nearestOnlyCell` the region alone; `nearestFace` asks the group for a patch not given, refused), OpenFOAM-12 stops on a group given with either, and a partner named by the group alone isn't compared; OpenFOAM-12's `samePatch`, a switch (`true`, `yes`, `on` and the like) or a number other than 0, names the patch of the same name, refused with a patch named too (not compared then), and alone compared and, where it is the description's, said to be unconfirmed, as OpenFOAM-12 refuses it beside a `neighbourPatch`, which it writes on a mapped patch and the mesh's patch keeps, and one that isn't a switch (quoted, too) refused, the patch not compared then; a name that isn't a word, empty (`""`) or a dictionary, is said to be refused, for the keys the version reads, a group's too, and so is a type that is a dictionary), a sample mode OpenFOAM-8 hasn't or one sampling no patch against one sampling a patch, an OpenFOAM-12 `method` (or `sampleMode` read as it) it hasn't, a patch changed that the description doesn't map, a value in `boundary` (which `changeDictionary` adds to the mesh's `boundary` file), a `~patch` there, quoted or not (on which `changeDictionary` stops where the mesh has the patch, or, with a block for it after, writes the block in its place without its faces; neither compared); other methods and modes, the offsets and values given by a macro or directive aren't compared (nor, with an OpenFOAM-8 `sampleMode` from one, the `samplePatch`), a patch mapped only through a pattern or group is said not to be there, keys a patch's block brings in (`$common;`, `#include`) aren't seen, and of a patch given twice only the last is read (OpenFOAM merges them). The case's own that maps them as the description does is fine. Not checked while the description doesn't read whole | -| `workflow.create-patch` | Warning | Each `createPatchDict` the description's meshes and steps read (`system//createPatchDict` for `createPatch -region`, `system/createPatchDict` for the regions meshed with `createPatch` in `constant/polyMesh`), against what [`workflow.dictionaries`](workflow.md#the-createpatchdicts) writes from the patches made of others (`from`) and their roles or types: when they can't be written (a patch made with neither a role nor a type, or in a region running no `createPatch`, a region running it both in and after its mesh with patches to make, regions sharing `system/createPatchDict` that make other patches, or make them in another order, a name that isn't a plain word), one missing or that doesn't load (or, where the case lists more files than are read, not loaded and not known to be there), one umcfGui wrote otherwise than it writes now, and the case's own where it makes the patches otherwise: a patch not made there, made of a set or of other patches, of another type or of none (`patchInfo` without a `type`), one made there the description doesn't make, two made in the other order (or one given again around the other: `createPatch` gives a face to the last patch that takes it, and any two may take the same faces, through a shared source, a pattern or a patch group), the `patches` list or OpenFOAM-8's `pointSync` missing, which `createPatch` stops without, a `pointSync` that isn't a switch (a word or a number, not a quoted string), a `patches` list whose count isn't its items'. The sources are compared as their union, in any order; a name or type quoted or not is the same, and so is a source quoted that OpenFOAM doesn't take for a pattern; what a macro or directive gives isn't compared (an item holding one by its name only). Where the case's own holds what the description can't (a patch it doesn't make or gives twice, one made of a face set or of sources it can't hold, `patchInfo` entries besides the type or other keys of an item, a key given twice in an item or its `patchInfo`, a value from a macro or directive, a list that can't be read whole, another entry at its top or in its `FoamFile` header, OpenFOAM-8's `pointSync` not off), it says so, also where it shows no difference (what a macro or directive gives isn't compared), and to describe them with `workflow.patch` or mend the file, as `workflow.dictionaries` leaves it as it is. Not checked while the description doesn't read whole | +| `workflow.create-patch` | Warning | Each `createPatchDict` the description's meshes and steps read (`system//createPatchDict` for `createPatch -region`, `system/createPatchDict` for the regions meshed with `createPatch` in `constant/polyMesh`), against what [`workflow.dictionaries`](workflow.md#the-createpatchdicts) writes from the patches made of others (`from`) and their roles or types: when they can't be written (a patch made with neither a role nor a type, or in a region running no `createPatch`, a region running it both in and after its mesh with patches to make, regions sharing `system/createPatchDict` that make other patches, or make them in another order, a name that isn't a plain word), one missing or that doesn't load (or, where the case lists more files than are read, not loaded and not known to be there), one umcfGui wrote otherwise than it writes now, and the case's own where it makes the patches otherwise: a patch not made there, made of a set or of other patches (or of both, in two items), of another type or of none (`patchInfo` without a `type`), one made there the description doesn't make, an item without a name or a `constructFrom` (at which `createPatch` stops), two made in the other order (or one given again around the other: `createPatch` gives a face to the last patch that takes it, and any two may take the same faces, through a shared source, a pattern or a patch group), the `patches` list or OpenFOAM-8's `pointSync` missing, which `createPatch` stops without, a `pointSync` that isn't a switch (a word or a number, not a quoted string), a `patches` list whose count isn't its items'. The sources are compared as their union, in any order; a name or type quoted or not is the same, and so is a source quoted that OpenFOAM doesn't take for a pattern; what a macro or directive gives isn't compared (an item holding one by its name only). Where the case's own holds what the description can't (a patch it doesn't make or gives twice, one made of a face set or of sources it can't hold, `patchInfo` entries besides the type or other keys of an item, a key given twice in an item or its `patchInfo`, a value from a macro or directive, a list that can't be read whole, another entry at its top or in its `FoamFile` header, OpenFOAM-8's `pointSync` not off), it says so, also where it shows no difference (what a macro or directive gives isn't compared), and to describe them with `workflow.patch` or mend the file, as `workflow.dictionaries` leaves it as it is. Not checked while the description doesn't read whole | | `workflow.split` | Warning | A region [split](workflow.md#split) from another by a cell zone: from a region the description doesn't list, lists after it or doesn't build; a zone not named (no script splits it), or that its `topoSetDict` doesn't make, a `topoSetDict` that makes other zones too (they would be split off as well; no script splits it) or whose zones can't be told (`#include`, a macro), or a dictionary the case doesn't have; a zone or `region1` named as a region (the split's clean-up would remove that region's directories), a region named `region` and a number (as `splitMeshRegions` names the parts outside the zone) | ## Finite-volume constraints and pressure limits (OpenFOAM-12) diff --git a/docs/user-guide/workflow.md b/docs/user-guide/workflow.md index c786906..6473388 100644 --- a/docs/user-guide/workflow.md +++ b/docs/user-guide/workflow.md @@ -163,7 +163,9 @@ patches by their roles and points them at their partners, as the - Generated, with a checksum: one umcfGui wrote and nobody changed since is written over as the description changes. One edited by hand or not written by umcfGui is written over only with `replace: true`; `case.save` keeps it in `.umcfgui/backup/` and `edit.undo` takes the write - back (a run that writes nothing adds no step to the history and leaves what can be redone). One that doesn't load (or a directory there), a symbolic link and one that is the same + back; after a save, saving again brings back a file the save wrote over, but a dictionary the save created stays on disk (`case.save` removes no file: + delete it by hand). A run that writes nothing adds no step to the history and leaves what can + be redone (the journal keeps it, for a case it would change). One that doesn't load (or a directory there), a symbolic link and one that is the same file as another dictionary aren't written over, and nothing is written then. `region` writes one region's only; a region with coupled patches whose steps don't run `changeDictionary` is noted. @@ -258,7 +260,7 @@ unless the two share `system/createPatchDict`). The case's own that holds what t can't (a patch it doesn't make or makes in two items, one made of a face set or of sources it can't hold, an entry of `patchInfo` besides its `type`, such as a cyclic's `neighbourPatch`, or another key of the item, a key given twice in an item or its `patchInfo` (OpenFOAM merges them), -a value given by a macro or directive, a `patches` list that can't be +a value given by a macro or directive (in its `FoamFile` header too), a `patches` list that can't be read whole, another entry at its top or in its `FoamFile` header, OpenFOAM-8's `pointSync` that isn't off) isn't written over, even with `replace`: it is left as it is and noted, naming what would be lost, for `workflow.patch` to give the patches their `from` and `type`, or for the file to be mended by @@ -266,15 +268,15 @@ hand; the other dictionaries are written. The case check (`workflow.create-patch`) says when one is missing, doesn't load, was written by umcfGui otherwise than it writes now, or is the case's own and makes the patches otherwise: a -patch not made there, made of a set or of other patches, of another type or of none, one made -there that the description doesn't make, two made in the other order, or one given again around another +patch not made there, made of a set or of other patches (or of both, in two items), of another type or of none, one made +there that the description doesn't make, an item without a name or a `constructFrom` (`createPatch` stops), two made in the other order, or one given again around another (`createPatch` gives a face to the last patch that takes it, and any two may take the same faces), the `patches` list or OpenFOAM-8's `pointSync` missing, which `createPatch` stops without, a `pointSync` that isn't a switch, and a `patches` list whose count isn't its items'; and the case's own that shows no difference but holds what it can't (as above). The sources are compared as `createPatch` takes them, their union in any order (of both items, for a patch given twice); a name or type quoted or not is the same, and so is a source quoted that OpenFOAM doesn't take for a pattern (`"defaultFaces"`: one without `. * + ? ( ) | [ ]` or a character a -word can't hold); what a macro or directive gives isn't compared (an item holding one is +word can't hold, and not read otherwise bare: `"123"` isn't `123`, a number); what a macro or directive gives isn't compared (an item holding one is compared by its name only). Where the case's own makes what the description can't hold, it says to give the patches their `from` with `workflow.patch` rather than to write it over. When the dictionaries can't be written from the description, it From f985684e13c2b1f899c3bd2bbdb0e3742708bfa3 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sat, 28 Nov 2026 10:44:22 +0100 Subject: [PATCH 6/6] M0.101: an item without a plain name said once in what a createPatchDict keeps (review) kept listed one entry per such item and skipped the cap on that path; a file with many gave a list as long as the file. No doc names the message. --- crates/model/src/create_patch.rs | 6 +++++- crates/model/src/create_patch_tests.rs | 2 ++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/model/src/create_patch.rs b/crates/model/src/create_patch.rs index 608bde8..1f84318 100644 --- a/crates/model/src/create_patch.rs +++ b/crates/model/src/create_patch.rs @@ -689,9 +689,13 @@ pub fn kept(root: &Dict, made: &[Made], version: OfVersion) -> Vec { }; let names: HashSet<&str> = made.iter().map(|m| m.patch.as_str()).collect(); let mut seen: HashSet<&str> = HashSet::with_capacity(there.len()); + let mut unnamed = false; for t in &there { let Some(n) = t.name.as_deref().filter(|n| !untold(n)) else { - out.push("a patch without a plain name".to_string()); + // Said once: the items can't be told apart, and a file may hold many. + if !std::mem::replace(&mut unnamed, true) { + out.push("a patch without a plain name".to_string()); + } continue; }; // An empty list moves no faces, which the description can't say (an empty from makes none). diff --git a/crates/model/src/create_patch_tests.rs b/crates/model/src/create_patch_tests.rs index 8e7d477..284e80e 100644 --- a/crates/model/src/create_patch_tests.rs +++ b/crates/model/src/create_patch_tests.rs @@ -573,6 +573,8 @@ fn a_header_of_its_own_is_kept_and_long_lists_are_capped() { let k = kept(&root(&format!("{many} patches ( );")), &[], OfVersion::V12); assert_eq!(k.len(), MAX_KEPT + 1); assert_eq!(k.last().map(String::as_str), Some("and more")); + let unnamed: String = (0..1000).map(|_| "{ name $n; constructFrom patches; patches (a); } ").collect(); + assert_eq!(kept(&root(&format!("patches ( {unnamed} );")), &[], OfVersion::V12), ["a patch without a plain name"]); } #[test]