|
| 1 | +import os |
| 2 | +import pandas as pd |
| 3 | +import numpy as np |
| 4 | +from goofi.data import Data, DataType |
| 5 | +from goofi.node import Node |
| 6 | +from goofi.params import StringParam, BoolParam |
| 7 | + |
| 8 | + |
| 9 | +class Replay(Node): |
| 10 | + @staticmethod |
| 11 | + def config_output_slots(): |
| 12 | + return {"table_output": DataType.TABLE} |
| 13 | + |
| 14 | + @staticmethod |
| 15 | + def config_params(): |
| 16 | + return { |
| 17 | + "Read": { |
| 18 | + "filename": StringParam("output.csv"), |
| 19 | + "play": BoolParam(False), |
| 20 | + "restart": BoolParam(False, trigger=True), |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + def setup(self): |
| 25 | + self.df = None |
| 26 | + self.current_index = 0 |
| 27 | + self.last_filename = None # Track filename changes |
| 28 | + self.load_csv() |
| 29 | + |
| 30 | + def load_csv(self): |
| 31 | + filename = self.params["Read"]["filename"].value |
| 32 | + if filename != self.last_filename: # Only reload if filename changed |
| 33 | + if os.path.exists(filename): |
| 34 | + self.df = pd.read_csv(filename) |
| 35 | + self.current_index = 0 |
| 36 | + else: |
| 37 | + self.df = None |
| 38 | + self.last_filename = filename |
| 39 | + |
| 40 | + def process(self): |
| 41 | + filename = self.params["Read"]["filename"].value |
| 42 | + |
| 43 | + # Reload CSV if filename has changed |
| 44 | + self.load_csv() |
| 45 | + |
| 46 | + if self.df is None or self.df.empty: |
| 47 | + return {"table_output": ({}, {})} # Return empty table instead of None |
| 48 | + |
| 49 | + if not self.params["Read"]["play"].value: |
| 50 | + return |
| 51 | + |
| 52 | + # Extract the current row as a dictionary |
| 53 | + row_data = self.df.iloc[self.current_index].to_dict() |
| 54 | + |
| 55 | + # Convert each value to the appropriate Data format |
| 56 | + table_output = { |
| 57 | + key: Data( |
| 58 | + DataType.ARRAY if not isinstance(value, str) else DataType.STRING, |
| 59 | + np.array([value]) if isinstance(value, (int, float)) else value, # Convert lists, ints, and floats to NumPy arrays |
| 60 | + {} |
| 61 | + ) |
| 62 | + for key, value in row_data.items() |
| 63 | + } |
| 64 | + |
| 65 | + # Increment index, loop back to the start when reaching the end |
| 66 | + self.current_index = (self.current_index + 1) % len(self.df) |
| 67 | + |
| 68 | + return {"table_output": (table_output, {})} |
| 69 | + |
| 70 | + def read_filename_changed(self): |
| 71 | + self.load_csv() |
| 72 | + |
| 73 | + def read_restart_changed(self): |
| 74 | + self.current_index = 0 # Reset index when restart is triggered |
0 commit comments