Skip to content

Commit 98174c3

Browse files
authored
Refactor createCSVData (#265)
1 parent 0b63a2b commit 98174c3

File tree

1 file changed

+44
-104
lines changed

1 file changed

+44
-104
lines changed

OMPython/ModelicaSystem.py

Lines changed: 44 additions & 104 deletions
Original file line numberDiff line numberDiff line change
@@ -854,112 +854,52 @@ def checkValidInputs(self, name):
854854
else:
855855
ModelicaSystemError('Error!!! Value must be in tuple format')
856856

857-
# To create csv file for inputs
858-
def createCSVData(self):
859-
sl = [] # Actual timestamps
860-
skip = False
861-
862-
# check for NONE in input list and replace with proper data (e.g) [(startTime, 0.0), (stopTime, 0.0)]
863-
tmpinputlist = {}
864-
for key, value in self.inputlist.items():
865-
if value is None:
866-
tmpinputlist[key] = [(float(self.simulateOptions["startTime"]), 0.0),
867-
(float(self.simulateOptions["stopTime"]), 0.0)]
857+
def createCSVData(self) -> None:
858+
start_time: float = float(self.simulateOptions["startTime"])
859+
stop_time: float = float(self.simulateOptions["stopTime"])
860+
861+
# Replace None inputs with a default constant zero signal
862+
inputs: dict[str, list[tuple[float, float]]] = {}
863+
for input_name, input_signal in self.inputlist.items():
864+
if input_signal is None:
865+
inputs[input_name] = [(start_time, 0.0), (stop_time, 0.0)]
868866
else:
869-
tmpinputlist[key] = value
870-
871-
inp = list(tmpinputlist.values())
872-
873-
for i in inp:
874-
cl = list()
875-
el = list()
876-
for t, x in i:
877-
cl.append(t)
878-
for i in cl:
879-
if skip is True:
880-
skip = False
881-
continue
882-
if i not in sl:
883-
el.append(i)
884-
else:
885-
elem_no = cl.count(i)
886-
sl_no = sl.count(i)
887-
if elem_no == 2 and sl_no == 1:
888-
el.append(i)
889-
skip = True
890-
sl = sl + el
891-
892-
sl.sort()
893-
for t in sl:
894-
for i in inp:
895-
for ttt in [tt[0] for tt in i]:
896-
if t not in [tt[0] for tt in i]:
897-
i.append((t, '?'))
898-
inpSortedList = list()
899-
sortedList = list()
900-
for i in inp:
901-
sortedList = sorted(i, key=lambda x: x[0])
902-
inpSortedList.append(sortedList)
903-
for i in inpSortedList:
904-
ind = 0
905-
for t, x in i:
906-
if x == '?':
907-
t1 = i[ind - 1][0]
908-
u1 = i[ind - 1][1]
909-
t2 = i[ind + 1][0]
910-
u2 = i[ind + 1][1]
911-
nex = 2
912-
while (u2 == '?'):
913-
u2 = i[ind + nex][1]
914-
t2 = i[ind + nex][0]
915-
nex += 1
916-
x = float(u1 + (u2 - u1) * (t - t1) / (t2 - t1))
917-
i[ind] = (t, x)
918-
ind += 1
919-
slSet = list()
920-
slSet = set(sl)
921-
for i in inpSortedList:
922-
tempTime = list()
923-
for (t, x) in i:
924-
tempTime.append(t)
925-
inSl = None
926-
inI = None
927-
for s in slSet:
928-
inSl = sl.count(s)
929-
inI = tempTime.count(s)
930-
if inSl != inI:
931-
test = list()
932-
test = [(x, y) for x, y in i if x == s]
933-
i.append(test[0])
934-
newInpList = list()
935-
tempSorting = list()
936-
for i in inpSortedList:
937-
# i.sort() => just sorting might not work so need to sort according to 1st element of a tuple
938-
tempSorting = sorted(i, key=lambda x: x[0])
939-
newInpList.append(tempSorting)
940-
941-
interpolated_inputs_all = list()
942-
for i in newInpList:
943-
templist = list()
944-
for (t, x) in i:
945-
templist.append(x)
946-
interpolated_inputs_all.append(templist)
947-
948-
name = ','.join(list(self.inputlist.keys()))
949-
name = f'time,{name},end'
950-
951-
a = ''
952-
l = []
953-
l.append(name)
954-
for i in range(0, len(sl)):
955-
a = f'{float(sl[i])},{",".join(str(float(inppp[i])) for inppp in interpolated_inputs_all)},0'
956-
l.append(a)
957-
958-
self.csvFile = (pathlib.Path(self.tempdir) / f'{self.modelName}.csv').as_posix()
867+
inputs[input_name] = input_signal
868+
869+
# Collect all unique timestamps across all input signals
870+
all_times = np.array(
871+
sorted({t for signal in inputs.values() for t, _ in signal}),
872+
dtype=float
873+
)
874+
875+
# Interpolate missing values
876+
interpolated_inputs: dict[str, np.ndarray] = {}
877+
for signal_name, signal_values in inputs.items():
878+
signal = np.array(signal_values)
879+
interpolated_inputs[signal_name] = np.interp(
880+
all_times,
881+
signal[:, 0], # times
882+
signal[:, 1] # values
883+
)
884+
885+
# Write CSV file
886+
input_names = list(interpolated_inputs.keys())
887+
header = ['time'] + input_names + ['end']
888+
889+
csv_rows = [header]
890+
for i, t in enumerate(all_times):
891+
row = [
892+
t, # time
893+
*(interpolated_inputs[name][i] for name in input_names), # input values
894+
0 # trailing 'end' column
895+
]
896+
csv_rows.append(row)
897+
898+
self.csvFile: str = (pathlib.Path(self.tempdir) / f'{self.modelName}.csv').as_posix()
899+
959900
with open(self.csvFile, "w", newline="") as f:
960-
writer = csv.writer(f, delimiter='\n')
961-
writer.writerow(l)
962-
f.close()
901+
writer = csv.writer(f)
902+
writer.writerows(csv_rows)
963903

964904
# to convert Modelica model to FMU
965905
def convertMo2Fmu(self, version="2.0", fmuType="me_cs", fileNamePrefix="<default>", includeResources=True): # 19

0 commit comments

Comments
 (0)