├── tests
├── unit
│ ├── test_dsmc
│ │ ├── __init__.py
│ │ ├── mesh
│ │ │ ├── __init__.py
│ │ │ └── mesh2d.py
│ │ ├── common.py
│ │ ├── diagnostics.py
│ │ ├── dsmc.py
│ │ ├── particles.py
│ │ ├── boundary.py
│ │ └── octree.py
│ ├── main.py
│ └── test_data
│ │ ├── create_test_particles.py
│ │ └── particles.csv
├── misc
│ ├── T_sample.py
│ ├── push_bound_test.py
│ ├── push_bound_open_test.py
│ ├── push_bound_inflow_test.py
│ └── hypersonic_flow_mini.py
├── perfomance
│ ├── integer.py
│ ├── vector3d.py
│ ├── vector.py
│ └── pusher.py
├── diagnostics
│ └── dia_test.py
├── octree
│ └── octree_test.py
└── domain
│ ├── domain_obj.py
│ └── boundary.py
├── dsmc
├── __init__.py
├── mesh
│ ├── __init__.py
│ └── mesh2d.py
├── writer
│ ├── __init__.py
│ ├── particles.py
│ ├── planar.py
│ └── octree.py
├── common.py
├── diagnostics.py
├── particles.py
├── boundary.py
├── octree.py
└── dsmc.py
├── examples
├── heat_bath
│ ├── heat_bath.png
│ └── heat_bath.py
├── shock_tube
│ ├── shock_tube.png
│ ├── ref_data
│ │ ├── sod_p.csv
│ │ ├── sod_T.csv
│ │ ├── sod_n.csv
│ │ └── sod_rho.csv
│ ├── plot.py
│ ├── shock_tube.py
│ └── tools
│ │ └── sod_analytical.py
└── hypersonic_flow
│ ├── hypersonic_flow.png
│ ├── hypersonic_flow_grid.png
│ ├── hypersonic_flow_grid_nrho.png
│ └── hypersonic_flow.py
├── setup.py
├── install_dependencies.sh
├── .circleci
└── config.yml
├── CHANGELOG.md
├── .gitignore
├── doc
├── octree_resolution.ipynb
└── Boundary.ipynb
├── README.md
└── LICENSE
/tests/unit/test_dsmc/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/dsmc/__init__.py:
--------------------------------------------------------------------------------
1 | from .dsmc import DSMC
2 |
--------------------------------------------------------------------------------
/dsmc/mesh/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 |
--------------------------------------------------------------------------------
/tests/unit/test_dsmc/mesh/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 |
--------------------------------------------------------------------------------
/examples/heat_bath/heat_bath.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LeoBasov/dsmc-python/HEAD/examples/heat_bath/heat_bath.png
--------------------------------------------------------------------------------
/examples/shock_tube/shock_tube.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LeoBasov/dsmc-python/HEAD/examples/shock_tube/shock_tube.png
--------------------------------------------------------------------------------
/examples/hypersonic_flow/hypersonic_flow.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LeoBasov/dsmc-python/HEAD/examples/hypersonic_flow/hypersonic_flow.png
--------------------------------------------------------------------------------
/dsmc/writer/__init__.py:
--------------------------------------------------------------------------------
1 | from .octree import write_buttom_leafs
2 | from .planar import write as write_planar
3 | from .particles import write_positions
4 |
--------------------------------------------------------------------------------
/examples/hypersonic_flow/hypersonic_flow_grid.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LeoBasov/dsmc-python/HEAD/examples/hypersonic_flow/hypersonic_flow_grid.png
--------------------------------------------------------------------------------
/examples/hypersonic_flow/hypersonic_flow_grid_nrho.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LeoBasov/dsmc-python/HEAD/examples/hypersonic_flow/hypersonic_flow_grid_nrho.png
--------------------------------------------------------------------------------
/dsmc/writer/particles.py:
--------------------------------------------------------------------------------
1 | def write_positions(particles, file_name="positions.csv"):
2 | with open(file_name, "w") as file:
3 | file.write("x, y, z\n")
4 | for pos in particles.Pos:
5 | file.write("{}, {}, {}\n".format(pos[0], pos[1], pos[2]))
--------------------------------------------------------------------------------
/examples/shock_tube/ref_data/sod_p.csv:
--------------------------------------------------------------------------------
1 | 0.0, 100.0
2 | 0.040318868926081886, 100.0
3 | 0.05, 26.000000000001506
4 | 0.056144031805670194, 26.000000000001506
5 | 0.056144031805670194, 26.000000000001506
6 | 0.06582516287958831, 26.000000000001506
7 | 0.06582516287958831, 10.0
8 | 0.1, 10.0
9 |
--------------------------------------------------------------------------------
/tests/unit/test_dsmc/common.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import dsmc.common as com
3 | import unittest
4 |
5 | class TestCommon(unittest.TestCase):
6 | def test_pass(self):
7 | box = np.array([[-1.0, 1.0], [-1.0, 1.0], [-1.0, 1.0]])
8 | V = com.get_V(box)
9 | self.assertEqual(8.0, V)
--------------------------------------------------------------------------------
/examples/shock_tube/ref_data/sod_T.csv:
--------------------------------------------------------------------------------
1 | 0.0, 300.00043556943234
2 | 0.040318868926081886, 300.00043556943234
3 | 0.05, 174.74734808382354
4 | 0.056144031805670194, 174.74734808382354
5 | 0.056144031805670194, 452.0973458360705
6 | 0.06582516287958831, 452.0973458360705
7 | 0.06582516287958831, 300.0004355694323
8 | 0.1, 300.0004355694323
9 |
--------------------------------------------------------------------------------
/examples/shock_tube/ref_data/sod_n.csv:
--------------------------------------------------------------------------------
1 | 0.0, 2.41432e+22
2 | 0.040318868926081886, 2.41432e+22
3 | 0.05, 1.077654313396024e+22
4 | 0.056144031805670194, 1.077654313396024e+22
5 | 0.056144031805670194, 4.1654133816864355e+21
6 | 0.06582516287958831, 4.1654133816864355e+21
7 | 0.06582516287958831, 2.4143200000000005e+21
8 | 0.1, 2.4143200000000005e+21
9 |
--------------------------------------------------------------------------------
/examples/shock_tube/ref_data/sod_rho.csv:
--------------------------------------------------------------------------------
1 | 0.0, 0.0016036396304
2 | 0.040318868926081886, 0.0016036396304
3 | 0.05, 0.000715799548043907
4 | 0.056144031805670194, 0.000715799548043907
5 | 0.056144031805670194, 0.0002766750876383764
6 | 0.06582516287958831, 0.0002766750876383764
7 | 0.06582516287958831, 0.00016036396304000002
8 | 0.1, 0.00016036396304000002
9 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from setuptools import setup
2 | setup(
3 | name='dsmc',
4 | version='0.10.1',
5 | author='Leo Basov',
6 | python_requires='>=3.10, <4',
7 | packages=["dsmc", "dsmc.writer", "dsmc.mesh"],
8 | install_requires=[
9 | 'numpy',
10 | 'llvmlite',
11 | 'scipy',
12 | 'numba'
13 | ],
14 | )
15 |
--------------------------------------------------------------------------------
/tests/unit/main.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | import unittest
4 |
5 | from test_dsmc.dsmc import *
6 | from test_dsmc.particles import *
7 | from test_dsmc.octree import *
8 | from test_dsmc.diagnostics import *
9 | from test_dsmc.common import *
10 | from test_dsmc.mesh.mesh2d import *
11 | from test_dsmc.boundary import *
12 |
13 | if __name__ == '__main__':
14 | unittest.main()
15 |
--------------------------------------------------------------------------------
/install_dependencies.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | sudo apt update
4 |
5 | sudo apt install -y python3
6 | sudo apt install -y python3-pip
7 | sudo apt install -y python3-dbg
8 |
9 | pip3 install --upgrade pip setuptools wheel
10 |
11 | pip3 install numpy
12 | pip3 install llvmlite
13 | pip3 install scipy
14 | pip3 install numba
15 | pip3 install pytest
16 |
17 | echo "INSTALLATION COMPLETE"
18 |
--------------------------------------------------------------------------------
/tests/unit/test_data/create_test_particles.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 |
3 | if __name__ == "__main__":
4 | N = 100
5 | print("writing {} particles".format(N))
6 | with open("particles.csv", "w") as file:
7 | for i in range(N):
8 | pos = np.random.random(3)*2.0 - np.ones(3)
9 | file.write("{},{},{}\n".format(pos[0], pos[1], pos[2]))
10 |
11 | print("done")
--------------------------------------------------------------------------------
/tests/unit/test_dsmc/diagnostics.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import dsmc.diagnostics as dia
3 | import unittest
4 |
5 | class TestDiagnostics(unittest.TestCase):
6 | def test_sort_bin(self):
7 | positions = np.array(([1, 2, 3], [9, 8, 7], [10, 11, 12], [4, 5, 6]))
8 | Nbins = 4
9 |
10 | bins1, box, x = dia.sort_bin(positions, 0, Nbins)
11 |
12 | self.assertEqual(Nbins, len(bins1))
13 |
14 | for b in bins1:
15 | self.assertEqual(1, len(b))
16 |
17 | self.assertEqual(0, bins1[0][0])
18 | self.assertEqual(3, bins1[1][0])
19 | self.assertEqual(1, bins1[2][0])
20 | self.assertEqual(2, bins1[3][0])
21 |
--------------------------------------------------------------------------------
/dsmc/common.py:
--------------------------------------------------------------------------------
1 | from numba import cfunc, njit
2 | import numba
3 | import numpy.typing as npt
4 |
5 | @cfunc("double(double[::3, ::2])")
6 | def get_V(a):
7 | return (a[0][1] - a[0][0]) * (a[1][1] - a[1][0]) * (a[2][1] - a[2][0])
8 |
9 | @njit((numba.int64[:], numba.int64, numba.int64), cache=True)
10 | def swap(arr, pos1, pos2):
11 | temp = arr[pos2]
12 | arr[pos2] = arr[pos1]
13 | arr[pos1] = temp
14 |
15 | @njit(cache=True)
16 | def is_inside(position : npt.NDArray, box : npt.NDArray) -> bool:
17 | a : bool = position[0] >= box[0][0] and position[0] <= box[0][1]
18 | b : bool = position[1] >= box[1][0] and position[1] <= box[1][1]
19 | c : bool = position[2] >= box[2][0] and position[2] <= box[2][1]
20 |
21 | return a and b and c
--------------------------------------------------------------------------------
/.circleci/config.yml:
--------------------------------------------------------------------------------
1 | version: 2.1
2 |
3 | commands:
4 | set_up_build_environment:
5 | steps:
6 | - checkout
7 | - run:
8 | name: Installing SUDO
9 | command: 'apt-get update && apt install -y sudo && rm -rf /var/lib/apt/lists/*'
10 | - run:
11 | name: Run INSTALL DEPENDENCIES
12 | command: bash install_dependencies.sh
13 | - run:
14 | name: Install DSMC
15 | command: pip3 install .
16 |
17 | run_unit_tests:
18 | steps:
19 | - run:
20 | name: Run UNIT TESTS
21 | command: cd tests/unit/ && python3 main.py -v
22 |
23 | executors:
24 | docker-jammy:
25 | docker:
26 | - image: "ubuntu:jammy"
27 |
28 | jobs:
29 | unit_tests:
30 | executor: docker-jammy
31 | steps:
32 | - set_up_build_environment
33 | - run_unit_tests
34 |
35 | workflows:
36 | build-and-run-tests:
37 | jobs:
38 | - unit_tests
39 |
--------------------------------------------------------------------------------
/tests/misc/T_sample.py:
--------------------------------------------------------------------------------
1 | import dsmc
2 | import dsmc.particles as prt
3 | import matplotlib.pyplot as plt
4 | import numpy as np
5 | import math
6 |
7 | def maxwell(x, T):
8 | return 2.0 * np.sqrt(x) * np.exp(-x/T) / (math.pow(T, 3.0/2.0) * np.sqrt(math.pi))
9 |
10 | def calc_x(velocities, mass):
11 | return np.array([mass*vel.dot(vel)/(2.0*prt.kb) for vel in velocities])
12 |
13 | if __name__ == '__main__':
14 | solver = dsmc.DSMC()
15 | domain = ((-0.1e-3, 0.1e-3), (-0.1e-3, 0.1e-3), (0, 50e-3))
16 | w = 1e6
17 | mass = 6.6422e-26
18 | T = 300
19 | n = 1e+20
20 | Nbins = 100
21 |
22 | solver.set_domain(domain)
23 | solver.set_weight(w)
24 | solver.set_mass(mass)
25 |
26 | solver.create_particles(domain, T, n)
27 |
28 | print(prt.calc_temperature(solver.particles.Vel, mass))
29 |
30 | x = calc_x(solver.particles.Vel, solver.mass)
31 |
32 | xm = np.linspace(0, 3500, 1000)
33 | dist = [maxwell(xi, 300) for xi in xm]
34 |
35 | plt.plot(xm, dist)
36 | plt.hist(x, Nbins, density=True)
37 | plt.show()
38 |
--------------------------------------------------------------------------------
/tests/perfomance/integer.py:
--------------------------------------------------------------------------------
1 | import numba
2 | import time
3 | import numpy as np
4 |
5 | def func(N):
6 | res = 0
7 |
8 | for i in range(N):
9 | res += i
10 |
11 | return res
12 |
13 | @numba.njit(cache=True)
14 | def func_njit(N):
15 | res = 0
16 |
17 | for i in range(N):
18 | res += i
19 |
20 | return res
21 |
22 | @numba.njit(numba.int32(numba.int32), cache=True)
23 | def func_njit_sig(N):
24 | res = 0
25 |
26 | for i in range(N):
27 | res += i
28 |
29 | return res
30 |
31 | def time_f(f, N):
32 | t = time.time()
33 | f(N)
34 | return time.time() - t
35 |
36 | if __name__ == '__main__':
37 | N = 10000000
38 |
39 | t = time_f(func, N)
40 | t_njit = time_f(func_njit, N)
41 | t_njit_sig = time_f(func_njit_sig, N)
42 |
43 | print("base line: {:.3e} ".format(t/t))
44 | print("njit / base line: {:.3e} ".format(t_njit/t))
45 | print("njit + signature / base line: {:.3e} ".format(t_njit_sig/t))
46 | print('done')
--------------------------------------------------------------------------------
/tests/perfomance/vector3d.py:
--------------------------------------------------------------------------------
1 | import numba
2 | import time
3 | import numpy as np
4 |
5 | def func(v):
6 | N = len(v)
7 |
8 | for i in range(N):
9 | v[i] += v[i]
10 |
11 | return v
12 |
13 | @numba.njit(cache=True)
14 | def func_njit(v):
15 | N = len(v)
16 |
17 | for i in range(N):
18 | v[i] += v[i]
19 |
20 | return v
21 |
22 | @numba.njit(numba.float64[:, :](numba.float64[:, :]), cache=True)
23 | def func_njit_sig(v):
24 | N = len(v)
25 |
26 | for i in range(N):
27 | v[i] += v[i]
28 |
29 | return v
30 |
31 | def time_f(f, v):
32 | t = time.time()
33 | f(v)
34 | return time.time() - t
35 |
36 | if __name__ == '__main__':
37 | N = 100000
38 | v = np.random.random((N, 3))
39 |
40 | t = time_f(func, v)
41 | t_njit = time_f(func_njit, v)
42 | t_njit_sig = time_f(func_njit_sig, v)
43 |
44 | print("base line: {:.3e} ".format(t/t))
45 | print("njit / base line: {:.3e} ".format(t_njit/t))
46 | print("njit + signature / base line: {:.3e} ".format(t_njit_sig/t))
47 | print('done')
--------------------------------------------------------------------------------
/tests/perfomance/vector.py:
--------------------------------------------------------------------------------
1 | import numba
2 | import time
3 | import numpy as np
4 |
5 | def func(v):
6 | res = 0.0
7 | N = len(v)
8 |
9 | for i in range(N):
10 | res += v[i]
11 |
12 | return res
13 |
14 | @numba.njit(cache=True)
15 | def func_njit(v):
16 | res = 0.0
17 | N = len(v)
18 |
19 | for i in range(N):
20 | res += v[i]
21 |
22 | return res
23 |
24 | @numba.njit(numba.float64(numba.float64[:]), cache=True)
25 | def func_njit_sig(v):
26 | res = 0.0
27 | N = len(v)
28 |
29 | for i in range(N):
30 | res += v[i]
31 |
32 | return res
33 |
34 | def time_f(f, v):
35 | t = time.time()
36 | f(v)
37 | return time.time() - t
38 |
39 | if __name__ == '__main__':
40 | N = 100000
41 | v = np.random.random(N)
42 |
43 | t = time_f(func, v)
44 | t_njit = time_f(func_njit, v)
45 | t_njit_sig = time_f(func_njit_sig, v)
46 |
47 | print("base line: {:.3e} ".format(t/t))
48 | print("njit / base line: {:.3e} ".format(t_njit/t))
49 | print("njit + signature / base line: {:.3e} ".format(t_njit_sig/t))
50 | print('done')
--------------------------------------------------------------------------------
/tests/misc/push_bound_test.py:
--------------------------------------------------------------------------------
1 | import dsmc
2 | import dsmc.octree as oc
3 | import dsmc.writer as wrt
4 | import numpy as np
5 |
6 | if __name__ == '__main__':
7 | # general parameters
8 | solver = dsmc.DSMC()
9 | tree = oc.Octree()
10 | domain = [(-0.5, 0.5), (-0.5, 0.5), (-0.5, 0.5)]
11 | positions = np.array([(-0.5, -0.5, -0.5), (0.5, 0.5, 0.5)])
12 | dt = 1e-5
13 | w = 1e+17
14 | n = 1e18
15 | mass = 6.6422e-26
16 | T = 300
17 | niter = 300
18 |
19 | # setup solver
20 | solver.set_domain(domain)
21 | solver.set_weight(w)
22 | solver.set_mass(mass)
23 |
24 | solver.create_particles(domain, T, n)
25 |
26 | tree.build(positions)
27 |
28 | for it in range(niter):
29 | print("iteration {:4}/{:4}".format(it + 1, niter), end="\r", flush=True)
30 | solver.advance(dt, collisions=False, octree=False)
31 |
32 | with open("particles_{}.csv".format(it), "w") as file:
33 | file.write("x, y, z\n")
34 | for pos in solver.particles.Pos:
35 | file.write("{},{},{}\n".format(pos[0], pos[1], pos[2]))
36 |
37 | wrt.write_buttom_leafs(tree, "octree.vtu")
38 |
39 |
40 | print("done")
--------------------------------------------------------------------------------
/tests/diagnostics/dia_test.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import dsmc.diagnostics as dia
3 | import dsmc.writer as wrt
4 | import time
5 |
6 | def create_particles(N, radius):
7 | positions = np.empty((N + 1, 3))
8 |
9 | for i in range(N):
10 | phi = np.random.random() * 2.0 * np.pi
11 | theta = np.random.random() * np.pi
12 | r = np.random.normal(0.0, 0.01)
13 | theta1 = np.random.random() * np.pi - 0.5 * np.pi
14 | dis = np.array((r * np.sin(theta) * np.cos(phi), r * np.sin(theta) * np.sin(phi), r * np.cos(theta)))
15 | offset = np.array((radius * np.sin(theta1), radius * np.cos(theta1), 0.0))
16 |
17 | dis += offset;
18 | positions[i] = dis
19 |
20 | positions[N] = np.array((0.0, -1.0, 0.0))
21 |
22 | return positions
23 |
24 | if __name__ == "__main__":
25 | N = 10000
26 | radius = 1.0
27 | positions = create_particles(N, radius)
28 |
29 | # set up sort
30 | Nx = 100
31 | Ny = 100
32 | x0 = -1.5
33 | x1 = 1.5
34 | y0 = -1.5
35 | y1 = 1.5
36 |
37 | start_time = time.time()
38 | boxes, values = dia.analyse_2d(positions, x0, x1, y0, y1, Nx, Ny)
39 | print("--- %s seconds ---" % (time.time() - start_time))
40 |
41 | print("writing to file")
42 |
43 | wrt.write_planar(boxes, values)
44 |
45 | print("done")
--------------------------------------------------------------------------------
/tests/unit/test_dsmc/dsmc.py:
--------------------------------------------------------------------------------
1 | import unittest
2 | import numpy as np
3 | from dsmc import dsmc as ds
4 |
5 | class TestDSMC(unittest.TestCase):
6 | def test_Constructor(self):
7 | ds.DSMC()
8 |
9 | def test__calc_prob(self):
10 | vel1 : np.ndarray = np.array([1.0, 2.0, 3.0])
11 | vel2 : np.ndarray = np.array([1.0, 2.0, 3.0])
12 | vel_rel = np.linalg.norm(vel1 - vel2)
13 | sigma_T : float = 1.0
14 | Vc : float = 1.0
15 | dt : float = 1.0
16 | w : float = 1.0
17 | N : int = 1
18 |
19 | res = ds._calc_prob(vel_rel, sigma_T, Vc, dt, w, N)
20 |
21 | self.assertEqual(np.linalg.norm(vel1 - vel2), res)
22 |
23 | def test__calc_post_col_vels(self):
24 | velocity1 : np.ndarray = np.array([1.0, 2.0, 3.0])
25 | velocity2 : np.ndarray = np.array([1.0, 2.0, 3.0])
26 | mass1 : float = 1.0
27 | mass2 : float = 1.0
28 | rel_vel_module : float = 1.0
29 | rand_number1 : float = 1.0
30 | rand_number2 : float = 1.0
31 |
32 | res = ds._calc_post_col_vels(velocity1, velocity2, mass1, mass2, rel_vel_module, rand_number1, rand_number2)
33 |
34 | self.assertEqual(1.5, res[0][0])
35 | self.assertEqual(2.0, res[0][1])
36 | self.assertEqual(3.0, res[0][2])
37 |
38 | self.assertEqual(0.5, res[1][0])
39 | self.assertEqual(2.0, res[1][1])
40 | self.assertEqual(3.0, res[1][2])
41 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 | All notable changes to this project will be documented in this file.
3 |
4 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
5 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6 |
7 | ## [Unreleased]
8 |
9 | ## [0.10.1] - 2023-03-12
10 | ## Fixed
11 | - use of numba features for marginal performance increase
12 |
13 | ## [0.10.0] - 2022-10-12
14 | ## Added
15 | - possibility to have centre of mass as division point for the octree
16 |
17 | ## [0.9.0] - 2022-10-09
18 | ## Added
19 | - mesh2d as for diagnostic purposes
20 | - particle writer
21 | - docs
22 | - hypersonic test case
23 | - backup boundary module
24 |
25 | ## [0.8.0] - 2022-10-03
26 | ### Added
27 | - planar writer
28 | - planar diagnostic
29 |
30 | ## [0.7.0] - 2022-10-01
31 | ### Added
32 | - inflow boundary condition
33 | - open boundary condition
34 |
35 | ## [0.6.0] - 2022-09-28
36 | ### Added
37 | - functionality for aspect ratio check in octree
38 |
39 | ### Fixed
40 | - bug in temperature initialization
41 | - several bugs in octree
42 |
43 | ## [0.5.1] - 2022-09-24
44 | ### Fixed
45 | - bugs in octree module
46 |
47 | ## [0.5.0] - 2022-09-23
48 | ### Added
49 | - writer module
50 |
51 | ## [0.4.0] - 2022-09-23
52 | ### Added
53 | - dsmc module
54 |
55 | ## [0.3.0] - 2022-09-22
56 | ### Added
57 | - octree module
58 |
59 | ## [0.2.0] - 2022-09-15
60 | ### Added
61 | - particle module
62 |
63 | ## [0.1.0] - 2022-09-15
64 | ### Added
65 | - unit test environment
66 | - cirlce ci integration
67 | - dependency installation script
68 | - dsmc module installation file
69 |
--------------------------------------------------------------------------------
/tests/misc/push_bound_open_test.py:
--------------------------------------------------------------------------------
1 | import dsmc
2 | import dsmc.octree as oc
3 | import dsmc.writer as wrt
4 | import numpy as np
5 |
6 | if __name__ == '__main__':
7 | # general parameters
8 | solver = dsmc.DSMC()
9 | tree = oc.Octree()
10 | domain = [(-0.5, 0.5), (-0.5, 0.5), (-0.5, 0.5)]
11 | positions = np.array([(-0.5, -0.5, -0.5), (0.5, 0.5, 0.5)])
12 | dt = 1e-5
13 | w = 1e+17
14 | n = 1e18
15 | mass = 6.6422e-26
16 | T = 300
17 | niter = 1000
18 |
19 | # setup solver
20 | solver.set_domain(domain)
21 | solver.set_weight(w)
22 | solver.set_mass(mass)
23 |
24 | solver.create_particles(domain, T, n)
25 |
26 | solver.set_bc_type("xmax", "open")
27 | solver.set_bc_type("xmin", "open")
28 | solver.set_bc_type("ymax", "open")
29 | solver.set_bc_type("ymin", "open")
30 | solver.set_bc_type("zmax", "open")
31 | solver.set_bc_type("zmin", "open")
32 |
33 | tree.build(positions)
34 |
35 | for it in range(niter):
36 | print("iteration {:4}/{:4}".format(it + 1, niter), end="\r", flush=True)
37 |
38 | try:
39 | solver.advance(dt, collisions=False, octree=False)
40 | except Exception as e:
41 | print(e)
42 | break
43 |
44 | with open("particles_{}.csv".format(it), "w") as file:
45 | file.write("x, y, z\n")
46 | for pos in solver.particles.Pos:
47 | file.write("{},{},{}\n".format(pos[0], pos[1], pos[2]))
48 |
49 | wrt.write_buttom_leafs(tree, "octree.vtu")
50 |
51 |
52 | print("done")
--------------------------------------------------------------------------------
/tests/misc/push_bound_inflow_test.py:
--------------------------------------------------------------------------------
1 | import dsmc
2 | import dsmc.octree as oc
3 | import dsmc.writer as wrt
4 | import numpy as np
5 |
6 | if __name__ == '__main__':
7 | # general parameters
8 | solver = dsmc.DSMC()
9 | tree = oc.Octree()
10 | domain = [(-0.5, 0.5), (-0.5, 0.5), (-0.5, 0.5)]
11 | positions = np.array([(-0.5, -0.5, -0.5), (0.5, 0.5, 0.5)])
12 | dt = 1e-5
13 | w = 1e+16
14 | n = 1e18
15 | u = np.array([1000.0, 0.0, 0.0])
16 | mass = 6.6422e-26
17 | T = 300
18 | niter = 1000
19 |
20 | # setup solver
21 | solver.set_domain(domain)
22 | solver.set_weight(w)
23 | solver.set_mass(mass)
24 |
25 | solver.create_particles(domain, T, n)
26 |
27 | solver.set_bc_type("xmax", "open")
28 |
29 | solver.set_bc_type("ymax", "open")
30 | solver.set_bc_type("ymin", "open")
31 | solver.set_bc_type("zmax", "open")
32 | solver.set_bc_type("zmin", "open")
33 |
34 | solver.set_bc_type("xmin", "inflow")
35 |
36 | solver.set_bc_values("xmin", T, n, u)
37 |
38 | tree.build(positions)
39 |
40 | for it in range(niter):
41 | print("iteration {:4}/{:4}".format(it + 1, niter), end="\r", flush=True)
42 |
43 | try:
44 | solver.advance(dt, collisions=False, octree=False)
45 | except Exception as e:
46 | print(e)
47 | break
48 |
49 | with open("particles_{}.csv".format(it), "w") as file:
50 | file.write("x, y, z\n")
51 | for pos in solver.particles.Pos:
52 | file.write("{},{},{}\n".format(pos[0], pos[1], pos[2]))
53 |
54 | wrt.write_buttom_leafs(tree, "octree.vtu")
55 |
56 |
57 | print("done")
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | *.egg-info/
24 | .installed.cfg
25 | *.egg
26 | MANIFEST
27 |
28 | # PyInstaller
29 | # Usually these files are written by a python script from a template
30 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
31 | *.manifest
32 | *.spec
33 |
34 | # Installer logs
35 | pip-log.txt
36 | pip-delete-this-directory.txt
37 |
38 | # Unit test / coverage reports
39 | htmlcov/
40 | .tox/
41 | .coverage
42 | .coverage.*
43 | .cache
44 | nosetests.xml
45 | coverage.xml
46 | *.cover
47 | .hypothesis/
48 | .pytest_cache/
49 |
50 | # Translations
51 | *.mo
52 | *.pot
53 |
54 | # Django stuff:
55 | *.log
56 | local_settings.py
57 | db.sqlite3
58 |
59 | # Flask stuff:
60 | instance/
61 | .webassets-cache
62 |
63 | # Scrapy stuff:
64 | .scrapy
65 |
66 | # Sphinx documentation
67 | docs/_build/
68 |
69 | # PyBuilder
70 | target/
71 |
72 | # Jupyter Notebook
73 | .ipynb_checkpoints
74 |
75 | # pyenv
76 | .python-version
77 |
78 | # celery beat schedule file
79 | celerybeat-schedule
80 |
81 | # SageMath parsed files
82 | *.sage.py
83 |
84 | # Environments
85 | .env
86 | .venv
87 | env/
88 | venv/
89 | ENV/
90 | env.bak/
91 | venv.bak/
92 |
93 | # Spyder project settings
94 | .spyderproject
95 | .spyproject
96 |
97 | # Rope project settings
98 | .ropeproject
99 |
100 | # mkdocs documentation
101 | /site
102 |
103 | # mypy
104 | .mypy_cache/
105 |
--------------------------------------------------------------------------------
/examples/shock_tube/plot.py:
--------------------------------------------------------------------------------
1 | import matplotlib.pyplot as plt
2 | import csv
3 | import numpy as np
4 |
5 | def read_data(file_name):
6 | with open(file_name) as file:
7 | reader = csv.reader(file, delimiter=',')
8 |
9 | for line in reader:
10 | l = [m for m in line if m]
11 | data = [float(l[i]) for i in range(len(l))]
12 |
13 | return data
14 |
15 | def read_ref_data(file_name):
16 | x = []
17 | val = []
18 | with open(file_name) as file:
19 | reader = csv.reader(file, delimiter=',')
20 |
21 | for line in reader:
22 | x.append(float(line[0]))
23 | val.append(float(line[1]))
24 |
25 | return x, val
26 |
27 | if __name__ == '__main__':
28 | n = read_data("n.csv")
29 | p = read_data("p.csv")
30 | T = read_data("T.csv")
31 |
32 | x_n, n_ref = read_ref_data("ref_data/sod_n.csv")
33 | p_n, p_ref = read_ref_data("ref_data/sod_p.csv")
34 | T_n, T_ref = read_ref_data("ref_data/sod_T.csv")
35 |
36 | fig, (ax0, ax1, ax2) = plt.subplots(nrows=1, ncols=3, figsize=(20, 6))
37 |
38 | ax0.plot(np.linspace(0, 0.1, len(n)), n)
39 | ax0.plot(x_n, n_ref)
40 | ax0.set_xlim([0, 0.1])
41 | ax0.set_ylim([0, 3e+22])
42 | ax0.set_title("number denisty")
43 | ax0.set_xlabel("L / m")
44 | ax0.set_ylabel("n / m^(-3)")
45 |
46 | ax1.plot(np.linspace(0, 0.1, len(n)), T)
47 | ax1.plot(T_n, T_ref)
48 | ax1.set_xlim([0, 0.1])
49 | ax1.set_ylim([150, 500])
50 | ax1.set_title("temperature")
51 | ax1.set_xlabel("L / m")
52 | ax1.set_ylabel("T / K")
53 |
54 | ax2.plot(np.linspace(0, 0.1, len(n)), p)
55 | ax2.plot(p_n, p_ref)
56 | ax2.set_xlim([0, 0.1])
57 | ax2.set_ylim([0, 120])
58 | ax2.set_title("pressure")
59 | ax2.set_xlabel("L / m")
60 | ax2.set_ylabel("p / Pa")
61 |
62 | plt.show()
63 |
--------------------------------------------------------------------------------
/doc/octree_resolution.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": 1,
6 | "id": "9db716f6-c301-4d2e-b06f-19cd98de2e5f",
7 | "metadata": {},
8 | "outputs": [],
9 | "source": [
10 | "import math"
11 | ]
12 | },
13 | {
14 | "cell_type": "markdown",
15 | "id": "772d42fa-dc37-48e9-a599-392077582e98",
16 | "metadata": {},
17 | "source": [
18 | "The mean free path can be written as\n",
19 | "$$\n",
20 | "\\lambda = \\frac{1}{\\sqrt{2} \\cdot n_{c} \\cdot \\sigma_T}\n",
21 | "$$\n",
22 | "where $n_c$ is the number density in the cell and $\\sigma_T$ is the total cross section.\n",
23 | "The number of particles in cell $N_{c}$ can be calculated as (asuming cubic cells)\n",
24 | "$$\n",
25 | "N_{c} = \\frac{1}{w} \\cdot L_c^3 \\cdot n_c\n",
26 | "$$\n",
27 | "where $L_C$ is the side length of the cell and $w$ being the particle weight.\n",
28 | "Assuming that the cell side fullfills the criteria\n",
29 | "$$\n",
30 | "\\frac{L_c}{\\lambda} \\leq \\frac{1}{2}.\n",
31 | "$$\n",
32 | "This leads to the criterium\n",
33 | "$$\n",
34 | "N \\leq \\frac{\\sqrt{2}}{32 \\cdot w \\cdot \\sigma^2_T \\cdot n^3_c}\n",
35 | "$$"
36 | ]
37 | },
38 | {
39 | "cell_type": "code",
40 | "execution_count": null,
41 | "id": "4f03b0f7-64a9-48e5-989c-2e253ce09c1d",
42 | "metadata": {},
43 | "outputs": [],
44 | "source": []
45 | }
46 | ],
47 | "metadata": {
48 | "kernelspec": {
49 | "display_name": "Python 3 (ipykernel)",
50 | "language": "python",
51 | "name": "python3"
52 | },
53 | "language_info": {
54 | "codemirror_mode": {
55 | "name": "ipython",
56 | "version": 3
57 | },
58 | "file_extension": ".py",
59 | "mimetype": "text/x-python",
60 | "name": "python",
61 | "nbconvert_exporter": "python",
62 | "pygments_lexer": "ipython3",
63 | "version": "3.9.12"
64 | }
65 | },
66 | "nbformat": 4,
67 | "nbformat_minor": 5
68 | }
69 |
--------------------------------------------------------------------------------
/examples/shock_tube/shock_tube.py:
--------------------------------------------------------------------------------
1 | import dsmc
2 | import dsmc.diagnostics as dia
3 | import time
4 |
5 | def write2file(solver, Nbins):
6 | # open files
7 | n_file = open("n.csv", "w")
8 | T_file = open("T.csv", "w")
9 | p_file = open("p.csv", "w")
10 |
11 | bins, box, x = dia.sort_bin(solver.particles.Pos, 2, Nbins)
12 | n = dia.calc_n(bins, box, 2, solver.w)
13 | T = dia.calc_T(bins, solver.particles.Vel, mass)
14 | p = dia.calc_p(n, T)
15 |
16 | for i in range(Nbins):
17 | n_file.write("{},".format(n[i]))
18 | T_file.write("{},".format(T[i]))
19 | p_file.write("{},".format(p[i]))
20 |
21 | n_file.write("\n")
22 | T_file.write("\n")
23 | p_file.write("\n")
24 |
25 | # close files
26 | n_file.close()
27 | T_file.close()
28 | p_file.close()
29 |
30 | if __name__ == '__main__':
31 | # general parameters
32 | solver = dsmc.DSMC()
33 | domain = [(-0.0001, 0.0001), (-0.0001, 0.0001), (0.0, 0.1)]
34 | dt = 1e-7
35 | w = 1e+8
36 | mass = 6.6422e-26
37 | niter = 300
38 | Nbins = 1000
39 |
40 | # high denisty particles
41 | nhigh = 2.41432e+22
42 | Thigh = 300
43 | Boxhigh = [(-0.0001, 0.0001), (-0.0001, 0.0001), (0.0, 0.05)]
44 |
45 | # low denisty particles
46 | nlow = nhigh*0.1
47 | Tlow = 300
48 | Boxlow = [(-0.0001, 0.0001), (-0.0001, 0.0001), (0.05, 0.1)]
49 |
50 | # setup solver
51 | solver.set_domain(domain)
52 | solver.set_weight(w)
53 | solver.set_mass(mass)
54 |
55 | solver.create_particles(Boxlow, Tlow, nlow)
56 | solver.create_particles(Boxhigh, Thigh, nhigh)
57 |
58 | # start timing
59 | start_time = time.time()
60 |
61 | for it in range(niter):
62 | print("iteration {:4}/{}".format(it + 1, niter), end="\r", flush=True)
63 | solver.advance(dt)
64 |
65 | print("")
66 | print("--- %s seconds ---" % (time.time() - start_time))
67 |
68 | write2file(solver, Nbins)
69 |
70 | print('done')
71 |
--------------------------------------------------------------------------------
/tests/misc/hypersonic_flow_mini.py:
--------------------------------------------------------------------------------
1 | import dsmc
2 | import dsmc.writer as wrt
3 | import dsmc.octree as oc
4 | import time
5 | import numpy as np
6 |
7 | if __name__ == '__main__':
8 | # general parameters
9 | solver = dsmc.DSMC()
10 | domain = [(-3.0, 3.0), (-1.5, 1.5), (-0.025, 0.025)]
11 | obj = [(-0.25, 0.25), (-0.25, 0.25), (-0.5, 0.5)]
12 | dt = 1e-6
13 | w = 0.2 * 2.3e+15
14 | mass = 6.6422e-26
15 | T = 273.0
16 | n = 2.6e+19
17 | u = np.array([0.0, -3043.0, 0.0])
18 | niter = 500
19 |
20 | h = domain[2][1] - domain[2][0]
21 |
22 | # setup solver
23 | solver.set_domain(domain)
24 | solver.set_weight(w)
25 | solver.set_mass(mass)
26 |
27 | # set object
28 | solver.add_object(obj)
29 |
30 | # trees
31 | tree_inner = oc.Octree()
32 | tree_outer = oc.Octree()
33 |
34 | inner_pos = np.array([[-0.25, -0.25, -0.025], [0.25, 0.25, 0.025]])
35 | outer_pos = np.array([[-3.0, -1.5, -0.025], [3.0, 1.5, 0.025]])
36 |
37 | tree_inner.build(inner_pos)
38 | tree_outer.build(outer_pos)
39 |
40 | # create particles
41 | positions = np.zeros((2, 3))
42 | velocities = np.zeros((2, 3))
43 |
44 | positions[0][0] = -0.01
45 | positions[0][1] = 1.4
46 | positions[0][2] = -0.01
47 |
48 | positions[1][0] = 0.01
49 | positions[1][1] = 1.3
50 | positions[1][2] = 0.01
51 |
52 | velocities[0][1] = -3043.0
53 | velocities[1][1] = -3043.0
54 |
55 | solver.particles.VelPos = (velocities, positions)
56 |
57 | # start timing
58 | start_time = time.time()
59 |
60 | for it in range(niter):
61 | print("iteration {:4}/{}".format(it + 1, niter), end="\r", flush=True)
62 | solver.advance(dt)
63 | wrt.write_positions(solver.particles, "pos_{}.csv".format(it))
64 |
65 | wrt.write_buttom_leafs(tree_inner, "innter.vtu")
66 | wrt.write_buttom_leafs(tree_outer, "outer.vtu")
67 |
68 | print("")
69 | print("--- %s seconds ---" % (time.time() - start_time))
70 | print('done')
--------------------------------------------------------------------------------
/tests/octree/octree_test.py:
--------------------------------------------------------------------------------
1 | import dsmc.writer as wrt
2 | import dsmc.octree as oc
3 | import numpy as np
4 | import argparse
5 |
6 | def create_particles(N, radius):
7 | positions = np.empty((N + 1, 3))
8 |
9 | for i in range(N):
10 | phi = np.random.random() * 2.0 * np.pi
11 | theta = np.random.random() * np.pi
12 | r = np.random.normal(0.0, 0.01)
13 | theta1 = np.random.random() * np.pi - 0.5 * np.pi
14 | dis = np.array((r * np.sin(theta) * np.cos(phi), r * np.sin(theta) * np.sin(phi), r * np.cos(theta)))
15 | offset = np.array((radius * np.sin(theta1), radius * np.cos(theta1), 0.0))
16 |
17 | dis += offset;
18 | positions[i] = dis
19 |
20 | positions[N] = np.array((0.0, -1.0, 0.0))
21 |
22 | return positions
23 |
24 | if __name__ == "__main__":
25 | parser = argparse.ArgumentParser(description='Process some integers.')
26 | parser.add_argument('N', type=int)
27 |
28 | args = parser.parse_args()
29 |
30 | radius = 1.0
31 | positions = create_particles(args.N, radius)
32 | octree = oc.Octree()
33 | octree.build(positions)
34 | wrt.write_buttom_leafs(octree)
35 |
36 | for i in range(len(octree.leafs)):
37 | box = octree.cell_boxes[i]
38 | leaf = octree.leafs[i]
39 | N = 0
40 | for j in range(leaf.elem_offset, leaf.elem_offset + leaf.number_elements):
41 | p = octree.permutations[j]
42 | pos = positions[p]
43 |
44 | if oc._is_inside(pos, box):
45 | N += 1
46 | else:
47 | raise Exception(pos, box)
48 |
49 | if N != leaf.number_elements:
50 | raise Exception(N, leaf.number_elements, box)
51 |
52 | with open("particles.csv", "w") as file:
53 | file.write("x, y, z\n")
54 |
55 | for i in range(len(octree.leafs)):
56 | leaf = octree.leafs[i]
57 | if leaf.number_children == 0 and leaf.number_elements > 0:
58 | for j in range(leaf.elem_offset, leaf.elem_offset + leaf.number_elements):
59 | p = octree.permutations[j]
60 | pos = positions[p]
61 | file.write("{}, {}, {}\n".format(pos[0], pos[1], pos[2]))
62 |
63 | print("done")
64 |
--------------------------------------------------------------------------------
/tests/perfomance/pusher.py:
--------------------------------------------------------------------------------
1 | import numba
2 | import numpy as np
3 | import time
4 |
5 | def _push(velocities, positions, dt):
6 | old_positions = np.copy(positions)
7 | for p in numba.prange(len(positions)):
8 | positions[p] = positions[p] + velocities[p]*dt
9 | return (velocities, positions, old_positions)
10 |
11 | def push(velocities, positions, dt):
12 | N = len(positions)
13 | for p in numba.prange(N):
14 | positions[p] = positions[p] + velocities[p]*dt
15 | return positions
16 |
17 | @numba.njit(cache=True)
18 | def push_njit(velocities, positions, dt):
19 | N = len(positions)
20 | for p in numba.prange(N):
21 | positions[p] = positions[p] + velocities[p]*dt
22 | return positions
23 |
24 | @numba.njit(numba.float64[:, :](numba.float64[:, :], numba.float64[:, :], numba.float64), cache=True)
25 | def push_njit_sig(velocities, positions, dt):
26 | N = len(positions)
27 | for p in numba.prange(N):
28 | positions[p] = positions[p] + velocities[p]*dt
29 | return positions
30 |
31 | @numba.njit(numba.float64[:, :](numba.float64[:, :], numba.float64[:, :], numba.float64), cache=True, parallel=True)
32 | def push_njit_sig_par(velocities, positions, dt):
33 | N = len(positions)
34 | for p in numba.prange(N):
35 | positions[p] += velocities[p]*dt
36 | return positions
37 |
38 | def time_f(f, v, p, dt):
39 | t = time.time()
40 | f(v, p, dt)
41 | return time.time() - t
42 |
43 | if __name__ == '__main__':
44 | N = 100000
45 | v = np.random.random((N, 3))
46 | p = np.random.random((N, 3))
47 | dt = 1e-6
48 |
49 | t = time_f(_push, v, p, dt)
50 | t_new = time_f(push, v, p, dt)
51 | t_njit = time_f(push_njit, v, p, dt)
52 | t_njit_sig = time_f(push_njit_sig, v, p, dt)
53 | t_njit_sig_par = time_f(push_njit_sig_par, v, p, dt)
54 |
55 | print("base line: {:.3e} ".format(t/t))
56 | print("new / base line: {:.3e} ".format(t_new/t))
57 | print("new / base line: {:.3e} ".format(t_njit/t))
58 | print("njit + signature / base line: {:.3e} ".format(t_njit_sig/t))
59 | print("njit + signature + par / base line: {:.3e} ".format(t_njit_sig_par/t))
60 | print('done')
--------------------------------------------------------------------------------
/examples/heat_bath/heat_bath.py:
--------------------------------------------------------------------------------
1 | import dsmc
2 | import dsmc.particles as prt
3 | import matplotlib.pyplot as plt
4 | import numpy as np
5 | import numba
6 | import math
7 | import time
8 |
9 | @numba.njit(numba.float64(numba.float64, numba.float64))
10 | def maxwell(x, T):
11 | return 2.0 * np.sqrt(x) * np.exp(-x/T) / (math.pow(T, 3.0/2.0) * np.sqrt(math.pi))
12 |
13 | @numba.njit(numba.float64[:](numba.float64[:, :], numba.float64))
14 | def calc_x(velocities, mass):
15 | return np.array([mass*vel.dot(vel)/(2.0*prt.kb) for vel in velocities])
16 |
17 | if __name__ == '__main__':
18 | # general parameters
19 | solver = dsmc.DSMC()
20 | domain = ((-1.0e-3, 1.0e-3), (-1.0e-3, 1.0e-3), (-1.0e-3, 1.0e-3))
21 | dt = 1e-5
22 | w = 0.5e+8
23 | mass = 6.6422e-26
24 | niter = 100
25 | Nbins = 200
26 |
27 | # particles
28 | n = 1.0e+20
29 | T = 300
30 | u = np.array((1000.0, 0.0, 0.0))
31 |
32 |
33 | solver.set_domain(domain)
34 | solver.set_weight(w)
35 | solver.set_mass(mass)
36 |
37 | solver.create_particles(domain, T, n, u)
38 |
39 | # time
40 | start_time = time.time()
41 |
42 | # set up plot
43 | xmax = 15000
44 |
45 | Tnew = prt.calc_temperature(solver.particles.Vel, solver.mass)
46 | xm = np.linspace(0, xmax, 1000)
47 | dist = [maxwell(xi, Tnew) for xi in xm]
48 | x = calc_x(solver.particles.Vel, solver.mass)
49 |
50 | fig, (ax0, ax1) = plt.subplots(nrows=1, ncols=2, figsize=(16, 6))
51 |
52 | ax0.plot(xm, dist)
53 | ax0.hist(x, Nbins, density=True)
54 | ax0.set_ylabel("probabilty density")
55 | ax0.set_xlabel("m v^2 / (2 kb)")
56 | ax0.set_title("initial condition")
57 | ax0.set_xlim([0, xmax])
58 | ax0.set_ylim([0, 0.00040])
59 |
60 | for it in range(niter):
61 | print("iteration {:4}/{}".format(it + 1, niter), end="\r", flush=True)
62 | solver.advance(dt)
63 | x = calc_x(solver.particles.Vel, solver.mass)
64 |
65 | print("")
66 | print("--- %s seconds ---" % (time.time() - start_time))
67 |
68 | ax1.plot(xm, dist)
69 | ax1.hist(x, Nbins, density=True)
70 | ax1.set_ylabel("probabilty density")
71 | ax1.set_xlabel("m v^2 / (2 kb)")
72 | ax1.set_title("final condition")
73 | ax1.set_xlim([0, xmax])
74 | ax1.set_ylim([0, 0.00040])
75 |
76 | fig.suptitle("Argon Heat Bath")
77 | plt.show()
78 |
79 | print('done')
80 |
--------------------------------------------------------------------------------
/tests/domain/domain_obj.py:
--------------------------------------------------------------------------------
1 | import dsmc
2 | import dsmc.octree as oc
3 | import dsmc.writer as wrt
4 | import time
5 | import numpy as np
6 |
7 | def create_pos_and_vels():
8 | positions = np.zeros((6, 3))
9 | velocitiies = np.zeros((6, 3))
10 |
11 | # x
12 | positions[0][0] = -0.75
13 | velocitiies[0][0] = 1.0
14 |
15 | positions[1][0] = 0.75
16 | velocitiies[1][0] = -1.0
17 |
18 | # y
19 | positions[2][1] = -0.75
20 | velocitiies[2][1] = 1.0
21 |
22 | positions[3][1] = 0.75
23 | velocitiies[3][1] = -1.0
24 |
25 | # z
26 | positions[4][2] = -0.75
27 | velocitiies[4][2] = 1.0
28 |
29 | positions[5][2] = 0.75
30 | velocitiies[5][2] = -1.0
31 |
32 | return (velocitiies, positions)
33 |
34 | def write_partices(positions, it):
35 | with open("particles_{}.csv".format(it), "w") as file:
36 | file.write("x, y, z\n")
37 | for pos in positions:
38 | file.write("{}, {}, {}\n".format(pos[0], pos[1], pos[2]))
39 |
40 | if __name__ == '__main__':
41 | # general parameters
42 | solver = dsmc.DSMC()
43 | domain = [(-1.0, 1.0), (-1.0, 1.0), (-1.0, 1.0)]
44 | obj = [(-0.5, 0.5), (-0.5, 0.5), (-0.5, 0.5)]
45 | dt = 0.01
46 | w = 2.3e+14
47 | mass = 6.6422e-26
48 | T = 273.0
49 | n = 2.6e+19
50 | niter = 200
51 |
52 | # trees
53 | tree_inner = oc.Octree()
54 | tree_outer = oc.Octree()
55 |
56 | inner_pos = np.array([[-0.5, -0.5, -0.5], [0.5, 0.5, 0.5]])
57 | outer_pos = np.array([[-1.0, -1.0, -1.0], [1.0, 1.0, 1.0]])
58 |
59 | tree_inner.build(inner_pos)
60 | tree_outer.build(outer_pos)
61 |
62 | # setup solver
63 | solver.set_domain(domain)
64 | solver.set_weight(w)
65 | solver.set_mass(mass)
66 |
67 | # set object
68 | solver.add_object(obj)
69 |
70 | # create particles
71 | solver.particles.VelPos = create_pos_and_vels()
72 |
73 | # start timing
74 | start_time = time.time()
75 |
76 | for it in range(niter):
77 | print("iteration {:4}/{}".format(it + 1, niter), end="\r", flush=True)
78 | solver.advance(dt, octree=False)
79 | write_partices(solver.particles.Pos, it)
80 |
81 | wrt.write_buttom_leafs(tree_inner, "inner_box.vtu")
82 | wrt.write_buttom_leafs(tree_outer, "outer_box.vtu")
83 |
84 | print("")
85 | print("--- %s seconds ---" % (time.time() - start_time))
86 | print('done')
--------------------------------------------------------------------------------
/dsmc/writer/planar.py:
--------------------------------------------------------------------------------
1 | def write(boxes, values, file_name="planar.vtu"):
2 | f = open(file_name, "w")
3 |
4 | _write_header(f)
5 | _wrtie_body(f, boxes, values)
6 | _write_footer(f)
7 |
8 | f.close()
9 |
10 | def _write_header(f):
11 | f.write("\n")
12 |
13 | def _wrtie_body(f, boxes, values):
14 | f.write("\n")
15 | f.write("\n".format(len(boxes) * 4, len(boxes)))
16 |
17 | _write_points(f, boxes)
18 | _write_cells(f, boxes)
19 | _write_cell_data(f, boxes, values)
20 |
21 | f.write("\n")
22 | f.write("\n")
23 |
24 | def _write_points(f, boxes):
25 | f.write("\n")
26 | f.write("\n")
27 |
28 | for box in boxes:
29 | f.write("{} ".format(box[0][0]))
30 | f.write("{} ".format(box[1][0]))
31 | f.write("{} ".format(0.0))
32 |
33 | f.write("{} ".format(box[0][1]))
34 | f.write("{} ".format(box[1][0]))
35 | f.write("{} ".format(0.0))
36 |
37 | f.write("{} ".format(box[0][1]))
38 | f.write("{} ".format(box[1][1]))
39 | f.write("{} ".format(0.0))
40 |
41 | f.write("{} ".format(box[0][0]))
42 | f.write("{} ".format(box[1][1]))
43 | f.write("{} ".format(0.0))
44 |
45 | f.write("\n")
46 | f.write("\n")
47 |
48 |
49 | def _write_cells(f, boxes):
50 | k = 0
51 |
52 | f.write("\n")
53 | f.write("\n")
54 |
55 | for i in range(len(boxes)):
56 | for _ in range(4):
57 | f.write("{} ".format(k))
58 | k += 1
59 |
60 | f.write("\n")
61 | f.write("\n")
62 |
63 | for i in range(len(boxes)):
64 | f.write("{} ".format((i + 1) * 4))
65 |
66 | f.write("\n")
67 | f.write("\n")
68 |
69 | for _ in range(len(boxes)):
70 | f.write("9 ")
71 |
72 | f.write("\n")
73 | f.write("\n")
74 |
75 | def _write_cell_data(f, boxes, values):
76 | f.write("\n")
77 | f.write("\n")
78 |
79 | for vals in values:
80 | f.write("{} ".format(vals.number_elements))
81 |
82 | f.write("\n")
83 | f.write("\n")
84 |
85 | def _write_footer(f):
86 | f.write("\n")
87 |
--------------------------------------------------------------------------------
/dsmc/diagnostics.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | from . import particles as prt
3 | from . import octree as oc
4 | #from . import common as com
5 |
6 | class Values:
7 | def __init__(self):
8 | self.number_elements = 0
9 |
10 | def calc_vals(self, positions, velocities, ids, box):
11 | #V = com.get_V(box)
12 | self.number_elements = len(ids)
13 |
14 |
15 | def analyse_2d(positions, velocities, mesh2d, h):
16 | boxes = np.empty((len(mesh2d.cells), 3, 2))
17 | values = [Values() for _ in range(len(mesh2d.cells))]
18 |
19 | for y in range(mesh2d.n_cells2):
20 | for x in range(mesh2d.n_cells1):
21 | N = x + y * mesh2d.n_cells1
22 |
23 | boxes[N][0][0] = mesh2d.min1 + mesh2d.cell_size1*x
24 | boxes[N][0][1] = mesh2d.min1 + mesh2d.cell_size1*(x + 1)
25 | boxes[N][1][0] = mesh2d.min2 + mesh2d.cell_size2*y
26 | boxes[N][1][1] = mesh2d.min2 + mesh2d.cell_size2*(y + 1)
27 | boxes[N][2][0] = 0.0
28 | boxes[N][2][1] = h
29 |
30 | values[N].calc_vals(positions, velocities, mesh2d.cells[N], boxes[N])
31 |
32 | return (boxes, values)
33 |
34 |
35 | def sort_bin(positions, axis, Nbin):
36 | bins = [[] for _ in range(Nbin)]
37 | b = 0
38 | box = oc._find_bounding_box(positions)
39 | dx = (box[axis][1] - box[axis][0]) / (Nbin - 1)
40 | xx = [dx]
41 | x = dx
42 | sub_pos = np.array([pos[axis] for pos in positions])
43 | sorted_pos = np.argsort(sub_pos)
44 |
45 | for i in range(len(sorted_pos)):
46 | p = sorted_pos[i]
47 | while positions[p][axis] > x:
48 | x += dx
49 | b += 1
50 | xx.append(x)
51 |
52 | bins[b].append(p)
53 |
54 | return bins, box, xx
55 |
56 | def calc_n(bins, box, axis, w):
57 | Nbins = len(bins)
58 | V = 1
59 | n = np.empty((Nbins, ))
60 | for i in range(3):
61 | if i == axis:
62 | V *= (box[i][1] - box[i][0]) / Nbins
63 | else:
64 | V *= (box[i][1] - box[i][0])
65 |
66 | for i in range(Nbins):
67 | n[i] = len(bins[i]) * w / V
68 |
69 | return n
70 |
71 | def calc_T(bins, velocities, mass):
72 | Nbins = len(bins)
73 | T = np.empty((Nbins, ))
74 |
75 | for i in range(Nbins):
76 | vels = np.array([velocities[p] for p in bins[i]])
77 | T[i] = prt.calc_temperature(vels, mass)
78 |
79 | return T
80 |
81 | def calc_p(n, T):
82 | Nbins = len(n)
83 | p = np.empty((Nbins, ))
84 |
85 | for i in range(Nbins):
86 | p[i] = n[i]*T[i]*prt.kb
87 |
88 | return p
89 |
--------------------------------------------------------------------------------
/tests/domain/boundary.py:
--------------------------------------------------------------------------------
1 | import dsmc.dsmc as ds
2 | import dsmc.particles as prt
3 | import dsmc.octree as oc
4 | import dsmc.writer as wrt
5 | import dsmc.boundary as bo
6 | import dsmc.common as co
7 | import time
8 | import numpy as np
9 |
10 | def create_pos_and_vels():
11 | positions = np.zeros((6, 3))
12 | velocitiies = np.zeros((6, 3))
13 |
14 | # x
15 | positions[0][0] = -0.75
16 | velocitiies[0][0] = 100.0
17 |
18 | positions[1][0] = 0.75
19 | velocitiies[1][0] = -100.0
20 |
21 | # y
22 | positions[2][1] = -0.75
23 | velocitiies[2][1] = 100.0
24 |
25 | positions[3][1] = 0.75
26 | velocitiies[3][1] = -100.0
27 |
28 | # z
29 | positions[4][2] = -0.75
30 | velocitiies[4][2] = 100.0
31 |
32 | positions[5][2] = 0.75
33 | velocitiies[5][2] = -100.0
34 |
35 | return (velocitiies, positions)
36 |
37 | if __name__ == '__main__':
38 | # general parameters
39 | boundary = bo.Boundary()
40 | particles = prt.Particles()
41 | domain = np.array([(-1.0, 1.0), (-1.0, 1.0), (-1.0, 1.0)])
42 | dt = 0.0001
43 | w = 2.3e+16
44 | mass = 6.6422e-26
45 | T = 273.0
46 | n = 2.6e+19
47 | N = int(co.get_V(domain)*n/w)
48 | niter = 1000
49 |
50 | # trees
51 | tree_outer = oc.Octree()
52 | outer_pos = np.array([[-1.0, -1.0, -1.0], [1.0, 1.0, 1.0]])
53 | tree_outer.build(outer_pos)
54 | #wrt.write_buttom_leafs(tree_outer, "outer_box.vtu")
55 |
56 | # setup solver
57 | boundary.domain = domain
58 |
59 | # create particles
60 | particles.create_particles(domain, mass, T, N)
61 |
62 | velocities, positions = particles.VelPos
63 |
64 | #particles.VelPos = create_pos_and_vels()
65 |
66 | # start timing
67 | start_time = time.time()
68 |
69 | wrt.write_positions(particles, "pos_{}.csv".format(0))
70 |
71 | E0 = 0.0
72 |
73 | for vel in particles.Vel:
74 | E0 += vel.dot(vel)
75 |
76 | for it in range(niter):
77 | E = 0.0
78 |
79 | velocities, positions, old_positions = ds._push(particles.Vel, particles.Pos, dt)
80 | velocities, positions, old_positions = boundary.boundary(velocities, positions, old_positions)
81 |
82 | particles.VelPos = (velocities, positions)
83 | wrt.write_positions(particles, "pos_{}.csv".format(it + 1))
84 |
85 | for vel in particles.Vel:
86 | E += vel.dot(vel)
87 |
88 | print("iteration {:4}/{}, N particles {}/{}, Efrac {}".format(it + 1, niter, particles.N, N, E/E0), end="\r", flush=True)
89 |
90 |
91 | print("")
92 | print("--- %s seconds ---" % (time.time() - start_time))
93 | print('done')
--------------------------------------------------------------------------------
/examples/hypersonic_flow/hypersonic_flow.py:
--------------------------------------------------------------------------------
1 | import dsmc
2 | import dsmc.writer as wrt
3 | import dsmc.diagnostics as dia
4 | import dsmc.mesh.mesh2d as msh2d
5 | import dsmc.octree as oc
6 | import time
7 | import numpy as np
8 |
9 | if __name__ == '__main__':
10 | # general parameters
11 | solver = dsmc.DSMC()
12 | domain = [(-3.0, 3.0), (-1.5, 1.5), (-0.025, 0.025)]
13 | obj = [(-0.25, 0.25), (-0.25, 0.25), (-0.5, 0.5)]
14 | dt = 1e-6
15 | w = 0.25e+15
16 | mass = 6.6422e-26
17 | T = 273.0
18 | n = 2.6e+19
19 | u = np.array([0.0, -3043.0, 0.0])
20 | niter = 2500
21 | niter_sample = 5000
22 |
23 | # set up mesh2
24 | mesh = msh2d.Mesh2d()
25 |
26 | mesh.n_cells1 = 200
27 | mesh.n_cells2 = 100
28 | mesh.min1 = domain[0][0]
29 | mesh.min2 = domain[1][0]
30 | mesh.cell_size1 = 0.03
31 | mesh.cell_size2 = 0.03
32 |
33 | h = domain[2][1] - domain[2][0]
34 |
35 | # setup solver
36 | solver.set_domain(domain)
37 | solver.set_weight(w)
38 | solver.set_mass(mass)
39 |
40 | # set up boundary
41 | solver.set_bc_type("xmin", "inflow")
42 | solver.set_bc_type("xmax", "inflow")
43 | solver.set_bc_type("ymax", "inflow")
44 |
45 | solver.set_bc_type("ymin", "open")
46 |
47 | solver.set_bc_values("xmin", T, n, u)
48 | solver.set_bc_values("xmax", T, n, u)
49 | solver.set_bc_values("ymax", T, n, u)
50 |
51 | # set object
52 | solver.add_object(obj)
53 |
54 | # create particles
55 | solver.create_particles(domain, T, n, u)
56 |
57 | # trees
58 | tree_inner = oc.Octree()
59 | tree_outer = oc.Octree()
60 |
61 | inner_pos = np.array([[-0.25, -0.25, -0.025], [0.25, 0.25, 0.025]])
62 | outer_pos = np.array([[-3.0, -1.5, -0.025], [3.0, 1.5, 0.025]])
63 |
64 | tree_inner.build(inner_pos)
65 | tree_outer.build(outer_pos)
66 |
67 | wrt.write_buttom_leafs(tree_inner, "innter.vtu")
68 | wrt.write_buttom_leafs(tree_outer, "outer.vtu")
69 |
70 | # start timing
71 | start_time = time.time()
72 |
73 | for it in range(niter):
74 | print("iteration {:4}/{}".format(it + 1, niter), end="\r", flush=True)
75 | solver.advance(dt)
76 |
77 | for it in range(niter_sample):
78 | print("iteration {:4}/{}".format(it + 1, niter_sample), end="\r", flush=True)
79 | solver.advance(dt)
80 |
81 | mesh.sort(solver.particles.Pos)
82 | boxes, values = dia.analyse_2d(solver.particles.Pos, solver.particles.Vel, mesh, h)
83 | wrt.write_planar(boxes, values, "hypersonic_{}.vtu".format(it))
84 |
85 | wrt.write_buttom_leafs(solver.octree)
86 |
87 | print("")
88 | print("--- %s seconds ---" % (time.time() - start_time))
89 | print('done')
--------------------------------------------------------------------------------
/tests/unit/test_dsmc/particles.py:
--------------------------------------------------------------------------------
1 | import unittest
2 | from dsmc import particles as pa
3 | import numpy as np
4 |
5 | class TestParticles(unittest.TestCase):
6 | def test_box_muller(self):
7 | T = 300
8 | result = pa.box_muller(T)
9 |
10 | def test_x2velocity(self):
11 | x = 1.0
12 | mass = 1.0e-26
13 | result = pa.x2velocity(x, mass)
14 |
15 | def test_get_vel(self):
16 | T = 300
17 | mass = 1.0e-26
18 | result = pa.get_vel(T, mass)
19 |
20 | def test_get_velocities(self):
21 | T = 300
22 | mass = 1.0e-26
23 | N = 1000
24 | u = np.zeros(3)
25 | velocities = pa.get_velocities(T, mass, N, u)
26 |
27 | self.assertEqual(N, len(velocities))
28 |
29 | def test_calc_temperature(self):
30 | T = 300
31 | mass = 1.0e-26
32 | N = 10000
33 | u = np.zeros(3)
34 | velocities = pa.get_velocities(T, mass, N, u)
35 | T_new = pa.calc_temperature(velocities, mass)
36 | diff = abs((T_new - T)/T)
37 |
38 | self.assertTrue(diff < 0.1)
39 |
40 | def test_calc_positions(self):
41 | x = (-1.0, 1.0)
42 | y = (2.0, 3.0)
43 | z = (-2.0, -1.0)
44 | X = np.array([x, y, z])
45 | N = 1000
46 | positions = pa.calc_positions(X, N)
47 |
48 | self.assertEqual(N, len(positions))
49 |
50 | def test_create_particles(self):
51 | x = (-1.0, 1.0)
52 | y = (2.0, 3.0)
53 | z = (-2.0, -1.0)
54 | X = np.array((x, y, z))
55 | N = 1000
56 | mass = 1.0e-26
57 | T = 300
58 | u = np.zeros(3)
59 | particles = pa.Particles()
60 |
61 | particles.create_particles(X, mass, T, N, u)
62 |
63 | self.assertEqual(N, len(particles.Pos))
64 | self.assertEqual(N, len(particles.Vel))
65 | self.assertEqual(N, particles.N)
66 |
67 | for i in range(N):
68 | self.assertTrue(particles.Pos[i][0] >= x[0] and particles.Pos[i][0] <= x[1])
69 | self.assertTrue(particles.Pos[i][1] >= y[0] and particles.Pos[i][1] <= y[1])
70 | self.assertTrue(particles.Pos[i][2] >= z[0] and particles.Pos[i][2] <= z[1])
71 |
72 | particles.create_particles(X, mass, T, N, u)
73 |
74 | self.assertEqual(2*N, len(particles.Pos))
75 | self.assertEqual(2*N, len(particles.Vel))
76 | self.assertEqual(2*N, particles.N)
77 |
78 | for i in range(2*N):
79 | self.assertTrue(particles.Pos[i][0] >= x[0] and particles.Pos[i][0] <= x[1])
80 | self.assertTrue(particles.Pos[i][1] >= y[0] and particles.Pos[i][1] <= y[1])
81 | self.assertTrue(particles.Pos[i][2] >= z[0] and particles.Pos[i][2] <= z[1])
82 |
83 | def test_calc_vp(self):
84 | T = 300
85 | mass = 1e-26
86 | vp = pa.calc_vp(T, mass)
87 |
88 | self.assertEqual(np.sqrt(2.0*pa.kb*T/mass), vp)
89 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Octree based DSMC - Python implementation
2 | [](https://app.circleci.com/pipelines/github/LeoBasov/dsmc-python/)
3 |
4 |
5 | # Table of Contents
6 | 1. Introduction
7 | 2. Requirements
8 | 3. Installation
9 | 4. Test Cases
10 |
11 | # 1. Introduction
12 | DSMC implementation using an octree as a variable mesh based on https://doi.org/10.1016/j.jcp.2008.04.038.
13 | Implementation in done in python 3.10.
14 |
15 | # 2. Requirements
16 | - python 3.10.
17 | - pip3
18 | - numpy
19 | - llvmlite
20 | - scipy
21 | - numba
22 |
23 | # 3. Installation
24 | The module can be installed using pip3 from the repository root as
25 |
26 | ``
27 | pip3 install .
28 | ``
29 |
30 | # 4. Test Cases
31 | All test cases were performed using Argon.
32 | The gas properties are as follows:
33 |
34 | | gas | $\sigma_T / m^2$ | $m / kg$ |
35 | |:---:|:----------------:|:----------:|
36 | | Ar | 3.631681e-19 | 6.6422e-26 |
37 |
38 | ## 4.1 Heat Bath
39 | Simulation of temperature relaxation of Argon in closed domain.
40 | The simulation domain is cube with a side length of $2 \cdot 10^{-3} m$.
41 | The simulation properties are as follows
42 |
43 |
44 | | $\Delta t / s$ | $w$ | $T / K$ | $n / m^{-3}$ | $u / (m/s)$ |
45 | |:--------------:|:------:|:-------:|:------------:|:-----------:|
46 | | 1e-5 | 0.5e-8 | 300 | 1e+20 | 1000.0 |
47 |
48 | where $\Delta t$ is the time step, $w$ is the particle weight, $T$ the temperature, $n$ the number density and $u$ the velocity in x direction.
49 | The simulation results can be seen below.
50 |
51 | 
52 |
53 | ## 4.2 Hypersonic flow around cube
54 | Hypersonic flow around a cuboid.
55 | The parameters are as follows
56 |
57 | | $\Delta t / s$ | $w$ | $T / K$ | $n / m^{-3}$ | $v_{x, z} / (m s^{-1})$ | $v_y / (m s^{-1})$ |
58 | |:--------------:|:--------:|:-------:|:------------:|:-----------------------:|:------------------:|
59 | | 1e-6 | 0.25e+15 | 273.0 | 2.6e+19 | 0 | -3043.0 |
60 |
61 | 
62 |
63 | 
64 |
65 | 
66 |
67 | ## 4.3 Shock Tube
68 |
69 | This test case is Sod's shock tube problem.
70 | Initial conditions for the left hand side $C_L$ and the right hand side $C_R$ are found below
71 |
72 | $$
73 | C_L =
74 | \begin{pmatrix}
75 | n_L \\
76 | u_L \\
77 | T_L \\
78 | \end{pmatrix} =
79 | \begin{pmatrix}
80 | 2.41432e22 \\
81 | 0 \\
82 | 300 \\
83 | \end{pmatrix}
84 | $$
85 |
86 | $$
87 | C_R =
88 | \begin{pmatrix}
89 | n_R \\
90 | u_R \\
91 | p_L \\
92 | \end{pmatrix}=
93 | \begin{pmatrix}
94 | 2.41432e21 \\
95 | 0 \\
96 | 300 \\
97 | \end{pmatrix}
98 | $$
99 |
100 | The simulation parameters
101 |
102 | | $\Delta t / s$ | $w$ |
103 | |:--------------:|:----:|
104 | | 1e-7 | 1e-8 |
105 |
106 | The simulation domain is a rectangular tube with a square cross section with the side length $2 \cdot 10^{-4} m$ and a length of $0.1 m$.
107 | Results can be seen below.
108 |
109 | 
110 |
--------------------------------------------------------------------------------
/dsmc/mesh/mesh2d.py:
--------------------------------------------------------------------------------
1 | from enum import Enum
2 | import math
3 | from numba import njit
4 | import numpy as np
5 |
6 | @njit
7 | def _get_cell_id(val1, val2, n_cells1, n_cells2, min1, min2, cell_size1, cell_size2):
8 | if (val1 < min1):
9 | return (False, 0)
10 | elif (val1 > (min1 + n_cells1 * cell_size1)):
11 | return (False, 0)
12 | else:
13 | cell_id1 = math.floor((val1 - min1) / cell_size1)
14 |
15 | if (val2 < min2):
16 | return (False, 0)
17 | elif (val2 > (min2 + n_cells2 * cell_size2)):
18 | return (False, 0)
19 | else:
20 | cell_id2 = math.floor((val2 - min2) / cell_size2)
21 |
22 | return (True, cell_id2 * n_cells1 + cell_id1)
23 |
24 | @njit
25 | def _sort(values1, values2, n_cells1, n_cells2, min1, min2, cell_size1, cell_size2):
26 | inside = np.empty((len(values1)), np.bool_)
27 | ids = np.empty((len(values1)), np.int_)
28 |
29 | for i in range(len(values1)):
30 | inside[i], ids[i] = _get_cell_id(values1[i], values2[i], n_cells1, n_cells2, min1, min2, cell_size1, cell_size2)
31 |
32 | return (inside, ids)
33 |
34 |
35 | class Plane(Enum):
36 | XY = 0
37 | YZ = 1
38 | XZ = 2
39 |
40 | class Mesh2d:
41 | def __init__(self):
42 | self.clear()
43 |
44 | def clear(self):
45 | self.cell_size1 = 1.0
46 | self.cell_size2 = 1.0
47 | self.min1 = 0.0
48 | self.min2 = 0.0
49 | self.n_cells1 = 1
50 | self.n_cells2 = 1
51 | self.plane = Plane.XY
52 | self.cells = None # this holds an 2d array, cells[] : cells, cells[][] position ids in cell
53 |
54 | def sort(self, position):
55 | self.cells = [[] for _ in range(self.n_cells1 * self.n_cells2)]
56 |
57 | match self.plane:
58 | case Plane.XY:
59 | positions1 = np.array([position[i][0] for i in range(len(position))])
60 | positions2 = np.array([position[i][1] for i in range(len(position))])
61 | case Plane.YZ:
62 | positions1 = np.array([position[i][1] for i in range(len(position))])
63 | positions2 = np.array([position[i][2] for i in range(len(position))])
64 | case Plane.XZ:
65 | positions1 = np.array([position[i][0] for i in range(len(position))])
66 | positions2 = np.array([position[i][2] for i in range(len(position))])
67 |
68 | inside, cell_ids = _sort(positions1, positions2, self.n_cells1, self.n_cells2, self.min1, self.min2, self.cell_size1, self.cell_size2)
69 | sorted_ids = np.argsort(cell_ids)
70 |
71 | for idx in sorted_ids:
72 | if inside[idx]:
73 | self.cells[cell_ids[idx]].append(idx)
74 |
75 | def get_cell_id(self, position):
76 | match self.plane:
77 | case Plane.XY:
78 | return _get_cell_id(position[0], position[1], self.n_cells1, self.n_cells2, self.min1, self.min2, self.cell_size1, self.cell_size2)
79 | case Plane.YZ:
80 | return _get_cell_id(position[1], position[2], self.n_cells1, self.n_cells2, self.min1, self.min2, self.cell_size1, self.cell_size2)
81 | case Plane.XZ:
82 | return _get_cell_id(position[0], position[2], self.n_cells1, self.n_cells2, self.min1, self.min2, self.cell_size1, self.cell_size2)
--------------------------------------------------------------------------------
/dsmc/writer/octree.py:
--------------------------------------------------------------------------------
1 | def write_buttom_leafs(octree, file_name="octree.vtu"):
2 | f = open(file_name, "w")
3 |
4 | _write_header(f)
5 | _wrtie_body(f, octree)
6 | _write_footer(f)
7 |
8 | f.close()
9 |
10 | def _write_header(f):
11 | f.write("\n")
12 |
13 | def _wrtie_body(f, octree):
14 | leaf_ids = []
15 | for i in range(len(octree.leafs)):
16 | if octree.leafs[i].number_children == 0:
17 | leaf_ids.append(i)
18 |
19 | f.write("\n")
20 | f.write("\n".format(len(leaf_ids) * 8, len(leaf_ids)))
21 |
22 | _write_points(f, octree, leaf_ids)
23 | _write_cells(f, octree, leaf_ids)
24 | _write_cell_data(f, octree, leaf_ids)
25 |
26 | f.write("\n")
27 | f.write("\n")
28 |
29 | def _write_points(f, octree, leaf_ids):
30 | f.write("\n")
31 | f.write("\n")
32 |
33 | for i in leaf_ids:
34 | box = octree.cell_boxes[i]
35 |
36 | f.write("{} ".format(box[0][0]))
37 | f.write("{} ".format(box[1][0]))
38 | f.write("{} ".format(box[2][0]))
39 |
40 | f.write("{} ".format(box[0][1]))
41 | f.write("{} ".format(box[1][0]))
42 | f.write("{} ".format(box[2][0]))
43 |
44 | f.write("{} ".format(box[0][1]))
45 | f.write("{} ".format(box[1][1]))
46 | f.write("{} ".format(box[2][0]))
47 |
48 | f.write("{} ".format(box[0][0]))
49 | f.write("{} ".format(box[1][1]))
50 | f.write("{} ".format(box[2][0]))
51 |
52 | f.write("{} ".format(box[0][0]))
53 | f.write("{} ".format(box[1][0]))
54 | f.write("{} ".format(box[2][1]))
55 |
56 | f.write("{} ".format(box[0][1]))
57 | f.write("{} ".format(box[1][0]))
58 | f.write("{} ".format(box[2][1]))
59 |
60 | f.write("{} ".format(box[0][1]))
61 | f.write("{} ".format(box[1][1]))
62 | f.write("{} ".format(box[2][1]))
63 |
64 | f.write("{} ".format(box[0][0]))
65 | f.write("{} ".format(box[1][1]))
66 | f.write("{} ".format(box[2][1]))
67 |
68 | f.write("\n")
69 | f.write("\n")
70 |
71 |
72 | def _write_cells(f, octree, leaf_ids):
73 | k = 0
74 |
75 | f.write("\n")
76 | f.write("\n")
77 |
78 | for i in range(len(leaf_ids)):
79 | for _ in range(8):
80 | f.write("{} ".format(k))
81 | k += 1
82 |
83 | f.write("\n")
84 | f.write("\n")
85 |
86 | for i in range(len(leaf_ids)):
87 | f.write("{} ".format((i + 1) * 8))
88 |
89 | f.write("\n")
90 | f.write("\n")
91 |
92 | for _ in range(len(leaf_ids)):
93 | f.write("12 ")
94 |
95 | f.write("\n")
96 | f.write("\n")
97 |
98 | def _write_cell_data(f, octree, leaf_ids):
99 | f.write("\n")
100 | f.write("\n")
101 |
102 | for i in leaf_ids:
103 | f.write("{} ".format(octree.leafs[i].number_elements))
104 |
105 | f.write("\n")
106 | f.write("\n")
107 |
108 | def _write_footer(f):
109 | f.write("\n")
110 |
--------------------------------------------------------------------------------
/doc/Boundary.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": 1,
6 | "id": "d49edbe1-fe92-4a67-82e9-78a877139d5d",
7 | "metadata": {},
8 | "outputs": [],
9 | "source": [
10 | "import numpy as np\n",
11 | "import sympy as sym"
12 | ]
13 | },
14 | {
15 | "cell_type": "markdown",
16 | "id": "7f598afc-282c-4bb5-8d47-80c77fcc1178",
17 | "metadata": {},
18 | "source": [
19 | "**Boundary collision method**\n",
20 | "\n",
21 | "Given a plane $\\Pi$ and and a line $L$ as\n",
22 | "\n",
23 | "$$\n",
24 | "\\Pi \\rightarrow (p - p_0) \\cdot \\vec{n}_p = 0 \\\\\n",
25 | "L \\rightarrow l = l_0 + t \\cdot \\vec{n}_l\n",
26 | "$$\n",
27 | "\n",
28 | "where $\\vec{n}_1$ is the normal vector of a plane given as\n",
29 | "\n",
30 | "$$\n",
31 | "\\vec{n}_p = (p_1 - p_0) \\times (p_2 - p_0)\n",
32 | "$$\n",
33 | "\n",
34 | "is a vector in the direction of the line as\n",
35 | "\n",
36 | "$$\n",
37 | "\\vec{n}_l = l_1 - l_0.\n",
38 | "$$\n",
39 | "\n",
40 | "The positons of the intersection point found by setting the point $p$ in the equation for the plane as being a point in the equation of the line:\n",
41 | "\n",
42 | "$$\n",
43 | "(l - p_0) \\cdot \\vec{n}_p = 0 = (l_0 + t \\cdot \\vec{n}_l - p_0) \\cdot \\vec{n}_p \\implies t = - \\frac{(l_0 - p_0) \\cdot \\vec{n}_p}{\\vec{n}_p \\cdot \\vec{n}_l}\n",
44 | "$$\n",
45 | "\n",
46 | "inserting the line equation the intersection point can be found as\n",
47 | "\n",
48 | "$$\n",
49 | "l^* = l_0 + t \\cdot \\vec{n}_l.\n",
50 | "$$"
51 | ]
52 | },
53 | {
54 | "cell_type": "code",
55 | "execution_count": 2,
56 | "id": "4abb0e41-5e15-4326-b663-df0b6b5cfe0b",
57 | "metadata": {
58 | "tags": []
59 | },
60 | "outputs": [
61 | {
62 | "name": "stdout",
63 | "output_type": "stream",
64 | "text": [
65 | "[0. 0. 0.]\n"
66 | ]
67 | }
68 | ],
69 | "source": [
70 | "l1 = np.array([1.0, 1.0, 0.0])\n",
71 | "l0 = np.array([-1.0, -1.0, 0.0])\n",
72 | "\n",
73 | "p0 = np.array([0.0, -1.0, -1.0])\n",
74 | "p1 = np.array([0.0, -1.0, 1.0])\n",
75 | "p2 = np.array([0.0, 1.0, 1.0])\n",
76 | "\n",
77 | "nl = l1 - l0\n",
78 | "n_p = np.cross((p1 - p0), (p2 - p0))\n",
79 | "\n",
80 | "t = - ((l0 - p0).dot(n_p) / n_p.dot(nl))\n",
81 | "\n",
82 | "ls = l0 +t*nl\n",
83 | "\n",
84 | "print(ls)"
85 | ]
86 | },
87 | {
88 | "cell_type": "markdown",
89 | "id": "d43f6e71-7324-4b21-9c0d-371fb76d01f6",
90 | "metadata": {},
91 | "source": [
92 | "**Reflections**\n",
93 | "\n",
94 | "The reflected line can be found as\n",
95 | "\n",
96 | "$$\n",
97 | "L_R \\rightarrow l_R = l^* + \\lambda \\cdot \\vec{n}_R\n",
98 | "$$\n",
99 | "\n",
100 | "with \n",
101 | "\n",
102 | "$$\n",
103 | "\\vec{n}_R = \\vec{n}_l - 2 \\frac{\\vec{n}_p \\cdot \\vec{n}_l}{|| \\vec{n}_p ||^2} \\cdot \\vec{n}_p.\n",
104 | "$$\n",
105 | "\n",
106 | "The reflected point can now the found as \n",
107 | "\n",
108 | "$$\n",
109 | "l_R = l^* + (1 - t) \\cdot \\vec{n}_R\n",
110 | "$$"
111 | ]
112 | },
113 | {
114 | "cell_type": "code",
115 | "execution_count": 3,
116 | "id": "91de06b7-7511-471d-9b64-f9c2a784d682",
117 | "metadata": {},
118 | "outputs": [
119 | {
120 | "data": {
121 | "text/plain": [
122 | "array([ 1., -1., 0.])"
123 | ]
124 | },
125 | "execution_count": 3,
126 | "metadata": {},
127 | "output_type": "execute_result"
128 | }
129 | ],
130 | "source": [
131 | "nR = nl - 2*(n_p.dot(nl) / n_p.dot(n_p))*n_p\n",
132 | "lR = ls - (1 -t )*nR\n",
133 | "\n",
134 | "lR"
135 | ]
136 | },
137 | {
138 | "cell_type": "code",
139 | "execution_count": null,
140 | "id": "a81e9e3a-d8d0-463f-a5e4-b8700e696875",
141 | "metadata": {},
142 | "outputs": [],
143 | "source": []
144 | }
145 | ],
146 | "metadata": {
147 | "kernelspec": {
148 | "display_name": "Python 3 (ipykernel)",
149 | "language": "python",
150 | "name": "python3"
151 | },
152 | "language_info": {
153 | "codemirror_mode": {
154 | "name": "ipython",
155 | "version": 3
156 | },
157 | "file_extension": ".py",
158 | "mimetype": "text/x-python",
159 | "name": "python",
160 | "nbconvert_exporter": "python",
161 | "pygments_lexer": "ipython3",
162 | "version": "3.8.10"
163 | }
164 | },
165 | "nbformat": 4,
166 | "nbformat_minor": 5
167 | }
168 |
--------------------------------------------------------------------------------
/dsmc/particles.py:
--------------------------------------------------------------------------------
1 | import math
2 | import numpy as np
3 | from numba import njit
4 | import numba
5 | from . import common as com
6 |
7 | kb = 1.380649e-23
8 |
9 | @njit(numba.float64(numba.float64, numba.float64))
10 | def calc_vp(T, mass):
11 | return np.sqrt(2*kb*T/mass)
12 |
13 | @njit(numba.float64(numba.float64))
14 | def box_muller(T):
15 | """
16 | Parameters
17 | ----------
18 | T : float
19 | temperature [K]
20 |
21 | Returns
22 | -------
23 | x : float
24 | m * v^2 / (2 * kb)
25 | """
26 | r1 = np.random.random()
27 | r2 = np.random.random()
28 | r3 = np.random.random()
29 |
30 | return T*(-np.log(r1) - np.log(r2) * math.pow(np.cos((np.pi/2.0)*r3), 2))
31 |
32 | @njit(numba.float64(numba.float64, numba.float64))
33 | def x2velocity(x, mass):
34 | """
35 | Parameters
36 | ----------
37 | x : float
38 | m * v^2 / (2 * kb)
39 | mass : float
40 | particle mass [kg]
41 |
42 | Returns
43 | -------
44 | speed of particle : float
45 | """
46 | return math.sqrt(2.0 * x * kb /mass)
47 |
48 | @njit(numba.float64[:](numba.float64, numba.float64))
49 | def get_vel(T, mass):
50 | """
51 | Parameters
52 | ----------
53 | T : float
54 | temperature [K]
55 | mass : float
56 | particle mass [kg]
57 |
58 | Returns
59 | -------
60 | velocity : np.array, shape = (3, 1)
61 | """
62 | v = np.random.random(3)*2.0 - np.ones(3)
63 | return v * x2velocity(box_muller(T), mass) / np.linalg.norm(v)
64 |
65 | @njit(numba.float64[:, :](numba.float64, numba.float64, numba.int64, numba.float64[:]))
66 | def get_velocities(T, mass, N, u):
67 | velocities = np.empty((N, 3))
68 |
69 | for i in range(N):
70 | velocities[i] = get_vel(T, mass) + u
71 |
72 | return velocities
73 |
74 | @njit
75 | def calc_temperature(velocities, mass):
76 | tot_e = 0.0
77 |
78 | if not len(velocities):
79 | return 0.0
80 |
81 | for i in range(len(velocities)):
82 | tot_e += 0.5 * mass * np.dot(velocities[i], velocities[i])
83 |
84 | return tot_e / ((3.0/2.0) * len(velocities) * kb)
85 |
86 | @njit(numba.float64[:, :](numba.float64[:, :], numba.int64))
87 | def calc_positions(X, N):
88 | """
89 | Parameters
90 | ----------
91 | x : tuple(2), dtype = float
92 | xmin, xmax
93 | y : tuple(2), dtype = float
94 | ymin, ymax
95 | z : tuple(2), dtype = float
96 | zmin, zmax
97 | """
98 | positions = np.empty((N, 3))
99 |
100 | for i in range(N):
101 | for j in range(3):
102 | positions[i][j] = X[j][0] + np.random.random() * (X[j][1] - X[j][0])
103 |
104 | return positions
105 |
106 | class Particles:
107 | def __init__(self):
108 | self._velocities = None
109 | self._positions = None
110 | self._N = 0 # number of particles
111 |
112 | @property
113 | def Vel(self):
114 | return self._velocities
115 |
116 | @property
117 | def Pos(self):
118 | return self._positions
119 |
120 | @property
121 | def N(self):
122 | return self._N
123 |
124 | @property
125 | def VelPos(self):
126 | return (self._velocities, self._positions)
127 |
128 | @VelPos.setter
129 | def VelPos(self, vel_pos):
130 | assert len(vel_pos[0]) == len(vel_pos[1])
131 |
132 | self._velocities = vel_pos[0]
133 | self._positions = vel_pos[1]
134 | self._N = len(self._positions)
135 |
136 | def create_particles(self, X, mass, T, N, u = np.zeros(3)):
137 | if self._N == 0:
138 | self._velocities = get_velocities(T, mass, N, u)
139 | self._positions = calc_positions(X, N)
140 | self._N = N
141 | else:
142 | self._velocities = np.concatenate((self._velocities, get_velocities(T, mass, N, u)))
143 | self._positions = np.concatenate((self._positions, calc_positions(X, N)))
144 | self._N += N
145 |
146 |
147 | def inflow(self, mass, T, u, n, w, dt, domain, axis, minmax):
148 | L = max(calc_vp(T, mass) * dt * 10, np.linalg.norm(u) * dt)
149 | box = np.copy(domain)
150 |
151 | if minmax == 0:
152 | box[axis][1] = box[axis][0]
153 | box[axis][0] = box[axis][1] - L
154 | elif minmax == 1:
155 | box[axis][0] = box[axis][1]
156 | box[axis][1] = box[axis][0] + L
157 |
158 | N = int(round(com.get_V(box) * n / w))
159 |
160 | self.create_particles(box, mass, T, N, u)
161 |
--------------------------------------------------------------------------------
/examples/shock_tube/tools/sod_analytical.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """
3 | Created on Thu Sep 29 12:03:03 2022
4 |
5 | @author: Leo Basov
6 | """
7 |
8 | import numpy as np
9 | import matplotlib.pyplot as plt
10 | import argparse
11 |
12 | kb = 1.380649e-23
13 |
14 | def _calc_u3(p1, p3, rhoL, Gamma, gamma, beta):
15 | num = (1 - Gamma**2) * p1**(1.0/gamma)
16 | denum = Gamma**2 * rhoL
17 | return (p1**beta - p3**beta) * np.sqrt(num / denum)
18 |
19 | def _calc_u4(p3, p5, rhoR, Gamma):
20 | return (p3 - p5) * np.sqrt((1 - Gamma) / (rhoR*(p3 - Gamma*p5)))
21 |
22 | def _calc_p3(p, rho, Gamma, gamma, beta):
23 | p1 = p[0]
24 | p3 = p[0]
25 | p5 = p[4]
26 | dp = p1 * 1e-3
27 | rhoL = rho[0]
28 | rhoR = rho[-1]
29 | err = 1e+5
30 | err_last = 1e+6
31 |
32 | while err < err_last:
33 | err_last = err
34 | err = abs(_calc_u3(p1, p3, rhoL, Gamma, gamma, beta) - _calc_u4(p3, p5, rhoR, Gamma))
35 | p3 -= dp
36 |
37 | return p3
38 |
39 | def plot_val(x, val, name):
40 | plt.plot((x[0], x[1]), (val[0], val[1]))
41 | plt.plot((x[1], x[2]), (val[1], val[2]))
42 | plt.plot((x[2], x[3]), (val[2], val[2]))
43 | plt.plot((x[3], x[3]), (val[2], val[3]))
44 | plt.plot((x[3], x[4]), (val[3], val[3]))
45 | plt.plot((x[4], x[4]), (val[3], val[4]))
46 | plt.plot((x[4], x[5]), (val[4], val[4]))
47 |
48 | plt.ylabel(name)
49 | plt.xlabel("x")
50 |
51 | plt.show()
52 |
53 | def write_values(x, val, name, file):
54 | with open(file + "_" + name + ".csv", "w") as file:
55 | file.write("{}, {}\n".format(x[0], val[0]))
56 | file.write("{}, {}\n".format(x[1], val[1]))
57 | file.write("{}, {}\n".format(x[2], val[2]))
58 | file.write("{}, {}\n".format(x[3], val[2]))
59 | file.write("{}, {}\n".format(x[3], val[3]))
60 | file.write("{}, {}\n".format(x[4], val[3]))
61 | file.write("{}, {}\n".format(x[4], val[4]))
62 | file.write("{}, {}\n".format(x[5], val[4]))
63 |
64 | def check_args(args):
65 | if args.p is not None and (args.p[0] <= args.p[1]):
66 | raise Exception("p1 must be > p2")
67 | elif args.rho is not None and (args.rho[0] <= args.rho[1]):
68 | raise Exception("rho1 must be > rho2")
69 | elif args.L is not None and (args.L <= 0.0):
70 | raise Exception("L must be > 0")
71 |
72 | if __name__ == '__main__':
73 | parser = argparse.ArgumentParser()
74 | parser.add_argument('-t', type=float, help='time of results', default=3.0e-5)
75 | parser.add_argument('-p', type=float, help='pressure', nargs = 2, default=(100, 10.0))
76 | parser.add_argument('-rho', type=float, help='density', nargs = 2, default=(0.0016036396304, 0.0016036396304*0.1))
77 | parser.add_argument('-L', type=float, help='tube length', default=0.1)
78 | parser.add_argument('-plt', type=bool, help='plot values', const=True, nargs='?')
79 | parser.add_argument('-w', type=str, help='write to file')
80 |
81 | args = parser.parse_args()
82 |
83 | check_args(args)
84 |
85 | # number points per segment
86 | N = 10
87 |
88 | # gas = Ar
89 | gamma = 1.67
90 | Gamma = (gamma - 1.0) / (gamma + 1.0)
91 | beta = (gamma - 1.0) / (2.0 * gamma)
92 | mass = 6.6422e-26
93 |
94 | # boundary conditions
95 | rho = np.zeros(5)
96 | p = np.zeros(5)
97 | u = np.zeros(5)
98 |
99 | rho[0] = args.rho[0]
100 | p[0] = args.p[0]
101 | u[0] = 0.0
102 |
103 | rho[-1] = args.rho[1]
104 | p[-1] = args.p[1]
105 | u[-1] = 0.0
106 |
107 | # calculating states
108 | p[1] = p[0]
109 | p[2] = _calc_p3(p, rho, Gamma, gamma, beta)
110 | p[3] = p[2]
111 |
112 | # speed of characterisics
113 | u[1] = np.sqrt(gamma * p[0] / rho[0]) # speed of rarefication going left
114 | u[2] = 0
115 | u[3] = (p[2] - p[4]) / np.sqrt((rho[4]/2) * ((gamma + 1) * p[2] + (gamma - 1) * p[4]))
116 | u[4] = np.sqrt(gamma * p[-1] / rho[-1]) # speed of pressure increase going right
117 |
118 | rho[1] = rho[0]
119 | rho[2] = rho[0]*(p[2] / p[0])**(1.0/gamma)
120 | rho[3] = rho[4] * (p[3] + Gamma*p[4]) / (p[4] + Gamma*p[3])
121 |
122 | n = [r/mass for r in rho]
123 | T = [p[i] / (n[i] * kb) for i in range(5)]
124 |
125 | # calc x
126 | x = np.array([0.0, args.L*0.5 - args.t*u[1], args.L*0.5, args.L*0.5 + args.t*u[3], args.L*0.5 + args.t*u[3] + args.t*u[4], args.L])
127 |
128 | if args.plt:
129 | plot_val(x, rho, "rho")
130 | plot_val(x, n, "n")
131 | plot_val(x, p, "p")
132 | plot_val(x, T, "T")
133 |
134 | if args.w:
135 | print("writing to file " + args.w + "_X.csv")
136 | write_values(x, rho, "rho", args.w)
137 | write_values(x, p, "p", args.w)
138 | write_values(x, n, "n", args.w)
139 | write_values(x, T, "T", args.w)
140 |
141 | print("done")
142 |
--------------------------------------------------------------------------------
/tests/unit/test_dsmc/mesh/mesh2d.py:
--------------------------------------------------------------------------------
1 | import dsmc.mesh.mesh2d as msh
2 | import unittest
3 | import numpy as np
4 |
5 | class TestMesh2(unittest.TestCase):
6 | def test_constructor(self):
7 | mesh = msh.Mesh2d()
8 |
9 | self.assertEqual(1.0, mesh.cell_size1)
10 | self.assertEqual(1.0, mesh.cell_size2)
11 | self.assertEqual(0.0, mesh.min1)
12 | self.assertEqual(0.0, mesh.min2)
13 | self.assertEqual(1, mesh.n_cells1)
14 | self.assertEqual(1, mesh.n_cells2)
15 | self.assertEqual(msh.Plane.XY, mesh.plane)
16 |
17 | def test__get_cell_id1(self):
18 | val1_f = -1.0
19 | val1_t = 0.1
20 | val2_f = -1.0
21 | val2_t = 0.1
22 | n_cells1 = 10
23 | n_cells2 = 10
24 | min1 = -0.5
25 | min2 = -0.5
26 | cell_size1 = 0.1
27 | cell_size2 = 0.1
28 |
29 | res1_f = msh._get_cell_id(val1_t, val2_f, n_cells1, n_cells2, min1, min2, cell_size1, cell_size2)
30 | res2_f = msh._get_cell_id(val1_f, val2_t, n_cells1, n_cells2, min1, min2, cell_size1, cell_size2)
31 | res3_t = msh._get_cell_id(val1_t, val2_t, n_cells1, n_cells2, min1, min2, cell_size1, cell_size2)
32 |
33 | self.assertFalse(res1_f[0])
34 | self.assertFalse(res2_f[0])
35 | self.assertTrue(res3_t[0])
36 |
37 | def test__get_cell_id2(self):
38 | val1 = (-0.45, -0.5)
39 | val2 = (-0.35, -0.35)
40 | n_cells1 = 10
41 | n_cells2 = 10
42 | min1 = -0.5
43 | min2 = -0.5
44 | cell_size1 = 0.1
45 | cell_size2 = 0.1
46 |
47 | res1 = msh._get_cell_id(val1[0], val1[1], n_cells1, n_cells2, min1, min2, cell_size1, cell_size2)
48 | res2 = msh._get_cell_id(val2[0], val2[1], n_cells1, n_cells2, min1, min2, cell_size1, cell_size2)
49 |
50 | self.assertTrue(res1[0])
51 | self.assertTrue(res2[0])
52 |
53 | self.assertEqual(0, res1[1])
54 | self.assertEqual(11, res2[1])
55 |
56 | def test_get_cell_id(self):
57 | mesh = msh.Mesh2d()
58 |
59 | mesh.n_cells1 = 10
60 | mesh.n_cells2 = 10
61 | mesh.min1 = -0.5
62 | mesh.min2 = -0.5
63 | mesh.cell_size1 = 0.1
64 | mesh.cell_size2 = 0.1
65 |
66 | pos = np.array([-0.45, -0.35, -0.25])
67 |
68 | # XY
69 | mesh.plane = msh.Plane.XY
70 | res = mesh.get_cell_id(pos)
71 |
72 | self.assertTrue(res[0])
73 | self.assertEqual(10, res[1])
74 |
75 | # YZ
76 | mesh.plane = msh.Plane.YZ
77 | res = mesh.get_cell_id(pos)
78 |
79 | self.assertTrue(res[0])
80 | self.assertEqual(21, res[1])
81 |
82 | # XZ
83 | mesh.plane = msh.Plane.XZ
84 | res = mesh.get_cell_id(pos)
85 |
86 | self.assertTrue(res[0])
87 | self.assertEqual(20, res[1])
88 |
89 | def test__sort(self):
90 | mesh = msh.Mesh2d()
91 |
92 | mesh.n_cells1 = 10
93 | mesh.n_cells2 = 10
94 | mesh.min1 = -0.5
95 | mesh.min2 = -0.5
96 | mesh.cell_size1 = 0.1
97 | mesh.cell_size2 = 0.1
98 |
99 | pos1 = np.array([-0.45, -0.35, 0.0])
100 | pos2 = np.array([-0.45, -3.50, 0.0])
101 | positions = np.array([pos1, pos2])
102 |
103 | values1 = np.array([positions[i][0] for i in range(len(positions))])
104 | values2 = np.array([positions[i][1] for i in range(len(positions))])
105 |
106 | inside, ids = msh._sort(values1, values2, mesh.n_cells1, mesh.n_cells2, mesh.min1, mesh.min2, mesh.cell_size1, mesh.cell_size2)
107 |
108 | self.assertTrue(inside[0])
109 | self.assertFalse(inside[1])
110 |
111 | self.assertEqual(10, ids[0])
112 | self.assertEqual(0, ids[1])
113 |
114 | def test_sort(self):
115 | mesh = msh.Mesh2d()
116 |
117 | mesh.n_cells1 = 10
118 | mesh.n_cells2 = 10
119 | mesh.min1 = -0.5
120 | mesh.min2 = -0.5
121 | mesh.cell_size1 = 0.1
122 | mesh.cell_size2 = 0.1
123 |
124 | positions = []
125 |
126 | positions.append([-0.45, -0.45, 0])
127 | positions.append([-0.45, -0.45, 0])
128 |
129 | positions.append([0.45, 0.45, 0])
130 |
131 | mesh.sort(positions)
132 |
133 | self.assertEqual(len(mesh.cells), mesh.n_cells1 * mesh.n_cells2)
134 | self.assertEqual(len(mesh.cells[0]), 2)
135 | self.assertEqual(len(mesh.cells[99]), 1)
136 |
137 | self.assertEqual(mesh.cells[0][0], 0)
138 | self.assertEqual(mesh.cells[0][1], 1)
139 | self.assertEqual(mesh.cells[99][0], 2)
140 |
141 | for i in range(len(mesh.cells)):
142 | if i != 0 and i != 99:
143 | self.assertEqual(0, len(mesh.cells[i]))
--------------------------------------------------------------------------------
/tests/unit/test_data/particles.csv:
--------------------------------------------------------------------------------
1 | 0.16720244270111206,0.8208120902385547,-0.15821775757746326
2 | -0.3539408610094026,0.6094479586781756,-0.2241998042084452
3 | -0.253602773408937,0.37842838770619047,0.5080805107290469
4 | 0.901801119661219,-0.3547753241315563,-0.7994223817818384
5 | -0.014540968173746727,-0.6057811852068014,-0.7747150654889452
6 | 0.6652045024170465,0.7496016129090863,0.09269932097207323
7 | -0.08371757238708022,-0.49569628427213286,-0.5230501995932113
8 | -0.45628210172061734,-0.7032547855919364,-0.01052801065881459
9 | -0.4050878274555494,0.16220023223033286,-0.13943218567361249
10 | -0.44015418512841675,0.4399168343737543,-0.13664372635262478
11 | 0.3822321359090435,-0.03867223327253977,-0.04984480804603453
12 | -0.5467265015048175,0.7694212897999899,0.5107554092663027
13 | 0.39267358552702203,0.8855795814797593,-0.3874196750436716
14 | -0.8339217114875397,-0.7277069297889218,0.6932782778950106
15 | -0.06677305356215668,0.08155865919002991,-0.22499099071269968
16 | 0.7461692085104521,-0.3569676906172021,0.19992850640433013
17 | -0.3183568330760138,0.8889477004291035,-0.22695163370221572
18 | 0.14226452585971483,0.6749945724336466,-0.10977565633862918
19 | 0.7567553000958556,0.6860849556496309,0.7019398659703175
20 | -0.45544407366595374,0.8415794987089842,0.4617571900758932
21 | 0.008921032851599175,0.09329133267050382,0.12341660395588416
22 | -0.11332760346288917,0.4042049964883072,-0.6363589932576024
23 | 0.45801429375353897,-0.9119723962473707,0.4512774411458276
24 | 0.46255470634607354,0.8505216562953395,-0.9625208705796366
25 | -0.1634911149788587,0.4954169015383527,-0.7514390159518116
26 | 0.9652111916953872,-0.326652317518793,-0.46448051286137493
27 | -0.012190671492502414,0.3513603108139549,0.21120932266533754
28 | -0.3219199072922947,-0.6707629224151808,-0.06547558541371457
29 | 0.0003677083723194752,-0.28631549200531037,-0.9589132043625856
30 | -0.48982911826707265,0.33709944881539533,-0.5705459675253599
31 | 0.24553297910626437,0.8153935258740543,0.7754269872933011
32 | -0.3597841927312453,-0.30153996145772344,-0.5545584807322563
33 | 0.4514246571306877,0.4022956382825962,-0.49522635923734093
34 | 0.28698107560336505,-0.2816866625438861,0.8615966614249093
35 | 0.09405268228661168,0.3419520966030001,0.7822256998740897
36 | -0.6883526842679561,-0.716974021117027,0.8038683522503012
37 | 0.8511390374742094,0.898837413751163,0.11732018920271692
38 | 0.10212127918229652,-0.6901138895567802,0.044572452623179215
39 | 0.9742771687163521,0.3900116089700414,0.2849645916426635
40 | -0.41446601047533616,-0.48501116366070063,-0.21171170708052967
41 | -0.8985239501161144,0.3231647945259839,0.20482889661142267
42 | 0.2691336467016665,0.019006468602156934,-0.5833077026738216
43 | 0.7753963192748963,0.4078932463220293,-0.17231148296520438
44 | -0.19696942316303256,0.10696738046497845,0.9229353551086716
45 | 0.5610982192389629,-0.36377857925636947,-0.39267739735571716
46 | -0.3199431452231085,-0.23776421953278826,-0.7917537970082731
47 | 0.7121864877364648,-0.8806372932737705,0.44221940740157173
48 | -0.4773400242683048,-0.4846890064033458,0.32609824265601484
49 | -0.25066582819700156,0.17875327390040763,0.6792664170237515
50 | -0.34955904993833786,-0.5269472436510836,0.05666029913257997
51 | -0.9841821357736698,0.4621791724011153,-0.38399251190936035
52 | -0.7925590286957733,0.8971899467301814,0.9465523534014599
53 | 0.7791035904527936,-0.3065439183432015,0.9668490966958605
54 | 0.7550138781918301,0.9954600710856267,0.15445789110262798
55 | 0.015132235590737064,-0.1279001510759381,-0.7784382777493579
56 | 0.7831998282225763,-0.45035646564466214,0.31822998226315025
57 | 0.25092976269744693,0.9085270898010307,-0.31735361664304573
58 | 0.3805923268337683,0.03787861289930383,-0.6266312154338713
59 | -0.6040348148625538,0.4530362126423204,0.498118925527959
60 | 0.4136176171187369,-0.9050493502417782,-0.29965017480855916
61 | -0.42774070010191867,-0.06461591748042528,-0.7976491333955078
62 | 0.09766097044471311,-0.16598582888531488,-0.7608659826062489
63 | 0.33798463823175595,-0.42150973385006063,-0.3713352945819577
64 | -0.58932187049589,0.3813552375040625,-0.26284015727708554
65 | -0.4907965754459813,0.20341783229024646,0.6622776161420185
66 | 0.8098477083222237,-0.8719199252159624,0.7488605548345317
67 | -0.8193929114745129,0.840626931453603,-0.6315912117747844
68 | -0.24239201418824297,0.47098841467093844,-0.669183593651901
69 | 0.5041947220259142,-0.29544662686416756,-0.5914541788966325
70 | -0.26262096117978784,0.9801755149383851,0.527269048439474
71 | 0.4275209506977513,-0.667659249339922,0.1347518319999672
72 | 0.9855519426068913,-0.6135765984848576,-0.4287141280807911
73 | 0.20982860758802357,0.07462089616107126,0.5943311631472485
74 | 0.32596254556079907,-0.5523299607926777,0.5000136968687108
75 | 0.6298276916469507,0.7866892509990404,-0.9079439336773338
76 | 0.78142640981854,0.5399877759560965,0.6973205654874475
77 | -0.3485450193568893,-0.6303033064361121,0.17527538428193168
78 | -0.8260677718113378,0.40584791574484824,-0.9942842646615264
79 | -0.20591928046068153,-0.5923212325551002,-0.968679333547988
80 | 0.45672042754779163,0.2149643271371091,0.21071030029661353
81 | 0.057075371525048046,-0.6650594086767447,-0.5251178367633449
82 | 0.1809775156746154,0.4818178472834924,0.3972083715175747
83 | -0.6207155824174482,-0.4160776878844272,0.6917477102880314
84 | -0.904590420565192,-0.193648165470109,0.5189271677890341
85 | 0.7951185512115042,-0.6569231762630592,0.3204489978755769
86 | 0.7584068620500117,-0.3176223099304243,-0.870445024417934
87 | -0.4922227934260852,-0.5001060615332293,-0.5348416435824386
88 | 0.8605684066110679,0.16239313316117032,-0.7627141519458742
89 | 0.6590758735534021,0.9222932137960997,-0.021059658756133137
90 | -0.5501989000546204,0.26214029221325275,-0.6910176960391732
91 | 0.967198486330149,-0.41117570121974034,0.6945615910511642
92 | 0.9468060139718262,0.5879482989935261,0.08334965744250988
93 | 0.4824650338598835,-0.21178248688885692,-0.9756564237429781
94 | 0.253591146580193,0.08009088613267878,0.4274284592732791
95 | -0.4389966392317204,0.22920620294282146,-0.0002775036237094852
96 | -0.7146674493249148,-0.538980218854364,0.879679600158005
97 | 0.8244476665630003,-0.7994155142294497,-0.6359195332795282
98 | 0.6824501498828124,-0.8031118692347363,0.9876378371063732
99 | 0.718260570290431,0.3877012248400389,0.5868224029728766
100 | -0.7941746749515597,-0.49028054610731187,0.9579007583397083
101 |
--------------------------------------------------------------------------------
/dsmc/boundary.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | from numba import njit
3 | from . import common as co
4 |
5 | @njit(cache=True)
6 | def _check_if_parallel(v1, v2, diff=1e-6):
7 | n1 = np.linalg.norm(v1)
8 | n2 = np.linalg.norm(v2)
9 |
10 | if n1 < 1.0e-13 or n2 < 1.0e-13:
11 | return False
12 |
13 | V1 = np.copy(v1) / n1
14 | V2 = np.copy(v2) / n2
15 |
16 | return V1.dot(V2) > diff
17 |
18 | @njit(cache=True)
19 | def _intersect(l0, l1, p0, p1, p2):
20 | """
21 | Args:
22 | l0 : first position on line
23 | l1 : second position on line
24 | p0 : first position on plane
25 | p1 : first position on plane
26 | p2 : first position on plane
27 |
28 | Returns:
29 | (intersected, n_l, n_r, t)
30 | """
31 | n_l = l1 - l0
32 | n_p = np.cross((p1 - p0), (p2 - p1))
33 |
34 | if _check_if_parallel(n_l, n_p):
35 | return (True, n_l, n_p, - ((l0 - p0).dot(n_p) / n_p.dot(n_l)))
36 | else:
37 | return (False, n_l, n_p, 0.0)
38 |
39 | @njit(cache=True)
40 | def _calc_nr(n_l, n_p):
41 | return n_l - 2.0 * (n_p.dot(n_l) / n_p.dot(n_p))*n_p
42 |
43 | @njit(cache=True)
44 | def _reflect(vel, pos, pos_old, p0, p1, p2, domain):
45 | intersected, n_l, n_p, t = _intersect(pos_old, pos, p0, p1, p2)
46 |
47 | if intersected and t < 1.0 and t > 0.0:
48 | k = 1.0
49 | p = pos_old + n_l*(t*k)
50 | while not co.is_inside(p, domain):
51 | k *= 0.9
52 | p = pos_old + n_l*(t*k)
53 | pos_old = p
54 | n_r = _calc_nr(n_l, n_p)
55 | pos = pos_old + (1.0 - t)*n_r
56 | vel = (np.linalg.norm(vel) / np.linalg.norm(n_r))*n_r
57 |
58 | return (vel, pos, pos_old)
59 |
60 | @njit(cache=True)
61 | def _get_plane(domain, i, j):
62 | if i == 0:
63 | if j == 0:
64 | p0 = np.array([domain[i][j], domain[1][0], domain[2][0]])
65 | p1 = np.array([domain[i][j], domain[1][0], domain[2][1]])
66 | p2 = np.array([domain[i][j], domain[1][1], domain[2][0]])
67 | elif j == 1:
68 | p0 = np.array([domain[i][j], domain[1][0], domain[2][0]])
69 | p1 = np.array([domain[i][j], domain[1][1], domain[2][0]])
70 | p2 = np.array([domain[i][j], domain[1][0], domain[2][1]])
71 | elif i == 1:
72 | if j == 0:
73 | p0 = np.array([domain[0][0], domain[i][j], domain[2][0]])
74 | p1 = np.array([domain[0][1], domain[i][j], domain[2][0]])
75 | p2 = np.array([domain[0][0], domain[i][j], domain[2][1]])
76 | if j == 1:
77 | p0 = np.array([domain[0][0], domain[i][j], domain[2][0]])
78 | p1 = np.array([domain[0][0], domain[i][j], domain[2][1]])
79 | p2 = np.array([domain[0][1], domain[i][j], domain[2][0]])
80 | elif i == 2:
81 | if j == 0:
82 | p0 = np.array([domain[0][0], domain[1][0], domain[i][j]])
83 | p1 = np.array([domain[0][0], domain[1][1], domain[i][j]])
84 | p2 = np.array([domain[0][1], domain[1][0], domain[i][j]])
85 | if j == 1:
86 | p0 = np.array([domain[0][0], domain[1][0], domain[i][j]])
87 | p1 = np.array([domain[0][1], domain[1][0], domain[i][j]])
88 | p2 = np.array([domain[0][0], domain[1][1], domain[i][j]])
89 |
90 | return (p0, p1, p2)
91 |
92 | @njit(cache=True)
93 | def _boundary(velocities, positions, old_positions, domain, boundary_conds):
94 | kept_parts = np.ones(positions.shape[0], dtype=np.uint)
95 |
96 | for p in range(len(positions)):
97 | counter = 0
98 | while not co.is_inside(positions[p], domain) and kept_parts[p]:
99 | if counter > 10:
100 | kept_parts[p] = 0
101 | break
102 |
103 | for i in range(3):
104 | for j in range(2):
105 | p0, p1, p2 = _get_plane(domain, i, j)
106 | if boundary_conds[i][j] == 0:
107 | velocities[p], positions[p], old_positions[p] = _reflect(velocities[p], positions[p], old_positions[p], p0, p1, p2, domain)
108 | counter += 1
109 | elif boundary_conds[i][j] == 1 or boundary_conds[i][j] == 2:
110 | if _intersect(old_positions[p], positions[p], p0, p1, p2)[0]:
111 | kept_parts[p] = 0
112 |
113 | N = int(sum(kept_parts))
114 | p = 0
115 | new_velocities = np.empty((N, 3))
116 | new_positions = np.empty((N, 3))
117 | new_old_positions = np.empty((N, 3))
118 |
119 | for i in range(positions.shape[0]):
120 | if kept_parts[i] == 1:
121 | new_velocities[p] = velocities[i]
122 | new_positions[p] = positions[i]
123 | new_old_positions[p] = old_positions[p]
124 | p += 1
125 | else:
126 | continue
127 |
128 | return (new_velocities, new_positions, new_old_positions)
129 |
130 | @njit(cache=True)
131 | def _get_boundary(boundary):
132 | if boundary == "xmin":
133 | return (0, 0)
134 | elif boundary == "xmax":
135 | return (0, 1)
136 | elif boundary == "ymin":
137 | return (1, 0)
138 | elif boundary == "ymax":
139 | return (1, 1)
140 | elif boundary == "zmin":
141 | return (2, 0)
142 | elif boundary == "zmax":
143 | return (2, 1)
144 |
145 | @njit(cache=True)
146 | def _get_bc_type(bc_type):
147 | if bc_type == "ela":
148 | return 0
149 | elif bc_type == "open":
150 | return 1
151 | elif bc_type == "inflow":
152 | return 2
153 |
154 | class Boundary:
155 | def __init__(self):
156 | self.T = np.ones((3, 2))*300.0
157 | self.n = np.ones((3, 2))*1e+18
158 | self.u = np.zeros((3, 2, 3))
159 | self.boundary_conds = np.array([[0, 0], [0, 0], [0, 0]], dtype=np.uint) # 0 = ela, 1 = open, 2 = inflow
160 | self.domain = None
161 |
162 | def boundary(self, velocities, positions, old_positions):
163 | return _boundary(velocities, positions, old_positions, self.domain, self.boundary_conds)
164 |
165 | def set_bc_type(self, boundary, bc_type):
166 | bound = _get_boundary(boundary)
167 | bc = _get_bc_type(bc_type)
168 |
169 | self.boundary_conds[bound[0]][bound[1]] = bc
170 |
171 | print("boundary [" + boundary + "] set to [" + bc_type + "]")
172 |
173 | def set_bc_values(self, boundary, T, n, u):
174 | i, j = _get_boundary(boundary)
175 |
176 | self.T[i][j] = T
177 | self.n[i][j] = n
178 | self.u[i][j] = u
179 |
180 | print("boundary [" + boundary + "] set to values T : {}, n : {}, u : {}".format(T, n, u))
--------------------------------------------------------------------------------
/tests/unit/test_dsmc/boundary.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import dsmc.boundary as bo
3 | import unittest
4 |
5 | class TestCommon(unittest.TestCase):
6 | def test__check_if_parallel(self):
7 | v1 = np.array([1.0, 0.0, 0.0])
8 | v2 = np.array([1.0, 0.0, 0.0])
9 | v3 = np.array([0.0, 1.0, 1.0])
10 | v4 = np.array([1.0e-6, 10.0, 10.0])
11 |
12 | self.assertTrue(bo._check_if_parallel(v1, v2))
13 | self.assertFalse(bo._check_if_parallel(v1, v3))
14 | self.assertFalse(bo._check_if_parallel(v1, v4))
15 |
16 | def test__intersect(self):
17 | l0 = np.array([-1.0, -1.0, 0.0])
18 | l1 = np.array([1.0, 1.0, 0.0])
19 |
20 | p0 = np.array([0.0, -1.0, -1.0])
21 | p1 = np.array([0.0, 1.0, -1.0])
22 | p2 = np.array([0.0, -1.0, 1.0])
23 |
24 | intersected, n_l, n_p, t = bo._intersect(l0, l1, p0, p1, p2)
25 |
26 | self.assertTrue(intersected)
27 |
28 | self.assertEqual(2.0, n_l[0])
29 | self.assertEqual(2.0, n_l[1])
30 | self.assertEqual(0.0, n_l[2])
31 |
32 | self.assertEqual(4.0, n_p[0])
33 | self.assertEqual(0.0, n_p[1])
34 | self.assertEqual(0.0, n_p[2])
35 |
36 | self.assertEqual(0.5, t)
37 |
38 | def test__calc_nr(self):
39 | l0 = np.array([-1.0, -1.0, 0.0])
40 | l1 = np.array([1.0, 1.0, 0.0])
41 |
42 | p0 = np.array([0.0, -1.0, -1.0])
43 | p1 = np.array([0.0, -1.0, 1.0])
44 | p2 = np.array([0.0, 1.0, 1.0])
45 |
46 | intersected, n_l, n_p, t = bo._intersect(l0, l1, p0, p1, p2)
47 | n_r = bo._calc_nr(n_l, n_p)
48 |
49 | self.assertEqual(-2.0, n_r[0])
50 | self.assertEqual(2.0, n_r[1])
51 | self.assertEqual(0.0, n_r[2])
52 |
53 | def test__reflect(self):
54 | vel = np.array([123.0, 123.0, 0.0])
55 | pos_old = np.array([-1.0, -1.0, 0.0])
56 | pos = np.array([1.0, 1.0, 0.0])
57 |
58 | domain = np.array([(-2.0, 0.0), (-1.0, 1.0), (-1.0, 1.0)])
59 |
60 | p0, p1, p2 = bo._get_plane(domain, 0, 1)
61 |
62 | new_vel, new_pos, new_pos_old = bo._reflect(vel, pos, pos_old, p0, p1, p2, domain)
63 |
64 | self.assertEqual(-123.0, new_vel[0])
65 | self.assertEqual(123.0, new_vel[1])
66 | self.assertEqual(0.0, new_vel[2])
67 |
68 | self.assertEqual(-1.0, new_pos[0])
69 | self.assertEqual(1.0, new_pos[1])
70 | self.assertEqual(0.0, new_pos[2])
71 |
72 | self.assertEqual(0.0, new_pos_old[0])
73 | self.assertEqual(0.0, new_pos_old[1])
74 | self.assertEqual(0.0, new_pos_old[2])
75 |
76 | def test__get_plane1(self):
77 | domain = np.array([(0, 1), (2, 4), (4, 7)])
78 | axis = 0
79 |
80 | p0, p1, p2 = bo._get_plane(domain, axis, 0)
81 |
82 | self.assertEqual((3,), p0.shape)
83 | self.assertEqual((3,), p1.shape)
84 | self.assertEqual((3,), p2.shape)
85 |
86 | self.assertEqual(0.0, p0[0])
87 | self.assertEqual(2.0, p0[1])
88 | self.assertEqual(4.0, p0[2])
89 |
90 | self.assertEqual(0.0, p1[0])
91 | self.assertEqual(2.0, p1[1])
92 | self.assertEqual(7.0, p1[2])
93 |
94 | self.assertEqual(0.0, p2[0])
95 | self.assertEqual(4.0, p2[1])
96 | self.assertEqual(4.0, p2[2])
97 |
98 | p0, p1, p2 = bo._get_plane(domain, axis, 1)
99 |
100 | self.assertEqual((3,), p0.shape)
101 | self.assertEqual((3,), p1.shape)
102 | self.assertEqual((3,), p2.shape)
103 |
104 | self.assertEqual(1.0, p0[0])
105 | self.assertEqual(2.0, p0[1])
106 | self.assertEqual(4.0, p0[2])
107 |
108 | self.assertEqual(1.0, p1[0])
109 | self.assertEqual(4.0, p1[1])
110 | self.assertEqual(4.0, p1[2])
111 |
112 | self.assertEqual(1.0, p2[0])
113 | self.assertEqual(2.0, p2[1])
114 | self.assertEqual(7.0, p2[2])
115 |
116 | def test__get_plane2(self):
117 | domain = np.array([(0, 1), (2, 4), (4, 7)])
118 | axis = 1
119 |
120 | p0, p1, p2 = bo._get_plane(domain, axis, 0)
121 |
122 | self.assertEqual((3,), p0.shape)
123 | self.assertEqual((3,), p1.shape)
124 | self.assertEqual((3,), p2.shape)
125 |
126 | self.assertEqual(0.0, p0[0])
127 | self.assertEqual(2.0, p0[1])
128 | self.assertEqual(4.0, p0[2])
129 |
130 | self.assertEqual(1.0, p1[0])
131 | self.assertEqual(2.0, p1[1])
132 | self.assertEqual(4.0, p1[2])
133 |
134 | self.assertEqual(0.0, p2[0])
135 | self.assertEqual(2.0, p2[1])
136 | self.assertEqual(7.0, p2[2])
137 |
138 | p0, p1, p2 = bo._get_plane(domain, axis, 1)
139 |
140 | self.assertEqual((3,), p0.shape)
141 | self.assertEqual((3,), p1.shape)
142 | self.assertEqual((3,), p2.shape)
143 |
144 | self.assertEqual(0.0, p0[0])
145 | self.assertEqual(4.0, p0[1])
146 | self.assertEqual(4.0, p0[2])
147 |
148 | self.assertEqual(0.0, p1[0])
149 | self.assertEqual(4.0, p1[1])
150 | self.assertEqual(7.0, p1[2])
151 |
152 | self.assertEqual(1.0, p2[0])
153 | self.assertEqual(4.0, p2[1])
154 | self.assertEqual(4.0, p2[2])
155 |
156 | def test__get_plane3(self):
157 | domain = np.array([(0, 1), (2, 4), (4, 7)])
158 | axis = 2
159 |
160 | p0, p1, p2 = bo._get_plane(domain, axis, 0)
161 |
162 | self.assertEqual((3,), p0.shape)
163 | self.assertEqual((3,), p1.shape)
164 | self.assertEqual((3,), p2.shape)
165 |
166 | self.assertEqual(0.0, p0[0])
167 | self.assertEqual(2.0, p0[1])
168 | self.assertEqual(4.0, p0[2])
169 |
170 | self.assertEqual(0.0, p1[0])
171 | self.assertEqual(4.0, p1[1])
172 | self.assertEqual(4.0, p1[2])
173 |
174 | self.assertEqual(1.0, p2[0])
175 | self.assertEqual(2.0, p2[1])
176 | self.assertEqual(4.0, p2[2])
177 |
178 | p0, p1, p2 = bo._get_plane(domain, axis, 1)
179 |
180 | self.assertEqual((3,), p0.shape)
181 | self.assertEqual((3,), p1.shape)
182 | self.assertEqual((3,), p2.shape)
183 |
184 | self.assertEqual(0.0, p0[0])
185 | self.assertEqual(2.0, p0[1])
186 | self.assertEqual(7.0, p0[2])
187 |
188 | self.assertEqual(1.0, p1[0])
189 | self.assertEqual(2.0, p1[1])
190 | self.assertEqual(7.0, p1[2])
191 |
192 | self.assertEqual(0.0, p2[0])
193 | self.assertEqual(4.0, p2[1])
194 | self.assertEqual(7.0, p2[2])
195 |
--------------------------------------------------------------------------------
/dsmc/octree.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import numpy.typing as npt
3 | from numba import njit
4 | import numba
5 | from enum import Enum
6 | from . import common as com
7 |
8 | fmin = np.finfo(float).min
9 | fmax = np.finfo(float).max
10 |
11 | @njit
12 | def _find_bounding_box(positions : npt.NDArray) -> npt.NDArray:
13 | box = np.array([[fmax, fmin], [fmax, fmin], [fmax, fmin]])
14 |
15 | for pos in positions:
16 | for i in range(3):
17 | if pos[i] < box[i][0]:
18 | box[i][0] = pos[i]
19 | if pos[i] > box[i][1]:
20 | box[i][1] = pos[i]
21 |
22 | return box
23 |
24 | @njit
25 | def _calc_N_res(w : float, sigma_T : float, n : float) -> int:
26 | """
27 | Parameters
28 | ----------
29 | w : float
30 | particle weight
31 | sigma_t : float
32 | total cross section [m^2]
33 | n : float
34 | number density [1/m^3]
35 | """
36 |
37 | return int(round(np.sqrt(2.0) / (32.0 * w * sigma_T**3 * n**2)))
38 |
39 | @njit
40 | def _calc_n(box : npt.NDArray, N : float, w : float) -> float:
41 | """Calculates number density in cell
42 |
43 | Parameters
44 | ----------
45 | box : np.array(3, 3)
46 | cell
47 | N : int
48 | number of particles in cell
49 | w : float
50 | particle weight
51 |
52 | Returns
53 | -------
54 | number density : float
55 | """
56 | return np.prod(np.array([box[i][1] - box[i][0] for i in range(3)])) * N / w
57 |
58 | @njit(numba.boolean(numba.float64[:, :], numba.int32, numba.float64, numba.float64, numba.int32, numba.int32))
59 | def _is_resolved(box : npt.NDArray, N : int, w : float, sigma_T : float, Nmin : int, Nmax : int) -> bool:
60 | if N == 0:
61 | return False
62 |
63 | n = _calc_n(box, N, w)
64 | Nres = _calc_N_res(w, sigma_T, n)
65 |
66 | return N > 2 * min(Nmin, max(Nmin, Nres))
67 |
68 | @njit
69 | def _is_inside(position : npt.NDArray, box : npt.NDArray) -> bool:
70 | a : bool = position[0] >= box[0][0] and position[0] <= box[0][1]
71 | b : bool = position[1] >= box[1][0] and position[1] <= box[1][1]
72 | c : bool = position[2] >= box[2][0] and position[2] <= box[2][1]
73 |
74 | return a and b and c
75 |
76 | @njit(numba.types.Tuple((numba.int64[:], numba.int64))(numba.int64[:], numba.float64[:, :], numba.float64[:, :], numba.int64, numba.int64), parallel=False)
77 | def _sort(permutations : npt.NDArray, box : npt.NDArray, positions : npt.NDArray, offset : int, N : int) -> tuple[npt.NDArray, int]:
78 | '''sort particles in cell
79 |
80 | Parameters
81 | ----------
82 | box : np.ndarray
83 | cell
84 | positions : ndarray((3, ))
85 | particle positions
86 | offset : int
87 | number offset
88 | N : int
89 | number of particles to be considered
90 |
91 | Returns
92 | -------
93 | new_permutations : ndarray[int]
94 | N : int
95 | number of found positions
96 | '''
97 | new_permutations = np.copy(permutations)
98 | runner = offset
99 | Nnew = 0
100 | for i in numba.prange(offset, offset + N):
101 | p = new_permutations[i]
102 | if _is_inside(positions[p], box):
103 | com.swap(new_permutations, i, runner)
104 | runner += 1
105 | Nnew += 1
106 |
107 | return new_permutations, Nnew
108 |
109 | @njit
110 | def _create_boxes(box):
111 | half = np.array([0.5*(box[i][0] + box[i][1]) for i in range(3)])
112 |
113 | child_geo1 = np.array(((half[0], box[0][1]), (half[1], box[1][1]), (half[2], box[2][1])))
114 | child_geo2 = np.array(((box[0][0], half[0]), (half[1], box[1][1]), (half[2], box[2][1])))
115 | child_geo3 = np.array(((box[0][0], half[0]), (box[1][0], half[1]), (half[2], box[2][1])))
116 | child_geo4 = np.array(((half[0], box[0][1]), (box[1][0], half[1]), (half[2], box[2][1])))
117 |
118 | child_geo5 = np.array(((half[0], box[0][1]), (half[1], box[1][1]), (box[2][0], half[2])))
119 | child_geo6 = np.array(((box[0][0], half[0]), (half[1], box[1][1]), (box[2][0], half[2])))
120 | child_geo7 = np.array(((box[0][0], half[0]), (box[1][0], half[1]), (box[2][0], half[2])))
121 | child_geo8 = np.array(((half[0], box[0][1]), (box[1][0], half[1]), (box[2][0], half[2])))
122 |
123 | return [child_geo1, child_geo2, child_geo3, child_geo4, child_geo5, child_geo6, child_geo7, child_geo8]
124 |
125 | @njit
126 | def _get_min_aspect_ratio(box, axis, half):
127 | half_loc = np.array([0.5*(half[i] - box[i][0]) for i in range(3)])
128 |
129 | match axis:
130 | case 0:
131 | return min(half_loc[0] / half_loc[1], half_loc[0] / half_loc[2]);
132 | case 1:
133 | return min(half_loc[1] / half_loc[0], half_loc[1] / half_loc[2]);
134 | case 2:
135 | return min(half_loc[2] / half_loc[1], half_loc[2] / half_loc[0]);
136 |
137 | @njit
138 | def _devide(box, axis, half):
139 | box1 = np.copy(box)
140 | box2 = np.copy(box)
141 |
142 | box1[axis][0] = box[axis][0]
143 | box1[axis][1] = half[axis]
144 |
145 | box2[axis][0] = half[axis]
146 | box2[axis][1] = box[axis][1]
147 |
148 | return (box1, box2)
149 |
150 | @njit
151 | def _create_combined_boxes(box, min_aspect_ratio, half):
152 | boxes = np.empty((15, 3, 2))
153 | boxes[0] = box
154 | N = 0
155 | Nold = 0
156 | q = 1
157 |
158 | for i in range(3):
159 | if _get_min_aspect_ratio(box, i, half) > min_aspect_ratio:
160 | for b in range(Nold, Nold + 2**N):
161 | new_boxes = _devide(boxes[b], i, half)
162 | boxes[q] = new_boxes[0]
163 | boxes[q + 1] = new_boxes[1]
164 | q += 2
165 | Nold += 2**N
166 | N += 1
167 |
168 | N = 2**N
169 | new_boxes = np.empty((N, 3, 2))
170 |
171 | for b in range(N):
172 | new_boxes[b] = boxes[Nold + b]
173 |
174 | return new_boxes
175 |
176 | @njit
177 | def _get_centre_of_mass(permutations, positions, offset, n_elements):
178 | com = np.zeros(3)
179 |
180 | for i in range(offset, offset + n_elements):
181 | p = permutations[i]
182 | com += positions[p]
183 |
184 | return com / float(n_elements)
185 |
186 | class Type(Enum):
187 | COV = 0
188 | COM = 1
189 |
190 | class Leaf:
191 | def __init__(self):
192 | self.level = 0
193 | self.elem_offset = 0
194 | self.number_elements = 0
195 | self.id_parent = None
196 | self.id_first_child = None
197 | self.number_children = 0
198 |
199 | class Octree:
200 | def __init__(self):
201 | self.clear()
202 | self.min_aspect_ratio = 2.0/3.0
203 | self.type = Type.COV
204 |
205 | def clear(self):
206 | self.cell_boxes = []
207 | self.leafs = []
208 | self.sigma_T = 3.631681e-19
209 | self.w = 1.0
210 | self.Nmin = 8
211 | self.Nmax = 64
212 | self.max_level = 10
213 | self.permutations = []
214 | self.cell_offsets = []
215 | self.level = 0
216 |
217 | def build(self, positions):
218 | self.clear()
219 | self._create_root(positions)
220 | self.permutations = np.array([i for i in range(len(positions))])
221 |
222 | for level in range(self.max_level):
223 | self.level += 1
224 | self.cell_offsets.append(self.cell_offsets[-1])
225 | for i in range(self.cell_offsets[level], self.cell_offsets[level + 1]):
226 | self._progress(i, positions)
227 |
228 | if self.cell_offsets[level + 1] == self.cell_offsets[level + 2]:
229 | break
230 |
231 | def _create_root(self, positions):
232 | box = _find_bounding_box(positions)
233 | leaf = Leaf()
234 | leaf.number_elements = len(positions)
235 |
236 | self.cell_offsets += [0, 1]
237 | self.leafs.append(leaf)
238 | self.cell_boxes.append(box)
239 |
240 | def _progress(self, leaf_id, positions):
241 | if _is_resolved(self.cell_boxes[leaf_id], self.leafs[leaf_id].number_elements, self.w, self.sigma_T, self.Nmin, self.Nmax):
242 |
243 | self.leafs[leaf_id].id_first_child = self.cell_offsets[-1]
244 |
245 | if self.type == Type.COV:
246 | half = 0.5 * np.array([self.cell_boxes[leaf_id][i][1] + self.cell_boxes[leaf_id][i][0] for i in range(3)])
247 | elif self.type == Type.COM:
248 | half = _get_centre_of_mass(self.permutations, positions, self.leafs[leaf_id].elem_offset, self.leafs[leaf_id].number_elements)
249 |
250 | new_boxes = _create_combined_boxes(self.cell_boxes[leaf_id], self.min_aspect_ratio, half)
251 | self.cell_offsets[-1] += len(new_boxes)
252 | self.leafs[leaf_id].number_children = len(new_boxes)
253 |
254 | for box in new_boxes:
255 | self.cell_boxes.append(box)
256 |
257 | else:
258 | pass
259 |
260 | offset = 0
261 |
262 | for i in range(self.leafs[leaf_id].number_children):
263 | new_leaf = Leaf()
264 | new_leaf.level = self.leafs[leaf_id].level + 1
265 | new_leaf.id_parent = leaf_id
266 |
267 | new_leaf.elem_offset = self.leafs[leaf_id].elem_offset + offset
268 |
269 | self.permutations, N = _sort(self.permutations, self.cell_boxes[self.leafs[leaf_id].id_first_child + i], positions, new_leaf.elem_offset, self.leafs[leaf_id].number_elements - offset)
270 |
271 | new_leaf.number_elements = N
272 | offset += N
273 |
274 | self.leafs.append(new_leaf)
275 |
--------------------------------------------------------------------------------
/dsmc/dsmc.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | from numba import njit
3 | from numba import prange
4 | import numba
5 | from . import particles as prt
6 | from . import octree as oc
7 | from . import common as com
8 |
9 | @njit(cache=True)
10 | def _push(velocities, positions, dt):
11 | old_positions = np.copy(positions)
12 | for p in prange(len(positions)):
13 | positions[p] = positions[p] + velocities[p]*dt
14 | return (velocities, positions, old_positions)
15 |
16 | @njit(cache=True)
17 | def _boundary(velocities, positions, old_positions, domain, boundary_conds):
18 | kept_parts = np.ones(positions.shape[0], dtype=np.uint)
19 |
20 | for p in prange(len(positions)):
21 | while not oc._is_inside(positions[p], domain) and kept_parts[p]:
22 | for i in range(3):
23 | if positions[p][i] < domain[i][0]:
24 | if boundary_conds[i][0] == 0:
25 | old_positions[p][i] = positions[p][i]
26 | positions[p][i] = 2.0 * domain[i][0] - positions[p][i]
27 | velocities[p][i] *= -1.0
28 | elif boundary_conds[i][0] == 1 or boundary_conds[i][0] == 2:
29 | kept_parts[p] = 0
30 | if positions[p][i] > domain[i][1]:
31 | if boundary_conds[i][1] == 0:
32 | old_positions[p][i] = positions[p][i]
33 | positions[p][i] = 2.0 * domain[i][1] - positions[p][i]
34 | velocities[p][i] *= -1.0
35 | elif boundary_conds[i][1] == 1 or boundary_conds[i][0] == 2:
36 | kept_parts[p] = 0
37 |
38 | N = int(sum(kept_parts))
39 | p = 0
40 | new_velocities = np.empty((N, 3))
41 | new_positions = np.empty((N, 3))
42 | new_old_positions = np.empty((N, 3))
43 |
44 | for i in range(positions.shape[0]):
45 | if kept_parts[i] == 1:
46 | new_velocities[p] = velocities[i]
47 | new_positions[p] = positions[i]
48 | new_old_positions[p] = old_positions[p]
49 | p += 1
50 | else:
51 | continue
52 |
53 | return (new_velocities, new_positions, new_old_positions)
54 |
55 | @njit(cache=True)
56 | def _check_positions(velocities, positions, old_positions, domain):
57 | kept_parts = np.ones(positions.shape[0], dtype=np.uint)
58 |
59 | for i in prange(positions.shape[0]):
60 | if (not oc._is_inside(positions[i], domain)) and (not oc._is_inside(old_positions[i], domain)):
61 | kept_parts[i] = 0
62 |
63 | N = sum(kept_parts)
64 | p = 0
65 | new_velocities = np.empty((N, 3))
66 | new_positions = np.empty((N, 3))
67 | new_old_positions = np.empty((N, 3))
68 |
69 | for i in prange(positions.shape[0]):
70 | if kept_parts[i] == 1:
71 | new_velocities[p] = velocities[i]
72 | new_positions[p] = positions[i]
73 | new_old_positions[p] = old_positions[i]
74 | p += 1
75 | else:
76 | continue
77 |
78 | return (new_velocities, new_positions, new_old_positions)
79 |
80 | @njit(cache=True)
81 | def _check_created_particles(velocities, positions, obj):
82 | kept_parts = np.ones(positions.shape[0], dtype=np.uint)
83 |
84 | for i in prange(positions.shape[0]):
85 | if oc._is_inside(positions[i], obj):
86 | kept_parts[i] = 0
87 |
88 | N = sum(kept_parts)
89 | p = 0
90 | new_velocities = np.empty((N, 3))
91 | new_positions = np.empty((N, 3))
92 |
93 | for i in prange(positions.shape[0]):
94 | if kept_parts[i] == 1:
95 | new_velocities[p] = velocities[i]
96 | new_positions[p] = positions[i]
97 | p += 1
98 | else:
99 | continue
100 |
101 | return (new_velocities, new_positions)
102 |
103 | @njit(cache=True)
104 | def _object(velocities, positions, old_positions, coll_obj):
105 | for p in range(positions.shape[0]):
106 | if oc._is_inside(positions[p], coll_obj):
107 | for i in range(3):
108 | if (old_positions[p][i] < coll_obj[i][0]):
109 | old_positions[p][i] = positions[p][i]
110 | positions[p][i] = 2.0 * coll_obj[i][0] - positions[p][i]
111 | velocities[p][i] *= -1.0
112 |
113 | if (old_positions[p][i] > coll_obj[i][1]):
114 | old_positions[p][i] = positions[p][i]
115 | positions[p][i] = 2.0 * coll_obj[i][1] - positions[p][i]
116 | velocities[p][i] *= -1.0
117 |
118 | return (velocities, positions, old_positions)
119 |
120 | @njit(cache=True)
121 | def _calc_prob(rel_vel : float, sigma_T : float, Vc : float, dt : float, w : float, N : int) -> np.single:
122 | """
123 | Parameters
124 | ----------
125 | vel1 : velocity
126 | vel2 : velocity
127 | sigma_T : float
128 | total cross section
129 | Vc : float
130 | cell volume
131 | w : float
132 | weight
133 | N : int
134 | number of particles
135 |
136 | Returns
137 | -------
138 | collision proability : float
139 | """
140 | return rel_vel * sigma_T * dt * w * N / Vc;
141 |
142 | @njit(numba.types.Tuple((numba.float64[:], numba.float64[:]))(numba.float64[:], numba.float64[:], numba.float64, numba.float64, numba.float64, numba.float64, numba.float64))
143 | def _calc_post_col_vels(velocity1 : np.ndarray, velocity2 : np.ndarray, mass1 : float, mass2 : float, rel_vel_module : float, rand_number1 : float, rand_number2 : float) -> tuple[np.ndarray, np.ndarray]:
144 | mass12 = (mass1 + mass2)
145 | mass1_12 = (mass1 / mass12)
146 | mass2_12 = (mass2 / mass12)
147 |
148 | cos_xi = (2.0 * rand_number1 - 1.0)
149 | sin_xi = (np.sqrt(1.0 - cos_xi * cos_xi))
150 | epsilon = (2.0 * np.pi * rand_number2)
151 |
152 | centre_of_mass_velocity = (velocity1 * mass1 + velocity2 * mass2) * (1.0 / mass12)
153 |
154 | rel_velocity_new = np.empty((3, ))
155 |
156 | rel_velocity_new[0] = rel_vel_module * cos_xi
157 | rel_velocity_new[1] = rel_vel_module * sin_xi * np.cos(epsilon)
158 | rel_velocity_new[2] = rel_vel_module * sin_xi * np.sin(epsilon)
159 |
160 | return (centre_of_mass_velocity + rel_velocity_new * mass2_12 , centre_of_mass_velocity - rel_velocity_new * mass1_12)
161 |
162 | @njit(numba.float64[:, :](numba.int64[:], numba.float64[:, :], numba.float64, numba.float64, numba.float64, numba.float64, numba.float64, numba.int64, numba.int64))
163 | def _update_velocities(permutations : np.ndarray, velocities : np.ndarray, mass : float, sigma_T : float, Vc : float, dt : float, w : float, offset : int, N : int) -> np.ndarray:
164 | for i in range(1, N, 2):
165 | p1 = permutations[offset + i - 1]
166 | p2 = permutations[offset + i]
167 | rel_vel = np.linalg.norm(velocities[p1] - velocities[p2])
168 | P = _calc_prob(rel_vel, sigma_T, Vc, dt, w, N)
169 | R = np.random.random(3)
170 |
171 | if R[0] < P:
172 | new_vels = _calc_post_col_vels(velocities[p1], velocities[p2], mass, mass, rel_vel, R[1], R[2])
173 | velocities[p1] = new_vels[0]
174 | velocities[p2] = new_vels[1]
175 |
176 | return velocities
177 |
178 | @njit(numba.float64[:, :](numba.int64[:], numba.float64[:, :], numba.float64, numba.float64, numba.float64, numba.float64, numba.int64[:], numba.int64[:], numba.int64[:], numba.float64[:, : , :], numba.int64))
179 | def _update_vels(permutations : np.ndarray, velocities : np.ndarray, mass : float, sigma_T : float, dt : float, w : float, elem_offsets : np.ndarray, number_elements : np.ndarray, number_children : np.ndarray, cell_boxes : np.ndarray, Nleafs : int) -> np.ndarray:
180 | for i in range(Nleafs):
181 | if not number_children[i] and number_elements[i]:
182 | Vc = com.get_V(cell_boxes[i])
183 | velocities = _update_velocities(permutations, velocities, mass, sigma_T, Vc, dt, w, elem_offsets[i], number_elements[i])
184 |
185 | return velocities
186 |
187 | @njit(cache=True)
188 | def _get_boundary(boundary):
189 | if boundary == "xmin":
190 | return (0, 0)
191 | elif boundary == "xmax":
192 | return (0, 1)
193 | elif boundary == "ymin":
194 | return (1, 0)
195 | elif boundary == "ymax":
196 | return (1, 1)
197 | elif boundary == "zmin":
198 | return (2, 0)
199 | elif boundary == "zmax":
200 | return (2, 1)
201 |
202 | @njit(cache=True)
203 | def _get_bc_type(bc_type):
204 | if bc_type == "ela":
205 | return 0
206 | elif bc_type == "open":
207 | return 1
208 | elif bc_type == "inflow":
209 | return 2
210 |
211 | class Boundary:
212 | def __init__(self):
213 | self.T = np.ones((3, 2))*300.0
214 | self.n = np.ones((3, 2))*1e+18
215 | self.u = np.zeros((3, 2, 3))
216 |
217 | class DSMC:
218 | def __init__(self):
219 | self.clear()
220 |
221 | def clear(self):
222 | self.particles = prt.Particles()
223 | self.octree = oc.Octree()
224 | self.w = None
225 | self.domain = None
226 | self.boundary_conds = np.array([[0, 0], [0, 0], [0, 0]], dtype=np.uint) # 0 = ela, 1 = open, 2 = inflow
227 | self.boundary = Boundary()
228 | self.sigma_T = 3.631681e-19
229 | self.mass = None
230 | self.objects = []
231 |
232 | def advance(self, dt, collisions=True, octree=True):
233 | if self.domain is None:
234 | raise Exception("simulation domain not defined")
235 | if self.particles.N == 0:
236 | print("warning: no particles in domain")
237 | if self.w == None:
238 | raise Exception("particle weight not set")
239 |
240 | for i in range(3):
241 | for j in range(2):
242 | if self.boundary_conds[i][j] == 2:
243 | self.particles.inflow(self.mass, self.boundary.T[i][j], self.boundary.u[i][j], self.boundary.n[i][j], self.w, dt, self.domain, i, j)
244 |
245 | velocities, positions, old_positions = _push(self.particles.Vel, self.particles.Pos, dt)
246 | velocities, positions, old_positions = _check_positions(velocities, positions, old_positions, self.domain)
247 |
248 |
249 | for obj in self.objects:
250 | velocities, positions, old_positions = _object(velocities, positions, old_positions, obj)
251 |
252 | velocities, positions, old_positions = _boundary(velocities, positions, old_positions, self.domain, self.boundary_conds)
253 |
254 | if octree:
255 | self.octree.build(positions)
256 | if collisions and octree:
257 | velocities = self._update_velocities(dt, velocities)
258 |
259 | self.particles.VelPos = (velocities, positions)
260 |
261 | def _update_velocities(self, dt, velocities):
262 | Nleafs : int = len(self.octree.leafs)
263 | elem_offsets : np.ndarray = np.array([leaf.elem_offset for leaf in self.octree.leafs], dtype=int)
264 | number_elements : np.ndarray = np.array([leaf.number_elements for leaf in self.octree.leafs], dtype=int)
265 | number_children : np.ndarray = np.array([leaf.number_children for leaf in self.octree.leafs], dtype=int)
266 | cell_boxes : np.ndarray = np.array([box for box in self.octree.cell_boxes])
267 |
268 | return _update_vels(self.octree.permutations, velocities, self.mass, self.sigma_T, dt, self.w, elem_offsets, number_elements, number_children, cell_boxes, Nleafs)
269 |
270 | def create_particles(self, box, T, n, u = np.zeros(3)):
271 | box = np.array(box)
272 | N = int(round(com.get_V(box) * n / self.w))
273 | print("creating {} particles".format(N))
274 | self.particles.create_particles(box, self.mass, T, N, u)
275 |
276 | for obj in self.objects:
277 | self.particles.VelPos = _check_created_particles(self.particles.Vel, self.particles.Pos, obj)
278 |
279 | print("now containing {} particles, {} total".format(N, self.particles.N))
280 |
281 | def set_domain(self, domain):
282 | self.domain = np.array(domain)
283 |
284 | def set_mass(self, mass):
285 | self.mass = mass
286 |
287 | def set_weight(self, w):
288 | self.octree.w = w
289 | self.w = w
290 |
291 | def set_bc_type(self, boundary, bc_type):
292 | bound = _get_boundary(boundary)
293 | bc = _get_bc_type(bc_type)
294 |
295 | self.boundary_conds[bound[0]][bound[1]] = bc
296 |
297 | print("boundary [" + boundary + "] set to [" + bc_type + "]")
298 |
299 | def set_bc_values(self, boundary, T, n, u):
300 | i, j = _get_boundary(boundary)
301 |
302 | self.boundary.T[i][j] = T
303 | self.boundary.n[i][j] = n
304 | self.boundary.u[i][j] = u
305 |
306 | print("boundary [" + boundary + "] set to values T : {}, n : {}, u : {}".format(T, n, u))
307 |
308 | def add_object(self, coll_object):
309 | self.objects.append(np.array(coll_object))
--------------------------------------------------------------------------------
/tests/unit/test_dsmc/octree.py:
--------------------------------------------------------------------------------
1 | import unittest
2 | import numpy as np
3 | from dsmc import octree as oc
4 | from dsmc import common as com
5 | import csv
6 |
7 | class TestOctree(unittest.TestCase):
8 | def test__find_bounding_box(self):
9 | positions = np.array([(0.0, 0.0, -1.0), (-2.0, -3.0, 0.0), (4.0, 5.0, 0.0)])
10 | box = oc._find_bounding_box(positions)
11 |
12 | self.assertEqual(-2.0, box[0][0])
13 | self.assertEqual(4.0, box[0][1])
14 |
15 | self.assertEqual(-3.0, box[1][0])
16 | self.assertEqual(5.0, box[1][1])
17 |
18 | self.assertEqual(-1.0, box[2][0])
19 | self.assertEqual(0.0, box[2][1])
20 |
21 | def test__calc_N_res(self):
22 | w = 1.0e+9
23 | sigma_T = 1.0e-16
24 | n = 1.0e+17
25 | ref = int(round(np.sqrt(2) / (32.0 * w * sigma_T**3 * n**2)))
26 | N = oc._calc_N_res(w, sigma_T, n)
27 |
28 | self.assertEqual(ref, N)
29 |
30 | def test__calc_n(self):
31 | box = ((0, 1), (2, 4), (4, 7))
32 | N = 300
33 | w = 100
34 | res = oc._calc_n(box, N, w)
35 |
36 | self.assertEqual(18.0, res)
37 |
38 | def test__is_inside(self):
39 | box = [[2.0, 3.0], [4.0, 6.0], [-1.0, 1.0]]
40 | box = np.array(box)
41 | position1 = np.array([2.5, 5.0, 0.0])
42 | position2 = np.array([0.0, 0.0, 0.0])
43 | position3 = np.array([2.5, 6.0, 0.5])
44 |
45 | self.assertTrue(oc._is_inside(position1, box))
46 | self.assertFalse(oc._is_inside(position2, box))
47 | self.assertTrue(oc._is_inside(position3, box))
48 |
49 | def test_sort(self):
50 | box = np.array([[0.0, 1.0], [0.0, 1.0], [0.0, 1.0]])
51 | positions1 = np.random.random((100, 3))
52 | positions2 = np.random.random((200, 3)) - np.ones((200, 3))*2
53 | positions = np.concatenate((positions2, positions1, positions2))
54 | permutations1 = np.array([i for i in range(len(positions2))])
55 | permutations2 = np.array([i for i in range(len(positions2), len(positions))])
56 | np.random.shuffle(permutations2)
57 | permutations = np.concatenate((permutations1, permutations2))
58 | offset = len(positions2)
59 | N = len(positions1) + len(positions2)
60 | count = 0
61 |
62 | for position in positions1:
63 | self.assertTrue(oc._is_inside(position, box))
64 |
65 | for position in positions2:
66 | self.assertFalse(oc._is_inside(position, box))
67 |
68 | for position in positions:
69 | if oc._is_inside(position, box):
70 | count += 1
71 |
72 | self.assertEqual(len(positions1), count)
73 |
74 | self.assertEqual(len(positions2), len(permutations1))
75 | self.assertEqual(len(positions1) + len(positions2), len(permutations2))
76 | self.assertEqual(len(positions), len(permutations))
77 |
78 | permutations, Nnew = oc._sort(permutations, box, positions, offset, N)
79 |
80 | self.assertEqual(Nnew, len(positions1))
81 |
82 | for i in range(offset, offset + Nnew):
83 | p = permutations[i]
84 | self.assertTrue(oc._is_inside(positions[p], box))
85 |
86 | for i in range(offset + Nnew, len(permutations)):
87 | p = permutations[i]
88 | self.assertFalse(oc._is_inside(positions[p], box))
89 |
90 | def test_sort2(self):
91 | box = np.array([[0.0, 1.0], [0.0, 1.0], [0.0, 1.0]])
92 | N = 20
93 | Nh = 10
94 | Nm = 15
95 | Np = 5
96 | positions = np.empty((N, 3))
97 | positions1 = np.empty((Np, 3))
98 | positions2 = np.empty((Np, 3))
99 | positions3 = np.empty((Nh, 3))
100 | permutations = np.array([i for i in range(N)])
101 |
102 | for i in range(Np):
103 | positions1[i] = np.random.random(3) - np.ones(3)
104 |
105 | for i in range(Np):
106 | positions2[i] = np.random.random(3)
107 |
108 | for i in range(Nh):
109 | positions3[i] = np.random.random(3) - np.ones(3)
110 |
111 | positions = np.concatenate((positions3, positions1, positions2))
112 | permutations, Nnew = oc._sort(permutations, box, positions, Nh, Nh)
113 |
114 | self.assertEqual(Nnew, Np)
115 |
116 | for i in range(Nh):
117 | p = permutations[i]
118 | pos = positions[p]
119 | a = not (pos[0] <= box[0][1])
120 | b = not (pos[0] >= box[0][0])
121 |
122 | c = not (pos[1] <= box[1][1])
123 | d = not (pos[1] >= box[1][0])
124 |
125 | e = not (pos[2] <= box[2][1])
126 | f = not (pos[2] >= box[2][0])
127 |
128 | self.assertTrue(a or b or c or d or e or f)
129 |
130 | for i in range(Nm, N):
131 | p = permutations[i]
132 | pos = positions[p]
133 | a = not (pos[0] <= box[0][1])
134 | b = not (pos[0] >= box[0][0])
135 |
136 | c = not (pos[1] <= box[1][1])
137 | d = not (pos[1] >= box[1][0])
138 |
139 | e = not (pos[2] <= box[2][1])
140 | f = not (pos[2] >= box[2][0])
141 |
142 | self.assertTrue(a or b or c or d or e or f)
143 |
144 | for i in range(Nh, Nm):
145 | p = permutations[i]
146 | pos = positions[p]
147 | a = (pos[0] <= box[0][1])
148 | b = (pos[0] >= box[0][0])
149 |
150 | c = (pos[1] <= box[1][1])
151 | d = (pos[1] >= box[1][0])
152 |
153 | e = (pos[2] <= box[2][1])
154 | f = (pos[2] >= box[2][0])
155 |
156 | self.assertTrue(a and b and c and d and e and f)
157 |
158 |
159 | def load_particles(self):
160 | positions = []
161 |
162 | with open("./test_data/particles.csv", "r", newline='') as csvfile:
163 | reader = csv.reader(csvfile, delimiter=',')
164 | for row in reader:
165 | positions.append([float(row[i]) for i in range(3)])
166 |
167 | return np.array(positions)
168 |
169 | def test_sort3(self):
170 | box = np.array([[-1.0, 1.0], [-1.0, 1.0], [-1.0, 1.0]])
171 | boxes = [] + oc._create_boxes(box)
172 | N = 100
173 | permutations = np.array([i for i in range(N)])
174 | positions = self.load_particles()
175 |
176 | permutations , Np1 = oc._sort(permutations, boxes[0], positions, 0, N)
177 | permutations , Np2 = oc._sort(permutations, boxes[1], positions, Np1, N - Np1)
178 | permutations , Np3 = oc._sort(permutations, boxes[2], positions, Np1 + Np2, N - Np2 - Np1)
179 | #permutations , Np4 = oc._sort(permutations, boxes[3], positions, Np3, N - Np3)
180 |
181 | #permutations , Np5 = oc._sort(permutations, boxes[4], positions, Np4, N - Np4)
182 | #permutations , Np6 = oc._sort(permutations, boxes[5], positions, Np5, N - Np5)
183 | #permutations , Np7 = oc._sort(permutations, boxes[6], positions, Np6, N - Np6)
184 | #permutations , Np8 = oc._sort(permutations, boxes[7], positions, Np7, N - Np7)
185 |
186 | Nnew = np.zeros(8, dtype=int)
187 |
188 | for i in range(Np1):
189 | p = permutations[i]
190 | pos = positions[p]
191 | if oc._is_inside(pos, boxes[0]):
192 | Nnew[0] += 1
193 |
194 | self.assertEqual(Nnew[0], Np1)
195 |
196 | for i in range(Np1, Np1 + Np2):
197 | p = permutations[i]
198 | pos = positions[p]
199 | if oc._is_inside(pos, boxes[1]):
200 | Nnew[1] += 1
201 |
202 | self.assertEqual(Nnew[1], Np2)
203 |
204 | for i in range(Np1 + Np2, Np1 + Np2 + Np3):
205 | p = permutations[i]
206 | pos = positions[p]
207 | if oc._is_inside(pos, boxes[2]):
208 | Nnew[2] += 1
209 |
210 | self.assertEqual(Nnew[2], Np3)
211 |
212 | def test__create_boxes(self):
213 | box_orig = np.array([[-1.0, 1.0], [-1.0, 1.0], [-1.0, 1.0]])
214 | boxes = oc._create_boxes(box_orig)
215 |
216 | self.assertEqual(8, len(boxes))
217 | V = 0.0
218 |
219 | for box in boxes:
220 | V += com.get_V(box)
221 |
222 | self.assertEqual(com.get_V(box_orig), V)
223 |
224 | def test__get_min_aspect_ratio_1(self):
225 | box = np.array([(0.0, 1.0), (0.0, 10.0), (0.0, 100.0)])
226 | half = 0.5 * np.array([box[i][1] + box[i][0] for i in range(3)])
227 | axis1 = 0
228 | axis2 = 1
229 | axis3 = 2
230 |
231 | self.assertEqual(0.01, oc._get_min_aspect_ratio(box, axis1, half))
232 | self.assertEqual(0.1, oc._get_min_aspect_ratio(box, axis2, half))
233 | self.assertEqual(10.0, oc._get_min_aspect_ratio(box, axis3, half))
234 |
235 | def test__get_min_aspect_ratio_2(self):
236 | box = np.array([(-1.0, 1.0), (-10.0, 10.0), (-100.0, 100.0)])
237 | half = 0.5 * np.array([box[i][1] + box[i][0] for i in range(3)])
238 | axis1 = 0
239 | axis2 = 1
240 | axis3 = 2
241 |
242 | self.assertEqual(0.01, oc._get_min_aspect_ratio(box, axis1, half))
243 | self.assertEqual(0.1, oc._get_min_aspect_ratio(box, axis2, half))
244 | self.assertEqual(10.0, oc._get_min_aspect_ratio(box, axis3, half))
245 |
246 | def test__devide(self):
247 | box = np.array([(0.0, 1.0), (0.0, 10.0), (0.0, 100.0)])
248 | half = 0.5 * np.array([box[i][1] + box[i][0] for i in range(3)])
249 | box_x1, box_x2 = oc._devide(box, 0, half)
250 | box_y1, box_y2 = oc._devide(box, 1, half)
251 | box_z1, box_z2 = oc._devide(box, 2, half)
252 |
253 | boxes = ((box_x1, box_x2), (box_y1, box_y2), (box_z1, box_z2))
254 |
255 | half = np.array([0.5*(box[i][0] + box[i][1]) for i in range(3)])
256 |
257 | for b in range(3):
258 | box_a = boxes[b][0]
259 | box_b = boxes[b][1]
260 |
261 | self.assertEqual(box_a[b][0], box[b][0])
262 | self.assertEqual(box_a[b][1], half[b])
263 |
264 | self.assertEqual(box_b[b][0], half[b])
265 | self.assertEqual(box_b[b][1], box[b][1])
266 |
267 | for i in range(3):
268 | for j in range(2):
269 | if b != i:
270 | self.assertEqual(box_a[i][j], box[i][j])
271 | self.assertEqual(box_b[i][j], box[i][j])
272 |
273 | def test__create_combined_boxes_1(self):
274 | box = np.array([(0.0, 1.0), (0.0, 10.0), (0.0, 100.0)])
275 | half = 0.5 * np.array([box[i][1] + box[i][0] for i in range(3)])
276 | min_aspect_ratio = 0.0
277 | boxes_old = oc._create_boxes(box)
278 | boxes_new = oc._create_combined_boxes(box, min_aspect_ratio, half)
279 | V = 0.0
280 |
281 | for b in boxes_new:
282 | V += com.get_V(b)
283 |
284 | self.assertEqual(com.get_V(box), V)
285 | self.assertEqual(len(boxes_old), len(boxes_new))
286 |
287 | def test__create_combined_boxes_2(self):
288 | box = np.array([(0.0, 1.0), (0.0, 10.0), (0.0, 100.0)])
289 | half = 0.5 * np.array([box[i][1] + box[i][0] for i in range(3)])
290 | min_aspect_ratio = 0.05
291 | boxes_new = oc._create_combined_boxes(box, min_aspect_ratio, half)
292 | V = 0.0
293 |
294 | for b in boxes_new:
295 | V += com.get_V(b)
296 |
297 | self.assertEqual(com.get_V(box), V)
298 | self.assertEqual(4, len(boxes_new))
299 |
300 | def test__create_combined_boxes_3(self):
301 | box = np.array([(-1.0, 1.0), (-10.0, 10.0), (-100.0, 100.0)])
302 | half = 0.5 * np.array([box[i][1] + box[i][0] for i in range(3)])
303 | min_aspect_ratio = 0.05
304 | boxes_new = oc._create_combined_boxes(box, min_aspect_ratio, half)
305 | V = 0.0
306 |
307 | for b in boxes_new:
308 | V += com.get_V(b)
309 |
310 | self.assertEqual(com.get_V(box), V)
311 | self.assertEqual(4, len(boxes_new))
312 |
313 | def test__create_combined_boxes_4(self):
314 | box = np.array([(-1.0, 1.0), (-10.0, 10.0), (-100.0, 100.0)])
315 | half = 0.5 * np.array([box[i][1] + box[i][0] for i in range(3)])
316 | min_aspect_ratio = 0.0
317 | boxes_new = oc._create_combined_boxes(box, min_aspect_ratio, half)
318 | V = 0.0
319 |
320 | for b in boxes_new:
321 | V += com.get_V(b)
322 |
323 | self.assertEqual(com.get_V(box), V)
324 | self.assertEqual(8, len(boxes_new))
325 |
326 |
327 | def test__get_centre_of_mass(self):
328 | permutations = np.array([i for i in range(4)])
329 | positions = np.array([[-1.0, -1.0, 0.0], [1.0, -1.0, 0.0], [1.0, 1.0, 0.0], [-1.0, 1.0, 0.0]])
330 | offset = 0
331 | n_elements = 4
332 |
333 | centre_of_mass = oc._get_centre_of_mass(permutations, positions, offset, n_elements)
334 |
335 | self.assertEqual(0.0, centre_of_mass[0])
336 | self.assertEqual(0.0, centre_of_mass[1])
337 | self.assertEqual(0.0, centre_of_mass[2])
338 |
339 | class TestOctreeOctree(unittest.TestCase):
340 | def test_build(self):
341 | positions = np.random.random((1000, 3))*2.0 - np.ones((1000, 3))
342 | octree = oc.Octree()
343 | octree.w = 1e+18
344 |
345 | octree.build(positions)
346 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------