waltsims / k-wave-python Goto Github PK
View Code? Open in Web Editor NEWA Python interface to k-Wave GPU accelerated binaries
Home Page: https://k-wave-python.readthedocs.io/en/latest/
License: GNU General Public License v3.0
A Python interface to k-Wave GPU accelerated binaries
Home Page: https://k-wave-python.readthedocs.io/en/latest/
License: GNU General Public License v3.0
Trying to run the example but getting a type error in the uff
dependency.
Using the latest version of k-wave-python from github on Ubuntu (WSL2).
(sim) ~ python3 bmode_reconstruction_example.py
Traceback (most recent call last):
File "/home/tnie/code/sim/k-wave-python/examples/bmode_reconstruction_example.py", line 4, in <module>
from kwave.reconstruction.beamform import beamform
File "/home/tnie/code/sim/k-wave-python/kwave/reconstruction/beamform.py", line 4, in <module>
from uff import UFF, ChannelData
File "/home/tnie/miniconda3/envs/sim/lib/python3.10/site-packages/uff/__init__.py", line 48, in <module>
from uff import converters, model # noqa
File "/home/tnie/miniconda3/envs/sim/lib/python3.10/site-packages/uff/model/__init__.py", line 48, in <module>
from . import uff_pb2 as uff_pb # noqa
File "/home/tnie/miniconda3/envs/sim/lib/python3.10/site-packages/uff/model/uff_pb2.py", line 33, in <module>
_descriptor.EnumValueDescriptor(
File "/home/tnie/miniconda3/envs/sim/lib/python3.10/site-packages/google/protobuf/descriptor.py", line 755, in __new__
_message.Message._CheckCalledFromGeneratedFile()
TypeError: Descriptors cannot not be created directly.
If this call came from a _pb2.py file, your generated code is out of date and must be regenerated with protoc >= 3.19.0.
If you cannot immediately regenerate your protos, some other possible workarounds are:
1. Downgrade the protobuf package to 3.20.x or lower.
2. Set PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python (but this will use pure-Python parsing and will be much slower).
More information: https://developers.google.com/protocol-buffers/docs/news/2022-05-06#python-updates
k-Wave fails to select a device and outputs no data on my system.
Setting up the k-wave grid...
Defining the input signal...
Setting up the transducer configuration...
Fetching phantom data...
RUN_SIMULATION set to True
Running simulation locally...
Computing scan line 1 of 96
/media/thurston/home/thurston/Projects/k-wave-python/venv_debug/lib/python3.8/site-packages/kwave/kspaceFirstOrder.py:99: UserWarning:
The binary file kspaceFirstOrder-OMP could not be found in None.
To use the C++ code, the C++ binaries for your operating system must be downloaded
from www.k-wave.org/download.php and placed in the binaries folder.
warn(f'''
start time: 04-May-2022-13-11-33
Running k-Wave simulation...
start time: 04-May-2022-13-11-33
reference sound speed: 1600.7033686418115 m/s
reference sound speed: 1600.7033686418115 m/s
prepending transducer.input_signal with 17 leading zeros
appending transducer.input_signal with 17 trailing zeros
dt: 36.075ns , t_end: 57.1429us , time steps: 1585
input grid size: 216 by 108 by 108 grid points (40.0 by 20.0 by 20.0 m)
maximum supported frequency: 3.78MHz
expanding computational grid...
computational grid size: 256 by 128 by 128 grid points
precomputation completed in 3.8572562130284496 s
saving input files to disk...
completed in 0.3157105499994941 s
┌───────────────────────────────────────────────────────────────┐
│ kspaceFirstOrder-CUDA v1.3 │
├───────────────────────────────────────────────────────────────┤
│ Reading simulation configuration: Done │
│ Selected GPU device id: Failed │
└───────────────────────────────────────────────────────────────┘
┌───────────────────────────────────────────────────────────────┐
│ !!! K-Wave experienced a fatal error !!! │
├───────────────────────────────────────────────────────────────┤
│ Error: All CUDA-capable devices are busy or unavailable. │
├───────────────────────────────────────────────────────────────┤
│ Execution terminated │
└───────────────────────────────────────────────────────────────┘
Traceback (most recent call last):
File "examples/bmode_reconstruction_example.py", line 174, in <module>
sensor_data = kspaceFirstOrder3DC(**{
File "/media/thurston/home/thurston/Projects/k-wave-python/venv_debug/lib/python3.8/site-packages/kwave/kspaceFirstOrder.py", line 283, in wrapper
res = func(kgrid=kgrid, medium=medium, source=source, sensor=sensor, **args, **kwargs)
File "/media/thurston/home/thurston/Projects/k-wave-python/venv_debug/lib/python3.8/site-packages/kwave/kspaceFirstOrder3D.py", line 92, in kspaceFirstOrder3DC
sensor_data = kspaceFirstOrder3D(**kwargs)
File "/media/thurston/home/thurston/Projects/k-wave-python/venv_debug/lib/python3.8/site-packages/kwave/kspaceFirstOrder3D.py", line 412, in kspaceFirstOrder3D
sensor_data = executor.run_simulation(input_filename, output_filename, options='--p_raw')
File "/media/thurston/home/thurston/Projects/k-wave-python/venv_debug/lib/python3.8/site-packages/kwave/executor.py", line 55, in run_simulation
with h5py.File(output_filename, 'r') as hf:
File "/media/thurston/home/thurston/Projects/k-wave-python/venv_debug/lib/python3.8/site-packages/h5py/_hl/files.py", line 507, in __init__
fid = make_fid(name, mode, userblock_size, fapl, fcpl, swmr=swmr)
File "/media/thurston/home/thurston/Projects/k-wave-python/venv_debug/lib/python3.8/site-packages/h5py/_hl/files.py", line 220, in make_fid
fid = h5f.open(name, flags, fapl=fapl)
File "h5py/_objects.pyx", line 54, in h5py._objects.with_phil.wrapper
File "h5py/_objects.pyx", line 55, in h5py._objects.with_phil.wrapper
File "h5py/h5f.pyx", line 106, in h5py.h5f.open
FileNotFoundError: [Errno 2] Unable to open file (unable to open file: name = '/tmp/output.h5', errno = 2, error message = 'No such file or directory', flags = 0, o_flags = 0)
Ruff is orders of magnitude faster than alternatives and supports pyproject.toml
Hey there,
Within the standardised image reconstruction project of the international photoacoustic standardisation consortium (IPASC) we were looking for a way to use the k-wave provided time reversal algorithm for image reconstruction from Python without having to invoke MATLAB.
https://github.com/IPASC/standardised-image-reconstruction
It seems that this project might be a solution to our problem. Fantastic! Either I or someone else from the project group will take a look in the next few weeks. It would be great if we could approach you with any questions we may have.
Kind regards,
Janek
Something like this could be helpful:
import numpy as np
class Vector(np.ndarray):
def __new__(cls, x, y, z):
obj = np.array([x, y, z], dtype=float).view(cls)
obj.x = obj[0]
obj.y = obj[1]
obj.z = obj[2]
return obj
def __array_finalize__(self, obj):
if obj is None: return
self.x = getattr(obj, 'x', None)
self.y = getattr(obj, 'y', None)
self.z = getattr(obj, 'z', None)
Add GitHub actions to auto-generate documentation from the source code.
Any plans to support k-wave elastic simulations?
https://stackoverflow.com/a/58930304 Allow for so specific downloads
Hello team! I was playing with a fresh install and following the example, however I believe that this line is not correct anymore?
I don't see SimulationExecutionOptions
in kwave.options
anymore.
Related to this, I believe that the entire kwave.options
module failed to render in the documentation: https://waltersimson.com/k-wave-python/kwave.options.html
Thanks for the great work again!
Vision here is to have something like the k-Wave-example pages in Jupyter notebooks.
Add kWave binaries to the packaging so that it is not required to download them separately.
When I run the example file the first time, it fails and gives an access denied error. I tried again and it worked. Possibly related to gdown.
Setting up the k-wave grid...
Defining the input signal...
Setting up the transducer configuration...
Fetching phantom data...
Access denied with the following error:
Cannot retrieve the public link of the file. You may need to change
the permission to 'Anyone with the link', or have had many accesses.
You may still be able to access the file from the browser:
https://drive.google.com/uc?id=1ZfSdJPe8nufZHz0U9IuwHR4chaOGAWO4
The use of @dataclass
is not applied consistently throughout. For example, kSource uses @dataclass
but the attributes are declared as class attributes instead so there is no benefit for kwarg instantiation or repr. There are several other classes that use @dataclass
with no benefit. On the other hand, kWaveMedium uses @dataclass
in the standard way. It would be nice to have all the classes with MATLAB k-wave analogs to have proper implementations as dataclasses.
It would be awesome if this worked on windows!
Hi, I was trying to run the exmaple and installed the requirments yet.
After precomputation.
sensor_data = kspaceFirstOrder3DG/3DC
raise error.
'Running on Windows and Mac is not implemented yet'
The version of python is 3.9.13.
Thank you!
The number of branches keeps increasing. I suggest we update the branch policy in GitHub so that branches get deleted when respective PR is merged.
Traceback (most recent call last):
File "C:\Users\nhl08\code\k-wave-python\examples\bmode_reconstruction_example.py", line 207, in <module>
beamform(channel_data)
File "C:\Users\nhl08\code\k-wave-python\kwave\reconstruction\beamform.py", line 73, in beamform
transform = ShiftedTransform.deserialize(probe.transform.serialize())
File "C:\Users\nhl08\miniconda3\envs\kwave\lib\site-packages\uff\uff_io.py", line 58, in deserialize
assert k in fields, f'Class {cls} does not have property named {k}.'
AssertionError: Class <class 'kwave.reconstruction.shifted_transform.ShiftedTransform'> does not have property named translation.
fresh install of k-wave-python with the example dependencies.
Seems to be caused by the Serializable
mechanism in uff
. Opened an issue in uff
to discuss.
As mentioned in #11, when running k-Wave binaries, k-wave-python erroneously warns that no binaries can be found:
<directory>/lib/python3.8/site-packages/kwave/kspaceFirstOrder.py:99: UserWarning:
The binary file kspaceFirstOrder-OMP could not be found in None.
To use the C++ code, the C++ binaries for your operating system must be downloaded
from www.k-wave.org/download.php and placed in the binaries folder.
warn(f'''
This should be fixed in a patch release.
Hi Walter,
Sorry to bother you again.
I would like to implement a project that only include k-wave simulation about the transducer/sensor receive the acoustic signal from source.
BTW, is this the definition of transducer in your code is the device can transmmit signal and sensor : the device only receive signal?
When I try to save the sensor_data in a similar way as your example in your 'bmode_reconstruction_example.py'
Some error retruns about 'kSensor' object has no attribute 'combine_sensor_data'
Code info:
`
import os
from tempfile import gettempdir
from kwave.ksource import kSource
from kwave.kspaceFirstOrder2D import kspaceFirstOrder2DC
from kwave.kspaceFirstOrder2D import kspaceFirstOrder2DG
from kwave.utils.maputils import makeDisc, makeCartCircle
from kwave.utils import dotdict
from kwave.ktransducer import *
from kwave.kmedium import kWaveMedium
from copy import deepcopy
pathname = '/home/wx/hdd1/k-wave-python/examples'
Nx = 128 # number of grid points in the x (row) direction
Ny = 128 # number of grid points in the y (column) direction
dx = 0.1e-3 # grid point spacing in the x direction [m]
dy = 0.1e-3 # grid point spacing in the y direction [m]
kgrid = kWaveGrid([Nx, Ny], [dx, dy])
t_end = (Nx * dx) * 2.2 / 1500 # [s]
kgrid.makeTime(1500, t_end=t_end)
medium = kWaveMedium(sound_speed=1500, alpha_coeff=0.75, alpha_power=1.5)
disc_magnitude = 5 # [Pa]
disc_x_pos = 50 # [grid points]
disc_y_pos = 50 # [grid points]
disc_radius = 8 # [grid points]
disc_1 = disc_magnitude * makeDisc(Nx, Ny, disc_x_pos, disc_y_pos, disc_radius)
disc_magnitude = 3 # [Pa]
disc_x_pos = 80 # [grid points]
disc_y_pos = 60 # [grid points]
disc_radius = 5 # [grid points]
disc_2 = disc_magnitude * makeDisc(Nx, Ny, disc_x_pos, disc_y_pos, disc_radius)
source = kSource()
source.p0 = disc_1 + disc_2
sensor_radius = 4e-3 # [m]
num_sensor_points = 50
sensor_mask = makeCartCircle(sensor_radius, num_sensor_points)
sensor = kSensor(sensor_mask)
input_filename = f'example_input.h5'
input_file_full_path = os.path.join(pathname, input_filename)
print(input_file_full_path)
input_args = {
'SaveToDisk':input_file_full_path,
'SaveToDiskExit': False
}
sensor_data = kspaceFirstOrder2DG(**{
'medium': medium,
'kgrid': kgrid,
'source': source,
'sensor': sensor,
**input_args
})
Error info:
File "/home/wx/anaconda3/envs/py39k-wave/lib/python3.9/site-packages/kwave/kspaceFirstOrder2D.py", line 386, in kspaceFirstOrder2D
return k_sim.sensor.combine_sensor_data(sensor_data)
AttributeError: 'kSensor' object has no attribute 'combine_sensor_data'`
Thanks for you help again, and I would like to become the beta tester of windows. Thank you agagin.
Best Regards
Chenzhe Li
Shipping kWave binaries with the package results in larger package sizes. As the kWave source code is under 1MB, it might better to compile kWave from scratch during installation. However, this might expand the dependency list. We should exemine the process and see if it is feasible to do.
Following dependencies are missing from the requirements file:
uff.py
gdown
And following dependencies are not used:
flask
Hi Walter,
Thank you for your fascinating work on implying k-wave in python.
But when i want to use k-wave-python to produce some images, I found it is not esay. The examples of k-wave in matlab can't be applied directly in your project. Because there are much difference between your work and k-wave in matlab.
So I expect that your could add complete examples, not only a part. Especially, 2D photoacoustic reconstrction.
Thanks a lot!
Publish package to PyPI and update the installation guide in Readme.
Add an example that loads the BMode simulation output and displays the reconstruction of it.
If I do pip install k-wave-python
, no dependencies are installed. Must install {numpy, scipy, h5py, opencv-python, etc.} manually.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.