Пример #1
0
def decompose_unittest(old, block):
    '''decompose the block into its component parts'''

    ''' returns indent, arglist, trailer 
        indent -- the indentation
        arglist -- the arguments to the unittest function
        trailer -- any extra junk after the closing paren, such as #commment
    '''
 
    indent = re.match(r'(\s*)', block).group()
    pat = re.search('self.' + old + r'\(', block)

    args, trailer = get_expr(block[pat.end():], ')')
    arglist = break_args(args, [])

    if arglist == ['']: # there weren't any
        return indent, [], trailer

    for i in range(len(arglist)):
        try:
            parser.expr(arglist[i].lstrip('\t '))
        except SyntaxError:
            if i == 0:
                arglist[i] = '(' + arglist[i] + ')'
            else:
                arglist[i] = ' (' + arglist[i] + ')'

    return indent, arglist, trailer
Пример #2
0
def decompose_unittest(old, block):
    """decompose the block into its component parts"""

    """ returns indent, arglist, trailer 
        indent -- the indentation
        arglist -- the arguments to the unittest function
        trailer -- any extra junk after the closing paren, such as #commment
    """

    indent = re.match(r"(\s*)", block).group()
    pat = re.search("self." + old + r"\(", block)

    args, trailer = get_expr(block[pat.end() :], ")")
    arglist = break_args(args, [])

    if arglist == [""]:  # there weren't any
        return indent, [], trailer

    for i in range(len(arglist)):
        try:
            parser.expr(arglist[i].lstrip("\t "))
        except SyntaxError:
            if i == 0:
                arglist[i] = "(" + arglist[i] + ")"
            else:
                arglist[i] = " (" + arglist[i] + ")"

    return indent, arglist, trailer
Пример #3
0
    def test_sizeof(self):
        def XXXROUNDUP(n):
            if n <= 1:
                return n
            if n <= 128:
                return (n + 3) & ~3
            return 1 << (n - 1).bit_length()

        basesize = support.calcobjsize('Pii')
        nodesize = struct.calcsize('hP3iP0h')
        def sizeofchildren(node):
            if node is None:
                return 0
            res = 0
            hasstr = len(node) > 1 and isinstance(node[-1], str)
            if hasstr:
                res += len(node[-1]) + 1
            children = node[1:-1] if hasstr else node[1:]
            if children:
                res += XXXROUNDUP(len(children)) * nodesize
                for child in children:
                    res += sizeofchildren(child)
            return res

        def check_st_sizeof(st):
            self.check_sizeof(st, basesize + nodesize +
                                  sizeofchildren(st.totuple()))

        check_st_sizeof(parser.expr('2 + 3'))
        check_st_sizeof(parser.expr('2 + 3 + 4'))
        check_st_sizeof(parser.suite('x = 2 + 3'))
        check_st_sizeof(parser.suite(''))
        check_st_sizeof(parser.suite('# -*- coding: utf-8 -*-'))
        check_st_sizeof(parser.expr('[' + '2,' * 1000 + ']'))
Пример #4
0
    def test_comparisons(self):
        # ST objects should support order and equality comparisons
        st1 = parser.expr('2 + 3')
        st2 = parser.suite('x = 2; y = x + 3')
        st3 = parser.expr('list(x**3 for x in range(20))')
        st1_copy = parser.expr('2 + 3')
        st2_copy = parser.suite('x = 2; y = x + 3')
        st3_copy = parser.expr('list(x**3 for x in range(20))')

        # exercise fast path for object identity
        self.assertEqual(st1 == st1, True)
        self.assertEqual(st2 == st2, True)
        self.assertEqual(st3 == st3, True)
        # slow path equality
        self.assertEqual(st1, st1_copy)
        self.assertEqual(st2, st2_copy)
        self.assertEqual(st3, st3_copy)
        self.assertEqual(st1 == st2, False)
        self.assertEqual(st1 == st3, False)
        self.assertEqual(st2 == st3, False)
        self.assertEqual(st1 != st1, False)
        self.assertEqual(st2 != st2, False)
        self.assertEqual(st3 != st3, False)
        self.assertEqual(st1 != st1_copy, False)
        self.assertEqual(st2 != st2_copy, False)
        self.assertEqual(st3 != st3_copy, False)
        self.assertEqual(st2 != st1, True)
        self.assertEqual(st1 != st3, True)
        self.assertEqual(st3 != st2, True)
        # we don't particularly care what the ordering is;  just that
        # it's usable and self-consistent
        self.assertEqual(st1 < st2, not (st2 <= st1))
        self.assertEqual(st1 < st3, not (st3 <= st1))
        self.assertEqual(st2 < st3, not (st3 <= st2))
        self.assertEqual(st1 < st2, st2 > st1)
        self.assertEqual(st1 < st3, st3 > st1)
        self.assertEqual(st2 < st3, st3 > st2)
        self.assertEqual(st1 <= st2, st2 >= st1)
        self.assertEqual(st3 <= st1, st1 >= st3)
        self.assertEqual(st2 <= st3, st3 >= st2)
        # transitivity
        bottom = min(st1, st2, st3)
        top = max(st1, st2, st3)
        mid = sorted([st1, st2, st3])[1]
        self.assertTrue(bottom < mid)
        self.assertTrue(bottom < top)
        self.assertTrue(mid < top)
        self.assertTrue(bottom <= mid)
        self.assertTrue(bottom <= top)
        self.assertTrue(mid <= top)
        self.assertTrue(bottom <= bottom)
        self.assertTrue(mid <= mid)
        self.assertTrue(top <= top)
        # interaction with other types
        self.assertEqual(st1 == 1588.602459, False)
        self.assertEqual('spanish armada' != st2, True)
        self.assertRaises(TypeError, operator.ge, st3, None)
        self.assertRaises(TypeError, operator.le, False, st1)
        self.assertRaises(TypeError, operator.lt, st1, 1815)
        self.assertRaises(TypeError, operator.gt, b'waterloo', st2)
Пример #5
0
    def _walk_doc(self):
        doc = self._get_root()
        self.output += "var {} = F();\n".format(doc)
        self._push_root(doc)
        self._switch("html")

        for child in self.doc.childNodes:
            if child.nodeType == child.COMMENT_NODE:
                comment_data = child.nodeValue.strip()

                if re.match(r"^\s*define\([^\)]*\)\s*$", comment_data):
                    st = parser.expr(comment_data)
                    c = st.compile()
                    ret = eval(c, {"define": lambda x: x})
                    if not isinstance(ret, dict):
                        raise Exception("Found a require() comment that does not specify a dict")
                    self.needed_args = OrderedDict(ret)

                elif re.match(r"^\s*Template\([^\)]*\)\s*$", comment_data):
                    st = parser.expr(comment_data)
                    c = st.compile()
                    ret = eval(c, {"Template": lambda *args: list(args)})
                    if not isinstance(ret, list):
                        raise Exception("Found a Template() comment that does not specify a list of globals")
                    self.tpl_vars = ret

            else:
                self._walk_node(child)

        self.output += "return {};\n".format(doc)
Пример #6
0
    def validate(self, string):
        """We use the ``parser`` module to determine if
        an expression is a valid python expression."""

        if isinstance(string, unicode):
            string = string.encode('utf-8')

        if string != "":
            parser.expr(string.strip())
Пример #7
0
 def consume(self, input):
   if not input.startswith('${'):
     return None, None, 0
   input = input[2:]
   try:
     parser.expr(input)
     raise Exception('Expected } but EOF found.')
   except SyntaxError, e:
     if input[e.offset - 1] != '}':
       raise
Пример #8
0
def compileEqn(eqn_str):
    eqn_str = eqn_str.replace('^','**')
    eqn_str = "".join(eqn_str.split()) # remove all whitespace
    if eqn_str[:2] == "if":
        cond, eqn_true, eqn_false = eqn_str[3:-1].split(',')
        if eval(parser.expr(cond).compile()):
            return parser.expr(eqn_true).compile()
        else:
            return parser.expr(eqn_false).compile()
    else:
        return parser.expr(eqn_str).compile()
Пример #9
0
 def test_copy_pickle(self):
     sts = [
         parser.expr('2 + 3'),
         parser.suite('x = 2; y = x + 3'),
         parser.expr('list(x**3 for x in range(20))')
     ]
     for st in sts:
         st_copy = copy.copy(st)
         self.assertEqual(st_copy.totuple(), st.totuple())
         st_copy = copy.deepcopy(st)
         self.assertEqual(st_copy.totuple(), st.totuple())
         for proto in range(pickle.HIGHEST_PROTOCOL+1):
             st_copy = pickle.loads(pickle.dumps(st, proto))
             self.assertEqual(st_copy.totuple(), st.totuple())
Пример #10
0
def _find_last_expr(code_lines):
    for x in range(len(code_lines) - 1, -1, -1):
        code = "\n".join(code_lines[x:])
        try:
            parser.suite(code)
            try:
                parser.expr(code)
            except:  # last statement is not an expression
                return None

            return x
        except:
            pass

    return None
Пример #11
0
def compile_unicode(source, filename, method):
    '''Compile Python source represented as unicode object. All string
    litterals containing non-ASCII character will be unicode objects.'''
    import parser
    from token import ISNONTERMINAL, STRING
    source = source.encode('utf-8')  # parser complains about unicode source
    if method=='exec':
        ast = parser.suite(source)
    elif method=='eval':
        ast = parser.expr(source)
    else:
        raise ValueError('Unsupported compilation method: %r' % (method,))
    ast_seq = ast.tolist(True)
    # non-recursive method to walk through tree
    stack = [iter([ast_seq]).next]
    while stack:
        try:
            node = stack[-1]()
        except StopIteration:
            stack.pop()
            continue
        if ISNONTERMINAL(node[0]):
            stack.append(iter(node[1:]).next)
        elif node[0]==STRING:
            s = eval(node[1])
            try:
                s.decode('ascii')
            except UnicodeDecodeError:
                s = s.decode('utf-8')
            node[1] = repr(s)
    return parser.sequence2ast(ast_seq).compile(filename)
Пример #12
0
def compile(src, file_name, ctype):
    if ctype=='eval': ast=parser.expr(src)
    elif ctype=='exec': ast=parser.suite(src)
    l=ast2list(ast)
    l=munge(l)
    ast=sequence2ast(l)
    return parser.compileast(ast, file_name)
def simpson(formula, a, b,n,cadena):
    cadena.append("Paso #1")
    ba=b-a
    h=ba/float(n)
    i=1
    cadena.append("tome h=("+str(b)+"-"+str(a)+")/"+str(n)+"="+str(h))
    cadena.append("Paso #2")
    code = parser.expr(formula).compile()
    x=a
    fa=eval(code)
    x=b
    fb=eval(code)
    Xl0=float(fa+fb)
    cadena.append("tome Xl0="+str(Xl0))
    Xl1=0
    Xl2=0
    cadena.append("Paso#3: Para i=1....,n-1 hacer pasos 4 y 5")
    while i< n:
        cadena.append("i="+str(i))
        X=float(a+(i*h))
        cadena.append("Paso#4: Tome X="+str(a)+str(i)+"*"+str(h)+"="+str(X))
        x=X
        fx=eval(code)
        if i%2==0: 
            Xl2=float(Xl2+fx)
            cadena.append("Paso#5:  i es par , entonces: Xl2="+str(Xl2))
        else:
            Xl1=float(Xl1+fx)
            cadena.append("Paso#5:  i es impar , entonces: Xl1="+str(Xl1))
        i=i+1
    Xl=float((h*(Xl0+(2*Xl2)+(4*Xl1)))/3)
    cadena.append("Paso#6: Xl="+str(h)+"*("+str(Xl0)+"+"+"2*"+str(Xl2)+"+"+"4*"+str(Xl1)+")/3")
    cadena.append("Paso#7: Xl="+str(Xl))
    return Xl
Пример #14
0
def CountBytes (sInputFile, SizeLimit = ''):

	nByteCount = 0

	try:
		FileToRead = open (sInputFile, 'r')

	except OSError:
		print ("Error opening file!")
		return

	sLine = FileToRead.readline ()

	if sLine[0] == ':':
		FileFormat = 'hex'

	elif sLine[0] == 'S':
		FileFormat = 's19'

	else:
		# Unknown file format
		print ("Unknown file format!")
		return

	if FileFormat == 'hex':
		# Read until we get an empty string (this does not include newlines)
		while not sLine == '':
			if sLine[7:9] == '00':
				# This line contains data --> add the byte count to our counter
				nByteCount += int (sLine[1:3], 16)

			sLine = FileToRead.readline ()

	elif FileFormat == 's19':
		# Read until we get an empty string (this does not include newlines)
		while not sLine == '':
			if sLine[1:2] == '1':
				# This line contains data and 3 non-data bytes --> add the data byte count to our counter
				nByteCount += (int (sLine[2:4], 16) - 3)
			elif sLine[1:2] == '2':
				# This line contains data and 4 non-data bytes --> add the data byte count to our counter
				nByteCount += (int (sLine[2:4], 16) - 4)
			elif sLine[1:2] == '3':
				# This line contains data and 5 non-data bytes --> add the data byte count to our counter
				nByteCount += (int (sLine[2:4], 16) - 5)

			sLine = FileToRead.readline ()

	# Print the results
	print ("Number of data bytes: " + str (nByteCount))

	if not SizeLimit == '':
		# Check for any suffixes on the size limit
		SizeLimit = str (SizeLimit).replace ('k', '* 1024')
		SizeLimit = str (SizeLimit).replace ('M', '* 1024**2')
		SizeLimit = str (SizeLimit).replace ('G', '* 1024**4')
		SizeLimit = eval (parser.expr(SizeLimit).compile())
		print ("Percent used: " + str (float (100 * nByteCount / SizeLimit)))

	return
