File: location.py

package info (click to toggle)
mutatormath 3.0.1-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,820 kB
  • sloc: python: 2,581; makefile: 10
file content (754 lines) | stat: -rw-r--r-- 21,772 bytes parent folder | download | duplicates (3)
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
# -*- coding: utf-8 -*-
from __future__ import print_function, division
import math, sys
import itertools, operator

from mutatorMath import __version__


_EPSILON = sys.float_info.epsilon

__all__ =  ["Location", "sortLocations"]


def numberToString(value):
    # return a nicely formatted string of this value
    # return tuples as a tuple-looking string with formatted numbers
    # return ints as ints, no commas
    # return floats as compact rounded value
    if value is None:
        return "None"
    if type(value)==tuple:
        t = []
        for v in value:
            t.append(numberToString(v))
        return "(%s)"%(",".join(t))
    if int(value) == value:
        # it is an int
        return "%d"%(value)
    return "%3.3f"%value


class Location(dict):
    """
    A object subclassed from dict to store n-dimensional locations.
    
    - key is dimension or axis name
    - value is the coordinate.

    - Location objects behave like numbers.
    - If a specific dimension is missing, assume it is zero.
    - Convert to and from dict, tuple.
    
    ::
    
        >>> l = Location(pop=1, snap=-100)
        >>> print(l)
        <Location pop:1, snap:-100 >
        

    Location objects can be used as math objects:

    ::

        >>> l = Location(pop=1)
        >>> l * 2
        <Location pop:2 >
        >>> 2 * l
        <Location pop:2 >
        >>> l / 2
        <Location pop:0.500 >
        
        >>> l = Location(pop=1)
        >>> m = Location(pop=10)
        >>> l + m
        <Location pop:11 >

        >>> l = Location(pop=1)
        >>> m = Location(pop=10)
        >>> l - m
        <Location pop:-9 >
    """
    
    def __repr__(self):
        t = ["<%s"%self.__class__.__name__]
        t.append(self.asString())
        t.append(">")
        return " ".join(t)

    def __lt__(self, other):
        if len(self) < len(other):
            return True
        elif len(self) > len(other):
            return False
        self_keys = sorted(self.keys())
        other_keys = sorted(other.keys())
        for i, key in enumerate(self_keys):
            if key < other_keys[i]:
                return True
            elif key > other_keys[i]:
                return False
            if self[key] < other[key]:
                return True
        return False
    
    def expand(self, axisNames):
        """
        Expand the location with zero values for all axes in axisNames that aren't filled in the current location.
        ::

            >>> l = Location(pop=1)
            >>> l.expand(['snap', 'crackle'])
            >>> print(l)
            <Location crackle:0, pop:1, snap:0 >
        """
        for k in axisNames:
            if k not in self:
                self[k] = 0
    
    def copy(self):
        """
        Return a copy of this location.
        ::
            
            >>> l = Location(pop=1, snap=0)
            >>> l.copy()
            <Location pop:1, snap:0 >

        """
        new = self.__class__()
        new.update(self)
        return new
        
    def fromTuple(self, locationTuple):
        """
        Read the coordinates from a tuple.
        ::
            
            >>> t = (('pop', 1), ('snap', -100))
            >>> l = Location()
            >>> l.fromTuple(t)
            >>> print(l)
            <Location pop:1, snap:-100 >

        """
        for key, value in locationTuple:
            try:
                self[key] = float(value)
            except TypeError:
                self[key] = tuple([float(v) for v in value])
        
    def asTuple(self):
        """Return the location as a tuple.
        Sort the dimension names alphabetically.
        ::
        
            >>> l = Location(pop=1, snap=-100)
            >>> l.asTuple()
            (('pop', 1), ('snap', -100))
        """
        t = []
        k = sorted(self.keys())
        for key in k:
            t.append((key, self[key]))
        return tuple(t)
    
    def getType(self, short=False):
        """Return a string describing the type of the location, i.e. origin, on axis, off axis etc.

        ::
            
            >>> l = Location()
            >>> l.getType()
            'origin'
            >>> l = Location(pop=1)
            >>> l.getType()
            'on-axis, pop'
            >>> l = Location(pop=1, snap=1)
            >>> l.getType()
            'off-axis, pop snap'
            >>> l = Location(pop=(1,2))
            >>> l.getType()
            'on-axis, pop, split'
        """
        if self.isOrigin():
            return "origin"
        t = []
        onAxis = self.isOnAxis()
        if onAxis is False:
            if short:
                t.append("off-axis")
            else:
                t.append("off-axis, "+ " ".join(self.getActiveAxes()))
        else:
            if short:
                t.append("on-axis")
            else:
                t.append("on-axis, %s"%onAxis)
        if self.isAmbivalent():
            t.append("split")
        return ', '.join(t)
    
    def getActiveAxes(self):
        """
        Return a list of names of axes which are not zero
        ::
        
            >>> l = Location(pop=1, snap=0, crackle=1)
            >>> l.getActiveAxes()
            ['crackle', 'pop']
        """
        names = sorted(k for k in self.keys() if self[k]!=0)
        return names
        
    def asString(self, strict=False):
        """
        Return the location as a string.
        ::
        
            >>> l = Location(pop=1, snap=(-100.0, -200))
            >>> l.asString()
            'pop:1, snap:(-100.000,-200.000)'
        """
        if len(self.keys())==0:
            return "origin"
        v = []
        n = []
        try:
            for name, value in self.asTuple():
                s = ''
                if value is None:
                    s = "None"
                elif type(value) == tuple or type(value) == list:
                    s = "(%.3f,%.3f)"%(value[0], value[1])
                elif int(value) == value:
                    s = "%d"%(int(value))
                else:
                    s = "%.3f"%(value)
                if s != '':
                    n.append("%s:%s"%(name, s))
            return ", ".join(n)
        except TypeError:
            import traceback
            print("Location value error:", name, value)
            for key, value in self.items():
                print("\t\tkey:", key)
                print("\t\tvalue:", value)
            traceback.print_exc()
            return "error"

    def asDict(self):
        """
        Return the location as a plain python dict.
        ::
        
            >>> l = Location(pop=1, snap=-100)
            >>> l.asDict()['snap']
            -100
            >>> l.asDict()['pop']
            1
        """
        new = {}
        new.update(self)
        return new
    
    def asSortedStringDict(self, roundValue=False):
        """ Return the data in a dict with sorted names and column titles.
        ::

            >>> l = Location(pop=1, snap=(1,10))
            >>> l.asSortedStringDict()[0]['value']
            '1'
            >>> l.asSortedStringDict()[0]['axis']
            'pop'
            >>> l.asSortedStringDict()[1]['axis']
            'snap'
            >>> l.asSortedStringDict()[1]['value']
            '(1,10)'
            
        """
        data = []
        names = sorted(self.keys())
        for n in names:
            data.append({'axis':n, 'value':numberToString(self[n])})
        return data
        
    def strip(self):
        """ Remove coordinates that are zero, the opposite of expand().

        ::

            >>> l = Location(pop=1, snap=0)
            >>> l.strip()
            <Location pop:1 >
            
        """
        result = []
        for k, v in self.items():
            if isinstance(v, tuple):
                if v > (_EPSILON, ) * len(v) or v < (-_EPSILON, ) * len(v):
                    result.append((k, v))
            elif v > _EPSILON or v < -_EPSILON:
                result.append((k, v))
        return self.__class__(result)
    
    def common(self, other):
        """
        Return two objects with the same dimensions if they lie in the same orthogonal plane.
        ::

            >>> l = Location(pop=1, snap=2)
            >>> m = Location(crackle=1, snap=3)
            >>> l.common(m)
            (<Location snap:2 >, <Location snap:3 >)
        """
        selfDim = set(self.keys())
        otherDim = set(other.keys())
        dims = selfDim | otherDim
        newSelf = None
        newOther = None
        for dim in dims:
            sd = self.get(dim, None)
            od = other.get(dim, None)
            if sd is None or od is None:
                # axis is missing in one or the other
                continue
            if -_EPSILON < sd < _EPSILON and -_EPSILON < od < _EPSILON:
                # values are both zero
                continue
            if newSelf is None:
                newSelf = self.__class__()
            if newOther is None:
                newOther = self.__class__()
            newSelf[dim] = self[dim]
            newOther[dim] = other[dim]
        return newSelf, newOther
    
    #
    #
    #   tests
    #
    #
    
    def isOrigin(self):
        """
        Return True if the location is at the origin.
        ::
            >>> l = Location(pop=1)
            >>> l.isOrigin()
            False
            >>> l = Location()
            >>> l.isOrigin()
            True
        """
        for name, value in self.items():
            if isinstance(value, tuple):
                if (value < (-_EPSILON,) * len(value)
                        or value > (_EPSILON,) * len(value)):
                    return False
            if value < -_EPSILON or value > _EPSILON:
                return False
        return True
        
    def isOnAxis(self):
        """
        Returns statements about this location:
        
            *   False if the location is not on-axis
            *   The name of the axis if it is on-axis
            *   None if the Location is at the origin

        Note: this is only valid for an unbiased location.
        ::

            >>> l = Location(pop=1)
            >>> l.isOnAxis()
            'pop'
            >>> l = Location(pop=1, snap=1)
            >>> l.isOnAxis()
            False
            >>> l = Location()
            >>> l.isOnAxis() is None
            True
        """     
        new = self.__class__()
        new.update(self)
        s = new.strip()
        dims = list(s.keys())
        if len(dims)> 1:
            return False
        elif len(dims)==1:
            return dims[0]
        return None
        
    def isAmbivalent(self, dim=None):
        """
        Return True if any of the factors are in fact tuples.
        If a dimension name is given only that dimension is tested.
        ::
            >>> l = Location(pop=1)
            >>> l.isAmbivalent()
            False
            >>> l = Location(pop=1, snap=(100, -100))
            >>> l.isAmbivalent()
            True
        """
        if dim is not None:
            try:
                return isinstance(self[dim], tuple)
            except KeyError:
                # dimension is not present, it should be 0, so not ambivalent
                return False
        for dim, val in self.items():
            if isinstance(val, tuple):
                return True
        return False
    
    def split(self):
        """
        Split an ambivalent location into 2. One for the x, the other for the y.
        ::

            >>> l = Location(pop=(-5,5))
            >>> l.split()
            (<Location pop:-5 >, <Location pop:5 >)
        """
        x = self.__class__()
        y = self.__class__()
        for dim, val in self.items():
            if isinstance(val, tuple):
                x[dim] = val[0]
                y[dim] = val[1]
            else:
                x[dim] = val
                y[dim] = val
        return x, y

    def spliceX(self):
        """
        Return a copy with the x values preferred for ambivalent locations.
        ::

            >>> l = Location(pop=(-5,5))
            >>> l.spliceX()
            <Location pop:-5 >
        """
        new = self.__class__()
        for dim, val in self.items():
            if isinstance(val, tuple):
                new[dim] = val[0]
            else:
                new[dim] = val
        return new
        
    def spliceY(self):
        """
        Return a copy with the y values preferred for ambivalent locations.
        ::

            >>> l = Location(pop=(-5,5))
            >>> l.spliceY()
            <Location pop:5 >
        """
        new = self.__class__()
        for dim, val in self.items():
            if isinstance(val, tuple):
                new[dim] = val[1]
            else:
                new[dim] = val
        return new
        
    def distance(self, other=None):
        """Return the geometric distance to the other location.
        If no object is provided, this will calculate the distance to the origin.

        ::

            >>> l = Location(pop=100)
            >>> m = Location(pop=200)
            >>> l.distance(m)
            100.0
            >>> l = Location()
            >>> m = Location(pop=200)
            >>> l.distance(m)
            200.0
            >>> l = Location(pop=3, snap=5)
            >>> m = Location(pop=7, snap=8)
            >>> l.distance(m)
            5.0
        """
        t = 0
        if other is None:
            other = self.__class__()
        for axisName in set(self.keys()) | set(other.keys()):
            t += (other.get(axisName,0)-self.get(axisName,0))**2
        return math.sqrt(t)
    
    def sameAs(self, other):
        """
        Check if this is the same location.
        ::
        
            >>> l = Location(pop=5, snap=100)
            >>> m = Location(pop=5.0, snap=100.0)
            >>> l.sameAs(m)
            0
            >>> l = Location(pop=5, snap=100)
            >>> m = Location(pop=5.0, snap=100.0001)
            >>> l.sameAs(m)
            -1
        """
        if not hasattr(other, "get"):
            return -1
        d = self.distance(other)
        if d < _EPSILON:
            return 0
        return -1
    
    # math operators
    def __add__(self, other):
        new = self.__class__()
        new.update(self)
        new.update(other)
        selfDim = set(self.keys())
        otherDim = set(other.keys())
        for key in selfDim & otherDim:
            ts = type(self[key])!=tuple
            to = type(other[key])!=tuple
            if ts:
                sx = sy = self[key]
            else:
                sx = self[key][0]
                sy = self[key][1]
            if to:
                ox = oy = other[key]
            else:
                ox = other[key][0]
                oy = other[key][1]
            x = sx+ox
            y = sy+oy
            if x==y:
                new[key] = x
            else:
                new[key] = x,y
        return new

    def __sub__(self, other):
        new = self.__class__()
        new.update(self)
        for key, value in other.items():
            try:
                new[key] = -value
            except TypeError:
                new[key] = (-value[0], -value[1])
        selfDim = set(self.keys())
        otherDim = set(other.keys())
        for key in selfDim & otherDim:
            ts = type(self[key])!=tuple
            to = type(other[key])!=tuple
            if ts:
                sx = sy = self[key]
            else:
                sx = self[key][0]
                sy = self[key][1]
            if to:
                ox = oy = other[key]
            else:
                ox = other[key][0]
                oy = other[key][1]
            x = sx-ox
            y = sy-oy
            if x==y:
                new[key] = x
            else:
                new[key] = x,y
        return new
    
    def __mul__(self, factor):
        new = self.__class__()
        if isinstance(factor, tuple):
            for key, value in self.items():
                if type(value) == tuple:
                    new[key] = factor[0] * value[0], factor[1] * value[1]
                else:
                    new[key] = factor[0] * value, factor[1] * value
        else:
            for key, value in self.items():
                if type(value) == tuple:
                    new[key] = factor * value[0], factor * value[1]
                else:
                    new[key] = factor * value
        return new
    
    __rmul__ = __mul__
    
    def __truediv__(self, factor):
        if factor == 0:
            raise ZeroDivisionError
        if isinstance(factor, tuple):
            if factor[0] == 0 or factor[1] == 0:
                raise ZeroDivisionError
            return self * (1.0/factor[0]) + self * (1.0/factor[1])
        return self * (1.0/factor)
    
    __div__ = __truediv__

    
    def transform(self, transformDict):
        if transformDict is None:
            return self
        new = self.__class__()
        for dim, (offset, scale) in transformDict.items():
            new[dim] = (self.get(dim,0)+offset)*scale
        return new


