def __init__(self, observer: Observer, functions: dict, combine_binnings: bool = True): """Initializes a new evaluator. Args: observer: Observer to use. functions: Dict of functions for the different filters. combine_binnings: Whether different binnings use the same functions. """ # init self._observer = observer self._time = None self._m = None self._b = None self._combine_binnings = combine_binnings # parse function if functions is None: functions = {} if combine_binnings: # in the simple case, the key is just the filter self._functions = { filter_name: Parser().parse(func) for filter_name, func in functions.items() } else: # in case of separate binnings, the key to the functions dict is a tuple of binning and filter self._functions = {} for binning, func in functions.items(): for filter_name, func in func.items(): self._functions[binning, filter_name] = Parser().parse(func)
def test_custom_functions_with_inline_strings(self): parser = Parser() expr = parser.parse("func(1, \"func(2, 4)\")") self.assertEqual(expr.variables(), ['func']) expr = parser.parse("func(1, 'func(2, 4)')") self.assertEqual(expr.variables(), ['func']) parser2 = Parser(string_literal_quotes=("'")) expr = parser2.parse("func(1, \"func(2, 4)\")") self.assertEqual(expr.variables(), ['func', "\"func(2, 4)\""]) expr = parser2.parse("func(1, 'func(2, 4)')") self.assertEqual(expr.variables(), ['func'])
def __init__(self, ruleType, left_context, predecessor, right_context, condition="", successor=[], probs=[]): # RuleTypes: self.TYPE_OL = 0 #context free rule self.TYPE_L1L = 1 #left context rule self.TYPE_R1L = 2 #right context rule self.TYPE_2L = 3 #left and right context rule # assigning variables self.ruleType = ruleType self.parser = Parser() self.predecessorSymbol = predecessor.symbol # the symbol of the predecessor self.symParam = predecessor.param # a list of symbolic representations of variables self.successor = successor # list of symbols and for every parameter an expression [[ "symbol", [param]], [...]] in case of stochastic a list of lists self.left_context = left_context self.right_context = right_context self.isStochastic = (probs != []) self.probs = probs # if stochastic then this contains a list of the probabilities # if the condition is non-empty parse it to an expression if condition != "": self.condition = self.parser.parse( condition) # the condition in string form else: self.condition = condition
def result_expr(self, values): p = Parser() return p.parse(self.exp).evaluate({ 'x': values[0], 'y': values[1], 'z': values[2] })
def gestionSecante (expresion, a, b, cifras, max_iteraciones, area_texto): area_texto.delete('1.0', 'end') parser = Parser() try: funcion = parser.parse(expresion) except Exception as exc: area_texto.insert('end', "Ha ocurrido un error al procesar las funciones, por favor revise los campos.\n") return try: inicio_a = (float)(a) inicio_b = (float)(b) cifras_significativas = (int)(cifras) tolerancia = calcularTolerancia(cifras_significativas) maximo_iteraciones = (int)(max_iteraciones) imprimirEncabezadoTabla(['n', 'x_n', 'f(x_n)', 'error'], area_texto) raiz = secante(funcion, inicio_a, inicio_b, tolerancia, 0.0005, maximo_iteraciones, area_texto) area_texto.insert('end', '\n') area_texto.insert('end', "La aproximación a la raíz es: " + str(raiz) + ".") except ValueError: area_texto.insert('end', "Uno o más de los valores introducidos no son numéricos. Por favor revise los campos.\n") except IteracionesInvalidasExcepcion as exc: area_texto.delete('1.0', 'end') area_texto.insert('end', exc.mensaje + "\n") except NumeroCercanoCeroExcepcion as exc2: area_texto.insert('end', exc2.mensaje + "\n") except MetodoFallidoExcepcion as exc3: area_texto.insert('end', exc3.mensaje + "\n") except Exception as exc4: area_texto.insert('end', "Ha ocurrido un error.\n" + exc4.message)
def setViaFile(cls, my_filename): dirname = os.path.dirname(__file__) wb = load_workbook(filename = os.path.join(dirname, './Rules/'+my_filename) ) ws = wb.active Distributions = [] for row in ws: Distribution = [] for enumerator, cell in enumerate(row): if cell.value == None: continue if str(cell.value).find('SUM') != -1: continue if re.search('[а-яА-ЯёЁ]|http', str(cell.value)): continue #if cell.value == "?": #print("Hey!!!!", my_filename) if cell.value == "f:": print("Hello!") i, j = cell.row, cell.col_idx str_expr = str(ws.cell(row = i, column = j + 1).value) print(str_expr) parser = Parser() expr = parser.parse(str_expr) Distribution = Distribution + [float(expr.evaluate({'x':x})) for x in range(ws.cell(row = i, column = j + 2).value, ws.cell(row = i, column = j + 3).value)] print(Distribution) break Distribution.append(cell.value) Distributions.append(Distribution) return cls(Distributions)
def gdal_mapcalc(expression, exp_val_paths, outRaster, template_rst, outNodata=-99999): """ GDAL Raster Calculator TODO: Check if rasters dimensions are equal """ import numpy as np from osgeo import gdal from py_expression_eval import Parser from glass.g.prop.img import get_nd from glass.g.wt.rst import obj_to_rst parser = Parser() EXPRESSION = parser.parse(expression) evalValue = {} noDatas = {} for x in EXPRESSION.variables(): img = gdal.Open(exp_val_paths[x]) arr = img.ReadAsArray().astype(float) evalValue[x] = arr noDatas[x] = get_nd(img) result = EXPRESSION.evaluate(evalValue) for v in noDatas: np.place(result, evalValue[v]==noDatas[v], outNodata) # Write output and return return obj_to_rst(result, outRaster, template_rst, noData=outNodata)
def calculate_price(expressionString, data, numeric=True): """Calculates price based on the expression. For example, "participants.age * 12" "participants * 12" will use participants' length if it is an array. todo: base 64 encode here. """ from .defaultContext import DEFAULT_CONTEXT if ":" in expressionString: expressionString = expressionString.replace(":", DELIM_VALUE) expressionString = expressionString.replace("$", "") parser = Parser() expr = parser.parse(expressionString) context = {} for variable in expr.variables(): escapedVariable = variable.replace(".", DOT_VALUE) if escapedVariable.startswith("CFF_FULL_"): _, actual_variable = escapedVariable.split("CFF_FULL_") context[escapedVariable] = parse_number_formula( data, actual_variable.replace(DOT_VALUE, "."), False) else: context[escapedVariable] = parse_number_formula( data, escapedVariable.replace(DOT_VALUE, ".")) expressionString = expressionString.replace(variable, escapedVariable) context = dict(context, **DEFAULT_CONTEXT) price = parser.parse(expressionString).evaluate(context) if not numeric: return price return ceil(float(price) * 100) / 100
def gestionTrapecioConocida (expresion, a, b, trapecios, area_texto): area_texto.delete('1.0', 'end') parser = Parser() try: funcion = parser.parse(expresion) except Exception as exc: area_texto.insert('end', "Ha ocurrido un error al procesar la función, por favor revise los campos.\n") return try: lim_inferior = (float)(a) lim_superior = (float)(b) if lim_inferior < lim_superior: numero_trapecios = (int)(trapecios) integral = integracionTrapecioConocida(funcion, lim_inferior, lim_superior, numero_trapecios) area_texto.insert('end', '\n') area_texto.insert('end', "La aproximación a la integral es: " + str(integral) + ".") else: area_texto.insert('end', "El límite superior debe ser mayor al inferior, por favor revise los campos.") except ValueError: area_texto.insert('end', "Uno o más de los valores introducidos no son numéricos. Por favor revise los campos.\n") except NumeroParticionesInvalidoExcepcion as exc: area_texto.insert('end', exc.mensaje + "\n") except Exception as exc2: area_texto.insert('end', "Ha ocurrido un error.\n" + exc2.message)
def evaluarExpresion(expresion: str, value=255): parser = Parser() try: response = parser.parse(expresion).evaluate({'x': value}) return response except Exception as e: return False
def is_expression_valid(expression: str, alias_list: list) -> bool: """ Check if a mathematical string expression is valid by attempting to parse it and checking if all the variables in it exist in the aliases list. Parameters ---------- expression : str String containing mathematical expression alias_list : list List of strings containing all the aliases in display Returns ------- bool True for valid expression, otherwise its false. """ parser = Parser() try: expr_var = parser.parse(expression) except Exception: return False else: return all(item in alias_list for item in expr_var.variables())
def test_parser(self): parser = Parser() self.assertEqual(parser.parse('2 * 3').evaluate({}), 6) self.assertEqual(parser.parse('2 ^ x').evaluate({'x': 3}), 8) self.assertEqual(parser.parse('2 * x + 1').evaluate({'x': 3}), 7) self.assertEqual(parser.parse('2 + 3 * x').evaluate({'x': 4}), 14) self.assertEqual(parser.parse('(2 + 3) * x').evaluate({'x': 4}), 20) self.assertEqual(parser.parse('2-3^x').evaluate({'x': 4}), -79) self.assertEqual(parser.parse('-2-3^x').evaluate({'x': 4}), -83) self.assertEqual(parser.parse('-3^x').evaluate({'x': 4}), -81) self.assertEqual(parser.parse('(-3)^x').evaluate({'x': 4}), 81) self.assertEqual(parser.parse('2*x + y').evaluate({'x': 4, 'y': 1}), 9) # test substitute expr = parser.parse('2 * x + 1') expr2 = expr.substitute('x', '4 * x') # ((2*(4*x))+1) self.assertEqual(expr2.evaluate({'x': 3}), 25) # test simplify expr = parser.parse('x * (y * atan(1))').simplify({'y': 4}) self.assertIn('x*3.141592', expr.toString()) self.assertEqual(expr.evaluate({'x': 2}), 6.283185307179586) # test variables expr = parser.parse('x * (y * atan(1))') self.assertEqual(expr.variables(), ['x', 'y']) self.assertEqual(expr.simplify({'y': 4}).variables(), ['x'])
def gestionPuntoFijo (expresion_f, expresion_g, punto_inicio, cifras, max_iteraciones, area_texto): area_texto.delete('1.0', 'end') parser = Parser() try: funcion_f = parser.parse(expresion_f) funcion_g = parser.parse(expresion_g) except Exception as exc: area_texto.insert('end', "Ha ocurrido un error al procesar las funciones, por favor revise los campos.\n") return try: inicio = (float)(punto_inicio) cifras_significativas = (int)(cifras) tolerancia = calcularTolerancia(cifras_significativas) maximo_iteraciones = (int)(max_iteraciones) imprimirEncabezadoTabla(['n', 'p_n', 'f(p_n)', 'error'], area_texto) raiz = puntoFijo(funcion_g, inicio, tolerancia, maximo_iteraciones, area_texto) area_texto.insert('end', '\n') area_texto.insert('end', "La aproximación a la raíz es: " + str(raiz) + ".") except ValueError: area_texto.insert('end', "Uno o más de los valores introducidos no son numéricos. Por favor revise los campos.\n") except IteracionesInvalidasExcepcion as exc: area_texto.delete('1.0', 'end') area_texto.insert('end', exc.mensaje + "\n") except MetodoFallidoExcepcion as exc2: area_texto.insert('end', exc2.mensaje + "\n") except Exception as exc3: area_texto.insert('end', "Ha ocurrido un error.\n" + exc3.message)
def update_apps_verification(): print('Check the users are verified for the apps') parser = Parser() apps = {app["_key"]: app['verification'] for app in db['apps'] if app.get('verification')} for user in db['users']: verifications = get_user_verification(user['_key']) for app in apps: try: expr = parser.parse(apps[app]) variables = expr.variables() verifications.update( {k: False for k in variables if k not in verifications}) verified = expr.evaluate(verifications) except: print('invalid verification expression') continue if verified and app not in verifications: db['verifications'].insert({ 'app': True, 'name': app, 'user': user['_key'], 'timestamp': int(time.time() * 1000) }) elif not verified and app in verifications: db['verifications'].delete_match({ 'app': True, 'name': app, 'user': user['_key'] })
def calculate_worker(self, task): logger.debug('Calculate task: ', task) parser = Parser() expression_id = task['expression_id'] expression = task['expression'] variables = task['variables'] signal.signal(signal.SIGALRM, signal_handler) signal.alarm(CALCULATION_TIMEOUT) try: result = parser.parse(expression).evaluate(variables) error_code = 0 except ZeroDivisionError: result = None error_code = 1 # ZeroDivisionError except OverflowError: result = None error_code = 2 # OverflowError except TimeoutError: result = None error_code = 3 # Calculation TimeoutError except Exception as e: logger.warning( f"Unexpected error while calculating task: {task}; error: ", e) result = None error_code = 4 # UnexpectedError finally: signal.alarm(0) res = (expression_id, expression, json.dumps(variables), result, error_code) result_queue.put(res)
def parse_expression(args): """generate data from a parsed expression Parameters ---------- expression = an expression to parse vars : Each key is a the variable name and the value is a DataValue to use in the expression Returns ------- a DataValue which is the result of the expression Raises ------ AttributeError if no attribute, value pair or dict is specified. """ verbose = False #make this more robust and test it XXX expression = args["expression"] vars = args["vars"] if verbose: print("expression:", pformat(expression), "\nvars:", pformat(vars)) parser = Parser() result = parser.parse(expression).evaluate(vars) return {'value': DV.DataValue(result)}
def post_expression(): try: raw_json = request.get_json() expression = raw_json['expression'] variables = raw_json['variables'] except TypeError: return jsonify_msg('No JSON found'), 400 except KeyError: return jsonify_msg('JSON has a wrong structure'), 400 try: parser = Parser() # mathematical expression validation parsed_expression = parser.parse(expression) # "py_expression_eval" uses Exception class for all exceptions except devision by zero and overflow :( except Exception: return jsonify_msg('Error occured while parsing expression'), 400 # variables matching validation variables_set = set(parsed_expression.variables()) if variables_set != set(variables): return jsonify_msg('JSON["variables"] does not match with variables in expression'), 400 expression_id = db.put_task(expression, variables) return jsonify(expression_id[0]), 200
def test_custom_functions(self): parser = Parser() def testFunction0(): return 13 def testFunction1(a): return 2 * a + 9 def testFunction2(a, b): return 2 * a + 3 * b # zero argument functions don't currently work # self.assertEqual(parser # .parse('testFunction()') # .evaluate({"testFunction":testFunction0}),13) self.assertExactEqual( parser.parse('testFunction(x)').evaluate({ "x": 2, "testFunction": testFunction1 }), 13) self.assertExactEqual( parser.parse('testFunction(x , y)').evaluate({ "x": 2, "y": 3, "testFunction": testFunction2 }), 13) # Add some "built-in" functions def mean(*xs): return sum(xs) / len(xs) parser.functions['mean'] = mean def counter(initial): class nonlocals: x = initial def count(increment): nonlocals.x += increment return nonlocals.x return count parser.functions['count'] = counter(0) self.assertEqual(parser.parse("mean(xs)").variables(), ["xs"]) self.assertEqual(parser.parse("mean(xs)").symbols(), ["mean", "xs"]) self.assertEqual( parser.evaluate("mean(xs)", variables={"xs": [1, 2, 3]}), 2) self.assertExactEqual( parser.evaluate("count(num)", variables={"num": 5}), 5) self.assertExactEqual( parser.evaluate("count(num)", variables={"num": 5}), 10)
def update_index_by_variable_name_appearing_in_formula(index_by_variable_name, formula): parser_formula = Parser() try: expr = parser_formula.parse(formula) except Exception, e: print formula raise (e)
def evaluate_rules(city, temp, n_rules): parser = Parser() for note_rule in n_rules: if parser.parse(note_rule['rule']).evaluate({"t": temp, "city": city}): return note_rule["note"] return ''
def calculate(expression): """ This function will calculate the result of the mathematical expression :param expression: the expression to be calculated/evaluated (str) :return: the result of the calculation (float or int) """ parser = Parser() return parser.parse(expression).evaluate({})
def test_custom_functions_substitute_strings(self): def func(var, str): if str == "custom text": return 1 return 0 parser = Parser() expr = parser.parse("func(1, \"custom text\")") self.assertEqual(expr.evaluate({"func": func}), 1)
def update_index_by_variable_name_appearing_in_formula(index_by_variable_name, formula): parser_formula = Parser() expr = parser_formula.parse(formula) formula_variables = expr.variables() components = dict( (formula_variable, {'code': formula_variable}) for formula_variable in formula_variables ) index_by_variable_name.update(components) return index_by_variable_name
def calculate(self, calculation): if calculation: try: # Solve formula and display it in entry # which is pointed at by display parser = Parser() self.display.text = str(parser.parse(calculation).evaluate({})) except Exception: self.display.text = "Error"
def evaluate_expression(self, s, monthly, calc=None): parse = Parser() e = self.get_expression(s) expr = parse.parse(e) vars = expr.variables() resolved_vars = self.lookup_vars(vars, monthly, calc) value = expr.evaluate(resolved_vars) return value
async def calc(self, ctx, *, message=None): if message is not None: try: parser = Parser() res = parser.parse(message).evaluate({}) answer = discord.Embed(title="🤖 Calculator", color=0x149FEA) answer.add_field(name=f"{message} = ", value=f"{res}") await ctx.send(embed=answer) except (ValueError, Exception): await ctx.send("Invalid Input.")
def __init__(self, targetFunction, a, b, delta, eps): self.targetExpression = targetFunction self.a = a self.b = b self.delta = delta self.eps = eps self.solution.clear() self.solutionEval.clear() self.expression = Parser().parse(self.targetExpression)
def get_y(): parser = Parser() y = [] try: expr = parser.parse(f_str) for _x in x: y.append(expr.evaluate({'x': _x})) return y except Exception: return [0] * len(x)
def test_custom_functions_substitute_strings(self): def func(var, str): if str == "custom text": return 1 if str == "foo": return 2 return 0 parser = Parser() expr = parser.parse("func(1, \"custom text\")") self.assertEqual(expr.evaluate({"func": func}), 1) parser = Parser(string_literal_quotes=("'")) expr = parser.parse("func(1, \"custom text\")") self.assertEqual( expr.evaluate({ "func": func, "\"custom text\"": "foo" }), 2)
def _evaluate(cls, models, formula): """ Parse a string into an arithmetic expression. Parameters ---------- models : list List of `Layer` objects that correspond to the given variables. formula : str A string describing the arithmetic operations to perform. """ try: parser = Parser() expr = parser.parse(formula) except: return # Extract variables vars = expr.variables() # List the models in the same order as the variables sorted_models = [m for v in vars for m in models if m.name == v] if len(sorted_models) > len(vars): logging.error("Incorrect model arithmetic formula: the number " "of models does not match the number of variables.") return elif len(sorted_models) < len(vars): extras = [ x for x in vars if x not in [y.name for y in sorted_models] ] for extra in extras: matches = re.findall('([\+\*\-\/]?\s?{})'.format(extra), formula) for match in matches: formula = formula.replace(match, "") try: expr = parser.parse(formula) vars = expr.variables() except: logging.error("An error occurred.") return try: result = parser.evaluate( expr.simplify({}).toString(), dict(pair for pair in zip(vars, sorted_models))) return result except (AttributeError, TypeError) as e: logging.error("Incorrectly formatted model formula: %s", e)