Exemple #1
0
 def __init__(self, args):
     self.args = args
     self._term = Terminal('OjoDnfExtractor> ')
     self._term.bind_function('open', Command.open, {
         'type': {'type': str, 'help': 'open file type, img/npk'},
         'file': {'type': str, 'help': 'open file path'},
     }, 'open a file.')
Exemple #2
0
    def __init__(self, p_help_w):
        """
            p_help_w: representa una instancia de HelpWindow.

            Constructor de la clase ControlHelpWindow.
        """       
        self.__term = Terminal()
        self.__term.feed_child("\n")
Exemple #3
0
class Command:
    def __init__(self, args):
        self.args = args
        self._term = Terminal('OjoDnfExtractor> ')
        self._term.bind_function('open', Command.open, {
            'type': {'type': str, 'help': 'open file type, img/npk'},
            'file': {'type': str, 'help': 'open file path'},
        }, 'open a file.')

    def start(self):
        files = self.args.files
        if len(files) > 0:
            self.open_auto(files[1])
        else:
            self._term.start()
        return 0

    @staticmethod
    def open(type_, path):
        if type_ == 'npk':
            with open(path, 'rb+') as io:
                NPKTerminal(NPK(io)).start()
        elif type_ == 'img':
            with open(path, 'rb+') as io:
                IMGTerminal(IMG(io)).start()
        else:
            raise Exception('Unsupport type_.')

    @staticmethod
    def open_auto(path):
        if os.path.exists(path):
            [dir, file] = os.path.split(path)
            if file[-4:].lower() == '.npk':
                Command.open('npk', path)
            elif file[-4:].lower() == '.img':
                Command.open('img', path)
            else:
                raise Exception('Unknown file type.', file)
        else:
            raise Exception('File not exists: %s' % path)
Exemple #4
0
    def update( self ):
        state = self._algorithm.get_state()

        # {
        #    "problem"   : self._problem_instance,
        #    "iteration" : self._iteration,
        #    "message"   : message,
        #    "solution"  : self._solution,
        #    "neighbor"  : self._neighbor
        # }

        message = ""
        if "message" in state: message = state["message"]

        # started
        if message == LocalSearchMessage.Started:
            Terminal.clear()
            Terminal.print_box( messages = [ self._algorithm.name, self._algorithm.description ] , font_color = FontColor.Green)
            Terminal.print_box( messages = [ "Problem: " + self._algorithm.problem.name ], font_color = FontColor.Yellow)

        # initialized
        elif message == LocalSearchMessage.Initialized:

            Terminal.print_box( messages = [ "Initialized" ] )
            Terminal.print_line( message= "Initial Solution:") 
            print(f"   Solution: {self._algorithm.solution.representation} - fitness: {self._algorithm.solution.fitness}")
            Terminal.print_box( messages = [ "Iterations"])

        elif message == LocalSearchMessage.ReplacementAccepted:
            iteration = -1
            if "iteration" in state: 
                iteration = state["iteration"]

            Terminal.print_line( message = f"Iteration {iteration:10d} | Solution: {self._algorithm.solution.representation } | Fitness: {self._algorithm.solution.fitness}")

        elif message == LocalSearchMessage.ReplacementRejected:
            iteration = -1
            if "iteration" in state: 
                iteration = state["iteration"]
            
            Terminal.print_line( message = f"Iteration {iteration:10d} | Solution: {self._algorithm.solution.representation } | Fitness: {self._algorithm.solution.fitness} *** (no change)")


        elif message == LocalSearchMessage.StoppedPrematurely:
            Terminal.print_box( messages = ["Stopped Prematurely!"], font_color = FontColor.Yellow )
        
        elif message == LocalSearchMessage.Stopped:
            Terminal.print_box( messages = ["Stopped Max Iterations!"])

        elif message == LocalSearchMessage.StoppedTargetAchieved:
            Terminal.print_box( messages = ["Stopped Target Achieved!"], font_color = FontColor.Green)
