comparison spyboat_cli.py @ 0:76733d05d8ef draft

"planemo upload for repository https://github.com/galaxyproject/tools-iuc/tree/master/packages/spyboat commit 5c60a414c785246371beac23ce52d8bbab3602d1"
author iuc
date Sat, 28 Nov 2020 13:45:34 +0000
parents
children 639d2031d998
comparison
equal deleted inserted replaced
-1:000000000000 0:76733d05d8ef
1 #!/usr/bin/env python
2
3 # Gets interfaced by Galaxy or can be used for bash scripting
4 import argparse
5 import logging
6 import os
7 import sys
8
9 import output_report
10 import spyboat
11 from numpy import float32
12 from skimage import io
13
14 logging.basicConfig(level=logging.INFO, stream=sys.stdout, force=True)
15 logger = logging.getLogger('spyboat-cli')
16
17 # ----------command line parameters ---------------
18
19 parser = argparse.ArgumentParser(description='Process some arguments.')
20
21 # I/O
22 parser.add_argument('--input_path', help="Input movie location", required=True)
23 parser.add_argument('--phase_out', help='Phase output file name', required=False)
24 parser.add_argument('--period_out', help='Period output file name', required=False)
25 parser.add_argument('--power_out', help='Power output file name', required=False)
26 parser.add_argument('--amplitude_out', help='Amplitude output file name', required=False)
27 parser.add_argument('--preprocessed_out', help="Preprocessed-input output file name", required=False)
28
29 # (Optional) Multiprocessing
30
31 parser.add_argument('--ncpu', help='Number of processors to use',
32 required=False, type=int, default=1)
33
34 # Optional spatial downsampling
35 parser.add_argument('--rescale_factor', help='Rescale the image by a factor given in %%, None means no rescaling',
36 required=False, type=int)
37 # Optional Gaussian smoothing
38 parser.add_argument('--gauss_sigma', help='Gaussian smoothing parameter, None means no smoothing', required=False,
39 type=float)
40
41 # Wavelet Analysis Parameters
42 parser.add_argument('--dt', help='Sampling interval', required=True, type=float)
43 parser.add_argument('--Tmin', help='Smallest period', required=True, type=float)
44 parser.add_argument('--Tmax', help='Biggest period', required=True, type=float)
45 parser.add_argument('--nT', help='Number of periods to scan for', required=True, type=int)
46
47 parser.add_argument('--Tcutoff', help='Sinc cut-off period, disables detrending if not set', required=False, type=float)
48 parser.add_argument('--win_size', help='Sliding window size for amplitude normalization, None means no normalization',
49 required=False, type=float)
50
51 # Optional masking
52 parser.add_argument('--masking', help="Set to either 'dynamic', 'static' or 'None' which is the default",
53 default='None', required=False, type=str)
54
55 parser.add_argument('--mask_frame',
56 help="The frame of the input movie to create a static mask from, needs masking set to 'static'",
57 required=False, type=int)
58
59 parser.add_argument('--mask_thresh',
60 help='The threshold of the mask, all pixels with less than this value get masked (if masking enabled).',
61 required=False, type=float,
62 default=0)
63
64 # output html report/snapshots
65 parser.add_argument('--html_fname', help="Name of the html report.",
66 default='OutputReport.html', required=False, type=str)
67
68 parser.add_argument('--report_img_path', help="For the html report, to be set in Galaxy. Without galaxy leave at cwd!",
69 default='.', required=False, type=str)
70
71 parser.add_argument('--version', action='version', version='0.1.0')
72
73 arguments = parser.parse_args()
74
75 logger.info("Received following arguments:")
76 for arg in vars(arguments):
77 logger.info(f'{arg} -> {getattr(arguments, arg)}')
78
79 # ------------Read the input----------------------------------------
80 try:
81 movie = spyboat.open_tif(arguments.input_path)
82 except FileNotFoundError:
83 logger.critical(f"Couldn't open {arguments.input_path}, check movie storage directory!")
84 sys.exit(1)
85 # problems get logged in 'open_tif'
86 if movie is None:
87 sys.exit(1)
88 # -------- Do (optional) spatial downsampling ---------------------------
89
90 scale_factor = arguments.rescale_factor
91
92 # defaults to None
93 if not scale_factor:
94 logger.info('No downsampling requested..')
95
96 elif 0 < scale_factor < 100:
97 logger.info(f'Downsampling the movie to {scale_factor:d}% of its original size..')
98 movie = spyboat.down_sample(movie, scale_factor / 100)
99 else:
100 raise ValueError('Scale factor must be between 0 and 100!')
101
102 # -------- Do (optional) pre-smoothing -------------------------
103 # note that downsampling already is a smoothing operation..
104
105 # check if pre-smoothing requested
106 if not arguments.gauss_sigma:
107 logger.info('No pre-smoothing requested..')
108 else:
109 logger.info(f'Pre-smoothing the movie with Gaussians, sigma = {arguments.gauss_sigma:.2f}..')
110
111 movie = spyboat.gaussian_blur(movie, arguments.gauss_sigma)
112
113 # ----- Set up Masking before processing ----
114
115 mask = None
116 if arguments.masking == 'static':
117 if not arguments.mask_frame:
118 logger.critical("Frame number for static masking is missing!")
119 sys.exit(1)
120
121 if (arguments.mask_frame > movie.shape[0]) or (arguments.mask_frame < 0):
122 logger.critical(f'Requested frame does not exist, input only has {movie.shape[0]} frames.. exiting')
123 sys.exit(1)
124
125 else:
126 logger.info(f'Creating static mask from frame {arguments.mask_frame} with threshold {arguments.mask_thresh}')
127 mask = spyboat.create_static_mask(movie, arguments.mask_frame,
128 arguments.mask_thresh)
129 elif arguments.masking == 'dynamic':
130 logger.info(f'Creating dynamic mask with threshold {arguments.mask_thresh}')
131 mask = spyboat.create_dynamic_mask(movie, arguments.mask_thresh)
132
133 else:
134 logger.info('No masking requested..')
135
136 # ------ Retrieve wavelet parameters ---------------------------
137
138 Wkwargs = {'dt': arguments.dt,
139 'Tmin': arguments.Tmin,
140 'Tmax': arguments.Tmax,
141 'nT': arguments.nT,
142 'T_c': arguments.Tcutoff, # defaults to None
143 'win_size': arguments.win_size # defaults to None
144 }
145
146 # --- start parallel processing ---
147
148 results = spyboat.run_parallel(movie, arguments.ncpu, **Wkwargs)
149
150 # --- masking? ---
151
152 if mask is not None:
153 # mask all output movies (in place!)
154 for key in results:
155 logger.info(f'Masking {key}')
156 spyboat.apply_mask(results[key], mask, fill_value=-1)
157
158 # --- Produce Output HTML Report Figures/png's ---
159
160 # create the directory, yes we have to do that ourselves :)
161 # galaxy then magically renders the html from that directory
162 try:
163
164 if arguments.report_img_path != '.':
165 logger.info(f'Creating report directory {arguments.report_img_path}')
166 os.mkdir(arguments.report_img_path)
167
168 # 4 snapshots each
169 Nsnap = 7
170 NFrames = movie.shape[0]
171 # show only frames at least one Tmin
172 # away from the edge (-effects)
173 start_frame = int(Wkwargs['Tmin'] / Wkwargs['dt'])
174
175 if (start_frame > NFrames // 2):
176 logger.warning("Smallest period already is larger than half the observation time!")
177 # set to 0 in this case
178 start_frame = 0
179
180 frame_increment = int((NFrames - 2 * start_frame) / Nsnap)
181 snapshot_frames = range(start_frame, NFrames - start_frame, frame_increment)
182
183 for snapshot_frame in snapshot_frames:
184 output_report.produce_snapshots(movie, results, snapshot_frame, Wkwargs, img_path=arguments.report_img_path)
185
186 output_report.produce_distr_plots(results, Wkwargs, img_path=arguments.report_img_path)
187
188 output_report.create_html(snapshot_frames, arguments.html_fname)
189
190 except FileExistsError as e:
191 logger.critical(f"Could not create html report directory: {repr(e)}")
192
193 # --- save out result movies ---
194
195 # None means output is filtered from galaxy settings
196 if arguments.phase_out is not None:
197 # save phase movie
198 io.imsave(arguments.phase_out, results['phase'], plugin="tifffile")
199 logger.info(f'Written phase to {arguments.phase_out}')
200 if arguments.period_out is not None:
201 # save period movie
202 io.imsave(arguments.period_out, results['period'], plugin="tifffile")
203 logger.info(f'Written period to {arguments.period_out}')
204 if arguments.power_out is not None:
205 # save power movie
206 io.imsave(arguments.power_out, results['power'], plugin="tifffile")
207 logger.info(f'Written power to {arguments.power_out}')
208 if arguments.amplitude_out is not None:
209 # save amplitude movie
210 io.imsave(arguments.amplitude_out, results['amplitude'], plugin="tifffile")
211 logger.info(f'Written amplitude to {arguments.amplitude_out}')
212
213 # save out the probably pre-processed (scaled and blurred) input movie for
214 # direct comparison to results and coordinate mapping etc.
215 if arguments.preprocessed_out is not None:
216 io.imsave(arguments.preprocessed_out, movie.astype(float32), plugin='tifffile')
217 logger.info(f'Written preprocessed to {arguments.preprocessed_out}')