<commit_before>"""
Class for associating Healpixels with OpSim Pointings. An example of usage can
be found in `examples/ObsHistIDsForTile`
"""
from __future__ import print_function, absolute_import, division
import numpy as np
import healpy as hp
import pandas as pd
from scipy.sparse import csr_matrix
from itertools import repeat 
import sqlite3
from .opsim_out import OpSimOutput

__all__  = ['addVec', 'HealPixelizedOpSim']

def addVec(df, raCol='ditheredRA', decCol='ditheredDec'):
    """
    Add a column of vectors to the dataFrame df

    Parameters
    ----------
    df : `pd.DataFrame`
        dataframe with two columns raCol and decCol having ra,
        dec in radians.
    raCol : string, optional, defaults to 'ditheredRA'
        column name for the column which has ra values
    decCol : string, optional, defaults to 'ditheredDec'
        column name for the column which has dec values
    """
    thetas  = - df[decCol] + np.pi /2.
    phis = df[raCol]
    df['vec'] = list(hp.ang2vec(thetas, phis))

class HealPixelizedOpSim(object):
    """
    Class to associate opsim pointings represented as records indexed by an
    integer variable obsHistID, with a set of healpixel tileIds. This class
    computes the (maximal set) of healpixel IDs associated with a certain
    pointing, as also the set of pointings associated with a healpixel ID.


    Parameters
    ----------
    opsimDF : `pd.DataFrame`, mandatory
        a dataframe representing the OpSim records of interest. The mandatory
        columns are an index column (obsHistID), raCol (specified by raCol), 
        dec Col (specified as decCol)
    raCol : string, defaults to 'ditheredRa', col should have units of radians
        column name for column of ras to use 
    decCol : string, defaults to 'ditheredDec', col should have units of radians
        column name for column of dec to use
    NSIDE : integer, `healpy.NSIDE`
        `NSIDE` for healpix giving rise to 12NSIDE **2 pixels on the sphere
    vecColName : string, optional, defaults to 'vec'
        column name where 3D vectors are computed corresponding to the angles
        of the pointing direction of the OpSim record.
    fieldRadius : float, optional, defaults to 1.75, units is degrees
        radius of the field in degrees

    Methods
    -------
    """

    def __init__(self, opsimDF, raCol='ditheredRA', decCol='ditheredDec',
                 NSIDE=1,
                 vecColName='vec',  fieldRadius=1.75):

        self.raCol = raCol
        self.decCol = decCol
        self.opsimdf = opsimDF.reset_index()
        self.cols = opsimDF.columns
        self.vecColName = vecColName
        self.validateDF()
        self._fieldRadius = np.radians(fieldRadius)

        if vecColName not in self.cols:
            addVec(self.opsimdf)
        self.nside = NSIDE
        self.nested = True
        self._rowdata = None
        self._coldata = None
        self._spmat = None

    @classmethod
    def fromOpSimDB(cls, opSimDBpath, subset='combined', propIDs=None,
                    NSIDE=256, raCol='ditheredRA', decCol='ditheredDec',
                    fieldRadius=1.75):
        """
        Parameters
        ----------
        opSimDBpath : 
        subset :
        propIDs :
        raCol :
        decCol :
        NSIDE :
        fieldRadius :

        Returns
        -------
        instance of the class
        """
        tableNames = ('Summary', 'Proposal')
        subset = subset
        propIDs = propIDs
        dbName = opSimDBpath

        opsimout = OpSimOutput

    
        
        
    @classmethod
    def fromOpSimHDF(self, opsimHDF):
        pass
    def obsHistIdsForTile(self, tileID):
        """
        return a `np.ndarray` of obsHistID values that intersect with the
        healpix tileID.
        """
        inds = self.sparseMat.getcol(tileID).nonzero()[0]
        return self.opsimdf.ix[inds, 'obsHistID'].values

    @property
    def sparseMat(self):
        """
        Sparse Matrix representation of the association between the obsHistIDs
        and healpix tileIDs.<commit_msg>Added classmethods to healpix.py 	modified:   opsimsummary/healpix.py<commit_after>"""
Class for associating Healpixels with OpSim Pointings. An example of usage can
be found in `examples/ObsHistIDsForTile`
"""
from __future__ import print_function, absolute_import, division
import numpy as np
import healpy as hp
import pandas as pd
from scipy.sparse import csr_matrix
from itertools import repeat 
import sqlite3
from .opsim_out import OpSimOutput

__all__  = ['addVec', 'HealPixelizedOpSim']

def addVec(df, raCol='ditheredRA', decCol='ditheredDec'):
    """
    Add a column of vectors to the dataFrame df

    Parameters
    ----------
    df : `pd.DataFrame`
        dataframe with two columns raCol and decCol having ra,
        dec in radians.
    raCol : string, optional, defaults to 'ditheredRA'
        column name for the column which has ra values
    decCol : string, optional, defaults to 'ditheredDec'
        column name for the column which has dec values
    """
    thetas  = - df[decCol] + np.pi /2.
    phis = df[raCol]
    df['vec'] = list(hp.ang2vec(thetas, phis))

class HealPixelizedOpSim(object):
    """
    Class to associate opsim pointings represented as records indexed by an
    integer variable obsHistID, with a set of healpixel tileIds. This class
    computes the (maximal set) of healpixel IDs associated with a certain
    pointing, as also the set of pointings associated with a healpixel ID.


    Parameters
    ----------
    opsimDF : `pd.DataFrame`, mandatory
        a dataframe representing the OpSim records of interest. The mandatory
        columns are an index column (obsHistID), raCol (specified by raCol), 
        dec Col (specified as decCol)
    raCol : string, defaults to 'ditheredRa', col should have units of radians
        column name for column of ras to use 
    decCol : string, defaults to 'ditheredDec', col should have units of radians
        column name for column of dec to use
    NSIDE : integer, `healpy.NSIDE`
        `NSIDE` for healpix giving rise to 12NSIDE **2 pixels on the sphere
    vecColName : string, optional, defaults to 'vec'
        column name where 3D vectors are computed corresponding to the angles
        of the pointing direction of the OpSim record.
    fieldRadius : float, optional, defaults to 1.75, units is degrees
        radius of the field in degrees

    Methods
    -------
    """

    def __init__(self, opsimDF, raCol='ditheredRA', decCol='ditheredDec',
                 NSIDE=1,
                 vecColName='vec',  fieldRadius=1.75):

        self.raCol = raCol
        self.decCol = decCol
        self.opsimdf = opsimDF.reset_index()
        self.cols = opsimDF.columns
        self.vecColName = vecColName
        self.validateDF()
        self._fieldRadius = np.radians(fieldRadius)

        if vecColName not in self.cols:
            addVec(self.opsimdf)
        self.nside = NSIDE
        self.nested = True
        self._rowdata = None
        self._coldata = None
        self._spmat = None

    @classmethod
    def fromOpSimDB(cls, opSimDBpath, subset='combined', propIDs=None,
                    NSIDE=256, raCol='ditheredRA', decCol='ditheredDec',
                    fieldRadius=1.75,  vecColName='vec'):
        """
        Parameters
        ----------
        opSimDBpath : 
        subset :
        propIDs :
        raCol :
        decCol :
        NSIDE :
        fieldRadius :

        Returns
        -------
        instance of the class
        """
        tableNames = ('Summary', 'Proposal')
        subset = subset
        propIDs = propIDs
        dbName = opSimDBpath

        opsimout = OpSimOutput.fromOpSimDB(opSimDBpath, subset=subset,
                                           tableNames=tableNames,
                                           propIDs=propIDs)
        summary = opsimout.summary 
        return cls(opsimDF=summary, raCol=raCol, decCol=decCol,
                 NSIDE=NSIDE, vecColName=vecColName,
                 fieldRadius=fieldRadius)


    
        
        
    @classmethod
    def fromOpSimHDF(cls, opSimHDF, subset='combined', propIDs=None,
                    NSIDE=256, raCol='ditheredRA', decCol='ditheredDec',
                    fieldRadius=1.75,  vecColName='vec'):
        """
        """
        tableNames = ('Summary', 'Proposal')
        subset = subset
        propIDs = propIDs
        opsimHDF = opsimHDF
        
        opsimout = OpSimOutput.fromOpSimHDF(opSimHDF, subset=subset,
                                           tableNames=tableNames,
                                           propIDs=propIDs)
        summary = opsimout.summary 
        return cls(opsimDF=summary, raCol=raCol, decCol=decCol,
                 NSIDE=NSIDE, vecColName=vecColName,
                 fieldRadius=fieldRadius)

        
    def obsHistIdsForTile(self, tileID):
        """
        return a `np.ndarray` of obsHistID values that intersect with the
        healpix tileID.
        """
        inds = self.sparseMat.getcol(tileID).nonzero()[0]
        return self.opsimdf.ix[inds, 'obsHistID'].values

    @property
    def sparseMat(self):
        """
        Sparse Matrix representation of the association between the obsHistIDs
        and healpix tileIDs.
{'fraction_non_alphanumeric': 0.08213750267723281, 'fraction_numerical': 0.005140286999357464, 'mean_word_length': 2.1550675675675675, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2723787', 'n_tokens_mistral': 2694, 'n_tokens_neox': 2590, 'n_words': 846}