Ejemplo n.º 1
0
    def convert_to_enum(self, cls, use_type='string'):
        Writer.convert_to_enum(self, cls, use_type)
        function = Function()
        function.name = '__toString'
        function.operations.append('return $this->_value;')
        cls.functions.append(function)

        function = Function()
        function.name = 'str'
        function.operations.append('return (string)$this;')
        cls.functions.append(function)

        for i, member in enumerate(cls.members):
            if member.name == '_value':
                member.type = 'string'

        function = Function()
        function.name = 'set'
        function.args.append(['value', ''])
        function.operations.append('$this->_value = $value;')
        cls.functions.append(function)

        function = Function()
        function.name = 'serialize'
        cls.functions.append(function)

        function = Function()
        function.name = 'deserialize'
        cls.functions.append(function)
Ejemplo n.º 2
0
    def create_deserialize(self):
        function = Function()
        function.name = 'deserialize'
        function.args.append(['json', ''])
        self.functions.append(function)

        function = Function()
        function.name = 'serialize'
        function.args.append(['json', ''])
        self.functions.append(function)
Ejemplo n.º 3
0
Archivo: Ear.py Proyecto: RemiBe/ear
    def __init__(self):
        self.root = Tk()
        self.root.title("Ear - Explicit Algorithm Representation")

        self.mainframe = ttk.Frame(self.root, padding="3 3 12 12")
        self.mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=1)

        # Buttons
        self.state = None
        fbutton = ttk.Button(self.mainframe, text="Function", command=lambda: self.change_state(STATE_FUNC))
        cbutton = ttk.Button(self.mainframe, text="Case", command=lambda: self.change_state(STATE_CASE))
        abutton = ttk.Button(self.mainframe, text="Arrow", command=lambda: self.change_state(STATE_ARROW))
        rbutton = ttk.Button(self.mainframe, text="Remove", command=lambda: self.change_state(STATE_RM))
        ibutton = ttk.Button(self.mainframe, text="Import", command=self.import_event)
        ebutton = ttk.Button(self.mainframe, text="Export", command=self.export)
        fbutton.grid(column=1, row=1)
        cbutton.grid(column=2, row=1)
        abutton.grid(column=3, row=1)
        rbutton.grid(column=4, row=1)
        ibutton.grid(column=5, row=1)
        ebutton.grid(column=6, row=1)
        self.buttons = {
                STATE_FUNC: fbutton,
                STATE_CASE: cbutton,
                STATE_ARROW: abutton,
                STATE_RM: rbutton,
                "import": ibutton,
                "export": ebutton,
        }

        # Canvas
        self.canvas = Canvas(self.mainframe, width=600, height=600, bg="grey") # TODO the mainframe should be grey
        self.canvas.grid(column=1, row=2, columnspan=len(self.buttons))
        self.canvas.bind("<Button-1>", self.register_position)
        self.canvas.bind("<B1-Motion>", self.hold_click)
        self.canvas.bind("<ButtonRelease-1>", self.simple_click)
        self.functions = []
        self.cases = []
        self.arrows = []
        self.start = None
        self.n_elems = 0

        # Display
        for child in self.mainframe.winfo_children():
            child.grid_configure(padx=5, pady=5)

        # Create start and end blocks
        d = 30
        start_f = Function(self, Properties.WINDOW_WIDTH / 2, d, name="start")
        end_f = Function(self, Properties.WINDOW_WIDTH / 2, Properties.WINDOW_HEIGHT - d, name="end")
        self.functions += [start_f, end_f]

        self.root.mainloop()
