Beispiel #1
0
def blockToStr(block, string):
    if not (Expression.IsBlock(block)
            ) and not type(block) == Expression.Expression:
        return string + str(block)
    if type(block) == Expression.PowerBlock:
        pars = type(
            block.expressions[1]
        ) == Expression.ExpressionBlock  #Expression.IsBlock(block.expressions[1]) # wenn der nenner ein block ist, klammern setzen
        if pars:
            return blockToStr(block.expressions[0],
                              string) + "^(" + blockToStr(
                                  block.expressions[1], "") + ")"
        else:
            return blockToStr(block.expressions[0], string) + "^" + blockToStr(
                block.expressions[1], "")
    elif type(block) == Expression.QuotientBlock:
        pars = type(
            block.expressions[1]
        ) == Expression.ExpressionBlock  #Expression.IsBlock(block.expressions[1]) # wenn der nenner ein block ist, klammern setzen
        if pars:
            return blockToStr(block.expressions[0],
                              string) + "/(" + blockToStr(
                                  block.expressions[1], "") + ")"
        else:
            return blockToStr(block.expressions[0], string) + "/" + blockToStr(
                block.expressions[1], "")
    for el in block.expressions:
        if Expression.IsBlock(el):
            string += "("
            string = blockToStr(el, string)
            string += ")"
        else:
            string += str(el)
    return string
Beispiel #2
0
def PackFunctions(expression):
    '''
        Wandelt Teile der Art <FunctionElement> <ExpressionBlock> in einen FunctionBlock um
    '''
    new_expressions = []
    i = 0
    while i < len(expression.expressions):
        #for el in expression.expressions:
        el = expression.expressions[i]
        #if type(el) == Expression.ExpressionBlock:
        if Expression.IsBlock(el):
            block = (type(el))()
            block.expressions = PackFunctions(el)
            new_expressions.append(block)
        elif type(el) == Expression.FunctionElement:
            new_block = Expression.FunctionBlock()
            new_block.append(el)
            if (i == len(expression.expressions) - 1):
                raise Exception("KEIN FUNC ARGUMENT")
            new_block.append(expression.expressions[i + 1])
            new_expressions.append(new_block)
            i += 1
        else:
            new_expressions.append(el)
        i += 1
    return new_expressions
Beispiel #3
0
    def primary(self):
        if self.curr_token_is([TokenType.OPEN_PAREN]):
            self.pop_token()
            paren_expr = self.expression()
            self.pop_token_expect([TokenType.CLOSE_PAREN],
                                  'PARSER ERROR: Expecting right parenthesis')
            return Expression.Grouping(paren_expr)

        primary_tokens = [
            TokenType.NUMBER, TokenType.STRING, TokenType.FALSE,
            TokenType.TRUE, TokenType.NIL, TokenType.IDENTIFIER
        ]
        curr_token = self.pop_token()
        if curr_token.token_type not in primary_tokens:
            error_msg = 'PARSER ERROR: Expecting one of: {0}, but got {1}'.format(
                primary_tokens, curr_token.token_type)
            self.lox_instance.raise_error_with_token(curr_token, error_msg)
            raise ParseError()

        if curr_token.token_type == TokenType.IDENTIFIER:
            return Expression.Variable(curr_token)

        primary_token_map = {
            TokenType.NUMBER: curr_token.literal,
            TokenType.STRING: curr_token.literal,
            TokenType.FALSE: False,
            TokenType.TRUE: True,
            TokenType.NIL: None
        }
        return Expression.Literal(primary_token_map[curr_token.token_type])
Beispiel #4
0
def CreateExpression(predictions):
    E = Expression()
    last = None
    for prediction in predictions:
        label = prediction[0]
        e = None
        if ord(label) >= 48 and ord(label) <= 57:
            if type(last) is Constant:
                last.addVal(label)
                e = last
                continue
            else:
                e = Constant(label)
        elif ord(label) == 42 or ord(label) == 120:
            e = Multiplication()
        elif ord(label) == 43 or ord(label) == 116:
            e = Addition()
        elif ord(label) == 45:
            e = Subtraction()
        elif ord(label) == 47:
            e = Division()
        elif (ord(label) >= 65
              and ord(label) <= 90) or (ord(label) >= 97
                                        and ord(label) <= 122):
            e = Variable(label)
        else:
            print("Unrecognized input")
        last = e
        E.addSubExpr(e)
    return E
def parse_simple_primitive_with_sets(spec):
    if isinstance(spec, float) or isinstance(spec, int):
        func = Primitives.create_value_func(spec)
        return Expression(spec, func, is_constant=True)

    if isinstance(spec, str):
        func = Primitives.create_value_func(SetPlaceholder(spec))
        return Expression(spec, func)
Beispiel #6
0
def analyseSelect(text, expression, count, flag, c):
    """
    Analyse une opération de Sélection entrée au clavier.
    Syntaxe attendue : 
        -exemple1 : Select(attr1,Cst(value),Rel(name))
        -exemple2 : Select(attr1,attr2,Rel(name))
        Note : Pas d'espace, pas de guillemets, 'Cst' est un mot réservé.
               Une Cst peut être soit un chaîne de caractère, soit un nombre
               Le dernier paramètre peut être autre chose qu'une relation (Ex : une autre expression)
    """
    flag.append(False)
    param1 = None
    attr = None
    param2 = None
    currentExpression = o.Selection(param1, param2, attr, c)
    #On analyse le param1 (L'attribut que l'on sélectionne)
    count += 1
    attr, j = analyseAttr(text,count)
    count = j
    currentExpression.param1 = e.Attribut(attr)
    #On analyse attr (Le deuxième élément de l'égalité)
    count += 1
    if(text[count : count +3] == "Cst"):
        #On égalise avec une constante
        count += 4
        vCst= ""
        while(text[count] != ")") :
            vCst += text[count]
            count += 1
        #On détermine le type de la constante
        if (vCst.isalpha() == False):
            vCst = float(vCst)
        currentExpression.attr = e.Cst(vCst)
        count += 1
    else:
        #On égalise avec un attribut
        attr, j = analyseAttr(text,count)
        count = j
        currentExpression.attr = e.Attribut(attr)
    #On analyse param2 (La relation ou l'expression sur laquelle on applique cette sélection)
    count += 1
    if(text[count:count+3] == "Rel"):
        #C'est une relation, l'expression est donc complète
        flag[-1] = True
        currentExpression.param2=(e.Relation(analyseRel(text, count), c))
    else:
        flag[-1] = False

    if (expression != None):
        #Ce n'est pas la première opération de l'expression : On ajoute l'opération à l'expression existante
        expression.addExpr(currentExpression)
        return expression, flag, count
    else:
        #C'est la première opération de l'expression 
        expression = currentExpression
        return expression, flag, count
def parse_simple_primitive(spec):
    if isinstance(spec, float) or isinstance(spec, int):
        func = Primitives.create_value_func(spec)
        return Expression(spec, func, is_constant=True)

    if isinstance(spec, str):
        func = Primitives.cardinality_functions[spec]
        return Expression(spec, func)

    raise ValueError('Unsupported input type {0}'.format(type(spec)))
Beispiel #8
0
def analyseJUD(text, expression, count, flag, OP, c):
    """
    Analyse une opération de jointure entrée au clavier.
    Le paramètre OP spécifie le type de l'Opération à créer:
        1) OP = "J" => Join
        2) OP = "U" => Union
        ") OP = "D" => Diff 
    Syntaxe attendue : 
        -exemple1 : Join(Rel(name);Rel(name))
        -exemple2 : Join(*expr1*;*expre2*)
        -exemple3 : Union(*expr1*;*expre2*)
        -exemple4 : Diff(*expr1*;*expre2*)
        Note : expr1 et expr2 sont des expressions SPJRUD entrée au clavier en respectant la syntaxe.
    """
    flag.append(False)
    param1 = None
    param2 = None
    if(OP == "J"):
        currentExpression = o.Join(param1,param2, c)
    elif (OP == "U"):
        currentExpression = o.Union(param1,param2, c)
    elif (OP == "D"):
        currentExpression = o.Diff(param1,param2, c)
    #On analyse le param1
    count += 1
    if(text[count:count+3] == "Rel"):
        currentExpression.param1=(e.Relation(analyseRel(text, count), c))
        while(text[count] != ";"):
            count += 1
    else:
        tempExpr = None
        tempf = []
        #On effectue une seconde récursion pour déterminer le premier paramètre
        l = analyseLen(text, count)
        tempExpr = analyseInput(text, tempExpr, count, tempf, c)
        currentExpression.param1 = tempExpr
        #On calcule l'indice de début du param2
        count += l
    #On analyse le param2
    count += 1
    if(text[count:count+3] == "Rel"):
        flag[-1] = True
        currentExpression.param2=(e.Relation(analyseRel(text, count), c))
    else:
        flag[-1] = False
    
    if (expression != None):
        #Ce n'est pas la première opération de l'expression : On ajoute l'opération à l'expression existante
        expression.addExpr(currentExpression)
        return expression, flag, count
    else:
        #C'est la première opération de l'expression 
        expression = currentExpression
        return expression, flag, count
Beispiel #9
0
def example_protocol():
    sf = StartField.StartField(
        'myProtocol',
        'This is an example protocol that says the second byte is the amount of wins I have if the first bit in the first byte is bigger than 8, otherwise it is the number of losses'
    )

    sf.set_dependency_pattern('Integer')
    sf.set_dependency_protocol('Dependent protocol')

    f1 = Field.Field(1)

    sf.set_next_constructs([f1])

    f1.set_field_info('TypeBitCheck', 'check', 'Checks first bit',
                      'ftypes.UINT8', 'base.HEX', '0x80', '?', 'True')

    ref_list = ReferenceList.ReferenceList('ref_list')
    ref_list.set_descriptions(['is a value'])
    ref_list.set_values(['13'])

    f1.set_ref_list(ref_list)

    expr1 = Expression.Expression()
    expr1.set_relational_operators(['>='])
    expr1.set_operands(['8'])

    expr2 = Expression.Expression()
    expr2.set_relational_operators(['<'])
    expr2.set_operands(['8'])

    dc = DecisionConstruct.DecisionConstruct()
    dc.set_expressions([expr1, expr2])
    f1.set_next_constructs([dc])

    f2 = Field.Field(1)
    f2.set_field_info('Number of wins', 'wins', 'Is the number of wins',
                      'ftypes.UINT8', 'base.HEX', '0xff', '?', 'True')

    f3 = Field.Field(1)
    f3.set_field_info('Number of loses', 'loses', 'Is the number of loses',
                      'ftypes.UINT8', 'base.HEX', '0xff', '?', 'True')

    dc.set_next_constructs([f2, f3])
    end_field = EndField.EndField()

    f2.set_next_constructs([end_field])
    f3.set_next_constructs([end_field])

    protocol = Protocol.Protocol()
    protocol_structure = protocol.get_protocol_structure(sf)
    return protocol_structure
Beispiel #10
0
    def __init__(self, aRandomGenerator, labelpointsx, labelpointsy, picId, graphicsfolder, graphExpr, xfrom, xto,
                 xstep, yfrom, yto, xlabel, ylabel, title, scale=50):
        IQPicture.__init__(self, aRandomGenerator, labelpointsx, labelpointsy, graphicsfolder, picId)

        self.xFrom = Expression.EvalExpression(xfrom, True, aRandomGenerator).Evaluate()
        self.xTo = Expression.EvalExpression(xto, True, aRandomGenerator).Evaluate()
        # if the user has specified the domain in the wrong way, switch it round (e.g. a domain from 1->-3 will be changed to -3 -> 1
        if self.xFrom > self.xTo:
            tmp = self.xFrom
            self.xFrom = self.xTo
            self.xTo = tmp

        self.yFrom = Expression.EvalExpression(yfrom, True, aRandomGenerator).Evaluate()
        self.yTo = Expression.EvalExpression(yto, True, aRandomGenerator).Evaluate()

        # if the user has specified the domain in the wrong way, switch it round (e.g. a domain from 1->-3 will be changed to -3 -> 1
        if self.yFrom > self.yTo:
            tmp = self.yFrom
            self.yFrom = self.yTo
            self.yTo = tmp

        self.xStep = float(xstep)
        self.scale = float(scale) / 100

        if xlabel <> '':
            self.xLabel = '$' + Expression.EvalExpression(xlabel, True, aRandomGenerator).GetLateXMathExpression(None) + '$'
        else:
            self.xLabel = ''

        if ylabel <> '':
            self.yLabel = '$' + Expression.EvalExpression(ylabel, True, aRandomGenerator).GetLateXMathExpression(None) + '$'
        else:
            self.yLabel = ''

        self.Titles = title.split(',')
        for i in range(0, len(self.Titles)):
            self.Titles[i] = Expression.EvalExpression(self.Titles[i], True, aRandomGenerator).ExpressionStringEval
            self.Titles[i] = '$' + Expression.EvalExpression(self.Titles[i], True,
                                                             aRandomGenerator).GetLateXMathExpression(None) + '$'
            # create the maths expressions
        mathExpressions = graphExpr.split(',')

        for i in range(0, len(mathExpressions)):
            mthExpression = Expression.EvalExpression(mathExpressions[i], True, aRandomGenerator)
            mthExpression = Expression.EvalExpression(mthExpression.ExpressionStringEval, True, aRandomGenerator)
            self.mthExpressions.append(mthExpression)
            # self.graphExpr = mthExpression.ExpressionStringEval
            # self.graphExpr = self.graphExpr.replace('^','**')
        self.GenerateFile('.\\', '')

        self.latexCode = '\\includegraphics[scale=' + str(self.scale) + ']{gfx/' + self.filename + '}'
Beispiel #11
0
def convert_groupref(group_names, name, id):
    assert type(id) != type(0), \
           "Martel cannot use numbered group reference: %d" % id
    # msre_parse returns the list from the GroupNames
    # Map that back to a number.
    pattern_name = group_names.reverse_name(id[0])
    return Expression.GroupRef(pattern_name)
Beispiel #12
0
def Alt(*args):
    """exp1, exp2, ... -> match exp1 or (if that fails) match exp2 or ..."""
    # Do some type checking
    for arg in args:
        assert isinstance(arg, Expression.Expression), \
               "expecting an Expression, not a %s" % type(arg)
    return Expression.Alt(args)
Beispiel #13
0
def main(args):
    with open(args['<config_filename>'], 'r') as cfg_file:
        config = json.load(cfg_file)

    expression_analysis = Expression.from_rsem_ebseq(
        config['treatments'], config['ebseq_runs'], config['treatments_dir'],
        config['ebseq_dir'], config['calc_expr_extension'])
Beispiel #14
0
def joinSql(table, table2, c, n):
    tempTable = Expression.Relation("temp" + str(n), c)
    rd.createTempAs(
        "temp" + str(n),
        rd.selectSql("*", table.name + " Natural Join " + table2.name, "", c),
        c)
    return tempTable
Beispiel #15
0
def RepN(expr, count):
    """expr, count -> match the expression 'count' number of time

    This option is handy for named group repeats since you don't have
    to use the name twice; for the min_count and max_count fields.
    """
    return Expression.MaxRepeat(expr, count, count)
Beispiel #16
0
def printBlock(block, indents):
    for el in block.expressions:
        if Expression.IsBlock(el):
            #print(type(el))
            printBlock(el,indents+2)
            continue
        print(indents*'-'+str(el))
def generate_simple_primitive_expressions(max_integer):
    expressions = {int: [], float: [], bool: [], SetPlaceholder: []}

    for i in range(0, max_integer+1, 2):
        expressions[int].append(Expression(i, Primitives.create_value_func(i), is_constant=True))

    for set_name in ['A', 'B', 'A-B', 'A&B']:
        expressions[int].append(Expression(set_name, Primitives.cardinality_functions[set_name]))

    for q in np.arange(0, 1, .1):
        expressions[float].append(Expression(q, Primitives.create_value_func(q), is_constant=True))

    for boolean in [True, False]:
        expressions[bool].append(Expression(boolean, Primitives.create_value_func(boolean), is_constant=True))

    return expressions
Beispiel #18
0
 def unary(self):
     unary_ops = [TokenType.MINUS, TokenType.BANG]
     if self.curr_token_is(unary_ops):
         operator = self.pop_token()
         right_side = self.function_call()
         return Expression.Unary(operator, right_side)
     return self.function_call()
Beispiel #19
0
def Main():
    while True:
        usrInput = None
        if sys.version_info < (3,0):
            usrInput = raw_input("Input: ").lower()
        else:
            usrInput = input("Input: ").lower()
            
        if (usrInput == ""):
            break

        exp = ParseInput.ParseInput(usrInput)
        
        print("--------------")
        variable = None
        for var in exp.variables:
            if var.variable == 'x':
                variable = var
                break
        if variable == None:
            if len(exp.variables) >0:
                variable = exp.variables[0]
            else:
                variable = Expression.VariableElement('x')
                
        print("f("+str(variable)+") = "+ParseInput.blockToStr(exp,""))
        derivative = Derivative.differentiate(exp,variable,makeNice=True)
        print("f'("+str(variable)+") = "+ ParseInput.blockToStr(derivative, ""))
Beispiel #20
0
 def get_boolean_expression(self):
     tok = self.lex.get_next_token()
     if tok.get_tok_type() == TokenType.EQ_TOK:
         self.match(tok, TokenType.EQ_TOK)
         rel_op = RelativeOperator.EQ_OP
     elif tok.get_tok_type() == TokenType.NE_TOK:
         self.match(tok, TokenType.NE_TOK)
         rel_op = RelativeOperator.NE_OP
     elif tok.get_tok_type() == TokenType.LT_TOK:
         self.match(tok, TokenType.LT_TOK)
         rel_op = RelativeOperator.LT_OP
     elif tok.get_tok_type() == TokenType.GT_TOK:
         self.match(tok, TokenType.GT_TOK)
         rel_op = RelativeOperator.GT_OP
     elif tok.get_tok_type() == TokenType.LE_TOK:
         self.match(tok, TokenType.LE_TOK)
         rel_op = RelativeOperator.LE_OP
     elif tok.get_tok_type() == TokenType.GE_TOK:
         self.match(tok, TokenType.GE_TOK)
         rel_op = RelativeOperator.GE_OP
     else:
         raise Exceptions.ParserError(Enumerated.RelativeOperator, tok)
     expr1 = self.get_expression()
     expr2 = self.get_expression()
     return Expression.BooleanExpression(rel_op, expr1, expr2)
Beispiel #21
0
 def get_binary_expression(self):
     tok = self.lex.get_next_token()
     if tok.get_tok_type() == TokenType.ADD_TOK:
         self.match(tok, TokenType.ADD_TOK)
         oper = ArithmeticOperator.ADD_OP
     elif tok.get_tok_type() == TokenType.MUL_TOK:
         self.match(tok, TokenType.MUL_TOK)
         oper = ArithmeticOperator.MUL_OP
     elif tok.get_tok_type() == TokenType.SUB_TOK:
         self.match(tok, TokenType.SUB_TOK)
         oper = ArithmeticOperator.SUB_OP
     elif tok.get_tok_type() == TokenType.DIV_TOK:
         self.match(tok, TokenType.DIV_TOK)
         oper = ArithmeticOperator.DIV_OP
     elif tok.get_tok_type() == TokenType.MOD_TOK:
         self.match(tok, TokenType.MOD_TOK)
         oper = ArithmeticOperator.MOD_OP
     elif tok.get_tok_type() == TokenType.REV_DIV_TOK:
         self.match(tok, TokenType.REV_DIV_TOK)
         oper = ArithmeticOperator.REV_DIV_OP
     elif tok.get_tok_type() == TokenType.EXP_TOK:
         self.match(tok, TokenType.EXP_TOK)
         oper = ArithmeticOperator.EXP_OP
     else:
         raise Exceptions.ParserError("Operator Token", tok)
     expr1 = self.get_expression()
     expr2 = self.get_expression()
     return Expression.BinaryExpression(oper, expr1, expr2)
Beispiel #22
0
    def __init__(self, lexer, parser, parent):
        Token.__init__(self, 'FunctionCall', lexer, parser, parent)
        self.funcname  = None
        self.arguments = []

        # Extract the function name.
        _, token = lexer.token()
        lexer.expect(self, 'open_function_call')
        self.funcname = token[:-1]
        function      = self.parent.get(self.funcname)
        if function is None:
            lexer.syntax_error('Undefined function %s' % self.funcname, self)

        # Parse the argument list.
        _, token = lexer.token()
        while 1:
            if lexer.next_if('close_bracket'):
                break
            self.arguments.append(Expression.Expression(lexer, parser, parent))
            ttype, token = lexer.token()
            if not lexer.next_if('comma') and not lexer.current_is('close_bracket'):
                error = 'Expected separator or argument list end but got %s'
                lexer.syntax_error(error % ttype, self)

        if parser.secure_only and not hasattr(function, '_is_secure'):
            msg = 'Use of insecure function %s is not permitted' % self.funcname
            lexer.error(msg, self, PermissionError)

        self.mark_end()
Beispiel #23
0
def selectionSqlAttr(attr1, attr2, table, c, n):
    tempTable = Expression.Relation("temp" + str(n), c)
    rd.createTempAs(
        "temp" + str(n),
        rd.selectSql("*", table, " WHERE " + attr1.name + "=" + attr2.name, c),
        c)
    return tempTable
Beispiel #24
0
def selectionSqlCst(attr, cst, table, c, n):
    tempTable = Expression.Relation("temp" + str(n), c)
    rd.createTempAs(
        "temp" + str(n),
        rd.selectSql("*", table,
                     " WHERE " + attr.name + "='" + str(cst.valeur) + "'", c),
        c)
    return tempTable
Beispiel #25
0
 def multiplication(self):
     curr_expr = self.unary()
     mult_ops = [TokenType.STAR, TokenType.SLASH, TokenType.PERCENT]
     while self.curr_token_is(mult_ops):
         operator = self.pop_token()
         right_side = self.unary()
         curr_expr = Expression.Binary(curr_expr, operator, right_side)
     return curr_expr
Beispiel #26
0
 def addition(self):
     curr_expr = self.multiplication()
     addition_ops = [TokenType.MINUS, TokenType.PLUS]
     while self.curr_token_is(addition_ops):
         operator = self.pop_token()
         right_side = self.multiplication()
         curr_expr = Expression.Binary(curr_expr, operator, right_side)
     return curr_expr
Beispiel #27
0
 def equality(self):
     curr_expr = self.comparison()
     equality_ops = [TokenType.EQUAL_EQUAL, TokenType.BANG_EQUAL]
     while self.curr_token_is(equality_ops):
         operator = self.pop_token()
         right_side = self.comparison()
         curr_expr = Expression.Binary(curr_expr, operator, right_side)
     return curr_expr
Beispiel #28
0
 def logical_ops(self):
     curr_expr = self.equality()
     logical_ops = [TokenType.OR, TokenType.AND]
     while self.curr_token_is(logical_ops):
         operator = self.pop_token()
         right_side = self.equality()
         curr_expr = Expression.Binary(curr_expr, operator, right_side)
     return curr_expr
Beispiel #29
0
def Seq(*args):
    """exp1, exp2, ... -> match exp1 followed by exp2 followed by ..."""
    # I'm always forgetting and passing strings into this function,
    # so make sure the arguments are expressions
    for arg in args:
        assert isinstance(arg, Expression.Expression), \
               "expecting an Expression, not a %s" % type(arg)

    return Expression.Seq(args)
def parse_expression(spec, setup):
    if isinstance(spec, list):
        func = operators[spec[0]].func
        arg_expressions = []
        for arg_spec in spec[1:]:
            arg_expressions.append(parse_expression(arg_spec,setup))
        return Expression(spec[0], func, *arg_expressions)

    return setup.parse_primitive(spec)