File size: 7,665 Bytes
5b87d5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

from collections.abc import Sequence

import numpy as np
import torch
import torch.autograd as autograd
import torch.nn as nn


class SubNet(nn.Module):
    """Fully connected network with trainable adaptive activations."""

    def __init__(self, layers: Sequence[int], activation: str = "tanh") -> None:
        super().__init__()
        if len(layers) < 2:
            raise ValueError("layers must contain at least an input and an output size")
        if activation not in {"tanh", "sin", "cos"}:
            raise ValueError(f"unsupported activation: {activation}")

        self.activation = activation
        self.linears = nn.ModuleList(
            nn.Linear(layers[index], layers[index + 1], dtype=torch.float64)
            for index in range(len(layers) - 1)
        )
        # Keep one value per layer for compatibility with the published checkpoints.
        self.a = nn.ParameterList(
            nn.Parameter(torch.tensor(0.05, dtype=torch.float64))
            for _ in range(len(layers) - 1)
        )

    def forward(self, inputs: torch.Tensor) -> torch.Tensor:
        hidden = inputs
        for index, linear in enumerate(self.linears[:-1]):
            hidden = 20.0 * self.a[index] * linear(hidden)
            hidden = getattr(torch, self.activation)(hidden)
        return self.linears[-1](hidden)


class gPINN(nn.Module):
    """Gradient-enhanced physics-informed neural network backbone."""

    def __init__(self, layers: Sequence[int], activation: str = "tanh") -> None:
        super().__init__()
        self.net = SubNet(layers, activation)

    def forward(self, inputs: torch.Tensor) -> torch.Tensor:
        return self.net(inputs)


class gPINNPoisson2D(nn.Module):
    """2D Poisson model whose output transform enforces zero boundaries."""

    def __init__(self, layers: Sequence[int]) -> None:
        super().__init__()
        self.net = gPINN(layers)

    def forward(self, coordinates: torch.Tensor) -> torch.Tensor:
        x = coordinates[:, 0:1]
        y = coordinates[:, 1:2]
        return x * y * (1.0 - x) * (1.0 - y) * self.net(coordinates)


def exact_poisson1d(x: np.ndarray) -> np.ndarray:
    solution = x + np.sin(8.0 * x) / 8.0
    for frequency in range(1, 5):
        solution += np.sin(frequency * x) / frequency
    return solution


def gpinn_loss_poisson1d(
    model: nn.Module,
    interior: torch.Tensor,
    boundary: torch.Tensor,
    boundary_values: torch.Tensor,
    gradient_weight: float,
) -> tuple[torch.Tensor, dict[str, float]]:
    x = interior.detach().requires_grad_(True)
    prediction = model(x)
    first = autograd.grad(prediction, x, torch.ones_like(prediction), create_graph=True)[0]
    second = autograd.grad(first, x, torch.ones_like(first), create_graph=True)[0]
    third = autograd.grad(second, x, torch.ones_like(second), create_graph=True)[0]

    source = 8.0 * torch.sin(8.0 * x) + sum(
        frequency * torch.sin(frequency * x) for frequency in range(1, 5)
    )
    source_gradient = (
        torch.cos(x)
        + 4.0 * torch.cos(2.0 * x)
        + 9.0 * torch.cos(3.0 * x)
        + 16.0 * torch.cos(4.0 * x)
        + 64.0 * torch.cos(8.0 * x)
    )

    residual = -second - source
    residual_gradient = -third - source_gradient
    residual_loss = torch.mean(residual.square())
    boundary_loss = torch.mean((model(boundary) - boundary_values).square())
    gradient_loss = torch.mean(residual_gradient.square())
    loss = residual_loss + boundary_loss + gradient_weight * gradient_loss
    return loss, {
        "residual": residual_loss.item(),
        "boundary": boundary_loss.item(),
        "gradient": gradient_loss.item(),
    }


def exact_poisson2d(x: np.ndarray, y: np.ndarray, exponent: float) -> np.ndarray:
    return (16.0 * x * y * (1.0 - x) * (1.0 - y)) ** exponent


