-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathaffine.py
745 lines (605 loc) · 21.6 KB
/
affine.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
"""Affine transformation matrices.
The Affine package is derived from Casey Duncan's Planar package. See the
copyright statement below.
"""
#############################################################################
# Copyright (c) 2010 by Casey Duncan
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name(s) of the copyright holders nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AS IS AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
# EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#############################################################################
from functools import cached_property
import math
from typing import Optional
import warnings
from attrs import astuple, define, field
__all__ = ["Affine"]
__author__ = "Sean Gillies"
__version__ = "3.0dev"
EPSILON: float = 1e-5
EPSILON2: float = 1e-10
class AffineError(Exception):
pass
class TransformNotInvertibleError(AffineError):
"""The transform could not be inverted."""
class UndefinedRotationError(AffineError):
"""The rotation angle could not be computed for this transform."""
def cos_sin_deg(deg: float):
"""Return the cosine and sin for the given angle in degrees.
With special-case handling of multiples of 90 for perfect right
angles.
"""
deg = deg % 360.0
if deg == 90.0:
return 0.0, 1.0
elif deg == 180.0:
return -1.0, 0
elif deg == 270.0:
return 0, -1.0
rad = math.radians(deg)
return math.cos(rad), math.sin(rad)
@define(frozen=True)
class Affine:
"""Two dimensional affine transform for 2D linear mapping.
Parameters
----------
a, b, c, d, e, f : float
Coefficients of an augmented affine transformation matrix
| x' | | a b c | | x |
| y' | = | d e f | | y |
| 1 | | 0 0 1 | | 1 |
`a`, `b`, and `c` are the elements of the first row of the
matrix. `d`, `e`, and `f` are the elements of the second row.
Attributes
----------
a, b, c, d, e, f, g, h, i : float
The coefficients of the 3x3 augmented affine transformation
matrix
| x' | | a b c | | x |
| y' | = | d e f | | y |
| 1 | | g h i | | 1 |
`g`, `h`, and `i` are always 0, 0, and 1.
The Affine package is derived from Casey Duncan's Planar package.
See the copyright statement below. Parallel lines are preserved by
these transforms. Affine transforms can perform any combination of
translations, scales/flips, shears, and rotations. Class methods
are provided to conveniently compose transforms from these
operations.
Internally the transform is stored as a 3x3 transformation matrix.
The transform may be constructed directly by specifying the first
two rows of matrix values as 6 floats. Since the matrix is an affine
transform, the last row is always ``(0, 0, 1)``.
N.B.: multiplication of a transform and an (x, y) vector *always*
returns the column vector that is the matrix multiplication product
of the transform and (x, y) as a column vector, no matter which is
on the left or right side. This is obviously not the case for
matrices and vectors in general, but provides a convenience for
users of this class.
"""
a: float = field(converter=float)
b: float = field(converter=float)
c: float = field(converter=float)
d: float = field(converter=float)
e: float = field(converter=float)
f: float = field(converter=float)
g: float = field(default=0.0, converter=float)
h: float = field(default=0.0, converter=float)
i: float = field(default=1.0, converter=float)
@classmethod
def from_gdal(cls, c: float, a: float, b: float, f: float, d: float, e: float):
"""Use same coefficient order as GDAL's GetGeoTransform().
Parameters
----------
c, a, b, f, d, e : float
Parameters ordered by GDAL's GeoTransform.
Returns
-------
Affine
"""
return cls(a, b, c, d, e, f)
@classmethod
def identity(cls):
"""Return the identity transform.
Returns
-------
Affine
"""
return identity
@classmethod
def translation(cls, xoff: float, yoff: float):
"""Create a translation transform from an offset vector.
Parameters
----------
xoff, yoff : float
Translation offsets in x and y directions.
Returns
-------
Affine
"""
return cls(1.0, 0.0, xoff, 0.0, 1.0, yoff)
@classmethod
def scale(cls, *scaling):
"""Create a scaling transform from a scalar or vector.
Parameters
----------
*scaling : float or sequence of two floats
One or two scaling factors. A scalar value will scale in both
dimensions equally. A vector scaling value scales the dimensions
independently.
Returns
-------
Affine
"""
if len(scaling) == 1:
sx = sy = float(scaling[0])
else:
sx, sy = scaling
return cls(sx, 0.0, 0.0, 0.0, sy, 0.0)
@classmethod
def shear(cls, x_angle: float = 0, y_angle: float = 0):
"""Create a shear transform along one or both axes.
Parameters
----------
x_angle, y_angle : float
Shear angles in degrees parallel to the x- and y-axis.
Returns
-------
Affine
"""
mx = math.tan(math.radians(x_angle))
my = math.tan(math.radians(y_angle))
return cls(1.0, mx, 0.0, my, 1.0, 0.0)
@classmethod
def rotation(cls, angle: float, pivot=None):
"""Create a rotation transform at the specified angle.
Parameters
----------
angle : float
Rotation angle in degrees, counter-clockwise about the pivot point.
pivot : sequence of float (px, py), optional
Pivot point coordinates to rotate around. If None (default), the
pivot point is the coordinate system origin (0.0, 0.0).
Returns
-------
Affine
"""
ca, sa = cos_sin_deg(angle)
if pivot is None:
return cls(ca, -sa, 0.0, sa, ca, 0.0)
else:
px, py = pivot
# fmt: off
return cls(
ca,
-sa,
px - px * ca + py * sa,
sa,
ca,
py - px * sa - py * ca,
)
# fmt: on
@classmethod
def permutation(cls, *scaling):
"""Create the permutation transform.
For 2x2 matrices, there is only one permutation matrix that is
not the identity.
Parameters
----------
*scaling : any
Ignored.
Returns
-------
Affine
"""
return cls(0.0, 1.0, 0.0, 1.0, 0.0, 0.0)
def __array__(self, dtype=None, copy=None):
"""Get affine matrix as a 3x3 NumPy array.
Parameters
----------
dtype : data-type, optional
The desired data-type for the array.
copy : bool, optional
If None (default) or True, a copy of the array is always returned.
If False, a ValueError is raised as this is not supported.
Returns
-------
array
Raises
------
ValueError
If ``copy=False`` is specified.
"""
import numpy as np
if copy is False:
raise ValueError("`copy=False` isn't supported. A copy is always created.")
return np.array(
[
[self.a, self.b, self.c],
[self.d, self.e, self.f],
[0.0, 0.0, 1.0],
],
dtype=dtype or float,
)
def __str__(self) -> str:
"""Concise string representation."""
return (
f"|{self.a: .2f},{self.b: .2f},{self.c: .2f}|\n"
f"|{self.d: .2f},{self.e: .2f},{self.f: .2f}|\n"
f"|{self.g: .2f},{self.h: .2f},{self.i: .2f}|"
)
def __repr__(self) -> str:
"""Precise string representation."""
return (
f"Affine({self.a!r}, {self.b!r}, {self.c!r},\n"
f" {self.d!r}, {self.e!r}, {self.f!r})"
)
def to_gdal(self):
"""Return same coefficient order expected by GDAL's SetGeoTransform().
Returns
-------
tuple
Ordered: c, a, b, f, d, e.
"""
return (self.c, self.a, self.b, self.f, self.d, self.e)
def to_shapely(self):
"""Return affine transformation parameters for shapely's affinity module.
Returns
-------
tuple
Ordered: a, b, d, e, c, f.
"""
return (self.a, self.b, self.d, self.e, self.c, self.f)
@property
def xoff(self) -> float:
"""Alias for 'c'."""
return self.c
@property
def yoff(self) -> float:
"""Alias for 'f'."""
return self.f
@cached_property
def determinant(self) -> float:
"""Evaluate the determinant of the transform matrix.
This value is equal to the area scaling factor when the
transform is applied to a shape.
Returns
-------
float
"""
return self.a * self.e - self.b * self.d
@property
def _scaling(self):
"""The absolute scaling factors of the transformation.
This tuple represents the absolute value of the scaling factors of the
transformation, sorted from bigger to smaller.
"""
a, b, d, e = self.a, self.b, self.d, self.e
# The singular values are the square root of the eigenvalues
# of the matrix times its transpose, M M*
# Computing trace and determinant of M M*
trace = a**2 + b**2 + d**2 + e**2
det2 = (a * e - b * d) ** 2
delta = trace**2 / 4.0 - det2
if delta < EPSILON2:
delta = 0.0
sqrt_delta = math.sqrt(delta)
l1 = math.sqrt(trace / 2.0 + sqrt_delta)
l2 = math.sqrt(trace / 2.0 - sqrt_delta)
return l1, l2
@property
def eccentricity(self) -> float:
"""The eccentricity of the affine transformation.
This value represents the eccentricity of an ellipse under
this affine transformation.
Raises
------
NotImplementedError
For improper transformations.
"""
l1, l2 = self._scaling
return math.sqrt(l1**2 - l2**2) / l1
@property
def rotation_angle(self) -> float:
"""The rotation angle in degrees of the affine transformation.
This is the rotation angle in degrees of the affine transformation,
assuming it is in the form M = R S, where R is a rotation and S is a
scaling.
Raises
------
UndefinedRotationError
For improper and degenerate transformations.
"""
if self.is_proper or self.is_degenerate:
l1, _ = self._scaling
y, x = self.d / l1, self.a / l1
return math.degrees(math.atan2(y, x))
else:
raise UndefinedRotationError
@property
def is_identity(self) -> bool:
"""True if this transform equals the identity matrix, within rounding limits."""
return self is identity or self.almost_equals(identity, EPSILON)
@property
def is_rectilinear(self) -> bool:
"""True if the transform is rectilinear.
i.e., whether a shape would remain axis-aligned, within rounding
limits, after applying the transform.
"""
return (abs(self.a) < EPSILON and abs(self.e) < EPSILON) or (
abs(self.d) < EPSILON and abs(self.b) < EPSILON
)
@property
def is_conformal(self) -> bool:
"""True if the transform is conformal.
i.e., if angles between points are preserved after applying the
transform, within rounding limits. This implies that the
transform has no effective shear.
"""
return abs(self.a * self.b + self.d * self.e) < EPSILON
@property
def is_orthonormal(self) -> bool:
"""True if the transform is orthonormal.
Which means that the transform represents a rigid motion, which
has no effective scaling or shear. Mathematically, this means
that the axis vectors of the transform matrix are perpendicular
and unit-length. Applying an orthonormal transform to a shape
always results in a congruent shape.
"""
a, b, d, e = self.a, self.b, self.d, self.e
return (
self.is_conformal
and abs(1.0 - (a * a + d * d)) < EPSILON
and abs(1.0 - (b * b + e * e)) < EPSILON
)
@cached_property
def is_degenerate(self) -> bool:
"""Return True if this transform is degenerate.
A degenerate transform will collapse a shape to an effective area
of zero, and cannot be inverted.
Returns
-------
bool
"""
return self.determinant == 0.0
@cached_property
def is_proper(self) -> bool:
"""Return True if this transform is proper.
A proper transform (with a positive determinant) does not include
reflection.
Returns
-------
bool
"""
return self.determinant > 0.0
@property
def column_vectors(self):
"""The values of the transform as three 2D column vectors.
Returns
-------
tuple of three tuple pairs
Ordered (a, d), (b, e), (c, f).
"""
return (self.a, self.d), (self.b, self.e), (self.c, self.f)
def almost_equals(self, other, precision: Optional[float] = None) -> bool:
"""Compare transforms for approximate equality.
Parameters
----------
other : Affine
Transform being compared.
precision : float, default EPSILON
Precision to use to evaluate equality.
Returns
-------
bool
True if absolute difference between each element
of each respective transform matrix < ``precision``.
"""
precision = precision or EPSILON
return all(abs(sv - ov) < precision for sv, ov in zip(self, other))
@cached_property
def _astuple(self):
return astuple(self)
def __getitem__(self, index):
return self._astuple[index]
def __iter__(self):
return iter(self._astuple)
def __len__(self):
return 9
def __gt__(self, other) -> bool:
return NotImplemented
__ge__ = __lt__ = __le__ = __gt__
# Override from base class. We do not support entrywise
# addition, subtraction or scalar multiplication because
# the result is not an affine transform
def __add__(self, other):
raise TypeError("Operation not supported")
__iadd__ = __add__
def __mul__(self, other):
"""Multiplication.
Apply the transform using matrix multiplication, creating
a resulting object of the same type. A transform may be applied
to another transform, a vector, vector array, or shape.
Parameters
----------
other : Affine or iterable of (vx, vy)
Returns
-------
Affine or a tuple of two floats
"""
sa, sb, sc, sd, se, sf = self.a, self.b, self.c, self.d, self.e, self.f
if isinstance(other, Affine):
oa, ob, oc, od, oe, of = (
other.a,
other.b,
other.c,
other.d,
other.e,
other.f,
)
return self.__class__(
sa * oa + sb * od,
sa * ob + sb * oe,
sa * oc + sb * of + sc,
sd * oa + se * od,
sd * ob + se * oe,
sd * oc + se * of + sf,
)
else:
try:
vx, vy = other
return (vx * sa + vy * sb + sc, vx * sd + vy * se + sf)
except (ValueError, TypeError):
return NotImplemented
def __rmul__(self, other):
"""Right hand multiplication.
.. deprecated:: 2.3.0
Right multiplication will be prohibited in version 3.0. This method
will raise AffineError.
Parameters
----------
other : Affine or iterable of (vx, vy)
Returns
-------
Affine
Notes
-----
We should not be called if other is an affine instance This is
just a guarantee, since we would potentially return the wrong
answer in that case.
"""
warnings.warn(
"Right multiplication will be prohibited in version 3.0",
DeprecationWarning,
stacklevel=2,
)
assert not isinstance(other, Affine)
return self.__mul__(other)
def __imul__(self, other):
"""Provide wrapper for `__mul__`, however `other` is not modified in-place."""
if isinstance(other, Affine) or isinstance(other, tuple):
return self.__mul__(other)
else:
return NotImplemented
def itransform(self, seq) -> None:
"""Transform a sequence of points or vectors in-place.
Parameters
----------
seq : mutable sequence
Returns
-------
None
The input sequence is mutated in-place.
"""
if self is not identity and self != identity:
sa, sb, sc, sd, se, sf = self.a, self.b, self.c, self.d, self.e, self.f
for i, (x, y) in enumerate(seq):
seq[i] = (x * sa + y * sb + sc, x * sd + y * se + sf)
def __invert__(self):
"""Return the inverse transform.
Raises
------
TransformNotInvertible
If the transform is degenerate.
"""
if self.is_degenerate:
raise TransformNotInvertibleError("Cannot invert degenerate transform")
idet = 1.0 / self.determinant
sa, sb, sc, sd, se, sf = self.a, self.b, self.c, self.d, self.e, self.f
ra = se * idet
rb = -sb * idet
rd = -sd * idet
re = sa * idet
return self.__class__(
ra,
rb,
-sc * ra - sf * rb,
rd,
re,
-sc * rd - sf * re,
)
def __getnewargs__(self):
"""Pickle protocol support.
Notes
-----
Normal unpickling creates a situation where __new__ receives all
9 elements rather than the 6 that are required for the
constructor. This method ensures that only the 6 are provided.
"""
return self.a, self.b, self.c, self.d, self.e, self.f
identity = Affine(1, 0, 0, 0, 1, 0)
"""The identity transform"""
# Miscellaneous utilities
def loadsw(s: str):
"""Return Affine from the contents of a world file string.
This method also translates the coefficients from center- to
corner-based coordinates.
Parameters
----------
s : str
String with 6 floats ordered in a world file.
Returns
-------
Affine
"""
if not hasattr(s, "split"):
raise TypeError("Cannot split input string")
coeffs = s.split()
if len(coeffs) != 6:
raise ValueError(f"Expected 6 coefficients, found {len(coeffs)}")
a, d, b, e, c, f = (float(x) for x in coeffs)
center = Affine(a, b, c, d, e, f)
return center * Affine.translation(-0.5, -0.5)
def dumpsw(obj) -> str:
"""Return string for a world file.
This method also translates the coefficients from corner- to
center-based coordinates.
Returns
-------
str
"""
center = obj * Affine.translation(0.5, 0.5)
return "\n".join(repr(getattr(center, x)) for x in list("adbecf")) + "\n"
def set_epsilon(epsilon: float) -> None:
"""Set the global absolute error value and rounding limit.
This value is accessible via the affine.EPSILON global variable.
Parameters
----------
epsilon : float
The global absolute error value and rounding limit for
approximate floating point comparison operations.
Returns
-------
None
Notes
-----
The default value of ``0.00001`` is suitable for values that are in
the "countable range". You may need a larger epsilon when using
large absolute values, and a smaller value for very small values
close to zero. Otherwise approximate comparison operations will not
behave as expected.
"""
global EPSILON, EPSILON2
EPSILON = float(epsilon)
EPSILON2 = EPSILON**2
set_epsilon(1e-5)