Пример #1
0
def brahms_process(persist, input):

    output = copy.deepcopy(persist["output"])

    if input["event"]["type"] == EVENT_INIT_CONNECT:

        # create output on first call
        if input["event"]["flags"] & F_FIRST_CALL:

            # create scalar output (fox population)
            #
            # operation: addPort, default set, class numeric, dims and
            # type, output port name, sample rate
            persist["outputPortHandle"] = brahms.operation(
                persist["self"], OPERATION_ADD_PORT, "", "std/2009/data/numeric", "DOUBLE/REAL/1", "out"
            )

            # set initial persist
            persist["foxes"] = 0.5

            # processed
        output["event"]["response"] = C_OK

    elif input["event"]["type"] == EVENT_INIT_POSTCONNECT:

        # processed
        output["event"]["response"] = C_OK

    elif input["event"]["type"] == EVENT_RUN_SERVICE:

        # read input
        rabbits = input["iif"]["default"]["ports"][0]["data"]

        # run dynamics
        T = 1 / input["time"]["sampleRate"]["rate"]
        d_foxes = -persist["foxes"] + 0.9 * rabbits * persist["foxes"]
        persist["foxes"] = persist["foxes"] + T * d_foxes

        # update output
        brahms.operation(
            persist["self"],
            OPERATION_SET_CONTENT,
            persist["outputPortHandle"],
            numpy.array(persist["foxes"], numpy.float64),
        )

        # processed
        output["event"]["response"] = C_OK

    elif input["event"]["type"] == EVENT_MODULE_INIT:

        # update output
        output["info"]["component"] = (0, 1)
        output["info"]["additional"] = "Author=Ben Mitch\nURL=http://brahms.sourceforge.net\n"

        # processed
        output["event"]["response"] = C_OK

    return (persist, output)
Пример #2
0
def brahms_process(persist, input):

    output = copy.deepcopy(persist['output'])

    if input['event']['type'] == EVENT_INIT_CONNECT:

        # create output on first call
        if input['event']['flags'] & F_FIRST_CALL:

            # create scalar output (fox population)
            #
            # operation: addPort, default set, class numeric, dims and
            # type, output port name, sample rate
            persist['outputPortHandle'] = brahms.operation(
                persist['self'], OPERATION_ADD_PORT, '',
                'std/2009/data/numeric', 'DOUBLE/REAL/1', 'out')

            # set initial persist
            persist['foxes'] = 0.5

        # processed
        output['event']['response'] = C_OK

    elif input['event']['type'] == EVENT_INIT_POSTCONNECT:

        # processed
        output['event']['response'] = C_OK

    elif input['event']['type'] == EVENT_RUN_SERVICE:

        # read input
        rabbits = input['iif']['default']['ports'][0]['data']

        # run dynamics
        T = 1 / input['time']['sampleRate']['rate']
        d_foxes = -persist['foxes'] + 0.9 * rabbits * persist['foxes']
        persist['foxes'] = persist['foxes'] + T * d_foxes

        # update output
        brahms.operation(persist['self'], OPERATION_SET_CONTENT,
                         persist['outputPortHandle'],
                         numpy.array(persist['foxes'], numpy.float64))

        # processed
        output['event']['response'] = C_OK

    elif input['event']['type'] == EVENT_MODULE_INIT:

        # update output
        output['info']['component'] = (0, 1)
        output['info'][
            'additional'] = 'Author=Ben Mitch\nURL=http://brahms.sourceforge.net\n'

        # processed
        output['event']['response'] = C_OK

    return (persist, output)
Пример #3
0
def brahms_process(persist, input):
    # Nominal output
    output = {'event': {'response': S_NULL}}

    # Switch on event type
    if input['event']['type'] == EVENT_MODULE_INIT:

        # Component information
        output['info'] = {}
        output['info']['component'] = (0, 1)
        output['info']['additional'] = ('Author=David Buxton\n')
        output['info']['flags'] = (F_NOT_RATE_CHANGER)

        # OK
        output['event']['response'] = C_OK

    # Switch on event type
    elif input['event']['type'] == EVENT_STATE_SET:

        # OK
        output['event']['response'] = C_OK

    # Switch on event type
    elif input['event']['type'] == EVENT_INIT_CONNECT:

        # On first call
        if input['event']['flags'] & F_FIRST_CALL:
            # Create output port with label 'bg_input'
            # The number here must match the number of BG channels
            persist['bg_input'] = brahms.operation(
                persist['self'],
                OPERATION_ADD_PORT,
                '',
                'std/2009/data/numeric',
                'DOUBLE/REAL/6',
                'bg_input'
            )

            # Initialise ROS nodes
            persist['ros_bg'] = rospy.Publisher("/basal_ganglia/mctx", String, queue_size=10)
            rospy.init_node('spineml_bg', anonymous=True)

            # Access MCtx output
            index = input['iif']['default']['index']['mctx_out']
            port = input['iif']['default']['ports'][index]

            # Store data
            persist['mctx_data'] = port['data']

            # Do nothing
            pass

        # On last call
        if input['event']['flags'] & F_LAST_CALL:
            # Do nothing
            pass

        # OK
        output['event']['response'] = C_OK

    # Switch on event type
    elif input['event']['type'] == EVENT_RUN_SERVICE:

        # DEBUG data
        print(persist['mctx_data'])

        # TODO: Run motor program associated with output channels of activity level 0.95 or above
        # TODO: Create standalone Python motor programs for each action

        # Set input values
        brahms.operation(
            persist['self'],
            OPERATION_SET_CONTENT,
            persist['bg_input'],
            np.array([0.7, 0.2, 0.5, 0.1, 0, 0], np.float64)
        )

        # Send output values to ROS
        persist['ros_bg'].publish(str(persist['mctx_data']))

        # OK
        output['event']['response'] = C_OK

    # Return
    return persist, output
Пример #4
0
def brahms_process(persist, input):


	output = copy.deepcopy(persist['output'])


	if input['event']['type'] == EVENT_INIT_CONNECT:
	
		# create output on first call
		if input['event']['flags'] & F_FIRST_CALL:

			# create scalar output (rabbit population)
			#
			# operation: addPort, default set, class numeric, dims and
			# type, output port name, sample rate
			persist['outputPortHandle'] = brahms.operation(
				persist['self'],
				OPERATION_ADD_PORT,
				'',
				'std/2009/data/numeric',
				'DOUBLE/REAL/1',
				'out'
			)

			# set initial persist
			persist['rabbits'] = 0.5

		# processed
		output['event']['response'] = C_OK



	elif input['event']['type'] == EVENT_INIT_POSTCONNECT:

		# processed
		output['event']['response'] = C_OK




	elif input['event']['type'] == EVENT_RUN_SERVICE:

		# read input
		foxes = input['iif']['default']['ports'][0]['data']

		# run dynamics
		T = 1 / input['time']['sampleRate']['rate']
		d_rabbits = 2 * persist['rabbits'] - 1.2 * persist['rabbits'] * foxes
		persist['rabbits'] = persist['rabbits'] + T * d_rabbits

		# update output
		brahms.operation(
			persist['self'],
			OPERATION_SET_CONTENT,
			persist['outputPortHandle'],
			numpy.array(persist['rabbits'], numpy.float64)
		)

		# processed
		output['event']['response'] = C_OK



	elif input['event']['type'] == EVENT_MODULE_INIT:

		# update output
		output['info']['component'] = (0, 1)
		output['info']['additional'] = 'Author=Ben Mitch\nURL=http://brahms.sourceforge.net\n'

		# processed
		output['event']['response'] = C_OK



	return (persist, output)