Ejemplo n.º 4
0
    def evaluate(self, tol, xi, niter, fun, dfun, type_error=1):

        fun = Function(fun)
        dfun = Function(dfun)

        fx = fun.evaluate2(xi)
        dfx = dfun.evaluate2(xi)

        if fx == 0:
            return str(fx) + " es una raiz."
        if dfun == 0:
            return "La derivada no puede ser 0"

        contador = 0
        error = tol + 1

        self.values.append(
            [contador,
             str(xi),
             str("{:.2e}".format(fx)),
             str(dfx), None])

        while error > tol and fx != 0 and dfx != 0 and contador < niter:
            xn = xi - (fx / dfx)
            fx = fun.evaluate2(xn)
            dfx = dfun.evaluate2(xn)

            if type_error == 0:
                error = abs(xn - xi)
            else:
                error = abs((xn - xi) / xn)

            xi = xn

            contador = contador + 1
            self.values.append([
                contador,
                str(xn),
                str("{:.2e}".format(fx)),
                str(dfx),
                str("{:.2e}".format(error))
            ])

        if fx == 0:
            return f"{xi} es raiz"
        elif error < tol:
            return f"{xn} es una aprox. a una raiz con una tolerancia = {tol}"
        elif dfx == 0:
            return f"{xn} es una posible raiz multiple"
        else:
            return f"El método fracasó en {niter} iteraciones"
Ejemplo n.º 5
0
    def evaluate(self,
                 xi,
                 tolerancia,
                 iter,
                 function,
                 g_function,
                 type_error=1):

        fun = Function(function)
        gx = Function(g_function)

        fx = fun.evaluate2(xi)

        if fx == 0:
            return f"{xi} es raiz"
        if iter < 1:
            return "El valor del iterador es incorrecto"
        if tolerancia < 0:
            return "Error en la tolerancia, debe ser mayor o igual a 0"

        self.values.append([0, str(xi), str("{:.2e}".format(fx)), None])
        contador = 0
        error = tolerancia + 0.1
        while fx != 0 and error > tolerancia and contador < iter:
            xn = gx.evaluate2(xi)
            fi = fun.evaluate2(xn)

            if type_error == 0:
                error = abs(xn - xi)
            else:
                error = abs((xn - xi) / xn)

            xi = xn

            contador = contador + 1
            self.values.append([
                contador,
                str(xn),
                str("{:.2e}".format(fi)),
                str("{:.2e}".format(error))
            ])

        if fx == 0:
            return f"{xi} es raiz"
        elif error < tolerancia:
            return f"{xi} es una aprox. con una tolerancia = {tolerancia}"
        else:
            return f"El método fracasó en {iter} iteraciones"
Ejemplo n.º 6
0
def eand_lsp(Xh, Yh, BestValue, BestCosts, nef, f, nPop2, ndv, LB, UB):

    # Initialization
    nPop2, ndv = int(nPop2), int(ndv)
    Mh = np.zeros((nPop2, ndv), dtype=int)  # Mutated values from local search
    MYh = np.zeros((nPop2, 1), dtype=float)  # Evaluation of Mh
    Delta = np.zeros(((nPop2 - 1), ndv), dtype=float)  # Delta matrix (Eq. 8)
    ''' Local mutation '''
    n = np.random.permutation(range(2))
    Mh[0] = Xh[0] + Xh[0] * (np.random.uniform(0, 1)) * (
        (-1)**n[0])  # First element mutation (Eq. 10)
    Mh[0] = np.round(Mh[0])  # Handling integer variables
    Mh[0] = eand_limit(Mh[0], LB, UB)  # Constraint handling procedure (Eq. 7)
    MYh[0] = Function(Mh[0])  # Evaluate MYh = f(Mh)
    nef += 1  # Update the number of evaluation functions
    if MYh[0] < BestValue:  # Update the best overall evaluation value
        BestValue = MYh[0]
        f = nef  # Number of evaluation functions to reach the fitness known value

    BestCosts[0, (nef -
                  1)] = BestValue  # Save the best value over the evaluations

    for i in range(nPop2 - 1):

        Delta[i] = Xh[0] - Xh[i + 1]  # Delta matrix (Eq. 8)
        for j in range(ndv):  # Restriction condition (Eq. 9)
            if Delta[i, j] == 0:
                Delta[i, j] = 1

        n = np.random.permutation(range(2))
        Mh[i + 1] = Xh[i + 1] + Delta[i] * (np.random.uniform(0, 1)) * (
            (-1)**n[0])  # Other elements mutation (Eq. 11)
        Mh[i + 1] = np.round(Mh[i + 1])  # Handling integer variables
        Mh[i + 1] = eand_limit(Mh[i + 1], LB,
                               UB)  # Constraint handling procedure (Eq. 7)
        MYh[i + 1] = Function(Mh[i + 1])  # Evaluate MYh = f(Mh)
        nef += 1  # Update the number of evaluation functions
        if MYh[i + 1] < BestValue:  # Update the best overall evaluation value
            BestValue = MYh[i + 1]
            f = nef  # Number of evaluation functions to reach the fitness known value

        BestCosts[0,
                  (nef -
                   1)] = BestValue  # Save the best value over the evaluations
    ''' Local selection technique '''
    Xh, Yh = eand_local_selection(Xh, Yh, Mh, MYh, nPop2, ndv)

    return Xh, Yh, BestValue, BestCosts, nef, f
