vog.py

Created by stimorol

Created on October 12, 2022

4.41 KB

Intelligence artificielle utilisant le machine learning. Il fonctionne avec la bibliothèque numpy, et n’est donc pas fonctionnel sur le système d’exploitation par défaut (il faudrait installer Upsilon).


from ulab import numpy as np
from kandinsky import *
from time import *
from random import *
from math import *

def rlist(list,n=0):
  return str([round(i,n) for i in list])

def create_bob(min,max):
  return np.array([uniform(min,max),uniform(min,max),uniform(min,max),uniform(min,max)])
#  return np.array([.1,.1,.1,.1])

class Engine:
  
  def __init__(self,gen_amount,learningRate=0.1,conf=['white','gray']):
    if input('WELCOME USER !\nEnable graphics ? (y/n) ')=='n':
      self.graphics=0
    else:self.graphics=1
    self.lRate=learningRate
    self.gen_amount=gen_amount
    self.conf=conf
    self.main(conf)

  def main(self,conf):
    self.create_gen()
    for gen in range(self.gen_amount):
      print("SIMULATION OF GEN",gen,"STARTING NOW")
      if self.graphics:
        fill_rect(0,0,322,222,conf[1])
        draw_string('SIMULATION OF GEN '+str(gen),10,10,conf[0],conf[1])
        sleep(1)
      self.simule(gen)
      if self.graphics:
        fill_rect(0,0,322,222,conf[1])
        draw_string('END OF GEN '+str(gen),10,10,conf[0],conf[1])
        draw_string('WINS: '+str([(1 if i<=0 else 0) for i in self.grades].count(1))+"/6\nGRADES:\n  "+rlist(self.grades,1),15,50,conf[0],conf[1],1)
        sleep(2)
      else:print("Grades:",self.grades)
      self.evolve()

  def evolve(self,bmin=-2,bmax=2):
    new_agent=[0,0,0,0,0,0]
    new_agent[0]=self.agent[self.grades.index(min(self.grades))]
    self.grades.remove(min(self.grades))
    new_agent[1]=self.agent[self.grades.index(min(self.grades))]
    new_agent[2]=new_agent[0]+np.array([uniform(-self.lRate,self.lRate) for i in range(4)])
    new_agent[3]=new_agent[1]+np.array([uniform(-self.lRate,self.lRate) for i in range(4)])
    for i in [4,5]:
      new_agent[i]=np.array([uniform(bmin,bmax),uniform(bmin,bmax),uniform(bmin,bmax),uniform(bmin,bmax)])
    self.agent=new_agent

  def create_gen(self):
    self.agent = []
    for i in range(6):self.agent.append(create_bob(-1,1))
  
  def simule(self,gen='N/A'):
    
    target = [randint(20,300),randint(20,180)]
    self.grades=[]
    graphics=self.graphics

    for i in range(6):
      sleep(.5)
      if self.graphics:
        fill_rect(0,0,322,222,self.conf[1])
        draw_string("*",target[0]-4,target[1]-8,"red",self.conf[1])
        draw_string('GEN '+str(gen),0,160,self.conf[0],self.conf[1],1)
      alive = True
      pos=[150,100]
      lastDir=-1
      if graphics:
        for j in range(6):
          draw_string(['A','B','AB','MA','R1','R2'][j],0+j*20,185,'red' if j==i else self.conf[0],self.conf[1],1)
        draw_string('BRAIN: '+rlist(self.agent[i],2)+'   '+str([(1 if j>0 else 0) for j in self.agent[i]].count(1))+'/4',0,200,self.conf[0],self.conf[1],1)
      startTime = monotonic()
      while alive:
        if self.graphics:set_pixel(pos[0],pos[1],'black')
        input_layer = self.input_layer(pos,target)
        out = self.compute(input_layer,i)
        bestOut=list(out).index(max(list(out)))
        if bestOut<2:
          pos[0]+=[1,-1][bestOut]
          if pos[0]<0 or pos[0]>322:
            self.grades.append(100_000)
            alive=False
        else:
          pos[1]+=[1,-1][bestOut-2]
          if pos[1]<0 or pos[1]>222:
            self.grades.append(100_000)
            alive=False
        if self.graphics and lastDir!=bestOut:
          set_pixel(pos[0],pos[1],'red')
          for i in range(4):
            draw_string(['+x','-x','+y','-y'][i],0,30+i*20,'red' if i==bestOut else self.conf[0],self.conf[1],1)
          draw_string('IN: '+rlist(input_layer,0)+'   ',0,0,self.conf[0],self.conf[1],1)
          draw_string('OUT: '+rlist(out,2)+'   ',0,15,self.conf[0],self.conf[1],1)
          lastDir=bestOut
        sleep(.02)
        if pos[0]==target[0] and pos[1]==target[1]:
          alive=False
          if graphics:draw_string('WIN !',270,0,self.conf[0],self.conf[1])
          self.grades.append(1/(startTime-monotonic()))
        if monotonic()-startTime > 4:
          alive=False
          if graphics:draw_string('LOST',280,0,self.conf[0],self.conf[1])
          self.grades.append(sqrt((target[0]-pos[0])**2+(target[1]-pos[1])**2))

  def compute(self,input_layer,i):
#    for j in range(4):print(input_layer[j],"*",self.agent[i][j],"=",input_layer[j]*self.agent[i][j])
    return input_layer*self.agent[i]

  def input_layer(self,pos,target):
    return np.array([int(target[0]-pos[0]),int(pos[0]-target[0]),int(target[1]-pos[1]),int(pos[1]-target[1])],dtype=np.int16)

Engine(50,1,['white','gray'])

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.