Пример #5
0
def brahms_process(persist, input):

    # nominal output
    output = {'event': {'response': S_NULL}}

    # switch on event type
    if input['event']['type'] == EVENT_MODULE_INIT:

        # provide component information
        output['info'] = {}
        output['info']['flags'] = F_NEEDS_ALL_INPUTS + F_NOT_RATE_CHANGER
        output['info']['component'] = (0, 0)
        output['info'][
            'additional'] = 'Author=Ben Mitch\nURL=http://brahms.sourceforge.net\n'

        # ok
        output['event']['response'] = C_OK

    # switch on event type
    elif input['event']['type'] == EVENT_STATE_SET:

        # ok
        output['event']['response'] = C_OK

    # switch on event type
    elif input['event']['type'] == EVENT_INIT_CONNECT:

        # create empty table
        persist['inputs'] = {}

        # access inputs
        ports = input['iif']['default']['ports']
        nports = len(ports)

        # for each input
        for p in range(0, nports):

            # access input
            port = ports[p]
            name = port['name']
            persist['inputs'][name] = port['data']

        # import
        for k in persist['inputs'].keys():
            persist['state']['function'] = persist['state'][
                'function'].replace("$" + k, "persist['" + k + "']")
            exec("persist['" + k + "']=persist['inputs']['" + k + "']")

        # compute function
        result = eval(persist['state']['function'])

        # get data type of result
        struc = numpyType2BrahmsType(result.dtype)

        # get dimensions of result
        dims = shape(result)
        ndims = size(dims)
        sdims = ""
        for i in range(0, ndims):
            if i:
                sdims = "," + sdims
            sdims = str(dims[i]) + sdims
        struc += sdims

        # create output
        persist['hOutputPort'] = brahms.operation(persist['self'],
                                                  OPERATION_ADD_PORT, '',
                                                  'std/2009/data/numeric',
                                                  struc, 'out')

        # ok
        output['event']['response'] = C_OK

    # switch on event type
    elif input['event']['type'] == EVENT_RUN_SERVICE:

        # changing from storing as persist['inputs']['varname'] to
        # persist['varname'] saved 14us a call (a call costs about
        # 175us now). that is to say, that indexing into these
        # arrays is a significant performance hit. if there was a
        # way of setting up the execution so it was "ready to go"
        # without any indexing, performance might improve considerably

        # in addition, we currently have to call ascontiguousarray() on
        # result before we pass it back to the bindings (if it was complex,
        # and we reduce it to real, for instance, it forms a non-contiguous
        # array). if the bindings could handle these sparse arrays, it would
        # be faster than converting it first.

        # compute function
        result = eval(persist['state']['function'])

        # set output
        brahms.operation(persist['self'], OPERATION_SET_CONTENT,
                         persist['hOutputPort'], ascontiguousarray(result))

        # ok
        output['event']['response'] = C_OK

    # return
    return (persist, output)
Пример #6
0
def brahms_process(persist, input):


	output = copy.deepcopy(persist['output'])


	if input['event']['type'] == EVENT_STATE_SET:

		# set initial pars
		persist['drive'] = 0
		persist['num_channels'] = int(persist['state']['numchannels']) # use parameter!
		persist['refractory_time'] = 0



	if input['event']['type'] == EVENT_INIT_CONNECT:
	
		# create output on first call
		if input['event']['flags'] & F_FIRST_CALL:

			# create spikes output (muscle drive)
			#
			# operation: addPort, default set, class numeric, dims and
			# type, output port name, sample rate
			persist['outputPortHandle'] = brahms.operation(
				persist['self'],
				OPERATION_ADD_PORT,
				'',
				'std/2009/data/spikes',
				str(persist['num_channels']),
				'out'
			)

		# processed
		output['event']['response'] = C_OK




	if input['event']['type'] == EVENT_RUN_SERVICE:

		# read input
		t_now = float(input['time']['now']) * input['time']['baseSampleRate']['period']
		head_tilt = input['iif']['default']['ports'][0]['data']
		if head_tilt > 1:
			persist['refractory_time'] = t_now + 0.1

		# run dynamics
		tau = 0.1
		target_drive = 1
		fS = input['time']['sampleRate']['rate']
		Lambda = math.exp(-1/(tau * fS))
		persist['drive'] = Lambda * persist['drive'] + (1-Lambda) * target_drive

		# refractory period (!!????!)
		if persist['refractory_time'] > t_now:
			persist['drive'] = 0

		# generate spiking output
		max_drive = 0.5
		prob_channel_on = max_drive * persist['drive']
		out = [chs for chs in xrange(persist['num_channels']) if random.random() < prob_channel_on]

		# update output
		brahms.operation(
			persist['self'],
			OPERATION_SET_CONTENT,
			persist['outputPortHandle'],
			numpy.array(out, numpy.int32)
		)

		# processed
		output['event']['response'] = C_OK



	if input['event']['type'] == EVENT_MODULE_INIT:

		# update output
		output['info']['component'] = (0, 1)
		output['info']['additional'] = 'Author=Ben Mitch\nURL=http://brahms.sourceforge.net\n'

		# processed
		output['event']['response'] = C_OK





	return (persist, output)
Пример #7
0
def brahms_process(persist, input):



	# nominal output (must use deepcopy)
	output = copy.deepcopy(persist['output'])



	# switch on event type
	if input['event']['type'] == EVENT_MODULE_INIT:

		# provide component information
		output['info']['flags'] = F_NOT_RATE_CHANGER
		output['info']['component'] = (__REL__, __REV__)
		output['info']['additional'] = 'Author=Ben Mitch\nURL=http://brahms.sourceforge.net\n'
		
		# ok
		output['event']['response'] = C_OK

	
		
	# switch on event type
	elif input['event']['type'] == EVENT_STATE_SET:

		# ok
		output['event']['response'] = C_OK



	# switch on event type
	elif input['event']['type'] == EVENT_INIT_CONNECT:

		# on first call
		if input['event']['flags'] & F_FIRST_CALL:

			# create output
			persist['hOutputPort'] = brahms.operation(
				persist['self'],
				OPERATION_ADD_PORT,
				'',
				'std/2009/data/numeric',
				'DOUBLE/COMPLEX/2,3',
				'out'
			)

		# on first call
		if input['event']['flags'] & F_LAST_CALL:

			# validate input
			p = input['iif']['default']['ports']
			if len(p) != 1:
				output['error'] = 'expects one input'
				return (persist, output)
			if p[0]['class'] != 'std/2009/data/numeric':
				output['error'] = 'expects input to be data/numeric class'
				return (persist, output)
			if p[0]['structure'] != 'DOUBLE/COMPLEX/2,3':
				output['error'] = 'expects 2x3 complex input'
				return (persist, output)

		# ok
		output['event']['response'] = C_OK



	# switch on event type
	elif input['event']['type'] == EVENT_RUN_SERVICE:

		# get input
		inp = input['iif']['default']['ports'][0]['data']

		inp[2][0] = 40+50j
		#print inp.shape

		# set output
		brahms.operation(persist['self'], OPERATION_SET_CONTENT, persist['hOutputPort'], inp)

		# ok
		output['event']['response'] = C_OK



	# return
	return (persist, output)
Пример #8
0
def brahms_process(persist, input):

	# nominal output
	output = {'event':{'response':S_NULL}}



	# switch on event type
	if input['event']['type'] == EVENT_MODULE_INIT:

		# provide component information
		output['info'] = {}
		output['info']['flags'] = F_NEEDS_ALL_INPUTS + F_NOT_RATE_CHANGER
		output['info']['component'] = (0, 0)
		output['info']['additional'] = 'Author=Ben Mitch\nURL=http://brahms.sourceforge.net\n'
		
		# ok
		output['event']['response'] = C_OK

	
		
	# switch on event type
	elif input['event']['type'] == EVENT_STATE_SET:

		# ok
		output['event']['response'] = C_OK



	# switch on event type
	elif input['event']['type'] == EVENT_INIT_CONNECT:

		# create empty table
		persist['inputs'] = {}

		# access inputs
		ports = input['iif']['default']['ports']
		nports = len(ports)

		# for each input
		for p in range(0, nports):

			# access input
			port = ports[p]
			name = port['name']
			persist['inputs'][name] = port['data']

		# import
		for k in persist['inputs'].keys():
			persist['state']['function'] = persist['state']['function'].replace("$" + k, "persist['" + k + "']")
			exec("persist['" + k + "']=persist['inputs']['" + k + "']")

		# compute function
		result = eval(persist['state']['function'])

		# get data type of result
		struc = numpyType2BrahmsType(result.dtype)

		# get dimensions of result
		dims = shape(result)
		ndims = size(dims)
		sdims = ""
		for i in range(0,ndims):
			if i:
				sdims = "," + sdims
			sdims = str(dims[i]) + sdims
		struc += sdims

		# create output
		persist['hOutputPort'] = brahms.operation(
			persist['self'],
			OPERATION_ADD_PORT,
			'',
			'std/2009/data/numeric',
			struc,
			'out'
		)

		# ok
		output['event']['response'] = C_OK



	# switch on event type
	elif input['event']['type'] == EVENT_RUN_SERVICE:

		# changing from storing as persist['inputs']['varname'] to
		# persist['varname'] saved 14us a call (a call costs about
		# 175us now). that is to say, that indexing into these
		# arrays is a significant performance hit. if there was a
		# way of setting up the execution so it was "ready to go"
		# without any indexing, performance might improve considerably

		# in addition, we currently have to call ascontiguousarray() on
		# result before we pass it back to the bindings (if it was complex,
		# and we reduce it to real, for instance, it forms a non-contiguous
		# array). if the bindings could handle these sparse arrays, it would
		# be faster than converting it first.

		# compute function
		result = eval(persist['state']['function'])

		# set output
		brahms.operation(persist['self'], OPERATION_SET_CONTENT, persist['hOutputPort'], ascontiguousarray(result))

		# ok
		output['event']['response'] = C_OK



	# return
	return (persist, output)
