In [1]:
import numpy as np
%matplotlib inline 
import matplotlib.pyplot as plt

In [2]:
# Required packages sqlachemy, pandas (both are part of anaconda distribution, or can be installed with a python installer)
# One step requires the LSST stack, can be skipped for a particular OPSIM database in question
import simlibs.summarize_opsim as so
from sqlalchemy import create_engine
import pandas as pd
print so.__file__


/Users/rbiswas/doc/projects/supernovae/LSST/simlib/build/lib/simlibs/summarize_opsim.pyc

In [3]:
# This step requires LSST SIMS package MAF. The main goal of this step is to set DD and WFD to integer keys that 
# label an observation as Deep Drilling or for Wide Fast Deep.
# If you want to skip this step, you can use the next cell by uncommenting it, and commenting out this cell, if all you
# care about is the database used in this example. But there is no guarantee that the numbers in the cell below will work
# on other versions of opsim database outputs

from lsst.sims.maf import db
from lsst.sims.maf.utils import opsimUtils

In [4]:
# DD = 366
# WFD = 364

Read in OpSim output for modern versions: (sqlite formats)

Description of OpSim outputs are available on the page https://confluence.lsstcorp.org/display/SIM/OpSim+Datasets+for+Cadence+Workshop+LSST2015http://tusken.astro.washington.edu:8080 Here we will use the opsim output http://ops2.tuc.noao.edu/runs/enigma_1189/data/enigma_1189_sqlite.db.gz I have downloaded this database, unzipped and use the variable dbname to point to its location


In [4]:
dbname = 'sqlite:////Users/rbiswas/data/LSST/OpSimData/enigma_1189_sqlite.db'
opsdb = db.OpsimDatabase(dbname)
propID, propTags = opsdb.fetchPropInfo()
DD = propTags['DD'][0]
WFD = propTags['DD'][0]

In [5]:
engine = create_engine(dbname)

Read in OpSim output for 2.168 cast in sqlite format (even though there are some differences)


In [6]:
dbname_2168 = 'sqlite:////Users/rbiswas/data/LSST/OpSimData/opsim2_168_sqlite.db'
engine_2168 = create_engine(dbname_2168)
dbAddressDict = {'dbAddress': dbname_2168, 'Summary':'summary'}
print dbAddressDict
opsimDb2168 = opsimUtils.connectOpsimDb(dbAddressDict)


{'Summary': 'summary', 'dbAddress': 'sqlite:////Users/rbiswas/data/LSST/OpSimData/opsim2_168_sqlite.db'}

In [7]:
propID, propTags = opsimDb2168.fetchPropInfo()

In [9]:
propTags


Out[9]:
{'DD': [], 'WFD': []}

This does not work for the old format. Read the SSTar document: http://opsimcvs.tuc.noao.edu/runs/opsim2.168/SSTAR-opsim2-168.pdf and find the deep drilling propIDs from Table 1.


In [10]:
DDold = 359, 360

Read in the OpSim DataBase into a pandas dataFrame

This subsection applies to more modern versions of OpSims (eg. Enigma_1189 used here)

The opsim database is a large file (approx 4.0 GB), but still possible to read into memory on new computers. You usually only need the Summary Table, which is about 900 MB. If you are only interested in the Deep Drilling Fields, you can use the read_sql_query to only select information pertaining to Deep Drilling Observations. This has a memory footprint of about 40 MB. Obviously, you can reduce this further by narrowing down the columns to those of interest only. For the entire Summary Table, this step takes a few minutes on my computer.


In [6]:
# Load to a dataframe
# Summary = pd.read_hdf('storage.h5', 'table')
# Summary = pd.read_sql_table('Summary', engine)
EnigmaDeep  = pd.read_sql_query('SELECT * FROM SUMMARY WHERE PROPID is 366', engine)

In [7]:
EnigmaDeep.fieldID.unique()


Out[7]:
array([1427, 2786,  290,  744, 2412])

In [8]:
# EnigmaDeepFields = pd.read_sql_table('Summary', engine)
# EnigmaDeepFields = EnigmaDeepFields.drop_duplicates()

In [8]:
# List columns 
EnigmaDeep.columns


Out[8]:
Index([u'obsHistID', u'sessionID', u'propID', u'fieldID', u'fieldRA', u'fieldDec', u'filter', u'expDate', u'expMJD', u'night', u'visitTime', u'visitExpTime', u'finRank', u'finSeeing', u'transparency', u'airmass', u'vSkyBright', u'filtSkyBrightness', u'rotSkyPos', u'lst', u'altitude', u'azimuth', u'dist2Moon', u'solarElong', u'moonRA', u'moonDec', u'moonAlt', u'moonAZ', u'moonPhase', u'sunAlt', u'sunAz', u'phaseAngle', u'rScatter', u'mieScatter', u'moonIllum', u'moonBright', u'darkBright', u'rawSeeing', u'wind', u'humidity', u'slewDist', u'slewTime', u'fiveSigmaDepth', u'ditheredRA', u'ditheredDec'], dtype='object')