def sortLocations(locations):
    """ Sort the locations by ranking:
            1.  all on-axis points
            2.  all off-axis points which project onto on-axis points
                these would be involved in master to master interpolations
                necessary for patching. Projecting off-axis masters have
                at least one coordinate in common with an on-axis master.
            3.  non-projecting off-axis points, 'wild' off axis points
                These would be involved in projecting limits and need to be patched.
    """
    onAxis = []
    onAxisValues = {}
    offAxis = []
    offAxis_projecting = []
    offAxis_wild = []
    # first get the on-axis points
    for l in locations:
        if l.isOrigin():
            continue
        if l.isOnAxis():
            onAxis.append(l)
            for axis in l.keys():
                if axis not in onAxisValues:
                    onAxisValues[axis] = []
                onAxisValues[axis].append(l[axis])
        else:
            offAxis.append(l)
    for l in offAxis:
        ok = False
        for axis in l.keys():
            if axis not in onAxisValues:
                continue
            if l[axis] in onAxisValues[axis]:
                ok = True
        if ok:
            offAxis_projecting.append(l)
        else:
            offAxis_wild.append(l)
    return onAxis, offAxis_projecting, offAxis_wild


def biasFromLocations(locs, preferOrigin=True):
    """
        Find the vector that translates the whole system to the origin. 
    """
    dims = {}
    locs.sort()
    for l in locs:
        for d in l.keys():
            if not d in dims:
                dims[d] = []
            v = l[d]
            if type(v)==tuple:
                dims[d].append(v[0])
                dims[d].append(v[1])
            else:
                dims[d].append(v)
    candidate = Location()
    for k in dims.keys():
        dims[k].sort()
        v = mostCommon(dims[k])
        if dims[k].count(v) > 1:
            # add the dimension with two or more hits
            candidate[k] = mostCommon(dims[k])
    matches = []
    # 1. do we have an exact match?
    for l in locs:
        if candidate == l:
            return l
    # 2. find a location that matches candidate (but has more dimensions)
    for l in locs:
        ok = True
        for k, v in candidate.items():
            if l.get(k)!=v:
                ok = False
                break
        if ok:
            if not l in matches:
                matches.append(l)
    matches.sort()
    if len(matches)>0:
        if preferOrigin:
            for c in matches:
                if c.isOrigin():
                    return c
        return matches[0]
    # 3. no matches. Find the best from the available locations
    results = {}
    for bias in locs:
        rel = []
        for l in locs:
            rel.append((l - bias).isOnAxis())
        c = rel.count(False)
        if not c in results:
            results[c] = []
        results[c].append(bias)
    if results:
        candidates = results[min(results.keys())]
        if preferOrigin:
            for c in candidates:
                if c.isOrigin():
                    return c
        candidates.sort()
        return candidates[0]
    return Location()


