Skip to content

ENH: Standard ODF section images and in-ball ODF sampling - #60

Closed
imikejackson wants to merge 16 commits into
developfrom
feature/odf_generation
Closed

imikejackson wants to merge 16 commits into
developfrom
feature/odf_generation

Conversation

@imikejackson

@imikejackson imikejackson commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Adds a standard orientation distribution function (ODF) section renderer to Source/EbsdLib/Utilities/ and corrects the ODF and misorientation distribution function (MDF) sampling that synthetic texture generation depends on. The sampling fixes keep every drawn orientation inside the homochoric ball, weight the random-texture baseline by the valid volume of each bin, and keep CalculateMDFData normalized for any weight set. Generator-taking overloads make symmetry randomization and MDF sampling reproducible from a caller-supplied seed. 46 files changed, +3145 / −87 lines.

Dependency: BlueQuartzSoftware/EbsdLib#61 — Correct ODF sampling and MDF normalization contains the first seven commits of this branch. Themes 1 and 2 below are identical to that PR. If #61 merges first, this PR reduces to themes 3 and 4.

1. ODF sampling inside the homochoric ball

  • Source/EbsdLib/LaueOps/
    • LaueOps.h, LaueOps.cpp — grid geometry, in-ball sampler, bin volume queries, fallback counter
    • MonoclinicOps.cpp, CubicLowOps.cpp — corrected ODF step size
    • all other *Ops.cpp — pass grid geometry to the base class, call the in-ball sampler
  • Source/EbsdLib/Orientation/Homochoric.hpp, Source/EbsdLib/Core/OrientationTransformation.hpp — domain clamp in the homochoric to axis-angle series
  • Source/EbsdLib/Texture/Texture.hpp — volume-weighted random baseline in CalculateODFData

The ODF bin grid is a box that circumscribes the homochoric ball, so many bins hold no valid orientation. On develop, determineEulerAngles can return a point outside the ball, and Homochoric::toAxisAngle then evaluates its 16-term fit outside its valid radius. That path returns a rotation angle above 180 degrees without a diagnostic, or NaN further out. The fit now clamps the squared magnitude to R1 * R1 and clamps the fitted cosine to [-1, 1] before acos. Points inside the ball take the same path as before.

LaueOps now stores each class's ODF grid origin and step. The new _calcDetermineHomochoricValuesInBall sampler keeps the first draw when it lies inside the ball. Otherwise it redraws inside the same bin with a deterministic stream seeded from the caller's random triple and the bin indices, so a given seed stays reproducible. After 4096 redraws it clamps the point to the ball surface and increments an atomic counter that clampFallbackCount() exposes. All eleven Laue classes use this sampler.

MonoclinicOps and CubicLowOps computed their ODF step as init / numBins / 2.0. The other nine classes use init / (numBins / 2). The smaller step made the inverse grid span -init to -init/2 while the forward bin map assumed -init to +init, so the two maps disagreed inside the same class. Both classes now use the same formula as the rest.

odfBinInBallFraction() and isOdfBinReachable() estimate the volume of each bin inside the ball. Fully inside and fully outside bins use exact corner bounds. Boundary bins use a fixed 6x6x6 sub-grid. CalculateODFData distributes the random baseline in proportion to these fractions, which is the uniform orientation measure in homochoric space. Grids that lie entirely inside the ball keep their previous arithmetic bit for bit, so Cubic m-3m and Hexagonal 6/mmm results do not change.

GetAllOrientationOps() returns one entry per crystal structure. The duplicate OrthoRhombicOps entry at index 11 is removed.

2. MDF normalization and seeded overloads

  • Source/EbsdLib/Texture/Texture.hpp — CalculateMDFData reserved-count scaling and generator overload
  • Source/EbsdLib/Texture/StatsGen.hpp — GenMDFPlotData generator overload
  • Source/EbsdLib/LaueOps/LaueOps.h, LaueOps.cpp — randomizeEulerAngles and getRandomSymmetryOperatorIndex generator overloads

