def crossover_pivot(cls, rules_set_1, rules_set_2):
        """
        1. Select pivot locus <i> in rule sets A and B
        2. All rules up until <i> remain in original set
        3. Rules A[i] and B[i] in each set is crossed-over:
            a. Its parameters (target, change, left context, right context, optionality) are crossed-over with uniform probability
        4. Rules after <i> are switched between the two sets
        """
        num_rules_1 = len(rules_set_1.rules)
        num_rules_2 = len(rules_set_2.rules)
        max_rules = max(num_rules_1, num_rules_2)

        if max_rules == 0:
            return rules_set_1, rules_set_2

        rules_1 = deepcopy(rules_set_1.rules)
        rules_2 = deepcopy(rules_set_2.rules)

        # pad the rule-set that has fewer rules
        rules_1 += [None] * (max_rules - num_rules_1)
        rules_2 += [None] * (max_rules - num_rules_2)

        locus = randrange(max_rules)
        print(locus)

        offspring_1_rules = []
        offspring_2_rules = []
        for i in range(max_rules):
            rule_1 = rules_1[i]
            rule_2 = rules_2[i]

            if i < locus:
                rule_for_offspring_1 = rule_1
                rule_for_offspring_2 = rule_2

            if i == locus:
                rule_for_offspring_1, rule_for_offspring_2 = cls._crossover_rule_pair(
                    rule_1, rule_2)

            if i > locus:
                rule_for_offspring_1 = rule_2
                rule_for_offspring_2 = rule_1

            if rule_for_offspring_1 is not None:
                offspring_1_rules.append(rule_for_offspring_1)
            if rule_for_offspring_2 is not None:
                offspring_2_rules.append(rule_for_offspring_2)

        offspring_1_rules = deepcopy(offspring_1_rules)
        offspring_2_rules = deepcopy(offspring_2_rules)

        return RuleSet(offspring_1_rules), RuleSet(offspring_2_rules)
    def crossover(self, h1, h2):
        if GeneticAlgorithm._is_incest(h1, h2):
            return h1, h2,

        crossover_rules = False
        crossover_hmm = False
        if ga_config.CROSSOVER_BOTH_HMM_AND_RULES:
            if configurations["EVOLVE_RULES"]:
                crossover_rules = True
            if configurations["EVOLVE_HMM"]:
                crossover_hmm = True

        else:
            loci = []
            if configurations["EVOLVE_RULES"]:
                loci.append('rules')
            if configurations["EVOLVE_HMM"]:
                loci.append('hmm')
            locus = random.choice(loci)

            if locus == 'rules':
                crossover_rules = True
            elif locus == 'hmm':
                crossover_hmm = True

        offspring_1 = deepcopy(h1)
        offspring_2 = deepcopy(h2)

        if crossover_rules:
            offspring_1_rule_set, offspring_2_rule_set = RuleSet.crossover(
                offspring_1.grammar.rule_set, offspring_2.grammar.rule_set)
        else:
            offspring_1_rule_set, offspring_2_rule_set = offspring_1.grammar.rule_set, offspring_2.grammar.rule_set

        if crossover_hmm:
            offspring_1_hmm, offspring_2_hmm = HMM.crossover(
                offspring_1.grammar.hmm, offspring_2.grammar.hmm)
        else:
            offspring_1_hmm, offspring_2_hmm = offspring_1.grammar.hmm, offspring_2.grammar.hmm

        offspring_1.grammar = Grammar(offspring_1_hmm, offspring_1_rule_set)
        offspring_2.grammar = Grammar(offspring_2_hmm, offspring_2_rule_set)

        # Invalidate mutated offspring fitness value (i.e. mark for re-evaluation)
        offspring_1.invalidate_fitness()
        offspring_1.invalidate_energy()
        offspring_2.invalidate_fitness()
        offspring_2.invalidate_energy()

        return offspring_1, offspring_2,
 def mutate(hypothesis):
     new_hypothesis = deepcopy(hypothesis)
     success = new_hypothesis.grammar.make_mutation()
     if success:
         # Invalidate mutated offspring energy and fitness value (i.e. mark for re-evaluation)
         new_hypothesis.invalidate_energy()
         new_hypothesis.invalidate_fitness()
         return new_hypothesis,
     return hypothesis,
    def crossover_unilateral(cls, rule_set_1, rule_set_2):
        """ Uniformly select rules from rule set 2, add them to rule set 1 at their original index in set 2"""

        num_rules_in_source = len(rule_set_2.rules)
        if num_rules_in_source == 0 or len(
                rule_set_1.rules) == configurations["MAX_NUMBER_OF_RULES"]:
            return rule_set_1, rule_set_2

        offspring_1 = deepcopy(rule_set_1)
        offspring_2 = deepcopy(rule_set_2)

        transition_probab = 1 / max(1, log(num_rules_in_source, 2))
        for source_rule_idx, source_rule in enumerate(rule_set_2.rules):
            if len(offspring_1.rules) == configurations["MAX_NUMBER_OF_RULES"]:
                break

            if random() < transition_probab:
                offspring_1.rules.insert(source_rule_idx, source_rule)

        return offspring_1, offspring_2
 def init_target_hypothesis(self):
     target_tuple = self.simulation.target_tuple
     target_rule_set = RuleSet.load_form_flat_list(target_tuple[1])
     target_hypothesis = Hypothesis.create_hypothesis(
         HMM(deepcopy(target_tuple[0])), target_rule_set)
     target_energy = target_hypothesis.get_energy()
     self.logger.info('Target hypothesis:')
     log_hypothesis(target_hypothesis, self.logger.info)
     self.logger.info('Target energy: {}'.format(target_energy))
     self.logger.info('Target hypothesis energy signature: {}'.format(
         target_hypothesis.get_recent_energy_signature()))
     return target_hypothesis, target_energy
    def crossover_old(cls, rules_set_1, rules_set_2):
        rules_1 = deepcopy(rules_set_1.rules)
        rules_2 = deepcopy(rules_set_2.rules)

        rule_idx_1, crossover_rule_1, is_null_1 = cls._select_rule_for_crossover(
            rules_1)
        rule_idx_2, crossover_rule_2, is_null_2 = cls._select_rule_for_crossover(
            rules_2)

        if is_null_1 or is_null_2:
            offspring_1_rule_set = RuleSet(rules_2)
            offspring_2_rule_set = RuleSet(rules_1)
        else:
            # TODO Randomize crossover locus
            rule_offspring_1 = Rule(
                target=crossover_rule_1.target_feature_bundle_list,
                change=crossover_rule_1.change_feature_bundle_list,
                left_context=crossover_rule_2.left_context_feature_bundle_list,
                right_context=crossover_rule_2.
                right_context_feature_bundle_list,
                obligatory=crossover_rule_2.obligatory)

            rule_offspring_2 = Rule(
                target=crossover_rule_2.target_feature_bundle_list,
                change=crossover_rule_2.change_feature_bundle_list,
                left_context=crossover_rule_1.left_context_feature_bundle_list,
                right_context=crossover_rule_1.
                right_context_feature_bundle_list,
                obligatory=crossover_rule_1.obligatory)

            offspring_1_rule_set = RuleSet(rules_1[:rule_idx_1] +
                                           [rule_offspring_1] +
                                           rules_2[rule_idx_2 + 1:])
            offspring_2_rule_set = RuleSet(rules_2[:rule_idx_2] +
                                           [rule_offspring_2] +
                                           rules_1[rule_idx_1 + 1:])

        return offspring_1_rule_set, offspring_2_rule_set
