-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathhatlc.py
More file actions
executable file
·1933 lines (1503 loc) · 59.8 KB
/
hatlc.py
File metadata and controls
executable file
·1933 lines (1503 loc) · 59.8 KB
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# hatlc.py - Waqas Bhatti (wbhatti@astro.princeton.edu) - Jan 2016
# License: MIT - see LICENSE for the full text.
'''This contains functions to read HAT sqlite ("sqlitecurves") and CSV light curves
generated by the new HAT data server.
The most useful functions in this module are::
read_csvlc(lcfile):
This reads a CSV light curve produced by the HAT data server into an
lcdict.
lcfile is the HAT gzipped CSV LC (with a .hatlc.csv.gz extension)
And::
read_and_filter_sqlitecurve(lcfile, columns=None, sqlfilters=None,
raiseonfail=False, forcerecompress=False):
This reads a sqlitecurve file and optionally filters it, returns an
lcdict.
Returns columns requested in columns. If None, then returns all columns
present in the latest columnlist in the lightcurve. See COLUMNDEFS for
the full list of HAT LC columns.
If sqlfilters is not None, it must be a list of text SQL filters that
apply to the columns in the lightcurve.
This returns an lcdict with an added 'lcfiltersql' key that indicates
what the parsed SQL filter string was.
If forcerecompress = True, will recompress the un-gzipped sqlitecurve
even if the gzipped form exists on disk already.
Finally::
describe(lcdict):
This describes the metadata of the light curve.
Command line usage
------------------
You can call this module directly from the command line:
If you just have this file alone::
$ chmod +x hatlc.py
$ ./hatlc.py --help
If astrobase is installed with pip, etc., this will be on your path already::
$ hatlc --help
These should give you the following::
usage: hatlc.py [-h] [--describe] hatlcfile
read a HAT LC of any format and output to stdout
positional arguments:
hatlcfile path to the light curve you want to read and pipe to stdout
optional arguments:
-h, --help show this help message and exit
--describe don't dump the columns, show only object info and LC metadata
Either one will dump any HAT LC recognized to stdout (or just dump the
description if requested).
Other useful functions
----------------------
Two other functions that might be useful::
normalize_lcdict(lcdict, timecol='rjd', magcols='all', mingap=4.0,
normto='sdssr', debugmode=False):
This normalizes magnitude columns (specified in the magcols keyword
argument) in an lcdict obtained from reading a HAT light curve. This
normalization is done by finding 'timegroups' in each magnitude column,
assuming that these belong to different 'eras' separated by a specified
gap in the mingap keyword argument, and thus may be offset vertically
from one another. Measurements within a timegroup are normalized to zero
using the meidan magnitude of the timegroup. Once all timegroups have
been processed this way, the whole time series is then re-normalized to
the specified value in the normto keyword argument.
And::
normalize_lcdict_byinst(lcdict, magcols='all', normto='sdssr',
normkeylist=('stf','ccd','flt','fld','prj','exp'),
debugmode=False)
This normalizes magnitude columns (specified in the magcols keyword
argument) in an lcdict obtained from reading a HAT light curve. This
normalization is done by generating a normalization key using columns in
the lcdict that specify various instrument properties. The default
normalization key (specified in the normkeylist kwarg) is a combination
of:
- HAT station IDs ('stf')
- camera position ID ('ccd'; useful for HATSouth observations)
- camera filters ('flt')
- observed HAT field names ('fld')
- HAT project IDs ('prj')
- camera exposure times ('exp')
with the assumption that measurements with identical normalization keys
belong to a single 'era'. Measurements within an era are normalized to
zero using the median magnitude of the era. Once all eras have been
processed this way, the whole time series is then re-normalized to the
specified value in the normto keyword argument.
There's an IPython notebook describing the use of this module and accompanying
modules from the astrobase package at:
https://github.com/waqasbhatti/astrobase-notebooks/blob/master/lightcurve-work.ipynb
'''
# put this in here because hatlc can be used as a standalone module
__version__ = '0.5.3'
#############
## LOGGING ##
#############
# the basic logging styles common to all astrobase modules
log_sub = '{'
log_fmt = '[{levelname:1.1} {asctime} {module}:{lineno}] {message}'
log_date_fmt = '%y%m%d %H:%M:%S'
import logging
DEBUG = False
if DEBUG:
level = logging.DEBUG
else:
level = logging.INFO
LOGGER = logging.getLogger(__name__)
logging.basicConfig(
level=level,
style=log_sub,
format=log_fmt,
datefmt=log_date_fmt,
)
LOGDEBUG = LOGGER.debug
LOGINFO = LOGGER.info
LOGWARNING = LOGGER.warning
LOGERROR = LOGGER.error
LOGEXCEPTION = LOGGER.exception
####################
## SYSTEM IMPORTS ##
####################
import os.path
import os
import gzip
import shutil
import re
import sqlite3 as sql
import json
from pprint import pformat
import sys
import textwrap
import numpy as np
from numpy import nan
#################
## DEFINITIONS ##
#################
# LC column definitions
# the first elem is the column description, the second is the format to use when
# writing a CSV LC column, the third is the type to use when parsing a CSV LC
# column
COLUMNDEFS = {
# TIME
'rjd':('time of observation in Reduced Julian date (JD = 2400000.0 + RJD)',
'%.7f',
float),
'bjd':(('time of observation in Baryocentric Julian date '
'(note: this is BJD_TDB)'),
'%.7f',
float),
# FRAME METADATA
'net':('network of telescopes observing this target',
'%s',
str),
'stf':('station ID of the telescope observing this target',
'%i',
int),
'cfn':('camera frame serial number',
'%i',
int),
'cfs':('camera subframe id',
'%s',
str),
'ccd':('camera CCD position number',
'%i',
int),
'prj':('project ID of this observation',
'%s',
str),
'fld':('observed field name',
'%s',
str),
'frt':('image frame type (flat, object, etc.)',
'%s',
str),
# FILTER CONFIG
'flt':('filter ID from the filters table',
'%i',
int),
'flv':('filter version used',
'%i',
int),
# CAMERA CONFIG
'cid':('camera ID ',
'%i',
int),
'cvn':('camera version',
'%i',
int),
'cbv':('camera bias-frame version',
'%i',
int),
'cdv':('camera dark-frame version',
'%i',
int),
'cfv':('camera flat-frame version',
'%i',
int),
'exp':('exposure time for this observation in seconds',
'%.3f',
float),
# TELESCOPE CONFIG
'tid':('telescope ID',
'%i',
int),
'tvn':('telescope version',
'%i',
int),
'tfs':('telescope focus setting',
'%i',
int),
'ttt':('telescope tube temperature [deg]',
'%.3f',
float),
'tms':('telescope mount state (tracking, drizzling, etc.)',
'%s',
str),
'tmi':('telescope mount ID',
'%i',
int),
'tmv':('telescope mount version',
'%i',
int),
'tgs':('telescope guider status (MGen)',
'%s',
str),
# ENVIRONMENT
'mph':('moon phase at this observation',
'%.2f',
float),
'iha':('hour angle of object at this observation',
'%.3f',
float),
'izd':('zenith distance of object at this observation',
'%.3f',
float),
# APERTURE PHOTOMETRY METADATA
'xcc':('x coordinate on CCD chip',
'%.3f',
float),
'ycc':('y coordinate on CCD chip',
'%.3f',
float),
'bgv':('sky background measurement around object in ADU',
'%.3f',
float),
'bge':('error in sky background measurement in ADU',
'%.3f',
float),
'fsv':('source extraction S parameter [1/(the PSF spatial RMS)^2]',
'%.5f',
float),
'fdv':('source extraction D parameter (the PSF ellipticity in xy)',
'%.5f',
float),
'fkv':('source extraction K parameter (the PSF diagonal ellipticity)',
'%.5f',
float),
# APERTURE PHOTOMETRY COLUMNS (NOTE: these are per aperture)
'aim':('aperture photometry raw instrumental magnitude in aperture %s',
'%.5f',
float),
'aie':('aperture photometry raw instrumental mag error in aperture %s',
'%.5f',
float),
'aiq':('aperture photometry raw instrumental mag quality flag, aperture %s',
'%s',
str),
'arm':('aperture photometry fit magnitude in aperture %s',
'%.5f',
float),
'aep':('aperture photometry EPD magnitude in aperture %s',
'%.5f',
float),
'atf':('aperture photometry TFA magnitude in aperture %s',
'%.5f',
float),
# PSF FIT PHOTOMETRY METADATA
'psv':('PSF fit S parameter (the PSF spatial RMS)',
'%.5f',
float),
'pdv':('PSF fit D parameter (the PSF spatial ellipticity in xy)',
'%.5f',
float),
'pkv':('PSF fit K parameter (the PSF spatial diagonal ellipticity)',
'%.5f',
float),
'ppx':('PSF fit number of pixels used for fit',
'%i',
int),
'psn':('PSF fit signal-to-noise ratio',
'%.3f',
float),
'pch':('PSF fit chi-squared value',
'%.5f',
float),
# PSF FIT PHOTOMETRY COLUMNS
'psim':('PSF fit instrumental raw magnitude',
'%.5f',
float),
'psie':('PSF fit instrumental raw magnitude error',
'%.5f',
float),
'psiq':('PSF fit instrumental raw magnitude quality flag',
'%s',
str),
'psrm':('PSF fit final magnitude after mag-fit',
'%.5f',
float),
'psrr':('PSF fit residual',
'%.5f',
float),
'psrn':('PSF fit number of sources used',
'%i',
int),
'psep':('PSF fit EPD magnitude',
'%.5f',
float),
'pstf':('PSF fit TFA magnitude',
'%.5f',
float),
# IMAGE SUBTRACTION PHOTOMETRY METADATA
'xic':('x coordinate on CCD chip after image-subtraction frame warp',
'%.3f',
float),
'yic':('y coordinate on CCD chip after image-subtraction frame warp',
'%.3f',
float),
# IMAGE SUBTRACTION PHOTOMETRY COLUMNS
'irm':('image subtraction fit magnitude in aperture %s',
'%.5f',
float),
'ire':('image subtraction fit magnitude error in aperture %s',
'%.5f',
float),
'irq':('image subtraction fit magnitude quality flag for aperture %s',
'%s',
str),
'iep':('image subtraction EPD magnitude in aperture %s',
'%.5f',
float),
'itf':('image subtraction TFA magnitude in aperture %s',
'%.5f',
float),
}
LC_MAG_COLUMNS = ('aim','arm','aep','atf',
'psim','psrm','psep','pstf',
'irm','iep','itf')
LC_ERR_COLUMNS = ('aie','psie','ire')
LC_FLAG_COLUMNS = ('aiq','psiq','irq')
# used to validate the filter string
# http://www.sqlite.org/lang_keywords.html
SQLITE_ALLOWED_WORDS = ['and','between','in',
'is','isnull','like','not',
'notnull','null','or',
'=','<','>','<=','>=','!=','%']
#######################
## UTILITY FUNCTIONS ##
#######################
# this is from Tornado's source (MIT License):
# http://www.tornadoweb.org/en/stable/_modules/tornado/escape.html#squeeze
def _squeeze(value):
"""Replace all sequences of whitespace chars with a single space."""
return re.sub(r"[\x00-\x20]+", " ", value).strip()
########################################
## SQLITECURVE COMPRESSIION FUNCTIONS ##
########################################
def _pycompress_sqlitecurve(sqlitecurve, force=False):
'''This just compresses the sqlitecurve. Should be independent of OS.
'''
outfile = '%s.gz' % sqlitecurve
try:
if os.path.exists(outfile) and not force:
os.remove(sqlitecurve)
return outfile
else:
with open(sqlitecurve,'rb') as infd:
with gzip.open(outfile,'wb') as outfd:
shutil.copyfileobj(infd, outfd)
if os.path.exists(outfile):
os.remove(sqlitecurve)
return outfile
except Exception:
return None
def _pyuncompress_sqlitecurve(sqlitecurve, force=False):
'''This just uncompresses the sqlitecurve. Should be independent of OS.
'''
outfile = sqlitecurve.replace('.gz','')
try:
if os.path.exists(outfile) and not force:
return outfile
else:
with gzip.open(sqlitecurve,'rb') as infd:
with open(outfile,'wb') as outfd:
shutil.copyfileobj(infd, outfd)
# do not remove the intput file yet
if os.path.exists(outfile):
return outfile
except Exception:
return None
_compress_sqlitecurve = _pycompress_sqlitecurve
_uncompress_sqlitecurve = _pyuncompress_sqlitecurve
GZIPTEST = None
###################################
## READING SQLITECURVE FUNCTIONS ##
###################################
def _validate_sqlitecurve_filters(filterstring, lccolumns):
'''This validates the sqlitecurve filter string.
This MUST be valid SQL but not contain any commands.
'''
# first, lowercase, then _squeeze to single spaces
stringelems = _squeeze(filterstring).lower()
# replace shady characters
stringelems = filterstring.replace('(','')
stringelems = stringelems.replace(')','')
stringelems = stringelems.replace(',','')
stringelems = stringelems.replace("'",'"')
stringelems = stringelems.replace('\n',' ')
stringelems = stringelems.replace('\t',' ')
stringelems = _squeeze(stringelems)
# split into words
stringelems = stringelems.split(' ')
stringelems = [x.strip() for x in stringelems]
# get rid of all numbers
stringwords = []
for x in stringelems:
try:
float(x)
except ValueError:
stringwords.append(x)
# get rid of everything within quotes
stringwords2 = []
for x in stringwords:
if not(x.startswith('"') and x.endswith('"')):
stringwords2.append(x)
stringwords2 = [x for x in stringwords2 if len(x) > 0]
# check the filterstring words against the allowed words
wordset = set(stringwords2)
# generate the allowed word set for these LC columns
allowedwords = SQLITE_ALLOWED_WORDS + lccolumns
checkset = set(allowedwords)
validatecheck = list(wordset - checkset)
# if there are words left over, then this filter string is suspicious
if len(validatecheck) > 0:
# check if validatecheck contains an elem with % in it
LOGWARNING("provided SQL filter string '%s' "
"contains non-allowed keywords" % filterstring)
return None
else:
return filterstring
def read_and_filter_sqlitecurve(lcfile,
columns=None,
sqlfilters=None,
raiseonfail=False,
returnarrays=True,
forcerecompress=False,
quiet=True):
'''This reads a HAT sqlitecurve and optionally filters it.
Parameters
----------
lcfile : str
The path to the HAT sqlitecurve file.
columns : list
A list of columns to extract from the ligh curve file. If None, then
returns all columns present in the latest `columnlist` in the light
curve.
sqlfilters : list of str
If no None, it must be a list of text SQL filters that apply to the
columns in the lightcurve.
raiseonfail : bool
If this is True, an Exception when reading the LC will crash the
function instead of failing silently and returning None as the result.
returnarrays : bool
If this is True, the output lcdict contains columns as np.arrays instead
of lists. You generally want this to be True.
forcerecompress : bool
If True, the sqlitecurve will be recompressed even if a compressed
version of it is found. This usually happens when sqlitecurve opening is
interrupted by the OS for some reason, leaving behind a gzipped and
un-gzipped copy. By default, this function refuses to overwrite the
existing gzipped version so if the un-gzipped version is corrupt but
that one isn't, it can be safely recovered.
quiet : bool
If True, will not warn about any problems, even if the light curve
reading fails (the only clue then will be the return value of
None). Useful for batch processing of many many light curves.
Returns
-------
tuple : (lcdict, status_message)
A two-element tuple is returned, with the first element being the
lcdict.
'''
# we're proceeding with reading the LC...
try:
# if this file is a gzipped sqlite3 db, then gunzip it
if '.gz' in lcfile[-4:]:
lcf = _uncompress_sqlitecurve(lcfile)
else:
lcf = lcfile
db = sql.connect(lcf)
cur = db.cursor()
# get the objectinfo from the sqlitecurve
query = ("select * from objectinfo")
cur.execute(query)
objectinfo = cur.fetchone()
# get the lcinfo from the sqlitecurve
query = ("select * from lcinfo "
"order by version desc limit 1")
cur.execute(query)
lcinfo = cur.fetchone()
(lcversion, lcdatarelease, lccols, lcsortcol,
lcapertures, lcbestaperture,
objinfocols, objidcol,
lcunixtime, lcgitrev, lccomment) = lcinfo
# load the JSON dicts
lcapertures = json.loads(lcapertures)
lcbestaperture = json.loads(lcbestaperture)
objectinfokeys = objinfocols.split(',')
objectinfodict = {x:y for (x,y) in zip(objectinfokeys, objectinfo)}
objectid = objectinfodict[objidcol]
# need to generate the objectinfo dict and the objectid from the lcinfo
# columns
# get the filters from the sqlitecurve
query = ("select * from filters")
cur.execute(query)
filterinfo = cur.fetchall()
# validate the requested columns
if columns and all(x in lccols.split(',') for x in columns):
LOGINFO('retrieving columns %s' % columns)
proceed = True
elif columns is None:
columns = lccols.split(',')
proceed = True
else:
proceed = False
# bail out if there's a problem and tell the user what happened
if not proceed:
# recompress the lightcurve at the end
if '.gz' in lcfile[-4:] and lcf:
_compress_sqlitecurve(lcf, force=forcerecompress)
LOGERROR('requested columns are invalid!')
return None, "requested columns are invalid"
# create the lcdict with the object, lc, and filter info
lcdict = {'objectid':objectid,
'objectinfo':objectinfodict,
'objectinfokeys':objectinfokeys,
'lcversion':lcversion,
'datarelease':lcdatarelease,
'columns':columns,
'lcsortcol':lcsortcol,
'lcapertures':lcapertures,
'lcbestaperture':lcbestaperture,
'lastupdated':lcunixtime,
'lcserver':lcgitrev,
'comment':lccomment,
'filters':filterinfo}
# validate the SQL filters for this LC
if ((sqlfilters is not None) and isinstance(sqlfilters,str)):
# give the validator the sqlfilters string and a list of lccols in
# the lightcurve
validatedfilters = _validate_sqlitecurve_filters(sqlfilters,
lccols.split(','))
if validatedfilters is not None:
LOGINFO('filtering LC using: %s' % validatedfilters)
filtersok = True
else:
filtersok = False
else:
validatedfilters = None
filtersok = None
# now read all the required columns in the order indicated
# we use the validated SQL filter string here
if validatedfilters is not None:
query = (
"select {columns} from lightcurve where {sqlfilter} "
"order by {sortcol} asc"
).format(
columns=','.join(columns), # columns is always a list
sqlfilter=validatedfilters,
sortcol=lcsortcol
)
lcdict['lcfiltersql'] = validatedfilters
else:
query = ("select %s from lightcurve order by %s asc") % (
','.join(columns),
lcsortcol
)
cur.execute(query)
lightcurve = cur.fetchall()
if lightcurve and len(lightcurve) > 0:
lightcurve = list(zip(*lightcurve))
lcdict.update({x:y for (x,y) in zip(lcdict['columns'],
lightcurve)})
lcok = True
# update the ndet after filtering
lcdict['objectinfo']['ndet'] = len(lightcurve[0])
else:
LOGWARNING('LC for %s has no detections' % lcdict['objectid'])
# fill the lightcurve with empty lists to indicate that it is empty
lcdict.update({x:y for (x,y) in
zip(lcdict['columns'],
[[] for x in lcdict['columns']])})
lcok = False
# generate the returned lcdict and status message
if filtersok is True and lcok:
statusmsg = 'SQL filters OK, LC OK'
elif filtersok is None and lcok:
statusmsg = 'no SQL filters, LC OK'
elif filtersok is False and lcok:
statusmsg = 'SQL filters invalid, LC OK'
else:
statusmsg = 'LC retrieval failed'
returnval = (lcdict, statusmsg)
# recompress the lightcurve at the end
if '.gz' in lcfile[-4:] and lcf:
_compress_sqlitecurve(lcf, force=forcerecompress)
# return ndarrays if that's set
if returnarrays:
for column in lcdict['columns']:
lcdict[column] = np.array([x if x is not None else np.nan
for x in lcdict[column]])
except Exception:
if not quiet:
LOGEXCEPTION('could not open sqlitecurve %s' % lcfile)
returnval = (None, 'error while reading lightcurve file')
# recompress the lightcurve at the end
if '.gz' in lcfile[-4:] and lcf:
_compress_sqlitecurve(lcf, force=forcerecompress)
if raiseonfail:
raise
return returnval
############################
## DESCRIBING THE COLUMNS ##
############################
DESCTEMPLATE = '''\
OBJECT
------
objectid = {objectid}
hatid = {hatid}; twomassid = {twomassid}
network = {network}; stations = {stations}; ndet = {ndet}
ra = {ra}; decl = {decl}
pmra = {pmra}; pmra_err = {pmra_err}
pmdecl = {pmdecl}; pmdecl_err = {pmdecl_err}
jmag = {jmag}; hmag = {hmag}; kmag = {kmag}; bmag = {bmag}; vmag = {vmag}
sdssg = {sdssg}; sdssr = {sdssr}; sdssi = {sdssi}
METADATA
--------
datarelease = {datarelease}; lcversion = {lcversion}
lastupdated = {lastupdated:.3f}; lcserver = {lcserver}
comment = {comment}
lcbestaperture = {lcbestaperture}
lcsortcol = {lcsortcol}
lcfiltersql = {lcfiltersql}
lcnormcols = {lcnormcols}
CAMFILTERS
----------
{filterdefs}
PHOTAPERTURES
-------------
{aperturedefs}
LIGHT CURVE COLUMNS
-------------------
{columndefs}'''
LCC_CSVLC_DESCTEMPLATE = '''\
OBJECT ID: {objectid}
OBJECT AND LIGHT CURVE METADATA
-------------------------------
{metadata_desc}
{metadata}
LIGHT CURVE COLUMNS
-------------------
{columndefs}'''
def describe(lcdict, returndesc=False, offsetwith=None):
'''This describes the light curve object and columns present.
Parameters
----------
lcdict : dict
The input lcdict to parse for column and metadata info.
returndesc : bool
If True, returns the description string as an str instead of just
printing it to stdout.
offsetwith : str
This is a character to offset the output description lines by. This is
useful to add comment characters like '#' to the output description
lines.
Returns
-------
str or None
If returndesc is True, returns the description lines as a str, otherwise
returns nothing.
'''
# transparently read LCC CSV format description
if 'lcformat' in lcdict and 'lcc-csv' in lcdict['lcformat'].lower():
return describe_lcc_csv(lcdict, returndesc=returndesc)
# figure out the columndefs part of the header string
columndefs = []
for colind, column in enumerate(lcdict['columns']):
if '_' in column:
colkey, colap = column.split('_')
coldesc = COLUMNDEFS[colkey][0] % colap
else:
coldesc = COLUMNDEFS[column][0]
columndefstr = '%03i - %s - %s' % (colind,
column,
coldesc)
columndefs.append(columndefstr)
columndefs = '\n'.join(columndefs)
# figure out the filterdefs
filterdefs = []
for row in lcdict['filters']:
filterid, filtername, filterdesc = row
filterdefstr = '%s - %s - %s' % (filterid,
filtername,
filterdesc)
filterdefs.append(filterdefstr)
filterdefs = '\n'.join(filterdefs)
# figure out the apertures
aperturedefs = []
for key in sorted(lcdict['lcapertures'].keys()):
aperturedefstr = '%s - %.2f px' % (key, lcdict['lcapertures'][key])
aperturedefs.append(aperturedefstr)
aperturedefs = '\n'.join(aperturedefs)
# now fill in the description
description = DESCTEMPLATE.format(
objectid=lcdict['objectid'],
hatid=lcdict['objectinfo']['hatid'],
twomassid=lcdict['objectinfo']['twomassid'].strip(),
ra=lcdict['objectinfo']['ra'],
decl=lcdict['objectinfo']['decl'],
pmra=lcdict['objectinfo']['pmra'],
pmra_err=lcdict['objectinfo']['pmra_err'],
pmdecl=lcdict['objectinfo']['pmdecl'],
pmdecl_err=lcdict['objectinfo']['pmdecl_err'],
jmag=lcdict['objectinfo']['jmag'],
hmag=lcdict['objectinfo']['hmag'],
kmag=lcdict['objectinfo']['kmag'],
bmag=lcdict['objectinfo']['bmag'],
vmag=lcdict['objectinfo']['vmag'],
sdssg=lcdict['objectinfo']['sdssg'],
sdssr=lcdict['objectinfo']['sdssr'],
sdssi=lcdict['objectinfo']['sdssi'],
ndet=lcdict['objectinfo']['ndet'],
lcsortcol=lcdict['lcsortcol'],
lcbestaperture=json.dumps(lcdict['lcbestaperture'],ensure_ascii=True),
network=lcdict['objectinfo']['network'],
stations=lcdict['objectinfo']['stations'],
lastupdated=lcdict['lastupdated'],
datarelease=lcdict['datarelease'],
lcversion=lcdict['lcversion'],
lcserver=lcdict['lcserver'],
comment=lcdict['comment'],
lcfiltersql=(lcdict['lcfiltersql'] if 'lcfiltersql' in lcdict else ''),
lcnormcols=(lcdict['lcnormcols'] if 'lcnormcols' in lcdict else ''),
filterdefs=filterdefs,
columndefs=columndefs,
aperturedefs=aperturedefs
)
if offsetwith is not None:
description = textwrap.indent(
description,
'%s ' % offsetwith,
lambda line: True
)
print(description)
else:
print(description)
if returndesc:
return description
######################################
## READING CSV LIGHTCURVES HATLC V2 ##
######################################
def _smartcast(castee, caster, subval=None):
'''
This just tries to apply the caster function to castee.
Returns None on failure.
'''
try:
return caster(castee)
except Exception:
if caster is float or caster is int:
return nan
elif caster is str:
return ''
else:
return subval
# these are the keys used in the metadata section of the CSV LC
METAKEYS = {'objectid':str,
'hatid':str,
'twomassid':str,
'ucac4id':str,
'network':str,
'stations':str,
'ndet':int,
'ra':float,
'decl':float,
'pmra':float,
'pmra_err':float,
'pmdecl':float,
'pmdecl_err':float,
'jmag':float,
'hmag':float,
'kmag':float,
'bmag':float,
'vmag':float,
'sdssg':float,
'sdssr':float,