File size: 22,887 Bytes
fc7d689 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 | import equinox as eqx
import jax.numpy as jnp
from jax.lax import stop_gradient
from jax_fdm.equilibrium import EquilibriumModel
from jaxtyping import Array, Bool, Float
from neural_fdm.helpers import (
calculate_area_loads,
calculate_equilibrium_state,
calculate_fd_params_state,
)
# ===============================================================================
# Autoencoders
# ===============================================================================
class AutoEncoder(eqx.Module):
"""
A model that pipes an encoder to a decoder.
Parameters
----------
encoder: `eqx.Module`
The encoder.
decoder: `eqx.Module`
The decoder.
"""
encoder: eqx.Module
decoder: eqx.Module
def __init__(self, encoder, decoder):
self.encoder = encoder
self.decoder = decoder
def __call__(self, x, structure, aux_data=False, *args, **kwargs):
"""
Predict a shape that approximates the target shape.
Parameters
----------
x: `jax.Array`
The target shape.
structure: `jax_fdm.EquilibriumStructure`
A structure with the discretization of the shape.
aux_data: `bool`, optional
Whether to return auxiliary data. The auxiliary data is a tuple of the
force density parameters, the fixed node positions, and the applied loads.
Returns
-------
x_hat: `jax.Array`
The predicted shape.
data: `tuple` of `jax.Array`
The auxiliary data if `aux_data` is `True`.
"""
# NOTE: x must be a flat vector
# GNN encoders need structure for edge connectivity
from neural_fdm.gnn import GNNEncoder
if isinstance(self.encoder, GNNEncoder):
q = self.encoder(x, structure=structure)
else:
q = self.encoder(x)
x_hat = self.decoder(q, x, structure, aux_data)
return x_hat
def encode(self, x):
"""
Generate the latent representation of a target shape.
Parameters
----------
x: `jax.Array`
The target shape.
Returns
-------
q: `jax.Array`
The latent representation.
"""
return self.encoder(x)
def decode(self, q, *args, **kwargs):
"""
Map a latent representation back to shape space.
Parameters
----------
q: `jax.Array`
The latent representation.
Returns
-------
x_hat: `jax.Array`
The predicted shape.
"""
return self.decoder(q, *args, **kwargs)
def predict_states(self, x, structure):
"""
Predict equilibrium and parameter states for visualization.
Parameters
----------
x: `jax.Array`
The target shape.
structure: `jax_fdm.EquilibriumStructure`
A structure with the discretization of the shape.
Returns
-------
eq_state: `jax_fdm.EquilibriumState`
The current equilibrium state of the structure.
fd_params_state: `jax_fdm.EquilibriumParametersState`
The current state of simulation parameters.
"""
# Predict shape
x_hat, params = self(x, structure, True)
return build_states(x_hat, params, structure)
class AutoEncoderPiggy(AutoEncoder):
"""
An autoencoder with a piggybacking decoder.
Parameters
----------
encoder: `eqx.Module`
The encoder.
decoder: `eqx.Module`
The decoder.
decoder_piggy: `eqx.Module`
The piggybacking decoder.
"""
decoder_piggy: eqx.Module
def __init__(self, encoder, decoder, decoder_piggy):
super().__init__(encoder, decoder)
self.decoder_piggy = decoder_piggy
def __call__(self, x, structure, aux_data=False, piggy_mode=True):
"""
Predict a shape that approximates the target shape.
Parameters
----------
x: `jax.Array`
The target shape.
structure: `jax_fdm.EquilibriumStructure`
A structure with the discretization of the shape.
aux_data: `bool`, optional
Whether to return auxiliary data. The auxiliary data is a tuple of the
force density parameters, the fixed node positions, and the applied loads.
piggy_mode: `bool`, optional
Whether to use the piggybacking decoder. If `True`, gradients are not backpropagated
from the piggybacking decoder into the encoder.
Returns
-------
x_hat: `jax.Array` or `tuple` of `jax.Array`
The predicted shape. If `aux_data` is `True`, this is a tuple of the
predicted shape and the auxiliary data.
y_hat: `jax.Array` or `tuple` of `jax.Array`
The predicted shape from the piggybacking decoder. If `aux_data` is `True`,
this is a tuple of the predicted shape and the auxiliary data from
the piggybacking decoder.
"""
q = self.encoder(x)
x_hat = self.decoder(q, x, structure, aux_data)
if piggy_mode:
q = stop_gradient(q)
x_hat = stop_gradient(x_hat)
y_hat = self.decoder_piggy(q, x, structure, aux_data)
return x_hat, y_hat
def decode(self, q, *args, **kwargs):
"""
Map a latent representation back to shape space.
Parameters
----------
q: `jax.Array`
The latent representation.
Returns
-------
x_hat: `jax.Array`
The predicted shape.
"""
return self.decoder_piggy(q, *args, **kwargs)
def predict_states(self, x, structure):
"""
Predict equilibrium and parameter states for visualization.
Parameters
----------
x: `jax.Array`
The target shape.
structure: `jax_fdm.EquilibriumStructure`
A structure with the discretization of the shape.
Returns
-------
eq_state: `jax_fdm.EquilibriumState`
The current equilibrium state of the structure.
fd_params_state: `jax_fdm.EquilibriumParametersState`
The current state of simulation parameters.
"""
# Predict shape
_, pred_piggy = self(x, structure, True)
x_hat, params = pred_piggy
return build_states(x_hat, params, structure)
# ===============================================================================
# Encoders
# ===============================================================================
class Encoder(eqx.Module):
"""
An encoder.
Parameters
----------
edges_signs: `jax.Array`
An array of +1s to denote tension and -1s to denote compression on the edges.
q_shift: `float`, optional
The minimum value of the latent representation.
slice_out: `bool`, optional
Whether to slice the output of the encoder to learn a mapping only
w.r.t. a slice of the target shape.
slice_indices: `jax.Array`, optional
The indices of the points to slice from the target shape.
"""
edges_signs: Array
q_shift: Float
slice_out: Bool
slice_indices: Array
def __init__(
self,
edges_signs,
q_shift=0.0,
slice_out=False,
slice_indices=None,
*args,
**kwargs
):
super().__init__(*args, **kwargs)
self.edges_signs = edges_signs
self.q_shift = q_shift
self.slice_out = slice_out
self.slice_indices = slice_indices
def __call__(self, x):
"""
Map a target shape to a latent representation.
Parameters
----------
x: `jax.Array`
The target shape.
Returns
-------
q: `jax.Array`
The latent representation.
"""
if self.slice_out:
x = jnp.reshape(x, (-1, 3))
x = x[self.slice_indices, :]
x = jnp.ravel(x)
return super().__call__(x)
class MLPEncoder(Encoder, eqx.nn.MLP):
"""
A MLP encoder.
Parameters
----------
edges_signs: `jax.Array`
An array of +1s to denote tension and -1s to denote compression on the edges.
q_shift: `float`, optional
The minimum value of the latent representation.
slice_out: `bool`, optional
Whether to slice the output of the encoder to learn a mapping only
w.r.t. a slice of the target shape.
slice_indices: `jax.Array`, optional
The indices of the points to slice from the target shape.
in_size: `int`
The dimension of the input.
out_size: `int`
The dimension of the output latents.
width_size: `int`
The size of the hidden layers.
depth: `int`
The number of hidden layers, including the output layer.
activation: `Callable`
The activation function for the hidden layers.
final_activation: `Callable`
The activation function for the output layer.
key: `jax.random.PRNGKey`
The random key.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def __call__(self, x):
"""
Map a target shape to a latent representation.
Parameters
----------
x: `jax.Array`
The target shape.
Returns
-------
q: `jax.Array`
The latent representation.
"""
# MLP prediction (must be positive due to softplus activation)
q_hat = super().__call__(x)
# NOTE: negative q denotes compression, positive tension.
return (q_hat + self.q_shift) * self.edges_signs
# ===============================================================================
# Decoders
# ===============================================================================
class Decoder(eqx.Module):
"""
A decoder.
Parameters
----------
load: `float`
The area load applied to the structure.
mask_edges: `jax.Array`
A mask vector for the latent values to zero out.
"""
load: Float
mask_edges: Array
def __init__(self, load, mask_edges, *args, **kwargs):
super().__init__(*args, **kwargs)
self.load = load
self.mask_edges = mask_edges
def __call__(self, q, x, structure, aux_data=False):
"""
Map a latent representation to a target shape.
Parameters
----------
q: `jax.Array`
The latent representation.
x: `jax.Array`
The target shape.
structure: `jax_fdm.EquilibriumStructure`
A structure with the discretization of the shape.
aux_data: `bool`, optional
Whether to return auxiliary data. The auxiliary data is a tuple of the
force density parameters, the fixed node positions, and the applied loads.
Returns
-------
x_hat: `jax.Array`
The predicted shape.
data: `tuple` of `jax.Array`
The auxiliary data if `aux_data` is `True`.
"""
# gather parameters
q = self.get_q(q)
xyz_fixed = self.get_xyz_fixed(x, structure)
loads = self.get_loads(x, structure)
# predict x
x_hat = self.get_xyz((q, xyz_fixed, loads), structure)
if aux_data:
data = (q, xyz_fixed, loads)
return x_hat, data
return x_hat
def get_q(self, q_hat):
"""
Mask the latent values to zero out.
Parameters
----------
q_hat: `jax.Array`
The latent representation.
Returns
-------
q: `jax.Array`
The masked latent representation.
"""
return q_hat * self.mask_edges
def get_xyz_fixed(self, x, structure):
"""
Calculate the fixed vertex positions.
Parameters
----------
x: `jax.Array`
The target shape.
structure: `jax_fdm.EquilibriumStructure`
A structure with the discretization of the shape.
Returns
-------
xyz_fixed: `jax.Array`
The fixed vertex positions.
"""
indices = structure.indices_fixed
x = jnp.reshape(x, (-1, 3))
return x[indices, :]
def get_loads(self, x, structure):
"""
Calculate the applied vertex loads from a global area load.
Parameters
----------
x: `jax.Array`
The target shape.
structure: `jax_fdm.EquilibriumStructure`
A structure with the discretization of the shape.
Returns
-------
loads: `jax.Array`
The applied vertex loads.
"""
if self.load:
return calculate_area_loads(x, structure, self.load)
return jnp.zeros((structure.num_vertices, 3))
def get_xyz(self, params, structure):
"""
Lower level method to predict the target shape. It must be implemented by the subclasses.
Parameters
----------
params: `tuple` of `jax.Array`
The parameters to predict the target shape from.
structure: `jax_fdm.EquilibriumStructure`
A structure with the discretization of the shape.
Returns
-------
x_hat: `jax.Array`
The predicted shape.
"""
raise NotImplementedError
# ===============================================================================
# Physics-based decoders
# ===============================================================================
class FDDecoder(Decoder):
"""
A physics-based force density decoder.
Parameters
----------
model: `jax_fdm.EquilibriumModel`
The force density model.
load: `float`
The area load applied to the structure.
mask_edges: `jax.Array`
A mask vector for the latent values to zero out.
"""
model: EquilibriumModel
def __init__(self, model, *args, **kwargs):
self.model = model
super().__init__(*args, **kwargs)
def get_xyz(self, params, structure):
"""
Predict the target shape from the simulation parameters.
Parameters
----------
params: `tuple` of `jax.Array`
The parameters to predict the target shape from.
structure: `jax_fdm.EquilibriumStructure`
A structure with the discretization of the shape.
Returns
-------
x_hat: `jax.Array`
The predicted shape.
"""
q, xyz_fixed, loads = params
# NOTE: to predict only free vertices, use instead
# self.model.nodes_free_positions(q, xyz_fixed, loads_nodes, structure)
x_hat = self.model.equilibrium(q,
xyz_fixed,
loads,
structure)
return jnp.ravel(x_hat)
class FDDecoderParametrized(FDDecoder):
"""
A physics-based force density decoder that is directly optimizable.
Parameters
----------
q: `jax.Array`
The initial force densities.
model: `jax_fdm.EquilibriumModel`
The force density model.
load: `float`
The area load applied to the structure.
mask_edges: `jax.Array`
A mask vector for the latent values to zero out.
"""
q: Array
def __init__(self, q, *args, **kwargs):
self.q = q
super().__init__(*args, **kwargs)
def __call__(self, x, structure, aux_data=False, *args, **kwargs):
"""
Solve equilibrium using stored force densities.
Parameters
----------
x: `jax.Array`
The target shape (unused; force densities come from self.q).
structure: `jax_fdm.EquilibriumStructure`
A structure with the discretization of the shape.
aux_data: `bool`, optional
Whether to return auxiliary data. The auxiliary data is a tuple of the
force density parameters, the fixed node positions, and the applied loads.
Returns
-------
x_hat: `jax.Array`
The predicted shape.
data: `tuple` of `jax.Array`
The auxiliary data if `aux_data` is `True`.
"""
return super().__call__(self.q, x, structure, aux_data)
def predict_states(self, x, structure):
"""
Predict equilibrium and parameter states for visualization.
Parameters
----------
x: `jax.Array`
The target shape.
structure: `jax_fdm.EquilibriumStructure`
A structure with the discretization of the shape.
Returns
-------
eq_state: `jax_fdm.EquilibriumState`
The current equilibrium state of the structure.
fd_params_state: `jax_fdm.EquilibriumParametersState`
The current state of simulation parameters.
"""
# Predict shape
x_hat, params = self(x, structure, True)
return build_states(x_hat, params, structure)
# ===============================================================================
# Neural decoders
# ===============================================================================
class MLPDecoder(Decoder, eqx.nn.MLP):
"""
A MLP decoder.
Parameters
----------
load: `float`
The area load applied to the structure.
mask_edges: `jax.Array`
A mask vector for the latent values to zero out.
in_size: `int`
The dimension of the input.
out_size: `int`
The dimension of the output.
width_size: `int`
The size of the hidden layers.
depth: `int`
The number of hidden layers, including the output layer.
activation: `Callable`
The activation function for the hidden layers.
key: `jax.random.PRNGKey`
The random key.
"""
# NOTE: Should the inheritance order be reversed?
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def get_xyz(self, params, structure):
"""
Map a latent representation to a target shape.
Parameters
----------
params: `tuple` of `jax.Array`
The parameters to predict the target shape from. The parameters are
the force density parameters, the fixed node positions, and the applied loads.
structure: `jax_fdm.EquilibriumStructure`
A structure with the discretization of the shape.
Returns
-------
x_hat: `jax.Array`
The predicted shape.
"""
# unpack parameters
q, x_fixed, loads = params
# predict x
x_free = self._get_xyz(params)
# Concatenate the position of the free and the fixed nodes
indices = structure.indices_freefixed
x_free = jnp.reshape(x_free, (-1, 3))
x_hat = jnp.concatenate((x_free, x_fixed))[indices, :]
return jnp.ravel(x_hat)
def _get_xyz(self, params):
"""
Map a latent representation to a target shape.
Parameters
----------
params: `tuple` of `jax.Array`
The parameters to predict the target shape from. The parameters are
the force density parameters, the fixed node positions, and the applied loads.
Returns
-------
x_hat: `jax.Array`
The predicted shape.
"""
# unpack parameters
q, x_fixed, loads = params
# NOTE: using this exotic way to call __call__ to map q to x due to multiple inheritance
return eqx.nn.MLP.__call__(self, q)
class MLPDecoderXL(MLPDecoder):
"""
A MLP decoder that maps latents and the boundary conditions (fixed positions and loads) to a shape.
It assumes that the load has only a z-component, while x and y are always 0.
Parameters
----------
load: `float`
The area load applied to the structure.
mask_edges: `jax.Array`
A mask vector for the latent values to zero out.
in_size: `int`
The dimension of the input.
out_size: `int`
The dimension of the output.
width_size: `int`
The size of the hidden layers.
depth: `int`
The number of hidden layers, including the output layer.
activation: `Callable`
The activation function for the hidden layers.
key: `jax.random.PRNGKey`
The random key.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def _get_xyz(self, params):
"""
Map a latent representation and the boundary conditions to a target shape.
Parameters
----------
params: `tuple` of `jax.Array`
The parameters to predict the target shape from. The parameters are
the force density parameters, the fixed node positions, and the applied loads.
Returns
-------
x_hat: `jax.Array`
The predicted shape.
"""
# unpack parameters
q, x_fixed, loads = params
# concatenate long array
x_fixed = jnp.ravel(x_fixed)
loads_z = loads[:, 2] # only z component, x and y are always 0
params = jnp.concatenate((q, x_fixed, loads_z))
return eqx.nn.MLP.__call__(self, params)
# ===============================================================================
# Helpers
# ===============================================================================
def build_states(x_hat, params, structure):
"""
Assemble equilibrium and parameter states for visualization.
Parameters
----------
xyz_hat: `jax.Array`
The predicted shape.
params: `tuple` of `jax.Array`
The parameters to predict the target shape from. The parameters are
the force density parameters, the fixed node positions, and the applied loads.
structure: `jax_fdm.EquilibriumStructure`
A structure with the discretization of the shape.
Returns
-------
eq_state: `jax_fdm.EquilibriumState`
The current equilibrium state of the structure.
fd_params_state: `jax_fdm.EquilibriumParametersState`
The current state of simulation parameters.
"""
# Unpack aux data
q, xyz_fixed, loads = params
# Equilibrium parameters
fd_params_state = calculate_fd_params_state(
q,
xyz_fixed,
loads
)
# Equilibrium state
x_hat = jnp.reshape(x_hat, (-1, 3))
eq_state = calculate_equilibrium_state(
q,
x_hat, # xyz_free | xyz_fixed
loads,
structure
)
return eq_state, fd_params_state
|