Ejemplo n.º 7
0
    def getMintermsAndDCs(functions):
        """

        :param functions: A list of strings in the format "m(1,2,3) + d(4,5,6)". Generally gotten from extractFunctions.
        :return: Returns a list of Function objects
        """
        parsed = []
        for fStr in functions:
            mString = InputParser.func_pattern.match(fStr).group("m")
            dcString = InputParser.func_pattern.match(fStr).group("dc")
            mList = [m.strip() for m in mString.split(",")]
            if dcString is not None:
                dcList = [dc.strip() for dc in dcString.split(",")]
            else:
                dcList = []

            if not (all([m.isdigit() for m in mList])
                    and all([dc.isdigit() for dc in dcList])):
                print "At least one invalid minterm entered. Check that all are comma-separated integers."
                continue

            mList = [Minterm(int(m)) for m in mList]
            dcList = [Minterm(int(dc)) for dc in dcList]

            f = Function(mList, dcList)

            parsed.append(f)

        return parsed
Ejemplo n.º 8
0
    def createSerializationFunction(self, cls, serialize_type):
        function = Function()
        function.name = 'serialize' if serialize_type == SERIALIZATION else 'deserialize'
        for func in cls.functions:
            if func.name == function.name:
                return

        function.args = [[self.getSerialiationFunctionArgs(), None]]

        if cls.behaviors:
            if self.serialize_format == 'xml':
                function.operations.append('parent::{}($xml);'.format(function.name))
            else:
                function.operations.append('parent::{}($json);'.format(function.name))
        for obj in cls.members:
            if obj.is_runtime:
                continue
            if obj.is_static:
                continue
            if obj.is_const and not obj.is_link:
                continue

            line = self._buildSerializeOperation(obj.name, obj.type, obj.initial_value, serialize_type, obj.template_args, obj.is_pointer, is_link=obj.is_link)
            function.operations.append(line)

        cls.functions.append(function)
Ejemplo n.º 9
0
def create_function(self, ctx, function_name, parameters,
                    initial_virtual_direction, literal, return_direction):
    """
    Name: create_function
    Description: Creates the information for the function with its corresponding quadruples.
    Parameters:
        ctx: Holds the context of the definition_function rule.
        function_name: The name of the function to create.
        parameters: The information of the parameters of the function.
        initial_virtual_direction: The virtual direction to access after Start Proc.
        literal: Information about the return literal.
        return_direction: The global direction used for the return.
    Returns: NA
    Important methods where its called:
        definition_function: To create the quadruples of the function.
    """
    # Ensure the new function is not already defined
    check_defined_function(function_name)
    code_virtual_direction = memory.get_last_code() + 1
    # Add the function to the functions table
    gl.functions[function_name] = Function(function_name, literal.type, {},
                                           parameters, False,
                                           initial_virtual_direction,
                                           code_virtual_direction,
                                           return_direction,
                                           literal.array_info)
    memory.add_quadruple(Operator.PARAMEND, None, None, None)
    self.function(ctx.function())
    gl.current_scope = global_function
    memory.add_quadruple(Operator.ENDPROC, None, None, None)
    memory.local_segment.clear()
