def combine_external_clause(self, conjunctiveClause, conclusion):
        premises = self.get_rule_premises_by_conclusion(conclusion)
        premises.add(conjunctiveClause)

        rule = self.get_rule_by_conclusion(conclusion)
        newRule = Rule(premises, conclusion)

        if rule != None:
            self.rules.remove(rule)

        self.rules.add(newRule)

        return self.rules
Пример #2
0
    def add_rule(self, rule, scope):
        """
        Parse and append rule to the block's rules
        :param rule: str-rule (string of the form 'if var1 is adj1 then var2 is adj2')
        :param scope: scope with variables and adjectives to parse the string
        """
        rule = Rule.parse(rule, scope, self.and_, self.or_, self.not_)

        for var in rule.input_vars():
            self.inputs[var.name] = var
        for var in rule.output_vars():
            self.outputs[var.name] = var

        self.rules.append(rule)
Пример #3
0
    def add_rule(self, rule, scope):
        """
        Parse and append rule to the block's rules
        :param rule: str-rule (string of the form 'if var1 is adj1 then var2 is adj2')
        :param scope: scope with variables and adjectives to parse the string
        """
        rule = Rule.parse(rule, scope, self.and_, self.or_, self.not_)

        for var in rule.input_vars():
            self.inputs[var.name] = var
        for var in rule.output_vars():
            self.outputs[var.name] = var

        self.rules.append(rule)
Пример #4
0
def test4():
    logger.info("***** Tes4 - Two Router Two Rules *****")
    args = {'verbose': True}
    bgp_router_match = Match("bgp_router", "global", "^router\s+bgp")
    bgp_rule = Rule("Match BGP routing")
    bgp_rule.set_confirm_match(bgp_router_match)
    ospf_router_match = Match("ospf_router", "global", "^router\s+ospf")
    ospf_lsa_match = Match("ospf_max_lsa", r"^\s*router ospf",
                           (False, r"max-metric router-lsa"))
    ospf_rule = Rule("Match OSPF routing")
    ospf_rule.set_confirm_match(ospf_router_match, '&', ospf_lsa_match)
    test_rules = {1: bgp_rule, 2: ospf_rule}
    task = TestTask(DEVICES, 'ios', 'cisco', 'cisco', optional_args=args)
    task.set_device_rules(list(test_rules.keys()), test_rules)
    task.run_all_rules()
    pprint(task.matches)
Пример #5
0
def _parse_C5_rule_str(rule_str, rule_conclusion_map,
                       prior_rule_confidence) -> Set[Rule]:
    rules_set: Set[Rule] = set()

    rule_str_lines = rule_str.split('\n')
    line_index = 2

    metadata_variables = parse_variable_str_to_dict(rule_str_lines[line_index])
    n_rules = metadata_variables['rules']

    for _ in range(0, n_rules):
        line_index += 1

        rule_data_variables = parse_variable_str_to_dict(
            rule_str_lines[line_index])
        n_rule_terms = rule_data_variables['conds']
        rule_conclusion = rule_conclusion_map[(rule_data_variables['class'])]

        # C5 rule confidence=(number of training cases correctly classified + 1)/(total training cases covered  + 2)
        rule_confidence = (rule_data_variables['ok'] +
                           1) / (rule_data_variables['cover'] + 2)
        # Weight rule confidence by confidence of previous rule
        rule_confidence = rule_confidence * prior_rule_confidence

        rule_terms: Set[Term] = set()
        for _ in range(0, n_rule_terms):
            line_index += 1

            term_variables = parse_variable_str_to_dict(
                rule_str_lines[line_index])
            term_neuron_str = term_variables['att'].split('_')
            term_neuron = Neuron(layer=int(term_neuron_str[1]),
                                 index=int(term_neuron_str[2]))

            term_operator = '<=' if term_variables[
                'result'] == '<' else '>'  # In C5, < -> <=, > -> >
            term_operand = term_variables['cut']

            rule_terms.add(
                Term(neuron=term_neuron,
                     operator=term_operator,
                     threshold=term_operand))

        rules_set.add(
            Rule.from_term_set(premise=rule_terms,
                               conclusion=rule_conclusion,
                               confidence=rule_confidence))

    return rules_set