CalculateMDFData accumulates reserved sample counts per folded misorientation bin, so duplicate rows add up instead of overwriting each other. When the reserved counts exceed the 10,000-sample budget, the function scales them to the budget with largest-remainder rounding. On develop that case skipped the random sampling loop and the output summed to weight / binCount instead of 1. The final normalization divides by the actual total.

LaueOps::randomizeEulerAngles, LaueOps::getRandomSymmetryOperatorIndex, Texture::CalculateMDFData, and StatsGen::GenMDFPlotData gain overloads that take a std::mt19937_64&. The base class implements the symmetry overloads once through getNumSymOps and getQuatSymOp. Each LaueOps subclass re-exposes the hidden base overload with a using-declaration. The existing signatures keep their per-call clock seeding and delegate to the new overloads, so current callers see no behavior change.

3. ODF section preparation and composition

  • Source/EbsdLib/Utilities/
    • ODFSectionUtilities.h, .cpp — grid validation, MUD conversion, periodic phi2 interpolation, Laue crop
    • ODFSectionCompositor.h, .cpp — layout computation, panel rasterization, shared color bar
    • ODFSectionChrome.h, .cpp — titles, axis ticks, label selection, gutter measurement
    • SourceList.cmake — registers the three new units

PrepareODFSections takes a borrowed full-cube Euler grid through ODFGridView. It validates the dimensions, origin, spacing, units, value count, and value range, and returns a negative error code with a diagnostic message on failure. Count-density values convert to multiples of a uniform distribution (MUD). The function interpolates a requested number of equal phi2 sections across the periodic phi2 extent and crops the phi1 and PHI axes to the Euler plot limits of the selected Laue class. GetODFEulerPlotLimits and GenerateODFSectionAngles expose those limits and section angles for all eleven classes.

ODFSectionCompositor::generateCompositeImage draws the prepared sections as a grid of panels on one RGBA page with a shared MUD color bar. ODFSectionConfiguration supplies the section count, columns, panel width, automatic or manual scale endpoints, color control points, and labels. ComputeODFSectionLayout computes deterministic page metrics and returns zero metrics when the inputs are invalid or exceed canvas integer limits. Error codes -7510 through -7513 identify width, column, scale, and color-control failures. Grid and section-count errors keep the preparation error codes.

The chrome helpers draw the φ₂ section headings, the φ₁ and Φ axis titles, tick hashes, numeric labels, and the color-bar title with the embedded font. ComputeODFLeftAxisGutter measures a gutter for the vertical title and numeric labels so the axes do not clip. GenerateODFAxisLabelTicks selects labels from rendered text widths with endpoint padding while all tick hashes remain.

4. Tests and test build

  • Source/Test/
    • ODFSectionUtilitiesTest.cpp — limits, angles, MUD conversion, linearization, interpolation, crop, invalid input
    • ODFSectionCompositorTest.cpp — layout, chrome text, glyph bounds, scale and color interpolation, invalid configuration
    • CanvasItyImplementation.cpp — compiles canvas_ity into the test executable
    • LaueOpsTest.cpp, TextureTest.cpp, ConvertToFundamentalZoneTest.cpp, PoleFigureCompositorTest.cpp, DirectionalStatsTest.cpp — sampling, MDF, and operator-count coverage
    • CMakeLists.txt — registers the new sources

The compositor tests call the canvas directly, so the test executable compiles the canvas_ity implementation itself. This resolves Windows linker errors and keeps the third-party canvas symbols out of the public EbsdLib DLL interface.

DirectionalStats.hpp and DirectionalStats.cpp gain the BlueQuartz license header and the EMsoft attribution block.

