slice-register.py 33.3 KB
Newer Older
Sean Fitzgibbon's avatar
Sean Fitzgibbon committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
#!/usr/bin/env python
# -*- coding: utf-8 -*-

#   _______   _____   _____    _
#  |__   __| |_   _| |  __ \  | |
#     | |      | |   | |__) | | |
#     | |      | |   |  _  /  | |
#     | |     _| |_  | | \ \  | |____
#     |_|    |_____| |_|  \_\ |______|
#
# Copyright (C) 2018-2020 University of Oxford
# Part of the FMRIB Software Library (FSL)
# Author: Istvan N. Huszar
# Date: 7 June 2020


# FMRIB Software Library, Release 6.0.4 (c) 2020, The University of Oxford
# (the "Software")
# 
# The Software remains the property of the University of Oxford ("the
# University").
# 
# The Software is distributed "AS IS" under this Licence solely for
# non-commercial use in the hope that it will be useful, but in order
# that the University as a charitable foundation protects its assets for
# the benefit of its educational and research purposes, the University
# makes clear that no condition is made or to be implied, nor is any
# warranty given or to be implied, as to the accuracy of the Software,
# or that it will be suitable for any particular purpose or for use
# under any specific conditions. Furthermore, the University disclaims
# all responsibility for the use which is made of the Software. It
# further disclaims any liability for the outcomes arising from using
# the Software.
# 
# The Licensee agrees to indemnify the University and hold the
# University harmless from and against any and all claims, damages and
# liabilities asserted by third parties (including claims for
# negligence) which arise directly or indirectly from the use of the
# Software or the sale of any products based on the Software.
# 
# No part of the Software may be reproduced, modified, transmitted or
# transferred in any form or by any means, electronic or mechanical,
# without the express permission of the University. The permission of
# the University is not required if the said reproduction, modification,
# transmission or transference is done without financial return, the
# conditions of this Licence are imposed upon the receiver of the
# product, and all original and amended source code is included in any
# transmitted product. You may be held legally responsible for any
# copyright infringement that is caused or encouraged by your failure to
# abide by these terms and conditions.
# 
# You are not permitted under this Licence to use this Software
# commercially. Use for which any financial return is received shall be
# defined as commercial use, and includes (1) integration of all or part
# of the source code or the Software into a product for sale or license
# by or on behalf of Licensee to third parties or (2) use of the
# Software or any derivative of it for research with the final aim of
# developing software products for sale or license to a third party or
# (3) use of the Software or any derivative of it for research with the
# final aim of developing non-software products for sale or license to a
# third party, or (4) use of the Software to provide any service to an
# external organisation for which payment is received. If you are
# interested in using the Software commercially, please contact Oxford
# University Innovation ("OUI"), the technology transfer company of the
# University, to negotiate a licence. Contact details are:
# Innovation@innovation.ox.ac.uk quoting reference BS/9564.
# 


"""
Oxford Post-Mortem MND Biomarkers Histology-MRI Registration Pipeline, Stage 1:
Registers a histology slide to the corresponding tissue block photograph.

After the input images are centralised, the registration employs sequential
rigid, affine and non-linear alignment. Depending on the chosen direction of
the registration (default: histology->block), the following TIRL chain is
optimised:

+-------------+
| Fixed image |
+-------------+
    offset:
        [centralisation]-->[resampling]
    chain:
        -->(2D anisotropic scale)-->(2D rigid rotation)-->(2D translation)
        -->(2D full affine)
        -->(2D full-resolution displacement field)

+--------------+
| Moving image |
+--------------+
    offset:
        [centralisation]

The above chain maps the full-resolution 2D histology coordinates to the 2D
space of the tissue block photograph.

"""

__tirlscript__ = True

# DEPENDENCIES

import argparse
import json
import logging
import os
import sys
import warnings
from math import radians, degrees

import numpy as np
import tirl
import tirl.scripts.mnd.image
import tirl.scripts.mnd.inout
import tirl.settings as ts
from attrdict import AttrMap
from skimage.measure import label, regionprops
from tirl.beta import beta_function
from tirl.chain import Chain
from tirl.constants import *
from tirl.costs.mind import CostMIND
from tirl.optimisation.gnoptdiff import GNOptimiserDiffusion
from tirl.optimisation.optgroup import OptimisationGroup
from tirl.optimisation.optnl import OptNL
from tirl.regularisers.diffusion import DiffusionRegulariser
from tirl.tfield import TField
from tirl.timage import TImage
from tirl.transformations.linear.affine import TxAffine
from tirl.transformations.linear.rotation import TxRotation2D
from tirl.transformations.linear.scale import TxScale, TxIsoScale
from tirl.transformations.linear.translation import TxTranslation
from tirl.transformations.nonlinear.displacement import TxDisplacementField

