-
Notifications
You must be signed in to change notification settings - Fork 1
/
MLab_coe.py
2012 lines (1739 loc) · 53.8 KB
/
MLab_coe.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
## Automatically adapted for numpy Jun 08, 2006 by convertcode.py
## ALSO CHECKED MANUALLY: from numpy import *
## CHANGED MANUALLY: inf -> Inf; nan -> NaN
"""Matlab(tm) compatibility functions.
This will hopefully become a complete set of the basic functions available in
matlab. The syntax is kept as close to the matlab syntax as possible. One
fundamental change is that the first index in matlab varies the fastest (as in
FORTRAN). That means that it will usually perform reductions over columns,
whereas with this object the most natural reductions are over rows. It's perfectly
possible to make this work the way it does in matlab if that's desired.
"""
# I CHANGED median -- DC
# I ADDED thetastd -- DC
# I ADDED histogram -- DC
# avgstd2, std2, sum, total, size, divisible, ndec, interp, bilin
# HAD TO REMOVE RandomArray BECAUSE OF AN ERROR:
# ImportError: ld.so.1: python: fatal: /home/coe/python/ranlib.so: wrong ELF data format: ELFDATA2LS
#from Numeric import *
from numpy import *
from compress2 import compress2 as compress
from bisect import bisect
from scipy.integrate import quad
from scipy.special import erf
from numpy.random import * # random
#from biggles import *
import string
try:
from roman import roman # Roman numerals
except:
pass
def argmin2d(a):
i = argmin(a.flat)
ny, nx = a.shape
iy = i / nx
ix = i % nx
return iy, ix
def argmax2d(a):
i = argmax(a.flat)
ny, nx = a.shape
iy = i / nx
ix = i % nx
return iy, ix
def matrix_multiply(MM):
"""Multiplies a list of matrices: M[0] * M[1] * M[2]..."""
P = MM[0]
for M in MM[1:]:
P = dot(P, M)
return P
def sinn(x):
"""
x < 0: sin
x > 0: sinh
"""
if x < 0:
return sin(x)
else:
return sinh(x)
def multiples(lo, hi, x=1, eps=1e-7):
"""Returns an array of the multiples of x between [lo,hi] inclusive"""
l = ceil((lo-eps)/x)*x
return arange(l, hi+eps, x)
def multiples2(lohi, x=1, eps=1e-7):
"""Returns an array of the multiples of x between [lo,hi] inclusive"""
lo, hi = lohi
return multiples(lo, hi, x, eps)
def multipleslog(lo, hi):
"""Returns an array of the log multiples between [lo,hi] inclusive.
That didn't make sense, but what I'm trying to say is:
multipleslog(2, 30) = 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30"""
loglo = log10(lo)
loghi = log10(hi)
ll = multiples(loglo, loghi)
ll = concatenate([[loglo], ll, [loghi]])
mm = []
for i in range(len(ll)-1):
lo = 10 ** ll[i]
hi = 10 ** ll[i+1]
ex = 10 ** floor(ll[i])
m1 = multiples(lo, hi, ex)
if len(mm):
if close(m1[0], mm[-1]):
m1 = m1[1:]
mm = concatenate([mm, m1])
return mm
def multiples2log(lohi):
"""Returns an array of the log multiples between [lo,hi] inclusive.
That didn't make sense, but what I'm trying to say is:
multipleslog(2, 30) = 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30"""
lo, hi = lohi
return multipleslog(lo, hi)
def onlyids(data, ids):
"""ALTERS ARRAY data TO INCLUDE ONLY NUMBERS IN ids
ALL OTHER VALUES SET TO zero"""
keys = arange(data.size)
keysc = compress(data.flat, keys)
valsc = compress(data.flat, data.flat)
mask = zeros(data.size)
for id in ids:
ee = equal(valsc, id)
mask = logical_or(mask, ee)
keyscm = compress(mask, keysc)
valscm = compress(mask, valsc)
datanew = zeros(data.shape)
datanew.put(keyscm, valscm)
return datanew
def cliplohi(xlo, xhi, xmin, xmax):
return max([xlo, xmin]), min([xhi, xmax])
def base(b, nums):
"""base(10, [1, 2, 3]) RETURNS 123"""
if not isinstance(nums, list):
nums = nums.tolist()
nums.reverse()
x = 0
for i, num in enumerate(nums):
x += array(num) * b**i
return x
def strbegin(str, phr): # coetools.py
return str[:len(phr)] == phr
def minsec(x, format=(), precision=None):
"""
CONVERTS decimal degrees/hours to degrees/hours : minutes : seconds
minsec(13.52340987)
minsec(13.52340987, ':')
minsec(13.52340987, 'hms')
minsec(13.52340987, 'dms')
minsec(13.52340987, 'dms', 1)
"""
f, i = math.modf(x)
i = int(i)
m = 60 * f
s, m = math.modf(m)
m = int(m)
s = 60 * s
if type(format) == str:
if precision == None:
s = '%f' % s
else:
fmt = '%%.%df' % precision
s = fmt % s
if strbegin(s, '60'): # rounded up
s = '0'
m = m + 1
m = '%d' % m
if m == '60': # rounded up
m = '0'
i += 1
i = '%d' % i
ims = (i,m,s)
if len(format) == 1:
out = string.join(ims, format)
elif len(format) == 3:
out = i+format[0] + m+format[1] + s+format[2]
else:
out = (i, m, s)
return out
def sec2hms(x, precision=0, mpersist=True):
"""
CONVERTS decimal seconds to hours : minutes : seconds
"""
out = ''
if x > 60:
if x > 3600:
h = int(x / 3600)
out = '%d:' % h
x = x - 3600 * h
m = int(x / 60)
out += '%d:' % m
x = x - 60 * m
elif mpersist:
out = '0:'
if precision == None:
fmt = '%g'
elif precision == 0:
fmt = '%d'
else:
fmt = '%%.%df' % precision
s = fmt % x
if (x < 10) and mpersist:
s = '0' + s
out += s
return out
def sec2yr(x, precision=0, mpersist=True):
"""
CONVERTS decimal seconds to years, months, days, hours : minutes : seconds
"""
out = ''
minsec = 60 # minute
if x > minsec: # minutes
hoursec = minsec * 60 # hour
if x > hoursec: # hours
daysec = 24 * hoursec # day
if x > daysec: # days
yearsec = 365.25 * daysec
monthsec = yearsec / 12.
if x > monthsec: # months
if x > yearsec: # years
y = int(x / yearsec)
out = '%d years, ' % y
x = x - y * yearsec
months = int(x / monthsec)
out += '%d months, ' % months
x = x - months * monthsec
d = int(x / daysec)
out += '%d days, ' % d
x = x - d * daysec
h = int(x / 3600)
out += '%d hours, ' % h
x = x - 3600 * h
m = int(x / 60)
out += '%d minutes, ' % m
x = x - 60 * m
elif mpersist:
out = '0 minutes, '
if precision == None:
fmt = '%g'
elif precision == 0:
fmt = '%d'
else:
fmt = '%%.%df' % precision
s = fmt % x
if (x < 10) and mpersist:
s = '0' + s
out += s
out += ' seconds'
return out
sec2yr(33333333333)
minsec = 60 # minute
hoursec = minsec * 60 # hour
daysec = 24 * hoursec # day
yearsec = 365.25 * daysec
monthsec = yearsec / 12.
def prange(x, xinclude=None, margin=0.05):
"""RETURNS GOOD RANGE FOR DATA x TO BE PLOTTED IN.
xinclude = VALUE YOU WANT TO BE INCLUDED IN RANGE.
margin = FRACTIONAL MARGIN ON EITHER SIDE OF DATA."""
xmin = min(x)
xmax = max(x)
if xinclude <> None:
xmin = min([xmin, xinclude])
xmax = max([xmax, xinclude])
dx = xmax - xmin
if dx:
xmin = xmin - dx * margin
xmax = xmax + dx * margin
else:
xmin = xmin - margin
xmax = xmax + margin
return [xmin, xmax]
def minmax(x, range=None):
if range:
lo, hi = range
good = between(lo, x, hi)
x = compress(good, x)
return min(x), max(x)
def rescale(x, lohi):
lo, hi = lohi
xlo, xhi = minmax(x)
dx = xhi - xlo
dy = hi - lo
y = x / dx * dy + lo
return y
def inrange(x, r):
lo, hi = minmax(r)
return between(lo, x, hi)
def pairs(x):
p = []
for i in range(len(x)):
for j in range(i+1, len(x)):
p.append((x[i], x[j]))
return p
def Psig(P, nsigma=1):
"""(ir, il) bound central nsigma of P
-- edges contain equal amounts of P"""
Pn = P / total(P)
g = gausst(nsigma)
Pl = cumsum(Pn)
Pr = cumsum(Pn[::-1])
n = len(P)
i = arange(n)
il = interp(g, Pl, i)
ir = interp(g, Pr, i)
ir = n - ir
return il, ir
def xsig(x, P, nsigma=1):
print 'xsigmom MUCH MORE ACCURATE THAN xsig IN MLab_coe'
return p2p(take(x, Psig(P, nsigma))) / 2.
def gaussin(nsigma=1):
"""FRACTION WITHIN nsigma"""
return erf(nsigma / sqrt(2))
def gaussp(nsigma=1):
"""FRACTION INCLUDED UP TO nsigma"""
return 0.5 + gaussin(nsigma) / 2.
def gaussbtw(nsig1, nsig2):
"""FRACTION BETWEEN nsig1, nsig2"""
return abs(gaussp(nsig2) - gaussp(nsig1))
#gaussbtw(0, 3)
sigma = gaussin
def gausst(nsigma=1):
"""FRACTION IN TAIL TO ONE SIDE OF nsigma"""
return 1 - gaussp(nsigma)
###
# ~/glens/h0limits/gravlens/mock/1/ptdrawbox24dsepL0.py
from scipy.optimize import golden
def mom2(x, y):
return sqrt(total(x**2 * y) / total(y))
def mom2dx(dx, x, y):
return mom2(x+dx, y)
def xsigmom(x, y):
"""1-sigma of y(x) calculated using moments"""
dx = golden(mom2dx, (x, y))
return mom2(x+dx, y)
def testxsigmom():
x = mgrid[-5:5:100001j]
g = gauss1(abs(x-0.98765), 0.123456789)
print xsig(x, g)
print xsigmom(x, g)
x = mgrid[-5:5:101j]
g = gauss1(abs(x-0.98765), 0.123456789)
print xsig(x, g)
print xsigmom(x, g)
###
def pick(x):
n = len(x)
i = random_integers(n)
return x[i-1]
def randrange(N=1):
return (2 * random(N) - 1)
def randrange2(lo, hi, N=1):
return ((hi - lo) * random(N) + lo)
class PDraw:
def __init__(self, x, P):
self.x = x
self.P = P
self.Pcum = cumsum(P)
self.N = self.Pcum[-1]
def draw(self, n=1):
r = self.N * random(n)
i = searchsorted(self.Pcum, r)
return take(self.x, i)
def hypotsq(dx, dy):
return dx**2 + dy**2
def hypotn(x):
return sqrt(sum(x**2))
def hypotnn(*x):
return hypotn(array(x))
#hypotnn(3, 4, 5)
def hypotxy(x1, y1, x2, y2):
return hypot(x1-x2, y1-y2)
def hypotinvn(x):
return 1 / sqrt(sum(1./x**2))
def hypotinvnn(*x):
return hypotinvn(array(x))
def hypotinv(x, y):
return hypotinvnn(x, y)
def subtend(x1, y1, x2, y2):
"""ANGLE SUBTENDED BY TWO VECTORS (wrt THE ORIGIN)"""
# v1 (dot) v2 = |v1| |v2| cos(theta)
# d = r1 r2 cos(theta)
d = dot([x1, y1], [x2, y2])
r1 = hypot(x1, y1)
r2 = hypot(x2, y2)
costheta = d / (r1 * r2)
theta = arccos(costheta)
return theta
def subtends(x, y):
n = len(x)
dd = []
for i in range(n-1):
for j in range(i+1,n):
dd.append(subtend(x[i], y[i], x[j], y[j]))
return array(dd)
def distances(x, y):
n = len(x)
dd = []
for i in range(n-1):
for j in range(i+1,n):
dd.append(hypot(x[i]-x[j], y[i]-y[j]))
return array(dd)
def differences(x):
n = len(x)
dd = []
for i in range(n-1):
for j in range(i+1,n):
dd.append(x[i]-x[j])
return array(dd)
def nrange(x, n=100):
"""n EQUALLY-SPACED SAMPLES ON THE RANGE OF x"""
return arange(n) / (n-1.) * (max(x) - min(x)) + min(x)
def range01(n=100):
"""n EQUALLY-SPACED SAMPLES ON THE RANGE OF [0,1]"""
return arange(n) / (n-1.)
def middle(x):
return (max(x) + min(x)) / 2.
def within(A, xc, yc, ro, yesorno=0): # --DC
"""RETURNS WHETHER EACH PIXEL OF AN ARRAY IS WITHIN A CIRCLE
DEFINED ON THE ARRAY'S COORDINATES.
FRACTIONAL MEMBERSHIP IS ALSO ESTIMATED
BY THE FRACTION OF THE BOX CROSSED BY THE CIRCLE AT THAT ANGLE.
IT'S LIKE ANTI-ALIASING.
THESE FRACTIONS ARE SLIGHTLY OVERESTIMATED
BUT ARE AN IMPROVEMENT OVER NOT USING THEM AT ALL!
TO TURN OFF FRACTIONS AND JUST RETURN True/False, SET yesorno=1"""
ny, nx = A.shape
a = ones((ny,nx))
y = arange(ny)
x = arange(nx)
x, y = meshgrid(x, y)
x = x-xc + 0.
y = y-yc + 0.
r = hypot(x,y)
xy = abs(divsafe(x, y, nan=0))
yx = abs(divsafe(y, x, nan=0))
m = min([xy, yx])
dr = hypot(1, m) # = 1 ON AXES, sqrt(2) ON DIAGONALS
if (ro - xc > 0.5) or (ro - yc > 0.5) \
or (ro + xc > nx - 0.5) or (ro + yc > ny - 0.5):
print 'WARNING: CIRCLE EXTENDS BEYOND BOX IN MLab_coe.within'
if yesorno:
v = less_equal(r, ro) # TRUE OR FALSE, WITHOUT FRACTIONS
else:
v = less_equal(r, ro-0.5*dr) * 1
v = v + between(ro-0.5*dr, r, ro+0.5*dr) * (ro+0.5*dr - r) / dr
#if showplot: matplotlib NOT LOADED IN MLab_coe
if 0:
matshow(v)
circle(xc+0.5, yc+0.5, ro, color='k', linewidth=2)
return v
#def sumwithin(A, xc, yc, ro, showplot=0):
# return total(A * within(A, xc, yc, ro, showplot=showplot))
def sumwithin(A, xc, yc, ro):
"""RETURNS SUM OF ARRAY WITHIN CIRCLE DEFINED ON ARRAY'S COORDINATES"""
return total(A * within(A, xc, yc, ro))
def floatin(x, l, ndec=3):
"""IS x IN THE LIST l?
WHO KNOWS WITH FLOATING POINTS!"""
x = int(x * 10**ndec + 0.1)
l = (array(l) * 10**ndec + 0.1).astype(int).tolist()
return x in l
def floatindex(x, l, ndec=3):
"""IS x IN THE LIST l?
WHO KNOWS WITH FLOATING POINTS!"""
x = int(x * 10**ndec + 0.1)
l = (array(l) * 10**ndec + 0.1).astype(int).tolist()
return l.index(x)
def integral(f, x1, x2):
return quad(f, x1, x2)[0]
def magnify(a, n):
"""MAGNIFIES A MATRIX BY n
YIELDING, FOR EXAMPLE:
>>> magnify(IndArr(3,3), 2)
001122
001122
334455
334455
667788
667788
"""
ny, nx = a.shape
a = repeat(a, n**2)
a = reshape(a, (ny,nx,n,n))
a = transpose(a, (0, 2, 1, 3))
a = reshape(a, (n*ny, n*nx))
return a
def demagnify(a, n, func='mean'):
"""DEMAGNIFIES A MATRIX BY n
YIELDING, FOR EXAMPLE:
>>> demagnify(magnify(IndArr(3,3), 2), 2)
012
345
678
"""
ny, nx = array(a.shape) / n
a = a[:ny*8,:nx*8] # Trim if not even multiples
a = reshape(a, (ny, n, nx, n))
a = transpose(a, (0, 2, 1, 3))
a = reshape(a, (ny, nx, n*n))
a = transpose(a, (2, 0, 1))
exec('a = %s(a)' % func)
return a
# Elementary Matrices
# zeros is from matrixmodule in C
# ones is from Numeric.py
import numpy.random as RandomArray
import math
def listo(x):
if singlevalue(x):
x = [x]
return x
# ~/glens/h0limits/scatterrea.py
def insidepoly1(xp, yp, x, y):
"""DETERMINES WHETHER THE POINT (x, y)
IS INSIDE THE CONVEX POLYGON DELIMITED BY (xp, yp)"""
xp, yp = CCWsort(xp, yp)
xp = xp.tolist()
yp = yp.tolist()
if xp[-1] <> xp[0]:
xp.append(xp[0])
yp.append(yp[0])
xo = mean(xp)
yo = mean(yp)
inpoly = 1
xa = [xo, x]
ya = [yo, y]
for j in range(len(xp)-1):
xb = xp[j:j+2]
yb = yp[j:j+2]
if linescross2(xa, ya, xb, yb):
inpoly = 0
break
return inpoly
# ~/glens/h0limits/scatterrea.py
# ALSO SEE matplotlib.nxutils.pnpoly & points_inside_poly()
# http://matplotlib.sourceforge.net/faq/howto_faq.html
def insidepoly(xp, yp, xx, yy):
"""DETERMINES WHETHER THE POINTS (xx, yy)
ARE INSIDE THE CONVEX POLYGON DELIMITED BY (xp, yp)"""
xp, yp = CCWsort(xp, yp)
xx = ravel(listo(xx))
yy = ravel(listo(yy))
inhull = []
for i in range(len(xx)):
if i and not (i % 10000):
print '%d / %d' % (i, len(xx))
inhull1 = insidepoly1(xp, yp, xx[i], yy[i])
inhull.append(inhull1)
return array(inhull).astype(int)
# TESTED IN ~/glens/lenspoints/optdefl/sourceconstraints/testconvexhull.py
# testinsidepoly() -- NEVER QUITE GOT THE TEST TO WORK HERE
def insidepolyshwag(xp, yp, xx, yy):
"""DETERMINES WHETHER THE POINTS (xx, yy)
ARE INSIDE THE CONVEX POLYGON DELIMITED BY (xp, yp)"""
xp, yp = CCWsort(xp, yp) # NEEDED
xp = xp.tolist()
yp = yp.tolist()
if xp[-1] <> xp[0]:
xp.append(xp[-1]) # SHOULD BE [0]
yp.append(yp[-1]) # SHOULD BE [0]
xo = mean(xp)
yo = mean(yp)
xx = ravel(listo(xx))
yy = ravel(listo(yy))
inhull = ones(len(xx)).astype(int)
for i in range(len(xx)):
if i and not (i % 10000):
print '%d / %d' % (i, len(xx))
xa = [xo, xx[i]]
ya = [yo, yy[i]]
for j in range(len(xp)-2):
xb = xp[j:j+2]
yb = yp[j:j+2]
if linescross2(xa, ya, xb, yb):
inhull[i] = 0
break
return inhull
def testinsidepoly():
#from numpy.random import random
N = 40
x = random(50) * N
y = random(50) * N
xh, yh = convexhull(x, y)
zz = arange(N)
xx, yy = meshgrid(zz, zz)
xx = ravel(xx)
yy = ravel(yy)
inhull = insidepoly(xh, yh, xx, yy)
figure(11)
clf()
plot(xh, yh)
ioff()
for i in range(len(XX)):
color = ['r', 'g'][ininin[i]]
p = plot([xx[i]], [yy[i]], 'o', mfc=color)
show()
def p2p(x): # DEFINED AS ptp IN MLab (BELOW)
return max(x) - min(x)
def rotate(x, y, ang):
"""ROTATES (x, y) BY ang RADIANS CCW"""
x2 = x * cos(ang) - y * sin(ang)
y2 = y * cos(ang) + x * sin(ang)
return x2, y2
def rotdeg(x, y, ang):
"""ROTATES (x, y) BY ang DEGREES CCW"""
return rotate(x, y, ang/180.*pi)
def linefit(x1, y1, x2, y2):
"""y = mx + b FIT TO TWO POINTS"""
if x2 == x1:
m = Inf
b = NaN
else:
m = (y2 - y1) / (x2 - x1)
b = y1 - m * x1
return m, b
def linescross(xa, ya, xb, yb):
"""
DO THE LINES CONNECTING A TO B CROSS?
A: TWO POINTS: (xa[0], ya[0]), (xa[1], ya[1])
B: TWO POINTS: (xb[0], yb[0]), (xb[1], yb[1])
DRAW LINE FROM A0 TO B0
IF A1 & B1 ARE ON OPPOSITE SIDES OF THIS LINE,
AND THE SAME IS TRUE VICE VERSA,
THEN THE LINES CROSS
"""
if xa[0] == xb[0]:
xb = list(xb)
xb[0] = xb[0] + 1e-10
if xa[1] == xb[1]:
xb = list(xb)
xb[1] = xb[1] + 1e-10
m0, b0 = linefit(xa[0], ya[0], xb[0], yb[0])
ya1 = m0 * xa[1] + b0
yb1 = m0 * xb[1] + b0
cross1 = (ya1 > ya[1]) <> (yb1 > yb[1])
m1, b1 = linefit(xa[1], ya[1], xb[1], yb[1])
ya0 = m1 * xa[0] + b1
yb0 = m1 * xb[0] + b1
cross0 = (ya0 > ya[0]) <> (yb0 > yb[0])
return cross0 and cross1
def linescross2(xa, ya, xb, yb):
"""
DO THE LINES A & B CROSS?
DIFFERENT NOTATION:
LINE A: (xa[0], ya[0]) -> (xa[1], ya[1])
LINE B: (xb[0], yb[0]) -> (xb[1], yb[1])
DRAW LINE A
IF THE B POINTS ARE ON OPPOSITE SIDES OF THIS LINE,
AND THE SAME IS TRUE VICE VERSA,
THEN THE LINES CROSS
"""
if xa[0] == xa[1]:
xa = list(xa)
xa[1] = xa[1] + 1e-10
if xb[0] == xb[1]:
xb = list(xb)
xb[1] = xb[1] + 1e-10
ma, ba = linefit(xa[0], ya[0], xa[1], ya[1])
yb0 = ma * xb[0] + ba
yb1 = ma * xb[1] + ba
crossb = (yb0 > yb[0]) <> (yb1 > yb[1])
mb, bb = linefit(xb[0], yb[0], xb[1], yb[1])
ya0 = mb * xa[0] + bb
ya1 = mb * xa[1] + bb
crossa = (ya0 > ya[0]) <> (ya1 > ya[1])
return crossa and crossb
def linescross2test():
# from numpy.random import random
xa = random(2)
ya = random(2)
xb = random(2)
yb = random(2)
figure(1)
clf()
plot(xa, ya)
plot(xb, yb)
title('%s' % linescross2(xa, ya, xb, yb))
show()
def linescrosstest():
# from random import random
xa = random(), random()
ya = random(), random()
xb = random(), random()
yb = random(), random()
figure(1)
clf()
atobplot(xa, ya, xb, yb, linetype='')
title('%s' % linescross(xa, ya, xb, yb))
show()
def outside(x, y, xo, yo):
"""GIVEN 3 POINTS a, b, c OF A POLYGON
WITH CENTER xo, yo
DETERMINE WHETHER b IS OUTSIDE ac,
THAT IS, WHETHER abc IS CONVEX"""
# DOES o--b CROSS a--c ?
# A--B A--B
xa, xb, xc = x
ya, yb, yc = y
xA = (xo, xa)
yA = (yo, ya)
xB = (xb, xc)
yB = (yb, yc)
return linescross(xA, yA, xB, yB)
# TESTED IN ~/glens/lenspoints/optdefl/sourceconstraints/testconvexhull.py
def convexhull(x, y, rep=1, nprev=0):
"""RETURNS THE CONVEX HULL OF x, y
THAT IS, THE EXTERIOR POINTS"""
x = x.astype(float)
y = y.astype(float)
x, y = CCWsort(x, y)
xo = mean(x)
yo = mean(y)
x = x.tolist()
y = y.tolist()
dmax = max([p2p(x), p2p(y)])
ngood = 0
while ngood < len(x)+1:
dx = x[1] - xo
dy = y[1] - yo
dr = hypot(dx, dy)
dx = dx * dmax / dr
dy = dy * dmax / dr
x1 = xo - dx
y1 = yo - dy
if not outside(x[:3], y[:3], x1, y1):
del x[1]
del y[1]
else: # ROTATE THE COORD LISTS
x.append(x.pop(0))
y.append(y.pop(0))
ngood += 1
x = array(x)
y = array(y)
# REPEAT UNTIL CONVERGENCE
if (nprev == 0) or (len(x) < nprev):
x, y = convexhull(x, y, nprev=len(x))
if rep:
x = concatenate((x, [x[0]]))
y = concatenate((y, [y[0]]))
return x, y
def gauss(r, sig=1., normsum=1):
"""GAUSSIAN NORMALIZED SUCH THAT AREA=1"""
r = clip(r/float(sig), 0, 10)
G = exp(-0.5 * r**2)
G = where(less(r, 10), G, 0)
if normsum:
G = G * 0.5 / (pi * sig**2)
return G
def gauss1(r, sig=1.):
"""GAUSSIAN NORMALIZED SUCH THAT PEAK AMPLITUDE = 1"""
return gauss(r, sig, 0)
def atanxy(x, y, degrees=0):
"""ANGLE CCW FROM x-axis"""
theta = arctan(divsafe(y, x, inf=1e30, nan=0))
theta = where(less(x, 0), theta + pi, theta)
theta = where(logical_and(greater(x, 0), less(y, 0)), theta + 2*pi, theta)
if degrees:
theta = theta * 180. / pi
return theta
def chebyshev(x,n):
if n == 0:
return x ** 0
elif n == 1:
return x
elif n == 2:
return 2 * x ** 2 - 1
elif n == 3:
return 4 * x ** 3 - 3 * x
elif n == 4:
return 8 * x ** 4 - 8 * x ** 2
elif n == 5:
return 16 * x ** 5 - 20 * x ** 3 + 5 * x
elif n == 6:
return 32 * x ** 6 - 48 * x ** 4 + 18 * x ** 2 - 1
def chebyshev2d(x,y,a):
A = x * 0
ncy, ncx = a.shape
for iy in range(ncy):
for ix in range(ncx):
if a[iy][ix]:
A = A + a[iy][ix] * chebyshev(x,ix) * chebyshev(y,iy)
return A
def crossprod(a, b):
"""CROSS PRODUCT (PROBABLY DEFINED IN SOME BUILT-IN MODULE!)"""
return a[0] * b[1] - a[1] * b[0]
def dotprod(a, b):
"""DOT PRODUCT (PROBABLY DEFINED IN SOME BUILT-IN MODULE!)"""
return a[0] * b[0] + a[0] * b[0]
def triarea(x, y, dir=0):
"""RETURNS THE AREA OF A TRIANGLE GIVEN THE COORDINATES OF ITS VERTICES
A = 0.5 * | u X v |
where u & v are vectors pointing from one vertex to the other two
and X is the cross-product
The dir flag lets you retain the sign (can tell if triangle is flipped)"""
ux = x[1] - x[0]
vx = x[2] - x[0]
uy = y[1] - y[0]
vy = y[2] - y[0]
A = 0.5 * (ux * vy - uy * vx)
if not dir:
A = abs(A)
return A
def CCWsort(x, y):
"""FOR A CONVEX SET OF POINTS,
SORT THEM SUCH THAT THEY GO AROUND IN ORDER CCW FROM THE x-AXIS"""
xc = mean(x)
yc = mean(y)
ang = atanxy(x-xc, y-yc)
SI = array(argsort(ang))
x2 = x.take(SI, 0)
y2 = y.take(SI, 0)
return x2, y2
def polyarea(x, y):
"""RETURNS THE AREA OF A CONVEX POLYGON
GIVEN ITS COORDINATES (IN ANY ORDER)"""
A = 0.
x, y = CCWsort(x, y)
for i in range(1, len(x)-1):
xtri = x.take((0, i, i+1), 0)
ytri = y.take((0, i, i+1), 0)
A += triarea(xtri, ytri)
return A
def odd(n):
"""RETURNS WHETHER AN INTEGER IS ODD"""
return n & 1
def even(n):
"""RETURNS WHETHER AN INTEGER IS EVEN"""
return 1 - odd(n)
def fpart(x):
"""FRACTIONAL PART OF A REAL NUMBER"""
if type(x) in [array, list]:
if len(x) == 1:
x = x[0]
return math.modf(x)[0]
def sigrange(x, nsigma=1):
lo = percentile(gausst(nsigma), x)
hi = percentile(gaussp(nsigma), x)
return lo, hi
def sqrtsafe(x):
"""sqrt(x) OR 0 IF x < 0"""
x = clip2(x, 0, None)
return sqrt(x)
def sgn(a):
return where(a, where(greater(a, 0), 1, -1), 0)
def sym8(a):
"""OKAY, SO THIS ISN'T QUITE RADIAL SYMMETRY..."""
x = a + flipud(a) + fliplr(a) + transpose(a) + rot90(transpose(a),2) + rot90(a,1) + rot90(a,2) + rot90(a,3)
return x / 8.
#def divsafe(a, b, inf=1e30, nan=0.):
def divsafe(a, b, inf=Inf, nan=NaN):
"""a / b with a / 0 = inf and 0 / 0 = nan"""
a = array(a).astype(float)
b = array(b).astype(float)
asgn = greater_equal(a, 0) * 2 - 1.
bsgn = greater_equal(b, 0) * 2 - 1.
xsgn = asgn * bsgn
sgn = where(b, xsgn, asgn)
sgn = where(a, xsgn, bsgn)
babs = clip(abs(b), 1e-200, 1e9999)
bb = bsgn * babs
#return where(b, a / bb, where(a, Inf, NaN))
return where(b, a / bb, where(a, sgn*inf, nan))
def expsafe(x):
x = array(x)
y = []
for xx in x:
if xx > 708:
y.append(1e333) # inf
elif xx < -740:
y.append(0)
else:
y.append(exp(xx))
if len(y) == 1:
return y[0]
else:
return array(y)
def floorint(x):
return(int(floor(x)))
def ceilint(x):
return(int(ceil(x)))