Guest User

recurrent neural network written in rpython

a guest
Jul 8th, 2010
601
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 18.70 KB | None | 0 0
  1. #!/usr/bin/python
  2. ## RPython Neural Network - 0.1b
  3. ## by Brett Hartshorn 2010
  4. ## tested with Ubuntu Lucid, copy this file to your pypy root directory and run "python rAI.py"
  5. ## you can test just pypy compilation with "python rAI.py --pypy --subprocess"
  6. ## you need to install SDL headers, apt-get install libsdl-dev
  7.  
  8. '''
  9. PyPY Tips
  10.  
  11. math.radians    not available
  12. random.uniform  not available
  13.  
  14. incorrect:
  15.     string.strip()  will not work without an arg
  16.     list.sort()     not available
  17.  
  18. correct:
  19.     string.strip(' \n')
  20.     list = sortd( list )
  21.     list.pop( index )       # no list.pop() with end as default
  22.  
  23. '''
  24.  
  25. COLUMNS = 24
  26. LAYERS = 5
  27. STEM = 8
  28.  
  29. import os, sys, time
  30. #from random import *       # not valid in rpython?
  31. import math             # math.radians is missing in pypy?
  32.  
  33. degToRad = math.pi / 180.0
  34. def radians(x):
  35.     """radians(x) -> converts angle x from degrees to radians
  36.     """
  37.     return x * degToRad
  38.  
  39. from pypy.rlib import streamio
  40. from pypy.rlib import rpoll
  41.  
  42. # apt-get install libsdl-dev
  43. from pypy.rlib.rsdl import RSDL, RSDL_helper
  44. from pypy.rlib.rarithmetic import r_uint
  45. from pypy.rpython.lltypesystem import lltype, rffi
  46. from pypy.rlib.listsort import TimSort
  47. from pypy.rlib.jit import hint, we_are_jitted, JitDriver, purefunction_promote
  48.  
  49. #random.randrange(0, up)        # not a replacement for random.uniform
  50. #Choose a random item from range(start, stop[, step]).  
  51. #This fixes the problem with randint() which includes the
  52. #endpoint; in Python this is usually not what you want.
  53.  
  54.  
  55. if '--pypy' in sys.argv:        # random.random works in pypy, but random.uniform is missing?
  56.     from pypy.rlib import rrandom
  57.     RAND = rrandom.Random()
  58.     RAND.init_by_array([1, 2, 3, 4])
  59.     def random(): return RAND.random()
  60.     def uniform(start,end): return ( RAND.random() * (end-start) ) - start
  61. else:
  62.     from random import *
  63.  
  64. def distance( v1, v2 ):
  65.     dx = v1[0] - v2[0]
  66.     dy = v1[1] - v2[1]
  67.     dz = v1[2] - v2[2]
  68.     t = dx*dx + dy*dy + dz*dz
  69.     return math.sqrt( float(t) )
  70.  
  71.  
  72. Njitdriver = JitDriver(
  73.     greens = 'cur train times branes last_spike spikers temporal thresh triggers self abs_refactory abs_refactory_value'.split(),
  74.     reds = 'i t a b c bias neuron'.split()
  75. )
  76. class RecurrentSpikingModel(object):
  77.     '''
  78.     Model runs in realtime and lossy - stores recent
  79.     spikes in a list for realtime learning.
  80.     Uses spike train, with time delay based on distance,        Spikes will trigger absolute refactory period.
  81.     Membrane has simple linear falloff.
  82.  
  83.         notes:
  84.             log(1.0) = 0.0
  85.             log(1.5) = 0.40546510810816438
  86.             log(2.0) = 0.69314718055994529
  87.             log(2.7) = 0.99325177301028345
  88.             log(3.0) = 1.0986122886681098
  89.  
  90.     '''
  91.     def iterate( self ):
  92.         now = float( time.time() )
  93.         self._state_dirty = True; train = self._train
  94.         brane = self._brane; rest = self._rest
  95.         branes = self._branes; temporal = self._temporal
  96.         abs_refactory = self._abs_refactory
  97.         abs_refactory_value = self._abs_refactory_value
  98.         fps = self._fps
  99.         elapsed = now - self._lasttime
  100.         clip = self._clip
  101.         cur = self._lasttime
  102.         last_spike = self._last_spike
  103.         spikers = self._spikers
  104.         thresh = self._thresh
  105.         triggers = self._triggers
  106.  
  107.         ## times of incomming spikes ##
  108.         times = train.keys()
  109.         ## To do, if seziure, lower all connection strengths
  110.         ##TimSort(times).sort()     # pypy note - list have no .sort(), and JIT dislikes builtin sorted(list)
  111.  
  112.         if not times:
  113.             a = now - self._lasttime
  114.             if a > 0.1: brane = rest
  115.             else:
  116.                 b = a * 10  # 0.0-1.0
  117.                 brane += (rest - brane) * b
  118.             branes.append( (brane,now) )
  119.  
  120.         i = 0
  121.         t = a = b = c = bias = .0
  122.         neuron = self
  123.         ntrain = len(train)
  124.         while train:        #the JIT does only properly support a while loop as the main dispatch loop
  125.             Njitdriver.can_enter_jit(
  126.                 cur=cur, train=train, times=times, branes=branes, last_spike=last_spike, spikers=spikers,
  127.                 temporal=temporal, thresh=thresh, triggers=triggers, self=self,
  128.                 abs_refactory=abs_refactory, abs_refactory_value=abs_refactory_value,
  129.                 i=i, t=t, a=a, b=b, c=c,
  130.                 neuron=neuron, bias=bias
  131.             )
  132.             Njitdriver.jit_merge_point(
  133.                 cur=cur, train=train, times=times, branes=branes, last_spike=last_spike, spikers=spikers,
  134.                 temporal=temporal, thresh=thresh, triggers=triggers, self=self,
  135.                 abs_refactory=abs_refactory, abs_refactory_value=abs_refactory_value,
  136.                 i=i, t=t, a=a, b=b, c=c,
  137.                 neuron=neuron, bias=bias
  138.             )
  139.             ##bias, neuron = train.pop( t ) ## not pypy
  140.             t = times[i]; i += 1
  141.             bias,neuron = train[t]
  142.             del train[t]
  143.  
  144.  
  145.             if t <= cur:
  146.                 #print 'time error'
  147.                 pass
  148.             else:
  149.                 a = t - cur
  150.                 cur += a
  151.                 #print 'delay', a
  152.                 if cur - last_spike < abs_refactory:
  153.                     brane = abs_refactory_value
  154.                     branes.append( (brane,cur) )
  155.                 else:
  156.                     spikers.append( neuron )
  157.                     if a > 0.1:
  158.                         brane = rest + bias
  159.                         branes.append( (brane,cur) )
  160.                     else:
  161.                         b = a * 10  # 0.0-1.0
  162.                         brane += (rest - brane) * b
  163.                         c = b * temporal
  164.                         bias *= math.log( (temporal-c)+2.8 )
  165.                         brane += bias
  166.                         branes.append( (brane,cur) )
  167.  
  168.                         if brane > thresh:
  169.                             triggers.append( neuron )
  170.                             self.spike( cur )
  171.                             brane = abs_refactory_value
  172.                             #fps *= 0.25        # was this to play catch up?
  173.                             break # this is efficient!
  174.  
  175.         #self._train = {}
  176.         self._brane = brane
  177.         #for lst in [branes, spikers, triggers]:    # not allowed in pypy
  178.         while len(branes) > clip: branes.pop(0)
  179.         while len(spikers) > clip: spikers.pop(0)
  180.         while len(triggers) > clip: triggers.pop(0)
  181.  
  182.         self._lasttime = end = float(time.time())
  183.         #print ntrain, end-now
  184.  
  185.  
  186.     def detach( self ):
  187.         self._inputs = {}       # time:neuron
  188.         self._outputs = []  # children (neurons)
  189.         self._train = {}
  190.         self._branes = []
  191.         self._spikers = []  # last spikers
  192.         self._triggers = [] # last spikers to cause a spike
  193.  
  194.     def __init__( self, name='neuron', x=.0,y=.0,z=.0, column=0, layer=0, fps=12, thresh=100.0, dendrite_bias=35.0, dendrite_noise=1.0, temporal=1.0, distance_factor=0.1, red=.0, green=.0, blue=.0 ):
  195.         self._name = name
  196.         self._fps = fps     # active fps 10?
  197.         self._thresh = thresh
  198.         self._column = column
  199.         self._layer = layer
  200.         self._brane = self._rest = -65.0
  201.         self._abs_refactory = 0.05
  202.         self._abs_refactory_value = -200.0
  203.         self._spike_value = 200.0
  204.         self._temporal = temporal   # ranges 1.0 - inf
  205.         self._distance_factor = distance_factor
  206.         self._dendrite_bias = dendrite_bias
  207.         self._dendrite_noise = dendrite_noise
  208.         self._clip = 128
  209.         self._learning = False
  210.         self._learning_rate = 0.1
  211.  
  212.         ## the spike train of incomming spikes
  213.         self._train = {}
  214.  
  215.         ## list of tuples, (brane value, abs time)
  216.         ## use this list to render wave timeline ##
  217.         self._branes = []
  218.  
  219.         self._spikers = []  # last spikers
  220.         self._triggers = [] # last spikers to cause a spike
  221.         self._lasttime = time.time()
  222.         self._last_spike = 0
  223.         self._inputs = {}       # time:neuron
  224.         self._outputs = []  # children (neurons)
  225.  
  226.         self._color = [ red, green, blue ]
  227.         #x = uniform( 0.2, 0.8 )
  228.         #y = random()   #uniform( 0.2, 0.8 )
  229.         #z = random()   #uniform( 0.2, 0.8 )
  230.         self._pos = [ x,y,z ]
  231.         self._spike_callback = None
  232.         self._state_dirty = False
  233.         self._active = False
  234.         self._cached_distances = {}
  235.         self._clipped_spikes = 0    # for debugging
  236.  
  237.         self._draw_spike = False
  238.         #self._braneRect = self._spikeRect = None
  239.  
  240.     def randomize( self ):
  241.         for n in self._inputs:
  242.             bias = self._dendrite_bias + uniform( -self._dendrite_noise, self._dendrite_noise )
  243.             self._inputs[ n ] = bias
  244.  
  245.  
  246.     def mutate( self, v ):
  247.         for n in self._spikers:
  248.             self._inputs[ n ] += uniform(-v*2,v*2)
  249.         for n in self._triggers:
  250.             self._inputs[ n ] += uniform(-v,v)
  251.  
  252.         if not self._spikes or not self._triggers:
  253.             for n in self._inputs:
  254.                 self._inputs[ n ] += uniform(-v,v)
  255.  
  256.  
  257.     def reward( self, v ):
  258.         if not self._spikers: print 'no spikers to reward'
  259.         for n in self._spikers:
  260.             bias = self._inputs[ n ]
  261.             if abs(bias) < 100:
  262.                 if bias > 15:
  263.                     self._inputs[ n ] += v
  264.                 else:
  265.                     self._inputs[ n ] -= v
  266.            
  267.  
  268.     def punish( self, v ):
  269.         for n in self._inputs:
  270.             self._inputs[n] *= 0.9
  271.            
  272.         for n in self._spikers:
  273.             self._inputs[ n ] += uniform( -v, v )
  274.  
  275.  
  276.  
  277.     def attach_dendrite( self, neuron ):
  278.         bias = self._dendrite_bias + uniform( -self._dendrite_noise, self._dendrite_noise )
  279.         # add neuron to input list
  280.         if neuron not in self._inputs:
  281.             self._inputs[ neuron ] = bias
  282.             #print 'attached neuron', neuron, bias
  283.         if self not in neuron._outputs:
  284.             neuron._outputs.append( self )
  285.             neuron.update_distances()
  286.         return bias
  287.  
  288.     def update_distances( self ):
  289.         for child in self._outputs:
  290.             dist = distance( self._pos, child._pos )
  291.             self._cached_distances[ child ] = dist
  292.  
  293.     def spike( self, t ):
  294.         #print 'spike', t
  295.         self._draw_spike = True
  296.         self._last_spike = t
  297.         self._branes.append( (self._spike_value,t) )
  298.         self._brane = self._abs_refactory_value
  299.         self._branes.append( (self._brane,t) )
  300.         if self._learning and self._triggers:
  301.             #print 'learning'
  302.             n = self._triggers[-1]
  303.             bias = self._inputs[ n ]
  304.             if bias > 0: self._inputs[n] += self._learning_rate
  305.             else: self._inputs[n] -= self._learning_rate
  306.  
  307.         if self._spike_callback:
  308.             self._spike_callback( t )
  309.  
  310.         for child in self._outputs:
  311.             #print 'spike to', child
  312.             bias = child._inputs[ self ]
  313.             #dist = distance( self._pos, child._pos )
  314.             dist = self._cached_distances[ child ]
  315.             dist *= self._distance_factor
  316.             child._train[ t+dist ] = (bias,self)
  317.  
  318.     def stop( self ):
  319.         self._active = False
  320.         print 'clipped spikes', self._clipped_spikes
  321.     def start( self ):
  322.         self._active = True
  323.         self.iterate()
  324.  
  325.     def setup_draw( self, format, braneRect, groupRect, spikeRect, colors ):
  326.         self._braneRect = braneRect
  327.         self._groupRect = groupRect
  328.         self._spikeRect = spikeRect
  329.         self._sdl_colors = colors
  330.         r,g,b = self._color
  331.         self._group_color = RSDL.MapRGB(format, int(r*255), int(g*255), int(b*255))
  332.  
  333.     def draw( self, surf ):
  334.         #if self._braneRect:
  335.         fmt = surf.c_format
  336.         b = int(self._brane * 6)
  337.         if b > 255: b = 255
  338.         elif b < 0: b = 0
  339.         color = RSDL.MapRGB(fmt, 0, 0, b)
  340.         RSDL.FillRect(surf, self._braneRect, color)
  341.         RSDL.FillRect(surf, self._groupRect, self._group_color)
  342.         if self._draw_spike:
  343.             RSDL.FillRect(surf, self._spikeRect, self._sdl_colors['white'])
  344.         else:
  345.             RSDL.FillRect(surf, self._spikeRect, color )#self._sdl_colors['black'])
  346.         self._draw_spike = False
  347.  
  348.  
  349.  
  350.  
  351. Bjitdriver = JitDriver(
  352.     reds=['loops'],
  353.     greens='layers neurons pulse_layers'.split()
  354. )
  355.  
  356. class Brain( object ):
  357.     def loop( self ):
  358.         self._active = True
  359.         fmt = self.screen.c_format
  360.         RSDL.FillRect(self.screen, lltype.nullptr(RSDL.Rect), self.ColorGrey)
  361.         layers = self._layers
  362.         neurons = self._neurons
  363.         pulse_layers = self._pulse_layers
  364.         screen = self.screen
  365.         loops = 0  
  366.         now = start = float( time.time() )
  367.         while self._active:
  368.             #Bjitdriver.can_enter_jit( layers=layers, neurons=neurons, pulse_layers=pulse_layers, loops=loops )
  369.             #Bjitdriver.jit_merge_point( layers=layers, neurons=neurons, pulse_layers=pulse_layers, loops=loops)
  370.             now = float( time.time() )
  371.             self._fps = loops / float(now-start)
  372.             for i,lay in enumerate(self._layers):
  373.                 if self._pulse_layers[i] and False:
  374.                     #print 'pulse layer: %s neurons: %s ' %(i, len(lay))
  375.                     for n in lay:
  376.                         if random()*random() > 0.8:
  377.                             n.spike( now )
  378.             for i,col in enumerate(self._columns):
  379.                 if self._pulse_columns[i]:
  380.                     for n in col: n.spike(now)
  381.             for n in self._neurons:
  382.                 n.iterate()
  383.                 n.draw(self.screen)
  384.             #r,w,x = rpoll.select( [self._stdin], [], [], 1 )   # wait
  385.             rl,wl,xl = rpoll.select( [0], [], [], 0.000001 )    # wait
  386.             if rl:
  387.                 cmd = self._stdin.readline().strip('\n').strip(' ')
  388.                 self.do_command( cmd )
  389.             loops += 1
  390.             self._iterations = loops
  391.             #print loops        # can not always print in mainloop, then select can never read from stdin
  392.             RSDL.Flip(self.screen)
  393.             #self._fps = float(time.time()) - now
  394.         #return loops
  395.         return 0
  396.  
  397.     def __init__(self):
  398.         start = float(time.time())
  399.         self._neurons = []
  400.         self._columns = []
  401.         self._layers = [ [] ] * LAYERS
  402.         self._pulse_layers = [0] * LAYERS
  403.         self._pulse_layers[ 0 ] = 1
  404.  
  405.         self._pulse_columns = [0] * COLUMNS
  406.         self._pulse_columns[ 0 ] = 1
  407.         self._pulse_columns[ 1 ] = 1
  408.         self._pulse_columns[ 2 ] = 1
  409.         self._pulse_columns[ 3 ] = 1
  410.  
  411.  
  412.         inc = 360.0 / COLUMNS
  413.         scale = float( LAYERS )
  414.         expansion = 1.333
  415.         linc = scale / LAYERS
  416.         for column in range(COLUMNS):
  417.             colNeurons = []
  418.             self._columns.append( colNeurons )
  419.             X = math.sin( radians(column*inc) )
  420.             Y = math.cos( radians(column*inc) )
  421.             expanding = STEM
  422.             width = 1.0 / scale
  423.             for layer in range(LAYERS):
  424.                 Z = layer * linc
  425.                 r = random() * random()
  426.                 g = 0.2
  427.                 b = 0.2
  428.                 for i in range(int(expanding)):
  429.                     x = uniform( -width, width )
  430.                     rr = random()*random()      # DJ's trick
  431.                     y = uniform( -width*rr, width*rr ) + X
  432.                     z = Z + Y
  433.                     # create 50/50 exitatory/inhibitory
  434.                     n = RecurrentSpikingModel(x=x, y=y, z=z, column=column, layer=layer, red=r, green=g, blue=b )
  435.                     self._neurons.append( n )
  436.                     colNeurons.append( n )
  437.                     self._layers[ layer ].append( n )
  438.  
  439.                 expanding *= expansion
  440.                 width *= expansion
  441.  
  442.         dendrites = 0
  443.         interlayer = 0
  444.         for lay in self._layers:
  445.             for a in lay:
  446.                 for b in lay:
  447.                     if a is not b and a._column == b._column:
  448.                         a.attach_dendrite( b )
  449.                         dendrites += 1
  450.                         interlayer += 1
  451.  
  452.         intercol = 0
  453.         for col in self._columns:
  454.             for a in col:
  455.                 for b in col:
  456.                     if a is not b and random()*random() > 0.75:
  457.                         a.attach_dendrite( b )
  458.                         intercol += 1
  459.                         dendrites += 1
  460.  
  461.         intercore = 0
  462.         core = self._layers[-1]
  463.         for a in core:
  464.             for b in core:
  465.                 if a is not b and random()*random() > 0.85:
  466.                     a.attach_dendrite( b )
  467.                     intercore += 1
  468.                     dendrites += 1
  469.  
  470.         print 'brain creation time (seconds)', float(time.time())-start
  471.         print 'neurons per column', len(self._columns[0])
  472.         print 'inter-layer dendrites', interlayer
  473.         print 'inter-column dendrites', intercol
  474.         print 'inter-neocoretex dendrites', intercore
  475.         print 'total dendrites', dendrites
  476.         print 'total neurons', len(self._neurons)
  477.         for i,lay in enumerate(self._layers):
  478.             print 'layer: %s    neurons: %s' %(i,len(lay))
  479.         for i,col in enumerate(self._columns):
  480.             print 'column: %s   neurons: %s' %(i,len(col))
  481.  
  482.  
  483.  
  484.         self._stdin = streamio.fdopen_as_stream(0, 'r', 1)
  485.         #self._stdout = streamio.fdopen_as_stream(1, 'w', 1)
  486.         #self._stderr = streamio.fdopen_as_stream(2, 'w', 1)
  487.  
  488.         self._width = 640; self._height = 480
  489.         assert RSDL.Init(RSDL.INIT_VIDEO) >= 0
  490.         self.screen = RSDL.SetVideoMode(self._width, self._height, 32, 0)
  491.         assert self.screen
  492.         fmt = self.screen.c_format
  493.         self.ColorWhite = white = RSDL.MapRGB(fmt, 255, 255, 255)
  494.         self.ColorGrey = grey = RSDL.MapRGB(fmt, 128, 128, 128)
  495.         self.ColorBlack = black = RSDL.MapRGB(fmt, 0, 0, 0)
  496.         self.ColorBlue = blue = RSDL.MapRGB(fmt, 0, 0, 200)
  497.  
  498.         colors = {'white':white, 'grey':grey, 'black':black, 'blue':blue}
  499.  
  500.         x = 1; y = 1
  501.         for i,n in enumerate(self._neurons):
  502.             braneRect = RSDL_helper.mallocrect(x, y, 12, 12)
  503.             groupRect = RSDL_helper.mallocrect(x, y, 12, 2)
  504.             spikeRect = RSDL_helper.mallocrect(x+4, y+4, 4, 4)
  505.             n.setup_draw( self.screen.c_format, braneRect, groupRect, spikeRect, colors )
  506.             x += 13
  507.             if x >= self._width-14:
  508.                 x = 1
  509.                 y += 13
  510.  
  511.     def do_command( self, cmd ):
  512.         if cmd == 'spike-all':
  513.             t = float(time.time())
  514.             for n in self._neurons: n.spike(t)
  515.         elif cmd == 'spike-one':
  516.             t = float(time.time())
  517.             self._neurons[0].spike(t)
  518.         elif cmd == 'spike-column':
  519.             t = float(time.time())
  520.             for n in self._columns[0]:
  521.                 n.spike(t)
  522.         elif cmd == 'info':
  523.             info = self.info()
  524.             #sys.stderr.write( info )
  525.             #sys.stderr.flush()
  526.             print info
  527.  
  528.     def info(self):
  529.         r = ' "num-layers": %s,' %len(self._layers)
  530.         r += ' "num-neurons": %s,' %len(self._neurons)
  531.         r += ' "fps" : %s, ' %self._fps
  532.         r += ' "iterations" : %s, ' %self._iterations
  533.         return '<load_info> { %s }' %r
  534.  
  535.  
  536.  
  537.  
  538.  
  539.  
  540. import subprocess, select, time
  541. import gtk, glib
  542.  
  543. class App:
  544.     def load_info( self, arg ): print arg
  545.  
  546.     def __init__(self):
  547.         self._commands = cmds = []
  548.         self.win = gtk.Window()
  549.         self.win.connect('destroy', lambda w: gtk.main_quit())
  550.         self.root = gtk.VBox(False,10); self.win.add( self.root )
  551.         self.root.set_border_width(20)
  552.         self.header = header = gtk.HBox()
  553.         self.root.pack_start( header, expand=False )
  554.         b = gtk.Button('spike all neurons')
  555.         b.connect('clicked', lambda b,s: s._commands.append('spike-all'), self )
  556.         self.header.pack_start( b, expand=False )
  557.  
  558.         b = gtk.Button('spike one neuron')
  559.         b.connect('clicked', lambda b,s: s._commands.append('spike-one'), self )
  560.         self.header.pack_start( b, expand=False )
  561.  
  562.         b = gtk.Button('spike column 1')
  563.         b.connect('clicked', lambda b,s: s._commands.append('spike-column'), self )
  564.         self.header.pack_start( b, expand=False )
  565.  
  566.         self.header.pack_start( gtk.SeparatorMenuItem() )
  567.  
  568.         b = gtk.Button('debug')
  569.         b.connect('clicked', lambda b,s: s._commands.append('info'), self )
  570.         self.header.pack_start( b, expand=False )
  571.  
  572.         da = gtk.DrawingArea()
  573.         da.set_size_request( 640,480 )
  574.         da.connect('realize', self.realize)
  575.         self.root.pack_start( da )
  576.  
  577.         self._read = None
  578.         glib.timeout_add( 33, self.loop )
  579.         self.win.show_all()
  580.  
  581.  
  582.     def realize(self, da ):
  583.         print 'realize'
  584.         xid = da.window.xid
  585.         self._process = process = subprocess.Popen( 'python rAI.py --pypy --subprocess %s' %xid, stdin=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=32, shell=True )
  586.         self._write = write = process.stdin
  587.         self._read = read = process.stdout
  588.         print 'read', read
  589.         print 'write', write
  590.  
  591.     def loop( self ):
  592.         if self._read:
  593.             rlist,wlist,xlist = select.select( [self._read], [], [], 0.001 )
  594.             while self._commands:
  595.                 cmd = self._commands.pop()
  596.                 print 'sending cmd ->', cmd
  597.                 self._write.write( '%s\n'%cmd )
  598.                 self._write.flush()
  599.             if rlist:
  600.                 a = self._read.readline().strip()
  601.                 if a:
  602.                     print a
  603.                     if a.startswith('<'):
  604.                         func = a[ 1 : a.index('>') ]
  605.                         arg = a[ a.index('>')+1 : ].strip()
  606.                         func = getattr(self, func)
  607.                         func( eval(arg) )
  608.         return True
  609.  
  610.  
  611. if '--subprocess' in sys.argv:
  612.     os.putenv('SDL_WINDOWID', sys.argv[-1])
  613.     def pypy_entry_point():
  614.         def jitpolicy(*args):
  615.             from pypy.jit.metainterp.policy import JitPolicy
  616.             return JitPolicy()
  617.  
  618.         brain = Brain()
  619.         brain.loop()
  620.     if '--pypy' in sys.argv:
  621.         from pypy.translator.interactive import Translation
  622.         t = Translation( pypy_entry_point )
  623.         ## NotImplementedError: --gcrootfinder=asmgcc requires standalone ##
  624.         #t.config.translation.suggest(jit=True, jit_debug='steps', jit_backend='x86', gc='boehm')
  625.         t.annotate()
  626.         t.rtype()
  627.         f = t.compile_c()
  628.         f()
  629.     else:
  630.         pypy_entry_point()
  631.  
  632. else:
  633.     a = App()
  634.     gtk.main()
  635.     print '-------------------exit toplevel-----------------'
Advertisement
Add Comment
Please, Sign In to add comment