In [16]:
# Alternatively, you can use Summary to read the entire table, and then slice using pandas

# DeepFields = Summary[Summary['propID'] == 366]
# WFD = Summary[Summary['propID'] == 364]
# season1Deep = DeepFields[DeepFields['night'] < 366]

We can read information about the Enigma Deep field summary table downloaded from Opsim with the command below to summarize the table. There are 110114 rows, and a total of 45 columns. The total memory on disk used is 38.6 MB


In [17]:
EnigmaDeep.fieldID.unique()


Out[17]:
array([1427, 2786,  290,  744, 2412])

This subsection is for sqlite transforms of old Versions of OpSim Outputs (eg. 2.168)


In [18]:
OpSim_2168_Deep = pd.read_sql_query('SELECT * FROM SUMMARY WHERE PROPID is 359 or PROPID is 360', engine_2168)

As shown from a similar command as above this OpSim database has 197332 rows (close to about twice as the enigma case) and 46 columns. The memory on disc is also larger by a similar factor and is 70 MB


In [19]:
OpSim_2168_Deep.info()


<class 'pandas.core.frame.DataFrame'>
Int64Index: 197332 entries, 0 to 197331
Data columns (total 46 columns):
airmass              197332 non-null float64
altitude             197332 non-null float64
azimuth              197332 non-null float64
darkBright           197332 non-null float64
dist2Moon            197332 non-null float64
ditheredDec          197332 non-null float64
ditheredRA           197332 non-null float64
expDate              197332 non-null int64
expMJD               197332 non-null float64
fieldDec             197332 non-null float64
fieldID              197332 non-null int64
fieldRA              197332 non-null float64
filtSkyBrightness    197332 non-null float64
filter               197332 non-null object
finRank              197332 non-null float64
finSeeing            197332 non-null float64
fiveSigmaDepth       197332 non-null float64
humidity             197332 non-null float64
lst                  197332 non-null float64
mieScatter           197332 non-null float64
moonAZ               197332 non-null float64
moonAlt              197332 non-null float64
moonBright           197332 non-null float64
moonDec              197332 non-null float64
moonIllum            197332 non-null float64
moonPhase            197332 non-null float64
moonRA               197332 non-null float64
night                197332 non-null int64
obsHistID            197332 non-null int64
phaseAngle           197332 non-null float64
propID               197332 non-null int64
rScatter             197332 non-null float64
rawSeeing            197332 non-null float64
rotSkyPos            197332 non-null float64
rotTelPos            197332 non-null float64
sessionID            197332 non-null int64
slewDist             197332 non-null float64
slewTime             197332 non-null float64
solarElong           197332 non-null float64
sunAlt               197332 non-null float64
sunAz                197332 non-null float64
transparency         197332 non-null float64
vSkyBright           197332 non-null float64
visitExpTime         197332 non-null float64
visitTime            197332 non-null int64
wind                 197332 non-null float64
dtypes: float64(38), int64(7), object(1)
memory usage: 70.8+ MB

In [20]:
OpSim_2168_Deep['propID'].unique()


Out[20]:
array([360, 359])

We can select a season, for example the first season by the following method. It would be trivial to add a column giving a season by dividing the night variable by 365.


In [21]:
Season0_2_168 = OpSim_2168_Deep[OpSim_2168_Deep['night'] < 366]

In [22]:
OpSim_2168_Deep.fieldID.unique()


Out[22]:
array([ 311,  519,  526,  764, 1427, 2082, 2412, 2712, 2731, 2786])

Write out Full 10 year Simlib

This is the point, where we start using this package. The stuff before was simply interacting with OpSim

OpSim 2.168


In [23]:
OpSim_2_168_DeepFull = so.SummaryOpsim(OpSim_2168_Deep)

We can view the summary for a particular field


In [24]:
OpSim_2_168_DeepFull.simlib(2082)[['expMJD','obsHistID','filter', 'night']].head()


Out[24]:
expMJD obsHistID filter night
103088 49400.275853 38713156 g 47
103089 49400.276270 38713158 g 47
103090 49400.276687 38713159 g 47
103091 49400.277103 38713160 g 47
103092 49400.277520 38713161 g 47

In [25]:
OpSim_2_168_DeepFull.writeSimlib('OpSim_2.168.DEEP.Full')

In [26]:
OpSim_2_168_DeepFull.fieldIds


Out[26]:
[2082, 519, 2731, 2412, 2786, 526, 1427, 311, 2712, 764]

In [27]:
fig = OpSim_2_168_DeepFull.cadence_plot(519, sql_query='night <365', nightMin=0, nightMax=365)



In [28]:
fig = map(lambda x: OpSim_2_168_DeepFull.cadence_plot(x, sql_query='night <365', nightMin=0, nightMax=365), OpSim_2_168_DeepFull.fieldIds)



In [29]:
fig = map(lambda x: OpSim_2_168_DeepFull.cadence_plot(x, sql_query='night <3650', nightMin=0, nightMax=3650), OpSim_2_168_DeepFull.fieldIds)


Enigma


In [7]:
EnigmaDeepSummary = so.SummaryOpsim(EnigmaDeep)

In [12]:
fig = plt.figure(figsize=(10, 5))
ax = fig.add_subplot(111, projection='mollweide');
fig = OpSim_2_168_DeepFull.showFields(ax=fig.axes[0], marker='o', s=80)


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-12-73eff151f92a> in <module>()
      1 fig = plt.figure(figsize=(10, 5))
      2 ax = fig.add_subplot(111, projection='mollweide');
----> 3 fig = OpSim_2_168_DeepFull.showFields(ax=fig.axes[0], marker='o', s=80)

NameError: name 'OpSim_2_168_DeepFull' is not defined

In [11]:
fig = EnigmaDeepSummary.showFields(ax=fig.axes[0], marker='s', color='r')


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-11-a0b0255fbf1e> in <module>()
----> 1 fig = EnigmaDeepSummary.showFields(ax=fig.axes[0], marker='s', color='r')

NameError: name 'fig' is not defined

In [33]:
ax = fig.gca()
ax.set_title('Deep Drilling Fields for 2.168, Enigma_1189')


Out[33]:
<matplotlib.text.Text at 0x117476750>

In [34]:
fig


Out[34]:

In [9]:
EnigmaDeepSummary.simlib(290).head()


Out[9]:
obsHistID sessionID propID fieldID fieldRA fieldDec filter expDate expMJD night ... wind humidity slewDist slewTime fiveSigmaDepth ditheredRA ditheredDec simLibPsf simLibZPTAVG simLibSkySig
2036 140297 1189 366 290 6.097944 -1.10516 r 15402156 49531.265704 178 ... 0 0 0.93277 83.261838 23.364830 6.076685 -1.088628 2.457219 31.682579 9.216794
2037 140298 1189 366 290 6.097944 -1.10516 r 15402193 49531.266133 178 ... 0 0 0.00000 3.000000 23.294772 6.076685 -1.088628 2.625730 31.682781 9.519887
2038 140299 1189 366 290 6.097944 -1.10516 r 15402229 49531.266549 178 ... 0 0 0.00000 2.000000 23.296010 6.076685 -1.088628 2.624079 31.683107 9.515891
2039 140300 1189 366 290 6.097944 -1.10516 r 15402266 49531.266978 178 ... 0 0 0.00000 3.000000 23.297206 6.076685 -1.088628 2.622481 31.683424 9.512040
2040 140301 1189 366 290 6.097944 -1.10516 r 15402303 49531.267406 178 ... 0 0 0.00000 3.000000 23.298434 6.076685 -1.088628 2.620845 31.683747 9.508076

5 rows × 48 columns


In [31]:
mat = EnigmaDeepSummary.cadence_Matrix(290, observedOnly=True)

In [33]:
mat[180:]


Out[33]:
Filters u g r i z Y
180 NaN NaN NaN NaN NaN NaN
181 NaN 1 1 1 1 1
182 NaN NaN NaN NaN NaN NaN
183 NaN NaN NaN NaN NaN NaN
184 NaN NaN NaN NaN NaN NaN
185 NaN NaN NaN NaN NaN NaN
186 NaN NaN NaN NaN NaN NaN
187 NaN NaN NaN NaN NaN NaN
188 NaN NaN NaN NaN NaN NaN
189 NaN NaN NaN NaN NaN NaN
190 NaN NaN NaN NaN NaN NaN
191 NaN NaN NaN NaN NaN NaN
192 NaN NaN NaN NaN NaN NaN
193 NaN NaN NaN NaN NaN NaN
194 NaN NaN NaN NaN NaN NaN
195 NaN 1 1 1 1 NaN
196 NaN NaN NaN NaN NaN NaN
197 NaN NaN NaN NaN NaN NaN
198 NaN NaN NaN NaN NaN NaN
199 NaN 1 1 1 1 1
200 NaN NaN NaN NaN NaN NaN
201 NaN NaN NaN NaN NaN NaN
202 NaN NaN NaN NaN NaN NaN
203 NaN NaN NaN NaN NaN NaN
204 NaN NaN NaN NaN NaN NaN
205 NaN NaN NaN NaN NaN NaN
206 NaN NaN NaN NaN NaN NaN
207 NaN NaN NaN NaN NaN NaN
208 NaN 1 1 1 1 1
209 NaN NaN NaN NaN NaN NaN
... ... ... ... ... ... ...
335 NaN NaN NaN NaN NaN NaN
336 NaN NaN NaN NaN NaN NaN
337 NaN NaN NaN NaN NaN NaN
338 NaN NaN NaN NaN NaN NaN
339 NaN NaN NaN NaN NaN NaN
340 NaN NaN NaN NaN NaN NaN
341 NaN NaN NaN NaN NaN NaN
342 NaN NaN NaN NaN NaN NaN
343 NaN NaN NaN NaN NaN NaN
344 NaN NaN NaN NaN NaN NaN
345 NaN NaN NaN NaN NaN NaN
346 NaN NaN NaN NaN NaN NaN
347 NaN NaN NaN NaN NaN NaN
348 NaN NaN NaN NaN NaN NaN
349 NaN NaN NaN NaN NaN NaN
350 NaN NaN NaN NaN NaN NaN
351 NaN NaN NaN NaN NaN NaN
352 NaN NaN NaN NaN NaN NaN
353 NaN NaN NaN NaN NaN NaN
354 NaN NaN NaN NaN NaN NaN
355 NaN NaN NaN NaN NaN NaN
356 NaN NaN NaN NaN NaN NaN
357 NaN NaN NaN NaN NaN NaN
358 NaN NaN NaN NaN NaN NaN
359 NaN NaN NaN NaN NaN NaN
360 NaN NaN NaN NaN NaN NaN
361 NaN NaN NaN NaN NaN NaN
362 NaN NaN NaN NaN NaN NaN
363 NaN NaN NaN NaN NaN NaN
364 NaN NaN NaN NaN NaN NaN

185 rows × 6 columns


In [25]:
gg = pd.DataFrame({'gg':mat.g.diff().values, 'rr':mat.r.diff().values})

In [30]:
gg['gg'].values[170:190]


Out[30]:
array([ nan,  nan,  nan,  nan,  nan,  nan,  nan,  nan,  nan,  nan,  nan,
        nan,  nan,  nan,  nan,  nan,  nan,  nan,  nan,  nan])

In [9]:
fig = EnigmaDeepSummary.cadence_plot(290, observedOnly=True)
plt.savefig('cadence.pdf')



In [20]:
matrix = EnigmaDeepSummary.cadence_plot(290, observedOnly=True)



In [106]:
axesImage = plt.matshow(matrix.transpose(), aspect='auto', cmap=plt.cm.gray_r, vmin=0., vmax=1.)
# plt.colorbar(orientation='horizontal')



In [107]:
ax = axesImage.axes

In [56]:
fig = ax.figure

In [103]:
EnigmaDeepSummary.dec(290)


Out[103]:
-1.1051599999999999

In [120]:
title = 'fieldID: {:0>2d} (ra: {:+3f} dec: {:+3f})'
title = title.format(290, EnigmaDeepSummary.ra(290), EnigmaDeepSummary.dec(290))
print title


fieldID: 290 (ra: +6.097944 dec: -1.105160)

In [67]:
ax.set_title(title)


Out[67]:
<matplotlib.text.Text at 0x10e8122d0>

In [113]:
for i, item in enumerate(ax.get_yticklabels()[1:-1]):
    print i, item.get_text(), ax.set_text(Filters[i]), item.get_text()


0 0 None u
1 1 None g
2 2 None r
3 3 None i
4 4 None z
5 5 None Y

In [68]:
fig.colorbar(cax=axesImage,)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-68-e267ed055bfb> in <module>()
----> 1 fig.colorbar(cax=axesImage,)

TypeError: colorbar() takes at least 2 arguments (2 given)

In [87]:
Filters = [u'u', u'g', u'r', u'i', u'z', u'Y']

In [92]:
len(yticklabels)


Out[92]:
8

In [91]:
for i, item in enumerate(yticklabels):
    item.set_text(Filters[i])


---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-91-f1bf3a9669cf> in <module>()
      1 for i, item in enumerate(yticklabels):
----> 2     item.set_text(Filters[i])

IndexError: list index out of range

In [89]:
yticklabels = ax.get_yticklabels()

In [93]:
[item.get_text() for item in yticklabels]


Out[93]:
[u'u', u'g', u'r', u'i', u'z', u'Y', u'5', u'']

In [81]:
ax.xaxis.tick_bottom()

In [114]:
fig = ax.figure
fig


Out[114]:

In [78]:
xticks = ax.get_xticks()

In [80]:
ax.set_xticks(xticks)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-80-35d94606649b> in <module>()
----> 1 xticks.getfield()

TypeError: Required argument 'dtype' (pos 1) not found

In [118]:
ax.set_yticklabels(['0'] +Filters, minor=False)


Out[118]:
[<matplotlib.text.Text at 0x10dcb5190>,
 <matplotlib.text.Text at 0x10d705bd0>,
 <matplotlib.text.Text at 0x10aedf050>,
 <matplotlib.text.Text at 0x10d457890>,
 <matplotlib.text.Text at 0x1145f3e50>,
 <matplotlib.text.Text at 0x1145f3e10>,
 <matplotlib.text.Text at 0x10d1c8290>]

In [119]:
fig


Out[119]:

In [36]:
fig = map(lambda x: EnigmaDeepSummary.cadence_plot(x, sql_query='night < 3650', nightMin=0, nightMax=3650), EnigmaDeepSummary.fieldIds)



In [37]:
EnigmaDeepFieldSummary = so.SummaryOpsim(EnigmaDeepFields)

In [38]:
EnigmaDeepFieldSummary.fieldIds[10]


Out[38]:
11

In [39]:
fig = EnigmaDeepFieldSummary.cadence_plot(, sql_query='night < 365', nightMax=365)



In [41]:
fig = EnigmaDeepSummary.cadence_plot(744, sql_query='night < 730', nightMin=0, nightMax=730)


ERROR! Session/line number was not unique in database. History logging moved to new session 1692

In [40]:
fig = map(lambda x: EnigmaDeepFieldSummary.cadence_plot(x, sql_query='night < 730', nightMin=0, nightMax=730), EnigmaDeepFieldSummary.fieldIds)


/usr/local/manual/anaconda/lib/python2.7/site-packages/matplotlib/pyplot.py:424: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`).
  max_open_warning, RuntimeWarning)
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-41-ff773bdcb9b7> in <module>()
----> 1 fig = map(lambda x: EnigmaDeepFieldSummary.cadence_plot(x, sql_query='night < 730', nightMin=0, nightMax=730), EnigmaDeepFieldSummary.fieldIds)

<ipython-input-41-ff773bdcb9b7> in <lambda>(x)
----> 1 fig = map(lambda x: EnigmaDeepFieldSummary.cadence_plot(x, sql_query='night < 730', nightMin=0, nightMax=730), EnigmaDeepFieldSummary.fieldIds)

/Users/rbiswas/doc/projects/supernovae/LSST/simlib/build/lib/simlibs/summarize_opsim.py in cadence_plot(self, fieldID, sql_query, Filters, nightMin, nightMax, observedOnly)
    119         cadence_dict['numObs'] = list(numObs)
    120         Matrix = pd.DataFrame(cadence_dict).pivot('night', 'Filters', 'numObs')
--> 121         M = Matrix[Filters]
    122         ss = pd.Series(np.arange(nightMin, nightMax))
    123         Matrix = M.reindex(ss, fill_value=0)

/usr/local/manual/anaconda/lib/python2.7/site-packages/pandas/core/frame.pyc in __getitem__(self, key)
   1779         if isinstance(key, (Series, np.ndarray, Index, list)):
   1780             # either boolean or fancy integer index
-> 1781             return self._getitem_array(key)
   1782         elif isinstance(key, DataFrame):
   1783             return self._getitem_frame(key)

/usr/local/manual/anaconda/lib/python2.7/site-packages/pandas/core/frame.pyc in _getitem_array(self, key)
   1823             return self.take(indexer, axis=0, convert=False)
   1824         else:
-> 1825             indexer = self.ix._convert_to_indexer(key, axis=1)
   1826             return self.take(indexer, axis=1, convert=True)
   1827 

/usr/local/manual/anaconda/lib/python2.7/site-packages/pandas/core/indexing.pyc in _convert_to_indexer(self, obj, axis, is_setter)
   1138                 mask = check == -1
   1139                 if mask.any():
-> 1140                     raise KeyError('%s not in index' % objarr[mask])
   1141 
   1142                 return _values_from_object(indexer)

KeyError: "[u'u' u'Y'] not in index"
Traceback (most recent call last):

  File "/usr/local/manual/anaconda/lib/python2.7/site-packages/IPython/kernel/zmq/ipkernel.py", line 389, in execute_request
    shell.run_cell(code, store_history=store_history, silent=silent)

  File "/usr/local/manual/anaconda/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2743, in run_cell
    self.events.trigger('post_execute')

  File "/usr/local/manual/anaconda/lib/python2.7/site-packages/IPython/core/events.py", line 82, in trigger
    func(*args, **kwargs)

  File "/usr/local/manual/anaconda/lib/python2.7/site-packages/IPython/kernel/zmq/pylab/backend_inline.py", line 118, in flush_figures
    return show(True)

  File "/usr/local/manual/anaconda/lib/python2.7/site-packages/IPython/kernel/zmq/pylab/backend_inline.py", line 43, in show
    display(figure_manager.canvas.figure)

  File "/usr/local/manual/anaconda/lib/python2.7/site-packages/IPython/core/display.py", line 131, in display
    format_dict, md_dict = format(obj, include=include, exclude=exclude)

  File "/usr/local/manual/anaconda/lib/python2.7/site-packages/IPython/core/formatters.py", line 200, in format
    data = formatter(obj)

  File "<string>", line 2, in __call__

  File "/usr/local/manual/anaconda/lib/python2.7/site-packages/IPython/core/formatters.py", line 233, in warn_format_error
    r = method(self, *args, **kwargs)

  File "/usr/local/manual/anaconda/lib/python2.7/site-packages/IPython/core/formatters.py", line 350, in __call__
    return printer(obj)

  File "/usr/local/manual/anaconda/lib/python2.7/site-packages/IPython/core/pylabtools.py", line 220, in <lambda>
    png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))

  File "/usr/local/manual/anaconda/lib/python2.7/site-packages/IPython/core/pylabtools.py", line 130, in print_figure
    fig.canvas.print_figure(bytes_io, **kw)

  File "/usr/local/manual/anaconda/lib/python2.7/site-packages/matplotlib/backend_bases.py", line 2158, in print_figure
    **kwargs)

  File "/usr/local/manual/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_agg.py", line 521, in print_png
    FigureCanvasAgg.draw(self)

  File "/usr/local/manual/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_agg.py", line 469, in draw
    self.figure.draw(self.renderer)

  File "/usr/local/manual/anaconda/lib/python2.7/site-packages/matplotlib/artist.py", line 59, in draw_wrapper
    draw(artist, renderer, *args, **kwargs)

  File "/usr/local/manual/anaconda/lib/python2.7/site-packages/matplotlib/figure.py", line 1085, in draw
    func(*args)

  File "/usr/local/manual/anaconda/lib/python2.7/site-packages/matplotlib/artist.py", line 59, in draw_wrapper
    draw(artist, renderer, *args, **kwargs)

  File "/usr/local/manual/anaconda/lib/python2.7/site-packages/matplotlib/axes/_base.py", line 2110, in draw
    a.draw(renderer)

  File "/usr/local/manual/anaconda/lib/python2.7/site-packages/matplotlib/artist.py", line 59, in draw_wrapper
    draw(artist, renderer, *args, **kwargs)

  File "/usr/local/manual/anaconda/lib/python2.7/site-packages/matplotlib/axis.py", line 1114, in draw
    ticks_to_draw = self._update_ticks(renderer)

  File "/usr/local/manual/anaconda/lib/python2.7/site-packages/matplotlib/axis.py", line 957, in _update_ticks
    tick_tups = [t for t in self.iter_ticks()]

  File "/usr/local/manual/anaconda/lib/python2.7/site-packages/matplotlib/axis.py", line 902, in iter_ticks
    majorTicks = self.get_major_ticks(len(majorLocs))

  File "/usr/local/manual/anaconda/lib/python2.7/site-packages/matplotlib/axis.py", line 1310, in get_major_ticks
    self._copy_tick_props(protoTick, tick)

  File "/usr/local/manual/anaconda/lib/python2.7/site-packages/matplotlib/axis.py", line 1266, in _copy_tick_props
    dest.tick2line.update_from(src.tick2line)

  File "/usr/local/manual/anaconda/lib/python2.7/site-packages/matplotlib/lines.py", line 1148, in update_from
    other._marker.get_fillstyle())

  File "/usr/local/manual/anaconda/lib/python2.7/site-packages/matplotlib/markers.py", line 169, in __init__
    self.set_marker(marker)

  File "/usr/local/manual/anaconda/lib/python2.7/site-packages/matplotlib/markers.py", line 250, in set_marker
    self._recache()

  File "/usr/local/manual/anaconda/lib/python2.7/site-packages/matplotlib/markers.py", line 191, in _recache
    self._marker_function()

  File "/usr/local/manual/anaconda/lib/python2.7/site-packages/matplotlib/markers.py", line 700, in _set_tickdown
    self._transform = Affine2D().scale(1.0, -1.0)

  File "/usr/local/manual/anaconda/lib/python2.7/site-packages/matplotlib/transforms.py", line 1915, in scale
    np.float_)

KeyboardInterrupt

Write out SIMLIB for Season 1


In [ ]:
season = season1Deep.copy(deep=True)

In [ ]:
oldseason = Season0_2_168.copy(deep=True)

In [ ]:
simlib_opsim_2_168 = so.SummaryOpsim(oldseason)

In [ ]:
simlib_opsim_2_168.fieldIds

In [ ]:
simlib_opsim_2_168.writeSimlib('Opsim.2.168.Simlib')

In [ ]:
simlib = so.SummaryOpsim(season)

In [ ]:
simlib.df['filter'].unique()

In [ ]:
simlib.fieldIds

In [ ]:
simlib.writeSimlib('test_out.simlib')

Scratch


In [ ]:
filtergroups = EnigmaDeepSummary.simlib(290).query('night < 366').groupby('filter')

In [ ]:
filters = filtergroups.groups.keys()
Filters = [u'u', u'g', u'r', u'i', u'z', u'Y']

In [ ]:
filtered = map(lambda x: filtergroups.get_group(x).copy(deep=True), filters)

In [ ]:
def cadence_plot(dd, fieldID, sql_query='night < 366', Filters=[u'u', u'g', u'r', u'i', u'z', u'Y'], nightMin=0, nightMax=365):
    filtergroups = dd.simlib(fieldID).query(sql_query).groupby('filter')
    times = dict()
    numExps = dict()
    numDays = nightMax - nightMin
    H = np.zeros(shape=(len(Filters), numDays))
    for i, filt in enumerate(Filters):
        expVals = np.zeros(numDays, dtype=int)
        filtered = map(lambda x: filtergroups.get_group(x).copy(deep=True), Filters)
        # filtered[i]['timeIndex'] = filtered[i].expMJD // deltaT
        timeBinned = filtered[i].groupby('night')
        timeKeys = timeBinned.groups.keys()
        times = map(int, timeBinned.night.apply(np.mean))
        times = np.array(times) - nightMin
        # print times
        # times = map(lambda x: timeBinned.get_group(x).expMJD.mean(), timeKeys)
        numExps = timeBinned.apply(len)
        expVals[times] = numExps
        H[i, :] = expVals
    
    #fig = plt.figure()
    # ax = fig.add_subplot(111)
    ax = plt.matshow(H, aspect='auto')
    plt.colorbar(orientation='horizontal', cmap=cm.gray_r)
    # ax.axhline(1,0, 365)
    fig = ax.figure
    # ax.grid(True)
    # fig = ax.figure
    
    return fig

In [ ]:
OpSim_2_168_DeepFull.fieldIds

In [ ]:
EnigmaDeepSummary.fieldIds

In [ ]:


In [ ]:
fig = EnigmaDeepSummary.cadence_plot(290, sql_query='night <366', nightMin=0, nightMax=365)

In [ ]:
fig = EnigmaDeepSummary.cadence_plot(1427, sql_query='night <365', nightMin=0, nightMax=365)

In [ ]:
fig = EnigmaDeepSummary.cadence_plot(2412, sql_query='night <365', nightMin=0, nightMax=365)

In [ ]:
fig = EnigmaDeepSummary.cadence_plot(2786, sql_query='night <365', nightMin=0, nightMax=365)

In [ ]:
fig = plt.figure()#figsize=(10*10, 4))
ax = fig.add_subplot(1,3,9)

In [ ]:
help(fig.add_subplot(10,1,1))

In [ ]:
help(plt.matshow)

In [ ]:
np.shape(H)

In [ ]:
plt.matshow(H, aspect='auto')
plt.colorbar(orientation='horizontal', cmap = cm.gray_r)

In [ ]:
help(plt.matshow)

In [ ]:
import matplotlib.cm as cm

In [ ]:
plt.colormaps()

In [ ]:
%matplotlib inline
import matplotlib.pyplot as plt
plt.plot(times[u'g'], numExps[u'g'])

In [ ]:
expVals = np.zeros(365)

In [ ]:
expVals

In [ ]:
times[u'g']

In [ ]:
t = np.zeros(len(times[u'g'].values), dtype=int)

In [ ]:
t = times[u'g'].values

In [ ]:
t = map(int, times[u'g'].values)

In [ ]:
expVals[t] = numExps[u'g']

In [ ]:
expVals

In [ ]:
numExps[u'g'].dtype

In [ ]:
cadence = filtergroups.get_group(u'g')

In [ ]:
cad = cadence.copy(deep=True)

In [ ]:
deltaT = 1
cad['timeIndex'] = cad.expMJD // deltaT

In [ ]:
gg = cad.groupby('timeIndex').apply(len)

In [ ]:
filters

In [ ]:
filtered[0]

In [ ]:
map(len,gg.values())

In [ ]:
obs = cadence.groupby('night')

In [ ]:


In [ ]:
map(lambda x: EnigmaDeepSummary.ra(x), EnigmaDeepSummary.fieldIds)

In [ ]:
EnigmaDeepSummary.ra(290)

In [ ]:
fieldSummary = EnigmaDeepSummary.simlib(290)

In [ ]:
dd = fieldSummary[fieldSummary['night'] < 366 ]

In [ ]:
xx = fieldSummary.query('night < 366')

In [ ]:
all(xx == dd)

In [ ]:
def nightsObserved(dd, band, color='k', ax=None):
    xx = dd.groupby(dd['filter']).get_group(band).groupby('night')
    yy = np.sort(xx.groups.keys())
    if ax is None:
        fig, ax = plt.subplots()
    ax.bar(yy, np.ones(len(yy)), color=color)

In [ ]:
def plotnightsObserved(dd):
    nightsObserved(dd, u'u', color='y')
    nightsObserved(dd, u'g', color='g')
    nightsObserved(dd, u'r', color='b')
    nightsObserved(dd, u'i', color ='k')
    nightsObserved(dd, u'z', color='red')
    nightsObserved(dd, u'Y', color='magenta')

In [ ]:
def plotnightsDeep()

In [ ]:
nightsObserved(dd, u'g')

In [ ]:
plotnightsObserved(EnigmaDeepSummary.simlib(744)[EnigmaDeepSummary.simlib(744)['night']<730])

In [ ]:
dd.night.hist(by=dd['filter'], bins=365, histtype='step', sharex=True)

In [ ]:
help(dd.night.hist)

In [ ]:
fd  = dd.groupby('filter')

In [ ]:
dp=fd.get_group(u'g')

In [ ]:
dd.groups.keys()

In [ ]:
dp.plot(dp['night'], bins=365, histtype='step')

In [ ]:
dd.get_group(u'g').night.plot(kind='bar')

In [ ]:
xd = dd.get_group(u'g').('expMJD', kind='bar')

In [ ]:
np.sort(xd.groups.keys())

In [ ]:
(map(lambda x: xd.get_group(x).obsHistID.size, xd.groups.keys()))

In [ ]:
def filterDiff(summary, fieldID, filter):
    x = summary.simlib(fieldID).groupby('filter').get_group(filter).night.unique()
    return np.diff(x)

In [ ]:
plt.hist(filterDiff(OpSim_2_168_DeepFull, 2082, 'g'), histtype='step', bins=20, color='g')
plt.hist(filterDiff(OpSim_2_168_DeepFull, 2082, 'u'), histtype='step', bins=20, color='r')
plt.hist(filterDiff(OpSim_2_168_DeepFull, 2082, 'Y'), histtype='step', bins=20, color='k')

In [ ]:
def drawfields(summ, ax=None, marker=None):
    if ax is None:
        fig = plt.figure()
        ax = fig.add_subplot(111, projection='mollweide')
    if marker is None:
        marker = 'o'
    ax.plot(summ.coords()[0], summ.coords()[1], marker);
    ax.grid(True)
    fig  = ax.figure;
    return fig
#ax.plot(np.radians([30., 45.]), np.radians([75, 45.]),'o')

In [ ]:
import seaborn as sns
sns.set()

# Load the example flights dataset and conver to long-form
flights_long = sns.load_dataset("flights")
flights = flights_long.pivot("month", "year", "passengers")

# Draw a heatmap with the numeric values in each cell
sns.heatmap(flights, annot=True, fmt="d", linewidths=.5)

In [ ]:
type(flights_long)

In [ ]:
flights_long

In [ ]:
type(flights)

In [ ]:
flights

In [ ]:
gg = EnigmaDeepSummary.simlib(744).groupby(['filter', 'night'])

In [ ]:
f1, nt = zip(*gg.groups.keys())

In [ ]:
gg.apply(len).values

In [ ]:
filts, nights = zip( *gg.groups.keys())
nums = gg.apply(len).values
df = pd.DataFrame({'filts': list(filts), 'nights': list(nights), 'nums': nums})

In [ ]:
df.columns

In [ ]:
dd = df.pivot('nights','filts','nums' )

In [ ]:
dd.columns

In [ ]:
ddd = dd.fillna(0).transpose()

In [ ]:
ss = pd.Series(np.arange(0,365))

In [ ]:
ddd.index

In [ ]:
ddd = ddd.reindex(ss, fill_value=0)

In [ ]:
xx = ddd[[u'u', u'g', u'r', u'i', u'z', u'Y']]

In [ ]:
xx.iloc[180:185]

In [ ]:
ddd.iloc[180:185]

In [ ]:
gg.apply(len).values

In [ ]:
fig = sns.heatmap(ddd.transpose(), annot=True, fmt='.2g', linewidth=0.5)

In [ ]:
def grayify_cmap(cmap):
    """Return a grayscale version of the colormap"""
    cmap = plt.cm.get_cmap(cmap)
    colors = cmap(np.arange(cmap.N))
    
    # convert RGBA to perceived greyscale luminance
    # cf. http://alienryderflex.com/hsp.html
    RGB_weight = [0.299, 0.587, 0.114]
    luminance = np.sqrt(np.dot(colors[:, :3] ** 2, RGB_weight))
    colors[:, :3] = luminance[:, np.newaxis]
    
    return cmap.from_list(cmap.name + "_grayscale", colors, cmap.N)

def show_colormap(cmap):
    im = np.outer(np.ones(10), np.arange(100))
    fig, ax = plt.subplots(2, figsize=(6, 1.5),
                           subplot_kw=dict(xticks=[], yticks=[]))
    fig.subplots_adjust(hspace=0.1)
    ax[0].imshow(im, cmap=cmap)
    ax[1].imshow(im, cmap=grayify_cmap(cmap))
    
show_colormap('gray')

In [ ]:
tips = sns.load_dataset("tips")

In [ ]:
tips

In [ ]:
sns.FacetGrid(tips, col='time', col_wrap=1)

In [ ]:
fig = plt.figure()

In [ ]:
import matplotlib.gridspec as gridspec

In [ ]:
gs = gridspec.GridSpec(10,1)

In [ ]:
ax0 = fig.add_subplot(gs[0])

In [ ]:
fig = EnigmaDeepSummary.cadence_plot(744, sql_query='night <366', nightMin=0, nightMax=365)

In [ ]:
plt.matshow(xx.transpose(), aspect='auto', cmap=plt.cm.gray_r)
plt.yticks(np.arange(6),('u', 'g', 'r', 'i', 'z', 'Y'))
plt.grid(True)

In [ ]:
np.arange(5, 12)

In [ ]:
(180 / np.pi)**2

In [17]:
l = np.array([1,0, 2, 3, 0, 0, 3])

In [19]:
np.where(l, 1, 0)


Out[19]:
array([1, 0, 1, 1, 0, 0, 1])

In [25]:
fig, ax = plt.subplots()
#ax = fig.axes[0]
ax.plot(l,l)
ax.set_title('tit;e')


Out[25]:
<matplotlib.text.Text at 0x10c201350>

In [ ]: