Esempio n. 1
0
def run(testSet, maxPageCount=None, knownPaginations=[], **kargs):
    class Individual(genetic.Individual):

        optimization = "MINIMIZE"
        separator = ','
        maxPageCount = 0

        def makechromosome(self):
            pages = solver_tools.Pagination(capacity)
            tiles = solver_tools.Batch(refTiles)
            firstFit(pages, tiles.getShuffledClone())
            result = [pages.pageIndexOfTile(tile) for tile in tiles]
            Individual.maxPageCount = max(
                max(result) + 1, Individual.maxPageCount)
            return result

        def evaluate(self, optimum=None):
            symbolsOnPages = [[] for _ in xrange(Individual.maxPageCount)]
            for (tileIndex, pageIndex) in enumerate(self.chromosome):
                symbolsOnPages[pageIndex].extend(refTiles[tileIndex])
            page_costs = [len(set(symbols)) for symbols in symbolsOnPages]
            if max(page_costs) > capacity:
                self.score = invalidPenalty + sum(
                    max(0, n - capacity) for n in page_costs)
            else:
                for i in xrange(Individual.maxPageCount - 1, -1, -1):
                    if page_costs[i]:
                        self.score = page_costs[i] + i * capacity
                        break

        def mutate(self, gene):
            self.chromosome[gene] = random.randrange(Individual.maxPageCount)

    # tiles = solver_tools.Batch(testSet["tiles"])
    capacity = testSet["capacity"]
    refTiles = solver_tools.Batch(testSet["tiles"])
    Individual.length = len(refTiles)
    invalidPenalty = capacity * testSet["tileCount"]
    # if knownPaginations:
    #     maxPageCount = min(len(knownPagination) for knownPagination in knownPaginations if knownPagination.isValid())

    # for (knownPaginationIndex,knownPagination) in enumerate(knownPaginations):
    #     if knownPagination.isValid() and len(knownPagination) == maxPageCount:
    #         for (tileIndex,tile) in enumerate(tiles):
    #             env.population[knownPaginationIndex].chromosome[tileIndex] = knownPagination.pageIndexOfTile(tile)
    env = genetic.Environment(Individual, **kargs)
    env.run()

    pages = solver_tools.Pagination(testSet["capacity"], name)
    for _ in range(max(env.best.chromosome) + 1):
        pages.newPage()
    for (tileIndex, pageIndex) in enumerate(env.best.chromosome):
        pages[pageIndex].add(refTiles[tileIndex])
    return pages
Esempio n. 2
0
        from os import path
        sys.path.append(path.dirname(path.abspath(__file__)))
        from common import covert_channel
        import genetic
        import arguments
else:
        from .common import covert_channel
        from . import genetic
        from . import arguments
channel = covert_channel("L1", data
		       , timeBetweenRuns=0.3
                       , runsPerTest=1
                       , readerCore=0
                       , senderCore=4)

if __name__ == '__main__':
        args = arguments.mkparser("L1").parse_args()
        if ('buddy' in args and args.buddy != None):
                channel = covert_channel("L1", data
                                         , buddy=args.buddy
                                         , timeBetweenRuns=0.3
                                         , runsPerTest=1
                                         , readerCore=0
                                         , senderCore=4)
        if (args.learn):
                env = genetic.Environment(channel, size=100, maxgenerations=100, optimum=1-0.015)
                env.run()
                env.best.dump("L1Results.json")
        else:
                channel.run()
Esempio n. 3
0
            p = 1000000

        if x1 <= 1.4 and x1 >= 0.5:
            d = 0
        else:
            d = 1000000
        if y <= 1 and y >= 0:
            e = 0
        else:
            e = 1000000

        fitness_value = t + p + d + e
        #print w,z

        self.score = fitness_value

    def mutate(self, gene):
        self.chromosome[gene] = not self.chromosome[gene]  # bit flip


if __name__ == "__main__":
    env = genetic.Environment(Min1, size=200, maxgenerations=500)
    env.run()
    # matplotlib is not ready for python 3.0 yet
    # use matplotlib to plot the convergence figure
    '''
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot(env.x, env.y)
    plt.show()
    '''
    def report(self):
        print "=" * 70
        print "generation: ", self.generation
        print "best:       ", self.best


#---------------------------------------------------------------------
#
# onemax.py - useage example
#
# the fittest individual will have a chromosome consisting of 30 '1's
#

import genetic


class OneMax(genetic.Individual):
    optimization = genetic.MAXIMIZE

    def evaluate(self, optimum=None):
        self.score = sum(self.chromosome)

    def mutate(self, gene):
        self.chromosome[gene] = not self.chromosome[gene]  # bit flip


if __name__ == "__main__":
    env = genetic.Environment(OneMax, maxgenerations=1000, optimum=30)
    env.run()
## end of http://code.activestate.com/recipes/199121/ }}}
Esempio n. 5
0
        self.score = fitness_value
        #第二階段,將各變數計算以變數個數,利用迴圈進行運算
        x = 0
        for i in range(0,self.var_number):
            for j in range(i*20,i*20+10):
                x +=self.chromosome[j]<<(j-(i*20))
            if (x>999):
                x=999
            x/=1000.
            for j in range(i*20+10,i*20+20):
                x +=self.chromosome[j]<<(j-(i*20+10))
            self.var[i] = x
        '''
        #第三階段,在實用上,將上述運算,寫進個別成員類別中,透過呼叫成員函式,取得各變數值
        self._getvar(self.chromosome)

        x = self.var[0]
        y = self.var[1]
        z = (SURFACE - x * y) / (2. * (x + y))
        fitness_value = x * y * z

        self.score = fitness_value

    def mutate(self, gene):
        self.chromosome[gene] = not self.chromosome[gene]  # bit flip


if __name__ == "__main__":
    env = genetic.Environment(Volume, size=500, maxgenerations=100)
    env.run()
Esempio n. 6
0
def run(testSet, **kargs):
    def mate(p1, left1, right1, p2, left2, right2):
        pages = solver_tools.Pagination(capacity)
        medianTiles = set(tile for i in xrange(left2, right2)
                          for tile in p2.chromosome[i])
        for i in xrange(0, left1):
            tilesToPlace = p1.chromosome[i].tileSet.difference(medianTiles)
            if tilesToPlace:
                pages.newPage(tilesToPlace)
        for i in xrange(left2, right2):
            pages.newPage(p2.chromosome[i])
        for i in xrange(right1, p1.length):
            tilesToPlace = p1.chromosome[i].tileSet.difference(medianTiles)
            if tilesToPlace:
                pages.newPage(tilesToPlace)
        pool = list(
            refTiles.difference(tile for page in pages for tile in page))
        pool.sort(key=lambda tile: tile.size, reverse=True)
        firstFit(pages, pool)
        child = Individual(pages)
        child.length = len(pages)
        return child

    class Individual(genetic.Individual):

        optimization = "MAXIMIZE"
        separator = ','

        def makechromosome(self):
            pages = solver_tools.Pagination(capacity)
            tiles = solver_tools.Batch(refTiles)
            firstFit(pages, tiles.getShuffledClone())
            self.length = len(pages)
            return pages

        def evaluate(self, optimum=None):
            # print self.length,
            self.score = sum((page.weight / maxPageWeight)**2
                             for page in self.chromosome) / self.length
            # NB. This should be equivalent to the faster formula:
            # self.score = sum(page.weight*page.weight for page in self.chromosome)/self.length/maxPageWeight/maxPageWeight
            # print self.score

        def mutate(self, gene):
            tiles = self.chromosome.pop(gene)
            firstFit(self.chromosome, tiles)
            self.length = len(self.chromosome)

        def crossover(self, other):
            if self is other or self.length < 3 or other.length < 3:
                return (self, other)
            left1 = random.randrange(1, self.length - 1)
            right1 = random.randrange(left1 + 1, self.length)
            left2 = random.randrange(1, other.length - 1)
            right2 = random.randrange(left2 + 1, other.length)
            return mate(self, left1, right1, other, left2,
                        right2), mate(other, left2, right2, self, left1,
                                      right1)

        def copy(self):
            twinPagination = solver_tools.Pagination(capacity)
            for page in self.chromosome:
                twinPagination.newPage(page)
            twin = Individual(twinPagination)
            twin.length = self.length
            twin.score = self.score
            # print "twin", twin.score
            return twin

    capacity = testSet["capacity"]
    refTiles = solver_tools.Batch(testSet["tiles"])
    maxPageWeight = float(
        sum(sorted(refTiles.weightBySymbol.values(), reverse=True)[:capacity]))
    pages = solver_tools.Pagination(capacity, name)
    env = genetic.Environment(Individual, **kargs)
    min_size_at_start = min(len(x.chromosome) for x in env.population)
    refTiles = set(tile for tile in refTiles)
    env.run()
    for page in env.best.chromosome:
        pages.newPage(page)
    return pages