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,700 @@
|
|
|
1
|
+
"""Isogeometric shape optimization: the control points of the geometry as the design.
|
|
2
|
+
|
|
3
|
+
In an isogeometric analysis the geometry is its control points, and moving them moves
|
|
4
|
+
the boundary exactly and smoothly: they are the natural variables of a shape
|
|
5
|
+
optimization (Wall, Frenzel & Cyron 2008; Qian 2010), without the remeshing and the
|
|
6
|
+
jagged boundaries of the methods that move the nodes of a mesh. Three levels:
|
|
7
|
+
|
|
8
|
+
* the *variables* ``x``: each moves some control points of the design along given
|
|
9
|
+
directions (:meth:`ShapeDesign.variable`; :meth:`ShapeDesign.radial` scales the control
|
|
10
|
+
points of a hole about its centre, with the symmetries of the cell). With the
|
|
11
|
+
``symmetry`` of the pattern — mirrors, rotations (:func:`mirror`, :func:`rotation`),
|
|
12
|
+
and the periods of the cell — a variable moves the images of its control points as
|
|
13
|
+
well: the design keeps its symmetry, and the control points of the boundary of a
|
|
14
|
+
cell that are a period apart move together;
|
|
15
|
+
* the *design*, a coarse assembly whose control points are ``P(x) = P_0 + M x``;
|
|
16
|
+
* the *analysis*, a refinement of the design (elements cut, degree raised): for given
|
|
17
|
+
weights its control points are linear in those of the design, ``Q = T P``
|
|
18
|
+
(:meth:`~morphogen.iga.geometry.Multipatch.refinement`). The geometry is the same at
|
|
19
|
+
both levels; the design keeps few variables, the analysis its accuracy.
|
|
20
|
+
|
|
21
|
+
Sensitivities. Let ``A(u, v) = int (E_u + eps(u)) : D : (E_v + eps(v)) dOmega`` for two
|
|
22
|
+
fields of given unknowns and uniform strains. Moving the control point ``a`` by ``dQ``
|
|
23
|
+
moves the points by ``V = R_a dQ``; then ``d(dOmega) = div V dOmega`` and ``d(grad u) =
|
|
24
|
+
-grad u grad V``, so that::
|
|
25
|
+
|
|
26
|
+
dA / dQ_a = int Sigma grad R_a dOmega,
|
|
27
|
+
Sigma = (eps_u : D : eps_v) 1 - grad u^T sigma_v - grad v^T sigma_u,
|
|
28
|
+
|
|
29
|
+
the energy-momentum tensor of Eshelby for the pair: the gradients are *analytical*, one
|
|
30
|
+
integral per pair of fields and no further solution. For a structure under given loads
|
|
31
|
+
(``K u = f``) the compliance ``c = f . u`` has ``dc/dQ = -dA(u, u)/dQ``; for a periodic
|
|
32
|
+
cell the effective tensor is ``C_IJ = A(chi_I, chi_J) / |Y|`` with the fluctuations of
|
|
33
|
+
:mod:`morphogen.iga.homogenization`, and ``dC_IJ/dQ = (dA/dQ) / |Y|`` since each
|
|
34
|
+
fluctuation makes its energy stationary. The area of the material has ``dA/dQ_a = int
|
|
35
|
+
grad R_a dOmega``. The chain ``d/dx = M^T T^T d/dQ`` brings them to the variables.
|
|
36
|
+
|
|
37
|
+
Optimization (:func:`optimize`, :func:`optimize_cell`, :func:`optimize_structure`):
|
|
38
|
+
sequential quadratic programming (SLSQP of SciPy) or the method of moving asymptotes
|
|
39
|
+
(:mod:`morphogen.optimization.mma`), with bounds on the variables that keep the patches
|
|
40
|
+
from folding. The objectives and constraints of a cell are functions of its effective
|
|
41
|
+
tensor and of its fraction of material — a modulus, Poisson's ratio, the distance to a
|
|
42
|
+
target tensor —, differentiated numerically with respect to these few numbers; linear
|
|
43
|
+
constraints on the variables (``linear``) keep sizes of the geometry — the width of a
|
|
44
|
+
ligament, the thickness of a member — since the control points are linear in them.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
from __future__ import annotations
|
|
48
|
+
|
|
49
|
+
import itertools
|
|
50
|
+
import math
|
|
51
|
+
import time
|
|
52
|
+
from collections.abc import Callable
|
|
53
|
+
from dataclasses import dataclass, field
|
|
54
|
+
|
|
55
|
+
import numpy as np
|
|
56
|
+
import scipy.optimize
|
|
57
|
+
from scipy.spatial import cKDTree
|
|
58
|
+
|
|
59
|
+
from morphogen.iga.analysis import Analysis
|
|
60
|
+
from morphogen.iga.geometry import Multipatch, Patch
|
|
61
|
+
from morphogen.iga.homogenization import Cell, CellSolution
|
|
62
|
+
|
|
63
|
+
METHODS = ("slsqp", "mma")
|
|
64
|
+
SYMMETRIES = (None, "d2", "d4")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
#: The largest group of symmetries of a design (those of a cubic cell are 48)
|
|
68
|
+
_GROUP = 192
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class FoldedDesign(ValueError):
|
|
72
|
+
"""The variables of a design fold one of its patches (a Jacobian that is not
|
|
73
|
+
positive): no analysis there."""
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def mirror(axis: int, at: float = 0.0, dim: int = 2) -> tuple[np.ndarray, np.ndarray]:
|
|
77
|
+
"""The mirror in the line (plane) where the coordinate ``axis`` is ``at``, as an
|
|
78
|
+
operation ``x -> matrix x + shift`` (for the ``symmetry`` of a variable)."""
|
|
79
|
+
matrix, shift = np.eye(dim), np.zeros(dim)
|
|
80
|
+
matrix[axis, axis] = -1.0
|
|
81
|
+
shift[axis] = 2.0 * float(at)
|
|
82
|
+
return matrix, shift
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def rotation(angle: float, centre=(0.0, 0.0)) -> tuple[np.ndarray, np.ndarray]:
|
|
86
|
+
"""The rotation of the plane by ``angle`` (degrees, anticlockwise) about ``centre``,
|
|
87
|
+
as an operation ``x -> matrix x + shift`` (for the ``symmetry`` of a variable)."""
|
|
88
|
+
turn = round(float(angle) / 90.0)
|
|
89
|
+
if abs(float(angle) - 90.0 * turn) < 1e-12: # exact quarter-turns
|
|
90
|
+
c, s = [(1.0, 0.0), (0.0, 1.0), (-1.0, 0.0), (0.0, -1.0)][turn % 4]
|
|
91
|
+
else:
|
|
92
|
+
c, s = math.cos(math.radians(angle)), math.sin(math.radians(angle))
|
|
93
|
+
matrix = np.array([[c, -s], [s, c]])
|
|
94
|
+
centre = np.asarray(centre, dtype=float)
|
|
95
|
+
return matrix, centre - matrix @ centre
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _group(operations, lattice, dim: int) -> list[tuple[np.ndarray, np.ndarray]]:
|
|
99
|
+
"""The operations ``x -> matrix x + shift`` that given ones generate, the shifts
|
|
100
|
+
counted up to the periods of ``lattice`` (when there is one)."""
|
|
101
|
+
inverse = None if lattice is None else np.linalg.inv(lattice)
|
|
102
|
+
|
|
103
|
+
def reduced(matrix, shift):
|
|
104
|
+
if inverse is not None:
|
|
105
|
+
share = (shift @ inverse) % 1.0
|
|
106
|
+
share[share > 1.0 - 1e-7] = 0.0
|
|
107
|
+
shift = share @ lattice
|
|
108
|
+
key = (tuple(np.round(matrix, 6).ravel() + 0.0), tuple(np.round(shift, 6) + 0.0))
|
|
109
|
+
return key, (matrix, shift)
|
|
110
|
+
|
|
111
|
+
generators = [(np.eye(dim), np.zeros(dim))]
|
|
112
|
+
for matrix, shift in operations:
|
|
113
|
+
matrix, shift = np.asarray(matrix, dtype=float), np.asarray(shift, dtype=float)
|
|
114
|
+
if matrix.shape != (dim, dim) or shift.shape != (dim,):
|
|
115
|
+
raise ValueError(f"symmetry: operations (matrix, shift) of {dim} dimensions")
|
|
116
|
+
if np.abs(matrix @ matrix.T - np.eye(dim)).max() > 1e-9:
|
|
117
|
+
raise ValueError("symmetry: mirrors and rotations (orthogonal matrices)")
|
|
118
|
+
generators.append((matrix, shift))
|
|
119
|
+
group = dict(reduced(m, t) for m, t in generators)
|
|
120
|
+
frontier = list(group.values())
|
|
121
|
+
while frontier:
|
|
122
|
+
found = []
|
|
123
|
+
for m1, t1 in frontier:
|
|
124
|
+
for m2, t2 in generators[1:]:
|
|
125
|
+
key, operation = reduced(m1 @ m2, m1 @ t2 + t1)
|
|
126
|
+
if key not in group:
|
|
127
|
+
group[key] = operation
|
|
128
|
+
found.append(operation)
|
|
129
|
+
if len(group) > _GROUP:
|
|
130
|
+
raise ValueError(
|
|
131
|
+
"symmetry: these operations do not make a finite group (up to the periods "
|
|
132
|
+
"of the lattice of the design)"
|
|
133
|
+
)
|
|
134
|
+
frontier = found
|
|
135
|
+
return list(group.values())
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def stress_tensors(flux: np.ndarray, dim: int, nd: int) -> np.ndarray:
|
|
139
|
+
"""The fluxes of the points as tensors (... x unknowns x dim): the stress tensors of
|
|
140
|
+
Voigt's components (elasticity), or the flux vectors as one row (conduction)."""
|
|
141
|
+
if nd == 1:
|
|
142
|
+
return flux[..., None, :]
|
|
143
|
+
out = np.empty((*flux.shape[:-1], dim, dim))
|
|
144
|
+
if dim == 2:
|
|
145
|
+
out[..., 0, 0], out[..., 1, 1] = flux[..., 0], flux[..., 1]
|
|
146
|
+
out[..., 0, 1] = out[..., 1, 0] = flux[..., 2]
|
|
147
|
+
else:
|
|
148
|
+
for k in range(3):
|
|
149
|
+
out[..., k, k] = flux[..., k]
|
|
150
|
+
out[..., 1, 2] = out[..., 2, 1] = flux[..., 3]
|
|
151
|
+
out[..., 0, 2] = out[..., 2, 0] = flux[..., 4]
|
|
152
|
+
out[..., 0, 1] = out[..., 1, 0] = flux[..., 5]
|
|
153
|
+
return out
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def energy_gradients(analysis: Analysis, fields, uniform=None) -> np.ndarray:
|
|
157
|
+
"""The derivatives of ``A(u_i, u_j)`` (see the module) with respect to the control
|
|
158
|
+
points of the analysis, for the fields ``fields`` (unknowns x m) and their uniform
|
|
159
|
+
strains ``uniform`` (components x m; none by default): m x m x control points x
|
|
160
|
+
dim."""
|
|
161
|
+
fields = np.asarray(fields, dtype=float)
|
|
162
|
+
fields = fields[:, None] if fields.ndim == 1 else fields
|
|
163
|
+
m = fields.shape[1]
|
|
164
|
+
model, dim, nd = analysis.model, analysis.dim, analysis.nd
|
|
165
|
+
out = np.zeros((m, m, model.n_nodes, dim))
|
|
166
|
+
eye = np.eye(dim)
|
|
167
|
+
for pts, b, d, dofs in analysis.points():
|
|
168
|
+
ue = fields[dofs] # elements x unknowns of the element x m
|
|
169
|
+
measure = np.einsum("eqsi,eim->eqsm", b, ue)
|
|
170
|
+
if uniform is not None:
|
|
171
|
+
measure = measure + np.asarray(uniform, dtype=float)[None, None]
|
|
172
|
+
flux = np.einsum("st,eqtm->eqsm", d, measure)
|
|
173
|
+
ua = ue.reshape(len(dofs), -1, nd, m)
|
|
174
|
+
grad = np.einsum("eqak,eacm->eqmck", pts.gradients, ua) # of the unknowns
|
|
175
|
+
sigma = stress_tensors(np.moveaxis(flux, -1, 2), dim, nd) # elements x points x m x ...
|
|
176
|
+
for i in range(m):
|
|
177
|
+
for j in range(i, m):
|
|
178
|
+
energy = np.einsum("eqs,eqs->eq", measure[..., i], flux[..., j])
|
|
179
|
+
tensor = energy[..., None, None] * eye
|
|
180
|
+
tensor = tensor - np.einsum("eqck,eqcj->eqkj", grad[:, :, i], sigma[:, :, j])
|
|
181
|
+
tensor = tensor - np.einsum("eqck,eqcj->eqkj", grad[:, :, j], sigma[:, :, i])
|
|
182
|
+
g = np.einsum("eq,eqkj,eqaj->eak", pts.weights, tensor, pts.gradients)
|
|
183
|
+
np.add.at(out[i, j], pts.nodes, g)
|
|
184
|
+
for i in range(m):
|
|
185
|
+
for j in range(i):
|
|
186
|
+
out[i, j] = out[j, i]
|
|
187
|
+
return out
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def measure_gradient(analysis: Analysis) -> np.ndarray:
|
|
191
|
+
"""The derivative of the area (volume) of the assembly with respect to its control
|
|
192
|
+
points: ``int grad R_a`` (control points x dim)."""
|
|
193
|
+
out = np.zeros((analysis.model.n_nodes, analysis.dim))
|
|
194
|
+
for pts, _, _, _ in analysis.points():
|
|
195
|
+
np.add.at(out, pts.nodes, np.einsum("eq,eqak->eak", pts.weights, pts.gradients))
|
|
196
|
+
return out
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
class ShapeDesign:
|
|
200
|
+
"""A design (see the module): the coarse assembly ``model`` and the refinement of
|
|
201
|
+
its analysis (``subdivisions`` of every element and degrees raised by ``elevate``,
|
|
202
|
+
one value or one per direction). Variables are added by :meth:`variable` and
|
|
203
|
+
:meth:`radial`."""
|
|
204
|
+
|
|
205
|
+
def __init__(self, model, *, subdivisions=4, elevate=1):
|
|
206
|
+
if isinstance(model, Patch):
|
|
207
|
+
model = Multipatch(model)
|
|
208
|
+
self.model = model
|
|
209
|
+
self.fine, self.matrix = model.refinement(subdivisions, elevate)
|
|
210
|
+
self._moves: list[tuple[np.ndarray, np.ndarray]] = []
|
|
211
|
+
self.lower: list[float] = []
|
|
212
|
+
self.upper: list[float] = []
|
|
213
|
+
self.names: list[str] = []
|
|
214
|
+
|
|
215
|
+
@property
|
|
216
|
+
def n(self) -> int:
|
|
217
|
+
"""The number of variables."""
|
|
218
|
+
return len(self._moves)
|
|
219
|
+
|
|
220
|
+
@property
|
|
221
|
+
def moves(self) -> list[tuple[np.ndarray, np.ndarray]]:
|
|
222
|
+
"""For each variable, the control points of the design that it moves and their
|
|
223
|
+
directions (the moves of a unit of the variable)."""
|
|
224
|
+
return [(nodes.copy(), directions.copy()) for nodes, directions in self._moves]
|
|
225
|
+
|
|
226
|
+
def variable(self, nodes, directions, lower: float = -np.inf, upper: float = np.inf,
|
|
227
|
+
name: str | None = None, symmetry=None) -> int: # fmt: skip
|
|
228
|
+
"""A variable that moves the control points ``nodes`` of the design by its value
|
|
229
|
+
times their ``directions`` (one vector each, or one for all); returns its index.
|
|
230
|
+
|
|
231
|
+
``symmetry``: operations ``(matrix, shift)`` that map the design onto itself,
|
|
232
|
+
``x -> matrix x + shift`` (:func:`mirror`, :func:`rotation`), up to the periods
|
|
233
|
+
of its ``lattice``. The variable then moves the images of its control points by
|
|
234
|
+
all the operations that these generate, along the images of their directions —
|
|
235
|
+
``nodes`` are those of one copy; a control point that an operation leaves in
|
|
236
|
+
place keeps the part of its direction that the operation keeps. With an empty
|
|
237
|
+
list, only the control points a period apart move together."""
|
|
238
|
+
nodes = np.atleast_1d(np.asarray(nodes, dtype=np.int64))
|
|
239
|
+
directions = np.broadcast_to(
|
|
240
|
+
np.asarray(directions, dtype=float), (len(nodes), self.model.dim)
|
|
241
|
+
).copy()
|
|
242
|
+
if nodes.size == 0 or nodes.min() < 0 or nodes.max() >= self.model.n_nodes:
|
|
243
|
+
raise ValueError("variable: control points of the design")
|
|
244
|
+
if not lower < upper:
|
|
245
|
+
raise ValueError("variable: lower < upper")
|
|
246
|
+
if symmetry is not None:
|
|
247
|
+
nodes, directions = self._images(nodes, directions, symmetry)
|
|
248
|
+
self._moves.append((nodes, directions))
|
|
249
|
+
self.lower.append(float(lower))
|
|
250
|
+
self.upper.append(float(upper))
|
|
251
|
+
self.names.append(name or f"x{len(self._moves)}")
|
|
252
|
+
return len(self._moves) - 1
|
|
253
|
+
|
|
254
|
+
def _images(self, nodes, directions, symmetry) -> tuple[np.ndarray, np.ndarray]:
|
|
255
|
+
"""The control points that the symmetry maps those of a variable onto, and their
|
|
256
|
+
directions."""
|
|
257
|
+
model = self.model
|
|
258
|
+
group = _group(symmetry, model.lattice, model.dim)
|
|
259
|
+
periods = np.zeros((1, model.dim))
|
|
260
|
+
if model.lattice is not None:
|
|
261
|
+
combos = itertools.product(range(-3, 4), repeat=model.dim)
|
|
262
|
+
periods = np.array(list(combos), dtype=float) @ model.lattice
|
|
263
|
+
tree = cKDTree(model.nodes)
|
|
264
|
+
tolerance = 1e-6 * float(np.ptp(model.nodes, axis=0).max())
|
|
265
|
+
moves: dict[int, np.ndarray] = {}
|
|
266
|
+
for node, direction in zip(nodes, directions, strict=True):
|
|
267
|
+
images: dict[int, list] = {}
|
|
268
|
+
for matrix, shift in group:
|
|
269
|
+
distance, found = tree.query(matrix @ model.nodes[node] + shift + periods)
|
|
270
|
+
found = found[distance <= tolerance]
|
|
271
|
+
if not len(found):
|
|
272
|
+
raise ValueError(
|
|
273
|
+
f"symmetry: no control point at an image of the control point {node}; "
|
|
274
|
+
"the operations must map the design onto itself"
|
|
275
|
+
)
|
|
276
|
+
for other in found:
|
|
277
|
+
images.setdefault(int(other), []).append(matrix @ direction)
|
|
278
|
+
for other, parts in images.items(): # as many operations for each image
|
|
279
|
+
moves[other] = moves.get(other, 0.0) + np.sum(parts, axis=0) / len(images[node])
|
|
280
|
+
ids = np.array(sorted(moves), dtype=np.int64)
|
|
281
|
+
out = np.array([moves[k] for k in ids])
|
|
282
|
+
if np.abs(out).max() < 1e-12 * max(float(np.abs(directions).max()), 1e-300):
|
|
283
|
+
raise ValueError("symmetry: it leaves nothing of the move of this variable")
|
|
284
|
+
return ids, out
|
|
285
|
+
|
|
286
|
+
def radial(self, nodes, centre, lower: float = -0.3, upper: float = 0.3,
|
|
287
|
+
symmetry: str | None = None) -> list[int]: # fmt: skip
|
|
288
|
+
"""Variables that scale the positions of control points about ``centre``: ``P =
|
|
289
|
+
centre + (1 + x) (P_0 - centre)``, ``x`` between ``lower`` and ``upper``. One
|
|
290
|
+
variable per control point, or per set of control points that the ``symmetry``
|
|
291
|
+
of the cell maps onto each other: ``"d2"`` (the two mirrors of a rectangle
|
|
292
|
+
through the centre) or ``"d4"`` (those of a square, diagonals included)."""
|
|
293
|
+
if symmetry not in SYMMETRIES:
|
|
294
|
+
raise ValueError(f"symmetry: one of {SYMMETRIES}")
|
|
295
|
+
nodes = np.unique(np.asarray(nodes, dtype=np.int64))
|
|
296
|
+
offsets = self.model.nodes[nodes] - np.asarray(centre, dtype=float)
|
|
297
|
+
if symmetry is None:
|
|
298
|
+
groups = [[k] for k in range(len(nodes))]
|
|
299
|
+
else:
|
|
300
|
+
folded = np.abs(offsets[:, :2])
|
|
301
|
+
if symmetry == "d4":
|
|
302
|
+
folded = np.sort(folded, axis=1)
|
|
303
|
+
scale = float(np.abs(offsets).max()) or 1.0
|
|
304
|
+
keys = np.round(folded / (1e-7 * scale)).astype(np.int64)
|
|
305
|
+
_, inverse = np.unique(keys, axis=0, return_inverse=True)
|
|
306
|
+
inverse = inverse.ravel()
|
|
307
|
+
groups = [np.flatnonzero(inverse == g).tolist() for g in range(inverse.max() + 1)]
|
|
308
|
+
return [self.variable(nodes[g], offsets[g], lower, upper) for g in groups]
|
|
309
|
+
|
|
310
|
+
# -- geometries ------------------------------------------------------------------------
|
|
311
|
+
|
|
312
|
+
def bounds(self) -> tuple[np.ndarray, np.ndarray]:
|
|
313
|
+
return np.array(self.lower), np.array(self.upper)
|
|
314
|
+
|
|
315
|
+
def control(self, x) -> np.ndarray:
|
|
316
|
+
"""The control points of the design for the variables ``x``."""
|
|
317
|
+
x = np.asarray(x, dtype=float)
|
|
318
|
+
if x.shape != (self.n,):
|
|
319
|
+
raise ValueError(f"x: {self.n} variables")
|
|
320
|
+
nodes = self.model.nodes.copy()
|
|
321
|
+
for value, (ids, directions) in zip(x, self._moves, strict=True):
|
|
322
|
+
np.add.at(nodes, ids, value * directions)
|
|
323
|
+
return nodes
|
|
324
|
+
|
|
325
|
+
def design_model(self, x) -> Multipatch:
|
|
326
|
+
"""The design moved by the variables ``x``."""
|
|
327
|
+
return self.model.with_nodes(self.control(x))
|
|
328
|
+
|
|
329
|
+
def analysis_model(self, x) -> Multipatch:
|
|
330
|
+
"""The refined assembly of the analysis for the variables ``x``; a
|
|
331
|
+
:class:`FoldedDesign` if a patch of the design folds there (a negative Jacobian,
|
|
332
|
+
its boundary included: :meth:`~morphogen.iga.geometry.Multipatch.jacobians`)."""
|
|
333
|
+
control = self.control(x)
|
|
334
|
+
low, high = self.model.with_nodes(control).jacobians()
|
|
335
|
+
if low < -1e-9 * high:
|
|
336
|
+
raise FoldedDesign(
|
|
337
|
+
"a patch of the design folds for these variables (a negative Jacobian); "
|
|
338
|
+
"tighten their bounds"
|
|
339
|
+
)
|
|
340
|
+
return self.fine.with_nodes(self.matrix @ control)
|
|
341
|
+
|
|
342
|
+
def pull(self, gradient) -> np.ndarray:
|
|
343
|
+
"""The derivative with respect to the variables of a quantity whose derivative
|
|
344
|
+
with respect to the control points of the analysis is ``gradient`` (control
|
|
345
|
+
points x dim)."""
|
|
346
|
+
coarse = self.matrix.T @ np.asarray(gradient, dtype=float)
|
|
347
|
+
return np.array(
|
|
348
|
+
[float(np.sum(coarse[ids] * directions)) for ids, directions in self._moves]
|
|
349
|
+
)
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
@dataclass
|
|
353
|
+
class CellResponse:
|
|
354
|
+
"""The effective ``tensor`` of a cell and its ``fraction`` of material for some
|
|
355
|
+
variables, with their derivatives (``d_tensor``: n x n x variables; ``d_fraction``:
|
|
356
|
+
variables) and the solution."""
|
|
357
|
+
|
|
358
|
+
tensor: np.ndarray
|
|
359
|
+
fraction: float
|
|
360
|
+
d_tensor: np.ndarray
|
|
361
|
+
d_fraction: np.ndarray
|
|
362
|
+
solution: CellSolution = field(repr=False)
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def cell_response(design: ShapeDesign, x, materials, *, physics: str = "elastic",
|
|
366
|
+
plane: str = "strain") -> CellResponse: # fmt: skip
|
|
367
|
+
"""The effective tensor and the fraction of material of the periodic cell of a
|
|
368
|
+
design for the variables ``x``, and their derivatives with respect to ``x``."""
|
|
369
|
+
cell = Cell(design.analysis_model(x), materials, physics=physics, plane=plane)
|
|
370
|
+
solution = cell.solve()
|
|
371
|
+
n = len(solution.tensor)
|
|
372
|
+
gradients = energy_gradients(cell.analysis, solution.fluctuations, np.eye(n))
|
|
373
|
+
d_tensor = np.empty((n, n, design.n))
|
|
374
|
+
for i in range(n):
|
|
375
|
+
for j in range(n):
|
|
376
|
+
d_tensor[i, j] = design.pull(gradients[i, j]) / cell.measure
|
|
377
|
+
d_fraction = design.pull(measure_gradient(cell.analysis)) / cell.measure
|
|
378
|
+
return CellResponse(solution.tensor, solution.fraction, d_tensor, d_fraction, solution)
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
@dataclass
|
|
382
|
+
class StructureResponse:
|
|
383
|
+
"""The ``compliance`` ``f . u`` of a structure and the ``measure`` (area, volume) of
|
|
384
|
+
its material, with their derivatives with respect to the variables, the unknowns
|
|
385
|
+
and the analysis."""
|
|
386
|
+
|
|
387
|
+
compliance: float
|
|
388
|
+
measure: float
|
|
389
|
+
d_compliance: np.ndarray
|
|
390
|
+
d_measure: np.ndarray
|
|
391
|
+
u: np.ndarray = field(repr=False)
|
|
392
|
+
analysis: Analysis = field(repr=False)
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def structure_response(design: ShapeDesign, x, materials, loads: Callable, supports: Callable,
|
|
396
|
+
*, plane: str = "strain") -> StructureResponse: # fmt: skip
|
|
397
|
+
"""The compliance of the structure of a design under the nodal forces
|
|
398
|
+
``loads(analysis)`` with the unknowns ``supports(analysis)`` fixed (functions of the
|
|
399
|
+
:class:`~morphogen.iga.analysis.Analysis`: the loads must not depend on the
|
|
400
|
+
variables — tractions on sides that the design does not move)."""
|
|
401
|
+
analysis = Analysis(design.analysis_model(x), materials, plane=plane)
|
|
402
|
+
forces = np.asarray(loads(analysis), dtype=float)
|
|
403
|
+
u = analysis.solve(forces, supports(analysis))
|
|
404
|
+
gradient = -energy_gradients(analysis, u)[0, 0]
|
|
405
|
+
return StructureResponse(
|
|
406
|
+
float(forces @ u),
|
|
407
|
+
analysis.measure(),
|
|
408
|
+
design.pull(gradient),
|
|
409
|
+
design.pull(measure_gradient(analysis)),
|
|
410
|
+
u,
|
|
411
|
+
analysis,
|
|
412
|
+
)
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
@dataclass
|
|
416
|
+
class ShapeResult:
|
|
417
|
+
"""An optimized shape: the variables ``x``, the ``design`` and the ``analysis``
|
|
418
|
+
assemblies, the ``objective`` and the ``constraints`` there, the ``history`` of the
|
|
419
|
+
iterations (objective, largest constraint, variables) and, for a cell, its effective
|
|
420
|
+
``tensor`` and ``fraction`` of material."""
|
|
421
|
+
|
|
422
|
+
x: np.ndarray
|
|
423
|
+
design: Multipatch
|
|
424
|
+
analysis: Multipatch
|
|
425
|
+
objective: float
|
|
426
|
+
constraints: np.ndarray
|
|
427
|
+
iterations: int
|
|
428
|
+
converged: bool
|
|
429
|
+
history: list = field(default_factory=list, repr=False)
|
|
430
|
+
tensor: np.ndarray | None = None
|
|
431
|
+
fraction: float | None = None
|
|
432
|
+
time_s: float = 0.0
|
|
433
|
+
message: str = ""
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def optimize(
|
|
437
|
+
evaluate: Callable,
|
|
438
|
+
x0,
|
|
439
|
+
lower,
|
|
440
|
+
upper,
|
|
441
|
+
*,
|
|
442
|
+
method: str = "slsqp",
|
|
443
|
+
maxiter: int = 100,
|
|
444
|
+
tolerance: float = 1e-7,
|
|
445
|
+
move: float = 0.2,
|
|
446
|
+
callback: Callable | None = None,
|
|
447
|
+
):
|
|
448
|
+
"""Minimize ``f(x)`` subject to ``g_i(x) <= 0`` and ``lower <= x <= upper``, with
|
|
449
|
+
``evaluate(x) -> (f, df, g, dg)`` (``g``: m values, ``dg``: m x n). ``method``:
|
|
450
|
+
``"slsqp"`` (sequential quadratic programming, SciPy) or ``"mma"`` (moving asymptotes).
|
|
451
|
+
``move`` bounds the steps as a share of the bounds: each step of MMA, and the first
|
|
452
|
+
of SLSQP (whose objective is scaled for it; the later ones follow its estimate of the
|
|
453
|
+
curvature). Returns ``(x, history, converged, message)``: the history holds the
|
|
454
|
+
points that the iterations kept, and ``callback(iteration, x, f, g)`` is called for
|
|
455
|
+
each. A trial point where ``evaluate`` raises :class:`FoldedDesign` is turned down:
|
|
456
|
+
the line search of SLSQP shortens its step, the step of MMA is halved."""
|
|
457
|
+
if method not in METHODS:
|
|
458
|
+
raise ValueError(f"method: one of {METHODS}")
|
|
459
|
+
x0 = np.clip(np.asarray(x0, dtype=float), lower, upper)
|
|
460
|
+
lower, upper = np.asarray(lower, dtype=float), np.asarray(upper, dtype=float)
|
|
461
|
+
trail: list[dict] = [] # the points evaluated, in order
|
|
462
|
+
history: list = []
|
|
463
|
+
|
|
464
|
+
def at(x) -> dict:
|
|
465
|
+
x = np.asarray(x, dtype=float)
|
|
466
|
+
if trail and np.array_equal(trail[-1]["x"], x):
|
|
467
|
+
return trail[-1]
|
|
468
|
+
try:
|
|
469
|
+
f, df, g, dg = evaluate(x)
|
|
470
|
+
except FoldedDesign:
|
|
471
|
+
valid = next((entry for entry in reversed(trail) if entry["valid"]), None)
|
|
472
|
+
if valid is None:
|
|
473
|
+
raise
|
|
474
|
+
# a trial step too far: a value that the line search turns down
|
|
475
|
+
entry = dict(valid, x=x.copy(), f=valid["f"] + 10.0 * (abs(valid["f"]) + 1.0))
|
|
476
|
+
entry["valid"] = False
|
|
477
|
+
else:
|
|
478
|
+
g = np.atleast_1d(np.asarray(g, dtype=float))
|
|
479
|
+
entry = {"x": x.copy(), "f": float(f), "df": np.asarray(df, dtype=float), "g": g,
|
|
480
|
+
"dg": np.asarray(dg, dtype=float).reshape(len(g), len(x)),
|
|
481
|
+
"valid": True} # fmt: skip
|
|
482
|
+
trail.append(entry)
|
|
483
|
+
return entry
|
|
484
|
+
|
|
485
|
+
def record(entry) -> None:
|
|
486
|
+
history.append({"objective": entry["f"], "x": entry["x"].copy(),
|
|
487
|
+
"constraint": float(entry["g"].max(initial=-np.inf))}) # fmt: skip
|
|
488
|
+
if callback is not None:
|
|
489
|
+
callback(len(history) - 1, entry["x"].copy(), entry["f"], entry["g"])
|
|
490
|
+
|
|
491
|
+
first = at(x0)
|
|
492
|
+
record(first)
|
|
493
|
+
if method == "slsqp":
|
|
494
|
+
# a first step of the size of ``move``: SLSQP starts from the steepest descent
|
|
495
|
+
spans = (upper - lower)[np.isfinite(upper - lower)]
|
|
496
|
+
typical = float(np.median(spans)) if spans.size else 1.0
|
|
497
|
+
scale = max(1.0, float(np.abs(first["df"]).max(initial=0.0)) / (move * typical))
|
|
498
|
+
|
|
499
|
+
def kept(_) -> None:
|
|
500
|
+
# SciPy calls this at the first trial point of an iteration: the point
|
|
501
|
+
# evaluated before it is the one that the previous iteration kept
|
|
502
|
+
if len(trail) > 1 and not np.array_equal(trail[-2]["x"], history[-1]["x"]):
|
|
503
|
+
record(trail[-2])
|
|
504
|
+
|
|
505
|
+
constraints = [
|
|
506
|
+
{
|
|
507
|
+
"type": "ineq",
|
|
508
|
+
"fun": lambda x, i=i: -at(x)["g"][i],
|
|
509
|
+
"jac": lambda x, i=i: -at(x)["dg"][i],
|
|
510
|
+
}
|
|
511
|
+
for i in range(len(first["g"]))
|
|
512
|
+
]
|
|
513
|
+
result = scipy.optimize.minimize(
|
|
514
|
+
lambda x: (at(x)["f"] / scale, at(x)["df"] / scale),
|
|
515
|
+
x0,
|
|
516
|
+
jac=True,
|
|
517
|
+
method="SLSQP",
|
|
518
|
+
bounds=list(zip(lower, upper, strict=True)),
|
|
519
|
+
constraints=constraints,
|
|
520
|
+
callback=kept,
|
|
521
|
+
options={"maxiter": int(maxiter), "ftol": float(tolerance) / scale},
|
|
522
|
+
)
|
|
523
|
+
last = at(np.asarray(result.x, dtype=float))
|
|
524
|
+
if not np.array_equal(last["x"], history[-1]["x"]):
|
|
525
|
+
record(last)
|
|
526
|
+
return last["x"], history, bool(result.success), str(result.message)
|
|
527
|
+
from morphogen.optimization.mma import MMA
|
|
528
|
+
|
|
529
|
+
x = x0.copy()
|
|
530
|
+
m = max(len(first["g"]), 1)
|
|
531
|
+
if m >= len(x):
|
|
532
|
+
raise ValueError("mma: fewer constraints than variables")
|
|
533
|
+
scale = abs(first["f"]) or 1.0
|
|
534
|
+
optimizer = MMA(len(x), m, lower, upper, move=move)
|
|
535
|
+
for _ in range(int(maxiter)):
|
|
536
|
+
entry = at(x)
|
|
537
|
+
g, dg = entry["g"], entry["dg"]
|
|
538
|
+
if len(g) == 0: # MMA needs a constraint: one that never binds
|
|
539
|
+
g, dg = np.array([-1.0]), np.zeros((1, len(x)))
|
|
540
|
+
new = optimizer.update(x, entry["f"] / scale, entry["df"] / scale, g, dg)
|
|
541
|
+
for _ in range(30): # a step that folds the design is halved
|
|
542
|
+
if at(new)["valid"]:
|
|
543
|
+
break
|
|
544
|
+
new = x + 0.5 * (new - x)
|
|
545
|
+
else:
|
|
546
|
+
raise FoldedDesign("mma: every step from these variables folds the design")
|
|
547
|
+
change = float(np.abs(new - x).max() / max(float((upper - lower).max()), 1e-30))
|
|
548
|
+
x = new
|
|
549
|
+
record(at(x))
|
|
550
|
+
if change < tolerance:
|
|
551
|
+
return x, history, True, "the variables no longer change"
|
|
552
|
+
return x, history, False, f"{maxiter} iterations"
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
def _partials(function: Callable, tensor: np.ndarray, fraction: float):
|
|
556
|
+
"""The value of ``function(tensor, fraction)`` and its derivatives with respect to
|
|
557
|
+
the entries of the tensor and to the fraction (central differences)."""
|
|
558
|
+
value = float(function(tensor, fraction))
|
|
559
|
+
step = 1e-6 * float(np.abs(tensor).max())
|
|
560
|
+
d_tensor = np.zeros_like(tensor)
|
|
561
|
+
for i in range(tensor.shape[0]):
|
|
562
|
+
for j in range(tensor.shape[1]):
|
|
563
|
+
plus, minus = tensor.copy(), tensor.copy()
|
|
564
|
+
plus[i, j] += step
|
|
565
|
+
minus[i, j] -= step
|
|
566
|
+
d_tensor[i, j] = (function(plus, fraction) - function(minus, fraction)) / (2 * step)
|
|
567
|
+
d_fraction = (function(tensor, fraction + 1e-6) - function(tensor, fraction - 1e-6)) / 2e-6
|
|
568
|
+
return value, d_tensor, float(d_fraction)
|
|
569
|
+
|
|
570
|
+
|
|
571
|
+
def optimize_cell(design: ShapeDesign, materials, objective: Callable, constraints=(), *,
|
|
572
|
+
linear=None, x0=None, physics: str = "elastic", plane: str = "strain",
|
|
573
|
+
method: str = "slsqp", maxiter: int = 100, tolerance: float = 1e-7,
|
|
574
|
+
move: float = 0.2, callback: Callable | None = None) -> ShapeResult: # fmt: skip
|
|
575
|
+
"""The shape of a periodic cell that minimizes ``objective(tensor, fraction)`` under
|
|
576
|
+
``constraint(tensor, fraction) <= 0`` for each of the ``constraints``: functions of
|
|
577
|
+
the effective tensor of the cell (Voigt's notation) and of its fraction of
|
|
578
|
+
material — for instance ``lambda c, f: -plane_constants(c)["bulk_modulus"]`` with
|
|
579
|
+
``lambda c, f: f - 0.6``. ``linear = (A, b)`` adds the constraints ``A x <= b`` on
|
|
580
|
+
the variables (sizes of the geometry: the control points are linear in them); they
|
|
581
|
+
follow the others in the ``constraints`` of the result, as ``A x - b``. The
|
|
582
|
+
variables start from ``x0`` (zeros by default: the design as it is)."""
|
|
583
|
+
t0 = time.perf_counter()
|
|
584
|
+
functions = [objective, *constraints]
|
|
585
|
+
rows = np.zeros((0, design.n)), np.zeros(0)
|
|
586
|
+
if linear is not None:
|
|
587
|
+
rows = np.atleast_2d(np.asarray(linear[0], dtype=float)), np.atleast_1d(linear[1])
|
|
588
|
+
if rows[0].shape != (len(rows[1]), design.n):
|
|
589
|
+
raise ValueError(f"linear: (A, b) with one row of {design.n} coefficients per bound")
|
|
590
|
+
|
|
591
|
+
def evaluate(x):
|
|
592
|
+
try:
|
|
593
|
+
response = cell_response(design, x, materials, physics=physics, plane=plane)
|
|
594
|
+
except FoldedDesign:
|
|
595
|
+
raise
|
|
596
|
+
except ValueError as exc:
|
|
597
|
+
raise FoldedDesign(
|
|
598
|
+
f"{exc}: the design folds for these variables; tighten their bounds"
|
|
599
|
+
) from None
|
|
600
|
+
values, gradients = [], []
|
|
601
|
+
for function in functions:
|
|
602
|
+
value, d_tensor, d_fraction = _partials(function, response.tensor, response.fraction)
|
|
603
|
+
values.append(value)
|
|
604
|
+
gradients.append(
|
|
605
|
+
np.einsum("ij,ijx->x", d_tensor, response.d_tensor)
|
|
606
|
+
+ d_fraction * response.d_fraction
|
|
607
|
+
)
|
|
608
|
+
return (
|
|
609
|
+
values[0],
|
|
610
|
+
gradients[0],
|
|
611
|
+
np.concatenate([values[1:], rows[0] @ x - rows[1]]),
|
|
612
|
+
np.concatenate([np.array(gradients[1:]).reshape(-1, design.n), rows[0]]),
|
|
613
|
+
)
|
|
614
|
+
|
|
615
|
+
lower, upper = design.bounds()
|
|
616
|
+
x0 = np.zeros(design.n) if x0 is None else np.asarray(x0, dtype=float)
|
|
617
|
+
x, history, converged, message = optimize(
|
|
618
|
+
evaluate, x0, lower, upper, method=method, maxiter=maxiter, tolerance=tolerance,
|
|
619
|
+
move=move, callback=callback,
|
|
620
|
+
) # fmt: skip
|
|
621
|
+
response = cell_response(design, x, materials, physics=physics, plane=plane)
|
|
622
|
+
values = [float(f(response.tensor, response.fraction)) for f in functions]
|
|
623
|
+
return ShapeResult(
|
|
624
|
+
x, design.design_model(x), design.analysis_model(x), values[0],
|
|
625
|
+
np.concatenate([values[1:], rows[0] @ x - rows[1]]),
|
|
626
|
+
len(history) - 1, converged, history, response.tensor, response.fraction,
|
|
627
|
+
time.perf_counter() - t0, message,
|
|
628
|
+
) # fmt: skip
|
|
629
|
+
|
|
630
|
+
|
|
631
|
+
def optimize_structure(
|
|
632
|
+
design: ShapeDesign,
|
|
633
|
+
materials,
|
|
634
|
+
loads: Callable,
|
|
635
|
+
supports: Callable,
|
|
636
|
+
*,
|
|
637
|
+
measure: float | None = None,
|
|
638
|
+
x0=None,
|
|
639
|
+
plane: str = "strain",
|
|
640
|
+
method: str = "slsqp",
|
|
641
|
+
maxiter: int = 100,
|
|
642
|
+
tolerance: float = 1e-7,
|
|
643
|
+
move: float = 0.2,
|
|
644
|
+
callback: Callable | None = None,
|
|
645
|
+
) -> ShapeResult:
|
|
646
|
+
"""The shape of a structure of smallest compliance under given loads
|
|
647
|
+
(:func:`structure_response`) whose material has at most the area (volume)
|
|
648
|
+
``measure`` (by default that of the design as it is)."""
|
|
649
|
+
t0 = time.perf_counter()
|
|
650
|
+
x0 = np.zeros(design.n) if x0 is None else np.asarray(x0, dtype=float)
|
|
651
|
+
if measure is None:
|
|
652
|
+
measure = Analysis(design.analysis_model(np.zeros(design.n)), materials).measure()
|
|
653
|
+
start = structure_response(design, x0, materials, loads, supports, plane=plane)
|
|
654
|
+
|
|
655
|
+
def evaluate(x):
|
|
656
|
+
try:
|
|
657
|
+
r = structure_response(design, x, materials, loads, supports, plane=plane)
|
|
658
|
+
except FoldedDesign:
|
|
659
|
+
raise
|
|
660
|
+
except ValueError as exc:
|
|
661
|
+
raise FoldedDesign(
|
|
662
|
+
f"{exc}: the design folds for these variables; tighten their bounds"
|
|
663
|
+
) from None
|
|
664
|
+
return (
|
|
665
|
+
r.compliance / start.compliance,
|
|
666
|
+
r.d_compliance / start.compliance,
|
|
667
|
+
np.array([r.measure / measure - 1.0]),
|
|
668
|
+
r.d_measure[None, :] / measure,
|
|
669
|
+
)
|
|
670
|
+
|
|
671
|
+
lower, upper = design.bounds()
|
|
672
|
+
x, history, converged, message = optimize(
|
|
673
|
+
evaluate, x0, lower, upper, method=method, maxiter=maxiter, tolerance=tolerance,
|
|
674
|
+
move=move, callback=callback,
|
|
675
|
+
) # fmt: skip
|
|
676
|
+
final = structure_response(design, x, materials, loads, supports, plane=plane)
|
|
677
|
+
return ShapeResult(
|
|
678
|
+
x, design.design_model(x), design.analysis_model(x), final.compliance,
|
|
679
|
+
np.array([final.measure / measure - 1.0]), len(history) - 1, converged, history,
|
|
680
|
+
None, None, time.perf_counter() - t0, message,
|
|
681
|
+
) # fmt: skip
|
|
682
|
+
|
|
683
|
+
|
|
684
|
+
__all__ = [
|
|
685
|
+
"METHODS",
|
|
686
|
+
"CellResponse",
|
|
687
|
+
"FoldedDesign",
|
|
688
|
+
"ShapeDesign",
|
|
689
|
+
"ShapeResult",
|
|
690
|
+
"StructureResponse",
|
|
691
|
+
"cell_response",
|
|
692
|
+
"energy_gradients",
|
|
693
|
+
"measure_gradient",
|
|
694
|
+
"mirror",
|
|
695
|
+
"optimize",
|
|
696
|
+
"optimize_cell",
|
|
697
|
+
"optimize_structure",
|
|
698
|
+
"rotation",
|
|
699
|
+
"structure_response",
|
|
700
|
+
]
|