Пример #15
0
    def delete(self, where=None, limit=None, desk=None):
        limit = int(limit.strip()) if limit else 0
        where = 'True' if not where else where
        where = self.fix_where(where)

        rez = 0
        del_indexes = []
        l = locals()
        i = 0
        mem = self._memory if not desk else reversed(self._memory)
        for d in mem:
            for name_, type_, len_ in self._schema:
                l[name_] = d[name_]

            st = parser.expr(where)
            is_ok = eval(st.compile())

            if is_ok:
                rez += 1
                del_indexes.append(i)

            i += 1

            if limit and rez >= limit:
                break

        z = 0
        for x in sorted(del_indexes):
            self._delete_dy_index(x - z)
            z += 1

        return rez
    def get_series_data(self, min_range=0, max_range=100, step=None):
        """
        NOTE: The symbol from the equation which varies should be named: var
        Returns the series data needed for plotting this equation.
        """
        if step is None:
            step = float(max_range - min_range) / DEFAULT_PLOT_GRANULARITY

        from math import sin, cos, sqrt, exp

        result = []
        parsed_equation = self.get_parsed_equation()
        parsed_equation = parser.expr(parsed_equation).compile()
        last_valid_point_value = 0
        was_exception_thrown = False
        for var in numpy.arange(min_range, max_range + step, step):
            try:
                point_value = eval(parsed_equation)
                #the number should have max 20 decimals
                point_value = round(point_value, 19)
                result.append([float(var), point_value])
                last_valid_point_value = point_value
            except OverflowError, exc:
                LOG.exception(exc)
                LOG.error("Could not evaluate the equation at step var = " + str(var))
                result.append([var, last_valid_point_value])
                was_exception_thrown = True
Пример #17
0
    def parse_line(self, line):
        print(line)
        dic = {}
        base = self.packet_base
        ll = line.split()

        # self.packet_struct['header'] is a list of header fields with sizes 1-2B
        for field in self.packet_struct['header']:
            dic[field['short']] = self.get_value(ll, base, field['encoding'], field['fsize'])
            base = base + field['fsize']
            print("base = {}, fiel = {}, val = {}".format(base, field['short'],
                dic[field['short']]))
        
        # self.packet_struct['sensors'] is a dict with integer keys equal to 
        # equals attribute in the XML specification of the protocol
        for sensor in range(dic['sensors']):
            sensor_id = int(ll[base],16)
            v = self.get_value(ll, base+1, 'BIG_ENDIAN', 2)
            # print('formula = {}'.format(self.packet_struct['sensors'][sensor_id]['formula']))
            code =  parser.expr(self.packet_struct['sensors'][sensor_id]['formula']).compile()
            # print('type = {}'.format(type(code)))
            sensor_value = eval(code)
            short = self.packet_struct['sensors'][sensor_id]['short']
            print("base = {}, id = {}, val = {}, short={}".format(base, sensor_id, sensor_value,
                short))
            dic[short] = sensor_value
            base = base + 3

        return dic
Пример #18
0
    def parse_basic_statement(self, component):
        '''
        turn: 'd-e-b+-a+1.223/2*4'
        into: ['d','-','e','-','b','+','','-','a','+','1.223','/','2','*','4']
        '''
        # extract parens, but allow internal parens if needed.. internal parens
        # are not supported in literal_eval.
        side = component[1:-1]
        pat = '([\(\)\-+*\/])'
        chopped = re.split(pat, side)

        # - replace known variable chars with intended variable
        # - remove empty elements
        for i, ch in enumerate(chopped):
            if ch in self.segments:
                chopped[i] = str(self.segments[ch]['data'][self.profile_idx])
        chopped = [ch for ch in chopped if ch]

        # - depending on the parsing mode, return found end value.
        string_repr = ''.join(chopped).strip()
        if self.extended_parsing:
            code = parser.expr(string_repr).compile()
            return eval(code)
        else:
            return literal_eval(string_repr)
Пример #19
0
    def insert(self, insert_obj_row):
        if not insert_obj_row.startswith('(') or not insert_obj_row.endswith(')'):
            return
        insert_obj_row = insert_obj_row.replace("'", "'''")
        insert_obj_row = insert_obj_row.replace("\"", "'''")
        try:
            st = parser.expr(insert_obj_row)
            obj = eval(st.compile())
            if type(obj) != tuple or len(obj) != len(self._schema):
                return

            d = {}
            i = 0
            for name_, type_, len_ in self._schema:
                d[name_] = obj[i]
                i += 1

                _ck = CHECKERS[type_]
                if _ck(d[name_]):
                    return

            self._insert(d)
            return d
        except Exception as e:
            self.error('Insertion error!', e)
            return
def runge_kutta_ecu_dif(formula, a, b, alfa, N,lista):
  
    h = float((b - a))/N
      
    t = a
    x = alfa

    t_list=[t]
    x_list=[x]
    
    funcion = parser.expr(formula).compile()
    
    itera = 1
    lista.append("f(t,x) ")
    lista.append ("f("+str(t)+","+str(x)+")")

    lista.append ("Paso #2")
    lista.append("Mientras i sea menor o igual al numero de iteraciones" )
    lista.append ("Hacer los pasos 3, 4, 5 x 6" )
    while itera <= N:
        lista.append ("------------- i = " + str(itera) + " ------------------")
        t_bak = t
        x_bak = x

        lista.append("Paso #3")
        fun_t_x = eval(funcion)
        k_1 = h * fun_t_x

        t = t_bak+float(h)/2
        x = x_bak+float(k_1)/2
        fun_t_x = eval(funcion)
        k_2 = h * fun_t_x
        
        t = t_bak+float(h)/2
        x = x_bak+float(k_2)/2
        fun_t_x = eval(funcion)
        k_3 = h * fun_t_x

        t = t_bak+ h
        x = x_bak+ k_3
        fun_t_x = eval(funcion)
        k_4 = h * fun_t_x

        x = x_bak + float((k_1 + 2*k_2 + 2*k_3 + k_4 ))/6
        t = a + itera * h

        t_list.append(t)
        x_list.append(x)

        lista.append ("f(t,x)")
        lista.append ("f("+str(t)+","+str(x)+")")
        itera = itera+1

    lista.append("------------- RESULTADOS ------------------")
    lista.append ("\tf(t,w)")
    for i in range(len(t_list)):
        lista.append("\tf("+str(t_list[i])+","+str(x_list[i])+")")

    return lista
Пример #21
0
def build_atom(expr_string):
    """ Build an ast for an atom from the given expr string.

        If expr_string is not a string, it is converted to a string
        before parsing to an ast_tuple.
    """
    # the [1][1] indexing below starts atoms at the third level
    # deep in the resulting parse tree.  parser.expr will return
    # a tree rooted with eval_input -> test_list -> test ...
    # I'm considering test to be the root of atom symbols.
    # It might be a better idea to move down a little in the
    # parse tree. Any benefits? Right now, this works fine.
    if isinstance(expr_string, str):
        ast = parser.expr(expr_string).totuple()[1][1]
    else:
        ast = parser.expr(repr(expr_string)).totuple()[1][1]
    return ast
Пример #22
0
def parse(expression_string):
    # To be forgiving, clean up the string a bit.
    expression_string = expression_string.replace("\n", " ").strip()
    # Now parse it.
    try:
        ast = parser.ast2tuple(parser.expr(expression_string))
    except parser.ParserError, exception:
        raise ParseError, str(exception)
Пример #23
0
    def operation(self):
        f = str(self.ventana.display.text())
        ff = parser.expr(f).compile()
        newF = eval(ff)
        if ! in myList:

        self.Calculadora.resultado = newF
        self.ventana.display.setText(str(newF))
Пример #24
0
def find_variables(expr):
    """Find the variables participating in an expressions

    Returns
    -------
    variables : tuple of str
        Variables occurring in expr.
    """
    return _find_vars(parser.expr(expr).totuple())
Пример #25
0
	def __init__(self, name, str_metric):
		self.name = name
		self.str_metric = str_metric

                # Adapts the metric to be readable by the pmctrack command data extractor (pmc_extract.py)
		str_metric_mod = re.sub(r"pmc(\d+)", r"float(field[self.pos['pmc\1']])", str_metric)
		str_metric_mod = re.sub(r"virt(\d+)", r"float(field[self.pos['virt\1']])", str_metric_mod)

		self.metric = parser.expr(str_metric_mod).compile()
Пример #26
0
	def _compute(self,series,parameters):
		
		expression = parameters['expression']
		variableDictionary = locals()
		variableDictionary['x'] = series
		code = parser.expr( expression ).compile()
		series = eval(code)

		return series
Пример #27
0
def is_gate_expr(exp, is_ogate):
    # check if the leading/trailing whitespace characters contains '\n'
    if is_ogate:
        prefix, postfix = '1*', '+1'
    else:
        prefix, postfix = '1+', '*1'

    exp_stripped = exp.strip()
    while len(exp_stripped) > 0 and exp_stripped[-1] == '\\':
        exp_stripped = exp_stripped[:-1].strip()

    try:
        parser.expr('(%s)' % exp_stripped)
        parser.expr('%s%s%s' % (prefix, exp, postfix))
    except SyntaxError:
        return False
    else:
        return True
Пример #28
0
 def test_issue_9011(self):
     # Issue 9011: compilation of an unary minus expression changed
     # the meaning of the ST, so that a second compilation produced
     # incorrect results.
     st = parser.expr('-3')
     code1 = parser.compilest(st)
     self.assertEqual(eval(code1), -3)
     code2 = parser.compilest(st)
     self.assertEqual(eval(code2), -3)
Пример #29
0
  def __init__(self,e):
    self.out=[]
    try:
      self.t=expr(e).tolist()[1]
      self.cc(self.t)
#    print self.t
      self.out=self.totex(self.t)
    except SyntaxError:
      self.out=e
Пример #30
0
def python_parse(source, mode='exec', lineno=False):
    """parse python source using CPython's parser module and return
    nested tuples
    """
    if mode == 'eval':
        tp = parser.expr(source)
    else:
        tp = parser.suite(source)
    return parser.ast2tuple(tp, line_info=lineno)
Пример #31
0
def _expand_as(func, predicate_string, *namespaces):
    """Pre-parse predicate string and register meta function"""

    args, varargs, kw, defaults = arginfo = inspect.getargspec(func)
    argnames = list(flatten(filter(None, [args, varargs, kw])))
    parsed = parser.expr(predicate_string).totuple(1)[1]
    builder = CriteriaBuilder(dict([(arg, Local(arg)) for arg in argnames]),
                              *namespaces)
    bindings = {}
    for b in builder.bindings[-len(namespaces):][::-1]:
        bindings.update(b)

    # Make a function that just gets the arguments we want
    c = Code.from_function(func)
    c.return_(Call(Const(locals), fold=False))
    getargs = new.function(c.code(), func.func_globals, func.func_name,
                           func.func_defaults, func.func_closure)

    def expand(builder, *args):
        builder.push(bindings)  # globals, locals, etc.
        builder.bind(apply_meta(builder, (getargs, {}, arginfo), *args))

        # build in the newly-isolated namespace
        result = build(builder, parsed)
        builder.pop()
        return result

    meta_functions[func] = expand
    func.__doc__  # workaround for PyPy issue #1293
    c = Code.from_function(func)
    c.return_()
    if func.func_code.co_code == c.code().co_code:  # function body is empty
        c = Code.from_function(func)
        c.return_(build(builder, parsed))
        func.func_code = c.code()

    return func
Пример #32
0
def tweak_field(moose_wildcard, field, assignment_string):
    """Tweak a specified field of all objects that match the
    moose_wildcard using assignment string. All identifiers in
    assignment string must be fields of the target object.

    Example:

    tweak_field('/mycell/##[Class=Compartment]', 'Rm', '1.5 / (3.1416 * diameter * length')

    will assign Rm to every compartment in mycell such that the
    specific membrane resistance is 1.5 Ohm-m2.
    """
    if not isinstance(moose_wildcard, str):
        raise TypeError('moose_wildcard must be a string.')
    id_list = moose.getWildcardList(moose_wildcard, True)
    expression = parser.expr(assignment_string)
    expr_list = expression.tolist()
    # This is a hack: I just tried out some possible syntax trees and
    # hand coded the replacement such that any identifier is replaced
    # by moose_obj.identifier
    def replace_fields_with_value(x):
        if len(x)>1:
            if x[0] == symbol.power and x[1][0] == symbol.atom and x[1][1][0] == token.NAME:
                field = x[1][1][1]
                x[1] = [symbol.atom, [token.NAME, 'moose_obj']]
                x.append([symbol.trailer, [token.DOT, '.'], [token.NAME, field]])
            for item in x:
                if isinstance(item, list):
                    replace_fields_with_value(item)
        return x
    tmp = replace_fields_with_value(expr_list)
    new_expr = parser.sequence2st(tmp)
    code = new_expr.compile()
    for moose_id in id_list:
        moose_obj = eval('moose.%s(moose_id)' % (moose.Neutral(moose_id).className))
        value = eval(code)
        moose.setField(moose_id, field, str(value))
Пример #33
0
def ab_7(t0, h, n, fty):
    expr = parser.expr(fty).compile()

    y0 = arr_y[len(arr_y) - 1]

    for i in range(len(arr_y), n + 1):
        arr_t.append(t0)

        # f(tn, yn)
        f_tn_yn = do_eval(arr_t[len(arr_y) - 1], y0, expr)

        # f(tn-1, yn-1)
        f_tn1_yn1 = do_eval(arr_t[len(arr_y) - 2], arr_y[len(arr_y) - 2], expr)

        # f(tn-2, yn-2)
        f_tn2_yn2 = do_eval(arr_t[len(arr_y) - 3], arr_y[len(arr_y) - 3], expr)

        # f(tn-3, yn-3)
        f_tn3_yn3 = do_eval(arr_t[len(arr_y) - 4], arr_y[len(arr_y) - 4], expr)

        # f(tn-4, yn-4)
        f_tn4_yn4 = do_eval(arr_t[len(arr_y) - 5], arr_y[len(arr_y) - 5], expr)

        # f(tn-5, yn-5)
        f_tn5_yn5 = do_eval(arr_t[len(arr_y) - 6], arr_y[len(arr_y) - 6], expr)

        # f(tn-6, yn-6)
        f_tn6_yn6 = do_eval(arr_t[len(arr_y) - 7], arr_y[len(arr_y) - 7], expr)

        # yn+1 = yn + h*((198721/60480)*f(tn, yn) - (18637/2520)*f(tn-1, yn-1) + (235183/20160)*f(tn-2, yn-2) - (10754/945)*f(tn-3, yn-3) + (135713/20160)*f(tn-4, yn-4) - (5603/2520)*f(tn-5, yn-5) + (19087/60480)*f(tn-6, yn-6))
        y0 += h * ((198721 / 60480) * f_tn_yn - (18637 / 2520) * f_tn1_yn1 +
                   (235183 / 20160) * f_tn2_yn2 - (10754 / 945) * f_tn3_yn3 +
                   (135713 / 20160) * f_tn4_yn4 - (5603 / 2520) * f_tn5_yn5 +
                   (19087 / 60480) * f_tn6_yn6)
        t0 += h

        arr_y.append(y0)
Пример #34
0
def bf_4(t0, h, n, fty):
    expr = parser.expr(fty).compile()

    for i in range(len(arr_y), n + 1):
        arr_t.append(t0)

        ### euler inverso para estimar yn+1 ###
        # yn+1 = yn + h*f(tn, yn)
        yn1_euler = arr_y[len(arr_y) - 1] + h * do_eval(
            arr_t[len(arr_y) - 1], arr_y[len(arr_y) - 1],
            expr)  # descobre yn+1

        # yn+1 = yn + h*f(tn+1, yn+1)
        yn1_be = arr_y[len(arr_y) - 1] + h * do_eval(t0, yn1_euler, expr)
        ### euler inverso para estimar yn+1 ###

        # f(tn+1, yn+1)
        f_tnp1_ynp1 = do_eval(arr_t[len(arr_t) - 1], yn1_be, expr)

        # yn
        yn = arr_y[len(arr_y) - 1]

        # yn-1
        yn1 = arr_y[len(arr_y) - 2]

        # yn-2
        yn2 = arr_y[len(arr_y) - 3]

        # yn-3
        yn3 = arr_y[len(arr_y) - 4]

        # yn+1 = (48/25)*yn - (36/25)*yn-1 + (16/25)*yn-2 - (3/25)*yn-3 + (12/25)*h*f(tn+1, yn+1)
        y0 = (48 / 25) * yn - (36 / 25) * yn1 + (16 / 25) * yn2 - (
            3 / 25) * yn3 + (12 / 25) * h * f_tnp1_ynp1
        t0 += h

        arr_y.append(y0)
Пример #35
0
def _interpretExpression(expression, cond_obj_amount, return_str = False):

	n_expression = ""

	for i in range(len(expression)):
		#remove spaces from expression
		if expression[i] != " " and expression[i] != "^":
			n_expression += expression[i]
		elif expression[i] == "^":
			n_expression += "**"

		#unknown character in expression
		if expression[i] not in _MainData.accepted_characters:
			return None

		#if number is followed by letter or letter is followed by letter, multiplication is implied
		if i != len(expression) - 1 and ((expression[i].isdigit() and (expression[i + 1].isalpha() or expression[i + 1] == "(")) or (expression[i].isalpha() and (expression[i + 1].isalpha() or expression[i + 1].isdigit() or expression[i + 1] == "("))):
			n_expression += "*"

	if not return_str:
		formula = expr(n_expression).compile()
		return formula

	return n_expression
Пример #36
0
    def create_compiled_code(self, str_funcs):
        """
        (String[]) -> (python compilable code[])

        Compiles the output function strings into python compilable code
        Includes the python math standard library, except for functions that require ','
        because ',' delimits outputfunctions

        Returns a list of the python compilable code of these function strings
        """

        code_list = []
        for f in str_funcs:
            try:
                #TODO pre-process functions with certain symbols and lack of multiplication
                f2 = f.replace("^", "**")
                code = parser.expr(f2).compile()
                code_list.append(code)
            except SyntaxError:
                # self.push_errors("Invalid function {}".format(f))
                self.push_error(
                    "'{}' :Oops! Your function was misinterpreted by the compiler. One or more variables/functions you are using may not be defined. \n"
                    .format(f))
        return code_list
Пример #37
0
    def ParseAndCompileUserFunctionString(self, inString):

        # shift user functions into numpy namespace at run time, not import time
        numpySafeTokenList = []
        for key in list(self.functionDictionary.keys()):
            numpySafeTokenList += self.functionDictionary[key]
        for key in list(self.constantsDictionary.keys()):
            numpySafeTokenList += self.constantsDictionary[key]

        # no blank lines of text, StringIO() allows using file methods on text
        stringToConvert = ''
        rawData = io.StringIO(inString).readlines()

        for line in rawData:
            stripped = line.strip()
            if len(stripped) > 0:  # no empty strings
                if stripped[0] != '#':  # no comment-only lines
                    stringToConvert += stripped + '\n'

        # convert brackets to parentheses
        stringToConvert = stringToConvert.replace('[', '(').replace(']', ')')

        if stringToConvert == '':
            raise Exception(
                'You must enter some function text for the software to use.')

        if -1 != stringToConvert.find('='):
            raise Exception(
                'Please do not use an equals sign "=" in your text.')

        st = parser.expr(stringToConvert)
        tup = st.totuple()
        tokens = self.GetTokensFromTupleParsingHelper(tup)

        if '^' in tokens:
            raise Exception(
                'The caret symbol "^" is not recognized by the parser, please substitute double asterisks "**" for "^".'
            )

        if 'ln' in tokens:
            raise Exception(
                "The parser uses log() for the natural log function, not ln(). Please use log() in your text."
            )

        if 'abs' in tokens:
            raise Exception(
                "The parser uses fabs() for the absolute value, not abs(). Please use fabs() in your text."
            )

        if 'EXP' in tokens:
            raise Exception(
                "The parser uses lower case exp(), not upper case EXP(). Please use lower case exp() in your text."
            )

        if 'LOG' in tokens:
            raise Exception(
                "The parser uses lower case log(), not upper case LOG(). Please use lower case log() in your text."
            )

        # test for required reserved tokens
        tokenNames = list(set(tokens) - set(numpySafeTokenList))
        if 'X' not in tokenNames:
            raise Exception(
                'You must use a separate upper case "X" in your function to enter a valid function of X.'
            )
        if 'Y' not in tokenNames:
            raise Exception(
                'You must use a separate upper case "Y" in your function to enter a valid function of Y.'
            )

        self._coefficientDesignators = sorted(
            list(set(tokenNames) - set(['X', 'Y'])))

        if len(self._coefficientDesignators) == 0:
            raise Exception(
                'I could not find any equation parameter or coefficient names, please check the function text'
            )

        # now compile code object using safe tokens with integer conversion
        self.safe_dict = locals()
        for f in numpySafeTokenList:
            self.safe_dict[f] = eval('numpy.' + f)

        # convert integer use such as (3/2) into floats such as (3.0/2.0)
        st = parser.expr(stringToConvert)
        stList = parser.st2list(st)
        stList = self.RecursivelyConvertIntStringsToFloatStrings(stList)
        st = parser.sequence2st(stList)

        # later evals re-use this compiled code for improved performance in EvaluateCachedData() methods
        self.userFunctionCodeObject = parser.compilest(st)
Пример #38
0
 def test_deeply_nested_list(self):
     # This has fluctuated between 99 levels in 2.x, down to 93 levels in
     # 3.7.X and back up to 99 in 3.8.X. Related to MAXSTACK size in Parser.h
     e = self._nested_expression(99)
     st = parser.expr(e)
     st.compile()
Пример #39
0
    def process(self):
        self.__csv = pd.read_csv(self.filepath, delimiter=self.delimiter, skip_blank_lines=self.skip_blank_lines, header=None)
        self.__csv = self.__csv.values

        labels = None
        result = []

        for it, data in enumerate(self.__csv):
            # Updating stats
            self.__stats['total_count_with_header'] += 1

            # Skipping the first line if needed
            if self.skip_header and it == 0:
                labels = data

                # Updating stats
                self.__stats['header_skipped'] = True

                continue

            # Updating stats
            self.__stats['total_count'] += 1

            item = {}
            cols_to_delete = []
            for map_key, map_value in self.mapping.items():

                if 'col' in map_value:
                    col = int(map_value['col'])

                    default = None
                    if 'default' in map_value:
                        default = map_value['default']

                    if col == '_all_':
                        finalvalue = data
                    else:
                        finalvalue = data[col]

                    # Set to None if value is NaN
                    finalvalue = Utils.clean_if_nan(finalvalue)

                    if finalvalue is None:
                        if default is None:
                            finalvalue = ''
                        else:
                            finalvalue = default

                    if 'transformations' in map_value:
                        finalvalue = handle_transformations(map_value['transformations'], finalvalue, error_tolerance=self.__error_tolerance)

                    item = apply_value(item, map_key, finalvalue)

                    if 'conditions' in map_value:
                        finalvalue = handle_conditions(map_value['conditions'], item, data)
                        item = apply_value(item, map_key, finalvalue)

                    # To remember which cols have already been retrieved
                    if self.__save_unmatched:
                        cols_to_delete.append(col)
                elif 'value' in map_value:
                    finalvalue = map_value['value']
                    if type(finalvalue) == str:
                        finalvalue = finalvalue.replace('$subject', 'item')
                        expr = parser.expr(finalvalue)
                        finalvalue = eval(expr.compile(''))

                    # Set to None if value is NaN
                    finalvalue = Utils.clean_if_nan(finalvalue)

                    item = apply_value(item, map_key, finalvalue)

                    if 'conditions' in map_value:
                        finalvalue = handle_conditions(map_value['conditions'], item, data)
                        item = apply_value(item, map_key, finalvalue)
                elif 'conditions' in map_value:
                    finalvalue = handle_conditions(map_value['conditions'], item, data)
                    item = apply_value(item, map_key, finalvalue)
                else:
                    text = '{} : No supported options found in mapping. Supported: [col, value, conditions]'.format(map_key)
                    if self.__error_tolerance:
                        Utils.log('error', text)
                        continue
                    else:
                        raise Exception(text)

            # Unmatched
            if self.__save_unmatched:
                for col in cols_to_delete:
                    data[col] = None

                item[self.__unmatched_key] = self.__get_unmatched(data, labels)

            result.append(item)

        return result
def calculate(equation):
    try:
        code = parser.expr(equation).compile()
        print eval(code)
    except:
        print("Syntax error.")
Пример #41
0
 def test_deeply_nested_list(self):
     e = self._nested_expression(99)
     st = parser.expr(e)
     st.compile()
Пример #42
0
def parseEquation(exp):
    return parser.expr(exp).compile()
Пример #43
0
def dump_and_modify(node):
    name = symbol.sym_name.get(node[0])
    if name is None:
        name = token.tok_name.get(node[0])
    print(name, end=' ')
    for i in range(1, len(node)):
        item = node[i]
        if type(item) is type([]):
            dump_and_modify(item)
        else:
            print(repr(item))
            if name == "NUMBER":
                # increment all numbers!
                node[i] = repr(int(item)+1)

ast = parser.expr("1 + 3")

list = ast.tolist()

dump_and_modify(list)

ast = parser.sequence2ast(list)

print(eval(parser.compileast(ast)))

## eval_input testlist test and_test not_test comparison
## expr xor_expr and_expr shift_expr arith_expr term factor
## power atom NUMBER '1'
## PLUS '+'
## term factor power atom NUMBER '3'
## NEWLINE ''
Пример #44
0
 def parseexpr(self, text):
     """Return a modified parse tree for the given expression text."""
     return self.transform(parser.expr(text))
Пример #45
0
def dump_and_modify(node):
    name = symbol.sym_name.get(node[0])
    if name is None:
        name = token.tok_name.get(node[0])
    print(name, '', end='')
    for i in range(1, len(node)):
        item = node[i]
        if type(item) is type([]):
            dump_and_modify(item)
        else:
            print(repr(item))
            if name == 'NUMBER':
                node[i] = repr(int(item) + 1)


ast = parser.expr('1 + 3')
list = ast.tolist()
dump_and_modify(list)

ast = parser.sequence2st(list)
print(eval(parser.compilest(ast)))
'''
eval_input testlist test or_test and_test not_test comparison expr xor_expr and_expr shift_expr arith_expr term factor power atom NUMBER '1'
PLUS '+'
term factor power atom NUMBER '3'
NEWLINE ''
ENDMARKER ''
6
[Finished in 0.2s]
'''
Пример #46
0
def main(argv):
  action = argv[1]
  argv = argv[2:]

  # Used at grammar BUILD time.
  OPS = {
      '.': Id.Expr_Dot,
      '->': Id.Expr_RArrow,
      '::': Id.Expr_DColon,

      '@': Id.Expr_At,
      '...': Id.Expr_Ellipsis,

      '$': Id.Expr_Dollar,  # Only for legacy eggex /d+$/
  }

  # Note: We have two lists of ops because Id.Op_Semi is used, not
  # Id.Arith_Semi.
  for _, token_str, id_ in lex.EXPR_OPS:
    assert token_str not in OPS, token_str
    OPS[token_str] = id_

  # Tokens that look like / or ${ or @{
  triples = (
      meta.ID_SPEC.LexerPairs(Kind.Arith) +
      lex.OIL_LEFT_SUBS +
      lex.OIL_LEFT_UNQUOTED +
      lex.EXPR_WORDS
  )
  more_ops = {}
  for _, token_str, id_ in triples:
    assert token_str not in more_ops, token_str
    more_ops[token_str] = id_

  # Tokens that look like 'for'
  keyword_ops = {}
  for _, token_str, id_ in lex.EXPR_WORDS:  # for, in, etc.
    assert token_str not in keyword_ops, token_str
    keyword_ops[token_str] = id_

  if 0:
    from pprint import pprint
    pprint(OPS)
    print('---')
    pprint(more_ops)
    print('---')
    pprint(keyword_ops)
    print('---')

  tok_def = OilTokenDef(OPS, more_ops, keyword_ops)

  if action == 'marshal':  # generate the grammar and parse it
    grammar_path = argv[0]
    out_dir = argv[1]

    basename, _ = os.path.splitext(os.path.basename(grammar_path))

    # HACK for find:
    if basename == 'find':
      from tools.find import tokenizer as find_tokenizer
      tok_def = find_tokenizer.TokenDef()

    with open(grammar_path) as f:
      gr = pgen.MakeGrammar(f, tok_def=tok_def)

    marshal_path = os.path.join(out_dir, basename + '.marshal')
    with open(marshal_path, 'wb') as out_f:
      gr.dump(out_f)

    nonterm_path = os.path.join(out_dir, basename + '_nt.py')
    with open(nonterm_path, 'w') as out_f:
      gr.dump_nonterminals(out_f)

    log('Compiled %s -> %s and %s', grammar_path, marshal_path, nonterm_path)
    #gr.report()

  elif action == 'parse':  # generate the grammar and parse it
    # Remove build dependency
    from frontend import parse_lib
    from oil_lang import expr_parse

    grammar_path = argv[0]
    start_symbol = argv[1]
    code_str = argv[2]

    # For choosing lexer and semantic actions
    grammar_name, _ = os.path.splitext(os.path.basename(grammar_path))

    with open(grammar_path) as f:
      gr = pgen.MakeGrammar(f, tok_def=tok_def)

    arena = alloc.Arena()
    lex_ = MakeOilLexer(code_str, arena)

    is_expr = grammar_name in ('calc', 'grammar')

    parse_opts = parse_lib.OilParseOptions()
    parse_ctx = parse_lib.ParseContext(arena, parse_opts, {}, gr)
    p = expr_parse.ExprParser(parse_ctx, gr)
    try:
      pnode, _ = p.Parse(lex_, gr.symbol2number[start_symbol])
    except parse.ParseError as e:
      log('Parse Error: %s', e)
      return 1

    names = parse_lib.MakeGrammarNames(gr)
    p_printer = expr_parse.ParseTreePrinter(names)  # print raw nodes
    p_printer.Print(pnode)

    if is_expr:
      from oil_lang import expr_to_ast
      tr = expr_to_ast.Transformer(gr)
      if start_symbol == 'eval_input':
        ast_node = tr.Expr(pnode)
      else:
        ast_node = tr.VarDecl(pnode)
      ast_node.PrettyPrint()
      print()

  elif action == 'stdlib-test':
    # This shows how deep Python's parse tree is.  It doesn't use semantic
    # actions to prune on the fly!

    import parser  # builtin module
    t = parser.expr('1+2')
    print(t)
    t2 = parser.st2tuple(t)
    print(t2)

  else:
    raise RuntimeError('Invalid action %r' % action)
Пример #47
0
                        help='function_formula (use x as the variable name)')
arg_parser.add_argument('start_point', type=float, help='Start point')
arg_parser.add_argument('step', type=float, help='Step size')
arg_parser.add_argument('steps', type=int, help='Number of steps')
arg_parser.add_argument('precision', type=float, help='Desired precision')

args = arg_parser.parse_args()
print("---------")
print("Args")
print(args)
print("---------")

x_k = args.start_point
print(f"Starting from point {x_k}")

code = parser.expr(args.formula).compile()
print(code)

for i in range(args.steps):
    x = x_k
    x_k = x_k - (eval(code)) / derv(code, x_k, args.step)
    print(f'Current point is: {x_k}')
'''
Exercise 2
The task should be performed using the BagOfWords program from previous classes.
Make it so that punctuation, numbers and all other characters do not interfere with
parsing text. Run it on the text of the hamlet. How many times does the word hamlet appear?
  What are the ten most common words?
'''
from io import IOBase
import re
Пример #48
0
def eval_on_faces(obj, expr, solvars, phys):
    '''
    evaluate nodal valus based on preproceessed 
    geometry data

    to be done : obj should be replaced by a dictionary
    '''
    from petram.helper.variables import Variable, var_g

    if len(obj.ifaces) == 0: return None
    variables = []

    st = parser.expr(expr)
    code = st.compile('<string>')
    names = code.co_names

    g = {}

    for key in phys._global_ns.keys():
        g[key] = phys._global_ns[key]
    for key in solvars.keys():
        g[key] = solvars[key]

    ll_name = []
    ll_value = []
    var_g2 = var_g.copy()

    new_names = []
    for n in names:
        if (n in g and isinstance(g[n], Variable)):
            new_names.extend(g[n].dependency)
            new_names.append(n)
        elif n in g:
            new_names.append(n)

    for n in new_names:
        if (n in g and isinstance(g[n], Variable)):
            if not g[n] in obj.knowns:
                obj.knowns[g[n]] = (g[n].ncface_values(
                    ifaces=obj.ifaces,
                    irs=obj.irs,
                    gtypes=obj.gtypes,
                    locs=obj.ptx,
                    attr1=obj.elattr1,
                    attr2=obj.elattr2,
                    g=g,
                    knowns=obj.knowns,
                    mesh=obj.mesh()[obj.emesh_idx]))
            ll_name.append(n)
            ll_value.append(obj.knowns[g[n]])
        elif (n in g):
            var_g2[n] = g[n]

    if len(ll_value) > 0:
        val = np.array([
            eval(code, var_g2, dict(zip(ll_name, v))) for v in zip(*ll_value)
        ])
    else:
        # if expr does not involve Varialbe, evaluate code once
        # and generate an array
        val = np.array([eval(code, var_g2)] * len(obj.ptx))
    return val
Пример #49
0
    def __init__(self,  exprs,  ind_vars, l, g, real=True):
        ''' 
        this is complicated....
           elemental (or array) form 
            [1,a,3]  (a is namespace variable) is given as [[1, a (valued), 3]]

           single box
              1+1j   is given as '(1+1j)' (string)

           matrix
              given as string like '[0, 1, 2, 3, 4]'
              if variable is used it is become string element '['=variable', 1, 2, 3, 4]'
              if =Varialbe in matrix form, it is passed as [['Variable']]
        '''
        flag, exprs = try_eval(exprs, l, g)
        #print("after try_eval", flag, exprs)
        if not flag:
            if isinstance(exprs, str):
                exprs = [exprs]
            #elif isinstance(exprs, float):
            #    exprs = [exprs]               
            #elif isinstance(exprs, long):
            #    exprs = [exprs]
            elif isinstance(exprs, numbers.Number):
                 exprs = [exprs]               
            else:
               pass
        if isinstance(exprs, list) and isinstance(exprs[0], list):
            exprs = exprs[0]
        #dprint1("final exprs", exprs)
        self.l = {}
        #### TODO g must be copied since some may passs _global_ns.
        #### (I don't do it now since it requires a substantial testing)
        self.g = g  
        for key in l.keys():
           self.g[key] = l[key]
        self.real = real
        self.variables = []

        self.co = []
        for expr in exprs:
           if isinstance(expr, str):
               st = parser.expr(expr.strip())
               code= st.compile('<string>')
               names = code.co_names
               for n in names:
                  if (n in g and isinstance(g[n], NativeCoefficientGenBase)):
                      coeff_var = CoefficientVariable(g[n], l, g)
                      self.variables.append((n, coeff_var))
                  elif n in g and isinstance(g[n], Variable):
                      self.variables.append((n, g[n]))
                      for nn in g[n].dependency:
                          self.variables.append((nn, g[nn]))
                  else:
                      pass
               self.co.append(code)
           else:
               self.co.append(expr)
               
        # 'x, y, z' -> 'x', 'y', 'z'
        self.ind_vars = [x.strip() for x in ind_vars.split(',')]
        self.exprs = exprs
        self.flags = [isinstance(co, types.CodeType) for co in self.co]
        self.variables_dd = dict(self.variables)
Пример #50
0
 def test_deeply_nested_list(self):
     # XXX used to be 99 levels in 2.x
     e = self._nested_expression(93)
     st = parser.expr(e)
     st.compile()
Пример #51
0
 def test_two_args_to_expr(self):
     # See bug #12264
     with self.assertRaises(TypeError):
         parser.expr("a", "b")
Пример #52
0
 def _convert(self, source):
     """
     Translates a pype file to a python file
     """
     with open(source, 'r') as f:
         source = f.read()
     # Define token recognising regex, helpers
     tags = [r'<\?=', r'<\?', r'\?>']
     rTags = re.compile('(' + '|'.join(tags) + ')')
     rQuot = re.compile('(""")')
     rEol = re.compile('[\n]{1}')
     rWhite = re.compile(r'[ \f\t]*')
     eol = '\n'
     indent = ''
     # Convert
     tag_open = None
     out = ['import sys']
     for part in rTags.split(source):
         if part == '?>':
             if tag_open is None:
                 self.error = 'Closing tag found without opening tag'
                 raise PypeError(self.error)
             tag_open = None
         elif part == '<?' or part == '<?=':
             if tag_open is not None:
                 self.error = 'Nested opening tag found'
                 raise PypeError(self.error)
             tag_open = part
         elif part == '"""':
             out.append('me!')
             out.append(indent + 'sys.stdout.write(\'"""\')')
         elif tag_open == '<?':
             # Full python statement, remember final indenting
             lines = rEol.split(part)
             if lines:
                 line = lines.pop()
             else:
                 line = part
             m = rWhite.match(line)
             indent = line[0:m.end()]
             out.append(part)
         elif tag_open == '<?=':
             # Quick printing statement, python code must be expression
             part = part.strip()
             try:
                 test = parser.expr(part)
             except Exception as e:
                 msg = 'Code within <?= ?> tags can only contain a single' \
                       ' expression.'
                 err = traceback.format_exc().splitlines()
                 err.append(msg)
                 self.error = '\n'.join(err)
                 raise PypeError(msg)
             out.append(indent + 'sys.stdout.write(str(' + part + '))')
         else:
             # Non-python code, just print
             # Triple quoted strings should be handled separately
             for part in rQuot.split(part):
                 if part == '"""':
                     out.append(indent + 'sys.stdout.write(\'"""\')')
                     continue
                 # If part ends in a ", this will cause problems, so...
                 nQuotes = 0
                 while part[-1:] == '"':
                     part = part[0:-1]
                     nQuotes += 1
                 out.append(indent + 'sys.stdout.write(r"""' + part +
                            '""")')
                 if nQuotes > 0:
                     out.append(indent + 'sys.stdout.write(\'' +
                                '"' * nQuotes + '\')')
     return '\n'.join(out)
    bench("topdown", parse)
    bench("topdown pretokenized", lambda program: parse(program_list))

    tokenize_python = custom_tokenize_python
    bench("custom topdown", parse)

    if pytoken:
        tokenize_python = pytoken.token_list
        bench("built-in topdown", parse)

    print

    bench("built-in compile", lambda program: compile(program, "", "eval"))
    bench("parser.parse",
          lambda program: parser.st2tuple(parser.expr(program)))

    print

    bench("compiler.parse", lambda program: compiler.parse(program, "eval"))
    bench("compiler.compile",
          lambda program: compiler.compile(program, "", "eval"))

    sys.exit(0)

# samples
test("1")
test("+1")
test("-1")
test("1+2")
test("1+2+3")
Пример #54
0
def f(fx, x):
    f = parser.expr(fx).compile()
    return eval(f)
Пример #55
0
def parse_expr(expr, builder):
    # include line numbers in parse data so valid symbols are never of length 2
    return build(builder, parser.expr(expr).totuple(1)[1])
Пример #56
0
 def compile(self, formula, x0, x1, x2=0): #x0, x1
     return eval(parser.expr(formula).compile())
Пример #57
0
 def test_compile_expr(self):
     st = parser.expr('2 + 3')
     code = parser.compilest(st)
     self.assertEquals(eval(code), 5)
 def parseexpr(self, text):
     return self.transform(parser.expr(text))
Пример #59
0
    def graphClicked(self):
        '''
        Show the graph.
        '''
        pyFormula = self.formulaTxt.get()

        try:
            d = GenerateSymbols()
            formula = sympy.latex(sympy.simplify(eval(pyFormula, d)))
        except Exception:
            formula = pyFormula

        self.code = parser.expr(pyFormula).compile()

        self.a = float(self.intervalMinTxt.get())
        self.b = float(self.intervalMaxTxt.get())
        self.N = int(self.nTxt.get())

        # x and y values for the trapezoid rule
        x = np.linspace(self.a, self.b, self.N + 1)
        y = self.f(x)

        # X and Y values for plotting y = f(x)
        X = np.linspace(self.a, self.b, 1000)
        Y = self.f(X)
        plt.plot(X, Y)  # Draw the line function

        ymax = 0
        for i in range(self.N):
            xs = [x[i], x[i], x[i + 1], x[i + 1]]
            ys = [0, y[i], y[i + 1], 0]
            plt.fill(xs, ys, 'b', edgecolor='b',
                     alpha=0.2)  # Draw the trapezoids
            if max(ys) > ymax:
                ymax = max(ys)

        # Calculate the area and errors
        tAprox = self.trapz()
        tReal = np.trapz(Y, x=X, dx=2)
        ae = np.abs(tReal - tAprox)
        re = np.abs((tReal - tAprox) / tReal)

        plt.title('Trapezoid Rule')  # Info box
        textstr = '\n'.join(
            ('f(x) = $%s$' % formula,
             'interval = [{0}, {1}]'.format(self.a,
                                            self.b), 'N = {0}'.format(self.N),
             'Area = ' + '%.5f' % tAprox, 'Absolute error: ' + '%.5f' % ae,
             'Relative error: ' + '%.5f' % re))
        # These are matplotlib.patch.Patch properties
        props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)

        # Place a text box in upper left in axes coords
        # Build a rectangle in axes coords
        left, width = 0, self.b
        bottom, height = 0, ymax
        right = left + width
        top = bottom + height
        plt.text(right,
                 top,
                 textstr,
                 fontsize=10,
                 horizontalalignment='right',
                 verticalalignment='top',
                 bbox=props)

        plt.grid(True)
        plt.show()
                                 default=135,
                                 type=np.int64)
    argument_parser.add_argument('-xavier_initialization',
                                 action='store_true',
                                 default=False)
    argument_parser.add_argument('-max_steps',
                                 action='store',
                                 default=1000,
                                 type=np.int32)
    argument_parser.add_argument('-replay_start',
                                 action='store',
                                 default=1000,
                                 type=np.int32)
    args = argument_parser.parse_args()

    alpha_code = parser.expr(args.alpha).compile()
    args.alpha = eval(args.alpha)
    """ Directories """
    working_directory = os.getcwd()
    database_path = os.path.join(working_directory, 'Experiment_Engine',
                                 'sampleOnPolicy.npy')
    assert os.path.isfile(database_path)
    results_directory = os.path.join(working_directory, "Results",
                                     "Mountain_Car_Prediction")
    if not os.path.exists(results_directory):
        os.makedirs(results_directory)
    run_results_directory = os.path.join(results_directory, args.name)
    if not os.path.exists(run_results_directory):
        os.makedirs(run_results_directory)

    exp_params = args