comparison plot_smb_tiff.py @ 0:9f331fb5be2c draft

planemo upload for repository https://github.com/rolfverberg/galaxytools commit ec74ae97e0ca220d04cb668baa656358abf190e9
author rv43
date Fri, 10 Mar 2023 20:57:05 +0000
parents
children 6be076b081c4
comparison
equal deleted inserted replaced
-1:000000000000 0:9f331fb5be2c
1 #!/usr/bin/env python3
2
3 import logging
4
5 import argparse
6 import matplotlib.pyplot as plt
7 import os
8 #from re import compile as re_compile
9 import sys
10
11 def __main__():
12
13 # Parse command line arguments
14 parser = argparse.ArgumentParser(
15 description='Plot an image for the SMB schema')
16 parser.add_argument('--cycle',
17 required=True,
18 help='''Run cycle.''')
19 parser.add_argument('--station',
20 required=True,
21 choices=['id1a3', 'id3a'],
22 help='''Beamline station.''')
23 parser.add_argument('--btr',
24 required=True,
25 help='''BTR.''')
26 parser.add_argument('--sample',
27 required=True,
28 help='''Sample name.''')
29 parser.add_argument('--scan_number',
30 default=-1,
31 type=int,
32 help='SPEC scan number')
33 parser.add_argument('--image_index',
34 default=0,
35 type=int,
36 help='Image index relative the first')
37 parser.add_argument('-l', '--log',
38 # type=argparse.FileType('w'),
39 default=sys.stdout,
40 help='Logging stream or filename')
41 parser.add_argument('--log_level',
42 choices=logging._nameToLevel.keys(),
43 default='INFO',
44 help='''Specify a preferred logging level.''')
45 args = parser.parse_args()
46
47 # Set log configuration
48 # When logging to file, the stdout log level defaults to WARNING
49 logging_format = '%(asctime)s : %(levelname)s - %(module)s : %(funcName)s - %(message)s'
50 level = logging.getLevelName(args.log_level)
51 if args.log is sys.stdout:
52 logging.basicConfig(format=logging_format, level=level, force=True,
53 handlers=[logging.StreamHandler()])
54 else:
55 if isinstance(args.log, str):
56 logging.basicConfig(filename=f'{args.log}', filemode='w',
57 format=logging_format, level=level, force=True)
58 elif isinstance(args.log, io.TextIOWrapper):
59 logging.basicConfig(filemode='w', format=logging_format, level=level,
60 stream=args.log, force=True)
61 else:
62 raise(ValueError(f'Invalid argument --log: {args.log}'))
63 stream_handler = logging.StreamHandler()
64 logging.getLogger().addHandler(stream_handler)
65 stream_handler.setLevel(logging.WARNING)
66 stream_handler.setFormatter(logging.Formatter(logging_format))
67
68 # Log command line arguments
69 logging.info(f'cycle = {args.cycle}')
70 logging.info(f'station = {args.station}')
71 logging.info(f'btr = {args.btr}')
72 logging.info(f'sample = {args.sample}')
73 logging.info(f'scan_number = {args.scan_number}')
74 logging.info(f'image_index = {args.image_index}')
75 logging.debug(f'log = {args.log}')
76 logging.debug(f'is log stdout? {args.log is sys.stdout}')
77
78 # Check input parameters
79 if args.image_index < 0:
80 raise ValueError(f'Invalid "image_index" parameter ({args.image_index})')
81
82 # Check work directory
83 workdir = f'/nfs/chess/{args.station}/{args.cycle}/{args.btr}/{args.sample}'
84 logging.info(f'workdir = {workdir}')
85 if not os.path.isdir(workdir):
86 raise ValueError('Invalid work directory: {workdir}')
87
88 # Get all available scan_numbers
89 scan_numbers = [int(v) for v in os.listdir(workdir) if v.isdigit() and
90 os.path.isdir(f'{workdir}/{v}')]
91
92 if args.scan_number == -1:
93 # Pick lowest scan_number with image files
94 image_file = None
95 for scan_number in sorted(scan_numbers):
96 if 'nf' in os.listdir(f'{workdir}/{scan_number}'):
97 # indexRegex = re_compile(r'\d+')
98 path = f'{workdir}/{scan_number}/nf'
99 # image_files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f)) and
100 # f.endswith(".tif") and indexRegex.search(f)]
101 image_files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))
102 and f.endswith(".tif")]
103 if len(image_files):
104 image_file = f'{path}/{image_files[0]}'
105 break
106 else:
107 # Pick requested image file
108 scan_number = args.scan_number
109 if not os.path.isdir(f'{workdir}/{scan_number}'):
110 raise ValueError('Invalid scan_number (non-existing directory {workdir}/{scan_number})')
111 path = f'{workdir}/{scan_number}/nf'
112 if 'nf' not in os.listdir(f'{workdir}/{scan_number}'):
113 raise ValueError('Unable to find directory {path}')
114 image_files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))
115 and f.endswith(".tif")]
116 if args.image_index >= len(image_files):
117 raise ValueError('Unable to open the {args.image_index}th image file in {path}')
118 image_file = f'{path}/{image_files[args.image_index]}'
119
120 # Plot image to file
121 if image_file is None:
122 raise ValueError('Unable to find a valid image')
123 data = plt.imread(image_file)
124 title = 'image_files[0]'
125 plt.figure(title)
126 plt.imshow(data)
127 plt.savefig('image.jpg')
128 plt.close(fig=title)
129
130 if __name__ == "__main__":
131 __main__()
132