コード例 #1
0
 def __call__(self, func):
     if self.on_individual:
         if self.names:
             for name in self.names:
                 GLOBAL_ESDL_FUNCTIONS[name] = OnIndividual(name, func)
         else:
             GLOBAL_ESDL_FUNCTIONS[func.__name__] = OnIndividual(
                 func.__name__, func)
     else:
         if self.names:
             for name in self.names:
                 GLOBAL_ESDL_FUNCTIONS[name] = func
         else:
             GLOBAL_ESDL_FUNCTIONS[func.__name__] = func
     return func
コード例 #2
0
def test_recombiners_Discrete_Selection_All():
    population = make_pop()

    _gen = OnIndividual('crossover_discrete')(_source=iter(population),
                                              two_children=True)
    offspring = list(_gen)
    print "len(offspring) = %d, len(population) = %d" % (len(offspring),
                                                         len(population))
    assert len(offspring) == len(population), "Did not select all individuals"
    print "intersection = %s" % set(offspring).intersection(set(population))
    assert len(set(offspring).intersection(
        set(population))) == 0, "Did not modify some individuals"
コード例 #3
0
def test_recombiners_Segmented_None():
    population = make_pop()
    _gen = OnIndividual('crossover_segmented')(_source=iter(population),
                                               per_pair_rate=0.0,
                                               two_children=True)
    offspring = list(_gen)
    print "len(offspring) = %d, len(population) = %d" % (len(offspring),
                                                         len(population))
    assert len(offspring) == len(population), "Did not select all individuals"
    print "difference = %s" % set(offspring).difference(set(population))
    assert len(set(offspring).difference(
        set(population))) == 0, "Modified some individuals"
コード例 #4
0
def test_recombiners_PerGeneTuple_None():
    population = make_pop()
    joined = list(joiners.DistinctRandomTuples(_source=[population] * 2))

    _gen = OnIndividual('crossover_tuple')(_source=iter(joined),
                                           per_indiv_rate=1.0,
                                           greediness=1.0)
    offspring = list(_gen)
    print "len(offspring) = %d, len(population) = %d" % (len(offspring),
                                                         len(population))
    assert len(offspring) == len(population), "Did not select all individuals"
    assert all(g1 is g2 for g1, g2 in izip(
        population, offspring)), "Did not return first individual"
コード例 #5
0
def test_recombiners_SingleDifferent_Selection_Half():
    population = make_pop_variable(shortest=4)

    modify_count = 0
    for _ in xrange(100):
        _gen = OnIndividual('crossover_one_different')(
            _source=iter(population), per_pair_rate=0.5, two_children=True)
        offspring = list(_gen)
        assert len(offspring) == len(
            population), "Did not select all individuals"
        modify_count += len(set(offspring).difference(set(population)))
    modify_rate = float(modify_count) / (100.0 * len(population))
    assert 0.4 <= modify_rate <= 0.6, "Did not modify approximately 50% of individuals"
コード例 #6
0
def test_recombiners_SingleDifferent_Selection_All():
    population = make_pop_variable(shortest=4)

    _gen = OnIndividual('crossover_different')(_source=iter(population),
                                               points=1,
                                               two_children=True)
    offspring = list(_gen)
    print "len(offspring) = %d, len(population) = %d" % (len(offspring),
                                                         len(population))
    assert len(offspring) == len(population), "Did not select all individuals"
    print "intersection = %s" % set(offspring).intersection(set(population))
    assert len(set(offspring).intersection(
        set(population))) == 0, "Did not modify some individuals"

    _gen = OnIndividual('crossover_different')(_source=iter(population),
                                               points=2,
                                               two_children=True)
    offspring = list(_gen)
    print "len(offspring) = %d, len(population) = %d" % (len(offspring),
                                                         len(population))
    assert len(offspring) == len(population), "Did not select all individuals"
    print "intersection = %s" % set(offspring).intersection(set(population))
    assert len(set(offspring).intersection(
        set(population))) == 0, "Did not modify some individuals"
コード例 #7
0
def test_recombiners_Discrete_Values():
    population = make_pop()

    _gen = OnIndividual('crossover_discrete')(_source=iter(population),
                                              two_children=True)
    children = list(_gen)
    child1, child2 = children[0:2]
    print "len(child1) = %d, len(child2) = %d, len(population[0]) = %d" % (
        len(child1), len(child2), len(population[0]))
    assert len(child1) == len(child2) == len(
        population[0]), "Individual's length was changed"
    print '\n'.join(str(set(child)) for child in children)
    assert not all(len(set(child)) != 2
                   for child in children), "Number of distinct values is not 2"
    child1_set, child2_set = set(child1.genome), set(child2.genome)
    print "set(child1) = %s" % child1_set
    print "set(child2) = %s" % child2_set
    assert child1_set == child2_set, "Distinct values are not matched"
コード例 #8
0
def test_recombiners_PerGeneTuple_NotFromFirst():
    population = make_pop()
    joined = list(joiners.DistinctRandomTuples(_source=[population] * 2))

    _gen = OnIndividual('crossover_tuple')(_source=iter(joined),
                                           per_indiv_rate=1.0,
                                           greediness=0.0)
    offspring = list(_gen)
    print "len(offspring) = %d, len(population) = %d" % (len(offspring),
                                                         len(population))
    assert len(offspring) == len(population), "Did not select all individuals"
    assert all(
        g1 is not g2
        for g1, g2 in izip(population, offspring)), "DistinctRandom failed"
    assert all(g not in population
               for g in offspring), "Some individuals were not cloned"
    assert sum(g.statistic.get('recombined', 0) for g in offspring) == len(
        offspring), "Some individuals were not recombined"
