Skip to content

Instantly share code, notes, and snippets.

@ksato9700
Created December 28, 2011 22:02
Show Gist options
  • Save ksato9700/1530011 to your computer and use it in GitHub Desktop.
Save ksato9700/1530011 to your computer and use it in GitHub Desktop.
Coffeescript implementation of systolic array simulation
events = require 'events'
initiator = new events.EventEmitter
class Pipe extends events.EventEmitter
constructor: (@name)->
@queue = []
recv: (event, value) =>
@queue.push(value)
@emit 'check'
@send(event, value)
send: (event, value) =>
@emit event, event, value
connect: (event, prev)->
prev.on event, @recv
class Input
constructor: (@name, @type, @sequence)->
@pipes = {}
@pipes[@type] = new Pipe("#{@name}_#{@type}")
initiator.on 'run', @run
run: =>
@sequence.push(null)
for s in @sequence
@pipes[@type].send(@type, s)
class Cell
constructor: (@name)->
@sum = 0
@pipes = {}
for i in ['a', 'b']
@pipes[i] = new Pipe("#{@name}_#{i}")
@pipes[i].on 'check', @check
connect: (neighbors) ->
for i in ['a', 'b']
@pipes[i].connect i, neighbors[i].pipes[i]
check: =>
aq = @pipes['a'].queue
bq = @pipes['b'].queue
if aq.length and bq.length
av = aq.shift()
bv = bq.shift()
if not av and not bv
console.log "Result #{@name}: #{@sum}"
else
@sum += av * bv
a_inputs = [
[3,2,3]
[4,5,2]
[2,3,5]
]
b_inputs = [
[3,4,2]
[2,5,3]
[3,2,5]
]
cells = {}
for i in [1..3]
for j in [1..3]
cells[[i,j]] = new Cell "c#{i}#{j}"
for i in [1..3]
cells[[i,0]] = new Input "a#{i}", 'a', a_inputs[i-1]
for i in [1..3]
cells[[0,i]] = new Input "b#{i}", 'b', b_inputs[i-1]
for i in [1..3]
for j in [1..3]
cells[[i,j]].connect
'a': cells[[i,j-1]]
'b': cells[[i-1,j]]
initiator.emit 'run'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment