Example #1
0
def evaluate():
    # TODO: cache expression / tables objects based on query params

    try:
        expr = request.args.get('expr')
        action = request.args.get('action')
        context = {}

        if expr is None or action is None:
            raise ValueError('Missing required params')

        expr = expr.strip()
        context['expr'] = expr
        b = BooleanExpression(expr)

        if action == 'table':
            t = TruthTable(b)
            context['is_table'] = True
            context['table'] = t
        elif action == 'satone':
            context['is_sat'] = True
            context['symbols'] = b.symbols

            sat_sol = b.sat_one()
            context['sat_iter'] = [sat_sol] if sat_sol else []
        elif action == 'satall':
            context['is_sat'] = True
            context['symbols'] = b.symbols
            context['sat_iter'] = list(b.sat_all())
        else:
            raise ValueError('Invalid option')
    except ValueError:
        context['is_error'] = True
        context['error_content'] = [
            'Please don\'t go out of your way to break this '
            'already-fragile system'
        ]
    except EmptyExpressionError:
        context['is_error'] = True
        context['error_content'] = ['You gave us an invalid expression!']
    except NoEvaluationVariationError:
        context['is_error'] = True
        context['error_content'] = [
            'You should be able to figure that out on your own'
        ]
    except GrammarError as e:
        context['is_error'] = True
        context['error_content'] = [e.message]
        if e.error_pos is not None:
            underlined_error_expr = ''
            for i, char in enumerate(expr):
                underlined_error_expr += (char if i != e.error_pos else
                                          '<u>{}</u>'.format(char))
            context['underlined_error_expr'] = underlined_error_expr
    except Exception as e:
        context['is_error'] = True
        context['error_content'] = ['An unexpected error occured :(']
        raise e

    return render_template('result.html', **context)
def diag_fail_circuit(logic_exp, table_fails):

    newtime = time.time()
    outputs = []
    for line in logic_exp:

        data = line.split('=')
        outputs.append(data[0])
        data.pop(0)

        expr = data[0].replace('p0', 'Z')
        expr = expr.replace('p1', 'Z')
        newexpr = BooleanExpression(expr)

        with open('diag53.txt', 'w') as myfile:
            myfile.write("Circuit Analysis: {} \n\n".format(outputs[0] + '=' +
                                                            data[0]))
            for s in newexpr.symbols:
                ocrr = find_occurrences(expr, s)
                for o in ocrr:
                    templist = list(''.join(expr))
                    templist[o] = '1'
                    finalExpr = ''.join(templist)
                    tempTruth = TruthTable(finalExpr)

                    if (len(table_fails.results) == (len(tempTruth.results))):
                        if table_fails.equivalent_to(tempTruth):
                            finalExpr = finalExpr.replace('Z', 'XX')
                            finalExpr = finalExpr.replace('1', 'PortaPresaEm1')
                            myfile.write(
                                "-> Possible fail: {}\n".format(finalExpr))

                    print("Expr: {}\n {} \n Fail: {}\n".format(
                        finalExpr, tempTruth, table_fails))

                    templist = list(''.join(expr))
                    templist[o] = '0'
                    finalExpr = ''.join(templist)
                    tempTruth = TruthTable(finalExpr)

                    if (len(table_fails.results) == (len(tempTruth.results))):
                        if table_fails.equivalent_to(tempTruth):
                            finalExpr = finalExpr.replace('Z', 'XX')
                            finalExpr = finalExpr.replace('0', 'PortaPresaEm0')
                            myfile.write(
                                "-> Possible fail: {}\n".format(finalExpr))

                    print("Expr: {}\n {} \n Fail: {}\n".format(
                        finalExpr, tempTruth, table_fails))

            myfile.write("\n\nTime elapsed: {} secs.".format(time.time() -
                                                             newtime))
            myfile.close()
Example #3
0
def __check(regulation, cobra_model, shadow_price):
    try:
        exp = BooleanExpression(regulation.rule)
    except Exception:
        return True
    tokens = exp.symbols
    value = []
    for i in tokens:
        if i.find('less_than') != -1:
            try:
                SP = shadow_price[i[0:i.find('less_than')] + '_c']
            except KeyError:
                value.append(False)
                continue
            if SP < 0:
                value.append(True)
            else:
                value.append(False)
        elif i.find('more_than') != -1:
            try:
                SP = shadow_price[i[0:i.find('more_than')] + '_c']
            except KeyError:
                value.append(False)
                continue
            if SP > 0:
                value.append(True)
            else:
                value.append(False)
        else:

            if __check_gene(cobra_model, i):
                value.append(True)
            else:
                value.append(False)
    truth = exp.evaluate(**dict(zip(tokens, value)))
    return truth
Example #4
0
def transformation_query_to_postfixe(booleanOperators, query):
    # query can contain keywords that do not pass ttable's is_valid_identifier function:
    # https://github.com/welchbj/tt/blob/43beecac6fae9ac7e2035b66b6e790cfc25167ba/tt/definitions/operands.py#L33-L90
    # we still want to be able to handle queries containing forbidden keywords like "class"
    # so we make the identifiers abstract
    abstract_query = []
    matcher = {}
    for token in query:
        if token in booleanOperators:
            matcher[token] = token
            abstract_query.append(token)
        else:
            abstract_token = f"var{len(abstract_query)}"
            abstract_query.append(abstract_token)
            matcher[abstract_token] = token
    postfix_abstract = BooleanExpression(
        ' '.join(abstract_query)).postfix_tokens
    return [matcher[key] for key in postfix_abstract]
Example #5
0
def getInput():
    # Get boolean expression string
    be = str(input("Enter a boolean expression: "))

    # Check if the string contains something other than alphabets
    tempBoolExpr = be.split()
    for item in tempBoolExpr:
        if not item.isalpha():
            print("Error: Expression has an unknown operator")
            exit(0)

    # Check if the string is a valid Boolean Expression
    try:
        expr = to_primitives(BooleanExpression(be))
    except:
        print("Error: Not a valid boolean expression")
        exit(0)

    return expr
Example #6
0
def build_expression(expression, mapping):
    """Build a nested dict encoding of a boolean expression

    Arguments:
        expression: boolean expression with whitespace, parens, symbols and operators
            example: a and b or c
        mapping: should resolve all symbols in expression
            example: {"a": 1, "b": 2, "c": 3}
    Returns:
        example:
            {"or": [3, {"and": [1, 2]}]}
    """
    expression = BooleanExpression(expression)
    symbols = expression.symbols
    undefined = set(symbols) - mapping.keys()
    if undefined:
        undefined = ', '.join(undefined)
        raise ExpressionValidationError(
            f'Undefined values in expression: {undefined}'
        )
    return _build_expression(expression, mapping)
Example #7
0
 def _transform_bool_query_to_postfix(self) -> List:
     """
     Transform boolean expression into postfix token list
     :return:
     """
     return BooleanExpression(self.query.lower()).postfix_tokens
Example #8
0
 def _transform_query_to_boolean(self) -> List:
     """
     Transform natural language into postfix token list
     :return:
     """
     return BooleanExpression(self.query.lower().replace(' ', ' and ')).postfix_tokens
Example #9
0
def entail(knowledge_base, truth_table, statement):
    kb = BooleanExpression(knowledge_base)
    t = cleanNullTerms(truth_table)

    combinations = []
    with kb.constrain(**t):
        for c in kb.sat_all():
            combinations.append(c)
    # print(len(combinations))

    kb_true = '{} and {}'.format(knowledge_base, statement)
    kb_true = BooleanExpression(kb_true)

    combinations_true = []
    with kb_true.constrain(**t):
        for c in kb_true.sat_all():
            combinations_true.append(c)

    # print('True')
    # print(len(combinations_true))
    # for c in combinations_true:
    #     print(c)

    kb_false = '{} and (not {})'.format(knowledge_base, statement)
    kb_false = BooleanExpression(kb_false)

    combinations_false = []
    with kb_false.constrain(**t):
        for c in kb_false.sat_all():
            combinations_false.append(c)

    # print('False')
    # print(len(combinations_false))
    # for c in combinations_false:
    #     print(c)

    if len(combinations_true) == len(combinations) and len(
            combinations_false) == len(combinations):
        print('BTF')
        return 'BTF'
    elif len(combinations_true) == len(
            combinations) and len(combinations_false) != len(combinations):
        print('DT')
        return 'DT'
    elif len(combinations_true) != len(combinations) and len(
            combinations_false) == len(combinations):
        print('DF')
        return 'DF'
    else:
        print('PTF')
        return 'PTF'
Example #10
0
def transformation_query_to_postfixe(query):
    b = BooleanExpression(query)
    return b.postfix_tokens
    with open("input53.txt", 'r') as myfile:
        data = myfile.read().strip()
        myfile.close()
    data = data.split('\n')
    originalData = data.copy()

    new_data, table = translate_circuit(data)
    """ S=(var <op> var) -> [S][var <op> var] """
    for line in range(len(new_data)):
        new_data[line] = new_data[line].split('=')
        outputs.append(new_data[line][0])
        new_data[line].pop(0)
    """ evaluate boolean expression and store in vec """
    for line in range(len(new_data)):
        inputs.append(BooleanExpression(new_data[line][0]).symbols)
        results.append(TruthTable(str(new_data[line][0])).results)

    for i in range(len(results)):

        # generate 0 1 matrix to assign to variables
        out = np.matrix(list(itertools.product([0, 1], repeat=len(inputs[i]))),
                        dtype='int')

        _matrix = np.array(np.column_stack((out, results[i])))
        matrix.append(_matrix)

        p = PrettyTable()
        p.field_names = np.hstack((inputs[i], outputs[i]))

        for line in _matrix:
Example #12
0
try:
    sys.stdout = open('Boolean Model\\output.txt', 'w')
except:
    sys.stdout = open('output.txt', 'w')

query_terms = {
    "ka": "information",
    "kb": "retrieval",
    "kc": "science",
    "kd": "data"
}
print("query terms:", query_terms)

query = query_terms["ka"] and (query_terms["kb"] or query_terms["kc"]
                               or not query_terms["kd"])
b = BooleanExpression('ka and (kb or kc or not kd)')
print("query:", b.raw_expr, "\n")
t = TruthTable(b)
# t = TruthTable("ka and (kb or not kc)")
eq = t.equivalent_to(t)
print(t)

dnf = ""
cq = ""
print("DNF:")
for line in t:
    if line[1]:
        dnf += "("
        cq += "("
        for counter in range(len(b.symbols)):
            if line[0][counter] == 1: