Skip to content

Commit 92a7988

Browse files
committed
some type hint issues
1 parent 14e7460 commit 92a7988

2 files changed

Lines changed: 54 additions & 40 deletions

File tree

.pre-commit-config.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ repos:
1919
- id: black-jupyter
2020
# isort import sorting
2121
- repo: https://github.com/timothycrosley/isort
22-
rev: "8.0.1"
22+
rev: "9.0.0a3"
2323
hooks:
2424
- id: isort
2525
args: ["--profile", "black"]

pyGCodeDecode/gcode_interpreter.py

Lines changed: 53 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,12 @@ def generate_planner_blocks(states: List[state], firmware=None):
5252
return block_list
5353

5454

55-
def find_current_segment(path: List[segment], t: float, last_index: int = None, keep_position: bool = False):
55+
def find_current_segment(
56+
path: List[segment],
57+
t: float,
58+
last_index: Optional[int] = None,
59+
keep_position: bool = False,
60+
):
5661
"""Find the current segment.
5762
5863
Args:
@@ -139,8 +144,8 @@ class simulation:
139144
def __init__(
140145
self,
141146
gcode_path: Path,
142-
machine_name: str = None,
143-
initial_machine_setup: "setup" = None,
147+
machine_name: Optional[str] = None,
148+
initial_machine_setup: Optional["setup"] = None,
144149
output_unit_system: str = "SI (mm)",
145150
verbosity_level: Optional[int] = None,
146151
):
@@ -190,20 +195,18 @@ def __init__(
190195
"Trying to create a setup from pyGCD's default values...",
191196
lvl=1,
192197
)
193-
default_presets_file = importlib.resources.files("pyGCodeDecode").joinpath(
194-
"data/default_printer_presets.yaml"
195-
)
196-
initial_machine_setup = setup(
197-
presets_file=default_presets_file,
198-
printer=machine_name,
199-
)
198+
with importlib.resources.as_file(
199+
importlib.resources.files("pyGCodeDecode") / "data" / "default_printer_presets.yaml"
200+
) as default_presets_file:
201+
initial_machine_setup = setup(presets_file=default_presets_file, printer=machine_name)
200202

201203
# SET INITIAL SETTINGS
202204
self.initial_machine_setup_dict = initial_machine_setup.check_initial_setup()
203205
self.firmware = self.initial_machine_setup_dict["firmware"]
204206

205207
self.states: List[state] = generate_states(
206-
filepath=self.filename, initial_machine_setup=self.initial_machine_setup_dict
208+
filepath=self.filename,
209+
initial_machine_setup=self.initial_machine_setup_dict,
207210
)
208211

209212
custom_print(
@@ -284,7 +287,7 @@ def time_average(calculator):
284287
else:
285288
raise ValueError(f"Unknown average type: {avg} for {calculator.name}")
286289

287-
def get_values(self, t: float, output_unit_system: str = None) -> Tuple[List[float]]:
290+
def get_values(self, t: float, output_unit_system: Optional[str] = None) -> Tuple[List[float], List[float]]:
288291
"""Return unit system scaled values for vel and pos.
289292
290293
Args:
@@ -320,7 +323,8 @@ def get_width(self, t: float, extrusion_h: float, filament_dia: Optional[float]
320323
Returns:
321324
float: width
322325
"""
323-
filament_dia = self.initial_machine_setup_dict["filament_diam"] if filament_dia is None else filament_dia
326+
if filament_dia is None:
327+
filament_dia: float = self.initial_machine_setup_dict["filament_diam"]
324328

325329
curr_val = self.get_values(t=t)
326330

@@ -329,7 +333,7 @@ def get_width(self, t: float, extrusion_h: float, filament_dia: Optional[float]
329333

330334
filament_cross_sec = np.pi * (filament_dia / 2) ** 2 # calculate cross area of filament
331335
width = (
332-
(flow_rate * filament_cross_sec) / (extrusion_h * feed_rate) if feed_rate > 0 else 0
336+
float((flow_rate * filament_cross_sec) / (extrusion_h * feed_rate)) if feed_rate > 0.0 else 0.0
333337
) # calculate width, zero if no movement.
334338

335339
return width
@@ -345,10 +349,10 @@ def print_summary(self, start_time: float):
345349
f" and generated {len(self.blocklist)} planner blocks.\n"
346350
f"Estimated time to travel all states with provided "
347351
f"printer settings is {self.blocklist[-1].get_segments()[-1].t_end:.2f} seconds.\n"
348-
f"The Simulation took {(time.time()-start_time):.2f} s of computation time."
352+
f"The Simulation took {(time.time() - start_time):.2f} s of computation time."
349353
)
350354

351-
def refresh(self, new_state_list: List[state] = None):
355+
def refresh(self, new_state_list: Optional[List[state]] = None):
352356
"""Refresh simulation. Either through new state list or by rerunning the self.states as input.
353357
354358
Args:
@@ -363,7 +367,7 @@ def refresh(self, new_state_list: List[state] = None):
363367
)
364368
self.trajectory_self_correct()
365369

366-
def extrusion_extent(self, output_unit_system: str = None) -> np.ndarray:
370+
def extrusion_extent(self, output_unit_system: Optional[str] = None) -> np.ndarray:
367371
"""Return scaled xyz min & max while extruding.
368372
369373
Args:
@@ -391,7 +395,7 @@ def extrusion_extent(self, output_unit_system: str = None) -> np.ndarray:
391395
else:
392396
raise ValueError("No extrusion happening.")
393397

394-
def extrusion_max_vel(self, output_unit_system: str = None) -> np.float64:
398+
def extrusion_max_vel(self, output_unit_system: Optional[str] = None) -> np.float64:
395399
"""Return scaled maximum velocity while extruding.
396400
397401
Args:
@@ -460,7 +464,7 @@ def save_summary(self, filepath: Union[Path, str]):
460464

461465
custom_print(f"💾 Summary written to 👉 {str(filepath)}")
462466

463-
def get_scaling_factor(self, output_unit_system: str = None) -> float:
467+
def get_scaling_factor(self, output_unit_system: Optional[str] = None) -> float:
464468
"""Get a scaling factor to convert lengths from mm to another supported unit system.
465469
466470
Args:
@@ -482,15 +486,15 @@ class setup:
482486

483487
def __init__(
484488
self,
485-
presets_file: str,
486-
printer: str = None,
489+
presets_file: Path | str,
490+
printer: Optional[str] = None,
487491
verbosity_level: Optional[int] = None,
488492
**kwargs,
489493
):
490494
"""Initialize the setup for the printing simulation.
491495
492496
Args:
493-
presets_file (str): Path to the YAML file containing printer presets.
497+
presets_file (Path or str): Path to the YAML file containing printer presets.
494498
printer (str, optional): Name of the printer to select from the preset file. Defaults to None.
495499
verbosity_level (int, optional): Verbosity level for logging (0: no output, 1: warnings, 2: info, 3: debug). Defaults to None.
496500
**kwargs: Additional properties to set or override in the setup.
@@ -516,33 +520,43 @@ def __getattr__(self, name):
516520

517521
def __setattr__(self, name, value):
518522
"""Set setup_dict keys."""
519-
if name in ["setup_dict", "filename", "available_unit_systems", "input_unit_system"]:
523+
if name in [
524+
"setup_dict",
525+
"filename",
526+
"available_unit_systems",
527+
"input_unit_system",
528+
]:
520529
super().__setattr__(name, value)
521530
else:
522531
self.setup_dict[name] = value
523532

524-
def load_setup(self, filepath, printer=None):
533+
def load_setup(self, filepath: str | Path, printer=None):
525534
"""Load setup from file.
526535
527536
Args:
528-
filepath: (string) specify path to setup file
537+
filepath: (string or Path) specify path to setup file
529538
"""
530-
file = open(file=filepath)
539+
if isinstance(filepath, str):
540+
filepath = Path(filepath)
531541

532-
setup_dict = yaml.load(file, Loader=yaml.Loader)
533-
if printer:
534-
self.setup_dict = setup_dict[printer]
535-
self.printer = printer
536-
else:
537-
printers_available = [printer for printer in setup_dict]
538-
539-
if len(printers_available) == 1:
540-
printer = printers_available[0]
542+
with filepath.open(mode="r") as file:
543+
setup_dict = yaml.load(file, Loader=yaml.Loader)
544+
if printer:
541545
self.setup_dict = setup_dict[printer]
542546
self.printer = printer
543-
custom_print(f"Automatically selected the '{printer}' printer in the setup file {filepath}.", lvl=2)
544547
else:
545-
raise ValueError("Multiple printers found but none has been selected.")
548+
printers_available = [printer for printer in setup_dict]
549+
550+
if len(printers_available) == 1:
551+
printer = printers_available[0]
552+
self.setup_dict = setup_dict[printer]
553+
self.printer = printer
554+
custom_print(
555+
f"Automatically selected the '{printer}' printer in the setup file {filepath}.",
556+
lvl=2,
557+
)
558+
else:
559+
raise ValueError("Multiple printers found but none has been selected.")
546560

547561
# parse initial position if set via config
548562
if "initial_position" in self.setup_dict:
@@ -604,7 +618,7 @@ def check_initial_setup(self):
604618
)
605619
return initial_machine_setup
606620

607-
def set_initial_position(self, initial_position: Union[tuple, dict], input_unit_system: str = None):
621+
def set_initial_position(self, initial_position: Union[tuple, dict], input_unit_system: Optional[str] = None):
608622
"""Set initial Position.
609623
610624
Args:
@@ -664,7 +678,7 @@ def get_dict(self) -> dict:
664678
return_dict = self.setup_dict
665679
return return_dict
666680

667-
def get_scaling_factor(self, input_unit_system: str = None) -> float:
681+
def get_scaling_factor(self, input_unit_system: Optional[str] = None) -> float:
668682
"""Get a scaling factor to convert lengths from mm to another supported unit system.
669683
670684
Args:

0 commit comments

Comments
 (0)