예제 #1
0
def G1DListCrossoverEdge(genome, **args):
    """ The Edge Recombination crossover for G1DList (widely used for TSP problem)

    See more information in the `Edge Recombination Operator
    <http://en.wikipedia.org/wiki/Edge_recombination_operator>`_
    Wikipedia entry.
    """
    gMom, sisterl = args["mom"], []
    gDad, brotherl = args["dad"], []

    mom_edges, dad_edges, merge_edges = Util.G1DListGetEdgesComposite(gMom, gDad)

    for c, u in (sisterl, set(gMom)), (brotherl, set(gDad)):
        curr = None
        for i in range(len(gMom)):
            curr = rand_choice(tuple(u)) if not curr else curr
            c.append(curr)
            u.remove(curr)
            d = [v for v in merge_edges.get(curr, []) if v in u]
            if d:
                curr = rand_choice(d)
            else:
                s = [v for v in mom_edges.get(curr, []) if v in u]
                s += [v for v in dad_edges.get(curr, []) if v in u]
                curr = rand_choice(s) if s else None

    sister = gMom.clone()
    brother = gDad.clone()
    sister.resetStats()
    brother.resetStats()

    sister.genomeList = sisterl
    brother.genomeList = brotherl

    return (sister, brother)
예제 #2
0
def gen_flag_sequence(flags,
                      times,
                      repeat_colours=True,
                      enforce_only_one_name_for_white=False):
    white_reset = rand_choice(whites)
    white_control = Colour(255, 255, 255)

    last_info = None
    sequence_build = []
    for flag_ind in range(times):
        chosen_flag = rand_choice(flags)
        chosen_info = rand_choice(chosen_flag.segments)

        if enforce_only_one_name_for_white:
            if chosen_info.colour == white_control:
                chosen_info = white_reset

        if not repeat_colours:
            last_info = chosen_info

            while chosen_info.colour == last_info.colour:
                chosen_flag = rand_choice(flags)
                chosen_info = rand_choice(chosen_flag.segments)

                if enforce_only_one_name_for_white:
                    if chosen_info.colour == white_control:
                        chosen_info = white_reset

        sequence_build.append(chosen_info)
        last_info = chosen_info

    return sequence_build
예제 #3
0
def chromosome_mutation(chromo,
                        problem_dict,
                        method=MutationMethodEnum.Standard):
    """
    Perform mutation on chromosome.
    :param dict chromo: chromosome to perform mutation on
    :param dict problem_dict: problem dictionary
    :param MutationMethodEnum method: mutation method
    :return dict: mutated chromosome
    """
    key_list = list(problem_dict.keys())
    mutated_chromo = copy(chromo)
    mutation_keys = []
    if method == MutationMethodEnum.Standard:
        mutation_keys.append(rand_choice(key_list))
    elif method == MutationMethodEnum.DoubleStandard:
        mutation_keys.extend(sample(key_list, 2))
    elif method == MutationMethodEnum.Range:
        for key in key_list:
            if random() > 0.5:
                mutation_keys.append(key)

    for selected_key in mutation_keys:
        mutated_chromo[selected_key] = rand_choice(problem_dict[selected_key])
    return mutated_chromo
예제 #4
0
def GTreeGPMutatorOperation(genome, **args):
   """ The mutator of GTreeGP, Operation Mutator

   .. versionadded:: 0.6
      The *GTreeGPMutatorOperation* function
   """

   if args["pmut"] <= 0.0:
      return 0
   elements = len(genome)
   mutations = args["pmut"] * elements
   ga_engine = args["ga_engine"]

   gp_terminals = ga_engine.getParam("gp_terminals")
   assert gp_terminals is not None

   gp_function_set = ga_engine.getParam("gp_function_set")
   assert gp_function_set is not None

   if mutations < 1.0:
      mutations = 0
      for i in range(len(genome)):
         if Util.randomFlipCoin(args["pmut"]):
            mutations += 1
            rand_node = genome.getRandomNode()
            assert rand_node is not None
            if rand_node.getType() == Consts.nodeType["TERMINAL"]:
               term_operator = rand_choice(gp_terminals)
            else:
               op_len = gp_function_set[rand_node.getData()]
               fun_candidates = []
               for o, l in list(gp_function_set.items()):
                  if l == op_len:
                     fun_candidates.append(o)

               if len(fun_candidates) <= 0:
                  continue

               term_operator = rand_choice(fun_candidates)
            rand_node.setData(term_operator)
   else:
      for it in range(int(round(mutations))):
         rand_node = genome.getRandomNode()
         assert rand_node is not None
         if rand_node.getType() == Consts.nodeType["TERMINAL"]:
            term_operator = rand_choice(gp_terminals)
         else:
            op_len = gp_function_set[rand_node.getData()]
            fun_candidates = []
            for o, l in list(gp_function_set.items()):
               if l == op_len:
                  fun_candidates.append(o)

            if len(fun_candidates) <= 0:
               continue

            term_operator = rand_choice(fun_candidates)
         rand_node.setData(term_operator)

   return int(mutations)
예제 #5
0
def _generate_random_boxes_based_on_image_characteristics(total_boxes, images):
    min_width = min(map(lambda i: i.size[0], images))
    max_width = max(map(lambda i: i.size[0], images))
    min_height = min(map(lambda i: i.size[1], images))
    max_height = max(map(lambda i: i.size[1], images))

    random_boxes = []
    for _ in range(total_boxes):
        rand = rand_choice(['black_white', 'random_color', 'salt_pepper'])

        random_box_width = randint(min_width, max_width)
        random_box_height = randint(min_height, max_height)
        random_box_size = (max(random_box_width + randint(-50, 50),
                               random_box_width),
                           max(random_box_height + randint(-50, 50),
                               random_box_height))
        if rand == 'black_white':
            random_box = Image.new('RGB', random_box_size,
                                   rand_choice([(1, 1, 1), (255, 255, 255)]))
        elif rand == 'random_color':
            random_box = Image.new(
                'RGB', random_box_size,
                (randint(0, 255), randint(0, 255), randint(0, 255)))
        else:
            random_box = Image.fromarray(
                np.random.randint(0,
                                  256, (*random_box_size, 3),
                                  dtype=np.uint8))
        random_boxes.append(random_box)

    return random_boxes
예제 #6
0
    def init_random_rule(all_src_ip, all_dst_ip, all_src_port, all_dst_port,
                         cnt):
        ip_list = list()
        port_list = list()
        rule_list = list()

        for src_ip, dst_ip in zip(all_src_ip, all_dst_ip):
            ip_list.append(
                IP(rand_choice([SRC, DST]), rand_choice([src_ip, dst_ip]),
                   Rule.random_t_or_f()))

        for src_port, dst_port in zip(all_src_port, all_dst_port):
            port_list.append(
                Port(rand_choice([SRC, DST]), rand_choice([src_port,
                                                           dst_port]),
                     Rule.random_t_or_f()))

        total_list = ip_list + port_list
        total_cnt = len(total_list)

        for i in range(cnt):
            rule_list.append(
                Rule([
                    rand_choice(total_list)
                    for _ in range(randint(1, total_cnt))
                ]))

        return rule_list
예제 #7
0
def G1DListCrossoverEdge(genome, **args):
   """ THe Edge Recombination crossover for G1DList (widely used for TSP problem)

   See more information in the `Edge Recombination Operator <http://en.wikipedia.org/wiki/Edge_recombination_operator>`_
   Wikipedia entry.
   """
   gMom, sisterl  = args["mom"], []
   gDad, brotherl = args["dad"], []

   mom_edges, dad_edges, merge_edges = Util.G1DListGetEdgesComposite(gMom, gDad)

   for c, u in (sisterl, set(gMom)), (brotherl, set(gDad)):
      curr = None
      for i in xrange(len(gMom)):
         curr = rand_choice(tuple(u)) if not curr else curr         
         c.append(curr)
         u.remove(curr)
         d = [v for v in merge_edges.get(curr, []) if v in u]
         if d: curr = rand_choice(d)
         else:
            s  = [v for v in mom_edges.get(curr, []) if v in u]
            s += [v for v in dad_edges.get(curr, []) if v in u]
            curr = rand_choice(s) if s else None

   sister = gMom.clone()
   brother = gDad.clone()
   sister.resetStats()
   brother.resetStats()

   sister.genomeList  = sisterl
   brother.genomeList = brotherl

   return (sister, brother)
예제 #8
0
def GTreeGPMutatorOperation(genome, **args):
   """ The mutator of GTreeGP, Operation Mutator

   .. versionadded:: 0.6
      The *GTreeGPMutatorOperation* function
   """

   if args["pmut"] <= 0.0:
      return 0
   elements = len(genome)
   mutations = args["pmut"] * elements
   ga_engine = args["ga_engine"]

   gp_terminals = ga_engine.getParam("gp_terminals")
   assert gp_terminals is not None

   gp_function_set = ga_engine.getParam("gp_function_set")
   assert gp_function_set is not None

   if mutations < 1.0:
      mutations = 0
      for i in xrange(len(genome)):
         if Util.randomFlipCoin(args["pmut"]):
            mutations += 1
            rand_node = genome.getRandomNode()
            assert rand_node is not None
            if rand_node.getType() == Consts.nodeType["TERMINAL"]:
               term_operator = rand_choice(gp_terminals)
            else:
               op_len = gp_function_set[rand_node.getData()]
               fun_candidates = []
               for o, l in gp_function_set.items():
                  if l == op_len:
                     fun_candidates.append(o)

               if len(fun_candidates) <= 0:
                  continue

               term_operator = rand_choice(fun_candidates)
            rand_node.setData(term_operator)
   else:
      for it in xrange(int(round(mutations))):
         rand_node = genome.getRandomNode()
         assert rand_node is not None
         if rand_node.getType() == Consts.nodeType["TERMINAL"]:
            term_operator = rand_choice(gp_terminals)
         else:
            op_len = gp_function_set[rand_node.getData()]
            fun_candidates = []
            for o, l in gp_function_set.items():
               if l == op_len:
                  fun_candidates.append(o)

            if len(fun_candidates) <= 0:
               continue

            term_operator = rand_choice(fun_candidates)
         rand_node.setData(term_operator)

   return int(mutations)
 def choose_attack(self):
     rand_row = rand_choice(row_range)
     rand_col = rand_choice(col_range)
     if self.enemy_board.cell_empty(rand_row, rand_col):
         return (rand_row, rand_col)
     else:
         return self.choose_attack()
예제 #10
0
    def __init__(self, position_x, position_y, data_set = {}, 
                previous_nodes = []):
        """ The initializator of CartesianNode representation,
        position_x and position_y must be specified, data_set and previous_nodes
        depends on type of the node """
        self.data = None
        self.inputs = []
        self.params = {}
        self.x = position_x
        self.y = position_y

        try:
            self.data = rand_choice(data_set.keys())
        except IndexError:
            self.data = ""

        try:
            inputs_count = data_set[self.data]-1
        except KeyError:
            inputs_count = 1

        if (len(previous_nodes) == 0 and inputs_count > 0):
            raise ValueError("Bad data set and previous nodes values " 
                            "combination. If specified data set with input args"
                            " then previous nodes can not be empty!")
            
        for i in range(0, inputs_count):
            self.inputs.append(rand_choice(previous_nodes))            
            
        for param in CartesianNode.paramMapping.keys():
            self.params[param] = eval(CartesianNode.paramMapping[param])
예제 #11
0
def GTreeCrossoverSinglePoint(genome, **args):
   """ The crossover for GTree, Single Point """
   sister = None
   brother = None
   gMom = args["mom"].clone()
   gDad = args["dad"].clone()

   gMom.resetStats()
   gDad.resetStats()

   node_mom_stack = []
   all_mom_nodes  = []
   node_mom_tmp   = None

   node_dad_stack = []
   all_dad_nodes  = []
   node_dad_tmp   = None

   node_mom_stack.append(gMom.getRoot())
   node_dad_stack.append(gDad.getRoot())

   while (len(node_mom_stack) > 0) and  (len(node_dad_stack) > 0):
      node_mom_tmp = node_mom_stack.pop()
      node_dad_tmp = node_dad_stack.pop()

      if node_mom_tmp != gMom.getRoot():
         all_mom_nodes.append(node_mom_tmp)
         all_dad_nodes.append(node_dad_tmp)

      node_mom_stack.extend(node_mom_tmp.getChilds())
      node_dad_stack.extend(node_dad_tmp.getChilds())

   if len(all_mom_nodes)==0 or len(all_dad_nodes)==0:
      return (gMom, gDad)

   if len(all_dad_nodes) == 1: nodeDad = all_dad_nodes[0]
   else: nodeDad = rand_choice(all_dad_nodes)

   if len(all_mom_nodes) == 1: nodeMom = all_mom_nodes[0]
   else: nodeMom = rand_choice(all_mom_nodes)

   nodeMom_parent = nodeMom.getParent()
   nodeDad_parent = nodeDad.getParent()

   # Sister
   if args["count"] >= 1:
      sister = gMom
      nodeDad.setParent(nodeMom_parent)
      nodeMom_parent.replaceChild(nodeMom, nodeDad)
      sister.processNodes()

   # Brother
   if args["count"] == 2:
      brother = gDad
      nodeMom.setParent(nodeDad_parent)
      nodeDad_parent.replaceChild(nodeDad, nodeMom)
      brother.processNodes()

   return (sister, brother)
