sin input - once again!

68 views
Skip to first unread message

Roxana Stefanescu

unread,
Aug 28, 2017, 12:39:32 PM8/28/17
to TVB Users
Dear Marmaduke and Lia, 
first thank you Marmaduke for your previous answer. Unfortunately, my questions still remains as I have no idea how I am suppose to use the functions you indicated in response to my previous posting.
As a reminder my question is: how do I implement an input to two particular brain regions (say no 10 and 15) in the form of a sin input of general form: I=A*sin*(w*t+phi_0)+B.
I would greatly appreciate if this time, you would not assume I am some sort of expert in TVB code (as I am not and I will never be) and perhaps provide a helpful example instead.
Thank you so much!
Best wishes, 
Roxana

P.S. You might want to include this example in the next version of TVB as it remains unclear how to specify an input that cannot be prescribed by the several types of equations available in TVB.  

Marmaduke Woodman

unread,
Aug 28, 2017, 6:26:35 PM8/28/17
to tvb-...@googlegroups.com
Hi

You might start with this:


import numpy as np
from tvb.datatypes import patterns

class SinStim(patterns.StimuliRegion):
    def __init__(self, A, w, phi_0, B):
        self.A = A
        self.w = w
        self.phi_0 = phi_0
        self.B = B
    def configure_time(self, t):
        self.t = t
    def __call__(self, i):
        return self.A*np.sin*(self.w*self.t[0, i]+self.phi_0)+self.B

ss = SinStim(A, w, phi_0, B)
...

--
You received this message because you are subscribed to the Google Groups "TVB Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to tvb-users+...@googlegroups.com.
To post to this group, send email to tvb-...@googlegroups.com.
Visit this group at https://groups.google.com/group/tvb-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/tvb-users/dca55df3-3683-4831-9ac2-25d5e984ffb6%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Roxana Stefanescu

unread,
Aug 29, 2017, 2:22:34 PM8/29/17
to TVB Users
Hi Marmaduke, 
while this might be a good start it doesn't seem to lead to a solution; the problem I think, resides in the fact that the function patterns.StimuliRegion does not accept for the "temporal" parameter anything other then an "equations" structure. 
Please find my code below; I also tried to use the "make_train" function which worked before with an equation (please see commented lines) but it doesn't work either.

I believe the ability to provide an arbitrary input to a brain region is of critical importance to TVB simulations in general. Therefore, I would greatly appreciate your help in finding a solution. 
Thank you so much!
Best wishes,
Roxana


Here is the code: 


%pylab nbagg
from tvb.simulator.lab import *
import numpy as np
import tvb.datatypes.projections as projections
from tvb.datatypes.projections import ProjectionSurfaceEEG
from tvb.datatypes.cortex import Cortex
from copy import deepcopy


# configure connectivity
conn = connectivity.Connectivity(load_default=True) # the default is "connectivity_76.zip"   
conn_coupling = coupling.Linear(a = 0.012) 

oscillator = models.ReducedSetHindmarshRose( K11 = 1.5, K12 = 0.25, mu = 3.1, sigma = 0.5,r = 0.012) #alpha 0.012
heunint = integrators.HeunStochastic(dt=2**-7, noise=noise.Additive(nsig=numpy.array([0, ]))) #2 ** -5

nnode = conn.weights.shape[0];

# configure stimulus
class MultiStimuliRegion(patterns.StimuliRegion):
        def __init__(self, *stimuli):
            self.stimuli = stimuli
        def configure_space(self, *args, **kwds):
            [stim.configure_space(*args, **kwds) for stim in self.stimuli]
        def configure_time(self, *args, **kwds):
            [stim.configure_time(*args, **kwds) for stim in self.stimuli]
        def __call__(self, *args, **kwds):
            return np.array([stim(*args, **kwds) for stim in self.stimuli]).sum(axis=0)

def make_train(node_idx, node_weights, **params):
        weighting = np.zeros(nnode)
        weighting[node_idx] = node_weights
        #eqn_t = equations.PulseTrain()
        #eqn_t.parameters.update(params)
        eqn_t = SinStim(params);
        stimulus = patterns.StimuliRegion(
            temporal=eqn_t,
            connectivity=conn,
            weight=weighting)
        return stimulus

class SinStim(patterns.StimuliRegion):
    def __init__(self, A, w, phi_0, B):
        self.A = A
        self.w = w
        self.phi_0 = phi_0
        self.B = B
    def configure_time(self, t):
        self.t = t
    def __call__(self, i):
        return self.A*np.sin*(self.w*self.t[0, i]+self.phi_0)+self.B

ss1 = SinStim(10, 5, 0, 1) 
ss2 = SinStim(10, 5, 1, 1)
stimulus = MultiStimuliRegion(ss1, ss2)

# train1 = make_train([15, 25], 1, 10, 5, 0, 1)
# train2 = make_train([10], 1, 10, 5, 0, 1)
# stimulus = MultiStimuliRegion(train1, train2)

stimulus.configure_space()
time = r_[0:3000:1]
stimulus.configure_time(time)
#pt = stimulus()

    #configure EEG 
rm = region_mapping.RegionMapping.from_file("regionMapping_16k_76.txt")
ss = sensors.SensorsEEG.from_file(source_file="eeg_unitvector_62.txt.bz2")
pr = ProjectionSurfaceEEG()
pr.projection_data = Cortex.from_file_projection_array("projection_eeg_62_surface_16k.mat",matlab_data_name="ProjectionMatrix")

    #configure monitors
fsamp = 1e3/1024 # 1024 Hz
mons = (monitors.EEG(projection=pr, sensors=ss, region_mapping=rm, period=fsamp),
            monitors.TemporalAverage(period=1.0),
            monitors.ProgressLogger(period=500.0))

    #configure simulator
sim = simulator.Simulator(model = oscillator, 
                              connectivity = conn,
                              coupling = conn_coupling, 
                              integrator = heunint, 
                              monitors = mons,
                              stimulus = stimulus,
                              simulation_length=3000.0).configure()

eeg1, tavg1, _ = sim.run() 

mmwoodman

unread,
Sep 1, 2017, 3:55:45 PM9/1/17
to TVB Users


On Tuesday, August 29, 2017 at 8:22:34 PM UTC+2, Roxana Stefanescu wrote:
the problem I think, resides in the fact that the function patterns.StimuliRegion does not accept for the "temporal" parameter anything other then an "equations" structure. 


Ah I see what you mean.. this is a one liner:

eqn_t = TemporalApplicableEquation(equation='A*sin*(w*var+phi_0)+B', parameters={"A": 2.0, ...})

Please look at the existing examples e.g. 


Roxana Stefanescu

unread,
Sep 14, 2017, 1:30:32 PM9/14/17
to TVB Users
Hi Marmaduke, 
sorry for the late response (Irma!).
I tried your suggestion and I get an error in MultiStimuliRegion when I try to configure the time (please see code and error message below). Any suggestions?
Thanks!


Code: 

%pylab nbagg
from tvb.simulator.lab import *
import numpy as np
import tvb.datatypes.projections as projections
from tvb.datatypes.projections import ProjectionSurfaceEEG
from tvb.datatypes.cortex import Cortex
from copy import deepcopy

# configure connectivity
conn = connectivity.Connectivity(load_default=True) # the default is "connectivity_76.zip"   
conn_coupling = coupling.Linear(a = 0.012) 

amp1 = 10; onset1 = 0.1e3; f1 = 0.005;
amp2 = 10; onset2 =0.4e3; f2 = 0.005;

# configure stimulus
class MultiStimuliRegion(patterns.StimuliRegion):
        def __init__(self, *stimuli):
            self.stimuli = stimuli
        def configure_space(self, *args, **kwds):
            [stim.configure_space(*args, **kwds) for stim in self.stimuli]
        def configure_time(self, *args, **kwds):
            [stim.configure_time(*args, **kwds) for stim in self.stimuli]
        def __call__(self, *args, **kwds):
            return np.array([stim(*args, **kwds) for stim in self.stimuli]).sum(axis=0)

nnode = conn.weights.shape[0]

def make_train(node_idx, node_weights, **params):
        weighting = np.zeros(nnode)
        weighting[node_idx] = node_weights
        eqn_t = equations.TemporalApplicableEquation(equation='A*sin*(w*var+phi_0)+B', parameters={"A": 2.0, "w": 5.0, "phi_0":0.1, "B": 1})
        #eqn_t = equations.Sinusoid()
        #eqn_t.parameters.update(params)
        stimulus = patterns.StimuliRegion(
            temporal=eqn_t,
            connectivity=conn,
            weight=weighting)
        return stimulus

