Advertisement
Guest User

recurrent neural network written in rpython

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