def read_from_file(self, filename): """Read configuration from a file. A filename can be passed in to load the configurations. """ parser = CustomCSSIConfigParser() try: parser.read(filename) except configparser.Error as error: raise CSSIException( "Couldn't read supplied configuration file {0}: {1}".format( filename, error)) status = False try: for option_spec in self.CONFIG_FILE_OPTIONS: was_set = self._set_config_attribute_from_option( parser, *option_spec) if was_set: status = True except ValueError as error: raise CSSIException( "Couldn't read supplied configuration file {0}: {1}".format( filename, error)) # cssi plugin options for plugin in self.plugins: if parser.has_section(plugin): self.plugin_options[plugin] = parser.get_section(plugin) status = True return status
def _calculate_ssq_total_score(self, questionnaire, filename): """Calculates the SSQ score for a particular questionnaire""" _n = 0.0 _o = 0.0 _d = 0.0 try: with open(self._get_meta_file_path(filename)) as meta_file: meta = json.load(meta_file) # Iterate through the symptoms and generate the # populate the `N`, `O` & `D` symptom scores. for s in meta["symptoms"]: if s["weight"]["N"] == 1: _n += int(questionnaire[s["symptom"]]) if s["weight"]["O"] == 1: _o += int(questionnaire[s["symptom"]]) if s["weight"]["D"] == 1: _d += int(questionnaire[s["symptom"]]) # Calculate the `N`, `O` & `D` weighted scores. # and finally compute the total score. n = _n * meta["conversion_multipliers"]["N"] o = _o * meta["conversion_multipliers"]["O"] d = _d * meta["conversion_multipliers"]["D"] ts = (_n + _o + _d) * meta["conversion_multipliers"]["TS"] return n, o, d, ts except FileNotFoundError as error: raise CSSIException( "Questionnaire meta file couldn't not be found at %s" % (self._get_meta_file_path(filename))) from error
def load_plugins(cls, modules, config, debug): """Loads the plugins Args: modules (list): List of plugins in the configuration file. config (object): An object of the Config class. debug (bool): Boolean specifying if debug is enabled or not. Returns: list: List of plugins. """ plugins = cls() plugins.debug = debug for module in modules: plugins.current_module = module __import__(module) mod = sys.modules[module] cssi_init = getattr(mod, "cssi_init", None) if not cssi_init: raise CSSIException( "The plugin module {0} doesn't contain a cssi_init function" .format(module)) options = config.get_plugin_options(module) cssi_init(plugins, options) plugins.current_module = None return plugins
def get_option(self, option_name): """Get an option from the configuration.""" # Check all the default options. for option_spec in self.CONFIG_FILE_OPTIONS: attr, where = option_spec[:2] if where == option_name: return getattr(self, attr) # Checks if it is a plugin option. plugin_name, _, key = option_name.partition(":") if key and plugin_name in self.plugins: return self.plugin_options.get(plugin_name, {}).get(key) raise CSSIException("The option was not found {0}".format(option_name))
def set_option(self, option_name, value): """Sets an option in the configuration.""" # Check all the default options. for option_spec in self.CONFIG_FILE_OPTIONS: attr, where = option_spec[:2] if where == option_name: setattr(self, attr, value) return # Checks if it is a plugin option. plugin_name, _, key = option_name.partition(":") if key and plugin_name in self.plugins: self.plugin_options.setdefault(plugin_name, {})[key] = value return raise CSSIException("The option was not found {0}".format(option_name))
def generate_cssi_score(self, tl, ts, tq, plugin_scores=None): """Generators the final CSSI score. This is the core function of the CSSI library and it takes in the scores and generates the final CSSI score for the test session. Args: tl (float): Total latency score ts (float): Total sentiment score tq (float): Total questionnaire score plugin_scores (list): A list of dictionaries containing plugin details. ex: [{"name": "heartrate.plugin", "score": 40.00}]. Returns: float: The CSSI score. Raises: CSSIException: If the calculations couldn't be completed successfully this exception will be thrown. Examples: >>> cssi.generate_cssi_score(tl, ts, tq, plugin_scores) """ tot_ps = 0.0 # Variable to store the sum of the plugin scores tot_pw = 0 # Variable to keep track total plugin weight # Checks if any plugins are provided for score calculation. if plugin_scores is not None: for plugin in plugin_scores: plugin_name = plugin["name"] # Checks if the plugin is registered in the configuration file # If not, raises an exception. if plugin_name not in self.config.plugins: raise CSSIException( "The plugin {0} appears to be invalid.".format( plugin_name)) else: plugin_weight = float( self.config.plugin_options[plugin_name] ["weight"]) / 100 plugin_score = plugin["score"] # Checks if the passed in plugin score is less than 100. # If not an exception will be thrown. if plugin_score > 100: raise CSSIException( "Invalid score provided for the plugin: {0}.". format(plugin_name)) # Ads the current plugin score to the total plugin score. tot_ps += plugin_score * plugin_weight # Ads the current plugin weight to the total plugin weight percentage. tot_pw += plugin_weight lw = float( self.config.latency_weight) / 100 # latency weight percentage sw = float( self.config.sentiment_weight) / 100 # sentiment weight percentage qw = float(self.config.questionnaire_weight ) / 100 # questionnaire weight percentage # Checks if the total weight is less than 100 percent. if (lw + sw + qw + tot_pw) > 1: raise CSSIException( "Invalid weight configuration. Please reconfigure and try again" ) # Calculating the CSSI score cssi = (tl * lw) + (ts * sw) + (tq * qw) + tot_ps # Double checks if the generated CSSI score is less than 100. if cssi > 100: raise CSSIException( "Invalid CSSI score was generated. Please try again") return cssi