Debian Codegraph @

planetary_system_stacker/pss_console.py

raw symbols SCIP
1 from argparse import ArgumentParser, ArgumentTypeError
2 from time import sleep
3 from glob import glob
4
5 from PyQt5 import QtCore
6
7 from configuration import Configuration
8 from exceptions import InternalError
9 from job_editor import Job
10 from miscellaneous import Miscellaneous
11 from workflow import Workflow
12
13 # Definition of data types, including value bounds, used in command line argument parsing.
14 def ram_size_type(x):
15 try:
16 x = int(x)
17 except:
18 raise ArgumentTypeError("Maximum RAM size must be an integer > 0")
19 if x < 1:
20 raise ArgumentTypeError("Maximum RAM size must be an integer > 0")
21 return x
22
23
24 def noise_type(x):
25 x = int(x)
26 if not 0 <= x <= 11:
27 raise ArgumentTypeError("Noise level must be between 0 and 11")
28 return x
29
30
31 def stab_size_type(x):
32 x = int(x)
33 if not 5 <= x <= 80:
34 raise ArgumentTypeError("Stabilization patch size must be between 5% and 80%")
35 return x
36
37
38 def stab_sw_type(x):
39 x = int(x)
40 if not 5 <= x <= 150:
41 raise ArgumentTypeError(
42 "Stabilization search width must be between 5 and 150 pixels")
43 return x
44
45
46 def rf_percent_type(x):
47 x = int(x)
48 if not 3 <= x <= 30:
49 raise ArgumentTypeError(
50 "Percentage of best frames for reference frame computation must be between 3% and 30%")
51 return x
52
53
54 def align_box_width_type(x):
55 x = int(x)
56 if not 20 <= x <= 140:
57 raise ArgumentTypeError(
58 "Alignment point box width must be between 20 and 140 pixels")
59 return x
60
61
62 def align_search_width_type(x):
63 x = int(x)
64 if not 6 <= x <= 30:
65 raise ArgumentTypeError(
66 "Alignment point search width must be between 6 and 30 pixels")
67 return x
68
69
70 def align_min_struct_type(x):
71 x = float(x)
72 if not 0.01 <= x <= 0.30:
73 raise ArgumentTypeError(
74 "Alignment point minimum structure must be between 0.01 and 0.30")
75 return x
76
77
78 def align_min_bright_type(x):
79 x = int(x)
80 if not 2 <= x <= 50:
81 raise ArgumentTypeError(
82 "Alignment point minimum brightness must be between 2 and 50")
83 return x
84
85
86 def stack_percent_type(x):
87 x = int(x)
88 if not 1 <= x <= 100:
89 raise ArgumentTypeError(
90 "Percentage of best frames to be stacked must be between 1 and 100")
91 return x
92
93
94 def stack_number_type(x):
95 x = int(x)
96 if not 1 <= x:
97 raise ArgumentTypeError(
98 "Number of best frames to be stacked must be greater or equal 1")
99 return x
100
101
102 def normalize_bco_type(x):
103 x = int(x)
104 if not 0 <= x <= 40:
105 raise ArgumentTypeError(
106 "Normalization black cut-off must be between 0 and 40")
107 return x
108
109
110 class PssConsole(QtCore.QObject):
111 """
112 This class replaces the class PlanetarySystemStacker if the program is started from the
113 command line. In this case no GUI activity is created, and there is no interactive mode.
114 """
115
116 # Define signals which trigger activities on the workflow thread.
117 signal_load_master_dark = QtCore.pyqtSignal(str)
118 signal_load_master_flat = QtCore.pyqtSignal(str)
119 signal_frames = QtCore.pyqtSignal(object)
120 signal_rank_frames = QtCore.pyqtSignal(bool)
121 signal_align_frames = QtCore.pyqtSignal(int, int, int, int)
122 signal_set_roi = QtCore.pyqtSignal(int, int, int, int)
123 signal_set_alignment_points = QtCore.pyqtSignal()
124 signal_compute_frame_qualities = QtCore.pyqtSignal()
125 signal_stack_frames = QtCore.pyqtSignal()
126 signal_save_stacked_image = QtCore.pyqtSignal()
127
128 def __init__(self, parent=None):
129 super(PssConsole, self).__init__(parent)
130
131 # Create the configuration object and modify it as specified in command line arguments.
132 self.setup_configuration()
133
134 # Start the workflow.
135 self.work_next_task("Read frames")
136
137 def setup_configuration(self):
138 """
139 Parse the command line arguments, initialize the configuration object and update
140 configuration parameters with values passed via command line arguments.
141
142 :return: -
143 """
144 parser = ArgumentParser()
145 parser.add_argument("job_input", nargs='+', help="input video files or still image folders")
146
147 parser.add_argument("-p", "--protocol", action="store_true",
148 help="Store protocol with results")
149 parser.add_argument("--protocol_detail", type=int, choices=[0, 1, 2], default=1,
150 help="Protocol detail level")
151 parser.add_argument("-b", "--buffering_level", choices=["auto", "0", "1", "2", "3", "4"],
152 default="auto", help="Buffering level")
153 parser.add_argument("-r", "--ram_size", type=ram_size_type, default=-1,
154 help="Maximum RAM for this job (GBytes)")
155 parser.add_argument("--out_format", choices=["png", "tiff", "fits"], default="png",
156 help="Image format for output")
157 parser.add_argument("--name_add_f", action="store_true",
158 help="Add number of stacked frames to output file name")
159 parser.add_argument("--name_add_p", action="store_true",
160 help="Add percentage of stacked frames to output file name")
161 parser.add_argument("--name_add_apb", action="store_true",
162 help="Add alignment point box size (pixels) to output file name")
163 parser.add_argument("--name_add_apn", action="store_true",
164 help="Add number of alignment points to output file name")
165
166 parser.add_argument("--debayering",
167 choices=["Auto detect color", "Grayscale", "RGB", "RGB", "BGR",
168 "Force Bayer RGGB", "Force Bayer GRBG",
169 "Force Bayer GBRG", "Force Bayer BGGR"],
170 default="Auto detect color", help="Debayering option")
171 parser.add_argument("--debayer_method",
172 choices=["Bilinear", "Variable Number of Gradients",
173 "Edge Aware"],
174 default="Bilinear", help="Debayering method to be used")
175 parser.add_argument("--noise", type=noise_type, default=7,
176 help="Noise level (add Gaussian blur)")
177 parser.add_argument("-m", "--stab_mode", choices=["Surface", "Planet"], default="Surface",
178 help="Frame stabilization mode")
179 parser.add_argument("--stab_size", type=stab_size_type, default=33,
180 help="Stabilization patch size (%% of frame)")
181 parser.add_argument("--stab_sw", type=stab_sw_type, default=34,
182 help="Stabilization search width (pixels)")
183 parser.add_argument("--rf_percent", type=rf_percent_type, default=5,
184 help="Percentage of best frames for reference frame computation")
185 parser.add_argument("--fast_changing_object", action="store_true",
186 help="The object is changing fast during video time span (e.g. Jupiter")
187 parser.add_argument("-d", "--dark", help="Image file for dark frame correction")
188 parser.add_argument("-f", "--flat", help="Image file for flat frame correction")
189
190 parser.add_argument("-a", "--align_box_width", type=align_box_width_type, default=48,
191 help="Alignment point box width (pixels)")
192 parser.add_argument("-w", "--align_search_width", type=align_search_width_type, default=14,
193 help="Alignment point search width (pixels)")
194 parser.add_argument("--align_min_struct", type=align_min_struct_type, default=0.04,
195 help="Alignment point minimum structure")
196 parser.add_argument("--align_min_bright", type=align_min_bright_type, default=10,
197 help="Alignment point minimum brightness")
198
199 parser.add_argument("-s", "--stack_percent", type=stack_percent_type, default=10,
200 help="Percentage of best frames to be stacked")
201 parser.add_argument("--stack_number", type=stack_number_type,
202 help="Number of best frames to be stacked")
203 parser.add_argument("-n", "--normalize_bright", action="store_true",
204 help="Normalize frame brightness")
205 parser.add_argument("--normalize_bco", type=normalize_bco_type, default=15,
206 help="Normalization black cut-off")
207 parser.add_argument("--drizzle", choices=["Off", "1.5x", "2x", "3x"], default="Off",
208 help="Drizzle factor (Off, 1.5x, 2x, 3x)")
209
210 arguments = parser.parse_args()
211 # self.print_arguments(arguments)
212
213 # Create and initialize the configuration object. The configuration stored in the .ini file
214 # in the user's home directory is ignored in this case. Modifications to standard values
215 # come as command line arguments.
216 self.configuration = Configuration()
217 self.configuration.initialize_configuration(read_from_file=False)
218
219 # In the standard configuration postprocessing is included in the workflow. This does not
220 # make sense in command line mode.
221 self.configuration.global_parameters_include_postprocessing = False
222
223 # Modify the standard configuration as specified in the command line arguments.
224 self.configuration.global_parameters_store_protocol_with_result = arguments.protocol
225 self.configuration.global_parameters_protocol_level = arguments.protocol_detail
226 if arguments.ram_size == -1:
227 self.configuration.global_parameters_maximum_memory_active = False
228 if arguments.buffering_level == "auto":
229 self.configuration.global_parameters_buffering_level = -1
230 else:
231 self.configuration.global_parameters_buffering_level = int(arguments.buffering_level)
232 else:
233 self.configuration.global_parameters_buffering_level = -1
234 self.configuration.global_parameters_maximum_memory_active = True
235 self.configuration.global_parameters_maximum_memory_amount = arguments.ram_size
236
237 self.configuration.global_parameters_image_format = arguments.out_format
238 self.configuration.global_parameters_parameters_in_filename = arguments.name_add_f or \
239 arguments.name_add_p or arguments.name_add_apb or arguments.name_add_apn
240 self.configuration.global_parameters_stack_number_frames = arguments.name_add_f
241 self.configuration.global_parameters_stack_percent_frames = arguments.name_add_p
242 self.configuration.global_parameters_ap_box_size = arguments.name_add_apb
243 self.configuration.global_parameters_ap_number = arguments.name_add_apn
244
245 self.configuration.frames_debayering_default = arguments.debayering
246 self.configuration.frames_debayering_method = arguments.debayer_method
247 self.configuration.frames_gauss_width = arguments.noise
248
249 self.configuration.align_frames_mode = arguments.stab_mode
250 self.configuration.align_frames_rectangle_scale_factor = 100. / arguments.stab_size
251 self.configuration.align_frames_search_width = arguments.stab_sw
252 self.configuration.align_frames_average_frame_percent = arguments.rf_percent
253 self.configuration.align_frames_fast_changing_object = arguments.fast_changing_object
254
255 self.configuration.alignment_points_half_box_width = int(
256 round(arguments.align_box_width / 2))
257 self.configuration.alignment_points_search_width = arguments.align_search_width
258 self.configuration.alignment_points_structure_threshold = arguments.align_min_struct
259 self.configuration.alignment_points_brightness_threshold = arguments.align_min_bright
260
261 self.configuration.alignment_points_frame_percent = arguments.stack_percent
262 self.configuration.alignment_points_frame_number = -1
263
264 # If the number of frames to be stacked is given, it has precedence over the percentage.
265 if arguments.stack_number is not None:
266 self.configuration.alignment_points_frame_number = arguments.stack_number
267 self.configuration.alignment_points_frame_percent = -1
268
269 self.configuration.frames_normalization = arguments.normalize_bright
270 self.configuration.frames_normalization_threshold = arguments.normalize_bco
271 self.configuration.stack_frames_drizzle_factor_string = arguments.drizzle
272
273 # Re-compute derived parameters after the configuration was changed.
274 self.configuration.set_derived_parameters()
275
276 # Create the workflow thread and start it.
277 self.thread = QtCore.QThread()
278 self.workflow = Workflow(self)
279 self.workflow.setParent(None)
280 self.workflow.moveToThread(self.thread)
281 self.workflow.calibration.report_calibration_error_signal.connect(
282 self.report_calibration_error)
283 self.workflow.work_next_task_signal.connect(self.work_next_task)
284 self.workflow.report_error_signal.connect(self.report_error)
285 self.workflow.abort_job_signal.connect(self.next_job_after_error)
286 self.thread.start()
287
288 # Connect signals to start activities on the workflow thread (e.g. in method
289 # "work_next_task").
290 self.signal_load_master_dark.connect(self.workflow.calibration.load_master_dark)
291 self.signal_load_master_flat.connect(self.workflow.calibration.load_master_flat)
292 self.signal_frames.connect(self.workflow.execute_frames)
293 self.signal_rank_frames.connect(self.workflow.execute_rank_frames)
294 self.signal_align_frames.connect(self.workflow.execute_align_frames)
295 self.signal_set_roi.connect(self.workflow.execute_set_roi)
296 self.signal_set_alignment_points.connect(self.workflow.execute_set_alignment_points)
297 self.signal_compute_frame_qualities.connect(
298 self.workflow.execute_compute_frame_qualities)
299 self.signal_stack_frames.connect(self.workflow.execute_stack_frames)
300 self.signal_save_stacked_image.connect(self.workflow.execute_save_stacked_image)
301
302 # Set "automatic" to True. There is no interactive mode in this case.
303 self.automatic = True
304
305 # Create the job objects using the names passed as positional arguments.
306 self.jobs = []
307 for name in [f for name in arguments.job_input for f in glob(name)]:
308 try:
309 job = Job(name)
310
311 # Test if the path specifies a stacking job.
312 if job.type == 'video' or job.type == 'image':
313 # Override the "Auto detect color" value of the "Job" object with the
314 # command line value.
315 job.bayer_option_selected = self.configuration.frames_debayering_default
316 self.jobs.append(job)
317 else:
318 if self.configuration.global_parameters_protocol_level > 0:
319 Miscellaneous.protocol(
320 "Error: '" + name + "' does not contain valid input for a stacking job,"
321 " continune with next job.\n",
322 self.workflow.attached_log_file)
323 except InternalError:
324 if self.configuration.global_parameters_protocol_level > 0:
325 Miscellaneous.protocol(
326 "Error: '" + name + "' does not contain valid input for a stacking job,"
327 " continune with next job.\n",
328 self.workflow.attached_log_file)
329
330 self.job_number = len(self.jobs)
331 if self.job_number == 0:
332 if self.configuration.global_parameters_protocol_level > 0:
333 Miscellaneous.protocol(
334 "Error: No valid job specified, execution halted.",
335 self.workflow.attached_log_file)
336 self.stop_execution()
337
338 self.job_index = 0
339
340 # If a dark frame was specified, load it.
341 if arguments.dark:
342 if self.configuration.global_parameters_protocol_level > 0:
343 Miscellaneous.protocol("+++ Loading master dark frame +++",
344 self.workflow.attached_log_file)
345 self.signal_load_master_dark.emit(arguments.dark)
346
347 # If a flat frame was specified, load it.
348 if arguments.flat:
349 if self.configuration.global_parameters_protocol_level > 0:
350 Miscellaneous.protocol("+++ Loading master flat frame +++",
351 self.workflow.attached_log_file)
352 self.signal_load_master_flat.emit(arguments.flat)
353
354 @QtCore.pyqtSlot(str)
355 def report_calibration_error(self, message):
356 if self.configuration.global_parameters_protocol_level > 0:
357 Miscellaneous.protocol(" " + message,
358 self.workflow.attached_log_file, precede_with_timestamp=False)
359
360 @QtCore.pyqtSlot(str)
361 def report_error(self, message):
362 """
363 This method is triggered by the workflow thread via a signal when an error is to be
364 reported. Depending on the protocol level, the error message is written to the
365 protocol (file).
366
367 :param message: Error message to be displayed
368 :return: -
369 """
370
371 if self.configuration.global_parameters_protocol_level > 0:
372 Miscellaneous.protocol(message + "\n", self.workflow.attached_log_file)
373
374 @QtCore.pyqtSlot(str)
375 def next_job_after_error(self, message):
376 """
377 This method is triggered by the workflow thread via a signal when an error causes a job to
378 be aborted. Depending on the protocol level, the error message is written to the
379 protocol (file).
380
381 :param message: Error message to be displayed
382 :return: -
383 """
384
385 # Report the error.
386 self.report_error(message)
387
388 # Abort the current job and go to the next one.
389 self.work_next_task("Next job")
390
391 def work_next_task(self, next_activity):
392 """
393 This is the central place where all activities are scheduled. Depending on the
394 "next_activity" chosen, the appropriate activity is started on the workflow thread.
395
396 :param next_activity: Activity to be performed next.
397 :return: -
398 """
399
400 # Make sure not to process an empty job list, or a job index out of range.
401 if not self.jobs or self.job_index >= self.job_number:
402 return
403
404 self.activity = next_activity
405
406 # Start workflow activities. When a workflow method terminates, it invokes this method on
407 # the GUI thread, with "next_activity" denoting the next step in the processing chain.
408 if self.activity == "Read frames":
409
410 # For the first activity (reading all frames from the file system) there is no
411 # GUI interaction. Start the workflow action immediately.
412 self.signal_frames.emit(self.jobs[self.job_index])
413
414 elif self.activity == "Rank frames":
415
416 # In batch mode no frames can be dropped in the user dialog.
417 update_index_translation_table = False
418 # Now start the corresponding action on the workflow thread.
419 self.signal_rank_frames.emit(update_index_translation_table)
420
421 elif self.activity == "Select frames":
422
423 # The dialog to exclude frames is not to be called. Go to frames alignment
424 # immediately.
425 self.signal_align_frames.emit(0, 0, 0, 0)
426
427 elif self.activity == "Select stack size":
428
429 # In automatic mode, nothing is to be done in the workflow thread. Start the next
430 # activity on the main thread immediately.
431 self.workflow.work_next_task_signal.emit("Set ROI")
432
433 elif self.activity == "Set ROI":
434
435 # If all index bounds are set to zero, no ROI is selected.
436 self.signal_set_roi.emit(0, 0, 0, 0)
437
438 elif self.activity == "Set alignment points":
439
440 # In automatic mode, compute the AP grid automatically in the workflow thread. In this
441 # case, the AlignmentPoints object is created there as well.
442 self.signal_set_alignment_points.emit()
443
444 elif self.activity == "Compute frame qualities":
445 self.signal_compute_frame_qualities.emit()
446
447 elif self.activity == "Stack frames":
448 self.signal_stack_frames.emit()
449
450 elif self.activity == "Save stacked image":
451 self.signal_save_stacked_image.emit()
452
453 elif self.activity == "Next job":
454 self.job_index += 1
455 if self.job_index < self.job_number:
456 # If the end of the queue is not reached yet, start with reading frames of next job.
457 self.activity = "Read frames"
458 self.signal_frames.emit(self.jobs[self.job_index])
459 else:
460 self.stop_execution()
461
462 def print_arguments(self, arguments):
463 """
464 This is an auxiliary method for debugging. It prints all arguments passed to the program.
465
466 :param arguments: Arguments object created by the ArgumentParser
467 :return: -
468 """
469
470 print("Jobs: " + str(arguments.job_input))
471 print("Store protocol with results: " + str(arguments.protocol))
472 print("Protocol detail level: " + str(arguments.protocol_detail))
473 print("Buffering level: " + str(arguments.buffering_level))
474 print("Maximum RAM size: " + str(arguments.ram_size))
475 print("Image format for output: " + arguments.out_format)
476 print("Add number of stacked frames to output file name: " + str(arguments.name_add_f))
477 print("Add percentage of stacked frames to output file name: " + str(arguments.name_add_p))
478 print(
479 "Add alignment point box size (pixels) to output file name: " + str(
480 arguments.name_add_apb))
481 print("Add number of alignment points to output file name: " + str(arguments.name_add_apn))
482 print("")
483 print("Debayering option: " + arguments.debayering)
484 print("Debayering method: " + arguments.debayer_method)
485 print("Noise level: " + str(arguments.noise))
486 print("Frame stabilization mode: " + arguments.stab_mode)
487 print("Stabilization patch size (% of frame): " + str(arguments.stab_size))
488 print("Stabilization search width (pixels): " + str(arguments.stab_sw))
489 print("Percentage of best frames for reference frame computation: " + str(
490 arguments.rf_percent))
491 if arguments.dark:
492 print("Image file for dark frame correction: " + arguments.dark)
493 if arguments.flat:
494 print("Image file for flat frame correction: " + arguments.flat)
495 print("")
496 print("Alignment point box width (pixels): " + str(arguments.align_box_width))
497 print("Alignment point search width (pixels): " + str(arguments.align_search_width))
498 print("Alignment point minimum structure: " + str(arguments.align_min_struct))
499 print("Alignment point minimum brightness: " + str(arguments.align_min_bright))
500 print("")
501 print("Percentage of best frames to be stacked: " + str(arguments.stack_percent))
502 print("Number of best frames to be stacked: " + str(arguments.stack_number))
503 print("Normalize frame brightness: " + str(arguments.normalize_bright))
504 print("Normalization black cut-off: " + str(arguments.normalize_bco))
505
506 def stop_execution(self):
507 """
508 Halt the application. (There might be a more elegant way to do this!)
509
510 :return: -
511 """
512 # Wait a little before exiting, so that output buffers can be purged.
513 sleep(0.2)
514 quit(0)