def __init__(self, tree, fields): self.fields = fields if tree['predicates'] is True: self.predicates = Predicates([True]) else: self.predicates = Predicates(tree['predicates']) self.id = None children = [] if 'children' in tree: for child in tree['children']: children.append(AnomalyTree(child, self.fields)) self.children = children
class AnomalyTree(object): """An anomaly tree-like predictive model. """ def __init__(self, tree, fields): self.fields = fields if tree['predicates'] is True: self.predicates = Predicates([True]) else: self.predicates = Predicates(tree['predicates']) self.id = None children = [] if 'children' in tree: for child in tree['children']: children.append(AnomalyTree(child, self.fields)) self.children = children def list_fields(self, out): """Lists a description of the model's fields. """ for field in [(val['name'], val['optype']) for _, val in sort_fields(self.fields)]: out.write(utf8(u'[%-32s : %s]\n' % (field[0], field[1]))) out.flush() return self.fields def depth(self, input_data, path=None, depth=0): """Returns the depth of the node that reaches the input data instance when ran through the tree, and the associated set of rules. If a node has any children whose predicates are all true given the instance, then the instance will flow through that child. If the node has no children or no children with all valid predicates, then it outputs the depth of the node. """ if path is None: path = [] # root node: if predicates are met, depth becomes 1, otherwise is 0 if depth == 0: if not self.predicates.apply(input_data, self.fields): return depth, path depth += 1 if self.children: for child in self.children: if child.predicates.apply(input_data, self.fields): path.append(child.predicates.to_rule(self.fields)) return child.depth(input_data, path=path, depth=depth + 1) return depth, path
def __init__(self, tree, fields): self.fields = fields if tree['predicates'] is True: self.predicates = Predicates([True]) else: self.predicates = Predicates(tree['predicates']) if 'id' in tree: self.id = tree['id'] self.parent_id = parent_id if isinstance(ids_map, dict): ids_map[self.id] = self else: self.id = None children = [] if 'children' in tree: for child in tree['children']: children.append(AnomalyTree(child, self.fields)) self.children = children