matterviz 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (286) hide show
  1. package/dist/FilePicker.svelte +37 -20
  2. package/dist/Icon.svelte +2 -2
  3. package/dist/MillerIndexInput.svelte +60 -0
  4. package/dist/MillerIndexInput.svelte.d.ts +7 -0
  5. package/dist/app.css +38 -2
  6. package/dist/brillouin/BrillouinZone.svelte +20 -62
  7. package/dist/brillouin/BrillouinZone.svelte.d.ts +1 -1
  8. package/dist/brillouin/BrillouinZoneExportPane.svelte +12 -20
  9. package/dist/brillouin/BrillouinZoneScene.svelte +2 -2
  10. package/dist/brillouin/BrillouinZoneScene.svelte.d.ts +1 -1
  11. package/dist/chempot-diagram/ChemPotDiagram.svelte +192 -0
  12. package/dist/chempot-diagram/ChemPotDiagram.svelte.d.ts +13 -0
  13. package/dist/chempot-diagram/ChemPotDiagram2D.svelte +677 -0
  14. package/dist/chempot-diagram/ChemPotDiagram2D.svelte.d.ts +16 -0
  15. package/dist/chempot-diagram/ChemPotDiagram3D.svelte +2688 -0
  16. package/dist/chempot-diagram/ChemPotDiagram3D.svelte.d.ts +16 -0
  17. package/dist/chempot-diagram/ChemPotScene3D.svelte +8 -0
  18. package/dist/chempot-diagram/ChemPotScene3D.svelte.d.ts +7 -0
  19. package/dist/chempot-diagram/color.d.ts +10 -0
  20. package/dist/chempot-diagram/color.js +33 -0
  21. package/dist/chempot-diagram/compute.d.ts +38 -0
  22. package/dist/chempot-diagram/compute.js +650 -0
  23. package/dist/chempot-diagram/index.d.ts +5 -0
  24. package/dist/chempot-diagram/index.js +5 -0
  25. package/dist/chempot-diagram/pointer.d.ts +16 -0
  26. package/dist/chempot-diagram/pointer.js +40 -0
  27. package/dist/chempot-diagram/temperature.d.ts +15 -0
  28. package/dist/chempot-diagram/temperature.js +37 -0
  29. package/dist/chempot-diagram/types.d.ts +83 -0
  30. package/dist/chempot-diagram/types.js +27 -0
  31. package/dist/colors/index.d.ts +3 -1
  32. package/dist/colors/index.js +4 -0
  33. package/dist/composition/BarChart.svelte +13 -22
  34. package/dist/composition/BubbleChart.svelte +5 -3
  35. package/dist/composition/FormulaFilter.svelte +770 -90
  36. package/dist/composition/FormulaFilter.svelte.d.ts +37 -1
  37. package/dist/composition/PieChart.svelte +43 -18
  38. package/dist/composition/PieChart.svelte.d.ts +1 -1
  39. package/dist/constants.d.ts +1 -0
  40. package/dist/constants.js +2 -0
  41. package/dist/convex-hull/ConvexHull.svelte +14 -1
  42. package/dist/convex-hull/ConvexHull.svelte.d.ts +1 -1
  43. package/dist/convex-hull/ConvexHull2D.svelte +14 -45
  44. package/dist/convex-hull/ConvexHull2D.svelte.d.ts +1 -1
  45. package/dist/convex-hull/ConvexHull3D.svelte +396 -134
  46. package/dist/convex-hull/ConvexHull3D.svelte.d.ts +1 -1
  47. package/dist/convex-hull/ConvexHull4D.svelte +93 -42
  48. package/dist/convex-hull/ConvexHull4D.svelte.d.ts +1 -1
  49. package/dist/convex-hull/ConvexHullControls.svelte +94 -31
  50. package/dist/convex-hull/ConvexHullControls.svelte.d.ts +4 -2
  51. package/dist/convex-hull/ConvexHullStats.svelte +697 -128
  52. package/dist/convex-hull/ConvexHullStats.svelte.d.ts +6 -1
  53. package/dist/convex-hull/ConvexHullTooltip.svelte +1 -0
  54. package/dist/convex-hull/GasPressureControls.svelte +72 -38
  55. package/dist/convex-hull/GasPressureControls.svelte.d.ts +2 -1
  56. package/dist/convex-hull/TemperatureSlider.svelte +46 -19
  57. package/dist/convex-hull/TemperatureSlider.svelte.d.ts +2 -1
  58. package/dist/convex-hull/demo-temperature.d.ts +6 -0
  59. package/dist/convex-hull/demo-temperature.js +36 -0
  60. package/dist/convex-hull/gas-thermodynamics.js +16 -5
  61. package/dist/convex-hull/helpers.d.ts +7 -1
  62. package/dist/convex-hull/helpers.js +45 -15
  63. package/dist/convex-hull/index.d.ts +15 -1
  64. package/dist/convex-hull/index.js +1 -0
  65. package/dist/convex-hull/thermodynamics.d.ts +8 -21
  66. package/dist/convex-hull/thermodynamics.js +106 -17
  67. package/dist/convex-hull/types.d.ts +7 -0
  68. package/dist/convex-hull/types.js +11 -0
  69. package/dist/coordination/CoordinationBarPlot.svelte +29 -46
  70. package/dist/element/BohrAtom.svelte +1 -1
  71. package/dist/element/data.js +2 -14
  72. package/dist/element/data.json.gz +0 -0
  73. package/dist/element/index.d.ts +1 -1
  74. package/dist/element/index.js +1 -0
  75. package/dist/element/types.d.ts +1 -0
  76. package/dist/fermi-surface/FermiSurface.svelte +21 -65
  77. package/dist/fermi-surface/FermiSurface.svelte.d.ts +1 -1
  78. package/dist/fermi-surface/FermiSurfaceControls.svelte.d.ts +1 -1
  79. package/dist/fermi-surface/FermiSurfaceScene.svelte +1 -1
  80. package/dist/fermi-surface/FermiSurfaceScene.svelte.d.ts +1 -1
  81. package/dist/fermi-surface/compute.js +1 -21
  82. package/dist/fermi-surface/marching-cubes.d.ts +2 -13
  83. package/dist/fermi-surface/marching-cubes.js +2 -519
  84. package/dist/fermi-surface/parse.js +17 -23
  85. package/dist/heatmap-matrix/HeatmapMatrix.svelte +1273 -0
  86. package/dist/heatmap-matrix/HeatmapMatrix.svelte.d.ts +110 -0
  87. package/dist/heatmap-matrix/HeatmapMatrixControls.svelte +171 -0
  88. package/dist/heatmap-matrix/HeatmapMatrixControls.svelte.d.ts +31 -0
  89. package/dist/heatmap-matrix/index.d.ts +53 -0
  90. package/dist/heatmap-matrix/index.js +100 -0
  91. package/dist/heatmap-matrix/shared.d.ts +2 -0
  92. package/dist/heatmap-matrix/shared.js +4 -0
  93. package/dist/icons.d.ts +119 -0
  94. package/dist/icons.js +119 -0
  95. package/dist/index.d.ts +6 -1
  96. package/dist/index.js +6 -1
  97. package/dist/io/export.js +15 -3
  98. package/dist/io/file-drop.d.ts +7 -0
  99. package/dist/io/file-drop.js +43 -0
  100. package/dist/io/index.d.ts +2 -2
  101. package/dist/io/index.js +2 -112
  102. package/dist/io/types.d.ts +1 -0
  103. package/dist/io/url-drop.d.ts +2 -0
  104. package/dist/io/url-drop.js +118 -0
  105. package/dist/isosurface/Isosurface.svelte +231 -0
  106. package/dist/isosurface/Isosurface.svelte.d.ts +8 -0
  107. package/dist/isosurface/IsosurfaceControls.svelte +273 -0
  108. package/dist/isosurface/IsosurfaceControls.svelte.d.ts +9 -0
  109. package/dist/isosurface/index.d.ts +5 -0
  110. package/dist/isosurface/index.js +6 -0
  111. package/dist/isosurface/parse.d.ts +6 -0
  112. package/dist/isosurface/parse.js +548 -0
  113. package/dist/isosurface/slice.d.ts +11 -0
  114. package/dist/isosurface/slice.js +145 -0
  115. package/dist/isosurface/types.d.ts +55 -0
  116. package/dist/isosurface/types.js +178 -0
  117. package/dist/labels.d.ts +2 -1
  118. package/dist/labels.js +1 -0
  119. package/dist/layout/InfoTag.svelte +62 -62
  120. package/dist/layout/SubpageGrid.svelte +74 -0
  121. package/dist/layout/SubpageGrid.svelte.d.ts +14 -0
  122. package/dist/layout/index.d.ts +1 -0
  123. package/dist/layout/index.js +1 -0
  124. package/dist/layout/json-tree/JsonNode.svelte +226 -53
  125. package/dist/layout/json-tree/JsonTree.svelte +425 -51
  126. package/dist/layout/json-tree/JsonTree.svelte.d.ts +1 -1
  127. package/dist/layout/json-tree/JsonValue.svelte +218 -97
  128. package/dist/layout/json-tree/types.d.ts +27 -2
  129. package/dist/layout/json-tree/utils.d.ts +14 -1
  130. package/dist/layout/json-tree/utils.js +254 -0
  131. package/dist/marching-cubes.d.ts +14 -0
  132. package/dist/marching-cubes.js +519 -0
  133. package/dist/math.d.ts +8 -0
  134. package/dist/math.js +374 -7
  135. package/dist/overlays/ContextMenu.svelte +3 -2
  136. package/dist/overlays/DraggablePane.svelte +163 -58
  137. package/dist/overlays/DraggablePane.svelte.d.ts +2 -0
  138. package/dist/phase-diagram/IsobaricBinaryPhaseDiagram.svelte +232 -77
  139. package/dist/phase-diagram/IsobaricBinaryPhaseDiagram.svelte.d.ts +6 -2
  140. package/dist/phase-diagram/PhaseDiagramControls.svelte +32 -11
  141. package/dist/phase-diagram/PhaseDiagramControls.svelte.d.ts +3 -2
  142. package/dist/phase-diagram/PhaseDiagramEditorPane.svelte +103 -0
  143. package/dist/phase-diagram/PhaseDiagramEditorPane.svelte.d.ts +15 -0
  144. package/dist/phase-diagram/PhaseDiagramExportPane.svelte +102 -95
  145. package/dist/phase-diagram/PhaseDiagramExportPane.svelte.d.ts +7 -0
  146. package/dist/phase-diagram/PhaseDiagramTooltip.svelte +100 -26
  147. package/dist/phase-diagram/PhaseDiagramTooltip.svelte.d.ts +6 -3
  148. package/dist/phase-diagram/index.d.ts +2 -0
  149. package/dist/phase-diagram/index.js +2 -0
  150. package/dist/phase-diagram/svg-to-diagram.d.ts +2 -0
  151. package/dist/phase-diagram/svg-to-diagram.js +865 -0
  152. package/dist/phase-diagram/types.d.ts +10 -0
  153. package/dist/phase-diagram/utils.d.ts +7 -4
  154. package/dist/phase-diagram/utils.js +149 -59
  155. package/dist/plot/AxisLabel.svelte +26 -0
  156. package/dist/plot/AxisLabel.svelte.d.ts +16 -0
  157. package/dist/plot/BarPlot.svelte +473 -228
  158. package/dist/plot/BarPlot.svelte.d.ts +3 -3
  159. package/dist/plot/BarPlotControls.svelte +3 -2
  160. package/dist/plot/BarPlotControls.svelte.d.ts +1 -1
  161. package/dist/plot/ColorBar.svelte +54 -54
  162. package/dist/plot/ColorBar.svelte.d.ts +1 -1
  163. package/dist/plot/ElementScatter.svelte +4 -3
  164. package/dist/plot/FillArea.svelte +4 -1
  165. package/dist/plot/Histogram.svelte +320 -230
  166. package/dist/plot/Histogram.svelte.d.ts +2 -2
  167. package/dist/plot/HistogramControls.svelte +29 -10
  168. package/dist/plot/HistogramControls.svelte.d.ts +6 -2
  169. package/dist/plot/InteractiveAxisLabel.svelte.d.ts +2 -2
  170. package/dist/plot/PlotControls.svelte +109 -27
  171. package/dist/plot/PlotControls.svelte.d.ts +1 -1
  172. package/dist/plot/PlotLegend.svelte +1 -1
  173. package/dist/plot/PortalSelect.svelte +2 -1
  174. package/dist/plot/ReferenceLine.svelte +2 -1
  175. package/dist/plot/ReferenceLine.svelte.d.ts +1 -0
  176. package/dist/plot/ReferencePlane.svelte +1 -3
  177. package/dist/plot/ScatterPlot.svelte +343 -209
  178. package/dist/plot/ScatterPlot.svelte.d.ts +3 -3
  179. package/dist/plot/ScatterPlot3D.svelte.d.ts +2 -2
  180. package/dist/plot/ScatterPlot3DControls.svelte +203 -250
  181. package/dist/plot/ScatterPlot3DScene.svelte +4 -7
  182. package/dist/plot/ScatterPlot3DScene.svelte.d.ts +2 -2
  183. package/dist/plot/ScatterPlotControls.svelte +95 -55
  184. package/dist/plot/ScatterPlotControls.svelte.d.ts +1 -1
  185. package/dist/plot/ZeroLines.svelte +44 -0
  186. package/dist/plot/ZeroLines.svelte.d.ts +32 -0
  187. package/dist/plot/ZoomRect.svelte +21 -0
  188. package/dist/plot/ZoomRect.svelte.d.ts +8 -0
  189. package/dist/plot/axis-utils.d.ts +1 -1
  190. package/dist/plot/data-cleaning.js +1 -5
  191. package/dist/plot/index.d.ts +6 -2
  192. package/dist/plot/index.js +6 -2
  193. package/dist/plot/interactions.d.ts +8 -10
  194. package/dist/plot/interactions.js +10 -19
  195. package/dist/plot/layout.d.ts +7 -1
  196. package/dist/plot/layout.js +12 -4
  197. package/dist/plot/reference-line.d.ts +4 -21
  198. package/dist/plot/reference-line.js +7 -81
  199. package/dist/plot/types.d.ts +42 -17
  200. package/dist/plot/types.js +10 -0
  201. package/dist/plot/utils/label-placement.js +14 -11
  202. package/dist/plot/utils.d.ts +1 -0
  203. package/dist/plot/utils.js +14 -0
  204. package/dist/rdf/RdfPlot.svelte +55 -66
  205. package/dist/rdf/RdfPlot.svelte.d.ts +1 -1
  206. package/dist/rdf/index.d.ts +1 -1
  207. package/dist/rdf/index.js +1 -1
  208. package/dist/settings.d.ts +5 -0
  209. package/dist/settings.js +37 -3
  210. package/dist/spectral/Bands.svelte +515 -143
  211. package/dist/spectral/Bands.svelte.d.ts +22 -2
  212. package/dist/spectral/helpers.d.ts +23 -1
  213. package/dist/spectral/helpers.js +65 -9
  214. package/dist/spectral/types.d.ts +2 -0
  215. package/dist/structure/AtomLegend.svelte +31 -10
  216. package/dist/structure/AtomLegend.svelte.d.ts +1 -1
  217. package/dist/structure/CellSelect.svelte +92 -22
  218. package/dist/structure/Lattice.svelte +2 -0
  219. package/dist/structure/Structure.svelte +716 -173
  220. package/dist/structure/Structure.svelte.d.ts +7 -2
  221. package/dist/structure/StructureControls.svelte +26 -14
  222. package/dist/structure/StructureControls.svelte.d.ts +5 -1
  223. package/dist/structure/StructureInfoPane.svelte +7 -1
  224. package/dist/structure/StructureScene.svelte +386 -95
  225. package/dist/structure/StructureScene.svelte.d.ts +15 -4
  226. package/dist/structure/atom-properties.d.ts +6 -2
  227. package/dist/structure/atom-properties.js +38 -25
  228. package/dist/structure/export.js +10 -7
  229. package/dist/structure/ferrox-wasm-types.d.ts +3 -2
  230. package/dist/structure/ferrox-wasm-types.js +0 -3
  231. package/dist/structure/ferrox-wasm.d.ts +3 -2
  232. package/dist/structure/ferrox-wasm.js +1 -2
  233. package/dist/structure/index.d.ts +7 -0
  234. package/dist/structure/index.js +22 -0
  235. package/dist/structure/parse.js +19 -16
  236. package/dist/structure/partial-occupancy.d.ts +25 -0
  237. package/dist/structure/partial-occupancy.js +102 -0
  238. package/dist/structure/validation.js +6 -3
  239. package/dist/symmetry/SymmetryStats.svelte +18 -4
  240. package/dist/symmetry/WyckoffTable.svelte +18 -10
  241. package/dist/symmetry/index.d.ts +7 -4
  242. package/dist/symmetry/index.js +83 -18
  243. package/dist/table/HeatmapTable.svelte +468 -69
  244. package/dist/table/HeatmapTable.svelte.d.ts +13 -1
  245. package/dist/table/ToggleMenu.svelte +291 -44
  246. package/dist/table/ToggleMenu.svelte.d.ts +4 -1
  247. package/dist/table/index.d.ts +3 -0
  248. package/dist/tooltip/index.d.ts +1 -1
  249. package/dist/tooltip/index.js +1 -0
  250. package/dist/trajectory/Trajectory.svelte +147 -145
  251. package/dist/trajectory/TrajectoryExportPane.svelte +13 -9
  252. package/dist/trajectory/TrajectoryExportPane.svelte.d.ts +1 -1
  253. package/dist/trajectory/constants.d.ts +6 -0
  254. package/dist/trajectory/constants.js +7 -0
  255. package/dist/trajectory/extract.js +3 -5
  256. package/dist/trajectory/format-detect.d.ts +9 -0
  257. package/dist/trajectory/format-detect.js +76 -0
  258. package/dist/trajectory/frame-reader.d.ts +17 -0
  259. package/dist/trajectory/frame-reader.js +339 -0
  260. package/dist/trajectory/helpers.d.ts +15 -0
  261. package/dist/trajectory/helpers.js +187 -0
  262. package/dist/trajectory/index.d.ts +1 -0
  263. package/dist/trajectory/index.js +11 -4
  264. package/dist/trajectory/parse/ase.d.ts +2 -0
  265. package/dist/trajectory/parse/ase.js +76 -0
  266. package/dist/trajectory/parse/hdf5.d.ts +2 -0
  267. package/dist/trajectory/parse/hdf5.js +121 -0
  268. package/dist/trajectory/parse/index.d.ts +12 -0
  269. package/dist/trajectory/parse/index.js +304 -0
  270. package/dist/trajectory/parse/lammps.d.ts +5 -0
  271. package/dist/trajectory/parse/lammps.js +169 -0
  272. package/dist/trajectory/parse/vasp.d.ts +2 -0
  273. package/dist/trajectory/parse/vasp.js +65 -0
  274. package/dist/trajectory/parse/xyz.d.ts +2 -0
  275. package/dist/trajectory/parse/xyz.js +109 -0
  276. package/dist/trajectory/types.d.ts +11 -0
  277. package/dist/trajectory/types.js +1 -0
  278. package/dist/utils.d.ts +2 -0
  279. package/dist/utils.js +4 -0
  280. package/dist/xrd/XrdPlot.svelte +6 -4
  281. package/dist/xrd/calc-xrd.js +0 -1
  282. package/package.json +33 -23
  283. package/readme.md +4 -4
  284. package/dist/trajectory/parse.d.ts +0 -42
  285. package/dist/trajectory/parse.js +0 -1267
  286. /package/dist/element/{data.json.d.ts → data.json.gz.d.ts} +0 -0