Example #7
0
    def crossover_uniform(cls, rules_set_1, rules_set_2):
        """
        For each rule pair r1, r2 in parent rule-sets A, B, select whether to switch between r1, r2.
        If one rule-set has more rules than the other, rules can be moved instead of switching.
        """

        num_rules_1 = len(rules_set_1.rules)
        num_rules_2 = len(rules_set_2.rules)
        max_rules = max(num_rules_1, num_rules_2)

        if max_rules == 0:
            return rules_set_1, rules_set_2

        rules_1 = deepcopy(rules_set_1.rules)
        rules_2 = deepcopy(rules_set_2.rules)

        rule_idx_should_cross_over = [randint(0, 1) for _ in range(max_rules)]

        # pad the rule-set that has fewer rules
        rules_1 += [None] * (max_rules - num_rules_1)
        rules_2 += [None] * (max_rules - num_rules_2)

        rules = [rules_1, rules_2]

        offspring_1_rules = []
        offspring_2_rules = []
        for i in range(max_rules):
            rule_for_offspring_1 = rules[rule_idx_should_cross_over[i]][i]
            rule_for_offspring_2 = rules[rule_idx_should_cross_over[i] - 1][i]

            if rule_for_offspring_1 is not None:
                offspring_1_rules.append(rule_for_offspring_1)
            if rule_for_offspring_2 is not None:
                offspring_2_rules.append(rule_for_offspring_2)

        return RuleSet(offspring_1_rules), RuleSet(offspring_2_rules)