# TIRL IMPORTS
# DEFINITIONS

# Rotation search: number of best initialisations to test
N_BEST = 3
# File extension of the snapshot images
SNAPSHOT_EXT = "png"
# NumPy print formatting
np.set_printoptions(precision=4)


# IMPLEMENTATION

def run(cnf=None, **options):
    """
    Runs TIRL histology-to-fixed registration (stage 1).

    :param cnf:
        Configuration file. If no file is specified (default), the default
        parameters will be used that are embedded in the source code file
        (see Definitions section above). Instead of a file, a dictionary with
        suitable content may also be specified.
    :type cnf: Union[str, dict, None]
    :param options:
        Overriding configuration parameters.
    :type options: Any

    """
    # Load script configuration
    if cnf is not None:
        if isinstance(cnf, dict):
            cnf = dict(cnf)
        elif isinstance(cnf, str):
            with open(cnf, "r") as configfile:
                cnf = dict(json.load(configfile))
        else:
            raise TypeError(
                f"Unrecognised configuration format: {cnf.__.class__.__name__}")
    cnf.update(options)
    p, logger = tirl.scripts.mnd.general.initialise_script(**cnf)
    p.logger = logger.name  # avoid globals

    # Load and configure input images
    if p.moving.export is True:
        ext = ts.EXTENSIONS["TImage"]
        p.moving.export = \
            os.path.join(p.general.outputdir, f"moving.{ext}")
    moving = tirl.scripts.mnd.inout.load_image(scope=globals(), **p.moving)
    if p.fixed.export is True:
        ext = ts.EXTENSIONS["TImage"]
        p.fixed.export = os.path.join(p.general.outputdir, f"fixed.{ext}")
    fixed = tirl.scripts.mnd.inout.load_image(scope=globals(), **p.fixed)

    # Having loaded both images, perform actions on the histology image prior
    # to registration, unless it was loaded from a TImage.
    # Actions are user-defined functions within the TIRL namespace. Actions
    # can be chain-loaded to perform preparatory analysis steps on the images
    # before registration begins.
    isalternative = p.moving.file.lower().endswith(
        (ts.EXTENSIONS["TImage"], ts.EXTENSIONS["TIRLObject"]))
    if not isalternative:
        moving = tirl.scripts.mnd.image.perform_image_operations(
            moving, *p.preprocessing.moving, scope=globals(), other=fixed,
            cnf=p)
        # Initialise registration frame
        moving.centralise(weighted=True)

    # Perform actions on the fixed image prior to registration, unless it was
    # loaded from a TImage file.
    isalternative = p.fixed.file.lower().endswith(
        (ts.EXTENSIONS["TImage"], ts.EXTENSIONS["TIRLObject"]))
    if not isalternative:
        fixed = tirl.scripts.mnd.image.perform_image_operations(
            fixed, *p.preprocessing.fixed, scope=globals(), other=moving, cnf=p)
        fixed.centralise(weighted=True)

    # Run the registration routine
    try:
        register(fixed, moving, p)
    except Exception as exc:
        logger.error(exc.args)
        logger.fatal(f"The registration terminated with an exception.")
        raise exc
    else:
        logger.fatal("The registration was completed successfully.")


def labkmeans(histo, **kwargs):
    """
    Segments the foreground (tissue) in a histological slide and sets it as the
    TImage mask.

    This method was tested on slides that were stained with DAB + haematoxylin,
    and scanned with a bright white background. The method was also effectively
    removing the shadow effect close to the slide edge.

    """
    from skimage.color import rgb2lab
    from sklearn.cluster import KMeans
    from skimage.exposure import rescale_intensity
    orig_order = histo.order
    histo.order = VOXEL_MAJOR
    imdata = np.asarray(
        rescale_intensity(histo.data[..., :3], out_range=np.uint8),
        dtype=np.uint8)
    lab_a = rgb2lab(imdata)[..., 1]
    X = lab_a.reshape(-1, 1)
    km = KMeans(n_clusters=2, random_state=0).fit(X)
    kc = km.cluster_centers_
    mask = km.labels_.reshape(histo.vshape)
    if kc[0] > kc[1]:  # make sure that the lower intensity is labeled 0
        mask = 1 - mask
    histo.order = orig_order
    return mask


def initialise_transformations(fixed, p):
    """
    Create transformation chain that will be optimised.

    """
    q = p.regparams

    # Scale
    lb = np.asarray(q.init.scale.lb)
    ub = np.asarray(q.init.scale.ub)
    if p.general.isotropic:
        bounds = (float(lb), float(ub))
        tx_scale = TxIsoScale(
            float(q.init.scale.x0), dim=2, bounds=bounds, name="scale")
    else:
        tx_scale = TxScale(*q.init.scale.x0, bounds=(lb, ub), name="scale")

    # Rotation
    if str(q.init.rotation.mode).lower() == "deg":
        lb = radians(float(q.init.rotation.lb))
        ub = radians(float(q.init.rotation.ub))
    else:
        lb = float(q.init.rotation.lb)
        ub = float(q.init.rotation.ub)
    tx_rotation = TxRotation2D(
        float(q.init.rotation.x0), mode=q.init.rotation.mode,
        bounds=(lb, ub), name="rotation")

    # Translation
    lb = np.asarray(q.init.translation.lb)
    ub = np.asarray(q.init.translation.ub)
    tx_trans = TxTranslation(
        *q.init.translation.x0, bounds=(lb, ub), name="translation")

    # Affine
    x0 = np.asarray(q.init.affine.x0).reshape((2, 3))
    lb = np.asarray(q.init.affine.lb)
    ub = np.asarray(q.init.affine.ub)
    tx_affine = TxAffine(x0, bounds=(lb, ub), name="affine")

    # Append linear transformations to the domain of the fixed image
    linear_chain = Chain(tx_rotation, tx_scale, tx_trans, tx_affine)
    domain = fixed.domain[:]
    domain.chain.extend(linear_chain)

    # Nonlinear
    x0 = float(q.init.nonlinear.x0) * np.ones((2, *fixed.vshape))
    if q.init.nonlinear.lb is None:
        lb = None
    else:
        lb = float(q.init.nonlinear.lb) * np.ones_like(x0)
    if q.init.nonlinear.ub is None:
        ub = None
    else:
        ub = float(q.init.nonlinear.ub) * np.ones_like(x0)
    field = TField.fromarray(
        x0, tensor_axes=(0,), copy=False, domain=domain[:], order=TENSOR_MAJOR)
    tx_nonlinear = TxDisplacementField(
        field, bounds=(lb, ub), name="nonlinear", mode=NL_REL)

    # Return the full transformation chain
    return Chain(*linear_chain, tx_nonlinear)


def register(fixed, moving, cnf):
    """
    Runs the four registration stages: rotation search, rigid, affine, and
    non-linear. The function has no return value. The transformation chain is
    attached to the Domain of the fixed TImage object and is optimised in situ.

    :param fixed:
        fixed image (to which the chain is attached)
    :type fixed: TImage
    :param moving:
        moving image (that defines the coordinate space that the mapping
        is into)
    :type moving: TImage
    :param cnf: all configuration options
    :type cnf: dict or AttrMap

    """
    p = AttrMap(cnf)
    q = p.regparams
    logger = logging.getLogger(p.logger)

    # Create transformation chain (does not change the fixed image)
    # rotation -> scale -> translation -> affine -> nonlinear
    logger.info("Initialising transformation chain...")
    chain = initialise_transformations(fixed, p)
    logger.info("Transformation chain has been initialised.")

    # Generate output: initial alignment
    fixed.save(os.path.join(
        p.general.outputdir, "fixed.timg"), overwrite=True)
    fixed.snapshot(os.path.join(
        p.general.outputdir, f"fixed.{SNAPSHOT_EXT}"), overwrite=True)
    moving.save(os.path.join(
        p.general.outputdir, "moving.timg"), overwrite=True)
    moving.snapshot(os.path.join(
        p.general.outputdir, f"moving.{SNAPSHOT_EXT}"), overwrite=True)

    # Set the first part of the chain
    fixed.domain.chain.extend(chain[:-2])

    # Rotation search
    if "rotation" in p.general.stages:
        logger.info("Starting rotation search...")
        rotation_search2d(fixed, moving, p)
        logger.info("Completed rotation search.")
        # Generate output
        fixed.save(os.path.join(
            p.general.outputdir, "fixed1_rotation.timg"), overwrite=True)
        moving.evaluate(fixed.domain).snapshot(os.path.join(
            p.general.outputdir, f"moving1_rotation.{SNAPSHOT_EXT}"),
            overwrite=True)
    else:
        logger.info("Rotation search was skipped.")

    # Rigid registration
    if "rigid" in p.general.stages:
        logger.info("Starting rigid registration...")
        rigid2d(fixed, moving, p)
        logger.info("Completed rigid registration.")
        # Generate output
        fixed.save(os.path.join(
            p.general.outputdir, "fixed2_rigid.timg"), overwrite=True)
        moving.evaluate(fixed.domain).snapshot(os.path.join(
            p.general.outputdir, f"moving2_rigid.{SNAPSHOT_EXT}"),
            overwrite=True)
    else:
        logger.info("Rigid registration was skipped.")

    # Affine registration
    fixed.domain.chain.append(chain[-2])
    if "affine" in p.general.stages:
        logger.info("Starting affine registration...")
        affine2d(fixed, moving, p)
        logger.info("Completed affine registration.")
        # Generate output
        fixed.save(os.path.join(
            p.general.outputdir, "fixed3_affine.timg"), overwrite=True)
        moving.evaluate(fixed.domain).snapshot(os.path.join(
            p.general.outputdir, f"moving3_affine.{SNAPSHOT_EXT}"),
            overwrite=True)
    else:
        logger.info("Affine registration was skipped.")

    # Non-linear registration
    tx_nonlinear = chain[-1]
    tx_nonlinear.domain.chain = fixed.domain.chain[:]
    fixed.domain.chain.append(tx_nonlinear)
    if "nonlinear" in p.general.stages:
        logger.info("Starting non-linear registration...")
        diffreg2d(fixed, moving, p)
        logger.info("Completed non-linear registration.")
        # Generate output
        fixed.save(os.path.join(
            p.general.outputdir, "fixed4_nonlinear.timg"), overwrite=True)
        moving.evaluate(fixed.domain).snapshot(os.path.join(
            p.general.outputdir, f"moving4_nonlinear.{SNAPSHOT_EXT}"),
            overwrite=True)
    else:
        logger.info("Non-linear registration was skipped.")


def rotation_search2d(fixed, moving, cnf):
    """
    Finds the best relative orientation of the images.

    :param fixed: Fixed image.
    :type fixed: TImage
    :param moving: Moving image.
    :type moving: TImage
    :param cnf: all configuration options
    :type cnf: dict or AttrMap

    """
    p = AttrMap(cnf)
    q = p.regparams.rotsearch
    logger = logging.getLogger(p.logger)

    # Part 1: coarse search for N best orientations

    # Coarse search at a predefined scale
    fixed.resample(float(q.scale), copy=False)
    moving.resample(float(q.scale), copy=False)

    step = radians(q.coarse)
    tx_rotation = fixed.domain.chain["rotation"]
    lb, ub = tx_rotation.parameters.get_bounds()[0]
    rotations = np.arange(lb, ub, step)
    costvals = []
    for i, angle in enumerate(rotations):
        tx_rotation.parameters.parameters[0] = angle
        tx_rotation.parameters.set_lower_bounds(angle - step / 2)
        tx_rotation.parameters.set_upper_bounds(angle + step / 2)
        cost = CostMIND(moving, fixed, normalise=True, kernel=MK_FULL)()
        #         cost = CostMI(moving, fixed, normalise=True, bins=32)()
        logger.debug(f"{degrees(angle)} deg: {cost}")
        costvals.append([cost, angle])
    else:
        costvals = np.asarray(costvals)

    # Test the best N initial rotations
    n_best = max(min(N_BEST, len(rotations)), 1)
    best_angles = costvals[np.argsort(costvals[:, 0]), 1][:n_best].ravel()
    logger.info(f"The {n_best} best initialisation angles: "
                f"{np.rad2deg(best_angles)} deg")

    # Part 2: fine-tune the rotation parameter by simultaneous additional
    # optimisation of translation and scaling, starting from the best three
    # orientations.
    tx_scale = fixed.domain.chain["scale"]
    tx_translation = fixed.domain.chain["translation"]
    og = OptimisationGroup(tx_rotation, tx_scale, tx_translation)
    scale_orig = tx_scale.parameters.parameters.copy()
    translation_orig = tx_translation.parameters.parameters.copy()
    costvals = []
    for angle in best_angles:
        tx_rotation.parameters.parameters[0] = angle
        tx_rotation.parameters.set_lower_bounds(angle - step / 2)
        tx_rotation.parameters.set_upper_bounds(angle + step / 2)
        tx_rotation.parameters.unlock()
        tx_scale.parameters.parameters[:] = scale_orig.copy()
        tx_translation.parameters.parameters[:] = translation_orig.copy()
        # Rescale to the same predefined resolution as above
        fixed.resample(float(q.scale), copy=False)
        moving.resample(float(q.scale), copy=False)
        # Set cost function
        cost = CostMIND(moving, fixed, maskmode="and", normalise=True)
        #         cost = CostMI(moving, fixed, maskmode="and", normalise=True)
        # Start optimisation
        logger.info(f"Co-optimising scale and translation at "
                    f"{degrees(angle)} deg...")

        OptNL(og, cost, method="LN_BOBYQA", visualise=q.visualise,
              xtol_abs=q.xtol_abs, xtol_rel=q.xtol_rel, step=q.opt_step,
              logger=logger, normalised=True)()
        costvals.append((cost(), og.parameters[:]))

    # Find best initialisation based on cost
    best_params = min(costvals, key=lambda r: r[0])[1]
    logger.info(f"Best parameters after rotation search: {best_params}")
    og.set(best_params)
    tx_rotation.parameters.set_lower_bounds(best_params[0] - step / 2)
    tx_rotation.parameters.set_upper_bounds(best_params[0] + step / 2)
    tx_rotation.parameters.unlock()

    # moving_mnd = CostMIND(moving, fixed, maskmode="and", normalise=True).mind(moving)
    # np.save('grot_moving_mind', moving_mnd.data)
    #
    # fixed_mnd = CostMIND(moving, fixed, maskmode="and", normalise=True).mind(fixed)
    # np.save('grot_fixed_mind', fixed_mnd.data)
    #
    # np.save('moving_mask', moving_mnd.mask)
    # np.save('fixed_mask', fixed_mnd.mask)

    # Return to full resolution after the rotation search
    fixed.resample(1, copy=False)
    moving.resample(1, copy=False)

    # moving_mnd = CostMIND(moving, fixed, maskmode="and", normalise=True).mind(moving)
    # np.save('grot_moving_mind_full', moving_mnd.data)
    #
    # fixed_mnd = CostMIND(moving, fixed, maskmode="and", normalise=True).mind(fixed)
    # np.save('grot_fixed_mind_full', fixed_mnd.data)


def rigid2d(fixed, moving, cnf):
    """
    Optimises rigid-body parameters and scaling.

    """
    p = AttrMap(cnf)
    q = p.regparams.rigid
    logger = logging.getLogger(p.logger)

    # Scaling-smoothing iteration
    for i, (sc, sm) in enumerate(zip(q.scaling, q.smoothing)):
        logger.debug(f"Scale: {sc}, smoothing: {sm} px...")
        # Prepare images for the current iteration
        fixed.resample(1. / sc, copy=False)
        moving.resample(1. / sc, copy=False)
        fixed_smooth = fixed.smooth(sm, copy=True)
        moving_smooth = moving.smooth(sm, copy=True)
        # Prepare co-optimised transformations
        tx_rotation = fixed_smooth.domain.chain["rotation"]
        tx_scale = fixed_smooth.domain.chain["scale"]
        tx_translation = fixed_smooth.domain.chain["translation"]
        og = OptimisationGroup(tx_rotation, tx_scale, tx_translation)
        lb, ub = og.get_bounds().T
        lb = lb - np.finfo(lb.dtype).eps
        ub = ub + np.finfo(lb.dtype).eps
        og.set_bounds(lb, ub)
        # Set cost function
        #         cost = CostMI(moving_smooth, fixed_smooth, normalise=True)
        cost = CostMIND(moving_smooth, fixed_smooth, normalise=True)
        # Start optimisation
        OptNL(og, cost, method="LN_BOBYQA", visualise=q.visualise,
              xtol_abs=q.xtol_abs, xtol_rel=q.xtol_rel, step=q.opt_step,
              logger=logger, normalised=True)()

        # Transfer optimised transformations to the non-smoothed images
        fixed.domain = fixed_smooth.domain
        moving.domain = moving_smooth.domain
    else:
        # Restore full resolution of the images
        fixed.resample(1, copy=False)
        moving.resample(1, copy=False)

    # np.save('grot_moving_mind_rigid', cost.mind(moving).data)
    # np.save('grot_fixed_mind_rigid', cost.mind(fixed).data)


def affine2d(fixed, moving, cnf):
    """
    Optimises a 6-DOF affine transformation after rigid alignment has been
    fine-tuned.

    """
    p = AttrMap(cnf)
    q = p.regparams.affine
    logger = logging.getLogger(p.logger)

    # Scaling-smoothing iterations
    for i, (sc, sm) in enumerate(zip(q.scaling, q.smoothing)):
        logger.debug(f"Scale: {sc}, smoothing: {sm} px...")
        # Prepare images for the current iteration
        fixed.resample(1. / sc, copy=False)
        moving.resample(1. / sc, copy=False)
        fixed_smooth = fixed.smooth(sm, copy=True)
        moving_smooth = moving.smooth(sm, copy=True)
        # Prepare transformation to optimise
        tx_affine = fixed_smooth.domain.chain["affine"]
        # Set cost function
        #         cost = CostMI(moving_smooth, fixed_smooth, normalise=True)
        cost = CostMIND(moving_smooth, fixed_smooth, normalise=True)
        # Start optimisation
        OptNL(tx_affine, cost, method="LN_BOBYQA",
              xtol_rel=q.xtol_rel, xtol_abs=q.xtol_abs,
              visualise=q.visualise, step=q.opt_step, logger=logger,
              normalised=True)()
        # Transfer optimised transformations to the non-smoothed images
        fixed.domain = fixed_smooth.domain
        moving.domain = moving_smooth.domain
    else:
        # Restore full resolution of the images
        fixed.resample(1, copy=False)
        moving.resample(1, copy=False)

    # np.save('grot_moving_mind_affine', cost.mind(moving).data)
    # np.save('grot_fixed_mind_affine', cost.mind(fixed).data)


def diffreg2d(fixed, moving, cnf):
    """
    Performs a non-linear registration. The transformation is parameterised as
    a dense displacement field. The cost is MIND, and diffusion regularisation
    is used to create smoothness in the deformation field.

    """
    p = AttrMap(cnf)
    q = p.regparams.nonlinear
    logger = logging.getLogger(p.logger)

    # Scaling-smoothing iteration
    for i, (sc, sm) in enumerate(zip(q.scaling, q.smoothing)):
        logger.debug(f"Scale: {sc}, smoothing: {sm} px...")
        # Prepare images for the current iteration
        fixed.resample(1 / sc, copy=False)
        moving.resample(1 / sc, copy=False)
        fixed_smooth = fixed.smooth(sm, copy=True)
        moving_smooth = moving.smooth(sm, copy=True)
        # Prepare transformation to optimise
        tx_nonlinear = fixed_smooth.domain.chain[-1]
        # Set cost and regulariser
        cost = CostMIND(moving_smooth, fixed_smooth, sigma=float(q.sigma),
                        truncate=float(q.truncate), kernel=MK_FULL)
        regularisation = DiffusionRegulariser(
            tx_nonlinear, weight=float(q.regweight))
        # Optimise the non-linear transformation
        GNOptimiserDiffusion(
            tx_nonlinear, cost, regularisation, maxiter=int(q.maxiter[i]),
            xtol_rel=q.xtol_rel, xtol_abs=q.xtol_abs, visualise=q.visualise,
            logger=logger)()
        # Transfer optimised transformations to the non-smoothed images
        fixed.domain = fixed_smooth.domain
        moving.domain = moving_smooth.domain
    else:
        # Restore the original resolution of the images
        fixed.resample(1, copy=False)
        moving.resample(1, copy=False)

        # AUXILIARY FUNCTIONS


# These functions may be used within other functions of the script. Their usage
# outside this script (via importing from this module) is discouraged. They are
# included here to prevent too frequent code repetitions.

def rgb2hsv(x):
    assert x.shape[-1] == 3, "The input must be RGB."
    _x = x / 255
    _x = _x.reshape(-1, 3)
    c_min = np.min(_x, axis=-1)
    c_max = np.max(_x, axis=-1)
    delta = c_max - c_min
    r, g, b = _x.reshape(-1, 3).T
    r = r.ravel()
    g = g.ravel()
    b = b.ravel()
    i2 = c_max == r
    i3 = c_max == g
    i4 = c_max == b

    # Calculate Hue
    h = np.zeros(r.size)
    h[i2] = 60 * ((g[i2] - b[i2]) / delta[i2] % 6)
    h[i3] = 60 * ((b[i3] - r[i3]) / delta[i3] + 2)
    h[i4] = 60 * ((r[i4] - g[i4]) / delta[i4] + 4)

    # Calculate Saturation
    s = np.where(np.isclose(c_max, 0), 0, delta / c_max)

    # Calculate Value
    v = c_max

    x_hsv = np.stack((h.ravel(), s.ravel(), v.ravel()), axis=-1)
    return x_hsv


def match_fixed_resolution(img, **kwargs):
    """
    Resamples histology image to match the resolution of another 2D image.

    """
    p = AttrMap(kwargs.get("cnf"))
    logger = logging.getLogger(p.logger)
    other = kwargs.get("other")

    res = other.resolution
    factors = np.divide(img.resolution, res)
    logger.info(f"Resampling 2D image by factors {tuple(factors)}...")
    img = img.resample(*factors, copy=True)
    img.reset_resmgr()
    img.storage = MEM
    img.domain.storage = MEM
    logger.info(f"Shape of the 2D image after resampling: {img.shape}.")

    # Save low-resolution image
    fp, fn = os.path.split(p.moving.file)
    fn, ext = os.path.splitext(fn)
    filename = os.path.join(p.general.outputdir, f"{fn}_lowres.{SNAPSHOT_EXT}")
    img.snapshot(filename, overwrite=True)
    logger.info(f"Saved low-resolution snapshot of the 2D image to: {filename}")

    return img


def resample40(img, **kwargs):
    p = AttrMap(kwargs.get("cnf"))
    logger = logging.getLogger(p.logger)

    logger.info(f"Shape of the 2D image before resampling: {img.shape}.")
    logger.info(f"Resolution of the 2D image before resampling: {img.resolution}.")
    factors = np.divide(img.resolution, 0.04)

    img = img.resample(*factors, copy=True)
    img.reset_resmgr()
    img.storage = MEM
    img.domain.storage = MEM
    logger.info(f"Shape of the 2D image after resampling: {img.shape}.")
    logger.info(f"Resolution of the 2D image after resampling: {img.resolution}.")

    # Save low-resolution image
    fp, fn = os.path.split(p.histology.file)
    fn, ext = os.path.splitext(fn)
    filename = os.path.join(p.general.outputdir, f"{fn}_lowres.{SNAPSHOT_EXT}")
    img.snapshot(filename, overwrite=True)
    logger.info(f"Saved low-resolution snapshot of the 2D image to: {filename}")

    return img


def moving_preprocessing(histo, **kwargs):
    """
    Preprocess the histology image.

    """
    # Convert to grayscale using the Y channel of the YIQ colour space.
    return tirl.scripts.mnd.image.rgb2yiq(histo.tensors[:3]).tensors[0]


def preprocessing_resample(img, **kwargs):
    p = AttrMap(kwargs.get("cnf"))
    logger = logging.getLogger(p.logger)
    img = img.resample(1 / 10, copy=True)
    img.reset_resmgr()
    img.storage = MEM
    img.domain.storage = MEM
    logger.info(f"Shape of the 2D image after resampling: {img.shape}.")

    # Save low-resolution image
    fp, fn = os.path.split(p.histology.file)
    fn, ext = os.path.splitext(fn)
    filename = os.path.join(p.general.outputdir, f"{fn}_resampled.{SNAPSHOT_EXT}")
    img.snapshot(filename, overwrite=True)
    logger.info(f"Saved low-resolution snapshot of the 2D image to: {filename}")

    return img


def fixed_preprocessing(block, **kwargs):
    """
    Preprocess the block photograph.

    """
    # Convert to grayscale using the Y channel of the YIQ colour space.
    return tirl.scripts.mnd.image.rgb2yiq(block.tensors[:3]).tensors[0]


def hsv_sat(timg, **kwargs):
    from skimage.color import rgb2hsv
    hsv = rgb2hsv(timg.data)
    return hsv[..., 1]


def hsv_invsat(timg, **kwargs):
    from skimage.color import rgb2hsv
    hsv = rgb2hsv(timg.data)
    return 1 - hsv[..., 1]


def dilated_object_mask(timg, **kwargs):
    from skimage.color import rgb2hsv
    hsv = rgb2hsv(timg.data)
    objmask = hsv[..., 2] > 0.1
    from skimage.morphology import binary_dilation
    objmask = binary_dilation(objmask.astype(np.uint8), selem=np.ones((20, 20)))
    return objmask.astype(np.float32)