Test plan

  • Every Laue class reports a zero non-finite rate from determineEulerAngles, and no homochoric to axis-angle conversion returns an angle above 180 degrees (LaueOpsTest).
  • odfBinInBallFraction agrees with a Monte Carlo volume estimate, unreachable bins carry zero ODF weight, and 200k draws per Laue class trigger zero clamp fallbacks (TextureTest).
  • CalculateMDFData sums to 1 for a half-weight row, an overflowing row, duplicate rows, and empty weights.
  • Same-seed calls to the generator-taking overloads reproduce their output, and the clock-seeded overloads still produce normalized results.
  • GetAllOrientationOps() returns eleven entries.
  • PrepareODFSections rejects null values, unsupported crystal codes, unsupported units, transposed dimensions, nonzero origins, nonuniform spacing, count mismatches, negative values, NaN values, and a single section.
  • generateCompositeImage rejects invalid widths, column counts, scale endpoints, and color controls, and propagates preparation errors.
  • Composed glyphs and axis labels stay inside their bounds at three panel sizes, and the Greek axis glyphs render from the embedded font.
  • The full ctest suite passes on the branch.
  • CI passes on macOS, Linux, and Windows.

@imikejackson imikejackson changed the title Feature/odf generation ENH: Standard ODF section images and in-ball ODF sampling Oct 15, 2026
@imikejackson
imikejackson force-pushed the feature/odf_generation branch 2 times, most recently from 4030941 to 3c776fc Compare October 15, 2026 15:47
@imikejackson
imikejackson force-pushed the feature/odf_generation branch from 3c776fc to 926ba90 Compare November 11, 2026 22:43
… count

* Accumulate the reserved sample counts per folded misorientation bin
  instead of overwriting, so duplicate rows add up
* Scale the reserved counts to the 10,000-sample budget when the weights
  sum past the MDF bin count; previously the random-sampling loop was
  skipped and the array summed to weight/binCount instead of 1
* Normalize by the actual total instead of the hard-coded budget
* Document the multiples-of-random weight semantics and add TextureTest
  cases for a half-weight row, an overflowing row, duplicate rows, and
  empty weights

Signed-off-by: Michael Jackson <mike.jackson@bluequartz.net>
Two defects made every ODF sample unreliable in the low-symmetry Laue classes.

The ODF bin grid is a rectangular box that circumscribes the homochoric ball,
so a large share of it holds no valid orientation. Homochoric::toAxisAngle
recovers the rotation angle from a 16-term fit that is only valid out to the
ball radius R1. Between R1 and 1.69247 the fit still returns a value inside the
domain of acos, so the function succeeded and handed back a rotation angle
above 180 degrees, which is not a valid axis-angle pair, with no diagnostic of
any kind; beyond that it returned NaN. The NaN rate therefore understated the
damage several times over. Measured invalid share against NaN rate: Triclinic
47.7 against 12.9 percent, Monoclinic 84.0 against 18.4, Tetragonal 4/m 29.9
against 3.8, Trigonal -3 22.4 against 2.3, Hexagonal 6/m 22.4 against 2.3.

Separately, MonoclinicOps and CubicLowOps computed their ODF step as
init/numBins/2 where the other nine classes use init/(numBins/2), a quarter of
the intended value. _calcODFBin maps an orientation to a bin assuming the grid
spans -init to +init, but the inverse then spanned only -init to -init/2, so
the forward and inverse maps disagreed inside the same class and the grid never
contained the origin. Monoclinic could not sample below roughly 140 degrees.

determineEulerAngles now draws through a new deterministic in-ball sampler that
redraws inside the chosen bin until the point is valid, seeded from the
caller's own random triple and the bin indices so results stay reproducible,
and falls back to a radial clamp for a bin with no valid volume. toAxisAngle
clamps an out-of-range magnitude to R1 before evaluating the series and clamps
the fitted value before acos, leaving the valid path untouched. The dead
OrientationTransformation copy of the routine carries the same guard.

After the fix every Laue class reports a 0.00 percent non-finite rate, the
conversion sweep returns no angle above 180 degrees against 326 before, and
grid round-trip agreement rises from 0.33 to 47.5 percent for Monoclinic and
from 0.00 to 23.9 for Cubic m-3, both inside the band their peers occupy.

Two regression tests cover the sampler and the conversion domain.

Signed-off-by: Michael Jackson <mike.jackson@bluequartz.net>
…F sampling

* LaueOps::randomizeEulerAngles and getRandomSymmetryOperatorIndex gain
  overloads that draw from a caller-supplied std::mt19937_64, implemented
  once in the base class through getNumSymOps and getQuatSymOp; every
  subclass re-exposes the hidden base overload with a using-declaration
* Texture::CalculateMDFData and StatsGen::GenMDFPlotData gain the same
  overload; the existing signatures keep their per-call clock seeding
  and delegate, so current callers see no behavior change
* Callers that hold a seed can now make symmetry-equivalent orientation
  selection and the 10,000-pair MDF background sample reproducible
* Tests cover same-seed reproducibility, symmetry equivalence and full
  operator coverage across all 11 Laue classes, and MDF normalization

Signed-off-by: Michael Jackson <mike.jackson@bluequartz.net>
Remove the duplicate operator retained after AxisOrthoRhombic was retired.
Return one entry for each of the eleven crystal structures.

Update count assertions, preserve all fundamental-zone reference rows,
and correct stale duplicate-entry comments.

Validation: Release build, 413/413 CTest tests, and clang-format 19.1.1.
Signed-off-by: Michael Jackson <mike.jackson@bluequartz.net>
…backs

* Store each Laue class's ODF grid origin and step in the LaueOps base
  so bin geometry can be queried without re-deriving it in every sampler
* Add odfBinInBallFraction() and isOdfBinReachable(): exact corner
  bounds decide bins fully inside or outside the homochoric ball, and a
  fixed 6x6x6 sub-grid estimates the fraction of boundary bins
* Raise the in-ball rejection sampler to 4096 redraws and count every
  radial clamp fallback through clampFallbackCount(), so callers can
  prove that a random texture never lands on the ball surface

Signed-off-by: Michael Jackson <mike.jackson@bluequartz.net>
* CalculateODFData spread the random-texture baseline over every bin of
  the homochoric grid, including bins that hold no valid orientation.
  Sampling those bins fell through to the radial clamp and returned 180
  degree rotations: one draw in five for Hexagonal 6/m and nearly half
  for Triclinic, visible as a spot at the centre of the (0001) pole
  figure and as a skewed random texture in Match Crystallography
* Distribute the baseline in proportion to odfBinInBallFraction() and
  renormalize, which is the uniform orientation measure in homochoric
  space. Grids entirely inside the ball keep their previous arithmetic
  bit for bit, so Cubic m-3m and Hexagonal 6/mmm results are unchanged
* Tests: bin fractions match a Monte Carlo estimate, unreachable bins
  carry zero weight, and 200k draws per Laue class trigger zero clamp
  fallbacks

Signed-off-by: Michael Jackson <mike.jackson@bluequartz.net>
Signed-off-by: Michael Jackson <mike.jackson@bluequartz.net>
Signed-off-by: Michael Jackson <mike.jackson@bluequartz.net>
Signed-off-by: Michael Jackson <mike.jackson@bluequartz.net>
Signed-off-by: Michael Jackson <mike.jackson@bluequartz.net>
Signed-off-by: Michael Jackson <mike.jackson@bluequartz.net>
Signed-off-by: Michael Jackson <mike.jackson@bluequartz.net>
Signed-off-by: Michael Jackson <mike.jackson@bluequartz.net>
Reserve a measured gutter for vertical titles and numeric labels.
Select labels from rendered widths with endpoint padding while retaining
all tick hashes. Verify composed glyphs and bounds at three panel sizes.

Signed-off-by: Michael Jackson <mike.jackson@bluequartz.net>
* Compile canvas_ity directly into the unit-test executable
* Resolve Windows linker errors from compositor tests that use canvas directly
* Keep third-party canvas symbols out of the EbsdLib public DLL interface

Signed-off-by: Michael Jackson <mike.jackson@bluequartz.net>
@imikejackson

Copy link
Copy Markdown
Collaborator Author

Closed in favor of #86, which merges this branch (with its history) together with the other open EbsdLib fixes for the next release, so simplnx can build against one EbsdLib branch. The branch is kept.

🤖 Generated with Claude Code

@imikejackson
imikejackson deleted the feature/odf_generation branch November 13, 2026 16:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant