In [1]:
import os
import numpy as np
import pandas as pd

Note For this to work, you will need the lsst.sims stack to be installed.

  • opsimsummary uses healpy which is installed with the sims stack, but also available from conda

In [2]:
import opsimsummary as oss
from opsimsummary import Tiling, HealpixTiles
# import snsims
import healpy as hp

In [3]:
%matplotlib inline
import matplotlib.pyplot as plt

In [4]:
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt

This section pertains to how to write a new Tiling class

noTile = snsims.Tiling()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-5f6f8a94508e> in <module>()
----> 1 noTile = snsims.Tiling()

TypeError: Can't instantiate abstract class Tiling with abstract methods __init__, area, pointingSequenceForTile, tileIDSequence, tileIDsForSN

The class snsims.Tiling is an abstract Base class. Therefore, this cannot be instantiated. It must be subclassed, and the set of methods outlined have to be implemented for this to work.


In [5]:
class NoTile(Tiling):
    pass

In [6]:
noTile = NoTile()


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-8ddedac7fb97> in <module>()
----> 1 noTile = NoTile()

TypeError: Can't instantiate abstract class NoTile with abstract methods __init__, area, pointingSequenceForTile, positions, tileIDSequence, tileIDsForSN
"""noTile = NoTile()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-8ddedac7fb97> in <module>()
----> 1 noTile = NoTile()

TypeError: Can't instantiate abstract class NoTile with abstract methods __init__, area, pointingSequenceForTile, positions, tileIDSequence, tileIDsForSN
"""

The above fails because the methods are not implemented. Below is a stupid (ie. not useful) but minimalist class that would work:


In [7]:
class MyTile(Tiling):
    def __init__(self):
        pass
    @property
    def tileIDSequence(self):
        return np.arange(100)
    
    def tileIDsForSN(self, ra, dec):
        x = ra + dec
        y = np.remainder(x, 100.)
        return np.floor(y)
    def area(self, tileID):
        return 1.
    def pointingSequenceForTile(self, tileID, pointings):
        return None
    def positions(self):
        pass

In [8]:
myTile = MyTile()

Using the class HealpixTiles

Currently there is only concrete tiling class that has been implemented. This is the snsims.HealpixTiles class.

This shows how to use the HealpixTiles Class


In [9]:
issubclass(HealpixTiles, Tiling)


Out[9]:
True

In [10]:
help(HealpixTiles)


Help on class HealpixTiles in module opsimsummary.healpixTiles:

class HealpixTiles(opsimsummary.tessellations.Tiling)
 |  A concrete Tiling class based on Healpix Tiles. The user is
 |  allowed to choose the following parameters:
 |  
 |  Attributes
 |  ----------
 |  nside : int, power of 2, defaults to 256
 |      healpix nside parameter
 |  
 |  Method resolution order:
 |      HealpixTiles
 |      opsimsummary.tessellations.Tiling
 |      __builtin__.object
 |  
 |  Methods defined here:
 |  
 |  __init__(self, nside=256, healpixelizedOpSim=None, preComputedMap=None)
 |      nside : int, power of 2, defaults to 256
 |          nside parameter of healpix. determines the size of the tiles
 |          so that there are 12 * nside **2 equally sized tiles covering
 |          the sphere.
 |  
 |  area(self, tileID)
 |  
 |  pointingSequenceForTile(self, tileID, allPointings=None, columns=None, **kwargs)
 |      return a maximal sequence of pointings for a particular tileID.
 |  
 |  positions(self, tileID, numSamples, rng=None)
 |      Return a tuple of (res_phi, res_theta) where res_phi and res_theta are
 |      spatially uniform samples  of positions of size numSamples within the
 |      healpix Tile with ipix=tileID in the nested scheme. The return values
 |      should be in degrees, with the convention that theta is 0 on the equator and 
 |      90 degrees at the North Pole.
 |      
 |      Parameters
 |      ---------
 |      tileID : int, mandatory
 |      
 |      numSamples : number of positions required
 |      
 |      rng : instance of `np.random.RandomState`
 |      
 |      
 |      Returns
 |      -------
 |      
 |      .. notes : 1. The inelegant method is sampling a circle with a radius
 |          twice that required to have an area equal to the healpix tile. This
 |          operation can be done by self.samplePatchOnSphere and returns 
 |          numSamples, some of which are not on the healpixTiles.
 |          2. `self._angularSamples` returns only those of this sequence which
 |          lie on the original tile.
 |          3. by repeating the process till the number obtained matches the number
 |          requested, we obtain nsamples on the tile.
 |          4. The method works as long as the radius is large enough so that
 |          corners of the tile are not outside the circle sampled.
 |  
 |  tileIDsForSN(self, ra, dec)
 |      Parameters
 |      ----------
 |      ra : `numpyp.ndarray` or float, degrees, mandatory
 |      dec : `numpy.ndarray` or float, degrees, mandatory
 |  
 |  tilesForPointing(self, pointing, alltiles=None, **kwargs)
 |      return a maximal sequence of tile ID s for a particular OpSim pointing
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  preComputedEngine
 |  
 |  preComputedMap
 |  
 |  tileIDSequence
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __abstractmethods__ = frozenset([])
 |  
 |  ----------------------------------------------------------------------
 |  Static methods inherited from opsimsummary.tessellations.Tiling:
 |  
 |  samplePatchOnSphere(phi, theta, delta, size, rng, degrees=True)
 |      Uniformly distributes samples on a patch on a sphere between
 |      phi \pm delta, and theta \pm delta on a sphere. Uniform distribution
 |      implies that the number of points in a patch of sphere is proportional
 |      to the area of the patch. Here, the coordinate system is the usual
 |      spherical coordinate system with the azimuthal angle theta going from
 |      0 degrees at the North Pole, to 90 degrees at the South Pole, through
 |      0. at the equator.
 |      
 |      This function is not equipped to handle wrap-around the ranges of theta
 |      phi and therefore does not work at the poles.
 |      
 |      Parameters
 |      ----------
 |      phi: float, mandatory, degrees
 |          center of the spherical patch in ra with range 
 |      theta: float, mandatory, degrees
 |      delta: float, mandatory, degrees
 |      size: int, mandatory
 |          number of samples
 |      seed : int, optional, defaults to 1
 |          random Seed used for generating values
 |      degrees : bool, optional, defaults to True
 |          if True, returns angles in degrees, else in
 |          radians
 |      
 |      Returns
 |      -------
 |      tuple of (phivals, thetavals) where phivals and thetavals are arrays of 
 |          size size in degrees.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from opsimsummary.tessellations.Tiling:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)


In [11]:
datadir = os.path.join(oss.__path__[0], 'example_data')
opsimdb = os.path.join(datadir, 'enigma_1189_micro.db')
healpixelizedDB = os.path.join(datadir, 'healpixels_micro.db')
#opsimdb = '/Users/rbiswas/data/LSST/OpSimData/minion_1016_sqlite.db'

In [12]:
NSIDE = 256

In [13]:
hpOpSim = oss.HealPixelizedOpSim.fromOpSimDB(opsimdb, NSIDE=NSIDE)


 reading from database sqlite:////Users/rbiswas/.local/lib/python2.7/site-packages/opsimsummary/example_data/enigma_1189_micro.db
/usr/local/miniconda/lib/python2.7/site-packages/pandas/core/indexing.py:476: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  self.obj[item] = s

In [18]:
opsout = oss.OpSimOutput.fromOpSimDB(opsimdb)


 reading from database sqlite:////Users/rbiswas/.local/lib/python2.7/site-packages/opsimsummary/example_data/enigma_1189_micro.db
SELECT * FROM Summary WHERE PROPID in (366, 364)

In [14]:
#x = np.ones(hp.nside2npix(256)) * hp.UNSEEN
#x[1] = -1
x = np.arange(hp.nside2npix(256))
hp.mollview(x, nest=True)



In [15]:
hptiles = HealpixTiles(healpixelizedOpSim=hpOpSim, nside=NSIDE)

In [16]:
from opsimsummary import HPTileVis

In [20]:
hptvis = HPTileVis(hptiles, opsout)

In [21]:
from opsimsummary import pixelsForAng, plot_south_steradian_view

In [22]:
pixelsForAng(54., -27.5, 4)


Out[22]:
array([141])

In [23]:
ra, dec = hptvis.pointingCenters(0)

In [24]:
figoverlaps = hptvis.plotTilePointings(135, projection='cyl', paddingFactors=1,
                                       query='night < 365',
                                       **dict(fill=False, color='g', alpha=0.1))


Faster evaluations with preComputedMap


In [25]:
hpchips = HealpixTiles(nside=128, preComputedMap=healpixelizedDB)

In [29]:
hpchips.pointingSequenceForTile(0)


Out[29]:
array([187059, 187073, 194374, 194375, 194419, 194421, 195238, 195240,
       195308, 195309, 196190, 196191, 196234, 196236, 196401, 196402,
       196403, 200849, 201724, 201725, 201731, 201754, 203411, 203413,
       203419, 203421, 203437, 203439, 203454, 203455, 203456, 203478,
       203480, 204359, 204360, 204373, 204375, 204430, 205282, 205298,
       206016, 206062, 206977, 210862, 210909, 210911, 210918, 211229,
       211230, 211231, 211261, 211262, 211279, 211537, 211538, 212803,
       212808, 212812, 214181, 214218, 214247, 215734, 215735, 215777,
       215778, 215912, 215913, 218393, 218394, 218813, 218849, 220581,
       220583, 220620, 220621, 225368, 225424, 230462, 230509, 230524,
       230575, 232648, 232688, 233394, 233395, 233432, 233433, 234056,
       234057, 234073, 234830, 234831, 234874, 234881, 235681, 235724,
       235733, 235760, 235779, 235805, 236380, 236383, 236434, 236435,
       239398, 239435, 243014, 243050, 244790, 246728, 246746, 248059,
       251634, 251666, 251678, 253031, 253033, 253068, 253070, 253742,
       253776, 254454, 254492, 255888, 255892, 255893, 266076, 266477,
       266478, 266489, 266490, 266497])

In [60]:
np.unique(hpchips.pointingSequenceForTile(0)).size


Out[60]:
132

In [32]:
from opsimsummary import convertToSphericalCoordinates

In [31]:
angs = opsout.summary[['fieldRA', 'fieldDec']]
ra, dec = angs.fieldRA.values, angs.fieldDec.values

In [33]:
convertToSphericalCoordinates??

In [34]:
theta, phi = convertToSphericalCoordinates(ra, dec, unit='radians')

In [35]:
vecs = hp.ang2vec(theta, phi)

In [37]:
vec = hp.pix2vec(128, 0, nest=True)

In [49]:
opsout.summary.iloc[np.abs(np.dot(vecs, vec)).argmin()].fieldID


Out[49]:
1859

In [50]:
obsHistIDsStatic = opsout.summary.query('fieldID==1859').index.values

In [52]:
def staticPoints(tileID):
    return obsHistIDsStatic

In [53]:
staticPoints(0)


Out[53]:
array([233783, 242822, 242847, 241228, 224988, 231482, 227466, 264801,
       264811, 264825, 264714, 259219, 271100, 270319, 270276, 271594,
       248626, 248582, 244304, 244350, 259175, 250707, 250675, 254369])

In [54]:
hpchipsStatic = HealpixTiles(nside=128, preComputedMap=staticPoints)

In [62]:
np.unique(hpchipsStatic.pointingSequenceForTile(0))


Out[62]:
array([224988, 227466, 231482, 233783, 241228, 242822, 242847, 244304,
       244350, 248582, 248626, 250675, 250707, 254369, 259175, 259219,
       264714, 264801, 264811, 264825, 270276, 270319, 271100, 271594])

In [24]:
hpvis = HPTileVis(hpchips, opsout)

In [25]:
fig2, tc, _ = hpvis.plotTilePointings(140785, projection='cea', paddingFactors=4,
                               drawPointings=True,
                               **dict(fill=False, color='g', alpha=1.0))


Scratch


In [47]:
figtile.savefig('HealpixTile_Pointings.pdf')

In [276]:
from opsimsummary import convertToCelestialCoordinates, healpix_boundaries, pixelsForAng
from matplotlib.patches import Polygon

In [371]:
class HPTileVis(HealpixTiles):
    def __init__(self, hpTile, opsout):
        """
        """
        self.hpTile = hpTile
        self.opsout = opsout
        self.nside = self.hpTile.nside
    
    def tileIDfromCelestialCoordinates(self, ra, dec, opsout, units='degrees'):
        """
        Parameters
        -----------
        ra : 
        dec : 
        units: {'degrees', 'radians'}
        """
        return pixelsForAng(lon=ra,lat=dec, unit=units )
    def tileCenter(self, tileID):
        theta, phi = hp.pix2ang(self.nside, tileID, nest=True)
        ra, dec = convertToCelestialCoordinates(theta, phi, input_unit='radians',
                                                output_unit='degrees')
        return ra, dec
        
    def pointingSummary(self, tileID, columns=('ditheredRA', 'ditheredDec'), 
                        allPointings=None):
        #if allPointings is None:
        #    allPointings = opsout.summary
        #    if query is not None:
        #        allPointings = allPointings.query(query)
        #    allPointings = allPointings.index.values
        obsHistIDs = self.hpTile.pointingSequenceForTile(tileID=tileID,
                                                         allPointings=allPointings)
        return self.opsout.summary.ix[obsHistIDs]#[list(columns)]
    def pointingCenters(self,
                tileID,
                raCol='ditheredRA',
                decCol='ditheredDec',
                query=None):
        summary = self.pointingSummary(tileID)#, columns=[raCol, decCol])
        
        if query is not None:
            summary = summary.query(query)
        ra = summary[raCol].apply(np.degrees).values
        dec = summary[decCol].apply(np.degrees).values
        return ra, dec
    def plotTilePointings(self, tileID, raCol='ditheredRA', decCol='ditheredDec', radius=1.75,
                          paddingFactors=1, query=None, ax=None, projection='cyl',**kwargs):
        """
        Parameters
        ----------
        
        """
        if ax is None:
            fig, ax = plt.subplots()
        padding = np.degrees(hp.max_pixrad(self.nside)) + radius
        ra_tile, dec_tile = self.tileCenter(tileID)
        
        llcrnrlat = dec_tile - padding * paddingFactors
        urcrnrlat = dec_tile + padding * paddingFactors
        llcrnrlon = ra_tile - padding * paddingFactors
        urcrnrlon = ra_tile + padding * paddingFactors
        
        m = Basemap(llcrnrlat=llcrnrlat, llcrnrlon=llcrnrlon,
                    urcrnrlat=urcrnrlat, urcrnrlon=urcrnrlon,
                    projection=projection, lon_0=ra_tile, lat_0=dec_tile,
                    ax=ax)
        
        parallels = np.linspace(llcrnrlat, urcrnrlat, 3)
        meridians = np.linspace(llcrnrlon, urcrnrlon, 3)
        m.drawparallels(parallels, labels=(1, 0, 0, 0)) #np.ones(len(parallels), dtype=bool))
        m.drawmeridians(meridians, labels=(0, 1, 1, 1)) #np.ones(len(meridians), dtype=bool))
        ra, dec = self.pointingCenters(tileID, raCol=raCol, decCol=decCol, query=query)
        lon, lat = healpix_boundaries(tileID, nside=self.nside, units='degrees',
                                      convention='celestial', step=10,
                                      nest=True)
        x, y = m(lon, lat)
        xy = zip(x, y)
        healpixels = Polygon(xy, facecolor='w',fill=False, alpha=1., edgecolor='k', lw=2)
        for ra, dec in zip(ra, dec):
            m.tissot(ra, dec, radius, 100, **kwargs)
        ax.add_patch(healpixels)
        return fig

In [365]:
tileID = pixelsForAng(54., -27.5, 4, unit='degrees')

In [366]:
tileID


Out[366]:
array([141])

In [367]:
theta, phi = hp.pix2ang(hptiles.nside, 0, nest=True)
ra, dec = oss.convertToCelestialCoordinates(theta, phi)

In [368]:



Out[368]:
(array([ 45.]), array([ 9.59406823]))

In [372]:
hptvis = HPTileVis(hptiles, opsout)

In [388]:
from palettable.colorbrewer import sequential

In [389]:
import palettable

In [ ]:
palettable

In [ ]:
from matplotlib.colorbar import

In [81]:
hptvis.plotTilePointings(, raCol='ditheredRA', decCol='ditheredDec', projection='gnom',
                         query=None,#'night <3650',
                         **dict(fill=False, color='g', alpha=1., lw=1., ls='solid'))


Out[81]:
(<matplotlib.figure.Figure at 0x10ddf5450>,
 (202.49999999999997, -30.000000000000014),
 (-46.322230670077914,
  186.17776932992206,
  -13.677769329922114,
  218.82223067007789))

In [376]:
hptvis.centers(0)


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-376-409616ab5162> in <module>()
----> 1 hptvis.centers(0)

AttributeError: 'HPTileVis' object has no attribute 'centers'

In [115]:
opsout.summary.ix[hpTileshpOpSim.pointingSequenceForTile(0, allPointings=None)][['ditheredRA', 'ditheredDec']]


Out[115]:
ditheredRA ditheredDec
obsHistID
179157 0.694620 0.013076
179167 0.694620 0.013076
179965 0.698441 0.013076
179998 0.698441 0.013076
180029 0.698441 0.013076
180068 0.698441 0.013076
181880 0.669784 0.016382
182972 0.728329 0.014223
183105 0.673605 0.016382
183107 0.728329 0.014223
183114 0.673605 0.016382
183911 0.677426 0.016382
183913 0.732150 0.014223
183946 0.677426 0.016382
183948 0.732150 0.014223
183962 0.732150 0.014223
183964 0.677426 0.016382
183989 0.677426 0.016382
183990 0.732150 0.014223
184010 0.732150 0.014223
184068 0.732150 0.014223
184871 0.764154 -0.030991
184872 0.735971 0.014223
184873 0.681247 0.016382
184985 0.681247 0.016382
184987 0.735971 0.014223
184988 0.764154 -0.030991
185002 0.764154 -0.030991
185003 0.735971 0.014223
185052 0.764154 -0.030991
... ... ...
258058 0.910659 0.028860
262233 0.656411 0.046140
262249 0.656411 0.046140
262250 0.711137 0.043981
262251 0.739337 -0.001233
262252 0.765688 0.040703
262253 0.739337 -0.001233
262254 0.711137 0.043981
262255 0.656411 0.046140
263659 0.882015 0.032167
263691 0.882015 0.032167
266074 0.893473 0.032167
266075 0.839176 0.036650
266076 0.813114 -0.005157
266077 0.786796 -0.046716
266477 0.788609 0.040703
266478 0.762245 -0.001233
266482 0.707293 0.001730
266483 0.679336 0.046140
266487 0.679336 0.046140
266488 0.734060 0.043981
266489 0.788609 0.040703
266490 0.816933 -0.005157
266491 0.842995 0.036650
266497 0.816933 -0.005157
266498 0.842995 0.036650
266500 0.897292 0.032167
269955 0.865914 0.036650
269956 0.811530 0.040703
269957 0.756984 0.043981

538 rows × 2 columns


In [ ]:


In [16]:
phi, theta = hpTileshpOpSim.positions(1, 10000)

In [ ]:


In [17]:
mapvals = np.ones(hp.nside2npix(NSIDE)) * hp.UNSEEN

In [18]:
mapvals[1] = 100

In [ ]:


In [19]:
hp.ang2pix(NSIDE, np.radians(theta), np.radians(phi), nest=True)


Out[19]:
array([13, 13, 13, ..., 13, 15, 15])

In [20]:
theta_c, phi_c = hp.pix2ang(4, 1, nest=True)

In [21]:
hp.mollview(mapvals, nest=True)
hp.projscatter(np.radians(theta), np.radians(phi), **dict(s=0.0002))
hp.projscatter(theta_c, phi_c, **dict(s=8., c='r'))


Out[21]:
<matplotlib.collections.PathCollection at 0x10d1be190>

In [22]:
%timeit hpTileshpOpSim.pointingSequenceForTile(33, allPointings=None)


100 loops, best of 3: 2.29 ms per loop

In [23]:
preCompMap = os.path.join(oss.__path__[0], 'example_data', 'healpixels_micro.db')

In [26]:
import os
os.path.exists(preCompMap)


Out[26]:
True

In [24]:
hpTilesMap = HealpixTiles(nside=1, preComputedMap=preCompMap)

In [25]:
obsHistIDs = hpTilesMap.pointingSequenceForTile(10, allPointings=None)


---------------------------------------------------------------------------
OperationalError                          Traceback (most recent call last)
<ipython-input-25-d1c704331bce> in <module>()
----> 1 obsHistIDs = hpTilesMap.pointingSequenceForTile(10, allPointings=None)

/Users/rbiswas/.local/lib/python2.7/site-packages/opsimsummary/healpixTiles.pyc in pointingSequenceForTile(self, tileID, allPointings, columns, **kwargs)
    124         obsHistIDs = None
    125         if self.preComputedMap is not None:
--> 126             obsHistIDs = self._pointingFromPrecomputedDB(tileID, tableName='simlib')
    127         elif self.hpOpSim is not None:
    128             obsHistIDs = self._pointingFromHpOpSim(tileID)

/Users/rbiswas/.local/lib/python2.7/site-packages/opsimsummary/healpixTiles.pyc in _pointingFromPrecomputedDB(self, tileID, tableName)
     90         sql = 'SELECT obsHistID FROM {0} WHERE ipix == {1}'\
     91             .format(tableName, tileID)
---> 92         return pd.read_sql_query(sql, con=self.preComputedEngine)\
     93             .values.flatten()
     94 

/usr/local/miniconda/lib/python2.7/site-packages/pandas/io/sql.pyc in read_sql_query(sql, con, index_col, coerce_float, params, parse_dates, chunksize)
    329     return pandas_sql.read_query(
    330         sql, index_col=index_col, params=params, coerce_float=coerce_float,
--> 331         parse_dates=parse_dates, chunksize=chunksize)
    332 
    333 

/usr/local/miniconda/lib/python2.7/site-packages/pandas/io/sql.pyc in read_query(self, sql, index_col, coerce_float, parse_dates, params, chunksize)
   1082         args = _convert_params(sql, params)
   1083 
-> 1084         result = self.execute(*args)
   1085         columns = result.keys()
   1086 

/usr/local/miniconda/lib/python2.7/site-packages/pandas/io/sql.pyc in execute(self, *args, **kwargs)
    973     def execute(self, *args, **kwargs):
    974         """Simple passthrough to SQLAlchemy connectable"""
--> 975         return self.connectable.execute(*args, **kwargs)
    976 
    977     def read_table(self, table_name, index_col=None, coerce_float=True,

/Users/rbiswas/soft/LSST_el_capitan/DarwinX86/sqlalchemy/1.0.8.lsst3+2/lib/python/SQLAlchemy-1.0.8-py2.7-macosx-10.6-x86_64.egg/sqlalchemy/engine/base.pyc in execute(self, statement, *multiparams, **params)
   1989 
   1990         connection = self.contextual_connect(close_with_result=True)
-> 1991         return connection.execute(statement, *multiparams, **params)
   1992 
   1993     def scalar(self, statement, *multiparams, **params):

/Users/rbiswas/soft/LSST_el_capitan/DarwinX86/sqlalchemy/1.0.8.lsst3+2/lib/python/SQLAlchemy-1.0.8-py2.7-macosx-10.6-x86_64.egg/sqlalchemy/engine/base.pyc in execute(self, object, *multiparams, **params)
    904         """
    905         if isinstance(object, util.string_types[0]):
--> 906             return self._execute_text(object, multiparams, params)
    907         try:
    908             meth = object._execute_on_connection

/Users/rbiswas/soft/LSST_el_capitan/DarwinX86/sqlalchemy/1.0.8.lsst3+2/lib/python/SQLAlchemy-1.0.8-py2.7-macosx-10.6-x86_64.egg/sqlalchemy/engine/base.pyc in _execute_text(self, statement, multiparams, params)
   1052             statement,
   1053             parameters,
-> 1054             statement, parameters
   1055         )
   1056         if self._has_events or self.engine._has_events:

/Users/rbiswas/soft/LSST_el_capitan/DarwinX86/sqlalchemy/1.0.8.lsst3+2/lib/python/SQLAlchemy-1.0.8-py2.7-macosx-10.6-x86_64.egg/sqlalchemy/engine/base.pyc in _execute_context(self, dialect, constructor, statement, parameters, *args)
   1144                 parameters,
   1145                 cursor,
-> 1146                 context)
   1147 
   1148         if self._has_events or self.engine._has_events:

/Users/rbiswas/soft/LSST_el_capitan/DarwinX86/sqlalchemy/1.0.8.lsst3+2/lib/python/SQLAlchemy-1.0.8-py2.7-macosx-10.6-x86_64.egg/sqlalchemy/engine/base.pyc in _handle_dbapi_exception(self, e, statement, parameters, cursor, context)
   1339                 util.raise_from_cause(
   1340                     sqlalchemy_exception,
-> 1341                     exc_info
   1342                 )
   1343             else:

/Users/rbiswas/soft/LSST_el_capitan/DarwinX86/sqlalchemy/1.0.8.lsst3+2/lib/python/SQLAlchemy-1.0.8-py2.7-macosx-10.6-x86_64.egg/sqlalchemy/util/compat.pyc in raise_from_cause(exception, exc_info)
    197             exc_info = sys.exc_info()
    198         exc_type, exc_value, exc_tb = exc_info
--> 199         reraise(type(exception), exception, tb=exc_tb)
    200 
    201 if py3k:

/Users/rbiswas/soft/LSST_el_capitan/DarwinX86/sqlalchemy/1.0.8.lsst3+2/lib/python/SQLAlchemy-1.0.8-py2.7-macosx-10.6-x86_64.egg/sqlalchemy/engine/base.pyc in _execute_context(self, dialect, constructor, statement, parameters, *args)
   1137                         statement,
   1138                         parameters,
-> 1139                         context)
   1140         except Exception as e:
   1141             self._handle_dbapi_exception(

/Users/rbiswas/soft/LSST_el_capitan/DarwinX86/sqlalchemy/1.0.8.lsst3+2/lib/python/SQLAlchemy-1.0.8-py2.7-macosx-10.6-x86_64.egg/sqlalchemy/engine/default.pyc in do_execute(self, cursor, statement, parameters, context)
    448 
    449     def do_execute(self, cursor, statement, parameters, context=None):
--> 450         cursor.execute(statement, parameters)
    451 
    452     def do_execute_no_params(self, cursor, statement, context=None):

OperationalError: (sqlite3.OperationalError) no such table: simlib [SQL: 'SELECT obsHistID FROM simlib WHERE ipix == 10']

In [28]:
from sqlalchemy import create_engine

In [36]:
engine = create_engine('sqlite:////' + preCompMap)

In [37]:
import pandas as pd

In [38]:
df = pd.read_sql_query('SELECT * FROM simlib Limit 5', engine)


---------------------------------------------------------------------------
OperationalError                          Traceback (most recent call last)
<ipython-input-38-9d8a6e1fe67f> in <module>()
----> 1 df = pd.read_sql_query('SELECT * FROM simlib Limit 5', engine)

/usr/local/miniconda/lib/python2.7/site-packages/pandas/io/sql.pyc in read_sql_query(sql, con, index_col, coerce_float, params, parse_dates, chunksize)
    329     return pandas_sql.read_query(
    330         sql, index_col=index_col, params=params, coerce_float=coerce_float,
--> 331         parse_dates=parse_dates, chunksize=chunksize)
    332 
    333 

/usr/local/miniconda/lib/python2.7/site-packages/pandas/io/sql.pyc in read_query(self, sql, index_col, coerce_float, parse_dates, params, chunksize)
   1082         args = _convert_params(sql, params)
   1083 
-> 1084         result = self.execute(*args)
   1085         columns = result.keys()
   1086 

/usr/local/miniconda/lib/python2.7/site-packages/pandas/io/sql.pyc in execute(self, *args, **kwargs)
    973     def execute(self, *args, **kwargs):
    974         """Simple passthrough to SQLAlchemy connectable"""
--> 975         return self.connectable.execute(*args, **kwargs)
    976 
    977     def read_table(self, table_name, index_col=None, coerce_float=True,

/Users/rbiswas/soft/LSST_el_capitan/DarwinX86/sqlalchemy/1.0.8.lsst3+2/lib/python/SQLAlchemy-1.0.8-py2.7-macosx-10.6-x86_64.egg/sqlalchemy/engine/base.pyc in execute(self, statement, *multiparams, **params)
   1989 
   1990         connection = self.contextual_connect(close_with_result=True)
-> 1991         return connection.execute(statement, *multiparams, **params)
   1992 
   1993     def scalar(self, statement, *multiparams, **params):

/Users/rbiswas/soft/LSST_el_capitan/DarwinX86/sqlalchemy/1.0.8.lsst3+2/lib/python/SQLAlchemy-1.0.8-py2.7-macosx-10.6-x86_64.egg/sqlalchemy/engine/base.pyc in execute(self, object, *multiparams, **params)
    904         """
    905         if isinstance(object, util.string_types[0]):
--> 906             return self._execute_text(object, multiparams, params)
    907         try:
    908             meth = object._execute_on_connection

/Users/rbiswas/soft/LSST_el_capitan/DarwinX86/sqlalchemy/1.0.8.lsst3+2/lib/python/SQLAlchemy-1.0.8-py2.7-macosx-10.6-x86_64.egg/sqlalchemy/engine/base.pyc in _execute_text(self, statement, multiparams, params)
   1052             statement,
   1053             parameters,
-> 1054             statement, parameters
   1055         )
   1056         if self._has_events or self.engine._has_events:

