language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
Python
def generateCARs(transactionDB: TransactionDB, support: float = 1, confidence: float = 50, maxlen: int = 10, **kwargs): """Function for generating ClassAssociationRules from a TransactionDB Parameters ---------- :param transactionDB : TransactionDB support : float minimum support in percents if positive absolute minimum support if negative confidence : float minimum confidence in percents if positive absolute minimum confidence if negative maxlen : int maximum length of mined rules **kwargs : arbitrary number of arguments that will be provided to the fim.apriori function Returns ------- list of CARs """ appear = transactionDB.appeardict rules = fim.apriori(transactionDB.string_representation, supp=support, conf=confidence, mode="o", target="r", report="sc", appear=appear, **kwargs, zmax=maxlen) return createCARs(rules)
def generateCARs(transactionDB: TransactionDB, support: float = 1, confidence: float = 50, maxlen: int = 10, **kwargs): """Function for generating ClassAssociationRules from a TransactionDB Parameters ---------- :param transactionDB : TransactionDB support : float minimum support in percents if positive absolute minimum support if negative confidence : float minimum confidence in percents if positive absolute minimum confidence if negative maxlen : int maximum length of mined rules **kwargs : arbitrary number of arguments that will be provided to the fim.apriori function Returns ------- list of CARs """ appear = transactionDB.appeardict rules = fim.apriori(transactionDB.string_representation, supp=support, conf=confidence, mode="o", target="r", report="sc", appear=appear, **kwargs, zmax=maxlen) return createCARs(rules)
Python
def top_rules(transactions, appearance: Optional[Dict] = None, target_rule_count: int = 1000, init_support: float = 0.05, init_confidence: float = 0.5, confidence_step: float = 0.05, support_step: float = 0.05, min_length: int = 2, init_max_length: int = 3, total_timeout: float = 100.0, max_iterations: int = 30, verbose: bool = True): """ Function for finding the best n (target_rule_count) rules from transaction list Returns list of mined rules. The rules are not ordered. :param transactions : 2D array of strings, e.g. [["a:=:1", "b:=:3"], ["a:=:4", "b:=:2"]] :param appearance : dict - dictionary specifying rule appearance :param target_rule_count : int - target number of rules to mine :param init_support : float - support from which to start mining :param init_confidence : float - confidence from which to start mining :param confidence_step : float :param support_step : float :param min_length : int - minimum len of rules to mine :param init_max_length : int - maximum len from which to start mining :param total_timeout : float - maximum execution time of the function :param max_iterations : int - maximum iterations to try before stopping execution :param verbose: bool """ if appearance is None: appearance = {} start_time: float = time.time() # the length of a rule is at most the length of a transaction. (All transactions have the same length.) MAX_RULE_LEN: int = len(transactions[0]) current_support: float = init_support current_confidence: float = init_confidence current_max_length: int = init_max_length keep_mining: bool = True is_max_length_decreased_due_timeout: bool = False current_iteration: int = 0 last_rule_count = -1 rules: Optional[List] = None if verbose: print("STARTING top_rules") while keep_mining: current_iteration += 1 if current_iteration > max_iterations: if verbose: print("Max iterations reached") break if verbose: print(f"--- iteration {current_iteration} ---") print((f"Running apriori with setting: " f"confidence={current_confidence}, " f"support={current_support}, " f"min_length={min_length}, " f"max_length={current_max_length}, " f"MAX_RULE_LEN={MAX_RULE_LEN}" )) current_rules = fim.arules(transactions, supp=current_support, conf=current_confidence, mode="o", report="sc", appear=appearance, zmax=current_max_length, zmin=min_length) current_nb_of_rules = len(current_rules) # assign rules = current_rules if verbose: print(f"Rule count: {current_nb_of_rules}, Iteration: {current_iteration}") if current_nb_of_rules >= target_rule_count: keep_mining = False if verbose: print(f"\tTarget rule count satisfied: {target_rule_count}") else: current_execution_time = time.time() - start_time # if timeout limit exceeded if current_execution_time > total_timeout: if verbose: print(f"\tExecution time exceeded: {total_timeout}") keep_mining = False # if we can still increase our rule length AND # the number of rules found has changed (increased?) since last time AND # there has elif current_max_length < MAX_RULE_LEN and last_rule_count != current_nb_of_rules and not is_max_length_decreased_due_timeout: current_max_length += 1 last_rule_count = current_nb_of_rules if verbose: print(f"\tIncreasing max_length {current_max_length}") # if we can still increase our rule length AND # # we can still increase our support # THEN: # increase our support # increment our max length elif current_max_length < MAX_RULE_LEN and is_max_length_decreased_due_timeout and current_support <= 1 - support_step: current_support += support_step current_max_length += 1 last_rule_count = current_nb_of_rules is_max_length_decreased_due_timeout = False if verbose: print(f"\tIncreasing maxlen to {current_max_length}") print(f"\tIncreasing minsup to {current_support}") # IF we can still decrease our confidence # THEN decrease our confidence elif current_confidence > confidence_step: current_confidence -= confidence_step if verbose: print(f"\tDecreasing confidence to {current_confidence}") else: if verbose: print("\tAll options exhausted") keep_mining = False if verbose: end_of_current_iteration_message = f"--- end iteration {current_iteration} ---" print(end_of_current_iteration_message) print("-" * len(end_of_current_iteration_message)) if verbose: print(f"FINISHED top_rules after {current_iteration} iterations") return rules
def top_rules(transactions, appearance: Optional[Dict] = None, target_rule_count: int = 1000, init_support: float = 0.05, init_confidence: float = 0.5, confidence_step: float = 0.05, support_step: float = 0.05, min_length: int = 2, init_max_length: int = 3, total_timeout: float = 100.0, max_iterations: int = 30, verbose: bool = True): """ Function for finding the best n (target_rule_count) rules from transaction list Returns list of mined rules. The rules are not ordered. :param transactions : 2D array of strings, e.g. [["a:=:1", "b:=:3"], ["a:=:4", "b:=:2"]] :param appearance : dict - dictionary specifying rule appearance :param target_rule_count : int - target number of rules to mine :param init_support : float - support from which to start mining :param init_confidence : float - confidence from which to start mining :param confidence_step : float :param support_step : float :param min_length : int - minimum len of rules to mine :param init_max_length : int - maximum len from which to start mining :param total_timeout : float - maximum execution time of the function :param max_iterations : int - maximum iterations to try before stopping execution :param verbose: bool """ if appearance is None: appearance = {} start_time: float = time.time() # the length of a rule is at most the length of a transaction. (All transactions have the same length.) MAX_RULE_LEN: int = len(transactions[0]) current_support: float = init_support current_confidence: float = init_confidence current_max_length: int = init_max_length keep_mining: bool = True is_max_length_decreased_due_timeout: bool = False current_iteration: int = 0 last_rule_count = -1 rules: Optional[List] = None if verbose: print("STARTING top_rules") while keep_mining: current_iteration += 1 if current_iteration > max_iterations: if verbose: print("Max iterations reached") break if verbose: print(f"--- iteration {current_iteration} ---") print((f"Running apriori with setting: " f"confidence={current_confidence}, " f"support={current_support}, " f"min_length={min_length}, " f"max_length={current_max_length}, " f"MAX_RULE_LEN={MAX_RULE_LEN}" )) current_rules = fim.arules(transactions, supp=current_support, conf=current_confidence, mode="o", report="sc", appear=appearance, zmax=current_max_length, zmin=min_length) current_nb_of_rules = len(current_rules) # assign rules = current_rules if verbose: print(f"Rule count: {current_nb_of_rules}, Iteration: {current_iteration}") if current_nb_of_rules >= target_rule_count: keep_mining = False if verbose: print(f"\tTarget rule count satisfied: {target_rule_count}") else: current_execution_time = time.time() - start_time # if timeout limit exceeded if current_execution_time > total_timeout: if verbose: print(f"\tExecution time exceeded: {total_timeout}") keep_mining = False # if we can still increase our rule length AND # the number of rules found has changed (increased?) since last time AND # there has elif current_max_length < MAX_RULE_LEN and last_rule_count != current_nb_of_rules and not is_max_length_decreased_due_timeout: current_max_length += 1 last_rule_count = current_nb_of_rules if verbose: print(f"\tIncreasing max_length {current_max_length}") # if we can still increase our rule length AND # # we can still increase our support # THEN: # increase our support # increment our max length elif current_max_length < MAX_RULE_LEN and is_max_length_decreased_due_timeout and current_support <= 1 - support_step: current_support += support_step current_max_length += 1 last_rule_count = current_nb_of_rules is_max_length_decreased_due_timeout = False if verbose: print(f"\tIncreasing maxlen to {current_max_length}") print(f"\tIncreasing minsup to {current_support}") # IF we can still decrease our confidence # THEN decrease our confidence elif current_confidence > confidence_step: current_confidence -= confidence_step if verbose: print(f"\tDecreasing confidence to {current_confidence}") else: if verbose: print("\tAll options exhausted") keep_mining = False if verbose: end_of_current_iteration_message = f"--- end iteration {current_iteration} ---" print(end_of_current_iteration_message) print("-" * len(end_of_current_iteration_message)) if verbose: print(f"FINISHED top_rules after {current_iteration} iterations") return rules
Python
def mine_cars_for_dataset_fold_target_attribute( dataset_name: str, fold_i: int, target_attribute: str, min_support: float, min_confidence: float, max_length: int, ): """ 1. load the required training data of the dataset fold. 2. make sure the target attribute is the last attribute 3. mine rules using the parameters settings --> check the number of rules! 4. save the rules to file :return: """ relative_name: str = f'{dataset_name}{fold_i}_{target_attribute}_{min_confidence}' logger = create_logger( logger_name=f'mine_filtered_single_target_cars_' + relative_name, log_file_name=os.path.join(assoc_vs_tree_based_single_target_car_dir(), f'{relative_name}_single_target_filtered_car_mining.log') ) # logger.info(f"rule_cutoff={rule_cutoff}") # # load the required training data of the dataset fold. # original_train_data_fold_abs_file_name = get_original_data_fold_abs_file_name( # dataset_name, fold_i, TrainTestEnum.train) # df_train_original_column_order = pd.read_csv(original_train_data_fold_abs_file_name, delimiter=',') # # 2. make sure the target attribute is the last attribute # df_train_reordered = reorder_columns(df_train_original_column_order, target_attribute) # # # REMOVE INSTANCES WITH NAN AS TARGET VALUE: # df_train_reordered = remove_instances_with_nans_in_column(df_train_reordered, target_attribute) df_train_reordered = prepare_arc_data(dataset_name, fold_i, target_attribute, TrainTestEnum.train) logger.info(f"start mining CARs for " + relative_name) st_mcars: List[MCAR] timings_dict: Dict[str, float] filtered_st_mcars, timings_dict = mine_single_target_MCARs_mlext(df_train_reordered, target_attribute=target_attribute, min_support=min_support, min_confidence=min_confidence, max_length=max_length) logger.info(f"finished mining CARs for {dataset_name} {fold_i}_{min_support}supp_{min_confidence}conf") logger.info( f"found {len(filtered_st_mcars)} CARs for {dataset_name} {fold_i}_{min_support}supp_{min_confidence}conf") filtered_st_mcars_abs_file_name: str = get_single_target_filtered_cars_abs_filename( dataset_name=dataset_name, fold_i=fold_i, target_attribute=target_attribute, confidence_boundary_val=min_confidence ) store_mcars(filtered_st_mcars_abs_file_name, filtered_st_mcars) logger.info(f"finished writing CARs to file: {filtered_st_mcars_abs_file_name}") filtered_st_mcars_mining_timings_abs_file_name = get_single_target_filtered_cars_mining_timings_abs_filename( dataset_name=dataset_name, fold_i=fold_i, target_attribute=target_attribute, confidence_boundary_val=min_confidence ) store_timings_dict(filtered_st_mcars_mining_timings_abs_file_name, timings_dict) close_logger(logger)
def mine_cars_for_dataset_fold_target_attribute( dataset_name: str, fold_i: int, target_attribute: str, min_support: float, min_confidence: float, max_length: int, ): """ 1. load the required training data of the dataset fold. 2. make sure the target attribute is the last attribute 3. mine rules using the parameters settings --> check the number of rules! 4. save the rules to file :return: """ relative_name: str = f'{dataset_name}{fold_i}_{target_attribute}_{min_confidence}' logger = create_logger( logger_name=f'mine_filtered_single_target_cars_' + relative_name, log_file_name=os.path.join(assoc_vs_tree_based_single_target_car_dir(), f'{relative_name}_single_target_filtered_car_mining.log') ) # logger.info(f"rule_cutoff={rule_cutoff}") # # load the required training data of the dataset fold. # original_train_data_fold_abs_file_name = get_original_data_fold_abs_file_name( # dataset_name, fold_i, TrainTestEnum.train) # df_train_original_column_order = pd.read_csv(original_train_data_fold_abs_file_name, delimiter=',') # # 2. make sure the target attribute is the last attribute # df_train_reordered = reorder_columns(df_train_original_column_order, target_attribute) # # # REMOVE INSTANCES WITH NAN AS TARGET VALUE: # df_train_reordered = remove_instances_with_nans_in_column(df_train_reordered, target_attribute) df_train_reordered = prepare_arc_data(dataset_name, fold_i, target_attribute, TrainTestEnum.train) logger.info(f"start mining CARs for " + relative_name) st_mcars: List[MCAR] timings_dict: Dict[str, float] filtered_st_mcars, timings_dict = mine_single_target_MCARs_mlext(df_train_reordered, target_attribute=target_attribute, min_support=min_support, min_confidence=min_confidence, max_length=max_length) logger.info(f"finished mining CARs for {dataset_name} {fold_i}_{min_support}supp_{min_confidence}conf") logger.info( f"found {len(filtered_st_mcars)} CARs for {dataset_name} {fold_i}_{min_support}supp_{min_confidence}conf") filtered_st_mcars_abs_file_name: str = get_single_target_filtered_cars_abs_filename( dataset_name=dataset_name, fold_i=fold_i, target_attribute=target_attribute, confidence_boundary_val=min_confidence ) store_mcars(filtered_st_mcars_abs_file_name, filtered_st_mcars) logger.info(f"finished writing CARs to file: {filtered_st_mcars_abs_file_name}") filtered_st_mcars_mining_timings_abs_file_name = get_single_target_filtered_cars_mining_timings_abs_filename( dataset_name=dataset_name, fold_i=fold_i, target_attribute=target_attribute, confidence_boundary_val=min_confidence ) store_timings_dict(filtered_st_mcars_mining_timings_abs_file_name, timings_dict) close_logger(logger)
Python
def find_overlap_mask(self, rule1: MIDSRule, rule2: MIDSRule, df: pd.DataFrame) -> np.ndarray: """ Compute the number of points which are covered both by r1 and r2 w.r.t. data frame df :param rule1: :param rule2: :param df: :return: """ # if not rule1.head_contains_target_attribute(target_attribute) or not rule2.head_contains_target_attribute( # target_attribute): # raise Exception("WARNING: overlap check where one of the two rules does not contain target attribute", # str(target_attribute)) # if rule1 == rule2: # raise Exception("Dont check a rule with itself for overlap") return np.logical_and( self.cover_checker.get_cover(rule1, df), self.cover_checker.get_cover(rule2, df) )
def find_overlap_mask(self, rule1: MIDSRule, rule2: MIDSRule, df: pd.DataFrame) -> np.ndarray: """ Compute the number of points which are covered both by r1 and r2 w.r.t. data frame df :param rule1: :param rule2: :param df: :return: """ # if not rule1.head_contains_target_attribute(target_attribute) or not rule2.head_contains_target_attribute( # target_attribute): # raise Exception("WARNING: overlap check where one of the two rules does not contain target attribute", # str(target_attribute)) # if rule1 == rule2: # raise Exception("Dont check a rule with itself for overlap") return np.logical_and( self.cover_checker.get_cover(rule1, df), self.cover_checker.get_cover(rule2, df) )
Python
def calc_f1(self): """ F1 score is the harmonic mean of the precision and recall. :return: """ if self.car.support == 0 or self.car.confidence == 0: return 0 # warnings.warn("possibly not correct for multi-target prediction") return st.hmean([self.car.support, self.car.confidence])
def calc_f1(self): """ F1 score is the harmonic mean of the precision and recall. :return: """ if self.car.support == 0 or self.car.confidence == 0: return 0 # warnings.warn("possibly not correct for multi-target prediction") return st.hmean([self.car.support, self.car.confidence])
Python
def does_rule_fire_for_instance(rule: MIDSRule, instance: pd.Series) -> bool: """ Return True if rule condition holds for an instance represented as a pandas Series, False otherwise. :param rule: :param instance: :return: """ antecedent: Antecedent = rule.get_antecedent() for literal in antecedent.get_literals(): does_literal_hold = literal.does_literal_hold_for_instance(instance) if not does_literal_hold: return False return True
def does_rule_fire_for_instance(rule: MIDSRule, instance: pd.Series) -> bool: """ Return True if rule condition holds for an instance represented as a pandas Series, False otherwise. :param rule: :param instance: :return: """ antecedent: Antecedent = rule.get_antecedent() for literal in antecedent.get_literals(): does_literal_hold = literal.does_literal_hold_for_instance(instance) if not does_literal_hold: return False return True
Python
def create_f2_f3_cache(total_rule_set: MIDSRuleSet, overlap_checker, quant_dataframe, f2_f3_target_attr_to_upper_bound_map: Dict[TargetAttr, int], nb_of_target_attributes: int ): """ create a cache, mapping each (unordered) pair of rules to their intra and inter - class overlap counts """ # raise Exception("INCORRECT") cache = {} # type: Dict[Tuple[RuleID,RuleID], Tuple[Count, Count]] for i, rule_i in enumerate(total_rule_set.ruleset): for j, rule_j in enumerate(total_rule_set.ruleset): if i >= j: continue target_attr_rule_i = rule_i.get_target_attributes() target_attr_rule_j = rule_j.get_target_attributes() shared_attributes = target_attr_rule_i & target_attr_rule_j # if both rules have at least one target attribute in common if len(shared_attributes) > 0: overlap_count = overlap_checker.get_pure_overlap_count(rule_i, rule_j, quant_dataframe) weighed_overlap_count_intra_class_sum = 0 weighted_overlap_count_inter_class_sum = 0 for target_attr in shared_attributes: # check whether the rules predict the same value for the target attribute target_value_rule_i = rule_i.get_predicted_value_for(target_attr) target_value_rule_j = rule_j.get_predicted_value_for(target_attr) f2_f3_upper_bound_for_target_attr = f2_f3_target_attr_to_upper_bound_map[target_attr] if target_value_rule_i == target_value_rule_j: weighed_overlap_count_intra_class_sum = weighed_overlap_count_intra_class_sum + \ overlap_count / (nb_of_target_attributes * f2_f3_upper_bound_for_target_attr) else: weighted_overlap_count_inter_class_sum = weighted_overlap_count_inter_class_sum + \ overlap_count / (nb_of_target_attributes * f2_f3_upper_bound_for_target_attr) # weighed_overlap_count_intra_class_sum = weighed_overlap_count_intra_class_sum / nb_of_target_attributes # weighted_overlap_count_inter_class_sum = weighted_overlap_count_inter_class_sum / nb_of_target_attributes cache_key = get_cache_key(rule_i, rule_j) cache[cache_key] = (weighed_overlap_count_intra_class_sum, weighted_overlap_count_inter_class_sum) return cache
def create_f2_f3_cache(total_rule_set: MIDSRuleSet, overlap_checker, quant_dataframe, f2_f3_target_attr_to_upper_bound_map: Dict[TargetAttr, int], nb_of_target_attributes: int ): """ create a cache, mapping each (unordered) pair of rules to their intra and inter - class overlap counts """ # raise Exception("INCORRECT") cache = {} # type: Dict[Tuple[RuleID,RuleID], Tuple[Count, Count]] for i, rule_i in enumerate(total_rule_set.ruleset): for j, rule_j in enumerate(total_rule_set.ruleset): if i >= j: continue target_attr_rule_i = rule_i.get_target_attributes() target_attr_rule_j = rule_j.get_target_attributes() shared_attributes = target_attr_rule_i & target_attr_rule_j # if both rules have at least one target attribute in common if len(shared_attributes) > 0: overlap_count = overlap_checker.get_pure_overlap_count(rule_i, rule_j, quant_dataframe) weighed_overlap_count_intra_class_sum = 0 weighted_overlap_count_inter_class_sum = 0 for target_attr in shared_attributes: # check whether the rules predict the same value for the target attribute target_value_rule_i = rule_i.get_predicted_value_for(target_attr) target_value_rule_j = rule_j.get_predicted_value_for(target_attr) f2_f3_upper_bound_for_target_attr = f2_f3_target_attr_to_upper_bound_map[target_attr] if target_value_rule_i == target_value_rule_j: weighed_overlap_count_intra_class_sum = weighed_overlap_count_intra_class_sum + \ overlap_count / (nb_of_target_attributes * f2_f3_upper_bound_for_target_attr) else: weighted_overlap_count_inter_class_sum = weighted_overlap_count_inter_class_sum + \ overlap_count / (nb_of_target_attributes * f2_f3_upper_bound_for_target_attr) # weighed_overlap_count_intra_class_sum = weighed_overlap_count_intra_class_sum / nb_of_target_attributes # weighted_overlap_count_inter_class_sum = weighted_overlap_count_inter_class_sum / nb_of_target_attributes cache_key = get_cache_key(rule_i, rule_j) cache[cache_key] = (weighed_overlap_count_intra_class_sum, weighted_overlap_count_inter_class_sum) return cache
Python
def from_DataFrame(clazz, df, unique_transactions=False): """ Allows the conversion of pandas DataFrame class to TransactionDB class. """ rows = df.values header = list(df.columns.values) return clazz(rows, header, unique_transactions=unique_transactions)
def from_DataFrame(clazz, df, unique_transactions=False): """ Allows the conversion of pandas DataFrame class to TransactionDB class. """ rows = df.values header = list(df.columns.values) return clazz(rows, header, unique_transactions=unique_transactions)
Python
def _fraction_overlap(ruleset: MIDSRuleSet, test_dataframe: pd.DataFrame, target_attr: Optional[TargetAttr] = None, cover_checker_on_test: Optional[CoverChecker] = None, overlap_checker_on_test: Optional[OverlapChecker] = None, debug=False) -> float: """ This metric captures the extend of overlap between every pair of rules in a decision set R. Smaller values of this metric signify higher interpretability. Boundary values: 0.0 if no rules in R overlap: 1.0 if all data points in are covered by all rules in R. NOTE: * this is 0.0 for any decision list, because their if-else structure ensures that a rule in the list applies only to those data points which have not been covered by any of the preceeding rules * this is 0.0 for the empty rule set :param ruleset: :param test_dataframe: :param cover_checker_on_test: :param overlap_checker_on_test: :return: """ if type(ruleset) != MIDSRuleSet: raise Exception(f"Type of ruleset must be MIDSRuleSet, but is {type(ruleset)}") # warnings.warn("FRACTION_OVERLAP IS CURRENTLY NOT RELATIVE TO A TARGET ATTRIBUTE. THIS MIGHT BE INCORRECT") ruleset_size: int = len(ruleset) if ruleset_size == 0: print("Warning: the MIDS rule set is empty.") return 0.0 nb_of_test_examples: int = test_dataframe.index.size if nb_of_test_examples == 0: raise Exception("There are no test instances to calculate overlap on") if cover_checker_on_test is None: cover_checker_on_test = DefaultCoverChecker() if overlap_checker_on_test is None: overlap_checker_on_test = DefaultOverlapChecker(cover_checker_on_test, debug) overlap_sum: int = 0 rule_i: MIDSRule rule_j: MIDSRule for i, rule_i in enumerate(ruleset.ruleset): for j, rule_j in enumerate(ruleset.ruleset): if i <= j: continue else: if target_attr is None: overlap_sum += overlap_checker_on_test.get_pure_overlap_count(rule_i, rule_j, test_dataframe) else: overlap_sum += overlap_checker_on_test.get_relative_overlap_count(rule_i, rule_j, test_dataframe, target_attr) if overlap_sum == 0: warnings.warn("overlap is 0, which is unlikely") return 0 else: frac_overlap = 2 / (ruleset_size * (ruleset_size - 1)) * overlap_sum / nb_of_test_examples if not is_valid_fraction(frac_overlap): raise Exception("Fraction overlap is not within [0,1]: " + str(frac_overlap)) return frac_overlap
def _fraction_overlap(ruleset: MIDSRuleSet, test_dataframe: pd.DataFrame, target_attr: Optional[TargetAttr] = None, cover_checker_on_test: Optional[CoverChecker] = None, overlap_checker_on_test: Optional[OverlapChecker] = None, debug=False) -> float: """ This metric captures the extend of overlap between every pair of rules in a decision set R. Smaller values of this metric signify higher interpretability. Boundary values: 0.0 if no rules in R overlap: 1.0 if all data points in are covered by all rules in R. NOTE: * this is 0.0 for any decision list, because their if-else structure ensures that a rule in the list applies only to those data points which have not been covered by any of the preceeding rules * this is 0.0 for the empty rule set :param ruleset: :param test_dataframe: :param cover_checker_on_test: :param overlap_checker_on_test: :return: """ if type(ruleset) != MIDSRuleSet: raise Exception(f"Type of ruleset must be MIDSRuleSet, but is {type(ruleset)}") # warnings.warn("FRACTION_OVERLAP IS CURRENTLY NOT RELATIVE TO A TARGET ATTRIBUTE. THIS MIGHT BE INCORRECT") ruleset_size: int = len(ruleset) if ruleset_size == 0: print("Warning: the MIDS rule set is empty.") return 0.0 nb_of_test_examples: int = test_dataframe.index.size if nb_of_test_examples == 0: raise Exception("There are no test instances to calculate overlap on") if cover_checker_on_test is None: cover_checker_on_test = DefaultCoverChecker() if overlap_checker_on_test is None: overlap_checker_on_test = DefaultOverlapChecker(cover_checker_on_test, debug) overlap_sum: int = 0 rule_i: MIDSRule rule_j: MIDSRule for i, rule_i in enumerate(ruleset.ruleset): for j, rule_j in enumerate(ruleset.ruleset): if i <= j: continue else: if target_attr is None: overlap_sum += overlap_checker_on_test.get_pure_overlap_count(rule_i, rule_j, test_dataframe) else: overlap_sum += overlap_checker_on_test.get_relative_overlap_count(rule_i, rule_j, test_dataframe, target_attr) if overlap_sum == 0: warnings.warn("overlap is 0, which is unlikely") return 0 else: frac_overlap = 2 / (ruleset_size * (ruleset_size - 1)) * overlap_sum / nb_of_test_examples if not is_valid_fraction(frac_overlap): raise Exception("Fraction overlap is not within [0,1]: " + str(frac_overlap)) return frac_overlap
Python
def fraction_uncovered_examples(ruleset: MIDSRuleSet, test_dataframe: pd.DataFrame, cover_checker_on_test: Optional[CoverChecker] = None ) -> float: """ This metric computes the fraction of the data points which are not covered by any rule in the decision set. REMEMBER, COVER is independent of the head of a rule. Boundary values: 0.0 if every data point is covered by some rule in the data set. 1.0 when no data point is covered by any rule in R (This could be the case when |R| = 0 ) Note: * for decision lists, this metric is the fraction of the data points that are covered by the ELSE clause of the list (i.e. the default prediction). :param ruleset: :param test_dataframe: :param cover_checker_on_test: :return: """ if type(ruleset) != MIDSRuleSet: raise Exception("Type of ruleset must be IDSRuleSet") if cover_checker_on_test is None: cover_checker_on_test = DefaultCoverChecker() nb_of_test_examples: int = test_dataframe.index.size if nb_of_test_examples == 0: raise Exception("There are no test instances to calculate the fraction uncovered on") cover_cumulative_mask: np.ndarray = np.zeros(nb_of_test_examples, dtype=bool) for rule in ruleset.ruleset: cover_mask = cover_checker_on_test.get_cover(rule, test_dataframe) cover_cumulative_mask = np.logical_or(cover_cumulative_mask, cover_mask) nb_of_covered_test_examples: int = np.count_nonzero(cover_cumulative_mask) frac_uncovered: float = 1 - 1 / nb_of_test_examples * nb_of_covered_test_examples if not is_valid_fraction(frac_uncovered): raise Exception("Fraction uncovered examples is not within [0,1]: " + str(frac_uncovered)) return frac_uncovered
def fraction_uncovered_examples(ruleset: MIDSRuleSet, test_dataframe: pd.DataFrame, cover_checker_on_test: Optional[CoverChecker] = None ) -> float: """ This metric computes the fraction of the data points which are not covered by any rule in the decision set. REMEMBER, COVER is independent of the head of a rule. Boundary values: 0.0 if every data point is covered by some rule in the data set. 1.0 when no data point is covered by any rule in R (This could be the case when |R| = 0 ) Note: * for decision lists, this metric is the fraction of the data points that are covered by the ELSE clause of the list (i.e. the default prediction). :param ruleset: :param test_dataframe: :param cover_checker_on_test: :return: """ if type(ruleset) != MIDSRuleSet: raise Exception("Type of ruleset must be IDSRuleSet") if cover_checker_on_test is None: cover_checker_on_test = DefaultCoverChecker() nb_of_test_examples: int = test_dataframe.index.size if nb_of_test_examples == 0: raise Exception("There are no test instances to calculate the fraction uncovered on") cover_cumulative_mask: np.ndarray = np.zeros(nb_of_test_examples, dtype=bool) for rule in ruleset.ruleset: cover_mask = cover_checker_on_test.get_cover(rule, test_dataframe) cover_cumulative_mask = np.logical_or(cover_cumulative_mask, cover_mask) nb_of_covered_test_examples: int = np.count_nonzero(cover_cumulative_mask) frac_uncovered: float = 1 - 1 / nb_of_test_examples * nb_of_covered_test_examples if not is_valid_fraction(frac_uncovered): raise Exception("Fraction uncovered examples is not within [0,1]: " + str(frac_uncovered)) return frac_uncovered
Python
def fraction_predicted_classes(ruleset: MIDSRuleSet, test_dataframe, target_attributes: List[TargetAttr] ) -> Tuple[float, Dict[TargetAttr, float]]: """ This metric denotes the fraction of the classes in the data that are predicted by the ruleset R. Returns: 1. fraction per target attribute, averaged over the different targets 2. a map from target attribute to fraction for that target attr Boundary value: 0.0 if no class is predicted (e.g. the ruleset is empty) 1.0 every class is predicted by some rule in R. Note: * The same for decision lists, but we not consider the ELSE clause (the default prediction). :param target_attributes: :param ruleset: :param test_dataframe: :return: """ if type(ruleset) != MIDSRuleSet: raise Exception("Type of ruleset must be IDSRuleSet") warnings.warn( "Ugly conversion to string to deal with numerical attributes." " Clean this up (look at Survived in Titanic).") values_in_data_per_target_attribute: Dict[TargetAttr, Set[TargetVal]] = {} predicted_values_per_target_attribute: Dict[TargetAttr, Set[TargetVal]] = {} for target_attr in target_attributes: values_as_str: List[str] = [str(val) for val in test_dataframe[target_attr].values] values_in_data_per_target_attribute[target_attr] = set(values_as_str) predicted_values_per_target_attribute[target_attr] = set() target_attribute_set: Set[TargetAttr] = set(target_attributes) for rule in ruleset.ruleset: consequent: Consequent = rule.car.consequent for literal in consequent.get_literals(): predicted_attribute: TargetAttr = literal.get_attribute() predicted_value: TargetVal = literal.get_value() if predicted_attribute in target_attribute_set: predicted_value_str = str(predicted_value) predicted_values: Set[TargetVal] = predicted_values_per_target_attribute[predicted_attribute] if predicted_value_str in values_in_data_per_target_attribute[predicted_attribute]: predicted_values.add(predicted_value_str) # print("values_in_data_per_target_attribute", values_in_data_per_target_attribute) # print("predicted_values_per_target_attribute", predicted_values_per_target_attribute) frac_predicted_classes_per_target_attr: Dict[TargetAttr, float] = {} avg_frac_predicted_classes: float = 0 for target_attr in values_in_data_per_target_attribute.keys(): values_occuring_in_data = values_in_data_per_target_attribute[target_attr] predicted_values = predicted_values_per_target_attribute[target_attr] domain_size_in_test_data = len(values_occuring_in_data) nb_of_predicted_values = len(predicted_values) frac_classes: float = nb_of_predicted_values / domain_size_in_test_data frac_predicted_classes_per_target_attr[target_attr] = frac_classes avg_frac_predicted_classes += frac_classes nb_of_target_attrs = len(target_attributes) avg_frac_predicted_classes = avg_frac_predicted_classes / nb_of_target_attrs if not is_valid_fraction(avg_frac_predicted_classes): raise Exception("Avg fraction predicted classes examples is not within [0,1]: " + str(avg_frac_predicted_classes)) return avg_frac_predicted_classes, frac_predicted_classes_per_target_attr
def fraction_predicted_classes(ruleset: MIDSRuleSet, test_dataframe, target_attributes: List[TargetAttr] ) -> Tuple[float, Dict[TargetAttr, float]]: """ This metric denotes the fraction of the classes in the data that are predicted by the ruleset R. Returns: 1. fraction per target attribute, averaged over the different targets 2. a map from target attribute to fraction for that target attr Boundary value: 0.0 if no class is predicted (e.g. the ruleset is empty) 1.0 every class is predicted by some rule in R. Note: * The same for decision lists, but we not consider the ELSE clause (the default prediction). :param target_attributes: :param ruleset: :param test_dataframe: :return: """ if type(ruleset) != MIDSRuleSet: raise Exception("Type of ruleset must be IDSRuleSet") warnings.warn( "Ugly conversion to string to deal with numerical attributes." " Clean this up (look at Survived in Titanic).") values_in_data_per_target_attribute: Dict[TargetAttr, Set[TargetVal]] = {} predicted_values_per_target_attribute: Dict[TargetAttr, Set[TargetVal]] = {} for target_attr in target_attributes: values_as_str: List[str] = [str(val) for val in test_dataframe[target_attr].values] values_in_data_per_target_attribute[target_attr] = set(values_as_str) predicted_values_per_target_attribute[target_attr] = set() target_attribute_set: Set[TargetAttr] = set(target_attributes) for rule in ruleset.ruleset: consequent: Consequent = rule.car.consequent for literal in consequent.get_literals(): predicted_attribute: TargetAttr = literal.get_attribute() predicted_value: TargetVal = literal.get_value() if predicted_attribute in target_attribute_set: predicted_value_str = str(predicted_value) predicted_values: Set[TargetVal] = predicted_values_per_target_attribute[predicted_attribute] if predicted_value_str in values_in_data_per_target_attribute[predicted_attribute]: predicted_values.add(predicted_value_str) # print("values_in_data_per_target_attribute", values_in_data_per_target_attribute) # print("predicted_values_per_target_attribute", predicted_values_per_target_attribute) frac_predicted_classes_per_target_attr: Dict[TargetAttr, float] = {} avg_frac_predicted_classes: float = 0 for target_attr in values_in_data_per_target_attribute.keys(): values_occuring_in_data = values_in_data_per_target_attribute[target_attr] predicted_values = predicted_values_per_target_attribute[target_attr] domain_size_in_test_data = len(values_occuring_in_data) nb_of_predicted_values = len(predicted_values) frac_classes: float = nb_of_predicted_values / domain_size_in_test_data frac_predicted_classes_per_target_attr[target_attr] = frac_classes avg_frac_predicted_classes += frac_classes nb_of_target_attrs = len(target_attributes) avg_frac_predicted_classes = avg_frac_predicted_classes / nb_of_target_attrs if not is_valid_fraction(avg_frac_predicted_classes): raise Exception("Avg fraction predicted classes examples is not within [0,1]: " + str(avg_frac_predicted_classes)) return avg_frac_predicted_classes, frac_predicted_classes_per_target_attr
Python
def f1_minimize_total_nb_of_literals(self, solution_set: MIDSRuleSet): """ Minimize the total number of terms in the rule set :param solution_set: :return: """ upper_bound_nb_of_literals = self.objective_func_params.f1_upper_bound_nb_literals f1_unnormalized = upper_bound_nb_of_literals - solution_set.sum_rule_length() if self.normalize: f1 = f1_unnormalized / upper_bound_nb_of_literals else: f1 = f1_unnormalized self._normalized_boundary_check(f1, 'f1') return f1
def f1_minimize_total_nb_of_literals(self, solution_set: MIDSRuleSet): """ Minimize the total number of terms in the rule set :param solution_set: :return: """ upper_bound_nb_of_literals = self.objective_func_params.f1_upper_bound_nb_literals f1_unnormalized = upper_bound_nb_of_literals - solution_set.sum_rule_length() if self.normalize: f1 = f1_unnormalized / upper_bound_nb_of_literals else: f1 = f1_unnormalized self._normalized_boundary_check(f1, 'f1') return f1
Python
def f4_at_least_one_rule_per_attribute_value_combo(self, solution_set: MIDSRuleSet): """ The requirement to have one rule for each value of each attribute might need to be relaxed, as it is no longer guaranteed that each value of each attribute occurs in at least one rule head. :param solution_set: :return: """ # 1. gather for each attribute the unique values that are predicted target_attr_to_val_set_dict: Dict[TargetAttr, Set[TargetVal]] \ = solution_set.get_predicted_values_per_predicted_attribute() # 2. count the total nb of values that are predicted over all attributes total_nb_of_attribute_values_covered: int = 0 for target_attr in self.objective_func_params.f4_target_attr_to_dom_size_map.keys(): predicted_values: Optional[Set[TargetVal]] = target_attr_to_val_set_dict.get(target_attr, None) if predicted_values is None: nb_of_predicted_values: int = 0 else: nb_of_predicted_values: int = len(predicted_values) if self.normalize: target_attr_dom_size: int = self.objective_func_params.f4_target_attr_to_dom_size_map[target_attr] total_nb_of_attribute_values_covered += nb_of_predicted_values / target_attr_dom_size else: total_nb_of_attribute_values_covered += nb_of_predicted_values f4: float = total_nb_of_attribute_values_covered / self.objective_func_params.nb_of_target_attrs self._normalized_boundary_check(f4, 'f4') return f4
def f4_at_least_one_rule_per_attribute_value_combo(self, solution_set: MIDSRuleSet): """ The requirement to have one rule for each value of each attribute might need to be relaxed, as it is no longer guaranteed that each value of each attribute occurs in at least one rule head. :param solution_set: :return: """ # 1. gather for each attribute the unique values that are predicted target_attr_to_val_set_dict: Dict[TargetAttr, Set[TargetVal]] \ = solution_set.get_predicted_values_per_predicted_attribute() # 2. count the total nb of values that are predicted over all attributes total_nb_of_attribute_values_covered: int = 0 for target_attr in self.objective_func_params.f4_target_attr_to_dom_size_map.keys(): predicted_values: Optional[Set[TargetVal]] = target_attr_to_val_set_dict.get(target_attr, None) if predicted_values is None: nb_of_predicted_values: int = 0 else: nb_of_predicted_values: int = len(predicted_values) if self.normalize: target_attr_dom_size: int = self.objective_func_params.f4_target_attr_to_dom_size_map[target_attr] total_nb_of_attribute_values_covered += nb_of_predicted_values / target_attr_dom_size else: total_nb_of_attribute_values_covered += nb_of_predicted_values f4: float = total_nb_of_attribute_values_covered / self.objective_func_params.nb_of_target_attrs self._normalized_boundary_check(f4, 'f4') return f4
Python
def f5_minimize_incorrect_cover(self, solution_set: MIDSRuleSet): """ Mazimize the precision, or minimize the nb examples that are in the incorrect-cover set the rules Parameters ---------- solution_set Returns ------- """ # nb_of_instances = self.objective_func_params.nb_of_training_examples # len_all_rules = self.objective_func_params.ground_set_size quant_dataframe = self.objective_func_params.quant_dataframe sum_incorrect_cover = 0 for rule in solution_set.ruleset: # self.cover_checker. sum_incorrect_cover += get_avg_incorrect_cover_size(rule, quant_dataframe, self.cover_checker) f5_upper_bound: int = self.objective_func_params.f5_upper_bound # print(f"MIDS f5 upper bound: {f5_upper_bound}") # print(f"MIDS f5 sum incorrect cover: {sum_incorrect_cover}") f5 = f5_upper_bound - sum_incorrect_cover if self.normalize: f5 = f5 / f5_upper_bound self._normalized_boundary_check(f5, 'f5') return f5
def f5_minimize_incorrect_cover(self, solution_set: MIDSRuleSet): """ Mazimize the precision, or minimize the nb examples that are in the incorrect-cover set the rules Parameters ---------- solution_set Returns ------- """ # nb_of_instances = self.objective_func_params.nb_of_training_examples # len_all_rules = self.objective_func_params.ground_set_size quant_dataframe = self.objective_func_params.quant_dataframe sum_incorrect_cover = 0 for rule in solution_set.ruleset: # self.cover_checker. sum_incorrect_cover += get_avg_incorrect_cover_size(rule, quant_dataframe, self.cover_checker) f5_upper_bound: int = self.objective_func_params.f5_upper_bound # print(f"MIDS f5 upper bound: {f5_upper_bound}") # print(f"MIDS f5 sum incorrect cover: {sum_incorrect_cover}") f5 = f5_upper_bound - sum_incorrect_cover if self.normalize: f5 = f5 / f5_upper_bound self._normalized_boundary_check(f5, 'f5') return f5
Python
def f6_cover_each_example(self, solution_set: MIDSRuleSet): """ Originally: Each data point should be covered by at least one rule. In other words, Each instance should be in the correct cover set (with respect to the target attribute) of at least one rule. Extension to multi-target rules: Each instance should be in the correct cover set of at least one rule for each of its attributes. :param solution_set: :return: """ # TODO: this is super expensive quant_dataframe = self.objective_func_params.quant_dataframe nb_of_training_examples = self.objective_func_params.nb_of_training_examples nb_of_target_attrs = self.objective_func_params.nb_of_target_attrs target_attrs: List[TargetAttr] = self.objective_func_params.target_attrs sum_correct_cover_sizes_over_all_attributes = 0 for target_attr in target_attrs: correctly_covered_instances_for_attribute_by_at_least_one_rule = np.zeros(nb_of_training_examples, dtype=bool) for rule in solution_set.ruleset: if target_attr in rule.get_target_attributes(): correct_cover_mask = self.cover_checker.get_correct_cover( rule, quant_dataframe, target_attribute=target_attr) correctly_covered_instances_for_attribute_by_at_least_one_rule = np.logical_or( correctly_covered_instances_for_attribute_by_at_least_one_rule, correct_cover_mask ) sum_correct_cover_sizes_over_all_attributes += np.sum( correctly_covered_instances_for_attribute_by_at_least_one_rule) f6 = sum_correct_cover_sizes_over_all_attributes / ( nb_of_training_examples * self.objective_func_params.nb_of_target_attrs) self._normalized_boundary_check(f6, 'f6') return f6
def f6_cover_each_example(self, solution_set: MIDSRuleSet): """ Originally: Each data point should be covered by at least one rule. In other words, Each instance should be in the correct cover set (with respect to the target attribute) of at least one rule. Extension to multi-target rules: Each instance should be in the correct cover set of at least one rule for each of its attributes. :param solution_set: :return: """ # TODO: this is super expensive quant_dataframe = self.objective_func_params.quant_dataframe nb_of_training_examples = self.objective_func_params.nb_of_training_examples nb_of_target_attrs = self.objective_func_params.nb_of_target_attrs target_attrs: List[TargetAttr] = self.objective_func_params.target_attrs sum_correct_cover_sizes_over_all_attributes = 0 for target_attr in target_attrs: correctly_covered_instances_for_attribute_by_at_least_one_rule = np.zeros(nb_of_training_examples, dtype=bool) for rule in solution_set.ruleset: if target_attr in rule.get_target_attributes(): correct_cover_mask = self.cover_checker.get_correct_cover( rule, quant_dataframe, target_attribute=target_attr) correctly_covered_instances_for_attribute_by_at_least_one_rule = np.logical_or( correctly_covered_instances_for_attribute_by_at_least_one_rule, correct_cover_mask ) sum_correct_cover_sizes_over_all_attributes += np.sum( correctly_covered_instances_for_attribute_by_at_least_one_rule) f6 = sum_correct_cover_sizes_over_all_attributes / ( nb_of_training_examples * self.objective_func_params.nb_of_target_attrs) self._normalized_boundary_check(f6, 'f6') return f6
Python
def add_encodings(self, original_to_encoding_map: Dict[Attr, List[Attr]]) -> None: """ Use this method if you want to add extra columns to an already existing mapping. """ if self.__original_to_ohe_attr_map is None: self.set_original_to_ohe_attr_map(original_to_encoding_map) else: for original_attr, ohe_attributes in original_to_encoding_map.items(): if original_attr in self.get_original_columns(): raise Exception("EncodingBookKeeper already contains encodings for " + str(original_attr)) else: self.__original_to_ohe_attr_map[original_attr] = ohe_attributes for ohe_attr in ohe_attributes: if ohe_attr in self.get_one_hot_encoded_columns(): raise Exception("EncodingBookKeeper already contains an encoding with name " + str(ohe_attr)) else: self.__ohe_attr_to_original_map[ohe_attr] = original_attr
def add_encodings(self, original_to_encoding_map: Dict[Attr, List[Attr]]) -> None: """ Use this method if you want to add extra columns to an already existing mapping. """ if self.__original_to_ohe_attr_map is None: self.set_original_to_ohe_attr_map(original_to_encoding_map) else: for original_attr, ohe_attributes in original_to_encoding_map.items(): if original_attr in self.get_original_columns(): raise Exception("EncodingBookKeeper already contains encodings for " + str(original_attr)) else: self.__original_to_ohe_attr_map[original_attr] = ohe_attributes for ohe_attr in ohe_attributes: if ohe_attr in self.get_one_hot_encoded_columns(): raise Exception("EncodingBookKeeper already contains an encoding with name " + str(ohe_attr)) else: self.__ohe_attr_to_original_map[ohe_attr] = original_attr
Python
def parse_one_hot_encoded_columns(ohe_columns, ohe_prefix_separator) -> Dict[Attr, List[Attr]]: """ Use this static method to parse a list of one-hot encoding columns into a mapping of original columns to their one-hot encoding columns. """ original_to_ohe_columns: Dict[Attr, List[Attr]] = {} for column in ohe_columns: splitted_ohe_column_name = str(column).split(ohe_prefix_separator) if len(splitted_ohe_column_name) == 1: # don't split it original_to_ohe_columns[column] = [column] elif len(splitted_ohe_column_name) == 2: original_column = splitted_ohe_column_name[0] if original_to_ohe_columns.get(original_column, None) is None: original_to_ohe_columns[original_column] = [column] else: original_to_ohe_columns[original_column].append(column) else: raise Exception("Handling split of " + str(column) + " using separator " + ohe_prefix_separator + " failed; got " + str(len(splitted_ohe_column_name)) + " piece(s)." ) return original_to_ohe_columns
def parse_one_hot_encoded_columns(ohe_columns, ohe_prefix_separator) -> Dict[Attr, List[Attr]]: """ Use this static method to parse a list of one-hot encoding columns into a mapping of original columns to their one-hot encoding columns. """ original_to_ohe_columns: Dict[Attr, List[Attr]] = {} for column in ohe_columns: splitted_ohe_column_name = str(column).split(ohe_prefix_separator) if len(splitted_ohe_column_name) == 1: # don't split it original_to_ohe_columns[column] = [column] elif len(splitted_ohe_column_name) == 2: original_column = splitted_ohe_column_name[0] if original_to_ohe_columns.get(original_column, None) is None: original_to_ohe_columns[original_column] = [column] else: original_to_ohe_columns[original_column].append(column) else: raise Exception("Handling split of " + str(column) + " using separator " + ohe_prefix_separator + " failed; got " + str(len(splitted_ohe_column_name)) + " piece(s)." ) return original_to_ohe_columns
Python
def parse_and_store_one_hot_encoded_columns(self, ohe_columns) -> None: """ Use this method to initialize an empty EncodingBookKeeper by paringing the given one-encoding columns. """ self.set_original_to_ohe_attr_map( self.parse_one_hot_encoded_columns(ohe_columns, self.ohe_prefix_separator))
def parse_and_store_one_hot_encoded_columns(self, ohe_columns) -> None: """ Use this method to initialize an empty EncodingBookKeeper by paringing the given one-encoding columns. """ self.set_original_to_ohe_attr_map( self.parse_one_hot_encoded_columns(ohe_columns, self.ohe_prefix_separator))
Python
def reorder_columns(df: pd.DataFrame, target_column: TargetAttr) -> pd.DataFrame: """ Generates a dataframe with reordered columns, such that the given target column is the last column :param df: :param target_column: :return: """ if target_column not in df.columns: message = f"the given target column {target_column} is not a column of the given dataframe" raise Exception(message) columns = df.columns reordered_columns = [] for possibly_other_column in columns: if str(possibly_other_column) != str(target_column): reordered_columns.append(possibly_other_column) # reordered_columns = [other_col for other_col in columns if str(other_col) is not str(target_column)] reordered_columns.append(target_column) new_df = df[reordered_columns] return new_df
def reorder_columns(df: pd.DataFrame, target_column: TargetAttr) -> pd.DataFrame: """ Generates a dataframe with reordered columns, such that the given target column is the last column :param df: :param target_column: :return: """ if target_column not in df.columns: message = f"the given target column {target_column} is not a column of the given dataframe" raise Exception(message) columns = df.columns reordered_columns = [] for possibly_other_column in columns: if str(possibly_other_column) != str(target_column): reordered_columns.append(possibly_other_column) # reordered_columns = [other_col for other_col in columns if str(other_col) is not str(target_column)] reordered_columns.append(target_column) new_df = df[reordered_columns] return new_df
Python
def predict(self, rules: Iterable[MIDSRule], dataframe: pd.DataFrame, target_attribute: str, default_value=None) -> List[object]: """ Predict a value for the given target attribute for each row, """ type_check_dataframe(dataframe) predicted_class_per_row = [] for _, instance_row in dataframe.iterrows(): predicted_class = self.get_combined_prediction(rules, instance_row, target_attribute, default_value) if predicted_class is not None: predicted_class_per_row.append(predicted_class) else: predicted_class_per_row.append(default_value) return predicted_class_per_row
def predict(self, rules: Iterable[MIDSRule], dataframe: pd.DataFrame, target_attribute: str, default_value=None) -> List[object]: """ Predict a value for the given target attribute for each row, """ type_check_dataframe(dataframe) predicted_class_per_row = [] for _, instance_row in dataframe.iterrows(): predicted_class = self.get_combined_prediction(rules, instance_row, target_attribute, default_value) if predicted_class is not None: predicted_class_per_row.append(predicted_class) else: predicted_class_per_row.append(default_value) return predicted_class_per_row
Python
def f4_one_rule_per_value(self, previous_f4_target_attr_val_rule_counts_map: Dict[TargetAttr, Dict[TargetVal, int]], previous_f4_nb_of_values_covered: float, added_rules: Iterable[MIDSRule], deleted_rules: Iterable[MIDSRule] ) -> Tuple[float, Dict[TargetAttr, Dict[TargetVal, int]]]: """ Each target value should be predicted by at least 1 rule. """ f4_target_attr_val_rule_counts_map: Dict[TargetAttr, Dict[TargetVal, int]] = copy.deepcopy( previous_f4_target_attr_val_rule_counts_map) weighted_total_nb_of_vals_covered: float = previous_f4_nb_of_values_covered f4_target_attr_to_dom_size_map: Dict[TargetAttr, int] \ = self.objective_func_params.f4_target_attr_to_dom_size_map nb_of_target_attrs: int = self.objective_func_params.nb_of_target_attrs rule_a: MIDSRule for rule_a in added_rules: cons: Consequent = rule_a.get_consequent() # for target_attr, target_val in cons.itemset.items(): for literal in cons.get_literals(): target_attr: TargetAttr = literal.get_attribute() target_val: TargetVal = literal.get_value() value_to_count_map: Optional[Dict[TargetVal, int]] \ = f4_target_attr_val_rule_counts_map.get(target_attr, None) if value_to_count_map is None: # no dictionary yet for the current target attribute new_dict: Dict[TargetVal, int] = {target_val: 1} f4_target_attr_val_rule_counts_map[target_attr] = new_dict weighted_total_nb_of_vals_covered += \ 1.0 / (nb_of_target_attrs * f4_target_attr_to_dom_size_map[target_attr]) else: value_count: Optional[int] = value_to_count_map.get(target_val, None) if value_count is None: value_to_count_map[target_val] = 1 weighted_total_nb_of_vals_covered += \ 1.0 / (nb_of_target_attrs * f4_target_attr_to_dom_size_map[target_attr]) else: value_to_count_map[target_val] += 1 rule_d: MIDSRule for rule_d in deleted_rules: cons: Consequent = rule_d.get_consequent() target_att: TargetAttr target_val: TargetVal # for target_attr, target_val in cons.itemset.items(): for literal in cons.get_literals(): target_attr: TargetAttr = literal.get_attribute() target_val: TargetVal = literal.get_value() value_to_count_map: Optional[Dict[TargetVal, int]] \ = f4_target_attr_val_rule_counts_map.get(target_attr, None) if value_to_count_map is None: raise Exception("Should still have counts for target " + str(target_attr)) else: value_count: Optional[int] = value_to_count_map.get(target_val, None) if value_count is None: raise Exception( "Should still have counts for target " + str(target_attr) + " and value " + str(target_val)) else: if value_count > 1: value_to_count_map[target_val] = value_count - 1 else: # value count should be 1 and become zero del value_to_count_map[target_val] if len(value_to_count_map) == 0: del f4_target_attr_val_rule_counts_map[target_attr] weighted_total_nb_of_vals_covered -= 1.0 / ( nb_of_target_attrs * f4_target_attr_to_dom_size_map[target_attr]) f4 = weighted_total_nb_of_vals_covered self._normalized_boundary_check(f4, 'f4') return f4, f4_target_attr_val_rule_counts_map
def f4_one_rule_per_value(self, previous_f4_target_attr_val_rule_counts_map: Dict[TargetAttr, Dict[TargetVal, int]], previous_f4_nb_of_values_covered: float, added_rules: Iterable[MIDSRule], deleted_rules: Iterable[MIDSRule] ) -> Tuple[float, Dict[TargetAttr, Dict[TargetVal, int]]]: """ Each target value should be predicted by at least 1 rule. """ f4_target_attr_val_rule_counts_map: Dict[TargetAttr, Dict[TargetVal, int]] = copy.deepcopy( previous_f4_target_attr_val_rule_counts_map) weighted_total_nb_of_vals_covered: float = previous_f4_nb_of_values_covered f4_target_attr_to_dom_size_map: Dict[TargetAttr, int] \ = self.objective_func_params.f4_target_attr_to_dom_size_map nb_of_target_attrs: int = self.objective_func_params.nb_of_target_attrs rule_a: MIDSRule for rule_a in added_rules: cons: Consequent = rule_a.get_consequent() # for target_attr, target_val in cons.itemset.items(): for literal in cons.get_literals(): target_attr: TargetAttr = literal.get_attribute() target_val: TargetVal = literal.get_value() value_to_count_map: Optional[Dict[TargetVal, int]] \ = f4_target_attr_val_rule_counts_map.get(target_attr, None) if value_to_count_map is None: # no dictionary yet for the current target attribute new_dict: Dict[TargetVal, int] = {target_val: 1} f4_target_attr_val_rule_counts_map[target_attr] = new_dict weighted_total_nb_of_vals_covered += \ 1.0 / (nb_of_target_attrs * f4_target_attr_to_dom_size_map[target_attr]) else: value_count: Optional[int] = value_to_count_map.get(target_val, None) if value_count is None: value_to_count_map[target_val] = 1 weighted_total_nb_of_vals_covered += \ 1.0 / (nb_of_target_attrs * f4_target_attr_to_dom_size_map[target_attr]) else: value_to_count_map[target_val] += 1 rule_d: MIDSRule for rule_d in deleted_rules: cons: Consequent = rule_d.get_consequent() target_att: TargetAttr target_val: TargetVal # for target_attr, target_val in cons.itemset.items(): for literal in cons.get_literals(): target_attr: TargetAttr = literal.get_attribute() target_val: TargetVal = literal.get_value() value_to_count_map: Optional[Dict[TargetVal, int]] \ = f4_target_attr_val_rule_counts_map.get(target_attr, None) if value_to_count_map is None: raise Exception("Should still have counts for target " + str(target_attr)) else: value_count: Optional[int] = value_to_count_map.get(target_val, None) if value_count is None: raise Exception( "Should still have counts for target " + str(target_attr) + " and value " + str(target_val)) else: if value_count > 1: value_to_count_map[target_val] = value_count - 1 else: # value count should be 1 and become zero del value_to_count_map[target_val] if len(value_to_count_map) == 0: del f4_target_attr_val_rule_counts_map[target_attr] weighted_total_nb_of_vals_covered -= 1.0 / ( nb_of_target_attrs * f4_target_attr_to_dom_size_map[target_attr]) f4 = weighted_total_nb_of_vals_covered self._normalized_boundary_check(f4, 'f4') return f4, f4_target_attr_val_rule_counts_map
Python
def _best_rules_to_consider(self, sorted_target_scores_per_rule: List[Tuple[RuleSetScore, MIDSRule]] ) -> List[Tuple[RuleSetScore, MIDSRule]]: """ Given a list of rules sorted on a goodness criterion, take the best rules. Best could be defined as: the x highest scoring rules the rules within a certain percentage of the best rule :param sorted_target_scores_per_rule: :return: """ best_tuple: Tuple[RuleSetScore, MIDSRule] = sorted_target_scores_per_rule[0] score_of_best_rule = best_tuple[0] best_rule_for_target = best_tuple[1] if self.verbose: print(f"best rule results in score {score_of_best_rule}") best_rules = [best_tuple] for other_tuple in sorted_target_scores_per_rule[1:]: score_other_rule = other_tuple[0] if self.close_enough(score_of_best_rule, score_other_rule, self.max_score_diff_with_best_rule): # other_rule = other_tuple[1] best_rules.append(other_tuple) if self.verbose: print(f"{len(best_rules)} rules are being considered as best...") return best_rules
def _best_rules_to_consider(self, sorted_target_scores_per_rule: List[Tuple[RuleSetScore, MIDSRule]] ) -> List[Tuple[RuleSetScore, MIDSRule]]: """ Given a list of rules sorted on a goodness criterion, take the best rules. Best could be defined as: the x highest scoring rules the rules within a certain percentage of the best rule :param sorted_target_scores_per_rule: :return: """ best_tuple: Tuple[RuleSetScore, MIDSRule] = sorted_target_scores_per_rule[0] score_of_best_rule = best_tuple[0] best_rule_for_target = best_tuple[1] if self.verbose: print(f"best rule results in score {score_of_best_rule}") best_rules = [best_tuple] for other_tuple in sorted_target_scores_per_rule[1:]: score_other_rule = other_tuple[0] if self.close_enough(score_of_best_rule, score_other_rule, self.max_score_diff_with_best_rule): # other_rule = other_tuple[1] best_rules.append(other_tuple) if self.verbose: print(f"{len(best_rules)} rules are being considered as best...") return best_rules
Python
def _get_rule_that_hurts_the_other_targets_the_least(self, rules_considered_as_best: List[Tuple[RuleSetScore, MIDSRule]], rule_to_eval_map: Dict[MIDSRule, Dict[TargetAttr, RuleSetScore]], main_target: TargetAttr, current_rule_set_scores: Dict[TargetAttr, RuleSetScore] ) -> Optional[MIDSRule]: """ We want to limit the damage done to the other targets. For each rule: for each target: calculate the difference in score for this target: score_diff = new_score - old_score. if score_diff > 0 --> good: the rule increases the score on this target if score_diff < 0 --> bad: the rule decreases the score on this target min_score_diff = the minimal score_diff over the targets of the rule --> the largest damage the rule can do we want the rule with the highest min_score diff :param rules_considered_as_best: :param rule_to_eval_map: :param main_target: :param current_rule_set_scores: :return: """ best_rule: Optional[MIDSRule] = None min_score_diff_of_best_rule = float('-inf') for rule_set_score, rule in rules_considered_as_best: extended_rule_set_scores: Dict[TargetAttr, RuleSetScore] = rule_to_eval_map[rule] score_diffs_per_target = [] for other_rule_target in extended_rule_set_scores.keys(): if other_rule_target is not main_target: # print(f"\tconsidering score for {other_rule_target}") other_target_score = extended_rule_set_scores[other_rule_target] current_rule_set_score = current_rule_set_scores[other_rule_target] score_diff = other_target_score - current_rule_set_score if self.verbose: print(f"\tconsidering score for {other_rule_target}: {score_diff}") score_diffs_per_target.append(score_diff) if len(score_diffs_per_target) == 0: min_score_diff = 0 else: min_score_diff = min(score_diffs_per_target) if min_score_diff > min_score_diff_of_best_rule: best_rule = rule min_score_diff_of_best_rule = min_score_diff return best_rule
def _get_rule_that_hurts_the_other_targets_the_least(self, rules_considered_as_best: List[Tuple[RuleSetScore, MIDSRule]], rule_to_eval_map: Dict[MIDSRule, Dict[TargetAttr, RuleSetScore]], main_target: TargetAttr, current_rule_set_scores: Dict[TargetAttr, RuleSetScore] ) -> Optional[MIDSRule]: """ We want to limit the damage done to the other targets. For each rule: for each target: calculate the difference in score for this target: score_diff = new_score - old_score. if score_diff > 0 --> good: the rule increases the score on this target if score_diff < 0 --> bad: the rule decreases the score on this target min_score_diff = the minimal score_diff over the targets of the rule --> the largest damage the rule can do we want the rule with the highest min_score diff :param rules_considered_as_best: :param rule_to_eval_map: :param main_target: :param current_rule_set_scores: :return: """ best_rule: Optional[MIDSRule] = None min_score_diff_of_best_rule = float('-inf') for rule_set_score, rule in rules_considered_as_best: extended_rule_set_scores: Dict[TargetAttr, RuleSetScore] = rule_to_eval_map[rule] score_diffs_per_target = [] for other_rule_target in extended_rule_set_scores.keys(): if other_rule_target is not main_target: # print(f"\tconsidering score for {other_rule_target}") other_target_score = extended_rule_set_scores[other_rule_target] current_rule_set_score = current_rule_set_scores[other_rule_target] score_diff = other_target_score - current_rule_set_score if self.verbose: print(f"\tconsidering score for {other_rule_target}: {score_diff}") score_diffs_per_target.append(score_diff) if len(score_diffs_per_target) == 0: min_score_diff = 0 else: min_score_diff = min(score_diffs_per_target) if min_score_diff > min_score_diff_of_best_rule: best_rule = rule min_score_diff_of_best_rule = min_score_diff return best_rule
Python
def convert(self, leaf_info: LeafInfo) -> List[EQLiteral]: """ This method converts a LeafInfo object to a Consequent of a rule. Note: a consequent can predict multiple attributes. It does this by storing one EQLiteral per predicted original attribute. A Scikit-learn DecisionTreeClassifier can predict multiple attributes. -- ONE-HOT ENCODED ATTRIBUTES -- In our framework, some of these target attributes belong to the same original attribute, using one-hot encodings. e.g. the following one-hot encoding attributes: Passenger_Cat=1st_class Passenger_Cat=2nd_class Passenger_Cat=3rd_class Passenger_Cat=crew all correspond to the same original target attribute: Passenger_Cat. We should group the decision tree target attributes per original target attribute. For each original attribute, we have to create an EQLiteral. Initial idea: Each one-hot encoding attribute has 2 possible class labels: [0, 1]. Each of these two possible class labels has a count: [c0, c1]. --> 1. take for each one-hot encoding target attribute the class label with the highest count, and create a literal for it, e.g.: Passenger_Cat=1st_class=0, (0 has higher count than 1) Passenger_Cat=2nd_class=0, (0 has higher count than 1) Passenger_Cat=3rd_class=0, (0 has higher count than 1) Passenger_Cat=crew=1 (1 has higher count than 0) 2. Only keep the literal with class label 1: Passenger_Cat=crew=1 3. Convert that literal back to the original attribute: Passenger_cat = crew PROBLEM: it might occur that for each one-hot encoded attribute, class label 0 has the highest count, e.g. Passenger_Cat=1st_class=0, (0 has higher count than 1) Passenger_Cat=2nd_class=0, (0 has higher count than 1) Passenger_Cat=3rd_class=0, (0 has higher count than 1) Passenger_Cat=crew=0 (0 has higher count than 1) --> NO literal with class value 1 --> EMPTY CONSEQUENT. SOLUTION: 1. for each one-hot encoding attribute, look at the count of class label 1 e.g. the following one-hot encoding attributes: Passenger_Cat=1st_class --> c11 for class label 1 Passenger_Cat=2nd_class --> c12 for class label 1 Passenger_Cat=3rd_class --> c13 for class label 1 Passenger_Cat=crew --> c14 for class label 1 2. pick the one-hot encoding attribute with the largest count for class label 1 -- BINARY ATTRIBUTES -- Parameters ---------- leaf_info nb_of_dt_target_attrs Returns ------- """ nb_of_target_attrs: int = leaf_info.nb_of_target_attributes self.__check_correct_number_of_target_attr(nb_of_target_attrs) literals: List[EQLiteral] = [] # get the indices for the decision tree target attributes corresponding to the original attributes: original_target_attr_to_decision_tree_target_attr_indices: Dict[Attr, List[int]] \ = self.get_original_attr_to_decision_tree_attr_mapping() original_target_attr: Attr dt_target_attr_indices: List[int] for original_target_attr, dt_target_attr_indices in \ original_target_attr_to_decision_tree_target_attr_indices.items(): if not self.__is_original_attr_binary(dt_target_attr_indices): opt_predictive_literal: Optional[EQLiteral] = self.__convert_n_ary_original_attibute( original_target_attr, dt_target_attr_indices, leaf_info) if opt_predictive_literal is not None: literals.append(opt_predictive_literal) elif self.__is_original_attr_binary(dt_target_attr_indices): predictive_literal: EQLiteral = self.__convert_binary_original_attribute( original_target_attr, dt_target_attr_indices, leaf_info) literals.append(predictive_literal) else: raise Exception("should not be in this situation") return literals
def convert(self, leaf_info: LeafInfo) -> List[EQLiteral]: """ This method converts a LeafInfo object to a Consequent of a rule. Note: a consequent can predict multiple attributes. It does this by storing one EQLiteral per predicted original attribute. A Scikit-learn DecisionTreeClassifier can predict multiple attributes. -- ONE-HOT ENCODED ATTRIBUTES -- In our framework, some of these target attributes belong to the same original attribute, using one-hot encodings. e.g. the following one-hot encoding attributes: Passenger_Cat=1st_class Passenger_Cat=2nd_class Passenger_Cat=3rd_class Passenger_Cat=crew all correspond to the same original target attribute: Passenger_Cat. We should group the decision tree target attributes per original target attribute. For each original attribute, we have to create an EQLiteral. Initial idea: Each one-hot encoding attribute has 2 possible class labels: [0, 1]. Each of these two possible class labels has a count: [c0, c1]. --> 1. take for each one-hot encoding target attribute the class label with the highest count, and create a literal for it, e.g.: Passenger_Cat=1st_class=0, (0 has higher count than 1) Passenger_Cat=2nd_class=0, (0 has higher count than 1) Passenger_Cat=3rd_class=0, (0 has higher count than 1) Passenger_Cat=crew=1 (1 has higher count than 0) 2. Only keep the literal with class label 1: Passenger_Cat=crew=1 3. Convert that literal back to the original attribute: Passenger_cat = crew PROBLEM: it might occur that for each one-hot encoded attribute, class label 0 has the highest count, e.g. Passenger_Cat=1st_class=0, (0 has higher count than 1) Passenger_Cat=2nd_class=0, (0 has higher count than 1) Passenger_Cat=3rd_class=0, (0 has higher count than 1) Passenger_Cat=crew=0 (0 has higher count than 1) --> NO literal with class value 1 --> EMPTY CONSEQUENT. SOLUTION: 1. for each one-hot encoding attribute, look at the count of class label 1 e.g. the following one-hot encoding attributes: Passenger_Cat=1st_class --> c11 for class label 1 Passenger_Cat=2nd_class --> c12 for class label 1 Passenger_Cat=3rd_class --> c13 for class label 1 Passenger_Cat=crew --> c14 for class label 1 2. pick the one-hot encoding attribute with the largest count for class label 1 -- BINARY ATTRIBUTES -- Parameters ---------- leaf_info nb_of_dt_target_attrs Returns ------- """ nb_of_target_attrs: int = leaf_info.nb_of_target_attributes self.__check_correct_number_of_target_attr(nb_of_target_attrs) literals: List[EQLiteral] = [] # get the indices for the decision tree target attributes corresponding to the original attributes: original_target_attr_to_decision_tree_target_attr_indices: Dict[Attr, List[int]] \ = self.get_original_attr_to_decision_tree_attr_mapping() original_target_attr: Attr dt_target_attr_indices: List[int] for original_target_attr, dt_target_attr_indices in \ original_target_attr_to_decision_tree_target_attr_indices.items(): if not self.__is_original_attr_binary(dt_target_attr_indices): opt_predictive_literal: Optional[EQLiteral] = self.__convert_n_ary_original_attibute( original_target_attr, dt_target_attr_indices, leaf_info) if opt_predictive_literal is not None: literals.append(opt_predictive_literal) elif self.__is_original_attr_binary(dt_target_attr_indices): predictive_literal: EQLiteral = self.__convert_binary_original_attribute( original_target_attr, dt_target_attr_indices, leaf_info) literals.append(predictive_literal) else: raise Exception("should not be in this situation") return literals
Python
def __get_decision_tree_attribute_with_highest_count_for_class_label_one(self, original_target_attr: Attr, dt_target_attr_indices: List[int], leaf_info: LeafInfo ) -> Optional[int]: """ Find the decision tree attribute with the highest count for class label 1 """ current_highest_count_for_class_label_one = float('-inf') dt_target_attr_index_with_current_highest_count: Optional[int] = None dt_target_attr_index: int for dt_target_attr_index in dt_target_attr_indices: # the possible class labels for the decision tree attribute, an array [0, 1] possible_class_labels_for_dt_target: SingleAttrClassLabelsList = \ leaf_info.get_possible_class_labels_for_decision_tree_attribute(dt_target_attr_index) # NOTE: it could be possible that the one-hot encoded lable does not occur. # in that case, the possible class labels for the decision tree attribute are [1] if possible_class_labels_for_dt_target.size > 2: raise Exception( f"expected two possible class labels (0 and 1) for " f"{self.dt_target_attr_names[dt_target_attr_index]} (original: {original_target_attr})," f" got {possible_class_labels_for_dt_target}") elif possible_class_labels_for_dt_target.size == 2: # counts per possible target label [0, 1] counts_per_label_for_target: np.ndarray = leaf_info.class_label_counts[dt_target_attr_index] if counts_per_label_for_target.size != 2: raise Exception( f"expected two counts for class labels 0 and 1 for " f"{self.dt_target_attr_names[dt_target_attr_index]} (original: {original_target_attr})," f" got {counts_per_label_for_target}") all_zeros: bool = not np.any(counts_per_label_for_target) if all_zeros: raise Exception("all labels have count 0") indexes_of_class_label_one = np.where(possible_class_labels_for_dt_target == 1) index_of_class_label_one: int = indexes_of_class_label_one[0][0] if index_of_class_label_one != 0 and index_of_class_label_one != 1: raise Exception( f"expected the index of class label 1 to be either 0 or 1 for " f"{self.dt_target_attr_names[dt_target_attr_index]} (original: {original_target_attr})," f" got {index_of_class_label_one}") count_of_class_label_one: int = counts_per_label_for_target[index_of_class_label_one] if count_of_class_label_one > current_highest_count_for_class_label_one: current_highest_count_for_class_label_one = count_of_class_label_one dt_target_attr_index_with_current_highest_count = dt_target_attr_index else: pass elif possible_class_labels_for_dt_target.size == 1: dt_target_attr = self.dt_target_attr_names[dt_target_attr_index] print(f"possible class labels for {dt_target_attr}: {possible_class_labels_for_dt_target}") counts_per_label_for_target: np.ndarray = leaf_info.class_label_counts[dt_target_attr_index] print(f"counts: {counts_per_label_for_target}") if counts_per_label_for_target.size != 2: raise Exception( f"expected two count for class labels 0 and 1" f"{self.dt_target_attr_names[dt_target_attr_index]} (original: {original_target_attr})," f" got {counts_per_label_for_target}") all_zeros: bool = not np.any(counts_per_label_for_target) if all_zeros: raise Exception("all labels have count 0") print("ONEONEONE") pass if dt_target_attr_index_with_current_highest_count is None: print( f"WARNING: no highest count for any attribute of {original_target_attr}. It might be constant in the training data.") return dt_target_attr_index_with_current_highest_count
def __get_decision_tree_attribute_with_highest_count_for_class_label_one(self, original_target_attr: Attr, dt_target_attr_indices: List[int], leaf_info: LeafInfo ) -> Optional[int]: """ Find the decision tree attribute with the highest count for class label 1 """ current_highest_count_for_class_label_one = float('-inf') dt_target_attr_index_with_current_highest_count: Optional[int] = None dt_target_attr_index: int for dt_target_attr_index in dt_target_attr_indices: # the possible class labels for the decision tree attribute, an array [0, 1] possible_class_labels_for_dt_target: SingleAttrClassLabelsList = \ leaf_info.get_possible_class_labels_for_decision_tree_attribute(dt_target_attr_index) # NOTE: it could be possible that the one-hot encoded lable does not occur. # in that case, the possible class labels for the decision tree attribute are [1] if possible_class_labels_for_dt_target.size > 2: raise Exception( f"expected two possible class labels (0 and 1) for " f"{self.dt_target_attr_names[dt_target_attr_index]} (original: {original_target_attr})," f" got {possible_class_labels_for_dt_target}") elif possible_class_labels_for_dt_target.size == 2: # counts per possible target label [0, 1] counts_per_label_for_target: np.ndarray = leaf_info.class_label_counts[dt_target_attr_index] if counts_per_label_for_target.size != 2: raise Exception( f"expected two counts for class labels 0 and 1 for " f"{self.dt_target_attr_names[dt_target_attr_index]} (original: {original_target_attr})," f" got {counts_per_label_for_target}") all_zeros: bool = not np.any(counts_per_label_for_target) if all_zeros: raise Exception("all labels have count 0") indexes_of_class_label_one = np.where(possible_class_labels_for_dt_target == 1) index_of_class_label_one: int = indexes_of_class_label_one[0][0] if index_of_class_label_one != 0 and index_of_class_label_one != 1: raise Exception( f"expected the index of class label 1 to be either 0 or 1 for " f"{self.dt_target_attr_names[dt_target_attr_index]} (original: {original_target_attr})," f" got {index_of_class_label_one}") count_of_class_label_one: int = counts_per_label_for_target[index_of_class_label_one] if count_of_class_label_one > current_highest_count_for_class_label_one: current_highest_count_for_class_label_one = count_of_class_label_one dt_target_attr_index_with_current_highest_count = dt_target_attr_index else: pass elif possible_class_labels_for_dt_target.size == 1: dt_target_attr = self.dt_target_attr_names[dt_target_attr_index] print(f"possible class labels for {dt_target_attr}: {possible_class_labels_for_dt_target}") counts_per_label_for_target: np.ndarray = leaf_info.class_label_counts[dt_target_attr_index] print(f"counts: {counts_per_label_for_target}") if counts_per_label_for_target.size != 2: raise Exception( f"expected two count for class labels 0 and 1" f"{self.dt_target_attr_names[dt_target_attr_index]} (original: {original_target_attr})," f" got {counts_per_label_for_target}") all_zeros: bool = not np.any(counts_per_label_for_target) if all_zeros: raise Exception("all labels have count 0") print("ONEONEONE") pass if dt_target_attr_index_with_current_highest_count is None: print( f"WARNING: no highest count for any attribute of {original_target_attr}. It might be constant in the training data.") return dt_target_attr_index_with_current_highest_count
Python
def ___minmax_class_in_uncovered_examples_for_target_attibute(self, ruleset: Set[MIDSRule], dataframe_training_data: pd.DataFrame, target_attribute: str, rule_combinator: RuleCombinator, to_get='MINORITY' ): """ Default class = majority class in the uncovered examples Examples not covered by ANY rule? Examples not covered by a rule predicting a target? I.e. per target attribute, a different set of attributes. :return: """ # note: following contains None if no predicted value found predicted_class_per_row = rule_combinator.predict(ruleset, dataframe_training_data, target_attribute, default_value=None) indexes_unclassified_instances = [idx for idx, val in enumerate(predicted_class_per_row) if val == None] actual_classes_unclassified_instances = dataframe_training_data[target_attribute].iloc[ indexes_unclassified_instances] # return random class if all examples have a predicted value if len(list(actual_classes_unclassified_instances)) == 0: distinct_class_values = set(np.unique(dataframe_training_data[target_attribute])) default_class = random.sample( distinct_class_values, 1 )[0] else: counts = Counter(list(actual_classes_unclassified_instances)) if to_get == 'MAJORITY': majority_class = max(counts, key=counts.get) default_class = majority_class elif to_get == 'MINORITY': minority_class = min(counts, key=counts.get) default_class = minority_class else: raise Exception("Should not reach this. Got " + str(to_get) + " as value of to_get parameter.") return default_class
def ___minmax_class_in_uncovered_examples_for_target_attibute(self, ruleset: Set[MIDSRule], dataframe_training_data: pd.DataFrame, target_attribute: str, rule_combinator: RuleCombinator, to_get='MINORITY' ): """ Default class = majority class in the uncovered examples Examples not covered by ANY rule? Examples not covered by a rule predicting a target? I.e. per target attribute, a different set of attributes. :return: """ # note: following contains None if no predicted value found predicted_class_per_row = rule_combinator.predict(ruleset, dataframe_training_data, target_attribute, default_value=None) indexes_unclassified_instances = [idx for idx, val in enumerate(predicted_class_per_row) if val == None] actual_classes_unclassified_instances = dataframe_training_data[target_attribute].iloc[ indexes_unclassified_instances] # return random class if all examples have a predicted value if len(list(actual_classes_unclassified_instances)) == 0: distinct_class_values = set(np.unique(dataframe_training_data[target_attribute])) default_class = random.sample( distinct_class_values, 1 )[0] else: counts = Counter(list(actual_classes_unclassified_instances)) if to_get == 'MAJORITY': majority_class = max(counts, key=counts.get) default_class = majority_class elif to_get == 'MINORITY': minority_class = min(counts, key=counts.get) default_class = minority_class else: raise Exception("Should not reach this. Got " + str(to_get) + " as value of to_get parameter.") return default_class
Python
def multi_target_cars_to_st_mcars(multi_target_mcars: List[MCAR], target_attr_list: Optional[List[TargetAttr]] = None ) -> Dict[TargetAttr, List[MCAR]]: """ Given a set of multi-target rules, get the single-target class association rules. :param target_attr_list: :param multi_target_mcars: :return: """ target_attr_to_st_rule_list_map: Dict[TargetAttr, List[MCAR]] = dict() rule: MCAR for rule in multi_target_mcars: if len(rule.consequent) == 1: target_attr: TargetAttr = list(rule.consequent.get_attributes())[0] # check if it already exists target_attr_rule_list: Optional[List[MCAR]] = target_attr_to_st_rule_list_map.get(target_attr, None) if target_attr_rule_list is None: target_attr_rule_list: List[MCAR] = [rule] target_attr_to_st_rule_list_map[target_attr] = target_attr_rule_list else: target_attr_rule_list.append(rule) else: pass if target_attr_list is not None: for target_attr in target_attr_list: if target_attr not in target_attr_to_st_rule_list_map.keys(): target_attr_to_st_rule_list_map[target_attr] = [] return target_attr_to_st_rule_list_map
def multi_target_cars_to_st_mcars(multi_target_mcars: List[MCAR], target_attr_list: Optional[List[TargetAttr]] = None ) -> Dict[TargetAttr, List[MCAR]]: """ Given a set of multi-target rules, get the single-target class association rules. :param target_attr_list: :param multi_target_mcars: :return: """ target_attr_to_st_rule_list_map: Dict[TargetAttr, List[MCAR]] = dict() rule: MCAR for rule in multi_target_mcars: if len(rule.consequent) == 1: target_attr: TargetAttr = list(rule.consequent.get_attributes())[0] # check if it already exists target_attr_rule_list: Optional[List[MCAR]] = target_attr_to_st_rule_list_map.get(target_attr, None) if target_attr_rule_list is None: target_attr_rule_list: List[MCAR] = [rule] target_attr_to_st_rule_list_map[target_attr] = target_attr_rule_list else: target_attr_rule_list.append(rule) else: pass if target_attr_list is not None: for target_attr in target_attr_list: if target_attr not in target_attr_to_st_rule_list_map.keys(): target_attr_to_st_rule_list_map[target_attr] = [] return target_attr_to_st_rule_list_map
Python
def mine_n_rules(self, df: pd.DataFrame, rule_cutoff: int) -> List[MCAR]: """ Tries to find the 'rule_cutoff' best rules in using an iterative approach. """ transactions: List[List[str]] = dataframe_to_list_of_transactions(df) best_rules: Optional[List[MCAR]] = self._iteratively_find_best_rules( transactions, target_rule_count=rule_cutoff) if best_rules is None: raise Exception("no rules found") if len(best_rules) > rule_cutoff: if self.should_sample_if_found_too_many_rules: rule_subset = self.__subsample_found_rules(best_rules, rule_cutoff) else: rule_subset = best_rules[:rule_cutoff] # TODO: this is pretty fishy else: rule_subset = best_rules return rule_subset
def mine_n_rules(self, df: pd.DataFrame, rule_cutoff: int) -> List[MCAR]: """ Tries to find the 'rule_cutoff' best rules in using an iterative approach. """ transactions: List[List[str]] = dataframe_to_list_of_transactions(df) best_rules: Optional[List[MCAR]] = self._iteratively_find_best_rules( transactions, target_rule_count=rule_cutoff) if best_rules is None: raise Exception("no rules found") if len(best_rules) > rule_cutoff: if self.should_sample_if_found_too_many_rules: rule_subset = self.__subsample_found_rules(best_rules, rule_cutoff) else: rule_subset = best_rules[:rule_cutoff] # TODO: this is pretty fishy else: rule_subset = best_rules return rule_subset
Python
def _iteratively_find_best_rules(self, transactions: List[List[str]], target_rule_count: int = 1000 ): """ Function for finding the best n (target_rule_count) rules from transaction list. PROBLEM: how to define 'best'? Iteratively: Search for the rules under the current mining parameters. Check the properties of the found rules. If there is still room for improvement, Then update the mining parameters, STOP if: - max nb of iterations is reached (default: 30). - the current nb of rules is more than the nb of rules we are looking for. - the time out is reach FIND all rules with as constraints: - min_support - min_confidence - max_length Parameters ---------- :param transactions : 2D array of strings, e.g. [["a:=:1", "b:=:3"], ["a:=:4", "b:=:2"]] :param target_rule_count : int - target number of rules to mine Returns ------- list of mined rules. The rules are not ordered. """ start_time: float = time.time() # the length of a rule is at most the length of a transaction. (All transactions have the same length.) TRANSACTION_LENGTH: int = len(transactions[0]) rule_length_upper_boundary = min(TRANSACTION_LENGTH, self.max_wanted_rule_length) keep_mining: bool = True self.__get_initial_mining_parameters() # current_support: float = self.init_support # current_confidence: float = self.init_confidence # current_max_length: int = self.init_max_length last_rule_count = -1 current_rules: Optional[List[MCAR]] = None current_iteration = 0 if self.verbose: print("STARTING top_rules") while keep_mining and not self._is_max_n_iterations_reached( current_iteration) and not self._is_time_out_exceeded(start_time): current_iteration += 1 if self._is_stuck_in_local_optimum(): break current_mining_params: MiningParameters = self.get_current_mining_params() if self.verbose: print(f"--- iteration {current_iteration} ---") print((f"Running apriori with setting: " f"confidence={current_mining_params.confidence}, " f"support={current_mining_params.support}, " f"min_length={self.min_length}, " f"max_length={current_mining_params.max_rule_length}, " f"TRANSACTION_LENGTH={TRANSACTION_LENGTH}", f"max_wanted_rule_length={self.max_wanted_rule_length}" )) current_rules: List[MCAR] = mine_MCARs_from_transactions_using_apyori( transactions, min_support=current_mining_params.support, min_confidence=current_mining_params.confidence, max_length=current_mining_params.max_rule_length) current_nb_of_rules = len(current_rules) if self.verbose: print(f"Rule count: {current_nb_of_rules}, Iteration: {current_iteration}") # if: nb of target rules is succeeded # then: increase the confidence if self._is_target_rule_count_exceeded(target_rule_count, current_nb_of_rules): if self.verbose: print(f"Target rule count exceeded: {current_nb_of_rules} > {target_rule_count}") if (1.0 - current_mining_params.confidence) > self.confidence_step: next_mining_params = current_mining_params.get_copy() next_mining_params.confidence += self.confidence_step self.add_update_mining_params(next_mining_params) if self.verbose: print(f"\tINcreasing confidence to {next_mining_params.confidence}") elif (1.0 - current_mining_params.support) > self.support_step: next_mining_params = current_mining_params.get_copy() next_mining_params.support += self.support_step self.add_update_mining_params(next_mining_params) if self.verbose: print(f"\tINcreasing support to {next_mining_params.support}") else: if self.verbose: print("Target rule count exceeded, no options left") keep_mining = False else: if self.verbose: print(f"Target rule count NOT exceeded: {current_nb_of_rules} < {target_rule_count}") # NB of rules is not exceeded! # what can we do? # * IF we have not reached the max rule length # and the nb of rules went up since last time # THEN: # increase the rule length # # if we can still increase our rule length AND # the number of rules found has changed (increased?) since last time AND # there has if ( current_mining_params.max_rule_length < rule_length_upper_boundary and last_rule_count != current_nb_of_rules ): next_mining_params = current_mining_params.get_copy() next_mining_params.max_rule_length += 1 self.add_update_mining_params(next_mining_params) if self.verbose: print(f"\tIncreasing max_length {next_mining_params.max_rule_length}") # if we can still increase our rule length AND # # we can still increase our support # THEN: # increase our support # increment our max length elif ( current_mining_params.max_rule_length < rule_length_upper_boundary and current_mining_params.support <= 1 - self.support_step ): next_mining_params = current_mining_params.get_copy() next_mining_params.support -= self.support_step self.add_update_mining_params(next_mining_params) if self.verbose: print(f"\tDecreasing minsup to {next_mining_params.support}") # IF we can still decrease our confidence # THEN decrease our confidence elif current_mining_params.confidence > self.confidence_step: next_mining_params = current_mining_params.get_copy() next_mining_params.confidence -= self.confidence_step self.add_update_mining_params(next_mining_params) if self.verbose: print(f"\tDecreasing confidence to {next_mining_params.confidence}") else: if self.verbose: print("\tAll options exhausted") keep_mining = False if self.verbose: end_of_current_iteration_message = f"--- end iteration {current_iteration} ---" print(end_of_current_iteration_message) print("-" * len(end_of_current_iteration_message)) last_rule_count = current_nb_of_rules if self.verbose: print(f"FINISHED top_rules after {current_iteration} iterations") return current_rules
def _iteratively_find_best_rules(self, transactions: List[List[str]], target_rule_count: int = 1000 ): """ Function for finding the best n (target_rule_count) rules from transaction list. PROBLEM: how to define 'best'? Iteratively: Search for the rules under the current mining parameters. Check the properties of the found rules. If there is still room for improvement, Then update the mining parameters, STOP if: - max nb of iterations is reached (default: 30). - the current nb of rules is more than the nb of rules we are looking for. - the time out is reach FIND all rules with as constraints: - min_support - min_confidence - max_length Parameters ---------- :param transactions : 2D array of strings, e.g. [["a:=:1", "b:=:3"], ["a:=:4", "b:=:2"]] :param target_rule_count : int - target number of rules to mine Returns ------- list of mined rules. The rules are not ordered. """ start_time: float = time.time() # the length of a rule is at most the length of a transaction. (All transactions have the same length.) TRANSACTION_LENGTH: int = len(transactions[0]) rule_length_upper_boundary = min(TRANSACTION_LENGTH, self.max_wanted_rule_length) keep_mining: bool = True self.__get_initial_mining_parameters() # current_support: float = self.init_support # current_confidence: float = self.init_confidence # current_max_length: int = self.init_max_length last_rule_count = -1 current_rules: Optional[List[MCAR]] = None current_iteration = 0 if self.verbose: print("STARTING top_rules") while keep_mining and not self._is_max_n_iterations_reached( current_iteration) and not self._is_time_out_exceeded(start_time): current_iteration += 1 if self._is_stuck_in_local_optimum(): break current_mining_params: MiningParameters = self.get_current_mining_params() if self.verbose: print(f"--- iteration {current_iteration} ---") print((f"Running apriori with setting: " f"confidence={current_mining_params.confidence}, " f"support={current_mining_params.support}, " f"min_length={self.min_length}, " f"max_length={current_mining_params.max_rule_length}, " f"TRANSACTION_LENGTH={TRANSACTION_LENGTH}", f"max_wanted_rule_length={self.max_wanted_rule_length}" )) current_rules: List[MCAR] = mine_MCARs_from_transactions_using_apyori( transactions, min_support=current_mining_params.support, min_confidence=current_mining_params.confidence, max_length=current_mining_params.max_rule_length) current_nb_of_rules = len(current_rules) if self.verbose: print(f"Rule count: {current_nb_of_rules}, Iteration: {current_iteration}") # if: nb of target rules is succeeded # then: increase the confidence if self._is_target_rule_count_exceeded(target_rule_count, current_nb_of_rules): if self.verbose: print(f"Target rule count exceeded: {current_nb_of_rules} > {target_rule_count}") if (1.0 - current_mining_params.confidence) > self.confidence_step: next_mining_params = current_mining_params.get_copy() next_mining_params.confidence += self.confidence_step self.add_update_mining_params(next_mining_params) if self.verbose: print(f"\tINcreasing confidence to {next_mining_params.confidence}") elif (1.0 - current_mining_params.support) > self.support_step: next_mining_params = current_mining_params.get_copy() next_mining_params.support += self.support_step self.add_update_mining_params(next_mining_params) if self.verbose: print(f"\tINcreasing support to {next_mining_params.support}") else: if self.verbose: print("Target rule count exceeded, no options left") keep_mining = False else: if self.verbose: print(f"Target rule count NOT exceeded: {current_nb_of_rules} < {target_rule_count}") # NB of rules is not exceeded! # what can we do? # * IF we have not reached the max rule length # and the nb of rules went up since last time # THEN: # increase the rule length # # if we can still increase our rule length AND # the number of rules found has changed (increased?) since last time AND # there has if ( current_mining_params.max_rule_length < rule_length_upper_boundary and last_rule_count != current_nb_of_rules ): next_mining_params = current_mining_params.get_copy() next_mining_params.max_rule_length += 1 self.add_update_mining_params(next_mining_params) if self.verbose: print(f"\tIncreasing max_length {next_mining_params.max_rule_length}") # if we can still increase our rule length AND # # we can still increase our support # THEN: # increase our support # increment our max length elif ( current_mining_params.max_rule_length < rule_length_upper_boundary and current_mining_params.support <= 1 - self.support_step ): next_mining_params = current_mining_params.get_copy() next_mining_params.support -= self.support_step self.add_update_mining_params(next_mining_params) if self.verbose: print(f"\tDecreasing minsup to {next_mining_params.support}") # IF we can still decrease our confidence # THEN decrease our confidence elif current_mining_params.confidence > self.confidence_step: next_mining_params = current_mining_params.get_copy() next_mining_params.confidence -= self.confidence_step self.add_update_mining_params(next_mining_params) if self.verbose: print(f"\tDecreasing confidence to {next_mining_params.confidence}") else: if self.verbose: print("\tAll options exhausted") keep_mining = False if self.verbose: end_of_current_iteration_message = f"--- end iteration {current_iteration} ---" print(end_of_current_iteration_message) print("-" * len(end_of_current_iteration_message)) last_rule_count = current_nb_of_rules if self.verbose: print(f"FINISHED top_rules after {current_iteration} iterations") return current_rules
Python
def main(): """ Example of how decision trees predicting multiple targets can be turned into a rule set. """ sys.path.append(os.path.join(project_dir, 'src')) sys.path.append(os.path.join(project_dir, 'external/pyARC')) sys.path.append(os.path.join(project_dir, 'external/pyIDS')) should_plot_trees: bool = True nb_of_original_targets_to_predict = 1 # --- Loading data ------------------------------------------------------------------------------------------------ dataset_name = 'titanic' train_test_dir = os.path.join(project_dir, 'data/interim/' + dataset_name) df_train_one_hot_encoded = pd.read_csv( os.path.join(train_test_dir, f'{dataset_name}_train_ohe.csv')) # df_test_one_hot_encoded = pd.read_csv( # os.path.join(train_test_dir, f'{dataset_name}_test_ohe.csv')) # --- creating an encoding ---------------------------------------------------------------------------------------- encoding_book_keeper = EncodingBookKeeper(ohe_prefix_separator='=') encoding_book_keeper.parse_and_store_one_hot_encoded_columns(df_train_one_hot_encoded.columns) # --- Learning one decision tree per attribute --------------------------------------------------------------------- tree_classifiers: Dict[Tuple[Attr], DTInfo] = {} original_target_attr_combo: Tuple[Attr] for original_target_attr_combo in get_combinations_of_original_target_attributes( encoding_book_keeper, nb_of_original_targets_to_predict): # --- Select the descriptive and target attributes ------------------------------------------------------------- ohe_descriptive_attrs: List[Attr] ohe_target_attrs: List[Attr] ohe_descriptive_attrs, ohe_target_attrs = get_ohe_descriptive_and_target_attributes( original_target_attr_combo, encoding_book_keeper) df_train_one_hot_encoded_descriptive = df_train_one_hot_encoded.loc[:, ohe_descriptive_attrs] df_train_one_hot_encoded_target = df_train_one_hot_encoded.loc[:, ohe_target_attrs] print("original targets:", original_target_attr_combo) print("OHE descriptive attrs:") print("\t", ohe_descriptive_attrs) print("OHE target attrs:") print("\t", ohe_target_attrs) # --- Fit a decision tree ----------------------------------------------------------------------------------- tree_clf = DecisionTreeClassifier() tree_clf.fit(df_train_one_hot_encoded_descriptive, df_train_one_hot_encoded_target) dt_info = DTInfo(original_target_attributes=original_target_attr_combo, tree_classifier=tree_clf, ohe_descriptive_attrs=ohe_descriptive_attrs, ohe_target_attrs=ohe_target_attrs) tree_classifiers[original_target_attr_combo] = dt_info print("---") # --- Convert the fitted decision tree classifiers to rules ------------------------------------------------------- all_rules: List[MIDSRule] = [] original_target_attributes: Tuple[Attr] dt_info: DTInfo for original_target_attributes, dt_info in tree_classifiers.items(): tree_clf = dt_info.tree_classifier if should_plot_trees: plot_tree(dt_info) list_of_dt_rules = convert_decision_tree_to_mids_rule_list( tree_classifier=tree_clf, one_hot_encoded_feature_names=dt_info.ohe_descriptive_attrs, target_attribute_names=dt_info.ohe_target_attrs, encoding_book_keeper=encoding_book_keeper) print(f"original target attributes: {original_target_attributes}") for rule in list_of_dt_rules: print("\t", mids_mcar_to_pretty_string(rule.car)) print() all_rules.extend(list_of_dt_rules)
def main(): """ Example of how decision trees predicting multiple targets can be turned into a rule set. """ sys.path.append(os.path.join(project_dir, 'src')) sys.path.append(os.path.join(project_dir, 'external/pyARC')) sys.path.append(os.path.join(project_dir, 'external/pyIDS')) should_plot_trees: bool = True nb_of_original_targets_to_predict = 1 # --- Loading data ------------------------------------------------------------------------------------------------ dataset_name = 'titanic' train_test_dir = os.path.join(project_dir, 'data/interim/' + dataset_name) df_train_one_hot_encoded = pd.read_csv( os.path.join(train_test_dir, f'{dataset_name}_train_ohe.csv')) # df_test_one_hot_encoded = pd.read_csv( # os.path.join(train_test_dir, f'{dataset_name}_test_ohe.csv')) # --- creating an encoding ---------------------------------------------------------------------------------------- encoding_book_keeper = EncodingBookKeeper(ohe_prefix_separator='=') encoding_book_keeper.parse_and_store_one_hot_encoded_columns(df_train_one_hot_encoded.columns) # --- Learning one decision tree per attribute --------------------------------------------------------------------- tree_classifiers: Dict[Tuple[Attr], DTInfo] = {} original_target_attr_combo: Tuple[Attr] for original_target_attr_combo in get_combinations_of_original_target_attributes( encoding_book_keeper, nb_of_original_targets_to_predict): # --- Select the descriptive and target attributes ------------------------------------------------------------- ohe_descriptive_attrs: List[Attr] ohe_target_attrs: List[Attr] ohe_descriptive_attrs, ohe_target_attrs = get_ohe_descriptive_and_target_attributes( original_target_attr_combo, encoding_book_keeper) df_train_one_hot_encoded_descriptive = df_train_one_hot_encoded.loc[:, ohe_descriptive_attrs] df_train_one_hot_encoded_target = df_train_one_hot_encoded.loc[:, ohe_target_attrs] print("original targets:", original_target_attr_combo) print("OHE descriptive attrs:") print("\t", ohe_descriptive_attrs) print("OHE target attrs:") print("\t", ohe_target_attrs) # --- Fit a decision tree ----------------------------------------------------------------------------------- tree_clf = DecisionTreeClassifier() tree_clf.fit(df_train_one_hot_encoded_descriptive, df_train_one_hot_encoded_target) dt_info = DTInfo(original_target_attributes=original_target_attr_combo, tree_classifier=tree_clf, ohe_descriptive_attrs=ohe_descriptive_attrs, ohe_target_attrs=ohe_target_attrs) tree_classifiers[original_target_attr_combo] = dt_info print("---") # --- Convert the fitted decision tree classifiers to rules ------------------------------------------------------- all_rules: List[MIDSRule] = [] original_target_attributes: Tuple[Attr] dt_info: DTInfo for original_target_attributes, dt_info in tree_classifiers.items(): tree_clf = dt_info.tree_classifier if should_plot_trees: plot_tree(dt_info) list_of_dt_rules = convert_decision_tree_to_mids_rule_list( tree_classifier=tree_clf, one_hot_encoded_feature_names=dt_info.ohe_descriptive_attrs, target_attribute_names=dt_info.ohe_target_attrs, encoding_book_keeper=encoding_book_keeper) print(f"original target attributes: {original_target_attributes}") for rule in list_of_dt_rules: print("\t", mids_mcar_to_pretty_string(rule.car)) print() all_rules.extend(list_of_dt_rules)
Python
def f0_minimize_rule_set_size(self, ground_set_size: int, current_nb_of_rules: int): """ Minimize the number of rules in the rule set :return: """ f0_unnormalized = ground_set_size - current_nb_of_rules if self.normalize and ground_set_size > 0: f0 = f0_unnormalized / ground_set_size else: f0 = f0_unnormalized self._normalized_boundary_check(f0, 'f0') return f0
def f0_minimize_rule_set_size(self, ground_set_size: int, current_nb_of_rules: int): """ Minimize the number of rules in the rule set :return: """ f0_unnormalized = ground_set_size - current_nb_of_rules if self.normalize and ground_set_size > 0: f0 = f0_unnormalized / ground_set_size else: f0 = f0_unnormalized self._normalized_boundary_check(f0, 'f0') return f0
Python
def fraction_bodily_overlap(ruleset: IDSRuleSet, quant_dataframe: QuantitativeDataFrame) -> float: """ This metric captures the extend of overlap between every pair of rules in a decision set R. Smaller values of this metric signify higher interpretability. Boundary values: 0.0 if no rules in R overlap: 1.0 if all data points in are covered by all rules in R. NOTE: * this is 0.0 for any decision list, because their if-else structure ensures that a rule in the list applies only to those data points which have not been covered by any of the preceeding rules * this is 0.0 for the empty rule set :param ruleset: :param quant_dataframe: :return: """ if type(ruleset) != IDSRuleSet: raise Exception("Type of ruleset must be IDSRuleSet") if type(quant_dataframe) != QuantitativeDataFrame: raise Exception("Type of quant_dataframe must be QuantitativeDataFrame") ruleset_size = len(ruleset) if ruleset_size == 0: print("Warning: the IDS rule set is empty.") return 0.0 nb_of_test_examples: int = quant_dataframe.dataframe.index.size if nb_of_test_examples == 0: raise Exception("There are no test instances to calculate overlap on") rule: IDSRule for rule in ruleset.ruleset: rule.calculate_cover(quant_dataframe) overlap_sum: int = 0 for i, rule_i in enumerate(ruleset.ruleset): for j, rule_j in enumerate(ruleset.ruleset): if i <= j: continue overlap_sum += np.sum(rule_i.rule_overlap(rule_j, quant_dataframe)) if overlap_sum == 0: warnings.warn("overlap is 0, which is unlikely") return 0 else: frac_overlap: float = 2 / (ruleset_size * (ruleset_size - 1)) * overlap_sum / nb_of_test_examples if not is_valid_fraction(frac_overlap): raise Exception("Fraction overlap is not within [0,1]: " + str(frac_overlap)) return frac_overlap
def fraction_bodily_overlap(ruleset: IDSRuleSet, quant_dataframe: QuantitativeDataFrame) -> float: """ This metric captures the extend of overlap between every pair of rules in a decision set R. Smaller values of this metric signify higher interpretability. Boundary values: 0.0 if no rules in R overlap: 1.0 if all data points in are covered by all rules in R. NOTE: * this is 0.0 for any decision list, because their if-else structure ensures that a rule in the list applies only to those data points which have not been covered by any of the preceeding rules * this is 0.0 for the empty rule set :param ruleset: :param quant_dataframe: :return: """ if type(ruleset) != IDSRuleSet: raise Exception("Type of ruleset must be IDSRuleSet") if type(quant_dataframe) != QuantitativeDataFrame: raise Exception("Type of quant_dataframe must be QuantitativeDataFrame") ruleset_size = len(ruleset) if ruleset_size == 0: print("Warning: the IDS rule set is empty.") return 0.0 nb_of_test_examples: int = quant_dataframe.dataframe.index.size if nb_of_test_examples == 0: raise Exception("There are no test instances to calculate overlap on") rule: IDSRule for rule in ruleset.ruleset: rule.calculate_cover(quant_dataframe) overlap_sum: int = 0 for i, rule_i in enumerate(ruleset.ruleset): for j, rule_j in enumerate(ruleset.ruleset): if i <= j: continue overlap_sum += np.sum(rule_i.rule_overlap(rule_j, quant_dataframe)) if overlap_sum == 0: warnings.warn("overlap is 0, which is unlikely") return 0 else: frac_overlap: float = 2 / (ruleset_size * (ruleset_size - 1)) * overlap_sum / nb_of_test_examples if not is_valid_fraction(frac_overlap): raise Exception("Fraction overlap is not within [0,1]: " + str(frac_overlap)) return frac_overlap
Python
def fraction_uncovered_examples(ruleset: IDSRuleSet, quant_dataframe: QuantitativeDataFrame) -> float: """ This metric computes the fraction of the data points which are not covered by any rule in the decision set. REMEMBER, COVER is independent of the head of a rule. Boundary values: 0.0 if every data point is covered by some rule in the data set. 1.0 when no data point is covered by any rule in R (This could be the case when |R| = 0 ) Note: * for decision lists, this metric is the fraction of the data points that are covered by the ELSE clause of the list (i.e. the default prediction). :param ruleset: :param quant_dataframe:: :return: """ if type(ruleset) != IDSRuleSet: raise Exception("Type of ruleset must be IDSRuleSet") if type(quant_dataframe) != QuantitativeDataFrame: raise Exception("Type of quant_dataframe must be QuantitativeDataFrame") nb_of_test_examples = quant_dataframe.dataframe.index.size if nb_of_test_examples == 0: raise Exception("There are no test instances to calculate the fraction uncovered on") cover_cumulative_mask: np.ndarray = np.zeros(nb_of_test_examples, dtype=bool) for rule in ruleset.ruleset: cover_mask = rule._cover(quant_dataframe) cover_cumulative_mask = np.logical_or(cover_cumulative_mask, cover_mask) nb_of_covered_test_examples: int = np.count_nonzero(cover_cumulative_mask) frac_uncovered = 1 - 1 / nb_of_test_examples * nb_of_covered_test_examples if not is_valid_fraction(frac_uncovered): raise Exception("Fraction uncovered examples is not within [0,1]: " + str(frac_uncovered)) return frac_uncovered
def fraction_uncovered_examples(ruleset: IDSRuleSet, quant_dataframe: QuantitativeDataFrame) -> float: """ This metric computes the fraction of the data points which are not covered by any rule in the decision set. REMEMBER, COVER is independent of the head of a rule. Boundary values: 0.0 if every data point is covered by some rule in the data set. 1.0 when no data point is covered by any rule in R (This could be the case when |R| = 0 ) Note: * for decision lists, this metric is the fraction of the data points that are covered by the ELSE clause of the list (i.e. the default prediction). :param ruleset: :param quant_dataframe:: :return: """ if type(ruleset) != IDSRuleSet: raise Exception("Type of ruleset must be IDSRuleSet") if type(quant_dataframe) != QuantitativeDataFrame: raise Exception("Type of quant_dataframe must be QuantitativeDataFrame") nb_of_test_examples = quant_dataframe.dataframe.index.size if nb_of_test_examples == 0: raise Exception("There are no test instances to calculate the fraction uncovered on") cover_cumulative_mask: np.ndarray = np.zeros(nb_of_test_examples, dtype=bool) for rule in ruleset.ruleset: cover_mask = rule._cover(quant_dataframe) cover_cumulative_mask = np.logical_or(cover_cumulative_mask, cover_mask) nb_of_covered_test_examples: int = np.count_nonzero(cover_cumulative_mask) frac_uncovered = 1 - 1 / nb_of_test_examples * nb_of_covered_test_examples if not is_valid_fraction(frac_uncovered): raise Exception("Fraction uncovered examples is not within [0,1]: " + str(frac_uncovered)) return frac_uncovered
Python
def fraction_predicted_classes(ruleset: IDSRuleSet, quant_dataframe: QuantitativeDataFrame) -> float: """ This metric denotes the fraction of the classes in the data that are predicted by the ruleset R. Boundary value: 0.0 if no class is predicted (e.g. the ruleset is empty) 1.0 every class is predicted by some rule in R. Note: * The same for decision lists, but we not consider the ELSE clause (the default prediction). :param ruleset: :param quant_dataframe: :return: """ if type(ruleset) != IDSRuleSet: raise Exception("Type of ruleset must be IDSRuleSet") if type(quant_dataframe) != QuantitativeDataFrame: raise Exception("Type of quant_dataframe must be QuantitativeDataFrame") values_occuring_in_data: Set[TargetVal] = set(quant_dataframe.dataframe.iloc[:, -1].values) values_predicted_by_rules: Set[TargetVal] = set() for rule in ruleset.ruleset: covered_class: TargetVal = rule.car.consequent.value if covered_class in values_occuring_in_data: values_predicted_by_rules.add(covered_class) nb_of_values_predicted_by_rules = len(values_predicted_by_rules) nb_of_values_occuring_in_test_data = len(values_occuring_in_data) frac_classes: float = nb_of_values_predicted_by_rules / nb_of_values_occuring_in_test_data if not is_valid_fraction(frac_classes): raise Exception("Fraction predicted classes examples is not within [0,1]: " + str(frac_classes)) return frac_classes
def fraction_predicted_classes(ruleset: IDSRuleSet, quant_dataframe: QuantitativeDataFrame) -> float: """ This metric denotes the fraction of the classes in the data that are predicted by the ruleset R. Boundary value: 0.0 if no class is predicted (e.g. the ruleset is empty) 1.0 every class is predicted by some rule in R. Note: * The same for decision lists, but we not consider the ELSE clause (the default prediction). :param ruleset: :param quant_dataframe: :return: """ if type(ruleset) != IDSRuleSet: raise Exception("Type of ruleset must be IDSRuleSet") if type(quant_dataframe) != QuantitativeDataFrame: raise Exception("Type of quant_dataframe must be QuantitativeDataFrame") values_occuring_in_data: Set[TargetVal] = set(quant_dataframe.dataframe.iloc[:, -1].values) values_predicted_by_rules: Set[TargetVal] = set() for rule in ruleset.ruleset: covered_class: TargetVal = rule.car.consequent.value if covered_class in values_occuring_in_data: values_predicted_by_rules.add(covered_class) nb_of_values_predicted_by_rules = len(values_predicted_by_rules) nb_of_values_occuring_in_test_data = len(values_occuring_in_data) frac_classes: float = nb_of_values_predicted_by_rules / nb_of_values_occuring_in_test_data if not is_valid_fraction(frac_classes): raise Exception("Fraction predicted classes examples is not within [0,1]: " + str(frac_classes)) return frac_classes
Python
def find_covered_by_antecedent_mask(self, antecedent) -> np.ndarray: """ returns: mask - an array of boolean values indicating which instances are covered by antecedent """ # todo: compute only once to make function faster dataset_size = self.size # type: int cummulated_mask = np.ones(dataset_size).astype(bool) # type: np.ndarray for literal in antecedent: current_mask = self.find_covered_by_literal_mask(literal) # type: np.ndarray cummulated_mask &= current_mask return cummulated_mask
def find_covered_by_antecedent_mask(self, antecedent) -> np.ndarray: """ returns: mask - an array of boolean values indicating which instances are covered by antecedent """ # todo: compute only once to make function faster dataset_size = self.size # type: int cummulated_mask = np.ones(dataset_size).astype(bool) # type: np.ndarray for literal in antecedent: current_mask = self.find_covered_by_literal_mask(literal) # type: np.ndarray cummulated_mask &= current_mask return cummulated_mask
Python
def find_covered_by_literal_mask(self, literal): """ returns: mask - an array of boolean values indicating which instances are covered by literal """ dataset_size = self.size attribute, interval = literal # the column that concerns the # iterated attribute # instead of pandas.Series, grab the ndarray # using values attribute relevant_column = self.__dataframe[[attribute]].values.reshape(dataset_size) # type: np.ndarray # this tells us which instances satisfy the literal current_mask = self.get_literal_coverage(literal, relevant_column) # type: np.ndarray return current_mask
def find_covered_by_literal_mask(self, literal): """ returns: mask - an array of boolean values indicating which instances are covered by literal """ dataset_size = self.size attribute, interval = literal # the column that concerns the # iterated attribute # instead of pandas.Series, grab the ndarray # using values attribute relevant_column = self.__dataframe[[attribute]].values.reshape(dataset_size) # type: np.ndarray # this tells us which instances satisfy the literal current_mask = self.get_literal_coverage(literal, relevant_column) # type: np.ndarray return current_mask
Python
def find_covered_by_rule_mask(self, rule) -> Tuple[np.ndarray, np.ndarray]: """ returns: covered_by_antecedent_mask: - array of boolean values indicating which dataset rows satisfy antecedent covered_by_consequent_mask: - array of boolean values indicating which dataset rows satisfy conseqeunt """ dataset_size = self.__dataframe.index.size # type: int # initialize a mask filled with True values # it will get modified as futher __literals get # tested # for optimization - create cummulated mask once # in constructor instances_satisfying_antecedent_mask = self.find_covered_by_antecedent_mask(rule.antecedent) instances_satisfying_consequent_mask = self.__get_consequent_coverage_mask(rule) instances_satisfying_consequent_mask = instances_satisfying_consequent_mask.reshape(dataset_size) return instances_satisfying_antecedent_mask, instances_satisfying_consequent_mask
def find_covered_by_rule_mask(self, rule) -> Tuple[np.ndarray, np.ndarray]: """ returns: covered_by_antecedent_mask: - array of boolean values indicating which dataset rows satisfy antecedent covered_by_consequent_mask: - array of boolean values indicating which dataset rows satisfy conseqeunt """ dataset_size = self.__dataframe.index.size # type: int # initialize a mask filled with True values # it will get modified as futher __literals get # tested # for optimization - create cummulated mask once # in constructor instances_satisfying_antecedent_mask = self.find_covered_by_antecedent_mask(rule.antecedent) instances_satisfying_consequent_mask = self.__get_consequent_coverage_mask(rule) instances_satisfying_consequent_mask = instances_satisfying_consequent_mask.reshape(dataset_size) return instances_satisfying_antecedent_mask, instances_satisfying_consequent_mask
Python
def calculate_rule_statistics(self, rule): """calculates rule's confidence and support using efficient numpy functions returns: -------- support: float confidence: float """ dataset_size = self.__dataframe.index.size # initialize a mask filled with True values # it will get modified as futher __literals get # tested # for optimization - create cummulated mask once # in constructor cummulated_mask = np.array([True] * dataset_size) for literal in rule.antecedent: attribute, interval = literal # the column that concerns the # iterated attribute # instead of pandas.Series, grab the ndarray # using values attribute relevant_column = self.__dataframe[[attribute]].values.reshape(dataset_size) # this tells us which instances satisfy the literal current_mask = self.get_literal_coverage(literal, relevant_column) # add cummulated and current mask using logical AND cummulated_mask &= current_mask instances_satisfying_antecedent = self.__dataframe[cummulated_mask].index instances_satisfying_antecedent_count = instances_satisfying_antecedent.size # using cummulated mask to filter out instances that satisfy consequent # but do not satisfy antecedent instances_satisfying_consequent_mask = self.__get_consequent_coverage_mask(rule) instances_satisfying_consequent_mask = instances_satisfying_consequent_mask.reshape(dataset_size) instances_satisfying_consequent_and_antecedent = self.__dataframe[ instances_satisfying_consequent_mask & cummulated_mask ].index instances_satisfying_consequent_and_antecedent_count = instances_satisfying_consequent_and_antecedent.size instances_satisfying_consequent_count = self.__dataframe[instances_satisfying_consequent_mask].index.size # instances satisfying consequent both antecedent and consequent support = instances_satisfying_antecedent_count / dataset_size confidence = 0 if instances_satisfying_antecedent_count != 0: confidence = instances_satisfying_consequent_and_antecedent_count / instances_satisfying_antecedent_count return support, confidence
def calculate_rule_statistics(self, rule): """calculates rule's confidence and support using efficient numpy functions returns: -------- support: float confidence: float """ dataset_size = self.__dataframe.index.size # initialize a mask filled with True values # it will get modified as futher __literals get # tested # for optimization - create cummulated mask once # in constructor cummulated_mask = np.array([True] * dataset_size) for literal in rule.antecedent: attribute, interval = literal # the column that concerns the # iterated attribute # instead of pandas.Series, grab the ndarray # using values attribute relevant_column = self.__dataframe[[attribute]].values.reshape(dataset_size) # this tells us which instances satisfy the literal current_mask = self.get_literal_coverage(literal, relevant_column) # add cummulated and current mask using logical AND cummulated_mask &= current_mask instances_satisfying_antecedent = self.__dataframe[cummulated_mask].index instances_satisfying_antecedent_count = instances_satisfying_antecedent.size # using cummulated mask to filter out instances that satisfy consequent # but do not satisfy antecedent instances_satisfying_consequent_mask = self.__get_consequent_coverage_mask(rule) instances_satisfying_consequent_mask = instances_satisfying_consequent_mask.reshape(dataset_size) instances_satisfying_consequent_and_antecedent = self.__dataframe[ instances_satisfying_consequent_mask & cummulated_mask ].index instances_satisfying_consequent_and_antecedent_count = instances_satisfying_consequent_and_antecedent.size instances_satisfying_consequent_count = self.__dataframe[instances_satisfying_consequent_mask].index.size # instances satisfying consequent both antecedent and consequent support = instances_satisfying_antecedent_count / dataset_size confidence = 0 if instances_satisfying_antecedent_count != 0: confidence = instances_satisfying_consequent_and_antecedent_count / instances_satisfying_antecedent_count return support, confidence
Python
def fit(self, quant_dataframe, use_targets_from_rule_set: bool, targets_to_use: Optional[List[str]] = None, class_association_rules: Optional[Iterable[MCAR]] = None, lambda_array: Optional[List[float]] = None, algorithm="RDGS", cache_cover_checks=True, cache_overlap_checks=True, default_class_type: DefaultClassStrategy = DefaultClassStrategy.MAJORITY_VALUE_OVER_WHOLE_TRAINING_SET, rule_combination_strategy=RuleCombiningStrategy.WEIGHTED_VOTE, debug=True, objective_scale_factor=1, ): """ Run the MIDS object on a dataset. """ type_check_dataframe(quant_dataframe) # --- Make sure the ground rule set is initialized ------------------------------------------------------------ if self.mids_ruleset is None and class_association_rules is not None: ids_rules = list(map(MIDSRule, class_association_rules)) # type: List[MIDSRule] mids_ruleset = MIDSRuleSet(ids_rules) elif self.mids_ruleset is not None: print("using provided mids ruleset and not class association rules") mids_ruleset = self.mids_ruleset else: raise Exception("Neither MCARs or MIDSRules are provided for fitting") # --- Use all target or only those in the ruleset? ----------------------------------------------------------- if targets_to_use is not None: targets_to_predict = set(targets_to_use) self.targets_to_predict = targets_to_use else: self.use_targets_from_rule_set = use_targets_from_rule_set if use_targets_from_rule_set: targets_to_predict: Set[TargetAttr] = mids_ruleset.get_target_attributes() else: targets_to_predict = set(quant_dataframe.columns) self.targets_to_predict = targets_to_predict # --- Initialize objective function -------------------------------------------------------------------------- objective_function_parameters = ObjectiveFunctionParameters( all_rules=mids_ruleset, quant_dataframe=quant_dataframe, lambda_array=lambda_array, target_attributes=list(targets_to_predict) ) # --- Initialize cover checker and overlap checker ------------------------------------------------------------ if self.cover_checker is None: if cache_cover_checks: self.cover_checker = CachedCoverChecker(mids_ruleset, quant_dataframe) else: self.cover_checker = CoverChecker() else: print("Reusing previously instantiated cover checker of type", str(type(self.cover_checker))) if self.overlap_checker is None: if cache_overlap_checks: self.overlap_checker = CachedOverlapChecker(mids_ruleset, quant_dataframe, self.cover_checker, debug=debug) else: self.overlap_checker = OverlapChecker(self.cover_checker, debug=debug) else: print("Reusing previously instantiated overlap checker of type", str(type(self.overlap_checker))) # --- Submodular maximization -------------------------------------------------------------------------------- # if len(mids_ruleset) > 0: # pass # else: # warnings.warn("Empty rule list was given") solution_set: Set[MIDSRule] = self._optimize( objective_function_parameters=objective_function_parameters, algorithm=algorithm, objective_scale_factor=objective_scale_factor, debug=debug ) optimization_meta_data: MIDSOptimizationMetaData = MIDSOptimizationMetaData( mids_objective_function=self.objective_function, optimization_algorithm=algorithm, solution_set_size=len(solution_set) ) self.classifier = MIDSClassifier(solution_set, quant_dataframe, list(targets_to_predict), optimization_meta_data, default_class_type, rule_combination_strategy) return self
def fit(self, quant_dataframe, use_targets_from_rule_set: bool, targets_to_use: Optional[List[str]] = None, class_association_rules: Optional[Iterable[MCAR]] = None, lambda_array: Optional[List[float]] = None, algorithm="RDGS", cache_cover_checks=True, cache_overlap_checks=True, default_class_type: DefaultClassStrategy = DefaultClassStrategy.MAJORITY_VALUE_OVER_WHOLE_TRAINING_SET, rule_combination_strategy=RuleCombiningStrategy.WEIGHTED_VOTE, debug=True, objective_scale_factor=1, ): """ Run the MIDS object on a dataset. """ type_check_dataframe(quant_dataframe) # --- Make sure the ground rule set is initialized ------------------------------------------------------------ if self.mids_ruleset is None and class_association_rules is not None: ids_rules = list(map(MIDSRule, class_association_rules)) # type: List[MIDSRule] mids_ruleset = MIDSRuleSet(ids_rules) elif self.mids_ruleset is not None: print("using provided mids ruleset and not class association rules") mids_ruleset = self.mids_ruleset else: raise Exception("Neither MCARs or MIDSRules are provided for fitting") # --- Use all target or only those in the ruleset? ----------------------------------------------------------- if targets_to_use is not None: targets_to_predict = set(targets_to_use) self.targets_to_predict = targets_to_use else: self.use_targets_from_rule_set = use_targets_from_rule_set if use_targets_from_rule_set: targets_to_predict: Set[TargetAttr] = mids_ruleset.get_target_attributes() else: targets_to_predict = set(quant_dataframe.columns) self.targets_to_predict = targets_to_predict # --- Initialize objective function -------------------------------------------------------------------------- objective_function_parameters = ObjectiveFunctionParameters( all_rules=mids_ruleset, quant_dataframe=quant_dataframe, lambda_array=lambda_array, target_attributes=list(targets_to_predict) ) # --- Initialize cover checker and overlap checker ------------------------------------------------------------ if self.cover_checker is None: if cache_cover_checks: self.cover_checker = CachedCoverChecker(mids_ruleset, quant_dataframe) else: self.cover_checker = CoverChecker() else: print("Reusing previously instantiated cover checker of type", str(type(self.cover_checker))) if self.overlap_checker is None: if cache_overlap_checks: self.overlap_checker = CachedOverlapChecker(mids_ruleset, quant_dataframe, self.cover_checker, debug=debug) else: self.overlap_checker = OverlapChecker(self.cover_checker, debug=debug) else: print("Reusing previously instantiated overlap checker of type", str(type(self.overlap_checker))) # --- Submodular maximization -------------------------------------------------------------------------------- # if len(mids_ruleset) > 0: # pass # else: # warnings.warn("Empty rule list was given") solution_set: Set[MIDSRule] = self._optimize( objective_function_parameters=objective_function_parameters, algorithm=algorithm, objective_scale_factor=objective_scale_factor, debug=debug ) optimization_meta_data: MIDSOptimizationMetaData = MIDSOptimizationMetaData( mids_objective_function=self.objective_function, optimization_algorithm=algorithm, solution_set_size=len(solution_set) ) self.classifier = MIDSClassifier(solution_set, quant_dataframe, list(targets_to_predict), optimization_meta_data, default_class_type, rule_combination_strategy) return self
Python
def __convert_apyori_result_to_MCARs(relation_record_generator, item_encoder: Optional[ItemEncoder] = None) -> List[MCAR]: """ Converts the output of apyori.apriori into MCARs :return: """ mcars = [] for relation_record in relation_record_generator: # type: RelationRecord # print("-- relation record ---") # print_relation_record(relation_record) # print("----------------------") # items = relation_record.items support = relation_record.support for ordered_statistic in relation_record.ordered_statistics: antecedent_tmp = ordered_statistic.items_base consequent_tmp = ordered_statistic.items_add confidence = ordered_statistic.confidence lift = ordered_statistic.lift if item_encoder is not None: antecedent_tmp = [item_encoder.decode_item(encoding) for encoding in antecedent_tmp] consequent_tmp = [item_encoder.decode_item(encoding) for encoding in consequent_tmp] antecedent_items = [EQLiteral(*item.split(attribute_value_separator)) for item in antecedent_tmp] consequent_items = [EQLiteral(*item.split(attribute_value_separator)) for item in consequent_tmp] # antecedent_items = [Item(*item.split(attribute_value_separator)) for item in antecedent_tmp] # consequent_items = [Item(*item.split(attribute_value_separator)) for item in consequent_tmp] antecedent = GeneralizedAntecedent(antecedent_items) # antecedent = Antecedent(antecedent_items) consequent = Consequent(consequent_items) rule = MCAR(antecedent, consequent, support, confidence) mcars.append(rule) return mcars
def __convert_apyori_result_to_MCARs(relation_record_generator, item_encoder: Optional[ItemEncoder] = None) -> List[MCAR]: """ Converts the output of apyori.apriori into MCARs :return: """ mcars = [] for relation_record in relation_record_generator: # type: RelationRecord # print("-- relation record ---") # print_relation_record(relation_record) # print("----------------------") # items = relation_record.items support = relation_record.support for ordered_statistic in relation_record.ordered_statistics: antecedent_tmp = ordered_statistic.items_base consequent_tmp = ordered_statistic.items_add confidence = ordered_statistic.confidence lift = ordered_statistic.lift if item_encoder is not None: antecedent_tmp = [item_encoder.decode_item(encoding) for encoding in antecedent_tmp] consequent_tmp = [item_encoder.decode_item(encoding) for encoding in consequent_tmp] antecedent_items = [EQLiteral(*item.split(attribute_value_separator)) for item in antecedent_tmp] consequent_items = [EQLiteral(*item.split(attribute_value_separator)) for item in consequent_tmp] # antecedent_items = [Item(*item.split(attribute_value_separator)) for item in antecedent_tmp] # consequent_items = [Item(*item.split(attribute_value_separator)) for item in consequent_tmp] antecedent = GeneralizedAntecedent(antecedent_items) # antecedent = Antecedent(antecedent_items) consequent = Consequent(consequent_items) rule = MCAR(antecedent, consequent, support, confidence) mcars.append(rule) return mcars
Python
def _top_rules_MIDS(transactions: List[List[str]], appearance: Optional[Dict] = None, target_rule_count: int = 1000, init_support: float = 0.05, init_confidence: float = 0.5, confidence_step: float = 0.05, support_step: float = 0.05, min_length: int = 2, init_max_length: int = 3, total_timeout: float = 100.0, # max time in seconds max_iterations: int = 30, verbose: bool = True ): """ Function for finding the best n (target_rule_count) rules from transaction list. PROBLEM: how to define 'best'? Iteratively: Search for the rules under the current mining parameters. Check the properties of the found rules. If there is still room for improvement, Then update the mining parameters, STOP if: - max nb of iterations is reached (default: 30). - the current nb of rules is more than the nb of rules we are looking for. - the time out is reach FIND all rules with as constraints: - min_support - min_confidence - max_length Parameters ---------- :param transactions : 2D array of strings, e.g. [["a:=:1", "b:=:3"], ["a:=:4", "b:=:2"]] :param appearance : dict - dictionary specifying rule appearance :param target_rule_count : int - target number of rules to mine :param init_support : float - support from which to start mining :param init_confidence : float - confidence from which to start mining :param confidence_step : float :param support_step : float :param min_length : int - minimum len of rules to mine :param init_max_length : int - maximum len from which to start mining :param total_timeout : float - maximum execution time of the function :param max_iterations : int - maximum iterations to try before stopping execution :param verbose : bool Returns ------- list of mined rules. The rules are not ordered. """ if appearance is None: appearance = {} start_time: float = time.time() # the length of a rule is at most the length of a transaction. (All transactions have the same length.) # max_rule_length_wanted = 10 # MAX_RULE_LEN: int = min(len(transactions[0]), max_rule_length_wanted) MAX_RULE_LEN: int = len(transactions[0]) current_support: float = init_support current_confidence: float = init_confidence current_max_length: int = init_max_length keep_mining: bool = True is_max_length_decreased_due_timeout = False current_iteration = 0 last_rule_count = -1 rules: Optional[List[MCAR]] = None if verbose: print("STARTING top_rules") while keep_mining: current_iteration += 1 if current_iteration > max_iterations: if verbose: print("Max iterations reached") break if verbose: print(f"--- iteration {current_iteration} ---") print((f"Running apriori with setting: " f"confidence={current_confidence}, " f"support={current_support}, " f"min_length={min_length}, " f"max_length={current_max_length}, " f"MAX_RULE_LEN={MAX_RULE_LEN}" )) current_rules: List[MCAR] = mine_MCARs_from_transactions_using_apyori( transactions, min_support=current_support, min_confidence=current_confidence, max_length=current_max_length) # rules_current = fim.arules(transactions, supp=support, conf=conf, mode="o", report="sc", appear=appearance, # zmax=maxlen, zmin=minlen) current_nb_of_rules = len(current_rules) # assign rules = current_rules if verbose: print(f"Rule count: {current_nb_of_rules}, Iteration: {current_iteration}") if current_nb_of_rules >= target_rule_count: keep_mining = False if verbose: print(f"\tTarget rule count satisfied: {target_rule_count}") else: current_execution_time = time.time() - start_time # if timeout limit exceeded if current_execution_time > total_timeout: if verbose: print("Execution time exceeded:", total_timeout) keep_mining = False # if we can still increase our rule length AND # the number of rules found has changed (increased?) since last time AND # there has elif current_max_length < MAX_RULE_LEN and last_rule_count != current_nb_of_rules and not is_max_length_decreased_due_timeout: current_max_length += 1 last_rule_count = current_nb_of_rules if verbose: print(f"\tIncreasing max_length {current_max_length}") # if we can still increase our rule length AND # # we can still increase our support # THEN: # increase our support # increment our max length elif current_max_length < MAX_RULE_LEN and is_max_length_decreased_due_timeout and current_support <= 1 - support_step: current_support += support_step current_max_length += 1 last_rule_count = current_nb_of_rules is_max_length_decreased_due_timeout = False if verbose: print(f"\tIncreasing maxlen to {current_max_length}") print(f"\tIncreasing minsup to {current_support}") # IF we can still decrease our confidence # THEN decrease our confidence elif current_confidence > confidence_step: current_confidence -= confidence_step if verbose: print(f"\tDecreasing confidence to {current_confidence}") else: if verbose: print("\tAll options exhausted") keep_mining = False if verbose: end_of_current_iteration_message = f"--- end iteration {current_iteration} ---" print(end_of_current_iteration_message) print("-" * len(end_of_current_iteration_message)) if verbose: print(f"FINISHED top_rules after {current_iteration} iterations") return rules
def _top_rules_MIDS(transactions: List[List[str]], appearance: Optional[Dict] = None, target_rule_count: int = 1000, init_support: float = 0.05, init_confidence: float = 0.5, confidence_step: float = 0.05, support_step: float = 0.05, min_length: int = 2, init_max_length: int = 3, total_timeout: float = 100.0, # max time in seconds max_iterations: int = 30, verbose: bool = True ): """ Function for finding the best n (target_rule_count) rules from transaction list. PROBLEM: how to define 'best'? Iteratively: Search for the rules under the current mining parameters. Check the properties of the found rules. If there is still room for improvement, Then update the mining parameters, STOP if: - max nb of iterations is reached (default: 30). - the current nb of rules is more than the nb of rules we are looking for. - the time out is reach FIND all rules with as constraints: - min_support - min_confidence - max_length Parameters ---------- :param transactions : 2D array of strings, e.g. [["a:=:1", "b:=:3"], ["a:=:4", "b:=:2"]] :param appearance : dict - dictionary specifying rule appearance :param target_rule_count : int - target number of rules to mine :param init_support : float - support from which to start mining :param init_confidence : float - confidence from which to start mining :param confidence_step : float :param support_step : float :param min_length : int - minimum len of rules to mine :param init_max_length : int - maximum len from which to start mining :param total_timeout : float - maximum execution time of the function :param max_iterations : int - maximum iterations to try before stopping execution :param verbose : bool Returns ------- list of mined rules. The rules are not ordered. """ if appearance is None: appearance = {} start_time: float = time.time() # the length of a rule is at most the length of a transaction. (All transactions have the same length.) # max_rule_length_wanted = 10 # MAX_RULE_LEN: int = min(len(transactions[0]), max_rule_length_wanted) MAX_RULE_LEN: int = len(transactions[0]) current_support: float = init_support current_confidence: float = init_confidence current_max_length: int = init_max_length keep_mining: bool = True is_max_length_decreased_due_timeout = False current_iteration = 0 last_rule_count = -1 rules: Optional[List[MCAR]] = None if verbose: print("STARTING top_rules") while keep_mining: current_iteration += 1 if current_iteration > max_iterations: if verbose: print("Max iterations reached") break if verbose: print(f"--- iteration {current_iteration} ---") print((f"Running apriori with setting: " f"confidence={current_confidence}, " f"support={current_support}, " f"min_length={min_length}, " f"max_length={current_max_length}, " f"MAX_RULE_LEN={MAX_RULE_LEN}" )) current_rules: List[MCAR] = mine_MCARs_from_transactions_using_apyori( transactions, min_support=current_support, min_confidence=current_confidence, max_length=current_max_length) # rules_current = fim.arules(transactions, supp=support, conf=conf, mode="o", report="sc", appear=appearance, # zmax=maxlen, zmin=minlen) current_nb_of_rules = len(current_rules) # assign rules = current_rules if verbose: print(f"Rule count: {current_nb_of_rules}, Iteration: {current_iteration}") if current_nb_of_rules >= target_rule_count: keep_mining = False if verbose: print(f"\tTarget rule count satisfied: {target_rule_count}") else: current_execution_time = time.time() - start_time # if timeout limit exceeded if current_execution_time > total_timeout: if verbose: print("Execution time exceeded:", total_timeout) keep_mining = False # if we can still increase our rule length AND # the number of rules found has changed (increased?) since last time AND # there has elif current_max_length < MAX_RULE_LEN and last_rule_count != current_nb_of_rules and not is_max_length_decreased_due_timeout: current_max_length += 1 last_rule_count = current_nb_of_rules if verbose: print(f"\tIncreasing max_length {current_max_length}") # if we can still increase our rule length AND # # we can still increase our support # THEN: # increase our support # increment our max length elif current_max_length < MAX_RULE_LEN and is_max_length_decreased_due_timeout and current_support <= 1 - support_step: current_support += support_step current_max_length += 1 last_rule_count = current_nb_of_rules is_max_length_decreased_due_timeout = False if verbose: print(f"\tIncreasing maxlen to {current_max_length}") print(f"\tIncreasing minsup to {current_support}") # IF we can still decrease our confidence # THEN decrease our confidence elif current_confidence > confidence_step: current_confidence -= confidence_step if verbose: print(f"\tDecreasing confidence to {current_confidence}") else: if verbose: print("\tAll options exhausted") keep_mining = False if verbose: end_of_current_iteration_message = f"--- end iteration {current_iteration} ---" print(end_of_current_iteration_message) print("-" * len(end_of_current_iteration_message)) if verbose: print(f"FINISHED top_rules after {current_iteration} iterations") return rules
Python
def ruleset_size(self) -> int: """ Returns the size of the rule set. :return: """ return self.rule_length_counter.count
def ruleset_size(self) -> int: """ Returns the size of the rule set. :return: """ return self.rule_length_counter.count
Python
def total_nb_of_literals(self) -> int: """ Returns the total nb of __literals in the rule set. """ return self.rule_length_counter.sum
def total_nb_of_literals(self) -> int: """ Returns the total nb of __literals in the rule set. """ return self.rule_length_counter.sum
Python
def avg_nb_of_literals_per_rule(self) -> float: """ Returns the avg nb of __literals over the rules in the rule set. """ return self.rule_length_counter.get_avg()
def avg_nb_of_literals_per_rule(self) -> float: """ Returns the avg nb of __literals over the rules in the rule set. """ return self.rule_length_counter.get_avg()
Python
def min_nb_of_literals(self) -> float: """ Returns the nb of __literals in the shortest rule """ return self.rule_length_counter.min
def min_nb_of_literals(self) -> float: """ Returns the nb of __literals in the shortest rule """ return self.rule_length_counter.min
Python
def max_nb_of_literals(self) -> float: """ Returns the nb of __literals in the longest rule """ return self.rule_length_counter.max
def max_nb_of_literals(self) -> float: """ Returns the nb of __literals in the longest rule """ return self.rule_length_counter.max
Python
def parse_unibet_api(id_league, sport): """ Get Unibet odds from league id and sport """ parameter = "" if sport == "tennis": parameter = "Vainqueur%2520du%2520match" elif sport == "basketball": parameter = "Vainqueur%2520du%2520match%2520%2528prolong.%2520incluses%2529" else: parameter = "R%25C3%25A9sultat%2520du%2520match" url = ("https://www.unibet.fr/zones/sportnode/markets.json?nodeId={}&filter=R%25C3%25A9sultat&marketname={}" .format(id_league, parameter)) content = requests.get(url).content parsed = json.loads(content) markets_by_type = parsed.get("marketsByType", []) odds_match = {} for market_by_type in markets_by_type: days = market_by_type["days"] for day in days: events = day["events"] for event in events: markets = event["markets"] for market in markets: name = (market["eventHomeTeamName"].replace(" - ", "-") + " - " + market["eventAwayTeamName"].replace(" - ", "-")) date = datetime.datetime.fromtimestamp(market["eventStartDate"]/1000) odds = [] selections = market["selections"] for selection in selections: price_up = int(selection["currentPriceUp"]) price_down = int(selection["currentPriceDown"]) odds.append(round(price_up / price_down + 1, 2)) odds_match[name] = {"date":date, "odds":{"unibet":odds}, "id":{"unibet":event["eventId"]}} return odds_match
def parse_unibet_api(id_league, sport): """ Get Unibet odds from league id and sport """ parameter = "" if sport == "tennis": parameter = "Vainqueur%2520du%2520match" elif sport == "basketball": parameter = "Vainqueur%2520du%2520match%2520%2528prolong.%2520incluses%2529" else: parameter = "R%25C3%25A9sultat%2520du%2520match" url = ("https://www.unibet.fr/zones/sportnode/markets.json?nodeId={}&filter=R%25C3%25A9sultat&marketname={}" .format(id_league, parameter)) content = requests.get(url).content parsed = json.loads(content) markets_by_type = parsed.get("marketsByType", []) odds_match = {} for market_by_type in markets_by_type: days = market_by_type["days"] for day in days: events = day["events"] for event in events: markets = event["markets"] for market in markets: name = (market["eventHomeTeamName"].replace(" - ", "-") + " - " + market["eventAwayTeamName"].replace(" - ", "-")) date = datetime.datetime.fromtimestamp(market["eventStartDate"]/1000) odds = [] selections = market["selections"] for selection in selections: price_up = int(selection["currentPriceUp"]) price_down = int(selection["currentPriceDown"]) odds.append(round(price_up / price_down + 1, 2)) odds_match[name] = {"date":date, "odds":{"unibet":odds}, "id":{"unibet":event["eventId"]}} return odds_match
Python
def parse_winamax(url): """ Retourne les cotes disponibles sur winamax """ ids = url.split("/sports/")[1] try: tournament_id = int(ids.split("/")[2]) except IndexError: tournament_id = -1 sport_id = int(ids.split("/")[0]) try: req = urllib.request.Request( url, headers={'User-Agent': sb.USER_AGENT}) webpage = urllib.request.urlopen(req, timeout=10).read() soup = BeautifulSoup(webpage, features="lxml") except urllib.error.HTTPError: raise sb.UnavailableSiteException match_odds_hash = {} for line in soup.find_all(['script']): if "PRELOADED_STATE" in str(line.string): json_text = (line.string.split("var PRELOADED_STATE = ")[1] .split(";var BETTING_CONFIGURATION")[0]) if json_text[-1] == ";": json_text = json_text[:-1] dict_matches = json.loads(json_text) if "matches" in dict_matches: for match in dict_matches["matches"].values(): if (tournament_id in (match['tournamentId'], -1) and match["competitor1Id"] != 0 and match['sportId'] == sport_id and 'isOutright' not in match.keys()): try: match_name = match["title"].strip().replace(" ", " ") date_time = datetime.datetime.fromtimestamp(match["matchStart"]) if date_time < datetime.datetime.today(): continue main_bet_id = match["mainBetId"] odds_ids = dict_matches["bets"][str( main_bet_id)]["outcomes"] odds = [dict_matches["odds"] [str(x)] for x in odds_ids] match_odds_hash[match_name] = {} match_odds_hash[match_name]['odds'] = { "winamax": odds} match_odds_hash[match_name]['date'] = date_time match_odds_hash[match_name]['id'] = { "winamax": str(match["matchId"])} except KeyError: pass if not match_odds_hash: raise sb.UnavailableCompetitionException return match_odds_hash raise sb.UnavailableSiteException
def parse_winamax(url): """ Retourne les cotes disponibles sur winamax """ ids = url.split("/sports/")[1] try: tournament_id = int(ids.split("/")[2]) except IndexError: tournament_id = -1 sport_id = int(ids.split("/")[0]) try: req = urllib.request.Request( url, headers={'User-Agent': sb.USER_AGENT}) webpage = urllib.request.urlopen(req, timeout=10).read() soup = BeautifulSoup(webpage, features="lxml") except urllib.error.HTTPError: raise sb.UnavailableSiteException match_odds_hash = {} for line in soup.find_all(['script']): if "PRELOADED_STATE" in str(line.string): json_text = (line.string.split("var PRELOADED_STATE = ")[1] .split(";var BETTING_CONFIGURATION")[0]) if json_text[-1] == ";": json_text = json_text[:-1] dict_matches = json.loads(json_text) if "matches" in dict_matches: for match in dict_matches["matches"].values(): if (tournament_id in (match['tournamentId'], -1) and match["competitor1Id"] != 0 and match['sportId'] == sport_id and 'isOutright' not in match.keys()): try: match_name = match["title"].strip().replace(" ", " ") date_time = datetime.datetime.fromtimestamp(match["matchStart"]) if date_time < datetime.datetime.today(): continue main_bet_id = match["mainBetId"] odds_ids = dict_matches["bets"][str( main_bet_id)]["outcomes"] odds = [dict_matches["odds"] [str(x)] for x in odds_ids] match_odds_hash[match_name] = {} match_odds_hash[match_name]['odds'] = { "winamax": odds} match_odds_hash[match_name]['date'] = date_time match_odds_hash[match_name]['id'] = { "winamax": str(match["matchId"])} except KeyError: pass if not match_odds_hash: raise sb.UnavailableCompetitionException return match_odds_hash raise sb.UnavailableSiteException
Python
def parse_sport_betclic(id_sport): """ Get odds from Betclic sport id """ url = ("https://offer.cdn.betclic.fr/api/pub/v2/sports/{}?application=2&countrycode=fr&language=fr&sitecode=frfr" .format(id_sport)) content = urllib.request.urlopen(url).read() parsed = json.loads(content) list_odds = [] competitions = parsed["competitions"] for competition in competitions: id_competition = competition["id"] list_odds.append(parse_betclic_api(id_competition)) return merge_dicts(list_odds)
def parse_sport_betclic(id_sport): """ Get odds from Betclic sport id """ url = ("https://offer.cdn.betclic.fr/api/pub/v2/sports/{}?application=2&countrycode=fr&language=fr&sitecode=frfr" .format(id_sport)) content = urllib.request.urlopen(url).read() parsed = json.loads(content) list_odds = [] competitions = parsed["competitions"] for competition in competitions: id_competition = competition["id"] list_odds.append(parse_betclic_api(id_competition)) return merge_dicts(list_odds)
Python
def parse_parionssport_match_basketball(id_match): """ Get ParionsSport odds from baskteball match id """ url = ("https://www.enligne.parionssport.fdj.fr/lvs-api/ff/{}?originId=3&lineId=1&showMarketTypeGroups=true&ext=1" "&showPromotions=true".format(id_match)) req = urllib.request.Request(url, headers={'X-LVS-HSToken': sb.TOKENS["parionssport"]}) content = urllib.request.urlopen(req).read() parsed = json.loads(content) items = parsed["items"] odds = [] odds_match = {} for item in items: if not item.startswith("o"): continue odd = items[item] market = items[odd["parent"]] if not "desc" in market: continue if not market["desc"] == "Face à Face": continue if not "period" in market: continue if not market["period"] == "Match": continue event = items[market["parent"]] if "date" not in odds_match: odds_match["date"] = datetime.datetime.strptime(event["start"], "%y%m%d%H%M") + datetime.timedelta(hours=2) odds.append(float(odd["price"].replace(",", "."))) if not odds: return odds_match odds_match["odds"] = {"parionssport" : odds} odds_match["id"] = {"parionssport" : market["parent"]} return odds_match
def parse_parionssport_match_basketball(id_match): """ Get ParionsSport odds from baskteball match id """ url = ("https://www.enligne.parionssport.fdj.fr/lvs-api/ff/{}?originId=3&lineId=1&showMarketTypeGroups=true&ext=1" "&showPromotions=true".format(id_match)) req = urllib.request.Request(url, headers={'X-LVS-HSToken': sb.TOKENS["parionssport"]}) content = urllib.request.urlopen(req).read() parsed = json.loads(content) items = parsed["items"] odds = [] odds_match = {} for item in items: if not item.startswith("o"): continue odd = items[item] market = items[odd["parent"]] if not "desc" in market: continue if not market["desc"] == "Face à Face": continue if not "period" in market: continue if not market["period"] == "Match": continue event = items[market["parent"]] if "date" not in odds_match: odds_match["date"] = datetime.datetime.strptime(event["start"], "%y%m%d%H%M") + datetime.timedelta(hours=2) odds.append(float(odd["price"].replace(",", "."))) if not odds: return odds_match odds_match["odds"] = {"parionssport" : odds} odds_match["id"] = {"parionssport" : market["parent"]} return odds_match
Python
def parse_parionssport_api(id_league): """ Get ParionsSport odds from league id """ url = ("https://www.enligne.parionssport.fdj.fr/lvs-api/next/50/{}?originId=3&lineId=1&breakdownEventsIntoDays=true" "&eType=G&showPromotions=true".format(id_league)) req = urllib.request.Request(url, headers={'X-LVS-HSToken': sb.TOKENS["parionssport"]}) content = urllib.request.urlopen(req).read() parsed = json.loads(content) odds_match = {} if "items" not in parsed: return odds_match items = parsed["items"] for item in items: if not item.startswith("o"): continue odd = items[item] market = items[odd["parent"]] if not market["style"] in ["WIN_DRAW_WIN", "TWO_OUTCOME_LONG"]: continue event = items[market["parent"]] name = event["a"] + " - " + event["b"] if event["code"] == "BASK": if name not in odds_match: odds = parse_parionssport_match_basketball(market["parent"]) if odds: odds_match[name] = odds else: if not name in odds_match: odds_match[name] = {} odds_match[name]["date"] = (datetime.datetime.strptime(event["start"], "%y%m%d%H%M") + datetime.timedelta(hours=2)) odds_match[name]["odds"] = {"parionssport":[]} odds_match[name]["odds"]["parionssport"].append(float(odd["price"].replace(",", "."))) odds_match[name]["id"] = {"parionssport":market["parent"]} return odds_match
def parse_parionssport_api(id_league): """ Get ParionsSport odds from league id """ url = ("https://www.enligne.parionssport.fdj.fr/lvs-api/next/50/{}?originId=3&lineId=1&breakdownEventsIntoDays=true" "&eType=G&showPromotions=true".format(id_league)) req = urllib.request.Request(url, headers={'X-LVS-HSToken': sb.TOKENS["parionssport"]}) content = urllib.request.urlopen(req).read() parsed = json.loads(content) odds_match = {} if "items" not in parsed: return odds_match items = parsed["items"] for item in items: if not item.startswith("o"): continue odd = items[item] market = items[odd["parent"]] if not market["style"] in ["WIN_DRAW_WIN", "TWO_OUTCOME_LONG"]: continue event = items[market["parent"]] name = event["a"] + " - " + event["b"] if event["code"] == "BASK": if name not in odds_match: odds = parse_parionssport_match_basketball(market["parent"]) if odds: odds_match[name] = odds else: if not name in odds_match: odds_match[name] = {} odds_match[name]["date"] = (datetime.datetime.strptime(event["start"], "%y%m%d%H%M") + datetime.timedelta(hours=2)) odds_match[name]["odds"] = {"parionssport":[]} odds_match[name]["odds"]["parionssport"].append(float(odd["price"].replace(",", "."))) odds_match[name]["id"] = {"parionssport":market["parent"]} return odds_match
Python
def parse_pmu_html(soup): """ Retourne les cotes disponibles sur une page html pmu """ match_odds_hash = {} match = "" date_time = "undefined" live = False handicap = False date = "" match_id = None for line in soup.find_all(): if "n'est pas accessible pour le moment !" in line.text: raise sb.UnavailableSiteException if "data-date" in line.attrs and "shadow" in line["class"]: date = line["data-date"] elif "class" in line.attrs and "trow--live--remaining-time" in line["class"]: hour = line.text if "'" in hour: date_time = datetime.datetime.today()+datetime.timedelta(minutes=int(hour.strip().strip("'")) - 1) date_time = truncate_datetime(date_time) continue try: date_time = datetime.datetime.strptime( date + " " + hour, "%Y-%m-%d %Hh%M") except ValueError: date_time = "undefined" elif "class" in line.attrs and "trow--live--logo-active" in line["class"]: live = True elif "class" in line.attrs and "trow--event--name" in line["class"]: string = "".join(list(line.stripped_strings)) if "//" in string: try: is_rugby_13 = line.find_parent("a")["data-sport_id"] == "rugby_a_xiii" except TypeError: is_rugby_13 = False if is_rugby_13 or live: continue handicap = False if "+" in string or "Egalité" in string: handicap = True match, odds = parse_page_match_pmu("https://paris-sportifs.pmu.fr" + line.parent["href"]) else: match = string.replace(" - ", "-") match = match.replace(" // ", " - ") match = match.replace("//", " - ") elif "class" in line.attrs and "event-list-odds-list" in line["class"]: if live or is_rugby_13: live = False is_rugby_13 = False continue if not handicap: odds = list( map(lambda x: float(x.replace(",", ".")), list(line.stripped_strings))) match_odds_hash[match] = {} match_odds_hash[match]['odds'] = {"pmu": odds} match_odds_hash[match]['date'] = date_time match_odds_hash[match]['id'] = {"pmu": match_id} elif "data-ev_id" in line.attrs: match_id = line["data-ev_id"] if not match_odds_hash: raise sb.UnavailableCompetitionException return match_odds_hash
def parse_pmu_html(soup): """ Retourne les cotes disponibles sur une page html pmu """ match_odds_hash = {} match = "" date_time = "undefined" live = False handicap = False date = "" match_id = None for line in soup.find_all(): if "n'est pas accessible pour le moment !" in line.text: raise sb.UnavailableSiteException if "data-date" in line.attrs and "shadow" in line["class"]: date = line["data-date"] elif "class" in line.attrs and "trow--live--remaining-time" in line["class"]: hour = line.text if "'" in hour: date_time = datetime.datetime.today()+datetime.timedelta(minutes=int(hour.strip().strip("'")) - 1) date_time = truncate_datetime(date_time) continue try: date_time = datetime.datetime.strptime( date + " " + hour, "%Y-%m-%d %Hh%M") except ValueError: date_time = "undefined" elif "class" in line.attrs and "trow--live--logo-active" in line["class"]: live = True elif "class" in line.attrs and "trow--event--name" in line["class"]: string = "".join(list(line.stripped_strings)) if "//" in string: try: is_rugby_13 = line.find_parent("a")["data-sport_id"] == "rugby_a_xiii" except TypeError: is_rugby_13 = False if is_rugby_13 or live: continue handicap = False if "+" in string or "Egalité" in string: handicap = True match, odds = parse_page_match_pmu("https://paris-sportifs.pmu.fr" + line.parent["href"]) else: match = string.replace(" - ", "-") match = match.replace(" // ", " - ") match = match.replace("//", " - ") elif "class" in line.attrs and "event-list-odds-list" in line["class"]: if live or is_rugby_13: live = False is_rugby_13 = False continue if not handicap: odds = list( map(lambda x: float(x.replace(",", ".")), list(line.stripped_strings))) match_odds_hash[match] = {} match_odds_hash[match]['odds'] = {"pmu": odds} match_odds_hash[match]['date'] = date_time match_odds_hash[match]['id'] = {"pmu": match_id} elif "data-ev_id" in line.attrs: match_id = line["data-ev_id"] if not match_odds_hash: raise sb.UnavailableCompetitionException return match_odds_hash
Python
def display_name(self) -> str: """Calculate display name for a room. Prefer returning the room name if it exists, falling back to a group-style name if not. Follows: https://matrix.org/docs/spec/client_server/r0.6.0#id342 """ return self.named_room_name() or self.group_name()
def display_name(self) -> str: """Calculate display name for a room. Prefer returning the room name if it exists, falling back to a group-style name if not. Follows: https://matrix.org/docs/spec/client_server/r0.6.0#id342 """ return self.named_room_name() or self.group_name()
Python
def group_name(self) -> str: """Return the group-style name of the room. In other words, a display name based on the names of room members. This is used for ad-hoc groups of people (usually direct chats). """ empty, user_ids, others = self.group_name_structure() names = [self.user_name(u) or u for u in user_ids] if others: text = "{} and {} other{}".format( ", ".join(names), others, "" if others == 1 else "s", ) elif len(names) == 0: text = "" elif len(names) == 1: text = names[0] else: text = "{} and {}".format(", ".join(names[:-1]), names[-1]) if empty and text: text = f"Empty Room (had {text})" elif empty: text = "Empty Room" return text
def group_name(self) -> str: """Return the group-style name of the room. In other words, a display name based on the names of room members. This is used for ad-hoc groups of people (usually direct chats). """ empty, user_ids, others = self.group_name_structure() names = [self.user_name(u) or u for u in user_ids] if others: text = "{} and {} other{}".format( ", ".join(names), others, "" if others == 1 else "s", ) elif len(names) == 0: text = "" elif len(names) == 1: text = names[0] else: text = "{} and {}".format(", ".join(names[:-1]), names[-1]) if empty and text: text = f"Empty Room (had {text})" elif empty: text = "Empty Room" return text
Python
def group_name_structure(self) -> Tuple[bool, List[str], int]: """Get if room is empty, ID for listed users and the N others count. """ try: heroes, joined, invited = self._summary_details() except ValueError: users = [ u for u in sorted(self.users, key=lambda u: self.user_name(u)) if u != self.own_user_id ] empty = not users if len(users) <= 5: return (empty, users, 0) return (empty, users[:5], len(users) - 5) empty = self.member_count <= 1 if len(heroes) >= self.member_count - 1: return (empty, heroes, 0) return (empty, heroes, self.member_count - 1 - len(heroes))
def group_name_structure(self) -> Tuple[bool, List[str], int]: """Get if room is empty, ID for listed users and the N others count. """ try: heroes, joined, invited = self._summary_details() except ValueError: users = [ u for u in sorted(self.users, key=lambda u: self.user_name(u)) if u != self.own_user_id ] empty = not users if len(users) <= 5: return (empty, users, 0) return (empty, users[:5], len(users) - 5) empty = self.member_count <= 1 if len(heroes) >= self.member_count - 1: return (empty, heroes, 0) return (empty, heroes, self.member_count - 1 - len(heroes))
Python
def user_name(self, user_id: str) -> Optional[str]: """Get disambiguated display name for a user. Returns display name of a user if display name is unique or returns a display name in form "<display name> (<matrix id>)" if there is more than one user with same display name. """ if user_id not in self.users: return None user = self.users[user_id] if len(self.names[user.name]) > 1: return user.disambiguated_name return user.name
def user_name(self, user_id: str) -> Optional[str]: """Get disambiguated display name for a user. Returns display name of a user if display name is unique or returns a display name in form "<display name> (<matrix id>)" if there is more than one user with same display name. """ if user_id not in self.users: return None user = self.users[user_id] if len(self.names[user.name]) > 1: return user.disambiguated_name return user.name
Python
def avatar_url(self, user_id: str) -> Optional[str]: """Get avatar url for a user. Returns a matrix content URI, or None if the user has no avatar. """ if user_id not in self.users: return None return self.users[user_id].avatar_url
def avatar_url(self, user_id: str) -> Optional[str]: """Get avatar url for a user. Returns a matrix content URI, or None if the user has no avatar. """ if user_id not in self.users: return None return self.users[user_id].avatar_url
Python
def gen_avatar_url(self) -> Optional[str]: """ Get the calculated room's avatar url. Either the room's avatar if one is set, or the avatar of the first user that's not ourselves if the room is an unnamed group or has exactly two users. """ if self.room_avatar_url: return self.room_avatar_url try: heroes, _, _ = self._summary_details() except ValueError: if self.is_group and len(self.users) == 2: return self.avatar_url(next( u for u in sorted(self.users, key=lambda u: self.user_name(u)) if u != self.own_user_id )) return None if self.is_group and self.member_count == 2 and len(heroes) >= 1: return self.avatar_url(heroes[0]) return None
def gen_avatar_url(self) -> Optional[str]: """ Get the calculated room's avatar url. Either the room's avatar if one is set, or the avatar of the first user that's not ourselves if the room is an unnamed group or has exactly two users. """ if self.room_avatar_url: return self.room_avatar_url try: heroes, _, _ = self._summary_details() except ValueError: if self.is_group and len(self.users) == 2: return self.avatar_url(next( u for u in sorted(self.users, key=lambda u: self.user_name(u)) if u != self.own_user_id )) return None if self.is_group and self.member_count == 2 and len(heroes) >= 1: return self.avatar_url(heroes[0]) return None
Python
def machine_name(self) -> str: """Calculate an unambiguous, unique machine name for a room. Either use the more human-friendly canonical alias, if it exists, or the internal room ID if not. """ return self.canonical_alias or self.room_id
def machine_name(self) -> str: """Calculate an unambiguous, unique machine name for a room. Either use the more human-friendly canonical alias, if it exists, or the internal room ID if not. """ return self.canonical_alias or self.room_id
Python
def is_named(self) -> bool: """Determine whether a room is named. A named room is a room with either the name or a canonical alias set. """ return bool(self.canonical_alias or self.name)
def is_named(self) -> bool: """Determine whether a room is named. A named room is a room with either the name or a canonical alias set. """ return bool(self.canonical_alias or self.name)
Python
def is_group(self) -> bool: """Determine whether a room is an ad-hoc group (often a direct chat). A group is an unnamed room with no canonical alias. """ return not self.is_named
def is_group(self) -> bool: """Determine whether a room is an ad-hoc group (often a direct chat). A group is an unnamed room with no canonical alias. """ return not self.is_named
Python
def handle_membership( self, event: Union[RoomMemberEvent, InviteMemberEvent], ) -> bool: """Handle a membership event for the room. Args: event (RoomMemberEvent): The event that should be handled that updates the room state. Returns True if the member list of the room has changed False otherwise. """ target_user = event.state_key invited = event.membership == "invite" if event.membership in ("invite", "join"): # Add member if not already present in self.users, # or the member is invited but not present in self.invited_users if (target_user not in self.users or (invited and target_user not in self.invited_users)): display_name = event.content.get("displayname", None) avatar_url = event.content.get("avatar_url", None) return self.add_member( target_user, display_name, avatar_url, invited, ) user = self.users[target_user] # Handle membership change user.invited = invited if not invited and target_user in self.invited_users: del self.invited_users[target_user] # Handle profile changes if "displayname" in event.content: self.names[user.name].remove(user.user_id) user.display_name = event.content["displayname"] self.names[user.name].append(user.user_id) if "avatar_url" in event.content: user.avatar_url = event.content["avatar_url"] return False elif event.membership in ("leave", "ban"): return self.remove_member(target_user) return False
def handle_membership( self, event: Union[RoomMemberEvent, InviteMemberEvent], ) -> bool: """Handle a membership event for the room. Args: event (RoomMemberEvent): The event that should be handled that updates the room state. Returns True if the member list of the room has changed False otherwise. """ target_user = event.state_key invited = event.membership == "invite" if event.membership in ("invite", "join"): # Add member if not already present in self.users, # or the member is invited but not present in self.invited_users if (target_user not in self.users or (invited and target_user not in self.invited_users)): display_name = event.content.get("displayname", None) avatar_url = event.content.get("avatar_url", None) return self.add_member( target_user, display_name, avatar_url, invited, ) user = self.users[target_user] # Handle membership change user.invited = invited if not invited and target_user in self.invited_users: del self.invited_users[target_user] # Handle profile changes if "displayname" in event.content: self.names[user.name].remove(user.user_id) user.display_name = event.content["displayname"] self.names[user.name].append(user.user_id) if "avatar_url" in event.content: user.avatar_url = event.content["avatar_url"] return False elif event.membership in ("leave", "ban"): return self.remove_member(target_user) return False
Python
def _summary_details(self) -> Tuple[List[str], int, int]: """Return the summary attributes if it can be used for calculations.""" valid = bool( self.summary is not None and self.summary.joined_member_count is not None and self.summary.invited_member_count is not None, ) if not valid: raise ValueError("Unusable summary") return ( # type: ignore self.summary.heroes, # type: ignore self.summary.joined_member_count, # type: ignore self.summary.invited_member_count, # type: ignore )
def _summary_details(self) -> Tuple[List[str], int, int]: """Return the summary attributes if it can be used for calculations.""" valid = bool( self.summary is not None and self.summary.joined_member_count is not None and self.summary.invited_member_count is not None, ) if not valid: raise ValueError("Unusable summary") return ( # type: ignore self.summary.heroes, # type: ignore self.summary.joined_member_count, # type: ignore self.summary.invited_member_count, # type: ignore )
Python
def members_synced(self) -> bool: """Check if the room member state is fully synced. Room members can be missing from the room if syncs are done using lazy member loading, the room summary will contain the full member count but other member info will be missing. A `joined_members` request should be done for this room to populate the member list. This is crucial for encrypted rooms before sending any messages. """ try: _, joined, invited = self._summary_details() except ValueError: return True return joined + invited == len(self.users)
def members_synced(self) -> bool: """Check if the room member state is fully synced. Room members can be missing from the room if syncs are done using lazy member loading, the room summary will contain the full member count but other member info will be missing. A `joined_members` request should be done for this room to populate the member list. This is crucial for encrypted rooms before sending any messages. """ try: _, joined, invited = self._summary_details() except ValueError: return True return joined + invited == len(self.users)
Python
def handle_membership( self, event: Union[RoomMemberEvent, InviteMemberEvent], ) -> bool: """Handle a membership event for the invited room. Args: event (RoomMemberEvent): The event that should be handled that updates the room state. Returns True if the member list of the room has changed False otherwise. """ if (event.membership == "invite" and event.state_key == self.own_user_id): self.inviter = event.sender return super().handle_membership(event)
def handle_membership( self, event: Union[RoomMemberEvent, InviteMemberEvent], ) -> bool: """Handle a membership event for the invited room. Args: event (RoomMemberEvent): The event that should be handled that updates the room state. Returns True if the member list of the room has changed False otherwise. """ if (event.membership == "invite" and event.state_key == self.own_user_id): self.inviter = event.sender return super().handle_membership(event)
Python
def logged_in(self) -> bool: """Check if we are logged in. Returns True if the client is logged in to the server, False otherwise. """ return bool(self.access_token)
def logged_in(self) -> bool: """Check if we are logged in. Returns True if the client is logged in to the server, False otherwise. """ return bool(self.access_token)
Python
def device_store(self) -> DeviceStore: """Store containing known devices. Returns a ``DeviceStore`` holding all known olm devices. """ assert self.olm return self.olm.device_store
def device_store(self) -> DeviceStore: """Store containing known devices. Returns a ``DeviceStore`` holding all known olm devices. """ assert self.olm return self.olm.device_store
Python
def olm_account_shared(self) -> bool: """Check if the clients Olm account is shared with the server. Returns True if the Olm account is shared, False otherwise. """ assert self.olm return self.olm.account.shared
def olm_account_shared(self) -> bool: """Check if the clients Olm account is shared with the server. Returns True if the Olm account is shared, False otherwise. """ assert self.olm return self.olm.account.shared
Python
def users_for_key_query(self) -> Set[str]: """Users for whom we should make a key query.""" if not self.olm: return set() return self.olm.users_for_key_query
def users_for_key_query(self) -> Set[str]: """Users for whom we should make a key query.""" if not self.olm: return set() return self.olm.users_for_key_query
Python
def should_upload_keys(self) -> bool: """Check if the client should upload encryption keys. Returns True if encryption keys need to be uploaded, false otherwise. """ if not self.olm: return False return self.olm.should_upload_keys
def should_upload_keys(self) -> bool: """Check if the client should upload encryption keys. Returns True if encryption keys need to be uploaded, false otherwise. """ if not self.olm: return False return self.olm.should_upload_keys
Python
def should_query_keys(self) -> bool: """Check if the client should make a key query call to the server. Returns True if a key query is necessary, false otherwise. """ if not self.olm: return False return self.olm.should_query_keys
def should_query_keys(self) -> bool: """Check if the client should make a key query call to the server. Returns True if a key query is necessary, false otherwise. """ if not self.olm: return False return self.olm.should_query_keys
Python
def should_claim_keys(self) -> bool: """Check if the client should claim one-time keys for some users. This should be periodically checked and if true a keys claim request should be made with the return value of a `get_users_for_key_claiming()` call as the payload. Keys need to be claimed for various reasons. Every time we need to send an encrypted message to a device and we don't have a working Olm session with them we need to claim one-time keys to create a new Olm session. Returns True if a key query is necessary, false otherwise. """ if not self.olm: return False return bool( self.olm.wedged_devices or self.olm.key_request_devices_no_session )
def should_claim_keys(self) -> bool: """Check if the client should claim one-time keys for some users. This should be periodically checked and if true a keys claim request should be made with the return value of a `get_users_for_key_claiming()` call as the payload. Keys need to be claimed for various reasons. Every time we need to send an encrypted message to a device and we don't have a working Olm session with them we need to claim one-time keys to create a new Olm session. Returns True if a key query is necessary, false otherwise. """ if not self.olm: return False return bool( self.olm.wedged_devices or self.olm.key_request_devices_no_session )
Python
def load_store(self): """Load the session store and olm account. Raises LocalProtocolError if the session_path, user_id and device_id are not set. """ if self.store: raise LocalProtocolError("Store is already loaded") if not self.store_path: raise LocalProtocolError("Store path is not defined.") if not self.user_id: raise LocalProtocolError("User id is not set") if not self.device_id: raise LocalProtocolError("Device id is not set") if not self.config.store: raise LocalProtocolError( "No store class was provided in the config." ) if self.config.encryption_enabled: self.store = self.config.store( self.user_id, self.device_id, self.store_path, self.config.pickle_key, self.config.store_name, ) assert self.store self.olm = Olm(self.user_id, self.device_id, self.store) self.encrypted_rooms = self.store.load_encrypted_rooms() if self.config.store_sync_tokens: self.loaded_sync_token = self.store.load_sync_token()
def load_store(self): """Load the session store and olm account. Raises LocalProtocolError if the session_path, user_id and device_id are not set. """ if self.store: raise LocalProtocolError("Store is already loaded") if not self.store_path: raise LocalProtocolError("Store path is not defined.") if not self.user_id: raise LocalProtocolError("User id is not set") if not self.device_id: raise LocalProtocolError("Device id is not set") if not self.config.store: raise LocalProtocolError( "No store class was provided in the config." ) if self.config.encryption_enabled: self.store = self.config.store( self.user_id, self.device_id, self.store_path, self.config.pickle_key, self.config.store_name, ) assert self.store self.olm = Olm(self.user_id, self.device_id, self.store) self.encrypted_rooms = self.store.load_encrypted_rooms() if self.config.store_sync_tokens: self.loaded_sync_token = self.store.load_sync_token()
Python
def room_contains_unverified(self, room_id: str) -> bool: """Check if a room contains unverified devices. Args: room_id (str): Room id of the room that should be checked. Returns True if the room contains unverified devices, false otherwise. Returns False if no Olm session is loaded or if the room isn't encrypted. """ try: room = self.rooms[room_id] except KeyError: raise LocalProtocolError( "No room found with room id {}".format(room_id) ) if not room.encrypted: return False if not self.olm: return False for user in room.users: if not self.olm.user_fully_verified(user): return True return False
def room_contains_unverified(self, room_id: str) -> bool: """Check if a room contains unverified devices. Args: room_id (str): Room id of the room that should be checked. Returns True if the room contains unverified devices, false otherwise. Returns False if no Olm session is loaded or if the room isn't encrypted. """ try: room = self.rooms[room_id] except KeyError: raise LocalProtocolError( "No room found with room id {}".format(room_id) ) if not room.encrypted: return False if not self.olm: return False for user in room.users: if not self.olm.user_fully_verified(user): return True return False
Python
def invalidate_outbound_session(self, room_id: str): """Explicitely remove encryption keys for a room. Args: room_id (str): Room id for the room the encryption keys should be removed. """ assert self.olm session = self.olm.outbound_group_sessions.pop(room_id, None) # There is no need to invalidate the session if it was never # shared, put it back where it was. if session and not session.shared: self.olm.outbound_group_sessions[room_id] = session elif session: logger.info("Invalidating session for {}".format(room_id))
def invalidate_outbound_session(self, room_id: str): """Explicitely remove encryption keys for a room. Args: room_id (str): Room id for the room the encryption keys should be removed. """ assert self.olm session = self.olm.outbound_group_sessions.pop(room_id, None) # There is no need to invalidate the session if it was never # shared, put it back where it was. if session and not session.shared: self.olm.outbound_group_sessions[room_id] = session elif session: logger.info("Invalidating session for {}".format(room_id))
Python
def verify_device(self, device: OlmDevice) -> bool: """Mark a device as verified. A device needs to be either trusted or blacklisted to either share room encryption keys with it or not. This method adds the device to the trusted devices and enables sharing room encryption keys with it. Args: device (OlmDevice): The device which should be added to the trust list. Returns true if the device was verified, false if it was already verified. """ assert self.olm changed = self.olm.verify_device(device) if changed: self._invalidate_outbound_sessions(device) return changed
def verify_device(self, device: OlmDevice) -> bool: """Mark a device as verified. A device needs to be either trusted or blacklisted to either share room encryption keys with it or not. This method adds the device to the trusted devices and enables sharing room encryption keys with it. Args: device (OlmDevice): The device which should be added to the trust list. Returns true if the device was verified, false if it was already verified. """ assert self.olm changed = self.olm.verify_device(device) if changed: self._invalidate_outbound_sessions(device) return changed
Python
def unverify_device(self, device: OlmDevice) -> bool: """Unmark a device as verified. This method removes the device from the trusted devices and disables sharing room encryption keys with it. It also invalidates any encryption keys for rooms that the device takes part of. Args: device (OlmDevice): The device which should be added to the trust list. Returns true if the device was unverified, false if it was already unverified. """ assert self.olm changed = self.olm.unverify_device(device) if changed: self._invalidate_outbound_sessions(device) return changed
def unverify_device(self, device: OlmDevice) -> bool: """Unmark a device as verified. This method removes the device from the trusted devices and disables sharing room encryption keys with it. It also invalidates any encryption keys for rooms that the device takes part of. Args: device (OlmDevice): The device which should be added to the trust list. Returns true if the device was unverified, false if it was already unverified. """ assert self.olm changed = self.olm.unverify_device(device) if changed: self._invalidate_outbound_sessions(device) return changed
Python
def blacklist_device(self, device: OlmDevice) -> bool: """Mark a device as blacklisted. Devices on the blacklist will not receive room encryption keys and therefore won't be able to decrypt messages coming from this client. Args: device (OlmDevice): The device which should be added to the blacklist. Returns true if the device was added, false if it was on the blacklist already. """ assert self.olm changed = self.olm.blacklist_device(device) if changed: self._invalidate_outbound_sessions(device) return changed
def blacklist_device(self, device: OlmDevice) -> bool: """Mark a device as blacklisted. Devices on the blacklist will not receive room encryption keys and therefore won't be able to decrypt messages coming from this client. Args: device (OlmDevice): The device which should be added to the blacklist. Returns true if the device was added, false if it was on the blacklist already. """ assert self.olm changed = self.olm.blacklist_device(device) if changed: self._invalidate_outbound_sessions(device) return changed
Python
def unblacklist_device(self, device: OlmDevice) -> bool: """Unmark a device as blacklisted. Args: device (OlmDevice): The device which should be removed from the blacklist. Returns true if the device was removed, false if it wasn't on the blacklist and no removal happened. """ assert self.olm changed = self.olm.unblacklist_device(device) if changed: self._invalidate_outbound_sessions(device) return changed
def unblacklist_device(self, device: OlmDevice) -> bool: """Unmark a device as blacklisted. Args: device (OlmDevice): The device which should be removed from the blacklist. Returns true if the device was removed, false if it wasn't on the blacklist and no removal happened. """ assert self.olm changed = self.olm.unblacklist_device(device) if changed: self._invalidate_outbound_sessions(device) return changed
Python
def ignore_device(self, device: OlmDevice) -> bool: """Mark a device as ignored. Ignored devices will still receive room encryption keys, despire not being verified. Args: device (OlmDevice): the device to ignore Returns true if device is ignored, or false if it is already on the list of ignored devices. """ assert self.olm changed = self.olm.ignore_device(device) if changed: self._invalidate_outbound_sessions(device) return changed
def ignore_device(self, device: OlmDevice) -> bool: """Mark a device as ignored. Ignored devices will still receive room encryption keys, despire not being verified. Args: device (OlmDevice): the device to ignore Returns true if device is ignored, or false if it is already on the list of ignored devices. """ assert self.olm changed = self.olm.ignore_device(device) if changed: self._invalidate_outbound_sessions(device) return changed
Python
def unignore_device(self, device: OlmDevice) -> bool: """Unmark a device as ignored. Args: device (OlmDevice): The device which should be removed from the list of ignored devices. Returns true if the device was removed, false if it wasn't on the list and no removal happened. """ assert self.olm changed = self.olm.unignore_device(device) if changed: self._invalidate_outbound_sessions(device) return changed
def unignore_device(self, device: OlmDevice) -> bool: """Unmark a device as ignored. Args: device (OlmDevice): The device which should be removed from the list of ignored devices. Returns true if the device was removed, false if it wasn't on the list and no removal happened. """ assert self.olm changed = self.olm.unignore_device(device) if changed: self._invalidate_outbound_sessions(device) return changed
Python
def decrypt_event(self, event: MegolmEvent) -> Union[Event, BadEventType]: """Try to decrypt an undecrypted megolm event. Args: event (MegolmEvent): Event that should be decrypted. Returns the decrypted event, raises EncryptionError if there was an error while decrypting. """ if not isinstance(event, MegolmEvent): raise ValueError( "Invalid event, this function can only decrypt " "MegolmEvents" ) assert self.olm return self.olm.decrypt_megolm_event(event)
def decrypt_event(self, event: MegolmEvent) -> Union[Event, BadEventType]: """Try to decrypt an undecrypted megolm event. Args: event (MegolmEvent): Event that should be decrypted. Returns the decrypted event, raises EncryptionError if there was an error while decrypting. """ if not isinstance(event, MegolmEvent): raise ValueError( "Invalid event, this function can only decrypt " "MegolmEvents" ) assert self.olm return self.olm.decrypt_megolm_event(event)
Python
def receive_response( self, response: Response ) -> Union[None, Coroutine[Any, Any, None]]: """Receive a Matrix Response and change the client state accordingly. Some responses will get edited for the callers convenience e.g. sync responses that contain encrypted messages. The encrypted messages will be replaced by decrypted ones if decryption is possible. Args: response (Response): the response that we wish the client to handle """ if not isinstance(response, Response): raise ValueError("Invalid response received") if isinstance(response, LoginResponse): self._handle_login(response) elif isinstance(response, LogoutResponse): self._handle_logout(response) elif isinstance(response, RegisterResponse): self._handle_register(response) elif isinstance(response, (SyncResponse, PartialSyncResponse)): self._handle_sync(response) elif isinstance(response, RoomMessagesResponse): self._handle_messages_response(response) elif isinstance(response, RoomContextResponse): self._handle_context_response(response) elif isinstance(response, KeysUploadResponse): self._handle_olm_response(response) elif isinstance(response, KeysQueryResponse): self._handle_olm_response(response) elif isinstance(response, KeysClaimResponse): self._handle_olm_response(response) elif isinstance(response, ShareGroupSessionResponse): self._handle_olm_response(response) elif isinstance(response, JoinedMembersResponse): self._handle_joined_members(response) elif isinstance(response, RoomKeyRequestResponse): self._handle_olm_response(response) elif isinstance(response, RoomForgetResponse): self._handle_room_forget_response(response) elif isinstance(response, ToDeviceResponse): self._handle_olm_response(response) elif isinstance(response, ErrorResponse): if response.soft_logout: self.access_token = "" return None
def receive_response( self, response: Response ) -> Union[None, Coroutine[Any, Any, None]]: """Receive a Matrix Response and change the client state accordingly. Some responses will get edited for the callers convenience e.g. sync responses that contain encrypted messages. The encrypted messages will be replaced by decrypted ones if decryption is possible. Args: response (Response): the response that we wish the client to handle """ if not isinstance(response, Response): raise ValueError("Invalid response received") if isinstance(response, LoginResponse): self._handle_login(response) elif isinstance(response, LogoutResponse): self._handle_logout(response) elif isinstance(response, RegisterResponse): self._handle_register(response) elif isinstance(response, (SyncResponse, PartialSyncResponse)): self._handle_sync(response) elif isinstance(response, RoomMessagesResponse): self._handle_messages_response(response) elif isinstance(response, RoomContextResponse): self._handle_context_response(response) elif isinstance(response, KeysUploadResponse): self._handle_olm_response(response) elif isinstance(response, KeysQueryResponse): self._handle_olm_response(response) elif isinstance(response, KeysClaimResponse): self._handle_olm_response(response) elif isinstance(response, ShareGroupSessionResponse): self._handle_olm_response(response) elif isinstance(response, JoinedMembersResponse): self._handle_joined_members(response) elif isinstance(response, RoomKeyRequestResponse): self._handle_olm_response(response) elif isinstance(response, RoomForgetResponse): self._handle_room_forget_response(response) elif isinstance(response, ToDeviceResponse): self._handle_olm_response(response) elif isinstance(response, ErrorResponse): if response.soft_logout: self.access_token = "" return None
Python
def export_keys(self, outfile: str, passphrase: str, count: int = 10000): """Export all the Megolm decryption keys of this device. The keys will be encrypted using the passphrase. Note that this does not save other information such as the private identity keys of the device. Args: outfile (str): The file to write the keys to. passphrase (str): The encryption passphrase. count (int): Optional. Round count for the underlying key derivation. It is not recommended to specify it unless absolutely sure of the consequences. """ assert self.olm self.olm.export_keys(outfile, passphrase, count=count)
def export_keys(self, outfile: str, passphrase: str, count: int = 10000): """Export all the Megolm decryption keys of this device. The keys will be encrypted using the passphrase. Note that this does not save other information such as the private identity keys of the device. Args: outfile (str): The file to write the keys to. passphrase (str): The encryption passphrase. count (int): Optional. Round count for the underlying key derivation. It is not recommended to specify it unless absolutely sure of the consequences. """ assert self.olm self.olm.export_keys(outfile, passphrase, count=count)
Python
def import_keys(self, infile: str, passphrase: str): """Import Megolm decryption keys. The keys will be added to the current instance as well as written to database. Args: infile (str): The file containing the keys. passphrase (str): The decryption passphrase. Raises `EncryptionError` if the file is invalid or couldn't be decrypted. Raises the usual file errors if the file couldn't be opened. """ assert self.olm self.olm.import_keys(infile, passphrase)
def import_keys(self, infile: str, passphrase: str): """Import Megolm decryption keys. The keys will be added to the current instance as well as written to database. Args: infile (str): The file containing the keys. passphrase (str): The decryption passphrase. Raises `EncryptionError` if the file is invalid or couldn't be decrypted. Raises the usual file errors if the file couldn't be opened. """ assert self.olm self.olm.import_keys(infile, passphrase)
Python
def encrypt( self, room_id: str, message_type: str, content: Dict[Any, Any] ) -> Tuple[str, Dict[str, str]]: """Encrypt a message to be sent to the provided room. Args: room_id (str): The room id of the room where the message will be sent. message_type (str): The type of the message. content (str): The dictionary containing the content of the message. Raises `GroupEncryptionError` if the group session for the provided room isn't shared yet. Raises `MembersSyncError` if the room is encrypted but the room members aren't fully loaded due to member lazy loading. Returns a tuple containing the new message type and the new encrypted content. """ assert self.olm try: room = self.rooms[room_id] except KeyError: raise LocalProtocolError( "No such room with id {} found.".format(room_id) ) if not room.encrypted: raise LocalProtocolError( "Room {} is not encrypted".format(room_id) ) if not room.members_synced: raise MembersSyncError( "The room is encrypted and the members " "aren't fully synced." ) encrypted_content = self.olm.group_encrypt( room_id, {"content": content, "type": message_type}, ) # The relationship needs to be sent unencrypted, so put it in the # unencrypted content. if "m.relates_to" in content: encrypted_content["m.relates_to"] = content["m.relates_to"] message_type = "m.room.encrypted" return message_type, encrypted_content
def encrypt( self, room_id: str, message_type: str, content: Dict[Any, Any] ) -> Tuple[str, Dict[str, str]]: """Encrypt a message to be sent to the provided room. Args: room_id (str): The room id of the room where the message will be sent. message_type (str): The type of the message. content (str): The dictionary containing the content of the message. Raises `GroupEncryptionError` if the group session for the provided room isn't shared yet. Raises `MembersSyncError` if the room is encrypted but the room members aren't fully loaded due to member lazy loading. Returns a tuple containing the new message type and the new encrypted content. """ assert self.olm try: room = self.rooms[room_id] except KeyError: raise LocalProtocolError( "No such room with id {} found.".format(room_id) ) if not room.encrypted: raise LocalProtocolError( "Room {} is not encrypted".format(room_id) ) if not room.members_synced: raise MembersSyncError( "The room is encrypted and the members " "aren't fully synced." ) encrypted_content = self.olm.group_encrypt( room_id, {"content": content, "type": message_type}, ) # The relationship needs to be sent unencrypted, so put it in the # unencrypted content. if "m.relates_to" in content: encrypted_content["m.relates_to"] = content["m.relates_to"] message_type = "m.room.encrypted" return message_type, encrypted_content
Python
def add_event_callback( self, callback: Callable[[MatrixRoom, Event], None], filter: Union[Type, Tuple[Type]], ): """Add a callback that will be executed on room events. The callback can be used on joined rooms as well as on invited rooms. The room parameter for the callback will have a different type depending on if the room is joined or invited. Args: callback (Callable[[MatrixRoom, Event], None]): A function that will be called if the event type in the filter argument is found in a room timeline. filter (Union[Type, Tuple[Type]]): The event type or a tuple containing multiple types for which the function will be called. """ cb = ClientCallback(callback, filter) self.event_callbacks.append(cb)
def add_event_callback( self, callback: Callable[[MatrixRoom, Event], None], filter: Union[Type, Tuple[Type]], ): """Add a callback that will be executed on room events. The callback can be used on joined rooms as well as on invited rooms. The room parameter for the callback will have a different type depending on if the room is joined or invited. Args: callback (Callable[[MatrixRoom, Event], None]): A function that will be called if the event type in the filter argument is found in a room timeline. filter (Union[Type, Tuple[Type]]): The event type or a tuple containing multiple types for which the function will be called. """ cb = ClientCallback(callback, filter) self.event_callbacks.append(cb)
Python
def add_ephemeral_callback( self, callback: Callable[[MatrixRoom, Event], None], filter: Union[Type, Tuple[Type]], ): """Add a callback that will be executed on ephemeral room events. Args: callback (Callable[MatrixRoom, Event]): A function that will be called if the event type in the filter argument is found in the ephemeral room event list. filter (Type, Tuple[Type]): The event type or a tuple containing multiple types for which the function will be called. """ cb = ClientCallback(callback, filter) self.ephemeral_callbacks.append(cb)
def add_ephemeral_callback( self, callback: Callable[[MatrixRoom, Event], None], filter: Union[Type, Tuple[Type]], ): """Add a callback that will be executed on ephemeral room events. Args: callback (Callable[MatrixRoom, Event]): A function that will be called if the event type in the filter argument is found in the ephemeral room event list. filter (Type, Tuple[Type]): The event type or a tuple containing multiple types for which the function will be called. """ cb = ClientCallback(callback, filter) self.ephemeral_callbacks.append(cb)
Python
def add_to_device_callback( self, callback: Callable[[ToDeviceEvent], None], filter: Union[Type, Tuple[Type]], ): """Add a callback that will be executed on to-device events. Args: callback (Callable[[ToDeviceEvent], None]): A function that will be called if the event type in the filter argument is found in a the to-device part of the sync response. filter (Union[Type, Tuple[Type]]): The event type or a tuple containing multiple types for which the function will be called. """ cb = ClientCallback(callback, filter) self.to_device_callbacks.append(cb)
def add_to_device_callback( self, callback: Callable[[ToDeviceEvent], None], filter: Union[Type, Tuple[Type]], ): """Add a callback that will be executed on to-device events. Args: callback (Callable[[ToDeviceEvent], None]): A function that will be called if the event type in the filter argument is found in a the to-device part of the sync response. filter (Union[Type, Tuple[Type]]): The event type or a tuple containing multiple types for which the function will be called. """ cb = ClientCallback(callback, filter) self.to_device_callbacks.append(cb)
Python
def create_key_verification(self, device: OlmDevice) -> ToDeviceMessage: """Start a new key verification process with the given device. Args: device (OlmDevice): The device which we would like to verify Returns a ``ToDeviceMessage`` that should be sent to to the homeserver. """ assert self.olm return self.olm.create_sas(device)
def create_key_verification(self, device: OlmDevice) -> ToDeviceMessage: """Start a new key verification process with the given device. Args: device (OlmDevice): The device which we would like to verify Returns a ``ToDeviceMessage`` that should be sent to to the homeserver. """ assert self.olm return self.olm.create_sas(device)
Python
def confirm_key_verification(self, transaction_id: str) -> ToDeviceMessage: """Confirm that the short auth string of a key verification matches. Args: transaction_id (str): The transaction id of the interactive key verification. Returns a ``ToDeviceMessage`` that should be sent to to the homeserver. If the other user already confirmed the short auth string on their side this function will also verify the device that is partaking in the verification process. """ if transaction_id not in self.key_verifications: raise LocalProtocolError( "Key verification with the transaction " "id {} does not exist.".format(transaction_id) ) sas = self.key_verifications[transaction_id] sas.accept_sas() message = sas.get_mac() if sas.verified: self.verify_device(sas.other_olm_device) return message
def confirm_key_verification(self, transaction_id: str) -> ToDeviceMessage: """Confirm that the short auth string of a key verification matches. Args: transaction_id (str): The transaction id of the interactive key verification. Returns a ``ToDeviceMessage`` that should be sent to to the homeserver. If the other user already confirmed the short auth string on their side this function will also verify the device that is partaking in the verification process. """ if transaction_id not in self.key_verifications: raise LocalProtocolError( "Key verification with the transaction " "id {} does not exist.".format(transaction_id) ) sas = self.key_verifications[transaction_id] sas.accept_sas() message = sas.get_mac() if sas.verified: self.verify_device(sas.other_olm_device) return message
Python
def room_devices(self, room_id: str) -> Dict[str, Dict[str, OlmDevice]]: """Get all Olm devices participating in a room. Args: room_id (str): The id of the room for which we would like to collect all the devices. Returns a dictionary holding the user as the key and a dictionary of the device id as the key and OlmDevice as the value. Raises LocalProtocolError if no room is found with the given room_id. """ devices: Dict[str, Dict[str, OlmDevice]] = defaultdict(dict) if not self.olm: return devices try: room = self.rooms[room_id] except KeyError: raise LocalProtocolError( "No room found with room id {}".format(room_id) ) if not room.encrypted: return devices users = room.users.keys() for user in users: user_devices = self.device_store.active_user_devices(user) devices[user] = {d.id: d for d in user_devices} return devices
def room_devices(self, room_id: str) -> Dict[str, Dict[str, OlmDevice]]: """Get all Olm devices participating in a room. Args: room_id (str): The id of the room for which we would like to collect all the devices. Returns a dictionary holding the user as the key and a dictionary of the device id as the key and OlmDevice as the value. Raises LocalProtocolError if no room is found with the given room_id. """ devices: Dict[str, Dict[str, OlmDevice]] = defaultdict(dict) if not self.olm: return devices try: room = self.rooms[room_id] except KeyError: raise LocalProtocolError( "No room found with room id {}".format(room_id) ) if not room.encrypted: return devices users = room.users.keys() for user in users: user_devices = self.device_store.active_user_devices(user) devices[user] = {d.id: d for d in user_devices} return devices
Python
def continue_key_share(self, event: RoomKeyRequest) -> bool: """Continue a previously interrupted key share event. To handle room key requests properly client users need to add a callback for RoomKeyRequest: >>> client.add_to_device_callback(callback, RoomKeyRequest) This callback will be run only if a room key request needs user interaction, that is if a room key request is coming from an untrusted device. After a user has verified the requesting device the key sharing can be continued using this method: >>> client.continue_key_share(room_key_request) Args: event (RoomKeyRequest): The event which we would like to continue. If the key share event is continued successfully a to-device message will be queued up in the `client.outgoing_to_device_messages` list waiting to be sent out Returns: bool: True if the request was continued, False otherwise. """ assert self.olm return self.olm.continue_key_share(event)
def continue_key_share(self, event: RoomKeyRequest) -> bool: """Continue a previously interrupted key share event. To handle room key requests properly client users need to add a callback for RoomKeyRequest: >>> client.add_to_device_callback(callback, RoomKeyRequest) This callback will be run only if a room key request needs user interaction, that is if a room key request is coming from an untrusted device. After a user has verified the requesting device the key sharing can be continued using this method: >>> client.continue_key_share(room_key_request) Args: event (RoomKeyRequest): The event which we would like to continue. If the key share event is continued successfully a to-device message will be queued up in the `client.outgoing_to_device_messages` list waiting to be sent out Returns: bool: True if the request was continued, False otherwise. """ assert self.olm return self.olm.continue_key_share(event)
Python
def cancel_key_share(self, event: RoomKeyRequest) -> bool: """Cancel a previously interrupted key share event. This method is the counterpart to the `continue_key_share()` method. If a user choses not to verify a device and does not want to share room keys with such a device it should cancel the request with this method. >>> client.cancel_key_share(room_key_request) Args: event (RoomKeyRequest): The event which we would like to cancel. Returns: bool: True if the request was cancelled, False otherwise. """ assert self.olm return self.olm.cancel_key_share(event)
def cancel_key_share(self, event: RoomKeyRequest) -> bool: """Cancel a previously interrupted key share event. This method is the counterpart to the `continue_key_share()` method. If a user choses not to verify a device and does not want to share room keys with such a device it should cancel the request with this method. >>> client.cancel_key_share(room_key_request) Args: event (RoomKeyRequest): The event which we would like to cancel. Returns: bool: True if the request was cancelled, False otherwise. """ assert self.olm return self.olm.cancel_key_share(event)
Python
def client_session(func): """Ensure that the Async client has a valid client session.""" @wraps(func) async def wrapper(self, *args, **kwargs): if not self.client_session: trace = TraceConfig() trace.on_request_chunk_sent.append(on_request_chunk_sent) self.client_session = ClientSession( timeout=ClientTimeout(total=self.config.request_timeout), trace_configs=[trace], ) self.client_session.connector.connect = partial( connect_wrapper, self.client_session.connector, ) return await func(self, *args, **kwargs) return wrapper
def client_session(func): """Ensure that the Async client has a valid client session.""" @wraps(func) async def wrapper(self, *args, **kwargs): if not self.client_session: trace = TraceConfig() trace.on_request_chunk_sent.append(on_request_chunk_sent) self.client_session = ClientSession( timeout=ClientTimeout(total=self.config.request_timeout), trace_configs=[trace], ) self.client_session.connector.connect = partial( connect_wrapper, self.client_session.connector, ) return await func(self, *args, **kwargs) return wrapper
Python
async def parse_body( self, transport_response: ClientResponse ) -> Dict[Any, Any]: """Parse the body of the response. Args: transport_response(ClientResponse): The transport response that contains the body of the response. Returns a dictionary representing the response. """ try: return await transport_response.json() except (JSONDecodeError, ContentTypeError): return {}
async def parse_body( self, transport_response: ClientResponse ) -> Dict[Any, Any]: """Parse the body of the response. Args: transport_response(ClientResponse): The transport response that contains the body of the response. Returns a dictionary representing the response. """ try: return await transport_response.json() except (JSONDecodeError, ContentTypeError): return {}
Python
async def create_matrix_response( self, response_class: Type, transport_response: ClientResponse, data: Tuple[Any, ...] = None, ) -> Response: """Transform a transport response into a nio matrix response. Args: response_class (Type): The class that the requests belongs to. transport_response (ClientResponse): The underlying transport response that contains our response body. data (Tuple, optional): Extra data that is required to instantiate the response class. Returns a subclass of `Response` depending on the type of the response_class argument. """ data = data or () content_type = transport_response.content_type is_json = content_type == "application/json" name = None if transport_response.content_disposition: name = transport_response.content_disposition.filename if issubclass(response_class, FileResponse) and is_json: parsed_dict = await self.parse_body(transport_response) resp = response_class.from_data(parsed_dict, content_type, name) elif issubclass(response_class, FileResponse): body = await transport_response.read() resp = response_class.from_data(body, content_type, name) elif ( transport_response.status == 401 and response_class == DeleteDevicesResponse ): parsed_dict = await self.parse_body(transport_response) resp = DeleteDevicesAuthResponse.from_dict(parsed_dict) else: parsed_dict = await self.parse_body(transport_response) resp = response_class.from_dict(parsed_dict, *data) resp.transport_response = transport_response return resp
async def create_matrix_response( self, response_class: Type, transport_response: ClientResponse, data: Tuple[Any, ...] = None, ) -> Response: """Transform a transport response into a nio matrix response. Args: response_class (Type): The class that the requests belongs to. transport_response (ClientResponse): The underlying transport response that contains our response body. data (Tuple, optional): Extra data that is required to instantiate the response class. Returns a subclass of `Response` depending on the type of the response_class argument. """ data = data or () content_type = transport_response.content_type is_json = content_type == "application/json" name = None if transport_response.content_disposition: name = transport_response.content_disposition.filename if issubclass(response_class, FileResponse) and is_json: parsed_dict = await self.parse_body(transport_response) resp = response_class.from_data(parsed_dict, content_type, name) elif issubclass(response_class, FileResponse): body = await transport_response.read() resp = response_class.from_data(body, content_type, name) elif ( transport_response.status == 401 and response_class == DeleteDevicesResponse ): parsed_dict = await self.parse_body(transport_response) resp = DeleteDevicesAuthResponse.from_dict(parsed_dict) else: parsed_dict = await self.parse_body(transport_response) resp = response_class.from_dict(parsed_dict, *data) resp.transport_response = transport_response return resp
Python
async def receive_response(self, response: Response) -> None: """Receive a Matrix Response and change the client state accordingly. Some responses will get edited for the callers convenience e.g. sync responses that contain encrypted messages. The encrypted messages will be replaced by decrypted ones if decryption is possible. Args: response (Response): the response that we wish the client to handle """ if not isinstance(response, Response): raise ValueError("Invalid response received") if isinstance(response, (SyncResponse, PartialSyncResponse)): await self._handle_sync(response) else: super().receive_response(response)
async def receive_response(self, response: Response) -> None: """Receive a Matrix Response and change the client state accordingly. Some responses will get edited for the callers convenience e.g. sync responses that contain encrypted messages. The encrypted messages will be replaced by decrypted ones if decryption is possible. Args: response (Response): the response that we wish the client to handle """ if not isinstance(response, Response): raise ValueError("Invalid response received") if isinstance(response, (SyncResponse, PartialSyncResponse)): await self._handle_sync(response) else: super().receive_response(response)
Python
async def send( self, method: str, path: str, data: Union[None, str, AsyncDataT] = None, headers: Optional[Dict[str, str]] = None, trace_context: Any = None, timeout: Optional[float] = None, ) -> ClientResponse: """Send a request to the homeserver. Args: method (str): The request method that should be used. One of get, post, put, delete. path (str): The URL path of the request. data (str, optional): Data that will be posted with the request. headers (Dict[str,str] , optional): Additional request headers that should be used with the request. trace_context (Any, optional): An object to use for the ClientSession TraceConfig context timeout (int, optional): How many seconds the request has before raising `asyncio.TimeoutError`. Overrides `AsyncClient.config.request_timeout` if not `None`. """ assert self.client_session return await self.client_session.request( method, self.homeserver + path, data=data, ssl=self.ssl, proxy=self.proxy, headers=headers, trace_request_ctx=trace_context, timeout=self.config.request_timeout if timeout is None else timeout, )
async def send( self, method: str, path: str, data: Union[None, str, AsyncDataT] = None, headers: Optional[Dict[str, str]] = None, trace_context: Any = None, timeout: Optional[float] = None, ) -> ClientResponse: """Send a request to the homeserver. Args: method (str): The request method that should be used. One of get, post, put, delete. path (str): The URL path of the request. data (str, optional): Data that will be posted with the request. headers (Dict[str,str] , optional): Additional request headers that should be used with the request. trace_context (Any, optional): An object to use for the ClientSession TraceConfig context timeout (int, optional): How many seconds the request has before raising `asyncio.TimeoutError`. Overrides `AsyncClient.config.request_timeout` if not `None`. """ assert self.client_session return await self.client_session.request( method, self.homeserver + path, data=data, ssl=self.ssl, proxy=self.proxy, headers=headers, trace_request_ctx=trace_context, timeout=self.config.request_timeout if timeout is None else timeout, )
Python
async def sync( self, timeout: Optional[int] = None, sync_filter: _FilterT = None, since: Optional[str] = None, full_state: Optional[bool] = None, ) -> Union[SyncResponse, SyncError]: """Synchronise the client's state with the latest state on the server. Args: timeout(int, optional): The maximum time that the server should wait for new events before it should return the request anyways, in milliseconds. If the server fails to return after 15 seconds of expected timeout, the client will timeout by itself. sync_filter (Union[None, str, Dict[Any, Any]): A filter ID or dict that should be used for this sync request. full_state (bool, optional): Controls whether to include the full state for all rooms the user is a member of. If this is set to true, then all state events will be returned, even if since is non-empty. The timeline will still be limited by the since parameter. since (str, optional): A token specifying a point in time where to continue the sync from. Defaults to the last sync token we received from the server using this API call. Returns either a `SyncResponse` if the request was successful or a `SyncError` if there was an error with the request. """ sync_token = since or self.next_batch method, path = Api.sync( self.access_token, since=sync_token or self.loaded_sync_token, timeout=timeout, filter=sync_filter, full_state=full_state, ) response = await self._send( SyncResponse, method, path, # + 15: give server a chance to naturally return before we timeout timeout=None if timeout is None else timeout / 1000 + 15, ) self.synced.set() self.synced.clear() return response
async def sync( self, timeout: Optional[int] = None, sync_filter: _FilterT = None, since: Optional[str] = None, full_state: Optional[bool] = None, ) -> Union[SyncResponse, SyncError]: """Synchronise the client's state with the latest state on the server. Args: timeout(int, optional): The maximum time that the server should wait for new events before it should return the request anyways, in milliseconds. If the server fails to return after 15 seconds of expected timeout, the client will timeout by itself. sync_filter (Union[None, str, Dict[Any, Any]): A filter ID or dict that should be used for this sync request. full_state (bool, optional): Controls whether to include the full state for all rooms the user is a member of. If this is set to true, then all state events will be returned, even if since is non-empty. The timeline will still be limited by the since parameter. since (str, optional): A token specifying a point in time where to continue the sync from. Defaults to the last sync token we received from the server using this API call. Returns either a `SyncResponse` if the request was successful or a `SyncError` if there was an error with the request. """ sync_token = since or self.next_batch method, path = Api.sync( self.access_token, since=sync_token or self.loaded_sync_token, timeout=timeout, filter=sync_filter, full_state=full_state, ) response = await self._send( SyncResponse, method, path, # + 15: give server a chance to naturally return before we timeout timeout=None if timeout is None else timeout / 1000 + 15, ) self.synced.set() self.synced.clear() return response