SPHShore 0.1.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
sphshore-0.1.1/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 SPHShore contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,4 @@
1
+ include LICENSE README.md
2
+ recursive-include cpp *.cpp
3
+ recursive-include examples *.py
4
+ recursive-include tests *.py
@@ -0,0 +1,174 @@
1
+ Metadata-Version: 2.4
2
+ Name: SPHShore
3
+ Version: 0.1.1
4
+ Summary: C++ accelerated three-dimensional SPH wave tank with sloping shore and vertical pillars
5
+ Author: SPHShore contributors
6
+ License-Expression: MIT
7
+ Keywords: SPH,smoothed particle hydrodynamics,waves,wave tank,fluid simulation,coastal
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Science/Research
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Classifier: Programming Language :: C++
13
+ Classifier: Topic :: Scientific/Engineering :: Physics
14
+ Classifier: Operating System :: OS Independent
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: numpy<2.3,>=1.26.4
19
+ Provides-Extra: dev
20
+ Requires-Dist: pytest>=7; extra == "dev"
21
+ Requires-Dist: build; extra == "dev"
22
+ Requires-Dist: twine; extra == "dev"
23
+ Requires-Dist: cibuildwheel>=2; extra == "dev"
24
+ Dynamic: license-file
25
+
26
+ # SPHShore
27
+
28
+ **SPHShore** is an early-stage, C++17-accelerated Python package for simulating water waves in a three-dimensional smoothed particle hydrodynamics (SPH) tank. It retains the original wave-tank solver, with a moving piston wavemaker, an inclined shoreline and two fixed vertical pillars (one submerged, one extending above the still-water level).
29
+ ## Install locally
30
+
31
+ Python 3.10+ and a C++17 compiler are required when building from source. On Windows, install Visual Studio Build Tools with the C++ workload; on Linux/macOS use a suitable C++ compiler.
32
+
33
+ ```bash
34
+ python -m pip install .
35
+ ```
36
+
37
+ For development:
38
+
39
+ ```bash
40
+ python -m pip install -e '.[dev]'
41
+ python -m pytest -q
42
+ ```
43
+
44
+ Once a release is actually uploaded to PyPI and wheels are built for your platform, the installation command will be:
45
+
46
+ ```bash
47
+ python -m pip install SPHShore
48
+ ```
49
+
50
+ **Do not assume the PyPI command works until the owner has published a release.**
51
+
52
+ ## Quick start
53
+
54
+ ```python
55
+ import sphshore
56
+
57
+ config = sphshore.Parameters(
58
+ MaxDimmensions=(1.20, 0.45, 0.30),
59
+ N=1200,
60
+ TimeStep=0.00005,
61
+ MapEveryIterations=50,
62
+ WriteFiles=False,
63
+ )
64
+
65
+ with sphshore.WaveTank(config) as tank:
66
+ for iteration, time, velocity_map in tank.run_maps(200):
67
+ print(iteration, time, velocity_map.shape)
68
+ positions = tank.positions() # shape (N, 3), metres
69
+ velocities = tank.velocities() # shape (N, 3), metres/s
70
+ particles = tank.particles() # shape (N, 9)
71
+ ```
72
+
73
+ ### Velocity map
74
+
75
+ `outputMap()` or `velocity_map()` uses the C++ spatial hashing grid and returns an `(M, 7)` `float64` NumPy array with columns:
76
+
77
+ | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
78
+ |---|---|---|---|---|---|---|
79
+ | x | y | z | vx | vy | vz | particle count |
80
+
81
+ Cell positions are in metres and average velocities in metres per second. The map includes only **occupied** cells. It is produced on demand and held in memory; no files are needed.
82
+
83
+ ### Fluid particles
84
+
85
+ `particles()` returns an `(N, 9)` `float64` array:
86
+
87
+ `id, x, y, z, vx, vy, vz, density, pressure`.
88
+
89
+ `positions()` and `velocities()` return copies with three columns each.
90
+
91
+ ### Adjustable parameters
92
+
93
+ | Python parameter | Meaning |
94
+ |---|---|
95
+ | `MaxDimmensions=(L,W,H)` | Dimensions in metres; rescales the shoreline, water depth and both pillars |
96
+ | `MinDimmensions=(x,y,z)` | Tank origin |
97
+ | `N` | Number of water particles |
98
+ | `TimeStep` | Solver integration timestep in seconds, checked against a CFL bound |
99
+ | `MapEveryIterations` | Python-side interval between successive returned velocity maps |
100
+ | `PistonBaseX` | Piston neutral X-position (metres); `None` means a scale-dependent default |
101
+ | `PistonAmplitude` | Piston oscillation amplitude (metres); `None` means a scale-dependent default |
102
+ | `WaveFrequency` | Sinusoidal piston frequency, in Hz |
103
+ | `WaveStartTime` | Piston start, in simulated seconds |
104
+ | `WaveRampTime` | Smooth piston startup duration |
105
+ | `WriteFiles` | Opt-in CSV log and configuration output; default `False` |
106
+ | `SaveEveryTime` | Simulated seconds between log snapshots when writing files |
107
+
108
+ Changing all three dimensions by the same factor preserves geometric similarity. For unequal X, Y and Z scaling, horizontal pillar cross sections stay circular; the ramp slope adjusts accordingly. Changing the tank scale does *not* automatically tune the timestep, wave period or numerical stability parameters.
109
+
110
+ ### Arbitrary run length
111
+
112
+ The C++ library has no fixed total-iteration cutoff. Python controls stepping:
113
+
114
+ ```python
115
+ with sphshore.WaveTank(config) as tank:
116
+ for _ in range(100):
117
+ tank.step(100)
118
+ ```
119
+
120
+ Calls to `step()` accept a nonnegative 64-bit integer count. The cumulative counter is also finite (`uint64_t`); practical limits include time, memory and numerical stability.
121
+
122
+ ### Custom piston motion
123
+
124
+ ```python
125
+ with sphshore.WaveTank(config) as tank:
126
+ for _ in range(100):
127
+ t = tank.time
128
+ tank.set_piston_state(position=0.03, velocity=0.0)
129
+ tank.step(1)
130
+ tank.use_sinusoidal_piston()
131
+ ```
132
+
133
+ Change the custom state before every individual timestep for non-constant motion. The position must stay within the safe flume region.
134
+
135
+ ### No disk output
136
+
137
+ `WriteFiles=False` (default) means no `LogBook.txt` or `SimulationConfig.txt` is created by the solver. All state and maps can be requested as NumPy arrays. When `WriteFiles=True`, the existing CSV schema remains available for the older animation scripts.
138
+
139
+ ### AddPropulsion
140
+
141
+ The original C++ `AddPropulsion` grid helper is retained in the solver source, but **not invoked or exposed** in this release, respecting the earlier request to keep it unused.
142
+
143
+ ## Building packages for distribution
144
+
145
+ ```bash
146
+ python -m pip install build
147
+ python -m build
148
+ ```
149
+
150
+ The output is placed in `dist/`. A platform-specific wheel requires a matching OS/Python/architecture; GitHub Actions uses `cibuildwheel` to produce supported wheels and run tests.
151
+
152
+ ### Release checklist
153
+
154
+ 1. **Review the MIT licence and owner/author attribution**, and verify rights to all included code.
155
+ 2. Put this directory into a GitHub repository you control.
156
+ 3. Enable CI and review/test cross-platform wheels.
157
+ 4. Create a PyPI account, verify ownership of the desired **SPHShore** project name, and configure a **Trusted Publisher** for the repository and `.github/workflows/release.yml` (environment `pypi`).
158
+ 5. Update the version in `pyproject.toml` and `src/sphshore/__init__.py` before each release.
159
+ 6. Create a GitHub Release; the release workflow builds wheels and source distribution, then requests publishing through PyPI Trusted Publishing.
160
+ 7. Verify `python -m pip install SPHShore` in a fresh environment.
161
+
162
+ No GitHub repository or PyPI project is created automatically by this source code. Publishing requires the owner's account authorization and review.
163
+
164
+ ## Scientific and implementation notes
165
+
166
+ - Weakly compressible SPH with a 3D cubic-spline kernel, pressure/viscous terms, density diffusion and spatial hashing.
167
+ - The water is constrained by a sloping rigid bed, moving piston, side walls and two fixed cylindrical obstacles.
168
+ - SPH boundary conditions are approximate; the geometry/solver has not been fully validated against experiments.
169
+ - Python calls a compiled C++ extension built from the existing solver source; it is not a Python rewrite of the physics.
170
+ - Copyright notices on the original source are retained. This package's licence should be approved by all code rights-holders before publication.
171
+
172
+ ## Contributing
173
+
174
+ Bug reports, benchmark comparisons and reproducible test cases are welcome after a public repository has been created. Include Python version, platform, compiler, timestep and tank geometry for any numerical issue.
@@ -0,0 +1,149 @@
1
+ # SPHShore
2
+
3
+ **SPHShore** is an early-stage, C++17-accelerated Python package for simulating water waves in a three-dimensional smoothed particle hydrodynamics (SPH) tank. It retains the original wave-tank solver, with a moving piston wavemaker, an inclined shoreline and two fixed vertical pillars (one submerged, one extending above the still-water level).
4
+ ## Install locally
5
+
6
+ Python 3.10+ and a C++17 compiler are required when building from source. On Windows, install Visual Studio Build Tools with the C++ workload; on Linux/macOS use a suitable C++ compiler.
7
+
8
+ ```bash
9
+ python -m pip install .
10
+ ```
11
+
12
+ For development:
13
+
14
+ ```bash
15
+ python -m pip install -e '.[dev]'
16
+ python -m pytest -q
17
+ ```
18
+
19
+ Once a release is actually uploaded to PyPI and wheels are built for your platform, the installation command will be:
20
+
21
+ ```bash
22
+ python -m pip install SPHShore
23
+ ```
24
+
25
+ **Do not assume the PyPI command works until the owner has published a release.**
26
+
27
+ ## Quick start
28
+
29
+ ```python
30
+ import sphshore
31
+
32
+ config = sphshore.Parameters(
33
+ MaxDimmensions=(1.20, 0.45, 0.30),
34
+ N=1200,
35
+ TimeStep=0.00005,
36
+ MapEveryIterations=50,
37
+ WriteFiles=False,
38
+ )
39
+
40
+ with sphshore.WaveTank(config) as tank:
41
+ for iteration, time, velocity_map in tank.run_maps(200):
42
+ print(iteration, time, velocity_map.shape)
43
+ positions = tank.positions() # shape (N, 3), metres
44
+ velocities = tank.velocities() # shape (N, 3), metres/s
45
+ particles = tank.particles() # shape (N, 9)
46
+ ```
47
+
48
+ ### Velocity map
49
+
50
+ `outputMap()` or `velocity_map()` uses the C++ spatial hashing grid and returns an `(M, 7)` `float64` NumPy array with columns:
51
+
52
+ | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
53
+ |---|---|---|---|---|---|---|
54
+ | x | y | z | vx | vy | vz | particle count |
55
+
56
+ Cell positions are in metres and average velocities in metres per second. The map includes only **occupied** cells. It is produced on demand and held in memory; no files are needed.
57
+
58
+ ### Fluid particles
59
+
60
+ `particles()` returns an `(N, 9)` `float64` array:
61
+
62
+ `id, x, y, z, vx, vy, vz, density, pressure`.
63
+
64
+ `positions()` and `velocities()` return copies with three columns each.
65
+
66
+ ### Adjustable parameters
67
+
68
+ | Python parameter | Meaning |
69
+ |---|---|
70
+ | `MaxDimmensions=(L,W,H)` | Dimensions in metres; rescales the shoreline, water depth and both pillars |
71
+ | `MinDimmensions=(x,y,z)` | Tank origin |
72
+ | `N` | Number of water particles |
73
+ | `TimeStep` | Solver integration timestep in seconds, checked against a CFL bound |
74
+ | `MapEveryIterations` | Python-side interval between successive returned velocity maps |
75
+ | `PistonBaseX` | Piston neutral X-position (metres); `None` means a scale-dependent default |
76
+ | `PistonAmplitude` | Piston oscillation amplitude (metres); `None` means a scale-dependent default |
77
+ | `WaveFrequency` | Sinusoidal piston frequency, in Hz |
78
+ | `WaveStartTime` | Piston start, in simulated seconds |
79
+ | `WaveRampTime` | Smooth piston startup duration |
80
+ | `WriteFiles` | Opt-in CSV log and configuration output; default `False` |
81
+ | `SaveEveryTime` | Simulated seconds between log snapshots when writing files |
82
+
83
+ Changing all three dimensions by the same factor preserves geometric similarity. For unequal X, Y and Z scaling, horizontal pillar cross sections stay circular; the ramp slope adjusts accordingly. Changing the tank scale does *not* automatically tune the timestep, wave period or numerical stability parameters.
84
+
85
+ ### Arbitrary run length
86
+
87
+ The C++ library has no fixed total-iteration cutoff. Python controls stepping:
88
+
89
+ ```python
90
+ with sphshore.WaveTank(config) as tank:
91
+ for _ in range(100):
92
+ tank.step(100)
93
+ ```
94
+
95
+ Calls to `step()` accept a nonnegative 64-bit integer count. The cumulative counter is also finite (`uint64_t`); practical limits include time, memory and numerical stability.
96
+
97
+ ### Custom piston motion
98
+
99
+ ```python
100
+ with sphshore.WaveTank(config) as tank:
101
+ for _ in range(100):
102
+ t = tank.time
103
+ tank.set_piston_state(position=0.03, velocity=0.0)
104
+ tank.step(1)
105
+ tank.use_sinusoidal_piston()
106
+ ```
107
+
108
+ Change the custom state before every individual timestep for non-constant motion. The position must stay within the safe flume region.
109
+
110
+ ### No disk output
111
+
112
+ `WriteFiles=False` (default) means no `LogBook.txt` or `SimulationConfig.txt` is created by the solver. All state and maps can be requested as NumPy arrays. When `WriteFiles=True`, the existing CSV schema remains available for the older animation scripts.
113
+
114
+ ### AddPropulsion
115
+
116
+ The original C++ `AddPropulsion` grid helper is retained in the solver source, but **not invoked or exposed** in this release, respecting the earlier request to keep it unused.
117
+
118
+ ## Building packages for distribution
119
+
120
+ ```bash
121
+ python -m pip install build
122
+ python -m build
123
+ ```
124
+
125
+ The output is placed in `dist/`. A platform-specific wheel requires a matching OS/Python/architecture; GitHub Actions uses `cibuildwheel` to produce supported wheels and run tests.
126
+
127
+ ### Release checklist
128
+
129
+ 1. **Review the MIT licence and owner/author attribution**, and verify rights to all included code.
130
+ 2. Put this directory into a GitHub repository you control.
131
+ 3. Enable CI and review/test cross-platform wheels.
132
+ 4. Create a PyPI account, verify ownership of the desired **SPHShore** project name, and configure a **Trusted Publisher** for the repository and `.github/workflows/release.yml` (environment `pypi`).
133
+ 5. Update the version in `pyproject.toml` and `src/sphshore/__init__.py` before each release.
134
+ 6. Create a GitHub Release; the release workflow builds wheels and source distribution, then requests publishing through PyPI Trusted Publishing.
135
+ 7. Verify `python -m pip install SPHShore` in a fresh environment.
136
+
137
+ No GitHub repository or PyPI project is created automatically by this source code. Publishing requires the owner's account authorization and review.
138
+
139
+ ## Scientific and implementation notes
140
+
141
+ - Weakly compressible SPH with a 3D cubic-spline kernel, pressure/viscous terms, density diffusion and spatial hashing.
142
+ - The water is constrained by a sloping rigid bed, moving piston, side walls and two fixed cylindrical obstacles.
143
+ - SPH boundary conditions are approximate; the geometry/solver has not been fully validated against experiments.
144
+ - Python calls a compiled C++ extension built from the existing solver source; it is not a Python rewrite of the physics.
145
+ - Copyright notices on the original source are retained. This package's licence should be approved by all code rights-holders before publication.
146
+
147
+ ## Contributing
148
+
149
+ Bug reports, benchmark comparisons and reproducible test cases are welcome after a public repository has been created. Include Python version, platform, compiler, timestep and tank geometry for any numerical issue.
@@ -0,0 +1,211 @@
1
+ // SPHShore Python extension: CPython C-API interface around the existing C++ solver.
2
+ // No third-party C++ binding dependency is required to build the wheels.
3
+ #define PY_SSIZE_T_CLEAN
4
+ #include <Python.h>
5
+ #include <cstdint>
6
+ #include <cmath>
7
+ #include <limits>
8
+ #include <vector>
9
+ #include <string>
10
+
11
+ // These declarations must match the original solver C ABI.
12
+ struct WT_Config {
13
+ int N;
14
+ double TimeStep;
15
+ double MinX, MinY, MinZ;
16
+ double MaxX, MaxY, MaxZ;
17
+ double PistonBaseX, PistonAmplitude, WaveFrequency;
18
+ double WaveStartTime, WaveRampTime;
19
+ double SoundSpeed, SmoothingLengthFactor;
20
+ double DensityDiffusion, ArtificialViscosity, XSPHFactor;
21
+ unsigned int RandomSeed;
22
+ int WriteFiles;
23
+ double SaveEveryTime;
24
+ };
25
+ struct WT_MapRow {
26
+ double X,Y,Z,VX,VY,VZ;
27
+ int Count;
28
+ };
29
+ struct WT_ParticleRow {
30
+ int ID;
31
+ double X,Y,Z,VX,VY,VZ,Density,Pressure;
32
+ };
33
+ struct WT_Info {
34
+ std::uint64_t Iteration;
35
+ double Time, Spacing, SmoothingLength, ParticleMass;
36
+ };
37
+ extern "C" {
38
+ const char* WT_LastError();
39
+ void* WT_Create(const WT_Config*);
40
+ void WT_Destroy(void*);
41
+ int WT_Step(void*, std::uint64_t);
42
+ std::int64_t WT_GetMap(void*, WT_MapRow*, std::uint64_t);
43
+ std::int64_t WT_GetParticles(void*, WT_ParticleRow*, std::uint64_t);
44
+ int WT_GetInfo(void*, WT_Info*);
45
+ int WT_SetPistonState(void*, double, double);
46
+ int WT_UseSinusoidalPiston(void*);
47
+ }
48
+
49
+ static constexpr const char* CapsuleName = "sphshore.Simulation";
50
+ static void CapsuleDestructor(PyObject* obj) {
51
+ void* handle = PyCapsule_GetPointer(obj, CapsuleName);
52
+ if (handle) WT_Destroy(handle);
53
+ else PyErr_Clear();
54
+ }
55
+ static void* Handle(PyObject* obj) {
56
+ return PyCapsule_GetPointer(obj, CapsuleName);
57
+ }
58
+ static PyObject* NativeError() {
59
+ const char* message = WT_LastError();
60
+ PyErr_SetString(PyExc_RuntimeError, (message && *message) ? message : "SPHShore native solver error");
61
+ return nullptr;
62
+ }
63
+ static PyObject* Create(PyObject*, PyObject* args) {
64
+ PyObject* config;
65
+ if (!PyArg_ParseTuple(args, "O", &config)) return nullptr;
66
+ if (!PyDict_Check(config)) {
67
+ PyErr_SetString(PyExc_TypeError, "Native config must be a dictionary");
68
+ return nullptr;
69
+ }
70
+ // The Python Parameters class performs type/range checks before this call.
71
+ auto val = [config](const char* key) -> PyObject* { return PyDict_GetItemString(config, key); };
72
+ auto number = [&](const char* key, double& destination) -> bool {
73
+ PyObject* o = val(key);
74
+ if (!o) { PyErr_Format(PyExc_KeyError, "Missing config: %s", key); return false; }
75
+ destination = PyFloat_AsDouble(o);
76
+ if (PyErr_Occurred()) return false;
77
+ if (!std::isfinite(destination)) { PyErr_Format(PyExc_ValueError, "%s must be finite", key); return false; }
78
+ return true;
79
+ };
80
+ auto integer = [&](const char* key, long long& destination) -> bool {
81
+ PyObject* o = val(key);
82
+ if (!o) { PyErr_Format(PyExc_KeyError, "Missing config: %s", key); return false; }
83
+ destination = PyLong_AsLongLong(o);
84
+ return !PyErr_Occurred();
85
+ };
86
+ WT_Config c{};
87
+ long long n=0, seed=0, write=0;
88
+ if (!integer("N",n) || !integer("RandomSeed",seed) || !integer("WriteFiles",write)) return nullptr;
89
+ if (n<=0 || n>std::numeric_limits<int>::max() || seed<0 || seed>UINT32_MAX || (write!=0 && write!=1)) {
90
+ PyErr_SetString(PyExc_ValueError,"Invalid N, RandomSeed or WriteFiles"); return nullptr;
91
+ }
92
+ c.N=(int)n; c.RandomSeed=(unsigned int)seed; c.WriteFiles=(int)write;
93
+ if (!number("TimeStep",c.TimeStep) ||
94
+ !number("MinX",c.MinX) || !number("MinY",c.MinY) || !number("MinZ",c.MinZ) ||
95
+ !number("MaxX",c.MaxX) || !number("MaxY",c.MaxY) || !number("MaxZ",c.MaxZ) ||
96
+ !number("PistonBaseX",c.PistonBaseX) || !number("PistonAmplitude",c.PistonAmplitude) ||
97
+ !number("WaveFrequency",c.WaveFrequency) || !number("WaveStartTime",c.WaveStartTime) ||
98
+ !number("WaveRampTime",c.WaveRampTime) || !number("SoundSpeed",c.SoundSpeed) ||
99
+ !number("SmoothingLengthFactor",c.SmoothingLengthFactor) ||
100
+ !number("DensityDiffusion",c.DensityDiffusion) ||
101
+ !number("ArtificialViscosity",c.ArtificialViscosity) ||
102
+ !number("XSPHFactor",c.XSPHFactor) || !number("SaveEveryTime",c.SaveEveryTime)) return nullptr;
103
+ void* handle = nullptr;
104
+ Py_BEGIN_ALLOW_THREADS
105
+ handle = WT_Create(&c);
106
+ Py_END_ALLOW_THREADS
107
+ if (!handle) return NativeError();
108
+ PyObject* capsule = PyCapsule_New(handle, CapsuleName, CapsuleDestructor);
109
+ if (!capsule) WT_Destroy(handle);
110
+ return capsule;
111
+ }
112
+ static PyObject* Close(PyObject*, PyObject* args) {
113
+ PyObject* obj;
114
+ if (!PyArg_ParseTuple(args,"O", &obj)) return nullptr;
115
+ void* handle=Handle(obj);
116
+ if (!handle) return nullptr;
117
+ // Remove destructor before removing handle, preventing a double free.
118
+ if (PyCapsule_SetDestructor(obj,nullptr) != 0) return nullptr;
119
+ if (PyCapsule_SetName(obj,"sphshore.ClosedSimulation") != 0) return nullptr;
120
+ WT_Destroy(handle);
121
+ Py_RETURN_NONE;
122
+ }
123
+ static PyObject* Step(PyObject*, PyObject* args) {
124
+ PyObject* obj;
125
+ unsigned long long iterations;
126
+ if (!PyArg_ParseTuple(args,"OK", &obj, &iterations)) return nullptr;
127
+ void* h=Handle(obj);
128
+ if (!h) return nullptr;
129
+ int code=0;
130
+ Py_BEGIN_ALLOW_THREADS
131
+ code=WT_Step(h, (std::uint64_t)iterations);
132
+ Py_END_ALLOW_THREADS
133
+ if (code) return NativeError();
134
+ Py_RETURN_NONE;
135
+ }
136
+ static PyObject* Info(PyObject*, PyObject* args) {
137
+ PyObject* obj;
138
+ if (!PyArg_ParseTuple(args,"O", &obj)) return nullptr;
139
+ void* h=Handle(obj); if (!h) return nullptr;
140
+ WT_Info info{};
141
+ if (WT_GetInfo(h,&info)) return NativeError();
142
+ return Py_BuildValue("{s:K,s:d,s:d,s:d,s:d}",
143
+ "iteration",(unsigned long long)info.Iteration,
144
+ "time",info.Time, "particle_spacing",info.Spacing,
145
+ "smoothing_length",info.SmoothingLength,"particle_mass",info.ParticleMass);
146
+ }
147
+ static PyObject* Map(PyObject*, PyObject* args) {
148
+ PyObject* obj;
149
+ if (!PyArg_ParseTuple(args,"O", &obj)) return nullptr;
150
+ void* h=Handle(obj); if (!h) return nullptr;
151
+ std::int64_t n=WT_GetMap(h,nullptr,0);
152
+ if (n<0) return NativeError();
153
+ if ((std::uint64_t)n > (std::uint64_t)PY_SSIZE_T_MAX) { PyErr_SetString(PyExc_OverflowError,"map too large"); return nullptr; }
154
+ std::vector<WT_MapRow> rows((size_t)n);
155
+ if (WT_GetMap(h,rows.data(),(std::uint64_t)n)<0) return NativeError();
156
+ PyObject* result=PyList_New((Py_ssize_t)n);
157
+ if (!result) return nullptr;
158
+ for (Py_ssize_t i=0;i<(Py_ssize_t)n;i++) {
159
+ const auto& r=rows[(size_t)i];
160
+ PyObject* item=Py_BuildValue("(ddddddi)",r.X,r.Y,r.Z,r.VX,r.VY,r.VZ,r.Count);
161
+ if (!item) { Py_DECREF(result); return nullptr; }
162
+ PyList_SET_ITEM(result,i,item);
163
+ }
164
+ return result;
165
+ }
166
+ static PyObject* Particles(PyObject*, PyObject* args) {
167
+ PyObject* obj;
168
+ if (!PyArg_ParseTuple(args,"O", &obj)) return nullptr;
169
+ void* h=Handle(obj); if (!h) return nullptr;
170
+ std::int64_t n=WT_GetParticles(h,nullptr,0);
171
+ if (n<0) return NativeError();
172
+ if ((std::uint64_t)n > (std::uint64_t)PY_SSIZE_T_MAX) { PyErr_SetString(PyExc_OverflowError,"particle array too large"); return nullptr; }
173
+ std::vector<WT_ParticleRow> rows((size_t)n);
174
+ if (WT_GetParticles(h,rows.data(),(std::uint64_t)n)<0) return NativeError();
175
+ PyObject* result=PyList_New((Py_ssize_t)n);
176
+ if (!result) return nullptr;
177
+ for (Py_ssize_t i=0;i<(Py_ssize_t)n;i++) {
178
+ const auto& r=rows[(size_t)i];
179
+ PyObject* item=Py_BuildValue("(idddddddd)",r.ID,r.X,r.Y,r.Z,r.VX,r.VY,r.VZ,r.Density,r.Pressure);
180
+ if (!item) { Py_DECREF(result); return nullptr; }
181
+ PyList_SET_ITEM(result,i,item);
182
+ }
183
+ return result;
184
+ }
185
+ static PyObject* SetPiston(PyObject*, PyObject* args) {
186
+ PyObject* obj; double position,velocity;
187
+ if (!PyArg_ParseTuple(args,"Odd", &obj,&position,&velocity)) return nullptr;
188
+ void* h=Handle(obj); if (!h) return nullptr;
189
+ if (WT_SetPistonState(h,position,velocity)) return NativeError();
190
+ Py_RETURN_NONE;
191
+ }
192
+ static PyObject* Sinusoidal(PyObject*, PyObject* args) {
193
+ PyObject* obj;
194
+ if (!PyArg_ParseTuple(args,"O", &obj)) return nullptr;
195
+ void* h=Handle(obj); if (!h) return nullptr;
196
+ if (WT_UseSinusoidalPiston(h)) return NativeError();
197
+ Py_RETURN_NONE;
198
+ }
199
+ static PyMethodDef Methods[]={
200
+ {"create",Create,METH_VARARGS,"Create a native SPHShore simulation"},
201
+ {"close",Close,METH_VARARGS,"Destroy a native simulation"},
202
+ {"step",Step,METH_VARARGS,"Advance the solver by a batch of steps"},
203
+ {"info",Info,METH_VARARGS,"Return solver state"},
204
+ {"output_map",Map,METH_VARARGS,"Return the spatial-hash velocity map"},
205
+ {"particles",Particles,METH_VARARGS,"Return fluid particle states"},
206
+ {"set_piston",SetPiston,METH_VARARGS,"Set custom piston position/velocity"},
207
+ {"use_sinusoidal_piston",Sinusoidal,METH_VARARGS,"Re-enable sinusoidal piston"},
208
+ {nullptr,nullptr,0,nullptr}
209
+ };
210
+ static struct PyModuleDef Module={PyModuleDef_HEAD_INIT,"_core","SPHShore native C++ solver",-1,Methods};
211
+ PyMODINIT_FUNC PyInit__core(void) { return PyModule_Create(&Module); }