Beispiel #1
0
def GTreeGPInitializator(genome, **args):
   """This initializator accepts the follow parameters:
      
   *max_depth*
      The max depth of the tree

   *method*
      The method, accepts "grow", "full" or "ramped"

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

   max_depth = genome.get_param("max_depth", 5)
   method    = genome.get_param("method", "grow")
   ga_engine = args["ga_engine"]

   if method == "grow":
      root = gtree_utils.buildGTreeGPGrow(ga_engine, 0, max_depth)
   elif method == "full":
      root = gtree_utils.buildGTreeGPFull(ga_engine, 0, max_depth)
   elif method == "ramped":
      if utils.random_flip_coin(0.5):
         root = gtree_utils.buildGTreeGPFull(ga_engine, 0, max_depth)
      else:
         root = gtree_utils.buildGTreeGPGrow(ga_engine, 0, max_depth)
   else:
      utils.raise_exception("Unknown tree initialization method [%s] !" % method)

   genome.setRoot(root)
   genome.processNodes()
   assert genome.get_height() <= max_depth
Beispiel #2
0
def GTreeGPMutatorSubtree(genome, **args):
   """ The mutator of GTreeGP, Subtree Mutator

   This mutator will recreate random subtree of the tree using the grow algorithm.
   
   .. versionadded:: 0.6
      The *GTreeGPMutatorSubtree* function
   """

   if args["pmut"] <= 0.0: return 0
   ga_engine = args["ga_engine"]
   max_depth = genome.get_param("max_depth", None)
   mutations = 0

   if max_depth is None:
      utils.raise_exception("You must specify the max_depth genome parameter !", ValueError)
      
   if max_depth < 0:
      utils.raise_exception("The max_depth must be >= 1, if you want to use GTreeGPMutatorSubtree crossover !", ValueError)

   branch_list = genome.nodes_branch
   elements = len(branch_list)
   
   for i in xrange(elements):

      node = branch_list[i]
      assert node is not None

      if utils.random_flip_coin(args["pmut"]):
         depth = genome.getNodeDepth(node)
         mutations += 1

         root_subtree = gtree_utils.buildGTreeGPGrow(ga_engine, 0, max_depth-depth)
         node_parent = node.getParent()

         if node_parent is None:
            genome.setRoot(root_subtree)
            genome.processNodes()
            return mutations
         else:
            root_subtree.setParent(node_parent)
            node_parent.replaceChild(node, root_subtree)
         genome.processNodes()
   
   return int(mutations)