/Users/rbiswas/soft/LSST_el_capitan/DarwinX86/sqlalchemy/1.0.8.lsst3+2/lib/python/SQLAlchemy-1.0.8-py2.7-macosx-10.6-x86_64.egg/sqlalchemy/engine/base.pyc in _execute_context(self, dialect, constructor, statement, parameters, *args)
   1144                 parameters,
   1145                 cursor,
-> 1146                 context)
   1147 
   1148         if self._has_events or self.engine._has_events:

/Users/rbiswas/soft/LSST_el_capitan/DarwinX86/sqlalchemy/1.0.8.lsst3+2/lib/python/SQLAlchemy-1.0.8-py2.7-macosx-10.6-x86_64.egg/sqlalchemy/engine/base.pyc in _handle_dbapi_exception(self, e, statement, parameters, cursor, context)
   1339                 util.raise_from_cause(
   1340                     sqlalchemy_exception,
-> 1341                     exc_info
   1342                 )
   1343             else:

/Users/rbiswas/soft/LSST_el_capitan/DarwinX86/sqlalchemy/1.0.8.lsst3+2/lib/python/SQLAlchemy-1.0.8-py2.7-macosx-10.6-x86_64.egg/sqlalchemy/util/compat.pyc in raise_from_cause(exception, exc_info)
    197             exc_info = sys.exc_info()
    198         exc_type, exc_value, exc_tb = exc_info
--> 199         reraise(type(exception), exception, tb=exc_tb)
    200 
    201 if py3k:

/Users/rbiswas/soft/LSST_el_capitan/DarwinX86/sqlalchemy/1.0.8.lsst3+2/lib/python/SQLAlchemy-1.0.8-py2.7-macosx-10.6-x86_64.egg/sqlalchemy/engine/base.pyc in _execute_context(self, dialect, constructor, statement, parameters, *args)
   1137                         statement,
   1138                         parameters,