예제 #12
0
def GTreeCrossoverSinglePoint(genome, **args):
    """ The crossover for GTree, Single Point """
    sister = None
    brother = None
    gMom = args["mom"].clone()
    gDad = args["dad"].clone()

    gMom.resetStats()
    gDad.resetStats()

    node_mom_stack = []
    all_mom_nodes = []
    node_mom_tmp = None

    node_dad_stack = []
    all_dad_nodes = []
    node_dad_tmp = None

    node_mom_stack.append(gMom.getRoot())
    node_dad_stack.append(gDad.getRoot())

    while (len(node_mom_stack) > 0) and (len(node_dad_stack) > 0):
        node_mom_tmp = node_mom_stack.pop()
        node_dad_tmp = node_dad_stack.pop()

        if node_mom_tmp != gMom.getRoot():
            all_mom_nodes.append(node_mom_tmp)
            all_dad_nodes.append(node_dad_tmp)

        node_mom_stack.extend(node_mom_tmp.getChilds())
        node_dad_stack.extend(node_dad_tmp.getChilds())

    if len(all_mom_nodes) == 0 or len(all_dad_nodes) == 0:
        return (gMom, gDad)

    if len(all_dad_nodes) == 1: nodeDad = all_dad_nodes[0]
    else: nodeDad = rand_choice(all_dad_nodes)

    if len(all_mom_nodes) == 1: nodeMom = all_mom_nodes[0]
    else: nodeMom = rand_choice(all_mom_nodes)

    nodeMom_parent = nodeMom.getParent()
    nodeDad_parent = nodeDad.getParent()

    # Sister
    if args["count"] >= 1:
        sister = gMom
        nodeDad.setParent(nodeMom_parent)
        nodeMom_parent.replaceChild(nodeMom, nodeDad)
        sister.processNodes()

    # Brother
    if args["count"] == 2:
        brother = gDad
        nodeMom.setParent(nodeDad_parent)
        nodeDad_parent.replaceChild(nodeDad, nodeMom)
        brother.processNodes()

    return (sister, brother)
예제 #13
0
    def random_ip_or_port():
        rule_type = rand_choice([SRC, DST])
        rule_class = rand_choice([IP, Port])
        active = rand_choice([True, False])

        rule_data = rand_choice(MAPDATA[rule_class])

        return rule_class(rule_type, rule_data, active)
예제 #14
0
    def __select_parent(self):
        """
        부모가 될 DNA 를 선출하는 함수.
        선출될 확률은 해당 DNA 의 fitness 값에 비례함.
        :return: DNA object tuple
        """

        return rand_choice(self.parent_roulette), rand_choice(
            self.parent_roulette)
예제 #15
0
def get_random_phrase(separator=' '):
    _syn = rand_choice(const_dicts.RALLY_SYNONYMS).capitalize()
    _adj = rand_choice(const_dicts.ADJECTIVES)
    _noun = rand_choice(const_dicts.NOUNS)

    return '{syn}{sep}of{sep}the{sep}{adj}{sep}{noun}'.format(syn=_syn,
                                                              adj=_adj,
                                                              noun=_noun,
                                                              sep=separator)
 def build_board(self):
     boat_list = [Submarine, Aircraft, PatrolBoat, PatrolBoat]
     while len(boat_list) != 0:
         rand_pos = (rand_choice(row_range), rand_choice(col_range))
         horizontal = randint(0, 1) == 0
         ship = boat_list[-1](rand_pos, horizontal)
         if ship.can_place(self.my_board):
             ship.place(self.my_board)
             boat_list.pop()
예제 #17
0
 async def send_testing_msg(self, ctx, bot=False, msg=None, leave=False):
     # log.info(leave)
     guild = ctx.message.guild
     guild_settings = await self.config.guild(guild).get_raw()
     # log.info(guild_settings)
     channel = guild.get_channel(guild_settings["CHANNEL"])
     if leave:
         channel = guild.get_channel(guild_settings["LEAVE_CHANNEL"])
     rand_msg = msg or rand_choice(guild_settings["GREETING"])
     if leave:
         rand_msg = msg or rand_choice(guild_settings["GOODBYE"])
     if bot:
         rand_msg = guild_settings["BOTS_MSG"]
     is_embed = guild_settings["EMBED"]
     member = ctx.message.author
     whisper_settings = guild_settings["WHISPER"]
     if channel is None and whisper_settings not in ["BOTH", True]:
         msg = _(
             "I can't find the specified channel. It might have been deleted."
         )
         await ctx.send(msg)
         return
     if channel is None:
         await ctx.send(_("`Sending a testing message to ") + "` DM")
     else:
         await ctx.send(
             _("`Sending a testing message to ") +
             "`{0.mention}".format(channel))
     if not bot and guild_settings["WHISPER"]:
         if is_embed:
             em = await self.make_embed(member, guild, rand_msg)
             await ctx.author.send(embed=em, delete_after=60)
         else:
             await ctx.author.send(await self.convert_parms(
                 member, guild, rand_msg),
                                   delete_after=60)
     if bot or whisper_settings is not True:
         if guild_settings["GROUPED"]:
             member = [ctx.author, ctx.me]
         if is_embed and channel.permissions_for(guild.me).embed_links:
             em = await self.make_embed(member, guild, rand_msg)
             if await self.config.guild(guild).EMBED_DATA.mention():
                 if guild_settings["GROUPED"]:
                     await channel.send(humanize_list(
                         [m.mention for m in member]),
                                        embed=em,
                                        delete_after=60)
                 else:
                     await channel.send(member.mention,
                                        embed=em,
                                        delete_after=60)
             else:
                 await channel.send(embed=em, delete_after=60)
         else:
             await channel.send(await
                                self.convert_parms(member, guild, rand_msg),
                                delete_after=60)
예제 #18
0
def get_random_travel_caption(place_name):
    caption = rand_choice(travel_quotes).format(place_name,
                                                rand_choice(sights),
                                                rand_choice(activities),
                                                number, date,
                                                rand_choice(adjectives),
                                                rand_choice(holiday_equipment))
    emojis = "".join(sample(EMOJIS, randint(1, 3)))
    tags = get_tags(1, 7) + " " + get_extra_tags([place_name.replace(",", "")])

    return caption[0].upper() + caption[1:] + " " + emojis + " " + tags
예제 #19
0
def mutate_code(code):
    v = randint(0, 2 if len(code) > 0 else 0)
    pos = randint(0, len(code))
    if v == 0:
        # insert symbol
        return code[:pos] + rand_choice(COMMANDS) + code[pos:]
    elif v == 1:
        # replace symbol
        return code[:pos] + rand_choice(COMMANDS) + code[pos + 1 :]
    else:
        # remove symbol
        return code[:pos] + code[pos + 1 :]
예제 #20
0
 async def send_testing_msg(self, ctx, bot=False, msg=None):
     server = ctx.message.server
     channel = self.get_welcome_channel(server)
     rand_msg = msg or rand_choice(self.settings[server.id]["GREETING"])
     if channel is None:
         await self.bot.send_message(
             ctx.message.channel, "I can't find the specified channel. "
             "It might have been deleted.")
         return
     await self.bot.send_message(
         ctx.message.channel, "`Sending a testing message to "
         "`{0.mention}".format(channel))
     if self.speak_permissions(server):
         msg = self.settings[server.id]["BOTS_MSG"] if bot else rand_msg
         if not bot and self.settings[server.id]["WHISPER"]:
             await self.bot.send_message(
                 ctx.message.author, msg.format(ctx.message.author, server))
         if bot or self.settings[server.id]["WHISPER"] is not True:
             await self.bot.send_message(
                 channel, msg.format(ctx.message.author, server))
     else:
         await self.bot.send_message(
             ctx.message.channel, "I do not have permissions "
             "to send messages to "
             "{0.mention}".format(channel))
예제 #21
0
    def _generate_table(self, dictionary):
        width, height = randint(min(200, self.width), self.width), randint(min(200, self.height), self.height)

        line_size_min = round(self.font_size * 1.3)
        line_size_max = round(self.font_size * 2.5)
        lines = np.cumsum(np.random.randint(line_size_min, line_size_max, 40))
        lines = lines[lines < height - line_size_min].tolist()
        columns = np.cumsum(np.random.randint(*TABLE_LAYOUT_RANGE['col_size_range'], 20))
        columns = columns[columns < width - TABLE_LAYOUT_RANGE['col_size_range'][0]].tolist()

        words, word_positions = [], []
        for i, c in enumerate([0] + columns):
            for j, l in enumerate([0] + lines):
                word_as_number = choice([True, False])
                if word_as_number:
                    n_letter = randint(2, 9)
                    word = f'{randint(0, 10**n_letter - 1):,}'
                else:
                    word = rand_choice(dictionary)
                    uppercase = choice([True, False])
                    if uppercase:
                        word = word.upper()

                cell_width = columns[i] - c if i < len(columns) else width - c
                cell_height = lines[j] - l if j < len(lines) else height - l
                while self.font.getsize(word)[0] + 2 * self.padding > cell_width and len(word) > 0:
                    word = word[:-1].strip()
                if len(word) > 0:
                    w, h = self.font.getsize(word)
                    p_c, p_l = (cell_width - w) // 2, (cell_height - h) // 2
                    words.append(word)
                    word_positions.append((c + p_c, l + p_l))

        return ({'lines': lines, 'columns': columns, 'words': words, 'word_positions': word_positions}, width, height)
예제 #22
0
    def generate_content(self):
        self.font_path = choice(DATABASE[GLYPH_FONT_RESRC_NAME])
        self.letter = self.parameters.get('letter') or rand_choice(
            string.ascii_uppercase)

        # To avoid oversized letters
        rescaled_height = (self.height * 2) // 3
        min_fs, max_fs = self.font_size_range
        actual_max_fs = min(rescaled_height, max_fs)
        tmp_font = ImageFont.truetype(self.font_path, size=actual_max_fs)
        while tmp_font.getsize(
                self.letter
        )[0] > self.width and actual_max_fs > self.font_size_range[0]:
            actual_max_fs -= 1
            tmp_font = ImageFont.truetype(self.font_path, size=actual_max_fs)
        if min_fs < actual_max_fs:
            self.font_size = randint(min_fs, actual_max_fs)
        else:
            self.font_size = actual_max_fs

        self.font = ImageFont.truetype(self.font_path, size=self.font_size)
        self.as_negative = self.parameters.get('as_negative', False)
        self.blur_radius = uniform(
            *NEG_ELEMENT_BLUR_RADIUS_RANGE) if self.as_negative else None
        self.opacity = randint(
            *NEG_ELEMENT_OPACITY_RANGE[self.name] if self.
            as_negative else POS_ELEMENT_OPACITY_RANGE[self.name])
        self.colored = choice([True, False],
                              p=[GLYPH_COLORED_FREQ, 1 - GLYPH_COLORED_FREQ])
        self.colors = (0, 0, 0) if not self.colored else tuple(
            [randint(0, 150) for _ in range(3)])
        self.content_width, self.content_height = self.font.getsize(
            self.letter)
        self.pos_x = randint(0, max(0, self.width - self.content_width))
        self.pos_y = randint(0, max(0, self.height - self.content_height))
예제 #23
0
    def exchange(self):
        """ This is the main method, is where the individuals
        are exchanged """

        if not self.isReady():
            return

        pool_to_send = self.selectPool(self.getNumIndividuals())
        pool_received  = self.comm.sendrecv(sendobj=pool_to_send,
                                            dest=self.dest,
                                            sendtag=0,
                                            recvobj=None,
                                            source=self.source,
                                            recvtag=0)

        population = self.GAEngine.getPopulation()

        pool = pool_received
        for i in xrange(self.getNumReplacement()):
            if len(pool) <= 0:
                break
            choice = rand_choice(pool)
            pool.remove(choice)

            # replace the worst
            population[len(population)-1-i] = choice

        self.gather_bests()
예제 #24
0
 def reset_req(self):
     """
     重置请求,拿出新的查询条件,并将请求起始位置重置为0
     :return:
     """
     # 从查询条件的ssdb队列中获取查询条件
     if DEBUG:
         self.condition = dict(eval(rand_choice(test_condition)))
     else:
         self.condition = dict(eval(self.get_wenshu_condition()))
     if self.condition["case_type"] == "0":
         self.req_data["Param"] = "法院名称:%s,裁判日期:%s" \
                                  % (self.condition["court"], self.condition["date"])
     else:
         if self.condition["case_type"] == "1":
             self.condition["case_type"] = "刑事案件"
         elif self.condition["case_type"] == "2":
             self.condition["case_type"] = "民事案件"
         elif self.condition["case_type"] == "3":
             self.condition["case_type"] = "行政案件"
         elif self.condition["case_type"] == "4":
             self.condition["case_type"] = "赔偿案件"
         elif self.condition["case_type"] == "5":
             self.condition["case_type"] = "执行案件"
         self.req_data["Param"] = "法院名称:%s,案件类型:%s,裁判日期:%s" \
                                  % (self.condition["court"], self.condition["case_type"],
                                     self.condition["date"])
     self.start_index = 1
예제 #25
0
    def exchange(self):
        """ This is the main method, is where the individuals
        are exchanged """

        if not self.isReady():
            return

        pool_to_send = self.selectPool(self.getNumIndividuals())
        pool_received = self.comm.sendrecv(sendobj=pool_to_send,
                                           dest=self.dest,
                                           sendtag=0,
                                           recvobj=None,
                                           source=self.source,
                                           recvtag=0)

        population = self.GAEngine.getPopulation()

        pool = pool_received
        for i in range(self.getNumReplacement()):
            if len(pool) <= 0:
                break

            choice = rand_choice(pool)
            pool.remove(choice)

            # replace the worst
            population[len(population) - 1 - i] = choice

        self.gather_bests()
예제 #26
0
def gen_disorder(board, n):
    """
    Use this function to verify your algorithm. It produces a disordered board
    and the corresponding solution path as output.
    """
    x = State(board, None, 0, "start")
    solutions = [x]
    for i in range(n):
        children = get_children(x)
        choice = rand_choice(children)  #pick a random child
        while choice.value in [sol.value for sol in solutions]:
            children.remove(choice)
            choice = rand_choice(children)
        solutions.append(choice)
        x = choice
    return solutions
예제 #27
0
    def _get_a_proxy(self):
        req_header = {
            'User-Agent':
            "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0",
            'Accept':
            'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Language': 'zh-CN,zh',
            'Connection': 'close',
        }
        check_url = "http://shop.10086.cn/i/v1/fee/real/15928016431?_=" + get_js_time(
        )

        for proxy in self.proxy_api.get_proxy_all():
            if proxy in self.bad_proxy:
                continue

            try:
                resp = http_get(check_url,
                                headers=req_header,
                                timeout=3,
                                proxies={'https': 'https://' + proxy})
                if b'"retCode":"' in resp.content:
                    resp = get_web_html_by_proxy(
                        "https://login.10086.cn/captchazh.htm?type=12",
                        proxies={'https': 'https://' + proxy})
                    if resp is not None:
                        return proxy
            except Exception:
                self.logger.error("proxy error")

            self.bad_proxy.add(proxy)
        else:
            return rand_choice(list(self.good_proxy))
예제 #28
0
def init_func(genome, **args):
   the_set = []
   set_size = randrange(1,MAX_SET_SIZE+1)
   for i in xrange(set_size):
      rule = [rand_choice(('0','1')) for j in xrange(RULE_SIZE)]
      the_set = the_set + rule
   genome.genomeList = the_set
예제 #29
0
    def __init__(self, sex=None):
        if not sex:
            sex = rand_choice(['Male', 'Female'])
            self.sex = sex
        else:
            self.sex = sex
        if self.sex == 'Male':
            self.first_name = rand_choice(FIRST_NAME_MALE_BASE)

        if self.sex == 'Female':
            self.first_name = rand_choice(FIRST_NAME_FEMALE_BASE)

        self.last_name = rand_choice(LAST_NAME_BASE)
        self.birth_day = get_birth_day()
        self.birth_month = get_birth_month()
        self.birth_year = get_birth_year()
예제 #30
0
 async def bot_welcome(self, member: discord.Member, guild: discord.Guild):
     bot_welcome = await self.config.guild(guild).BOTS_MSG()
     bot_role = await self.config.guild(guild).BOTS_ROLE()
     msg = bot_welcome or rand_choice(await self.config.guild(guild).GREETING())
     channel = await self.get_welcome_channel(member, guild)
     is_embed = await self.config.guild(guild).EMBED()
     if bot_role:
         try:
             role = cast(discord.abc.Snowflake, guild.get_role(bot_role))
             await member.add_roles(role, reason=_("Automatic Bot Role"))
         except Exception:
             log.error(
                 _("welcome.py: unable to add  a role. ") + f"{bot_role} {member}",
                 exc_info=True,
             )
         else:
             log.debug(
                 _("welcome.py: added ") + str(role) + _(" role to ") + _("bot, ") + str(member)
             )
     if bot_welcome:
         # finally, welcome them
         if not channel:
             return
         if is_embed and channel.permissions_for(guild.me).embed_links:
             em = await self.make_embed(member, guild, msg, False)
             if await self.config.guild(guild).EMBED_DATA.mention():
                 await channel.send(member.mention, embed=em)
             else:
                 await channel.send(embed=em)
         else:
             await channel.send(
                 filter_mass_mentions(
                     await self.convert_parms(member, guild, bot_welcome, False)
                 )
             )
예제 #31
0
파일: events.py 프로젝트: ColterD/Coda-Cogs
 async def bot_welcome(self, member, guild):
     bot_welcome = await self.config.guild(guild).BOTS_MSG()
     bot_role = await self.config.guild(guild).BOTS_ROLE()
     msg = bot_welcome or rand_choice(await
                                      self.config.guild(guild).GREETING())
     channel = await self.get_welcome_channel(member, guild)
     is_embed = await self.config.guild(guild).EMBED()
     if bot_role:
         try:
             role = guild.get_role(bot_role)
             await member.add_roles(role)
         except Exception:
             log.error(_("welcome.py: unable to add  a role. ") +
                       f"{bot_role} {member}",
                       exc_info=True)
         else:
             log.debug(
                 _("welcome.py: added ") + str(role) + _(" role to ") +
                 _("bot, ") + str(member))
     if bot_welcome:
         # finally, welcome them
         if is_embed and channel.permissions_for(guild.me).embed_links:
             em = await self.make_embed(member, guild, msg)
             if await self.config.guild(guild).EMBED_DATA.mention():
                 await channel.send(member.mention, embed=em)
             else:
                 await channel.send(embed=em)
         else:
             await channel.send(await
                                self.convert_parms(member, guild,
                                                   bot_welcome))
예제 #32
0
파일: search.py 프로젝트: menmikimen/tui03
def spawn_local_seeker(problem, location, ngh):
    """
    Create random global seeker
    :param dict problem: problem dictionary
    :param dict location: location to spawn seeker at
    :param int ngh: neighbourhood size
    :returns dict: randomly created seeker
    """
    key_list = list(problem.keys())
    changed_dimensions_count = rand_choice(list(range(1, ngh + 1)))
    changed_dimensions = rand_choices(key_list, k=changed_dimensions_count)
    new_location = copy(location)
    for changed_dimension in changed_dimensions:
        new_location[changed_dimension] = rand_choice(
            problem[changed_dimension])
    return new_location
예제 #33
0
    async def member_leave(self, member):
        server = member.server
        if server.id not in self.goodbye:
            self.goodbye[server.id] = deepcopy(default_goodbyeset)
            self.goodbye[server.id]["CHANNEL"] = server.default_channel.id
            dataIO.save_json(goodbye_path, self.goodbye)
        if not self.goodbye[server.id]["ON"]:
            return
        if server is None:
            print("Server is None. Private Message or some new fangled "
                  "Discord thing?.. Anyways there be an error, "
                  "the user was {}".format(member.name))
            return

        bot_goodbye = member.bot and self.goodbye[server.id]["BOTS_MSG"]
        msg = bot_goodbye or rand_choice(self.goodbye[server.id]["GOODBYE"])

        # grab the welcome channel
        channel = self.get_goodbye_channel(server)
        if channel is None:  # complain even if only whisper
            print('welcome.py: Channel not found. It was most '
                  'likely deleted. User joined: {}'.format(member.name))
            return
        # we can stop here
        if not self.speak_permissions(server):
            print("Permissions Error. User that joined: "
                  "{0.name}".format(member))
            print("Bot doesn't have permissions to send messages to "
                  "{0.name}'s #{1.name} channel".format(server, channel))
            return
        # finally, welcome them
        await self.bot.send_message(channel, msg.format(member, server))
예제 #34
0
    def exchange(self):
        if not self.isReady():
            return

        pool_to_send = self.selectPool(self.getNumIndividuals())

        for genome in pool_to_send:
            self.beforeSerialization(genome)

        pool_received = self.comm.sendrecv(sendobj=pool_to_send,
                                            dest=self.dest,
                                            sendtag=0,
                                            recvobj=None,
                                            source=self.source,
                                            recvtag=0)
        for genome in pool_to_send:
            self.afterSerialization(genome)

        for genome in pool_received:
            self.afterSerialization(genome)

        population = self.GAEngine.getPopulation()

        pool = pool_received
        for i in xrange(self.getNumReplacement()):
            if len(pool) <= 0:
                break

            choice = rand_choice(pool)
            pool.remove(choice)

            # replace the worst
            population[len(population) - 1 - i] = choice

        self.gather_bests()
예제 #35
0
 async def send_testing_msg(self, ctx, bot=False, msg=None):
     server = ctx.message.server
     channel = self.get_welcome_channel(server)
     rand_msg = msg or rand_choice(self.settings[server.id]["GREETING"])
     if channel is None:
         await self.bot.send_message(ctx.message.channel,
                                     "I can't find the specified channel. "
                                     "It might have been deleted.")
         return
     await self.bot.send_message(ctx.message.channel,
                                 "`Sending a testing message to "
                                 "`{0.mention}".format(channel))
     if self.speak_permissions(server):
         msg = self.settings[server.id]["BOTS_MSG"] if bot else rand_msg
         if not bot and self.settings[server.id]["WHISPER"]:
             await self.bot.send_message(ctx.message.author,
                     msg.format(ctx.message.author,server))
         if bot or self.settings[server.id]["WHISPER"] is not True:
             await self.bot.send_message(channel,
                     msg.format(ctx.message.author, server))
     else:
         await self.bot.send_message(ctx.message.channel,
                                     "I do not have permissions "
                                     "to send messages to "
                                     "{0.mention}".format(channel))
def main():
    intervals = {'major 2nd': 2,
                 'minor 3rd': 3, 'major 3rd': 4,
                 'perfect 4th': 5,
                 'perfect 5th': 7}
    interval_lookup = {}
    for key, val in intervals.copy().iteritems():
        # We don't want to modify the dict we're iterating though
        interval_lookup[val] = key  # Add the reverse to the dict

    used_tones = [False] * 12
    notes = len(Note.chromatic)
    tune = []

    def prev_interval():
        """Return the most recent interval"""
        previous_interval = (tune[-2] - tune[-1]) % notes
        # interval might not be in intervals
        if previous_interval in interval_lookup:
            previous_interval = interval_lookup[previous_interval]
        return previous_interval

    def get_new_note(pitch, interval=None):
        """This is embedded so we don't need to pass in used_tones.
        Checks that the note is valid otherwise it picks a new note and sets it
        as used"""
        if interval is not None:
            pitch = (pitch + interval) % len(Note.chromatic)
        if used_tones[pitch] is True and False in used_tones:
            pitch = rand_choice([i for i, used in enumerate(used_tones)
                                 if used is False])
        used_tones[pitch] = True
        return pitch


    tune.append(get_new_note(randint(0, notes - 1)))
    tune.append(get_new_note(tune[-1], rand_choice(intervals.values())))

    while False in used_tones:
        # intelligently choose a new pitch based on the interval between the
        # previous two
        note = get_new_note(randint(0, notes - 1))
        if randint(1, 4) > 1:  # 1 in 4 chance for a random note
            if prev_interval() == 'major 3rd':
                # if the previous interval was a minor 3rd, attempt to follow
                # it with a major 2nd
                # mod is used to stay in the octave
                note = get_new_note(tune[-1], intervals['major 2nd'])
            elif prev_interval == 'perfect 4th':
                # if the previous interval was a major 3rd, attempt to follow
                # by going down a minor 3rd
                note = get_new_note(tune[-1], -1* intervals['major 3rd'])

        tune.append(note)

    mixer.pre_init(44100, -16, 1, 1024)
    pygame.init()
    play_tune([Note.chromatic[note] for note in tune])
    pygame.quit()
예제 #37
0
def init(genome, **args):
	_set = []
	size = randrange(1,SET_SIZE +1)
	for i in xrange(size):
		rule = [ rand_choice(('0','1')) for j in xrange(RULE_SIZE)]
		_set = _set + rule
	genome.genomeString = _set
	genome.stringLength = len(_set)
예제 #38
0
def generate_operands(length):
    choices = [0, 1, 2, 3]
    operands = []

    for i in range(0, length):
        rnum = rand_choice(choices)
        operands.append(rnum)
    return operands
예제 #39
0
def GD1BinaryStringSetInitializator(genome, **args):
    """ 1D Binary String initializator """
    initial_ruleset_len = 2  #number of rules by default
    for i in range(0, initial_ruleset_len):
        #create random rule of fixed length
        rule = [rand_choice((0, 1)) for j in xrange(genome.rule_length)]
        rule = ''.join(map(str, rule))
        genome.addRuleAsString(rule)
예제 #40
0
def GD1BinaryStringSetInitializator(genome,**args):
   """ 1D Binary String initializator """
   initial_ruleset_len = 2 #number of rules by default
   for i in range(0,initial_ruleset_len):
   		#create random rule of fixed length
   		rule = [ rand_choice((0,1)) for j in xrange(genome.rule_length) ]
   		rule = ''.join(map(str,rule))
   		genome.addRuleAsString(rule)
예제 #41
0
    async def on_member_remove(self, member):
        guild = member.guild
        if not await self.config.guild(guild).LEAVE_ON():
            return
        if guild is None:
            return

        if guild.id not in self.joined:
            self.joined[guild.id] = []
        if await self.config.guild(guild).GROUPED() and member in self.joined[guild.id]:
            self.joined[guild.id].remove(member)
            return

        bot_welcome = member.bot and await self.config.guild(guild).BOTS_MSG()
        msg = bot_welcome or rand_choice(await self.config.guild(guild).GOODBYE())
        is_embed = await self.config.guild(guild).EMBED()
        delete_after = await self.config.guild(guild).DELETE_AFTER_GOODBYE()
        save_msg = None

        # grab the welcome channel
        # guild_settings = await self.config.guild(guild).guild_settings()
        channel = self.bot.get_channel(await self.config.guild(guild).LEAVE_CHANNEL())
        if channel is None:  # complain even if only whisper
            log.info(
                _("welcome.py: Channel not found in {guild}. It was most likely deleted.").format(
                    guild=guild
                )
            )
            return
        # we can stop here
        if await self.config.guild(guild).DELETE_PREVIOUS_GOODBYE():
            old_id = await self.config.guild(guild).LAST_GOODBYE()
            if channel is not None and old_id is not None:
                try:
                    old_msg = await channel.fetch_message(old_id)
                    await old_msg.delete()
                except discord.errors.NotFound:
                    log.debug(_("Message not found for deletion."))
                    pass
                except discord.errors.Forbidden:
                    await self.config.guild(guild).DELETE_PREVIOUS_GOODBYE.set(False)

        if not channel.permissions_for(guild.me).send_messages:
            log.info(_("Permissions Error in {guild}"))
            return
        elif not member.bot:
            if is_embed and channel.permissions_for(guild.me).embed_links:
                em = await self.make_embed(member, guild, msg, False)
                if await self.config.guild(guild).EMBED_DATA.mention():
                    save_msg = await channel.send(member.mention, embed=em, delete_after=delete_after)
                else:
                    save_msg = await channel.send(embed=em, delete_after=delete_after)
            else:
                save_msg = await channel.send(
                    await self.convert_parms(member, guild, msg, False),
                    delete_after=delete_after)
        if save_msg is not None:
            await self.config.guild(guild).LAST_GOODBYE.set(save_msg.id)
예제 #42
0
 def generate_colors(self, num=None):
     if num:
         to_generate = num
     else:
         to_generate = len(self.empty_cells) if len(
             self.empty_cells) < self.spawn_count else self.spawn_count
     for i in range(to_generate):
         color = rand_choice(self.game_colors)
         self.colors_to_spawn.append(color)
예제 #43
0
def seed_next_random():
    """
    Generates a redirect view to a random Place object (State, ZipCode, or County)
    and caches it. Picking a random place is expensive on the DB and CPU since there
    are over 40000 objects that it picks from, which strains the DB (since it causes
    an iteration over the objects to select the ID).
    
    See random_place() below, for notes on usage.
    """
    response = None
    while not response:
        try:
            PlaceClass = rand_choice([State,ZipCode,County])
            
            # Cached list of all of the ID numbers for this place type.
            cache_key = "all_ids: %s" % (PlaceClass.__name__)
            all_ids = safe_get_cache(cache_key)
            if not all_ids:
                all_ids = PlaceClass.objects.only('id').order_by().values_list('pk') # [(0,),(1,),...]
                all_ids = map(lambda x: x[0], all_ids) # pull ID out of tuples for a "regular" list
                safe_set_cache(cache_key,all_ids,604800)
            
            rand_id = rand_choice(all_ids)
            
            if PlaceClass.__name__ == "County":
                place = PlaceClass.objects.get(pk=rand_id)
                url = reverse("places:county_detail",args=(place.state.abbr.lower(),urlencode(place.name.lower())),current_app="places")
                call_in_bg(county_detail, (None, place.state.abbr.lower(),urlencode(place.name.lower())))
            elif PlaceClass.__name__ == "State":
                place = PlaceClass.objects.only('slug').get(pk=rand_id)
                url = reverse("places:state_detail",args=(place.slug,),current_app="places")
                call_in_bg(state_detail, (None, place.slug))
            else:
                place = PlaceClass.objects.only('slug').get(pk=rand_id)
                url = reverse("places:zipcode_detail",args=(place.slug,),current_app="places")
                call_in_bg(zipcode_detail, (None, place.slug))
            response = HttpResponseRedirect(url)
        except:
            from traceback import print_exc
            print_exc()
            response = None
    safe_set_cache("random_place",response,604800)
    
    return response
 def get_new_note(pitch, interval=None):
     """This is embedded so we don't need to pass in used_tones.
     Checks that the note is valid otherwise it picks a new note and sets it
     as used"""
     if interval is not None:
         pitch = (pitch + interval) % len(Note.chromatic)
     if used_tones[pitch] is True and False in used_tones:
         pitch = rand_choice([i for i, used in enumerate(used_tones)
                              if used is False])
     used_tones[pitch] = True
     return pitch
예제 #45
0
   def getRandomNode(self, node_type=0):
      """ Returns a random node from the Tree

      :param node_type: 0 = Any, 1 = Leaf, 2 = Branch
      :rtype: random node
      """
      lists = (self.nodes_list, self.nodes_leaf, self.nodes_branch)
      cho = lists[node_type]
      if len(cho) <= 0:
         return None
      return rand_choice(cho)
예제 #46
0
def G2DBinaryStringInitializator(genome, **args):
   """ Integer initialization function of 2D Binary String
   
   .. versionadded:: 0.6
      The *G2DBinaryStringInitializator* function
   """
   genome.clearString()
   
   for i in xrange(genome.getHeight()):
      for j in xrange(genome.getWidth()):
         random_gene = rand_choice((0,1))
         genome.setItem(i, j, random_gene)
예제 #47
0
   def applyFunctions(self, obj, **args):
      """ Generator to apply all function slots in obj

      :param obj: this object is passes as parameter to the function
      :param args: this args dictionary is passed to the function   

      """
      if len(self.funcList) <= 0:
         raise Exception("No function defined: " + self.slotName)
      if not self.rand_apply:
         for f in self.funcList:
            yield f(obj, **args)
      else:
         yield rand_choice(self.funcList)(obj, **args)
예제 #48
0
 def create_random_form(self):
     code = ""
     for i in range(randint(4, 15)):
         code += rand_choice(COMMANDS)
     tries = 5
     while tries > 0:
         x = randint(0, WORLD_SIZE - 1)
         y = randint(0, WORLD_SIZE - 1)
         if self.worldmap[(x, y)] is None:
             form = LifeForm(self, code, x, y)
             self.lifeforms.append(form)
             self.worldmap[(x, y)] = form
             break
         tries -= 1
예제 #49
0
파일: GTree.py 프로젝트: tomerf/Pyevolve
   def getRandomNode(self, node_type=0, out_type=0, in_type=0):
      """ Returns a random node from the Tree

      :param node_type: 0 = Any, 1 = Leaf, 2 = Branch
      :param out_type: the type returned to the node's parent
      :param in_type: the type returned from the node's children
      :rtype: random node
      """
      lists = (self.nodes_list, self.nodes_leaf, self.nodes_branch)
      cho = lists[node_type]
      if node_type == 2:
         cho = [c for c in cho if c.getOutType() == out_type and c.getInType() == in_type]
      if len(cho) <= 0:
         return None
      return rand_choice(cho)
예제 #50
0
def random_place(request):
    """
    If a random place is in the cache, use it and return that to the user.
    If not, generate one right now.
    
    Before returning to the user, queue up a background task that generates
    the next random place, to save DB/CPU usage when responding to user. (Prevents
    this view from locking up while Django picks a suitable random object.)
    """
    response = None
    while not response:
        try:
            PlaceClass = rand_choice([State,County])
            
            # Cached list of all of the ID numbers for this place type.
            cache_key = "all_ids: %s" % (PlaceClass.__name__)
            all_ids = safe_get_cache(cache_key)
            if not all_ids:
                all_ids = PlaceClass.objects.only('id').order_by().values_list('pk') # [(0,),(1,),...]
                all_ids = map(lambda x: x[0], all_ids) # pull ID out of tuples for a "regular" list
                safe_set_cache(cache_key,all_ids,604800)
            
            rand_id = rand_choice(all_ids)
            
            if PlaceClass.__name__ == "County":
                place = PlaceClass.objects.get(pk=rand_id)
                url = reverse("places:county_detail",args=(place.state.abbr.lower(),urlencode(place.name.lower())),current_app="places")
            else:
                place = PlaceClass.objects.only('slug').get(pk=rand_id)
                url = reverse("places:state_detail",args=(place.slug,),current_app="places")
            response = HttpResponseRedirect(url)
        except:
            from traceback import print_exc
            print_exc()
            response = None
    return response
예제 #51
0
def Pruner(genome):
    missing = []
    doubles = []
    for i in xrange(genome.getListSize()):
        c = genome.genomeList.count(i)
        if (c == 0):
            missing.append(i)
        if (c > 1):
            doubles.append(i)
    
    for d in doubles:
        indices = [i for i,j in enumerate(genome) if (j == d)]
        for i in indices[1:]:
            y = rand_choice(xrange(len(missing)))
            genome[i] = missing[y]
            missing.remove(missing[y])
예제 #52
0
 async def welcomeset(self, ctx):
     """Sets welcome module settings"""
     server = ctx.message.server
     if server.id not in self.settings:
         self.settings[server.id] = deepcopy(default_settings)
         self.settings[server.id]["CHANNEL"] = server.default_channel.id
         dataIO.save_json(settings_path, self.settings)
     if ctx.invoked_subcommand is None:
         await send_cmd_help(ctx)
         msg = "```"
         msg += "Random GREETING: {}\n".format(rand_choice(self.settings[server.id]["GREETING"]))
         msg += "CHANNEL: #{}\n".format(self.get_welcome_channel(server))
         msg += "ON: {}\n".format(self.settings[server.id]["ON"])
         msg += "WHISPER: {}\n".format(self.settings[server.id]["WHISPER"])
         msg += "BOTS_MSG: {}\n".format(self.settings[server.id]["BOTS_MSG"])
         msg += "BOTS_ROLE: {}\n".format(self.settings[server.id]["BOTS_ROLE"])
         msg += "```"
         await self.bot.say(msg)
예제 #53
0
파일: gct.py 프로젝트: glasperfan/thesis
def optimalchoice(choices):
    # Dyads: select 5th over 4th, 7th over 2nd
    if len(choices[0][1]) == 2:
        for choice in choices:
            if sum(choice[1]) > 6: # 6 semitones
                return choice
    choices_f = [x for x in choices if x[1][1] < 9]
    for choice in choices_f:
        # Select dominant chords with the correct root
        if choice[1] == DOMINANT:
            return choice
    # Prefer chords with intervals larger than major 2nd (i.e. to select minor 7ths or major chords with add 6th)
    for choice in choices_f:
        intervals = chord_to_intervals(choice[1])
        if all(x > 2 for x in intervals):
            return choice
    # If all else fails, choose randomly
    return rand_choice(choices_f)
예제 #54
0
    def exchange(self):
        """ This is the main method, is where the individuals
        are exchanged """

        if not self.isReady():
            return

        # Client section --------------------------------------
        # How many will migrate ?
        pool = self.selectPool(self.getNumIndividuals())

        for individual in pool:
            # (code, group name, individual)
            networkObject = (Consts.CDefNetworkIndividual,
                             self.getGroupName(), individual)
            networkData = Network.pickleAndCompress(
                networkObject, self.getCompressionLevel())
            # Send the individuals to the topology
            self.clientThread.addData(networkData)

        # Server section --------------------------------------
        pool = []
        while self.serverThread.isReady():
            # (IP source, data)
            networkData = self.serverThread.popPool()
            networkObject = Network.unpickleAndDecompress(networkData[1])
            # (code, group name, individual)
            pool.append(networkObject)

        # No individuals received
        if len(pool) <= 0:
            return

        population = self.GAEngine.getPopulation()

        for i in xrange(self.getNumReplacement()):
            if len(pool) <= 0:
                break
            choice = rand_choice(pool)
            pool.remove(choice)

            # replace the worst
            population[len(population) - 1 - i] = choice[2]
예제 #55
0
    def play_fx(self, sound_name, loops=0, key=None):
        """Plays a preloaded sound effect using the first available channel.

        :param: sound_name: The sound name (without extension).
        :type sound_name: :class:`str`

        :param loops: Number of times to play through the sound.
        :type loops: :class:`int`

        :param key: The key to be used to identify the sound
        :type key: :class:`int`
        """
        sounds = self.sounds[sound_name]
        filepath, sound = rand_choice(sounds)
        channel = Mix_PlayChannel(-1, sound, loops)
        if channel == -1:
            LOG.error('Cannot play sound "{}: {}"'.format(
                sound_name, filepath))
        elif key is not None:
            self.sound_map[key] = channel
예제 #56
0
 def pull_card(self):
     """Funcdoc."""
     card = rand_choice(self.cards)
     self.cards.remove(card)
     return card
예제 #57
0
 def pull_card(self):
     """Funcdoc."""
     deck = rand_choice(self.decks)
     if deck and len(deck) > 0:
         return deck.pull_card()
     return False
예제 #58
0
def G1DBinaryStringInitializator(genome, **args):
   """ 1D Binary String initializator """
   genome.genomeList = [ rand_choice((0,1)) for i in xrange(genome.getListSize()) ]