Пример #9
0
def brahms_process(persist, input):



	# nominal output (must use deepcopy)
	output = copy.deepcopy(persist['output'])



	# switch on event type
	if input['event']['type'] == EVENT_MODULE_INIT:

		# provide component information
		output['info']['flags'] = F_NEEDS_ALL_INPUTS + F_NOT_RATE_CHANGER
		output['info']['component'] = (__REL__, __REV__)
		output['info']['additional'] = 'Author=Ben Mitch\nURL=http://brahms.sourceforge.net\n'
		
		# ok
		output['event']['response'] = C_OK

	
		
	# switch on event type
	elif input['event']['type'] == EVENT_STATE_SET:

		# say hello
		brahms.operation(
			persist['self'],
			OPERATION_BOUT,
			'Hello from Python',
			D_INFO
			)

		# set state
		persist['accum'] = 0

		# get random seed from framework
		seed = brahms.operation(
			persist['self'],
			OPERATION_GET_RANDOM_SEED
		)

		# create an RNG utility
		rng = brahms.operation(
			persist['self'],
			OPERATION_GET_UTILITY_OBJECT,
			'std/2009/util/rng',
			0,
		)

		# get select function from RNG utility
		fselect = brahms.operation(
			persist['self'],
			OPERATION_GET_UTILITY_FUNCTION,
			rng,
			'select'
		)

		# get seed function from RNG utility
		fseed = brahms.operation(
			persist['self'],
			OPERATION_GET_UTILITY_FUNCTION,
			rng,
			'seed')

		# get fill function from RNG utility
		persist['ffill'] = brahms.operation(
			persist['self'],
			OPERATION_GET_UTILITY_FUNCTION,
			rng,
			'fill'
		)

		# select the MT2000.normal generator
		brahms.operation(
			persist['self'],
			OPERATION_CALL_UTILITY_FUNCTION,
			fselect,
			('MT2000.normal', )
		)

		# seed the generator
		brahms.operation(
			persist['self'],
			OPERATION_CALL_UTILITY_FUNCTION,
			fseed,
			(seed, )
		)

		# ok
		output['event']['response'] = C_OK



	# switch on event type
	elif input['event']['type'] == EVENT_INIT_CONNECT:

		# validate input
		p = input['iif']['default']['ports']
		if len(p) != 1:
			output['error'] = 'expects one input'
			return (persist, output)
		if p[0]['class'] != 'std/2009/data/numeric':
			output['error'] = 'expects input to be data/numeric class'
			return (persist, output)
		if p[0]['structure'] != 'DOUBLE/REAL/1':
			output['error'] = 'expects scalar real double input'
			return (persist, output)

		# create output
		persist['hOutputPort'] = brahms.operation(
			persist['self'],
			OPERATION_ADD_PORT,
			'',
			'std/2009/data/numeric',
			'DOUBLE/REAL/' + str(int(persist['state']['count'][0])),
			'out'
		)

		# ok
		output['event']['response'] = C_OK



	# switch on event type
	elif input['event']['type'] == EVENT_RUN_SERVICE:

		# get input
		inp = input['iif']['default']['ports'][0]['data']

		# process
		persist['accum'] = 0.9 * persist['accum'] + inp

		# get values from the generator
		rnd = brahms.operation(
			persist['self'],
			OPERATION_CALL_UTILITY_FUNCTION,
			persist['ffill'],
			(
				numpy.array([]),
				numpy.array(persist['state']['count'], numpy.uint32),
				numpy.array(persist['state']['noise']),
				numpy.array(0.0)
			)
		)

		# spread to multiple channels and add some noise
		myOutput = persist['accum'] * numpy.ones(persist['state']['count'], numpy.float64) + rnd

		# set output
		brahms.operation(persist['self'], OPERATION_SET_CONTENT, persist['hOutputPort'], myOutput)

		# ok
		output['event']['response'] = C_OK



	# return
	return (persist, output)