def mostCommon(L):
    """
        #   http://stackoverflow.com/questions/1518522/python-most-common-element-in-a-list
        
        >>> mostCommon([1, 2, 2, 3])
        2
        >>> mostCommon([1, 2, 3])
        1
        >>> mostCommon([-1, 2, 3])
        -1
        >>> mostCommon([-1, -2, -3])
        -1
        >>> mostCommon([-1, -2, -3, -1])
        -1
        >>> mostCommon([-1, -1, -2, -2])
        -1
        >>> mostCommon([0, 0.125, 0.275, 1])
        0
        >>> mostCommon([0, 0.1, 0.4, 0.4])
        0.4
    """
    # get an iterable of (item, iterable) pairs
    SL = sorted((x, i) for i, x in enumerate(L))
    # print 'SL:', SL
    groups = itertools.groupby(SL, key=operator.itemgetter(0))
    # auxiliary function to get "quality" for an item
    def _auxfun(g):
        item, iterable = g
        count = 0
        min_index = len(L)
        for _, where in iterable:
            count += 1
            min_index = min(min_index, where)
        # print 'item %r, count %r, minind %r' % (item, count, min_index)
        return count, -min_index
    # pick the highest-count/earliest item
    return max(groups, key=_auxfun)[0]


if __name__ == "__main__":
    import doctest
    sys.exit(doctest.testmod().failed)