def _poisson2d_source(coordinates: torch.Tensor, exponent: float) -> torch.Tensor:
    x = coordinates[:, 0:1]
    y = coordinates[:, 1:2]
    exact = (16.0 * x * y * (1.0 - x) * (1.0 - y)) ** exponent
    exact_gradient = autograd.grad(
        exact, coordinates, torch.ones_like(exact), create_graph=True
    )[0]
    exact_xx = autograd.grad(
        exact_gradient[:, 0:1],
        coordinates,
        torch.ones_like(exact_gradient[:, 0:1]),
        create_graph=True,
    )[0][:, 0:1]
    exact_yy = autograd.grad(
        exact_gradient[:, 1:2],
        coordinates,
        torch.ones_like(exact_gradient[:, 1:2]),
        create_graph=True,
    )[0][:, 1:2]
    return -(exact_xx + exact_yy)


def gpinn_loss_poisson2d(
    model: nn.Module,
    interior: torch.Tensor,
    gradient_weight: float,
    exponent: float,
) -> tuple[torch.Tensor, dict[str, float]]:
    coordinates = interior.detach().requires_grad_(True)
    prediction = model(coordinates)
    prediction_gradient = autograd.grad(
        prediction, coordinates, torch.ones_like(prediction), create_graph=True
    )[0]
    prediction_xx = autograd.grad(
        prediction_gradient[:, 0:1],
        coordinates,
        torch.ones_like(prediction_gradient[:, 0:1]),
        create_graph=True,
    )[0][:, 0:1]
    prediction_yy = autograd.grad(
        prediction_gradient[:, 1:2],
        coordinates,
        torch.ones_like(prediction_gradient[:, 1:2]),
        create_graph=True,
    )[0][:, 1:2]

    residual = prediction_xx + prediction_yy + _poisson2d_source(coordinates, exponent)
    residual_gradient = autograd.grad(
        residual, coordinates, torch.ones_like(residual), create_graph=True
    )[0]
    residual_loss = torch.mean(residual.square())
    gradient_loss = torch.mean(residual_gradient[:, 0:1].square()) + torch.mean(
        residual_gradient[:, 1:2].square()
    )
    loss = residual_loss + gradient_weight * gradient_loss
    return loss, {"residual": residual_loss.item(), "gradient": gradient_loss.item()}


def output_transform_burgers(
    coordinates: torch.Tensor, raw_prediction: torch.Tensor
) -> torch.Tensor:
    x = coordinates[:, 0:1]
    t = coordinates[:, 1:2]
    return (
        (1.0 - x) * (1.0 + x) * (1.0 - torch.exp(-t)) * raw_prediction
        - torch.sin(torch.pi * x)
    )


class gPINNBurgers(nn.Module):
    """Burgers model with hard initial and boundary constraints."""

    def __init__(self, layers: Sequence[int]) -> None:
        super().__init__()
        self.net = gPINN(layers)

    def forward(self, coordinates: torch.Tensor) -> torch.Tensor:
        return output_transform_burgers(coordinates, self.net(coordinates))


def burgers_residual(
    model: nn.Module, coordinates: torch.Tensor, create_graph: bool = True
) -> tuple[torch.Tensor, torch.Tensor]:
    inputs = coordinates.detach().requires_grad_(True)
    prediction = model(inputs)
    prediction_gradient = autograd.grad(
        prediction, inputs, torch.ones_like(prediction), create_graph=True
    )[0]
    prediction_x = prediction_gradient[:, 0:1]
    prediction_t = prediction_gradient[:, 1:2]
    prediction_xx = autograd.grad(
        prediction_x,
        inputs,
        torch.ones_like(prediction_x),
        create_graph=create_graph,
    )[0][:, 0:1]
    viscosity = 0.01 / torch.pi
    residual = prediction_t + prediction * prediction_x - viscosity * prediction_xx
    return residual, inputs


def burgers_gpinn_terms(
    model: nn.Module, coordinates: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
    residual, inputs = burgers_residual(model, coordinates, create_graph=True)
    residual_gradient = autograd.grad(
        residual, inputs, torch.ones_like(residual), create_graph=True
    )[0]
    return residual, residual_gradient[:, 0:1], residual_gradient[:, 1:2]