Пример #10
0
def brahms_process(persist, input):

	# nominal output
	output = {'event':{'response':S_NULL}}


	# switch on event type
	if input['event']['type'] == EVENT_MODULE_INIT:

		# provide component information
		output['info'] = {}
		output['info']['component'] = (0, 1)
		output['info']['additional'] = ('Author=David Buxton\n')
		output['info']['flags'] = (F_NOT_RATE_CHANGER)
		
		# ok
		output['event']['response'] = C_OK

			
	# switch on event type
	elif input['event']['type'] == EVENT_STATE_SET:

		# ok
		output['event']['response'] = C_OK


	# switch on event type
	elif input['event']['type'] == EVENT_INIT_CONNECT:

		# on first call
		if input['event']['flags'] & F_FIRST_CALL:

			# Access input port 'python_in'
			index = input['iif']['default']['index']['python_in']
			port = input['iif']['default']['ports'][index]
			
			# Store data			
			persist['python_in'] = port['data']

			# Create output port with label 'python_out'
			persist['hOutputPort'] = brahms.operation(persist['self'], OPERATION_ADD_PORT, '', 'std/2009/data/numeric', 'DOUBLE/REAL/1', 'python_out')

			# do nothing
			pass

		# on last call
		if input['event']['flags'] & F_LAST_CALL:

			# do nothing
			pass

		# ok
		output['event']['response'] = C_OK


	# switch on event type
	elif input['event']['type'] == EVENT_RUN_SERVICE:

		# Move input data to local variable	
		input_value = persist['python_in']

		# Set output value to input * 2
		brahms.operation(
			persist['self'],
			OPERATION_SET_CONTENT,
			persist['hOutputPort'],
			numpy.array([input_value * 2], numpy.float64)
		)

		# ok
		output['event']['response'] = C_OK


	# return
	return (persist, output)
Пример #11
0
def brahms_process(persist, input):

    output = copy.deepcopy(persist['output'])

    if input['event']['type'] == EVENT_INIT_CONNECT:

        # create output on first call
        if input['event']['flags'] & F_FIRST_CALL:

            # create scalar output (muscle position)
            #
            # operation: addPort, default set, class numeric, dims and
            # type, output port name, sample rate
            persist['outputPortHandle'] = brahms.operation(
                persist['self'], OPERATION_ADD_PORT, '',
                'std/2009/data/numeric', 'DOUBLE/REAL/1', 'tilt')

            # set initial persist
            persist['position'] = 0

        # processed
        output['event']['response'] = C_OK

    if input['event']['type'] == EVENT_INIT_POSTCONNECT:

        # can get structure of input now
        persist['num_channels'] = int(
            input['iif']['default']['ports'][0]['structure'])

        # processed
        output['event']['response'] = C_OK

    if input['event']['type'] == EVENT_RUN_SERVICE:

        # read input (spikes)
        drive = copy.copy(input['iif']['default']['ports'][0]['data'])

        # convert to activity
        drive = sum(drive) / persist['num_channels']

        # run dynamics
        tau = 0.2
        fS = input['time']['sampleRate']['rate']
        Lambda = math.exp(-1 / (tau * fS))
        T = 1 / fS
        persist['position'] = Lambda * persist['position'] + T * drive

        # update output
        brahms.operation(persist['self'], OPERATION_SET_CONTENT,
                         persist['outputPortHandle'],
                         numpy.array(persist['position'], numpy.float64))

        # processed
        output['event']['response'] = C_OK

    if input['event']['type'] == EVENT_MODULE_INIT:

        # update output
        output['info']['component'] = (0, 1)
        output['info'][
            'additional'] = 'Author=Ben Mitch\nURL=http://brahms.sourceforge.net\n'

        # processed
        output['event']['response'] = C_OK

    return (persist, output)