Skip to content

Commit

Permalink
updated Path
Browse files Browse the repository at this point in the history
  • Loading branch information
alexlib committed Mar 6, 2024
1 parent ae1a2f6 commit d4ed11e
Show file tree
Hide file tree
Showing 29 changed files with 367 additions and 778 deletions.
18 changes: 8 additions & 10 deletions openptv_python/calibration.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Calibration data structures and functions."""

import copy
import pathlib
from pathlib import Path
from typing import Optional

import numpy as np
Expand Down Expand Up @@ -127,7 +127,7 @@ def __init__(self,


@classmethod
def from_file(cls, ori_file: str, add_file: str | None):
def from_file(cls, ori_file: Path, add_file: Path | None):
"""
Read exterior and interior orientation, and if available, parameters for distortion corrections.
Expand All @@ -141,7 +141,7 @@ def from_file(cls, ori_file: str, add_file: str | None):
-------
- ext_par, int_par, glass, addp: Calibration object parts without multimedia lookup table.
"""
if not pathlib.Path(ori_file).exists():
if not ori_file.exists():
raise IOError(f"File {ori_file} does not exist")

ret = cls()
Expand All @@ -166,6 +166,8 @@ def from_file(cls, ori_file: str, add_file: str | None):
# this is anyhow default
# self.mmlut.data = None # no multimedia data yet

ret.added_par = np.array([0,0,0,0,0,1,0], dtype=np.float64)

# Additional parameters
if add_file is not None:
with open(add_file, "r", encoding="utf-8") as fp:
Expand All @@ -179,10 +181,6 @@ def from_file(cls, ori_file: str, add_file: str | None):
else:
# print("no addpar fallback used") # Waits for proper logging.
print("No addpar file found. Using default values for radial distortion")
# ret.added_par.k1 = ret.added_par.k2 = ret.added_par.k3 \
# = ret.added_par.p1 = ret.added_par.p2 = ret.added_par.she = 0.0
# ret.added_par.scx = 1.0
ret.added_par = np.array([0,0,0,0,0,1,0], dtype=np.float64)

return ret
# print(f"Calibration data read from files {ori_file} and {add_file}")
Expand Down Expand Up @@ -395,7 +393,7 @@ def write_ori(
ext_par: np.recarray,
int_par: np.recarray,
glass: np.ndarray,
added_par: np.recarray,
added_par: np.ndarray,
filename: str,
add_file: Optional[str],
) -> bool:
Expand Down Expand Up @@ -424,7 +422,7 @@ def write_ori(
return success


def read_ori(ori_file: str, add_file: str) -> Calibration:
def read_ori(ori_file: Path, add_file: Path) -> Calibration:
"""
Read exterior and interior orientation, and if available, parameters for distortion corrections.
Expand Down Expand Up @@ -495,7 +493,7 @@ def compare_addpar(a1, a2):
return np.array_equal(a1, a2)


def read_calibration(ori_file: str, addpar_file: str) -> Calibration:
def read_calibration(ori_file: Path, addpar_file: Path | None) -> Calibration:
"""Read the orientation file including the added parameters."""
return Calibration().from_file(ori_file, addpar_file)

Expand Down
39 changes: 19 additions & 20 deletions openptv_python/parameters.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""Parameters for OpenPTV-Python."""
import os
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import List, Tuple
Expand Down Expand Up @@ -146,9 +145,9 @@ def get_last(self):
return self.last

@classmethod
def from_file(cls, filename: str, num_cams: int):
def from_file(cls, filename: Path, num_cams: int):
"""Read sequence parameters from file."""
if not Path(filename).exists():
if not filename.exists():
raise IOError("File {filename} does not exist.")

ret = cls()
Expand All @@ -162,7 +161,7 @@ def from_file(cls, filename: str, num_cams: int):
return ret


def read_sequence_par(filename: str, num_cams: int = TR_MAX_CAMS) -> SequencePar:
def read_sequence_par(filename: Path, num_cams: int = TR_MAX_CAMS) -> SequencePar:
"""Read sequence parameters from file and return SequencePar object."""
return SequencePar().from_file(filename, num_cams)

Expand Down Expand Up @@ -213,7 +212,7 @@ class TrackPar(Parameters):
# }

@classmethod
def from_file(cls, filename: str):
def from_file(cls, filename: Path):
"""Read tracking parameters from file and return TrackPar object.
Note that the structure has 13 attributes, from which we read only 9
Expand Down Expand Up @@ -306,7 +305,7 @@ def get_dny(self):
return self.dny


def read_track_par(filename: str) -> TrackPar:
def read_track_par(filename: Path) -> TrackPar:
"""Read tracking parameters from file and return TrackPar object."""
return TrackPar().from_file(filename)

Expand Down Expand Up @@ -377,7 +376,7 @@ def set_corrmin(self, corrmin: float):
self.corrmin = corrmin

@classmethod
def from_file(cls, filename: str):
def from_file(cls, filename: Path):
"""Read volume parameters from file.
Args:
Expand All @@ -401,7 +400,7 @@ def from_file(cls, filename: str):
return cls(x_lay, z_min_lay, z_max_lay, cn, cnx, cny, csumg, eps0, corrmin)


def read_volume_par(filename: str) -> VolumePar:
def read_volume_par(filename: Path) -> VolumePar:
"""Read volume parameters from file and returns volume_par object.
Args:
Expand Down Expand Up @@ -497,10 +496,10 @@ def get_tiff_flag(self):
return self.tiff_flag

@classmethod
def from_file(cls, filename: str):
def from_file(cls, filename: Path):
"""Read control parameters from file and return ControlPar object."""
ret = cls()
if not os.path.isfile(filename):
if not filename.exists():
raise FileNotFoundError(f"Could not open file {filename}")

with open(filename, "r", encoding="utf-8") as par_file:
Expand Down Expand Up @@ -546,7 +545,7 @@ def to_dict(cls, data):
return control_par_dict


def read_control_par(filename: str) -> ControlPar:
def read_control_par(filename: Path) -> ControlPar:
"""Read control parameters from file and return ControlPar object."""
return ControlPar().from_file(filename)

Expand Down Expand Up @@ -608,7 +607,7 @@ class TargetPar(Parameters):
# }

@classmethod
def from_file(cls, filename: str):
def from_file(cls, filename: Path):
"""Read target parameters from file and returns target_par object.
Reads target recognition parameters from a legacy detect_plate.par file,
Expand Down Expand Up @@ -673,7 +672,7 @@ def get_min_sum_grey(self):
"""Return the sum grey bounds."""
return self.sumg_min

def read_target_par(filename: str) -> TargetPar:
def read_target_par(filename: Path) -> TargetPar:
"""Read target parameters from file and returns target_par object."""
tpar = TargetPar()
return tpar.from_file(filename)
Expand Down Expand Up @@ -712,7 +711,7 @@ class OrientPar(Parameters):
interfflag: int = 0

@classmethod
def from_file(cls, filename: str):
def from_file(cls, filename: Path):
"""Read orientation parameters from file and returns orient_par object."""
ret = cls()
try:
Expand Down Expand Up @@ -777,7 +776,7 @@ def from_file(cls, file_path: str, num_cams: int):
return cls(fixp_name, img_name, img_ori0, tiff_flag, pair_flag, chfield)


def read_cal_ori_parameters(file_path: str, num_cams: int) -> CalibrationPar:
def read_cal_ori_parameters(file_path: Path, num_cams: int) -> CalibrationPar:
"""Read from cal_ori.par file."""
with open(file_path, 'r', encoding="utf-8") as file:
fixp_name = file.readline().strip()
Expand All @@ -799,7 +798,7 @@ class MultiPlanesPar(Parameters):
filename: list = field(default_factory=list)

@classmethod
def from_file(cls, file_path: str):
def from_file(cls, file_path: Path):
"""Read from multiplanes.par file."""
with open(file_path, 'r', encoding="utf-8") as file:
num_planes = int(file.readline().strip())
Expand All @@ -814,14 +813,14 @@ class ExaminePar(Parameters):
combine_flag: bool = False

@classmethod
def from_file(cls, file_path: str):
def from_file(cls, file_path: Path):
"""Read from examine.par file."""
with open(file_path, 'r', encoding="utf-8") as file:
examine_flag = bool(int(file.readline().strip()))
combine_flag = bool(int(file.readline().strip()))
return cls(examine_flag, combine_flag)

def read_examine_par(file_path: str) -> ExaminePar:
def read_examine_par(file_path: Path) -> ExaminePar:
"""Read from examine.par file."""
with open(file_path, 'r', encoding="utf-8") as file:
examine_flag = bool(int(file.readline().strip()))
Expand All @@ -835,14 +834,14 @@ class PftVersionPar(Parameters):
existing_target_flag: bool = False

@classmethod
def from_file(cls, file_path: str):
def from_file(cls, file_path: Path):
"""Read from pft_version.par file."""
with open(file_path, 'r', encoding="utf-8") as file:
pft_version = bool(int(file.readline().strip()))
return cls(pft_version)

@classmethod
def write(cls, file_path: str):
def write(cls, file_path: Path):
"""Write to pft_version.par file."""
with open(file_path, 'w', encoding="utf-8") as file:
file.write(f"{cls.existing_target_flag}\n")
3 changes: 2 additions & 1 deletion openptv_python/sortgrid.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from pathlib import Path
from typing import List

import numpy as np
Expand Down Expand Up @@ -119,7 +120,7 @@ def read_sortgrid_par(filename) -> int:
return eps


def read_calblock(filename: str) -> np.recarray: #List[Coord3d]:
def read_calblock(filename: Path) -> np.recarray: #List[Coord3d]:
"""
Read the calibration block file into the structure of 3D positions and pointers.
Expand Down
6 changes: 4 additions & 2 deletions openptv_python/tracking_frame_buf.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Tracking frame buffer."""
from collections import deque
from dataclasses import dataclass, field
from pathlib import Path
from typing import Deque, List, Tuple

import numpy as np
Expand Down Expand Up @@ -172,10 +173,11 @@ def read_targets(file_base: str, frame_num: int) -> List[Target]:

if frame_num > 0:
# filename = f"{file_base}{frame_num:04d}_targets"
filename = file_base % frame_num + '_targets'
fname = file_base % frame_num + '_targets'
else:
filename = f"{file_base}_targets"
fname = f"{file_base}_targets"

filename = Path(fname)
print(f" filename: {filename}")

try:
Expand Down
9 changes: 5 additions & 4 deletions openptv_python/tracking_run.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Tracking run module."""
import math
from dataclasses import dataclass
from pathlib import Path
from typing import List

from openptv_python.calibration import Calibration
Expand Down Expand Up @@ -97,10 +98,10 @@ def __init__(


def tr_new(
seq_par_fname: str,
tpar_fname: str,
vpar_fname: str,
cpar_fname: str,
seq_par_fname: Path,
tpar_fname: Path,
vpar_fname: Path,
cpar_fname: Path,
buf_len: int,
max_targets: int,
corres_file_base: str,
Expand Down
11 changes: 6 additions & 5 deletions tests/gen_track_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
testing. It starts from (0,0,0) and moves in a straight line on the x axis,
at a slow velocity.
"""
from pathlib import Path
from typing import List

import numpy as np
Expand All @@ -21,16 +22,16 @@
part_traject[:, 0] = np.r_[:num_frames] * velocity

# Find targets on each camera.
cpar = ControlPar(num_cams=3).from_file("testing_fodder/track/parameters/control_newpart.par")
cpar = ControlPar(num_cams=3).from_file(Path("tests/testing_fodder/track/parameters/control_newpart.par"))

targs: List[List[List[float]]] = [
[[0.0, 0.0] for _ in range(num_frames)] for _ in range(num_cams)
]

for cam in range(num_cams):
cal = Calibration().from_file(
f"testing_fodder/cal/sym_cam{cam+1}.tif.ori",
"testing_fodder/cal/cam1.tif.addpar",
Path(f"tests/testing_fodder/cal/sym_cam{cam+1}.tif.ori"),
Path("tests/testing_fodder/cal/cam1.tif.addpar"),
)
# check this out
for frame in range(num_frames):
Expand All @@ -41,7 +42,7 @@
for frame in range(num_frames):
# write 3D positions:
with open(
f"testing_fodder/track/res_orig/particles.{frame+1}", "w", encoding="utf-8"
f"tests/testing_fodder/track/res_orig/particles.{frame+1}", "w", encoding="utf-8"
) as outfile:
# Note correspondence to the single target in each frame.
outfile.writelines(
Expand All @@ -63,7 +64,7 @@
# write associated targets from all cameras:
for cam in range(num_cams):
with open(
f"testing_fodder/track/newpart/cam{cam+1}.{frame+1:04d}_targets",
f"tests/testing_fodder/track/newpart/cam{cam+1}.{frame+1:04d}_targets",
"w",
encoding="utf-8",
) as outfile:
Expand Down
21 changes: 11 additions & 10 deletions tests/test_burgers.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ def read_all_calibration(num_cams: int = 4) -> list[Calibration]:
for cam in range(num_cams):
ori_name = ori_tmpl % (cam + 1)
added_name = added_tmpl % (cam + 1)
calib.append(read_calibration(ori_name, added_name))
calib.append(read_calibration( Path(ori_name), Path(added_name) ))

return calib

Expand All @@ -71,6 +71,7 @@ def test_burgers(self):
current_directory = Path.cwd()
print(f"working from {current_directory}")
directory = Path("tests/testing_fodder/burgers")
parameters_path = (directory / "parameters").resolve(strict=True)

os.chdir(directory)

Expand All @@ -86,7 +87,7 @@ def test_burgers(self):
copy_directory("res_orig/", "res/")
copy_directory("img_orig/", "img/")

cpar = read_control_par("parameters/ptv.par")
cpar = read_control_par(parameters_path / "ptv.par")
self.assertIsNotNone(cpar)

calib = read_all_calibration(cpar.num_cams)
Expand All @@ -95,10 +96,10 @@ def test_burgers(self):
print("Test Burgers vortex case")

run = tr_new(
"parameters/sequence.par",
"parameters/track.par",
"parameters/criteria.par",
"parameters/ptv.par",
parameters_path / "sequence.par",
parameters_path / "track.par",
parameters_path / "criteria.par",
parameters_path / "ptv.par",
4,
20000,
"res/rt_is",
Expand All @@ -124,10 +125,10 @@ def test_burgers(self):
run.nlinks, 17, f"Was expecting nlinks == 17 but found {run.nlinks}")

run = tr_new(
"parameters/sequence.par",
"parameters/track.par",
"parameters/criteria.par",
"parameters/ptv.par",
parameters_path / "sequence.par",
parameters_path / "track.par",
parameters_path / "criteria.par",
parameters_path / "ptv.par",
4,
20000,
"res/rt_is",
Expand Down
Loading

0 comments on commit d4ed11e

Please sign in to comment.