@beta_function
def mask_roi_defects(histo, block, p):
    # Highlight non-matching areas between affine-registered images
    tmp = histo.evaluate(block.domain)
    tmp = np.where(tmp.data > 0.05, 1, 0)
    binary = np.where(block.data > 1, 1, 0)
    totalarea = np.count_nonzero(binary)
    # print(totalarea)
    area = p.area * totalarea if p.area < 1 else p.area
    # print(area)
    binary[tmp == 1] = 0
    del tmp

    # Discard small regions, that should actually drive non-linear registration

    # Area filter
    labels = label(binary, background=0, connectivity=binary.ndim)
    regions = regionprops(labels)
    # print(sorted([region["area"] for region in regions])[::-1])
    large_region_labels = [region["label"] for region in regions
                           if region["area"] > area]
    binary[...] = 0
    for value in large_region_labels:
        binary[labels == value] = 1

    labels = label(binary, background=0, connectivity=binary.ndim)
    n_defects = np.max(labels)
    TImage(labels).preview()

    # Warn the user about ROI defects
    if n_defects:
        warnings.warn("Number of ROI defects found: {}.".format(int(n_defects)))

    # Add the identified ROI defects to the block mask
    binary = 1 - binary
    bmask = block.mask.data
    # bmask[bmask == 0.1] = 0
    block.mask = bmask * binary


def pad(timg, **kwargs):
    """ Zero-pads the image by 1/5 of the image shape on both ends along each
    spatial dimension. """
    padding = []
    for dim in timg.vshape:
        padding.append((dim // 6, dim // 6))
    padding = tuple(padding)
    offset = TxTranslation([-pad[0] for pad in padding], name="padding")
    lpad = ((0, 0),) * timg.tdim
    if timg.order == TENSOR_MAJOR:
        padding = lpad + padding
    else:
        padding = padding + lpad
    imdata = np.pad(timg.data, padding, mode="maximum")
    offset = offset + timg.domain.offset
    chain = timg.domain.chain
    padded = TImage.fromarray(imdata, tensor_axes=timg.taxes)
    padded.domain.offset = offset
    padded.domain.chain = chain
    return padded

    # PROGRAM FLOW CONTROL


def slide_to_slide(args):
    """
    Main program code. Controls program flow, handles command-line arguments.

    """
    cnf = args.config
    if os.path.isfile(cnf):
        with open(cnf, "r") as fp:
            cnf = dict(json.load(fp))
    else:
        raise FileNotFoundError(f"The provided configuration file "
                                f"does not exist: {args.config}")

    # Override histology and block file paths in the configuration file with
    # those provided on the command line.
    if args.moving and os.path.isfile(args.moving):
        cnf["moving"]["file"] = args.moving
    if args.fixed and os.path.isfile(args.fixed):
        cnf["fixed"]["file"] = args.fixed
    if args.out:
        cnf["general"]["outputdir"] = args.out
        cnf["general"]["logfile"] = f'{args.out}/logfile.log'
        cnf["general"]["paramlogfile"] = f'{args.out}/paramlog.log'

    # Override verbose option in configurations
    cnf["general"]["verbose"] = args.verbose

    # Run registration script
    run(cnf)


def create_cli(parser):
    """
    Sets up the CLI argument parser instance.

    """
    parser.add_argument("--moving", metavar="image",
                        help="Moving slide", default=None, type=str,
                        required=False)
    parser.add_argument("--fixed", metavar="image",
                        help="Fixed slide", default=None, type=str,
                        required=False)
    parser.add_argument("--out", metavar="dir",
                        help="Output directory", default=None, type=str,
                        required=False)
    parser.add_argument("--config", metavar="cnf_file.json",
                        help="configuration file", default='default.json', type=str,
                        required=False)
    parser.add_argument("-v", "--verbose", default=False, action="store_true",
                        help="Print status messages to the command line",
                        required=False)

    return parser


def main(*args):
    """ Main program code. """

    parser = argparse.ArgumentParser(
        prog="slide_to_slide",
        description="Registers a histology slide to "
                    "another histology slide.")
    parser = create_cli(parser)

    if args:
        slide_to_slide(parser.parse_args(args))
    else:
        parser.print_help()


if __name__ == "__main__":
    main(*sys.argv[1:])