def translate_policy_to_access_structure(policy: str) -> list:
    """
    Translate an access policy to an access structure.
    Example: (ONE AND THREE) OR (TWO AND FOUR) is translated to
                [['ONE', 'THREE'], ['TWO', 'FOUR']]
    :param policy: The policy to translate
    :return:
    >>> policy = '(ONE AND THREE) OR (TWO AND FOUR)'
    >>> translated = translate_policy_to_access_structure(policy)
    >>> equal_access_structures(translated, [['ONE', 'THREE'], ['TWO', 'FOUR']])
    True
    >>> policy = 'ONE'
    >>> translated = translate_policy_to_access_structure(policy)
    >>> equal_access_structures(translated, [['ONE']])
    True
    >>> policy = '(ONE@A1 AND THREE@A1) OR (TWO@A2 AND FOUR@A2)'
    >>> translated = translate_policy_to_access_structure(policy)
    >>> equal_access_structures(translated, [['ONE@A1', 'THREE@A1'], ['TWO@A2', 'FOUR@A2']])
    True
    >>> policy = '(ONE AND THREE) OR (TWO AND FOUR AND FIVE) OR (SEVEN AND SIX)'
    >>> translated = translate_policy_to_access_structure(policy)
    >>> equal_access_structures(translated, [['ONE', 'THREE'], ['TWO', 'FOUR', 'FIVE'], ['SEVEN', 'SIX']])
    True
    >>> policy = '(ONE OR THREE) AND (TWO OR FOUR)'
    >>> translated = translate_policy_to_access_structure(policy)
    >>> equal_access_structures(translated, [['ONE', 'TWO'], ['ONE', 'FOUR'], ['THREE', 'TWO'], ['THREE', 'FOUR']])
    True
    """
    algebra = boolean.BooleanAlgebra()
    policy = algebra.parse(policy.replace('@', '::'))
    dnf = policy if isinstance(policy, Symbol) else algebra.dnf(policy)
    return dnf_algebra_to_access_structure(dnf)
Example #2
0
def execute_query(query, max_results, inverted_index):
    # Remove punctuations that are not allowed
    filtered_query = kit.filter_boolean_expression(query)

    # Try to parse the logical expression or return no documents' id
    algebra = boolean.BooleanAlgebra()
    try:
        expression = algebra.parse(filtered_query)
    except Exception:
        return []

    # Filter all terms inside the query
    symbols = expression.symbols
    filtered_terms = [kit.filter_text(item.obj)[0] for item in symbols]

    # Create a small inverted index of the terms with only documents id (not frequency)
    query_index = {}
    for term in filtered_terms:
        ref_docs = set(ref[0]
                       for ref in inverted_index.get_term_references(term))
        query_index[term] = ref_docs

    # Create a tree of the expression and find the documents
    tree = create_expression_tree(expression)
    documents = tree.evaluate(query_index)
    # Reduce documents to the maximum allowed number (if there are more)
    if len(documents) > max_results:
        documents = list(documents)[:max_results]
    return documents
Example #3
0
def parsercnf2dimacs(cnf_str):
    """Parse cnf in string to DIMACS format
    Args:
        cnf_str : string
            a string of cnf
            
    Returns
    -------
        dimacs : list of lists
            dimacs format
    """
    algebra = boolean.BooleanAlgebra()
    logic_formule = algebra.parse(cnf_str)
    variables = logic_formule.symbols
    variables = list(map(str, variables))

    cluste_list = cnf_str.split('&')
    num_cluste = len(cluste_list)

    dimacs = [
        'c this is a simple dimacs'.split(), 'c this is a comment 0'.split()
    ]
    dimacs.append("p cnf {} {}".format(len(variables), num_cluste).split())
    for i in range(num_cluste):
        f = cluste_list[i]
        element_list = f.replace('(', '').replace(')', '').split('|')
        mid_f = []
        for ele in element_list:
            if ele.startswith('~'):
                mid_f.append(-(variables.index(ele.replace('~', '')) + 1))
            else:
                mid_f.append(variables.index(ele) + 1)
        mid_f.append(0)
        dimacs.append(mid_f)
    return dimacs
Example #4
0
 def __init__(self, features_table, reduct, settings):
     self.features_table = features_table.copy()
     self.reduct = reduct
     self.settings = settings
     self.algebra = boolean.BooleanAlgebra()
     self.TRUE, self.FALSE, self.NOT, self.AND, self.OR, self.Symbol = self.algebra.definition(
     )
Example #5
0
def testLogic(file_path):
    json_string = ""
    with io.open(file_path, 'r') as file:
        for line in file.readlines():
            json_string += line.split('#')[0].replace('\n', ' ')
    json_string = re.sub(' +', ' ', json_string)
    try:
        region_json = json.loads(json_string)
    except json.JSONDecodeError as error:
        raise Exception("JSON parse error around text:\n" + \
                        json_string[error.pos-35:error.pos+35] + "\n" + \
                        "                                   ^^\n")
    #print(region_json)
    alg = boolean.BooleanAlgebra()
    t, f, n, a, o, s = alg.definition()
    for region in region_json:
        #print(region['region_name'])
        pregion = region
        if ('locations' in region):
            for loc, rule in region['locations'].items():
                pregion['locations'][loc] = {
                    'logic': rule,
                    'items': [],
                    'paths': []
                }
                #print("\t" + loc)
                rule = parseFunctions(rule)
                print("\t\t" + rule)
                boolrule = alg.parse(rule, simplify=True)
                syms = boolrule.symbols
                args = len(syms)
                if args > 0:
                    testReplacements(syms, s,
                                     pregion['locations'][loc]['logic'])
Example #6
0
def main():
    # ct = time.clock()

    state = pickle.load(open("index.txt", "rb"))
    if state['encoding'] == 'varbyte':
        encoder = VarbyteEncoder()
    elif state['encoding'] == 'simple9':
        encoder = Simple9Encoder()
    else:
        raise Exception("Unsupported encoding!")

    encoder.set_state(state)
    # print("Time for loading: {}".format(1000 * (time.clock() - ct)))

    IdMerger.MAX_ID = len(encoder._urls)
    algebra = boolean.BooleanAlgebra()
    for query in sys.stdin:
        tree_query = algebra.parse(query.decode('utf-8'))

        result = get_doc_ids(encoder, tree_query)

        sys.stdout.write(query)
        sys.stdout.write(str(len(result.ids)))
        sys.stdout.write('\n')
        for url in encoder.get_urls(sorted(result.ids)):
            sys.stdout.write(url)
            sys.stdout.write('\n')
Example #7
0
 def __init__(self, domain, data, manager, **constants):
     self.domain = domain
     self.data = data
     self.manager = manager
     self.constants = self.__class__.default_constants.copy()
     self.constants.update(constants)
     self.ba = boolean.BooleanAlgebra()
     self._silenced = {}
     self.__fresh_id = -1
Example #8
0
    def filter_ruleset(self, metadata_filter=None):
        """Applies boolean filter against the ruleset and returns list of matching SIDs.

        :param metadata_filter: A string that defines the desired outcome based on
            Boolean logic, and uses the metadata key-value pairs as values in the
            Boolean algebra. Defaults to ``self.metadata_filter`` which must be set
            if this parameter is not set.
        :type metadata_filter: string, optional
        :returns: list of matching SIDs
        :rtype: list
        :raises: `AristotleException`
        """
        if not metadata_filter:
            metadata_filter = self.metadata_filter
        if metadata_filter is None:
            print_error("No metadata_filter set or passed to filter_ruleset()",
                        fatal=True)
        metadata_filter_original = metadata_filter
        # the boolean.py library uses tokenize which isn't designed to
        # handle multi-word tokens (and doesn't support quoting). So
        # just replace and map to single word. This way we can still
        # leverage boolean.py to do simplifying and building of the tree.
        mytokens = re.findall(r'\x22[a-zA-Z0-9_]+[^\x22]+\x22',
                              metadata_filter, re.DOTALL)
        if not mytokens or len(mytokens) == 0:
            # nothing to filter on so exit
            print_error("metadata_filter string contains no tokens",
                        fatal=True)
        for t in mytokens:
            # key-value pairs are case insensitive; make everything lower case
            tstrip = t.strip('"').lower()
            # also remove extra spaces before, after, and between key and value
            tstrip = ' '.join(
                [e.strip() for e in tstrip.strip().split(' ', 1)])
            print_debug(tstrip)
            if len(tstrip.split(' ')) == 1:
                # if just key provided (no value), match on all values
                tstrip = "{} <all>".format(tstrip)
            # if token begins with digit, the tokenizer doesn't like it
            hashstr = "D" + hashlib.md5(tstrip.encode()).hexdigest()
            # add to mapp dict
            self.metadata_map[hashstr] = tstrip
            # replace in filter str
            metadata_filter = metadata_filter.replace(t, hashstr)

        print_debug("{}".format(metadata_filter_original))
        print_debug("\t{}".format(metadata_filter))
        try:
            algebra = boolean.BooleanAlgebra()
            mytree = algebra.parse(metadata_filter).literalize().simplify()
            return self.evaluate(mytree)
        except Exception as e:
            print_error(
                "Problem processing metadata_filter string:\n\n{}\n\nError:\n{}"
                .format(metadata_filter_original, e),
                fatal=True)
Example #9
0
 def readBNet(self, filename):
     self.model = {}
     algebra = boolean.BooleanAlgebra()
     with open(filename, 'r') as f:
         lines = f.readlines()
         for line in lines:
             species, formula = [value.strip() for value in line.split(",")]
             if species != "target" and formula != "factors":
                 b_formula = algebra.parse(formula).simplify()
                 self.model.update({species: b_formula})
Example #10
0
def parseLogicBool(file_path):
    json_string = ""
    with io.open(file_path, 'r') as file:
        for line in file.readlines():
            json_string += line.split('#')[0].replace('\n', ' ')
    json_string = re.sub(' +', ' ', json_string)
    try:
        region_json = json.loads(json_string)
    except json.JSONDecodeError as error:
        raise Exception("JSON parse error around text:\n" + \
                        json_string[error.pos-35:error.pos+35] + "\n" + \
                        "                                   ^^\n")
    #print(region_json)
    alg = boolean.BooleanAlgebra()
    t, f, n, a, o, s = alg.definition()
    region_map = []
    for region in region_json:
        print(region['region_name'])
        pregion = region
        if ('locations' in region):
            for loc,rule in region['locations'].items():
                pregion['locations'][loc] = {'logic': rule, 'items':[], 'paths':[]}
                print("\t" + loc)
                rule = parseFunctions(rule)
                print("\t\t" + rule)
                boolrule = alg.parse(rule, simplify=True)
                syms = boolrule.symbols
                args = len(syms)
                if args > 0:
                    ttable = list(itertools.product([f, t], repeat=args))
                    total = len(ttable)
                    k = 0
                    for combo in ttable:
                        k = k + 1
                        print(str(k) + ' of ' + str(total), end='\r', flush=True)
                        tup = {}
                        evalrule = boolrule
                        for i,sym in enumerate(syms):
                            tup[sym] = combo[i]
                        r = evalrule.subs(tup, simplify=True)
                        if r:
                            pregion['locations'][loc]['items'].append(compressItems(syms, tup, s))
                            #print(pregion['locations'][loc]['items'])
                            #print(json.dumps(pregion['locations'][loc]))
                            #print(str(combo) + " " + str(r))
                else:
                    r = boolrule
                    st = "N/A"
                    if r:
                        pregion['locations'][loc]['items'].append(compressItems(syms, [True], s))
                        #print(json.dumps(pregion['locations'][loc]))
                        #print(st + " " + str(r))
        region_map.append(pregion)
    print(json.dumps(region_map))
    def parser(self):

        self.transform()

        algebra = boolean.BooleanAlgebra()
        try:
            res = algebra.parse(self.query)
        except SyntaxError:
            raise SyntaxError("Invalid syntax in query")
        self.query = str(res)
        self.convert_to_postfix()
        return self.query
    def get_region_index(self, region_name):
        region_name = utils.convert_region_name_to_logical_exp(region_name)
        if region_name == 'ξ':
            return self.num_regions - 1
        elif region_name in self.main_set_names:
            return  self.main_name_index_map[region_name]
        else:
            algebra = boolean.BooleanAlgebra()

            exp = str(algebra.parse(region_name).pretty())
            return utils.evaluate_logic_exp_tree(exp, self.num_sets, self.main_name_index_map, self.get_union_index,
                                                 self.get_intersection_index, self.get_complement_index)
Example #13
0
 def __init__(self, data=None, Symbol_class=boolean.Symbol, **kwargs):
     super(BooleanNetwork, self).__init__()
     self.ba = boolean.BooleanAlgebra(NOT_class=NOT,
                                      Symbol_class=Symbol_class)
     if data:
         if isinstance(data, str):
             self.import_data(data.split("\n"))
         elif isinstance(data, dict):
             for a, f in data.items():
                 self[a] = f
         else:
             self.import_data(data)
     for a, f in kwargs.items():
         self[a] = f
Example #14
0
def task_exp(tasks, task, n_goals, symbols):
    exp = '{0}&~{0}|'.format(symbols[0])
    for i in range(n_goals):
        if task[i]:
            for j in range(len(tasks)):
                if tasks[j][i]:
                    exp += symbols[j]
                else:
                    exp += '~' + symbols[j]
                exp += '&'
            exp = exp[:-1]
            exp += '|'
    exp = exp[:-1]
    algebra = boolean.BooleanAlgebra()
    exp = algebra.parse(exp)
    return exp
def q18(r):
    '''Rank inizin her hex digitini minterm olarak alıp, 4-giriş
    (ABCD), 1-çıkış (X) doğruluk tablosu çıkarınız.
    K-map ile en sade şeklini gerçekleştiriniz.
    SOP formunu SystemVerilog syntax ına uygun olarak giriniz.'''
    import boolean

    algebra = boolean.BooleanAlgebra()
    # minterm
    # read the rank as a hex digit list
    # bring the corresponding boolean expressions from the bools table
    # then create a SOP representation with | stiching
    r = list(format(r, '04x').lower())
    exp = ' | '.join(map(lambda x: bools[str(x)], r))
    # simplify and return the simplified expression
    e = algebra.parse(exp, simplify=True)
    return str(e)
Example #16
0
 def fill_region_elements(self, region_name, info):
     region_name = utils.convert_region_name_to_logical_exp(region_name)
     if region_name == 'ξ':
         if (self.data is not None
                 and self.data[len(self.data) - 1] is not None
                 and self.data[len(self.data) - 1].elements is not None):
             return self.data[len(self.data) - 1].elements
         else:
             print("ERROR")
     else:
         # if(region_name in info.main_set_names):
         #     if(self.data[info.get_main_name_index_map[region_name]].elements is not None):
         #         return self.data[info.get_main_name_index_map[region_name]].elements
         algebra = boolean.BooleanAlgebra()
         exp = str(algebra.parse(region_name).pretty())
         return utils.evaluate_logic_exp_tree(
             exp, info.get_num_sets(), info.get_main_name_index_map(),
             self.get_union, self.get_intersection, self.get_complement)
Example #17
0
    def __init__(self,
                 data=None,
                 Symbol_class=boolean.Symbol,
                 allowed_in_name=('.', '_', ':', '-'),
                 **kwargs):
        super().__init__()
        self.ba = boolean.BooleanAlgebra(NOT_class=NOT,
                                         Symbol_class=Symbol_class,
                                         allowed_in_token=allowed_in_name)
        if data:
            if isinstance(data, str):
                if "\n" in data or not os.path.exists(data):
                    self.import_data(data.splitlines())
                else:
                    with open(data) as fp:
                        self.import_data(fp)
            elif isinstance(data, dict):
                for a, f in data.items():
                    self[a] = f
            else:
                imported = False

                def biolqm_import(biolqm, lqm):
                    bnfile = new_output_file(self.biolqm_format)
                    assert biolqm.save(lqm, bnfile)
                    with open(bnfile) as fp:
                        self.import_data(fp)
                    return True

                if "biolqm" in sys.modules:
                    biolqm = sys.modules["biolqm"]
                    if biolqm.is_biolqm_object(data):
                        imported = biolqm_import(biolqm, data)
                if not imported and "ginsim" in sys.modules:
                    ginsim = sys.modules["ginsim"]
                    if ginsim.is_ginsim_object(data):
                        biolqm = import_colomoto_tool("biolqm")
                        imported = biolqm_import(biolqm,
                                                 ginsim.to_biolqm(data))
                if not imported:
                    self.import_data(data)
        for a, f in kwargs.items():
            self[a] = f
Example #18
0
def parsePrerequisites(prerequisites: str) -> str:
    courseNums = re.findall(r'[1-4]\d\d', prerequisites)
    department = re.findall(r'[A-Z]{4}', prerequisites)
    courses = {}
    # for i in range(len(courseNums)):
    #     courses[ascii_lowercase[i]] = str(department[i] + " " + courseNums[i])
    
    # print(courses)
    prereq = str(((re.search(r'\((.*)\)', prerequisites).group()).split(courseNums[-1], 1))[0] + str(courseNums[-1]) + ")")
    # for key in courses:
    #     prereq = prereq.replace(str(courses[key]), key)
    #     print(key)

    return prereq
    # return ((re.search(r'\((.*)\)', prerequisites).group()).split(courseNums[-1], 1))[0] + str(courseNums[-1]) + ")"
    
    # courses = re.search(r'\((.*)\)', prerequisites).group()
    algebra = boolean.BooleanAlgebra()
    return algebra.parse(prereq).simplify()
def q19(r):
    '''Rank inizin her hex digitini maxterm olarak alıp, 4-giriş
    (ABCD), 1-çıkış (X) doğruluk tablosu çıkarınız.
    K-map ile en sade şeklini gerçekleştiriniz.
    SOP formunu SystemVerilog syntax ına uygun olarak giriniz.'''
    import boolean

    algebra = boolean.BooleanAlgebra()
    # maxterm
    # read the rank as a hex digit list
    # since this is max term, exclude the ones in the rank
    # bring the rest of the boolean expressions from the bools table
    # then create a SOP representation with | stiching
    r = list(format(r, '04x').lower())
    rb = [format(i, '1x').lower() for i in range(16) if format(i, '1x').lower() not in r]
    exp = ' | '.join(map(lambda x: bools[str(x)], rb))
    # simplify and return the simplified expression
    e = algebra.parse(exp, simplify=True)
    return str(e)
Example #20
0
    class Query:
        class AND_SQL(boolean.AND):
            def __str__(self):
                return '(' + ' AND '.join(str(a) for a in self.args) + ')'

        class OR_SQL(boolean.OR):
            def __str__(self):
                return '(' + ' OR '.join(str(a) for a in self.args) + ')'

        class NOT_SQL(boolean.NOT):
            def __str__(self):
                return '(NOT {})'.format(self.args[0])

        class Symbol_SQL(boolean.Symbol):
            def __str__(self):
                return '(id IN "{}")'.format(self.obj)

        parser = boolean.BooleanAlgebra(AND_class=AND_SQL,
                                        OR_class=OR_SQL,
                                        NOT_class=NOT_SQL,
                                        Symbol_class=Symbol_SQL)

        def parse(self, query_str):
            try:
                self.expr = Items.Query.parser.parse(query_str)
                tags = [s.obj for s in self.expr.symbols]
                self.tags = Tag.select().where(Tag.name << tags)
                return len(self.tags) == len(tags)
            except boolean.ParseError:
                return False

        def execute(self):
            if self.expr is None:
                return None

            ctes = [(TagItemJoin.select(TagItemJoin.item_id).where(
                TagItemJoin.tag_id == tag.id).cte(tag.name))
                    for tag in self.tags]

            return list(Item.select().with_cte(*ctes).where(
                peewee.SQL(str(self.expr))))
Example #21
0
def run_search(dict_file, postings_file, queries_file, results_file):
    """
    using the given dictionary file and postings file,
    perform searching on the given queries file and output the results to a file
    """
    print('running search on the queries...')

    with open(dict_file, mode="rb") as dictionary_file,\
            open(postings_file, mode="rb") as posting_file,\
            open(queries_file, encoding="utf8") as q_in,\
            open(results_file, mode="w", encoding="utf8") as q_out:
        ''' load dictionary and postings '''
        # dict(k,v) -> token, Entry(frequency, offset, size)
        # postings -> the dict containing the entries and metadata of the postings file
        # skiplist -> list of all doc IDs
        dictionary = pickle.load(dictionary_file)
        postings = Posting(dictionary, posting_file)
        file_list = postings['__all__']
        ''' process query, and write the query result to result file '''
        for query in q_in:
            query = preprocess_query(query)
            algebra = boolean.BooleanAlgebra()
            # Simplify query, e.g. tautology
            expression = algebra.parse(query, simplify=True)
            # special cases after simplification
            if str(expression) == "0":
                print("", end='\n', file=q_out)
                continue
            elif str(expression) == "1":
                print(" ".join(map(str, file_list)), end='\n', file=q_out)
                continue

            print(" ".join(
                map(
                    str,
                    shunting(get_input(str(expression))).eval(
                        postings, file_list).list)),
                  end='\n',
                  file=q_out)
Example #22
0
def parser(string, queryset):
    """
    Parses the lexicated list and applies the appropriate django
    filters. Returns a queryset.
    """
    QueryObjects.D = {}
    QueryObjects.B = []
    QueryObjects.IND = 0
    QueryObjects.TEMP_FIELD = None

    algebra = boolean.BooleanAlgebra()
    query_list = lexer(string)
    query_string = ' '.join(query_list)
    qs = algebra.parse(query_string)

    if QueryObjects.TEMP_FIELD:
        queryset = queryset.annotate(**QueryObjects.TEMP_FIELD)
        QueryObjects.TEMP_FIELD = None

    locals().update(QueryObjects.D.items())
    query = str(qs)
    query = eval(query)
    queryset = queryset.filter(query)
    return queryset
Example #23
0
    elif isinstance(tree, boolean.AND):
        first = get_doc_ids(encoder, tree.args[0])
        for a in tree.args[1:]:
            first = first.andd(get_doc_ids(encoder, a))
        return first
    elif isinstance(tree, boolean.OR):
        first = get_doc_ids(encoder, tree.args[0])
        for a in tree.args[1:]:
            first = first.orr(get_doc_ids(encoder, a))
        return first
    else:
        raise Exception(u"Unexpected operator!")


if __name__ == '__main__':
    index = pickle.load(open("index_20.p", "rb"))
    allIdx = merger(xrange(len(index['urls'])))
    encoding = index['encoding']
    for query in sys.stdin:
        algebra = boolean.BooleanAlgebra()
        tree_query = algebra.parse(query.decode('utf-8'))
        result = get_doc_ids(encoding, tree_query)
        rl = list(result.ids)
        print query[:-1]
        if len(rl) > 0:
            print len(rl)
            for d in sorted(rl):
                print index['urls'][d]
        else:
            print 0
Example #24
0
    def normalize(self, where):
        booleans = ['NOT', 'OR', 'AND']
        bool_ops = ['~', '|', '&']
        parenthesis = ['(', ')']
        expressions = []
        temp = ""

        # Extract expressions
        for token in where.flatten():

            tok = str(token)
            if (tok == " " or tok == ";" or tok.upper() == "WHERE"):
                continue
            if ((tok not in booleans) and (tok not in parenthesis)):
                temp += tok
            else:
                if (temp not in expressions and temp != ""
                        and temp.upper() != "WHERE"):
                    expressions.append(temp)
                temp = ""
        if (temp not in expressions and temp != ""
                and temp.upper() != "WHERE"):
            expressions.append(temp)
        temp = ""
        print("expr ", expressions)
        #Convert statement to boolean statement with expression variables
        bool_expr = ""
        vari = "x_"
        for token in where.flatten():
            tok = str(token)
            if (tok == " " or tok == ";" or tok.upper() == "WHERE"):
                continue
            if ((tok not in booleans) and (tok not in parenthesis)):
                temp += tok
            else:
                if (temp != "" and temp.upper() != 'WHERE'):
                    indi = expressions.index(temp)
                    bool_expr += vari + str(indi)
                    self.expr_dict[bool_expr] = expressions[indi]
                if (tok in booleans):
                    tok = bool_ops[booleans.index(tok)]
                bool_expr += tok
                temp = ""
        if (temp != "" and temp.upper() != 'WHERE'):
            bool_expr += vari + str(expressions.index(temp))
        print("boolexpr ", bool_expr)
        #Evaluate boolean expression
        algebra = boolean.BooleanAlgebra()
        normalized = str(
            algebra.normalize(algebra.parse(bool_expr), algebra.AND))
        temp = ""
        fin_string = ""
        for charac in normalized:
            tok = charac
            if (tok == " " or tok == ";" or tok.upper() == "WHERE"):
                continue
            if ((tok not in bool_ops) and (tok not in parenthesis)):
                temp += tok
            else:
                if (temp != "" and temp.upper() != 'WHERE'):
                    fin_string += expressions[int(temp.split("_")[-1])]
                if (tok in bool_ops):
                    tok = booleans[bool_ops.index(tok)]
                fin_string += " " + tok + " "
                temp = ""
        if (temp != "" and temp.upper() != 'WHERE'):
            fin_string += expressions[int(temp.split("_")[-1])]
        print("normal ", normalized)
        return normalized, expressions
def term_parse(term_string):
    term_string = term_string.replace("||","OR")
    term_string = term_string.replace("&&","AND")
    algebra = boolean.BooleanAlgebra()
    return algebra.parse(term_string)
Example #26
0
"""

from datetime import datetime, time
from typing import NamedTuple, List, Dict, Optional, Union, Tuple, Iterator
import dataclasses
from dataclasses import dataclass
import matplotlib.pyplot as plt  # type:ignore
from enum import Enum, IntEnum
import boolean
import networkx as nx
import yaml
import random

VERSION_TAG = "0.1.0"

ALGEBRA = boolean.BooleanAlgebra()

# Type alias for identifiers
NodeID = str

# A unique identifier
ID = str

# a (login,password/token) credential pair is abstracted as just a unique
# string identifier
CredentialID = str

# Intrinsic value of a reaching a given node in [0,100]
NodeValue = int

PortName = str
Example #27
0
def str_to_formule(formule_in_string):
    algebra = boolean.BooleanAlgebra()
    return algebra.parse(formule_in_string)
def boolean_compare(r, e):
    '''compare two boolean strings. First check if they are the same boolean expressions
    if not, boolean module does not provide an equality check. so just generate 16 different
    true false inputs, and feed into both equations to see if they produce the same results'''
    import boolean
    algebra = boolean.BooleanAlgebra()

    try:
        r = algebra.parse(r)
    except:
        # some other character is in use
        # auto fail
        return 0, 17

    e = algebra.parse(e)

    # lets try our luck
    if r == e:
        return 1, 0

    # damn
    a, b, c, d = algebra.symbols('a','b','c','d')
    t = algebra.TRUE
    f = algebra.FALSE
    hacks = {
        '0'  : [f, f, f, f],
        '1'  : [f, f, f, t],
        '2'  : [f, f, t, f],
        '3'  : [f, f, t, t],
        '4'  : [f, t, f, f],
        '5'  : [f, t, f, t],
        '6'  : [f, t, t, f],
        '7'  : [f, t, t, t],
        '8'  : [t, f, f, f],
        '9'  : [t, f, f, t],
        '10' : [t, f, t, f],
        '11' : [t, f, t, t],
        '12' : [t, t, f, f],
        '13' : [t, t, f, t],
        '14' : [t, t, t, f],
        '15' : [t, t, t, t]
    }
    # replace all the terms with true or false, then simplify them
    # simplification should return 0 or 1
    # do that for all input combinations, and count the number of mismatches
    err = 0
    for i in range(16):
        rres = r.subs({a:hacks[str(i)][0],
                       b:hacks[str(i)][1],
                       c:hacks[str(i)][2],
                       d:hacks[str(i)][3]}).simplify()

        eres = e.subs({a:hacks[str(i)][0],
                       b:hacks[str(i)][1],
                       c:hacks[str(i)][2],
                       d:hacks[str(i)][3]}).simplify()

        if eres != rres:
            err += 1

    if err == 0:
        return 1, err
    else:
        return 0, err
Example #29
0
def split_peering(peering):
    asn_list = set()

    if re.fullmatch(RE_ASN, peering, flags=re.IGNORECASE):
        return peering
    elif re.fullmatch(RE_ASSET, peering, flags=re.IGNORECASE):
        return uncover_asset(peering)

    asn_logic = re.sub(r"([\s(])EXCEPT([\s)])",
                       r"\1AND NOT\2",
                       peering,
                       flags=re.IGNORECASE)

    asset_list = set(
        map(lambda findall_list: findall_list[0],
            re.findall(RE_ASSET, peering, re.IGNORECASE)))

    if 0 < len(asset_list):

        def replace_asset(_asn_logic, _asset_name):

            if _asn_logic is None:
                return None

            asset_asn_list = uncover_asset(_asset_name)

            if asset_asn_list is None:
                return None
            if 0 < len(asset_asn_list):
                asset_members = "(" + " OR ".join(asset_asn_list) + ")"
                return re.sub(_asset_name + r"([\s)]|$)",
                              asset_members + r"\1",
                              _asn_logic,
                              count=1,
                              flags=re.IGNORECASE)

            return _asn_logic

        asn_logic = str(reduce(replace_asset, asset_list, asn_logic))

        if asn_logic is None:
            return None

    asn_expr = boolean.BooleanAlgebra()

    try:
        asnexpr_parsed = asn_expr.parse(asn_logic)
        asnexpr_list = asn_expr.dnf(asnexpr_parsed)

        def reduce_asnexpr(_asn_list, _expr):
            peer_asn_list = set()
            present_asn_expr = set(
                filter(lambda literal: type(literal) is not asn_expr.NOT,
                       _expr.literals))
            present_asn = set(map(lambda asn: str(asn), present_asn_expr))
            if 0 < len(present_asn):
                if RE_ASSET_ANY in present_asn:
                    return RE_ASSET_ANY

                peer_asn_list = set(
                    filter(lambda asn: re.match(RE_ASN, asn, re.IGNORECASE),
                           present_asn))
            return _asn_list.union(peer_asn_list)

        if type(asnexpr_list) is asn_expr.OR:
            asn_list = reduce(reduce_asnexpr, asnexpr_list.args, asn_list)
        elif asnexpr_list == asn_expr.FALSE:
            asn_list.clear()
        elif asnexpr_list == asn_expr.TRUE:
            asn_list = {RE_ASSET_ANY}
        else:
            asn_list = reduce_asnexpr(asn_list, asnexpr_list)

    except boolean.ParseError:
        asn_list.clear()

    return asn_list
Example #30
0
            return False
        return True


class Symbol(boolean.Symbol):

    def __bool__(self, tags_for_check=None):
        if self.obj in tags_for_check:
            return True
        return False


class FALSE(boolean.boolean._FALSE):

    def __bool__(self, tags_for_check=None):
        if not tags_for_check:
            return True
        return False


class TRUE(boolean.boolean._TRUE):

    def __bool__(self, tags_for_check=None):
        if tags_for_check:
            return True
        return False


algebra = boolean.BooleanAlgebra(AND_class=AND, OR_class=OR, NOT_class=NOT, Symbol_class=Symbol,
                                 FALSE_class=FALSE, TRUE_class=TRUE)