Esempio n. 1
0
    def __init__(self, ws, name='', var_range=None, var=None, max_var=None, exp=None, fracs=None):
        """Initialize TruncExponential instance

        :param ROOT.RooWorkspace ws: RooFit workspace
        :param str name: name of model
        :param tuple var_range: range of PDF variable: (min, max)
        :param tuple var: PDF variable: (name, value)
        :param tuple max_var: variable upper limit of PDF range: (name, value)
        :param list exp: list of exponential-rate parameters: [(name0, value0), (name1, value1), ...]
        :param list fracs: list of exponential-fraction parameters: [(name0, value0), ...]
        """

        # load Eskapade RooFit library
        roofit_utils.load_libesroofit()

        # initialize RooFitModel instance
        super(TruncExponential, self).__init__(ws, name)
        self._pdf_name = self.name

        # set attributes
        self._var_range = (float(var_range[0]), float(var_range[1])) if var_range else (0., 1.)
        self._var = (str(var[0]), float(var[1])) if var else ('var', 0.)
        self._max_var = (str(max_var[0]), float(max_var[1])) if max_var else ('max_var', 1.)
        self._exp = [(str(v[0]), float(v[1])) for v in exp] if exp else [('exp', -1.)]
        self._fracs = [(str(v[0]), float(v[1])) for v in fracs] if fracs else []
Esempio n. 2
0
    def initialize(self):
        """Initialize the link."""
        # check input arguments
        self.check_arg_types(pages_key=str)

        if isinstance(self.copy_into_ws, str):
            self.copy_into_ws = [self.copy_into_ws]
        assert isinstance(
            self.copy_into_ws,
            list), 'copy_into_ws needs to be a string or list of strings.'

        if isinstance(self.copy_into_ds, str):
            self.copy_into_ds = [self.copy_into_ds]
        assert isinstance(
            self.copy_into_ds,
            list), 'copy_into_ds needs to be a string or list of strings.'

        # read report templates
        with open(resources.template('df_summary_report.tex')) as templ_file:
            self.report_template = templ_file.read()
        with open(resources.template(
                'df_summary_report_page.tex')) as templ_file:
            self.page_template = templ_file.read()
        with open(
                resources.template('df_summary_table_page.tex')) as templ_file:
            self.table_template = templ_file.read()

        self._process_results_path()

        # make sure Eskapade RooFit library is loaded for fitting (for plotting correlation matrix)
        if self._fit:
            roofit_utils.load_libesroofit()

        return StatusCode.Success
Esempio n. 3
0
    def initialize(self):
        """Initialize the link.."""
        # check input arguments
        self.check_arg_types(read_key=str, binning_name=str)
        self.check_arg_vals('read_key', 'binning_name', 'var_number_of_bins')

        # make sure Eskapade RooFit library is loaded for the RooNonCentralBinning class
        roofit_utils.load_libesroofit()

        return StatusCode.Success
Esempio n. 4
0
    def initialize(self):
        """Initialize WsUtils"""

        # check input arguments
        self.check_arg_types(pages_key=str)

        if isinstance(self.copy_into_ws, str):
            self.copy_into_ws = [self.copy_into_ws]
        assert isinstance(self.copy_into_ws, list), 'copy_into_ws needs to be a string or list of strings.'

        if isinstance(self.copy_into_ds, str):
            self.copy_into_ds = [self.copy_into_ds]
        assert isinstance(self.copy_into_ds, list), 'copy_into_ds needs to be a string or list of strings.'

        # get I/O configuration
        io_conf = ProcessManager().service(ConfigObject).io_conf()

        # read report templates
        with open(core.persistence.io_path('templates', io_conf, 'df_summary_report.tex')) as templ_file:
            self.report_template = templ_file.read()
        with open(core.persistence.io_path('templates', io_conf, 'df_summary_report_page.tex')) as templ_file:
            self.page_template = templ_file.read()
        with open(persistence.io_path('templates', io_conf, 'df_summary_table_page.tex')) as templ_file:
            self.table_template = templ_file.read()

        # get path to results directory
        if not self.results_path:
            # get I/O configuration
            io_conf = ProcessManager().service(ConfigObject).io_conf()
            self.results_path = core.persistence.io_path('results_data', io_conf, 'report')

        # check if output directory exists
        if os.path.exists(self.results_path):
            # check if path is a directory
            if not os.path.isdir(self.results_path):
                self.log().critical('output path "%s" is not a directory', self.results_path)
                raise AssertionError('output path is not a directory')
        else:
            # create directory
            self.log().debug('Making output directory %s', self.results_path)
            os.makedirs(self.results_path)

        # make sure Eskapade RooFit library is loaded for fitting (for plotting correlation matrix)
        if self._fit:
            roofit_utils.load_libesroofit()

        return StatusCode.Success