Ejemplo n.º 10
0
    def buildIf(self):
        self.delmov()

        sline = self.current_token.start.line

        if(self.current_token.start.line != sline):
            throw(ExpectedValue(self.current_token))
            return

        if self.current_token.tok == T_ID:
            self.checkDefn()
            self.update()
        multitok = False
        definitionTokens = [self.current_token]
        self.delmov()

        while(self.current_token.start.line == sline):
            if self.current_token.tok == T_ID:
                self.checkDefn()
                self.update()
                self.current_token.start.line = sline
                continue
            definitionTokens.append(self.current_token)
            self.delmov()

        tmpfn = Function("empty", [], VOID, config.GlobalCompiler, [])
        value = determineConstexpr(False, definitionTokens, tmpfn)
        if value.accessor == 0:
            self.skipIfbody()
        else:
            pass
Ejemplo n.º 11
0
    def find_an_approximation(self, function_table: dict) -> Function:
        try:
            SLNX = sum(log(x) for x in function_table.keys())
            SLNXX = sum(log(x) * log(x) for x in function_table.keys())
            SLNY = sum(log(y) for y in function_table.values())
            SLNXY = sum(log(x) * log(y) for x, y in function_table.items())
            n = len(function_table)
        except ValueError:
            return None

        try:
            b, a = self.solve_matrix22([[n, SLNX], [SLNX, SLNXX]],
                                       [SLNY, SLNXY])
            if a is None:
                return None
            a = exp(a)
            fun = lambda x: a * (x**b)
            s = sum(
                (fun(x) - function_table[x])**2 for x in function_table.keys())
            root_mean_square_deviation = sqrt(s / n)
            f = Function(fun, f'ф = {round(a, 3)}*x^({round(b, 3)})', s,
                         root_mean_square_deviation)
            self.print_approximation_table(function_table, f,
                                           self.function_type)
            return f
        except TypeError:
            return None
Ejemplo n.º 12
0
Archivo: Ear.py Proyecto: RemiBe/ear
 def simple_click(self, event):
     """If clicked on an empty space: add a function/case/arrow,
     Else if in state "remove", remove the function/case/arrow,
     Else edit the function/case.
     """
     print("simple_click: selected is {}, moving is {}".format(self.selected, self.moving))
     if self.selected is None:
         if self.state == STATE_FUNC:
             f = Function(self, event.x, event.y)
             if not f.cancelled:
                 self.functions.append(f)
         elif self.state == STATE_CASE:
             c = Case(self, event.x, event.y)
             if not c.cancelled:
                 self.cases.append(c)
     else:
         if self.state == STATE_RM and not self.moving:
             self.selected.destroy()
             self.start = None
         elif self.state == STATE_ARROW:
             if self.start is None:
                 self.start = self.selected
             else:
                 a = Arrow(self, self.start, self.selected)
                 self.arrows.append(a)
                 self.start = None
         elif not self.moving:
             self.selected.edit()
             self.start = None
         else:
             self.start = None
     self.moving = False
 def byte_MAKE_FUNCTION(self, argc):
     name = self.pop()
     code = self.pop()
     defaults = self.popn(argc)
     globs = self.frame.f_globals
     fn = Function(name, code, globs, defaults, None, self)
     self.push(fn)
Ejemplo n.º 14
0
    def buildCastOverload(self):
        starttok = self.current_token
        self.advance()
        t = self.compiler.checkType()
        self.update()
        if self.current_token.tok != T_OPENP:
            throw(ExpectedToken(self.current_token, T_OPENP))
        self.advance()
        if self.current_token.tok != T_CLSP:
            throw(ExpectedToken(self.current_token, T_CLSP))
        self.advance()
        if self.current_token.tok != T_OPENSCOPE:
            throw(ExpectedToken(self.current_token, T_CLSP))
        self.advance()
        start = self.compiler.ctidx
        self.compiler.skipBody()
        end = self.compiler.ctidx

        body = self.compiler.currentTokens[start:end + 1]

        fun = Function(
            f"operator@{t}",
            [],
            t,
            self.compiler,
            body,
            memberfn=True,
            parentstruct=self.prototypeType,
            declare_token=starttok,
        )
        self.compiler.functions.append(fun)
        self.prototypeType.operators[t.name] = fun
        self.current_token = self.compiler.currentTokens[end + 1]
Ejemplo n.º 15
0
 def MAKE_FUNCTION(self, flags):
     name = self.pop()
     code = self.pop()
     defaults = self.popn(flags)
     globs = self.frame.f_globals
     func = Function(name, code, globs, defaults, None, self)
     self.push(func)
Ejemplo n.º 16
0
 def MAKE_CLOSURE(self, argc):
     name = self.pop()
     closure, code = self.popn(2)
     defaults = self.popn(argc)
     globs = self.frame.f_globals
     func = Function(name, code, globs, defaults, closure, self)
     self.push(func)
Ejemplo n.º 17
0
 def test_give_proper_value_third_degree(self):
     sut = Function()
     sut.coefficients.clear()
     sut.coefficients.append(3)
     sut.coefficients.append(4)
     sut.coefficients.append(5)
     self.assertEqual(sut.get_value(2), 25)
Ejemplo n.º 18
0
    def add_serialization(self, class_, serialization_type):
        function = Function()
        if serialization_type == SERIALIZATION:
            function.is_const = True
            function.name = 'serialize'
            function.args.append(
                self.get_serialization_object_arg(serialization_type))
        if serialization_type == DESERIALIZATION:
            function.name = 'deserialize'
            function.args.append(
                self.get_serialization_object_arg(serialization_type))
        function.return_type = 'void'
        function.link()

        for behabior in class_.behaviors:
            if not behabior.is_serialized:
                continue
            operation = self.get_behavior_call_format().format(
                behabior.name, function.name)
            function.operations.append(operation)

        for obj in class_.members:
            if obj.is_runtime or obj.is_static or (obj.is_const
                                                   and not obj.is_link):
                continue
            operation = self._build_serialize_object_operation(
                obj, serialization_type)
            function.operations.append(operation)
        class_.functions.append(function)
Ejemplo n.º 19
0
    def findChiParams(self):
        dataFileName = 'testData.txt'
        function = Function()
        chiLinear = ChiSquare(function.evalLinear, dataFileName)
        optimiser = Optimise()

        #m = params[0]
        #c = params[1]
        paramsGuess = [0., 1.]
        paramsAccuracy = [0.000000001, 0.000000001]
        paramsJump = [1., 1.]
        #evals minimum m and c for our ChiSquare
        params = optimiser.min(chiLinear.evalChiSquare, paramsGuess,
                               paramsJump, paramsAccuracy, [])

        minM = params[0]
        minC = params[1]
        minChi = chiLinear.evalChiSquare(params)

        #finding err of values in params by finding where the chiSquare
        #increases by 1 either side of the minimum
        mRootParamGuess = [minM + 1., minC]
        cRootParamGuess = [minM, minC + 1.]
        rootParamsJump = [0.0001, 0.001]
        rootParamsAccuracy = [0.000001, 0.000001]
        mErrPos = abs(
            optimiser.equalTo(
                (minChi + 1), chiLinear.evalChiSquare, mRootParamGuess,
                rootParamsJump, rootParamsAccuracy, [1])[0] - minM)
        cErrPos = abs(
            optimiser.equalTo(
                (minChi + 1), chiLinear.evalChiSquare, cRootParamGuess,
                rootParamsJump, rootParamsAccuracy, [0])[1] - minC)
        mErrNeg = abs(
            optimiser.equalTo(
                (minChi + 1), chiLinear.evalChiSquare, [minM - mErrPos, minC],
                rootParamsJump, rootParamsAccuracy, [1])[0] - minM)
        cErrNeg = abs(
            optimiser.equalTo(
                (minChi + 1), chiLinear.evalChiSquare, [minM, minC - cErrPos],
                rootParamsJump, rootParamsAccuracy, [0])[1] - minC)

        mErrMean = (mErrPos + mErrNeg) / 2.
        cErrMean = (cErrPos + cErrNeg) / 2.

        print("")
        print("[m,c]:\t" + str(np.around(np.array(params), 6)) + "\n")
        print("mErr:\t+" + str(np.round(mErrPos, 6)) + "\t-" +
              str(np.round(mErrNeg, 6)))
        print("mean:\t" + str(np.round(mErrMean, 6)) + "\n")
        print("cErr:\t+" + str(np.round(cErrPos, 6)) + "\t-" +
              str(np.round(cErrNeg, 6)))
        print("Mean:\t" + str(np.round(cErrMean, 6)))
        print("")

        #self.plotChiAroundMin(chiLinear.evalChiSquare, params, [mErrPos, cErrPos], [mErrNeg, cErrNeg])
        plotter = Plot()
        plotter.plotChiAroundMin(chiLinear.evalChiSquare, params,
                                 [mErrPos, cErrPos], [mErrNeg, cErrNeg])
Ejemplo n.º 20
0
 def add_function(type_, name, args, const):
     function = Function()
     function.return_type = type_
     function.name = name
     function.args = args
     function.is_const = const
     cls.functions.append(function)
     return function
Ejemplo n.º 21
0
 def __init__(self, elf):
     self.functions = []
     self.name_dict = dict()
     self.__table_header = "{0:30} : {1:15} ~ {2:15} | {3:10}"
     for func in elf.functions.values():
         f = Function(func, elf)
         self.functions.append(f)
         self.name_dict[f.name] = f
Ejemplo n.º 22
0
    def _generate_setters_function(self, parser):
        function = Function()
        function.name = constants.CLASS_FUNCTION_SET_PROPERTY
        function.return_type = 'void'
        function.args.append(['name', 'string'])
        function.args.append(['value', 'string'])

        add_function = False
        for member in self.members:
            if member.is_pointer:
                continue
            if member.is_runtime:
                continue
            if member.is_static:
                continue
            if member.is_const:
                continue
            supported_types = {
                'string': 'std::string',
                'int': 0,
                'float': 0,
                'bool': 0
            }
            if member.type in supported_types:
                type_ = member.type
                type_ = type_ if supported_types[
                    type_] == 0 else supported_types[type_]
                op = 'if(name == "{0}") \n{2}\nthis->{0} = strTo<{1}>(value);\n{3}'
                if len(function.operations):
                    op = 'else ' + op
                function.operations.append(
                    op.format(member.name, type_, '{', '}'))
                add_function = True

        override = False
        if self.behaviors:
            for class_ in self.behaviors:
                if class_.is_abstract:
                    continue
                for func in class_.functions:
                    equal = func.name == function.name and func.get_return_type(
                    ).type == function.get_return_type().type
                    for i, arg in enumerate(func.args):
                        equal = equal and func.args[i][1] == function.args[i][1]
                    if equal:
                        override = True
                        if len(function.operations):
                            op = 'else \n{1}\n{0}::{3}(name, value);\n{2}'
                        else:
                            op = '{0}::{3}(name, value);'
                        function.operations.append(
                            op.format(class_.name, '{', '}',
                                      constants.CLASS_FUNCTION_SET_PROPERTY))
                        break

        if add_function or not override:
            self.functions.append(function)
Ejemplo n.º 23
0
 def create_shared_method(self):
     function = Function()
     function.name = 'shared'
     function.args.append(['', ''])
     function.return_type = '{}&:const'.format(self.name)
     function.is_static = True
     function.operations.append('static {} instance;'.format(self.name))
     function.operations.append('return instance;')
     self.functions.append(function)
Ejemplo n.º 24
0
 def insertFunc(self, funcId, func):
     if funcId in self.dictionary:
         raise Exception(
             "{} already exists in the directory".format(funcId))
     else:
         self.dictionary[funcId] = Function(func.startPosition,
                                            func.parameterTable,
                                            func.tempVariableTable,
                                            func.funcReturnType)
Ejemplo n.º 25
0
 def get_header_getter(self):
     function = Function()
     function.name = 'get'
     function.args.append(['name', 'string'])
     function.return_type = Object()
     function.return_type.type = 'template <class T> const T*'
     function.is_const = True
     function.is_template = True
     return function
Ejemplo n.º 26
0
    def create_getters(self, classes):
        for class_ in classes:
            if class_.is_storage and (class_.side == self.parser.side or class_.side == 'both'):
                map_name = get_data_list_name(get_data_name(class_.name))
                function = Function()
                function.name = 'get' + class_.name
                function.args.append(['name', ''])
                function.operations.append(self.get_getter_pattern())
                function.operations[0] = function.operations[0].replace('@{array}', map_name)
                function.operations[0] = function.operations[0].replace('@{type}', class_.name)
                self.functions.append(function)

                function = Function()
                function.name = 'loadAll' + get_data_list_name(class_.name)
                function.operations.append(self.get_load_all_pattern())
                function.operations[0] = function.operations[0].replace('@{array}', map_name)
                function.operations[0] = function.operations[0].replace('@{type}', class_.name)
                self.functions.append(function)
Ejemplo n.º 27
0
 def __init__(self, compiler, templated, tns):
     self.compiler = compiler
     self.templated = templated
     self.tns = tns
     self.current_token = self.compiler.current_token
     self.size = 0
     self.prototypeType = DType("", 0, [], 0, True, constructors=[])
     self.emptyfn = Function("empty", [], VOID.copy(), self.compiler, [])
     self.doAlign = False
Ejemplo n.º 28
0
 def _create_function(self, text):
     body, header, text = find_body(text)
     function = Function()
     function.parse(header)
     if not self.is_side(function.side):
         return text
     function.parse_body(body)
     self.functions.append(function)
     return text
Ejemplo n.º 29
0
    def run(self):
        # vertex input
        print("Please enter list of NODES separated by comma(No less than 3 nodes)")
        isTrue = True
        while isTrue:
            Text = input("Node: ")
            self.temp = Text.split(",")
            counter = 0
            for x in self.temp:
                self.vertexObjectList.append(Node(x))
                counter += 1
            if counter < 3:
                print("Nodes num must be greater than three")
            elif counter >= 3:
                isTrue = False

        for x in self.temp:
            self.vertexNameList.append(x)

        isTrue = True
        while isTrue:
            userInput = input("Please input the start Node, finish Node and distance between them separated by comma: ")
            self.edgeInnerNameList = userInput.split(",")
            counter = 0
            for x in self.edgeInnerNameList:
                if self.edgeInnerNameList[0] and self.edgeInnerNameList[1] in self.vertexNameList:
                    counter += 1
                else:
                    print("Node not found in the list")
            if counter < 2:
                print("Please enter correct information")

            userInput2 = input("Do you want to keep enter Node? (y/n)")
            if userInput2 == 'n':
                isTrue = False
                self.edgeObjectList.append(Edge(self.vertexObjectList[0], self.vertexObjectList[1], int(self.edgeInnerNameList[-1])))
            elif userInput2 == 'y':
                isTrue = True
            else:
                print("Please enter correct selection")

        algorithm = Function()
        i = 0

        while i < len(self.vertexObjectList):
            if i > 0:
                for elements in self.vertexObjectList:
                    elements.minDistance = sys.maxsize
            algorithm.calculateShortestPath(self.vertexObjectList[i], self.vertexObjectList, self.edgeObjectList)
            i += 1
            j = 0
            while j < len(self.vertexObjectList):
                self.printMatrix.append(self.vertexObjectList[j].minDistance)
                j += 1

        printRoutingTable(self.vertexNameList, self.printMatrix)
Ejemplo n.º 30
0
    def __mul__(self, other):
        """Returns the cartesian product of the two groups"""
        if not isinstance(other, Group):
            raise TypeError("other must be a group")
        bin_op = Function((self.Set * other.Set) * (self.Set * other.Set), \
                             (self.Set * other.Set), \
                             lambda x: (self.bin_op((x[0][0], x[1][0])), \
                                        other.bin_op((x[0][1], x[1][1]))))

        return Group(self.Set * other.Set, bin_op)