Biyomorf programı

Başlatan utdmr, 27 Haziran 2010 - 23:49:51

« önceki - sonraki »

0 Üyeler ve 2 Ziyaretçi konuyu incelemekte.

utdmr

Richard Dawkins'in Kör Saatçi(The Blind Watchmaker) kitabını okuyanlar bilir, orada bir program hazırlanmıştı. Program sadece tek bir çizgiden rastgele dallar çıkararak yeni şekiller türetiyordu. Siz bu şekillerden istediğinizi seçerek daha karmaşık formlara doğru ilerliyordunuz. Birikimli doğal seçilimle karmaşık yapıların oluşabileceğini basitçe göstermişti. Ben de bundan esinlenerek kendi biyomorf programımı yaptım(bir arkadaşımla beraber).

Program PyQt ve PIL istiyor. Depolardan kurabilirsiniz.
sudo apt-get install python-imaging python-qt4

Ardından aşağıdaki kodu bir metin belgesine kaydedip çalıştırılabilir haklarını verip çalıştırabilirsiniz.

Kullanımı basit. Gözünüze güzel gelen biyomorfa tıklayın, giderek daha güzelleri gelecek :).

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Simple Biomorph Creator

2010 Utku Demir

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

Contact:
Utku Demir
utdemir@gmail.com
"""

from PIL import Image, ImageDraw
from math import radians,cos,sin
from PyQt4 import QtGui,QtCore
from os import unlink,urandom
from sys import argv
from tempfile import NamedTemporaryFile
from copy import deepcopy
from time import time
import random

COUNT=4
random.seed(urandom(10)+str(time()))

class phenotype:
def __init__(self,g):
self.im=Image.new("RGB",[240,240],(255,255,255))
self.p=(120,120)
self.a=0
for i in g.genes: #draw lines here
self.add_line(i)
self.p=(120,120)
self.a=0
for i in g.genes: #draw the other side of the biomorph, it is optional, but good-looking :)
i.angle=180-i.angle
self.add_line(i)

def get(self):
out=NamedTemporaryFile(delete=False)
path=out.name
self.im.save(out, "PNG")
out.close()
return path
def add_line(self,t):
self.p=self.draw_line(t.angle,t.length,t.width,t.color)
def draw_line(self,angle,length,width,color):
#angle=self.a+angle
#self.a=angle
d=ImageDraw.Draw(self.im)
x=length*cos(radians(angle))   
y=length*sin(radians(angle))
new=(self.p[0]+x,self.p[1]+y) #here is ending point
d.line((self.p[0],self.p[1])+new,fill=color,width=width)
return new

class gene:
def __init__(self):
self.mutation(start=True) #start with a random gene
def mutation(self,start=False):
choice=random.randint(1,4)

if choice==1 or start:
self.angle=random.randint(0,360)
#self.angle=random.randint(0,24)
#self.angle=self.angle*15
if choice==2 or start:
self.length=random.randint(5,20)
if choice==3 or start:
self.width=random.randint(1,2)
if choice==4 or start:
self.color=(random.randint(0,230),random.randint(0,230),random.randint(0,230))

class genotype:
def __init__(self):
self.genes=[]
a=gene()
self.genes.append(a) # start with only one gene
def replicate(self):
g=deepcopy(self)
if len(g.genes)==0:
choice=1
else:
choice=random.randint(1,3)  #what must i do?
if choice==1: # add one gene
which=random.randint(0,len(g.genes))
a=gene()
g.genes.insert(which,a)
exp="<font color=blue><center>Added one gene to %s. section.</center></font>"%str(which+1)
#g.genes=g.genes[:which]+[a]+g.genes[which:]
#g.genes.append(a)   
elif choice==2: # gene mutation
if len(g.genes)==1:
g.genes[0].mutation()
exp="<font color=green><center>The gene mutated.</center></font>"
else:
which=random.randint(0,len(g.genes)-1)
g.genes[which].mutation()
exp="<font color=green><center>Gene %s mutated.</center></font>"%str(which+1)
elif choice==3: # destroy one gene
if len(g.genes)==1:
del g.genes[0]
exp="<font color=red><center>Genotype disappeared!</center></font>"
else:
which=random.randint(0,len(g.genes)-1)
del g.genes[which]
exp="<font color=red><center>Gene %s disappeared.</center></font>"%str(which+1)
return (g,exp)

class gui:
def __init__(self):
app = QtGui.QApplication(argv)

w=QtGui.QWidget()
w.setWindowTitle('Simple Biomorph Creator')

screen=QtGui.QDesktopWidget().screenGeometry()
size=w.geometry()
w.move((screen.width()-size.width())/2, (screen.height()-size.height())/2) # center the window



l=QtGui.QVBoxLayout()

row1=QtGui.QHBoxLayout() # contains choices
row2=QtGui.QHBoxLayout() # contains explanations

g=genotype()
g.genes=[]
p=phenotype(g)#create an empty image
p=p.get()
self.parentlabel=QtGui.QLabel()
self.parentlabel.setPixmap(QtGui.QPixmap(p))
self.parentlabel.setAlignment(QtCore.Qt.AlignCenter)
self.parentlabel.resize(240,240)

unlink(p)

parenttip=QtGui.QLabel()
parenttip.setText("Parent")
parenttip.setAlignment(QtCore.Qt.AlignCenter)

l.addWidget(self.parentlabel) #will contain parent
l.addWidget(parenttip)
l.addLayout(row1)
l.addLayout(row2)

self.genotypes=[]
self.labels=[]
self.explanations=[]

#self.labels=[ClickableQLabel()]*COUNT  #Why it isn't working?... Got it. References, instances, complicated stuff :)

for i in range(COUNT):
self.labels.append(ClickableQLabel())
self.explanations.append(QtGui.QLabel())

for i in range(COUNT):
g=genotype()
self.genotypes.append(g)

p=phenotype(g)
p=p.get()
self.labels[i].setPixmap(QtGui.QPixmap(p))
unlink(p)

for i in self.labels:
row1.addWidget(i)
for i in self.explanations:
row2.addWidget(i)

for i in range(COUNT):
i=str(i)
eval('QtCore.QObject.connect(self.labels[%s],QtCore.SIGNAL("clicked()"),self.clicked%s)'%((i,)*2))

w.setLayout(l)

w.show()

app.exec_()

def clicked0(self):  #...
self.choose(0)
def clicked1(self):  #...
self.choose(1)
def clicked2(self):  #...
self.choose(2)
def clicked3(self):  #...
self.choose(3)
def clicked4(self):  #...
self.choose(4)
def clicked5(self):  #...
self.choose(5)
def clicked6(self):  #...
self.choose(6)
def clicked7(self):  #...
self.choose(7)
def clicked8(self):  #...
self.choose(8)
def clicked9(self):  #there must be a better way....
self.choose(9)

def choose(self,a):
chosen=self.genotypes[a] # only one can survive...
self.genotypes=[]
explanations=[]
for i in range(COUNT):
k=chosen.replicate() #note: k[0] is the new genotype, k[1] says what happened when replicating.
self.explanations[i].setText(k[1])
self.genotypes.append(k[0])
# now it's the time to draw phenotypes
p=phenotype(k[0])
path=p.get()
self.labels[i].setPixmap(QtGui.QPixmap(path))
unlink(path)

parent=phenotype(chosen) #draw the parent ...
parent=parent.get()
self.parentlabel.setPixmap(QtGui.QPixmap(parent))
unlink(parent)

class ClickableQLabel(QtGui.QLabel):
def __init(self, parent):
QLabel.__init__(self, parent)
def mouseReleaseEvent(self, ev):
self.emit(QtCore.SIGNAL('clicked()'))

if __name__=='__main__':
gui()


Bu da bir ekran görüntüsü:

Kişisel Blogum: Çoğunlukla Zararsız - cogunluklazararsiz.org
--
Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius -and a lot of courage- to move in the opposite direction.

ubuntuki lilith

Eline, aklına sağlık utdemir. Çok özgün bir çalışma olmuş.

sem

İlginç bir çalışma, eline sağlık...
".NET çemberinden geçen lirisist etkisi bir 'Volcano', bir yüzüm Java bir yüzüm Badalamenti Don Tano"
----------------------------------------------------------------------------------------------------------------------
"Her yer ölüm yine, burası dünya
Derken ölüm bile bu nasıl dünya?
Benden ölüm dile, batıyor gün yine
Burası dünya?

heartsmagic

Alıntı yapılan: ubuntuki lilith - 27 Haziran 2010 - 23:54:19
Eline, aklına sağlık utdemir. Çok özgün bir çalışma olmuş.

Nadire +1 derim :)
+1
Hayattan çıkarı olmayanların, ölümden de çıkarı olmayacaktır.
Hayatlarıyla yanlış olanların ölümleriyle doğru olmalarına imkân var mıdır?


Böylece yalan, dünyanın düzenine dönüştürülüyor.