<commit_before>"""
A class to download the truth parameters of objects and build light curves
from them.
"""

from __future__ import absolute_import, division, print_function
"""
Module to obtain truth values and truth light curves from the catsim database
"""
import numpy as np
import pandas as pd
import lsst.sims.catUtils.baseCatalogModels as bcm
from lsst.sims.catUtils.supernovae import SNObject
# import pymssql
# import os
# from lsst.utils import getPackageDir
# from lsst.daf.persistence import DbAuth


class RefLightCurves(object):
    """
    Class to connect to the database tables on fatboy and obtain reference
    light curves

    Parameters
    ----------
    tableName: string, mandatory
        case insensitive string name of table on database to connect to
        for model parameters of astrophysical objects
    idCol: string, optional, defaults to 'snid'
        column name of Index on the table
    columns: tuple of strings, optional, defaults to values for SN
        tuple of strings that completely specify the truth values for
        the astrophysical object
    dbConnection: `pymssql.connection` instance, mandatory
        connection to the database where the relevant tables of catsim
        objects are stored
    dbCursor: `pymssql.connection.cursor` instnce, optional, defaults to None
        cursor to the DataBase Connection. If None, a new cursor is obtained
        from self.dbConnection
    idSequence: sequence of one dimension, optional, defaults to None
        sequence of unique ids in the catsim universe indexing the
        astrophysical objects in the database.

    Examples
    --------
    >>> reflc = RefLightCurves(idSequence=(6001163623700, 6000324908000),
                               tableName='TwinkSN',
                               dbConnection=DBConnection,
                               dbCursor=db) # doctest: +SKIP
    """
    def __init__(self,
                 tableName,
                 idCol='snid',
                 columns=('snid', 'redshift', 'snra', 'sndec', 't0', 'x0',
                          'x1', 'c'),
                 dbConnection=None,
                 dbCursor=None,
                 idSequence=None):

        self.columns = columns
        self.dbConnection = dbConnection
        self._dbCursor = dbCursor
        self._idSequence = idSequence
        self.columns = columns
        self.idCol = idCol
        self.tableName = tableName
        self._idvals = None
        self.objectID = 42

    @property
    def dbCursor(self):
        if self._dbCursor is None:
            self._dbCursor = self.dbConnection.cursor()
        return self._dbCursor

    @staticmethod
    def uniqueIDtoTableId(uniqueID, objTypeID, nshift=10):
        id = uniqueID - objTypeID
        return np.right_shift(id, nshift) 

    @property
    def idSequence(self):
        if self._idSequence is None:
            return None
        x = np.asarray(self._idSequence)
        return self.uniqueIDtoTableId(x, objTypeID=42, nshift=10)


    def allIdinTable(self, sqlconstraint='', chunksize=None):
        """
        return a `pd.Series`of all IDs in the table with an optional
        constraint specified as sqlconstraint. If chunkSize is not
        None, but set to an integer, it returns a generator to the
        series returning chunkSize values at a time.

        Parameters
        ----------
        sqlconstraint: string, optional, defaults to ''
            sql constraint specified through a WHERE clause
        chunksize: integer, optional, defaults to None
            if not None, the return value is a generator to
            a series getting chunkSize values at a time

        Returns
        -------<commit_msg>Added connection features as requested by @jchiang 	modified:   python/desc/monitor/truth.py<commit_after>"""
A class to download the truth parameters of objects and build light curves
from them.
"""

from __future__ import absolute_import, division, print_function
"""
Module to obtain truth values and truth light curves from the catsim database
"""
import numpy as np
import pandas as pd
import lsst.sims.catUtils.baseCatalogModels as bcm
from lsst.sims.catUtils.supernovae import SNObject
import pymssql
import os
from lsst.utils import getPackageDir
from lsst.daf.persistence import DbAuth


class RefLightCurves(object):
    """
    Class to connect to the database tables on fatboy and obtain reference
    light curves

    Parameters
    ----------
    tableName: string, mandatory
        case insensitive string name of table on database to connect to
        for model parameters of astrophysical objects
    idCol: string, optional, defaults to 'snid'
        column name of Index on the table
    columns: tuple of strings, optional, defaults to values for SN
        tuple of strings that completely specify the truth values for
        the astrophysical object
    dbConnection: `pymssql.connection` instance, mandatory
        connection to the database where the relevant tables of catsim
        objects are stored
    dbCursor: `pymssql.connection.cursor` instnce, optional, defaults to None
        cursor to the DataBase Connection. If None, a new cursor is obtained
        from self.dbConnection
    idSequence: sequence of one dimension, optional, defaults to None
        sequence of unique ids in the catsim universe indexing the
        astrophysical objects in the database.

    Examples
    --------
    >>> reflc = RefLightCurves(idSequence=(6001163623700, 6000324908000),
                               tableName='TwinkSN',
                               dbConnection=DBConnection,
                               dbCursor=db) # doctest: +SKIP
    """
    def __init__(self,
                 tableName,
                 idCol='snid',
                 columns=('snid', 'redshift', 'snra', 'sndec', 't0', 'x0',
                          'x1', 'c'),
                 dbConnection=None,
                 dbCursor=None,
                 dbHostName=None,
                 idSequence=None):

        self.columns = columns
        self._dbConnection = dbConnection
        self._dbCursor = dbCursor
        self._idSequence = idSequence
        self.columns = columns
        self.idCol = idCol
        self.tableName = tableName
        self._idvals = None
        self.objectID = 42
        if dbHostName is not None:
            self.dbHostName = dbHostName

    @property
    def dbConnection(self):
        if self._dbConnection is None:
            config = bcm.BaseCatalogConfig()
            config.load(os.path.join(getPackageDir("sims_catUtils"), "config",
                                     "db.py"))

            username = DbAuth.username(config.host, config.port)
            password = DbAuth.password(config.host, config.port)
            hostname = config.host
            if self.dbHostName is not None:
                hostname = self.dbHostName
            DBConnection = pymssql.connect(user=username,
                                           password=password,
                                           host=hostname,
                                           database=config.database,
                                           port=config.port)
            return DBConnection
        else:
            return self._dbConnection

    @property
    def dbCursor(self):
        """
        Cursor to the catsim database connection. This is not reset if one
        exists.
        """
        if self._dbCursor is None:
            self._dbCursor = self.dbConnection.cursor()
        return self._dbCursor

    @staticmethod
    def uniqueIDtoTableId(uniqueID, objTypeID, nshift=10):
        """
        Given a sequence of catsim uniqueIDs, convert it to a numpy
        array of IDs in the table of the object (called refIDCol) using
        objTypeID.

        Parameters
        ----------
        uniqueID: 1D sequence of unique IDs as found in catsim/phosim Instance
            catalogs.
        objTypeID: A unique ID assigned to each class of object in the catsim
            database.
        nshift: integer, optional, defaults to 10
            Number of bit shifts, exactly the same as in catsim.

        Returns
        -------
        `numpy.ndarray` of IDs indexing the table of the particular object.

        .. note: This is an inverse of the catsim function
            `lsst.sims.catalogs_measures.Instance.get_uniqueId`. Later on I
            hope this code will be moved to a similar location.
        """
        id = np.asarray(uniqueID) - objTypeID
        return np.right_shift(id, nshift)

    @property
    def idSequence(self):
        """
        An array of IDs indexing the astrophysical objects on the catsim
        database

        Returns
        -------
        `numpy.ndarray` of IDs on a table for an astrophysical object
        """
        if self._idSequence is None:
            return None
        x = np.asarray(self._idSequence)
        return self.uniqueIDtoTableId(x, objTypeID=self.objTypeID, nshift=10)


    def allIdinTable(self, sqlconstraint='', chunksize=None):
        """
        return a `pd.Series`of all IDs in the table with an optional
        constraint specified as sqlconstraint. If chunkSize is not
        None, but set to an integer, it returns a generator to the
        series returning chunkSize values at a time.

        Parameters
        ----------
        sqlconstraint: string, optional, defaults to ''
            sql constraint specified through a WHERE clause
        chunksize: integer, optional, defaults to None
            if not None, the return value is a generator to
            a series getting chunkSize values at a time

        Returns
        -------
{'fraction_non_alphanumeric': 0.06832681621732867, 'fraction_numerical': 0.007717637373945256, 'mean_word_length': 2.0006174745291756, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 11, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5660753', 'n_tokens_mistral': 2485, 'n_tokens_neox': 2368, 'n_words': 905}