-
Notifications
You must be signed in to change notification settings - Fork 5
/
create_summary.py
250 lines (180 loc) · 8.94 KB
/
create_summary.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
'''
This function is meant to be called from nwb_table_readme.py script to test NWBE compatibility
'''
import sys
import os
import heapq
import numpy as np
import matplotlib.pyplot as plt #add to docker
import math
from hdmf.backends.hdf5.h5_utils import H5DataIO
import pandas as pd
import pynwb
from pynwb import NWBHDF5IO
from pynwb.image import ImageSeries
from pynwb.base import TimeSeries
from pynwb.behavior import BehavioralTimeSeries, BehavioralEvents
from dandi.pynwb_utils import get_nwb_version
from nwbinspector import inspect_nwb
from nwbinspector.register_checks import Importance
from nwbinspector.inspector_tools import save_report, format_messages, MessageFormatter
import ast
from collections import Counter
def plot_and_save_timeseries(timeseries,path_to_save,image_tag,file_size):
ts = timeseries
file_path = os.path.join(path_to_save,f'plot_'+str(image_tag)+'.png')
if isinstance(ts, TimeSeries):
plt.figure()
selected_trace = ts.data[:]
if ts.timestamps is not None:
num_timestamps = min(len(ts.timestamps), len(selected_trace))
plt.plot(ts.timestamps[:num_timestamps], selected_trace[:num_timestamps])
plt.xlabel('Time')
plt.ylabel('Value')
plt.title(f"Timeseries: {ts.name}")
plt.savefig("temp.png", bbox_inches='tight')
curr_file_size = os.path.getsize("temp.png")
if curr_file_size > file_size:
file_size = curr_file_size
plt.savefig(file_path, bbox_inches='tight')
plt.close()
return((file_size,image_tag))
else:
plt.plot(selected_trace)
plt.title(f"Timeseries: {ts.name}")
plt.savefig("temp.png", bbox_inches='tight')
curr_file_size = os.path.getsize("temp.png")
if curr_file_size > file_size:
file_size = curr_file_size
plt.savefig(file_path, bbox_inches='tight')
plt.close()
return((file_size,image_tag))
return((file_size,image_tag))
def save_images_as_png(images,path_to_save,image_tag,file_size):
file_path = os.path.join(path_to_save,f'image_'+str(image_tag)+'.png')
for idx, image in enumerate(images):
plt.imshow(image, cmap='gray') # Assuming grayscale images
plt.axis('off')
plt.savefig("temp.png", bbox_inches='tight')
curr_file_size = os.path.getsize("temp.png")
if curr_file_size > file_size:
file_size = curr_file_size
plt.savefig(file_path, bbox_inches='tight')
plt.close()
return((file_size,image_tag))
def scan_processing(obj,plot_pairs,image_pairs,plot_counter,im_counter,plot_tag,image_tag,dandi_path):
if isinstance(obj, ImageSeries):
images_to_save = obj.data[:5]
if im_counter == 5:
comp = heapq.heappop(image_pairs)
temp = save_images_as_png(images_to_save,dandi_path,comp[1],comp[0])
heapq.heappush(image_pairs, temp)
else:
temp = save_images_as_png(images_to_save,dandi_path,image_tag,0)
image_tag=image_tag+1
im_counter=im_counter+1
heapq.heappush(image_pairs, temp)
elif isinstance(obj, TimeSeries):
if plot_counter == 5:
comp = heapq.heappop(plot_pairs)
temp = plot_and_save_timeseries(obj,dandi_path,comp[1],comp[0])
heapq.heappush(plot_pairs, temp)
else:
temp = plot_and_save_timeseries(obj,dandi_path,plot_tag,0)
plot_tag=plot_tag+1
plot_counter=plot_counter+1
heapq.heappush(plot_pairs, temp)
return(plot_pairs,image_pairs,plot_counter,im_counter,plot_tag,image_tag)
def scan_acquisiton(obj,plot_pairs,plot_counter,plot_tag,dandi_path):
if plot_counter == 5:
comp = heapq.heappop(plot_pairs)
temp = plot_and_save_timeseries(obj,dandi_path,comp[1],comp[0])
heapq.heappush(plot_pairs, temp)
else:
temp = plot_and_save_timeseries(obj,dandi_path,plot_tag,0)
plot_tag=plot_tag+1
plot_counter=plot_counter+1
heapq.heappush(plot_pairs, temp)
return(plot_pairs,plot_counter,plot_tag)
def create_summary(nwb_path,dandi_ident,html_tag):
# Step 0: Base variables
save_folder = 'testing/validation_folder'
html_folder = os.path.join(save_folder,'Summaries')
file_folder = 'file_'+str(html_tag)
dandi_path = os.path.join(html_folder,os.path.join(str(dandi_ident),file_folder))
html_temp = 'testing/summary_template.html' #add docker args
html_path = os.path.join(dandi_path,'README.md')
if not os.path.exists(dandi_path):
os.makedirs(dandi_path)
# Step 1: Open the html file template and store it in base variable
try:
with open(html_temp, "r") as file:
html_content = file.read()
except FileNotFoundError:
print(f"File '{html_temp}' not found.")
html_content = ""
html_variable = f"""{html_content}"""
# Step 2: Create html file for edit (add right dir, this is only for test)
myfile = open(html_path, 'w')
title = "Dandiset Summary"
html_content = html_content.replace("{ident}", dandi_ident)
# Step 3: Add Metadata to HTML
metadatatmpl = """<div><div>{title}</div><div>{info}</div></div>"""
html_content = html_content.replace("{file_name}",nwb_path.split('/')[-1])
# Adding plots for timeseries -----------------------------------------
io = NWBHDF5IO(nwb_path,mode='r',load_namespaces=True) # Add try except block
nwbfile = io.read()
image_html = ""
plots_html = ""
image_tmpl = """<img src="{path}" alt="Image">"""
plot_pairs = []
image_pairs = []
heapq.heapify(plot_pairs)
heapq.heapify(image_pairs)
plot_counter = 0
im_counter = 0
plot_tag = 1
image_tag = 1
for processing_module_name in nwbfile.processing:
for p2 in nwbfile.processing[processing_module_name].data_interfaces:
try:
for field in nwbfile.processing[processing_module_name].data_interfaces[p2].time_series:
plot_pairs,image_pairs,plot_counter,im_counter,plot_tag,image_tag = scan_processing(nwbfile.processing[processing_module_name].data_interfaces[p2].time_series[field],plot_pairs,image_pairs,plot_counter,im_counter,plot_tag,image_tag,dandi_path)
except:
plot_pairs,image_pairs,plot_counter,im_counter,plot_tag,image_tag = scan_processing(nwbfile.processing[processing_module_name].data_interfaces,plot_pairs,image_pairs,plot_counter,im_counter,plot_tag,image_tag,dandi_path)
for processing_module_name in nwbfile.acquisition:
try:
for field in nwbfile.acquisition[processing_module_name].time_series:
plot_pairs,plot_counter,plot_tag = scan_acquisiton(nwbfile.acquisition[processing_module_name].time_series[field],plot_pairs,plot_counter,plot_tag,dandi_path)
except:
plot_pairs,plot_counter,plot_tag = scan_acquisiton(nwbfile.acquisition[processing_module_name],plot_pairs,plot_counter,plot_tag,dandi_path)
for processing_module_name in nwbfile.stimulus:
try:
for field in nwbfile.stimulus[processing_module_name].time_series:
plot_pairs,plot_counter,plot_tag = scan_acquisiton(nwbfile.stimulus[processing_module_name].time_series[field],plot_pairs,plot_counter,plot_tag,dandi_path)
except:
plot_pairs,plot_counter,plot_tag = scan_acquisiton(nwbfile.stimulus[processing_module_name],plot_pairs,plot_counter,plot_tag,dandi_path)
if(os.path.exists("temp.png")):
os.remove("temp.png")
io.close()
if len(os.listdir(dandi_path))>1 :
for file_name in sorted(os.listdir(dandi_path)):
if file_name.startswith("image"):
image_html+=image_tmpl.format(path=file_name)
elif file_name.startswith("plot"):
plots_html+=image_tmpl.format(path=file_name)
else:
raise Exception("Data couldn't be accessed .")
if plots_html != "":
html_content = html_content.replace("{Plots}", plots_html)
else:
html_content = html_content.replace("{Plots}", "No Plots Were Found !")
if image_html != "":
html_content = html_content.replace("{Images}", image_html)
else:
html_content = html_content.replace("{Images}", "No Images Were Found !")
# --------------------------------------------------------------------------
myfile.write(html_content)
myfile.close()
if __name__ == '__main__':
create_summary(sys.argv[1],sys.argv[2],sys.argv[3])