|
a |
|
b/CLI/MusculoskeletalAnalysisCLITools/writeReport.py |
|
|
1 |
import os.path |
|
|
2 |
import numpy as np |
|
|
3 |
|
|
|
4 |
# Writes data to a tab seperated format |
|
|
5 |
# filepath: The filename and path of the file to write to |
|
|
6 |
# header: A list of collumn names, written as the first line if this is a new file |
|
|
7 |
# data: A list of data elements, each element can be single or a numpy ndarray |
|
|
8 |
def writeReport(filepath, header, data): |
|
|
9 |
if os.path.exists(filepath): |
|
|
10 |
# If the file exist open and append to it |
|
|
11 |
fOut = open(filepath, "a") |
|
|
12 |
else: |
|
|
13 |
# If the file does not exist create it and write header |
|
|
14 |
fOut = open(filepath, "w") |
|
|
15 |
if len(header) > 0: |
|
|
16 |
for h in header[:-1]: |
|
|
17 |
fOut.write(h+"\t") |
|
|
18 |
fOut.write(header[-1]+"\n") |
|
|
19 |
if len(data) > 0: |
|
|
20 |
# Write the data |
|
|
21 |
# If data contains ndarray write multiple lines, skipping over collumns that are not ndarray |
|
|
22 |
maxLength = max(numEl(d) for d in data) |
|
|
23 |
for i in range(maxLength): |
|
|
24 |
for j in range(len(data)): |
|
|
25 |
d = data[j] |
|
|
26 |
if numEl(d) > i: |
|
|
27 |
if isinstance(d, np.ndarray): |
|
|
28 |
fOut.write(str(d[i])) |
|
|
29 |
else: |
|
|
30 |
fOut.write(str(d)) |
|
|
31 |
if j < len(data)-1: |
|
|
32 |
fOut.write("\t") |
|
|
33 |
else: |
|
|
34 |
fOut.write("\n") |
|
|
35 |
fOut.close() |
|
|
36 |
|
|
|
37 |
# Gets the number of elements in a datapoint, |
|
|
38 |
# Returns the length of ndarray or 1 |
|
|
39 |
def numEl(d): |
|
|
40 |
if isinstance(d, np.ndarray): |
|
|
41 |
return len(d) |
|
|
42 |
else: |
|
|
43 |
return 1 |