/
coordinate_map.py
1850 lines (1453 loc) · 60.6 KB
/
coordinate_map.py
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
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
This module describes two types of *mappings*:
* CoordinateMap: a general function from a domain to a range, with a possible
inverse function.
* AffineTransform: an affine function from a domain to a range, not
necessarily of the same dimension, hence not always invertible.
Each of these objects is meant to encapsulate a tuple of
(domain, range, function).
Each of the mapping objects contain all the details about their domain
CoordinateSystem, their range CoordinateSystem and the mapping between
them.
Common API
----------
They are separate classes, neither one inheriting from the other.
They do, however, share some parts of an API, each having methods:
* renamed_domain : rename on the coordinates of the domain (returns a new mapping)
* renamed_range : rename the coordinates of the range (returns a new mapping)
* reordered_domain : reorder the coordinates of the domain (returns a new mapping)
* reordered_range : reorder the coordinates of the range (returns a new mapping)
* inverse : when appropriate, return the inverse *mapping*
These methods are implemented by module level functions of the same name.
They also share some attributes:
* ndims : the dimensions of the domain and range, respectively
* function_domain : CoordinateSystem describing the domain
* function_range : CoordinateSystem describing the range
Operations on mappings (module level functions)
-----------------------------------------------
* compose : Take a sequence of mappings (either CoordinateMaps or AffineTransforms)
and return their composition. If they are all AffineTransforms, an AffineTransform is
returned. This checks to ensure that domains and ranges of the various
mappings agree.
* product : Take a sequence of mappings (either CoordinateMaps or AffineTransforms)
and return a new mapping that has domain and range given by the concatenation of their
domains and ranges, and the mapping simply concatenates the output of
each of the individual mappings. If they are all AffineTransforms, an AffineTransform is
returned. If they are all AffineTransforms that are in fact linear (i.e. origin=0)
then can is represented as a block matrix with the size of the blocks determined by
* concat : Take a mapping and prepend a coordinate to its domain and range.
For mapping `m`, this is the same as product(AffineTransform.identity('concat'), `m`)
"""
import warnings
import numpy as np
from nipy.utils.onetime import setattr_on_read
import nipy.core.transforms.affines as affines
from nipy.core.reference.coordinate_system import(CoordinateSystem,
safe_dtype)
from nipy.core.reference.coordinate_system import product as coordsys_product
# shorthand
CS = CoordinateSystem
__docformat__ = 'restructuredtext'
class CoordinateMap(object):
"""A set of domain and range CoordinateSystems and a function between them.
For example, the function may represent the mapping of a voxel
(the domain of the function) to real space (the range).
The function may be an affine or non-affine
transformation.
Attributes
----------
function_domain : :class:`CoordinateSystem`
The input coordinate system.
function_range : :class:`CoordinateSystem`
The output coordinate system.
function : callable
A callable that maps the function_domain to the function_range.
inverse_function : None or callable
A callable that maps the function_range to the function_domain.
Not all functions have an inverse, in which case
inverse_function is None.
Examples
--------
>>> function_domain = CoordinateSystem('ijk', 'voxels')
>>> function_range = CoordinateSystem('xyz', 'world')
>>> mni_orig = np.array([-90.0, -126.0, -72.0])
>>> function = lambda x: x + mni_orig
>>> inv_function = lambda x: x - mni_orig
>>> cm = CoordinateMap(function_domain, function_range, function, inv_function)
Map the first 3 voxel coordinates, along the x-axis, to mni space:
>>> x = np.array([[0,0,0], [1,0,0], [2,0,0]])
>>> cm.function(x)
array([[ -90., -126., -72.],
[ -89., -126., -72.],
[ -88., -126., -72.]])
>>> x = CoordinateSystem('x')
>>> y = CoordinateSystem('y')
>>> m = CoordinateMap(x, y, np.exp, np.log)
>>> m
CoordinateMap(
function_domain=CoordinateSystem(coord_names=('x',), name='', coord_dtype=float64),
function_range=CoordinateSystem(coord_names=('y',), name='', coord_dtype=float64),
function=<ufunc 'exp'>,
inverse_function=<ufunc 'log'>
)
>>> m.inverse()
CoordinateMap(
function_domain=CoordinateSystem(coord_names=('y',), name='', coord_dtype=float64),
function_range=CoordinateSystem(coord_names=('x',), name='', coord_dtype=float64),
function=<ufunc 'log'>,
inverse_function=<ufunc 'exp'>
)
>>>
"""
_doc = {}
function = np.exp
_doc['function'] = 'The function from function_domain to function_range.'
function_domain = CoordinateSystem('x')
_doc['function_domain'] = 'The domain of the function, a CoordinateSystem.'
function_range = CoordinateSystem('y')
_doc['function_range'] = 'The range of the function, a CoordinateSystem.'
inverse_function = np.log
_doc['inverse_function'] = 'The inverse function from function_range' + \
'to function_domain, if supplied.'
ndims = (1,1)
_doc['ndims'] = 'Number of dimensions of domain and range, respectively.'
def __init__(self, function_domain,
function_range,
function,
inverse_function=None):
"""Create a CoordinateMap given the function and its
domain and range.
Parameters
----------
function : callable
The function between function_domain and function_range.
function_domain : :class:`CoordinateSystem`
The input coordinate system
function_range : :class:`CoordinateSystem`
The output coordinate system
inverse_function : None or callable, optional
The optional inverse of function, with the intention being
``x = inverse_function(function(x))``. If the function is
affine and invertible, then this is true for all x. The
default is None
Returns
-------
coordmap : CoordinateMap
"""
warnings.warn('CoordinateMaps are not as robust as AffineTransform')
# These attrs define the structure of the coordmap.
self.function = function
self.function_domain = function_domain
self.function_range = function_range
self.inverse_function = inverse_function
self.ndims = (function_domain.ndim, function_range.ndim)
if not callable(function):
raise ValueError('The function must be callable.')
if inverse_function is not None:
if not callable(inverse_function):
raise ValueError('The inverse_function must be callable.')
self._checkfunction()
# All attributes are read only
def __setattr__(self, key, value):
if key in self.__dict__:
raise AttributeError('the value of %s has already been set and all attributes are read-only' % key)
object.__setattr__(self, key, value)
###################################################################
#
# Properties
#
###################################################################
###################################################################
#
# Methods
#
###################################################################
def reordered_domain(self, order=None):
"""
Create a new CoordinateMap with the coordinates of function_domain reordered.
Default behaviour is to reverse the order of the coordinates.
Parameters
----------
order: sequence
Order to use, defaults to reverse. The elements
can be integers, strings or 2-tuples of strings.
If they are strings, they should be in
mapping.function_domain.coord_names.
Returns:
--------
newmapping :CoordinateMap
A new CoordinateMap with the coordinates of function_domain reordered.
>>> input_cs = CoordinateSystem('ijk')
>>> output_cs = CoordinateSystem('xyz')
>>> cm = CoordinateMap(input_cs, output_cs, lambda x:x+1)
>>> print cm.reordered_domain('ikj').function_domain
CoordinateSystem(coord_names=('i', 'k', 'j'), name='', coord_dtype=float64)
"""
return reordered_domain(self, order)
def reordered_range(self, order=None):
"""
Create a new CoordinateMap with the coordinates of function_range reordered.
Defaults to reversing the coordinates of function_range.
Parameters
----------
order: sequence
Order to use, defaults to reverse. The elements
can be integers, strings or 2-tuples of strings.
If they are strings, they should be in
mapping.function_range.coord_names.
Returns:
--------
newmapping : CoordinateMap
A new CoordinateMap with the coordinates of function_range reordered.
>>> input_cs = CoordinateSystem('ijk')
>>> output_cs = CoordinateSystem('xyz')
>>> cm = CoordinateMap(input_cs, output_cs, lambda x:x+1)
>>> print cm.reordered_range('xzy').function_range
CoordinateSystem(coord_names=('x', 'z', 'y'), name='', coord_dtype=float64)
>>> print cm.reordered_range([0,2,1]).function_range.coord_names
('x', 'z', 'y')
>>> newcm = cm.reordered_range('yzx')
>>> newcm.function_range.coord_names
('y', 'z', 'x')
"""
return reordered_range(self, order)
def renamed_domain(self, newnames, name=''):
"""
Create a new CoordinateMap with the coordinates of function_domain renamed.
Inputs:
-------
newnames: dictionary
A dictionary whose keys are integers or are in
mapping.function_domain.coord_names
and whose values are the new names.
Returns:
--------
newmaping : CoordinateMap
A new CoordinateMap with renamed function_domain.
>>> domain = CoordinateSystem('ijk')
>>> range = CoordinateSystem('xyz')
>>> cm = CoordinateMap(domain, range, lambda x:x+1)
>>> new_cm = cm.renamed_domain({'i':'phase','k':'freq','j':'slice'})
>>> print new_cm.function_domain
CoordinateSystem(coord_names=('phase', 'slice', 'freq'), name='', coord_dtype=float64)
>>> new_cm = cm.renamed_domain({'i':'phase','k':'freq','l':'slice'})
Traceback (most recent call last):
...
ValueError: no domain coordinate named l
>>>
"""
return renamed_domain(self, newnames)
def renamed_range(self, newnames, name=''):
"""
Create a new CoordinateMap with the coordinates of function_domain renamed.
Inputs:
-------
newnames: dictionary
A dictionary whose keys are integers or are in
mapping.function_range.coord_names
and whose values are the new names.
Returns:
--------
newmapping : CoordinateMap
A new CoordinateMap with renamed function_range.
>>> domain = CoordinateSystem('ijk')
>>> range = CoordinateSystem('xyz')
>>> cm = CoordinateMap(domain, range, lambda x:x+1)
>>> new_cm = cm.renamed_range({'x':'u'})
>>> print new_cm.function_range
CoordinateSystem(coord_names=('u', 'y', 'z'), name='', coord_dtype=float64)
>>> new_cm = cm.renamed_range({'w':'u'})
Traceback (most recent call last):
...
ValueError: no range coordinate named w
"""
return renamed_range(self, newnames)
def inverse(self):
"""
Return a new CoordinateMap with the functions reversed
"""
if self.inverse_function is None:
return None
return CoordinateMap(self.function_range,
self.function_domain,
self.inverse_function,
inverse_function=self.function)
def __call__(self, x):
"""Return mapping evaluated at x
Also, check x and the return value of self.function for
compatiblity with function_domain
and function_range coordinate systems respectively.
Parameters
----------
x : array-like
Values in domain coordinate system space that will be mapped
to the range coordinate system space, using
``self.mapping``
Returns
-------
y : array
Values in range coordinate system space
Examples
--------
>>> input_cs = CoordinateSystem('ijk')
>>> output_cs = CoordinateSystem('xyz')
>>> function = lambda x:x+1
>>> inverse = lambda x:x-1
>>> cm = CoordinateMap(input_cs, output_cs, function, inverse)
>>> cm([2,3,4])
array([3, 4, 5])
>>> cmi = cm.inverse()
>>> cmi([2,6,12])
array([ 1, 5, 11])
"""
x = np.asarray(x)
in_vals = self.function_domain._checked_values(x)
out_vals = self.function(in_vals)
final_vals = self.function_range._checked_values(out_vals)
# Try to set the shape reasonably for self.ndims[0] == 1
if x.ndim == 1:
return final_vals.reshape(-1)
elif x.ndim == 0:
return np.squeeze(final_vals)
else:
return final_vals
def __copy__(self):
"""Create a copy of the coordmap.
Returns
-------
coordmap : CoordinateMap
"""
return CoordinateMap(self.function_domain,
self.function_range,
self.function,
inverse_function=self.inverse_function)
###################################################################
#
# Private methods
#
###################################################################
def __repr__(self):
if self.inverse_function is None:
return "CoordinateMap(\n function_domain=%s,\n function_range=%s,\n function=%s\n )" % (self.function_domain, self.function_range, repr(self.function))
else:
return "CoordinateMap(\n function_domain=%s,\n function_range=%s,\n function=%s,\n inverse_function=%s\n )" % (self.function_domain, self.function_range, repr(self.function), repr(self.inverse_function))
def _checkfunction(self):
"""Verify that the domain and range of self.function work
can be used for calling self.function.
We do this by passing something that should work, through __call__
"""
inp = np.zeros((10, self.ndims[0]),
dtype=self.function_domain.coord_dtype)
out = self(inp)
def __eq__(self, other):
return (isinstance(other, self.__class__)
and (self.function == other.function)
and (self.function_domain ==
other.function_domain)
and (self.function_range ==
other.function_range)
and (self.inverse_function ==
other.inverse_function))
def __ne__(self, other):
return not self.__eq__(other)
class AffineTransform(object):
"""
A class representing an affine transformation from a
domain to a range.
This class has an affine attribute, which is a matrix representing
the affine transformation in homogeneous coordinates. This matrix
is used to evaluate the function, rather than having an explicit
function.
>>> inp_cs = CoordinateSystem('ijk')
>>> out_cs = CoordinateSystem('xyz')
>>> cm = AffineTransform(inp_cs, out_cs, np.diag([1, 2, 3, 1]))
>>> cm
AffineTransform(
function_domain=CoordinateSystem(coord_names=('i', 'j', 'k'), name='', coord_dtype=float64),
function_range=CoordinateSystem(coord_names=('x', 'y', 'z'), name='', coord_dtype=float64),
affine=array([[ 1., 0., 0., 0.],
[ 0., 2., 0., 0.],
[ 0., 0., 3., 0.],
[ 0., 0., 0., 1.]])
)
>>> cm.affine
array([[ 1., 0., 0., 0.],
[ 0., 2., 0., 0.],
[ 0., 0., 3., 0.],
[ 0., 0., 0., 1.]])
>>> cm([1,1,1])
array([ 1., 2., 3.])
>>> icm = cm.inverse()
>>> icm([1,2,3])
array([ 1., 1., 1.])
"""
_doc = {}
affine = np.diag([3,4,5,1])
_doc['affine'] = 'The matrix representing an affine transformation ' + \
'homogeneous form.'
function_domain = CoordinateSystem('x')
_doc['function_domain'] = 'The domain of the affine transformation, ' + \
'a CoordinateSystem.'
function_range = CoordinateSystem('y')
_doc['function_range'] = 'The range of the affine transformation, ' + \
'a CoordinateSystem.'
ndims = (3,3)
_doc['ndims'] = 'Number of dimensions of domain and range, respectively.'
def __init__(self, function_domain, function_range, affine):
"""
Return an CoordinateMap specified by an affine transformation
in homogeneous coordinates.
Parameters
----------
affine : array-like
affine homogenous coordinate matrix
function_domain : :class:`CoordinateSystem`
input coordinates
function_range : :class:`CoordinateSystem`
output coordinates
Notes
-----
The dtype of the resulting matrix is determined by finding a
safe typecast for the function_domain, function_range and affine.
"""
affine = np.asarray(affine)
dtype = safe_dtype(affine.dtype,
function_domain.coord_dtype,
function_range.coord_dtype)
inaxes = function_domain.coord_names
outaxes = function_range.coord_names
self.function_domain = CoordinateSystem(inaxes,
function_domain.name,
dtype)
self.function_range = CoordinateSystem(outaxes,
function_range.name,
dtype)
self.ndims = (self.function_domain.ndim,
self.function_range.ndim)
affine = np.asarray(affine, dtype=dtype)
if affine.shape != (self.ndims[1]+1, self.ndims[0]+1):
raise ValueError('coordinate lengths do not match '
'affine matrix shape')
# Test that it is actually an affine mapping in homogeneous
# form
bottom_row = np.array([0]*self.ndims[0] + [1])
if not np.all(affine[-1] == bottom_row):
raise ValueError('the homogeneous transform should have bottom=' + \
'row %s' % repr(bottom_row))
self.affine = affine
###################################################################
#
# Properties
#
###################################################################
def inverse(self):
"""
Return the inverse affine transform, when appropriate, or None.
"""
try:
return AffineTransform(self.function_range,
self.function_domain,
np.linalg.inv(self.affine))
except np.linalg.linalg.LinAlgError:
return None
###################################################################
#
# Helper constructors
#
###################################################################
@staticmethod
def from_params(innames, outnames, params, domain_name='',
range_name=''):
"""
Create an `AffineTransform` instance from sequences of innames and outnames.
Parameters
----------
innames : ``tuple`` of ``string``
The names of the axes of the domain.
outnames : ``tuple`` of ``string``
The names of the axes of the range.
params : `AffineTransform`, `ndarray` or `(ndarray, ndarray)`
An affine function between the domain and range.
This can be represented either by a single
ndarray (which is interpreted as the representation of the
function in homogeneous coordinates) or an (A,b) tuple.
domain_name : ``string``
Name of domain CoordinateSystem
range_name : ``string``
Name of range CoordinateSystem
Returns
-------
aff : `AffineTransform` object instance
Notes
-----
:Precondition: ``len(shape) == len(names)``
:Raises ValueError: ``if len(shape) != len(names)``
"""
if type(params) == type(()):
A, b = params
params = affines.from_matrix_vector(A, b)
ndim = (len(innames) + 1, len(outnames) + 1)
if params.shape != ndim[::-1]:
raise ValueError('shape and number of axis names do not agree')
dtype = params.dtype
function_domain = CoordinateSystem(innames, domain_name)
function_range = CoordinateSystem(outnames, range_name)
return AffineTransform(function_domain, function_range, params)
@staticmethod
def from_start_step(innames, outnames, start, step, domain_name='',
range_name=''):
"""
Create an `AffineTransform` instance from sequences of names, start
and step.
Parameters
----------
innames : ``tuple`` of ``string``
The names of the axes of the domain.
outnames : ``tuple`` of ``string``
The names of the axes of the range.
start : ``tuple`` of ``float``
Start vector used in constructing affine transformation
step : ``tuple`` of ``float``
Step vector used in constructing affine transformation
domain_name : ``string``
Name of domain CoordinateSystem
range_name : ``string``
Name of range CoordinateSystem
Returns
-------
cm : `CoordinateMap`
Examples
--------
>>> cm = AffineTransform.from_start_step('ijk', 'xyz', [1, 2, 3], [4, 5, 6])
>>> cm.affine
array([[ 4., 0., 0., 1.],
[ 0., 5., 0., 2.],
[ 0., 0., 6., 3.],
[ 0., 0., 0., 1.]])
Notes
-----
``len(names) == len(start) == len(step)``
"""
ndim = len(innames)
if len(outnames) != ndim:
raise ValueError('len(innames) != len(outnames)')
return AffineTransform.from_params(innames,
outnames,
(np.diag(step), start),
domain_name=domain_name,
range_name=range_name)
@staticmethod
def identity(coord_names, name=''):
"""
Return an identity coordmap of the given shape.
Parameters
----------
coord_names : ``tuple`` of ``string``
Names of Axes in domain CoordinateSystem
name : ``string``
Name of origin of coordinate system
Returns
-------
cm : `CoordinateMap`
``CoordinateMap`` with `CoordinateSystem` domain and an
identity transform, with identical domain and range.
Examples
--------
>>> cm = AffineTransform.identity('ijk', 'somewhere')
>>> cm.affine
array([[ 1., 0., 0., 0.],
[ 0., 1., 0., 0.],
[ 0., 0., 1., 0.],
[ 0., 0., 0., 1.]])
>>> print cm.function_domain
CoordinateSystem(coord_names=('i', 'j', 'k'), name='somewhere', coord_dtype=float64)
>>> print cm.function_range
CoordinateSystem(coord_names=('i', 'j', 'k'), name='somewhere', coord_dtype=float64)
"""
return AffineTransform.from_start_step(coord_names, coord_names, [0]*len(coord_names),
[1]*len(coord_names), name, name)
###################################################################
#
# Methods
#
###################################################################
def reordered_domain(self, order=None):
"""
Create a new AffineTransform with the coordinates of function_domain reordered.
Default behaviour is to reverse the order of the coordinates.
Parameters
----------
order: sequence
Order to use, defaults to reverse. The elements
can be integers, strings or 2-tuples of strings.
If they are strings, they should be in
mapping.function_domain.coord_names.
Returns:
--------
newmapping :AffineTransform
A new AffineTransform with the coordinates of function_domain reordered.
>>> input_cs = CoordinateSystem('ijk')
>>> output_cs = CoordinateSystem('xyz')
>>> cm = AffineTransform(input_cs, output_cs, np.identity(4))
>>> print cm.reordered_domain('ikj').function_domain
CoordinateSystem(coord_names=('i', 'k', 'j'), name='', coord_dtype=float64)
"""
return reordered_domain(self, order)
def reordered_range(self, order=None):
"""
Create a new AffineTransform with the coordinates of function_range reordered.
Defaults to reversing the coordinates of function_range.
Parameters
----------
order: sequence
Order to use, defaults to reverse. The elements
can be integers, strings or 2-tuples of strings.
If they are strings, they should be in
mapping.function_range.coord_names.
Returns:
--------
newmapping : AffineTransform
A new AffineTransform with the coordinates of function_range reordered.
>>> input_cs = CoordinateSystem('ijk')
>>> output_cs = CoordinateSystem('xyz')
>>> cm = AffineTransform(input_cs, output_cs, np.identity(4))
>>> print cm.reordered_range('xzy').function_range
CoordinateSystem(coord_names=('x', 'z', 'y'), name='', coord_dtype=float64)
>>> print cm.reordered_range([0,2,1]).function_range.coord_names
('x', 'z', 'y')
>>> newcm = cm.reordered_range('yzx')
>>> newcm.function_range.coord_names
('y', 'z', 'x')
"""
return reordered_range(self, order)
def renamed_domain(self, newnames, name=''):
"""
Create a new AffineTransform with the coordinates of function_domain renamed.
Inputs:
-------
newnames: dictionary
A dictionary whose keys are integers or are in
mapping.function_domain.coord_names
and whose values are the new names.
Returns:
--------
newmapping : AffineTransform
A new AffineTransform with renamed function_domain.
>>> affine_domain = CoordinateSystem('ijk')
>>> affine_range = CoordinateSystem('xyz')
>>> affine_matrix = np.identity(4)
>>> affine_mapping = AffineTransform(affine_domain, affine_range, affine_matrix)
>>> new_affine_mapping = affine_mapping.renamed_domain({'i':'phase','k':'freq','j':'slice'})
>>> print new_affine_mapping.function_domain
CoordinateSystem(coord_names=('phase', 'slice', 'freq'), name='', coord_dtype=float64)
>>> new_affine_mapping = affine_mapping.renamed_domain({'i':'phase','k':'freq','l':'slice'})
Traceback (most recent call last):
...
ValueError: no domain coordinate named l
>>>
"""
return renamed_domain(self, newnames)
def renamed_range(self, newnames, name=''):
"""
Create a new AffineTransform with the coordinates of function_domain renamed.
Inputs:
-------
newnames: dictionary
A dictionary whose keys are integers or are in
mapping.function_range.coord_names
and whose values are the new names.
Returns:
--------
newmapping : AffineTransform
A new AffineTransform with renamed function_range.
>>> affine_domain = CoordinateSystem('ijk')
>>> affine_range = CoordinateSystem('xyz')
>>> affine_matrix = np.identity(4)
>>> affine_mapping = AffineTransform(affine_domain, affine_range, affine_matrix)
>>> new_affine_mapping = affine_mapping.renamed_range({'x':'u'})
>>> print new_affine_mapping.function_range
CoordinateSystem(coord_names=('u', 'y', 'z'), name='', coord_dtype=float64)
>>> new_affine_mapping = affine_mapping.renamed_range({'w':'u'})
Traceback (most recent call last):
...
ValueError: no range coordinate named w
"""
return renamed_range(self, newnames)
def __call__(self, x):
"""Return mapping evaluated at x
Parameters
----------
x : array-like
Values in domain coordinate system space that will be mapped
to the range coordinate system space, using
the homogeneous transform matrix self.affine.
Returns
-------
y : array
Values in range coordinate system space
Examples
--------
>>> input_cs = CoordinateSystem('ijk', coord_dtype=np.int)
>>> output_cs = CoordinateSystem('xyz', coord_dtype=np.int)
>>> affine = np.array([[1,0,0,1],
... [0,1,0,1],
... [0,0,1,1],
... [0,0,0,1]])
>>> affine_transform = AffineTransform(input_cs, output_cs, affine)
>>> affine_transform([2,3,4])
array([3, 4, 5])
>>> affine_transform_inv = affine_transform.inverse()
>>> # Its inverse has a matrix of np.float
>>> # because np.linalg.inv was called.
>>> affine_transform_inv([2,6,12])
array([ 1., 5., 11.])
"""
x = np.asarray(x)
A, b = affines.to_matrix_vector(self.affine)
x_reshaped = x.reshape((-1, self.ndims[0]))
y_reshaped = np.dot(x_reshaped, A.T) + b[np.newaxis,:]
y = y_reshaped.reshape(x.shape[:-1] + (self.ndims[1],))
return y
###################################################################
#
# Private methods
#
###################################################################
def __copy__(self):
"""
Create a copy of the AffineTransform.
Returns
-------
affine_transform : AffineTransform
Examples
--------
>>> import copy
>>> cm = AffineTransform(CoordinateSystem('ijk'), CoordinateSystem('xyz'), np.eye(4))
>>> cm_copy = copy.copy(cm)
>>> cm is cm_copy
False
Note that the matrix (affine) is not a pointer to the
same data, it's a full independent copy
>>> cm.affine[0,0] = 2.0
>>> cm_copy.affine[0,0]
1.0
"""
return AffineTransform(self.function_domain,
self.function_range,
self.affine.copy())
def __repr__(self):
return "AffineTransform(\n function_domain=%s,\n function_range=%s,\n affine=%s\n)" % (self.function_domain,
self.function_range,
'\n '.join(repr(self.affine).split('\n')))
def __eq__(self, other):
test1, test2, test3, test4 =(isinstance(other, self.__class__),
np.allclose(self.affine, other.affine),
(self.function_domain ==
other.function_domain),
(self.function_range ==
other.function_range))
value = test1 and test2 and test3 and test4
return value
def __ne__(self, other):
return not self.__eq__(other)
####################################################################################
#
# Module level functions
#
####################################################################################
def product(*cmaps):
"""
Return the "topological" product of two or more mappings, which
can be either AffineTransforms or CoordinateMaps.
If they are all AffineTransforms, the result is an AffineTransform,
else it is a CoordinateMap.
Parameters
----------
cmaps : sequence of CoordinateMaps or AffineTransforms
Returns
-------
cmap : ``CoordinateMap``
>>> inc1 = AffineTransform.from_params('i', 'x', np.diag([2,1]))
>>> inc2 = AffineTransform.from_params('j', 'y', np.diag([3,1]))
>>> inc3 = AffineTransform.from_params('k', 'z', np.diag([4,1]))
>>> cmap = product(inc1, inc3, inc2)
>>> cmap.function_domain.coord_names
('i', 'k', 'j')
>>> cmap.function_range.coord_names
('x', 'z', 'y')