train1 = make_train([15, 42], amp1)
train2 = make_train([10], amp2)
stimulus = MultiStimuliRegion(train1, train2)
stimulus.configure_space()
time = r_[0:3000:1]
stimulus.configure_time(time)
#pt = stimulus()



Error reads:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-19-5ff9fa3012dd> in <module>()
     38 stimulus.configure_space()
     39 time = r_[0:3000:1]
---> 40 stimulus.configure_time(time)
     41 #pt = stimulus()

<ipython-input-19-5ff9fa3012dd> in configure_time(self, *args, **kwds)
     13             [stim.configure_space(*args, **kwds) for stim in self.stimuli]
     14         def configure_time(self, *args, **kwds):
---> 15             [stim.configure_time(*args, **kwds) for stim in self.stimuli]
     16         def __call__(self, *args, **kwds):
     17             return np.array([stim(*args, **kwds) for stim in self.stimuli]).sum(axis=0)

C:\D Drive\rTVB_vs15\TVB_Distribution\tvb_data\Lib\site-packages\tvb\datatypes\patterns.pyc in configure_time(self, time)
    174         """
    175         self.time = time
--> 176         self.temporal_pattern = self.time
    177 
    178 

C:\D Drive\rTVB_vs15\TVB_Distribution\tvb_data\Lib\site-packages\tvb\datatypes\patterns.pyc in _set_temporal_pattern(self, t)
    162         Generate a discrete representation of the temporal pattern.
    163         """
--> 164         self.temporal.pattern = t
    165         self._temporal_pattern = numpy.reshape(self.temporal.pattern, (1, -1))
    166 

C:\D Drive\rTVB_vs15\TVB_Distribution\tvb_data\Lib\site-packages\tvb\datatypes\equations.pyc in _set_pattern(self, var)
    107         """
    108 
--> 109         self._pattern = numexpr.evaluate(self.equation, global_dict=self.parameters)
    110 
    111     pattern = property(fget=_get_pattern, fset=_set_pattern)

C:\D Drive\rTVB_vs15\TVB_Distribution\tvb_data\Lib\site-packages\numexpr\necompiler.pyc in evaluate(ex, local_dict, global_dict, out, order, casting, **kwargs)
    762         expr_key = (ex, tuple(sorted(context.items())))
    763         if expr_key not in _names_cache:
--> 764             _names_cache[expr_key] = getExprNames(ex, context)
    765         names, ex_uses_vml = _names_cache[expr_key]
    766         # Get the arguments based on the names.

C:\D Drive\rTVB_vs15\TVB_Distribution\tvb_data\Lib\site-packages\numexpr\necompiler.pyc in getExprNames(text, context)
    688 
    689 def getExprNames(text, context):
--> 690     ex = stringToExpression(text, {}, context)
    691     ast = expressionToAST(ex)
    692     input_order = getInputOrder(ast, None)

C:\D Drive\rTVB_vs15\TVB_Distribution\tvb_data\Lib\site-packages\numexpr\necompiler.pyc in stringToExpression(s, types, context)
    282         names.update(expressions.functions)
    283         # now build the expression
--> 284         ex = eval(c, names)
    285         if expressions.isConstant(ex):
    286             ex = expressions.ConstantNode(ex, expressions.getKind(ex))

<expr> in <module>()

C:\D Drive\rTVB_vs15\TVB_Distribution\tvb_data\Lib\site-packages\numexpr\expressions.pyc in func(*args)
     90                 args[i] = x = ConstantNode(x)
     91             if not isinstance(x, ExpressionNode):
---> 92                 raise TypeError("unsupported object type: %s" % type(x))
     93         return f(*args)
     94 

TypeError: unsupported object type: <type 'function'>

WOODMAN Michael

unread,
Sep 14, 2017, 2:15:04 PM9/14/17
to tvb-...@googlegroups.com
Hi Roxana

You have written sin * (...) which is a syntax error.

Marmaduke Woodman, TVB Platform Engineer, UMR1106; +33 6 46 61 89 34, @maedoc



--
You received this message because you are subscribed to the Google Groups "TVB Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to tvb-users+...@googlegroups.com.
To post to this group, send email to tvb-...@googlegroups.com.
Visit this group at https://groups.google.com/group/tvb-users.

Roxana Stefanescu

unread,
Sep 14, 2017, 3:16:10 PM9/14/17
to TVB Users
Oh, thanks! Didn't see this one! :-)
It works! Thank you so much!! :-)
Best wishes, 
Roxana
Reply all
Reply to author
Forward
0 new messages