Esempio n. 5
0
    def __init__(self, ws, name='', load_libesroofit=False):
        """Initialize model instance.

        :param ROOT.RooWorkspace ws: RooFit workspace
        :param str name: name of model
        :param bool load_libesroofit: load Eskapade RooFit library upon initialization (default is False)
        """
        # check workspace
        if not isinstance(ws, ROOT.RooWorkspace):
            raise TypeError('invalid workspace specified (type "{}")'.format(
                ws.__class__.__name__))

        # set attributes
        self._name = str(name) if name else self.__class__.__name__
        self._ws = ws
        self._is_built = False
        self._pdf_name = None

        if load_libesroofit:
            # load Eskapade RooFit library
            roofit_utils.load_libesroofit()
Esempio n. 6
0
    def test_load_libesroofit(self, mock_objects, mock_load,
                              mock_get_libraries):
        """Test loading Eskapade RooFit library"""

        # set custom object attributes
        ROOT.MyCustomClass = mock.Mock(name='MyCustomClass')
        ROOT.MyCustomNamespace = mock.Mock(name='MyCustomNamespace')

        # the Eskapade RooFit library name
        esroofit_lib_base = 'libesroofit'
        if sys.platform == 'darwin':
            esroofit_lib_ext = '.dylib'
        else:
            esroofit_lib_ext = '.so'
        esroofit_lib_name = esroofit_lib_base + esroofit_lib_ext

        # test normal build/load
        mock_objects.__iter__ = lambda s: iter(
            ('MyCustomClass', ('MyCustomNamespace', 'MyCustomFunction')))
        mock_load.return_value = 0
        mock_get_libraries.return_value = 'lib/libmylib.so'
        load_libesroofit()
        mock_load.assert_called_once_with(resources.lib(esroofit_lib_name))
        mock_load.reset_mock()

        # test with loaded library
        mock_get_libraries.return_value = 'lib/libmylib.so lib/{}'.format(
            esroofit_lib_name)
        load_libesroofit()
        mock_load.assert_not_called()
        mock_get_libraries.return_value = 'lib/libmylib.so'
        mock_load.reset_mock()

        # test failed load
        mock_load.return_value = -1
        with self.assertRaises(RuntimeError):
            load_libesroofit()
        mock_load.return_value = 0
        mock_load.reset_mock()

        # test missing custom class
        mock_objects.__iter__ = lambda s: iter(('NoSuchClass', ))
        with self.assertRaises(RuntimeError):
            load_libesroofit()

        # delete custom class attribute
        del ROOT.MyCustomClass
Esempio n. 7
0
Licence:
    Redistribution and use in source and binary forms, with or without
    modification, are permitted according to the terms listed in the file
    LICENSE.
"""

from eskapade import ConfigObject, Chain
from eskapade import process_manager
from eskapade import root_analysis
from eskapade.core import persistence
from eskapade.logger import Logger
from eskapade.root_analysis import roofit_utils

# make sure Eskapade RooFit library is loaded
roofit_utils.load_libesroofit()

import ROOT
from ROOT import RooFit

logger = Logger()

logger.debug(
    'Now parsing configuration file esk411_weibull_predictive_maintenance')

#########################################################################################
# --- minimal analysis information

settings = process_manager.service(ConfigObject)
settings['analysisName'] = 'esk411_weibull_predictive_maintenance'
settings['version'] = 0
Esempio n. 8
0
    def initialize(self):
        """Initialize the link."""
        # check input arguments
        self.check_arg_types(read_key=str,
                             significance_key=str,
                             sk_significance_map=str,
                             sk_residuals_map=str,
                             sk_residuals_overview=str,
                             default_number_of_bins=int,
                             nsims_per_significance=int,
                             prefix=str,
                             z_threshold=float,
                             pages_key=str,
                             client_pages_key=str,
                             hist_dict_key=str)
        self.check_arg_types(recurse=True, allow_none=True, columns=str)
        self.check_arg_types(recurse=True, allow_none=True, x_columns=str)
        self.check_arg_types(recurse=True, allow_none=True, y_columns=str)
        self.check_arg_types(recurse=True,
                             allow_none=True,
                             ignore_categories=str)
        self.check_arg_types(recurse=True,
                             allow_none=True,
                             var_ignore_categories=str)
        self.check_arg_vals('read_key')
        self.check_arg_vals('significance_key')

        if self.map_to_original and not isinstance(self.map_to_original, str) \
                and not isinstance(self.map_to_original, dict):
            raise TypeError(
                'map_to_original needs to be a dict or string (to fetch a dict from the datastore)'
            )

        # read report templates
        with open(resources.template('df_summary_report.tex')) as templ_file:
            self.report_template = templ_file.read()
        with open(resources.template(
                'df_summary_report_page.tex')) as templ_file:
            self.page_template = templ_file.read()
        with open(
                resources.template('df_summary_table_page.tex')) as templ_file:
            self.table_template = templ_file.read()

        self._process_results_path()
        self._process_prefix()

        # check provided columns
        if self.columns:
            assert not self.x_columns and not self.y_columns, 'Set either columns OR x_columns and y_columns.'
        if self.x_columns:
            assert not self.columns and self.y_columns, 'Set either columns OR x_columns and y_columns.'

        # check that var_ignore_categories are set correctly.
        for col, ic in self.var_ignore_categories.items():
            if isinstance(ic, str):
                self.var_ignore_categories[col] = [ic]
            elif not isinstance(ic, list):
                raise TypeError(
                    'var_ignore_categories key "{}" needs to be a string or list of strings'
                    .format(col))

        # load roofit classes
        roofit_utils.load_libesroofit()

        return StatusCode.Success
Esempio n. 9
0
    def initialize(self):
        """Initialize UncorrelationHypothesisTester"""

        # check input arguments
        self.check_arg_types(read_key=str, significance_key=str, sk_significance_map=str, sk_residuals_map=str,
                             sk_residuals_overview=str, default_number_of_bins=int, nsims_per_significance=int, prefix=str,
                             z_threshold=float, pages_key=str, clientpages_key=str, hist_dict_key=str)
        self.check_arg_types(recurse=True, allow_none=True, columns=str)
        self.check_arg_types(recurse=True, allow_none=True, x_columns=str)
        self.check_arg_types(recurse=True, allow_none=True, y_columns=str)
        self.check_arg_types(recurse=True, allow_none=True, ignore_categories=str)
        self.check_arg_types(recurse=True, allow_none=True, var_ignore_categories=str)
        self.check_arg_vals('read_key')
        self.check_arg_vals('significance_key')

        if self.map_to_original and not isinstance(self.map_to_original, str) \
                and not isinstance(self.map_to_original, dict):
            raise TypeError('map_to_original needs to be a dict or string (to fetch a dict from the datastore)')

        # get I/O configuration
        io_conf = ProcessManager().service(ConfigObject).io_conf()

        # read report templates
        with open(persistence.io_path('templates', io_conf, 'df_summary_report.tex')) as templ_file:
            self.report_template = templ_file.read()
        with open(persistence.io_path('templates', io_conf, 'df_summary_report_page.tex')) as templ_file:
            self.page_template = templ_file.read()
        with open(persistence.io_path('templates', io_conf, 'df_summary_table_page.tex')) as templ_file:
            self.table_template = templ_file.read()

        # get path to results directory
        if not self.results_path:
            self.results_path = persistence.io_path('results_data', io_conf, 'report')
        if self.results_path and not self.results_path.endswith('/'):
            self.results_path = self.results_path + '/'

        # check if output directory exists
        if os.path.exists(self.results_path):
            # check if path is a directory
            if not os.path.isdir(self.results_path):
                self.log().critical('output path "%s" is not a directory', self.results_path)
                raise AssertionError('output path is not a directory')
        else:
            # create directory
            self.log().debug('Making output directory "%s"', self.results_path)
            os.makedirs(self.results_path)

        # prefix for file storage
        if self.prefix and not self.prefix.endswith('_'):
            self.prefix = self.prefix + '_'

        # check provided columns
        if len(self.columns):
            assert len(self.x_columns) == 0 and len(self.y_columns) == 0, \
                'Set either columns OR x_columns and y_columns.'
        if len(self.x_columns):
            assert len(self.columns) == 0 and len(self.y_columns) > 0, \
                'Set either columns OR x_columns and y_columns.'
        self._all_columns = []

        # check that var_ignore_categories are set correctly.
        for col, ic in self.var_ignore_categories.items():
            if isinstance(ic, str):
                self.var_ignore_categories[col] = [ic]
            elif not isinstance(ic, list):
                raise TypeError('var_ignore_categories key "%s" needs to be a string or list of strings' % col)

        # load roofit classes
        roofit_utils.load_libesroofit()

        return StatusCode.Success