コード例 #9
0
def test_recombiners_Segmented_Normal():
    population = make_pop()
    _gen = OnIndividual('crossover_segmented')(_source=iter(population),
                                               per_pair_rate=1.0,
                                               switch_rate=0.9,
                                               two_children=True)
    offspring = list(_gen)
    print "len(offspring) = %d, len(population) = %d" % (len(offspring),
                                                         len(population))
    assert len(offspring) == len(population), "Did not select all individuals"
    print "intersection = %s" % set(offspring).intersection(set(population))
    assert len(set(offspring).intersection(
        set(population))) == 0, "Did not modify some individuals"

    for indiv in offspring:
        distinct_genes = set(indiv.genome)
        if len(distinct_genes) != 2: print indiv.genome
        assert len(distinct_genes) == 2, "Did not cross individuals"
コード例 #10
0
def test_recombiners_SingleSame_Values():
    population = make_pop()

    _gen = OnIndividual('crossover_one')(_source=iter(population),
                                         two_children=True)
    child1, child2 = next(_gen), next(_gen)
    print "len(child1) = %d, len(child2) = %d, len(population[0]) = %d" % (
        len(child1), len(child2), len(population[0]))
    assert len(child1) == len(child2) == len(
        population[0]), "Individual's length was changed"
    child1_set, child2_set = set(child1.genome), set(child2.genome)
    print "len(set(child1)) = %d, len(set(child2)) = %d" % (len(child1_set),
                                                            len(child2_set))
    assert len(child1_set) == len(
        child2_set) == 2, "Number of distinct values is not 2"
    print "set(child1) = %s" % child1_set
    print "set(child2) = %s" % child2_set
    assert child1_set == child2_set, "Distinct values are not matched"
コード例 #11
0
def test_recombiners_SingleDifferent_Values():
    population = make_pop_variable(shortest=4)

    _gen = OnIndividual('crossover_one_different')(_source=iter(population),
                                                   two_children=True)
    child1, child2 = next(_gen), next(_gen)
    print "len(child1) = %d, len(child2) = %d, len(pop[0]) = %d, len(pop[1]) = %d" % (
        len(child1), len(child2), len(population[0]), len(population[1]))
    assert len(child1) + len(child2) == len(population[0]) + len(
        population[1]), "Genes were gained/lost"
    child1_set, child2_set = set(child1.genome), set(child2.genome)
    source_set = set(population[0].genome).union(set(population[1].genome))
    print "len(set(child1)) = %d, len(set(child2)) = %d" % (len(child1_set),
                                                            len(child2_set))
    assert len(child1_set) <= 2 and len(
        child2_set) <= 2, "Number of distinct values is not 2 or less"
    print "set(child1) = %s" % child1_set
    print "set(child2) = %s" % child2_set
    print "set(pop[0] U pop[1]) = %s" % source_set
    assert child1_set.issubset(source_set) and child2_set.issubset(
        source_set), "Genes were invented"
コード例 #12
0
    def __init__(self, cfg, lscape=None, monitor=None):
        # Merge syntax and default details
        self.syntax = merge_cls_dicts(self, 'syntax')
        self.cfg = ConfigDict(merge_cls_dicts(self, 'default'))
        # Merge in all globally defined ESDL functions
        for key, value in GLOBAL_ESDL_FUNCTIONS.iteritems():
            self.cfg.system[key.lower()] = value
        # Now apply user cfg details and test against syntax
        self.cfg.overlay(cfg)
        # If no default evaluator has been provided, use `lscape`
        cfg_validate(self.cfg, self.syntax, type(self), warnings=False)
        
        # Initialise empty members
        self._code = None
        self._code_string = None
        
        self.monitor = None
        self.selector = None
        self.selector_current = None
        
        self._in_step = False
        self._next_block = []
        self._block_cache = {}

        # Compile code
        self.definition = self.cfg.system.definition
        self._context = context = {
            'config': self.cfg,
            'rand': random.Random(cfg.random_seed),
            'notify': self._do_notify
        }
        
        # Add species settings to context
        for cls in SPECIES:
            inst = context[cls.name] = cls(self.cfg, lscape)
            try:
                for key, value in inst.public_context.iteritems():
                    context[key.lower()] = value
            except AttributeError: pass

        # Add external values to context
        for key, value in self.cfg.system.iteritems():
            if isinstance(key, str):
                key_lower = key.lower()
                if key_lower in context:
                    warn("Overriding variable/function '%s'" % key_lower)
                context[key_lower] = value
            else:
                warn('System dictionary contains non-string key %r' % key)
        
        
        model, self.validation_result = compileESDL(self.definition, context)
        if not self.validation_result:
            raise ESDLCompilerError(self.validation_result, "Errors occurred while compiling system.")
        self._code_string, internal_context = emit(model, out=None, optimise_level=0, profile='_profiler' in context)
        
        internal_context['_yield'] = lambda name, group: self.monitor.on_yield(self, name, group)
        internal_context['_alias'] = GroupAlias
        
        for key, value in internal_context.iteritems():
            if key in context:
                warn("Variable/function '%s' is overridden by internal value" % key)
            context[key] = value

        esec.context._context.context = context
        esec.context._context.config = context['config']
        esec.context._context.rand = context['rand']
        esec.context._context.notify = context['notify']
        
        self.monitor = monitor or MonitorBase()
        self.selector = self.cfg['selector'] or [name for name in model.block_names if name != model.INIT_BLOCK_NAME]
        self.selector_current = iter(self.selector)
        
        for func in model.externals.iterkeys():
            if func not in context:
                context[func] = OnIndividual(func)
        
        self._code = compile(self._code_string, 'ESDL Definition', 'exec')