-> 1139                         context)
   1140         except Exception as e:
   1141             self._handle_dbapi_exception(

/Users/rbiswas/soft/LSST_el_capitan/DarwinX86/sqlalchemy/1.0.8.lsst3+2/lib/python/SQLAlchemy-1.0.8-py2.7-macosx-10.6-x86_64.egg/sqlalchemy/engine/default.pyc in do_execute(self, cursor, statement, parameters, context)
    448 
    449     def do_execute(self, cursor, statement, parameters, context=None):
--> 450         cursor.execute(statement, parameters)
    451 
    452     def do_execute_no_params(self, cursor, statement, context=None):

OperationalError: (sqlite3.OperationalError) no such table: simlib [SQL: 'SELECT * FROM simlib Limit 5']

In [35]:
preCompMap


Out[35]:
'/Users/rbiswas/.local/lib/python2.7/site-packages/opsimsummary/example_data/healpixels_micro.db'

In [35]:
%timeit hpOpSim.obsHistIdsForTile(34)


100 loops, best of 3: 2.49 ms per loop

In [36]:
hpTiles = HealpixTiles(healpixelizedOpSim=hpOpSim)

In [37]:
hpTiles.pointingSequenceForTile(34, allPointings=None)


Out[37]:
array([], dtype=int64)

In [390]:
df = opsout.summary.copy()

In [393]:
df.fieldID.unique().size


Out[393]:
2264

In [398]:
df.query('fieldID == 744')[['fieldRA', 'fieldDec', 'ditheredRA', 'ditheredDec', 'expMJD', 'filter']].head()


Out[398]:
fieldRA fieldDec ditheredRA ditheredDec expMJD filter
obsHistID
175159 0.0 -0.794553 6.277736 -0.821004 49573.415395 u
175744 0.0 -0.794553 0.000000 -0.821004 49574.225892 u
175746 0.0 -0.794553 0.000000 -0.821004 49574.226725 u
175748 0.0 -0.794553 0.000000 -0.821004 49574.227570 u
175750 0.0 -0.794553 0.000000 -0.821004 49574.228403 u

In [399]:
df.query('fieldID == 744')['ditheredDec'] = df.query('fieldID == 744')['fieldDec']


/usr/local/miniconda/lib/python2.7/site-packages/ipykernel/__main__.py:1: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  if __name__ == '__main__':

In [405]:
def fixdec(mydf, fieldIDs):
    return mydf.fieldID.apply(lambda x: x in fieldIDs)

In [407]:
fixdec(df, (744, 1427, 290)).astype(np.int) * df.fieldRA + (1.0 - fixdec(df, (744, 1427, 290)).astype(np.int))


Out[407]:
obsHistID
171077    0
171078    0
171079    0
171080    0
171081    0
171082    0
171083    0
171084    0
171085    0
171086    0
171087    0
171088    0
171089    0
171090    0
171091    0
171092    0
171093    0
171094    0
171095    0
171096    0
171097    0
171098    0
171099    0
171100    0
171101    0
171102    0
171103    0
171104    0
171105    0
171106    0
         ..
272045    1
272046    1
272047    1
272048    1
272049    1
272050    1
272051    1
272052    1
272053    1
272054    1
272405    0
272406    0
272407    0
272408    0
272409    0
272410    0
272411    0
272412    0
272413    0
272414    0
272415    0
272416    0
272417    0
272418    0
272419    0
272420    0
272421    0
272422    0
272423    0
272424    0
Name: fieldID, dtype: int64

In [400]:
df.query('fieldID == 744')[['fieldRA', 'fieldDec', 'ditheredRA', 'ditheredDec', 'expMJD', 'filter']].head()


Out[400]:
fieldRA fieldDec ditheredRA ditheredDec expMJD filter
obsHistID
175159 0.0 -0.794553 6.277736 -0.821004 49573.415395 u
175744 0.0 -0.794553 0.000000 -0.821004 49574.225892 u
175746 0.0 -0.794553 0.000000 -0.821004 49574.226725 u
175748 0.0 -0.794553 0.000000 -0.821004 49574.227570 u
175750 0.0 -0.794553 0.000000 -0.821004 49574.228403 u

In [54]:
df = opsout.summary.copy()

In [55]:
grouped = df.groupby('propID')

In [59]:
grouped.groups.keys()


Out[59]:
[364, 366]

In [62]:
grouped.get_group(366).fieldRA


Out[62]:
obsHistID
231872    0.925184
231873    0.925184
231874    0.925184
231875    0.925184
231876    0.925184
231877    0.925184
231878    0.925184
231879    0.925184
231880    0.925184
231881    0.925184
231882    0.925184
231883    0.925184
231884    0.925184
231885    0.925184
231886    0.925184
231887    0.925184
231888    0.925184
231889    0.925184
231890    0.925184
231892    0.925184
231893    0.925184
231894    0.925184
231895    0.925184
231896    0.925184
231897    0.925184
231898    0.925184
231899    0.925184
231900    0.925184
231902    0.925184
231903    0.925184
            ...   
272045    0.925184
272046    0.925184
272047    0.925184
272048    0.925184
272049    0.925184
272050    0.925184
272051    0.925184
272052    0.925184
272053    0.925184
272054    0.925184
272405    2.624318
272406    2.624318
272407    2.624318
272408    2.624318
272409    2.624318
272410    2.624318
272411    2.624318
272412    2.624318
272413    2.624318
272414    2.624318
272415    2.624318
272416    2.624318
272417    2.624318
272418    2.624318
272419    2.624318
272420    2.624318
272421    2.624318
272422    2.624318
272423    2.624318
272424    2.624318
Name: fieldRA, dtype: float64

In [ ]: