Ejemplo n.º 1
0
def check_generated(i):
    if i.image == '':
        im = GA.display(i.genome)
        out = "{}.png".format(i)
        storage_utils.upload(im, 'media/' + out)
        i.image = out
        i.save()
Ejemplo n.º 2
0
def globalhome(request):
    username = request.user
    if is_lazy_user(request.user):
        request.session.guest = True

    pop = Artist.objects.filter(global_pop=True, alive=True)
    top_image = sorted(pop,
                       key=lambda x: ((x.mean_fitness / 10)**2) *
                       (math.log(max(1, x.seen)) + 1),
                       reverse=True)[0]
    gen = max([a.generation for a in pop])
    users = len(set([a.user for a in pop]))
    fits = [a.mean_fitness for a in pop.filter(seen__gte=0)]
    fitness = round(sum(fits) / len(fits), 2)
    variety = conrad_utils.genetic_diversity(pop)

    if top_image.image500 == '':
        im = GA.display(top_image.genome, size=(500, 500))
        out = "{}_500.PNG".format(top_image)
        storage_utils.upload(im, 'media/' + out)
        top_image.image500 = out
        top_image.save()

    top_image = top_image.image500.url

    pop_data = [top_image, gen, fitness, variety, users]

    context = {'pop_data': pop_data, 'username': username}
    return render(request, 'conrad/globalhome.html', context)
Ejemplo n.º 3
0
def userhome(request):
    username = request.user
    if is_lazy_user(request.user):
        request.session.guest = True

    pop_list = list(
        set([
            p.population
            for p in Artist.objects.filter(user=username, global_pop=False)
        ]))
    if pop_list:
        pops = [
            Artist.objects.filter(user=username,
                                  population=p,
                                  global_pop=False) for p in pop_list
        ]
        top_images = [
            p.filter(seen__gte=0).order_by('-fitness', '-created')[0]
            for p in pops
        ]
        gens = [max([a.generation for a in p]) for p in pops]
        la = [max([a.last_active for a in p]) for p in pops]
        fitnesses = [
            round(
                sum([a.fitness for a in p.filter(seen__gte=0)]) /
                len([a.fitness for a in p.filter(seen__gte=0)]), 2)
            for p in pops
        ]
        varieties = [
            conrad_utils.genetic_diversity(pops[i].filter(generation=gens[i]))
            for i in range(len(pops))
        ]
        no_to_go = [(len(pops[i].filter(generation=gens[i], seen__lte=0)))
                    for i in range(len(pops))]
        for i in top_images:
            if i.image == '':
                im = GA.display(i.genome)
                out = "{}.PNG".format(i)
                storage_utils.upload(im, 'media/' + out)
                i.image = out
            i.save()
        top_images = [i.image.url for i in top_images]
        user_pops = [[
            pop_list[i], top_images[i], gens[i], fitnesses[i], varieties[i],
            no_to_go[i], la[i]
        ] for i in range(len(pop_list))]
        new_pop = max(pop_list) + 1
    else:
        user_pops = []
        new_pop = 0

    context = {
        'user_pops': user_pops,
        'username': username,
        'new_pop': new_pop
    }
    return render(request, 'conrad/userhome.html', context)
Ejemplo n.º 4
0
def generate_image(artist_id):
    i = Artist.objects.get(pk=artist_id)
    print("Generating {} in the background".format(i))
    logger.info("Generating {} in the background".format(i))
    if i.image == '':
        im = GA.display(i.genome)
        out = "{}.PNG".format(i)
        storage_utils.upload(im, 'media/'+out)
        i.image = out
        i.save()
Ejemplo n.º 5
0
def newpop(popsize, genlength, pop, user):
    for i in range(popsize):
        a = Artist(population=pop,
                   generation=0,
                   fitness=0,
                   member=i,
                   seen=False,
                   image=None,
                   genome=GA.birth(genlength),
                   user=user)
        a.save()
        tasks.generate_image(a.id)
Ejemplo n.º 6
0
def inspect(request, id):
    a = Artist.objects.get(pk=id)
    if a.mother.values().filter(generation=(a.generation - 1)):
        mother = Artist.objects.get(pk=a.mother.values().filter(
            generation=(a.generation - 1))[0]['id'])
        conrad_utils.check_generated(mother)
    else:
        mother = ''
    if a.father.values().filter(generation=(a.generation - 1)):
        father = Artist.objects.get(pk=a.father.values().filter(
            generation=(a.generation - 1))[0]['id'])
        conrad_utils.check_generated(mother)
    else:
        father = ''

    fchildren = [
        Artist.objects.get(pk=c['id'])
        for c in a.father.values().filter(generation=(a.generation + 1))
    ]
    mchildren = [
        Artist.objects.get(pk=c['id'])
        for c in a.mother.values().filter(generation=(a.generation + 1))
    ]
    if not a.image500:
        im = GA.display(a.genome, size=(500, 500))
        out = "{}_500.PNG".format(a)
        storage_utils.upload(im, 'media/' + out)
        a.image500 = out
        a.save()

    for c in [fchildren, mchildren]:
        for i in c:
            conrad_utils.check_generated(i)

    children = mchildren + fchildren
    context = {
        'artist': a,
        'mother': mother,
        'father': father,
        'children': children
    }
    return render(request, 'conrad/inspect.html', context)
Ejemplo n.º 7
0
def newgen(population):
    popNo = population[0].population
    gen = population[0].generation + 1
    user = population[0].user
    population = list(population)
    random.shuffle(population)

    for i in range(len(population) - int(len(population) / 10)):
        mother = select_parent(population)
        father = select_parent(population)
        if len(father.genome) < len(mother.genome):
            mother, father = father, mother
        child = crossover(mother, father)
        child = mutate(child, 0.1, 0.5)
        a = Artist(population=popNo,
                   generation=gen,
                   fitness=0,
                   member=i,
                   seen=False,
                   image='',
                   image500='',
                   genome=child,
                   user=user)
        a.save()
        a.mother.set([mother.id])
        a.father.set([father.id])
        a.save()
        tasks.generate_image(a.id)
    for i in range(int(len(population) / 10)):
        a = Artist(population=popNo,
                   generation=gen,
                   fitness=0,
                   member=len(population) - int(len(population) / 10) + i,
                   seen=False,
                   image='',
                   image500='',
                   genome=GA.birth(30),
                   user=user)
        a.save()
        tasks.generate_image(a.id)
Ejemplo n.º 8
0
def global_mate(mother, population, username):
    popNo = mother.population
    gen = mother.generation + 1
    member = max([p.member
                  for p in population if p.generation == gen] + [-1]) + 1
    mf = round(sum([p.mean_fitness for p in population]))
    father = select_parent(population, mean=True)
    if len(father.genome) < len(mother.genome):
        mother, father = father, mother
    child = crossover(mother, father)
    child = mutate(child, 0.1, 0.5)
    a = Artist(population=popNo,
               generation=gen,
               fitness=mf,
               member=member,
               seen=False,
               image='',
               image500='',
               genome=child,
               user=username,
               global_pop=True)
    a.save()
    a.mother.set([mother.id])
    a.father.set([father.id])
    a.save()
    tasks.generate_image(a.id)
    if random.random() < 0.1:
        a = Artist(population=popNo,
                   generation=gen,
                   fitness=mf,
                   member=member + 1,
                   seen=False,
                   image='',
                   image500='',
                   genome=GA.birth(30),
                   user='******',
                   global_pop=True)
        a.save()
        tasks.generate_image(a.id)
Ejemplo n.º 9
0
def newgen(request, population, gen, username):
    pop = Artist.objects.filter(user=username,
                                population=population,
                                global_pop=False,
                                generation=gen)
    fitness = round(sum([a.fitness for a in pop]) / len(pop), 2)
    diversity = conrad_utils.genetic_diversity(pop)
    top_image = pop.order_by('-fitness', '-created')[0]
    if not top_image.image500:
        im = GA.display(top_image.genome, size=(500, 500))
        out = "{}_500.PNG".format(top_image)
        storage_utils.upload(im, 'media/' + out)
        top_image.image500 = out
        top_image.save()

    return render(
        request, 'conrad/end_gen.html', {
            'population': population,
            'generation': gen,
            'top_image': top_image,
            'fitness': fitness,
            'diversity': diversity
        })
Ejemplo n.º 10
0
def sandbox(request):
    genome1 = request.GET.get('image1')
    genome2 = request.GET.get('image2')
    if genome1:
        genome1 = genome1.upper()
        if re.search('[^ATCG]', genome1):
            error_message = "Genomes can only contain 'A's, 'T's, 'C's, and 'G's."
            return render(request, 'conrad/sandbox.html', {
                'image1': '',
                'function1': '',
                'error_message': error_message
            })
        if len(genome1) < 30 or len(genome1) > 90:
            error_message = "Genomes must be between 30 and 90 characters"
            return render(request, 'conrad/sandbox.html', {
                'image1': '',
                'function1': '',
                'error_message': error_message
            })
        else:
            image1 = 'media/' + genome1 + '.png'
            if not storage_utils.check_exists(genome1 + 'png'):
                im1 = GA.display(genome1)
                storage_utils.upload(im1, image1)
            image1 = storage_utils.get_url(image1)
            function1 = image.print_gene(genome1, 0, 1)

            if genome2:
                genome2 = genome2.upper()
                if re.search('[^ATCG]', genome2):
                    error_message = "Genomes can only contain 'A's, 'T's, 'C's, and 'G's."
                    return render(request, 'conrad/sandbox.html',
                                  {'error_message': error_message})
                if len(genome1) < 30 or len(genome1) > 90:
                    error_message = "Genomes must be between 30 and 90 characters"
                    return render(
                        request, 'conrad/sandbox.html', {
                            'image1': '',
                            'function1': '',
                            'error_message': error_message
                        })
                else:
                    image2 = 'media/' + genome2 + '.png'
                    if not storage_utils.check_exists(genome2 + 'png'):
                        im2 = GA.display(genome2)
                        storage_utils.upload(im2, image2)
                    image2 = storage_utils.get_url(image2)
                    function2 = image.print_gene(genome2, 0, 1)
                    offspring = request.GET.get('offspring')
                    if offspring == "True":
                        random.seed(timezone.now())
                        genome3 = GA.crossover(genome1, genome2)
                        image3 = 'media/' + genome3 + '.png'
                        if not storage_utils.check_exists(genome3 + 'png'):
                            im3 = GA.display(genome3)
                            storage_utils.upload(im3, image3)
                        image3 = storage_utils.get_url(image3)
                        function3 = image.print_gene(genome3, 0, 1)

                        return render(
                            request, 'conrad/sandbox.html', {
                                'image1': image1,
                                'function1': function1,
                                'genome1': genome1,
                                'image2': image2,
                                'function2': function2,
                                'genome2': genome2,
                                'image3': image3,
                                'function3': function3,
                                'genome3': genome3
                            })
                    else:
                        return render(
                            request, 'conrad/sandbox.html', {
                                'image1': image1,
                                'function1': function1,
                                'genome1': genome1,
                                'image2': image2,
                                'function2': function2,
                                'genome2': genome2
                            })

            else:
                return render(request, 'conrad/sandbox.html', {
                    'image1': image1,
                    'function1': function1,
                    'genome1': genome1
                })
    else:
        return render(request, 'conrad/sandbox.html', {
            'image1': '',
            'function1': ''
        })
Ejemplo n.º 11
0
def gallery(request, sort, time, group, index):
    try:
        a = Artist.objects.get(pk=request.POST['artist'])
        score = request.POST['score']

    except (KeyError, Artist.DoesNotExist):
        pass
    else:
        a.gallery_fitness += int(score)
        a.seen += 1
        a.voters.add(request.user)
        a.gallery_voters.add(request.user)
        a.save()

    n = timezone.now()

    if time == 'alltime':
        time_filtered = Artist.objects.all()
    else:
        time_dict = {'day': 1, 'week': 7, 'month': 30, 'year': 365}
        time_threshold = n - datetime.timedelta(time_dict[time])
        time_filtered = Artist.objects.filter(created__gte=time_threshold)

    if group == 'local':
        filtered = time_filtered.filter(global_pop=False)
    elif group == 'global':
        filtered = time_filtered.filter(global_pop=True)
    elif group == 'all':
        filtered = time_filtered
    else:
        filtered = time_filtered.filter(user=group)

    filtered = filtered.filter(seen__gte=1)

    if sort == 'top':
        top_images = filtered.order_by('-gallery_fitness')
    elif sort == 'average':
        top_images = sorted(filtered,
                            key=lambda x: x.mean_fitness,
                            reverse=True)
    elif sort == 'best':
        top_images = sorted(filtered,
                            key=lambda x: ((x.mean_fitness / 10)**2) *
                            (math.log(max(1, x.seen)) + 1),
                            reverse=True)
    elif sort == 'recent':
        top_images = sorted(filtered.filter(fitness__gte=9),
                            key=lambda x: x.created,
                            reverse=True)

    top_images = top_images[index:index + 10]

    if index < 10:
        pindex = 0
    else:
        pindex = index - 10

    lindex = (len(filtered) // 10) * 10

    nindex = index + 10

    for i in top_images:
        if i.image == '':
            im = GA.display(i.genome)
            out = "{}.PNG".format(i)
            storage_utils.upload(im, 'media/' + out)
            i.image = out
            i.save()

    voted = [
        i + 1 for i in range(len(top_images))
        if top_images[i].voters.values().filter(
            username=request.user.username).count()
    ]
    context = {
        'top_images': top_images,
        'sort': sort,
        'time': time,
        'group': group,
        'index': index,
        'nindex': nindex,
        'pindex': pindex,
        'lindex': lindex,
        'voted': voted
    }

    return render(request, 'conrad/gallery.html', context)
Ejemplo n.º 12
0
def global_game(request, population):
    username = str(request.user)

    if is_lazy_user(request.user):
        request.session.guest = True
        request.session.save()
        request.session.modified = True

    if not Artist.objects.filter(user=username):
        if 'howto' not in request.session:
            request.session['howto'] = True
            return HttpResponseRedirect(
                reverse('conrad:how_to') +
                '?next={}'.format(reverse('conrad:global_game', args=[0])))
    try:
        artists = request.POST.getlist('artist[]')
        scores = []
        for i in range(1, 6):
            scores.append(request.POST.get('score[{}]'.format(i)))
        print(scores)

    except (KeyError, Artist.DoesNotExist):
        pass
    else:
        for i in range(len(artists)):
            a = Artist.objects.get(pk=artists[i])
            a.fitness += int(scores[i])
            a.gallery_fitness += int(scores[i])
            a.seen += 1
            a.last_active = timezone.now()
            a.voters.add(request.user)
            a.save()
            livepop = Artist.objects.filter(alive=True,
                                            population=population,
                                            global_pop=True)
            conrad_utils.global_mate(a, livepop, username)

    while len(
            Artist.objects.filter(
                alive=True, population=population, global_pop=True)) > 200:
        candidate = conrad_utils.cull(
            Artist.objects.filter(alive=True,
                                  population=population,
                                  global_pop=True))
        victim = Artist.objects.get(pk=candidate.id)
        victim.alive = False
        victim.save()

    alive_pop = Artist.objects.filter(alive=True,
                                      population=population,
                                      global_pop=True)
    maxgen = max([a.generation for a in alive_pop])
    top_images_temp = alive_pop.order_by('last_active')[:20]

    top_images = random.sample(list(top_images_temp), 5)
    for i in top_images:
        if i.image == '':
            im = GA.display(i.genome)
            out = "{}.PNG".format(i)
            storage_utils.upload(im, 'media/' + out)
            i.image = out
        i.save()
    context = {
        'top_images': top_images,
        'population': population,
        'username': username,
        'maxgen': maxgen
    }

    return render(request, 'conrad/global.html', context)
Ejemplo n.º 13
0
def local(request, population):
    username = str(request.user)
    if is_lazy_user(request.user):
        request.session.guest = True
    if username == 'global':
        return global_game(request, population)

    for key in request.POST:
        print(key)
        value = request.POST[key]
        print(value)
    try:
        artists = request.POST.getlist('artist[]')
        scores = []
        for i in range(1, 6):
            scores.append(request.POST.get('score[{}]'.format(i)))
        print(scores)

    except (KeyError, Artist.DoesNotExist):
        pass
    else:
        for i in range(len(artists)):
            a = Artist.objects.get(pk=artists[i])
            a.fitness = scores[i]
            a.gallery_fitness = scores[i]
            a.seen = True
            a.last_active = timezone.now()
            a.voters.add(request.user)
            a.save()

    if not Artist.objects.filter(
            population=population, user=username, global_pop=False):
        conrad_utils.newpop(30, 30, population, username)
        return HttpResponseRedirect(
            reverse('conrad:how_to') +
            '?next={}'.format(reverse('conrad:local', args=[population])) +
            '&newpop=True')
    else:
        currentpop = Artist.objects.filter(seen=False,
                                           population=population,
                                           user=username,
                                           global_pop=False)
        if not currentpop:
            maxgen = max([
                f.generation for f in Artist.objects.filter(
                    population=population, user=username, global_pop=False)
            ])
            conrad_utils.newgen(
                Artist.objects.filter(population=population,
                                      generation=maxgen,
                                      user=username,
                                      global_pop=False))
            return newgen(request, population, maxgen, username)

    top_images = Artist.objects.filter(seen=False,
                                       population=population,
                                       user=username,
                                       global_pop=False).order_by('member')[:5]
    for i in top_images:
        if i.image == '':
            im = GA.display(i.genome)
            out = "{}.PNG".format(i)
            storage_utils.upload(im, 'media/' + out)
            i.image = out
        i.save()
    context = {
        'top_images': top_images,
        'username': username,
        'population': population
    }

    return render(request, 'conrad/local.html', context)