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.
- morphogen/__init__.py +60 -0
- morphogen/__main__.py +7 -0
- morphogen/_platform.py +55 -0
- morphogen/_public.py +153 -0
- morphogen/_utils.py +80 -0
- morphogen/_version.py +1 -0
- morphogen/analysis/__init__.py +174 -0
- morphogen/analysis/anisotropy.py +135 -0
- morphogen/analysis/basic.py +38 -0
- morphogen/analysis/cells.py +54 -0
- morphogen/analysis/connectivity.py +156 -0
- morphogen/analysis/correlation.py +195 -0
- morphogen/analysis/covariance.py +80 -0
- morphogen/analysis/fractal.py +54 -0
- morphogen/analysis/measures.py +188 -0
- morphogen/analysis/morphology.py +265 -0
- morphogen/analysis/particles.py +160 -0
- morphogen/analysis/percolation.py +2034 -0
- morphogen/analysis/power_laws.py +143 -0
- morphogen/analysis/random_sets.py +351 -0
- morphogen/analysis/stereology.py +289 -0
- morphogen/analysis/surface.py +107 -0
- morphogen/analysis/topology.py +92 -0
- morphogen/automata/__init__.py +74 -0
- morphogen/automata/engine.py +211 -0
- morphogen/automata/growth.py +686 -0
- morphogen/automata/lattice.py +143 -0
- morphogen/automata/reaction.py +255 -0
- morphogen/automata/rules.py +353 -0
- morphogen/automata/tilings.py +1715 -0
- morphogen/cli.py +3526 -0
- morphogen/config.py +2167 -0
- morphogen/contact/__init__.py +113 -0
- morphogen/contact/experiments.py +368 -0
- morphogen/contact/hertz.py +104 -0
- morphogen/contact/kernels.py +827 -0
- morphogen/contact/periodic.py +278 -0
- morphogen/contact/problem.py +578 -0
- morphogen/contact/surfaces.py +310 -0
- morphogen/coupling/__init__.py +43 -0
- morphogen/coupling/ageing.py +143 -0
- morphogen/coupling/diffusion.py +226 -0
- morphogen/coupling/fenicsx.py +484 -0
- morphogen/coupling/oxidation.py +447 -0
- morphogen/coupling/plates.py +247 -0
- morphogen/design/__init__.py +51 -0
- morphogen/design/csp.py +616 -0
- morphogen/design/frames.py +277 -0
- morphogen/design/search.py +287 -0
- morphogen/design/tiles.py +336 -0
- morphogen/distributions.py +312 -0
- morphogen/domain.py +203 -0
- morphogen/dynamics/__init__.py +179 -0
- morphogen/dynamics/model.py +638 -0
- morphogen/dynamics/openradioss.py +643 -0
- morphogen/dynamics/results.py +515 -0
- morphogen/fracture/__init__.py +170 -0
- morphogen/fracture/bulk.py +349 -0
- morphogen/fracture/cohesive.py +1614 -0
- morphogen/fracture/ductile.py +557 -0
- morphogen/fracture/lefm.py +1168 -0
- morphogen/fracture/mixed.py +1178 -0
- morphogen/fracture/periodic.py +733 -0
- morphogen/fracture/phasefield.py +714 -0
- morphogen/fracture/phasefield_finite.py +368 -0
- morphogen/fracture/surface.py +572 -0
- morphogen/fracture/toughness.py +566 -0
- morphogen/gpu.py +108 -0
- morphogen/gui/__init__.py +8 -0
- morphogen/gui/api.py +1927 -0
- morphogen/gui/desktop.py +387 -0
- morphogen/gui/icon.png +0 -0
- morphogen/gui/index.html +1909 -0
- morphogen/gui/server.py +229 -0
- morphogen/gui/tools/__init__.py +629 -0
- morphogen/gui/tools/compare.py +149 -0
- morphogen/gui/tools/contact.py +391 -0
- morphogen/gui/tools/couplings.py +1085 -0
- morphogen/gui/tools/crackfront.py +245 -0
- morphogen/gui/tools/design.py +224 -0
- morphogen/gui/tools/dynamics.py +824 -0
- morphogen/gui/tools/fracture.py +2586 -0
- morphogen/gui/tools/interop.py +1654 -0
- morphogen/gui/tools/learning.py +595 -0
- morphogen/gui/tools/mechanics.py +3881 -0
- morphogen/gui/tools/nonlocal_damage.py +1321 -0
- morphogen/gui/tools/phasefield.py +215 -0
- morphogen/gui/tools/physics.py +597 -0
- morphogen/gui/tools/stability.py +1756 -0
- morphogen/gui/tools/statistics.py +1408 -0
- morphogen/gui/viewer.js +1100 -0
- morphogen/homogenization/__init__.py +210 -0
- morphogen/homogenization/acoustics.py +566 -0
- morphogen/homogenization/amg.py +1005 -0
- morphogen/homogenization/apparent.py +1046 -0
- morphogen/homogenization/behaviours.cu +2285 -0
- morphogen/homogenization/behaviours.py +944 -0
- morphogen/homogenization/beremin.py +263 -0
- morphogen/homogenization/bifurcation.py +1085 -0
- morphogen/homogenization/bloch.py +507 -0
- morphogen/homogenization/bounds.py +226 -0
- morphogen/homogenization/core.py +458 -0
- morphogen/homogenization/coupled.py +1135 -0
- morphogen/homogenization/crystal.py +2967 -0
- morphogen/homogenization/dilatation.py +454 -0
- morphogen/homogenization/elements.py +157 -0
- morphogen/homogenization/fatigue.py +768 -0
- morphogen/homogenization/fe.py +1739 -0
- morphogen/homogenization/fenicsx.py +307 -0
- morphogen/homogenization/fft.py +499 -0
- morphogen/homogenization/fft_nonlinear.py +391 -0
- morphogen/homogenization/finite.py +613 -0
- morphogen/homogenization/flow.py +361 -0
- morphogen/homogenization/frames.py +1125 -0
- morphogen/homogenization/gpu.py +1241 -0
- morphogen/homogenization/harmonic.py +427 -0
- morphogen/homogenization/identification.py +579 -0
- morphogen/homogenization/kernels.py +760 -0
- morphogen/homogenization/laws.py +2061 -0
- morphogen/homogenization/materials.py +1080 -0
- morphogen/homogenization/mfront.py +589 -0
- morphogen/homogenization/networks.py +880 -0
- morphogen/homogenization/nonlinear.py +2612 -0
- morphogen/homogenization/ntfa.py +577 -0
- morphogen/homogenization/paths.py +476 -0
- morphogen/homogenization/photonic.py +467 -0
- morphogen/homogenization/poroelastic.py +212 -0
- morphogen/homogenization/porous.py +1120 -0
- morphogen/homogenization/postprocess.py +290 -0
- morphogen/homogenization/solvers.py +1140 -0
- morphogen/homogenization/tensors.py +240 -0
- morphogen/homogenization/voxel_fe.py +457 -0
- morphogen/homogenization/xfem.py +1016 -0
- morphogen/homogenization/zmat.py +1258 -0
- morphogen/iga/__init__.py +48 -0
- morphogen/iga/analysis.py +508 -0
- morphogen/iga/basis.py +214 -0
- morphogen/iga/geometry.py +501 -0
- morphogen/iga/homogenization.py +219 -0
- morphogen/iga/optimization.py +700 -0
- morphogen/iga/shapes.py +331 -0
- morphogen/image.py +128 -0
- morphogen/io/__init__.py +246 -0
- morphogen/io/amitex.py +741 -0
- morphogen/io/ebsd.py +881 -0
- morphogen/io/export.py +196 -0
- morphogen/io/geometry.py +158 -0
- morphogen/io/medit.py +147 -0
- morphogen/io/meshes.py +844 -0
- morphogen/io/metaimage.py +97 -0
- morphogen/io/mfront.py +1104 -0
- morphogen/io/native.py +57 -0
- morphogen/io/radioss.py +764 -0
- morphogen/io/solvers.py +371 -0
- morphogen/io/tables.py +278 -0
- morphogen/io/tiff.py +66 -0
- morphogen/io/vtk.py +701 -0
- morphogen/io/xdmf.py +200 -0
- morphogen/kernels/__init__.py +5 -0
- morphogen/kernels/annealing.py +192 -0
- morphogen/kernels/cells.py +69 -0
- morphogen/kernels/collective.py +87 -0
- morphogen/kernels/force_biased.py +595 -0
- morphogen/kernels/implicit.py +145 -0
- morphogen/kernels/leaves.py +132 -0
- morphogen/kernels/packing.py +304 -0
- morphogen/kernels/raster.py +279 -0
- morphogen/kernels/rsa.py +371 -0
- morphogen/kernels/union.py +135 -0
- morphogen/kernels/watershed.py +190 -0
- morphogen/laser/__init__.py +234 -0
- morphogen/laser/architectures.py +375 -0
- morphogen/laser/bending.py +216 -0
- morphogen/laser/cells.py +1694 -0
- morphogen/laser/design.py +940 -0
- morphogen/laser/figures.py +227 -0
- morphogen/laser/heat.py +804 -0
- morphogen/laser/materials.py +691 -0
- morphogen/laser/mechanics.py +1670 -0
- morphogen/laser/metallurgy.py +615 -0
- morphogen/laser/patterns.py +828 -0
- morphogen/laser/periodic.py +392 -0
- morphogen/laser/process.py +362 -0
- morphogen/laser/run.py +534 -0
- morphogen/laser/solid.py +216 -0
- morphogen/laser/specimen.py +200 -0
- morphogen/laser/structures.py +708 -0
- morphogen/learning/__init__.py +81 -0
- morphogen/learning/behaviour.py +398 -0
- morphogen/learning/data.py +328 -0
- morphogen/learning/learned.cpp +668 -0
- morphogen/learning/logarithmic.py +202 -0
- morphogen/learning/mfront.py +409 -0
- morphogen/learning/networks.py +767 -0
- morphogen/learning/run.py +212 -0
- morphogen/learning/standard.py +814 -0
- morphogen/learning/training.py +235 -0
- morphogen/mesh/__init__.py +29 -0
- morphogen/mesh/conforming.py +1423 -0
- morphogen/mesh/curved.py +600 -0
- morphogen/mesh/exact.py +1717 -0
- morphogen/mesh/octree.py +350 -0
- morphogen/mesh/polycrystal.py +1041 -0
- morphogen/mesh/polyhedra.py +677 -0
- morphogen/mesh/regularize.py +570 -0
- morphogen/mesh/surface.py +97 -0
- morphogen/mesh/tetra.py +512 -0
- morphogen/mesh/voxel.py +124 -0
- morphogen/micromorphic/__init__.py +31 -0
- morphogen/micromorphic/damage.py +359 -0
- morphogen/micromorphic/ductile.py +534 -0
- morphogen/micromorphic/finite.py +220 -0
- morphogen/micromorphic/microfoam.py +787 -0
- morphogen/micromorphic/space.py +341 -0
- morphogen/models/__init__.py +195 -0
- morphogen/models/affine.py +384 -0
- morphogen/models/automata.py +592 -0
- morphogen/models/base.py +500 -0
- morphogen/models/boolean.py +310 -0
- morphogen/models/bouligand.py +331 -0
- morphogen/models/branching.py +241 -0
- morphogen/models/combination.py +430 -0
- morphogen/models/deadleaves.py +766 -0
- morphogen/models/design.py +289 -0
- morphogen/models/ebsd.py +206 -0
- morphogen/models/fibers.py +1476 -0
- morphogen/models/foam.py +594 -0
- morphogen/models/gaussian.py +314 -0
- morphogen/models/growth.py +459 -0
- morphogen/models/hardcore.py +317 -0
- morphogen/models/hierarchical.py +269 -0
- morphogen/models/honeycomb.py +749 -0
- morphogen/models/implicit.py +177 -0
- morphogen/models/laminate.py +470 -0
- morphogen/models/lattice.py +351 -0
- morphogen/models/lattice_field.py +345 -0
- morphogen/models/levelset_foam.py +563 -0
- morphogen/models/nacre.py +411 -0
- morphogen/models/nested.py +924 -0
- morphogen/models/osteons.py +374 -0
- morphogen/models/pieces.py +167 -0
- morphogen/models/planar.py +126 -0
- morphogen/models/reconstruction.py +203 -0
- morphogen/models/scale_rich.py +1409 -0
- morphogen/models/scale_rich_3d.py +1616 -0
- morphogen/models/tessellation.py +735 -0
- morphogen/models/tiling_field.py +302 -0
- morphogen/models/tpms.py +197 -0
- morphogen/models/transparent.py +406 -0
- morphogen/models/union.py +141 -0
- morphogen/optimization/__init__.py +43 -0
- morphogen/optimization/cell.py +295 -0
- morphogen/optimization/filters.py +115 -0
- morphogen/optimization/mma.py +226 -0
- morphogen/optimization/run.py +219 -0
- morphogen/optimization/topology.py +632 -0
- morphogen/orientations.py +568 -0
- morphogen/parallel.py +599 -0
- morphogen/pipeline.py +978 -0
- morphogen/primitives.py +188 -0
- morphogen/results.py +564 -0
- morphogen/rve/__init__.py +73 -0
- morphogen/rve/report.py +627 -0
- morphogen/rve/scaling.py +363 -0
- morphogen/rve/study.py +1054 -0
- morphogen/rve/windows.py +345 -0
- morphogen/seeding.py +51 -0
- morphogen/settings.py +118 -0
- morphogen/stopping.py +48 -0
- morphogen/symmetry.py +384 -0
- morphogen/templates/activator_inhibitor.yaml +22 -0
- morphogen/templates/aggregation.yaml +23 -0
- morphogen/templates/boolean_cylinders.yaml +20 -0
- morphogen/templates/boolean_spheres.yaml +22 -0
- morphogen/templates/bouligand.yaml +28 -0
- morphogen/templates/cellular_automaton.yaml +25 -0
- morphogen/templates/coated_spheres.yaml +26 -0
- morphogen/templates/contact_fibers.yaml +27 -0
- morphogen/templates/cox_nanocomposite.yaml +22 -0
- morphogen/templates/cross_linked_fibers.yaml +26 -0
- morphogen/templates/curved_arcs.yaml +28 -0
- morphogen/templates/curved_fibers.yaml +24 -0
- morphogen/templates/dead_leaves.yaml +22 -0
- morphogen/templates/delaunay_network.yaml +22 -0
- morphogen/templates/dense_packing.yaml +22 -0
- morphogen/templates/diffusion.yaml +33 -0
- morphogen/templates/ebsd.yaml +34 -0
- morphogen/templates/ebsd_map.ctf +3087 -0
- morphogen/templates/fracture_composite.yaml +42 -0
- morphogen/templates/fracture_rubber.yaml +47 -0
- morphogen/templates/gaussian_excursion.yaml +17 -0
- morphogen/templates/graded_lattice.yaml +24 -0
- morphogen/templates/hardcore_fibers.yaml +22 -0
- morphogen/templates/hardcore_spheres.yaml +22 -0
- morphogen/templates/hierarchical_lattice.yaml +22 -0
- morphogen/templates/homogenization_acoustic_foam.yaml +36 -0
- morphogen/templates/homogenization_beremin.yaml +50 -0
- morphogen/templates/homogenization_cleavage.yaml +51 -0
- morphogen/templates/homogenization_cleavage_band.yaml +55 -0
- morphogen/templates/homogenization_contact.yaml +43 -0
- morphogen/templates/homogenization_crack_closure.yaml +49 -0
- morphogen/templates/homogenization_crystal_plasticity.yaml +50 -0
- morphogen/templates/homogenization_crystal_plasticity_fft.yaml +52 -0
- morphogen/templates/homogenization_crystallization.yaml +30 -0
- morphogen/templates/homogenization_debonding.yaml +43 -0
- morphogen/templates/homogenization_detwinning.yaml +58 -0
- morphogen/templates/homogenization_ductile_damage.yaml +47 -0
- morphogen/templates/homogenization_fatigue.yaml +40 -0
- morphogen/templates/homogenization_grain_fracture.yaml +56 -0
- morphogen/templates/homogenization_gyroid.yaml +30 -0
- morphogen/templates/homogenization_intergranular.yaml +43 -0
- morphogen/templates/homogenization_interphase.yaml +42 -0
- morphogen/templates/homogenization_mixed_loading.yaml +33 -0
- morphogen/templates/homogenization_ntfa.yaml +56 -0
- morphogen/templates/homogenization_piezoelectric.yaml +27 -0
- morphogen/templates/homogenization_polycrystal.yaml +30 -0
- morphogen/templates/homogenization_polycrystal_inclusions.yaml +30 -0
- morphogen/templates/homogenization_poroelastic.yaml +26 -0
- morphogen/templates/homogenization_rubber.yaml +40 -0
- morphogen/templates/homogenization_slip_cleavage.yaml +50 -0
- morphogen/templates/homogenization_spheres.yaml +31 -0
- morphogen/templates/homogenization_transport.yaml +29 -0
- morphogen/templates/homogenization_twinning.yaml +54 -0
- morphogen/templates/homogenization_viscoelastic.yaml +34 -0
- morphogen/templates/homogenization_viscoplastic.yaml +42 -0
- morphogen/templates/homogenization_voronoi.yaml +26 -0
- morphogen/templates/homogenization_xfem.yaml +23 -0
- morphogen/templates/hyperuniform_cells.yaml +24 -0
- morphogen/templates/laguerre.yaml +18 -0
- morphogen/templates/laser_bending.yaml +35 -0
- morphogen/templates/laser_cells.yaml +38 -0
- morphogen/templates/laser_corrugated.yaml +36 -0
- morphogen/templates/level_set_foam.yaml +29 -0
- morphogen/templates/menger_sponge.yaml +17 -0
- morphogen/templates/nacre.yaml +25 -0
- morphogen/templates/nucleation_growth.yaml +25 -0
- morphogen/templates/optimize_auxetic.yaml +29 -0
- morphogen/templates/optimize_auxetic_3d.yaml +27 -0
- morphogen/templates/optimize_bulk.yaml +23 -0
- morphogen/templates/optimize_conductivity.yaml +20 -0
- morphogen/templates/osteons.yaml +28 -0
- morphogen/templates/penetrable_spheres.yaml +21 -0
- morphogen/templates/poisson_fibers.yaml +21 -0
- morphogen/templates/random_laminate.yaml +26 -0
- morphogen/templates/random_lattice.yaml +27 -0
- morphogen/templates/random_walk_fibers.yaml +26 -0
- morphogen/templates/reaction_diffusion.yaml +22 -0
- morphogen/templates/reconstruction.yaml +22 -0
- morphogen/templates/rve_cellular_automaton.yaml +23 -0
- morphogen/templates/rve_crystal_plasticity_fft.yaml +51 -0
- morphogen/templates/rve_multiphysics.yaml +43 -0
- morphogen/templates/rve_poisson_fibers.yaml +22 -0
- morphogen/templates/rve_poisson_fibers_fe.yaml +33 -0
- morphogen/templates/rve_voronoi_windows.yaml +20 -0
- morphogen/templates/scale_rich_network.yaml +29 -0
- morphogen/templates/scale_rich_plates.yaml +30 -0
- morphogen/templates/sequential_dead_leaves.yaml +25 -0
- morphogen/templates/strut_lattice.yaml +21 -0
- morphogen/templates/tile_assembly.yaml +28 -0
- morphogen/templates/tpms.yaml +19 -0
- morphogen/templates/trabecular_bone.yaml +29 -0
- morphogen/templates/transparent_dead_leaves.yaml +23 -0
- morphogen/templates/vascular_tree.yaml +23 -0
- morphogen/templates/voronoi.yaml +20 -0
- morphogen/templates/wood.yaml +34 -0
- morphogen/templates/workflow.yaml +56 -0
- morphogen/texture.py +665 -0
- morphogen/theory.py +162 -0
- morphogen/viz/__init__.py +12 -0
- morphogen/viz/export.py +244 -0
- morphogen/viz/figures.py +707 -0
- morphogen/viz/png.py +148 -0
- morphogen/viz/sections.py +696 -0
- morphogen/viz/surfaces.py +1352 -0
- morphogen/viz/video.py +904 -0
- morphogen/viz/workflow.py +488 -0
- morphogen-1.0.0.dist-info/METADATA +2316 -0
- morphogen-1.0.0.dist-info/RECORD +381 -0
- morphogen-1.0.0.dist-info/WHEEL +4 -0
- morphogen-1.0.0.dist-info/entry_points.txt +5 -0
- morphogen-1.0.0.dist-info/licenses/LICENSE +674 -0
|
@@ -0,0 +1,940 @@
|
|
|
1
|
+
"""Design of laser-architectured sheets: the simulation of a case and the optimization of
|
|
2
|
+
its laser path.
|
|
3
|
+
|
|
4
|
+
A :class:`SheetCase` gathers the choices of a study: the base material and its
|
|
5
|
+
thickness, the treatment (hardening, or carburizing, nitriding, alloying in the melt
|
|
6
|
+
pool), the laser configuration (one beam, or two aligned beams on both faces), the
|
|
7
|
+
specimen and its mesh, and the pattern of the tracks. :meth:`SheetCase.evaluate` runs
|
|
8
|
+
the chain: the path drawn on the parallel part of the specimen, the treatment at the
|
|
9
|
+
Gauss points of the mesh (:mod:`morphogen.laser.process`), the flow law of each point
|
|
10
|
+
and layer (:mod:`morphogen.laser.materials`), the tensile test
|
|
11
|
+
(:mod:`morphogen.laser.mechanics`), and the measures (:data:`MEASURES`) — or, with the
|
|
12
|
+
loading ``cell``, the periodic cell of the sheet treated all over and its homogenized
|
|
13
|
+
tensile tests (:mod:`morphogen.laser.periodic`).
|
|
14
|
+
|
|
15
|
+
**Objectives** (:data:`OBJECTIVES`, maximized): ``strength_ductility`` the product of
|
|
16
|
+
the tensile strength and the uniform elongation (MPa, the balance of the "banana" chart
|
|
17
|
+
of AHSS), ``energy`` the work absorbed up to necking (MJ/m³, the area under the
|
|
18
|
+
engineering curve up to the maximum force), ``uniform_elongation``,
|
|
19
|
+
``tensile_strength``, ``yield_strength``; ``target``: the opposite of the squared
|
|
20
|
+
relative distances to target measures. **Constraints** bound any measure, e.g. the
|
|
21
|
+
reinforced volume fraction, the yield strength, the smallest gap between tracks (their
|
|
22
|
+
neighbours temper them) or the smallest radius of curvature of a track (the
|
|
23
|
+
quasi-steady thermal cycles need radii larger than the heated width), the length of the
|
|
24
|
+
path in the specimen (the time and energy of the process); a violation adds a penalty.
|
|
25
|
+
|
|
26
|
+
**Optimization** (:func:`optimize`) of the parameters of the pattern and of the laser
|
|
27
|
+
(dotted names: ``pattern.amplitude``, ``pattern.coefficients.1.0``, ``beam.power``,
|
|
28
|
+
``bottom.power``...), each between bounds, by ``grid`` (the full factorial of the
|
|
29
|
+
thesis's parametric studies), ``nelder_mead``, ``differential_evolution`` (SciPy),
|
|
30
|
+
``genetic`` (:func:`morphogen.design.search.genetic_algorithm`) or ``bayesian``: a
|
|
31
|
+
Gaussian process (Matérn 5/2, automatic relevance, hyperparameters by the marginal
|
|
32
|
+
likelihood) fitted to the penalized costs of a Latin hypercube of first designs, then
|
|
33
|
+
the design of largest expected improvement at each evaluation (Jones et al. 1998), for
|
|
34
|
+
the costly finite element evaluations.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
from __future__ import annotations
|
|
38
|
+
|
|
39
|
+
import copy
|
|
40
|
+
import itertools
|
|
41
|
+
import math
|
|
42
|
+
import time
|
|
43
|
+
from dataclasses import dataclass, field, replace
|
|
44
|
+
|
|
45
|
+
import numpy as np
|
|
46
|
+
from scipy import optimize as sopt
|
|
47
|
+
from scipy.stats import norm, qmc
|
|
48
|
+
|
|
49
|
+
from morphogen.laser.bending import BendingResult, three_point_bending
|
|
50
|
+
from morphogen.laser.heat import Beam
|
|
51
|
+
from morphogen.laser.materials import SheetMaterial
|
|
52
|
+
from morphogen.laser.mechanics import Membrane, TensileResult, tensile_test
|
|
53
|
+
from morphogen.laser.patterns import LaserPath, make_pattern
|
|
54
|
+
from morphogen.laser.process import LaserTreatment, TreatmentResult
|
|
55
|
+
from morphogen.laser.specimen import Specimen
|
|
56
|
+
|
|
57
|
+
#: Measures of a case: of the tensile test (MPa, engineering strain, MJ/m³), of the
|
|
58
|
+
#: bending test (N, N/mm, mJ), of the treated parallel part (fractions, HV, °C), of the
|
|
59
|
+
#: process (mm, s, J), and with several directions the anisotropy (the spread of a
|
|
60
|
+
#: measure over the directions over its mean); the measures of one direction ``d``
|
|
61
|
+
#: take the suffix ``_d`` (``yield_strength_45``).
|
|
62
|
+
MEASURES = (
|
|
63
|
+
"yield_strength",
|
|
64
|
+
"tensile_strength",
|
|
65
|
+
"uniform_elongation",
|
|
66
|
+
"energy",
|
|
67
|
+
"strength_ductility",
|
|
68
|
+
"failure_strain",
|
|
69
|
+
"ductility",
|
|
70
|
+
"bending_load",
|
|
71
|
+
"bending_stiffness",
|
|
72
|
+
"bending_load_at_deflection",
|
|
73
|
+
"bending_energy",
|
|
74
|
+
"volume_fraction",
|
|
75
|
+
"area_fraction",
|
|
76
|
+
"mean_hardness",
|
|
77
|
+
"max_hardness",
|
|
78
|
+
"melted_fraction",
|
|
79
|
+
"peak_temperature",
|
|
80
|
+
"path_length",
|
|
81
|
+
"laser_time",
|
|
82
|
+
"laser_energy",
|
|
83
|
+
"min_gap",
|
|
84
|
+
"min_radius",
|
|
85
|
+
"yield_anisotropy",
|
|
86
|
+
"strength_anisotropy",
|
|
87
|
+
"elongation_anisotropy",
|
|
88
|
+
"r_value",
|
|
89
|
+
"r_anisotropy",
|
|
90
|
+
"r_bar",
|
|
91
|
+
"delta_r",
|
|
92
|
+
"hill_f",
|
|
93
|
+
"hill_g",
|
|
94
|
+
"hill_h",
|
|
95
|
+
"hill_n",
|
|
96
|
+
)
|
|
97
|
+
#: Objectives (maximized): measures, ``isotropy`` (the opposite of the anisotropy of
|
|
98
|
+
#: the yield strength), ``flow_isotropy`` (of the Lankford coefficient) and ``target``
|
|
99
|
+
#: (the opposite of the squared relative distances to target measures).
|
|
100
|
+
OBJECTIVES = (
|
|
101
|
+
"strength_ductility",
|
|
102
|
+
"energy",
|
|
103
|
+
"uniform_elongation",
|
|
104
|
+
"ductility",
|
|
105
|
+
"tensile_strength",
|
|
106
|
+
"yield_strength",
|
|
107
|
+
"bending_load_at_deflection",
|
|
108
|
+
"bending_energy",
|
|
109
|
+
"bending_load",
|
|
110
|
+
"isotropy",
|
|
111
|
+
"flow_isotropy",
|
|
112
|
+
"target",
|
|
113
|
+
)
|
|
114
|
+
#: Load cases.
|
|
115
|
+
LOADINGS = ("tension", "bending", "cell")
|
|
116
|
+
#: The keys of the loading ``cell`` that set the cell (the others go to its test).
|
|
117
|
+
CELL_KEYS = ("kind", "vectors", "element", "along")
|
|
118
|
+
#: How far around the periodic cell its pattern is drawn (mm): the heat of the tracks.
|
|
119
|
+
CELL_REACH = 5.0
|
|
120
|
+
#: Optimization methods.
|
|
121
|
+
METHODS = ("grid", "nelder_mead", "differential_evolution", "genetic", "bayesian")
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def hill48(r_values: dict) -> dict:
|
|
125
|
+
"""Hill's 1948 criterion of a sheet from its Lankford coefficients at 0°, 45° and
|
|
126
|
+
90° (``{direction: r}``): ``F``, ``G``, ``H``, ``N`` normalized by ``G + H = 1``
|
|
127
|
+
(``F = r0 / (r90 (1 + r0))``, ``G = 1/(1 + r0)``, ``H = r0/(1 + r0)``, ``N = (r0 +
|
|
128
|
+
r90)(1 + 2 r45) / (2 r90 (1 + r0))``; isotropy: 0.5, 0.5, 0.5, 1.5), the normal
|
|
129
|
+
anisotropy ``r̄ = (r0 + 2 r45 + r90)/4`` and the planar ``Δr = (r0 − 2 r45 + r90)/2``;
|
|
130
|
+
NaN without the three directions."""
|
|
131
|
+
keys = ("r_bar", "delta_r", "hill_f", "hill_g", "hill_h", "hill_n")
|
|
132
|
+
try:
|
|
133
|
+
r0, r45, r90 = (float(r_values[d]) for d in (0, 45, 90))
|
|
134
|
+
except (KeyError, TypeError, ValueError):
|
|
135
|
+
return dict.fromkeys(keys, math.nan)
|
|
136
|
+
if not all(np.isfinite([r0, r45, r90])) or r90 == 0 or r0 == -1:
|
|
137
|
+
return dict.fromkeys(keys, math.nan)
|
|
138
|
+
return {
|
|
139
|
+
"r_bar": (r0 + 2 * r45 + r90) / 4,
|
|
140
|
+
"delta_r": (r0 - 2 * r45 + r90) / 2,
|
|
141
|
+
"hill_f": r0 / (r90 * (1 + r0)),
|
|
142
|
+
"hill_g": 1 / (1 + r0),
|
|
143
|
+
"hill_h": r0 / (1 + r0),
|
|
144
|
+
"hill_n": (r0 + r90) * (1 + 2 * r45) / (2 * r90 * (1 + r0)),
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
@dataclass
|
|
149
|
+
class SheetResult:
|
|
150
|
+
"""The evaluation of a case: its path, the treated sheet at the Gauss points (or at
|
|
151
|
+
the fibres of the bending sections), the tensile test or the bending test, the
|
|
152
|
+
measures; with several directions, the result of each (``directions``, by angle),
|
|
153
|
+
the others being those of the first."""
|
|
154
|
+
|
|
155
|
+
path: LaserPath
|
|
156
|
+
treatment: TreatmentResult
|
|
157
|
+
tensile: TensileResult | None
|
|
158
|
+
measures: dict
|
|
159
|
+
time_s: float = 0.0
|
|
160
|
+
bending: BendingResult | None = None
|
|
161
|
+
directions: dict = field(default_factory=dict)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
@dataclass
|
|
165
|
+
class SheetCase:
|
|
166
|
+
"""The choices of a study (see the module). ``beam``: the beam of the upper face
|
|
167
|
+
(and of both faces in the ``symmetric`` configuration unless ``bottom`` is given);
|
|
168
|
+
``pattern``: the kind and parameters of
|
|
169
|
+
:func:`~morphogen.laser.patterns.make_pattern`; ``element``: the size of the elements
|
|
170
|
+
(mm); ``loading``: the load case, ``kind`` ``tension`` (the default; the other keys
|
|
171
|
+
are options of :func:`~morphogen.laser.mechanics.tensile_test`) or ``bending``
|
|
172
|
+
(three-point bending of the strip: ``span``, ``deflection`` the reference
|
|
173
|
+
deflection, ``sections`` along the span, the fibres across the width at about
|
|
174
|
+
``element``; :func:`~morphogen.laser.bending.three_point_bending`) or ``cell`` (the
|
|
175
|
+
periodic cell of the sheet treated all over by the pattern repeated: its lattice
|
|
176
|
+
from the pattern or ``vectors``, its elements of ``element`` mm; the other keys are
|
|
177
|
+
options of :func:`~morphogen.laser.periodic.cell_test`; the measures of the treatment
|
|
178
|
+
over the cell, those of the path over the parallel part of the specimen);
|
|
179
|
+
``directions``: angles (degrees) of the tensile axis from the x axis of the pattern
|
|
180
|
+
(the rolling direction), a specimen for each (the pattern turned by the opposite
|
|
181
|
+
angle; the cell is pulled in each direction instead): the measures are their means,
|
|
182
|
+
each one's with its suffix, and the anisotropies."""
|
|
183
|
+
|
|
184
|
+
material: SheetMaterial | str = "annealed_ms1500"
|
|
185
|
+
specimen: Specimen = field(default_factory=Specimen)
|
|
186
|
+
beam: Beam = field(default_factory=lambda: Beam(150.0, 10.0, 0.5, 0.55))
|
|
187
|
+
bottom: Beam | None = field(
|
|
188
|
+
default_factory=lambda: Beam(100.0, 10.0, 0.6, 0.55, profile="tophat")
|
|
189
|
+
)
|
|
190
|
+
configuration: str = "symmetric"
|
|
191
|
+
treatment: str = "hardening"
|
|
192
|
+
alloying: dict | None = None
|
|
193
|
+
layers: int = 4
|
|
194
|
+
pattern: dict = field(default_factory=lambda: {"kind": "straight", "count": 1})
|
|
195
|
+
pause: float = 30.0
|
|
196
|
+
element: float = 0.5
|
|
197
|
+
loading: dict = field(default_factory=dict)
|
|
198
|
+
ambient: float = 20.0
|
|
199
|
+
directions: tuple | None = None
|
|
200
|
+
|
|
201
|
+
def __post_init__(self):
|
|
202
|
+
self.material = SheetMaterial.from_config(self.material)
|
|
203
|
+
self.specimen = Specimen.from_config(self.specimen)
|
|
204
|
+
if self.configuration == "single":
|
|
205
|
+
self.bottom = None
|
|
206
|
+
self.pattern = dict(self.pattern)
|
|
207
|
+
if "kind" not in self.pattern:
|
|
208
|
+
raise ValueError("pattern: a kind")
|
|
209
|
+
self.loading = dict(self.loading)
|
|
210
|
+
if self.loading.get("kind", "tension") not in LOADINGS:
|
|
211
|
+
raise ValueError(f"loading kind: one of {LOADINGS}")
|
|
212
|
+
if self.directions is not None:
|
|
213
|
+
self.directions = tuple(float(d) for d in np.atleast_1d(self.directions))
|
|
214
|
+
self._treatments: dict = {}
|
|
215
|
+
|
|
216
|
+
def laser_treatment(self) -> LaserTreatment:
|
|
217
|
+
"""The treatment of the sheet (cached: its tabulated cycles are reused)."""
|
|
218
|
+
key = (
|
|
219
|
+
self.material.name,
|
|
220
|
+
self.specimen.thickness,
|
|
221
|
+
self.configuration,
|
|
222
|
+
self.layers,
|
|
223
|
+
self.treatment,
|
|
224
|
+
repr(self.alloying),
|
|
225
|
+
self.ambient,
|
|
226
|
+
)
|
|
227
|
+
if key not in self._treatments:
|
|
228
|
+
self._treatments[key] = LaserTreatment(
|
|
229
|
+
self.material,
|
|
230
|
+
thickness=self.specimen.thickness,
|
|
231
|
+
configuration=self.configuration,
|
|
232
|
+
layers=self.layers,
|
|
233
|
+
treatment=self.treatment,
|
|
234
|
+
alloying=self.alloying,
|
|
235
|
+
ambient=self.ambient,
|
|
236
|
+
)
|
|
237
|
+
return self._treatments[key]
|
|
238
|
+
|
|
239
|
+
def path(self) -> LaserPath:
|
|
240
|
+
"""The laser path drawn on the parallel part of the specimen."""
|
|
241
|
+
params = dict(self.pattern)
|
|
242
|
+
kind = params.pop("kind")
|
|
243
|
+
if kind == "none":
|
|
244
|
+
return LaserPath([])
|
|
245
|
+
return make_pattern(
|
|
246
|
+
kind,
|
|
247
|
+
self.specimen.band(),
|
|
248
|
+
beam=self.beam,
|
|
249
|
+
bottom=self.bottom,
|
|
250
|
+
pause=self.pause,
|
|
251
|
+
**params,
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
def with_values(self, values: dict) -> SheetCase:
|
|
255
|
+
"""A copy with parameters set by dotted names (``pattern.amplitude``,
|
|
256
|
+
``beam.power``, ``bottom.radius``, ``specimen.width``, ``layers``...)."""
|
|
257
|
+
new = copy.copy(self)
|
|
258
|
+
new.pattern = copy.deepcopy(self.pattern)
|
|
259
|
+
for name, value in values.items():
|
|
260
|
+
head, _, rest = name.partition(".")
|
|
261
|
+
if head == "pattern":
|
|
262
|
+
_set_dotted(new.pattern, rest, value)
|
|
263
|
+
elif head in ("beam", "bottom", "specimen"):
|
|
264
|
+
obj = getattr(new, head)
|
|
265
|
+
if obj is None:
|
|
266
|
+
raise ValueError(f"{name}: no {head}")
|
|
267
|
+
setattr(new, head, replace(obj, **{rest: value}))
|
|
268
|
+
elif head == "loading" and rest:
|
|
269
|
+
new.loading = {**new.loading, rest: value}
|
|
270
|
+
elif hasattr(new, head) and not rest:
|
|
271
|
+
setattr(new, head, value)
|
|
272
|
+
else:
|
|
273
|
+
raise ValueError(f"unknown parameter {name!r}")
|
|
274
|
+
if new.bottom is not None and "beam.speed" in values:
|
|
275
|
+
new.bottom = replace(new.bottom, speed=new.beam.speed)
|
|
276
|
+
return new
|
|
277
|
+
|
|
278
|
+
def evaluate(self, *, keep_fields: bool = False) -> SheetResult:
|
|
279
|
+
"""Run the chain (see the module), in each direction if several."""
|
|
280
|
+
if self.loading.get("kind") == "cell":
|
|
281
|
+
return self._evaluate_cell(keep_fields)
|
|
282
|
+
if not self.directions:
|
|
283
|
+
return self._evaluate(keep_fields)
|
|
284
|
+
t0 = time.perf_counter()
|
|
285
|
+
results = {}
|
|
286
|
+
for d in self.directions:
|
|
287
|
+
sub = copy.copy(self)
|
|
288
|
+
sub.directions = None
|
|
289
|
+
sub.pattern = dict(self.pattern)
|
|
290
|
+
sub.pattern["rotation"] = float(self.pattern.get("rotation", 0.0)) - d
|
|
291
|
+
sub._direction = float(d) # the specimen cut at d from the rolling direction
|
|
292
|
+
results[d] = sub._evaluate(keep_fields)
|
|
293
|
+
return self._combine(results, t0)
|
|
294
|
+
|
|
295
|
+
def _combine(self, results: dict, t0: float) -> SheetResult:
|
|
296
|
+
"""The result of several directions: the first's, with the means, the values of
|
|
297
|
+
each direction and the anisotropies."""
|
|
298
|
+
first = results[next(iter(results))]
|
|
299
|
+
measures = {}
|
|
300
|
+
spreads = (
|
|
301
|
+
"yield_anisotropy",
|
|
302
|
+
"strength_anisotropy",
|
|
303
|
+
"elongation_anisotropy",
|
|
304
|
+
"r_anisotropy",
|
|
305
|
+
"r_bar",
|
|
306
|
+
"delta_r",
|
|
307
|
+
"hill_f",
|
|
308
|
+
"hill_g",
|
|
309
|
+
"hill_h",
|
|
310
|
+
"hill_n",
|
|
311
|
+
)
|
|
312
|
+
for k, v in first.measures.items():
|
|
313
|
+
vals = np.array([r.measures[k] for r in results.values()], dtype=float)
|
|
314
|
+
measures[k] = bool(v) if isinstance(v, bool) else float(np.mean(vals))
|
|
315
|
+
if not isinstance(v, bool) and k not in spreads:
|
|
316
|
+
for d, r in results.items():
|
|
317
|
+
measures[f"{k}_{d:g}"] = float(r.measures[k])
|
|
318
|
+
for name, key in (
|
|
319
|
+
("yield_anisotropy", "yield_strength"),
|
|
320
|
+
("strength_anisotropy", "tensile_strength"),
|
|
321
|
+
("elongation_anisotropy", "uniform_elongation"),
|
|
322
|
+
("r_anisotropy", "r_value"),
|
|
323
|
+
):
|
|
324
|
+
vals = np.array([r.measures[key] for r in results.values()], dtype=float)
|
|
325
|
+
mean = float(np.mean(vals))
|
|
326
|
+
measures[name] = float((vals.max() - vals.min()) / mean) if mean else math.nan
|
|
327
|
+
measures.update(hill48({d: r.measures["r_value"] for d, r in results.items()}))
|
|
328
|
+
return replace(
|
|
329
|
+
first, measures=measures, time_s=time.perf_counter() - t0, directions=results
|
|
330
|
+
)
|
|
331
|
+
|
|
332
|
+
def cell(self):
|
|
333
|
+
"""The periodic cell of the treated sheet
|
|
334
|
+
(:class:`~morphogen.laser.periodic.PeriodicCell`): the lattice of the pattern
|
|
335
|
+
(its length ``along`` straight tracks from the loading if given), or the
|
|
336
|
+
``vectors`` of the loading, its elements of ``element`` mm (or the loading's
|
|
337
|
+
``element``), centred on the parallel part of the specimen."""
|
|
338
|
+
from morphogen.laser.periodic import PeriodicCell, lattice, reduce_basis
|
|
339
|
+
|
|
340
|
+
vectors = self.loading.get("vectors")
|
|
341
|
+
if vectors is None:
|
|
342
|
+
a1, a2 = lattice(self.pattern, self.loading.get("along"))
|
|
343
|
+
else:
|
|
344
|
+
a1, a2 = reduce_basis(*vectors)
|
|
345
|
+
x0, x1, y0, y1 = self.specimen.band()
|
|
346
|
+
return PeriodicCell.build(
|
|
347
|
+
a1,
|
|
348
|
+
a2,
|
|
349
|
+
element=float(self.loading.get("element", self.element)),
|
|
350
|
+
centre=(0.5 * (x0 + x1), 0.5 * (y0 + y1)),
|
|
351
|
+
)
|
|
352
|
+
|
|
353
|
+
def _evaluate_cell(self, keep_fields: bool) -> SheetResult:
|
|
354
|
+
"""The periodic cell of the sheet (loading ``cell``): its treatment once, its
|
|
355
|
+
tensile test in each direction (:func:`~morphogen.laser.periodic.cell_test`)."""
|
|
356
|
+
from morphogen.laser.periodic import cell_test
|
|
357
|
+
|
|
358
|
+
t0 = time.perf_counter()
|
|
359
|
+
cell = self.cell()
|
|
360
|
+
load = {k: v for k, v in self.loading.items() if k not in CELL_KEYS}
|
|
361
|
+
params = dict(self.pattern)
|
|
362
|
+
kind = params.pop("kind")
|
|
363
|
+
sheet = ( # the pattern over the sheet around the cell, as far as it heats it
|
|
364
|
+
LaserPath([])
|
|
365
|
+
if kind == "none"
|
|
366
|
+
else make_pattern(
|
|
367
|
+
kind,
|
|
368
|
+
cell.box(CELL_REACH),
|
|
369
|
+
beam=self.beam,
|
|
370
|
+
bottom=self.bottom,
|
|
371
|
+
pause=self.pause,
|
|
372
|
+
cover=True,
|
|
373
|
+
**params,
|
|
374
|
+
)
|
|
375
|
+
)
|
|
376
|
+
pts, _, wts = cell.mesh.gauss()
|
|
377
|
+
treat = self.laser_treatment().apply(sheet, pts.reshape(-1, 2), wts.reshape(-1))
|
|
378
|
+
ne = len(cell.mesh.quads)
|
|
379
|
+
flow = tuple(v.reshape(ne, 4, -1) for v in treat.flow())
|
|
380
|
+
m = self.material
|
|
381
|
+
critical, radius = m.critical_strain(treat.hardness), None
|
|
382
|
+
if critical is not None:
|
|
383
|
+
critical = critical.reshape(ne, 4, -1)
|
|
384
|
+
radius = m.fracture.get("radius")
|
|
385
|
+
aniso = None
|
|
386
|
+
if m.anisotropy: # the rolling direction along x, the tests at their angles
|
|
387
|
+
aniso = m.yield_criterion(treat.treated.reshape(ne, 4, -1), angle=0.0)
|
|
388
|
+
membrane = Membrane(
|
|
389
|
+
cell.mesh,
|
|
390
|
+
flow,
|
|
391
|
+
young=m.young,
|
|
392
|
+
poisson=m.poisson,
|
|
393
|
+
thickness=self.specimen.thickness,
|
|
394
|
+
critical=critical,
|
|
395
|
+
fracture_radius=radius,
|
|
396
|
+
anisotropy=aniso,
|
|
397
|
+
)
|
|
398
|
+
path = self.path() # the measures of the path: on the specimen's parallel part
|
|
399
|
+
everywhere = np.ones(len(treat.points), dtype=bool)
|
|
400
|
+
results = {}
|
|
401
|
+
for d in self.directions or (0.0,):
|
|
402
|
+
t1 = time.perf_counter()
|
|
403
|
+
tens = cell_test(membrane, cell, float(d), keep_fields=keep_fields, **load)
|
|
404
|
+
measures = case_measures(self, path, treat, tens, inside=everywhere)
|
|
405
|
+
results[d] = SheetResult(path, treat, tens, measures, time.perf_counter() - t1)
|
|
406
|
+
if not self.directions:
|
|
407
|
+
return replace(results[0.0], time_s=time.perf_counter() - t0)
|
|
408
|
+
return self._combine(results, t0)
|
|
409
|
+
|
|
410
|
+
def _evaluate(self, keep_fields: bool) -> SheetResult:
|
|
411
|
+
t0 = time.perf_counter()
|
|
412
|
+
path = self.path()
|
|
413
|
+
load = dict(self.loading)
|
|
414
|
+
if load.pop("kind", "tension") == "bending":
|
|
415
|
+
return self._bend(path, load, t0)
|
|
416
|
+
mesh = self.specimen.mesh(self.element)
|
|
417
|
+
pts, _, wts = mesh.gauss()
|
|
418
|
+
treat = self.laser_treatment().apply(path, pts.reshape(-1, 2), wts.reshape(-1))
|
|
419
|
+
flow = tuple(v.reshape(len(mesh.quads), 4, -1) for v in treat.flow())
|
|
420
|
+
m = self.material
|
|
421
|
+
critical, radius = m.critical_strain(treat.hardness), None
|
|
422
|
+
if critical is not None:
|
|
423
|
+
critical = critical.reshape(len(mesh.quads), 4, -1)
|
|
424
|
+
radius = m.fracture.get("radius")
|
|
425
|
+
aniso = None
|
|
426
|
+
if m.anisotropy: # the rolling direction at -direction in the specimen
|
|
427
|
+
share = treat.treated.reshape(len(mesh.quads), 4, -1)
|
|
428
|
+
aniso = m.yield_criterion(share, angle=-getattr(self, "_direction", 0.0))
|
|
429
|
+
membrane = Membrane(
|
|
430
|
+
mesh,
|
|
431
|
+
flow,
|
|
432
|
+
young=m.young,
|
|
433
|
+
poisson=m.poisson,
|
|
434
|
+
thickness=self.specimen.thickness,
|
|
435
|
+
critical=critical,
|
|
436
|
+
fracture_radius=radius,
|
|
437
|
+
anisotropy=aniso,
|
|
438
|
+
)
|
|
439
|
+
tens = tensile_test(self.specimen, membrane, keep_fields=keep_fields, **load)
|
|
440
|
+
measures = case_measures(self, path, treat, tens)
|
|
441
|
+
return SheetResult(path, treat, tens, measures, time.perf_counter() - t0)
|
|
442
|
+
|
|
443
|
+
def _bend(self, path, load: dict, t0: float) -> SheetResult:
|
|
444
|
+
"""Three-point bending of the strip: the treatment at the fibres of its sections."""
|
|
445
|
+
x0, x1, y0, y1 = self.specimen.band()
|
|
446
|
+
span = float(load.get("span", 0.8 * (x1 - x0)))
|
|
447
|
+
if not 0 < span <= x1 - x0:
|
|
448
|
+
raise ValueError("bending: 0 < span <= the length of the strip")
|
|
449
|
+
ns = int(load.get("sections", max(21, round(span / self.element) + 1)))
|
|
450
|
+
ns += 1 - ns % 2 # odd: a section under the load
|
|
451
|
+
ny = max(4, round((y1 - y0) / self.element))
|
|
452
|
+
xc = 0.5 * (x0 + x1)
|
|
453
|
+
xs = np.linspace(xc - 0.5 * span, xc + 0.5 * span, ns)
|
|
454
|
+
ys = y0 + (np.arange(ny) + 0.5) * (y1 - y0) / ny
|
|
455
|
+
pts = np.column_stack([np.repeat(xs, ny), np.tile(ys, ns)])
|
|
456
|
+
dx = span / (ns - 1)
|
|
457
|
+
wts = np.full(len(pts), dx * (y1 - y0) / ny)
|
|
458
|
+
treat = self.laser_treatment().apply(path, pts, wts)
|
|
459
|
+
kind, s0, a, b = (v.reshape(ns, ny, -1) for v in treat.flow())
|
|
460
|
+
bend = three_point_bending(
|
|
461
|
+
kind,
|
|
462
|
+
s0,
|
|
463
|
+
a,
|
|
464
|
+
b,
|
|
465
|
+
span=span,
|
|
466
|
+
width=y1 - y0,
|
|
467
|
+
thickness=self.specimen.thickness,
|
|
468
|
+
young=self.material.young,
|
|
469
|
+
deflection=load.get("deflection"),
|
|
470
|
+
)
|
|
471
|
+
measures = case_measures(self, path, treat, None, bend)
|
|
472
|
+
return SheetResult(path, treat, None, measures, time.perf_counter() - t0, bending=bend)
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
def _set_dotted(mapping, dotted: str, value) -> None:
|
|
476
|
+
keys = dotted.split(".")
|
|
477
|
+
target = mapping
|
|
478
|
+
for i, k in enumerate(keys[:-1]):
|
|
479
|
+
nxt = keys[i + 1]
|
|
480
|
+
if isinstance(target, list):
|
|
481
|
+
k = int(k)
|
|
482
|
+
if isinstance(target, dict) and k not in target:
|
|
483
|
+
target[k] = [] if nxt.isdigit() else {}
|
|
484
|
+
target = target[k]
|
|
485
|
+
last = keys[-1]
|
|
486
|
+
if isinstance(target, list):
|
|
487
|
+
i = int(last)
|
|
488
|
+
while len(target) <= i:
|
|
489
|
+
target.append(0.0)
|
|
490
|
+
target[i] = value
|
|
491
|
+
else:
|
|
492
|
+
target[last] = value
|
|
493
|
+
return None
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
def _coerce_coefficients(pattern: dict) -> None:
|
|
497
|
+
if "coefficients" in pattern:
|
|
498
|
+
pattern["coefficients"] = [
|
|
499
|
+
list(map(float, row)) if isinstance(row, (list, tuple)) else row
|
|
500
|
+
for row in pattern["coefficients"]
|
|
501
|
+
]
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
def case_measures(
|
|
505
|
+
case: SheetCase,
|
|
506
|
+
path: LaserPath,
|
|
507
|
+
treat: TreatmentResult,
|
|
508
|
+
tens: TensileResult | None,
|
|
509
|
+
bend: BendingResult | None = None,
|
|
510
|
+
*,
|
|
511
|
+
inside=None,
|
|
512
|
+
) -> dict:
|
|
513
|
+
"""The measures (:data:`MEASURES`) of an evaluated case: those of the tensile or of
|
|
514
|
+
the bending test (NaN for the other), and those of the treated parallel part (or of
|
|
515
|
+
the points ``inside``: the periodic cell) and of the path."""
|
|
516
|
+
x0, x1, y0, y1 = case.specimen.band()
|
|
517
|
+
p = treat.points
|
|
518
|
+
if inside is None:
|
|
519
|
+
inside = (p[:, 0] >= x0) & (p[:, 0] <= x1) & (p[:, 1] >= y0) & (p[:, 1] <= y1)
|
|
520
|
+
w = treat.weights[inside]
|
|
521
|
+
share = treat.treated[inside]
|
|
522
|
+
hard = treat.hardness[inside]
|
|
523
|
+
out = dict.fromkeys(MEASURES, math.nan)
|
|
524
|
+
if tens is not None:
|
|
525
|
+
out.update(tens.summary())
|
|
526
|
+
out.pop("necked", None)
|
|
527
|
+
out["necked"] = bool(tens.necked)
|
|
528
|
+
if bend is not None:
|
|
529
|
+
out.update(bend.summary())
|
|
530
|
+
wsum = max(w.sum(), 1e-300)
|
|
531
|
+
out["volume_fraction"] = float((w[:, None] * share).sum() / (treat.layers * wsum))
|
|
532
|
+
out["area_fraction"] = float((w * (share.mean(axis=1) >= 0.5)).sum() / wsum)
|
|
533
|
+
out["mean_hardness"] = float((w[:, None] * hard).sum() / (treat.layers * wsum))
|
|
534
|
+
out["max_hardness"] = float(hard.max()) if hard.size else math.nan
|
|
535
|
+
out["melted_fraction"] = float(
|
|
536
|
+
(w[:, None] * treat.melted[inside]).sum() / (treat.layers * wsum)
|
|
537
|
+
)
|
|
538
|
+
out["peak_temperature"] = float(treat.peak.max()) if treat.peak.size else math.nan
|
|
539
|
+
lo, hi = (x0, y0), (x1, y1)
|
|
540
|
+
out["path_length"] = path.clipped_length(lo, hi) if len(path) else 0.0
|
|
541
|
+
out["laser_time"] = path.time if len(path) else 0.0
|
|
542
|
+
out["laser_energy"] = path.energy if len(path) else 0.0
|
|
543
|
+
out["min_gap"] = path.min_gap(lo, hi) if len(path) > 1 else math.inf
|
|
544
|
+
out["min_radius"] = path.min_radius() if len(path) else math.inf
|
|
545
|
+
return out
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
# -- optimization -------------------------------------------------------------------------
|
|
549
|
+
|
|
550
|
+
|
|
551
|
+
@dataclass
|
|
552
|
+
class Parameter:
|
|
553
|
+
"""A design variable: a dotted name (see :meth:`SheetCase.with_values`), its bounds,
|
|
554
|
+
whether it takes integer values."""
|
|
555
|
+
|
|
556
|
+
name: str
|
|
557
|
+
low: float
|
|
558
|
+
high: float
|
|
559
|
+
integer: bool = False
|
|
560
|
+
|
|
561
|
+
def __post_init__(self):
|
|
562
|
+
if not self.high > self.low:
|
|
563
|
+
raise ValueError(f"parameter {self.name}: high > low")
|
|
564
|
+
|
|
565
|
+
def value(self, u: float):
|
|
566
|
+
v = self.low + float(np.clip(u, 0.0, 1.0)) * (self.high - self.low)
|
|
567
|
+
return round(v) if self.integer else float(v)
|
|
568
|
+
|
|
569
|
+
def unit(self, value) -> float:
|
|
570
|
+
return (float(value) - self.low) / (self.high - self.low)
|
|
571
|
+
|
|
572
|
+
@classmethod
|
|
573
|
+
def from_config(cls, name: str, spec) -> Parameter:
|
|
574
|
+
if isinstance(spec, Parameter):
|
|
575
|
+
return spec
|
|
576
|
+
if isinstance(spec, dict):
|
|
577
|
+
return cls(
|
|
578
|
+
name, float(spec["low"]), float(spec["high"]), bool(spec.get("integer", False))
|
|
579
|
+
)
|
|
580
|
+
low, high = spec[:2]
|
|
581
|
+
integer = (
|
|
582
|
+
bool(spec[2]) if len(spec) > 2 else (isinstance(low, int) and isinstance(high, int))
|
|
583
|
+
)
|
|
584
|
+
return cls(name, float(low), float(high), integer)
|
|
585
|
+
|
|
586
|
+
|
|
587
|
+
@dataclass
|
|
588
|
+
class OptimizationResult:
|
|
589
|
+
"""The best values found, their evaluation, the objective and the history of every
|
|
590
|
+
evaluation (values, measures, objective, penalty, cost)."""
|
|
591
|
+
|
|
592
|
+
values: dict
|
|
593
|
+
result: SheetResult | None
|
|
594
|
+
objective: float
|
|
595
|
+
feasible: bool
|
|
596
|
+
history: list
|
|
597
|
+
method: str
|
|
598
|
+
evaluations: int
|
|
599
|
+
time_s: float
|
|
600
|
+
settings: dict = field(default_factory=dict)
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
def _is_measure(name: str) -> bool:
|
|
604
|
+
"""A measure, or a measure of one direction (``yield_strength_45``)."""
|
|
605
|
+
if name in MEASURES:
|
|
606
|
+
return True
|
|
607
|
+
base, _, angle = name.rpartition("_")
|
|
608
|
+
try:
|
|
609
|
+
float(angle)
|
|
610
|
+
except ValueError:
|
|
611
|
+
return False
|
|
612
|
+
return base in MEASURES
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
class _Problem:
|
|
616
|
+
"""The penalized cost of normalized designs, with a cache of the evaluations."""
|
|
617
|
+
|
|
618
|
+
def __init__(self, case, parameters, objective, constraints, target, penalty, callback):
|
|
619
|
+
self.case = case
|
|
620
|
+
self.parameters = parameters
|
|
621
|
+
self.objective = objective
|
|
622
|
+
self.constraints = {k: tuple(v) for k, v in (constraints or {}).items()}
|
|
623
|
+
for k in self.constraints:
|
|
624
|
+
if not _is_measure(k):
|
|
625
|
+
raise ValueError(f"constraint on {k!r}: one of the measures {MEASURES}")
|
|
626
|
+
self.target = dict(target or {})
|
|
627
|
+
if objective == "target":
|
|
628
|
+
if not self.target:
|
|
629
|
+
raise ValueError("objective target: give the target measures")
|
|
630
|
+
for k in self.target:
|
|
631
|
+
if not _is_measure(k):
|
|
632
|
+
raise ValueError(f"target {k!r}: one of the measures {MEASURES}")
|
|
633
|
+
elif objective not in OBJECTIVES:
|
|
634
|
+
raise ValueError(f"objective: one of {OBJECTIVES}")
|
|
635
|
+
self.penalty = float(penalty)
|
|
636
|
+
self.callback = callback
|
|
637
|
+
self.cache: dict = {}
|
|
638
|
+
self.history: list = []
|
|
639
|
+
self.results: dict = {}
|
|
640
|
+
self.scale = None
|
|
641
|
+
|
|
642
|
+
def values(self, u) -> dict:
|
|
643
|
+
return {p.name: p.value(x) for p, x in zip(self.parameters, np.atleast_1d(u), strict=True)}
|
|
644
|
+
|
|
645
|
+
def score(self, m: dict) -> float:
|
|
646
|
+
if self.objective == "target":
|
|
647
|
+
return -sum(((m[k] - v) / (abs(v) or 1.0)) ** 2 for k, v in self.target.items())
|
|
648
|
+
if self.objective == "isotropy":
|
|
649
|
+
return -float(m["yield_anisotropy"])
|
|
650
|
+
if self.objective == "flow_isotropy":
|
|
651
|
+
return -float(m["r_anisotropy"])
|
|
652
|
+
return float(m[self.objective])
|
|
653
|
+
|
|
654
|
+
def violation(self, m: dict) -> float:
|
|
655
|
+
total = 0.0
|
|
656
|
+
for k, (lo, hi) in self.constraints.items():
|
|
657
|
+
v = m[k]
|
|
658
|
+
if not np.isfinite(v):
|
|
659
|
+
v = 1e300 if v > 0 else -1e300
|
|
660
|
+
if lo is not None and v < lo:
|
|
661
|
+
total += min((lo - v) / (abs(lo) or 1.0), 10.0)
|
|
662
|
+
if hi is not None and v > hi:
|
|
663
|
+
total += min((v - hi) / (abs(hi) or 1.0), 10.0)
|
|
664
|
+
return total
|
|
665
|
+
|
|
666
|
+
def __call__(self, u) -> float:
|
|
667
|
+
vals = self.values(u)
|
|
668
|
+
key = tuple(round(v, 9) if isinstance(v, float) else v for v in vals.values())
|
|
669
|
+
if key in self.cache:
|
|
670
|
+
return self.cache[key]
|
|
671
|
+
case = self.case.with_values(vals)
|
|
672
|
+
_coerce_coefficients(case.pattern)
|
|
673
|
+
try:
|
|
674
|
+
res = case.evaluate()
|
|
675
|
+
m = res.measures
|
|
676
|
+
obj = self.score(m)
|
|
677
|
+
bad = not np.isfinite(obj)
|
|
678
|
+
except (ValueError, FloatingPointError, np.linalg.LinAlgError) as exc:
|
|
679
|
+
res, m, obj, bad = None, {"error": str(exc)}, math.nan, True
|
|
680
|
+
viol = self.violation(m) if not bad else 10.0
|
|
681
|
+
if self.scale is None and not bad and self.objective != "target":
|
|
682
|
+
self.scale = max(abs(obj), 1e-12)
|
|
683
|
+
scale = self.scale or 1.0
|
|
684
|
+
cost = (-obj / scale if not bad else 1.0) + self.penalty * viol
|
|
685
|
+
self.cache[key] = cost
|
|
686
|
+
row = {
|
|
687
|
+
"evaluation": len(self.history) + 1,
|
|
688
|
+
**vals,
|
|
689
|
+
**{k: m.get(k, math.nan) for k in MEASURES},
|
|
690
|
+
**{k: v for k, v in m.items() if k not in MEASURES and _is_measure(k)},
|
|
691
|
+
"objective": obj,
|
|
692
|
+
"violation": viol,
|
|
693
|
+
"cost": cost,
|
|
694
|
+
"feasible": (viol == 0.0 and not bad),
|
|
695
|
+
}
|
|
696
|
+
if "error" in m:
|
|
697
|
+
row["error"] = m["error"]
|
|
698
|
+
self.history.append(row)
|
|
699
|
+
self.results[key] = res
|
|
700
|
+
if self.callback is not None:
|
|
701
|
+
self.callback(row)
|
|
702
|
+
return cost
|
|
703
|
+
|
|
704
|
+
|
|
705
|
+
def optimize(
|
|
706
|
+
case: SheetCase,
|
|
707
|
+
parameters,
|
|
708
|
+
*,
|
|
709
|
+
objective: str = "strength_ductility",
|
|
710
|
+
constraints=None,
|
|
711
|
+
target=None,
|
|
712
|
+
method: str = "bayesian",
|
|
713
|
+
evaluations: int = 40,
|
|
714
|
+
initial: int | None = None,
|
|
715
|
+
levels=5,
|
|
716
|
+
penalty: float = 100.0,
|
|
717
|
+
seed: int = 0,
|
|
718
|
+
callback=None,
|
|
719
|
+
**options,
|
|
720
|
+
) -> OptimizationResult:
|
|
721
|
+
"""Optimize the parameters of a case (see the module). ``parameters``: a mapping of
|
|
722
|
+
dotted names to ``[low, high]`` (``[low, high, true]`` for integers) or
|
|
723
|
+
:class:`Parameter` s; ``constraints``: a mapping of measures to ``[low, high]``
|
|
724
|
+
(None for no bound); ``target``: the target measures of the objective ``target``;
|
|
725
|
+
``evaluations``: the budget of evaluations (``grid``: ``levels`` per parameter
|
|
726
|
+
instead); ``initial``: the first designs of the Bayesian optimization (Latin
|
|
727
|
+
hypercube; default 2 d + 2); ``options``: those of the SciPy methods."""
|
|
728
|
+
if method not in METHODS:
|
|
729
|
+
raise ValueError(f"method: one of {METHODS}")
|
|
730
|
+
params = [Parameter.from_config(k, v) for k, v in dict(parameters).items()]
|
|
731
|
+
if not params:
|
|
732
|
+
raise ValueError("parameters: at least one")
|
|
733
|
+
prob = _Problem(case, params, objective, constraints, target, penalty, callback)
|
|
734
|
+
rng = np.random.default_rng(seed)
|
|
735
|
+
d = len(params)
|
|
736
|
+
t0 = time.perf_counter()
|
|
737
|
+
if method == "grid":
|
|
738
|
+
lv = [levels] * d if np.ndim(levels) == 0 else list(levels)
|
|
739
|
+
axes = []
|
|
740
|
+
for p, n in zip(params, lv, strict=True):
|
|
741
|
+
n = int(n)
|
|
742
|
+
if p.integer:
|
|
743
|
+
vals = np.arange(int(p.low), int(p.high) + 1)
|
|
744
|
+
axes.append(
|
|
745
|
+
[p.unit(v) for v in vals]
|
|
746
|
+
if len(vals) <= n or n < 2
|
|
747
|
+
else list(np.linspace(0.0, 1.0, n))
|
|
748
|
+
)
|
|
749
|
+
else:
|
|
750
|
+
axes.append(list(np.linspace(0.0, 1.0, max(n, 1))) if n > 1 else [0.5])
|
|
751
|
+
for u in itertools.product(*axes):
|
|
752
|
+
prob(np.array(u))
|
|
753
|
+
elif method == "nelder_mead":
|
|
754
|
+
x0 = np.full(d, 0.5)
|
|
755
|
+
|
|
756
|
+
def boxed(u):
|
|
757
|
+
out = np.clip(u, 0.0, 1.0)
|
|
758
|
+
return prob(out) + 10.0 * float(np.sum((u - out) ** 2))
|
|
759
|
+
|
|
760
|
+
simplex = np.vstack([x0] + [x0 + 0.25 * np.eye(d)[i] for i in range(d)])
|
|
761
|
+
sopt.minimize(
|
|
762
|
+
boxed,
|
|
763
|
+
x0,
|
|
764
|
+
method="Nelder-Mead",
|
|
765
|
+
options={
|
|
766
|
+
"maxfev": evaluations,
|
|
767
|
+
"initial_simplex": simplex,
|
|
768
|
+
"xatol": 1e-3,
|
|
769
|
+
"fatol": 1e-6,
|
|
770
|
+
**options,
|
|
771
|
+
},
|
|
772
|
+
)
|
|
773
|
+
elif method == "differential_evolution":
|
|
774
|
+
popsize = int(options.pop("popsize", 6))
|
|
775
|
+
maxiter = max(1, evaluations // (popsize * d) - 1)
|
|
776
|
+
sopt.differential_evolution(
|
|
777
|
+
prob,
|
|
778
|
+
[(0.0, 1.0)] * d,
|
|
779
|
+
maxiter=maxiter,
|
|
780
|
+
popsize=popsize,
|
|
781
|
+
polish=False,
|
|
782
|
+
init="latinhypercube",
|
|
783
|
+
tol=0.0,
|
|
784
|
+
**_seeded(sopt.differential_evolution, seed),
|
|
785
|
+
**options,
|
|
786
|
+
)
|
|
787
|
+
elif method == "genetic":
|
|
788
|
+
from morphogen.design.search import genetic_algorithm
|
|
789
|
+
|
|
790
|
+
size = int(options.pop("population", max(6, 2 * d + 2)))
|
|
791
|
+
gens = max(1, evaluations // size - 1)
|
|
792
|
+
pop = [rng.random(d) for _ in range(size)]
|
|
793
|
+
|
|
794
|
+
def mutate(x, r):
|
|
795
|
+
return np.clip(x + r.normal(0.0, 0.1, d), 0.0, 1.0)
|
|
796
|
+
|
|
797
|
+
def crossover(a, b, r):
|
|
798
|
+
w = r.random(d)
|
|
799
|
+
return w * a + (1 - w) * b
|
|
800
|
+
|
|
801
|
+
genetic_algorithm(
|
|
802
|
+
pop,
|
|
803
|
+
prob,
|
|
804
|
+
rng,
|
|
805
|
+
mutate=mutate,
|
|
806
|
+
crossover=crossover,
|
|
807
|
+
generations=gens,
|
|
808
|
+
elite=1,
|
|
809
|
+
tournament=2,
|
|
810
|
+
)
|
|
811
|
+
else:
|
|
812
|
+
_bayesian(prob, d, evaluations, initial if initial is not None else 2 * d + 2, rng)
|
|
813
|
+
hist = prob.history
|
|
814
|
+
if not hist:
|
|
815
|
+
raise RuntimeError("no evaluation")
|
|
816
|
+
feasible = [h for h in hist if h["feasible"]]
|
|
817
|
+
pool = feasible or hist
|
|
818
|
+
best = min(pool, key=lambda h: h["cost"])
|
|
819
|
+
values = {p.name: best[p.name] for p in params}
|
|
820
|
+
key = tuple(round(v, 9) if isinstance(v, float) else v for v in values.values())
|
|
821
|
+
return OptimizationResult(
|
|
822
|
+
values=values,
|
|
823
|
+
result=prob.results.get(key),
|
|
824
|
+
objective=best["objective"],
|
|
825
|
+
feasible=bool(best["feasible"]),
|
|
826
|
+
history=hist,
|
|
827
|
+
method=method,
|
|
828
|
+
evaluations=len(hist),
|
|
829
|
+
time_s=time.perf_counter() - t0,
|
|
830
|
+
settings={
|
|
831
|
+
"objective": objective,
|
|
832
|
+
"constraints": prob.constraints,
|
|
833
|
+
"target": prob.target,
|
|
834
|
+
"parameters": {p.name: [p.low, p.high, p.integer] for p in params},
|
|
835
|
+
},
|
|
836
|
+
)
|
|
837
|
+
|
|
838
|
+
|
|
839
|
+
# -- Bayesian optimization ----------------------------------------------------------------
|
|
840
|
+
|
|
841
|
+
|
|
842
|
+
def _seeded(func, value) -> dict:
|
|
843
|
+
"""The seed keyword of a SciPy function: ``rng`` from SciPy 1.15, ``seed`` before."""
|
|
844
|
+
import inspect
|
|
845
|
+
|
|
846
|
+
return {"rng" if "rng" in inspect.signature(func).parameters else "seed": value}
|
|
847
|
+
|
|
848
|
+
|
|
849
|
+
def _matern52(x1, x2, ls):
|
|
850
|
+
d = np.sqrt(np.maximum(((x1[:, None, :] - x2[None, :, :]) / ls) ** 2, 0.0).sum(axis=-1))
|
|
851
|
+
s5 = math.sqrt(5.0) * d
|
|
852
|
+
return (1.0 + s5 + 5.0 / 3.0 * d * d) * np.exp(-s5)
|
|
853
|
+
|
|
854
|
+
|
|
855
|
+
class GaussianProcess:
|
|
856
|
+
"""Gaussian process regression of costs on the unit cube: a constant mean, a Matérn
|
|
857
|
+
5/2 kernel with a length scale per dimension, a nugget; the hyperparameters maximize
|
|
858
|
+
the marginal likelihood (L-BFGS-B from a few starts)."""
|
|
859
|
+
|
|
860
|
+
def __init__(self, x, y, *, seed: int = 0):
|
|
861
|
+
self.x = np.asarray(x, dtype=float)
|
|
862
|
+
y = np.asarray(y, dtype=float)
|
|
863
|
+
self.mu, self.sd = float(y.mean()), float(y.std() or 1.0)
|
|
864
|
+
self.y = (y - self.mu) / self.sd
|
|
865
|
+
d = self.x.shape[1]
|
|
866
|
+
rng = np.random.default_rng(seed)
|
|
867
|
+
best = None
|
|
868
|
+
starts = [np.r_[np.full(d, np.log(0.3)), np.log(1e-3)]]
|
|
869
|
+
starts += [np.r_[rng.uniform(np.log(0.05), np.log(2.0), d), np.log(1e-2)] for _ in range(3)]
|
|
870
|
+
bounds = [(np.log(0.02), np.log(10.0))] * d + [(np.log(1e-8), np.log(0.5))]
|
|
871
|
+
for s in starts:
|
|
872
|
+
try:
|
|
873
|
+
r = sopt.minimize(self._nll, s, method="L-BFGS-B", bounds=bounds)
|
|
874
|
+
except (np.linalg.LinAlgError, ValueError):
|
|
875
|
+
continue
|
|
876
|
+
if best is None or r.fun < best.fun:
|
|
877
|
+
best = r
|
|
878
|
+
theta = best.x if best is not None else starts[0]
|
|
879
|
+
self._set(theta)
|
|
880
|
+
|
|
881
|
+
def _factor(self, theta):
|
|
882
|
+
d = self.x.shape[1]
|
|
883
|
+
ls, nug = np.exp(theta[:d]), np.exp(theta[d])
|
|
884
|
+
k = _matern52(self.x, self.x, ls) + (nug + 1e-10) * np.eye(len(self.x))
|
|
885
|
+
return np.linalg.cholesky(k), ls
|
|
886
|
+
|
|
887
|
+
def _nll(self, theta):
|
|
888
|
+
try:
|
|
889
|
+
c, _ = self._factor(theta)
|
|
890
|
+
except np.linalg.LinAlgError:
|
|
891
|
+
return 1e10
|
|
892
|
+
alpha = np.linalg.solve(c.T, np.linalg.solve(c, self.y))
|
|
893
|
+
return 0.5 * self.y @ alpha + np.log(np.diag(c)).sum()
|
|
894
|
+
|
|
895
|
+
def _set(self, theta):
|
|
896
|
+
self.chol, self.ls = self._factor(theta)
|
|
897
|
+
self.alpha = np.linalg.solve(self.chol.T, np.linalg.solve(self.chol, self.y))
|
|
898
|
+
|
|
899
|
+
def predict(self, xs) -> tuple[np.ndarray, np.ndarray]:
|
|
900
|
+
"""Mean and standard deviation of the costs at points of the cube."""
|
|
901
|
+
ks = _matern52(np.atleast_2d(xs), self.x, self.ls)
|
|
902
|
+
mean = ks @ self.alpha
|
|
903
|
+
v = np.linalg.solve(self.chol, ks.T)
|
|
904
|
+
var = np.maximum(1.0 - (v * v).sum(axis=0), 1e-12)
|
|
905
|
+
return self.mu + self.sd * mean, self.sd * np.sqrt(var)
|
|
906
|
+
|
|
907
|
+
|
|
908
|
+
def expected_improvement(mean, std, best: float) -> np.ndarray:
|
|
909
|
+
"""Expected improvement of costs below ``best`` (minimization)."""
|
|
910
|
+
z = (best - mean) / std
|
|
911
|
+
return (best - mean) * norm.cdf(z) + std * norm.pdf(z)
|
|
912
|
+
|
|
913
|
+
|
|
914
|
+
def _bayesian(prob, d: int, evaluations: int, initial: int, rng) -> None:
|
|
915
|
+
initial = max(2, min(int(initial), evaluations))
|
|
916
|
+
sampler = qmc.LatinHypercube(d=d, **_seeded(qmc.LatinHypercube, rng))
|
|
917
|
+
xs = list(sampler.random(initial))
|
|
918
|
+
ys = [prob(x) for x in xs]
|
|
919
|
+
while len(prob.history) < evaluations:
|
|
920
|
+
x_arr, y_arr = np.array(xs), np.array(ys)
|
|
921
|
+
ok = np.isfinite(y_arr)
|
|
922
|
+
gp = GaussianProcess(x_arr[ok], y_arr[ok], seed=int(rng.integers(1 << 31)))
|
|
923
|
+
best = float(y_arr[ok].min())
|
|
924
|
+
cand = qmc.Sobol(d=d, **_seeded(qmc.Sobol, rng)).random(1024)
|
|
925
|
+
xb = x_arr[ok][np.argmin(y_arr[ok])]
|
|
926
|
+
local = np.clip(xb + rng.normal(0.0, 0.05, (256, d)), 0.0, 1.0)
|
|
927
|
+
cand = np.vstack([cand, local])
|
|
928
|
+
m, s = gp.predict(cand)
|
|
929
|
+
ei = expected_improvement(m, s, best)
|
|
930
|
+
# keep away from the evaluated designs (the cache would return them)
|
|
931
|
+
dist = np.min(np.linalg.norm(cand[:, None, :] - x_arr[None, :, :], axis=-1), axis=1)
|
|
932
|
+
ei[dist < 1e-3] = -1.0
|
|
933
|
+
x_new = cand[int(np.argmax(ei))]
|
|
934
|
+
xs.append(x_new)
|
|
935
|
+
before = len(prob.history)
|
|
936
|
+
ys.append(prob(x_new))
|
|
937
|
+
if len(prob.history) == before: # a cached design: a random one instead
|
|
938
|
+
x_new = rng.random(d)
|
|
939
|
+
xs.append(x_new)
|
|
940
|
+
ys.append(prob(x_new))
|