-
Notifications
You must be signed in to change notification settings - Fork 1
/
analysis.py
4685 lines (3614 loc) · 143 KB
/
analysis.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
""" My module for various data analysis tasks.
:REQUIREMENTS: :doc:`numpy`, :doc:`tools` (for :func:`errxy`)
2008-07-25 16:20 IJC: Created.
2009-12-08 11:31 IJC: Updated transit flag in planet objects and
:func:`rveph` function.
2010-02-18 14:06 IJC: Added :func:`medianfilter`
2010-08-03 15:38 IJC: Merged versions.
2010-10-28 11:53 IJMC: Updated documentation strings for Sphinx;
moved pylab import inside individual
function.
2011-04-13 14:29 IJMC: Added keyword functionality to :func:`fmin`
(taken from scipy.optimize).
2011-04-14 09:48 IJMC: Added a few fundamental constants.
2011-04-22 14:48 IJMC: Added :func:`trueanomaly` and
:func:`eccentricanomaly`.
2011-06-21 13:15 IJMC: Added :func:`get_t23` and :func:`get_t14` to
planet objects.
"""
import numpy as np
from numpy import ones, std, sum, mean, median, array, linalg, tile, concatenate, floor, Inf, arange, meshgrid, zeros, sin, cos, tan, arctan, sqrt, exp, nan, max
import pdb
from pylab import find
from scipy import optimize
import scipy.odr as odr
c = 299792458 # speed of light, m/s
h = 6.626068e-34 # SI units: Planck's constant
k = 1.3806503e-23 # SI units: Boltzmann constant, J/K
G = 6.67300e-11 # SI units: Gravitational constant
sigma = 5.670373e-8 # SI units: Stefan-Boltzmann constant
qe = 1.602176565e-19 # Electron charge, in Coulombs
me = 9.11e-31 # electron mass, in kg
ev = 1.602176565e-19 # electron Volt, in Joules
amu = 1.66053886e-27 # atomic mass unit, in kg
mh = 1.008 * amu # mass of hydrogen atom, in kg
pi = 3.14159265358979
AU = 149597870691.0 # AU in meters
day = 86400.0 # seconds in a Julian Day
rsun = 6.95508e8 # Solar mean radius, in m
msun = 1.9891e30 # solar mass in kg
rearth = 6.378136e6 # Earth's equatorial radius in m; [Allen's]
mearth = 5.9737e24 # in kg; [Allen's]
rjup = 7.1492e7 # Jupiter equatorial radius in m
mjup = 1898.7e24 # Jupiter mass in kg
pc = 3.08568025e16 # parsec in meters
class planet:
"""Very handy planet object.
Best initialized using :func:`getobj`.
:REQUIREMENTS: Database file `exoplanets.csv` from http://exoplanets.org/
"""
# 2010-03-07 22:21 IJC: Created
# 2011-01-22 17:15 IJMC: Updated format b/c CPS folks keep changing
# their database file format
# 2011-05-19 16:11 IJMC: Updated format b/c CPS folks keep
# changing their database file format -- but
# it's almost worth it to finally have
# stellar radii.
# 2014-11-21 15:31 IJMC: Simplified check on number of keys vs. args.
def __init__(self, *args):
keys = ['name','comp','ncomp','mult','discmeth','firstref','firsturl','date','jsname','etdname','per','uper','t0','ut0','ecc','uecc','ueccd','om','uom','k','uk','msini','umsini','a','ua','orbref','orburl','transit','t14','ut14','tt','utt','ar','uar','uard','i','ui','uid','b','ub','ubd','depth','udepth','udepthd','r','ur','density','udensity','gravity','ugravity','transitref','transiturl','trend','dvdt','udvdt','freeze_ecc','rms','chi2','nobs','star','hd','hr','hipp','sao','gl','othername','sptype','binary','v','bmv','j','h','ks','ra','dec','ra_string','dec_string','rstar', 'urstar', 'urstard', 'rstarref', 'rstarurl','mstar','umstar','umstard','teff','uteff','vsini','uvsini','fe','ufe','logg','ulogg','shk','rhk','par','upar','distance','udistance','lambd', 'ulambd', 'massref','massurl','specref','specurl','distref','disturl','simbadname','nstedid','binaryref', 'binaryurl']
if len(keys)>len(args):
print "Incorrect number of input arguments (%i, but should be %i)" % (len(args), len(keys))
return None
for key,arg in zip(keys, args):
try:
temp = float(arg)+1
isnumber = True
except:
isnumber = False
if isnumber:
exec('self.%s=%s' % (key,arg) )
else:
exec('self.%s="%s"' % (key,arg) )
return None
def get_t23(self, *args):
"""Compute full transit duration (in days) for a transiting planet.
Returns:
nan if required fields are missing.
Using Eq. 15 of J. Winn's chapter in S. Seager's book "Exoplanets."
:SEE ALSO:
:func:`get_t14`
"""
# 2011-06-21 12:53 IJMC: Created
# Get necessary parameters:
per, ra, k, b, inc, ecc, om = self.per, 1./self.ar, sqrt(self.depth), self.b, self.i, self.ecc, self.om
inc *= np.pi/180.
om *= np.pi/180.
ret = 0.
# Check that no parameters are empty:
if per=='' or k=='':
ret = nan
if b=='':
try:
b = (cos(inc)/ra) * (1. - ecc**2) / (1. + ecc * sin(om))
except:
ret = nan
elif ra=='':
try:
ra = (cos(inc)/b) * (1. - ecc**2) / (1. + ecc * sin(om))
except:
ret = nan
elif inc=='':
try:
inc = np.arccos((b * ra) / ((1. - ecc**2) / (1. + ecc * sin(om))))
except:
ret = nan
if np.isnan(ret):
print "Could not compute t_23. Parameters are:"
print "period>>", per
print "r_*/a>>", ra
print "r_p/r_*>>", k
print "impact parameter (b)>>", b
print "inclination>>", inc*180./np.pi, " deg"
print "eccentricity>>", ecc
print "omega>>", om*180./np.pi, " deg"
else:
ret = (per/np.pi) * np.arcsin(ra * np.sqrt((1. - k)**2 - b**2) / np.sin(inc))
return ret
def get_t14(self, *args):
"""Compute total transit duration (in days) for a transiting planet.
Returns:
nan if required fields are missing.
Using Eq. 14 of J. Winn's chapter in S. Seager's book "Exoplanets."
:SEE ALSO:
:func:`get_t23`
"""
# 2011-06-21 12:53 IJMC: Created
# Get necessary parameters:
per, ra, k, b, inc, ecc, om = self.per, 1./self.ar, sqrt(self.depth), self.b, self.i, self.ecc, self.om
inc *= np.pi/180.
om *= np.pi/180.
ret = 0.
# Check that no parameters are empty:
if per=='' or k=='':
ret = nan
if b=='':
try:
b = (cos(inc)/ra) * (1. - ecc**2) / (1. + ecc * sin(om))
except:
ret = nan
elif ra=='':
try:
ra = (cos(inc)/b) * (1. - ecc**2) / (1. + ecc * sin(om))
except:
ret = nan
elif inc=='':
try:
inc = np.arccos((b * ra) / ((1. - ecc**2) / (1. + ecc * sin(om))))
except:
ret = nan
if np.isnan(ret):
print "Could not compute t_14. Parameters are:"
print "period>>", per
print "r_*/a>>", ra
print "r_p/r_*>>", k
print "impact parameter (b)>>", b
print "inclination>>", inc*180./np.pi, " deg"
print "eccentricity>>", ecc
print "omega>>", om*180./np.pi, " deg"
else:
ret = (per/np.pi) * np.arcsin(ra * np.sqrt((1. + k)**2 - b**2) / np.sin(inc))
return ret
def get_scaleheight(self, ab=0.2, f=0.33, mu=2.3):
"""Compute atmospheric scale height (in m).
:INPUTS:
ab : scalar, 0 <= ab <= 1
Bond albedo.
f : scalar, 0.25 <= ab <= 2/3.
Recirculation efficiency. A value of 0.25 indicates full
redistribution of incident heat, while 2/3 indicates zero
redistribution.
mu : scalar
Mean atmospheric ('molecular') mass, in amu.
"""
# 2016-07-14 10:29 IJMC: Created
teq = self.get_teq(ab=ab, f=f)
try:
mass = mjup * self.msini / np.sin(self.i * np.pi/180.)
except:
mass = self.msini * mjup
g = G * mass / (self.r * rjup)**2
return k*teq / (mu*amu * g)
def get_teq(self, ab, f, reterr=False):
"""Compute equilibrium temperature.
:INPUTS:
ab : scalar, 0 <= ab <= 1
Bond albedo.
f : scalar, 0.25 <= ab <= 2/3.
Recirculation efficiency. A value of 0.25 indicates full
redistribution of incident heat, while 2/3 indicates zero
redistribution.
:EXAMPLE:
::
import analysis
planet = analysis.getobj('HD 189733 b')
planet.get_teq(0.0, 0.25) # zero albedo, full recirculation
:REFERENCE:
S. Seager, "Exoplanets," 2010. Eq. 3.9
"""
# 2012-09-07 16:24 IJMC: Created
return self.teff/np.sqrt(self.ar) * (f * (1. - ab))**0.25
def rv(self, **kw):
"""Compute radial velocity on a planet object for given Julian Date.
:EXAMPLE:
::
import analysis
p = analysis.getobj('HD 189733 b')
jd = 2400000.
print p.rv(jd)
refer to function `analysis.rv` for full documentation.
SEE ALSO: :func:`analysis.rv`, :func:`analysis.mjd`
"""
return rv(self, **kw)
def rveph(self, jd):
"""Compute the most recently elapsed RV emphemeris of a given
planet at a given JD. RV ephemeris is defined by the having
radial velocity equal to zero.
refer to :func:`analysis.rv` for full documentation.
SEE ALSO: :func:`analysis.getobj`, :func:`analysis.phase`
"""
return rveph(self, jd)
def phase(self, hjd):
"""Get phase of an orbiting planet.
refer to function `analysis.getorbitalphase` for full documentation.
SEE ALSO: :func:`analysis.getorbitalphase`, :func:`analysis.mjd`
"""
# 2009-09-28 14:07 IJC: Implemented object-oriented version
return getorbitalphase(self, hjd)
def writetext(self, filename, **kw):
"""See :func:`analysis.planettext`"""
return planettext(self, filename, **kw)
def loaddata(filelist, path='', band=1):
"""Load a set of reduced spectra into a single data file.
datalist = ['file1.fits', 'file2.fits']
datapath = '~/data/'
data = loaddata(datalist, path=datapath, band=1)
The input can also be the name of an IRAF-style file list.
"""
# 2008-07-25 16:26 IJC: Created
# 2010-01-20 12:58 IJC: Made function work for IRTF low-res data.
# Replaced 'warn' command with 'print'.
# 2011-04-08 11:42 IJC: Updated; moved inside analysis.py.
# 2011-04-12 09:57 IJC: Fixed misnamed imports
try:
from astropy.io import fits as pyfits
except:
import pyfits
data = array([])
if filelist.__class__==str or isinstance(filelist,np.string_):
filelist = ns.file2list(filelist)
elif filelist.__class__<>list:
print('Input to loaddata must be a python list or string')
return data
num = len(filelist)
# Load one file just to get the dimensions right.
irspec = pyfits.getdata(filelist[0])
ii = 0
for element in filelist:
irspec = pyfits.getdata(element)
if ii==0:
irsh = irspec.shape
data = zeros((num,)+irsh[1::], float)
if len(irsh)>2:
for jj in range(irsh[1]):
data[ii, jj, :] = irspec[band-1, jj, :]
else:
data[ii,:] = irspec[band-1,:]
ii=ii+1
return data
def getobj(*args, **kw):
"""Get data for a specified planet.
:INPUTS: (str) -- planet name, e.g. "HD 189733 b"
:OPTIONAL INPUTS:
datafile : str
datafile name
verbose : bool
verbosity flag
:EXAMPLE:
::
p = getobj('55cnce')
p.period ---> 2.81705
The attributes of the returned object are many and varied, and
can be listed using the 'dir' command on the returned object.
This looks up data from the local datafile, which could be out
of date.
SEE ALSO: :func:`rv`"""
# 2008-07-30 16:56 IJC: Created
# 2010-03-07 22:24 IJC: Updated w/new exoplanets.org data table!
# 2010-03-11 10:01 IJC: If planet name not found, return list of
# planet names. Restructured input format.
# 2010-11-01 13:30 IJC: Added "import os"
# 2011-05-19 15:56 IJC: Modified documentation.
import os
if kw.has_key('datafile'):
datafile=kw['datafile']
else:
datafile=os.path.expanduser('~/python/exoplanets.csv')
if kw.has_key('verbose'):
verbose = kw['verbose']
else:
verbose=False
if len(args)==0:
inp = 'noplanetname'
else:
inp = args[0]
if verbose: print "datafile>>" + datafile
f = open(datafile, 'r')
data = f.readlines()
f.close()
data = data[1::] # remove header line
names = array([line.split(',')[0] for line in data])
foundobj = (names==inp)
if (not foundobj.any()):
if verbose: print "could not find desired planet; returning names of known planets"
return names
else:
planetind = int(find(foundobj))
pinfo = data[planetind].strip().split(',')
myplanet = planet(*pinfo)
return myplanet
def getorbitalphase(planet, hjd, **kw):
"""Get phase of an orbiting planet.
INPUT:
planet -- a planet from getobj; e.g., getobj('55cnce')
hjd
OUTPUT:
orbital phase -- from 0 to 1.
NOTES:
If planet.transit==True, phase is based on the transit time ephemeris.
If planet.transit==False, phase is based on the RV ephemeris as
computed by function rveph
SEE ALSO: :func:`getobj`, :func:`mjd`, :func:`rveph`
"""
hjd = array(hjd).copy()
if bool(planet.transit)==True:
thiseph = planet.tt
else:
thiseph = planet.rveph(hjd.max())
orbphase = ((hjd - thiseph) ) / planet.per
orbphase -= int(orbphase.mean())
return orbphase
def mjd(date):
"""Convert Julian Date to Modified Julian Date, or vice versa.
if date>=2400000.5, add 2400000.5
if date<2400000.5, subtract 2400000.5
"""
# 2009-09-24 09:54 IJC: Created
date = array(date, dtype=float, copy=True, subok=True)
offset = 2400000.5
if (date<offset).all():
date += offset
elif (date>=offset).all():
date -= offset
else:
print "Input contains date both below and above %f" % offset
return date
def rveph(p, jd):
"""Compute the most recently elapsed RV emphemeris of a given
planet at a given JD. RV ephemeris is defined by the having
radial velocity equal to zero.
:EXAMPLE:
::
from analysis import getobj, rveph
jd = 2454693 # date: 2008/08/14
p = getobj('55cnce') # planet: 55 Cnc e
t = rveph(p, jd)
returns t ~
SEE ALSO: :func:`getobj`, :func:`phase`
"""
# 2009-12-08 11:20 IJC: Created. Ref: Beauge et al. 2008 in
# "Extrasolar Planets," R. Dvorak ed.
# 2010-03-12 09:34 IJC: Updated for new planet-style object.
from numpy import cos, arccos, arctan, sqrt, tan, pi, sin, int
if p.__class__<>planet:
raise Exception, "First input must be a 'planet' object."
omega = p.om*pi/180
tau = p.t0
ecc = p.ecc
per = p.per
f = arccos(-ecc * cos(omega)) - omega # true anomaly
u = 2.*arctan(sqrt((1-ecc)/(1+ecc))*tan(f/2.)) # eccentric anomaly
n = 2*pi/per
time0 = tau+ (u-ecc*sin(u))/n
norb = int((time0-jd)/per)
time = time0-norb*per
return time
def rv(p, jd=None, e=None, reteanom=False, tol=1e-8):
""" Compute unprojected astrocentric RV of a planet for a given JD in m/s.
:INPUTS:
p : planet object, or 5- or 6-sequence
planet object: see :func:`get_obj`
OR:
sequence: [period, t_peri, ecc, a, long_peri, gamma]
(if gamma is omitted, it is set to zero)
(long_peri should be in radians!)
jd : NumPy array
Dates of observation (in same time system as t_peri).
e : NumPy array
Eccentric Anomaly of observations (can be precomputed to
save time)
:EXAMPLE:
::
jd = 2454693 # date: 2008/08/14
p = getobj('55 Cnc e') # planet: 55 Cnc e
vp = rv(p, jd)
returns vp ~ 1.47e5 [m/s]
The result will need to be multiplied by the sine of the
inclination angle (i.e., "sin i"). Positive radial velocities
are directed _AWAY_ from the observer.
To compute the barycentric radial velocity of the host star,
scale the returned values by the mass ratio -m/(m+M).
SEE ALSO: :func:`getobj`, :func:`rvstar`
"""
# 2008-08-13 12:59 IJC: Created with help from Debra Fischer,
# Murray & Dermott, and Beauge et al. 2008 in "Extrasolar
# Planets," R. Dvorak ed.
# 2008-09-25 12:55 IJC: Updated documentation to be more clear.
# 2009-10-01 10:25 IJC: Moved "import" statement within func.
# 2010-03-12 09:13 IJC: Updated w/new planet-type objects
# 2012-10-15 17:20 IJMC: First input can now be a list of
# elements. Added option to pass in
# eccentric anomaly.
# 2016-10-21 10:49 IJMC: Now include gamma in calculation
jd = array(jd, copy=True, subok=True)
if jd.shape==():
singlevalueinput = True
jd = array([jd])
else:
singlevalueinput = False
if ((jd-2454692) > 5000).any():
raise Exception, "Implausible Julian Date entered."
if hasattr(p, '__iter__'):
if len(p)==5:
per, tau, ecc, a, omega = p
gamma = 0.
else:
per, tau, ecc, a, omega, gamma = p[0:6]
if ecc > 1: # Reset eccentricity directly
ecc = 1. - tol
p[2] = ecc
elif ecc < 0:
ecc = np.abs(ecc)
p[2] = ecc
else:
if p.__class__<>planet:
raise Exception, "First input must be a 'planet' object."
try:
per = p.per
tau = p.t0
ecc = p.ecc
a = p.a
omega = p.om * pi/180.0
gamma = 0.
except:
raise Exception, "Could not load all desired planet parameters."
if ecc < 0:
ecc = np.abs(ecc)
if ecc > 1:
ecc = 1. - tol
if e is None:
n = 2.*pi/per # mean motion
m = n*(jd - tau) # mean anomaly
e = []
for element in m: # compute eccentric anomaly
def kep(e): return element - e + ecc*sin(e)
e.append(optimize.brentq(kep, element-1, element+1, xtol=tol, disp=False))
#e.append(optimize.newton(kep, 0, tol=tol))
else:
pass
e = array(e, copy=False)
f = 2. * arctan( sqrt((1+ecc)/(1.-ecc)) * tan(e/2.) )
#r = a*(1-ecc*cos(e))
#x = r*cos(f)
#y = r*sin(f)
K = n * a / sqrt(1-ecc**2)
vz = -K * ( cos(f+omega) + ecc*cos(omega) )
vzms = vz * AU/day # convert to m/s
vzms += gamma
if singlevalueinput:
vzms = vzms[0]
if reteanom:
ret = vzms, e
else:
ret = vzms
return ret
def rvstar(p, jd=None, e=None, reteanom=False, tol=1e-8):
""" Compute radial velocity of a star which has an orbiting planet.
:INPUTS:
p : planet object, or 5- or 6-sequence
planet object: see :func:`get_obj`
OR:
sequence: [period, t_peri, ecc, K, long_peri, gamma]
(if gamma is omitted, it is set to zero)
jd : NumPy array
Dates of observation (in same time system as t_peri).
e : NumPy array
Eccentric Anomaly of observations (can be precomputed to
save time)
:EXAMPLE:
::
jd = 2454693 # date: 2008/08/14
p = getobj('55 Cnc e') # planet: 55 Cnc e
vp = rv(p, jd)
Positive radial velocities are directed _AWAY_ from the
observer.
:SEE_ALSO: :func:`rv`, :func:`getobj`
"""
# 2012-10-15 22:34 IJMC: Created from function 'rv'
jd = array(jd, copy=True, subok=True)
if jd.shape==():
singlevalueinput = True
jd = array([jd])
else:
singlevalueinput = False
if ((jd-2454692) > 5000).any():
raise Exception, "Implausible Julian Date entered."
if hasattr(p, '__iter__'):
if len(p)==5:
per, tau, ecc, k, omega = p
gamma = 0.
else:
per, tau, ecc, k, omega, gamma = p[0:6]
omega *= np.pi/180.
if ecc < 0:
ecc = np.abs(ecc)
p[2] = ecc
elif ecc > 1:
ecc = 1. - tol
p[2] = ecc
else:
if p.__class__<>planet:
raise Exception, "First input must be a 'planet' object."
try:
per = p.per
tau = p.t0
ecc = p.ecc
k = p.k
omega = p.om * pi/180.0
gamma = 0.
except:
raise Exception, "Could not load all desired planet parameters."
if ecc < 0:
ecc = np.abs(ecc)
if ecc > 1:
ecc = 1. - tol
if e is None:
n = 2.*pi/per # mean motion
m = n*(jd - tau) # mean anomaly
e = np.zeros(m.shape)
for ii,element in enumerate(m): # compute eccentric anomaly
def kep(e): return element - e + ecc*sin(e)
e[ii] = optimize.brentq(kep, element-1, element+1, xtol=tol, disp=False)
#e.append(optimize.newton(kep, 0, tol=tol))
else:
pass
# Compute true anomaly:
f = 2. * arctan( sqrt((1+ecc)/(1.-ecc)) * tan(e/2.) )
vrstar = k * (np.cos(f + omega) + ecc*np.cos(omega)) + gamma
if singlevalueinput:
vrstar = vrstar[0]
if reteanom:
ret = vrstar, e
else:
ret = vrstar
return ret
def dopspec(starspec, planetspec, starrv, planetrv, disp, starphase=[], planetphase=[], wlscale=True):
""" Generate combined time series spectra using planet and star
models, planet and star RV profiles.
D = dopspec(sspec, pspec, sRV, pRV, disp, sphase=[], pphase=[])
:INPUTS:
sspec, pspec: star, planet spectra; must be on a common
logarithmic wavelength grid
sRV, pRV: star, planet radial velocities in m/s
disp: constant logarithmic dispersion of the wavelength
grid: LAMBDA_i/LAMBDA_(i-1)
:OPTIONAL INPUTS:
sphase, pphase: normalized phase functions of star and planet.
The inputs sspec and pspec will be scaled
by these values for each observation.
wlscale: return relative wavelength scale for new data
NOTE: Input spectra must be linearly spaced in log wavelength and increasing:
that is, they must have [lambda_i / lambda_(i-1)] = disp =
constant > 1
Positive velocities are directed AWAY from the observer."""
#2008-08-19 16:30 IJC: Created
# Options: 1. chop off ends or not? 2. phase function.
# 4. Noise level 5. telluric? 6. hold star RV constant
# Initialize:
starspec = array(starspec ).ravel()
planetspec = array(planetspec).ravel()
starrv = array(starrv ).ravel()
planetrv = array(planetrv ).ravel()
ns = len(starspec)
nr = len(starrv)
starphase = array(starphase ).ravel()
planetphase = array(planetphase).ravel()
if len(starphase)==0:
starphase = ones(nr, float)
if len(planetphase)==0:
planetphase = ones(nr, float)
# Check inputs:
if ns<>len(planetspec):
raise Exception, "Star and planet spectra must be same length."
if nr<>len(planetrv):
raise Exception, "Star and planet RV profiles must be same length."
logdisp = log(disp)
# Calculate wavelength shift limits for each RV point
sshift = ( log(1.0+starrv /c) / logdisp ).round()
pshift = ( log(1.0+planetrv/c) / logdisp ).round()
limlo = int( concatenate((sshift, pshift)).min() )
limhi = int( concatenate((sshift, pshift)).max() )
ns2 = ns + (limhi - limlo)
data = zeros((nr, ns2), float)
# Iterate over RV values, constructing spectra
for ii in range(nr):
data[ii, (sshift[ii]-limlo):(ns+sshift[ii]-limlo)] = \
starphase[ii] * starspec
data[ii, (pshift[ii]-limlo):(ns+pshift[ii]-limlo)] = \
data[ii, (pshift[ii]-limlo):(ns+pshift[ii]-limlo)] + \
planetphase[ii] * planetspec
if wlscale:
data = (data, disp**(arange(ns2) + limlo))
return data
def loadatran(filename, wl=True, verbose=False):
""" Load ATRAN atmospheric transmission data file.
t = loadatran(filename, wl=True)
INPUT:
filename -- filename of the ATRAN file. This should be an
ASCII array where the second column is
wavelength and the third is the atmospheric
transmission.
(This can also be a list of filenames!)
:OPTIONAL INPUT:
wl -- if True (DEFAULT) also return the wavelength scale.
This can take up to twice as long for large files.
RETURNS:
if wl==True: returns a 2D array, with columns [lambda, transmission]
if wl==False: returns a 1D Numpy array of the transmission
NOTE: A list of these return values is created if
'filename' is actually an input list."""
# 2008-08-21 09:42 IJC: Created to save myself a bit of time
# 2008-08-25 10:08 IJC: Read in all lines at once; should go
# faster with sufficient memory
# 2008-09-09 13:56 IJC: Only convert the wavelength and flux
# columns(#1 & #2) -- speed up slightly.
if filename.__class__==list:
returnlist = []
for element in filename:
returnlist.append(loadatran(element, wl=wl))
return returnlist
f = open(filename, 'r')
dat = f.readlines()
f.close()
if verbose:
print dat[0]
print dat[0].split()
print dat[0].split()[1:3]
print dat[0].split()[2]
if wl:
data = array([map(float, line.split()[1:3]) for line in dat])
else:
data = array([float(line.split()[2]) for line in dat])
return data
def poly2cheby(cin):
"""Convert straight monomial coefficients to chebychev coefficients.
INPUT: poly coefficients (e.g., for use w/polyval)
OUTPUT: chebyt coefficients
SEE ALSO: :func:`gpolyval`; scipy.special.chebyt
"""
# 2009-07-07 09:41 IJC: Created
from scipy.special import poly1d, chebyt
cin = poly1d(cin)
cout = []
ord = cin.order
for ii in range(ord+1):
chebyii = chebyt(ord-ii)
cout.append(cin.coeffs[0]/chebyii.coeffs[0])
cin -= chebyii*cout[ii]
return cout
def cheby2poly(cin):
"""Convert chebychev coefficients to 'normal' polyval coefficients .
:INPUT: chebyt coefficients
:OUTPUT: poly coefficients (e.g., for use w/polyval)
:SEE ALSO: :func:`poly2cheby`, :func:`gpolyval`; scipy.special.chebyt
"""
# 2009-10-22 22:19 IJC: Created
from scipy.special import poly1d, chebyt
cin = poly1d(cin)
cout = poly1d(0)
ord = cin.order
for ii in range(ord+1):
cout += chebyt(ii)*cin[ii]
return cout
def gpolyval(c,x, mode='poly', retp=False):
"""Generic polynomial evaluator.
INPUT:
c (1D array) -- coefficients of polynomial to evaluate,
from highest-order to lowest.
x (1D array) -- pixel values at which to evaluate C
OPTINAL INPUTS:
MODE='poly' -- 'poly' uses standard monomial coefficients
as accepted by, e.g., polyval. Other
modes -- 'cheby' (1st kind) and 'legendre'
(P_n) -- convert input 'x' to a normalized
[-1,+1] domain
RETP=False -- Return coefficients as well as evaluated poly.
OUTPUT:
y -- array of shape X; evaluated polynomial.
(y, p) (if retp=True)
SEE ALSO: :func:`poly2cheby`
"""
# 2009-06-17 15:42 IJC: Created
# 2011-12-29 23:11 IJMC: Fixed normalization of the input 'x' array
# 2014-12-18 22:55 IJMC: poly1d has moved from scipy.special to NumPy
from scipy import special
from numpy import zeros, polyval, concatenate, poly1d
c = array(c).copy()
nc = len(c)
if mode=='poly':
totalcoef = c
ret = polyval(totalcoef, x)
elif mode=='cheby':
x = 2. * (x - 0.5*(x.max() + x.min())) / (x.max() - x.min())
totalcoef = poly1d([0])
for ii in range(nc):
totalcoef += c[ii]*special.chebyt(nc-ii-1)
ret = polyval(totalcoef, x)
elif mode=='legendre':
x = 2. * (x - 0.5*(x.max() + x.min())) / (x.max() - x.min())
totalcoef = poly1d([0])
for ii in range(nc):
totalcoef += c[ii]*special.legendre(nc-ii-1)
ret = polyval(totalcoef, x)
if retp:
return (ret, totalcoef)
else:
return ret
return -1
def stdr(x, nsigma=3, niter=Inf, finite=True, verbose=False, axis=None):
"""Return the standard deviation of an array after removing outliers.
:INPUTS:
x -- (array) data set to find std of
:OPTIONAL INPUT:
nsigma -- (float) number of standard deviations for clipping
niter -- number of iterations.
finite -- if True, remove all non-finite elements (e.g. Inf, NaN)
axis -- (int) axis along which to compute the mean.
:EXAMPLE:
::
from numpy import *
from analysis import stdr
x = concatenate((randn(200),[1000]))
print std(x), stdr(x, nsigma=3)
x = concatenate((x,[nan,inf]))
print std(x), stdr(x, nsigma=3)