Exemple #1
0
 def find_snapshots(self, preds, disjunctive=False):
     """Find snapshots that match to the predicates."""
     if not self._mode: raise TarCMS.TarCMSError('not open: %r' % self)
     sel = Selection(self._indexdb, preds, disjunctive=disjunctive)
     for x in sel:
         yield sel.get_snippet(x)
     return
Exemple #2
0
 def find_snapshots(self, preds, disjunctive=False):
   """Find snapshots that match to the predicates."""
   if not self._mode: raise TarCMS.TarCMSError('not open: %r' % self)
   sel = Selection(self._indexdb, preds, disjunctive=disjunctive)
   for x in sel:
     yield sel.get_snippet(x)
   return
 def _separate(verdict) -> Selection:
     total_length = verdict[-1][1] + len(verdict[-1][2])
     garbage_selection = Selection(universe=slice(0, total_length))
     for label, offset, substring in verdict:
         not_english = label.strip() == label
         if not_english:
             garbage_selection.exclude(offset, offset + len(substring))
     return garbage_selection
Exemple #4
0
 def __init__(self, client, object_type):
     self.client = client
     self.object_type = object_type.__name__.lower() + 's'
     self.selection = {
         'devices': Selection(),
         'sensors': Selection(),
         'rules': Selection()
     }
     self.pipeline = []
     self.operation = None
Exemple #5
0
    def __init__(self, population_size, m, k, d, crossover_type):
        """ Create the SGA, describing parameters of our fitness function
        as well as the type of crossover to be used
        """
        self.population_size = population_size
        if (self.population_size % 2 == 1):
            print("Error: population size must be multiple of 2")
            sys.exit()

        self.fitness_function = FitnessFunction(m, k, d)
        self.genotype_length = m * k
        self.variation = Variation(crossover_type)
        self.selection = Selection()
        self.population = []
        self.peak_fitnesses = []
Exemple #6
0
    def __init__(self,
                 parent_genotypes: np.ndarray,
                 possibilites: List[float],
                 population_of_progeny: int,
                 maximum_feature=None,
                 selection: str = "gebv",
                 max_age: int = 1,
                 max_number: int = sys.maxsize):
        if len(parent_genotypes.shape) != 3 or parent_genotypes.shape[:2] != (
                2, 2) or any(_ <= 0 for _ in parent_genotypes.shape):
            raise AttributeError(
                "Массив генотипов особей задан неверно! Размерность должна быть (2 x 2 x N)"
            )
        if max_age <= 0:
            raise AttributeError(
                "Максимальный возраст сущнсоти должен быть >= 1")
        if not Selection.selection_implemented(selection):
            raise NotImplementedError(f"Селекция {selection} не реализована!")

        self.generations: List[Generation] = [
            Generation(index=0,
                       genotypes=list(
                           Genotype(genotype)
                           for genotype in parent_genotypes),
                       population=parent_genotypes.shape[0])
        ]
        self.possibilities = possibilites
        self.population_of_progeny = population_of_progeny
        self._current_generation = 0
        self.maximum_feature = (
            self.generations[0].genotypes[0].matrix.shape[1] *
            2 if maximum_feature is None else maximum_feature)
        self.selection = selection
        self.max_age = max_age
        self.max_number = max_number
    def evolve(self):
        for i in range(0, self.parameters['n.generations']):
            mating_pool = GeneticOperators.select(self.population)
            new_pop = GeneticOperators.crossover(mating_pool)
            GeneticOperators.mutate_in_place(new_pop)
            self.environment.decode(new_pop)
            self.environment.evaluate(new_pop)
            self.scale_fitness(new_pop)

            if('elitism' in self.parameters and \
            self.parameters['elitism']):
                if(self.population.parameters['type']== \
                'nsga-ii'):
                    union = Population(self.population.environment,\
                    self.population.parameters,\
                    self.population.individuals+new_pop.individuals)
                    new_pop = Selection.pareto_crowded(union)
                else:
                    new_pop =\
                    Population(self.population.environment,\
                    self.population.parameters,\
                    sorted(self.population.individuals+new_pop.individuals,\
                    key=lambda x:x.fitness,reverse=True)\
                    [:self.population.size])

            self.population = new_pop

            self.report(i, self.parameters['n.generations'])

        self.report()
Exemple #8
0
 def get_child_generation(self, parent_generation: Generation):
     selection = Selection(parent_generation,
                           possibilites=self.possibilities)
     parent1, parent2 = getattr(selection, f"_{self.selection}_selection")()
     children = self.get_reproduce(parent1, parent2)
     return Generation(index=parent_generation.index + 1,
                       genotypes=children,
                       population=len(children))
Exemple #9
0
    def next_generation(self, population):
        selection = Selection(deepcopy(population),
                              strategy=SelectionStrategy.TOURNAMENT.value)
        selection.apply()
        mating = Mating(selection)
        mating.apply()
        crossover = Crossover(mating)
        crossover.apply()

        for i, individual in enumerate(
                crossover.mating.selection.population.individuals):
            mutation = Mutation(individual)
            crossover.mating.selection.population.individuals[
                i] = mutation.mutate()

        print(f'Individuals: {len(self.individuals)}')
        print(f'New generation: {len(crossover.new_generation)}')
        return crossover.mating.selection.population
Exemple #10
0
class WorldWindow(pyglet.window.Window):
    def __init__(self, world, **kwargs):
        self.world = world
        self.selection = Selection()
        super(WorldWindow,self).__init__(**kwargs)

    def on_mouse_press(self, x, y, button, modifiers):
        location = Vector(x,y)
        if button == mouse.LEFT:
            self.selection.start = location

    def on_mouse_release(self, x, y, button, modifiers):
        location = Vector(x,y)
        if button == mouse.LEFT:
            # select bunnies
            self.selection.end = location
            self.selection.select(self.world)

        elif button == mouse.RIGHT:
            # command bunnies
            destination = tile_coordinate(location)
            for bunny in self.selection.selected_objects:
                bunny.current_action = Move(bunny, destination)

        elif button == mouse.MIDDLE:
            self.create_grass(location)

    def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
        location = Vector(x,y)
        if buttons & mouse.LEFT:
            self.selection.end = location

    def create_grass(self, location):
        tile = tile_coordinate(location)
        cell = self.world.get_cell(tile)
        if cell.grass:
            cell.grass = 0
        else:
            cell.grass = cell.grass_max

    def on_draw(self):
            self.clear()
            self.world.draw()
            self.selection.draw()
Exemple #11
0
 def __init__(self, id, ai=False, score=0):
     self.id = id
     self.isAI = ai
     if ai:
         self.ai = AI(player=self)
     self.wall = Wall()
     self.queue = Queue()
     self.penalty = Penalty()
     self.selection = Selection()
     self.score = score
Exemple #12
0
    def __init__(self):
        super(MainWidget, self).__init__()

        songpath1 = 'together-we-are.wav'
        songpath2 = 'lionhearted.wav'

        self.selection = Selection()

        song1 = Song(songpath1, song1_structure, self.selection)
        song2 = Song(songpath2, song2_structure, self.selection)

        self.beatgen = BeatwiseGenerator()
        self.beatgen.add_song(song1)
        self.beatgen.add_song(song2)

        audio = Audio()
        audio.add_generator(self.beatgen)

        self.selection.beatgen = self.beatgen

        self.clock = ClassClock()
        self.conductor = Conductor(self.clock)
        self.scheduler = Scheduler(self.conductor)

        self.conductor.set_bpm(128)

        #info = Label(text = "text", pos=(0, 500), text_size=(100,100), valign='top')
        #self.add_widget(info)

        # root = ScrollView(size_hint=(None, None), size=(800, 600),
        #                   pos_hint={'center_x': .5, 'center_y': .5})
        # self.add_widget(root)

        #self.rel = AnchorLayout(size_hint=(None, None), width=9000, pos_hint={'center_x': .5, 'center_y': .5},
        #                        anchor_x='left', anchor_y='top')
        self.rel = RelativeLayout(size_hint=(None, None), width=9000, pos_hint={'center_x': .5, 'center_y': .5})
        self.add_widget(self.rel)

        # anchor = AnchorLayout(anchor_x='left', anchor_y='top')
        # self.rel.add_widget(anchor)

        layout = GridLayout(cols=1, padding=50, spacing=50, size_hint=(None, None), width=9000, row_force_default=True,
                            row_default_height=100)
        self.rel.add_widget(layout)

        for song in self.beatgen.get_songs():
            container = RelativeLayout()
            layout.add_widget(container)
            container.add_widget(song)

        self.nowline = Nowline(self.scheduler)
        self.rel.add_widget(self.nowline)

        self.beatgen.nowline = self.nowline
