optionsParser.py 120 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
"""
Library of SPAM functions for parsing inputs to the scripts
Copyright (C) 2020 SPAM Contributors

This program is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option)
any later version.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
more details.

You should have received a copy of the GNU General Public License along with
this program.  If not, see <http://www.gnu.org/licenses/>.
"""

import argparse
20
import numpy
21
import tifffile
22
23
import os

24
# Nice str2bool suggestion from Maxim (https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse)
Emmanuel Roubin's avatar
MMR    
Emmanuel Roubin committed
25

26
def str2bool(v):
Emmanuel Roubin's avatar
MMR    
Emmanuel Roubin committed
27
28
29
30
31
32
33
    if v.lower() in ('yes', 'true', 't', 'y', '1'):
        return True
    elif v.lower() in ('no', 'false', 'f', 'n', '0'):
        return False
    else:
        raise argparse.ArgumentTypeError('Boolean value expected.')

Edward Andò's avatar
Edward Andò committed
34
35
36
GLPv3descriptionHeader = "Copyright (C) 2020 SPAM developers\n"+\
                         "This program comes with ABSOLUTELY NO WARRANTY.\n"+\
                         "This is free software, and you are welcome to redistribute it under certain conditions\n\n\n"
37

38

39
40
41
42

def pixelSearch(parser):
    parser.add_argument('im1',
                        metavar='im1',
43
                        type=argparse.FileType('r'),
44
45
46
47
48
49
50
51
52
53
54
55
56
                        help="Greyscale image of reference state for correlation")

    parser.add_argument('im2',
                        metavar='im2',
                        type=argparse.FileType('r'),
                        help="Greyscale image of deformed state for correlation")

    parser.add_argument('-lab1',
                        '--labelledFile1',
                        dest='LAB1',
                        default=None,
                        type=argparse.FileType('r'),
                        help="Path to tiff file containing a labelled image 1 that defines zones to correlate. Disactivates -hws and -ns options")
57

58
59
60
61
62
63
64
    parser.add_argument('-np',
                        '--number-of-processes',
                        default=None,
                        type=int,
                        dest='PROCESSES',
                        help="Number of parallel processes to use. Default = multiprocessing.cpu_count()")

65
66
67
68
69
70
71
    parser.add_argument('-ld',
                        '--label-dilate',
                        type=int,
                        default=1,
                        dest='LABEL_DILATE',
                        help="Only if -lab1 is defined: Number of times to dilate labels. Default = 1")

72
73
74
75
76
77
78
    parser.add_argument('-lvt',
                        '--label-volume-threshold',
                        type=numpy.uint,
                        default=100,
                        dest='LABEL_VOLUME_THRESHOLD',
                        help="Volume threshold below which labels are ignored. Default = 100")

79
80
81
    parser.add_argument('-mf1',
                        '--maskFile1',
                        dest='MASK1',
Emmanuel Roubin's avatar
MMR    
Emmanuel Roubin committed
82
                        default=None,
83
                        type=argparse.FileType('r'),
84
                        help="Path to tiff file containing the mask of image 1 -- masks zones not to correlate, which should be == 0")
85

86
87
88
89
90
91
92
93
94
95
96
97
98
    parser.add_argument('-mf2',
                        '--maskFile2',
                        dest='MASK2',
                        default=None,
                        type=argparse.FileType('r'),
                        help="Path to tiff file containing the mask of image 2 -- masks zones not to correlate, which should be == 0")

    parser.add_argument('-mc',
                        '--mask-coverage',
                        type=float,
                        default=0.5,
                        dest='MASK_COVERAGE',
                        help="In case a mask is defined, tolerance for a subvolume's pixels to be masked before it is skipped with RS=-5. Default = 0.5")
Emmanuel Roubin's avatar
MMR    
Emmanuel Roubin committed
99

Edward Andò's avatar
Edward Andò committed
100
101
102
    parser.add_argument('-pf',
                        '-phiFile',
                        dest='PHIFILE',
Emmanuel Roubin's avatar
MMR    
Emmanuel Roubin committed
103
                        default=None,
104
                        type=argparse.FileType('r'),
105
                        help="Path to TSV file containing the deformation function field (required)")
106

Edward Andò's avatar
Edward Andò committed
107
108
    parser.add_argument('-pfb',
                        '--phiFile-bin-ratio',
109
110
                        type=float,
                        default=1.0,
Edward Andò's avatar
Edward Andò committed
111
                        dest='PHIFILE_BIN_RATIO',
112
                        help="Ratio of binning level between loaded Phi file and current calculation. If the input Phi file has been obtained on a 500x500x500 image and now the calculation is on 1000x1000x1000, this should be 2. Default = 1")
113

114
115
116
117
118
119
120
121
    parser.add_argument('-F',
                        '--apply-F',
                        type=str,
                        default='all',
                        dest='APPLY_F',
                        help="Apply the F part of Phi guess? Accepted values are:\n\t\"all\": apply all of F" +
                             "\n\t\"rigid\": apply rigid part (mostly rotation) \n\t\"no\": don't apply it \"all\" is default")

122
123
    #parser.add_argument('-regs',
                        #'--subtract-registration',
124
                        #action="store_true",
125
126
                        #dest='REGSUB',
                        #help='Subtract rigid part of input registration from output displacements? Only works if you load a registration TSV. Default = False')
127

128
129
130
131
132
133
134
    parser.add_argument('-sr',
                        '--search-range',
                        nargs=6,
                        type=int,
                        default=[-3, 3, -3, 3, -3, 3],
                        dest='SEARCH_RANGE',
                        help='Z- Z+ Y- Y+ X- X+ ranges (in pixels) for the pxiel search. Requires pixel search to be activated. Default = +-3px')
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157

    # Default: node spacing equal in all three directions
    parser.add_argument('-ns',
                        '--node-spacing',
                        nargs=1,
                        type=int,
                        default=None,
                        dest='NS',
                        help="Node spacing in pixels (assumed equal in all 3 directions -- see -ns3 for different setting). Default = 10px")

    # Possible: node spacing different in all three directions
    parser.add_argument('-ns3',
                        '--node-spacing-3',
                        nargs=3,
                        type=int,
                        default=None,
                        dest='NS',
                        help="Node spacing in pixels (different in 3 directions). Default = 10, 10, 10px")

    # Default: window size equal in all three directions
    parser.add_argument('-hws',
                        '--half-window-size',
                        nargs=1,
Olga Stamati's avatar
Olga Stamati committed
158
                        type=int,
159
160
                        default=None,
                        dest='HWS',
161
                        help="Half correlation window size, measured each side of the node pixel (assumed equal in all 3 directions -- see -hws3 for different setting). Default = 10 px")
162
163
164
165
166
167
168
169
170
171

    # Possible: node spacing different in all three directions
    parser.add_argument('-hws3',
                        '--half-window-size-3',
                        nargs=3,
                        type=int,
                        default=None,
                        dest='HWS',
                        help="Half correlation window size, measured each side of the node pixel (different in 3 directions). Default = 10, 10, 10px")

172
173
    parser.add_argument('-glt',
                        '--grey-low-threshold',
174
                        type=float,
175
176
177
                        default=-numpy.inf,
                        dest='GREY_LOW_THRESH',
                        help="Grey threshold on mean of reference imagette BELOW which the correlation is not performed. Default = -infinity")
178

179
180
181
182
183
184
    parser.add_argument('-ght',
                        '--grey-high-threshold',
                        type=float,
                        default=numpy.inf,
                        dest='GREY_HIGH_THRESH',
                        help="Grey threshold on mean of reference imagette ABOVE which the correlation is not performed. Default = infinity")
185

186
187
188
189
190
    parser.add_argument('-od',
                        '--out-dir',
                        type=str,
                        default=None,
                        dest='OUT_DIR',
191
                        help="Output directory, default is the dirname of gmsh file")
192
193
194
195
196
197

    parser.add_argument('-pre',
                        '--prefix',
                        type=str,
                        default=None,
                        dest='PREFIX',
198
199
200
201
202
203
204
205
                        help='Prefix for output files (without extension). Default is basename of mesh file')

    #parser.add_argument('-def',
                        #'--save-deformed-image1',
                        #action="store_true",
                        #default=False,
                        #dest='DEF',
                        #help="Activate the saving of a deformed image 1 (as <im1>-reg-def.tif)")
206
207
208
209
210
211
212

    parser.add_argument('-vtk',
                        '--VTKout',
                        action="store_true",
                        dest='VTK',
                        help='Activate VTK output format. Default = False')

Edward Andò's avatar
Edward Andò committed
213
    parser.add_argument('-notsv',
214
                        '--noTSVout',
215
                        action="store_false",
216
                        dest='TSV',
217
                        help='Disactivate TSV output format. Default = False')
218
219
220
221
222
223

    parser.add_argument('-tif',
                        '-tiff',
                        '--TIFFout',
                        '--TIFout',
                        action="store_true",
Edward Andò's avatar
Edward Andò committed
224
225
                        dest='TIFF',
                        help='Activate TIFFoutput format. Default = False')
226
227
228

    args = parser.parse_args()

229
    # 2019-04-05 EA: 2D image detection approved by Christophe Golke, update for shape 2019-08-29
230
    tiff = tifffile.TiffFile(args.im1.name)
231
    if len(tiff.pages) == 1 and len(tiff.series[0].shape) == 2:
Edward Andò's avatar
Edward Andò committed
232
233
234
235
        twoD = True
    else:
        twoD = False
    tiff.close()
236

237
    # If we have no out dir specified, deliver on our default promise -- this can't be done inline before since parser.parse_args() has not been run at that stage.
Emmanuel Roubin's avatar
MMR    
Emmanuel Roubin committed
238
    if args.OUT_DIR is None:
239
        args.OUT_DIR = os.path.dirname(args.im1.name)
240
        # However if we have no dir, notice this and make it the current directory.
Emmanuel Roubin's avatar
MMR    
Emmanuel Roubin committed
241
242
        if args.OUT_DIR == "":
            args.OUT_DIR = "./"
243
244
245
246
247
248
    else:
        # Check existence of output directory
        try:
            if args.OUT_DIR:
                os.makedirs(args.OUT_DIR)
            else:
249
                args.DIR_out = os.path.dirname(args.im1.name)
250
251
252
253
254
        except OSError:
            if not os.path.isdir(args.OUT_DIR):
                raise


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
    if args.LAB1 is not None:
        # We have a labelled image and so no nodeSpacing or halfWindowSize
        print("I have been passed a labelled image and so I am disactivating node spacing and half-window size and mask and setting mask coverage to 0")
        args.HWS           = None
        args.NS            = None
        args.MASK1         = None
        args.MASK_COVERAGE = 0
        # Catch and overwrite 2D options
        if twoD:
            args.SEARCH_RANGE[0] = 0
            args.SEARCH_RANGE[1] = 0
    else:
        # We are in grid, with a nodeSpacing and halfWindowSize
        # Catch interdependent node spacing and correlation window sizes
        #if args.NS is None:
            #print("\nUsing default node spacing: "),
            #if args.HWS is None:
                #print("2x default half window size"),
                #args.HWS = [10]
                #print("({}) which is".format(args.HWS[0])),
                #args.NS = [args.HWS[0] * 2]
            #else:
                #print("2x user-set half window size"),
                #if len(args.HWS) == 1:
                    #print("({}) which is".format(args.HWS[0])),
                    #args.NS = [int(args.HWS[0] * 2)]
                #elif len(args.HWS) == 3:
                    #print("({} -- selecting smallest) which is".format(args.HWS)),
                    #args.NS = [int(min(args.HWS) * 2)]
            #print(args.NS)
285

286
287
288
        if args.HWS is None:
            print("spam-pixelSearch: in grid mode (without -lab1) HWS must be defined.")
            exit()
289

290
291
292
293
        ## Catch 3D options
        if args.NS is not None:
            if len(args.NS) == 1:
                args.NS = [args.NS[0], args.NS[0], args.NS[0]]
Emmanuel Roubin's avatar
MMR    
Emmanuel Roubin committed
294

295
296
        if len(args.HWS) == 1:
            args.HWS = [args.HWS[0], args.HWS[0], args.HWS[0]]
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
        # Catch and overwrite 2D options
        if twoD:
            if args.NS is not None: args.NS[0] = 1
            args.HWS[0] = 0
            args.SEARCH_RANGE[0] = 0
            args.SEARCH_RANGE[1] = 0

    # Output file name prefix
    if args.PREFIX is None:
        args.PREFIX = os.path.splitext(os.path.basename(args.im1.name))[0] + "-" + os.path.splitext(os.path.basename(args.im2.name))[0] + "-pixelSearch"
    else:
        args.PREFIX += "-pixelSearch"

    if args.APPLY_F not in ["all", "rigid", "no",]:
        print("-F should be 'all' 'rigid' or 'no'")
        exit()

    return args


def pixelSearchPropagate(parser):
    parser.add_argument('im1',
                        metavar='im1',
                        type=argparse.FileType('r'),
                        help="Greyscale image of reference state for correlation")

    parser.add_argument('im2',
                        metavar='im2',
                        type=argparse.FileType('r'),
                        help="Greyscale image of deformed state for correlation")

    parser.add_argument('-sp',
                        '--starting-point-and-displacement',
                        nargs=6,
                        type=int,
                        default=[-1, -1, -1, 0, 0, 0],
                        dest='START_POINT_DISP',
                        help='Z Y X of first point for the propagation, Z Y X displacement of that point, required')

    parser.add_argument('-gp',
                        '--guiding-points-file',
                        dest='GUIDING_POINTS_FILE',
                        default=None,
                        type=argparse.FileType('r'),
                        help='Path to file containing the guiding points')

    parser.add_argument('-lab1',
                        '--labelledFile1',
                        dest='LAB1',
                        default=None,
                        type=argparse.FileType('r'),
                        help="Path to tiff file containing a labelled image 1 that defines zones to correlate. Disactivates -hws and -ns options")

    parser.add_argument('-ld',
                        '--label-dilate',
                        type=int,
                        default=1,
                        dest='LABEL_DILATE',
                        help="Only if -lab1 is defined: Number of times to dilate labels. Default = 1")

    parser.add_argument('-mf1',
                        '--maskFile1',
                        dest='MASK1',
                        default=None,
                        type=argparse.FileType('r'),
                        help="Path to tiff file containing the mask of image 1 -- masks zones not to correlate, which should be == 0")

    parser.add_argument('-mf2',
                        '--maskFile2',
                        dest='MASK2',
                        default=None,
                        type=argparse.FileType('r'),
                        help="Path to tiff file containing the mask of image 2 -- masks zones not to correlate, which should be == 0")

    parser.add_argument('-mc',
                        '--mask-coverage',
                        type=float,
                        default=0.5,
                        dest='MASK_COVERAGE',
                        help="In case a mask is defined, tolerance for a subvolume's pixels to be masked before it is skipped with RS=-5. Default = 0.5")

    parser.add_argument('-sr',
                        '--search-range',
                        nargs=6,
                        type=int,
                        default=[-3, 3, -3, 3, -3, 3],
                        dest='SEARCH_RANGE',
                        help='Z- Z+ Y- Y+ X- X+ ranges (in pixels) for the pixel search. Default = +-3px')

    # Default: window size equal in all three directions
    parser.add_argument('-hws',
                        '--half-window-size',
                        nargs=1,
                        type=int,
                        default=[5],
                        dest='HWS',
                        help="Half correlation window size (in pixels), measured each side of the node pixel (assumed equal in all 3 directions -- see -hws3 for different setting). Default = 5 px")

    # Possible: window size different in all three directions
    parser.add_argument('-hws3',
                        '--half-window-size-3',
                        nargs=3,
                        type=int,
                        default=None,
                        dest='HWS',
                        help="Half correlation window size (in pixels), measured each side of the node pixel (different in 3 directions). Default = 10, 10, 10px")

    # Default: node spacing equal in all three directions
    parser.add_argument('-ns',
                        '--node-spacing',
                        nargs=1,
                        type=int,
                        default=None,
                        dest='NS',
                        help="Node spacing in pixels (assumed equal in all 3 directions -- see -ns3 for different setting). Default = 10px")

    parser.add_argument('-ns3',
                        '--node-spacing-3',
                        nargs=3,
                        type=int,
                        default=None,
                        dest='NS',
                        help="Node spacing in pixels (different in 3 directions). Default = 10, 10, 10px")

    parser.add_argument('-nr',
                        '--neighbourhood-radius',
                        type=float,
                        default=None,
                        dest='RADIUS',
                        help="Radius (in pixels) inside which to select neighbours. Default = mean(hws)+mean(sr)")

    parser.add_argument('-gwd',
                        '--gaussian-weighting-distance',
                        type=float,
                        default=None,
                        dest='DIST',
                        help="Distance (in pixels) over which the neighbour's distance is weighted. Default = sum(hws)+sum(sr)")

    parser.add_argument('-cct',
                        '--CC-threshold',
                        type=float,
                        default=0.9,
                        dest='CC_MIN',
                        help="Pixel search correlation coefficient threshold BELOW which the point is considered badly correlated. Default = 0.9")

    parser.add_argument('-glt',
                        '--grey-low-threshold',
                        type=float,
                        default=-numpy.inf,
                        dest='GREY_LOW_THRESH',
                        help="Grey threshold on mean of reference imagette BELOW which the correlation is not performed. Default = -infinity")

    parser.add_argument('-ght',
                        '--grey-high-threshold',
                        type=float,
                        default=numpy.inf,
                        dest='GREY_HIGH_THRESH',
                        help="Grey threshold on mean of reference imagette ABOVE which the correlation is not performed. Default = infinity")

    parser.add_argument('-od',
                        '--out-dir',
                        type=str,
                        default=None,
                        dest='OUT_DIR',
                        help="Output directory, default is the dirname of im1 file")

    parser.add_argument('-pre',
                        '--prefix',
                        type=str,
                        default=None,
                        dest='PREFIX',
                        help='Prefix for output files (without extension). Default is basename of im1 and im2 files')

    parser.add_argument('-vtk',
                        '--VTKout',
                        action="store_true",
                        dest='VTK',
                        help='Activate VTK output format. Default = False')

    parser.add_argument('-notsv',
                        '--noTSVout',
                        action="store_false",
                        dest='TSV',
                        help='Disactivate TSV output format. Default = False')

    parser.add_argument('-tif',
                        '-tiff',
                        '--TIFFout',
                        '--TIFout',
                        action="store_true",
                        dest='TIFF',
                        help='Activate TIFFoutput format. Default = False')

    args = parser.parse_args()

    # 2019-04-05 EA: 2D image detection approved by Christophe Golke, update for shape 2019-08-29
    #tiff = tifffile.TiffFile(args.im1.name)
    #if len(tiff.pages) == 1 and len(tiff.series[0].shape) == 2:
    #    twoD = True
    #else:
    #    twoD = False
    #tiff.close()

    if args.GUIDING_POINTS_FILE is None:
        # You really need a start point...
        if args.START_POINT_DISP[0:3] == [-1, -1, -1]:
            print("You need to input a starting point from which to propagate!\n(even if displacement is zero)")
            exit()

    # If we have no out dir specified, deliver on our default promise -- this can't be done inline before since parser.parse_args() has not been run at that stage.
    if args.OUT_DIR is None:
        args.OUT_DIR = os.path.dirname(args.im1.name)
        # However if we have no dir, notice this and make it the current directory.
        if args.OUT_DIR == "":
            args.OUT_DIR = "./"
    else:
        # Check existence of output directory
        try:
            if args.OUT_DIR:
                os.makedirs(args.OUT_DIR)
            else:
                args.DIR_out = os.path.dirname(args.im1.name)
        except OSError:
            if not os.path.isdir(args.OUT_DIR):
                raise

    # Output file name prefix
    if args.PREFIX is None:
        args.PREFIX = os.path.splitext(os.path.basename(args.im1.name))[0] + "-" + os.path.splitext(os.path.basename(args.im2.name))[0] + "-pixelSearchPropagate"
    else:
        args.PREFIX += "-pixelSearchPropagate"


    # Fill radius and dist if not given
    if args.RADIUS is None:
        args.RADIUS = numpy.mean(args.HWS) + (args.SEARCH_RANGE[1]+args.SEARCH_RANGE[3]+args.SEARCH_RANGE[5])/3.0

    if args.DIST is None:
        args.DIST = numpy.sum(args.HWS) + numpy.sum(args.SEARCH_RANGE[1]+args.SEARCH_RANGE[3]+args.SEARCH_RANGE[5])

    ### There are 3 modes:
    # - points-to-correlate defined by input "guiding points", which should be points with good texture
    # - points-to-correlate defined by labelled image
    # - points-to-correlate defined by regular grid
    if args.GUIDING_POINTS_FILE is not None:
        print("I have been passed a guiding points file, so I am disactivating:")
        print("\t- node spacing")
        print("\t- label file")
        args.NS            = None
        args.LAB1          = None
        # Catch 3D options
        if len(args.HWS) == 1:
            args.HWS = [args.HWS[0]]*3

    elif args.LAB1 is not None: 
        # We have a labelled image and so no nodeSpacing or halfWindowSize
        print("I have been passed a labelled image and so I am disactivating:")
        print("\t- node spacing")
        print("\t- half-window size")
        args.HWS           = None
        args.NS            = None
        args.MASK1         = None
        args.MASK_COVERAGE = 0


    else:
        print("Regular grid mode")
        # We are in grid, with a nodeSpacing and halfWindowSize
        # Catch interdependent node spacing and correlation window sizes
        if args.NS is None:
            print("\nUsing default node spacing: "),
            if args.HWS is None:
                print("2x default half window size"),
                args.HWS = [10]
                print("({}) which is".format(args.HWS[0])),
                args.NS = [args.HWS[0] * 2]
            else:
                print("2x user-set half window size"),
                if len(args.HWS) == 1:
                    print("({}) which is".format(args.HWS[0])),
                    args.NS = [int(args.HWS[0] * 2)]
                elif len(args.HWS) == 3:
                    print("({} -- selecting smallest) which is".format(args.HWS)),
                    args.NS = [int(min(args.HWS) * 2)]
            print(args.NS)

        # Catch 3D options
        if len(args.NS) == 1:
            args.NS = [args.NS[0], args.NS[0], args.NS[0]]

        if len(args.HWS) == 1:
            args.HWS = [args.HWS[0], args.HWS[0], args.HWS[0]]

    return args


def ldicParser(parser):
    parser.add_argument('inFiles',
                        nargs='+',
                        type=argparse.FileType('r'),
                        help="A space-separated list of two or more 3D greyscale tiff files to correlate, in order")

    parser.add_argument('-np',
                        '--number-of-processes',
                        default=None,
                        type=int,
                        dest='PROCESSES',
                        help="Number of parallel processes to use. Default = multiprocessing.cpu_count()")

    parser.add_argument('-mf1',
                        '--maskFile1',
                        dest='MASK1',
                        default=None,
                        type=argparse.FileType('r'),
                        help="Path to tiff file containing the mask of image 1 -- masks zones not to correlate, which should be == 0")

    # parser.add_argument('-mf2',
    #                     '--maskFile2',
    #                     dest='MASK2',
    #                     default=None,
    #                     type=argparse.FileType('r'),
    #                     help="Path to tiff file containing the mask of image 2 -- masks correlation windows")

    parser.add_argument('-pf',
                        '-phiFile',
                        dest='PHIFILE',
                        default=None,
                        type=argparse.FileType('r'),
                        help="Path to TSV file containing initial Phi guess, can be single-point registration or multiple point correlation. Default = None")

    parser.add_argument('-pfb',
                        '--phiFile-bin-ratio',
630
631
                        type=float,
                        default=1.0,
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
                        dest='PHIFILE_BIN_RATIO',
                        help="Ratio of binning level between loaded Phi file and current calculation. If the input Phi file has been obtained on a 500x500x500 image and now the calculation is on 1000x1000x1000, this should be 2. Default = 1")

    parser.add_argument('-F',
                        '--apply-F',
                        type=str,
                        default='all',
                        dest='APPLY_F',
                        help="Apply the F part of Phi guess? Accepted values are:\n\t\"all\": apply all of F" +
                             "\n\t\"rigid\": apply rigid part (mostly rotation) \n\t\"no\": don't apply it \"all\" is default")

    parser.add_argument('-glt',
                        '--grey-low-threshold',
                        type=float,
                        default=-numpy.inf,
                        dest='GREY_LOW_THRESH',
                        help="Grey threshold on mean of reference imagette BELOW which the correlation is not performed. Default = -infinity")

    parser.add_argument('-ght',
                        '--grey-high-threshold',
                        type=float,
                        default=numpy.inf,
                        dest='GREY_HIGH_THRESH',
                        help="Grey threshold on mean of reference imagette ABOVE which the correlation is not performed. Default = infinity")

    # Default: node spacing equal in all three directions
    parser.add_argument('-ns',
                        '--node-spacing',
                        nargs=1,
                        type=int,
                        default=None,
                        dest='NS',
                        help="Node spacing in pixels (assumed equal in all 3 directions -- see -ns3 for different setting). Default = 10px")

    # Possible: node spacing different in all three directions
    parser.add_argument('-ns3',
                        '--node-spacing-3',
                        nargs=3,
                        type=int,
                        default=None,
                        dest='NS',
                        help="Node spacing in pixels (different in 3 directions). Default = 10, 10, 10px")

    # Default: window size equal in all three directions
    parser.add_argument('-hws',
                        '--half-window-size',
                        nargs=1,
                        type=int,
                        default=None,
                        dest='HWS',
                        help="Half correlation window size, measured each side of the node pixel (assumed equal in all 3 directions -- see -hws3 for different setting). Default = 10 px")

    # Possible: node spacing different in all three directions
    parser.add_argument('-hws3',
                        '--half-window-size-3',
                        nargs=3,
                        type=int,
                        default=None,
                        dest='HWS',
                        help="Half correlation window size, measured each side of the node pixel (different in 3 directions). Default = 10, 10, 10px")

    parser.add_argument('-m',
                        '-mar',
                        '-margin',
                        nargs=1,
                        type=int,
                        default=[3],
                        dest='MARGIN',
                        help="Margin in pixels for the correlation of each local subvolume. Default = 3 px")

    parser.add_argument('-m3',
                        '-mar3',
                        '-margin3',
                        nargs=3,
                        type=int,
                        default=None,
                        dest='MARGIN',
                        help="Margin in pixels for the correlation of each local subvolume. Default = 3 px")

    parser.add_argument('-it',
                        '--max-iterations',
                        type=int,
                        default=50,
                        dest='MAX_ITERATIONS',
                        help="Maximum iterations for local correlation. Default = 50")

    parser.add_argument('-dp',
                        '--min-delta-phi',
                        type=numpy.float,
                        default=0.001,
                        dest='MIN_DELTA_PHI',
                        help="Minimum change in Phi for local convergence. Default = 0.001")

    parser.add_argument('-o',
                        '--interpolation-order',
                        type=int,
                        default=1,
                        dest='INTERPOLATION_ORDER',
                        help="Image interpolation order for local correlation. Default = 1, i.e., linear interpolation")

    parser.add_argument('-mc',
                        '--mask-coverage',
                        type=float,
                        default=0.5,
                        dest='MASK_COVERAGE',
                        help="In case a mask is defined, tolerance for a subvolume's pixels to be masked before it is skipped with RS=-5. Default = 0.5")

    parser.add_argument('-ug',
                        '--update-gradient',
                        action="store_true",
                        dest='UPDATE_GRADIENT',
                        help='Update gradient in local correlation? More computation time but sometimes more robust and possibly fewer iterations.')

    #parser.add_argument('-sef',
                        #'--series-Ffile',
                        #action="store_true",
                        #dest='SERIES_PHIFILE',
                        #help='During a total analysis, activate use of previous Ffield for next correlation')

    parser.add_argument('-sei',
                        '--series-incremental',
                        action="store_true",
                        dest='SERIES_INCREMENTAL',
                        help='Perform incremental correlations between images')

    parser.add_argument('-od',
                        '--out-dir',
                        type=str,
                        default=None,
                        dest='OUT_DIR',
                        help="Output directory, default is the dirname of input file")

    parser.add_argument('-pre',
                        '--prefix',
                        type=str,
                        default=None,
                        dest='PREFIX',
                        help="Prefix for output files (without extension). Default is basename of input file")

    parser.add_argument('-vtk',
                        '--VTKout',
                        action="store_true",
                        dest='VTK',
                        help='Activate VTK output format. Default = False')

    parser.add_argument('-notsv',
                        '--noTSV',
                        action="store_false",
                        dest='TSV',
                        help='Disactivate TSV output format. Default = True')

    parser.add_argument('-tif',
                        '-tiff',
                        '--TIFFout',
                        '--TIFout',
                        action="store_true",
                        dest='TIFF',
                        help='Activate TIFFoutput format. Default = False')

    args = parser.parse_args()

    # 2018-03-24 check for 2D without loading images
    # try:
    # except BaseException:
    #     print("DICregularGrid: Input TIFF files need to be writeable in order to guess their dimensionality")
    #     exit()
    # 2019-03-21 EA: better check for dimensions, doesn't depend on writability of files
    tiff = tifffile.TiffFile(args.inFiles[0].name)
    #imagejSingleSlice = True
    # if tiff.imagej_metadata is not None:
    #     if 'slices' in tiff.imagej_metadata:
    #         if tiff.imagej_metadata['slices'] > 1:
    #             imagejSingleSlice = False

    # 2019-04-05 EA: 2D image detection approved by Christophe Golke, update for shape 2019-08-29
    if len(tiff.pages) == 1 and len(tiff.series[0].shape) == 2:
        twoD = True
    else:
        twoD = False
    tiff.close()

    # If we have no out dir specified, deliver on our default promise -- this can't be done inline before since parser.parse_args() has not been run at that stage.
    if args.OUT_DIR is None:
        args.OUT_DIR = os.path.dirname(args.inFiles[0].name)
        # However if we have no dir, notice this and make it the current directory.
        if args.OUT_DIR == "":
            args.OUT_DIR = "./"
    else:
        # Check existence of output directory
        try:
            if args.OUT_DIR:
                os.makedirs(args.OUT_DIR)
            else:
                args.DIR_out = os.path.dirname(args.inFiles[0].name)
        except OSError:
            if not os.path.isdir(args.OUT_DIR):
                raise

    # Catch interdependent node spacing and correlation window sizes
    #if args.NS is None:
        #print("\nUsing default node spacing: "),
        #if args.HWS is None:
            #print("2x default half window size"),
            #args.HWS = [10]
            #print("({}) which is".format(args.HWS[0])),
            #args.NS = [args.HWS[0] * 2]
        #else:
            #print("2x user-set half window size"),
            #if len(args.HWS) == 1:
                #print("({}) which is".format(args.HWS[0])),
                #args.NS = [int(args.HWS[0] * 2)]
            #elif len(args.HWS) == 3:
                #print("({} -- selecting smallest) which is".format(args.HWS)),
                #args.NS = [int(min(args.HWS) * 2)]
        #print(args.NS)

    if args.HWS is None:
        print("spam-ldic: HWS must be defined.")
        exit()

    ## Catch 3D options
    if args.NS is not None:
        if len(args.NS) == 1:
            args.NS = [args.NS[0], args.NS[0], args.NS[0]]

    if len(args.HWS) == 1:
        args.HWS = [args.HWS[0], args.HWS[0], args.HWS[0]]

    if len(args.MARGIN) == 1:
        args.MARGIN = [args.MARGIN[0], args.MARGIN[0], args.MARGIN[0]]

    if type(args.MAX_ITERATIONS) == list:
        args.MAX_ITERATIONS = args.MAX_ITERATIONS[0]

    # Catch and overwrite 2D options
867
    if twoD:
868
        if args.NS is not None: args.NS[0] = 1
869
        args.HWS[0] = 0
870
871
        args.MARGIN[0] = 0

872
    
873
874
875
876
877
878
879
880
881
    # Behaviour undefined for series run and im1 mask since im1 will change, complain and continue
    if args.MASK1 is not None and args.SERIES_INCREMENTAL:
        print("#############################################################")
        print("#############################################################")
        print("###  WARNING: You set an im1 mask and an incremental      ###")
        print("###  series correlation, meaning that im1 will change...  ###")
        print("#############################################################")
        print("#############################################################")

882
    # Make sure at least one output format has been asked for
Edward Andò's avatar
Edward Andò committed
883
    if args.VTK + args.TSV + args.TIFF== 0:
Emmanuel Roubin's avatar
MMR    
Emmanuel Roubin committed
884
885
        print("#############################################################")
        print("#############################################################")
Edward Andò's avatar
Edward Andò committed
886
        print("###  WARNING: No output type of VTK, TSV and TIFFoptions  ###")
Emmanuel Roubin's avatar
MMR    
Emmanuel Roubin committed
887
888
889
        print("###  Are you sure this is right?!                         ###")
        print("#############################################################")
        print("#############################################################")
890

891
892
    #if args.SERIES_PHIFILE:
        #args.TSV = True
893

894
    # Nor prefix here because LDIC can still do an image series and needs to update the name
895
896
897
    if args.APPLY_F not in ["all", "rigid", "no",]:
        print("-F should be 'all' 'rigid' or 'no'")
        exit()
898

899
900
901
    return args


902
def ddicParser(parser):
903
904
905
906
907
    parser.add_argument('im1',
                        metavar='im1',
                        type=argparse.FileType('r'),
                        help="Greyscale image of reference state for correlation")

908
909
910
911
912
    parser.add_argument('lab1',
                        metavar='lab1',
                        type=argparse.FileType('r'),
                        help="Labelled image of reference state for correlation")

913
914
915
916
    parser.add_argument('im2',
                        metavar='im2',
                        type=argparse.FileType('r'),
                        help="Greyscale image of deformed state for correlation")
917

918
919
920
921
922
923
924
    parser.add_argument('-np',
                        '--number-of-processes',
                        default=None,
                        type=int,
                        dest='PROCESSES',
                        help="Number of parallel processes to use. Default = multiprocessing.cpu_count()")

925
926
    parser.add_argument('-ld',
                        '--label-dilate',
927
                        type=int,
928
929
930
931
                        default=1,
                        dest='LABEL_DILATE',
                        help="Number of times to dilate labels. Default = 1")

Edward Andò's avatar
Edward Andò committed
932
933
934
935
936
937
    #parser.add_argument('-ldmax',
                        #'--label-dilate-maximum',
                        #type=int,
                        #default=None,
                        #dest='LABEL_DILATE_MAX',
                        #help="Maximum dilation for label if they don't converge with -ld setting. Default = same as -ld setting")
Edward Andò's avatar
Edward Andò committed
938

939
940
941
942
943
944
945
    parser.add_argument('-vt',
                        '--volume-threshold',
                        type=numpy.uint,
                        default=100,
                        dest='VOLUME_THRESHOLD',
                        help="Volume threshold below which labels are ignored. Default = 100")

Edward Andò's avatar
Edward Andò committed
946
947
948
    parser.add_argument('-pf',
                        '-phiFile',
                        dest='PHIFILE',
Emmanuel Roubin's avatar
MMR    
Emmanuel Roubin committed
949
                        default=None,
950
                        type=argparse.FileType('r'),
951
                        help="Path to TSV file containing initial Phi guess, can be single-point registration or multiple point correlation. Default = None")
952

Edward Andò's avatar
Edward Andò committed
953
954
    parser.add_argument('-pfb',
                        '--phiFile-bin-ratio',
955
956
                        type=float,
                        default=1.0,
Edward Andò's avatar
Edward Andò committed
957
                        dest='PHIFILE_BIN_RATIO',
958
                        help="Ratio of binning level between loaded Phi file and current calculation. If the input Phi file has been obtained on a 500x500x500 image and now the calculation is on 1000x1000x1000, this should be 2. Default = 1")
959

960
961
962
963
964
965
966
    parser.add_argument('-F',
                        '--apply-F',
                        type=str,
                        default='rigid',
                        dest='APPLY_F',
                        help="Apply the F part of Phi guess? Accepted values are:\n\t\"all\": apply all of F" +
                             "\n\t\"rigid\": apply rigid part (mostly rotation) \n\t\"no\": don't apply it \"rigid\" is default")
967

968
969
970
    parser.add_argument('-m',
                        '-mar',
                        '-margin',
Olga Stamati's avatar
Olga Stamati committed
971
                        type=int,
972
                        default=5,
973
974
975
976
977
                        dest='MARGIN',
                        help="Margin in pixels for the correlation of each local subvolume. Default = 5 px")

    parser.add_argument('-it',
                        '--max-iterations',
978
                        type=numpy.uint,
979
                        default=50,
980
                        dest='MAX_ITERATIONS',
981
                        help="Maximum iterations for label correlation. Default = 50")
982

983
984
    parser.add_argument('-dp',
                        '--min-delta-phi',
985
986
                        type=numpy.float,
                        default=0.001,
987
                        dest='MIN_PHI_CHANGE',
988
                        help="Minimum change in Phi to consider label correlation as converged. Default = 0.001")
989

990
991
    parser.add_argument('-o',
                        '--interpolation-order',
992
                        type=numpy.uint,
993
                        default=1,
994
                        dest='INTERPOLATION_ORDER',
995
                        help="Interpolation order for label correlation. Default = 3")
996

997
998
    parser.add_argument('-nr',
                        '--non-rigid',
999
                        action="store_false",
1000
                        dest='CORRELATE_RIGID',
1001
1002
                        help='Activate non-rigid registration for each label')

1003
1004
    parser.add_argument('-ug',
                        '--update-gradient',
1005
                        action="store_true",
1006
                        dest='UPDATE_GRADIENT',
1007
1008
                        help='Update gradient in label registration? More computation time but more robust and possibly fewer iterations.')

1009
1010
1011
1012
1013
1014
    #parser.add_argument('-lcms',
                        #'--label-correlate-multiscale',
                        #action="store_true",
                        #dest='LABEL_CORRELATE_MULTISCALE',
                        #help='Activate multiscale correlation for the label? If you set this, please indicate -lcmsb')

1015
1016
    parser.add_argument('-msb',
                        '--multiscale-binning',
1017
1018
                        type=numpy.uint,
                        default=1,
1019
                        dest='MULTISCALE_BINNING',
1020
1021
                        help="Binning level for multiscale label correlation. Default = 1")

1022
1023
    parser.add_argument('-dmo',
                        '--dont-mask-others',
1024
                        action="store_false",
1025
                        dest='MASK_OTHERS',
1026
                        help='Prevent masking other labels when dilating?')
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039

    parser.add_argument('-od',
                        '--out-dir',
                        type=str,
                        default=None,
                        dest='OUT_DIR',
                        help="Output directory, default is the dirname of input file")

    parser.add_argument('-pre',
                        '--prefix',
                        type=str,
                        default=None,
                        dest='PREFIX',
Edward Andò's avatar
Edward Andò committed
1040
                        help="Prefix for output files (without extension). Default is basename of input file")
1041

1042
1043
1044
    parser.add_argument('-skp',
                        '--skip',
                        action="store_true",
Edward Andò's avatar
Edward Andò committed
1045
                        default=False,
1046
                        dest='SKIP_PARTICLES',
1047
                        help="Read the return status of the Phi file run ddic only for the non-converged grains. Default = False")
1048

1049
1050
1051
    parser.add_argument('-d',
                        '--debug',
                        action="store_true",
Edward Andò's avatar
Edward Andò committed
1052
                        default=False,
1053
1054
1055
                        dest='DEBUG',
                        help="Extremely verbose mode with graphs and text output. Only use for a few particles. Do not use with mpirun")

1056
1057
1058
    args = parser.parse_args()

    # If we have no out dir specified, deliver on our default promise -- this can't be done inline before since parser.parse_args() has not been run at that stage.
Emmanuel Roubin's avatar
MMR    
Emmanuel Roubin committed
1059
1060
    if args.OUT_DIR is None:
        args.OUT_DIR = os.path.dirname(args.lab1.name)
1061
        # However if we have no dir, notice this and make it the current directory.
Emmanuel Roubin's avatar
MMR    
Emmanuel Roubin committed
1062
1063
        if args.OUT_DIR == "":
            args.OUT_DIR = "./"
1064
1065
1066
1067
1068
    else:
        # Check existence of output directory
        try:
            if args.OUT_DIR:
                os.makedirs(args.OUT_DIR)
1069
            else:
Emmanuel Roubin's avatar
gdic    
Emmanuel Roubin committed
1070
                args.DIR_out = os.path.dirname(args.lab1.name)
1071
1072
1073
1074
1075
        except OSError:
            if not os.path.isdir(args.OUT_DIR):
                raise

    # Output file name prefix
Emmanuel Roubin's avatar
MMR    
Emmanuel Roubin committed
1076
    if args.PREFIX is None:
Emmanuel Roubin's avatar
Emmanuel Roubin committed
1077
        args.PREFIX = os.path.splitext(os.path.basename(args.im1.name))[0] + "-" + os.path.splitext(os.path.basename(args.im2.name))[0]
1078

Edward Andò's avatar
Edward Andò committed
1079
1080
1081
    ## Set label dilate max as label dilate if it is none
    #if args.LABEL_DILATE_MAX is None:
        #args.LABEL_DILATE_MAX = args.LABEL_DILATE
Edward Andò's avatar
Edward Andò committed
1082

Edward Andò's avatar
Edward Andò committed
1083
1084
1085
    #if args.LABEL_DILATE_MAX < args.LABEL_DILATE:
        #print("spam-ddic: Warning \"label dilate max\" is less than \"label dilate\" setting them equal")
        #args.LABEL_DILATE_MAX = args.LABEL_DILATE
Edward Andò's avatar
Edward Andò committed
1086

1087
1088
1089
1090
    if args.DEBUG:
        print("spam-ddic: DEBUG mode activated, forcing number of processes to 1")
        args.PROCESSES = 1

1091
    return args
1092
1093


Emmanuel Roubin's avatar
MMR    
Emmanuel Roubin committed
1094
def multiModalRegistrationParser(parser):
1095
    import spam.DIC
Edward Andò's avatar
Edward Andò committed
1096
    import numpy
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131

    parser.add_argument('im1',
                        metavar='im1',
                        type=argparse.FileType('r'),
                        help="Greyscale image of reference state for correlation")

    parser.add_argument('im2',
                        metavar='im2',
                        type=argparse.FileType('r'),
                        help="Greyscale image of deformed state for correlation")

    parser.add_argument('-im1min',
                        type=float,
                        default=None,
                        dest='IM1_MIN',
                        help="Minimum of im1 for greylevel scaling. Default = im1.min()")

    parser.add_argument('-im1max',
                        type=float,
                        default=None,
                        dest='IM1_MAX',
                        help="Maximum of im1 for greylevel scaling. Default = im1.max()")

    parser.add_argument('-im2min',
                        type=float,
                        default=None,
                        dest='IM2_MIN',
                        help="Minimum of im2 for greylevel scaling. Default = im2.min()")

    parser.add_argument('-im2max',
                        type=float,
                        default=None,
                        dest='IM2_MAX',
                        help="Maximum of im2 for greylevel scaling. Default = im2.max()")

Emmanuel Roubin's avatar
MMR    
Emmanuel Roubin committed
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
    parser.add_argument('-im1th',
                        '--im1-threshold',
                        type=int,
                        default=0,
                        dest='IM1_THRESHOLD',
                        help='Greylevel threshold for image 1. Below this threshold, peaks in the histogram are ignored.')

    parser.add_argument('-im2th',
                        '--im2-threshold',
                        type=int,
                        default=0,
                        dest='IM2_THRESHOLD',
                        help='Greylevel threshold for image 2. Below this threshold, peaks in the histogram are ignored.')

1146
1147
    parser.add_argument('-bin',
                        '--bin-levels',
Edward Andò's avatar
Edward Andò committed
1148
                        type=int,
Edward Andò's avatar
Edward Andò committed
1149
1150
1151
                        default=1,
                        dest='NBINS',
                        help='Number of binning levels to apply to the data (if given 3, the binning levels used will be 4 2 1). The -phase option is necessary and should define this many phases (i.e., 3 different numbers in this example)')
1152
1153
1154
1155
1156
1157
1158

    parser.add_argument('-ph',
                        '--phases',
                        nargs='+',
                        type=int,
                        default=[2],
                        dest='PHASES',
1159
                        help='Number of phases?')
1160
1161
1162

    parser.add_argument('-jhb',
                        '--joint-histogram-bins',
Emmanuel Roubin's avatar
MMR    
Emmanuel Roubin committed
1163
                        # nargs=1,
1164
1165
1166
1167
1168
                        type=int,
                        default=128,
                        dest='JOINT_HISTO_BINS',
                        help='The number of greylevel bins for both images in the joint histogram')

Emmanuel Roubin's avatar
MMR    
Emmanuel Roubin committed
1169
1170
1171
1172
1173
    parser.add_argument('-dst',
                        '--dist-between-max',
                        type=int,
                        default=None,
                        dest='DIST_BETWEEN_MAX',
Emmanuel Roubin's avatar
Emmanuel Roubin committed
1174
1175
1176
1177
1178
1179
1180
1181
                        help='Minimal distance between two maxima in the histogram')

    parser.add_argument('-fdi',
                        '--fit-distance',
                        type=float,
                        default=None,
                        dest='FIT_DISTANCE',
                        help='Distance considered around a peak for the Gaussian ellipsoid fitting')
Emmanuel Roubin's avatar
MMR    
Emmanuel Roubin committed
1182

Emmanuel Roubin's avatar
Emmanuel Roubin committed
1183
1184
1185
1186
1187
    parser.add_argument('-voc',
                        '--voxel-coverage',
                        type=float,
                        default=1.0,
                        dest='VOXEL_COVERAGE',
Emmanuel Roubin's avatar
Emmanuel Roubin committed
1188
                        help='Percentage (between 0 and 1) of voxel coverage of the phases in the joint histogram')
Emmanuel Roubin's avatar
Emmanuel Roubin committed
1189

1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
    parser.add_argument('-int',
                        '--interactive',
                        action="store_true",
                        dest='INTERACTIVE',
                        help='Present live-updating plots to the user')

    parser.add_argument('-gra',
                        '--graphs',
                        action="store_true",
                        dest='GRAPHS',
                        help='Save graphs to file')

Emmanuel Roubin's avatar
MMR    
Emmanuel Roubin committed
1202
1203
1204
1205
1206
1207
1208
    parser.add_argument('-ssl',
                        '--show-slice-axis',
                        type=int,
                        default=0,
                        dest='SHOW_SLICE_AXIS',
                        help='Axis of the cut used for the plots')

1209
    parser.add_argument('-spp',
1210
                        '--grid-point-min-phi-change',
1211
                        type=numpy.float,
1212
                        default=0.0005,
1213
                        dest='GRID_POINT_MIN_PHI_CHANGE',
Edward Andò's avatar
Edward Andò committed
1214
1215
1216
                        help="Subpixel min change in Phi to stop iterations. Default = 0.001")

    parser.add_argument('-spi',
1217
                        '--grid-point-max-iterations',
Olga Stamati's avatar
Olga Stamati committed
1218
                        type=int,
Edward Andò's avatar
Edward Andò committed
1219
                        default=50,
1220
                        dest='GRID_POINT_MAX_ITERATIONS',
Edward Andò's avatar
Edward Andò committed
1221
                        help="Max number of iterations to optimise Phi. Default = 50")
1222

Emmanuel Roubin's avatar
MMR    
Emmanuel Roubin committed
1223
1224
1225
1226
1227
    # parser.add_argument('-tmp',
    #                     '--writeTemporaryFiles',
    #                     action="store_true",
    #                     dest='DATA',
    #                     help='Save temporary files (joint histogram) to \"dat\" file')
1228

1229
1230
1231
1232
1233
    #parser.add_argument('-loadprev',
                        #'--load-previous-iteration',
                        #action="store_true",
                        #dest='LOADPREV',
                        #help='Load output pickle files from previous iterations (2* coarser binning)')
Edward Andò's avatar
Edward Andò committed
1234

1235
    parser.add_argument('-mar',
Emmanuel Roubin's avatar
Emmanuel Roubin committed
1236
                        '--margin',
1237
1238
                        type=float,
                        default=0.1,
Emmanuel Roubin's avatar
Emmanuel Roubin committed
1239
1240
1241
1242
1243
1244
1245
1246
1247
                        dest='MARGIN',
                        help='Margin of both images. Default = 0.1, which means 0.1 * image size from both sides')

    parser.add_argument('-cro',
                        '--crop',
                        type=float,
                        default=0.1,
                        dest='CROP',
                        help='Initial crop of both images. Default = 0.1, which means 0.1 * image size from both sides')
1248

1249
1250
1251
1252
1253
    #parser.add_argument('-pif',
                        #default=None,
                        #type=argparse.FileType('rb'),
                        #dest='FGUESS_PICKLE',
                        #help="Pickle file name for initial guess. Should be in position 0 in the array and labeled as 'F' as for registration.")
Emmanuel Roubin's avatar
MMR    
Emmanuel Roubin committed
1254

Edward Andò's avatar
Edward Andò committed
1255
    # Remove next two arguments for F input, and replace with displacement and rotation inputs on command line
1256
1257
1258
    parser.add_argument('-pf',
                        '--phiFile',
                        dest='PHIFILE',
1259
                        default=None,
1260
                        type=argparse.FileType('r'),
1261
                        help="Path to TSV file containing a single Phi guess (not a field) that deforms im1 onto im2. Default = None")
Emmanuel Roubin's avatar
MMR    
Emmanuel Roubin committed
1262
1263
1264
1265
1266

    # parser.add_argument('-Ffb',
    # '--Ffile-bin-ratio',
    # type=int,
    # default=1,
Edward Andò's avatar
Edward Andò committed
1267
    # dest='PHIFILE_BIN_RATIO',
1268
    # help="Ratio of binning level between loaded Phi file and current calculation. If the input Phi file has been obtained on a 500x500x500 image and now the calculation is on 1000x1000x1000, this should be 2. Default = 1")
Edward Andò's avatar
Edward Andò committed
1269

1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
    # parser.add_argument('-tra',
    # '--translation',
    # nargs=3,
    # type=float,
    # default=None,
    # dest='TRA',
    # help="Z, Y, X initial displacements to apply at the bin 1 scale")

    # parser.add_argument('-rot',
    # '--rotation',
    # nargs=3,
    # type=float,
    # default=None,
    # dest='ROT',
    # help="Z, Y, X components of rotation vector to apply at the bin 1 scale")
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297

    parser.add_argument('-od',
                        '--out-dir',
                        type=str,
                        default=None,
                        dest='OUT_DIR',
                        help="Output directory, default is the dirname of input file")

    parser.add_argument('-pre',
                        '--prefix',
                        type=str,
                        default=None,
                        dest='PREFIX',
Edward Andò's avatar
Edward Andò committed
1298
                        help="Prefix for output files (without extension). Default is basename of input file")
1299
1300
1301
1302

    args = parser.parse_args()

    # The number of bin levels must be the same as the number of phases
Edward Andò's avatar
Edward Andò committed
1303
    if (args.NBINS != len(args.PHASES)):
1304
1305
1306
        print("\toptionsParser.multiModalRegistrationParser(): Number of bin levels and number of phases not the same, exiting")
        exit()

Edward Andò's avatar
Edward Andò committed
1307
1308
1309
    # For back compatibility, generate list of bins
    args.BINS = []
    for i in range(args.NBINS)[::-1]:
Emmanuel Roubin's avatar
MMR    
Emmanuel Roubin committed
1310
        args.BINS.append(2**i)
Edward Andò's avatar
Edward Andò committed
1311

1312
    # If we have no out dir specified, deliver on our default promise -- this can't be done inline before since parser.parse_args() has not been run at that stage.
Emmanuel Roubin's avatar
MMR    
Emmanuel Roubin committed
1313
1314
    if args.OUT_DIR is None:
        args.OUT_DIR = os.path.dirname(args.im1.name)
1315
        # However if we have no dir, notice this and make it the current directory.
Emmanuel Roubin's avatar
MMR    
Emmanuel Roubin committed
1316
1317
        if args.OUT_DIR == "":
            args.OUT_DIR = "./"
1318
1319
1320
1321
1322
1323
    else:
        # Check existence of output directory
        try:
            if args.OUT_DIR:
                os.makedirs(args.OUT_DIR)
            else:
Emmanuel Roubin's avatar
gdic    
Emmanuel Roubin committed
1324
                args.DIR_out = os.path.dirname(args.im1.name)
1325
1326
1327
1328
        except OSError:
            if not os.path.isdir(args.OUT_DIR):
                raise

Edward Andò's avatar
Edward Andò committed
1329
    # Get initial guesses
1330
1331
    if args.PHIFILE is not None:
        import spam.helpers
1332
        args.FGUESS = spam.helpers.readCorrelationTSV(args.PHIFILE.name, readConvergence=False, readOnlyDisplacements=False)['PhiField'][0]
Edward Andò's avatar
Edward Andò committed
1333
1334
1335
    else:
        args.FGUESS = numpy.eye(4)

1336
    # Output file name prefix
Emmanuel Roubin's avatar
MMR    
Emmanuel Roubin committed
1337
    if args.PREFIX is None:
Emmanuel Roubin's avatar
Emmanuel Roubin committed
1338
        args.PREFIX = os.path.splitext(os.path.basename(args.im1.name))[0] + "-" + os.path.splitext(os.path.basename(args.im2.name))[0]
1339
1340

    return args
Emmanuel Roubin's avatar
gdic    
Emmanuel Roubin committed
1341
1342


Emmanuel Roubin's avatar
Emmanuel Roubin committed
1343
def gdicParser(parser):
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
    parser.add_argument('inFiles',
                        nargs='+',
                        type=argparse.FileType('r'),
                        help="A space-separated list of two 3D greyscale tiff files to correlate, in order")

    parser.add_argument('-mf1',
                        '--maskFile1',
                        dest='MASK1',
                        default=None,
                        type=argparse.FileType('r'),
                        help="Path to tiff file containing the mask of image 1 -- masks  zones not to correlate")

    parser.add_argument('-mf2',
                        '--maskFile2',
                        dest='MASK2',
                        default=None,
                        type=argparse.FileType('r'),
                        help="Path to tiff file containing the mask of image 2 -- masks correlation windows")

    parser.add_argument('-pf',
                        '-phiFile',
                        dest='PHIFILE',
                        default=None,
                        type=argparse.FileType('r'),
1368
                        help="Path to TSV file containing initial Phi guess, can be single-point registration or multiple point correlation. Default = None")
1369
1370
1371

    parser.add_argument('-pfb',
                        '--phiFile-bin-ratio',
1372
1373
                        type=float,
                        default=1.0,
1374
                        dest='PHIFILE_BIN_RATIO',
1375
                        help="Ratio of binning level between loaded Phi file and current calculation. If the input Phi file has been obtained on a 500x500x500 image and now the calculation is on 1000x1000x1000, this should be 2. Default = 1")
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390

    # parser.add_argument('-glt',
    #                     '--grey-low-threshold',
    #                     type=float,
    #                     default=-numpy.inf,
    #                     dest='GREY_LOW_THRESH',
    #                     help="Grey threshold on mean of reference imagette BELOW which the correlation is not performed. Default = -infinity")
    #
    # parser.add_argument('-ght',
    #                     '--grey-high-threshold',
    #                     type=float,
    #                     default=numpy.inf,
    #                     dest='GREY_HIGH_THRESH',
    #                     help="Grey threshold on mean of reference imagette ABOVE which the correlation is not performed. Default = infinity")

Edward's avatar
Edward committed
1391
1392
1393
1394
1395
1396
    parser.add_argument('-d',
                        '--debug',
                        action="store_true",
                        dest='DEBUG_FILES',
                        help='Output debug files during iterations? Default = False')

1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
    parser.add_argument('-reg',
                        '--registration',
                        action="store_true",
                        dest='REG',
                        help='Perform an initial registration? Default = False')

    parser.add_argument('-regb',
                        '--registration-binning',
                        type=int,
                        default=1,
                        dest='REG_BIN',
                        help='Binning to apply to input images for registration. Default = 1')

    parser.add_argument('-regm',
                        '--registration-margin',
                        type=float,
                        default=0.1,
                        dest='REG_MARGIN',
                        help='Registration margin in proportions of image size. Default = 0.1, which means 0.1 * image size from both sides')

1417
1418
1419
1420
1421
1422
    parser.add_argument('-regu',
                        '--registration-update',
                        action="store_true",
                        dest='REG_UPDATE',
                        help='Update gradient in initial registration? More computation time but more robust and possibly fewer iterations. Default = False')

1423
1424
    parser.add_argument('-mit',
                        '--max-iterations',
Olga Stamati's avatar
Olga Stamati committed
1425
                        type=int,
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
                        default=25,
                        dest='MAX_ITERATIONS',
                        help="Max iterations for global correlation. Default = 25")

    parser.add_argument('-cc',
                        '--convergence-criterion',
                        type=numpy.float,
                        default=0.01,
                        dest='CONVERGENCE_CRITERION',
                        help="Displacement convergence criterion in pixels (norm of incremental displacements). Default = 0.01")

    parser.add_argument('-str',
                        '--calculate-strain',
                        action="store_true",
                        dest='STRAIN',
                        help='Calculate strain? This is added to the VTK output files')
Emmanuel Roubin's avatar
gdic    
Emmanuel Roubin committed
1442

1443
1444
1445
1446
1447
    parser.add_argument('-ss',
                        '--small--strains',
                        action="store_true",
                        dest='SMALL_STRAINS',
                        help='Strain field is computed under the hypothesis of small strain. Default = False')
Emmanuel Roubin's avatar
gdic    
Emmanuel Roubin committed
1448

1449
    # parser.add_argument('-spo',
1450
    #                     '--grid-point-interpolation-order',
1451
1452
    #                     type=numpy.uint,
    #                     default=1,
1453
    #                     dest='GRID_POINT_INTERPOLATION_ORDER',
1454
    #                     help="Subpixel interpolation order. Default = 1")
Emmanuel Roubin's avatar
gdic    
Emmanuel Roubin committed
1455

1456
1457
1458
1459
1460
    # parser.add_argument('-cif',
    #                     '--correct-input-field',
    #                     action="store_true",
    #                     dest='CF',
    #                     help='Correction of the input F field. Default = True')
Emmanuel Roubin's avatar
gdic    
Emmanuel Roubin committed
1461

1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
    # parser.add_argument('-nfi',
    #                     '--neighbours-for-field-interpolation',
    #                     type=numpy.uint,
    #                     default=12,
    #                     dest='NEIGHBOURS',
    #                     help="Neighbours for field interpolation. Default = 12")

    parser.add_argument('-od',
                        '--out-dir',
                        type=str,
                        default=None,
                        dest='OUT_DIR',
                        help="Output directory, default is the dirname of input file")

    parser.add_argument('-pre',
                        '--prefix',
                        type=str,
Emmanuel Roubin's avatar
Emmanuel Roubin committed
1479
                        default=None,
1480
                        dest='PREFIX',
Edward Andò's avatar
Edward Andò committed
1481
                        help="Prefix for output files (without extension). Default is basename of input file")
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494

    parser.add_argument('-Mfile',
                        dest='MESH_FILE',
                        default=None,
                        type=argparse.FileType('rb'),
                        help="Path to pickle file containing mesh information needed for the correlation (coordinates, connectivity, labels and padding). Default = None.")

    parser.add_argument('-Mcube',
                        '--mesh-cuboid',
                        nargs=7,
                        type=numpy.float,
                        default=None,
                        dest='MESH_CUBOID',
1495
                        help='7 floats parameters to mesh a cuboid. first 3 are position of the bottom corner (Z, Y, X), next 3 are the lenghts of the cube (Z, Y, X) and the last one is the average length between two nodes.')
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519

    args = parser.parse_args()

    if args.MESH_FILE is None and args.MESH_CUBOID is None:
        print("\tgdic: a mesh is needed. Use one of this option: -Mcube or -Mfile.")
        print("\tgdic: exiting.")
        exit()

    # If we have no out dir specified, deliver on our default promise -- this can't be done inline before since parser.parse_args() has not been run at that stage.
    if args.OUT_DIR is None:
        args.OUT_DIR = os.path.dirname(args.inFiles[0].name)
        # However if we have no dir, notice this and make it the current directory.
        if args.OUT_DIR == "":
            args.OUT_DIR = "./"
    else:
        # Check existence of output directory
        try:
            if args.OUT_DIR:
                os.makedirs(args.OUT_DIR)
            else:
                args.DIR_out = os.path.dirname(args.inFiles[0].name)
        except OSError:
            if not os.path.isdir(args.OUT_DIR):
                raise
Emmanuel Roubin's avatar
gdic    
Emmanuel Roubin committed
1520

1521
1522
    # Output file name prefix
    if args.PREFIX is None:
Emmanuel Roubin's avatar
Emmanuel Roubin committed
1523
        args.PREFIX = "GDIC_{}-{}".format(os.path.splitext(os.path.basename(args.inFiles[0].name))[0], os.path.splitext(os.path.basename(args.inFiles[1].name))[0])
Emmanuel Roubin's avatar
gdic    
Emmanuel Roubin committed
1524

1525
1526
    if type(args.MAX_ITERATIONS) == list:
        args.MAX_ITERATIONS = args.MAX_ITERATIONS[0]