Example #8
0
    def run(self):

        if self.getTime() < 2.0:
            walk_request.noWalk()
            kick_request.setNoKick()
            commands.setStiffness(cfgstiff.One, 0.3)
            return

        st = self.state

        if st.inState(st.stop):
            st.transition(st.checkarms)

        if st.inState(st.checkarms):
            shoulderCutoff = core.DEG_T_RAD * -90
            lpitch = core.joint_values[core.LShoulderPitch]
            rpitch = core.joint_values[core.RShoulderPitch]
            if lpitch > shoulderCutoff and rpitch > shoulderCutoff:
                st.transition(st.sit)
            else:
                st.transition(st.movearms)
        elif st.inState(st.movearms):
            pose = util.deepcopy(cfgpose.sittingPoseV3)
            for joint, val in cfgpose.armSidePose.items():
                pose[joint] = val
            st.transition(st.sit)
            return ToPoseMoveHead(tilt=0.0, pose=pose)
        elif st.inState(st.sit):
            self.skippedState = False
            st.transition(st.relaxknee)
            return ToPoseMoveHead(pose=cfgpose.sittingPoseV3, time=1.0)
        elif st.inState(st.relaxknee):
            self.lower_time = self.getTime()
            commands.setStiffness(cfgstiff.ZeroKneeAnklePitch, 0.3)
            st.transition(st.relaxbody)
        elif st.inState(st.relaxbody) and st.timeSinceTransition() > 0.7:
            commands.setStiffness(cfgstiff.Zero, 0.3)
            st.transition(st.finish)
        elif st.inState(st.finish):
            self.finish()
Example #9
0
  def run(self):
        
    if self.getTime() < 2.0:
      core.walk_request.noWalk()
      core.kick_request.setNoKick()
      commands.setStiffness(cfgstiff.One, 0.3)
      return

    st = self.state

    if st.inState(st.stop):
      st.transition(st.checkarms)

    if st.inState(st.checkarms):
      shoulderCutoff = core.DEG_T_RAD * -90
      if percepts.joint_angles[core.LShoulderPitch] > shoulderCutoff and percepts.joint_angles[core.RShoulderPitch] > shoulderCutoff:
        st.transition(st.sit)
      else:
        st.transition(st.movearms)
    elif st.inState(st.movearms):
      pose = util.deepcopy(cfgpose.sittingPoseV3)
      for joint, val in cfgpose.armSidePose.items():
        pose[joint] = val
      self.subtask = skills.ToPoseMoveHead(tilt = 0.0, pose = pose)
      self.subtask.start()
      st.transition(st.sit)
    elif st.inState(st.sit) and (not self.subtask or self.subtask.finished()):
      self.skippedState = False
      self.subtask = skills.ToPoseMoveHead(pose = cfgpose.sittingPoseV3, time = 1.0)
      self.subtask.start()
      st.transition(st.relaxknee)
    elif st.inState(st.relaxknee) and self.subtask.finished():
      self.lower_time = self.getTime()
      commands.setStiffness(cfgstiff.ZeroKneeAnklePitch, 0.3)
      st.transition(st.relaxbody)
    elif st.inState(st.relaxbody) and st.timeSinceTransition() > 0.7:
      commands.setStiffness(cfgstiff.Zero, 0.3)
      st.transition(st.finish)
    elif st.inState(st.finish):
      self.finish()
Example #10
0
  def run(self):
        
    if self.getTime() < 2.0:
      walk_request.noWalk()
      kick_request.setNoKick()
      commands.setStiffness(cfgstiff.One, 0.3)
      return

    st = self.state

    if st.inState(st.stop):
      st.transition(st.checkarms)

    if st.inState(st.checkarms):
      shoulderCutoff = core.DEG_T_RAD * -90
      lpitch = core.joint_values[core.LShoulderPitch] 
      rpitch = core.joint_values[core.RShoulderPitch]
      if lpitch > shoulderCutoff and rpitch > shoulderCutoff:
        st.transition(st.sit)
      else:
        st.transition(st.movearms)
    elif st.inState(st.movearms):
      pose = util.deepcopy(cfgpose.sittingPoseV3)
      for joint, val in cfgpose.armSidePose.items():
        pose[joint] = val
      st.transition(st.sit)
      return ToPoseMoveHead(tilt = 0.0, pose = pose)
    elif st.inState(st.sit):
      self.skippedState = False
      st.transition(st.relaxknee)
      return ToPoseMoveHead(pose = cfgpose.sittingPoseV3)
    elif st.inState(st.relaxknee):
      self.lower_time = self.getTime()
      commands.setStiffness(cfgstiff.ZeroKneeAnklePitch, 0.3)
      st.transition(st.relaxbody)
    elif st.inState(st.relaxbody) and st.timeSinceTransition() > 0.7:
      commands.setStiffness(cfgstiff.Zero, 0.3)
      st.transition(st.finish)
    elif st.inState(st.finish):
      self.finish()