Пример #6
0
def apply_rules(template_rules, known_file, spooky_file):
    """[summary]

    Arguments:
        template_rules {dict} -- [description]
        known_file {xarray.Dataset} -- [description]
        spooky_file {xarray.Dataset} -- [description]

    Returns:
        [list] -- [description]
    """

    rules = []

    # if template_rules.get('check_attrs'):
    # rules += [known_file.attrs[a] == spooky_file.attrs[a]
    #         for a in template_rules['check_attrs']]

    if template_rules.get('check_dimensions_identical'):
        rules += [Rule(known_file.dims == spooky_file.dims)]

    if template_rules.get('check_unlimited_time_dim'):

        def find_time_dim():
            for d in spooky_file.dims.keys():
                if 'time' in d:
                    return d

        time_dim_key = find_time_dim()

        rules += [Rule(time_dim_key in spooky_file.encoding['unlimited_dims'])]

    if template_rules.get('check_variables'):
        rules += [Rule(known_file.variables == spooky_file.variables)]

    return rules
    def combine_ruleset(self, other):
        conclusions_self = self.get_ruleset_conclusions()
        conclusions_other = other.get_ruleset_conclusions()
        combined_rules = set()

        diff = conclusions_self.symmetric_difference(conclusions_other)
        intersect = conclusions_self.intersection(conclusions_other)

        for rule in self.rules.union(other.rules):
            if rule.get_conclusion() in diff:
                combined_rules.add(rule)

        for rule in self.rules:
            if rule.get_conclusion() in intersect:
                premise = other.get_rule_premises_by_conclusion(rule.get_conclusion())
                combined_premise = premise.union(rule.get_premise())
                combined_rule = Rule(combined_premise, rule.get_conclusion())
                combined_rules.add(combined_rule)
        return combined_rules
Пример #8
0
def build_rules():
    nxos_interface_fpath_match = Match(
        "nxos_interface_fpath",
        r"^interface", [(True, r"switchport\s+mode\s+fabricpath"),
                        (False, r"vpc\s+peer-link"),
                        (True, r"^\s*no\s+shutdown"),
                        (False, r"channel\-group\s+\d+")])
    nxos_interface_fpath_rule = Rule("Shutdown fabricpath ports")
    nxos_interface_fpath_rule.set_confirm_match(nxos_interface_fpath_match)
    template = "{% for interface in objects['nxos_interface_fpath'][0] %}\n{{ interface.text }}\n  shutdown\n{% endfor %}\n" \
               "\n********** Undo **********\n" \
               "{% for interface in objects['nxos_interface_fpath'][0] %}\n{{ interface.text }}\n  no shut\n{% endfor %}\n"
    nxos_interface_fpath_rule.set_config_template(template)
    fpath_vdc_rules["fpath"] = nxos_interface_fpath_rule

    nxos_interface_vpc_match = Match("nxos_interface_vpc",
                                     r"interface port-channel",
                                     [(True, r"vpc\s+\d+"),
                                      (False, r"^\s*shutdown")])
    nxos_interface_vpc_rule = Rule("Shutdown vpc ports")
    nxos_interface_vpc_rule.set_confirm_match(nxos_interface_vpc_match)
    template = "{% for interface in objects['nxos_interface_vpc'][0] %}\n{{ interface.text }}\n  shutdown\n{% endfor %}\n" \
               "\n********** Undo **********\n" \
               "{% for interface in objects['nxos_interface_vpc'][0] %}\n{{ interface.text }}\n  no shut\n{% endfor %}\n"
    nxos_interface_vpc_rule.set_config_template(template)
    default_vdc_rules[545325] = nxos_interface_vpc_rule
    fpath_vdc_rules[545325] = nxos_interface_vpc_rule

    nxos_interface_pka_match = Match("nxos_interface_pka", r"^interface",
                                     [(True, r"^\s*ip\s+address"),
                                      (True, r"vrf\s+member\s+vpc\-keepalive"),
                                      (False, r"^\s*shutdown")])
    nxos_interface_pka_rule = Rule("Shutdown PKA")
    nxos_interface_pka_rule.set_confirm_match(nxos_interface_pka_match)
    template = "{% for interface in objects['nxos_interface_pka'][0] %}\n{{ interface.text }}\n  shutdown\n{% endfor %}\n" \
               "\n********** Undo **********\n" \
               "{% for interface in objects['nxos_interface_pka'][0] %}\n{{ interface.text }}\n  no shut\n{% endfor %}\n"
    nxos_interface_pka_rule.set_config_template(template)
    default_vdc_rules["pka"] = nxos_interface_pka_rule
    fpath_vdc_rules["pka"] = nxos_interface_pka_rule

    nxos_interface_peerlink_match = Match("nxos_interface_peerlink",
                                          r"interface port-channel",
                                          [(True, r"vpc\s+peer-link"),
                                           (False, r"^\s*shutdown")])
    nxos_interface_peerlink_rule = Rule("Shutdown vpc peer link ports")
    nxos_interface_peerlink_rule.set_confirm_match(
        nxos_interface_peerlink_match)
    template = "{% for interface in objects['nxos_interface_peerlink'][0] %}\n{{ interface.text }}\n  shutdown\n{% endfor %}\n" \
               "\n********** Undo **********\n" \
               "{% for interface in objects['nxos_interface_peerlink'][0] %}\n{{ interface.text }}\n  no shut\n{% endfor %}\n"
    nxos_interface_peerlink_rule.set_config_template(template)
    default_vdc_rules["peerlink"] = nxos_interface_peerlink_rule
    fpath_vdc_rules["peerlnk"] = nxos_interface_peerlink_rule

    bgp_router_match = Match("bgp_router", "global", "^router\s+bgp")
    # bgp_routemap_match = BlockMatch("bgp_routemap_match", r"^\s+route-map")
    # bgp_neighbors_af_match = ChildMatch("bgp_neighbors_af_match", r"\s+neighbor", r"\s+(address-family.*)")
    # bgp_routemap_rule = Rule("BGP Prepend to All Neighbors")
    # bgp_routemap_rule.set_confirm_match(bgp_router_match, '&', bgp_routemap_match, '&', bgp_neighbors_af_match)
    # """
    # !*** BGP Prepend to All Neighbors ***
    #  {'bgp_router': [[<IOSCfgLine # 225 'router bgp 65534'>]],
    #  'bgp_routemap_match': ['router bgp 65534', '  neighbor 172.29.231.238 remote-as 65534', '    address-family ipv4 unicast',
    #  '      route-map CIENA-ROUTES out', '  neighbor 172.29.231.246 remote-as 65534', '    address-family ipv4 unicast',
    #  '      route-map CIENA-ROUTES out', '  neighbor 172.29.231.250 remote-as 65534', '    address-family ipv4 unicast',
    #  '      route-map CIENA-ROUTES ou'],
    #  'bgp_neighbors_af_match': {'parents': [<IOSCfgLine # 228 '  neighbor 172.26.33.194 remote-as 65535' (parent is # 225)>,
    #  <IOSCfgLine # 231 '  neighbor 172.29.231.238 remote-as 65534' (parent is # 225)>,
    #  <IOSCfgLine # 235 '  neighbor 172.29.231.246 remote-as 65534' (parent is # 225)>,
    #  <IOSCfgLine # 239 '  neighbor 172.29.231.250 remote-as 65534' (parent is # 225)>],
    #  'children': {'  neighbor 172.26.33.194 remote-as 65535': ('address-family ipv4 unicast',),
    #  '  neighbor 172.29.231.238 remote-as 65534': ('address-family ipv4 unicast',),
    #  '  neighbor 172.29.231.246 remote-as 65534': ('address-family ipv4 unicast',),
    #  '  neighbor 172.29.231.250 remote-as 65534': ('address-family ipv4 unicast',)}}}
    # """
    # template = "route-map THESOUTHERNREACH permit 10\n  set as-path prepend 65534 65534 65534 65534 \n" \
    #            "{{ objects['bgp_router'][0][0].text }}" \
    #            "{% for neighbor, af_tuple in objects['bgp_neighbors_af_match']['children'].items() %}\n" \
    #            "{{ neighbor }}\n" \
    #            "{% for af in af_tuple %}" \
    #            "    {{ af }}\n" \
    #            "      route-map THESOUTHERNREACH out\n" \
    #            "{% endfor %}\n" \
    #            "{% endfor %}\n" \
    #            "\n ********** Undo **********\n" \
    #            "{{ objects['bgp_router'][0][0].text }}" \
    #            "{% for neighbor, af_tuple in objects['bgp_neighbors_af_match']['children'].items() %}\n" \
    #            "{{ neighbor }}\n" \
    #            "{% for af in af_tuple %}" \
    #            "    {{ af }}\n" \
    #            "      no route-map THESOUTHERNREACH out\n" \
    #            "{% endfor %}\n" \
    #            "{% endfor %}\n" \
    #            "{% for line in objects['bgp_routemap_match'] %}" \
    #            "{{ line  }}\n" \
    #            "{% endfor %}\n"
    # bgp_routemap_rule.set_config_template(template)
    bgp_shutdown_rule = Rule("Shutdown BGP routing")
    bgp_shutdown_rule.set_confirm_match(bgp_router_match)
    template = "{{ objects['bgp_router'][0][0].text }}" \
               " shutdown\n" \
               "\n ********** Undo **********\n" \
               "{{ objects['bgp_router'][0][0].text }}" \
               "  no shutdown\n"
    bgp_shutdown_rule.set_config_template(template)
    default_vdc_rules["bgp"] = bgp_shutdown_rule

    ospf_router_match = Match("ospf_router", "global", "^router\s+ospf")
    ospf_shutdown_match = Match("ospf_max_lsa", r"^\s*router ospf",
                                (False, r"max-metric router-lsa"))
    ospf_shutdown_rule = Rule("Disable OSPF routing")
    ospf_shutdown_rule.set_confirm_match(ospf_router_match, '&',
                                         ospf_shutdown_match)
    template = "{% for router in objects['ospf_router'][0] %}\n{{ router.text }}\n  max-metric router-lsa\n{% endfor %}\n" \
               "\n ********** Undo **********\n" \
               "{% for router in objects['ospf_router'][0] %}\n{{ router.text }}\n  no max-metric router-lsa\n{% endfor %}\n"
    ospf_shutdown_rule.set_config_template(template)
    default_vdc_rules["ospf shutdown"] = ospf_shutdown_rule

    nxos_interface_ipint_match = Match(
        "nxos_interface_ipint", r"^interface\s+(?:Ethernet)",
        [(True, r"^\s*ip\s+address"),
         (False, r"vrf\s+member\s+vpc\-keepalive"),
         (True, r"^\s*no\s+shutdown")])
    nxos_interface_ipint_rule = Rule("Shutdown L3 Interfaces")
    nxos_interface_ipint_rule.set_confirm_match(nxos_interface_ipint_match)
    template = "{% for interface in objects['nxos_interface_ipint'][0] %}\n{{ interface.text }}\n  shutdown\n{% endfor %}\n" \
               "\n ********** Undo **********\n" \
               "{% for interface in objects['nxos_interface_ipint'][0] %}\n{{ interface.text }}\n  no shut\n{% endfor %}\n"
    nxos_interface_ipint_rule.set_config_template(template)
    default_vdc_rules["ipint"] = nxos_interface_ipint_rule

    nxos_pc_ipint_match = Match("nxos_pc_ipint",
                                r"^interface\s+(?:port\-channel)",
                                [(True, r"^\s*ip\s+address"),
                                 (False, r"vrf\s+member\s+vpc\-keepalive"),
                                 (False, r"^\s*shutdown")])
    nxos_pc_ipint_rule = Rule("Shutdown L3 PC Interfaces")
    nxos_pc_ipint_rule.set_confirm_match(nxos_pc_ipint_match)
    template = "{% for interface in objects['nxos_pc_ipint'][0] %}\n{{ interface.text }}\n  shutdown\n{% endfor %}\n" \
               "\n ********** Undo **********\n" \
               "{% for interface in objects['nxos_pc_ipint'][0] %}\n{{ interface.text }}\n  no shut\n{% endfor %}\n"
    nxos_pc_ipint_rule.set_config_template(template)
    default_vdc_rules["pcipint"] = nxos_pc_ipint_rule
Пример #9
0
 def run(self, mix, boundaries):
     tracks = Rule.getTracks(mix)
     change = max([abs(track.playRate - 1) for track in tracks])
     score = 1 if change < self.minPlayRateChange else 1 - \
         (change-self.minPlayRateChange)/(self.maxPlayRateChange-self.minPlayRateChange)
     return max(score, 0)
Пример #10
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 27 16:33:13 2020
@author: cristian
"""
from rules.Psi import Psi
from rules.basicsRules.mainRule import *
from datetime import datetime
from rules.rule import Rule
from saveDatas.csvSave import csvSave
if __name__ == '__main__':
    # -- -- -- -- -- -- -- -- E-E -- -- -- -- -- -- -- -- -- -- -- -- --
    #Criando a lista de setups para o fenômeno
    Setups = [('Data', type(datetime.today())), ('Responsavel', str),
              ('Código', int), ('Identificador', int)]
    #Lista de fenômenos inicia vazia
    PhenomenonList = []
    #Cria um novo fenômeno com os setups
    newPhenomenon = Phenomenon(Setups)
    #Adiciona os dados presentes na planilha. O algoritmo vai automaticamente separar o as tags,
    #instâncias e dados
    newPhenomenon.from_xls_data('Datas/example.xlsx')
    #adiciona o fenômeno na lista de fenômenos
    PhenomenonList.append(newPhenomenon)
    # -- -- -- -- -- -- -- -- E-T -- -- -- -- -- -- -- -- -- -- -- -- --
    #Criando a lista de regras
    #R = []
    R = [
        Rule(0, fixStrInt),