Exemple #5
0
    def __init__(self, p_path, p_conn, p_wspace, p_parent, p_lvars_model):
        """
            p_path:         una cadena que indica la direccion del fichero
                            que contiene las variables.
            p_conn:         un 'Connection' que es la conexion con Octave.
            p_wspace:       un 'Workspace'.
            p_parent:       un 'gtk.Window' que es la ventana principal.
            p_lvars_model:  el 'gtk.ListStore' asociado al 'ListVars'.

            Retorna:        un nuevo 'ImportWizard'.

            Crea un nuevo 'ImportWizard'.
        """
        gtk.Window.__init__(self)

        self.__path = p_path
        self.__conn = p_conn
        self.__workspace = p_wspace
        self.__lvars_model = p_lvars_model

        self.set_title("Import Wizard")
        self.set_border_width(5)
        self.set_size_request(692, 406)
        self.set_transient_for(p_parent)
        self.set_position(gtk.WIN_POS_CENTER_ON_PARENT)

        vbox = gtk.VBox(False, 5)
        self.add(vbox)

        # Direccion del archivo a importar.
        label = gtk.Label()
        label.set_alignment(0.0, 0.5)
        text = "Variables in %s" % self.__path
        label.set_markup('<span foreground="#316AC4"><b>%s</b></span>' % text)
        vbox.pack_start(label, False)

        # Horizontal paned.
        hpaned = gtk.HPaned()
        hpaned.set_position(346)
        vbox.pack_start(hpaned)

        # Listado de variables.
        self.__model = gtk.ListStore("gboolean", gtk.gdk.Pixbuf, str, str, str,
                                     str, str)
        tree = gtk.TreeView(self.__model)
        self.__selec = tree.get_selection()
        self.__selec.connect("changed", self.on_selection_changed)

        # Columna Import.
        cell = gtk.CellRendererToggle()
        cell.set_property("activatable", True)
        cell.connect("toggled", self.on_import_toggled)
        col = gtk.TreeViewColumn("Import", cell, active=0)
        col.set_resizable(True)
        tree.append_column(col)

        # Columna Name.
        col = gtk.TreeViewColumn("Name")
        col.set_resizable(True)
        cell = gtk.CellRendererPixbuf()
        col.pack_start(cell, False)
        col.add_attribute(cell, "pixbuf", 1)
        cell = gtk.CellRendererText()
        col.pack_start(cell, False)
        col.add_attribute(cell, "text", 2)
        tree.append_column(col)

        # Columnas Size, Bytes, Class, Attributes.
        for pos, name in enumerate(["Size", "Bytes", "Class", "Attributes"]):
            cell = gtk.CellRendererText()
            col = gtk.TreeViewColumn(name, cell, text=pos + 3)
            col.set_resizable(True)
            tree.append_column(col)

        scroll = gtk.ScrolledWindow()
        scroll.set_shadow_type(gtk.SHADOW_IN)
        scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        scroll.add(tree)
        hpaned.add1(scroll)

        # Vista previa.
        self.__textview = gtk.TextView()
        self.__textview.set_editable(False)
        self.__textview.set_cursor_visible(False)
        self.__textview.modify_font(
            pango.FontDescription("monospace Expanded 10"))
        self.__textview.set_left_margin(3)
        self.__textview.get_buffer().set_text("Loading...")
        scroll = gtk.ScrolledWindow()
        scroll.set_shadow_type(gtk.SHADOW_IN)
        scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        scroll.add(self.__textview)
        hpaned.add2(scroll)

        # Caja de botones.
        buttonbox = gtk.HButtonBox()
        buttonbox.set_layout(gtk.BUTTONBOX_END)
        buttonbox.set_spacing(5)
        vbox.pack_start(buttonbox, False)

        # Boton aplicar.
        self.__apply_butt = gtk.Button(stock=gtk.STOCK_APPLY)
        self.__apply_butt.set_sensitive(False)
        self.__apply_butt.connect("clicked", self.on_apply_clicked)
        buttonbox.pack_start(self.__apply_butt)

        # Boton cancelar.
        self.__cancel_butt = gtk.Button(stock=gtk.STOCK_CANCEL)
        self.__cancel_butt.connect("clicked", lambda p_butt: self.cancel())
        buttonbox.pack_start(self.__cancel_butt)

        # Terminal de la cual vamos a sacar los
        # datos para mostrarselos al usuario.
        self.__term = Terminal()
        self.__term.feed_child(self._get_cmds(), self.extract_names)

        self.__wait = False
        self.__update = False

        self.connect("delete-event", lambda p_wiz, p_event: self.cancel())
        self.show_all()
Exemple #6
0
class ImportWizard(gtk.Window):
    """
        Asistente para importar variables al 'Workspace'.
    """
    def __init__(self, p_path, p_conn, p_wspace, p_parent, p_lvars_model):
        """
            p_path:         una cadena que indica la direccion del fichero
                            que contiene las variables.
            p_conn:         un 'Connection' que es la conexion con Octave.
            p_wspace:       un 'Workspace'.
            p_parent:       un 'gtk.Window' que es la ventana principal.
            p_lvars_model:  el 'gtk.ListStore' asociado al 'ListVars'.

            Retorna:        un nuevo 'ImportWizard'.

            Crea un nuevo 'ImportWizard'.
        """
        gtk.Window.__init__(self)

        self.__path = p_path
        self.__conn = p_conn
        self.__workspace = p_wspace
        self.__lvars_model = p_lvars_model

        self.set_title("Import Wizard")
        self.set_border_width(5)
        self.set_size_request(692, 406)
        self.set_transient_for(p_parent)
        self.set_position(gtk.WIN_POS_CENTER_ON_PARENT)

        vbox = gtk.VBox(False, 5)
        self.add(vbox)

        # Direccion del archivo a importar.
        label = gtk.Label()
        label.set_alignment(0.0, 0.5)
        text = "Variables in %s" % self.__path
        label.set_markup('<span foreground="#316AC4"><b>%s</b></span>' % text)
        vbox.pack_start(label, False)

        # Horizontal paned.
        hpaned = gtk.HPaned()
        hpaned.set_position(346)
        vbox.pack_start(hpaned)

        # Listado de variables.
        self.__model = gtk.ListStore("gboolean", gtk.gdk.Pixbuf, str, str, str,
                                     str, str)
        tree = gtk.TreeView(self.__model)
        self.__selec = tree.get_selection()
        self.__selec.connect("changed", self.on_selection_changed)

        # Columna Import.
        cell = gtk.CellRendererToggle()
        cell.set_property("activatable", True)
        cell.connect("toggled", self.on_import_toggled)
        col = gtk.TreeViewColumn("Import", cell, active=0)
        col.set_resizable(True)
        tree.append_column(col)

        # Columna Name.
        col = gtk.TreeViewColumn("Name")
        col.set_resizable(True)
        cell = gtk.CellRendererPixbuf()
        col.pack_start(cell, False)
        col.add_attribute(cell, "pixbuf", 1)
        cell = gtk.CellRendererText()
        col.pack_start(cell, False)
        col.add_attribute(cell, "text", 2)
        tree.append_column(col)

        # Columnas Size, Bytes, Class, Attributes.
        for pos, name in enumerate(["Size", "Bytes", "Class", "Attributes"]):
            cell = gtk.CellRendererText()
            col = gtk.TreeViewColumn(name, cell, text=pos + 3)
            col.set_resizable(True)
            tree.append_column(col)

        scroll = gtk.ScrolledWindow()
        scroll.set_shadow_type(gtk.SHADOW_IN)
        scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        scroll.add(tree)
        hpaned.add1(scroll)

        # Vista previa.
        self.__textview = gtk.TextView()
        self.__textview.set_editable(False)
        self.__textview.set_cursor_visible(False)
        self.__textview.modify_font(
            pango.FontDescription("monospace Expanded 10"))
        self.__textview.set_left_margin(3)
        self.__textview.get_buffer().set_text("Loading...")
        scroll = gtk.ScrolledWindow()
        scroll.set_shadow_type(gtk.SHADOW_IN)
        scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        scroll.add(self.__textview)
        hpaned.add2(scroll)

        # Caja de botones.
        buttonbox = gtk.HButtonBox()
        buttonbox.set_layout(gtk.BUTTONBOX_END)
        buttonbox.set_spacing(5)
        vbox.pack_start(buttonbox, False)

        # Boton aplicar.
        self.__apply_butt = gtk.Button(stock=gtk.STOCK_APPLY)
        self.__apply_butt.set_sensitive(False)
        self.__apply_butt.connect("clicked", self.on_apply_clicked)
        buttonbox.pack_start(self.__apply_butt)

        # Boton cancelar.
        self.__cancel_butt = gtk.Button(stock=gtk.STOCK_CANCEL)
        self.__cancel_butt.connect("clicked", lambda p_butt: self.cancel())
        buttonbox.pack_start(self.__cancel_butt)

        # Terminal de la cual vamos a sacar los
        # datos para mostrarselos al usuario.
        self.__term = Terminal()
        self.__term.feed_child(self._get_cmds(), self.extract_names)

        self.__wait = False
        self.__update = False

        self.connect("delete-event", lambda p_wiz, p_event: self.cancel())
        self.show_all()

    def on_import_toggled(self, p_cell, p_path):
        """
            p_cell: el 'gtk.CellRendererToggle' que recibio la sennal.
            p_path: una cadena que representa un camino de arbol. Indica la
                    fila de 'p_cell'.

            Se ejecuta cuando el usuario da click en los checkboxes de la
            columna 'Import'. Cambia el estado del checkbox correspondiente.
        """
        self.__model[p_path][0] = not self.__model[p_path][0]

    def _get_cmds(self):
        """
            Retorna: una cadena.

            Metodo auxiliar que retorna codigo Octave que permite determinar
            los nombres de las variables que estan en el archivo del cual se
            quiere importar.
        """
        path = os.path.join(os.path.dirname(__file__), "disp_names.m")

        file_ = open(path, "r")
        code = file_.read().strip()
        file_.close()

        replacer = lambda match: {
            "var": VAR,
            "index": VAR + "1",
            "value": VALUE,
            "path": self.__path,
            "\n": ""
        }[match.group()]

        pattern = re.compile("(var|index|value|path|\n)")
        code = re.sub(pattern, replacer, code)

        return code + "\n"

    def extract_names(self, p_text):
        """
            p_text: una cadena devuelta por 'Octave' la cual contiene los
                    nombres de las variables contenidas en el archivo a
                    importar.

            Extrae de 'p_text' los nombres de las variables.
        """
        lines = p_text.split("\n")
        names = []

        pos = -2
        while lines[pos] != "***":
            names.insert(0, lines[pos])
            pos -= 1

        if names:
            self.__term.feed_child("whos;\n", self.show_vars, [names])
        else:
            self.__textview.get_buffer().set_text(
                "Could not import any variable.")

    def _get_vars(self, p_text):
        """
            p_text:  una cadena que es la salida del comando 'whos;'
                     enviado anteriormente a 'Octave'.

            Retorna: una lista('list') de listas, donde cada sublista contiene
                     los datos de una variable determinada, los datos son:

                     - atributos
                     - nombre
                     - tamanno
                     - bytes
                     - clase

            Metodo auxiliar que retorna los datos de las variables extraidas
            de 'p_text'.
        """
        lines = p_text.splitlines()
        length = len(lines)
        pos = 0

        find_equal = True
        pattern = re.compile("Total is \d+ elements? using \d+ bytes?",
                             re.IGNORECASE)

        vars_ = []
        while pos < length:
            line = lines[pos]

            if find_equal:
                if "=" in line:
                    find_equal = False

            else:  # find_vars
                if re.search(pattern, line):
                    break

                var = line.split()
                if var:
                    if len(var) == 4:
                        var.insert(0, "")
                    vars_.append(var)

            pos += 1
        return vars_

    def show_vars(self, p_text, p_names):
        """
            p_text:  una cadena que es la salida del comando 'whos;'
                     enviado anteriormente a 'Octave'.
            p_names: una lista('list') que contiene los nombres de las
                     variables contenidas en el archivo a importar.

            Muestra en un listado las variables contenidas en el archivo a
            importar. De cada variable se expone su nombre, tamanno, bytes,
            clase y atributos.
        """
        vars_ = self._get_vars(p_text)
        model = self.__model
        root = os.path.abspath(os.path.join(__file__, os.pardir, os.pardir))
        images = {
            "double": "class_double.png",
            "char": "class_char.png",
            "struct": "class_struct.png",
            "cell": "class_cell.png",
            "sym": "class_sym.png"
        }

        for var in vars_:
            if var[1] in p_names:
                img = images.get(var[4], "class_double.png")
                pixbuf = gtk.gdk.pixbuf_new_from_file(
                    os.path.join(root, "images", img))
                model.append(
                    [True, pixbuf, var[1], var[2], var[3], var[4], var[0]])

        self.__apply_butt.set_sensitive(True)
        self.__textview.get_buffer().set_text(
            "No variable selected for preview.")

    def on_selection_changed(self, p_selec):
        """
            p_selec: el 'gtk.TreeSelection' asociado al listado de variables
                     del 'ImportWizard'.

            Se ejecuta cuando cambia la seleccion en el listado de variables
            del 'ImportWizard'. Si hay alguna fila seleccionada entonces se
            obtiene el valor de la variable correspondiente y se llama el
            metodo 'ImportWizard.show_preview' pasandole como parametro dicho
            valor.
        """
        if self.__wait:
            self.__update = True
            return

        model, iter_ = p_selec.get_selected()

        if iter_:
            size = 1
            for dim in model.get_value(iter_, 3).split("x"):
                size *= int(dim)

            if size <= 2000:
                self.__term.feed_child(
                    "disp(%s);\n" % model.get_value(iter_, 2),
                    self.show_preview)
                self.__wait = True
            else:
                self.__textview.get_buffer().set_text(
                    "Preview too large to be displayed properly.")

        else:
            self.__textview.get_buffer().set_text(
                "No variable selected for preview.")

    def show_preview(self, p_text):
        """
            p_text: una cadena que es el valor de la variable seleccionada
                    en el 'ImportWizard'.

            Muestra 'p_text' en la vista de texto del 'ImportWizard'.
        """
        self.__textview.get_buffer().set_text(p_text[p_text.index("\n") +
                                                     1:p_text.rindex("\n")])
        self.__wait = False
        if self.__update:
            self.on_selection_changed(self.__selec)
            self.__update = False

    def cancel(self):
        """
            Cancela la importacion y cierra el asistente.
        """
        self.__term.feed_child("exit\n")
        self.destroy()
        self.__workspace.import_wiz_closed()

    def on_apply_clicked(self, p_butt):
        """
            p_butt: el 'gtk.Button' que recibio la sennal.

            Se ejecuta cuando el usuario da click en el boton 'Aplicar'.
            Chequea si alguna de las variables a importar ya existe en el
            'Workspace', en dicho caso se le informa al usuario. Si el usuario
            confirma todo, entonces se importan hacia el 'Workspace' las
            variables marcadas en los checkboxes.
        """
        new_names = [row[2] for row in self.__model if row[0]]

        if not new_names:
            self.cancel()
            return

        old_names = [row[1] for row in self.__lvars_model]
        equals = []
        for new in new_names:
            if new in old_names:
                equals.append(new)
                if len(equals) == 3:
                    break

        if equals:
            if len(equals) == 1:
                msg = "A variable named\n%s\n" \
                      "already exist in the EIDMAT Workspace." %equals[0]
            elif len(equals) == 2:
                msg = "Variables named\n%s and %s\n" \
                      "already exist in the EIDMAT Workspace." %tuple(equals)
            else:
                msg = "Variables with some of these names already exist\n" \
                      "in the EIDMAT Workspace."
            msg += "\n\nAre you sure that you want to overwrite them?"

            if not Confirm(gtk.STOCK_DIALOG_QUESTION, msg, "Import Wizard",
                           self).run():
                return

        if len(new_names) == len(self.__model):
            self.__conn.append_command(LoadVars([], self.__path))
        else:
            self.__conn.append_command(LoadVars(new_names, self.__path))

        self.cancel()
Exemple #7
0
            f" i: {_} - {solution.representation} - fitness: {solution.fitness}"
        )
        _ += 1


# Knapsack Problem
# -------------------------------------------------------------------------------------------------
knapsack_problem_instance = KnapsackProblem(
    decision_variables=knapsack_decision_variables_example,
    constraints=knapsack_constraints_example)

ga1 = GeneticAlgorithm(problem_instance=knapsack_problem_instance,
                       params={"Population-Size": 15})
ga1._initialize_randomly()

Terminal.clear()
Terminal.print_box(["Population Initialization"], font_color=FontColor.Yellow)

print_population(population=ga1._population)

# Parent Selection - Roulette Wheel
# -------------------------------------------------------------------------------------------------
Terminal.print_box(["Parent Selection - Roulette wheel"],
                   font_color=FontColor.Yellow)
rws = RouletteWheelSelection()
parent1, parent2 = rws.select(population=ga1._population,
                              objective=knapsack_problem_instance.objective,
                              params={})

print(str(parent1))
print(str(parent2))
Exemple #8
0
    def search(self):
        """
            Genetic Algorithm Search Algorithm
            1. Initial population

            2. Repeat n generations )(#1 loop )
                
                2.1. Repeat until generate the next generation (#2 loop )
                    1. Selection
                    2. Try Apply Crossover (depends on the crossover probability)
                    3. Try Apply Mutation (depends on the mutation probability)
                
                2.2. Replacement

            3. Return the best solution    
        """
        problem = self._problem_instance
        select = self._selection_approach.select
        cross = self._crossover_approach
        mutate = self._mutation_approach
        replace = self._replacement_approach
        is_admissible = self._problem_instance.is_admissible

        Terminal.print_box(['Genetic Algorithms - Search Started'],
                           font_color=FontColor.Green)
        print(f' - Crossover Probability : {self._crossover_probability}')
        print(f' - Mutation  Probability : {self._mutation_probability}')

        self._generation = 0

        # 1. Initial population
        self._population = self._initialize(problem, self._population_size)

        Terminal.print_line(message=f'\nGeneration # {0}')
        print(
            f' > Fittest # { self._population.fittest.representation } - fitness: {self._population.fittest.fitness} - weight: {self.calc_weights( self._population.fittest )}'
        )
        self._population.sort()
        for solution in self._population.solutions:
            print(
                f' > {solution.id} - {solution.representation} - Fitness : {solution.fitness} - weight: {self.calc_weights( solution )}'
            )

        #2. Repeat n generations )(#1 loop )
        for generation in range(1, self._number_of_generations):

            new_population = Population(problem=problem,
                                        maximum_size=self._population_size,
                                        solution_list=[])
            i = 0

            Terminal.print_line(message=f'\nGeneration # {generation}')
            # 2.1. Repeat until generate the next generation (#2 loop )
            while new_population.has_space:
                #print('.', end = '')
                # 2.1.1. Selection
                parent1, parent2 = select(self._population, problem.objective,
                                          self._params)
                offspring1 = deepcopy(parent1)  # parent1.clone()
                offspring2 = deepcopy(parent2)  # parent2.clone()
                # 2.1.2. Try Apply Crossover (depends on the crossover probability)
                if self.apply_crossover:
                    offspring1, Offspring2 = cross(problem, parent1, parent2)
                    offspring1.id = [generation, i]
                    i += 1
                    offspring2.id = [generation, i]
                    i += 2
                    #print(f'XO')
                    #print(f'P1:        {parent1.id}-{parent1.representation}')
                    #print(f'P2:        {parent2.id}-{parent2.representation}')
                    #print(f'O1:        {offspring1.id}-{offspring1.representation}')
                    #print(f'O2:        {offspring2.id}-{offspring2.representation}')

                # 2.1.3. Try Apply Mutation (depends on the mutation probability)
                if self.apply_mutation:
                    offspring1 = mutate(problem, offspring1)
                    offspring1.id = [generation, i]
                    i += 1
                    #print(f'MU : O1    {offspring1.id}-{offspring1.representation}')
                if self.apply_mutation:
                    offspring2 = mutate(problem, offspring2)
                    offspring2.id = [generation, i]
                    i += 1
                    #print(f'MU : O2    {offspring2.id}-{offspring2.representation}')

                # add the offsprings in the new population (New Generation)
                if new_population.has_space and is_admissible(offspring1):
                    problem.evaluate_solution(offspring1)
                    new_population.solutions.append(offspring1)
                    #print(f'Added O1 - {offspring1.id}-{offspring1.representation}')

                if new_population.has_space and is_admissible(offspring2):
                    problem.evaluate_solution(offspring2)
                    new_population.solutions.append(offspring2)
                    #print(f'Added O2 - {offspring2.id}-{offspring2.representation}')

            # 2.2. Replacement

            #print('\n # NEW GENERATION *** BEFORE *** REPLACEMENT')
            #fittest = new_population.fittest
            #print( f' > Fittest # id: {fittest.id} - { fittest.representation } - fitness: {fittest.fitness} - weight: {self.calc_weights( fittest )}' )
            #for solution in new_population.solutions:
            #    print(f' > {solution.id} - {solution.representation} - Fitness : {solution.fitness} - weight: {self.calc_weights( solution )}')

            #print(' # CURRENT GENERATION' )
            #fittest = self._population.fittest
            #print( f' > Fittest # id: {fittest.id} - { fittest.representation } - fitness: {fittest.fitness} - weight: {self.calc_weights( fittest )}' )
            #for solution in self._population.solutions:
            #    print(f' > {solution.id} - {solution.representation} - Fitness : {solution.fitness} - weight: {self.calc_weights( solution )}')

            self._population = replace(problem, self._population,
                                       new_population)

            #print(' # NEW GENERATION *** AFTER *** REPLACEMENT' )
            fittest = self._population.fittest
            print(
                f' > Fittest # id: {fittest.id} - { fittest.representation } - fitness: {fittest.fitness} - weight: {self.calc_weights( fittest )}'
            )
Exemple #9
0
class ControlHelpWindow:
    """
        Clase controladora que permite realizar peticiones a Octave, leer las 
        respuestas y busca palabras en componentes Web.
    """    
    def __init__(self, p_help_w):
        """
            p_help_w: representa una instancia de HelpWindow.

            Constructor de la clase ControlHelpWindow.
        """       
        self.__term = Terminal()
        self.__term.feed_child("\n")

    def excec_command(self, p_command, p_method):
        """
            p_command: representa una cadena de texto.
            p_method: representa un metodo de la clase HelpWindow.

            Metodo que solicita la ayuda correspondiente a un comando propio 
            de Octave.
        """
        self.__term.feed_child(p_command, p_method)

    def destroy_terminal(self):
        """
            Metodo que destruye la instancia a Octave tras el cierre de la
            ventana Ayuda.
        """
        self.__term.feed_child("exit\n")

    def web_search(self, p_localization, p_texto, p_sal = None):
        """
            p_localization: representa una cadena de texto con la direccion 
                            de la pagina web solicitada.
            p_texto: representa una cadena de texto.
            p_sal: representa True o False en correspondencia con el tipo de 
                   busqueda.

            Retorna: el codigo de una pagina web con la frase contenida en 
                     <p_text> de color rojo o un mensaje dando a conocer que la
                     misma no se encontro. En caso de que <p_sal!=None> y se 
                     encuentre la frase al menos una vez, se retorna tambien 
                     una cadena de control.         
            
            Metodo que busca una palabra o frase en la documentacion de Octave
            retornando una pagina con la frase remarcada en color rojo si la 
            busqueda es local o una cadena de control si la palabra o frase fue
            encontrada al menos una vez durante una busqueda global.
        """        
        web_code = ""
        if not p_localization:
            return "No se busco"
        loc = p_localization.replace("file:///", "/")            
        if "#" in loc:
            aux = ""
            for i in loc:
                if i == "#":
                    break
                aux += i
            loc = aux
        f = open(loc, "r")
        for linea in f:            
            web_code += linea                 
        f.close()
        flag = False
        aux = ""
        cant_letters = len(p_texto)
        valid_word = ""
        iter1 = 0
        ampersan = False
        valid_flag = False
        if p_texto in web_code:
            for i in web_code:                
                if i == '>':
                    flag = True                    
                if i == '<' :
                    if len(valid_word) > 0:
                        aux += valid_word
                    flag = False
                if i == '&':
                    if len(valid_word) > 0:
                        aux += valid_word
                    flag = False
                    ampersan = True
                if i == ';' and ampersan:
                    flag = True 
                    ampersan = False    
                if flag == True:
                    valid_word += i
                    if p_texto[iter1].lower() == i.lower():
                        iter1 += 1
                    else:
                        aux += valid_word
                        valid_word = ""
                        iter1 = 0
                    if iter1 == cant_letters:
                        if p_sal:
                            return "si"
                        aux = aux + '<em style="color:red">' + valid_word \
                                                                + '</em>'                        
                        iter1 = 0
                        valid_word = ""
                        valid_flag = True
                else:
                    aux += i
                    valid_word = ""
                    iter1 = 0                        
            web_code = aux
            if valid_flag:                
                return web_code     
            else:
                return "No se encontro"
        else:
            return "No se encontro"

    def web_search_file(self, p_word, p_loc):     
        """
            p_word: representa la palabra a buscar. 
            p_loc: representa la localizacion o direccion de la pagina web.

            Retorna: localizacion de la pagina web o la cadena <no> en caso de 
                     no encontrarse la palabra o frase deseada en la pagina.

            Metodo que busca una palabra o frase deseada dentro de una pagina 
            web especificada. Solo se lee el fichero y se pregunta si esta o
            no la palabra sin diferenciar su estancia dentro de un tag.
        """
        dir_ = os.path.join(os.path.dirname(sys.argv[0]), "help", "octave_doc",
                            p_loc + ".html")
        f = open(dir_, "r")
        text = f.read()
        f.close()
        if p_word in text:
            return p_loc
        return "no"