Example #1
0
    def set_equations(self, conf_equations=None, user=None,
                      keep_solvers=False, make_virtual=False):
        """
        Set equations of the problem using the `equations` problem
        description entry.

        Fields and Regions have to be already set.
        """
        conf_equations = get_default(conf_equations,
                                     self.conf.get_default_attr('equations',
                                                                None))

        self.set_variables()
        variables = Variables.from_conf(self.conf_variables, self.fields)

        self.set_materials()
        materials = Materials.from_conf(self.conf_materials, self.functions)

        self.integrals = self.get_integrals()
        equations = Equations.from_conf(conf_equations, variables,
                                        self.domain.regions,
                                        materials, self.integrals,
                                        user=user,
                                        make_virtual=make_virtual)

        self.equations = equations

        if not keep_solvers:
            self.solvers = None
Example #2
0
    def set_equations(self, conf_equations=None, user=None,
                      keep_solvers=False, make_virtual=False):
        """
        Set equations of the problem using the `equations` problem
        description entry.

        Fields and Regions have to be already set.
        """
        conf_equations = get_default(conf_equations,
                                     self.conf.get('equations', None))

        self.set_variables()
        variables = Variables.from_conf(self.conf_variables, self.fields)

        self.set_materials()
        materials = Materials.from_conf(self.conf_materials, self.functions)

        self.integrals = self.get_integrals()
        equations = Equations.from_conf(conf_equations, variables,
                                        self.domain.regions,
                                        materials, self.integrals,
                                        user=user)

        self.equations = equations

        if not keep_solvers:
            self.solvers = None
Example #3
0
    def __init__(self):
        is_debug = self._debug_detect()
        if not is_debug:
            import RPi.GPIO as GPIO
            GPIO.setwarnings(False)
            GPIO.setmode(GPIO.BCM)

        buttons = Buttons_HW(is_debug)
        buttons.listen_buttons(self._buttons_callback)

        self._game_select = GameSelect()
        self._game_select.set_callback(self._change_menu_mode)

        self._equations = Equations()
        self._equations.set_callback(self._change_menu_mode)

        self._display = Display_LCD(is_debug, self._draw)

        if is_debug:
            self._draw(self._display.debug_draw())
            self._display.debug_show()
Example #4
0
def assemble_by_blocks(
    conf_equations, problem, conf_ebc=None, conf_epbc=None, dw_mode="matrix", restore_variables=True
):
    """Instead of a global matrix, return its building blocks as defined in
    `conf_equations`. The name and row/column variables of each block have to
    be encoded in the equation's name, as in:

    conf_equations = {
      'A,v,u' : "dw_lin_elastic_iso.i1.Y2( inclusion.lame, v, u )",
    }
    """
    equations = Equations.from_conf(conf_equations)
    equations.setup_terms(problem.domain.regions, problem.variables, problem.materials)

    var_names = equations.get_variable_names()
    conf_variables = select_by_names(problem.conf.variables, var_names)
    problem.set_variables(conf_variables)

    dummy = problem.create_state_vector()

    indx = problem.variables.get_indx
    matrices = {}
    for key, mtx_term in conf_equations.iteritems():
        ks = key.split(",")
        mtx_name, var_names = ks[0], ks[1:]
        output(mtx_name, var_names)

        problem.set_equations({"eq": mtx_term})
        problem.time_update(conf_ebc=conf_ebc, conf_epbc=conf_epbc)

        ir = indx(var_names[0], stripped=True, allow_dual=True)
        ic = indx(var_names[1], stripped=True, allow_dual=True)

        mtx = eval_term_op(dummy, mtx_term, problem, dw_mode="matrix")
        matrices[mtx_name] = mtx[ir, ic]

    if restore_variables:
        problem.set_variables()

    return matrices
Example #5
0
    def set_equations(self, conf_equations, user=None, cache_override=None, keep_solvers=False):
        equations = Equations.from_conf(conf_equations)
        equations.setup_terms(self.domain.regions, self.variables, self.materials, user)

        i_names = equations.get_term_integral_names()
        self.integrals = Integrals.from_conf(self.conf.integrals, i_names)
        self.integrals.set_quadratures(fea.collect_quadratures())

        self.geometries = {}
        equations.describe_geometry(self.geometries, self.variables, self.integrals)

        ##         print self.geometries
        ##         pause()
        # Call after describe_geometry(), as it sets ap.surface_data.
        self.variables.setup_dof_conns()

        if cache_override is None:
            cache_override = get_default_attr(self.conf.fe, "cache_override", True)
        equations.set_cache_mode(cache_override)

        self.equations = equations

        if not keep_solvers:
            self.solvers = None
Example #6
0
def create_evaluable(expression, fields, materials, variables, integrals,
                     update_materials=True,
                     ebcs=None, epbcs=None, lcbcs=None, ts=None, functions=None,
                     auto_init=False, mode='eval', extra_args=None,
                     verbose=True, kwargs=None):
    """
    Create evaluable object (equations and corresponding variables)
    from the `expression` string.

    Parameters
    ----------
    expression : str
        The expression to evaluate.
    fields : dict
        The dictionary of fields used in `variables`.
    materials : Materials instance
        The materials used in the expression.
    variables : Variables instance
        The variables used in the expression.
    integrals : Integrals instance
        The integrals to be used.
    update_materials : bool
        Call time update function of the materials. Safe but can be slow.
    ebcs : Conditions instance, optional
        The essential (Dirichlet) boundary conditions for 'weak'
        mode.
    epbcs : Conditions instance, optional
        The periodic boundary conditions for 'weak'
        mode.
    lcbcs : Conditions instance, optional
        The linear combination boundary conditions for 'weak'
        mode.
    ts : TimeStepper instance, optional
        The time stepper.
    functions : Functions instance, optional
        The user functions for boundary conditions, materials
        etc.
    auto_init : bool
        Set values of all variables to all zeros.
    mode : one of 'eval', 'el_avg', 'qp', 'weak'
        The evaluation mode - 'weak' means the finite element
        assembling, 'qp' requests the values in quadrature points,
        'el_avg' element averages and 'eval' means integration over
        each term region.
    extra_args : dict, optional
        Extra arguments to be passed to terms in the expression.
    verbose : bool
        If False, reduce verbosity.
    kwargs : dict, optional
        The variables (dictionary of (variable name) : (Variable
        instance)) to be used in the expression.

    Returns
    -------
    equation : Equation instance
        The equation that is ready to be evaluated.
    variables : Variables instance
        The variables used in the equation.
    """
    if kwargs is None:
        kwargs = {}

    domain = fields[fields.keys()[0]].domain
    caches = DataCaches()

    # Create temporary variables.
    aux_vars = Variables(variables)

    if extra_args is None:
        extra_args = kwargs

    else:
        extra_args = copy(extra_args)
        extra_args.update(kwargs)

    equations = Equations.from_conf({'tmp' : expression},
                                    aux_vars, domain.regions,
                                    materials, integrals,
                                    setup=False,
                                    caches=caches, user=extra_args,
                                    verbose=verbose)
    equations.collect_conn_info()
    equations.assign_geometries()

    # The true variables used in the expression.
    variables = equations.variables
    if auto_init:
        for var in variables:
            var.init_data(step=0)

    if mode == 'weak':
        setup_dof_conns(equations.conn_info)
        if update_materials:
            materials.time_update(ts, domain, equations, verbose=False)
        equations.time_update(ts, ebcs, epbcs, lcbcs, functions)

    else:
        setup_extra_data(equations.conn_info)
        if update_materials:
            materials.time_update(ts, domain, equations, verbose=False)

    return equations, variables
Example #7
0
from equations import Equations
from random import randint
import subprocess, os, platform, sys

user_input = ''
args = []
print("Loading ...")
user_equation = Equations()

def printOptions():
    print("Please pass arguments a number/symbol at a time")
    print("Acceptable inputs are:")
    print("Any one digit number (0-9)")
    print("Addition, Subtraction, Multiplication and Division symbols (+, -, *, /)")
    print("If you would like to input numbers with multiple digits, place them one after another")
    print("Input 's' to have the program solve the inputted function")
    print("Input 'r' to reset the equation")
    print("Input 'd' to see a simple demo of the program")
    print("Input 'e' to solve a random equation")
    print("Input 'p' to print out your current list of arguments")
    print("Input 'u' to remove the last item added to the arguments")
    print("Input 'q' to quit the program")
    print("Input 'c' to clear the terminal and list options again")


symbol_inputs = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '-', '*', '/',]

printOptions()

while True:
    user_input = input("Enter Symbol: ")
def evaluate_infix(expression):
    """
    The highest level function for evaluation of expressions
    :param expression: string representing an infix expression
    :return: err_start, err_end, message, interpreted expression in case of any error,
    None, None, solution, interpreted_expression otherwise
    """
    pat_unallowed = re.compile(r'([^A-Za-z0-9+\-*/=.,\s()])')
    if len(pat_unallowed.findall(expression)) > 0:
        pos = next(pat_unallowed.finditer(expression)).start()
        return pos, pos, "Unallowed symbol detected: %s" % expression[
            pos], expression

    if "=" in expression:  # Solve an equation
        if expression.count("=") > 1:
            pos = expression.index("=") + expression[expression.index("=") +
                                                     1:].index("=") + 1
            return pos, pos, "More than one '=' symbols in expression can't be interpreted", expression

        result = Equations.solve(*expression.split("="))
        if len(result) == 4:
            return result
        else:
            try:
                varname = result[0]
                polynomial = result[1]
                interpreted_expression = result[2]
            except (TypeError, IndexError):
                return -1, -1, "Something has gone terribly wrong", expression
    else:
        postfix_expression = PostfixExpression(expression)
        interpreted_expression = postfix_expression.interpreted_expression
        if postfix_expression.error_msg is not None:
            pos = postfix_expression.error_place
            return pos[0], pos[
                1], postfix_expression.error_msg, interpreted_expression
        else:
            varname = ""
            polynomial = postfix_expression.result.polynomial

    solver = PolynomialSolver()
    try:
        # Take the first (and the only) solution
        result = solver.solve(polynomial)[0]
    except NotImplementedError as e:
        return -1, -1, e.args[0], expression
    if result[1] == 0:
        if '=' in expression:
            return -1, -1, "The expression doesn't have a variable " + \
                   "(or the coefficient before it is 0), but " + \
                   "has a '=' sign. It cannot be interpreted.", expression
        # Formatting the result
        num_result = result[0] if math.floor(
            result[0]) != result[0] else math.floor(result[0])
        return None, None, str(num_result), interpreted_expression
    else:
        if '=' not in expression:
            return -1, -1, "The expression has variables but doesn't have '=' sign." + \
                   "Should it be treated as equation?", expression
        # Formatting the result
        num_result = result[0] if math.floor(
            result[0]) != result[0] else math.floor(result[0])
        return None, None, varname + ' = ' + str(
            num_result), interpreted_expression
Example #9
0
class PiGame:

    _index = 0
    _display = None

    _menu_mode = MenuMode.GAME_SELECT

    _game_select = None
    _equations = None

    def __init__(self):
        is_debug = self._debug_detect()
        if not is_debug:
            import RPi.GPIO as GPIO
            GPIO.setwarnings(False)
            GPIO.setmode(GPIO.BCM)

        buttons = Buttons_HW(is_debug)
        buttons.listen_buttons(self._buttons_callback)

        self._game_select = GameSelect()
        self._game_select.set_callback(self._change_menu_mode)

        self._equations = Equations()
        self._equations.set_callback(self._change_menu_mode)

        self._display = Display_LCD(is_debug, self._draw)

        if is_debug:
            self._draw(self._display.debug_draw())
            self._display.debug_show()

    def _draw(self, draw):
        if self._menu_mode == MenuMode.GAME_SELECT:
            self._game_select.draw(draw)
        elif self._menu_mode == MenuMode.EQUATIONS:
            self._equations.draw(draw)
        elif self._menu_mode == MenuMode.MATH_SQUARE:
            draw.text((2, 2), "TODO", fill="white")

    def _buttons_callback(self, button):
        print(button)
        if self._menu_mode == MenuMode.GAME_SELECT:
            self._game_select.handle_button(button)
        elif self._menu_mode == MenuMode.EQUATIONS:
            self._equations.handle_button(button)
        elif self._menu_mode == MenuMode.MATH_SQUARE:
            pass

        if self._debug_detect():
            self._display.debug_clear()
            self._draw(self._display.debug_draw())
            self._display.debug_show()

    def _change_menu_mode(self, menu_mode):
        self._menu_mode = menu_mode

    def _debug_detect(self):
        try:
            # Check if user named `pi` exists
            # If exists then we known that code is running on Raspberry
            pwd.getpwnam('pi')
            return False
        except KeyError:
            return True
Example #10
0
def main():
    obj = Equations()
    while obj.runloop:
        obj.loop()