Example #11
0
    def __init__(self,
                 blocks,
                 total_cells,
                 netlists,
                 raw_netlist,
                 board,
                 board_pos,
                 is_legal=None,
                 fold_reg=True,
                 seed=0):
        """Please notice that netlists has to be prepared already, i.e., replace
        the remote partition with a pseudo block.
        Also assumes that available_pos is the same size as blocks. If not,
        you have to shrink it the available_pos.
        The board can be an empty board.
        """
        self.blocks = blocks
        # TODO:
        # switch every thing into dictionary based
        available_pos = total_cells["p"]
        self.total_cells = total_cells
        self.available_pos = available_pos
        self.netlists = netlists
        self.blk_pos = board_pos
        self.board = board
        if fold_reg:
            assert (len(blocks) >= len(available_pos))
        else:
            assert (len(blocks) == len(available_pos))
        if is_legal is None:
            if fold_reg:
                self.is_legal = self.__is_legal_fold
            else:
                self.is_legal = lambda pos, blk_id, s: True
        else:
            self.is_legal = is_legal
        self.fold_reg = fold_reg

        # figure out which position on which regs cannot be on the top

        self.reg_no_pos = {}
        if fold_reg:
            linked_nets, _, _ = group_reg_nets(raw_netlist)
            for net_id in netlists:
                net = netlists[net_id]
                if net_id in linked_nets:
                    for reg_net_id in linked_nets[net_id]:
                        if reg_net_id in netlists:
                            net += netlists[reg_net_id]
                for blk in net:
                    # we only care about the wire it's driving
                    if blk[0] == "r" and blk in self.blocks:
                        if blk not in self.reg_no_pos:
                            self.reg_no_pos[blk] = set()
                        for bb in net:
                            if bb == blk:
                                continue
                            if bb in self.blocks:
                                self.reg_no_pos[blk].add(bb)

        rand = random.Random()
        rand.seed(seed)
        state = self.__init_placement(rand)

        Annealer.__init__(self, initial_state=state, rand=rand)

        # schedule
        self.steps = len(blocks) * 125
        self.num_nets = len(netlists)

        # fast calculation
        self.moves = set()
        self.blk_index = self.__index_netlists(netlists, blocks)

        self.pre_state = deepcopy(state)
        self.pre_energy = self.init_energy()
Example #12
0
    def __init_placement(self, rand):
        # filling in PE tiles first
        pos = list(self.available_pos)
        num_pos = len(pos)
        state = {}
        pe_blocks = [b for b in self.blocks if b[0] == "p"]
        pe_blocks.sort(key=lambda x: int(x[1:]))
        reg_blocks = [b for b in self.blocks if b[0] == "r"]
        reg_blocks.sort(key=lambda x: int(x[1:]))
        special_blocks = [
            b for b in self.blocks
            if b not in pe_blocks and b not in reg_blocks
        ]
        # make sure there is enough space
        assert (max(len(pe_blocks), len(reg_blocks) < len(pos)))
        total_blocks = pe_blocks + reg_blocks

        board = {}
        pos_index = 0
        index = 0
        while index < len(total_blocks):
            blk_id = total_blocks[index]
            new_pos = pos[pos_index % num_pos]
            pos_index += 1
            if new_pos not in board:
                board[new_pos] = []
            if len(board[new_pos]) > 1:
                continue
            if blk_id[0] == "p":
                if len(board[new_pos]) > 0 and board[new_pos][0][0] == "p":
                    continue
                # make sure we're not putting it in the reg net
                elif len(board[new_pos]) > 0 and board[new_pos][0][0] == "r":
                    reg = board[new_pos][0]
                    if reg in self.reg_no_pos and \
                            blk_id in self.reg_no_pos[reg]:
                        continue
                board[new_pos].append(blk_id)
                state[blk_id] = new_pos
                index += 1
            else:
                if len(board[new_pos]) > 0 and board[new_pos][0][0] == "r":
                    continue
                    # make sure we're not putting it in the reg net
                elif len(board[new_pos]) > 0 and board[new_pos][0][0] == "p":
                    p_block = board[new_pos][0]
                    if blk_id in self.reg_no_pos and \
                            p_block in self.reg_no_pos[blk_id]:
                        continue
                board[new_pos].append(blk_id)
                state[blk_id] = new_pos
                index += 1

        # place special blocks
        special_cells = deepcopy(self.total_cells)
        for blk_type in special_cells:
            blks = [b for b in special_blocks if b[0] == blk_type]
            if len(blks) == 0:
                continue
            # random pick up some blocks
            available_cells = special_cells[blk_type]
            cells = rand.sample(available_cells, len(blks))
            for i in range(len(blks)):
                state[blks[i]] = cells[i]

        return state
Example #13
0
 def copy_resource(routing_resource):
     res = deepcopy(routing_resource)
     return res