-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
executable file
·3713 lines (3051 loc) · 102 KB
/
utils.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
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 5 18:11:33 2016
@author: johnlewisiii
"""
import math
import os
import statistics
import sys
from importlib import reload
import warnings
import emcee
import matplotlib as mpl
import matplotlib.cm as cm
import matplotlib.colors as colors
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from astropy import constants as constants
from astropy import units as u
from astropy.coordinates import SkyCoord
from astropy.io import fits
from astropy.table import Table
from astropy.wcs import WCS
from mpl_toolkits.axes_grid1 import make_axes_locatable, axes_size
from scipy import integrate, interpolate, ndimage, signal, stats
import scipy.special as special
from weighted import quantile
from bces.bces import bces
from astropy.stats import mad_std
from matplotlib.patheffects import withStroke
import john_plot as jplot
import error_prop as jerr
import sphere as sphere
import background as background
#from john_plot import annotate
import moment_masking as jmm
import alma_helpers as ah
reload(jplot)
reload(jerr)
reload(sphere)
reload(background)
reload(jmm)
reload(ah)
nd = ndimage
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
__filtertable__ = Table.read(
os.path.join(__location__, "FilterSpecs.tsv"), format="ascii"
)
def nice_pandas(format="{:3.3g}"):
pd.set_option("display.float_format", lambda x: format.format(x))
#############################
#############################
#### Plotting commands ####
#############################
#############################
# Set uniform plot options
# some constants
fwhm = 2 * np.sqrt(2 * np.log(2))
#legacy
def set_plot_opts(serif_fonts=True):
if serif_fonts:
mpl.rcParams["mathtext.fontset"] = "stix"
mpl.rcParams["font.family"] = "serif"
mpl.rcParams["font.size"] = 14
return None
# def annotate(*args,**kwargs):
# return jplot.annotate(*args,**kwargs)
def annotate(text, x, y, ax=None,
horizontalalignment="center",
verticalalignment="center",
ha=None, va=None, transform="axes",
fontsize=9,
color="k",
facecolor="w",
edgecolor='0.75',
alpha=0.75,
text_alpha=1,
bbox=dict(),
stroke = None,
**kwargs,
):
"""wrapper for Axes.text
Parameters
----------
text : str
text
x : number
x coordinate
y : number
x coordinate
ax : axes, optional
[description], by default None
horizontalalignment : str, optional
by default "center"
verticalalignment : str, optional
by default "center"
ha : alias for horizontalalignment
va : alias for verticalalignment
transform : str, optional
use 'axes' (ax.transAxes) or 'data' (ax.transData) to interpret x,y
fontsize : int, optional
by default 9
color : str, optional
text color, by default "k"
facecolor : str, optional
color of frame area, by default "w"
edgecolor : str, optional
color of frame edge, by default '0.75'
alpha : float, optional
transparency of frame area, by default 0.75
text_alpha : int, optional
transparency of text, by default 1
bbox : [type], optional
dictionary defining the bounding box or frame, by default dict()
stroke : (list, mpl.patheffects,dict), optional
most often should be dict with {'foregroud':"w", linewidth:3}
if using stroke, use should set bbox=None
Returns
-------
text
the annotation
"""
if ax is None:
ax = plt.gca()
horizontalalignment = ha or horizontalalignment
verticalalignment = va or verticalalignment
if transform == "axes":
transform = ax.transAxes
elif transform == "data":
transform = ax.transData
if bbox is None:
bbox1 = dict(facecolor='none', alpha=0,edgecolor='none')
else:
bbox1 = dict(facecolor=facecolor, alpha=alpha,edgecolor=edgecolor)
bbox1.update(bbox)
text = ax.text(
x,
y,
text,
horizontalalignment=horizontalalignment,
verticalalignment=verticalalignment,
transform=transform,
color=color,
fontsize=fontsize,
bbox=bbox1,
**kwargs,
)
if stroke is not None:
if type(stroke) == dict:
text.set_path_effects([withStroke(**stroke)])
elif isinstance(stroke,(list,tuple)):
text.set_path_effects([*stroke])
elif isinstnace(stroke,mpl.patheffects.AbstractPathEffect):
text.set_path_effects([stroke])
return text
def check_iterable(arr):
return hasattr(arr, "__iter__")
def color_array(arr, alpha=1):
""" take an array of colors and convert to
an RGBA image that can be displayed
with imshow
"""
img = np.zeros(arr.shape + (4,))
for row in range(arr.shape[0]):
for col in range(arr.shape[1]):
c = mpl.colors.to_rgb(arr[row, col])
img[row, col, 0:3] = c
img[row, col, 3] = alpha
return img
def arr_to_rgb(arr, rgb=(0, 0, 0), alpha=1, invert=False, ax=None):
"""
arr to be made a mask
rgb:assumed using floats (0..1,0..1,0..1) or string
"""
#check if boolean or single value
is_bool = ((arr==0) | (arr==1)).all() or (arr.dtype is np.dtype(bool))
# arr should be scaled to 1
img = np.asarray(arr, dtype=np.float64)
if not is_bool:
img = img - np.nanmin(img)
img = img / np.nanmax(img)
im2 = np.zeros(img.shape + (4,))
if isinstance(rgb, str):
rgb = mpl.colors.to_rgb(rgb)
if invert:
img = 1 - img
im2[:, :, 3] = img * alpha
r, g, b = rgb
im2[:, :, 0] = r
im2[:, :, 1] = g
im2[:, :, 2] = b
# if ax is None:
# ax = plt.gca()
# plt.sca(ax)
# plt.imshow(im2)
return im2
def invert_color(ml, *args, **kwargs):
rgb = mpl.colors.to_rgb(ml)
hsv = mpl.colors.rgb_to_hsv(rgb)
h, s, v = hsv
h = 1 - h
s = 1 - s
v = 1 - v
return mpl.colors.to_hex(mpl.colors.hsv_to_rgb((h, s, v)))
def icol(*args, **kwargs):
return invert_color(*args, **kwargs)
def to64(arr):
# Convert numpy to 64-bit precision
if hasattr(arr, "astype"):
return arr.astype("float64")
else:
if hasattr(arr, "__iter__"):
if isinstance(arr[0], u.quantity.Quantity):
return u.quantity.Quantity(arr, dtype=np.float64)
return np.float64(arr)
def get_xylim(ax=None):
if ax is None:
ax = plt.gca()
xlim, ylim = ax.get_xlim(), ax.get_ylim()
return xlim, ylim
def set_xylim(xlim=None, ylim=None, ax=None, origin=None):
"""set xylims with tuples
xlim: tuple of x axis limits
ylim: tuple of y axis limits
origin: sometimes you just want to change the origin
so you can keep the axis limits the same
but just change origin
"""
if ax is None:
ax = plt.gca()
if xlim is None:
xlim = ax.get_xlim()
if ylim is None:
ylim = ax.get_ylim()
if isinstance(xlim, tuple):
xlim = list(xlim)
if isinstance(ylim, tuple):
ylim = list(ylim)
if origin is not None:
if origin is True:
if ax.get_xaxis().get_scale()[:3] != "log":
xlim[0] = 0
if ax.get_yaxis().get_scale()[:3] != "log":
ylim[0] = 0
else:
xlim[0] = origin[0]
ylim[0] = origin[1]
ax.set_xlim(xlim)
ax.set_ylim(ylim)
return tuple(xlim), tuple(ylim)
def _normalize_location_orientation(location, orientation):
loc_settings = {
"left": {
"location": "left",
"orientation": "vertical",
"anchor": (1.0, 0.5),
"panchor": (0.0, 0.5),
"pad": 0.10,
},
"right": {
"location": "right",
"orientation": "vertical",
"anchor": (0.0, 0.5),
"panchor": (1.0, 0.5),
"pad": 0.05,
},
"top": {
"location": "top",
"orientation": "horizontal",
"anchor": (0.5, 0.0),
"panchor": (0.5, 1.0),
"pad": 0.05,
},
"bottom": {
"location": "bottom",
"orientation": "horizontal",
"anchor": (0.5, 1.0),
"panchor": (0.5, 0.0),
"pad": 0.15,
},
}
return loc_settings
def get_cax(ax=None, position=None, frac=0.03, pad=0.02):
"""get a colorbar axes of the same height as current axes
position: "left" "right" ( vertical | )
"top" "bottom" (horizontal --- )
"""
if ax is None:
ax = plt.gca()
size = f"{frac*100}%"
divider = make_axes_locatable(ax)
if position is None:
position = 'right'
if position is 'bottom':
pad += 0.15
if position is 'right':
left = 1 + pad
width = frac
bottom = 0.0
height = 1.0
elif position is 'bottom':
left = 0.0
width = 1.0
bottom = 0 - pad
height = frac*2
else:
raise ValueError(f"position {position} not supported")
p = [left, bottom, width, height]
cax = ax.inset_axes(p, transform=ax.transAxes)
plt.sca(ax)
return cax
def colorbar(mappable=None, cax=None, ax=None, size=0.03, pad=0.05, position=None, orientation='vertical', **kw):
"""wrapper for pyplot.colorbar.
"""
if ax is None:
ax = plt.gca()
if orientation[0].lower()=='h':
pos = 'bottom'
elif orientation[0].lower()=='v':
pos = 'right'
if cax is None:
cax = get_cax(ax=ax, frac=size, pad=pad, position=position)
elif (cax == 'inset') & (orientation[0].lower()=='h'):
cax = ax.inset_axes([0.2,.1,0.6,0.05])
elif (cax == 'inset') & (orientation[0].lower()=='v'):
cax = ax.inset_axes([0.85,.1,0.05,0.8])
ret = plt.colorbar(mappable, cax=cax, ax=ax, **kw)
return ret
# Plot the KDE for a set of x,y values. No weighting code modified from
# http://stackoverflow.com/questions/30145957/plotting-2d-kernel-density-estimation-with-python
def kdeplot(xp, yp, filled=False, ax=None, grid=None, bw=None, *args, **kwargs):
if ax is None:
ax = plt.gca()
rvs = np.append(xp.reshape((xp.shape[0], 1)), yp.reshape((yp.shape[0], 1)), axis=1)
kde = stats.kde.gaussian_kde(rvs.T)
# kde.covariance_factor = lambda: 0.3
# kde._compute_covariance()
kde.set_bandwidth(bw)
# Regular grid to evaluate kde upon
if grid is None:
x_flat = np.r_[rvs[:, 0].min() : rvs[:, 0].max() : 256j]
y_flat = np.r_[rvs[:, 1].min() : rvs[:, 1].max() : 256j]
else:
x_flat = np.r_[0 : grid[0] : complex(0, grid[0])]
y_flat = np.r_[0 : grid[1] : complex(0, grid[1])]
x, y = np.meshgrid(x_flat, y_flat)
grid_coords = np.append(x.reshape(-1, 1), y.reshape(-1, 1), axis=1)
z = kde(grid_coords.T)
z = z.reshape(x.shape[0], x.shape[1])
if filled:
cont = ax.contourf
else:
cont = ax.contour
cs = cont(x_flat, y_flat, z, *args, **kwargs)
return cs
AtomicMass = {"H2": 2, "12CO": 12 + 16, "13CO": 13 + 16, "C18O": 12 + 18, "ISM": 2.33}
def thermal_v(T, mu=None, mol=None):
"""thermal_v(T,mu)
get thermal velocity for a temperature & molecular mass mu
Arguments:
T {[float]} -- [temperature in kelvin]
Keyword Arguments:
mu {int} -- [description] (default: {1})
ISM: 2.33
12CO, 13CO,C18O = 18,19,20
Returns:
[type] -- [description]
"""
if mu is None:
if mol in AtomicMass.keys():
mu = AtomicMass[mol]
else:
mu = 1
return np.sqrt(constants.k_B * T * u.Kelvin / (mu * constants.m_p)).to("km/s").value
def virial(sig, mass, r):
s = 1.33 * (sig * (u.km / u.s)) ** 2
r = r * u.pc
m = constants.G * (mass * u.Msun)
return (s * r / m).si.value
def numdens(mass, radius):
"""number density from mass/radius
assuming spherical symmetry
Parameters
----------
mass : float
in solar masses
radius : float
in parsecs
Returns
-------
float
in cm^-3
"""
mass = mass * u.solMass
radius = radius * u.pc
volume = (4 / 3) * np.pi * (radius ** 3)
dens = (mass / volume) / (2.33 * constants.m_p)
return dens.to(u.cm ** -3).value
def jeansmass(temp, numdens, mu=2.33): # 12.03388 msun T=n=1
"""
temp in K
numdens in cm^-3
mu is mean molecular weight [default: 2.33, ISM w/ Helium corr]
returns Mjeans in solar masses
.5 * (5 * kb / G)^3 * (3/4π) * (1/2.33 mp)^4 * T^3 / n
"""
mj = (5 * constants.k_B / (constants.G)) ** 3
mj *= 3 / (4 * np.pi)
mj *= (1 / (mu * constants.m_p)) ** 4
mj = mj * (temp * u.K) ** 3
mj = mj * (u.cm ** 3 / numdens)
mj = mj ** 0.5
return mj.to(u.solMass).value
#############################
#############################
# Convenience math functions
#############################
#############################
def freq_grid(t, fmin=None, fmax=None, pmin=None, pmax=None, oversamp=10.0, ):
"""
freq_grid(t,fmin=None,fmax=None,oversamp=10.,pmin=None,pmax=None)
Generate a 1D list of frequences over a certain range
[oversamp] * nyquist sampling
"""
if pmax is not None:
if pmax == pmin:
pmax = 10 * pmax
fmin = 1.0 / pmax
if pmin is not None:
if pmax == pmin:
pmin = 0.1 * pmin
fmax = 1.0 / pmin
dt = t.max() - t.min()
nyquist = 2.0 / dt
df = nyquist / oversamp
Nf = 1 + int(np.round((fmax - fmin) / df))
return fmin + df * np.arange(Nf)
def sigconf1d(n):
"""
calculate the percentile corresponding to n*sigma
for a 1D gaussian
"""
cdf = (1 / 2.0) * (1 + special.erf(n / np.sqrt(2)))
return (1 - cdf) * 100, 100 * cdf # , 100 * special.erf(n / np.sqrt(2))
def nsigma(dim=1, n=1,return_interval=False):
"""Generalized n-sigma relation
Parameters
----------
dim : float, optional
dimensionality, by default 1
n : float, optional
N-sigma, by default 1
Returns
-------
float
the percential/100 corresponding the given sigma
References:
https://math.stackexchange.com/a/3668447
https://mathworld.wolfram.com/RegularizedGammaFunction.html
The generalized N-sigma relation for M dimensions is given
by the Regularized Lower Incomplete Gamma Function -
P(a,z) = γ(a,z)/Γ(a), where γ(a,z) is the lower incomplete gamma function
The Incomplete Gamma Function is defined
$\Gamma(a,z0,z1) = \int_z0^z1 t^{a-1} e^{-t} dt$
For 1D: $Erf(n/sqrt(2)) = \Gamma(1,0,n^2/2)/\Gamma(1)$ gives the Percentile for n-sigma
For 2D: 1 - exp(-m^2 /2) gives the Percentile for n-sigma
P(m/2,n^2 / 2) generalizes this to m dimensions
We need the regularized lower incomplete gamma, which is Gamma(a,z0,z1)/Gamma(a,0,inf)
this is the incomp. reg. gamma func P(a,z) in
If we want to think about this in terms of Mahalanobis distance
Then, well, the Mahalanobis distance is distributed like
a chi2-distribution with k = m degrees of freedom (assuming the
eigenvectors are of the covariance matrix are all independent)
So this covariance is also written as the
SurvivalFunction(χ^2(k=m),x=n**2) where n = mahalanobis distance
this would be written stats.chi2(m).cdf(n**2), but this is half
the speed of using special.gammainc
@astrojthe3
"""
if return_interval:
p = special.gammainc(dim/2,n**2 /2)/2
return (1 - p)/2, (1 + p)/2
return special.gammainc(dim/2,n**2 /2)
def sort_bool(g, srt):
" get only the elements of sort that are true in the original array order"
return srt[g[srt]]
def scale_ptp(arr):
g = np.isfinite(arr)
if g.any():
return (arr - np.nanmin(arr[g]))/np.ptp(arr[g])
else:
return arr
def wcsaxis(header, N=6, ax=None, fmt="%0.2f", use_axes=False,label=True):
oldax = plt.gca()
if ax is None:
ax = plt.gca()
plt.sca(ax)
xlim = ax.axes.get_xlim()
ylim = ax.axes.get_ylim()
if isinstance(header,WCS):
wcs = header
else:
wcs = WCS(header)
# naxis = header["NAXIS"] # naxis
naxis = wcs.wcs.naxis
# naxis1 = header["NAXIS1"] # naxis1
# naxis2 = header["NAXIS2"] # naxis2
# crpix1 = hdr['CRPIX1']
# crpix2 = hdr['CRPIX2']
# crval1 = hdr['CRVAL1']
# crval2 = hdr['CRVAL2']
# try:
# cdelt1 = wcs['CDELT1']
# cdelt2 = wcs['CDELT2']
# except BaseException:
# cdelt1 = wcs['CD1_1']
# cdelt2 = wcs['CD2_2']
if not use_axes:
xoffset = ((xlim[1] - xlim[0]) / N) / 5
x = np.linspace(xlim[0] + xoffset, xlim[1] - xoffset, N)
if naxis >= 2:
yoffset = ((ylim[1] - ylim[0]) / N) / 5
y = np.linspace(ylim[0] + yoffset, ylim[1] - yoffset, N)
else:
x = ax.get_xticks()
if naxis >= 2:
y = ax.get_yticks()
if naxis == 1:
x_tick = wcs.all_pix2world(x, 0)
elif naxis == 2:
coord = list(zip(x, y))
x_tick, y_tick = wcs.all_pix2world(coord, 0).T
elif naxis > 2:
c = [x, y]
for i in range(naxis - 2):
c.append([0] * N)
coord = list(zip(*c))
ticks = wcs.all_pix2world(coord, 0)
x_tick, y_tick = np.asarray(ticks)[:, :2].T
plt.xticks(x, [fmt % i for i in x_tick],rotation=45)
plt.yticks(y, [fmt % i for i in y_tick])
if label:
if wcs.wcs.ctype[0][0].lower() == "g":
ax.set_xlabel("Galactic Longitude (l)")
ax.set_ylabel("Galactic Latitude (b)")
else:
ax.set_xlabel("Right Ascension (J2000)")
ax.set_ylabel("Declination (J2000)")
ax.axes.set_xlim(xlim[0], xlim[1])
ax.axes.set_ylim(ylim[0], ylim[1])
plt.sca(oldax)
return ax
# In[ writefits]
def writefits(filename, data, header=None, wcs=None, clobber=True):
if header is None:
if wcs is not None:
header = wcs
hdu = fits.PrimaryHDU(data, header=header)
hdu.writeto(filename, overwrite=clobber)
return hdu
def grid_data(
x,
y,
z,
nxy=(512, 512),
interp="linear",
):
"""
stick x,y,z data on a grid and return
XX, YY, ZZ
"""
xmin, xmax = x.min(), x.max()
ymin, ymax = y.min(), y.max()
nx, ny = nxy
xi = np.linspace(xmin, xmax, nx)
yi = np.linspace(ymin, ymax, ny)
xi, yi = np.meshgrid(xi, yi)
zi = interpolate.griddata((x, y), z, (xi, yi), method=interp)
return xi, yi, zi
##########################################
##########################################
# A general utility to convert fluxes
# and magnitudes.
def convert_flux(mag=None, emag=None, filt=None, return_wavelength=False):
""""Return flux for a given magnitude/filter combo
Input:
mag -- the input magnitude. either a number or numpy array
filter -- either filter zeropoint or filer name
"""
if mag is None or filt is None:
print("List of filters and filter properties")
__filtertable__.pprint(max_lines=len(__filtertable__) + 3)
return None
if not isinstance(filt, float):
tab = __filtertable__
tab["fname"] = [s.lower() for s in tab["fname"]]
if not filt.lower() in tab["fname"]:
print("Filter %s not found" % filt.lower())
print("Please select one of the following")
print(tab["fname"].data)
filt = eval(input("Include quotes in answer (example ('johnsonK')): "))
f0 = tab["F0_Jy"][np.where(filt.lower() == tab["fname"])][0]
else:
f0 = filt
flux = f0 * 10.0 ** (-mag / 2.5)
if emag is not None:
eflux = 1.08574 * emag * flux
if return_wavelength:
return (
flux,
eflux,
tab["Wavelength"][np.where(filt.lower() == tab["fname"])],
)
else:
return flux, eflux
else:
if return_wavelength:
return flux, tab["Wavelength"][np.where(filt.lower() == tab["fname"])][0]
else:
return flux
# ================================================================== #
#
# Function copied from schmidt_funcs to make them generally available
#
def rot_matrix(theta):
"""
rot_matrix(theta)
2D rotation matrix for theta in radians
returns numpy matrix
"""
c, s = np.cos(theta), np.sin(theta)
return np.matrix([[c, -s], [s, c]])
def rectangle(c, w, h, angle=0, center=True):
"""
create rotated rectangle
for input into PIL ImageDraw.polygon
to make a rectangle polygon mask
Rectagle is created and rotated with center
at zero, and then translated to center position
accepts centers
Default : center
options for center: tl, tr, bl, br
"""
cx, cy = c
# define initial polygon irrespective of center
x = -w / 2.0, +w / 2.0, +w / 2.0, -w / 2.0
y = +h / 2.0, +h / 2.0, -h / 2.0, -h / 2.0
# correct the center if starting from corner
if center is not True:
if center[0] == "b":
# y = tuple([i + h/2. for i in y])
cy = cy + h / 2.0
else:
# y = tuple([i - h/2. for i in y])
cy = cy - h / 2.0
if center[1] == "l":
# x = tuple([i + w/2 for i in x])
cx = cx + w / 2.0
else:
# x = tuple([i - w/2 for i in x])
cx = cx - w / 2.0
R = rot_matrix(angle * np.pi / 180.0)
c = []
for i in range(4):
xr, yr = np.dot(R, np.asarray([x[i], y[i]])).A.ravel()
# coord switch to match ordering of FITs dimensions
c.append((cx + xr, cy + yr))
# print (cx,cy)
return c
def rot_mask(img, pivot=None, angle=0):
### https://stackoverflow.com/a/25459080/11594175
if pivot is None:
pivot = list(map(int, nd.center_of_mass(img)))[::-1]
img = img * 1
padX = [img.shape[1] - (pivot[0]), pivot[0]]
padY = [img.shape[0] - pivot[1], pivot[1]]
imgP = np.pad(img, [padY, padX], "constant")
imgR = nd.rotate(imgP, angle, reshape=False)
imgC = imgR[padY[0] : -padY[1], padX[0] : -padX[1]]
return imgC
def rectangle2(c, w, h, angle=0, center=True):
"""
create rotated rectangle
for input into PIL ImageDraw.polygon
to make a rectangle polygon mask
Rectagle is created and rotated with center
at zero, and then translated to center position
accepts centers
Default : center
options for center: tl, tr, bl, br
"""
cx, cy = c
# define initial polygon irrespective of center
x = -w / 2.0, +w / 2.0, +w / 2.0, -w / 2.0
y = +h / 2.0, +h / 2.0, -h / 2.0, -h / 2.0
# correct center if starting from corner
if center is not True:
if center[0] == "b":
# y = tuple([i + h/2. for i in y])
cy = cy + h / 2.0
else:
# y = tuple([i - h/2. for i in y])
cy = cy - h / 2.0
if center[1] == "l":
# x = tuple([i + w/2 for i in x])
cx = cx + w / 2.0
else:
# x = tuple([i - w/2 for i in x])
cx = cx - w / 2.0
R = rot_matrix(angle * np.pi / 180.0)
c = []
for i in range(4):
xr, yr = np.dot(R, np.asarray([x[i], y[i]])).A.ravel()
# coord switch to match ordering of FITs dimensions
c.append((cx + xr, cy + yr))
# print (cx,cy)
return np.array([c[0], c[1], c[2], c[3], c[0]]).T
def plot_rectangle(c, w, h, angle=0, center=True, ax=None, n=10, m="-", **plot_kwargs):
if False: # center is True:
print("Hey, did you know this is built into matplotlib")
print(
"Yeah, just do ax.add_patch(plt.Rectangle(xy=(cx,cy),height=h, width=w, angle=deg))"
)
print(
"of course this one will work even if grid is not rectilinear and can use points"
)
print("defined w.r.t. a corner")
if ax is None:
ax = plt.gca()
x, y = rectangle2(c, w, h, angle=angle, center=center)
ax.plot(x, y, **plot_kwargs)
n = n * 1j
# interpolate each linear segment
leg1 = np.r_[x[0] : x[1] : n], np.r_[y[0] : y[1] : n]
leg2 = np.r_[x[1] : x[2] : n], np.r_[y[1] : y[2] : n]
leg3 = np.r_[x[2] : x[3] : n], np.r_[y[2] : y[3] : n]
leg4 = np.r_[x[3] : x[4] : n], np.r_[y[3] : y[4] : n]
ax.plot(*leg1, m, *leg2, m, *leg3, m, *leg4, m, **plot_kwargs)
return ax
def rolling_window(arr, window):
"""[summary]
Arguments:
arr {[numpy.ndarray]} -- N-d numpy array
window {[int]} -- length of window
Returns:
out -- array s.t. np.mean(arr,axis=-1) gives the running mean along rows (or -1 axis of a)
out.shape = arr.shape[:-1] + (arr.shape[-1] - window + 1, window)
"""
shape = arr.shape[:-1] + (
arr.shape[-1] - window + 1,
window,
) # the new shape (a.shape)
strides = arr.strides + (arr.strides[-1],)
return np.lib.stride_tricks.as_strided(arr, shape=shape, strides=strides)
def embiggenA(arr, zoom):
"""
Faster when zoom is large
i.e.; zoom**2 > arr.shape[0]*arr.shape[1]/zoom
embiggenB is the preferred function for large arrays
"""
shape = arr.shape
arr2 = np.zeros((shape[0]*zoom,shape[1]*zoom))
for i in range(arr.shape[0]):
for j in range(arr.shape[1]):
istart = i * zoom
iend = istart + zoom
jstart = j * zoom
jend = jstart + zoom
arr2[istart:iend,jstart:jend] = arr[i,j]
return arr2
def embiggenB(arr, zoom):
"""
Faster when zoom is small
i.e.; zoom**2 < arr.shape[0]*arr.shape[1]/zoom
This is normally the faster one, we are usually
aren't zoom by more than a few
"""
shape = arr.shape
arr2 = np.zeros((shape[0]*zoom,shape[1]*zoom),dtype=float)
for i in range(zoom):
for j in range(zoom):
arr2[i::zoom,j::zoom] = arr
return arr2
def embiggen(arr,zoom):
if zoom**2 > (arr.shape[0]* arr.shape[1])/zoom:
return embiggenA(arr,zoom)
else:
return embiggenB(arr,zoom)
def minmax(arr, axis=None):
return np.nanmin(arr, axis=axis), np.nanmax(arr, axis=axis)
def comp(arr):
"""
returns the compressed version
of the input array if it is a
numpy MaskedArray
"""
try:
return arr.compressed()
except BaseException:
return arr
def mavg(arr, n=2, axis=-1):
"""
returns the moving average of an array.
returned array is shorter by (n-1)
applied along last axis by default
"""
return np.mean(rolling_window(arr, n), axis=axis)
def weighted_generic_moment(x, k, w=None):
x = np.asarray(x, dtype=np.float64)
if w is not None:
w = np.asarray(w, dtype=np.float64)
else:
w = np.ones_like(x)
return np.sum(x ** k * w) / np.sum(w)
def weighted_mean(x, w=1.):
return np.sum(x * w) / np.sum(w)
def weighted_std(x, w):
x = np.asarray(x, dtype=np.float64)
w = np.asarray(w, dtype=np.float64)
SS = np.sum(w * (x - weighted_mean(x, w)) ** 2) / np.sum(w)
# quantile(x, w, 0.5)
return np.sqrt(SS)