morphogen 1.0.0__py3-none-any.whl

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 (381) hide show
  1. morphogen/__init__.py +60 -0
  2. morphogen/__main__.py +7 -0
  3. morphogen/_platform.py +55 -0
  4. morphogen/_public.py +153 -0
  5. morphogen/_utils.py +80 -0
  6. morphogen/_version.py +1 -0
  7. morphogen/analysis/__init__.py +174 -0
  8. morphogen/analysis/anisotropy.py +135 -0
  9. morphogen/analysis/basic.py +38 -0
  10. morphogen/analysis/cells.py +54 -0
  11. morphogen/analysis/connectivity.py +156 -0
  12. morphogen/analysis/correlation.py +195 -0
  13. morphogen/analysis/covariance.py +80 -0
  14. morphogen/analysis/fractal.py +54 -0
  15. morphogen/analysis/measures.py +188 -0
  16. morphogen/analysis/morphology.py +265 -0
  17. morphogen/analysis/particles.py +160 -0
  18. morphogen/analysis/percolation.py +2034 -0
  19. morphogen/analysis/power_laws.py +143 -0
  20. morphogen/analysis/random_sets.py +351 -0
  21. morphogen/analysis/stereology.py +289 -0
  22. morphogen/analysis/surface.py +107 -0
  23. morphogen/analysis/topology.py +92 -0
  24. morphogen/automata/__init__.py +74 -0
  25. morphogen/automata/engine.py +211 -0
  26. morphogen/automata/growth.py +686 -0
  27. morphogen/automata/lattice.py +143 -0
  28. morphogen/automata/reaction.py +255 -0
  29. morphogen/automata/rules.py +353 -0
  30. morphogen/automata/tilings.py +1715 -0
  31. morphogen/cli.py +3526 -0
  32. morphogen/config.py +2167 -0
  33. morphogen/contact/__init__.py +113 -0
  34. morphogen/contact/experiments.py +368 -0
  35. morphogen/contact/hertz.py +104 -0
  36. morphogen/contact/kernels.py +827 -0
  37. morphogen/contact/periodic.py +278 -0
  38. morphogen/contact/problem.py +578 -0
  39. morphogen/contact/surfaces.py +310 -0
  40. morphogen/coupling/__init__.py +43 -0
  41. morphogen/coupling/ageing.py +143 -0
  42. morphogen/coupling/diffusion.py +226 -0
  43. morphogen/coupling/fenicsx.py +484 -0
  44. morphogen/coupling/oxidation.py +447 -0
  45. morphogen/coupling/plates.py +247 -0
  46. morphogen/design/__init__.py +51 -0
  47. morphogen/design/csp.py +616 -0
  48. morphogen/design/frames.py +277 -0
  49. morphogen/design/search.py +287 -0
  50. morphogen/design/tiles.py +336 -0
  51. morphogen/distributions.py +312 -0
  52. morphogen/domain.py +203 -0
  53. morphogen/dynamics/__init__.py +179 -0
  54. morphogen/dynamics/model.py +638 -0
  55. morphogen/dynamics/openradioss.py +643 -0
  56. morphogen/dynamics/results.py +515 -0
  57. morphogen/fracture/__init__.py +170 -0
  58. morphogen/fracture/bulk.py +349 -0
  59. morphogen/fracture/cohesive.py +1614 -0
  60. morphogen/fracture/ductile.py +557 -0
  61. morphogen/fracture/lefm.py +1168 -0
  62. morphogen/fracture/mixed.py +1178 -0
  63. morphogen/fracture/periodic.py +733 -0
  64. morphogen/fracture/phasefield.py +714 -0
  65. morphogen/fracture/phasefield_finite.py +368 -0
  66. morphogen/fracture/surface.py +572 -0
  67. morphogen/fracture/toughness.py +566 -0
  68. morphogen/gpu.py +108 -0
  69. morphogen/gui/__init__.py +8 -0
  70. morphogen/gui/api.py +1927 -0
  71. morphogen/gui/desktop.py +387 -0
  72. morphogen/gui/icon.png +0 -0
  73. morphogen/gui/index.html +1909 -0
  74. morphogen/gui/server.py +229 -0
  75. morphogen/gui/tools/__init__.py +629 -0
  76. morphogen/gui/tools/compare.py +149 -0
  77. morphogen/gui/tools/contact.py +391 -0
  78. morphogen/gui/tools/couplings.py +1085 -0
  79. morphogen/gui/tools/crackfront.py +245 -0
  80. morphogen/gui/tools/design.py +224 -0
  81. morphogen/gui/tools/dynamics.py +824 -0
  82. morphogen/gui/tools/fracture.py +2586 -0
  83. morphogen/gui/tools/interop.py +1654 -0
  84. morphogen/gui/tools/learning.py +595 -0
  85. morphogen/gui/tools/mechanics.py +3881 -0
  86. morphogen/gui/tools/nonlocal_damage.py +1321 -0
  87. morphogen/gui/tools/phasefield.py +215 -0
  88. morphogen/gui/tools/physics.py +597 -0
  89. morphogen/gui/tools/stability.py +1756 -0
  90. morphogen/gui/tools/statistics.py +1408 -0
  91. morphogen/gui/viewer.js +1100 -0
  92. morphogen/homogenization/__init__.py +210 -0
  93. morphogen/homogenization/acoustics.py +566 -0
  94. morphogen/homogenization/amg.py +1005 -0
  95. morphogen/homogenization/apparent.py +1046 -0
  96. morphogen/homogenization/behaviours.cu +2285 -0
  97. morphogen/homogenization/behaviours.py +944 -0
  98. morphogen/homogenization/beremin.py +263 -0
  99. morphogen/homogenization/bifurcation.py +1085 -0
  100. morphogen/homogenization/bloch.py +507 -0
  101. morphogen/homogenization/bounds.py +226 -0
  102. morphogen/homogenization/core.py +458 -0
  103. morphogen/homogenization/coupled.py +1135 -0
  104. morphogen/homogenization/crystal.py +2967 -0
  105. morphogen/homogenization/dilatation.py +454 -0
  106. morphogen/homogenization/elements.py +157 -0
  107. morphogen/homogenization/fatigue.py +768 -0
  108. morphogen/homogenization/fe.py +1739 -0
  109. morphogen/homogenization/fenicsx.py +307 -0
  110. morphogen/homogenization/fft.py +499 -0
  111. morphogen/homogenization/fft_nonlinear.py +391 -0
  112. morphogen/homogenization/finite.py +613 -0
  113. morphogen/homogenization/flow.py +361 -0
  114. morphogen/homogenization/frames.py +1125 -0
  115. morphogen/homogenization/gpu.py +1241 -0
  116. morphogen/homogenization/harmonic.py +427 -0
  117. morphogen/homogenization/identification.py +579 -0
  118. morphogen/homogenization/kernels.py +760 -0
  119. morphogen/homogenization/laws.py +2061 -0
  120. morphogen/homogenization/materials.py +1080 -0
  121. morphogen/homogenization/mfront.py +589 -0
  122. morphogen/homogenization/networks.py +880 -0
  123. morphogen/homogenization/nonlinear.py +2612 -0
  124. morphogen/homogenization/ntfa.py +577 -0
  125. morphogen/homogenization/paths.py +476 -0
  126. morphogen/homogenization/photonic.py +467 -0
  127. morphogen/homogenization/poroelastic.py +212 -0
  128. morphogen/homogenization/porous.py +1120 -0
  129. morphogen/homogenization/postprocess.py +290 -0
  130. morphogen/homogenization/solvers.py +1140 -0
  131. morphogen/homogenization/tensors.py +240 -0
  132. morphogen/homogenization/voxel_fe.py +457 -0
  133. morphogen/homogenization/xfem.py +1016 -0
  134. morphogen/homogenization/zmat.py +1258 -0
  135. morphogen/iga/__init__.py +48 -0
  136. morphogen/iga/analysis.py +508 -0
  137. morphogen/iga/basis.py +214 -0
  138. morphogen/iga/geometry.py +501 -0
  139. morphogen/iga/homogenization.py +219 -0
  140. morphogen/iga/optimization.py +700 -0
  141. morphogen/iga/shapes.py +331 -0
  142. morphogen/image.py +128 -0
  143. morphogen/io/__init__.py +246 -0
  144. morphogen/io/amitex.py +741 -0
  145. morphogen/io/ebsd.py +881 -0
  146. morphogen/io/export.py +196 -0
  147. morphogen/io/geometry.py +158 -0
  148. morphogen/io/medit.py +147 -0
  149. morphogen/io/meshes.py +844 -0
  150. morphogen/io/metaimage.py +97 -0
  151. morphogen/io/mfront.py +1104 -0
  152. morphogen/io/native.py +57 -0
  153. morphogen/io/radioss.py +764 -0
  154. morphogen/io/solvers.py +371 -0
  155. morphogen/io/tables.py +278 -0
  156. morphogen/io/tiff.py +66 -0
  157. morphogen/io/vtk.py +701 -0
  158. morphogen/io/xdmf.py +200 -0
  159. morphogen/kernels/__init__.py +5 -0
  160. morphogen/kernels/annealing.py +192 -0
  161. morphogen/kernels/cells.py +69 -0
  162. morphogen/kernels/collective.py +87 -0
  163. morphogen/kernels/force_biased.py +595 -0
  164. morphogen/kernels/implicit.py +145 -0
  165. morphogen/kernels/leaves.py +132 -0
  166. morphogen/kernels/packing.py +304 -0
  167. morphogen/kernels/raster.py +279 -0
  168. morphogen/kernels/rsa.py +371 -0
  169. morphogen/kernels/union.py +135 -0
  170. morphogen/kernels/watershed.py +190 -0
  171. morphogen/laser/__init__.py +234 -0
  172. morphogen/laser/architectures.py +375 -0
  173. morphogen/laser/bending.py +216 -0
  174. morphogen/laser/cells.py +1694 -0
  175. morphogen/laser/design.py +940 -0
  176. morphogen/laser/figures.py +227 -0
  177. morphogen/laser/heat.py +804 -0
  178. morphogen/laser/materials.py +691 -0
  179. morphogen/laser/mechanics.py +1670 -0
  180. morphogen/laser/metallurgy.py +615 -0
  181. morphogen/laser/patterns.py +828 -0
  182. morphogen/laser/periodic.py +392 -0
  183. morphogen/laser/process.py +362 -0
  184. morphogen/laser/run.py +534 -0
  185. morphogen/laser/solid.py +216 -0
  186. morphogen/laser/specimen.py +200 -0
  187. morphogen/laser/structures.py +708 -0
  188. morphogen/learning/__init__.py +81 -0
  189. morphogen/learning/behaviour.py +398 -0
  190. morphogen/learning/data.py +328 -0
  191. morphogen/learning/learned.cpp +668 -0
  192. morphogen/learning/logarithmic.py +202 -0
  193. morphogen/learning/mfront.py +409 -0
  194. morphogen/learning/networks.py +767 -0
  195. morphogen/learning/run.py +212 -0
  196. morphogen/learning/standard.py +814 -0
  197. morphogen/learning/training.py +235 -0
  198. morphogen/mesh/__init__.py +29 -0
  199. morphogen/mesh/conforming.py +1423 -0
  200. morphogen/mesh/curved.py +600 -0
  201. morphogen/mesh/exact.py +1717 -0
  202. morphogen/mesh/octree.py +350 -0
  203. morphogen/mesh/polycrystal.py +1041 -0
  204. morphogen/mesh/polyhedra.py +677 -0
  205. morphogen/mesh/regularize.py +570 -0
  206. morphogen/mesh/surface.py +97 -0
  207. morphogen/mesh/tetra.py +512 -0
  208. morphogen/mesh/voxel.py +124 -0
  209. morphogen/micromorphic/__init__.py +31 -0
  210. morphogen/micromorphic/damage.py +359 -0
  211. morphogen/micromorphic/ductile.py +534 -0
  212. morphogen/micromorphic/finite.py +220 -0
  213. morphogen/micromorphic/microfoam.py +787 -0
  214. morphogen/micromorphic/space.py +341 -0
  215. morphogen/models/__init__.py +195 -0
  216. morphogen/models/affine.py +384 -0
  217. morphogen/models/automata.py +592 -0
  218. morphogen/models/base.py +500 -0
  219. morphogen/models/boolean.py +310 -0
  220. morphogen/models/bouligand.py +331 -0
  221. morphogen/models/branching.py +241 -0
  222. morphogen/models/combination.py +430 -0
  223. morphogen/models/deadleaves.py +766 -0
  224. morphogen/models/design.py +289 -0
  225. morphogen/models/ebsd.py +206 -0
  226. morphogen/models/fibers.py +1476 -0
  227. morphogen/models/foam.py +594 -0
  228. morphogen/models/gaussian.py +314 -0
  229. morphogen/models/growth.py +459 -0
  230. morphogen/models/hardcore.py +317 -0
  231. morphogen/models/hierarchical.py +269 -0
  232. morphogen/models/honeycomb.py +749 -0
  233. morphogen/models/implicit.py +177 -0
  234. morphogen/models/laminate.py +470 -0
  235. morphogen/models/lattice.py +351 -0
  236. morphogen/models/lattice_field.py +345 -0
  237. morphogen/models/levelset_foam.py +563 -0
  238. morphogen/models/nacre.py +411 -0
  239. morphogen/models/nested.py +924 -0
  240. morphogen/models/osteons.py +374 -0
  241. morphogen/models/pieces.py +167 -0
  242. morphogen/models/planar.py +126 -0
  243. morphogen/models/reconstruction.py +203 -0
  244. morphogen/models/scale_rich.py +1409 -0
  245. morphogen/models/scale_rich_3d.py +1616 -0
  246. morphogen/models/tessellation.py +735 -0
  247. morphogen/models/tiling_field.py +302 -0
  248. morphogen/models/tpms.py +197 -0
  249. morphogen/models/transparent.py +406 -0
  250. morphogen/models/union.py +141 -0
  251. morphogen/optimization/__init__.py +43 -0
  252. morphogen/optimization/cell.py +295 -0
  253. morphogen/optimization/filters.py +115 -0
  254. morphogen/optimization/mma.py +226 -0
  255. morphogen/optimization/run.py +219 -0
  256. morphogen/optimization/topology.py +632 -0
  257. morphogen/orientations.py +568 -0
  258. morphogen/parallel.py +599 -0
  259. morphogen/pipeline.py +978 -0
  260. morphogen/primitives.py +188 -0
  261. morphogen/results.py +564 -0
  262. morphogen/rve/__init__.py +73 -0
  263. morphogen/rve/report.py +627 -0
  264. morphogen/rve/scaling.py +363 -0
  265. morphogen/rve/study.py +1054 -0
  266. morphogen/rve/windows.py +345 -0
  267. morphogen/seeding.py +51 -0
  268. morphogen/settings.py +118 -0
  269. morphogen/stopping.py +48 -0
  270. morphogen/symmetry.py +384 -0
  271. morphogen/templates/activator_inhibitor.yaml +22 -0
  272. morphogen/templates/aggregation.yaml +23 -0
  273. morphogen/templates/boolean_cylinders.yaml +20 -0
  274. morphogen/templates/boolean_spheres.yaml +22 -0
  275. morphogen/templates/bouligand.yaml +28 -0
  276. morphogen/templates/cellular_automaton.yaml +25 -0
  277. morphogen/templates/coated_spheres.yaml +26 -0
  278. morphogen/templates/contact_fibers.yaml +27 -0
  279. morphogen/templates/cox_nanocomposite.yaml +22 -0
  280. morphogen/templates/cross_linked_fibers.yaml +26 -0
  281. morphogen/templates/curved_arcs.yaml +28 -0
  282. morphogen/templates/curved_fibers.yaml +24 -0
  283. morphogen/templates/dead_leaves.yaml +22 -0
  284. morphogen/templates/delaunay_network.yaml +22 -0
  285. morphogen/templates/dense_packing.yaml +22 -0
  286. morphogen/templates/diffusion.yaml +33 -0
  287. morphogen/templates/ebsd.yaml +34 -0
  288. morphogen/templates/ebsd_map.ctf +3087 -0
  289. morphogen/templates/fracture_composite.yaml +42 -0
  290. morphogen/templates/fracture_rubber.yaml +47 -0
  291. morphogen/templates/gaussian_excursion.yaml +17 -0
  292. morphogen/templates/graded_lattice.yaml +24 -0
  293. morphogen/templates/hardcore_fibers.yaml +22 -0
  294. morphogen/templates/hardcore_spheres.yaml +22 -0
  295. morphogen/templates/hierarchical_lattice.yaml +22 -0
  296. morphogen/templates/homogenization_acoustic_foam.yaml +36 -0
  297. morphogen/templates/homogenization_beremin.yaml +50 -0
  298. morphogen/templates/homogenization_cleavage.yaml +51 -0
  299. morphogen/templates/homogenization_cleavage_band.yaml +55 -0
  300. morphogen/templates/homogenization_contact.yaml +43 -0
  301. morphogen/templates/homogenization_crack_closure.yaml +49 -0
  302. morphogen/templates/homogenization_crystal_plasticity.yaml +50 -0
  303. morphogen/templates/homogenization_crystal_plasticity_fft.yaml +52 -0
  304. morphogen/templates/homogenization_crystallization.yaml +30 -0
  305. morphogen/templates/homogenization_debonding.yaml +43 -0
  306. morphogen/templates/homogenization_detwinning.yaml +58 -0
  307. morphogen/templates/homogenization_ductile_damage.yaml +47 -0
  308. morphogen/templates/homogenization_fatigue.yaml +40 -0
  309. morphogen/templates/homogenization_grain_fracture.yaml +56 -0
  310. morphogen/templates/homogenization_gyroid.yaml +30 -0
  311. morphogen/templates/homogenization_intergranular.yaml +43 -0
  312. morphogen/templates/homogenization_interphase.yaml +42 -0
  313. morphogen/templates/homogenization_mixed_loading.yaml +33 -0
  314. morphogen/templates/homogenization_ntfa.yaml +56 -0
  315. morphogen/templates/homogenization_piezoelectric.yaml +27 -0
  316. morphogen/templates/homogenization_polycrystal.yaml +30 -0
  317. morphogen/templates/homogenization_polycrystal_inclusions.yaml +30 -0
  318. morphogen/templates/homogenization_poroelastic.yaml +26 -0
  319. morphogen/templates/homogenization_rubber.yaml +40 -0
  320. morphogen/templates/homogenization_slip_cleavage.yaml +50 -0
  321. morphogen/templates/homogenization_spheres.yaml +31 -0
  322. morphogen/templates/homogenization_transport.yaml +29 -0
  323. morphogen/templates/homogenization_twinning.yaml +54 -0
  324. morphogen/templates/homogenization_viscoelastic.yaml +34 -0
  325. morphogen/templates/homogenization_viscoplastic.yaml +42 -0
  326. morphogen/templates/homogenization_voronoi.yaml +26 -0
  327. morphogen/templates/homogenization_xfem.yaml +23 -0
  328. morphogen/templates/hyperuniform_cells.yaml +24 -0
  329. morphogen/templates/laguerre.yaml +18 -0
  330. morphogen/templates/laser_bending.yaml +35 -0
  331. morphogen/templates/laser_cells.yaml +38 -0
  332. morphogen/templates/laser_corrugated.yaml +36 -0
  333. morphogen/templates/level_set_foam.yaml +29 -0
  334. morphogen/templates/menger_sponge.yaml +17 -0
  335. morphogen/templates/nacre.yaml +25 -0
  336. morphogen/templates/nucleation_growth.yaml +25 -0
  337. morphogen/templates/optimize_auxetic.yaml +29 -0
  338. morphogen/templates/optimize_auxetic_3d.yaml +27 -0
  339. morphogen/templates/optimize_bulk.yaml +23 -0
  340. morphogen/templates/optimize_conductivity.yaml +20 -0
  341. morphogen/templates/osteons.yaml +28 -0
  342. morphogen/templates/penetrable_spheres.yaml +21 -0
  343. morphogen/templates/poisson_fibers.yaml +21 -0
  344. morphogen/templates/random_laminate.yaml +26 -0
  345. morphogen/templates/random_lattice.yaml +27 -0
  346. morphogen/templates/random_walk_fibers.yaml +26 -0
  347. morphogen/templates/reaction_diffusion.yaml +22 -0
  348. morphogen/templates/reconstruction.yaml +22 -0
  349. morphogen/templates/rve_cellular_automaton.yaml +23 -0
  350. morphogen/templates/rve_crystal_plasticity_fft.yaml +51 -0
  351. morphogen/templates/rve_multiphysics.yaml +43 -0
  352. morphogen/templates/rve_poisson_fibers.yaml +22 -0
  353. morphogen/templates/rve_poisson_fibers_fe.yaml +33 -0
  354. morphogen/templates/rve_voronoi_windows.yaml +20 -0
  355. morphogen/templates/scale_rich_network.yaml +29 -0
  356. morphogen/templates/scale_rich_plates.yaml +30 -0
  357. morphogen/templates/sequential_dead_leaves.yaml +25 -0
  358. morphogen/templates/strut_lattice.yaml +21 -0
  359. morphogen/templates/tile_assembly.yaml +28 -0
  360. morphogen/templates/tpms.yaml +19 -0
  361. morphogen/templates/trabecular_bone.yaml +29 -0
  362. morphogen/templates/transparent_dead_leaves.yaml +23 -0
  363. morphogen/templates/vascular_tree.yaml +23 -0
  364. morphogen/templates/voronoi.yaml +20 -0
  365. morphogen/templates/wood.yaml +34 -0
  366. morphogen/templates/workflow.yaml +56 -0
  367. morphogen/texture.py +665 -0
  368. morphogen/theory.py +162 -0
  369. morphogen/viz/__init__.py +12 -0
  370. morphogen/viz/export.py +244 -0
  371. morphogen/viz/figures.py +707 -0
  372. morphogen/viz/png.py +148 -0
  373. morphogen/viz/sections.py +696 -0
  374. morphogen/viz/surfaces.py +1352 -0
  375. morphogen/viz/video.py +904 -0
  376. morphogen/viz/workflow.py +488 -0
  377. morphogen-1.0.0.dist-info/METADATA +2316 -0
  378. morphogen-1.0.0.dist-info/RECORD +381 -0
  379. morphogen-1.0.0.dist-info/WHEEL +4 -0
  380. morphogen-1.0.0.dist-info/entry_points.txt +5 -0
  381. morphogen-1.0.0.dist-info/licenses/LICENSE +674 -0
@@ -0,0 +1,804 @@
1
+ """Heat conduction of the laser treatment of a sheet: a moving beam on a plate.
2
+
3
+ Units: lengths in millimetres, times in seconds, temperatures in degrees Celsius, powers
4
+ in watts. The thermal properties are given in SI units, as in the handbooks
5
+ (W m⁻¹ K⁻¹, kg m⁻³, J kg⁻¹ K⁻¹, W m⁻² K⁻¹), and converted.
6
+
7
+ **The quasi-steady track** (:func:`moving_source`, :class:`TrackKernel`). A beam of
8
+ absorbed power ``P`` moves at speed ``v`` along ``x`` on a plate of thickness ``h`` with
9
+ constant properties (conductivity ``k``, volumetric heat ``ρc``, diffusivity
10
+ ``a = k/ρc``), on its upper face (``single``) or on both faces at once (``symmetric``:
11
+ two aligned beams, the double-laser platform of Wang et al. 2022). An instantaneous
12
+ source of energy ``dE`` on the upper face spreads as ``dE/ρc G(x, y; τ) Z(z; τ)
13
+ exp(−βτ)`` after a time ``τ``:
14
+
15
+ * in the plane, the beam profile convolved with the heat kernel: a Gaussian beam of
16
+ 1/e² radius ``w`` (standard deviation ``s0 = w/2``) gives
17
+ ``G = exp(−r²/(2 s²)) / (2π s²)``, ``s² = s0² + 2aτ`` (Cline & Anthony 1977, Eagar &
18
+ Tsai 1983); a rectangular top hat of half sizes ``bx``, ``by`` gives the product of
19
+ ``(erf((x + b)/√(4aτ)) − erf((x − b)/√(4aτ))) / (4b)``;
20
+ * through the thickness, the adiabatic faces reflect the source: images at ``z = 2mh``,
21
+ ``Z = Σ 2 exp(−(z − 2mh)²/(4aτ)) / √(4πaτ) = (1/h)(1 + 2 Σ exp(−n²π²aτ/h²)
22
+ cos(nπz/h))`` (the series where it converges faster); a beam on the lower face adds
23
+ ``Z(h − z)``;
24
+ * the faces lose heat by convection and linearized radiation, ``h_f (T − T0)`` each,
25
+ approximated by the uniform loss rate ``β = 2 h_f/(ρc h)`` of a thin plate.
26
+
27
+ In the frame of the beam (``ξ = x − vt``) the quasi-steady field is
28
+ ``T − T0 = P/ρc ∫₀^∞ G(ξ + vτ, y; τ) Z(z; τ) exp(−βτ) dτ``, integrated on a logarithmic
29
+ grid of ``τ``. Its limits are Rosenthal's (1946) solutions, checked in the tests: a point
30
+ source on a thick plate, ``T − T0 = P/(2πkR) exp(−v(R + ξ)/(2a))``
31
+ (:func:`rosenthal_point`), and a line source through a thin plate with surface losses,
32
+ ``T − T0 = P/(2πkh) exp(−vξ/(2a)) K0(r √(v²/(4a²) + β/a))`` (Rykalin;
33
+ :func:`rosenthal_line`). A point at the distance ``d`` of the axis of a long straight
34
+ track sees the thermal cycle ``T(t) = T(ξ = −vt, d, z)``: :class:`TrackKernel` tabulates
35
+ these cycles over ``d`` and the depths of the layers, from which the peak temperatures,
36
+ the widths of the zones that reach a temperature (hardened, melted) and the kinetic
37
+ integrals follow.
38
+
39
+ **The transient sheet** (:class:`TransientHeat`). Arbitrary paths, their sequence, the
40
+ heat left by the previous tracks and the edges of the blank: finite volumes on a grid of
41
+ the blank (cells through the thickness for a single beam, one for a thin sheet),
42
+ locally one-dimensional implicit steps (Yanenko's splitting: unconditionally stable,
43
+ tridiagonal solves along x, y and z; Numba), adiabatic edges, the beam deposited on the
44
+ faces as its profile averaged over the positions it takes during a step, the faces
45
+ cooled by ``h_f``. Each step can update a metallurgical state (:mod:`morphogen.laser.metallurgy`).
46
+ """
47
+
48
+ from __future__ import annotations
49
+
50
+ import math
51
+ from dataclasses import dataclass, field, replace
52
+
53
+ import numpy as np
54
+ from numba import njit, prange
55
+ from scipy.special import erf, k0
56
+
57
+ #: Stefan–Boltzmann constant (W m⁻² K⁻⁴).
58
+ STEFAN_BOLTZMANN = 5.670374419e-8
59
+ #: Beam profiles.
60
+ PROFILES = ("gaussian", "tophat")
61
+ #: Laser configurations: one beam on the upper face, or two aligned beams on both faces.
62
+ CONFIGURATIONS = ("single", "symmetric")
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class ThermalProperties:
67
+ """Thermal properties of the sheet, in SI units: conductivity (W m⁻¹ K⁻¹), density
68
+ (kg m⁻³), mean specific heat over the thermal cycle (J kg⁻¹ K⁻¹), convection
69
+ coefficient of each face (W m⁻² K⁻¹) and emissivity (radiation linearized about
70
+ ``radiation_temperature``, °C)."""
71
+
72
+ conductivity: float = 25.0
73
+ density: float = 7700.0
74
+ heat_capacity: float = 600.0
75
+ convection: float = 20.0
76
+ emissivity: float = 0.0
77
+ radiation_temperature: float = 800.0
78
+
79
+ def __post_init__(self):
80
+ for name in ("conductivity", "density", "heat_capacity"):
81
+ if not getattr(self, name) > 0:
82
+ raise ValueError(f"thermal properties: {name} must be positive")
83
+ if self.convection < 0 or not 0 <= self.emissivity <= 1:
84
+ raise ValueError("thermal properties: convection >= 0, emissivity in [0, 1]")
85
+
86
+ @property
87
+ def k(self) -> float:
88
+ """Conductivity in W mm⁻¹ K⁻¹."""
89
+ return self.conductivity * 1e-3
90
+
91
+ @property
92
+ def rho_c(self) -> float:
93
+ """Volumetric heat in J mm⁻³ K⁻¹."""
94
+ return self.density * self.heat_capacity * 1e-9
95
+
96
+ @property
97
+ def diffusivity(self) -> float:
98
+ """Thermal diffusivity in mm² s⁻¹."""
99
+ return self.k / self.rho_c
100
+
101
+ def film(self, ambient: float = 20.0) -> float:
102
+ """Heat transfer coefficient of a face in W mm⁻² K⁻¹: convection plus the
103
+ radiation ``εσ(T_r² + T0²)(T_r + T0)`` linearized about ``radiation_temperature``."""
104
+ t_r, t_0 = self.radiation_temperature + 273.15, ambient + 273.15
105
+ rad = self.emissivity * STEFAN_BOLTZMANN * (t_r**2 + t_0**2) * (t_r + t_0)
106
+ return (self.convection + rad) * 1e-6
107
+
108
+ def loss_rate(self, thickness: float, ambient: float = 20.0) -> float:
109
+ """Loss rate ``β = 2 h_f / (ρc h)`` (s⁻¹) of a plate cooled on both faces."""
110
+ return 2.0 * self.film(ambient) / (self.rho_c * float(thickness))
111
+
112
+ @classmethod
113
+ def from_config(cls, data) -> ThermalProperties:
114
+ if isinstance(data, ThermalProperties):
115
+ return data
116
+ return cls(**dict(data or {}))
117
+
118
+
119
+ @dataclass(frozen=True)
120
+ class Beam:
121
+ """A continuous laser beam: incident power per beam (W), speed (mm/s), radius (mm:
122
+ the 1/e² radius of a Gaussian beam, the half side of a top hat), absorptivity, and
123
+ for a rectangular top hat its half length along the motion (``length``, default the
124
+ radius)."""
125
+
126
+ power: float
127
+ speed: float
128
+ radius: float
129
+ absorptivity: float = 0.35
130
+ profile: str = "gaussian"
131
+ length: float | None = None
132
+
133
+ def __post_init__(self):
134
+ if self.profile not in PROFILES:
135
+ raise ValueError(f"beam profile: one of {PROFILES}")
136
+ if not (self.power >= 0 and self.speed > 0 and self.radius > 0):
137
+ raise ValueError("beam: power >= 0, speed > 0 and radius > 0")
138
+ if not 0 < self.absorptivity <= 1:
139
+ raise ValueError("beam: absorptivity in (0, 1]")
140
+ if self.length is not None and not self.length > 0:
141
+ raise ValueError("beam: length must be positive")
142
+
143
+ @property
144
+ def absorbed(self) -> float:
145
+ """Absorbed power (W) of one beam."""
146
+ return self.power * self.absorptivity
147
+
148
+ @property
149
+ def line_energy(self) -> float:
150
+ """Linear energy density ``P/v`` (J/mm), incident, of one beam."""
151
+ return self.power / self.speed
152
+
153
+ @property
154
+ def interaction_time(self) -> float:
155
+ """Time (s) the beam takes to pass over a point: its diameter over its speed."""
156
+ return 2.0 * (self.length or self.radius) / self.speed
157
+
158
+ def with_(self, **changes) -> Beam:
159
+ return replace(self, **changes)
160
+
161
+ @classmethod
162
+ def from_config(cls, data) -> Beam:
163
+ if isinstance(data, Beam):
164
+ return data
165
+ return cls(**dict(data))
166
+
167
+
168
+ # -- closed forms --------------------------------------------------------------------------
169
+
170
+
171
+ def rosenthal_point(
172
+ xi, y, z, power: float, speed: float, props: ThermalProperties, ambient: float = 20.0
173
+ ):
174
+ """Rosenthal's point source on the surface of a semi-infinite body (absorbed power
175
+ ``power``): ``T0 + P/(2πkR) exp(−v(R + ξ)/(2a))``, ``R`` the distance to the source."""
176
+ a, k = props.diffusivity, props.k
177
+ xi, y, z = (np.asarray(v, dtype=float) for v in (xi, y, z))
178
+ r = np.sqrt(xi * xi + y * y + z * z)
179
+ return ambient + power / (2.0 * math.pi * k * r) * np.exp(-speed * (r + xi) / (2.0 * a))
180
+
181
+
182
+ def rosenthal_line(
183
+ xi,
184
+ y,
185
+ power: float,
186
+ speed: float,
187
+ thickness: float,
188
+ props: ThermalProperties,
189
+ ambient: float = 20.0,
190
+ *,
191
+ losses: bool = True,
192
+ ):
193
+ """The line source through a thin plate (Rosenthal 1946; with the surface losses of
194
+ Rykalin): ``T0 + P/(2πkh) exp(−vξ/(2a)) K0(r √(v²/(4a²) + β/a))``."""
195
+ a, k, h = props.diffusivity, props.k, float(thickness)
196
+ beta = props.loss_rate(h, ambient) if losses else 0.0
197
+ xi, y = np.asarray(xi, dtype=float), np.asarray(y, dtype=float)
198
+ r = np.sqrt(xi * xi + y * y)
199
+ arg = r * math.sqrt(speed * speed / (4.0 * a * a) + beta / a)
200
+ return ambient + power / (2.0 * math.pi * k * h) * np.exp(-speed * xi / (2.0 * a)) * k0(arg)
201
+
202
+
203
+ # -- the quasi-steady field of a moving beam -----------------------------------------------
204
+
205
+
206
+ def _depth(z, tau, a: float, h: float):
207
+ """``Z(z; τ)`` of a source on the face ``z = 0`` of a plate ``0 <= z <= h`` with
208
+ adiabatic faces (1/mm): images for short times, the cosine series for long ones."""
209
+ u = a * tau / (h * h)
210
+ out = np.empty(np.broadcast(z, tau).shape)
211
+ short = np.broadcast_to(u < 0.2, out.shape)
212
+ zz, tt = np.broadcast_arrays(z, tau)
213
+ if short.any():
214
+ zs, ts = zz[short], tt[short]
215
+ s = np.zeros_like(zs)
216
+ four_at = 4.0 * a * ts
217
+ for m in range(-3, 4):
218
+ d = zs - 2.0 * m * h
219
+ s += np.exp(-d * d / four_at)
220
+ out[short] = 2.0 * s / np.sqrt(math.pi * four_at)
221
+ if (~short).any():
222
+ zl, ul = zz[~short], np.broadcast_to(u, out.shape)[~short]
223
+ s = np.ones_like(zl)
224
+ for n in range(1, 9):
225
+ s += 2.0 * np.exp(-((n * math.pi) ** 2) * ul) * np.cos(n * math.pi * zl / h)
226
+ out[~short] = s / h
227
+ return out
228
+
229
+
230
+ def _plane(x, y, tau, a: float, beam: Beam):
231
+ """``G(x, y; τ)`` (1/mm²): the beam profile spread by the heat kernel."""
232
+ if beam.profile == "gaussian":
233
+ s2 = 0.25 * beam.radius**2 + 2.0 * a * tau
234
+ return np.exp(-(x * x + y * y) / (2.0 * s2)) / (2.0 * math.pi * s2)
235
+ bx, by = beam.length or beam.radius, beam.radius
236
+ sq = np.sqrt(4.0 * a * tau)
237
+ gx = (erf((x + bx) / sq) - erf((x - bx) / sq)) / (4.0 * bx)
238
+ gy = (erf((y + by) / sq) - erf((y - by) / sq)) / (4.0 * by)
239
+ return gx * gy
240
+
241
+
242
+ def _tau_grid(beam: Beam, a: float, h: float, beta: float, reach: float, nodes: int):
243
+ """Logarithmic grid of the delays ``τ`` and its trapezoidal weights (in ``ln τ``)."""
244
+ v = beam.speed
245
+ s0 = max(0.5 * (beam.length or beam.radius), 1e-6)
246
+ lo = 1e-6 * min(s0 * s0, h * h) / a
247
+ hi = max(60.0 * 4.0 * a / (v * v), 4.0 * reach / v + 10.0 * s0 / v, 1e-3)
248
+ if beta > 0:
249
+ hi = min(hi, max(40.0 / beta, 4.0 * reach / v))
250
+ tau = np.geomspace(lo, hi, int(nodes))
251
+ ds = math.log(hi / lo) / (nodes - 1)
252
+ w = np.full(nodes, ds)
253
+ w[0] = w[-1] = 0.5 * ds
254
+ return tau, w * tau
255
+
256
+
257
+ def _beams(beam: Beam, bottom, configuration: str):
258
+ """The beams on the upper and lower faces: ``bottom`` if given, else the same beam
259
+ for the ``symmetric`` configuration, none for ``single``."""
260
+ if configuration not in CONFIGURATIONS:
261
+ raise ValueError(f"configuration: one of {CONFIGURATIONS}")
262
+ if bottom is None and configuration == "symmetric":
263
+ bottom = beam
264
+ if bottom is not None and not math.isclose(bottom.speed, beam.speed):
265
+ raise ValueError("the beams of both faces move together: the same speed")
266
+ return beam, bottom
267
+
268
+
269
+ def moving_source(
270
+ xi,
271
+ y,
272
+ z,
273
+ beam: Beam,
274
+ thickness: float,
275
+ props: ThermalProperties,
276
+ *,
277
+ bottom: Beam | None = None,
278
+ configuration: str = "single",
279
+ ambient: float = 20.0,
280
+ nodes: int = 1600,
281
+ chunk: int = 4096,
282
+ ):
283
+ """Quasi-steady temperature (°C) at the points ``(ξ, y, z)`` (mm) in the frame of a
284
+ beam moving along +x on a plate of thickness ``thickness``, its upper face at
285
+ ``z = 0``: one beam on the upper face (``single``), the same beam on both faces
286
+ (``symmetric``), or ``bottom``, another beam aligned with it on the lower face (a
287
+ fibre laser above and a diode below, say)."""
288
+ top, bottom = _beams(beam, bottom, configuration)
289
+ h = float(thickness)
290
+ if not h > 0:
291
+ raise ValueError("thickness must be positive")
292
+ xi, y, z = np.broadcast_arrays(*(np.asarray(v, dtype=float) for v in (xi, y, z)))
293
+ shape = xi.shape
294
+ xi, y, z = xi.ravel(), y.ravel(), z.ravel()
295
+ a = props.diffusivity
296
+ beta = props.loss_rate(h, ambient)
297
+ reach = float(np.max(np.abs(xi))) if xi.size else 0.0
298
+ narrow = top if bottom is None else min((top, bottom), key=lambda b: b.radius)
299
+ tau, w = _tau_grid(narrow, a, h, beta, reach, nodes)
300
+ # the depth factor depends on z and tau only: once per depth
301
+ zu, zi = np.unique(z, return_inverse=True)
302
+ damp = (w * np.exp(-beta * tau))[None, :]
303
+ faces = [(top, _depth(zu[:, None], tau[None, :], a, h) * damp)]
304
+ if bottom is not None:
305
+ zb = _depth(h - zu[:, None], tau[None, :], a, h) * damp
306
+ same = (
307
+ bottom.profile == top.profile
308
+ and bottom.radius == top.radius
309
+ and (bottom.length == top.length)
310
+ )
311
+ if same: # one plane kernel: the powers weight the depth factors
312
+ faces = [(top, faces[0][1] + zb * (bottom.absorbed / max(top.absorbed, 1e-300)))]
313
+ if top.absorbed == 0:
314
+ faces = [(bottom, zb)]
315
+ else:
316
+ faces.append((bottom, zb))
317
+ out = np.zeros(xi.size)
318
+ v = top.speed
319
+ for b, ztab in faces:
320
+ part = np.empty(xi.size)
321
+ for start in range(0, xi.size, chunk):
322
+ sl = slice(start, start + chunk)
323
+ g = _plane(xi[sl, None] + v * tau[None, :], y[sl, None], tau[None, :], a, b)
324
+ part[sl] = np.einsum("ij,ij->i", g, ztab[zi[sl]])
325
+ out += b.absorbed * part
326
+ return (ambient + out / props.rho_c).reshape(shape)
327
+
328
+
329
+ def moving_source_grid(
330
+ xi,
331
+ y,
332
+ z,
333
+ beam: Beam,
334
+ thickness: float,
335
+ props: ThermalProperties,
336
+ *,
337
+ bottom: Beam | None = None,
338
+ configuration: str = "single",
339
+ ambient: float = 20.0,
340
+ nodes: int = 1600,
341
+ ) -> np.ndarray:
342
+ """:func:`moving_source` on the grid ``xi x y x z`` (1D arrays), shape
343
+ ``(len(xi), len(y), len(z))``: the plane kernel is separable, so that the integral
344
+ over the delays is a product of matrices for each depth (no exponential per point)."""
345
+ top, bottom = _beams(beam, bottom, configuration)
346
+ h = float(thickness)
347
+ if not h > 0:
348
+ raise ValueError("thickness must be positive")
349
+ xi, y, z = (np.atleast_1d(np.asarray(v, dtype=float)) for v in (xi, y, z))
350
+ a = props.diffusivity
351
+ beta = props.loss_rate(h, ambient)
352
+ reach = float(np.max(np.abs(xi))) if xi.size else 0.0
353
+ narrow = top if bottom is None else min((top, bottom), key=lambda b: b.radius)
354
+ tau, w = _tau_grid(narrow, a, h, beta, reach, nodes)
355
+ damp = w * np.exp(-beta * tau)
356
+ out = np.zeros((xi.size, y.size, z.size))
357
+ v = top.speed
358
+ for b, zz in ((top, z), (bottom, h - z)):
359
+ if b is None or b.absorbed == 0:
360
+ continue
361
+ ztab = _depth(zz[:, None], tau[None, :], a, h) * damp[None, :]
362
+ gx, gy = _plane_factors_moving(xi, y, tau, v, a, b)
363
+ for k in range(z.size):
364
+ out[:, :, k] += b.absorbed * ((gx * ztab[k][None, :]) @ gy.T)
365
+ return ambient + out / props.rho_c
366
+
367
+
368
+ def _plane_factors_moving(xi, y, tau, v: float, a: float, beam: Beam):
369
+ """``gx(ξ + vτ; τ)`` (len(xi) x len(tau)) and ``gy(y; τ)`` (len(y) x len(tau))."""
370
+ x = xi[:, None] + v * tau[None, :]
371
+ if beam.profile == "gaussian":
372
+ s2 = 0.25 * beam.radius**2 + 2.0 * a * tau[None, :]
373
+ gx = np.exp(-(x * x) / (2.0 * s2)) / (2.0 * math.pi * s2)
374
+ gy = np.exp(-(y[:, None] ** 2) / (2.0 * s2))
375
+ return gx, gy
376
+ bx, by = beam.length or beam.radius, beam.radius
377
+ sq = np.sqrt(4.0 * a * tau)[None, :]
378
+ gx = (erf((x + bx) / sq) - erf((x - bx) / sq)) / (4.0 * bx)
379
+ gy = (erf((y[:, None] + by) / sq) - erf((y[:, None] - by) / sq)) / (4.0 * by)
380
+ return gx, gy
381
+
382
+
383
+ @dataclass
384
+ class TrackKernel:
385
+ """The thermal cycles that a long straight track imposes on the points of the sheet:
386
+ ``temperature[i, j, k]`` at the distance ``distances[i]`` (mm) of its axis, the time
387
+ ``times[j]`` (s; 0 when the beam passes the point's abscissa) and the depth
388
+ ``depths[k]`` (mm, the middles of the layers), with their peaks; ``bottom`` is the
389
+ beam of the lower face, if any."""
390
+
391
+ beam: Beam
392
+ bottom: Beam | None
393
+ thickness: float
394
+ ambient: float
395
+ distances: np.ndarray
396
+ depths: np.ndarray
397
+ times: np.ndarray
398
+ temperature: np.ndarray
399
+ peak: np.ndarray = field(init=False)
400
+
401
+ def __post_init__(self):
402
+ self.peak = self.temperature.max(axis=1)
403
+
404
+ @property
405
+ def layers(self) -> int:
406
+ return len(self.depths)
407
+
408
+ @property
409
+ def reach(self) -> float:
410
+ """The largest distance tabulated: beyond it the track leaves the sheet as it is."""
411
+ return float(self.distances[-1])
412
+
413
+ @property
414
+ def configuration(self) -> str:
415
+ return "single" if self.bottom is None else "symmetric"
416
+
417
+ def peak_at(self, distance, layer: int | None = None) -> np.ndarray:
418
+ """Peak temperature at distances from the axis (``(..., layers)``, or one layer)."""
419
+ d = np.abs(np.asarray(distance, dtype=float))
420
+ cols = range(self.layers) if layer is None else [int(layer)]
421
+ out = np.stack(
422
+ [np.interp(d, self.distances, self.peak[:, k], right=self.ambient) for k in cols],
423
+ axis=-1,
424
+ )
425
+ return out if layer is None else out[..., 0]
426
+
427
+ def width(self, temperature: float, layer: int | None = None) -> float:
428
+ """Width (mm) of the band whose peak temperature reaches ``temperature`` (in one
429
+ layer, or in any)."""
430
+ peak = self.peak.max(axis=1) if layer is None else self.peak[:, int(layer)]
431
+ above = peak >= temperature
432
+ if not above[0]:
433
+ return 0.0
434
+ if above.all():
435
+ return 2.0 * self.reach
436
+ i = int(np.argmin(above)) # the first distance below
437
+ d0, d1, t0, t1 = self.distances[i - 1], self.distances[i], peak[i - 1], peak[i]
438
+ return 2.0 * float(d0 + (t0 - temperature) / (t0 - t1) * (d1 - d0))
439
+
440
+ def through_width(self, temperature: float) -> float:
441
+ """Width (mm) of the band whose peak temperature reaches ``temperature`` in every
442
+ layer: treated through the whole thickness."""
443
+ return (
444
+ self.width(temperature, None)
445
+ if self.layers == 1
446
+ else min(self.width(temperature, k) for k in range(self.layers))
447
+ )
448
+
449
+ def cycles(self, distance) -> np.ndarray:
450
+ """Thermal cycles at distances from the axis: ``(points, times, layers)``,
451
+ interpolated linearly between the tabulated distances (ambient beyond)."""
452
+ d = np.abs(np.asarray(distance, dtype=float)).ravel()
453
+ x = np.clip(d, 0.0, self.reach)
454
+ i = np.clip(
455
+ np.searchsorted(self.distances, x, side="right") - 1, 0, len(self.distances) - 2
456
+ )
457
+ d0, d1 = self.distances[i], self.distances[i + 1]
458
+ f = ((x - d0) / (d1 - d0))[:, None, None]
459
+ out = (1.0 - f) * self.temperature[i] + f * self.temperature[i + 1]
460
+ out[d > self.reach] = self.ambient
461
+ return out
462
+
463
+ def kinetic_integral(self, activation: float, distance=0.0) -> np.ndarray:
464
+ """``∫ exp(−Q/(R T(t))) dt`` (s) of the cycles at distances, ``Q`` in J/mol (per
465
+ layer): the effective time of a thermally activated process; e.g. the diffusion
466
+ length of a species of diffusivity ``D0 exp(−Q/RT)`` is ``√(D0 × it)``."""
467
+ cyc = self.cycles(distance) + 273.15
468
+ f = np.exp(-float(activation) / (8.314462618 * cyc))
469
+ return np.trapezoid(f, self.times, axis=1)
470
+
471
+ def cooling_time(self, distance=0.0, upper: float = 800.0, lower: float = 500.0) -> np.ndarray:
472
+ """Time (s) to cool from ``upper`` to ``lower`` (°C) after the peak, ``t8/5`` by
473
+ default (NaN where the peak stays below ``upper``)."""
474
+ cyc = self.cycles(distance)
475
+ out = np.full(cyc.shape[::2], np.nan)
476
+ for p in range(cyc.shape[0]):
477
+ for k in range(cyc.shape[2]):
478
+ c = cyc[p, :, k]
479
+ j = int(np.argmax(c))
480
+ if c[j] < upper:
481
+ continue
482
+ tail, tt = c[j:], self.times[j:]
483
+ if tail[-1] > lower:
484
+ continue
485
+ t_up = np.interp(-upper, -tail, tt)
486
+ t_lo = np.interp(-lower, -tail, tt)
487
+ out[p, k] = t_lo - t_up
488
+ return out
489
+
490
+
491
+ def track_kernel(
492
+ beam: Beam,
493
+ thickness: float,
494
+ props: ThermalProperties,
495
+ *,
496
+ bottom: Beam | None = None,
497
+ configuration: str = "single",
498
+ layers: int = 1,
499
+ ambient: float = 20.0,
500
+ cutoff: float | None = None,
501
+ distances: int = 48,
502
+ times: int = 240,
503
+ nodes: int = 1200,
504
+ max_reach: float | None = None,
505
+ ) -> TrackKernel:
506
+ """Tabulate the thermal cycles of a long straight track (see :class:`TrackKernel`):
507
+ the distances up to where the peak falls to ``cutoff`` (°C; default: a tenth of the
508
+ peak rise above ambient, at least 100 °C above it; at most ``max_reach`` mm), the
509
+ times from ahead of the beam to a tail of cooling, ``layers`` layers through the
510
+ thickness. The beams: as in :func:`moving_source`."""
511
+ top, bottom = _beams(beam, bottom, configuration)
512
+ if layers < 1:
513
+ raise ValueError("layers: at least one")
514
+ h = float(thickness)
515
+ a = props.diffusivity
516
+ big = top if bottom is None else max((top, bottom), key=lambda b: b.length or b.radius)
517
+ s0 = 0.5 * (big.length or big.radius)
518
+ depths = (np.arange(layers) + 0.5) * h / layers
519
+ max_reach = float(max_reach) if max_reach is not None else max(30.0 * s0, 10.0 * h)
520
+ kw = {"bottom": bottom, "ambient": ambient, "nodes": nodes}
521
+
522
+ # where is the peak behind the beam, how far does the heat reach: a coarse look first
523
+ far = max(4.0 * max_reach, 40.0 * s0)
524
+ xs = np.concatenate(
525
+ [np.linspace(3.0 * s0, 0.0, 12, endpoint=False), -np.geomspace(1e-3 * far, far, 40)]
526
+ )
527
+ coarse_d = np.concatenate([[0.0], np.geomspace(0.05 * s0, max_reach, 30)])
528
+ pk = moving_source_grid(xs, coarse_d, depths, top, h, props, **kw).max(axis=0).max(axis=1)
529
+ rise = pk[0] - ambient
530
+ if cutoff is None:
531
+ cutoff = ambient + max(0.1 * rise, 100.0)
532
+ if pk[-1] >= cutoff:
533
+ reach = max_reach
534
+ else:
535
+ reach = float(coarse_d[int(np.argmax(pk < cutoff))])
536
+ reach = max(reach, 2.0 * s0)
537
+ knee = min(reach, 3.0 * s0)
538
+ dist = np.unique(
539
+ np.concatenate(
540
+ [
541
+ np.linspace(0.0, knee, max(2, distances // 2)),
542
+ np.linspace(knee, reach, max(2, distances - distances // 2)),
543
+ ]
544
+ )
545
+ )
546
+ # times: dense around the passage, geometric afterwards (the slow tail of thin plates)
547
+ t_int = 2.0 * s0 * 2.0 / top.speed
548
+ t_ahead = 3.0 * t_int
549
+ t_tail = max(40.0 * t_int, 4.0 * reach / top.speed + 4.0 * h * h / a)
550
+ dense = np.linspace(-t_ahead, 4.0 * t_int, times // 2)
551
+ tail = np.geomspace(4.0 * t_int, t_tail, times - times // 2 + 1)[1:]
552
+ tt = np.concatenate([dense, tail])
553
+ temp = moving_source_grid(-top.speed * tt, dist, depths, top, h, props, **kw)
554
+ temp = np.ascontiguousarray(np.transpose(temp, (1, 0, 2))) # distances x times x layers
555
+ return TrackKernel(top, bottom, h, float(ambient), dist, depths, tt, temp)
556
+
557
+
558
+ # -- transient finite volumes --------------------------------------------------------------
559
+
560
+
561
+ @njit(cache=True)
562
+ def _thomas(lower, diag, upper, rhs, n): # pragma: no cover - compiled
563
+ """Tridiagonal solve in place (rhs holds the solution)."""
564
+ c = np.empty(n)
565
+ c[0] = upper[0] / diag[0]
566
+ rhs[0] = rhs[0] / diag[0]
567
+ for i in range(1, n):
568
+ m = diag[i] - lower[i] * c[i - 1]
569
+ c[i] = upper[i] / m
570
+ rhs[i] = (rhs[i] - lower[i] * rhs[i - 1]) / m
571
+ for i in range(n - 2, -1, -1):
572
+ rhs[i] -= c[i] * rhs[i + 1]
573
+
574
+
575
+ @njit(parallel=True, cache=True)
576
+ def _sweep(t, axis, r, loss, ambient): # pragma: no cover - compiled
577
+ """Implicit 1D diffusion along ``axis`` of every line of ``t`` (nx, ny, nz), Neumann
578
+ ends; ``loss`` (along z only) adds the cooling of the two outer faces."""
579
+ nx, ny, nz = t.shape
580
+ n = t.shape[axis]
581
+ if axis == 0:
582
+ m1, m2 = ny, nz
583
+ elif axis == 1:
584
+ m1, m2 = nx, nz
585
+ else:
586
+ m1, m2 = nx, ny
587
+ for idx in prange(m1 * m2):
588
+ p, q = idx // m2, idx % m2
589
+ lower = np.full(n, -r)
590
+ upper = np.full(n, -r)
591
+ diag = np.full(n, 1.0 + 2.0 * r)
592
+ rhs = np.empty(n)
593
+ for i in range(n):
594
+ if axis == 0:
595
+ rhs[i] = t[i, p, q]
596
+ elif axis == 1:
597
+ rhs[i] = t[p, i, q]
598
+ else:
599
+ rhs[i] = t[p, q, i]
600
+ lower[0] = 0.0
601
+ upper[n - 1] = 0.0
602
+ diag[0] -= r
603
+ diag[n - 1] -= r
604
+ if loss > 0.0:
605
+ diag[0] += loss
606
+ rhs[0] += loss * ambient
607
+ diag[n - 1] += loss
608
+ rhs[n - 1] += loss * ambient
609
+ _thomas(lower, diag, upper, rhs, n)
610
+ for i in range(n):
611
+ if axis == 0:
612
+ t[i, p, q] = rhs[i]
613
+ elif axis == 1:
614
+ t[p, i, q] = rhs[i]
615
+ else:
616
+ t[p, q, i] = rhs[i]
617
+
618
+
619
+ @dataclass
620
+ class TransientResult:
621
+ """Fields of a transient run: the final and peak temperatures (nx, ny, nz), the
622
+ time of the end of the run, and the metallurgical state when a model was given."""
623
+
624
+ temperature: np.ndarray
625
+ peak: np.ndarray
626
+ time: float
627
+ steps: int
628
+ state: dict | None = None
629
+
630
+
631
+ class TransientHeat:
632
+ """Finite volumes on a blank ``[x0, x0 + lx] x [y0, y0 + ly]`` of thickness
633
+ ``thickness``: ``cell`` in the plane (mm), ``layers`` cells through the thickness
634
+ (1 for a thin sheet treated on both faces)."""
635
+
636
+ def __init__(
637
+ self,
638
+ size,
639
+ thickness: float,
640
+ props: ThermalProperties,
641
+ *,
642
+ cell: float,
643
+ layers: int = 1,
644
+ origin=(0.0, 0.0),
645
+ ambient: float = 20.0,
646
+ ):
647
+ self.size = (float(size[0]), float(size[1]))
648
+ self.origin = (float(origin[0]), float(origin[1]))
649
+ self.thickness = float(thickness)
650
+ self.props = props
651
+ self.ambient = float(ambient)
652
+ self.nx = max(1, round(self.size[0] / cell))
653
+ self.ny = max(1, round(self.size[1] / cell))
654
+ self.nz = int(layers)
655
+ self.dx, self.dy = self.size[0] / self.nx, self.size[1] / self.ny
656
+ self.dz = self.thickness / self.nz
657
+ self.x = self.origin[0] + (np.arange(self.nx) + 0.5) * self.dx
658
+ self.y = self.origin[1] + (np.arange(self.ny) + 0.5) * self.dy
659
+ self.z = (np.arange(self.nz) + 0.5) * self.dz
660
+
661
+ @property
662
+ def shape(self) -> tuple[int, int, int]:
663
+ return (self.nx, self.ny, self.nz)
664
+
665
+ def _flux(self, beam: Beam, centres) -> np.ndarray:
666
+ """Absorbed flux (W/mm²) of the cells of a face, averaged over beam centres. Each
667
+ centre's profile is sampled at the cell centres of a window that may overhang the
668
+ blank, normalized to unit energy over the window (the discrete profile of a
669
+ coarse grid keeps the power), then cut by the blank: the part of the beam that
670
+ falls off the sheet is lost."""
671
+ q = np.zeros((self.nx, self.ny))
672
+ if beam.profile == "gaussian":
673
+ reach = 1.6 * beam.radius + 2.0 * max(self.dx, self.dy)
674
+ else:
675
+ reach = math.hypot(beam.length or beam.radius, beam.radius) + 2.0 * max(
676
+ self.dx, self.dy
677
+ )
678
+ x0, y0 = self.origin
679
+ for cx, cy, ux, uy in centres:
680
+ ia = math.floor((cx - reach - x0) / self.dx)
681
+ ib = math.ceil((cx + reach - x0) / self.dx) + 1
682
+ ja = math.floor((cy - reach - y0) / self.dy)
683
+ jb = math.ceil((cy + reach - y0) / self.dy) + 1
684
+ gx, gy = np.meshgrid(
685
+ x0 + (np.arange(ia, ib) + 0.5) * self.dx - cx,
686
+ y0 + (np.arange(ja, jb) + 0.5) * self.dy - cy,
687
+ indexing="ij",
688
+ )
689
+ if beam.profile == "gaussian":
690
+ w = beam.radius
691
+ prof = np.exp(-2.0 * (gx * gx + gy * gy) / (w * w))
692
+ else:
693
+ along = np.abs(gx * ux + gy * uy)
694
+ across = np.abs(-gx * uy + gy * ux)
695
+ prof = ((along <= (beam.length or beam.radius)) & (across <= beam.radius)).astype(
696
+ float
697
+ )
698
+ total = prof.sum() * self.dx * self.dy
699
+ if total <= 0: # a top hat narrower than the cells: its nearest cell
700
+ prof[np.unravel_index(np.argmin(gx * gx + gy * gy), prof.shape)] = 1.0
701
+ total = self.dx * self.dy
702
+ prof /= total
703
+ i0, i1 = max(ia, 0), min(ib, self.nx)
704
+ j0, j1 = max(ja, 0), min(jb, self.ny)
705
+ if i0 < i1 and j0 < j1:
706
+ q[i0:i1, j0:j1] += prof[i0 - ia : i1 - ia, j0 - ja : j1 - ja]
707
+ return q * (beam.absorbed / max(len(centres), 1))
708
+
709
+ def run(
710
+ self,
711
+ segments,
712
+ *,
713
+ configuration: str = "single",
714
+ model=None,
715
+ state=None,
716
+ dt_max: float = 0.5,
717
+ cooling: float | None = None,
718
+ substeps: int = 4,
719
+ callback=None,
720
+ ) -> TransientResult:
721
+ """Run a sequence of laser moves. ``segments``: iterable of
722
+ ``(points, beam, bottom, pause)``: a polyline (n x 2, mm) followed at the speed of
723
+ ``beam`` (upper face) with ``bottom`` on the lower face (None: none, or the same
724
+ beam in the ``symmetric`` configuration), then ``pause`` seconds with the lasers
725
+ off (the move to the next track). ``model``: a metallurgical model updated at each
726
+ step (its ``state`` returned). ``cooling``: after the last segment, cool until the
727
+ hottest cell falls below this temperature (°C)."""
728
+ if configuration not in CONFIGURATIONS:
729
+ raise ValueError(f"configuration: one of {CONFIGURATIONS}")
730
+ a = self.props.diffusivity
731
+ film = self.props.film(self.ambient)
732
+ rho_c = self.props.rho_c
733
+ t = np.full(self.shape, self.ambient)
734
+ peak = t.copy()
735
+ if model is not None and state is None:
736
+ state = model.initial_state(t.size)
737
+ time, steps = 0.0, 0
738
+ cell = min(self.dx, self.dy)
739
+
740
+ def advance(dt, flux_top, flux_bottom):
741
+ nonlocal time, steps
742
+ old = t.copy()
743
+ depth_top = self.thickness if self.nz == 1 else self.dz
744
+ if flux_top is not None:
745
+ t[:, :, 0] += flux_top * dt / (rho_c * depth_top)
746
+ if flux_bottom is not None:
747
+ t[:, :, -1] += flux_bottom * dt / (rho_c * depth_top)
748
+ if self.nx > 1:
749
+ _sweep(t, 0, a * dt / self.dx**2, 0.0, self.ambient)
750
+ if self.ny > 1:
751
+ _sweep(t, 1, a * dt / self.dy**2, 0.0, self.ambient)
752
+ rz = a * dt / self.dz**2 if self.nz > 1 else 0.0
753
+ _sweep(t, 2, rz, film * dt / (rho_c * depth_top), self.ambient)
754
+ np.maximum(peak, t, out=peak)
755
+ if model is not None:
756
+ model.step(state, old.reshape(-1), t.reshape(-1), dt)
757
+ time += dt
758
+ steps += 1
759
+ if callback is not None:
760
+ callback(time, t)
761
+
762
+ for points, beam, bottom, pause in segments:
763
+ top, low = _beams(beam, bottom, configuration)
764
+ pts = np.asarray(points, dtype=float).reshape(-1, 2)
765
+ seg = np.diff(pts, axis=0)
766
+ lengths = np.hypot(seg[:, 0], seg[:, 1])
767
+ total = float(lengths.sum())
768
+ if total > 0:
769
+ cum = np.concatenate([[0.0], np.cumsum(lengths)])
770
+ ds = min(0.5 * cell, 0.5 * top.radius)
771
+ n = max(1, math.ceil(total / ds))
772
+ dt = total / top.speed / n
773
+ for s in range(n):
774
+ arc = (s + (np.arange(substeps) + 0.5) / substeps) * total / n
775
+ centres = []
776
+ for u in arc:
777
+ k = min(int(np.searchsorted(cum, u, side="right")) - 1, len(lengths) - 1)
778
+ f = (u - cum[k]) / max(lengths[k], 1e-300)
779
+ c = pts[k] + f * seg[k]
780
+ d = seg[k] / max(lengths[k], 1e-300)
781
+ centres.append((c[0], c[1], d[0], d[1]))
782
+ q_top = self._flux(top, centres) if top.absorbed > 0 else None
783
+ q_bot = self._flux(low, centres) if low is not None else None
784
+ advance(dt, q_top, q_bot)
785
+ self._cool(advance, float(pause or 0.0), dt_max)
786
+ if cooling is not None:
787
+ span = 0.0
788
+ while t.max() > cooling and span < 600.0:
789
+ dt = min(dt_max, max(1e-3, 0.05 * max(span, 0.02)))
790
+ advance(dt, None, None)
791
+ span += dt
792
+ if model is not None:
793
+ model.finish(state)
794
+ return TransientResult(t, peak, time, steps, state)
795
+
796
+ @staticmethod
797
+ def _cool(advance, pause: float, dt_max: float) -> None:
798
+ """Steps with the laser off for ``pause`` seconds, growing geometrically."""
799
+ span, dt = 0.0, min(1e-3, pause) if pause > 0 else 0.0
800
+ while span < pause - 1e-12:
801
+ dt = min(dt, pause - span, dt_max)
802
+ advance(dt, None, None)
803
+ span += dt
804
+ dt *= 1.5