1
- # python $SIMS_MAF_DIR/examples/pythonScripts/opsimMovie.py ops2_1088_sqlite .db --sqlConstraint 'night=130' --outDir Output
1
+ # python $SIMS_MAF_DIR/examples/pythonScripts/opsimMovie.py enigma_1189_sqlite .db --sqlConstraint 'night=130' --outDir Output
2
2
#
3
3
# --ips = number of images to stitch together per second of view (default is 10).
4
4
# --fps = frames per second for the output video .. default just matches ips. If specified as higher than ips,
22
22
import lsst .sims .maf .slicers as slicers
23
23
import lsst .sims .maf .metrics as metrics
24
24
import lsst .sims .maf .stackers as stackers
25
- import lsst .sims .maf .sliceMetrics as sliceMetrics
25
+ import lsst .sims .maf .metricBundles as metricBundles
26
+ import lsst .sims .maf .plots as plots
26
27
from lsst .sims .maf .utils import TelescopeInfo
27
28
28
29
import time
@@ -53,31 +54,29 @@ def getData(opsDb, sqlconstraint):
53
54
54
55
def setupMetrics (opsimName , metadata , plotlabel = '' , t0 = 0 , tStep = 40. / 24. / 60. / 60. , years = 0 ,
55
56
onlyFilterColors = False , verbose = False ):
56
- # Set up metrics. Will apply one to ms and one to ms_curr, but note that
57
- # because of the nature of this script, the metrics are applied to cumulative data (from all filters).
57
+ # Set up metrics and plotDicts (they will be bundled with the appropriate opsim slicers below).
58
58
t = time .time ()
59
59
nvisitsMax = 90 * (years + 1 )
60
60
colorMax = int (nvisitsMax / 4 )
61
61
metricList = []
62
+ plotDictList = []
62
63
if not onlyFilterColors :
63
- metricList .append (metrics .CountMetric ('expMJD' , metricName = 'Nvisits' ,
64
- plotDict = {'colorMin' :0 , 'colorMax' :nvisitsMax ,
65
- 'xlabel' :'Number of visits' ,
66
- 'title' : 'Cumulative visits (all bands)' }) )
64
+ metricList .append (metrics .CountMetric ('expMJD' , metricName = 'Nvisits' ))
65
+ plotDictList . append ( {'colorMin' :0 , 'colorMax' :nvisitsMax ,
66
+ 'xlabel' :'Number of visits' , 'title' : 'Cumulative visits (all bands) ' ,
67
+ 'label' : plotlabel , 'metricIsColor' : False } )
67
68
for f in (['u' , 'g' , 'r' , 'i' , 'z' , 'y' ]):
68
- metricList .append (metrics .CountSubsetMetric ('filter' , subset = f , metricName = 'Nvisits_' + f ,
69
- plotDict = {'colorMin' :0 , 'colorMax' :colorMax ,
70
- 'cbarFormat' : '%d' , 'xlabel' :'Number of Visits' ,
71
- 'title' :'%s band' % (f )}))
72
- # Apply plotlabel only to nvisits plots (will place it on FilterColors by hand).
73
- for m in metricList :
74
- m .plotDict ['label' ] = plotlabel
75
- metricList .append (metrics .FilterColorsMetric (t0 = t0 , tStep = tStep ,
76
- plotDict = {'title' :'Simulation %s: %s' % (opsimName , metadata )}))
69
+ metricList .append (metrics .CountSubsetMetric ('filter' , subset = f , metricName = 'Nvisits_' + f ))
70
+ plotDictList .append ({'colorMin' :0 , 'colorMax' :colorMax , 'cbarFormat' : '%d' ,
71
+ 'xlabel' :'Number of Visits' , 'title' :'%s band' % (f ),
72
+ 'label' :plotlabel , 'metricIsColor' :False })
73
+ metricList .append (metrics .FilterColorsMetric (t0 = t0 , tStep = tStep ))
74
+ plotDictList .append ({'title' :'Simulation %s: %s' % (opsimName , metadata ), 'bgcolor' :None ,
75
+ 'metricIsColor' :True })
77
76
dt , t = dtime (t )
78
77
if verbose :
79
78
print 'Set up metrics %f s' % (dt )
80
- return metricList
79
+ return metricList , plotDictList
81
80
82
81
def setupMovieSlicer (simdata , bins , verbose = False ):
83
82
t = time .time ()
@@ -88,15 +87,6 @@ def setupMovieSlicer(simdata, bins, verbose=False):
88
87
print 'Set up movie slicers in %f s' % (dt )
89
88
return movieslicer
90
89
91
- def setupOpsimFieldSlicer (verbose = False ):
92
- t = time .time ()
93
- ops = slicers .OpsimFieldSlicer (plotFuncs = 'plotSkyMap' )
94
- dt , t = dtime (t )
95
- if verbose :
96
- print 'Set up opsim field slicer in %s' % (dt )
97
- return ops
98
-
99
-
100
90
def addHorizon (horizon_altitude = np .radians (20. ), lat_telescope = TelescopeInfo ('LSST' ).lat , raCen = 0. ):
101
91
"""
102
92
Adds a horizon at horizon_altitude, using the telescope latitude lat_telescope.
@@ -124,7 +114,7 @@ def addHorizon(horizon_altitude=np.radians(20.), lat_telescope=TelescopeInfo('LS
124
114
lon = - (lon - np .pi ) % (np .pi * 2 ) - np .pi
125
115
return lon , lat
126
116
127
- def runSlices (opsimName , metadata , simdata , fields , bins , args , verbose = False ):
117
+ def runSlices (opsimName , metadata , simdata , fields , bins , args , opsDb , verbose = False ):
128
118
# Set up the movie slicer.
129
119
movieslicer = setupMovieSlicer (simdata , bins )
130
120
# Set up formatting for output suffix.
@@ -151,34 +141,49 @@ def runSlices(opsimName, metadata, simdata, fields, bins, args, verbose=False):
151
141
days = times_from_start - years * 365
152
142
plotlabel = 'Year %d Day %.4f' % (years , days )
153
143
# Set up metrics.
154
- metricList = setupMetrics (opsimName , metadata , plotlabel = plotlabel ,
144
+ metricList , plotDictList = setupMetrics (opsimName , metadata , plotlabel = plotlabel ,
155
145
t0 = ms ['slicePoint' ]['binRight' ], tStep = tstep , years = years , verbose = verbose )
156
146
# Identify the subset of simdata in the movieslicer 'data slice'
157
147
simdatasubset = simdata [ms ['idxs' ]]
158
148
# Set up opsim slicer on subset of simdata provided by movieslicer
159
- ops = setupOpsimFieldSlicer ()
160
- # Set up sliceMetric to handle healpix slicer + metrics calculation + plotting
161
- sm = sliceMetrics .RunSliceMetric (outDir = args .outDir , useResultsDb = False ,
162
- figformat = 'png' , dpi = 72 , thumbnail = False )
163
- sm .setMetricsSlicerStackers (metricList , ops )
164
- sm .runSlices (simdatasubset , simDataName = opsimName , fieldData = fields )
149
+ opslicer = slicers .OpsimFieldSlicer ()
150
+ # Set up metricBundles to combine metrics, plotdicts and slicer.
151
+ bundles = []
152
+ sqlconstraint = ''
153
+ for metric , plotDict in zip (metricList , plotDictList ):
154
+ bundles .append (metricBundles .MetricBundle (metric , opslicer , sqlconstraint = sqlconstraint ,
155
+ metadata = metadata , runName = opsimName ,
156
+ plotDict = plotDict ))
157
+ # Remove (default) stackers from bundles, because we've already run them above on the original data.
158
+ for mb in bundles :
159
+ mb .stackerList = []
160
+ bundledict = metricBundles .makeBundlesDictFromList (bundles )
161
+ # Set up metricBundleGroup to handle metrics calculation + plotting
162
+ bg = metricBundles .MetricBundleGroup (bundledict , opsDb , outDir = args .outDir , resultsDb = None , saveEarly = False )
163
+ # 'Hack' bundleGroup to just go ahead and run the metrics, without querying the database.
164
+ simData = simdatasubset
165
+ bg .fieldData = fields
166
+ bg .setCurrent (sqlconstraint )
167
+ bg .runCurrent (sqlconstraint = sqlconstraint , simData = simData )
165
168
# Plot data each metric, for this slice of the movie, adding slicenumber as a suffix for output plots.
166
169
# Plotting here, rather than automatically via sliceMetric method because we're going to rotate the sky,
167
170
# and add extra legend info and figure text (for FilterColors metric).
171
+ ph = plots .PlotHandler (outDir = args .outDir , figformat = 'png' , dpi = 72 , thumbnail = False , savefig = False )
168
172
obsnow = np .where (simdatasubset ['expMJD' ] == simdatasubset ['expMJD' ].max ())[0 ]
169
173
raCen = np .mean (simdatasubset [obsnow ]['lst' ])
170
174
# Calculate horizon location.
171
175
horizonlon , horizonlat = addHorizon (lat_telescope = lat_tele , raCen = raCen )
172
- # Create the plot for each metric.
173
- for mId in sm .metricValues :
174
- fignum = ops .plotSkyMap (sm .metricValues [mId ], raCen = raCen , ** sm .plotDicts [mId ])
176
+ # Create the plot for each metric and save it (after some additional manipulation).
177
+ for mb in bundles :
178
+ ph .setMetricBundles ([mb ])
179
+ fignum = ph .plot (plotFunc = plots .BaseSkyMap (), plotDicts = {'raCen' :raCen })
175
180
fig = plt .figure (fignum )
176
181
ax = plt .gca ()
177
182
# Add horizon and zenith.
178
183
plt .plot (horizonlon , horizonlat , 'k.' , alpha = 0.3 , markersize = 1.8 )
179
184
plt .plot (0 , lat_tele , 'k+' )
180
185
# For the FilterColors metric, add some extra items.
181
- if sm . metricNames [ mId ] == 'FilterColors' :
186
+ if mb . metric . name == 'FilterColors' :
182
187
# Add the time stamp info (plotlabel) with a fancybox.
183
188
plt .figtext (0.75 , 0.9 , '%s' % (plotlabel ), bbox = dict (boxstyle = 'Round, pad=0.7' , fc = 'w' , ec = 'k' , alpha = 0.5 ))
184
189
# Add a legend for the filters.
@@ -204,7 +209,7 @@ def runSlices(opsimName, metadata, simdata, fields, bins, args, verbose=False):
204
209
plt .legend (handles = [horizon , zenith , galaxy , ecliptic , moon ], loc = [0.1 , - 0.35 ], ncol = 3 , frameon = False ,
205
210
title = 'Aitoff plot showing HA/Dec of simulated survey pointings' , numpoints = 1 , fontsize = 'small' )
206
211
# Save figure.
207
- plt .savefig (os .path .join (args .outDir , sm . metricNames [ mId ] + '_' + slicenumber + '_SkyMap.png' ), format = 'png' , dpi = 72 )
212
+ plt .savefig (os .path .join (args .outDir , mb . metric . name + '_' + slicenumber + '_SkyMap.png' ), format = 'png' , dpi = 72 )
208
213
plt .close ('all' )
209
214
dt , t = dtime (t )
210
215
if verbose :
@@ -217,7 +222,7 @@ def stitchMovie(metricList, args):
217
222
for metric in metricList :
218
223
# Identify filenames.
219
224
outfileroot = metric .name
220
- plotfiles = fnmatch .filter (os .listdir (args .outDir ), outfileroot + '*SkyMap .png' )
225
+ plotfiles = fnmatch .filter (os .listdir (args .outDir ), outfileroot + '*_SkyMap .png' )
221
226
slicenum = plotfiles [0 ].replace (outfileroot , '' ).replace ('_SkyMap.png' , '' ).replace ('_' , '' )
222
227
sliceformat = '%s0%dd' % ('%' , len (slicenum ))
223
228
n_images = len (plotfiles )
@@ -236,7 +241,7 @@ def stitchMovie(metricList, args):
236
241
else :
237
242
args .fps = 30.0
238
243
# Create the movie.
239
- movieslicer .plotMovie (outfileroot , sliceformat , plotType = 'SkyMap' , figformat = 'png' ,
244
+ movieslicer .makeMovie (outfileroot , sliceformat , plotType = 'SkyMap' , figformat = 'png' ,
240
245
outDir = args .outDir , ips = args .ips , fps = args .fps )
241
246
242
247
if __name__ == '__main__' :
@@ -287,8 +292,8 @@ def stitchMovie(metricList, args):
287
292
if not args .skipComp :
288
293
verbose = False
289
294
# Get db connection info, and connect to database.
290
- dbAddress = 'sqlite:///' + os .path .join (args .dbDir , args .opsimDb )
291
- oo = db .OpsimDatabase (dbAddress )
295
+ dbfile = os .path .join (args .dbDir , args .opsimDb )
296
+ oo = db .OpsimDatabase (dbfile )
292
297
sqlconstraint = args .sqlConstraint
293
298
# Fetch the data from opsim.
294
299
simdata , fields = getData (oo , sqlconstraint )
@@ -310,10 +315,10 @@ def stitchMovie(metricList, args):
310
315
bins [0 ] = simdata ['expMJD' ][0 ]
311
316
312
317
# Run the movie slicer (and at each step, setup opsim slicer and calculate metrics).
313
- runSlices (opsimName , metadata , simdata , fields , bins , args , verbose = verbose )
318
+ runSlices (opsimName , metadata , simdata , fields , bins , args , oo , verbose = verbose )
314
319
315
320
# Need to set up the metrics to get their names, but don't need to have realistic arguments.
316
- metricList = setupMetrics (opsimName , metadata )
321
+ metricList , plotDictList = setupMetrics (opsimName , metadata )
317
322
stitchMovie (metricList , args )
318
323
end_t , start_t = dtime (start_t )
319
324
print 'Total time to create movie: ' , end_t
0 commit comments