@@ -0,0 +1,865 @@
1
+ // SVG-to-DiagramInput converter
2
+ // Parses phase diagram SVGs (matplotlib or simple/Gemini format) into DiagramInput JSON
3
+ // for immediate rendering by IsobaricBinaryPhaseDiagram
4
+ // Two-phase color keys to cycle through for region assignment
5
+ const TWO_PHASE_COLORS = [
6
+ `two_phase`,
7
+ `two_phase_intermetallic`,
8
+ `two_phase_fcc_liquid`,
9
+ `two_phase_intermetallic_alt`,
10
+ `two_phase_alt`,
11
+ `two_phase_gamma`,
12
+ `two_phase_mixed`,
13
+ `two_phase_si`,
14
+ `two_phase_bcc_liquid`,
15
+ `two_phase_hcp_liquid`,
16
+ `two_phase_theta_liquid`,
17
+ `two_phase_eta`,
18
+ ];
19
+ // Round to 6 decimal places for clean floating-point output
20
+ const round = (val) => Math.round(val * 1e6) / 1e6;
21
+ // === Format Detection ===
22
+ // Detect whether the SVG is matplotlib, MPDS, or simple format
23
+ function detect_format(doc) {
24
+ // Matplotlib SVGs have xtick/ytick group IDs
25
+ if (doc.querySelector(`[id^="xtick_"]`) || doc.querySelector(`[id^="ytick_"]`)) {
26
+ return `matplotlib`;
27
+ }
28
+ // MPDS SVGs (from CorelDRAW/Inkscape) have sodipodi namespace or inkscape attributes
29
+ const svg_el = doc.querySelector(`svg`);
30
+ if (svg_el?.getAttribute(`sodipodi:docname`) ||
31
+ svg_el?.getAttribute(`inkscape:version`) ||
32
+ svg_el?.getAttributeNS(`http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd`, `docname`)) {
33
+ return `mpds`;
34
+ }
35
+ return `simple`;
36
+ }
37
+ // === Axis Scale Extraction ===
38
+ // Extract x and y axis scales from tick marks
39
+ function extract_axis_scales(doc, format) {
40
+ const x_ticks = [];
41
+ const y_ticks = [];
42
+ if (format === `matplotlib`) {
43
+ extract_matplotlib_ticks(doc, x_ticks, y_ticks);
44
+ }
45
+ else if (format === `mpds`) {
46
+ return extract_mpds_scales(doc);
47
+ }
48
+ else {
49
+ extract_simple_ticks(doc, x_ticks, y_ticks);
50
+ }
51
+ if (x_ticks.length < 2) {
52
+ throw new Error(`Need at least 2 x-axis ticks, found ${x_ticks.length}`);
53
+ }
54
+ if (y_ticks.length < 2) {
55
+ throw new Error(`Need at least 2 y-axis ticks, found ${y_ticks.length}`);
56
+ }
57
+ return {
58
+ x_scale: build_scale(x_ticks),
59
+ y_scale: build_scale(y_ticks), // y-axis inverted (SVG y down, temp up)
60
+ };
61
+ }
62
+ // Extract ticks from matplotlib SVG (id="xtick_N", comment-based values)
63
+ function extract_matplotlib_ticks(doc, x_ticks, y_ticks) {
64
+ const axes = [
65
+ [`xtick_`, `x`, x_ticks],
66
+ [`ytick_`, `y`, y_ticks],
67
+ ];
68
+ for (const [prefix, attr, ticks] of axes) {
69
+ for (const group of Array.from(doc.querySelectorAll(`[id^="${prefix}"]`))) {
70
+ const value = extract_comment_number(group);
71
+ const use_el = group.querySelector(`use`);
72
+ if (value !== null && use_el) {
73
+ const px = parse_float_attr(use_el, attr);
74
+ if (px !== null)
75
+ ticks.push({ px, value });
76
+ }
77
+ }
78
+ }
79
+ }
80
+ // Extract ticks from simple SVG (class-based text elements)
81
+ function extract_simple_ticks(doc, x_ticks, y_ticks) {
82
+ // Y-axis ticks: class="tick-text" with text-anchor: end
83
+ for (const text_el of Array.from(doc.querySelectorAll(`.tick-text`))) {
84
+ const value = parseFloat(text_el.textContent?.trim() ?? ``);
85
+ if (isNaN(value))
86
+ continue;
87
+ // Find the immediately preceding sibling tick line (not just any line in parent)
88
+ const tick_line = text_el.previousElementSibling;
89
+ if (!tick_line || !tick_line.matches(`.tick-line, line`))
90
+ continue;
91
+ const py = parse_float_attr(tick_line, `y1`);
92
+ // Apply parent group transform if present
93
+ const parent = text_el.parentElement;
94
+ const transform_y = get_group_translate(parent, `y`);
95
+ if (py !== null)
96
+ y_ticks.push({ px: py + transform_y, value });
97
+ }
98
+ // X-axis ticks: class="tick-text-x"
99
+ for (const text_el of Array.from(doc.querySelectorAll(`.tick-text-x`))) {
100
+ const value = parseFloat(text_el.textContent?.trim() ?? ``);
101
+ if (isNaN(value))
102
+ continue;
103
+ const px_x = parse_float_attr(text_el, `x`);
104
+ // Apply parent group transform if present
105
+ const parent = text_el.parentElement;
106
+ const transform_x = get_group_translate(parent, `x`);
107
+ if (px_x !== null)
108
+ x_ticks.push({ px: px_x + transform_x, value });
109
+ }
110
+ }
111
+ // Extract scales from MPDS SVGs using tick mark paths and text values
112
+ // MPDS SVGs store tick marks as multi-segment paths with major ticks (longer)
113
+ // and minor ticks (shorter). Text values are not positionally useful but
114
+ // tell us the data range.
115
+ function extract_mpds_scales(doc) {
116
+ // Extract all numeric text values to infer axis ranges
117
+ const numbers = [];
118
+ for (const text_el of Array.from(doc.querySelectorAll(`text`))) {
119
+ const val = parseFloat(text_el.textContent?.trim() ?? ``);
120
+ if (!isNaN(val))
121
+ numbers.push(val);
122
+ }
123
+ // Separate composition (0-100 at%) from temperature (typically 100-3000)
124
+ // Note: value 100 appears in both filters (valid as 100 at% and 100°C).
125
+ // This is intentional — only endpoints are used for scale mapping.
126
+ const comp_vals = [
127
+ ...new Set(numbers.filter((v) => v >= 0 && v <= 100 && v % 10 === 0)),
128
+ ].sort((a, b) => a - b);
129
+ const temp_vals = [
130
+ ...new Set(numbers.filter((v) => v >= 100 && v % 100 === 0 && v <= 3000)),
131
+ ].sort((a, b) => a - b);
132
+ if (comp_vals.length < 2 || temp_vals.length < 2) {
133
+ throw new Error(`MPDS SVG: could not infer axis ranges (found ${comp_vals.length} composition, ${temp_vals.length} temperature values)`);
134
+ }
135
+ // Find tick mark paths — multi-segment paths with stroke-width ~0.5
136
+ // containing both major (longer) and minor (shorter) tick marks
137
+ const x_major_ticks = [];
138
+ const y_major_ticks = [];
139
+ for (const path of Array.from(doc.querySelectorAll(`path`))) {
140
+ const d = path.getAttribute(`d`) ?? ``;
141
+ const stroke_width = parse_stroke_width(path);
142
+ // Tick mark paths have stroke-width ~0.5
143
+ if (stroke_width < 0.3 || stroke_width > 1.0)
144
+ continue;
145
+ // Parse path into absolute line segments (handles both absolute & relative commands)
146
+ const segments = parse_path_segments(d);
147
+ if (segments.length < 3)
148
+ continue;
149
+ for (const [sx1, sy1, sx2, sy2] of segments) {
150
+ const seg_dx = Math.abs(sx2 - sx1);
151
+ const seg_dy = Math.abs(sy2 - sy1);
152
+ // Major ticks are longer (~3.9 px), minor are shorter (~1.7 px)
153
+ if (Math.hypot(seg_dx, seg_dy) < 3)
154
+ continue;
155
+ // Horizontal tick segments → y-axis tick (x changes, y constant)
156
+ if (seg_dy < 0.1 && seg_dx > 2) {
157
+ y_major_ticks.push(Math.round(sy1 * 100) / 100);
158
+ }
159
+ // Vertical tick segments → x-axis tick (y changes, x constant)
160
+ if (seg_dx < 0.1 && seg_dy > 2) {
161
+ x_major_ticks.push(Math.round(sx1 * 100) / 100);
162
+ }
163
+ }
164
+ }
165
+ // Deduplicate and sort
166
+ const x_ticks_sorted = [...new Set(x_major_ticks.map((v) => Math.round(v * 10) / 10))]
167
+ .sort((a, b) => a - b);
168
+ const y_ticks_sorted = [...new Set(y_major_ticks.map((v) => Math.round(v * 10) / 10))]
169
+ .sort((a, b) => a - b);
170
+ if (x_ticks_sorted.length < 2 || y_ticks_sorted.length < 2) {
171
+ throw new Error(`MPDS SVG: could not find tick marks (found ${x_ticks_sorted.length} x-ticks, ${y_ticks_sorted.length} y-ticks)`);
172
+ }
173
+ // Map tick positions to data values using endpoints
174
+ // Only the first and last tick+value need to match for a linear scale
175
+ // x-axis: composition in at% → fraction; y-axis: temperature (SVG y inverted)
176
+ const x_ticks = [
177
+ { px: x_ticks_sorted[0], value: comp_vals[0] / 100 },
178
+ {
179
+ px: x_ticks_sorted[x_ticks_sorted.length - 1],
180
+ value: comp_vals[comp_vals.length - 1] / 100,
181
+ },
182
+ ];
183
+ const y_ticks = [
184
+ { px: y_ticks_sorted[0], value: temp_vals[temp_vals.length - 1] }, // top = highest temp
185
+ { px: y_ticks_sorted[y_ticks_sorted.length - 1], value: temp_vals[0] }, // bottom = lowest temp
186
+ ];
187
+ return {
188
+ x_scale: build_scale(x_ticks),
189
+ y_scale: build_scale(y_ticks),
190
+ };
191
+ }
192
+ // Build a linear scale from tick data points
193
+ function build_scale(ticks) {
194
+ ticks.sort((a, b) => a.value - b.value);
195
+ const first = ticks[0];
196
+ const last = ticks[ticks.length - 1];
197
+ const range = last.value - first.value;
198
+ if (range === 0) {
199
+ return { to_data: () => first.value, domain: [first.value, last.value] };
200
+ }
201
+ const px_per_unit = (last.px - first.px) / range;
202
+ return {
203
+ to_data: (px) => first.value + (px - first.px) / px_per_unit,
204
+ domain: [first.value, last.value],
205
+ };
206
+ }
207
+ // === Boundary Extraction ===
208
+ // Extract phase boundary lines from SVG and convert to data coordinates
209
+ function extract_boundaries(doc, format, x_scale, y_scale) {
210
+ const boundaries = [];
211
+ const epsilon = 0.5; // pixel tolerance for classifying horizontal/vertical
212
+ if (format === `mpds`) {
213
+ extract_mpds_boundaries(doc, boundaries, x_scale, y_scale, epsilon);
214
+ }
215
+ else if (format === `matplotlib`) {
216
+ // Matplotlib: look for line2d_N groups with path elements (skip tick marks at line2d_1..12ish)
217
+ for (const group of Array.from(doc.querySelectorAll(`[id^="line2d_"]`))) {
218
+ const path_el = group.querySelector(`path`);
219
+ if (!path_el)
220
+ continue;
221
+ const d_attr = path_el.getAttribute(`d`);
222
+ if (!d_attr)
223
+ continue;
224
+ // Parse "M x1 y1 L x2 y2" path data
225
+ const coords = parse_ml_path(d_attr);
226
+ if (!coords)
227
+ continue;
228
+ // Skip tick mark lines (short lines, typically < 10px)
229
+ const dx = Math.abs(coords.x2 - coords.x1);
230
+ const dy = Math.abs(coords.y2 - coords.y1);
231
+ if (dx < 15 && dy < 15)
232
+ continue;
233
+ // Check stroke-width to distinguish boundaries from axis lines
234
+ const stroke_width = parse_stroke_width(path_el) || 1;
235
+ // Axis patches (id="patch_*") are axis borders, not phase boundaries
236
+ const parent_id = group.getAttribute(`id`) ?? ``;
237
+ if (parent_id.startsWith(`patch_`))
238
+ continue;
239
+ // Only include lines with meaningful stroke
240
+ if (stroke_width < 1)
241
+ continue;
242
+ add_boundary(boundaries, coords, x_scale, y_scale, epsilon);
243
+ }
244
+ }
245
+ else {
246
+ // Simple: <line class="phase-boundary">
247
+ for (const line_el of Array.from(doc.querySelectorAll(`.phase-boundary, line[class*="phase-boundary"]`))) {
248
+ const x1 = parse_float_attr(line_el, `x1`);
249
+ const y1 = parse_float_attr(line_el, `y1`);
250
+ const x2 = parse_float_attr(line_el, `x2`);
251
+ const y2 = parse_float_attr(line_el, `y2`);
252
+ if (x1 === null || y1 === null || x2 === null || y2 === null)
253
+ continue;
254
+ add_boundary(boundaries, { x1, y1, x2, y2 }, x_scale, y_scale, epsilon);
255
+ }
256
+ }
257
+ return boundaries;
258
+ }
259
+ // Extract boundaries from MPDS SVGs — simple M x1,y1 L x2,y2 path elements
260
+ // inside the plot area with thin stroke (0.216) and dark color
261
+ function extract_mpds_boundaries(doc, boundaries, x_scale, y_scale, epsilon) {
262
+ // Find the plot border to filter boundaries inside it
263
+ const plot_rect = find_mpds_plot_rect(doc);
264
+ if (!plot_rect)
265
+ return;
266
+ const { left, right, top, bottom } = plot_rect;
267
+ for (const path of Array.from(doc.querySelectorAll(`path`))) {
268
+ const d = path.getAttribute(`d`) ?? ``;
269
+ const style = path.getAttribute(`style`) ?? ``;
270
+ // Skip tick mark paths (stroke-width > 0.3)
271
+ const stroke_width = parse_stroke_width(path);
272
+ if (stroke_width > 0.3 || stroke_width === 0)
273
+ continue;
274
+ // Skip filled regions (phase region fills)
275
+ if (style.includes(`fill-rule`) || style.includes(`fill: #`) || style.includes(`fill:#`)) {
276
+ if (!style.includes(`fill: none`) && !style.includes(`fill:none`))
277
+ continue;
278
+ }
279
+ // Skip red annotation lines
280
+ if (style.includes(`#e30016`) || style.includes(`#E30016`))
281
+ continue;
282
+ // Parse as simple M...L line
283
+ const coords = parse_ml_path(d);
284
+ if (!coords)
285
+ continue;
286
+ // Must be inside the plot area
287
+ const inside = coords.x1 >= left - 1 && coords.x1 <= right + 1 &&
288
+ coords.x2 >= left - 1 && coords.x2 <= right + 1 &&
289
+ coords.y1 >= top - 1 && coords.y1 <= bottom + 1 &&
290
+ coords.y2 >= top - 1 && coords.y2 <= bottom + 1;
291
+ if (!inside)
292
+ continue;
293
+ // Skip very short segments (< 10px)
294
+ const dx = Math.abs(coords.x2 - coords.x1);
295
+ const dy = Math.abs(coords.y2 - coords.y1);
296
+ if (dx < 10 && dy < 10)
297
+ continue;
298
+ // Skip the plot border itself (connects all 4 edges)
299
+ const touches_left = Math.abs(coords.x1 - left) < 2 || Math.abs(coords.x2 - left) < 2;
300
+ const touches_right = Math.abs(coords.x1 - right) < 2 ||
301
+ Math.abs(coords.x2 - right) < 2;
302
+ if (touches_left && touches_right)
303
+ continue; // spans full width = likely axis
304
+ add_boundary(boundaries, coords, x_scale, y_scale, epsilon);
305
+ }
306
+ }
307
+ // Find the plot area rectangle in an MPDS SVG
308
+ // Handles both M...L...L...L...Z and M...V...H...V...Z formats
309
+ function find_mpds_plot_rect(doc) {
310
+ for (const path of Array.from(doc.querySelectorAll(`path`))) {
311
+ const d = path.getAttribute(`d`) ?? ``;
312
+ const style = path.getAttribute(`style`) ?? ``;
313
+ if (!style.includes(`fill: none`) && !style.includes(`fill:none`))
314
+ continue;
315
+ if (!d.includes(`Z`) && !d.includes(`z`))
316
+ continue;
317
+ // Parse path into absolute segments and extract corner points
318
+ const segments = parse_path_segments(d);
319
+ if (segments.length < 3)
320
+ continue; // rectangle needs at least 3 segments (4th is Z)
321
+ // Collect all x and y coordinates from segment endpoints
322
+ const xs = [];
323
+ const ys = [];
324
+ for (const [x1, y1, x2, y2] of segments) {
325
+ xs.push(Math.round(x1 * 10) / 10, Math.round(x2 * 10) / 10);
326
+ ys.push(Math.round(y1 * 10) / 10, Math.round(y2 * 10) / 10);
327
+ }
328
+ const unique_x = [...new Set(xs)];
329
+ const unique_y = [...new Set(ys)];
330
+ // Rectangle has exactly 2 unique x and 2 unique y values
331
+ if (unique_x.length === 2 && unique_y.length === 2) {
332
+ return {
333
+ left: Math.min(...unique_x),
334
+ right: Math.max(...unique_x),
335
+ top: Math.min(...unique_y),
336
+ bottom: Math.max(...unique_y),
337
+ };
338
+ }
339
+ }
340
+ return null;
341
+ }
342
+ // Add a boundary line, classifying as horizontal or vertical
343
+ function add_boundary(boundaries, px, x_scale, y_scale, epsilon) {
344
+ const is_vertical = Math.abs(px.x1 - px.x2) < epsilon;
345
+ const is_horizontal = Math.abs(px.y1 - px.y2) < epsilon;
346
+ if (!is_vertical && !is_horizontal)
347
+ return; // skip diagonal lines
348
+ const data_x1 = x_scale.to_data(px.x1);
349
+ const data_y1 = y_scale.to_data(px.y1);
350
+ const data_x2 = x_scale.to_data(px.x2);
351
+ const data_y2 = y_scale.to_data(px.y2);
352
+ boundaries.push({
353
+ x1: Math.min(data_x1, data_x2),
354
+ y1: Math.min(data_y1, data_y2),
355
+ x2: Math.max(data_x1, data_x2),
356
+ y2: Math.max(data_y1, data_y2),
357
+ orientation: is_vertical ? `vertical` : `horizontal`,
358
+ });
359
+ }
360
+ // === Label Extraction ===
361
+ // Extract phase region labels with their pixel positions
362
+ function extract_labels(doc, format) {
363
+ const labels = [];
364
+ if (format === `matplotlib`) {
365
+ extract_matplotlib_labels(doc, labels);
366
+ }
367
+ else if (format === `mpds`) {
368
+ // MPDS labels use garbled encoding; skip label extraction
369
+ // Regions will get auto-generated names from infer_regions
370
+ }
371
+ else {
372
+ extract_simple_labels(doc, labels);
373
+ }
374
+ return labels;
375
+ }
376
+ // Extract labels from matplotlib SVG using XML comments
377
+ function extract_matplotlib_labels(doc, labels) {
378
+ // Find text groups with comments containing phase names
379
+ // Matplotlib may split multi-line labels (especially rotated ones) into
380
+ // separate <g> groups: text_N has "La$_2$NiO$_4$", followed by a sibling
381
+ // with "+ La$_3$Ni$_2$O$_7$". We concatenate these continuation groups.
382
+ for (const group of Array.from(doc.querySelectorAll(`[id^="text_"]`))) {
383
+ let comment = find_comment_text(group);
384
+ if (!comment)
385
+ continue;
386
+ // Check following sibling groups for continuation comments starting with "+"
387
+ let sibling = group.nextElementSibling;
388
+ while (sibling) {
389
+ // Stop at the next text_N group (that's a separate label)
390
+ if (sibling.id?.startsWith(`text_`))
391
+ break;
392
+ const continuation = find_comment_text(sibling);
393
+ if (continuation?.trimStart().startsWith(`+`)) {
394
+ comment += ` ${continuation.trim()}`;
395
+ sibling = sibling.nextElementSibling;
396
+ }
397
+ else {
398
+ break;
399
+ }
400
+ }
401
+ if (!comment.includes(`+`))
402
+ continue; // skip axis labels (no "+")
403
+ // Clean LaTeX: "La$_2$NiO$_4$ + NiO" -> "La2NiO4 + NiO"
404
+ const text = clean_latex(comment.trim());
405
+ // Get position from transform="translate(x, y)"
406
+ const pos = parse_translate(group.querySelector(`g[transform]`)) ??
407
+ parse_translate(group);
408
+ if (!pos)
409
+ continue;
410
+ labels.push({ text, px_x: pos[0], px_y: pos[1] });
411
+ }
412
+ }
413
+ // Extract labels from simple SVG using class="label-main"
414
+ function extract_simple_labels(doc, labels) {
415
+ for (const text_el of Array.from(doc.querySelectorAll(`.label-main`))) {
416
+ // Get plain text content (strips tspan tags)
417
+ const text = (text_el.textContent ?? ``).replace(/\s+/g, ` `).trim();
418
+ if (!text.includes(`+`))
419
+ continue; // skip non-phase labels
420
+ // Get position from transform or x/y attributes
421
+ const pos = parse_translate(text_el);
422
+ const px_x = pos?.[0] ?? parse_float_attr(text_el, `x`);
423
+ const px_y = pos?.[1] ?? parse_float_attr(text_el, `y`);
424
+ if (px_x !== null && px_y !== null) {
425
+ labels.push({ text, px_x, px_y });
426
+ }
427
+ }
428
+ }
429
+ // === Component Inference ===
430
+ // Infer binary components from region labels
431
+ function infer_components(labels) {
432
+ // Sort labels by x position, split each into phases
433
+ const sorted = [...labels].sort((a, b) => a.px_x - b.px_x);
434
+ if (sorted.length < 2)
435
+ return [`A`, `B`];
436
+ const split = (label) => label.text.split(/\s*\+\s*/);
437
+ const leftmost = split(sorted[0]);
438
+ const rightmost = split(sorted[sorted.length - 1]);
439
+ // Component A: the unique phase in the leftmost region that doesn't appear on the right
440
+ // For "La2NiO4 + La2O3", La2O3 is the pure A endpoint
441
+ let comp_a = `A`;
442
+ if (leftmost.length === 2) {
443
+ const right_phases = sorted.slice(-3).flatMap(split);
444
+ comp_a = leftmost.find((p) => !right_phases.includes(p)) ?? leftmost[1] ?? `A`;
445
+ }
446
+ // Component B: the unique phase in the rightmost region that doesn't appear on the left
447
+ let comp_b = `B`;
448
+ if (rightmost.length === 2) {
449
+ const left_phases = sorted.slice(0, 3).flatMap(split);
450
+ comp_b = rightmost.find((p) => !left_phases.includes(p)) ?? rightmost[1] ?? `B`;
451
+ }
452
+ return [comp_a, comp_b];
453
+ }
454
+ // === Region Inference ===
455
+ // Infer phase regions from orthogonal boundaries using flood-fill on a cell grid
456
+ function infer_regions(boundaries, labels, x_scale, y_scale) {
457
+ const verticals = boundaries.filter((b) => b.orientation === `vertical`);
458
+ const horizontals = boundaries.filter((b) => b.orientation === `horizontal`);
459
+ // Collect all unique x and y coordinates (boundaries + domain edges)
460
+ const x_coords = collect_unique_sorted([
461
+ x_scale.domain[0],
462
+ x_scale.domain[1],
463
+ ...verticals.map((b) => b.x1), // x1 === x2 for vertical
464
+ ]);
465
+ const y_coords = collect_unique_sorted([
466
+ y_scale.domain[0],
467
+ y_scale.domain[1],
468
+ ...horizontals.map((b) => b.y1), // y1 === y2 for horizontal
469
+ ]);
470
+ // Build cell grid: cells[col][row]
471
+ const n_cols = x_coords.length - 1;
472
+ const n_rows = y_coords.length - 1;
473
+ const cell_ids = Array.from({ length: n_cols }, () => new Array(n_rows).fill(-1));
474
+ // Check which cell edges have boundaries
475
+ const h_walls = Array.from({ length: n_cols }, () => new Array(n_rows + 1).fill(false));
476
+ const v_walls = Array.from({ length: n_cols + 1 }, () => new Array(n_rows).fill(false));
477
+ // Mark horizontal walls (bottom/top of cells)
478
+ for (const hb of horizontals) {
479
+ const row = find_coord_index(y_coords, hb.y1);
480
+ if (row === -1)
481
+ continue;
482
+ for (let col = 0; col < n_cols; col++) {
483
+ const cell_x_min = x_coords[col];
484
+ const cell_x_max = x_coords[col + 1];
485
+ // Check if the boundary spans this cell's x range
486
+ if (hb.x1 <= cell_x_min + 1e-6 && hb.x2 >= cell_x_max - 1e-6) {
487
+ h_walls[col][row] = true;
488
+ }
489
+ }
490
+ }
491
+ // Mark vertical walls (left/right of cells)
492
+ for (const vb of verticals) {
493
+ const col = find_coord_index(x_coords, vb.x1);
494
+ if (col === -1)
495
+ continue;
496
+ for (let row = 0; row < n_rows; row++) {
497
+ const cell_y_min = y_coords[row];
498
+ const cell_y_max = y_coords[row + 1];
499
+ // Check if the boundary spans this cell's y range
500
+ if (vb.y1 <= cell_y_min + 1e-6 && vb.y2 >= cell_y_max - 1e-6) {
501
+ v_walls[col][row] = true;
502
+ }
503
+ }
504
+ }
505
+ // Plot edges are always walls
506
+ for (let col = 0; col < n_cols; col++) {
507
+ h_walls[col][0] = true; // bottom edge
508
+ h_walls[col][n_rows] = true; // top edge
509
+ }
510
+ for (let row = 0; row < n_rows; row++) {
511
+ v_walls[0][row] = true; // left edge
512
+ v_walls[n_cols][row] = true; // right edge
513
+ }
514
+ // Flood-fill to assign region IDs
515
+ let next_region_id = 0;
516
+ for (let col = 0; col < n_cols; col++) {
517
+ for (let row = 0; row < n_rows; row++) {
518
+ if (cell_ids[col][row] !== -1)
519
+ continue;
520
+ flood_fill(cell_ids, h_walls, v_walls, col, row, n_cols, n_rows, next_region_id);
521
+ next_region_id++;
522
+ }
523
+ }
524
+ // Assign labels to regions by checking which region contains each label's position
525
+ const region_labels = new Map();
526
+ for (const label of labels) {
527
+ const data_x = x_scale.to_data(label.px_x);
528
+ const data_y = y_scale.to_data(label.px_y);
529
+ const col = find_cell_index(x_coords, data_x);
530
+ const row = find_cell_index(y_coords, data_y);
531
+ if (col >= 0 && col < n_cols && row >= 0 && row < n_rows) {
532
+ const region_id = cell_ids[col][row];
533
+ if (region_id !== -1) {
534
+ region_labels.set(region_id, label.text);
535
+ }
536
+ }
537
+ }
538
+ // Build region polygons from merged cells
539
+ const regions = [];
540
+ for (let region_id = 0; region_id < next_region_id; region_id++) {
541
+ const name = region_labels.get(region_id) ?? `Region ${region_id + 1}`;
542
+ // Slug can be empty for non-ASCII labels like "α + β" — fall back to region_N
543
+ const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, `_`).replace(/^_|_$/g, ``) || `region_${region_id + 1}`;
544
+ // Find bounding box of all cells in this region
545
+ let min_x = Infinity;
546
+ let max_x = -Infinity;
547
+ let min_y = Infinity;
548
+ let max_y = -Infinity;
549
+ for (let col = 0; col < n_cols; col++) {
550
+ for (let row = 0; row < n_rows; row++) {
551
+ if (cell_ids[col][row] !== region_id)
552
+ continue;
553
+ min_x = Math.min(min_x, x_coords[col]);
554
+ max_x = Math.max(max_x, x_coords[col + 1]);
555
+ min_y = Math.min(min_y, y_coords[row]);
556
+ max_y = Math.max(max_y, y_coords[row + 1]);
557
+ }
558
+ }
559
+ if (min_x === Infinity)
560
+ continue;
561
+ const bounds = [
562
+ [round(min_x), round(min_y)],
563
+ [round(max_x), round(min_y)],
564
+ [round(max_x), round(max_y)],
565
+ [round(min_x), round(max_y)],
566
+ ];
567
+ regions.push({
568
+ id: slug,
569
+ name,
570
+ color: TWO_PHASE_COLORS[region_id % TWO_PHASE_COLORS.length],
571
+ bounds,
572
+ });
573
+ }
574
+ return regions;
575
+ }
576
+ // Flood-fill connected cells that share an open edge
577
+ function flood_fill(cell_ids, h_walls, v_walls, start_col, start_row, n_cols, n_rows, region_id) {
578
+ const stack = [[start_col, start_row]];
579
+ for (let item = stack.pop(); item; item = stack.pop()) {
580
+ const [col, row] = item;
581
+ if (col < 0 || col >= n_cols || row < 0 || row >= n_rows)
582
+ continue;
583
+ if (cell_ids[col][row] !== -1)
584
+ continue;
585
+ cell_ids[col][row] = region_id;
586
+ // Check neighbors (no wall between them)
587
+ // Left neighbor: check v_walls[col][row]
588
+ if (col > 0 && !v_walls[col][row])
589
+ stack.push([col - 1, row]);
590
+ // Right neighbor: check v_walls[col+1][row]
591
+ if (col < n_cols - 1 && !v_walls[col + 1][row])
592
+ stack.push([col + 1, row]);
593
+ // Bottom neighbor: check h_walls[col][row]
594
+ if (row > 0 && !h_walls[col][row])
595
+ stack.push([col, row - 1]);
596
+ // Top neighbor: check h_walls[col][row+1]
597
+ if (row < n_rows - 1 && !h_walls[col][row + 1])
598
+ stack.push([col, row + 1]);
599
+ }
600
+ }
601
+ // === Curve Generation ===
602
+ // Generate named curves from boundaries for the DiagramInput format
603
+ function generate_curves(boundaries) {
604
+ const curves = {};
605
+ const counts = { vertical: 0, horizontal: 0 };
606
+ for (const bnd of boundaries) {
607
+ const is_vert = bnd.orientation === `vertical`;
608
+ const name = `${bnd.orientation}_${counts[bnd.orientation]++}`;
609
+ curves[name] = [
610
+ [round(bnd.x1), round(bnd.y1)],
611
+ [round(is_vert ? bnd.x1 : bnd.x2), round(is_vert ? bnd.y2 : bnd.y1)],
612
+ ];
613
+ }
614
+ return curves;
615
+ }
616
+ // === Main Entry Point ===
617
+ // Parse a phase diagram SVG string and return a DiagramInput
618
+ export function parse_phase_diagram_svg(svg_string) {
619
+ const parser = new DOMParser();
620
+ const doc = parser.parseFromString(svg_string, `image/svg+xml`);
621
+ // Check for parse errors
622
+ const parse_error = doc.querySelector(`parsererror`);
623
+ if (parse_error) {
624
+ throw new Error(`Invalid SVG: ${parse_error.textContent}`);
625
+ }
626
+ const format = detect_format(doc);
627
+ const { x_scale, y_scale } = extract_axis_scales(doc, format);
628
+ const boundaries = extract_boundaries(doc, format, x_scale, y_scale);
629
+ const labels = extract_labels(doc, format);
630
+ const components = format === `mpds`
631
+ ? infer_mpds_components(doc)
632
+ : infer_components(labels);
633
+ if (boundaries.length === 0) {
634
+ throw new Error(`No phase boundaries found in SVG`);
635
+ }
636
+ const regions = infer_regions(boundaries, labels, x_scale, y_scale);
637
+ const curves = generate_curves(boundaries);
638
+ // MPDS SVGs use °C for temperature
639
+ const temp_unit = format === `mpds` ? `°C` : `K`;
640
+ return {
641
+ meta: {
642
+ components,
643
+ temp_range: y_scale.domain,
644
+ temp_unit,
645
+ comp_unit: `fraction`,
646
+ title: `Imported Phase Diagram`,
647
+ },
648
+ curves,
649
+ regions,
650
+ };
651
+ }
652
+ // Infer components from MPDS SVGs by finding element-like text content
653
+ // MPDS SVGs have readable element names as text (e.g., "Cu", "Si")
654
+ function infer_mpds_components(doc) {
655
+ const elements = new Set();
656
+ for (const text_el of Array.from(doc.querySelectorAll(`text`))) {
657
+ const content = text_el.textContent?.trim() ?? ``;
658
+ // Match single/two-letter element symbols, exclude common non-element text
659
+ if (/^[A-Z][a-z]?$/.test(content) && content !== `L` && content !== `M`) {
660
+ elements.add(content);
661
+ }
662
+ }
663
+ const unique = [...elements];
664
+ return [unique[0] ?? `A`, unique[1] ?? `B`];
665
+ }
666
+ // === Utility Functions ===
667
+ // Parse stroke-width from style attribute or direct attribute (returns 0 if not found)
668
+ function parse_stroke_width(el) {
669
+ const style_match = (el.getAttribute(`style`) ?? ``).match(/stroke-width:\s*([\d.]+)/);
670
+ if (style_match)
671
+ return parseFloat(style_match[1]);
672
+ const attr = el.getAttribute(`stroke-width`);
673
+ return attr ? parseFloat(attr) || 0 : 0;
674
+ }
675
+ // Parse a float attribute from an SVG element
676
+ function parse_float_attr(el, attr) {
677
+ const val = el.getAttribute(attr);
678
+ if (val === null)
679
+ return null;
680
+ const parsed = parseFloat(val);
681
+ return isNaN(parsed) ? null : parsed;
682
+ }
683
+ // Extract a number from XML comment nodes inside a group element
684
+ function extract_comment_number(group) {
685
+ const walker = group.ownerDocument.createTreeWalker(group, NodeFilter.SHOW_COMMENT);
686
+ let node;
687
+ while ((node = walker.nextNode())) {
688
+ const value = parseFloat(node.textContent?.trim() ?? ``);
689
+ if (!isNaN(value))
690
+ return value;
691
+ }
692
+ return null;
693
+ }
694
+ // Find the first XML comment text inside or preceding a group
695
+ function find_comment_text(group) {
696
+ // Check comment nodes inside the group
697
+ const walker = group.ownerDocument.createTreeWalker(group, NodeFilter.SHOW_COMMENT);
698
+ let node;
699
+ while ((node = walker.nextNode())) {
700
+ const text = node.textContent?.trim();
701
+ if (text && text.length > 1)
702
+ return text;
703
+ }
704
+ // Check preceding sibling comments
705
+ let sibling = group.previousSibling;
706
+ while (sibling) {
707
+ if (sibling.nodeType === Node.COMMENT_NODE) {
708
+ const text = sibling.textContent?.trim();
709
+ if (text && text.length > 1)
710
+ return text;
711
+ }
712
+ if (sibling.nodeType === Node.ELEMENT_NODE)
713
+ break; // stop at previous element
714
+ sibling = sibling.previousSibling;
715
+ }
716
+ return null;
717
+ }
718
+ // Clean LaTeX subscript notation: "La$_2$NiO$_4$" -> "La2NiO4"
719
+ function clean_latex(text) {
720
+ return text
721
+ .replace(/\$_\{([^}]*)\}\$/g, `$1`) // $_{10}$ -> 10
722
+ .replace(/\$_(\d)\$/g, `$1`) // $_2$ -> 2
723
+ .replace(/\$/g, ``) // remove any remaining $
724
+ .replace(/\s+/g, ` `)
725
+ .trim();
726
+ }
727
+ // Parse SVG path data into absolute line segments [x1,y1,x2,y2]
728
+ // Handles all SVG path commands (M/L/H/V/C/S/Q/T/A/Z, both absolute and relative)
729
+ // Curves (C/S/Q/T/A) are approximated as straight lines from start to endpoint
730
+ // After M/m, implicit coordinates are treated as L/l per SVG spec
731
+ function parse_path_segments(d) {
732
+ const segments = [];
733
+ let [cursor_x, cursor_y] = [0, 0];
734
+ let [start_x, start_y] = [0, 0];
735
+ let last_cmd = ``;
736
+ // Numbers to skip before the endpoint x,y for each curve command
737
+ const curve_skip = { C: 4, S: 2, Q: 2, T: 0, A: 5 };
738
+ const tokens = d.match(/[MmLlHhVvCcSsQqTtAaZz]|[-+]?[\d]*\.?[\d]+(?:[eE][-+]?\d+)?/g);
739
+ if (!tokens)
740
+ return segments;
741
+ let idx = 0;
742
+ const peek = () => tokens[idx];
743
+ const next_num = () => parseFloat(tokens[idx++] ?? `0`);
744
+ while (idx < tokens.length) {
745
+ let cmd = peek() ?? ``;
746
+ if (cmd.length === 1 && /[A-Za-z]/.test(cmd)) {
747
+ idx++;
748
+ last_cmd = cmd;
749
+ }
750
+ else {
751
+ // Implicit repeat: after M→L, after m→l, others repeat themselves
752
+ cmd = last_cmd === `M` ? `L` : last_cmd === `m` ? `l` : last_cmd;
753
+ }
754
+ if (cmd === `M` || cmd === `m`) {
755
+ const next_x = next_num();
756
+ const next_y = next_num();
757
+ cursor_x = cmd === `M` ? next_x : cursor_x + next_x;
758
+ cursor_y = cmd === `M` ? next_y : cursor_y + next_y;
759
+ start_x = cursor_x;
760
+ start_y = cursor_y;
761
+ last_cmd = cmd;
762
+ }
763
+ else if (cmd === `L` || cmd === `l`) {
764
+ const next_x = next_num();
765
+ const next_y = next_num();
766
+ const x2 = cmd === `L` ? next_x : cursor_x + next_x;
767
+ const y2 = cmd === `L` ? next_y : cursor_y + next_y;
768
+ segments.push([cursor_x, cursor_y, x2, y2]);
769
+ cursor_x = x2;
770
+ cursor_y = y2;
771
+ }
772
+ else if (cmd === `H` || cmd === `h`) {
773
+ const next_x = next_num();
774
+ const x2 = cmd === `H` ? next_x : cursor_x + next_x;
775
+ segments.push([cursor_x, cursor_y, x2, cursor_y]);
776
+ cursor_x = x2;
777
+ }
778
+ else if (cmd === `V` || cmd === `v`) {
779
+ const next_y = next_num();
780
+ const y2 = cmd === `V` ? next_y : cursor_y + next_y;
781
+ segments.push([cursor_x, cursor_y, cursor_x, y2]);
782
+ cursor_y = y2;
783
+ }
784
+ else if (cmd === `Z` || cmd === `z`) {
785
+ if (cursor_x !== start_x || cursor_y !== start_y) {
786
+ segments.push([cursor_x, cursor_y, start_x, start_y]);
787
+ }
788
+ cursor_x = start_x;
789
+ cursor_y = start_y;
790
+ }
791
+ else {
792
+ // Curve commands: skip control/arc params, use endpoint as straight line
793
+ // C=4 skip, S=2, Q=2, T=0, A=5 (numbers before the final x,y endpoint)
794
+ const upper = cmd.toUpperCase();
795
+ const skip = curve_skip[upper];
796
+ if (skip !== undefined) {
797
+ for (let _skip = 0; _skip < skip; _skip++)
798
+ next_num();
799
+ const end_x = next_num();
800
+ const end_y = next_num();
801
+ const x2 = cmd === upper ? end_x : cursor_x + end_x;
802
+ const y2 = cmd === upper ? end_y : cursor_y + end_y;
803
+ segments.push([cursor_x, cursor_y, x2, y2]);
804
+ cursor_x = x2;
805
+ cursor_y = y2;
806
+ }
807
+ else {
808
+ idx++; // skip unknown tokens
809
+ }
810
+ }
811
+ }
812
+ return segments;
813
+ }
814
+ // Parse a simple 2-point line path (M...L only). Returns null for multi-segment paths
815
+ // to enforce the single-line contract expected by boundary extraction.
816
+ function parse_ml_path(d) {
817
+ const segments = parse_path_segments(d);
818
+ if (segments.length !== 1)
819
+ return null;
820
+ const [x1, y1, x2, y2] = segments[0];
821
+ return { x1, y1, x2, y2 };
822
+ }
823
+ // Parse translate(x, y) or translate(x) from a transform attribute
824
+ // Single-arg translate uses implicit y=0 per SVG spec
825
+ function parse_translate(el) {
826
+ const match = (el?.getAttribute(`transform`) ?? ``).match(/translate\(\s*([\d.eE+-]+)(?:\s*[,\s]\s*([\d.eE+-]+))?\s*\)/);
827
+ if (!match)
828
+ return null;
829
+ return [parseFloat(match[1]), match[2] ? parseFloat(match[2]) : 0];
830
+ }
831
+ // Get translate X or Y from a group's transform attribute
832
+ function get_group_translate(el, axis) {
833
+ const coords = parse_translate(el);
834
+ return coords ? coords[axis === `x` ? 0 : 1] : 0;
835
+ }
836
+ // Collect unique sorted values from an array (with epsilon deduplication)
837
+ function collect_unique_sorted(values) {
838
+ if (values.length === 0)
839
+ return [];
840
+ const sorted = [...values].sort((a, b) => a - b);
841
+ const unique = [sorted[0]];
842
+ for (let idx = 1; idx < sorted.length; idx++) {
843
+ if (Math.abs(sorted[idx] - unique[unique.length - 1]) > 1e-4) {
844
+ unique.push(sorted[idx]);
845
+ }
846
+ }
847
+ return unique;
848
+ }
849
+ // Find the index of a coordinate in a sorted array (with epsilon tolerance)
850
+ function find_coord_index(coords, value) {
851
+ for (let idx = 0; idx < coords.length; idx++) {
852
+ if (Math.abs(coords[idx] - value) < 1e-4)
853
+ return idx;
854
+ }
855
+ return -1;
856
+ }
857
+ // Find which cell interval a value falls into
858
+ function find_cell_index(coords, value) {
859
+ for (let idx = 0; idx < coords.length - 1; idx++) {
860
+ if (value >= coords[idx] - 1e-4 && value <= coords[idx + 1] + 1e-4) {
861
+ return idx;
862
+ }
863
+ }
864
+ return -1;
865
+ }