-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathbase.py
executable file
·1540 lines (1280 loc) · 56.6 KB
/
base.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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Main functions for running input videos through trace.
The overall algorithm is contained in `interleaved_reading_and_tracing`.
* The input can be a video file or a directory of PF files.
* Chunks of ~200 frames are read using ffmpeg, and then written to disk
as uncompressed tiff stacks.
* Trace is called in parallel on each tiff stack
* Additional chunks are read as trace completes.
* At the end, all of the HDF5 files are stitched together.
The previous function `pipeline_trace` is now deprecated.
"""
from __future__ import print_function
from builtins import zip
from builtins import map
from builtins import str
from builtins import range
from builtins import object
try:
import tifffile
except ImportError:
pass
import os
import numpy as np
import subprocess
import multiprocessing
import tables
try:
from whisk.python import trace
from whisk.python.traj import MeasurementsTable
except ImportError:
print("cannot import whisk")
import pandas
import WhiskiWrap
from WhiskiWrap import video_utils
import my
import scipy.io
import ctypes
import glob
import time
import shutil
import itertools
# Find the repo directory and the default param files
# The banks don't differe with sensitive or default
DIRECTORY = os.path.split(__file__)[0]
PARAMETERS_FILE = os.path.join(DIRECTORY, 'default.parameters')
SENSITIVE_PARAMETERS_FILE = os.path.join(DIRECTORY, 'sensitive.parameters')
HALFSPACE_DB_FILE = os.path.join(DIRECTORY, 'halfspace.detectorbank')
LINE_DB_FILE = os.path.join(DIRECTORY, 'line.detectorbank')
# libpfDoubleRate library, needed for PFReader
LIB_DOUBLERATE = os.path.join(DIRECTORY, 'libpfDoubleRate.so')
def copy_parameters_files(target_directory, sensitive=False):
"""Copies in parameters and banks"""
if sensitive:
shutil.copyfile(SENSITIVE_PARAMETERS_FILE, os.path.join(target_directory,
'default.parameters'))
else:
shutil.copyfile(PARAMETERS_FILE, os.path.join(target_directory,
'default.parameters'))
# Banks are the same regardless
shutil.copyfile(HALFSPACE_DB_FILE, os.path.join(target_directory,
'halfspace.detectorbank'))
shutil.copyfile(LINE_DB_FILE, os.path.join(target_directory,
'line.detectorbank'))
class WhiskerSeg(tables.IsDescription):
time = tables.UInt32Col()
id = tables.UInt16Col()
tip_x = tables.Float32Col()
tip_y = tables.Float32Col()
fol_x = tables.Float32Col()
fol_y = tables.Float32Col()
pixlen = tables.UInt16Col()
chunk_start = tables.UInt32Col()
class WhiskerSeg_measure(tables.IsDescription):
time = tables.UInt32Col()
id = tables.UInt16Col()
tip_x = tables.Float32Col()
tip_y = tables.Float32Col()
fol_x = tables.Float32Col()
fol_y = tables.Float32Col()
pixlen = tables.UInt16Col()
length = tables.Float32Col()
score = tables.Float32Col()
angle = tables.Float32Col()
curvature = tables.Float32Col()
chunk_start = tables.UInt32Col()
def write_chunk(chunk, chunkname, directory='.'):
tifffile.imsave(os.path.join(directory, chunkname), chunk, compress=0)
def trace_chunk(video_filename, delete_when_done=False):
"""Run trace on an input file
First we create a whiskers filename from `video_filename`, which is
the same file with '.whiskers' replacing the extension. Then we run
trace using subprocess.
Care is taken to move into the working directory during trace, and then
back to the original directory.
Returns:
stdout, stderr
"""
print("Starting", video_filename)
orig_dir = os.getcwd()
run_dir, raw_video_filename = os.path.split(os.path.abspath(video_filename))
whiskers_file = WhiskiWrap.utils.FileNamer.from_video(video_filename).whiskers
command = ['trace', raw_video_filename, whiskers_file]
os.chdir(run_dir)
try:
pipe = subprocess.Popen(command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout, stderr = pipe.communicate()
except:
raise
finally:
os.chdir(orig_dir)
print("Done", video_filename)
if not os.path.exists(whiskers_file):
print(raw_video_filename)
raise IOError("tracing seems to have failed")
if delete_when_done:
os.remove(video_filename)
return {'video_filename': video_filename, 'stdout': stdout, 'stderr': stderr}
def measure_chunk(whiskers_filename, face, delete_when_done=False):
"""Run measure on an input file
First we create a measurement filename from `whiskers_filename`, which is
the same file with '.measurements' replacing the extension. Then we run
trace using subprocess.
Care is taken to move into the working directory during trace, and then
back to the original directory.
Returns:
stdout, stderr
"""
print("Starting", whiskers_filename)
orig_dir = os.getcwd()
run_dir, raw_whiskers_filename = os.path.split(os.path.abspath(whiskers_filename))
measurements_file = WhiskiWrap.utils.FileNamer.from_whiskers(whiskers_filename).measurements
command = ['measure', '--face', face, raw_whiskers_filename, measurements_file]
os.chdir(run_dir)
try:
pipe = subprocess.Popen(command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout, stderr = pipe.communicate()
except:
raise
finally:
os.chdir(orig_dir)
print("Done", whiskers_filename)
if not os.path.exists(measurements_file):
print(raw_whiskers_filename)
raise IOError("measurement seems to have failed")
if delete_when_done:
os.remove(whiskers_filename)
return {'whiskers_filename': whiskers_filename, 'stdout': stdout, 'stderr': stderr}
def trace_and_measure_chunk(video_filename, delete_when_done=False, face='right'):
"""Run trace on an input file
First we create a whiskers filename from `video_filename`, which is
the same file with '.whiskers' replacing the extension. Then we run
trace using subprocess.
Care is taken to move into the working directory during trace, and then
back to the original directory.
Returns:
stdout, stderr
"""
print("Starting", video_filename)
orig_dir = os.getcwd()
run_dir, raw_video_filename = os.path.split(os.path.abspath(video_filename))
# Run trace:
whiskers_file = WhiskiWrap.utils.FileNamer.from_video(video_filename).whiskers
trace_command = ['trace', raw_video_filename, whiskers_file]
os.chdir(run_dir)
try:
trace_pipe = subprocess.Popen(trace_command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout, stderr = trace_pipe.communicate()
except:
raise
finally:
os.chdir(orig_dir)
print("Done", video_filename)
if not os.path.exists(whiskers_file):
print(raw_video_filename)
raise IOError("tracing seems to have failed")
# Run measure:
measurements_file = WhiskiWrap.utils.FileNamer.from_video(video_filename).measurements
measure_command = ['measure', '--face', face, whiskers_file, measurements_file]
os.chdir(run_dir)
try:
measure_pipe = subprocess.Popen(measure_command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout, stderr = measure_pipe.communicate()
except:
raise
finally:
os.chdir(orig_dir)
print("Done", whiskers_file)
if not os.path.exists(measurements_file):
print(whiskers_file)
raise IOError("measuring seems to have failed")
# Clean up:
if delete_when_done:
os.remove(video_filename)
return {'video_filename': video_filename,'stdout': stdout, 'stderr': stderr}
def sham_trace_chunk(video_filename):
print("sham tracing", video_filename)
time.sleep(2)
return video_filename
def setup_hdf5(h5_filename, expectedrows, measure=False):
# Open file
h5file = tables.open_file(h5_filename, mode="w")
if not measure:
WhiskerDescription = WhiskerSeg
elif measure:
WhiskerDescription = WhiskerSeg_measure
# A group for the normal data
table = h5file.create_table(h5file.root, "summary", WhiskerDescription,
"Summary data about each whisker segment",
expectedrows=expectedrows)
# Put the contour here
xpixels_vlarray = h5file.create_vlarray(
h5file.root, 'pixels_x',
tables.Float32Atom(shape=()),
title='Every pixel of each whisker (x-coordinate)',
expectedrows=expectedrows)
ypixels_vlarray = h5file.create_vlarray(
h5file.root, 'pixels_y',
tables.Float32Atom(shape=()),
title='Every pixel of each whisker (y-coordinate)',
expectedrows=expectedrows)
h5file.close()
def append_whiskers_to_hdf5(whisk_filename, h5_filename, chunk_start, measurements_filename=None):
"""Load data from whisk_file and put it into an hdf5 file
The HDF5 file will have two basic components:
/summary : A table with the following columns:
time, id, fol_x, fol_y, tip_x, tip_y, pixlen
These are all directly taken from the whisk file
/pixels_x : A vlarray of the same length as summary but with the
entire array of x-coordinates of each segment.
/pixels_y : Same but for y-coordinates
"""
## Load it, so we know what expectedrows is
# This loads all whisker info into C data types
# wv is like an array of trace.LP_cWhisker_Seg
# Each entry is a trace.cWhisker_Seg and can be converted to
# a python object via: wseg = trace.Whisker_Seg(wv[idx])
# The python object responds to .time and .id (integers) and .x and .y (numpy
# float arrays).
#wv, nwhisk = trace.Debug_Load_Whiskers(whisk_filename)
print(whisk_filename)
whiskers = trace.Load_Whiskers(whisk_filename)
nwhisk = np.sum(list(map(len, list(whiskers.values()))))
if measurements_filename is not None:
print(measurements_filename)
M = MeasurementsTable(str(measurements_filename))
measurements = M.asarray()
measurements_idx = 0
# Open file
h5file = tables.open_file(h5_filename, mode="a")
## Iterate over rows and store
table = h5file.get_node('/summary')
h5seg = table.row
xpixels_vlarray = h5file.get_node('/pixels_x')
ypixels_vlarray = h5file.get_node('/pixels_y')
for frame, frame_whiskers in whiskers.items():
for whisker_id, wseg in frame_whiskers.items():
# Write to the table
h5seg['chunk_start'] = chunk_start
h5seg['time'] = wseg.time + chunk_start
h5seg['id'] = wseg.id
h5seg['fol_x'] = wseg.x[0]
h5seg['fol_y'] = wseg.y[0]
h5seg['tip_x'] = wseg.x[-1]
h5seg['tip_y'] = wseg.y[-1]
if measurements_filename is not None:
h5seg['length'] = measurements[measurements_idx][3]
h5seg['score'] = measurements[measurements_idx][4]
h5seg['angle'] = measurements[measurements_idx][5]
h5seg['curvature'] = measurements[measurements_idx][6]
h5seg['pixlen'] = len(wseg.x)
h5seg['fol_x'] = measurements[measurements_idx][7]
h5seg['fol_y'] = measurements[measurements_idx][8]
h5seg['tip_x'] = measurements[measurements_idx][9]
h5seg['tip_y'] = measurements[measurements_idx][10]
measurements_idx += 1
assert len(wseg.x) == len(wseg.y)
h5seg.append()
# Write x
xpixels_vlarray.append(wseg.x)
ypixels_vlarray.append(wseg.y)
table.flush()
h5file.close()
def pipeline_trace(input_vfile, h5_filename,
epoch_sz_frames=3200, chunk_sz_frames=200,
frame_start=0, frame_stop=None,
n_trace_processes=4, expectedrows=1000000, flush_interval=100000,
measure=False,face='right'):
"""Trace a video file using a chunked strategy.
This is now deprecated in favor of interleaved_reading_and_tracing.
The issue with this function is that it has to write out all of the tiffs
first, before tracing, which is a wasteful use of disk space.
input_vfile : input video filename
h5_filename : output HDF5 file
epoch_sz_frames : Video is first broken into epochs of this length
chunk_sz_frames : Each epoch is broken into chunks of this length
frame_start, frame_stop : where to start and stop processing
n_trace_processes : how many simultaneous processes to use for tracing
expectedrows, flush_interval : used to set up hdf5 file
TODO: combine the reading and writing stages using frame_func so that
we don't have to load the whole epoch in at once. In fact then we don't
even need epochs at all.
"""
WhiskiWrap.utils.probe_needed_commands()
# Figure out where to store temporary data
input_vfile = os.path.abspath(input_vfile)
input_dir = os.path.split(input_vfile)[0]
# Setup the result file
setup_hdf5(h5_filename, expectedrows, measure=measure)
# Figure out how many frames and epochs
duration = my.video.get_video_duration2(input_vfile)
frame_rate = my.video.get_video_params(input_vfile)[2]
total_frames = int(np.rint(duration * frame_rate))
if frame_stop is None:
frame_stop = total_frames
if frame_stop > total_frames:
print("too many frames requested, truncating")
frame_stop = total_frames
# Iterate over epochs
for start_epoch in range(frame_start, frame_stop, epoch_sz_frames):
# How many frames in this epoch
stop_epoch = np.min([frame_stop, start_epoch + epoch_sz_frames])
print("Epoch %d - %d" % (start_epoch, stop_epoch))
# Chunks
chunk_starts = np.arange(start_epoch, stop_epoch, chunk_sz_frames)
chunk_names = ['chunk%08d.tif' % nframe for nframe in chunk_starts]
whisk_names = ['chunk%08d.whiskers' % nframe for nframe in chunk_starts]
# read everything
# need to be able to crop here
print("Reading")
frames = video_utils.process_chunks_of_video(input_vfile,
frame_start=start_epoch, frame_stop=stop_epoch,
frames_per_chunk=chunk_sz_frames, # only necessary for chunk_func
frame_func=None, chunk_func=None,
verbose=False, finalize='listcomp')
# Dump frames into tiffs or lossless
print("Writing")
for n_whiski_chunk, chunk_name in enumerate(chunk_names):
print(n_whiski_chunk)
chunkstart = n_whiski_chunk * chunk_sz_frames
chunkstop = (n_whiski_chunk + 1) * chunk_sz_frames
chunk = frames[chunkstart:chunkstop]
if len(chunk) in [3, 4]:
print("WARNING: trace will fail on tiff stacks of length 3 or 4")
write_chunk(chunk, chunk_name, input_dir)
# Also write lossless and/or lossy monitor video here?
# would really only be useful if cropping applied
# trace each
print("Tracing")
pool = multiprocessing.Pool(n_trace_processes)
trace_res = pool.map(trace_chunk,
[os.path.join(input_dir, chunk_name)
for chunk_name in chunk_names])
pool.close()
# take measurements:
if measure:
print("Measuring")
pool = multiprocessing.Pool(n_trace_processes)
meas_res = pool.map(measure_chunk_star,
zip([os.path.join(input_dir, whisk_name)
for whisk_name in whisk_names],itertools.repeat(face)))
pool.close()
# stitch
print("Stitching")
for chunk_start, chunk_name in zip(chunk_starts, chunk_names):
# Append each chunk to the hdf5 file
fn = WhiskiWrap.utils.FileNamer.from_tiff_stack(
os.path.join(input_dir, chunk_name))
if not measure:
append_whiskers_to_hdf5(
whisk_filename=fn.whiskers,
h5_filename=h5_filename,
chunk_start=chunk_start)
elif measure:
append_whiskers_to_hdf5(
whisk_filename=fn.whiskers,
measurements_filename=fn.measurements,
h5_filename=h5_filename,
chunk_start=chunk_start)
def write_video_as_chunked_tiffs(input_reader, tiffs_to_trace_directory,
chunk_size=200, chunk_name_pattern='chunk%08d.tif',
stop_after_frame=None, monitor_video=None, timestamps_filename=None,
monitor_video_kwargs=None):
"""Write frames to disk as tiff stacks
input_reader : object providing .iter_frames() method and perhaps
also a .timestamps attribute. For instance, PFReader, or some
FFmpegReader object.
tiffs_to_trace_directory : where to store the chunked tiffs
stop_after_frame : to stop early
monitor_video : if not None, should be a filename to write a movie to
timestamps_filename : if not None, should be the name to write timestamps
monitor_video_kwargs : ffmpeg params
Returns: ChunkedTiffWriter object
"""
# Tiff writer
ctw = WhiskiWrap.ChunkedTiffWriter(tiffs_to_trace_directory,
chunk_size=chunk_size, chunk_name_pattern=chunk_name_pattern)
# FFmpeg writer is initalized after first frame
ffw = None
# Iterate over frames
for nframe, frame in enumerate(input_reader.iter_frames()):
# Stop early?
if stop_after_frame is not None and nframe >= stop_after_frame:
break
# Write to chunked tiff
ctw.write(frame)
# Optionally write to monitor video
if monitor_video is not None:
# Initialize ffw after first frame so we know the size
if ffw is None:
ffw = WhiskiWrap.FFmpegWriter(monitor_video,
frame_width=frame.shape[1], frame_height=frame.shape[0],
**monitor_video_kwargs)
ffw.write(frame)
# Finalize writers
ctw.close()
if ffw is not None:
ff_stdout, ff_stderr = ffw.close()
# Also write timestamps as numpy file
if hasattr(input_reader, 'timestamps') and timestamps_filename is not None:
timestamps = np.concatenate(input_reader.timestamps)
assert len(timestamps) >= ctw.frames_written
np.save(timestamps_filename, timestamps[:ctw.frames_written])
return ctw
def trace_chunked_tiffs(input_tiff_directory, h5_filename,
n_trace_processes=4, expectedrows=1000000,
):
"""Trace tiffs that have been written to disk in parallel and stitch.
input_tiff_directory : directory containing tiffs
h5_filename : output HDF5 file
n_trace_processes : how many simultaneous processes to use for tracing
expectedrows : used to set up hdf5 file
"""
WhiskiWrap.utils.probe_needed_commands()
# Setup the result file
setup_hdf5(h5_filename, expectedrows)
# The tiffs have been written, figure out which they are
tif_file_number_strings = my.misc.apply_and_filter_by_regex(
'^chunk(\d+).tif$', os.listdir(input_tiff_directory), sort=False)
tif_full_filenames = [
os.path.join(input_tiff_directory, 'chunk%s.tif' % fns)
for fns in tif_file_number_strings]
tif_file_numbers = list(map(int, tif_file_number_strings))
tif_ordering = np.argsort(tif_file_numbers)
tif_sorted_filenames = np.array(tif_full_filenames)[
tif_ordering]
tif_sorted_file_numbers = np.array(tif_file_numbers)[
tif_ordering]
# trace each
print("Tracing")
pool = multiprocessing.Pool(n_trace_processes)
trace_res = pool.map(trace_chunk, tif_sorted_filenames)
pool.close()
# stitch
print("Stitching")
for chunk_start, chunk_name in zip(tif_sorted_file_numbers, tif_sorted_filenames):
# Append each chunk to the hdf5 file
fn = WhiskiWrap.utils.FileNamer.from_tiff_stack(chunk_name)
append_whiskers_to_hdf5(
whisk_filename=fn.whiskers,
h5_filename=h5_filename,
chunk_start=chunk_start)
def interleaved_read_trace_and_measure(input_reader, tiffs_to_trace_directory,
sensitive=False,
chunk_size=200, chunk_name_pattern='chunk%08d.tif',
stop_after_frame=None, delete_tiffs=True,
timestamps_filename=None, monitor_video=None,
monitor_video_kwargs=None, write_monitor_ffmpeg_stderr_to_screen=False,
h5_filename=None, frame_func=None,
n_trace_processes=4, expectedrows=1000000,
verbose=True, skip_stitch=False, face='right'
):
"""Read, write, and trace each chunk, one at a time.
This is an alternative to first calling:
write_video_as_chunked_tiffs
And then calling
trace_chunked_tiffs
input_reader : Typically a PFReader or FFmpegReader
tiffs_to_trace_directory : Location to write the tiffs
sensitive: if False, use default. If True, lower MIN_SIGNAL
chunk_size : frames per chunk
chunk_name_pattern : how to name them
stop_after_frame : break early, for debugging
delete_tiffs : whether to delete tiffs after done tracing
timestamps_filename : Where to store the timestamps
Only vallid for PFReader input_reader
monitor_video : filename for a monitor video
If None, no monitor video will be written
monitor_video_kwargs : kwargs to pass to FFmpegWriter for monitor
write_monitor_ffmpeg_stderr_to_screen : whether to display
output from ffmpeg writing instance
h5_filename : hdf5 file to stitch whiskers information into
frame_func : function to apply to each frame
If 'invert', will apply 255 - frame
n_trace_processes : number of simultaneous trace processes
expectedrows : how to set up hdf5 file
verbose : verbose
skip_stitch : skip the stitching phase
Returns: dict
trace_pool_results : result of each call to trace
monitor_ff_stderr, monitor_ff_stdout : results from monitor
video ffmpeg instance
"""
## Set up kwargs
if monitor_video_kwargs is None:
monitor_video_kwargs = {}
if frame_func == 'invert':
frame_func = lambda frame: 255 - frame
# Check commands
WhiskiWrap.utils.probe_needed_commands()
## Initialize readers and writers
if verbose:
print("initalizing readers and writers")
# Tiff writer
ctw = WhiskiWrap.ChunkedTiffWriter(tiffs_to_trace_directory,
chunk_size=chunk_size, chunk_name_pattern=chunk_name_pattern)
# FFmpeg writer is initalized after first frame
ffw = None
# Setup the result file
if not skip_stitch:
setup_hdf5(h5_filename, expectedrows, measure=True)
# Copy the parameters files
copy_parameters_files(tiffs_to_trace_directory, sensitive=sensitive)
## Set up the worker pool
# Pool of trace workers
trace_pool = multiprocessing.Pool(n_trace_processes)
# Keep track of results
trace_pool_results = []
deleted_tiffs = []
def log_result(result):
trace_pool_results.append(result)
## Iterate over chunks
out_of_frames = False
nframe = 0
# Init the iterator outside of the loop so that it persists
iter_obj = input_reader.iter_frames()
while not out_of_frames:
# Get a chunk of frames
if verbose:
print("loading chunk of frames starting with ", nframe)
chunk_of_frames = []
for frame in iter_obj:
if frame_func is not None:
frame = frame_func(frame)
chunk_of_frames.append(frame)
nframe = nframe + 1
if stop_after_frame is not None and nframe >= stop_after_frame:
break
if len(chunk_of_frames) == chunk_size:
break
# Check if we ran out
if len(chunk_of_frames) != chunk_size:
out_of_frames = True
## Write tiffs
# We do this synchronously to ensure that it happens before
# the trace starts
for frame in chunk_of_frames:
ctw.write(frame)
# Make sure the chunk was written, in case this is the last one
# and we didn't reach chunk_size yet
if len(chunk_of_frames) != chunk_size:
ctw._write_chunk()
assert ctw.count_unwritten_frames() == 0
# Figure out which tiff file was just generated
tif_filename = ctw.chunknames_written[-1]
## Start trace
trace_pool.apply_async(trace_and_measure_chunk, args=(tif_filename, delete_tiffs, face),
callback=log_result)
## Determine whether we can delete any tiffs
#~ if delete_tiffs:
#~ tiffs_to_delete = [
#~ tpres['video_filename'] for tpres in trace_pool_results
#~ if tpres['video_filename'] not in deleted_tiffs]
#~ for filename in tiffs_to_delete:
#~ if verbose:
#~ print "deleting", filename
#~ os.remove(filename)
## Start monitor encode
# This is also synchronous, otherwise the input buffer might fill up
if monitor_video is not None:
if ffw is None:
ffw = WhiskiWrap.FFmpegWriter(monitor_video,
frame_width=frame.shape[1], frame_height=frame.shape[0],
write_stderr_to_screen=write_monitor_ffmpeg_stderr_to_screen,
**monitor_video_kwargs)
for frame in chunk_of_frames:
ffw.write(frame)
## Determine if we should pause
while len(ctw.chunknames_written) > len(trace_pool_results) + 2 * n_trace_processes:
print("waiting for tracing to catch up")
time.sleep(30)
## Wait for trace to complete
if verbose:
print("done with reading and writing, just waiting for tracing")
# Tell it no more jobs, so close when done
trace_pool.close()
# Wait for everything to finish
trace_pool.join()
## Error check the tifs that were processed
# Get the tifs we wrote, and the tifs we trace
written_chunks = sorted(ctw.chunknames_written)
traced_filenames = sorted([
res['video_filename'] for res in trace_pool_results])
# Check that they are the same
if not np.all(np.array(written_chunks) == np.array(traced_filenames)):
raise ValueError("not all chunks were traced")
## Extract the chunk numbers from the filenames
# The tiffs have been written, figure out which they are
split_traced_filenames = [os.path.split(fn)[1] for fn in traced_filenames]
tif_file_number_strings = my.misc.apply_and_filter_by_regex(
'^chunk(\d+).tif$', split_traced_filenames, sort=False)
tif_full_filenames = [
os.path.join(tiffs_to_trace_directory, 'chunk%s.tif' % fns)
for fns in tif_file_number_strings]
tif_file_numbers = list(map(int, tif_file_number_strings))
tif_ordering = np.argsort(tif_file_numbers)
tif_sorted_filenames = np.array(tif_full_filenames)[
tif_ordering]
tif_sorted_file_numbers = np.array(tif_file_numbers)[
tif_ordering]
# stitch
if not skip_stitch:
print("Stitching")
zobj = list(zip(tif_sorted_file_numbers, tif_sorted_filenames))
for chunk_start, chunk_name in zobj:
# Append each chunk to the hdf5 file
fn = WhiskiWrap.utils.FileNamer.from_tiff_stack(chunk_name)
append_whiskers_to_hdf5(
whisk_filename=fn.whiskers,
measurements_filename = fn.measurements,
h5_filename=h5_filename,
chunk_start=chunk_start)
# Finalize writers
ctw.close()
if ffw is not None:
ff_stdout, ff_stderr = ffw.close()
else:
ff_stdout, ff_stderr = None, None
# Also write timestamps as numpy file
if hasattr(input_reader, 'timestamps') and timestamps_filename is not None:
timestamps = np.concatenate(input_reader.timestamps)
assert len(timestamps) >= ctw.frames_written
np.save(timestamps_filename, timestamps[:ctw.frames_written])
return {'trace_pool_results': trace_pool_results,
'monitor_ff_stdout': ff_stdout,
'monitor_ff_stderr': ff_stderr,
'tif_sorted_file_numbers': tif_sorted_file_numbers,
'tif_sorted_filenames': tif_sorted_filenames,
}
def interleaved_reading_and_tracing(input_reader, tiffs_to_trace_directory,
sensitive=False,
chunk_size=200, chunk_name_pattern='chunk%08d.tif',
stop_after_frame=None, delete_tiffs=True,
timestamps_filename=None, monitor_video=None,
monitor_video_kwargs=None, write_monitor_ffmpeg_stderr_to_screen=False,
h5_filename=None, frame_func=None,
n_trace_processes=4, expectedrows=1000000,
verbose=True, skip_stitch=False,
):
"""Read, write, and trace each chunk, one at a time.
This is an alternative to first calling:
write_video_as_chunked_tiffs
And then calling
trace_chunked_tiffs
input_reader : Typically a PFReader or FFmpegReader
tiffs_to_trace_directory : Location to write the tiffs
sensitive: if False, use default. If True, lower MIN_SIGNAL
chunk_size : frames per chunk
chunk_name_pattern : how to name them
stop_after_frame : break early, for debugging
delete_tiffs : whether to delete tiffs after done tracing
timestamps_filename : Where to store the timestamps
Only vallid for PFReader input_reader
monitor_video : filename for a monitor video
If None, no monitor video will be written
monitor_video_kwargs : kwargs to pass to FFmpegWriter for monitor
write_monitor_ffmpeg_stderr_to_screen : whether to display
output from ffmpeg writing instance
h5_filename : hdf5 file to stitch whiskers information into
frame_func : function to apply to each frame
If 'invert', will apply 255 - frame
n_trace_processes : number of simultaneous trace processes
expectedrows : how to set up hdf5 file
verbose : verbose
skip_stitch : skip the stitching phase
Returns: dict
trace_pool_results : result of each call to trace
monitor_ff_stderr, monitor_ff_stdout : results from monitor
video ffmpeg instance
"""
## Set up kwargs
if monitor_video_kwargs is None:
monitor_video_kwargs = {}
if frame_func == 'invert':
frame_func = lambda frame: 255 - frame
# Check commands
WhiskiWrap.utils.probe_needed_commands()
## Initialize readers and writers
if verbose:
print("initalizing readers and writers")
# Tiff writer
ctw = WhiskiWrap.ChunkedTiffWriter(tiffs_to_trace_directory,
chunk_size=chunk_size, chunk_name_pattern=chunk_name_pattern)
# FFmpeg writer is initalized after first frame
ffw = None
# Setup the result file
if not skip_stitch:
setup_hdf5(h5_filename, expectedrows)
# Copy the parameters files
copy_parameters_files(tiffs_to_trace_directory, sensitive=sensitive)
## Set up the worker pool
# Pool of trace workers
trace_pool = multiprocessing.Pool(n_trace_processes)
# Keep track of results
trace_pool_results = []
deleted_tiffs = []
def log_result(result):
trace_pool_results.append(result)
## Iterate over chunks
out_of_frames = False
nframe = 0
# Init the iterator outside of the loop so that it persists
iter_obj = input_reader.iter_frames()
while not out_of_frames:
# Get a chunk of frames
if verbose:
print("loading chunk of frames starting with ", nframe)
chunk_of_frames = []
for frame in iter_obj:
if frame_func is not None:
frame = frame_func(frame)
chunk_of_frames.append(frame)
nframe = nframe + 1
if stop_after_frame is not None and nframe >= stop_after_frame:
break
if len(chunk_of_frames) == chunk_size:
break
# Check if we ran out
if len(chunk_of_frames) != chunk_size:
out_of_frames = True
## Write tiffs
# We do this synchronously to ensure that it happens before
# the trace starts
for frame in chunk_of_frames:
ctw.write(frame)
# Make sure the chunk was written, in case this is the last one
# and we didn't reach chunk_size yet
if len(chunk_of_frames) != chunk_size:
ctw._write_chunk()
assert ctw.count_unwritten_frames() == 0
# Figure out which tiff file was just generated
tif_filename = ctw.chunknames_written[-1]
## Start trace
trace_pool.apply_async(trace_chunk, args=(tif_filename, delete_tiffs),
callback=log_result)
## Determine whether we can delete any tiffs
#~ if delete_tiffs:
#~ tiffs_to_delete = [
#~ tpres['video_filename'] for tpres in trace_pool_results
#~ if tpres['video_filename'] not in deleted_tiffs]
#~ for filename in tiffs_to_delete:
#~ if verbose:
#~ print "deleting", filename
#~ os.remove(filename)
## Start monitor encode
# This is also synchronous, otherwise the input buffer might fill up
if monitor_video is not None:
if ffw is None:
ffw = WhiskiWrap.FFmpegWriter(monitor_video,
frame_width=frame.shape[1], frame_height=frame.shape[0],
write_stderr_to_screen=write_monitor_ffmpeg_stderr_to_screen,
**monitor_video_kwargs)
for frame in chunk_of_frames:
ffw.write(frame)
## Determine if we should pause
while len(ctw.chunknames_written) > len(trace_pool_results) + 2 * n_trace_processes:
print("waiting for tracing to catch up")
time.sleep(30)
## Wait for trace to complete
if verbose:
print("done with reading and writing, just waiting for tracing")
# Tell it no more jobs, so close when done
trace_pool.close()
# Wait for everything to finish
trace_pool.join()
## Error check the tifs that were processed
# Get the tifs we wrote, and the tifs we trace
written_chunks = sorted(ctw.chunknames_written)
traced_filenames = sorted([
res['video_filename'] for res in trace_pool_results])
# Check that they are the same
if not np.all(np.array(written_chunks) == np.array(traced_filenames)):
raise ValueError("not all chunks were traced")
## Extract the chunk numbers from the filenames
# The tiffs have been written, figure out which they are
split_traced_filenames = [os.path.split(fn)[1] for fn in traced_filenames]
tif_file_number_strings = my.misc.apply_and_filter_by_regex(
'^chunk(\d+).tif$', split_traced_filenames, sort=False)
tif_full_filenames = [
os.path.join(tiffs_to_trace_directory, 'chunk%s.tif' % fns)
for fns in tif_file_number_strings]
tif_file_numbers = list(map(int, tif_file_number_strings))
tif_ordering = np.argsort(tif_file_numbers)
tif_sorted_filenames = np.array(tif_full_filenames)[
tif_ordering]
tif_sorted_file_numbers = np.array(tif_file_numbers)[
tif_ordering]
# stitch
if not skip_stitch:
print("Stitching")
zobj = list(zip(tif_sorted_file_numbers, tif_sorted_filenames))
for chunk_start, chunk_name in zobj:
# Append each chunk to the hdf5 file
fn = WhiskiWrap.utils.FileNamer.from_tiff_stack(chunk_name)
append_whiskers_to_hdf5(
whisk_filename=fn.whiskers,
h5_filename=h5_filename,
chunk_start=chunk_start)
# Finalize writers
ctw.close()
if ffw is not None:
ff_stdout, ff_stderr = ffw.close()
else:
ff_stdout, ff_stderr = None, None
# Also write timestamps as numpy file
if hasattr(input_reader, 'timestamps') and timestamps_filename is not None:
timestamps = np.concatenate(input_reader.timestamps)
assert len(timestamps) >= ctw.frames_written