Skip to content
Snippets Groups Projects
Commit 90fc88f7 authored by Simon Wittl's avatar Simon Wittl
Browse files

init mirror

parent 29a00470
No related branches found
No related tags found
1 merge request!1init mirror
Showing
with 1142 additions and 90 deletions
artistlib/_version.py export-subst
__pycache__
artistlib.egg-info
dist
/venv/
/.venv/
*.tif
/workspace/
*.raw
*.stl
*.json
*.aRTist
*.ply
/build/
/examples/
\ No newline at end of file
3.10
MIT License
Copyright (c) 2022 Bundesanstalt für Materialforschung und -prüfung
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# aRTist API
# PythonLib aRTist
Python library and scripts to control the BAM X-ray simulation tool "aRTist" remotely and automatically.
Please refer to the **[documentation](https://bamresearch.github.io/aRTist-PythonLib/)** to get started.
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://mygit.th-deg.de/roboct-public/artist-api.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://mygit.th-deg.de/roboct-public/artist-api/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
For more information on aRTist see its **[website](https://www.artist.bam.de)** and its **[online guide](https://bamresearch.github.io/aRTist-handbook/)**.
[project]
name = "artist-pythonlib"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
authors = [
{ name = "swittl", email = "simon.wittl@th-deg.de" }
]
requires-python = ">=3.10"
dependencies = [
"matplotlib>=3.9.2",
"numpy>=2.1.3",
"pillow>=11.0.0",
"scipy>=1.14.1",
"thd-json>=0.1.0",
"xraydb>=4.5.4",
]
[project.optional-dependencies]
thd = [
"thd-json",
]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[tool.uv.sources]
thd-json = { git = "https://mygit.th-deg.de/roboct-public/roboct-schemas" }
# -*- coding: UTF-8 -*-
"""The aRTist Python library is intended to remote control and automate the radiographic simulator aRTist.
.. include:: ./documentation.md
"""
from .remote_connection import Junction
from .api import API
from .common_types import SAVEMODES, SOURCETYPES, PROJECTIONGEOMETRIES
__all__ = ["SAVEMODES", "SOURCETYPES", "PROJECTIONGEOMETRIES", "Junction", "API"]
# Copyright 2023 Simon Wittl (Deggendorf Institute of Technology)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
import numpy as np
from scipy.spatial.transform import Rotation
from pathlib import Path
import json
from artist_pythonlib.geometries import projection_geometry, thd_projection_geometry
from artist_pythonlib.common_types import PROJECTIONGEOMETRIES, SAVEMODES
from artist_pythonlib.remote_connection import Junction, _rc
class API:
def __init__(self, remote_control: Junction = None) -> None:
if remote_control is None:
remote_control = _rc
self.rc = remote_control
@staticmethod
def path_to_artist(path: Path) -> str:
return str(path.absolute()).replace("\\", "\\\\")
def get_image(self) -> np.ndarray:
"""Make a projection of the current scene.
Returns:
np.ndarray: projection as ndarray.
"""
self.rc.send("set imgList [Engine::Go]")
self.rc.send("RemoteControl::SendImage [lindex $imgList 0]")
return self.rc.get_image()
def save_image(
self,
save_path: Path,
save_mode: SAVEMODES = SAVEMODES.UINT16,
save_projection_geometry: PROJECTIONGEOMETRIES = PROJECTIONGEOMETRIES.NONE,
):
"""Save the current scene as projection. The projection geometry can be stored in a .json file.
Args:
save_path (Path): Save path of the Projection
save_mode (SAVEMODES, optional): File type of saved projection. Defaults to SAVEMODES.UINT16.
save_projection_geometry (bool, optional): Projection geometry of the scene. Stem of save_path is used as path. Defaults to True.
"""
save_path = save_path.resolve()
if save_projection_geometry > 0:
if save_projection_geometry == PROJECTIONGEOMETRIES.THD:
geom = self.projection_geometry(save_projection_geometry)
name = f'{geom["image"]["image_path"][:-4]}_{save_path.stem}'
save_path = save_path.parent / f"{name}.tif"
save_path_json = save_path.parent / f"{name}.json"
geom['image']['image_path'] = save_path.name
else:
save_path_json = save_path.parent / f"{save_path.stem}.json"
with open(str(save_path_json), "w") as f:
json.dump(geom, f, indent=4)
if save_mode == SAVEMODES.UINT8:
self._save_image_uint8(save_path)
elif save_mode == SAVEMODES.UINT16:
self._save_image_uint16(save_path)
elif save_mode == SAVEMODES.FLOAT_TIFF:
self._save_image_float_tiff(save_path)
elif save_mode == SAVEMODES.FLOAT_RAW:
self._save_image_float_raw(save_path)
elif save_mode == SAVEMODES.PNG:
self._save_image_png(save_path)
def _save_image_uint16(self, save_path: Path):
"""Saves the current scene as projection (.tif) and geometry (.json).
Args:
save_path (Path): Save path of the projection.
"""
# self.rc.send('set imgList [Engine::Go]')
save_path_projection = str(save_path.absolute()).replace("\\", "\\\\")
self.rc.send(
f'set imgList [Engine::Go]; Image::SaveFloatTIFF [lindex $imgList 0] {save_path_projection} True; {r"foreach i $imgList {$i Delete}"}'
)
def _save_image_uint8(self, save_path: Path):
"""Saves the current scene as projection (.tif) and geometry (.json).
Args:
save_path (Path): Save path of the projection.
"""
# self.rc.send('set imgList [Engine::Go]')
save_path_projection = str(save_path.absolute()).replace("\\", "\\\\")
save_path_json = (
save_path.parent / (save_path.stem + ".json")
) # Image::SaveFile [lindex $imgList 0] [file join $env(HOME) Pictures/artistlib2.tif] true',
self.rc.send(
f'set imgList [Engine::Go]; Image::SaveFloatTIFF [lindex $imgList 0] {save_path_projection} True; {r"foreach i $imgList {$i Delete}"}'
)
with open(str(save_path_json), "w") as f:
json.dump(self.projection_geometry(), f, indent=4)
def _save_image_float_tiff(self, save_path: Path):
"""Saves the current scene as projection (.tiff) and geometry (.json).
Args:
save_path (Path): Save path of the projection.
"""
# self.rc.send('set imgList [Engine::Go]')
save_path_projection = str(save_path.absolute()).replace("\\", "\\\\")
self.rc.send(
f'set imgList [Engine::Go]; Image::SaveFloatTIFF [lindex $imgList 0] {save_path_projection} True; {r"foreach i $imgList {$i Delete}"}'
)
# self.rc.send('foreach i $imgList {$i Delete}')
def _save_image_float_raw(self, save_path: Path):
"""Saves the current scene as projection (.raw) and geometry (.json).
Args:
save_path (Path): Save path of the projection.
"""
# self.rc.send('set imgList [Engine::Go]')
save_path_projection = str(save_path.absolute()).replace("\\", "\\\\")
save_path_json = (
save_path.parent / (save_path.stem + ".json")
) # Image::SaveFile [lindex $imgList 0] [file join $env(HOME) Pictures/artistlib2.tif] true',
self.rc.send(
f'set imgList [Engine::Go]; Image::SaveFloatTIFF [lindex $imgList 0] {save_path_projection} True; {r"foreach i $imgList {$i Delete}"}'
)
with open(str(save_path_json), "w") as f:
json.dump(self.projection_geometry(), f, indent=4)
def _save_image_png(self, save_path: Path):
"""Saves the current scene as projection (.png) and geometry (.json).
Args:
save_path (Path): Save path of the projection.
"""
# self.rc.send('set imgList [Engine::Go]')
save_path_projection = str(save_path.absolute()).replace("\\", "\\\\")
self.rc.send(
f'set imgList [Engine::Go]; Image::SaveFloatTIFF [lindex $imgList 0] {save_path_projection} True; {r"foreach i $imgList {$i Delete}"}'
)
def translate(
self, id: int | str, x: float = 0.0, y: float = 0.0, z: float = 0.0
) -> None:
"""Moves an object to an absolute position. All values in [mm].
Args:
id (int | str): ID of the Object.
x (float, optional): Absolute X position. Defaults to 0.0.
y (float, optional): Absolute Y position. Defaults to 0.0.
z (float, optional): Absolute Z position. Defaults to 0.0.
"""
self.rc.send(
f"::PartList::Invoke {str(id)} SetPosition {str(x)} {str(y)} {str(z)};"
)
self.rc.send(
f"::PartList::Invoke {str(id)} SetRefPos {str(x)} {str(y)} {str(z)};"
)
def scale(self, id: int | str, x: float = 1.0) -> None:
"""Moves an object to an absolute position. All values in [mm].
Args:
id (int | str): ID of the Object.
x (float, optional): Absolute X position. Defaults to 0.0.
y (float, optional): Absolute Y position. Defaults to 0.0.
z (float, optional): Absolute Z position. Defaults to 0.0.
"""
self.rc.send(
f"::PartList::Invoke {str(id)} SetScale {str(x)} {str(x)} {str(x)};"
)
def rotate(
self, id: int | str, alpha: float = 0.0, beta: float = 0.0, gamma: float = 0.0
) -> None:
"""Rotates an object to an absolute position. All values in [°].
Args:
id (int | str): _description_
alpha (float, optional): Absolute alpha rotation. Defaults to 0.0.
beta (float, optional): Absolute beta rotation. Defaults to 0.0.
gamma (float, optional): Absolute gamma rotation. Defaults to 0.0.
"""
position = self.get_position(id)
self.rc.send(
f"::PartList::Invoke {str(id)} SetRefPos {str(position[0])} {str(position[1])} {str(position[2])};"
)
self.rc.send(
f"::PartList::Invoke {str(id)} SetOrientation {str(alpha)} {str(beta)} {str(gamma)};"
)
def rotate_from_rotation_matrix(
self, id: int | str, rotation_matrix: np.ndarray
) -> None:
"""Rotates an object to an absolute position.
Args:
id (int | str): ID of the Object.
rotation_matrix (np.ndarray): Rotation matrix in world coordinate system.
"""
rotation = Rotation.from_matrix(rotation_matrix)
euler_scipy = rotation.as_euler("ZXY", degrees=True)
euler_scipy = [euler_scipy[1], euler_scipy[2], euler_scipy[0]]
self.rotate(id, *euler_scipy)
def rotate_from_quat(self, id: int | str, qaurternion: np.ndarray) -> None:
"""Rotates an object to an absolute position.
Args:
id (int | str): ID of the Object.
qaurternion (np.ndarray): Quarternion in world coordinate system.
"""
self.rotate_from_rotation_matrix(
id, Rotation.from_quat(qaurternion).as_matrix()
)
def get_position(self, id: int | str) -> np.ndarray:
"""Returns the current position of the object in [mm].
Args:
id (int | str): ID of the Object.
Returns:
np.ndarray: position (x,y,z) in [mm].
"""
result = self.rc.send(f"[::PartList::Get {id} Obj] GetPosition")
return np.float32(result[1:-1].split(" "))
def get_euler_angles(self, id: int | str) -> np.ndarray:
"""Returns the current orientation of the object as euler angles in the ZXY convention.
Args:
id (int | str): ID of the Object.
Returns:
np.ndarray: Euler angle in ZXY convention.
"""
result = self.rc.send(f"[::PartList::Get {id} Obj] GetOrientation")
return np.float32(result[1:-1].split(" "))
def get_rotation_matrix(self, id: int | str) -> np.ndarray:
euler_angles = self.get_euler_angles(id)
R_x = Rotation.from_euler("x", euler_angles[0], degrees=True).as_matrix()
R_y = Rotation.from_euler("y", euler_angles[1], degrees=True).as_matrix()
R_z = Rotation.from_euler("z", euler_angles[2], degrees=True).as_matrix()
# rotation = Rotation.from_euler('zxy', -euler_angles, degrees=True).as_matrix()
rotation = R_z
rotation: np.ndarray = rotation.dot(R_x)
rotation = rotation.dot(R_y)
# rotation = R_y
# rotation = rotation.dot(R_x)
# rotation = rotation.dot(R_z)
return rotation
def get_orientation(self, id) -> np.ndarray:
"""Return the current orientation of the object as quaternion.
Args:
id (int | str): ID of the Object.
Returns:
np.ndarray: Quaternion of the object in the world coordinate system.
"""
rotation = Rotation.from_matrix(self.get_rotation_matrix(id))
return rotation.as_quat()
def projection_geometry(
self, mode: PROJECTIONGEOMETRIES = PROJECTIONGEOMETRIES.THD
) -> dict:
"""Returns the current projection geometry of the scene. All positions are in [mm].
Returns:
dict: Dictionary of the projection geometry. Keys are: 'focal_spot_position_mm',
'focal_spot_orientation_matrix', 'detector_center_position_mm',
'detector_center_orientation_matrix', 'detector_center_orientation_quat',
'detector_count_px' and 'detector_resolution_mm'
"""
if mode == PROJECTIONGEOMETRIES.STANDARD:
return projection_geometry(self)
elif mode == PROJECTIONGEOMETRIES.THD:
return thd_projection_geometry(self)
def get_detector_resolution(self) -> np.ndarray:
"""Returns the current pixel pitch of the detector as array
Returns:
np.ndarray: Pixel pitch of the detector (u, v).
"""
result = self.rc.send("::XDetector::GetResolution")
return np.array(np.float32(result.split(" ")))
def get_detector_pixel_count(self) -> np.ndarray:
"""Returns the current pixel count of the detector.
Returns:
np.ndarray: Pixel count (u, v).
"""
result = self.rc.send("::XDetector::GetPixelSize")
return np.array(np.int32(result.split(" ")))
def set_material(self, id: int | str, material: str):
"""Changes the material of the object.
Args:
id (int | str): ID of the Object.
material (str): Matiral as string. !!!Must be in the material database of artist!!!
"""
self.rc.send(f"::PartList::SetMaterial {material} {id}")
def get_material(self, id: int | str):
"""Returns the material of the object.
Args:
id (int | str): ID of the Object.
"""
return_value = self.rc.send(f"::PartList::Get {id} Material")
return return_value
def load_part(
self, load_path: Path, material: str = "Al", name: str = "Object"
) -> int:
"""Loads a mesh file into the artist scene. Returns the object id for further mainpulations.
Args:
load_path (Path): Path object pointing to the mesh file.
material (str, optional): Material of the mesh file. Defaults to 'Al'.
name (str, optional): Displayed name in the aRTist GUI. Defaults to 'Object'.
Returns:
int: Object ID for further Manipulations.
"""
return_value = self.rc.send(
f'set obj [::PartList::LoadPart "{self.path_to_artist(load_path)}" "{material}" "{name}"]'
)
return int(return_value)
def delete_part(self, id: int | str):
"""Delets the object from the scene.
Args:
id (int | str): ID of the Object.
"""
self.rc.send(f'::PartList::Delete "{id}"')
def set_visibility(self, id: int | str, visible: bool = True):
"""Sets the Object in/visiible.
Args:
id (int | str): ID of the Object.
visible (bool, optional): Visible: True. Defaults to True.
"""
visible = "on" if visible else "off"
self.rc.send(f'[::PartList::Get {id} Obj] SetVisibility "{visible}"')
def clear_scene(self):
"""Clears all objects from the scene."""
self.rc.send("::PartList::Clear")
def load_project(self, project_file: Path):
if project_file.suffix != ".aRTist":
raise ValueError(
"Wrong File / Path. The *project_file* path must be a .aRTist File!"
)
self.rc.send(
f'::XRayProject::LoadProject "{self.path_to_artist(project_file)}"'
)
\ No newline at end of file
# Copyright 2023 Simon Wittl (Deggendorf Institute of Technology)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from enum import IntEnum
class SOURCETYPES(IntEnum):
MONOCHROMATIC = 0
GENERAL = 1
class SAVEMODES(IntEnum):
UINT8 = 0
UINT16 = 1
FLOAT_TIFF = 2
FLOAT_RAW = 3
PNG = 4
class PROJECTIONGEOMETRIES(IntEnum):
NONE = 0
STANDARD = 1
THD = 2
from .standard_format import projection_geometry
from .thd_format import thd_projection_geometry
__all__ = ["projection_geometry", "thd_projection_geometry"]
from __future__ import annotations
import numpy as np
from scipy.spatial.transform import Rotation
def projection_geometry(api) -> dict:
"""Returns the current projection geometry of the scene. All positions are in [mm].
Returns:
dict: Dictionary of the projection geometry. Keys are: 'focal_spot_position_mm',
'focal_spot_orientation_matrix', 'detector_center_position_mm',
'detector_center_orientation_matrix', 'detector_center_orientation_quat',
'detector_count_px' and 'detector_resolution_mm'
"""
source_position = np.array(api.get_position("S"))
source_orientation = np.array(api.get_rotation_matrix("S"))
detector_position = np.array(api.get_position("D"))
detector_orientation = np.array(api.get_rotation_matrix("D"))
detector_resolution = api.get_detector_resolution()
detector_pixel_count = api.get_detector_pixel_count()
data_dict = dict()
data_dict["focal_spot_position_mm"] = source_position.tolist()
data_dict["focal_spot_orientation_quat"] = (
Rotation.from_matrix(source_orientation).as_quat().tolist()
)
data_dict["detector_center_position_mm"] = detector_position.tolist()
data_dict["detector_center_orientation_quat"] = (
Rotation.from_matrix(detector_orientation).as_quat().tolist()
)
data_dict["image_width_px"] = detector_pixel_count.tolist()[0]
data_dict["pixel_pitch_width_mm"] = detector_resolution.tolist()[0]
data_dict["image_height_px"] = detector_pixel_count.tolist()[1]
data_dict["pixel_pitch_height_mm"] = detector_resolution.tolist()[1]
return data_dict
import numpy as np
from scipy.spatial.transform import Rotation
try:
from thd_json.header import generate_header
from thd_json.projection import get_projection_dict
except ModuleNotFoundError:
from warnings import warn
warn(
"The optional modules of `thd` is not installed. THD Json geometry is not available."
)
def thd_projection_geometry(api) -> dict:
"""Returns the current projection geometry of the scene. All positions are in [mm].
Returns:
dict: Dictionary of the projection geometry. Keys are: 'focal_spot_position_mm',
'focal_spot_orientation_matrix', 'detector_center_position_mm',
'detector_center_orientation_matrix', 'detector_center_orientation_quat',
'detector_count_px' and 'detector_resolution_mm'
"""
source_position = np.array(api.get_position("S"))
source_orientation = np.array(api.get_rotation_matrix("S"))
detector_position = np.array(api.get_position("D"))
detector_orientation = np.array(api.get_rotation_matrix("D"))
detector_resolution = api.get_detector_resolution()
detector_pixel_count = api.get_detector_pixel_count()
json_header = generate_header()
image_path = f"{json_header.uuid}.tif"
data_dict = get_projection_dict(
image_path,
source_position,
detector_position,
Rotation.from_matrix(detector_orientation).as_quat(),
np.asarray(detector_pixel_count),
np.asarray(detector_resolution),
json_header,
Rotation.from_matrix(source_orientation).as_quat())
return data_dict
# Copyright 2023 Simon Wittl (Deggendorf Institute of Technology)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from .xray_source import XraySource
from .xray_detector import XrayDetector
__all__ = ["XraySource", "XrayDetector"]
# Copyright 2023 Simon Wittl (Deggendorf Institute of Technology)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
from ..remote_connection import Junction, _rc
from ..api import API
class BaseHardware:
def __init__(self, remote_control: Junction | API = None) -> None:
if isinstance(remote_control, Junction):
self.rc = remote_control
elif isinstance(remote_control, API):
self.rc = remote_control.rc
elif remote_control is None:
self.rc = _rc
else:
raise ValueError("Wrong remote_control argument?")
# Copyright 2023 Simon Wittl (Deggendorf Institute of Technology)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
from artist_pythonlib.api import API
from artist_pythonlib.remote_connection import Junction
from .base_hardware import BaseHardware
import numpy as np
class XrayDetector(BaseHardware):
def __init__(self, remote_control: Junction | API = None) -> None:
"""XRay detector object. Needs a remote control connection.
Args:
remote_control (Junction | API, optional): Remote control connection for the communication with artist. Defaults to None.
"""
super().__init__(remote_control)
@property
def detector_resolution_mm(self) -> np.ndarray:
"""Current detector resolution / pixel pitch in [mm].
Returns:
np.ndarray: Detector resolution (u, v) in [mm].
"""
return_value = self.rc.send("::XDetector::GetResolution")
return_value = np.array(np.float32(return_value.split(" ")))
return return_value
@detector_resolution_mm.setter
def detector_resolution_mm(self, detector_resolution_mm: np.ndarray) -> None:
self.rc.send(f"set ::Xsetup_private(DGdx) {detector_resolution_mm[0]}")
self.rc.send(f"set ::Xsetup_private(DGdy) {detector_resolution_mm[1]}")
@property
def detector_count_px(self) -> np.ndarray:
"""Current detector pixel count.
Returns:
np.ndarray: Detector pixel count (u, v) in [n].
"""
return_value = self.rc.send("::XDetector::GetPixelSize")
return_value = np.array(np.int32(return_value.split(" ")))
return return_value
@detector_count_px.setter
def detector_count_px(self, detector_count_px: np.ndarray) -> None:
self.rc.send(f"set ::Xsetup(DetectorPixelX) {detector_count_px[0]}")
self.rc.send(f"set ::Xsetup(DetectorPixelY) {detector_count_px[1]}")
@property
def flatfield_correction(self) -> bool:
"""Faltfiled corrected?
Returns:
bool: Return wheter the projection is flatfield corrected or not.
"""
return_value = self.rc.send("array get Xdetector FFCorrRun")
return_value = return_value.split(" ")[1]
return bool(return_value)
# Copyright 2023 Simon Wittl (Deggendorf Institute of Technology)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
from artist_pythonlib.api import API
from artist_pythonlib.remote_connection import Junction
from .base_hardware import BaseHardware
from ..common_types import SOURCETYPES
class XraySource(BaseHardware):
def __init__(self, remote_control: Junction | API = None) -> None:
"""Xray source objet. Needs a remote control connection.
Args:
remote_control (Junction | API, optional): remote connection to communicate with aRTist. Defaults to None.
"""
super().__init__(remote_control)
@property
def voltage_kv(self) -> float:
"""Current voltage setting of the XRay source.
Returns:
float: Voltage value in [kV].
"""
return_value = self.rc.send("array get Xsource Voltage")
return_value = return_value.split(" ")[1]
return float(return_value)
@voltage_kv.setter
def voltage_kv(self, voltage_kv: float) -> None:
self.rc.send(f"set ::Xsource(Voltage) {voltage_kv}")
self.rc.send("::XSource::ComputeSpectrum")
@property
def exposure_ma(self) -> float:
"""Current set exposure of the XRay source
Returns:
float: Exposure in [µA].
"""
return_value = self.rc.send("array get Xsource Exposure")
return_value = return_value.split(" ")[1]
return float(return_value)
@exposure_ma.setter
def exposure_ma(self, exposure_ma: float) -> None:
self.rc.send(f"set ::Xsource(Exposure) {exposure_ma}")
@property
def filter_material(self) -> str:
"""Filter Material of the XRay source.
Returns:
str: Filter material of the XRay source.
"""
return_value = self.rc.send("array get Xsource FilterMaterial")
return_value = return_value.split(" ")[1]
return str(return_value)
@filter_material.setter
def filter_material(self, filter_material: float) -> None:
self.rc.send(f"set ::Xsource(FilterMaterial) {filter_material}")
self.rc.send("::XSource::ComputeSpectrum")
@property
def filter_thickness_mm(self) -> float:
"""Thickness of the filter in [mm].
Returns:
float: Filter thickness in [mm].
"""
return_value = self.rc.send("array get Xsource FilterThickness")
return_value = return_value.split(" ")[1]
return float(return_value)
@filter_thickness_mm.setter
def filter_thickness_mm(self, filter_thickness_mm: float) -> None:
self.rc.send(f"set ::Xsource(FilterThickness) {filter_thickness_mm}")
self.rc.send("::XSource::ComputeSpectrum")
@property
def source_type(self) -> int:
"""Source type of the XRay source. Types are Monocromatic or General. See SOURCETYPES.
Returns:
int: Source type as integer. Use SOURCETYPES.
"""
return_value = self.rc.send("array get Xsource Tube")
return_value = return_value.split(" ")[1]
if str(return_value).startswith("Mono"):
return SOURCETYPES.MONOCHROMATIC
elif str(return_value).startswith("General"):
return SOURCETYPES.GENERAL
@source_type.setter
def source_type(self, source_type: SOURCETYPES) -> None:
if source_type == SOURCETYPES.MONOCHROMATIC:
self.rc.send("set ::Xsource(Tube) Mono")
elif source_type == SOURCETYPES.GENERAL:
self.rc.send("set ::Xsource(Tube) General")
self.rc.send("::XSource::ComputeSpectrum")
# Copyright 2023 Simon Wittl (Deggendorf Institute of Technology)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import socket
import base64
import pathlib
from PIL import Image
class Junction:
"""Remote control of aRTist simulator (this is a test)"""
def __init__(self, host="localhost", port=3658, bufferSize=1024, timeout=10):
self.host = host
self.port = port
self.bufferSize = bufferSize
self.timeout = timeout
self.error = 0
self.progress = 0
self.answer = {}
self.connect()
def connect(self):
try:
self.S = socket.socket() # Create socket (for TCP)
self.S.connect((self.host, self.port)) # Connect to aRTist
self.S.settimeout(self.timeout)
self.S.setblocking(True)
self.listen(0)
except ConnectionRefusedError:
print(
"The Connection to aRTist was refused. Is aRTist running and the remote connection enabled?"
)
except Exception as e:
raise e
return self
def send(self, command, msgType="RESULT"):
c = command + "\n"
self.S.send(c.encode())
return self.listen(msgType=msgType)
def listen(self, command_no=1, msgType="RESULT"):
answer = ""
stop = False
if command_no == 0:
self.S.settimeout(0.2)
while not stop: # and ("SUCCESS" not in total) and ("ERROR" not in total): # Solange server antwortet und nicht "SUCCESS" enthält
try:
msg = self.S.recv(self.bufferSize).decode()
except BaseException as e:
err = e.args[0]
if err == "timed out":
# print("Timeout\n")
answer += "RESULT Timeout\n"
# print(answer)
stop = True
continue
else:
if "SUCCESS" in msg:
answer += msg
stop = True
continue
elif "ERROR" in msg:
answer += msg
stop = True
# global error
self.error = self.error + 1
continue
elif "PROGRESS" in msg:
try:
self.progress = float(msg.strip("PROGRESS "))
except ValueError:
self.progress = 0
continue
else:
if command_no == 0:
print(msg)
answer += msg
self.S.settimeout(self.timeout)
self.answer.update(
{
"SUCCESS": self.pick(answer, "SUCCESS"),
"RESULT": self.pick(answer, "RESULT"),
"SDTOUT": self.pick(answer, "STDOUT"),
"BASE64": self.pick(answer, "BASE64"),
"IMAGE": self.pick(answer, "IMAGE"),
"FILE": self.pick(answer, "FILE"),
}
)
if msgType != "*":
answer = self.pick(answer, msgType)
return answer
def pick(self, answer, res="RESULT"):
picked = ""
for a in answer.split("\n"):
if a.find(res) == 0:
picked += a[1 + len(res) :].strip("\r") + "\n"
if len(picked) == 0:
return res + " not found."
return picked
def get_answer(self, key):
return self.answer[key]
def save_image(self, imageName: str):
imageData = self.answer["BASE64"]
decodedData = base64.b64decode((imageData))
imageHeader = self.answer["IMAGE"].split()
im = np.frombuffer(decodedData, np.double).reshape(
(int(imageHeader[1]), int(imageHeader[2]))
)
Image.fromarray(im).save(imageName)
def receive_file(self, fileName):
fileData = self.answer["BASE64"]
decodedFile = base64.b64decode((fileData))
artistFile = open(fileName, "wb")
artistFile.write(decodedFile)
artistFile.close()
def send_file(self, fileName):
outFile = open(fileName, "br")
fileBytes = outFile.read()
encBytes = base64.b64encode((fileBytes))
encString = str(encBytes)
encString = encString.lstrip("b'").rstrip("'")
fileExtension = pathlib.Path(fileName).suffix
com = "::RemoteControl::ReceiveFile " + encString + " " + fileExtension
recAnswer = self.send(com, "RESULT")
return recAnswer
def get_image(self) -> np.ndarray:
imageData = self.answer["BASE64"]
decodedData = base64.b64decode((imageData))
imageHeader = self.answer["IMAGE"].split()
dtype = np.double
return np.frombuffer(decodedData, dtype).reshape(
(int(imageHeader[1]), int(imageHeader[2]))
)
_rc = Junction()
# Copyright 2023 Simon Wittl (Deggendorf Institute of Technology)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from .ct_trajectories import (
circular_trajectory,
look_at_orientation,
sphere_trajectory,
arbitary_circular_trajectory,
)
__all__ = [
"circular_trajectory",
"look_at_orientation",
"sphere_trajectory",
"arbitary_circular_trajectory",
]
# Copyright 2023 Simon Wittl (Deggendorf Institute of Technology)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
import numpy as np
from scipy.spatial.transform import Rotation
def circular_trajectory(
fod_mm: float, fdd_mm: float, number_of_projections: int, opening_angle: float = 0.2
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
if fod_mm > fdd_mm:
raise ValueError("fod > fdd.")
rotation_angles = np.linspace(
0.0, np.pi * (1.0 + opening_angle), number_of_projections, endpoint=False
)
rotation_object = Rotation.from_euler("Y", rotation_angles, degrees=False)
source_initial_position = np.array([0.0, 0.0, fod_mm])
detector_initial_position = np.array([0.0, 0.0, fod_mm - fdd_mm])
source_positions = rotation_object.apply(source_initial_position)
detector_positions = rotation_object.apply(detector_initial_position)
return source_positions, detector_positions, rotation_object.as_matrix()
def look_at_orientation(
source, detector, up_vector: np.ndarray = np.array([0.0, 0.0, 1.0])
):
normal = source - detector
normal = normal / np.linalg.norm(normal)
up_axis = int(np.argmax(up_vector))
line = np.cross(normal, up_vector)
col = np.cross(line, normal)
if np.sign(col[up_axis]) != np.sign(up_vector[up_axis]):
col *= -1.0
line = np.cross(normal, col)
rotation_matrix = np.eye(3)
rotation_matrix[:, 0] = line
rotation_matrix[:, 1] = col
rotation_matrix[:, 2] = normal
if np.linalg.det(rotation_matrix) < 0.0:
rotation_matrix[:, np.argmax(up_vector)] *= -1.0
return rotation_matrix
def sphere_trajectory(
fod_mm: float, fdd_mm: float, number_of_projections: int
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
phi = (1.0 + np.sqrt(5.0)) / 2.0
start = -(number_of_projections - 1.0)
end = number_of_projections - 1.0
i = np.linspace(start, end, number_of_projections)
theta = np.divide(2.0 * i * np.pi, phi)
sphi = i / number_of_projections
cphi = (
np.sqrt((number_of_projections + i) * (number_of_projections - i))
/ number_of_projections
)
point_array = np.zeros((number_of_projections, 3))
point_array[:, 0] = cphi * np.cos(theta)
point_array[:, 1] = cphi * np.sin(theta)
point_array[:, 2] = sphi
source_positions = point_array * fod_mm
detector_positions = point_array * (fod_mm - fdd_mm)
orientation = np.array(
list(map(look_at_orientation, source_positions, detector_positions))
)
return source_positions, detector_positions, orientation
def arbitary_circular_trajectory(
fod_mm: float,
fdd_mm: float,
number_of_projections: int,
transformation: np.ndarray = np.eye(4),
opening_angle: float = 0.2,
):
source_positions, detector_positions, orientation = circular_trajectory(
fod_mm, fdd_mm, number_of_projections, opening_angle
)
source_transformation_matrix = np.zeros((number_of_projections, 4, 4))
source_transformation_matrix[:, 3, 3] = 1.0
detector_transformation_matrix = source_transformation_matrix.copy()
source_transformation_matrix[:, :3, 3] = source_positions
detector_transformation_matrix[:, :3, 3] = detector_positions
source_transformation_matrix[:, :3, :3] = orientation
detector_transformation_matrix[:, :3, :3] = orientation
transformation = np.expand_dims(transformation, 0)
source_transformation_matrix = transformation @ source_transformation_matrix
detector_transformation_matrix = transformation @ detector_transformation_matrix
return (
source_transformation_matrix[:, :3, 3].reshape((number_of_projections, 3)),
detector_transformation_matrix[:, :3, 3].reshape((number_of_projections, 3)),
detector_transformation_matrix[:, :3, :3].reshape(
(number_of_projections, 3, 3)
),
)
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment