Skip to content

Commit

Permalink
Fix lint
Browse files Browse the repository at this point in the history
  • Loading branch information
s9latimm committed Oct 11, 2024
1 parent 9a16697 commit 9c6eb93
Show file tree
Hide file tree
Showing 11 changed files with 107 additions and 103 deletions.
24 changes: 15 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,11 @@

![UML](images/classes.svg)

## References

- [Raissi, M. et al.: Physics Informed Deep Learning (Part II)](https://arxiv.org/pdf/1711.10566)

## Requirements
## Setup

### Virtual Environment

#### Windows
#### Windows (Powershell)

```shell
$ python -m venv .venv
Expand All @@ -36,7 +32,7 @@ $ python -m venv .venv
$ source ./venv/bin/activate
```

### Packages
### Dependencies

```shell
$ python -m pip install --upgrade pip
Expand All @@ -47,9 +43,9 @@ $ python -m pip install -r requirements.txt

## Tools

### Navier Stokes Equation
### Navier-Stokes Equation

- [Incompressible Flow](https://en.wikipedia.org/wiki/Navier%E2%80%93Stokes_equations#Incompressible_flow)
- [Wikipedia](https://en.wikipedia.org/wiki/Navier%E2%80%93Stokes_equations#Incompressible_flow)

```
usage: nse [-h] -e {step,block,wing} [-i <intake>] [--nu <nu>] [--rho <rho>] [--id <id>] [-n <train>] [-l <layers>] [-d {cpu,cuda}] [-f] [--supervised] [-p] [-r] [--save]
Expand Down Expand Up @@ -95,3 +91,13 @@ $ python -m src.nse -e wing --id wing -l 100:100:100:100 -i 1 --nu .01 -d cuda -
```shell
$ python -m src.nse -e block
```

### Burgers' Equation

- [Wikipedia](https://en.wikipedia.org/wiki/Burgers%27_equation)

TODO

## References

- [Raissi, M. et al.: Physics Informed Deep Learning (Part II)](https://arxiv.org/pdf/1711.10566)
28 changes: 14 additions & 14 deletions src/base/mesh.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import typing as tp
from abc import abstractmethod

import numpy as np

Expand Down Expand Up @@ -151,6 +152,7 @@ def __init__(self, xs: tp.Sequence[float], ys: tp.Sequence[float]) -> None:
self.__mesh[i][j] = Coordinate(x, y)

def __getattr__(self, item) -> np.ndarray:
# pylint: disable=protected-access
return self.map(lambda i: i.__getattribute__(item)).__mesh

def __iter__(self) -> tp.Iterator:
Expand Down Expand Up @@ -184,6 +186,7 @@ def transform(self, cloud: Cloud):
return self.map(lambda i: cloud[i])

def map(self, f) -> Mesh:
# pylint: disable=protected-access
copy = Mesh([], [])
copy.__mesh = np.array(list(map(lambda i: np.array(list(map(f, i))), self.__mesh.copy())))
copy.__width = self.__width
Expand All @@ -194,7 +197,7 @@ def map(self, f) -> Mesh:
class Cloud:

def __init__(self) -> None:
self.__cloud: dict[Coordinate, tp.Any] = dict()
self.__cloud: dict[Coordinate, ...] = {}

def __contains__(self, coordinate: tuple[float, float] | Coordinate) -> bool:
return Coordinate(*coordinate) in self.__cloud.keys()
Expand All @@ -205,21 +208,13 @@ def __getitem__(self, coordinate: tuple[float, float] | Coordinate) -> tp.Any:
raise KeyError(c)
return self.__cloud[c]

def mesh(self, refine=0) -> Mesh:
xs = sorted({i.x for i in self.__cloud.keys()})
ys = sorted({i.y for i in self.__cloud.keys()})

# if refine > 0:
# xs = (xs[:, None] + np.linspace(0., 1., refine)).ravel()
# print(xs)
# ys = (ys[:, None] + np.linspace(0., 1., refine)).ravel()

return Mesh(xs, ys)
def mesh(self) -> Mesh:
return Mesh(sorted({i.x for i in self.__cloud.keys()}), sorted({i.y for i in self.__cloud.keys()}))

def keys(self) -> list[Coordinate]:
return list(self.__cloud.keys())

def __iter__(self) -> tp.Iterator[tuple[Coordinate, tp.Any]]:
def __iter__(self) -> tp.Iterator[tuple[Coordinate, ...]]:
return iter(self.__cloud.items())

def __len__(self) -> int:
Expand All @@ -231,22 +226,27 @@ def __repr__(self) -> str:
def __str__(self) -> str:
return self.__repr__()

def add(self, coordinate: tuple[float, float] | Coordinate, value: tp.Any) -> tp.Any:
def _insert(self, coordinate: tuple[float, float] | Coordinate, value: ...) -> tp.Any:
c = Coordinate(*coordinate)
if c in self.__cloud:
raise KeyError(c)
self.__cloud[c] = value
return self.__cloud[c]

@abstractmethod
def emplace(self, key: tuple | Coordinate, **kwargs) -> tp.Any:
...

def clear(self) -> None:
self.__cloud.clear()

def copy(self) -> tp.Any:
# pylint: disable=protected-access
cloud = Cloud()
cloud.__cloud = self.__cloud.copy()
return cloud

def detach(self) -> list[tuple[Coordinate, tp.Any]]:
def detach(self) -> list[tuple[Coordinate, ...]]:
return list(self.__cloud.copy().items())

def numpy(self) -> np.ndarray:
Expand Down
29 changes: 14 additions & 15 deletions src/base/plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
import typing as tp
from pathlib import Path

import matplotlib.colors as colors
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import colors
from matplotlib.ticker import FuncFormatter

from src.base.mesh import Coordinate, Cloud
Expand All @@ -27,7 +27,7 @@
SCALE: float = 5.


def draw(ax: plt.Axes, shape: Shape) -> None:
def draw_shape(ax: plt.Axes, shape: Shape) -> None:
polygon = shape[::.01]
ax.plot(polygon.x, polygon.y, color='k', linestyle='--', linewidth=1, zorder=999)

Expand All @@ -50,15 +50,14 @@ def plot_losses(

ax = fig.add_subplot(len(plots), 1, i + 1)

m = np.infty
n = -np.infty
t_min, t_max = np.infty, -np.infty
for j, line in enumerate(lines):
l, y = line

ax.plot(np.arange(1, len(y) + 1, 1), y, label=l, color=COLORS[j])
ax.axhline(y=float(y[-1]), color=COLORS[j], linestyle='--')
m = min(m, min(y))
n = max(n, max(y))
y_min, y_max = min(y), max(y)
t_min, t_max = min(t_min, y_min), max(t_max, y_max)

ax.set_xlabel('iter')
ax.set_ylabel('err')
Expand All @@ -71,7 +70,7 @@ def plot_losses(
ax.set_xlim([1, len(lines[0][1])])
ax.set_xticks([1, 10**np.floor(np.log10(len(lines[0][1])))])
ax.set_yscale('log')
ax.set_yticks([10**np.floor(np.log10(n)), 10**np.floor(np.log10(m)), 10**np.ceil(np.log10(m))])
ax.set_yticks([10**np.floor(np.log10(t_max)), 10**np.floor(np.log10(t_min)), 10**np.ceil(np.log10(t_min))])

ax.legend(loc='upper right')

Expand Down Expand Up @@ -99,7 +98,7 @@ def __init__(self, x: np.ndarray, y: np.ndarray, path: Path = None, n: int = 1)
q = (int(np.round(x.max())) - int(np.round(x.min()))) / (int(np.round(y.max())) - int(np.round(y.min())))
super().__init__(figsize=(q * SCALE, n * SCALE))

def layout(self, ax: plt.Axes, title: str, boundary: Figure = None, figure: Figure = None) -> None:
def setup(self, ax: plt.Axes, title: str, boundary: Figure = None, figure: Figure = None) -> None:
ax.pcolormesh(
self.__x,
self.__y,
Expand All @@ -125,10 +124,10 @@ def layout(self, ax: plt.Axes, title: str, boundary: Figure = None, figure: Figu

if boundary is not None:
for shape in boundary:
draw(ax, shape)
draw_shape(ax, shape)
if figure is not None:
for shape in figure:
draw(ax, shape)
draw_shape(ax, shape)

ax.set_title(title)

Expand Down Expand Up @@ -163,7 +162,7 @@ def plot_heatmaps(
label, z = plot

ax = fig.add_subplot(len(plots), 1, i + 1)
fig.layout(ax, label, boundary, figure)
fig.setup(ax, label, boundary, figure)

if z.min() < 0 < z.max():
slope = colors.TwoSlopeNorm(vmin=z.min(), vcenter=0, vmax=z.max())
Expand Down Expand Up @@ -239,7 +238,7 @@ def plot_heatmaps(
format=FuncFormatter(lambda j, pos: f'{j:.1f}'),
)

ticks = list()
ticks = []
if z.min() < 0:
ticks.append(z.min())
ticks.append(0)
Expand All @@ -262,7 +261,7 @@ def plot_clouds(
plots = []
masks = []

for p, label, in enumerate(labels):
for label, in labels:
plots.append((label, np.full(x.shape, np.nan)))
masks.append(np.full(x.shape, .5))

Expand Down Expand Up @@ -290,7 +289,7 @@ def plot_streamlines(
) -> None:
with Plot(x, y, path) as fig:
ax = fig.add_subplot()
fig.layout(ax, title, boundary, figure)
fig.setup(ax, title, boundary, figure)

speed = np.sqrt(np.square(u) + np.square(v))
speed = 1 + 4 * speed / speed.max()
Expand Down Expand Up @@ -320,7 +319,7 @@ def plot_arrows(
) -> None:
with Plot(x, y, path) as fig:
ax = fig.add_subplot()
fig.layout(ax, title, boundary, figure)
fig.setup(ax, title, boundary, figure)

for i in range(x.shape[0]):
for j in range(x.shape[1]):
Expand Down
2 changes: 1 addition & 1 deletion src/base/shape.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ def __f(self, x) -> tuple[Coordinate, Coordinate]:
return upper, lower

def __contains__(self, coordinate: tuple[float, float] | Coordinate) -> bool:
c = ((Coordinate(*coordinate) - self.__a) / self.__length)
c = (Coordinate(*coordinate) - self.__a) / self.__length
if 0 <= c.x <= 1:
upper, lower = self.__f(c.x)
return lower.y <= c.y <= upper.y
Expand Down
41 changes: 21 additions & 20 deletions src/nse/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def main(
logging.info(f'GRID: {experiment.knowledge.mesh().shape}')
logging.info(f'DIMENSIONS: {experiment.dim}')
logging.info(f'HIRES: {HIRES}')
logging.info(f'STEPS: {args.train}')
logging.info(f'STEPS: {n}')
logging.info(f'TIMESTAMP: {TIMESTAMP}')
logging.info(f'OUTPUT: {(OUTPUT_DIR / identifier).relative_to(ROOT_DIR)}')

Expand Down Expand Up @@ -81,7 +81,7 @@ def callback(history):
logging.info('PLOT: PREDICTION')
plot_prediction(pbar.n, experiment, model, identifier)
logging.info('PLOT: LOSS')
plot_history(pbar.n, experiment, model, identifier)
plot_history(pbar.n, model, identifier)
if hires and pbar.n % 1e4 == 0:
logging.info('PLOT: HIRES PREDICTION')
plot_prediction(pbar.n, experiment, model, identifier, hires=True)
Expand All @@ -100,7 +100,7 @@ def callback(history):
logging.info('PLOT: PREDICTION')
plot_prediction(n, experiment, model, identifier)
logging.info('PLOT: LOSS')
plot_history(pbar.n, experiment, model, identifier)
plot_history(pbar.n, model, identifier)

if hires:
logging.info('PLOT: HIRES PREDICTION')
Expand Down Expand Up @@ -175,6 +175,7 @@ def layers_type(arg: str) -> list[int]:
return layers
except (TypeError, ValueError):
parser.error(f"argument -l/--layers: invalid value: '{arg}'")
return []

parser.add_argument(
'-l',
Expand Down Expand Up @@ -240,12 +241,12 @@ def layers_type(arg: str) -> list[int]:


if __name__ == '__main__':
args = parse_cmd()
if args.plot:
(OUTPUT_DIR / args.id).mkdir(parents=True, exist_ok=args.id != TIMESTAMP)
cmd = parse_cmd()
if cmd.plot:
(OUTPUT_DIR / cmd.id).mkdir(parents=True, exist_ok=cmd.id != TIMESTAMP)
logging.basicConfig(format='%(message)s',
handlers=[
logging.FileHandler(OUTPUT_DIR / args.id / 'log.txt', mode='w'),
logging.FileHandler(OUTPUT_DIR / cmd.id / 'log.txt', mode='w'),
logging.StreamHandler(sys.stdout)
],
encoding='utf-8',
Expand All @@ -258,20 +259,20 @@ def layers_type(arg: str) -> list[int]:

try:
main(
EXPERIMENTS[args.experiment](
args.nu,
args.rho,
args.intake,
args.supervised,
EXPERIMENTS[cmd.experiment](
cmd.nu,
cmd.rho,
cmd.intake,
cmd.supervised,
),
args.train,
args.plot,
args.id,
args.device,
args.foam,
args.hires,
args.save,
args.layers,
cmd.train,
cmd.plot,
cmd.id,
cmd.device,
cmd.foam,
cmd.hires,
cmd.save,
cmd.layers,
)
logging.info('EXIT: SUCCESS')
except KeyboardInterrupt:
Expand Down
4 changes: 2 additions & 2 deletions src/nse/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,8 @@ class NSECloud(Cloud):
def __getitem__(self, key: tuple | Coordinate) -> NSEFact:
return super().__getitem__(key)

def add(self, key: tuple | Coordinate, **kwargs) -> NSEFact:
return super().add(key, NSEFact(**kwargs))
def emplace(self, key: tuple | Coordinate, **kwargs) -> NSEFact:
return super()._insert(key, NSEFact(**kwargs))

def copy(self) -> NSECloud:
return super().copy()
Expand Down
12 changes: 6 additions & 6 deletions src/nse/experiments/block.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,20 +44,20 @@ def __init__(
# inlet
for y in arrange(0, 2, s):
u = inlet(0, 2, flow)(y)
self._knowledge.add((0, y), u=u, v=0)
self._outlet.add((10, y))
self._knowledge.emplace((0, y), u=u, v=0)
self._outlet.emplace((10, y))

# border
for x in arrange(s, 10 - s, s):
self._knowledge.add((x, 0), u=0, v=0)
self._knowledge.add((x, 2), u=0, v=0)
self._knowledge.emplace((x, 0), u=0, v=0)
self._knowledge.emplace((x, 2), u=0, v=0)

for figure in self.obstruction:
for c in figure[::s]:
self._knowledge.add(c, u=0, v=0)
self._knowledge.emplace(c, u=0, v=0)

# training
mesh = Mesh(self.x.arrange(t), self.y.arrange(t))
for c in mesh:
if c not in self._knowledge and c not in self._learning and c not in self.obstruction:
self._learning.add(c)
self._learning.emplace(c)
Loading

0 comments on commit 9c6eb93

Please sign in to comment.