Exemple #13
0
class TestSelection(unittest.TestCase):
    # to be executed prior to running tests
    def setUp(self):
        self.cms_selection = Selection()
        pass

    # to be executed after running tests, regardless of pass/fail
    # only called if setUp succeeds
    def tearDown(self):
        pass

    def test_selection_return_code(self):
        self.assertEqual( self.cms_selection.main(), 0 )
Exemple #14
0
class TestSelection(unittest.TestCase):
    # to be executed prior to running tests
    def setUp(self):
        self.cms_selection = Selection()
        pass

    # to be executed after running tests, regardless of pass/fail
    # only called if setUp succeeds
    def tearDown(self):
        pass

    def test_selection_return_code(self):
        self.assertEqual(self.cms_selection.main(), 0)
Exemple #15
0
    def selectAll(self):

        self.signals.autoUpdateTool.emit(0)
        selection = Selection(QtCore.QPoint(0, 0), self.context, self)
        selection.setGeometry(0, 0, self.image().image.width(), self.image().image.height())
        selection.originTopLeft = QtCore.QPoint(0, 0)
        selection.image = QtGui.QImage(self.context.currentQImage())
        self.makeSelectionTransparent(self.context.transparentSelection)
        selection.finished = True
        selection.show()
        self.image().selection = selection
        painter = QtGui.QPainter(self.context.currentQImage())
        painter.setCompositionMode(QtGui.QPainter.CompositionMode_Source)
        painter.fillRect(self.image().selection.rect, self.image().bgColor)
        painter.end()
Exemple #16
0
    def EvolvePopulation(self):

        for g in tqdm(range(self.number_of_generations), desc='Generation'):

            self.best_fitness = 0
            self.best_index = 0
            self.best_x = np.zeros([1, self.number_of_variables])
            self.EvaluatePopulation()

            temp_population = np.copy(self.population)

            for itVar in range(0, self.population_size, 2):
                i1 = Selection(self.population_fitness)
                i2 = Selection(self.population_fitness)

                chromosome1 = temp_population[i1, :]
                chromosome2 = temp_population[i2, :]

                r = np.random.rand()
                if r < self.crossover_probability:
                    crossed1, crossed2 = CrossoverMutation(chromosome1,
                                                           chromosome2,
                                                           gene_length=1)

                    temp_population[itVar, :] = crossed1
                    temp_population[itVar + 1, :] = crossed2
                else:
                    temp_population[itVar, :] = chromosome1
                    temp_population[itVar + 1, :] = chromosome2

            for itVar in range(self.population_size):
                original_chromosome = temp_population[itVar, :]
                mutated_chromosome = GeneticMutation(original_chromosome)
                temp_population[itVar, :] = mutated_chromosome

            best_individual = self.population[self.best_index, :]
            temp_population[0, :] = np.copy(best_individual)
            self.population = np.copy(temp_population)
Exemple #17
0
    def __init__(self,
                 parent_genotypes: np.ndarray,
                 possibilites: List[float],
                 population_of_progeny: int,
                 maximum_feature=None,
                 selection: str = "gebv",
                 max_age: int = 1,
                 max_population: int = sys.maxsize,
                 possibilities_for_selection: List[float] = None,
                 crosses: int = 1,
                 puberty_period=0):
        if len(parent_genotypes.shape
               ) != 3 or parent_genotypes.shape[1] != 2 or any(
                   _ <= 0 for _ in parent_genotypes.shape):
            raise AttributeError(
                "Массив генотипов особей задан неверно! Размерность должна быть (2 x 2 x N)"
            )
        if max_age <= 0:
            raise AttributeError(
                "Максимальный возраст сущности должен быть >= 1")
        if not Selection.selection_implemented(selection):
            raise NotImplementedError(f"Селекция {selection} не реализована!")
        if len(parent_genotypes) // 2 < crosses:
            raise AttributeError(
                "Число скрещиваний не должно превышать количество родительских особей"
            )
        if max_age <= puberty_period:
            raise AttributeError(
                "Внимание! Ваша особь умирает прежде, чем начинает размножаться!"
            )

        self.generations: List[Generation] = [
            Generation(index=0,
                       genotypes=list(
                           Genotype(genotype)
                           for genotype in parent_genotypes),
                       population=parent_genotypes.shape[0])
        ]
        self.possibilities = possibilites
        self.population_of_progeny = population_of_progeny
        self._current_generation = 0
        self.maximum_feature = (
            self.generations[0].genotypes[0].matrix.shape[1] *
            2 if maximum_feature is None else maximum_feature)
        self.selection = selection
        self.max_age = max_age
        self.max_population = max_population
        self.possibilities_for_selection = possibilities_for_selection
        self.crosses = crosses
        self.puberty_period = puberty_period
def test4():
    print(
        "Test con input size crescente. Input random(0,{}). Lista di {} elementi.\n"
        .format(amount, amount))
    k = int(amount / 2)

    for i in range(50, 250, 5):
        random.seed(i)
        basel = [randint(0, (1 << 32) - 1)
                 for j in range(1000 * i)]  # @UnusedVariable
        l = list(basel)
        start = time()
        res = Selection.sortSelect(l, k)
        elapsed = time() - start
        print('{},{}'.format(1000 * i, elapsed))
def test5():
    print("Test con k differenti. Input random(0,{}). Lista di {} elementi.\n".
          format(amount, amount))

    basel = [randint(0, 1 << 32) for i in range(amount)]  # @UnusedVariable
    k = int(amount / 2)

    kNumber = 101

    for i in range(1, kNumber):
        k = int(amount / kNumber) * i - 1
        l = list(basel)
        start = time()
        res = Selection.quickSelectDet(l, k, 10)
        elapsed = time() - start
        print('{},{}'.format(k, elapsed))
Exemple #20
0
 def get_child_generation(self, parent_generation: Generation,
                          max_generations: int):
     if parent_generation.genotypes:
         selection = Selection(
             parent_generation,
             max_generations,
             possibilities=self.possibilities_for_selection,
             crosses=self.crosses)
         parents = getattr(selection, f"_{self.selection}_selection")()
         childrens = []
         for pair in parents:
             childrens += self.get_reproduce(pair[0], pair[1])
         #childrens = [self.get_reproduce(pair[0], pair[1]) for pair in parents]
     else:
         childrens = list()
     return Generation(index=parent_generation.index + 1,
                       genotypes=childrens,
                       population=len(childrens))
Exemple #21
0
class Text(object):
    def __init__(self):

        self.stt_engine = STT()
        self.tts_engine = TTS()
        self.mic = Mic(self.tts_engine, self.stt_engine, self.stt_engine)
        self.selection = Selection(self.tts_engine)

    def handle(self):

        while True:
            threshold, translate = self.mic.passiveListen("JARVIS")
            if not translate or not threshold:
                continue
            input = self.mic.activeListen(threshold)
            print input
            if input:
                string = self.selection.select(input)
            else:
                self.tts_engine.say("Pardon?")
Exemple #22
0
 def setUp(self):
     self.cms_selection = Selection()
     pass
Exemple #23
0
 def __init__(self, world, **kwargs):
     self.world = world
     self.selection = Selection()
     super(WorldWindow,self).__init__(**kwargs)
from addel import AdDel
from selection import Selection
from editentry import EditEntry
import datetime

cannajobs_entry = AdDel()
cannajobs_selection = Selection()
cannajobs_edit = EditEntry()
# job number, receive date, tests, status
#cannajobs_selection.select_all_from_table_descending(7, True)
#cannajobs_entry.delete_canna_customer_entry((258,))
cannajobs_selection.select_all_from_table_descending(1, True)
cannajobs_entry.delete_cannajob_entry((1063, ))
cannajobs_selection.select_all_from_table_descending(1, True)
#cannajobs_edit = EditEntry()
#cannajobs_edit.edit_cannajobs_entry(1, 452, 1)
#print('----')
#cannajobs_entry.delete_canna_customer_entry((193,))
Exemple #25
0
 def selection(self):
     if self._selection is None:
         from selection import Selection
         self._selection = Selection.by_key(self._subject,
                                            instance_filter=False)
     return self._selection
Exemple #26
0
class MainWidget(BaseWidget):
    def __init__(self):
        super(MainWidget, self).__init__()

        songpath1 = 'together-we-are.wav'
        songpath2 = 'lionhearted.wav'

        self.selection = Selection()

        song1 = Song(songpath1, song1_structure, self.selection)
        song2 = Song(songpath2, song2_structure, self.selection)

        self.beatgen = BeatwiseGenerator()
        self.beatgen.add_song(song1)
        self.beatgen.add_song(song2)

        audio = Audio()
        audio.add_generator(self.beatgen)

        self.selection.beatgen = self.beatgen

        self.clock = ClassClock()
        self.conductor = Conductor(self.clock)
        self.scheduler = Scheduler(self.conductor)

        self.conductor.set_bpm(128)

        #info = Label(text = "text", pos=(0, 500), text_size=(100,100), valign='top')
        #self.add_widget(info)

        # root = ScrollView(size_hint=(None, None), size=(800, 600),
        #                   pos_hint={'center_x': .5, 'center_y': .5})
        # self.add_widget(root)

        #self.rel = AnchorLayout(size_hint=(None, None), width=9000, pos_hint={'center_x': .5, 'center_y': .5},
        #                        anchor_x='left', anchor_y='top')
        self.rel = RelativeLayout(size_hint=(None, None), width=9000, pos_hint={'center_x': .5, 'center_y': .5})
        self.add_widget(self.rel)

        # anchor = AnchorLayout(anchor_x='left', anchor_y='top')
        # self.rel.add_widget(anchor)

        layout = GridLayout(cols=1, padding=50, spacing=50, size_hint=(None, None), width=9000, row_force_default=True,
                            row_default_height=100)
        self.rel.add_widget(layout)

        for song in self.beatgen.get_songs():
            container = RelativeLayout()
            layout.add_widget(container)
            container.add_widget(song)

        self.nowline = Nowline(self.scheduler)
        self.rel.add_widget(self.nowline)

        self.beatgen.nowline = self.nowline

    def on_update(self):
        self.scheduler.on_update()

    def on_touch_down(self, touch):
        return super(MainWidget, self).on_touch_down(touch)

    def on_key_down(self, keycode, modifiers):
        (idx, char) = keycode
        if char == 'backspace':
            self.selection.set_state('NORMAL')
        elif char == 'c':
            self.selection.set_state('CUT')
        elif char == 'l':
            self.selection.set_state('LINK')
        elif char == 'g':
            self.selection.set_state('GO')

        # elif char == 'q':
        #     pass

        elif char == 'w':
            self.beatgen.next_beat -= 32

        elif char == 'e':
            self.beatgen.next_beat += 32

        elif char == 'spacebar':
            #self.clock.toggle()
            # print self.scheduler.cond.get_tick()
            self.beatgen.toggle()

        elif char == 'right':
            self.rel.x -= 100

        elif char == 'left':
            self.rel.x += 100

        elif char == 'up':
            self.rel.y -= 100

        elif char == 'down':
            self.rel.y += 100
Exemple #27
0
from createtb import CreateTb
from dbviews import DbViews
from addel import AdDel
from selection import Selection

Rolodex_entry = AdDel()
Rolodex_selection = Selection()
#fake_entry = ["6", "a", "b", "1", "abc", "cash", True, "online"]
#Rolodex_entry.new_rolodex_entry(fake_entry)
Rolodex_selection.select_all_from_table(1, True)
Exemple #28
0
            starting_population = population.init_next_gen_population(
                next_gen_population=next_gen_population)
            # Reset next gen population list
            next_gen_population = []

        # score chromosomes in the population against fitness goal
        scored_population = []
        for chromosome in starting_population:
            fitness = Fitness(chromosome=chromosome, fitness_goal=fitness_goal)
            scored_chromosome = fitness.calculate_fitness()
            scored_population.append(scored_chromosome)

        # Select parents for offspring generation
        for ch in range(0, scored_population.__len__(), 1):
            # perform parent selection from scored population
            selection = Selection(population=scored_population)
            parents = selection.select()

            # perform crossover based on 50% probability
            crossover_prob = random.choice([True, False])
            crossover = Crossover(parents,
                                  crossover_probability=crossover_prob)
            offspring = crossover.perform_crossover()

            # perform mutation based on 50% probability
            mutation_prob = random.choice([True, False])
            mutation = Mutation(offspring, mutation_probability=mutation_prob)
            final_offspring = mutation.mutate()

            # add offspring to next generation
            next_gen_population.append(final_offspring)
Exemple #29
0
    def parse_cmd(self):
        parser = argparse.ArgumentParser()
        parser.add_argument(
            '-A',
            default=0,
            help='Algorithm type: 0 for genetic algorithm, 1 for CSP')
        parser.add_argument(
            '-GP',
            default=0,
            help=
            'Genetic problem: 0 for string search, 1 for N-queens, 2 for 0-1 knapsack'
        )
        parser.add_argument(
            '-KP',
            default=1,
            help='Knapsack problem number. Can be between 1 and 8')
        parser.add_argument('-QN', default=8, help='Queens number')
        parser.add_argument(
            '-QM',
            default=0,
            help=
            'N-queens mutation type: 0 for exchange mutation, 1 for simple inversion mutation'
        )
        parser.add_argument(
            '-QC',
            default=0,
            help=
            'N-queens crossover type: 0 for PMX crossover, 1 for OX crossover')
        parser.add_argument(
            '-SF',
            default=0,
            help=
            'String search fitness function: 0 for ASCII distance from target '
            'string, 1 for bulls and cows.')
        parser.add_argument(
            '-SC',
            default=0,
            help=
            'String search crossover type: 0 for one-point crossover, 1 for two-point crossover.'
        )
        parser.add_argument(
            '-S',
            default=0,
            help='Selection type: 0 for Random from the top half, 1 for RWS, '
            '2 for aging, 3 for tournament.')
        parser.add_argument('-PS', default=2048, help='Population size')
        args = parser.parse_args()

        try:
            algorithm_type = int(args.A)
            if algorithm_type != 0 and algorithm_type != 1:
                print("Algorithm can only be 0 or 1.")
                sys.exit()
        except ValueError:
            print("Algorithm can only be 0 or 1.")
            sys.exit()

        try:
            genetic_prob = int(args.GP)
            if genetic_prob != 0 and genetic_prob != 1 and genetic_prob != 2:
                print("Genetic problem can only be 0, 1 or 2.")
                sys.exit()
        except ValueError:
            print("Genetic problem can only be 0, 1 or 2.")
            sys.exit()

        try:
            knapsack_problem = int(args.KP)
            if knapsack_problem != 1 and knapsack_problem != 2 and knapsack_problem != 3 and knapsack_problem != 4\
                    and knapsack_problem != 5 and knapsack_problem != 6 and knapsack_problem != 7\
                    and knapsack_problem != 8:
                print(
                    "Knapsack problem number can only be a number between 1 and 8 (including)."
                )
                sys.exit()
        except ValueError:
            print(
                "Knapsack problem number can only be a number between 1 and 8 (including)."
            )
            sys.exit()

        try:
            queens_number = int(args.QN)
            if queens_number < 1 or queens_number > 100:
                print("Queens number can only be a number between 1 and 100.")
                sys.exit()
        except ValueError:
            print("Queens number can only be a number between 1 and 100.")
            sys.exit()

        try:
            mutation_number = int(args.QM)
            if mutation_number != 0 and mutation_number != 1:
                print("N-queens mutation number can only be 0 or 1.")
                sys.exit()
        except ValueError:
            print("N-queens mutation number can only be 0 or 1.")
            sys.exit()

        try:
            crossover_number = int(args.QC)
            if crossover_number != 0 and crossover_number != 1:
                print("N-queens crossover number can only be 0 or 1.")
                sys.exit()
        except ValueError:
            print("N-queens crossover number can only be 0 or 1.")
            sys.exit()

        try:
            fitness_function = int(args.SF)
            if fitness_function != 0 and fitness_function != 1:
                print("String search fitness function can only be 0 or 1.")
                sys.exit()
        except ValueError:
            print("String search fitness function can only be 0 or 1.")
            sys.exit()

        try:
            crossover_type = int(args.SC)
            if crossover_type != 0 and crossover_type != 1:
                print("String search crossover type can only be 0 or 1.")
                sys.exit()
        except ValueError:
            print("String search crossover type can only be 0 or 1.")
            sys.exit()

        try:
            selection_type = int(args.S)
            if selection_type != 0 and selection_type != 1 and selection_type != 2 and selection_type != 3:
                print("Selection type can only be 0, 1, 2 or 3.")
                sys.exit()
        except ValueError:
            print("Selection type can only be 0, 1, 2 or 3.")
            sys.exit()

        try:
            population_size = int(args.PS)
            if population_size < 10:
                print("Population size can only be 10 or larger.")
                sys.exit()
        except ValueError:
            print("Population size can only be a number, 10 or larger.")
            sys.exit()

        # Initialize general values
        self.algorithm = Algorithm(algorithm_type)
        self.genetic_problem = GeneticProblem(genetic_prob)
        self.selection = Selection(selection_type)
        self.original_selection = self.selection
        self.ga_popsize = population_size

        # Initialize string-search values
        self.string_search_crossover = StringSearchCrossOver(crossover_type)
        self.string_search_fitness = StringSearchFitness(fitness_function)

        # Initialize n-queens values
        self.queens_num = queens_number
        self.queens_mutation = NQueensMutation(mutation_number)
        self.queens_crossover = NQueensCrossover(crossover_number)

        # Initialize knapsack values:
        self.knapsack_problem = knapsack_problem - 1
Exemple #30
0
from flask import Flask, request, render_template, redirect, url_for, Response
from flaskext.mysql import MySQL
from tts import TTS
from selection import Selection
from camera import VideoCamera

tts = TTS()
s = Selection(tts)
mysql = MySQL()
app = Flask(__name__)
app.config['MYSQL_DATABASE_USER'] = '******'
app.config['MYSQL_DATABASE_PASSWORD'] = '******'
app.config['MYSQL_DATABASE_DB'] = 'jarvis'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)

data = None


@app.route("/", methods=['GET', 'POST'])
def auth():
    con = mysql.connect()
    cursor = con.cursor()
    if request.method == 'POST':
        email = request.form["email"]
        passw = request.form["passw"]

        cursor.execute("select * from users where email='" + email +
                       "' and password='******'")
        data = cursor.fetchone()
Exemple #31
0
 def FinishInit( self ):
     base.FinishInit()
     
     # Create project manager
     self.project = Project( self )
     base.project = self.project
     self.frame.SetProjectPath( self.frame.cfg.Read( 'projDirPath' ) )
     
     # Create grid
     self.SetupGrid()
     
     # Create frame rate meter
     self.frameRate = p3d.FrameRate()
     
     # Create shading mode keys
     dsp = p3d.DisplayShading()
     dsp.accept( '4', dsp.Wireframe )
     dsp.accept( '5', dsp.Shade )
     dsp.accept( '6', dsp.Texture )
     
     # Set up gizmos
     self.SetupGizmoManager()
     
     # Bind mouse events
     self.accept( 'mouse1', self.OnMouse1Down )
     self.accept( 'shift-mouse1', self.OnMouse1Down, [True] )
     self.accept( 'control-mouse1', self.OnMouse1Down )
     self.accept( 'mouse2', self.OnMouse2Down )
     self.accept( 'mouse1-up', self.OnMouse1Up )
     self.accept( 'mouse2-up', self.OnMouse2Up )
     
     # Create selection manager
     self.selection = Selection(
         camera=base.edCamera, 
         root2d=base.edRender2d, 
         win=base.win, 
         mouseWatcherNode=base.edMouseWatcherNode 
     )
     base.selection = self.selection
     
     # Create our managers.
     self.assetMgr = AssetManager()
     self.dDropMgr = DragDropManager()
     self.actnMgr = actions.Manager()
     
     # Bind events
     self.accept( 'z', self.Undo )
     self.accept( 'shift-z', self.Redo )
     self.accept( 'f', self.FrameSelection )
     self.accept( 'del', lambda fn: cmds.Remove( fn() ), [self.selection.Get] )
     self.accept( 'backspace', lambda fn: cmds.Remove( fn() ), [self.selection.Get] )
     self.accept( 'control-d', lambda fn: cmds.Duplicate( fn() ), [self.selection.Get] )
     self.accept( 'control-g', lambda fn: cmds.Group( fn() ), [self.selection.Get] )
     self.accept( 'control-s', self.frame.OnFileSave, [None] )
     self.accept( 'arrow_up', lambda fn: cmds.Select( fn() ), [self.selection.SelectParent] )
     self.accept( 'arrow_down', lambda fn: cmds.Select( fn() ), [self.selection.SelectChild] )
     self.accept( 'arrow_left', lambda fn: cmds.Select( fn() ), [self.selection.SelectPrev] )
     self.accept( 'arrow_right', lambda fn: cmds.Select( fn() ), [self.selection.SelectNext] )
     self.accept( 'projectFilesModified', self.OnProjectFilesModified )
     
     # Create a "game"
     self.game = editor.Base()
     self.game.OnInit()
     
     # Start with a new scene
     self.CreateScene()
     self.doc.OnRefresh()
     
     return True
Exemple #32
0
    def __init__(self):
        """Start the app."""
        self.base = ShowBase()
        self.base.disableMouse()

        filters = CommonFilters(self.base.win, self.base.cam)
        filters.setBloom(blend=(0, 0, 0, 1))
        self.base.render.setShaderAuto(
            BitMask32.allOn() & ~BitMask32.bit(Shader.BitAutoShaderGlow))
        ts = TextureStage('ts')
        ts.setMode(TextureStage.MGlow)
        tex = self.base.loader.loadTexture('models/black.png')
        self.base.render.setTexture(ts, tex)

        self.terrain = Terrain(self.base.render, self.base.loader)

        minimap_size = 200
        self.minimap = Minimap(
            self.base.win.makeDisplayRegion(
                1 - minimap_size / self.base.win.getProperties().getXSize(), 1,
                1 - minimap_size / self.base.win.getProperties().getYSize(),
                1))
        self.minimap.node_path.reparentTo(self.base.render)

        # self.light_nodes =
        self.set_lights()
        self.set_fog()

        self.key_state = dict.fromkeys(Object.values(config.key_map.character),
                                       False)
        self.set_key_state_handler()

        self.game_state = "pause"
        self.toggle_pause()

        self.selection = Selection(self.base.loader, self.terrain.geom_node)
        self.selection_text = OnscreenText(
            mayChange=True,
            scale=0.07,
            align=TextNode.ALeft,
            pos=(0.02 - self.base.getAspectRatio(), 1 - 0.07))
        self.timer_text = OnscreenText(mayChange=True,
                                       scale=0.07,
                                       align=TextNode.ALeft,
                                       pos=(0.02 - self.base.getAspectRatio(),
                                            -1 + 0.02 + 0.07))

        self.enemies = set()

        self.base.accept(config.key_map.utility.pause, self.toggle_pause)
        self.base.accept(
            "q", lambda: self.selection.advance_tower(self.base.loader))
        self.base.accept("mouse1", self.player_click)
        self.base.cam.node().setCameraMask(BitMask32.bit(0))
        self.base.setBackgroundColor(*config.map_params.colors.sky)

        self.player = Player()
        self.base.taskMgr.add(lambda task: self.terrain.start_up(), "start up")
        self.mouse_pos = (0.0, 0.0)
        self.base.taskMgr.add(self.move_player_task, "move_player_task")
        self.base.taskMgr.add(self.move_enemies_task, "move_enemies_task")
        self.base.taskMgr.add(self.player_select_task, "player_select_task")
        self.base.taskMgr.add(self.tower_task, "tower_task")
        self.base.taskMgr.add(self.check_end_game, "check_end_game_task")
        rand = Random()
        rand.seed(config.map_params.seed)
        self.base.taskMgr.doMethodLater(1,
                                        self.clock_task,
                                        'clock_task',
                                        extraArgs=[rand])
        self.rounds = 0
        self.coin = 40
Exemple #33
0
    else:
        log_level = logging.INFO

    if args.log:
        logging.basicConfig(filename=args.log, level=log_level)

    try:
        config = json.load(open(args.config, "U"))
    except IOError:
        raise EnrichError('Failed to open "%s"' % args.config, _DRIVER_NAME)
    except ValueError:
        raise EnrichError("Improperly formatted .json file", _DRIVER_NAME)

    if config_check.is_experiment(config):
        obj = Experiment(config)
    elif config_check.is_selection(config):
        obj = Selection(config)
    elif config_check.is_seqlib(config):
        obj = globals()[config_check.seqlib_type(config)](config)
    else:
        raise EnrichError("Unrecognized .json config", _DRIVER_NAME)

    if obj.output_base is None:
        raise EnrichError("No output directory set", _DRIVER_NAME)

    obj.calculate()
    obj.write_data()
    if args.plots:
        pass
#        obj.make_plots()
Exemple #34
0
    def parse_cmd(self):
        parser = argparse.ArgumentParser()
        parser.add_argument('-GP', default=4,
                            help='Genetic problem: 0 for string search, 1 for N-queens, 2 for 0-1 knapsack, '
                                 '3 for Baldwin effect, 4 for pareto optima')
        parser.add_argument('-KP', default=1, help='Knapsack problem number. Can be between 1 and 8')
        parser.add_argument('-LOS', default=0, help='Local optima signals. 0 for off, 1 for standard deviation, '
                                                    '2 for similarity of citizens')
        parser.add_argument('-ELO', default=0, help='Evade local optima. 0 for hyper mutations, 1 for niching and '
                                                    '2 for random immigrants')
        parser.add_argument('-QN', default=8, help='Queens number')
        parser.add_argument('-QM', default=0,
                            help='N-queens mutation type: 0 for exchange mutation, 1 for simple inversion mutation')
        parser.add_argument('-QC', default=0, help='N-queens crossover type: 0 for PMX crossover, 1 for OX crossover')
        parser.add_argument('-SF', default=0, help='String search fitness function: 0 for ASCII distance from target '
                                                   'string, 1 for bulls and cows.')
        parser.add_argument('-SC', default=0,
                            help='String search crossover type: 0 for one-point crossover, 1 for two-point crossover.')
        parser.add_argument('-S', default=0, help='Selection type: 0 for Random from the top half, 1 for RWS, '
                                                  '2 for aging, 3 for tournament.')
        parser.add_argument('-PS', default=2048, help='Population size')
        args = parser.parse_args()

        try:
            genetic_prob = int(args.GP)
            if genetic_prob != 0 and genetic_prob != 1 and genetic_prob != 2 and genetic_prob != 3 \
                    and genetic_prob != 4:
                print("Genetic problem can only be 0, 1, 2, 3 or 4.")
                sys.exit()
        except ValueError:
            print("Genetic problem can only be 0, 1, 2, 3 or 4.")
            sys.exit()

        try:
            knapsack_problem = int(args.KP)
            if knapsack_problem != 1 and knapsack_problem != 2 and knapsack_problem != 3 and knapsack_problem != 4\
                    and knapsack_problem != 5 and knapsack_problem != 6 and knapsack_problem != 7\
                    and knapsack_problem != 8:
                print("Knapsack problem number can only be a number between 1 and 8 (including).")
                sys.exit()
        except ValueError:
            print("Knapsack problem number can only be a number between 1 and 8 (including).")
            sys.exit()

        try:
            local_optimal_signal = int(args.LOS)
            if local_optimal_signal != 0 and local_optimal_signal != 1 and local_optimal_signal != 2:
                print("Local optimal signal number can only be 0 for none, 1 for standard deviation and 2 for "
                      "citizen similarity.")
                sys.exit()
        except ValueError:
            print("Local optimal signal number can only be 0 for none, 1 for standard deviation and 2 for "
                  "citizen similarity.")
            sys.exit()

        try:
            evade_local_optima = int(args.ELO)
            if evade_local_optima != 0 and evade_local_optima != 1 and evade_local_optima != 2:
                print("Evade local optima number can only be 0 for hyper-mutations, 1 for niching and 2 for "
                      "random immigrants.")
                sys.exit()
        except ValueError:
            print("Evade local optima number can only be 0 for hyper-mutations, 1 for niching and 2 for "
                  "random immigrants.")
            sys.exit()

        try:
            queens_number = int(args.QN)
            if queens_number < 1 or queens_number > 100:
                print("Queens number can only be a number between 1 and 100.")
                sys.exit()
        except ValueError:
            print("Queens number can only be a number between 1 and 100.")
            sys.exit()

        try:
            mutation_number = int(args.QM)
            if mutation_number != 0 and mutation_number != 1:
                print("N-queens mutation number can only be 0 or 1.")
                sys.exit()
        except ValueError:
            print("N-queens mutation number can only be 0 or 1.")
            sys.exit()

        try:
            crossover_number = int(args.QC)
            if crossover_number != 0 and crossover_number != 1:
                print("N-queens crossover number can only be 0 or 1.")
                sys.exit()
        except ValueError:
            print("N-queens crossover number can only be 0 or 1.")
            sys.exit()

        try:
            fitness_function = int(args.SF)
            if fitness_function != 0 and fitness_function != 1:
                print("String search fitness function can only be 0 or 1.")
                sys.exit()
        except ValueError:
            print("String search fitness function can only be 0 or 1.")
            sys.exit()

        try:
            crossover_type = int(args.SC)
            if crossover_type != 0 and crossover_type != 1:
                print("String search crossover type can only be 0 or 1.")
                sys.exit()
        except ValueError:
            print("String search crossover type can only be 0 or 1.")
            sys.exit()

        try:
            selection_type = int(args.S)
            if selection_type != 0 and selection_type != 1 and selection_type != 2 and selection_type != 3:
                print("Selection type can only be 0, 1, 2 or 3.")
                sys.exit()
        except ValueError:
            print("Selection type can only be 0, 1, 2 or 3.")
            sys.exit()

        try:
            population_size = int(args.PS)
            if population_size < 10:
                print("Population size can only be 10 or larger.")
                sys.exit()
        except ValueError:
            print("Population size can only be a number, 10 or larger.")
            sys.exit()

        # Initialize general values
        if genetic_prob == 3:
            local_optimal_signal = LocalOptimaSignal.Off
            print("Baldwin effect turns off local optima signal")
            selection_type = 1
            print("Baldwin effect runs only with roulette wheel selection (RWS)")
        if genetic_prob == 4:
            local_optimal_signal = LocalOptimaSignal.Off
            print("Parito optimal turns off local optima signal")
        self.genetic_problem = GeneticProblem(genetic_prob)
        self.selection = Selection(selection_type)
        self.original_selection = self.selection
        self.ga_popsize = population_size
        self.local_optima_signal = LocalOptimaSignal(local_optimal_signal)
        self.evade_local_optima_method = CombatEarlyConvergence(evade_local_optima)

        # Initialize string-search values
        self.string_search_crossover = StringSearchCrossOver(crossover_type)
        self.string_search_fitness = StringSearchFitness(fitness_function)

        # Initialize n-queens values
        self.queens_num = queens_number
        self.queens_mutation = NQueensMutation(mutation_number)
        self.queens_crossover = NQueensCrossover(crossover_number)

        # Initialize knapsack values:
        self.knapsack_problem = knapsack_problem - 1
Exemple #35
0
class SimpleGeneticAlgorithm:
    """ Object to wrap the SGA to maximize the fitness function
    """
    def __init__(self, population_size, m, k, d, crossover_type):
        """ Create the SGA, describing parameters of our fitness function
        as well as the type of crossover to be used
        """
        self.population_size = population_size
        if (self.population_size % 2 == 1):
            print("Error: population size must be multiple of 2")
            sys.exit()

        self.fitness_function = FitnessFunction(m, k, d)
        self.genotype_length = m * k
        self.variation = Variation(crossover_type)
        self.selection = Selection()
        self.population = []
        self.peak_fitnesses = []

    def checkTerminationCondition(self, generation_limit, evaluations_limit,
                                  time_limit):
        """ function to decide when to stop running the SGA
        """
        # terminate if most fitnesses are equal
        fitnesses = np.array(list(map(lambda x: x.fitness, self.population)))
        if len(np.unique(fitnesses)) == 1: return True
        # if len(list(filter(lambda x: x.fitness == max(fitnesses), self.population))) > .9*len(self.population): return True

        # terminate if the population contains very few unique genotypes
        # strings = list(map(lambda x: x.__repr__(), self.population))
        # if len(set(strings)) < len(self.population) / (self.genotype_length): return True

        # terminate if the fitness of the elite has stopped increasing

        if (generation_limit > 0 and self.generation >= generation_limit):
            return True

        elif (evaluations_limit > 0
              and self.fitness_function.evaluations >= evaluations_limit):
            return True

        elapsed_time = time.time() - self.start_time
        if (time_limit > 0 and elapsed_time >= time_limit):
            return True

        return False

    def run(self, generation_limit, evaluations_limit, time_limit):
        """ perform the SGA
        """

        # set the starting point of the algorithm
        self.generation = 0
        self.start_time = time.time()

        # create the iniitial population and evaluate them
        for i in range(self.population_size):
            individual = Individual(self.genotype_length)
            self.fitness_function.evaluate(individual)
            self.population.append(individual)

        # evolutionary loop
        while (not self.checkTerminationCondition(
                generation_limit, evaluations_limit, time_limit)):
            # log info

            # create permutation of indices
            offspring = []
            perm = list(range(self.population_size))
            shuffle(perm)

            # generate offspring
            for i in range(self.population_size // 2):
                offspring += self.variation.perform_crossover(
                    self.population[perm[2 * i]],
                    self.population[perm[2 * i + 1]])

            # evaluate offspring
            for o in offspring:
                self.fitness_function.evaluate(o)

            # join parents and offspring
            p_and_o = []
            p_and_o += self.population
            p_and_o += offspring

            # select out offspring
            self.population = self.selection.tournamentSelect(p_and_o)
            self.generation += 1

            # update list of peak fitnesses
            self.peak_fitnesses.append(self.fitness_function.elite.fitness)
Exemple #36
0
functions = get_functions()
constants = get_constants(lower=-10, upper=10, bit=True)
ppl.createPopulation(functions=functions,
                     constants=constants,
                     n_ind=n_ind,
                     n_gene=n_gene,
                     n_register=n_register)
eval_function = lambda x: x[0] ^ x[1]  # xor
ppl.excute_all(inputs, eval_function)

# revolution
p = ProgressBar(0, revolution)
for i in range(revolution):
    #print("revolution: ", i)
    p.update(i + 1)
    elite = Selection.elite(ppl, elite_size)
    new_p = copy.deepcopy(elite)
    for j in range(n_ind - elite_size):
        parent = Selection.tournament(ppl, tourn_size)
        elite.append(parent)
        child = Crossover.randomPoints(elite, cross_rate)
        child = Mutation.mutation(child, mutate_rate, n_register, functions,
                                  constants)
        new_p.append(child)
    ppl.setPopulation(new_p)
    ppl.excute_all(inputs, eval_function)
    if ((i % 100) == 0):
        ppl.result()
ppl.result()
ppl.write_result(path)
p.finish()
Exemple #37
0
 def setUp(self):
     self.cms_selection = Selection()
     pass
Exemple #38
0
    def __init__(self):

        self.stt_engine = STT()
        self.tts_engine = TTS()
        self.mic = Mic(self.tts_engine, self.stt_engine, self.stt_engine)
        self.selection = Selection(self.tts_engine)
Exemple #39
0
class MyApp:
    """The main class."""
    def __init__(self):
        """Start the app."""
        self.base = ShowBase()
        self.base.disableMouse()

        filters = CommonFilters(self.base.win, self.base.cam)
        filters.setBloom(blend=(0, 0, 0, 1))
        self.base.render.setShaderAuto(
            BitMask32.allOn() & ~BitMask32.bit(Shader.BitAutoShaderGlow))
        ts = TextureStage('ts')
        ts.setMode(TextureStage.MGlow)
        tex = self.base.loader.loadTexture('models/black.png')
        self.base.render.setTexture(ts, tex)

        self.terrain = Terrain(self.base.render, self.base.loader)

        minimap_size = 200
        self.minimap = Minimap(
            self.base.win.makeDisplayRegion(
                1 - minimap_size / self.base.win.getProperties().getXSize(), 1,
                1 - minimap_size / self.base.win.getProperties().getYSize(),
                1))
        self.minimap.node_path.reparentTo(self.base.render)

        # self.light_nodes =
        self.set_lights()
        self.set_fog()

        self.key_state = dict.fromkeys(Object.values(config.key_map.character),
                                       False)
        self.set_key_state_handler()

        self.game_state = "pause"
        self.toggle_pause()

        self.selection = Selection(self.base.loader, self.terrain.geom_node)
        self.selection_text = OnscreenText(
            mayChange=True,
            scale=0.07,
            align=TextNode.ALeft,
            pos=(0.02 - self.base.getAspectRatio(), 1 - 0.07))
        self.timer_text = OnscreenText(mayChange=True,
                                       scale=0.07,
                                       align=TextNode.ALeft,
                                       pos=(0.02 - self.base.getAspectRatio(),
                                            -1 + 0.02 + 0.07))

        self.enemies = set()

        self.base.accept(config.key_map.utility.pause, self.toggle_pause)
        self.base.accept(
            "q", lambda: self.selection.advance_tower(self.base.loader))
        self.base.accept("mouse1", self.player_click)
        self.base.cam.node().setCameraMask(BitMask32.bit(0))
        self.base.setBackgroundColor(*config.map_params.colors.sky)

        self.player = Player()
        self.base.taskMgr.add(lambda task: self.terrain.start_up(), "start up")
        self.mouse_pos = (0.0, 0.0)
        self.base.taskMgr.add(self.move_player_task, "move_player_task")
        self.base.taskMgr.add(self.move_enemies_task, "move_enemies_task")
        self.base.taskMgr.add(self.player_select_task, "player_select_task")
        self.base.taskMgr.add(self.tower_task, "tower_task")
        self.base.taskMgr.add(self.check_end_game, "check_end_game_task")
        rand = Random()
        rand.seed(config.map_params.seed)
        self.base.taskMgr.doMethodLater(1,
                                        self.clock_task,
                                        'clock_task',
                                        extraArgs=[rand])
        self.rounds = 0
        self.coin = 40
        # self.base.setFrameRateMeter(True)

    def set_fog(self):
        """Set render distance of camera."""
        fog = Fog("Scene fog")
        fog.setColor(0.7, 0.7, 0.7)
        fog.setExpDensity(0.01)
        # self.terrain.geom_node.setFog(fog)
        self.base.camLens.setFar(4000.0)
        return fog

    def set_lights(self):
        """Set up the lights."""
        light_nodes = [None] * 9
        for i, dirs in zip(range(9), [0] + Object.values(directions) * 2):
            dlight = DirectionalLight(f"directional light {i}")
            if i <= 4:
                dlight.setColor((0.5, 0.5, 0.5, 0.8))
            else:
                dlight.setColor((2, 2, 2, 2))
            light_nodes[i] = self.base.render.attachNewNode(dlight)
            if i == 0:
                light_nodes[i].setPos(0, 0, 1)
            else:
                light_nodes[i].setPos(*dirs, 0)
            light_nodes[i].lookAt(0, 0, 0)
            if i <= 4:
                self.base.render.setLight(light_nodes[i])
                self.terrain.terrain_node.clearLight(light_nodes[i])
            else:
                # self.terrain.terrain_node.setLight(light_nodes[i])
                pass

        alight = AmbientLight('ambient light')
        alight.setColor((0.3, 0.3, 0.3, 1))
        ambient_light_node = self.base.render.attachNewNode(alight)
        self.base.render.setLight(ambient_light_node)
        return light_nodes, ambient_light_node

    def set_key_state_handler(self):
        """Accept key and records to key_state."""
        def set_key_state(key, state):
            self.key_state[key] = state

        for key in self.key_state:
            self.base.accept(key, set_key_state, [key, True])
            self.base.accept(key + "-up", set_key_state, [key, False])

    def toggle_pause(self):
        """Toggle pause."""
        if self.game_state == "ended":
            return
        if self.game_state == "pause":
            self.game_state = "active"
            props = WindowProperties()
            props.setCursorHidden(True)
            props.setMouseMode(WindowProperties.M_confined)
            self.base.win.requestProperties(props)
        else:
            self.game_state = "pause"
            props = WindowProperties()
            props.setCursorHidden(False)
            props.setMouseMode(WindowProperties.M_absolute)
            self.base.win.requestProperties(props)
        print("toggled pause")

    def move_player_task(self, task):  # pylint: disable=unused-argument
        """The task that handles player movement."""
        if self.game_state != "active":
            return Task.cont
        if not self.base.mouseWatcherNode.hasMouse():
            self.toggle_pause()
            return Task.cont
        self.player.update_pos(self.key_state,
                               ClockObject.getGlobalClock().getDt(),
                               lambda pos: self.terrain.get_tile(pos).walkable)
        self.mouse_pos = (
            self.mouse_pos[0] + self.base.mouseWatcherNode.getMouseX(),
            self.mouse_pos[1] + self.base.mouseWatcherNode.getMouseY(),
        )
        self.player.update_hpr(self.mouse_pos)
        self.base.win.movePointer(0,
                                  self.base.win.getXSize() // 2,
                                  self.base.win.getYSize() // 2)
        self.base.camera.setPos(self.player.pos)
        self.minimap.set_pos(self.player.pos, self.player.hpr)
        self.base.camera.setHpr(self.player.hpr)
        self.terrain.update_player_pos(tuple(self.player.pos))
        return Task.cont

    def move_enemies_task(self, task):  # pylint: disable=unused-argument
        """The task that handles enemy movement."""
        if self.game_state != "active":
            return Task.cont
        for enemy in set(self.enemies):
            if not enemy.generated:
                enemy.generate(self.terrain.path_finder, self.base.loader,
                               self.terrain.geom_node, self.terrain.get_tile)
            if not enemy.check_active():
                self.enemies.remove(enemy)
                continue
            # enemy.model.setPos(self.player.pos)
            enemy.move(ClockObject.getGlobalClock().getDt())
        return Task.cont

    def tower_task(self, task):
        if self.game_state != "active":
            return Task.cont
        for tower in set(self.terrain.towers):
            if not tower.generated:
                tower.generate(self.base.loader, self.terrain.geom_node,
                               self.terrain.get_tile)
            if not tower.check_active():
                self.terrain.towers.remove(tower)
                self.terrain[tower.grid_pos] = Floor()
                continue
            tower.move(ClockObject.getGlobalClock().getDt(), self.enemies)
            tower.generate_bullet(self.base.loader, self.terrain.geom_node,
                                  self.terrain.get_tile)
        return Task.cont

    def player_select_task(self, task):
        self.selection.set_selection(
            self.player.view(self.terrain.get_tile, self.enemies))
        self.selection_text.setText(self.selection.get_text())
        if self.selection.tower_class != Empty:
            self.selection.set_disable(
                self.coin < self.selection.tower_class.cost)
        return Task.cont

    def player_click(self):
        if isinstance(self.selection.select, Floor) and \
                issubclass(self.selection.tower_class, Tower) and \
                self.selection.tower_class.cost <= self.coin:
            self.coin -= self.selection.tower_class.cost
            pos = self.selection.model.getPos()
            coord_pos = (int(pos[0] // config.map_params.unit_size),
                         int(pos[1] // config.map_params.unit_size))
            self.terrain[coord_pos] = self.selection.tower_class(coord_pos)

    def spawn_enemies(self, rand):
        if self.game_state != "active":
            return Task.cont
        dsts = [tower.model.getPos().length() for tower in self.terrain.towers]
        radius = max(dsts + [0]) + 100
        num = (self.rounds + config.game.sep // 2) // config.game.sep
        for _ in range(num):
            theta = rand.uniform(0, 2 * pi)
            enemy = Kikiboss if _ % 5 or num % 5 else Dabi
            self.enemies.add(enemy(Vec3(cos(theta), sin(theta), 0) * radius))
        return Task.again

    def clock_task(self, rand):
        if self.game_state != "active":
            return Task.cont
        self.rounds += 1
        self.coin += 1
        ending = "y" if self.coin <= 1 else "ies"
        self.timer_text.setText(
            f"You have {self.coin} cherr{ending}\n" +
            f"{config.game.sep - self.rounds % config.game.sep}s " +
            f"until wave {self.rounds // config.game.sep + 1}.")
        if self.rounds % config.game.sep == 0:
            return self.spawn_enemies(rand)
        return Task.again

    def check_end_game(self, task):
        if self.terrain[(0, 0)].hp <= 0:
            if self.game_state == "active":
                self.toggle_pause()
            self.game_state = "ended"
            self.terrain.geom_node.setColorScale(0.2, 0.2, 0.2, 1)
            OnscreenText(text="GAME OVER",
                         scale=0.2,
                         fg=(1, 0, 0, 1),
                         align=TextNode.ACenter,
                         pos=(0, 0))
            OnscreenText(text=f"score: {self.rounds}",
                         scale=0.07,
                         align=TextNode.ACenter,
                         pos=(0, -.15))
            return task.done
        return task.cont

    def run(self):
        """Run."""
        self.base.run()
    action = None
    for action in actions:
        keyact[action['name']] = action

    keyact.update(adds or {})

    if not keyact:
        raise common.message(_('No action defined'))

    if len(keyact) == 1:
        key = keyact.keys()[0]
        if data.get('context'):
            data['context'].update(rpc.session.context)
        return execute(keyact[key], **data)
    else:
        return Selection().create(keyact, **data)


@tools.expose(template="/openerp/controllers/templates/closepopup.mako")
def close_popup(reload=True):
    """ Closes an opened dialog box or popup.

    :param reload: whether the background view should be reloaded when closing the popup
    :type reload: bool

    :return: the rendered popup-closing template
    :rtype: str
    """
    active_id = False
    if getattr(cherrypy.request, 'params', []):
        if getattr(cherrypy.request.params, 'context', {}):
Exemple #41
0
 def selection(self):
     if self._selection is None:
         from selection import Selection
         self._selection = Selection.by_key(self._subject,
                                            instance_filter=False)
     return self._selection
Exemple #42
0
class App( p3d.wx.App ):
    
    """Base editor class."""
    
    def OnInit( self ):
        self.gizmo = False
        self._xformTask = None
        
        # Bind publisher events
        pub.subscribe( self.OnUpdate, 'Update' )
        
        # Build main frame, start Panda and replace the wx event loop with
        # Panda's.
        self.frame = ui.MainFrame( None, size=(800, 600) )
        ShowBase( self.frame.pnlViewport )
        self.ReplaceEventLoop()
        self.frame.Show()
        wx.CallAfter( self.FinishInit )
        
        return True
    
    def FinishInit( self ):
        base.FinishInit()
        
        # Create project manager
        self.project = Project( self )
        base.project = self.project
        self.frame.SetProjectPath( self.frame.cfg.Read( 'projDirPath' ) )
        
        # Create grid
        self.SetupGrid()
        
        # Create frame rate meter
        self.frameRate = p3d.FrameRate()
        
        # Create shading mode keys
        dsp = p3d.DisplayShading()
        dsp.accept( '4', dsp.Wireframe )
        dsp.accept( '5', dsp.Shade )
        dsp.accept( '6', dsp.Texture )
        
        # Set up gizmos
        self.SetupGizmoManager()
        
        # Bind mouse events
        self.accept( 'mouse1', self.OnMouse1Down )
        self.accept( 'shift-mouse1', self.OnMouse1Down, [True] )
        self.accept( 'control-mouse1', self.OnMouse1Down )
        self.accept( 'mouse2', self.OnMouse2Down )
        self.accept( 'mouse1-up', self.OnMouse1Up )
        self.accept( 'mouse2-up', self.OnMouse2Up )
        
        # Create selection manager
        self.selection = Selection(
            camera=base.edCamera, 
            root2d=base.edRender2d, 
            win=base.win, 
            mouseWatcherNode=base.edMouseWatcherNode 
        )
        base.selection = self.selection
        
        # Create our managers.
        self.assetMgr = AssetManager()
        self.dDropMgr = DragDropManager()
        self.actnMgr = actions.Manager()
        
        # Bind events
        self.accept( 'z', self.Undo )
        self.accept( 'shift-z', self.Redo )
        self.accept( 'f', self.FrameSelection )
        self.accept( 'del', lambda fn: cmds.Remove( fn() ), [self.selection.Get] )
        self.accept( 'backspace', lambda fn: cmds.Remove( fn() ), [self.selection.Get] )
        self.accept( 'control-d', lambda fn: cmds.Duplicate( fn() ), [self.selection.Get] )
        self.accept( 'control-g', lambda fn: cmds.Group( fn() ), [self.selection.Get] )
        self.accept( 'control-s', self.frame.OnFileSave, [None] )
        self.accept( 'arrow_up', lambda fn: cmds.Select( fn() ), [self.selection.SelectParent] )
        self.accept( 'arrow_down', lambda fn: cmds.Select( fn() ), [self.selection.SelectChild] )
        self.accept( 'arrow_left', lambda fn: cmds.Select( fn() ), [self.selection.SelectPrev] )
        self.accept( 'arrow_right', lambda fn: cmds.Select( fn() ), [self.selection.SelectNext] )
        self.accept( 'projectFilesModified', self.OnProjectFilesModified )
        
        # Create a "game"
        self.game = editor.Base()
        self.game.OnInit()
        
        # Start with a new scene
        self.CreateScene()
        self.doc.OnRefresh()
        
        return True
    
    def SetupGrid( self ):
        """Create the grid and set up its appearance."""
        self.grid = DirectGrid( 
            gridSize=20.0,
            gridSpacing=1.0,
            planeColor=(0.5, 0.5, 0.5, 0.0),
            parent=base.edRender
        )
        self.grid.snapMarker.hide()
        self.grid.centerLines.setColor( (0, 0, 0, 0) )
        self.grid.centerLines.setThickness( 2 )
        self.grid.majorLines.setColor( (0.25, 0.25, 0.25, 0) )
        self.grid.majorLines.setThickness( 1 )
        self.grid.minorLines.setColor( (0.5, 0.5, 0.5, 0) )
        self.grid.updateGrid()
    
    def SetupGizmoManager( self ):
        """Create gizmo manager."""
        gizmoMgrRootNp = base.edRender.attachNewNode( 'gizmoManager' )
        kwargs = {
            'camera':base.edCamera, 
            'rootNp':gizmoMgrRootNp, 
            'win':base.win, 
            'mouseWatcherNode':base.edMouseWatcherNode
        }
        self.gizmoMgr = gizmos.Manager( **kwargs )
        self.gizmoMgr.AddGizmo( gizmos.Translation( 'pos', **kwargs ) )
        self.gizmoMgr.AddGizmo( gizmos.Rotation( 'rot', **kwargs ) )
        self.gizmoMgr.AddGizmo( gizmos.Scale( 'scl', **kwargs ) )
        
        # Bind gizmo manager events
        self.accept( 'q', self.SetActiveGizmo, [None] )
        self.accept( 'w', self.SetActiveGizmo, ['pos'] )
        self.accept( 'e', self.SetActiveGizmo, ['rot'] )
        self.accept( 'r', self.SetActiveGizmo, ['scl'] )
        self.accept( 'space', self.ToggleGizmoLocal )
        self.accept( '+', self.gizmoMgr.SetSize, [2] )
        self.accept( '-', self.gizmoMgr.SetSize, [0.5] )
        
    def SetActiveGizmo( self, name ):
        self.gizmoMgr.SetActiveGizmo( name )
        self.frame.OnUpdateXform( None )
        
    def SetGizmoLocal( self, val ):
        self.gizmoMgr.SetLocal( val )
        self.frame.OnUpdateXform( None )
        
    def ToggleGizmoLocal( self ):
        self.gizmoMgr.ToggleLocal()
        self.frame.OnUpdateXform( None )
        
    def OnMouse1Down( self, shift=False ):
        """
        Handle mouse button 1 down event. Start the drag select operation if
        a gizmo is not being used and the alt key is not down, otherwise start 
        the transform operation.
        """
        if ( not self.gizmoMgr.IsDragging() and 
             p3d.MOUSE_ALT not in base.edCamera.mouse.modifiers ):
            self.selection.StartDragSelect( shift )
        elif self.gizmoMgr.IsDragging():
            self.StartTransform()
            
    def OnMouse2Down( self ):
        """
        Handle mouse button 2 down event. Start the transform operation if a
        gizmo is being used.
        """
        if self.gizmoMgr.IsDragging():
            self.StartTransform()
                    
    def OnMouse1Up( self ):
        """
        Handle mouse button 1 up event. Stop the drag select operation if the
        marquee is running, otherwise stop the transform operation if a gizmo
        is being used.
        """
        if self.selection.marquee.IsRunning():
            cmds.Select( self.selection.StopDragSelect() )
        elif self.gizmoMgr.IsDragging() or self.gizmo:
            self.StopTransform()
            
    def OnMouse2Up( self ):
        """
        Handle mouse button 2 up event. Stop the transform operation if a 
        gizmo is being used.
        """
        if self.gizmoMgr.IsDragging() or self.gizmo:
            self.StopTransform()
            
    def StartTransform( self ):
        """
        Start the transfrom operation by adding a task to constantly send a
        selection modified message while transfoming.
        """
        self.gizmo = True
        self._xformTask = taskMgr.add( self.doc.OnSelectionModified, 
                                       'SelectionModified' )
            
    def StopTransform( self ):
        """
        Stop the transfrom operation by removing the selection modified 
        message task. Also create a transform action and push it onto the undo 
        queue.
        """
        # Remove the transform task
        if self._xformTask in taskMgr.getAllTasks():
            taskMgr.remove( self._xformTask )
            self._xformTask = None
            
        actGizmo = self.gizmoMgr.GetActiveGizmo()
        actns = []
        for i, np in enumerate( actGizmo.attachedNps ):
            actns.append( actions.Transform( np, np.getTransform(), actGizmo.initNpXforms[i] ) )
        actn = actions.Composite( actns )
        self.actnMgr.Push( actn )
        self.gizmo = False
        
        # Make sure to mark the NodePath as dirty in case it is a child of a
        # model root.
        wrpr = base.game.nodeMgr.Wrap( np )
        wrpr.SetModified( True )
        
        # Call OnModified next frame. Not sure why but if we call it straight
        # away it causes a small jitter when xforming...
        taskMgr.doMethodLater( 0, self.doc.OnModified, 'dragDrop', 
                               [actGizmo.attachedNps] )
        
    def FrameSelection( self ):
        """
        Call frame selection on the camera if there are some node paths in the 
        selection.
        """
        nps = self.selection.GetNodePaths()
        if nps:
            base.edCamera.Frame( nps )
        else:
            base.edCamera.Frame( [base.scene.rootNp] )
            
    def OnUpdate( self, msg ):
        """
        Subscribed to the update selection message. Make sure that the
        selected nodes are attached to the managed gizmos, then refresh the
        active one.
        """
        nps = self.selection.GetNodePaths()
        self.gizmoMgr.AttachNodePaths( nps )
        self.gizmoMgr.RefreshActiveGizmo()
        self.selection.Update()
                    
    def CreateScene( self, filePath=None, newDoc=True ):
        """
        Create an empty scene and set its root node to the picker's root node.
        """
        # Reset undo queue if creating a new document
        if newDoc:
            self.actnMgr.Reset()
        
        # Close the current scene if there is one
        self.selection.Clear()
        if hasattr( self, 'scene' ):
            self.scene.Close()
            
        # Create a new scene
        self.scene = editor.Scene()
        self.scene.rootNp.reparentTo( base.edRender )
        
        # Set the selection and picker root node to the scene's root node
        self.selection.rootNp = self.scene.rootNp
        self.selection.picker.rootNp = self.scene.rootNp
        self.selection.marquee.rootNp = self.scene.rootNp
        
        # Create the document wrapper if creating a new document
        if newDoc:
            self.doc = ui.Document( filePath, self.scene )
        
    def AddComponent( self, typeStr, *args, **kwargs ):
        wrprCls = base.game.nodeMgr.GetWrapperByName( typeStr )
        wrpr = wrprCls.Create( *args, **kwargs )
        wrpr.SetDefaultValues()
        wrpr.SetParent( wrpr.GetDefaultParent() )
        
        # Bit of a hack. Sometimes a wrapper can create multiple components 
        # when Create is called. Make sure to set default values on all the 
        # components that were created.
        if hasattr( wrpr, 'extraNps' ):
            for np in wrpr.extraNps:
                eWrpr = base.game.nodeMgr.Wrap( np )
                eWrpr.SetDefaultValues()
        cmds.Add( [wrpr.data] )
        
        return wrpr
        
    def OnProjectFilesModified( self, filePaths ):
        self.assetMgr.OnAssetModified( filePaths )
        self.game.pluginMgr.OnProjectFilesModified( filePaths )
        
    def Undo( self ):
        self.actnMgr.Undo()
        self.doc.OnModified()
        
    def Redo( self ):
        self.actnMgr.Redo()
        self.doc.OnModified()
        
    def Group( self ):
        nps = self.selection.GetNodePaths()
        if nps:
            cmds.Group( nps )
        
    def Ungroup( self ):
        nps = self.selection.GetNodePaths()
        if nps:
            cmds.Ungroup( nps )
        
    def Parent( self ):
        pass
        
    def Unparent( self ):
        pass