code stringlengths 1 18.2k |
|---|
def shutdown_login_server(self, ): """Shutdown the login server and thread :returns: None :rtype: None :raises: None """ log.debug('Shutting down the login server thread.') self.login_server.shutdown() self.login_server.server_close() self.login_thread.join() |
def token(self, token): """Set the oauth token and the current_user :param token: the oauth token :type token: :class:`dict` :returns: None :rtype: None :raises: None """ self._token = token if token: self.current_user = self.query_login_user() |
def kraken_request(self, method, endpoint, **kwargs): """Make a request to one of the kraken api endpoints. Headers are automatically set to accept :data:`TWITCH_HEADER_ACCEPT`. Also the client id from :data:`CLIENT_ID` will be set. The url will be constructed of :data:`TWITCH_KRAKENURL` and the given endpoint. :param ... |
def usher_request(self, method, endpoint, **kwargs): """Make a request to one of the usher api endpoints. The url will be constructed of :data:`TWITCH_USHERURL` and the given endpoint. :param method: the request method :type method: :class:`str` :param endpoint: the endpoint of the usher api. The base url is automatica... |
def oldapi_request(self, method, endpoint, **kwargs): """Make a request to one of the old api endpoints. The url will be constructed of :data:`TWITCH_APIURL` and the given endpoint. :param method: the request method :type method: :class:`str` :param endpoint: the endpoint of the old api. The base url is automatically p... |
def fetch_viewers(self, game): """Query the viewers and channels of the given game and set them on the object :returns: the given game :rtype: :class:`models.Game` :raises: None """ r = self.kraken_request('GET', 'streams/summary', params={'game': game.name}).json() game.viewers = r['viewers'] game.channels = r['channe... |
def search_games(self, query, live=True): """Search for games that are similar to the query :param query: the query string :type query: :class:`str` :param live: If true, only returns games that are live on at least one channel :type live: :class:`bool` :returns: A list of games :rtype: :class:`list` of :class:`models.... |
def top_games(self, limit=10, offset=0): """Return the current top games :param limit: the maximum amount of top games to query :type limit: :class:`int` :param offset: the offset in the top games :type offset: :class:`int` :returns: a list of top games :rtype: :class:`list` of :class:`models.Game` :raises: None """ r ... |
def get_game(self, name): """Get the game instance for a game name :param name: the name of the game :type name: :class:`str` :returns: the game instance :rtype: :class:`models.Game` | None :raises: None """ games = self.search_games(query=name, live=False) for g in games: if g.name == name: return g |
def get_channel(self, name): """Return the channel for the given name :param name: the channel name :type name: :class:`str` :returns: the model instance :rtype: :class:`models.Channel` :raises: None """ r = self.kraken_request('GET', 'channels/' + name) return models.Channel.wrap_get_channel(r) |
def search_channels(self, query, limit=25, offset=0): """Search for channels and return them :param query: the query string :type query: :class:`str` :param limit: maximum number of results :type limit: :class:`int` :param offset: offset for pagination :type offset: :class:`int` :returns: A list of channels :rtype: :cl... |
def get_stream(self, channel): """Return the stream of the given channel :param channel: the channel that is broadcasting. Either name or models.Channel instance :type channel: :class:`str` | :class:`models.Channel` :returns: the stream or None, if the channel is offline :rtype: :class:`models.Stream` | None :raises: N... |
def get_streams(self, game=None, channels=None, limit=25, offset=0): """Return a list of streams queried by a number of parameters sorted by number of viewers descending :param game: the game or name of the game :type game: :class:`str` | :class:`models.Game` :param channels: list of models.Channels or channel names (c... |
models.Stream.wrap_search(r) |
def search_streams(self, query, hls=False, limit=25, offset=0): """Search for streams and return them :param query: the query string :type query: :class:`str` :param hls: If true, only return streams that have hls stream :type hls: :class:`bool` :param limit: maximum number of results :type limit: :class:`int` :param o... |
def followed_streams(self, limit=25, offset=0): """Return the streams the current user follows. Needs authorization ``user_read``. :param limit: maximum number of results :type limit: :class:`int` :param offset: offset for pagination :type offset: :class:`int` :returns: A list of streams :rtype: :class:`list`of :class:... |
def get_user(self, name): """Get the user for the given name :param name: The username :type name: :class:`str` :returns: the user instance :rtype: :class:`models.User` :raises: None """ r = self.kraken_request('GET', 'user/' + name) return models.User.wrap_get_user(r) |
def get_playlist(self, channel): """Return the playlist for the given channel :param channel: the channel :type channel: :class:`models.Channel` | :class:`str` :returns: the playlist :rtype: :class:`m3u8.M3U8` :raises: :class:`requests.HTTPError` if channel is offline. """ if isinstance(channel, models.Channel): channe... |
def get_quality_options(self, channel): """Get the available quality options for streams of the given channel Possible values in the list: * source * high * medium * low * mobile * audio :param channel: the channel or channel name :type channel: :class:`models.Channel` | :class:`str` :returns: list of quality options :... |
def get_channel_access_token(self, channel): """Return the token and sig for the given channel :param channel: the channel or channel name to get the access token for :type channel: :class:`channel` | :class:`str` :returns: The token and sig for the given channel :rtype: (:class:`unicode`, :class:`unicode`) :raises: No... |
def get_chat_server(self, channel): """Get an appropriate chat server for the given channel Usually the server is irc.twitch.tv. But because of the delicate twitch chat, they use a lot of servers. Big events are on special event servers. This method tries to find a good one. :param channel: the channel with the chat :t... |
def _find_best_chat_server(servers, stats): """Find the best from servers by comparing with the stats :param servers: a list if server adresses, e.g. ['0.0.0.0:80'] :type servers: :class:`list` of :class:`str` :param stats: list of server statuses :type stats: :class:`list` of :class:`chat.ChatServerStatus` :returns: t... |
# statuses, which are worse break return best |
def get_emote_picture(self, emote, size=1.0): """Return the picture for the given emote :param emote: the emote object :type emote: :class:`pytwitcherapi.chat.message.Emote` :param size: the size of the picture. Choices are: 1.0, 2.0, 3.0 :type size: :class:`float` :returns: A string resembling the picturedata of the e... |
def escapejson(string): ''' Escape `string`, which should be syntactically valid JSON (this is not verified), so that it is safe for inclusion in HTML <script> environments and as literal javascript. ''' for fro, to in replacements: string = string.replace(fro, to) return string |
def strip_glob(string, split_str=' '): """ Strip glob portion in `string`. >>> strip_glob('*glob*like') 'glob like' >>> strip_glob('glob?') 'glo' >>> strip_glob('glob[seq]') 'glob' >>> strip_glob('glob[!seq]') 'glob' :type string: str :rtype: str """ string = _GLOB_PORTION_RE.sub(split_str, string) return string.strip(... |
def daterange(start, end, delta=timedelta(days=1), lower=Interval.CLOSED, upper=Interval.OPEN): """Returns a generator which creates the next value in the range on demand""" date_interval = Interval(lower=lower, lower_value=start, upper_value=end, upper=upper) current = start if start in date_interval else start + delt... |
def send_message(self, target_app, dictionary): """ Send a message to the given app, which should be currently running on the Pebble (unless using a non-standard AppMessage endpoint, in which case its rules apply). AppMessage can only represent flat dictionaries with integer keys; as such, ``dictionary`` must be flat a... |
CString("friendship"), }) :param target_app: The UUID of the app to which to send a message. :type target_app: ~uuid.UUID :param dictionary: The dictionary to send. :type dictionary: dict :return: The transaction ID sent message, as used in the ``ack`` and ``nack`` events. :rtype: int """ tid = self._get_txid() message... |
def simulate(): '''instantiate and execute network simulation''' #separate model execution from parameters for safe import from other files nest.ResetKernel() ''' Configuration of the simulation kernel by the previously defined time resolution used in the simulation. Setting "print_time" to True prints the already proc... |
the returned handles in variables for later reference. Here the excitatory and inhibitory, as well as the poisson generator and two spike detectors. The spike detectors will later be used to record excitatory and inhibitory spikes. ''' nodes_ex = nest.Create("iaf_psc_alpha",NE) nodes_in = nest.Create("iaf_psc_alpha",NI... |
that each spike is saved to file by stating the gid of the spiking neuron and the spike time in one line. ''' nest.SetStatus(espikes,[{ "label": os.path.join(spike_output_path, label + "-EX"), "withtime": True, "withgid": True, "to_file": True, }]) nest.SetStatus(ispikes,[{ "label": os.path.join(spike_output_path, labe... |
excitatory and inhibitory neurons using the excitatory synapse. Since the poisson generator is connected to all neurons in the population the default rule ('all_to_all') of Connect() is used. The synaptic properties are inserted via syn_spec which expects a dictionary when defining multiple variables or a string when s... |
Here we use the connection rule 'fixed_indegree', which requires the definition of the indegree. Since the synapse specification is reduced to assigning the pre-defined excitatory synapse it suffices to insert a string. ''' conn_params_ex = {'rule': 'fixed_indegree', 'indegree': CE} nest.Connect(nodes_ex, nodes_ex+node... |
a variable. ''' endsimulate= time.time() ''' Reading out the total number of spikes received from the spike detector connected to the excitatory population and the inhibitory population. ''' events_ex = nest.GetStatus(espikes,"n_events")[0] events_in = nest.GetStatus(ispikes,"n_events")[0] ''' Calculation of the averag... |
by taking the difference of the pre-defined time variables. ''' build_time = endbuild-startbuild sim_time = endsimulate-endbuild ''' Printing the network properties, firing rates and building times. ''' print("Brunel network simulation (Python)") print("Number of neurons : {0}".format(N_neurons)) print("Number of synap... |
def new_metric(name, class_, *args, **kwargs): """Create a new metric of the given class. Raise DuplicateMetricError if the given name has been already registered before Internal function - use "new_<type> instead" """ with LOCK: try: item = REGISTRY[name] except KeyError: item = REGISTRY[name] = class_(*args, **kwargs... |
def delete_metric(name): """Remove the named metric""" with LOCK: old_metric = REGISTRY.pop(name, None) # look for the metric name in the tags and remove it for _, tags in py3comp.iteritems(TAGS): if name in tags: tags.remove(name) return old_metric |
def new_histogram(name, reservoir=None): """ Build a new histogram metric with a given reservoir object If the reservoir is not provided, a uniform reservoir with the default size is used """ if reservoir is None: reservoir = histogram.UniformReservoir(histogram.DEFAULT_UNIFORM_RESERVOIR_SIZE) return new_metric(name, h... |
def new_histogram_with_implicit_reservoir(name, reservoir_type='uniform', *reservoir_args, **reservoir_kwargs): """ Build a new histogram metric and a reservoir from the given parameters """ reservoir = new_reservoir(reservoir_type, *reservoir_args, **reservoir_kwargs) return new_histogram(name, reservoir) |
def new_reservoir(reservoir_type='uniform', *reservoir_args, **reservoir_kwargs): """ Build a new reservoir """ try: reservoir_cls = RESERVOIR_TYPES[reservoir_type] except KeyError: raise InvalidMetricError("Unknown reservoir type: {}".format(reservoir_type)) return reservoir_cls(*reservoir_args, **reservoir_kwargs) |
def get_or_create_histogram(name, reservoir_type, *reservoir_args, **reservoir_kwargs): """ Will return a histogram matching the given parameters or raise DuplicateMetricError if it can't be created due to a name collision with another histogram with different parameters. """ reservoir = new_reservoir(reservoir_type, *... |
def with_histogram(name, reservoir_type="uniform", *reservoir_args, **reservoir_kwargs): """ Time-measuring decorator: the time spent in the wrapped function is measured and added to the named metric. metric_args and metric_kwargs are passed to new_histogram() """ hmetric = get_or_create_histogram(name, reservoir_type,... |
def with_meter(name, tick_interval=meter.DEFAULT_TICK_INTERVAL): """ Call-counting decorator: each time the wrapped function is called the named meter is incremented by one. metric_args and metric_kwargs are passed to new_meter() """ try: mmetric = new_meter(name, tick_interval) except DuplicateMetricError as e: mmetri... |
def timer(name, reservoir_type="uniform", *reservoir_args, **reservoir_kwargs): """ Time-measuring context manager: the time spent in the wrapped block if measured and added to the named metric. """ hmetric = get_or_create_histogram(name, reservoir_type, *reservoir_args, **reservoir_kwargs) t1 = time.time() yield t2 = ... |
def tag(name, tag_name): """ Tag the named metric with the given tag. """ with LOCK: # just to check if <name> exists metric(name) TAGS.setdefault(tag_name, set()).add(name) |
def untag(name, tag_name): """ Remove the given tag from the given metric. Return True if the metric was tagged, False otherwise """ with LOCK: by_tag = TAGS.get(tag_name, None) if not by_tag: return False try: by_tag.remove(name) # remove the tag if no associations left if not by_tag: TAGS.pop(tag_name) return True ex... |
def metrics_by_name_list(names): """ Return a dictionary with {metric name: metric value} for all the metrics with the given names. """ results = {} for name in names: # no lock - a metric could have been removed in the meanwhile try: results[name] = get(name) except InvalidMetricError: continue return results |
def connectivity(ax): '''make an imshow of the intranetwork connectivity''' masked_array = np.ma.array(params.C_YX, mask=params.C_YX==0) # if analysis_params.bw: # cmap = plt.get_cmap(gray, 20) # cmap.set_bad('k', 1.) # else: # cmap = plt.get_cmap('hot', 20) # cmap.set_bad('k', 0.5) # im = ax.imshow(masked_array, cmap=... |
def cell_type_specificity(ax): '''make an imshow of the intranetwork connectivity''' masked_array = np.ma.array(params.T_yX, mask=params.T_yX==0) # cmap = plt.get_cmap('hot', 20) # cmap.set_bad('k', 0.5) # im = ax.imshow(masked_array, cmap=cmap, vmin=0, interpolation='nearest') im = ax.pcolormesh(masked_array, cmap=cma... |
def quantity_yXL(fig, left, bottom, top, quantity=params.L_yXL, label=r'$\mathcal{L}_{yXL}$'): '''make a bunch of image plots, each showing the spatial normalized connectivity of synapses''' layers = ['L1', 'L2/3', 'L4', 'L5', 'L6'] ncols = len(params.y) / 4 #assess vlims vmin = 0 vmax = 0 for y in params.y: if quantit... |
horizontalalignment='center', verticalalignment='center', # transform=ax.transAxes,fontsize=5.5) #colorbar rect = np.array(ax.get_position().bounds) rect[0] += rect[2] + 0.01 rect[1] = bottom rect[2] = 0.01 rect[3] = top-bottom cax = fig.add_axes(rect) cbar = plt.colorbar(im, cax=cax) #cbar.set_label(label, ha='center'... |
def get(self, url, proto='http'): """ Load an url using the GET method. Keyword arguments: url -- the Universal Resource Location proto -- the protocol (default 'http') """ self.last_response = self.session.get(proto + self.base_uri + url, headers=self.headers, cookies=self.cookies, allow_redirects=True, verify=self.ve... |
def post(self, url, data, proto='http', form_name=None): """ Load an url using the POST method. Keyword arguments: url -- the Universal Resource Location data -- the form to be sent proto -- the protocol (default 'http') form_name -- the form name to search the default values """ form = self.translator.fill_form(self.l... |
def fig_kernel_lfp(savefolders, params, transient=200, T=[800., 1000.], X='L5E', lags=[20, 20], channels=[0,3,7,11,13]): ''' This function calculates the STA of LFP, extracts kernels and recontructs the LFP from kernels. Arguments :: transient : the time in milliseconds, after which the analysis should begin so as to a... |
/ srate # slice inds = (tvec < params.tstop) & (tvec >= transient) data_sg_raw = f['data'].value.astype(float) data_sg = data_sg_raw[:, inds] f.close() # kernel width kwidth = 20 # create some dummy spike times activationtimes = np.array([x*100 for x in range(3,11)] + [200]) networkSimSpikegen = CachedNetwork(**params.... |
= plt.rcParams['lines.linewidth'] # zorder=1 else: color=('k' if analysis_params.bw else analysis_params.colorE, 'gray' if analysis_params.bw else analysis_params.colorI)[j] lw = 0.75 if color in ['gray', 'r', 'b'] else plt.rcParams['lines.linewidth'] zorder = 0 if 'I' in X_ else 1 # plot kernel as correlation of spike... |
os.path.join(params.savefolder, 'figures') params.spike_output_path = os.path.join(params.savefolder, 'processed_nest_output') params.networkSimParams['spike_output_path'] = params.spike_output_path #load spike as database inside function to avoid buggy behaviour networkSim = CachedNetwork(**params.networkSimParams) # ... |
y is the id of the cell. x, y = networkSim.get_xy([0,params.tstop]) # Get the spikes for the population of interest given as 'Y' bins = np.arange(0, params.tstop+2) + 0.5 x0_raw = np.histogram(x[X], bins=bins)[0] x0 = x0_raw[inds].astype(float) # correlation between firing rate and LFP deviation # from mean normalized ... |
gridspec.GridSpec(2*len(channels)+1, 8) ax = fig.add_subplot(gsb[1+len(channels):, (i*4):(i*4+2)]) phlp.annotate_subplot(ax, ncols=8/2., nrows=4, letter=alphabet[i*3+2], linear_offset=0.02) # extract kernels, force negative lags to be zero kernels = np.zeros((len(params.N_X), 16, kwidth*2)) for j in range(len(params.X)... |
= fig.add_subplot(gsb[1+len(channels):, i*4+2:i*4+3]) phlp.remove_axis_junk(ax) phlp.annotate_subplot(ax, ncols=8./1, nrows=4, letter=alphabet[i*3+3], linear_offset=0.02) cc = np.zeros(len(zvec)) for ch in np.arange(len(zvec)): cc[ch] = np.corrcoef(data[ch], LFP_reconst[ch])[1, 0] ax.barh(zvec, cc, height=80, align='ce... |
// 2-1) #half-sided real and imaginary component real = abs(X0[1:X0.size // 2])*np.cos(theta) imag = abs(X0[1:X0.size // 2])*np.sin(theta) #account for the antisymmetric phase values X0.imag[1:imag.size+1] = imag X0.imag[imag.size+2:] = -imag[::-1] X0.real[1:real.size+1] = real X0.real[real.size+2:] = real[::-1] x0 = n... |
estimate freqs, PSD_data = calc_signal_power(params, fname=data, transient=transient, Df=None, mlab=True, NFFT=256, noverlap=128, window=plt.mlab.window_hanning) freqs, PSD_LFP_reconst = calc_signal_power(params, fname=LFP_reconst, transient=transient, Df=None, mlab=True, NFFT=256, noverlap=128, window=plt.mlab.window_... |
def fig_kernel_lfp_CINPLA(savefolders, params, transient=200, X='L5E', lags=[20, 20]): ''' This function calculates the STA of LFP, extracts kernels and recontructs the LFP from kernels. kwargs: :: transient : the time in milliseconds, after which the analysis should begin so as to avoid any starting transients X : id ... |
# slice inds = (tvec < params.tstop) & (tvec >= transient) data_sg_raw = f['data'].value.astype(float) f.close() # # kernel width kwidth = 20 # extract kernels kernels = np.zeros((len(params.N_X), 16, 100)) for j in range(len(params.X)): kernels[j] = data_sg_raw[:, 100+kwidth+j*100:100+kwidth+(j+1)*100] / params.N_X[j]... |
np.histogram(x[X_], bins=tvec[cinds])[0].astype(float) if X_ == ('TC'): color='r' else: color=('r', 'b')[j] # plot kernel as correlation of spikegen LFP signal with delta spike train xcorr, vlimround = plotting_correlation(x0_sg/x0_sg.sum()**2, data_sg_raw[:, cinds[:-1]]*1E3, ax, normalize=False, lag=kwidth, color=colo... |
h5py.File(os.path.join(params.savefolder, 'LFPsum.h5')) data_raw = f['data'].value srate = f['srate'].value tvec = np.arange(data_raw.shape[1]) * 1000. / srate # slice inds = (tvec < params.tstop) & (tvec >= transient) data = data_raw[:,inds] # subtract mean dataT = data.T - data.mean(axis=1) data = dataT.T f.close() #... |
from mean normalized by the number of spikes xcorr, vlimround = plotting_correlation(x0/x0.sum(), data*1E3, ax, normalize=False, #unit='%.3f mV', lag=lag, scalebar=False, color='k', title='stLFP\n(trigger %s)' %X, ) # Create scale bar ax.plot([lag, lag], [-1500, -1400], lw=2, color='k', clip_on=False) ax.text(lag*1.04,... |
def fig_kernel_lfp_EITN_II(savefolders, params, transient=200, T=[800., 1000.], X='L5E', lags=[20, 20], channels=[0,3,7,11,13]): ''' This function calculates the STA of LFP, extracts kernels and recontructs the LFP from kernels. Arguments :: transient : the time in milliseconds, after which the analysis should begin so... |
np.arange(f['data'].shape[1]) * 1000. / srate # slice inds = (tvec < params.tstop) & (tvec >= transient) data_sg_raw = f['data'].value.astype(float) data_sg = data_sg_raw[:, inds] f.close() # kernel width kwidth = 20 # create some dummy spike times activationtimes = np.array([x*100 for x in range(3,11)] + [200]) networ... |
# activationtimes[np.arange(-1, 8)][COUNTER]+kwidth+2) # x0_sg = np.histogram(x[X_], bins=cinds)[0].astype(float) # # if X_ == ('TC'): # color='r' # else: # color=('r', 'b')[j] # # # # plot kernel as correlation of spikegen LFP signal with delta spike train # xcorr, vlimround = plotting_correlation(params, # x0_sg/x0_s... |
# path to simulation files params.savefolder = os.path.join(os.path.split(params.savefolder)[0], savefolder) params.figures_path = os.path.join(params.savefolder, 'figures') params.spike_output_path = os.path.join(params.savefolder, 'processed_nest_output') params.networkSimParams['spike_output_path'] = params.spike_ou... |
i == 0: # phlp.annotate_subplot(ax, ncols=15, nrows=4, letter=alphabet[i+1], # linear_offset=0.02) # #collect the spikes x is the times, y is the id of the cell. x, y = networkSim.get_xy([0,params.tstop]) # ## Get the spikes for the population of interest given as 'Y' bins = np.arange(0, params.tstop+2) + 0.5 x0_raw = ... |
## create spikegen histogram for population Y #x0_sg = np.zeros(x0.shape, dtype=float) #x0_sg[activationtimes[Xind]] += params.N_X[Xind] # # #ax.set_yticklabels([]) #ax.set_xticks([-lag, 0, lag]) #ax.set_xticklabels([-lag, 0, lag]) ########################################################################### # Part C, F:... |
fname=LFP_reconst_raw, unit='mV', scaling_factor= 1., scalebar=False, vlimround=vlimround, T=T, ylim=[-1550, 50], color='r', label='$reconstr$', rasterized=False) ax.set_title('LFP & population \n rate predictor') if i > 0: ax.set_yticklabels([]) #########################################################################... |
>= 1 # frequencies greater than 1 Hz for j, ch in enumerate(channels): ax = fig.add_subplot(gsb[j, (i*4+3):(i*4+4)]) if j == 0: phlp.annotate_subplot(ax, ncols=8./1, nrows=4.5*len(channels), letter=alphabet[i*3+4], linear_offset=0.02) ax.set_title('PSD') phlp.remove_axis_junk(ax) ax.loglog(freqs[inds], PSD_data[ch, ind... |
def watch_record(indexer, use_polling=False): """ Start watching `cfstore.record_path`. :type indexer: rash.indexer.Indexer """ if use_polling: from watchdog.observers.polling import PollingObserver as Observer Observer # fool pyflakes else: from watchdog.observers import Observer event_handler = RecordHandler(indexer)... |
def run_sim(morphology='patdemo/cells/j4a.hoc', cell_rotation=dict(x=4.99, y=-4.33, z=3.14), closest_idx=dict(x=-200., y=0., z=800.)): '''set up simple cell simulation with LFPs in the plane''' # Create cell cell = LFPy.Cell(morphology=morphology, **cell_parameters) # Align cell cell.set_rotation(**cell_rotation) # Def... |
def plot_sim(ax, cell, synapse, grid_electrode, point_electrode, letter='a'): '''create a plot''' fig = plt.figure(figsize = (3.27*2/3, 3.27*2/3)) ax = fig.add_axes([.1,.05,.9,.9], aspect='equal', frameon=False) phlp.annotate_subplot(ax, ncols=1, nrows=1, letter=letter, fontsize=16) cax = fig.add_axes([0.8, 0.2, 0.02, ... |
ax.set_ylabel(r'$\phi(\mathbf{r}, t)$ (nV)') #rotation='horizontal') ax.set_xlabel('$t$ (ms)', va='center') for loc, spine in ax.spines.iteritems(): if loc in ['right', 'top']: spine.set_color('none') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') plt.axes([.11, 0.285, .25, .2]) plt.plot(cell... |
def plot_sim_tstep(fig, ax, cell, synapse, grid_electrode, point_electrode, tstep=0, letter='a',title='', cbar=True, show_legend=False): '''create a plot''' ax.set_title(title) if letter != None: phlp.annotate_subplot(ax, ncols=3, nrows=1, letter=letter, linear_offset=0.05, fontsize=16) LFP = grid_electrode.LFP[:, tste... |
fig.add_axes((bbox[2]-0.01, 0.2, 0.01, 0.4), frameon=False) cbar = fig.colorbar(im, cax=cax, format=FormatStrFormatter('%i'), values=[-vlim, vlim]) cbar.set_ticks(cbarticks) cbar.set_label('$\phi(\mathbf{r}, t)$ (nV)', labelpad=0) cbar.outline.set_visible(False) if show_legend: proxy = [plt.Line2D((0,1),(0,1), color='g... |
in xrange(2): ax.plot(point_electrode_parameters['x'][i], point_electrode_parameters['z'][i],'o',ms=6, markeredgecolor='k', markerfacecolor=color_vec[i]) bbox = np.array(ax.get_position()).flatten() ax1 = fig.add_axes((bbox[0], bbox[1], 0.05, 0.2)) ax1.plot(cell.tvec,point_electrode.LFP[0]*1e6,color=color_vec[0], clip_... |
def get_F_y(fname='binzegger_connectivity_table.json', y=['p23']): ''' Extract frequency of occurrences of those cell types that are modeled. The data set contains cell types that are not modeled (TCs etc.) The returned percentages are renormalized onto modeled cell-types, i.e. they sum up to 1 ''' # Load data from jso... |
def get_L_yXL(fname, y, x_in_X, L): ''' compute the layer specificity, defined as: :: L_yXL = k_yXL / k_yX ''' def _get_L_yXL_per_yXL(fname, x_in_X, X_index, y, layer): # Load data from json dictionary f = open(fname, 'r') data = json.load(f) f.close() # Get number of synapses if layer in [str(key) for key in data['dat... |
{} #iterate over postsynaptic cell types for y_value in y: #container data = np.zeros((len(L), len(x_in_X))) #iterate over lamina for i, Li in enumerate(L): #iterate over presynapse population inds for j in range(len(x_in_X)): data[i][j]= _get_L_yXL_per_yXL(fname, x_in_X, X_index=j, y=y_value, layer=Li) L_yXL[y_value] ... |
def get_T_yX(fname, y, y_in_Y, x_in_X, F_y): ''' compute the cell type specificity, defined as: :: T_yX = K_yX / K_YX = F_y * k_yX / sum_y(F_y*k_yX) ''' def _get_k_yX_mul_F_y(y, y_index, X_index): # Load data from json dictionary f = open(fname, 'r') data = json.load(f) f.close() #init variables k_yX = 0. for l in [str... |
yy_value)[0][0] k_yX_mul_F_y += _get_k_yX_mul_F_y(yy_value, ii, j) if k_yX_mul_F_y != 0: T_yX[i, j] = _get_k_yX_mul_F_y(y_value, i, j) / k_yX_mul_F_y return T_yX |
def _compute_J(self): ''' Compute the current amplitude corresponding to the exponential synapse model PSP amplitude Derivation using sympy: :: from sympy import * #define symbols t, tm, Cm, ts, Is, Vmax = symbols('t tm Cm ts Is Vmax') #assume zero delay, t >= 0 #using eq. 8.10 in Sterrat et al V = tm*ts*Is*(exp(-t/tm)... |
Cm*Vmax*(-tm + ts)/(tm*ts*(exp(tm*log(ts/tm)/(tm - ts)) - exp(ts*log(ts/tm)/(tm - ts)))) ''' #LIF params tm = self.model_params['tau_m'] Cm = self.model_params['C_m'] #synapse ts = self.model_params['tau_syn_ex'] Vmax = self.PSP_e #max current amplitude J = Cm*Vmax*(-tm + ts)/(tm*ts*(np.exp(tm*np.log(ts/tm)/(tm - ts)) ... |
def _synDelayParams(self): ''' set up the detailed synaptic delay parameters, loc is mean delay, scale is std with low bound cutoff, assumes numpy.random.normal is used later ''' delays = {} #mean delays loc = np.zeros((len(self.y), len(self.X))) loc[:, 0] = self.delays[0] loc[:, 1::2] = self.delays[0] loc[:, 2::2] = s... |
def _calcDepths(self): ''' return the cortical depth of each subpopulation ''' depths = self.layerBoundaries.mean(axis=1)[1:] depth_y = [] for y in self.y: if y in ['p23', 'b23', 'nb23']: depth_y = np.r_[depth_y, depths[0]] elif y in ['p4', 'ss4(L23)', 'ss4(L4)', 'b4', 'nb4']: depth_y = np.r_[depth_y, depths[1]] elif y... |
def _yCellParams(self): ''' Return dict with parameters for each population. The main operation is filling in cell type specific morphology ''' #cell type specific parameters going into LFPy.Cell yCellParams = {} for layer, morpho, _, _ in self.y_zip_list: yCellParams.update({layer : self.cellParams.copy()}) yCellParam... |
def _set_up_savefolder(self): """ Create catalogs for different file output to clean up savefolder. Non-public method Parameters ---------- None Returns ------- None """ if self.savefolder == None: return self.cells_path = os.path.join(self.savefolder, 'cells') if RANK == 0: if not os.path.isdir(self.cells_path): os.mk... |
def run(self): """ Distribute individual cell simulations across ranks. This method takes no keyword arguments. Parameters ---------- None Returns ------- None """ for cellindex in self.RANK_CELLINDICES: self.cellsim(cellindex) COMM.Barrier() |
def set_pop_soma_pos(self): """ Set `pop_soma_pos` using draw_rand_pos(). This method takes no keyword arguments. Parameters ---------- None Returns ------- numpy.ndarray (x,y,z) coordinates of each neuron in the population See also -------- PopulationSuper.draw_rand_pos """ tic = time() if RANK == 0: pop_soma_pos = se... |
def calc_min_cell_interdist(self, x, y, z): """ Calculate cell interdistance from input coordinates. Parameters ---------- x, y, z : numpy.ndarray xyz-coordinates of each cell-body. Returns ------- min_cell_interdist : np.nparray For each cell-body center, the distance to nearest neighboring cell """ min_cell_interdist... |
def draw_rand_pos(self, radius, z_min, z_max, min_r=np.array([0]), min_cell_interdist=10., **args): """ Draw some random location within radius, z_min, z_max, and constrained by min_r and the minimum cell interdistance. Returned argument is a list of dicts [{'xpos', 'ypos', 'zpos'},]. Parameters ---------- radius : flo... |
np.random.rand(self.POPULATION_SIZE)*(z_max - z_min) + z_min min_r_z = {} min_r = np.array(min_r) if min_r.size > 0: if type(min_r) == type(np.array([])): j = 0 for j in range(min_r.shape[0]): min_r_z[j] = np.interp(z, min_r[0,], min_r[1,]) if j > 0: [w] = np.where(min_r_z[j] < min_r_z[j-1]) min_r_z[j][w] = min_r_z[j-1... |
< min_r_z[j-1]) min_r_z[j][w] = min_r_z[j-1][w] minrz = min_r_z[j] else: minrz[u[i]] = np.interp(z[u[i]], min_r[0,], min_r[1,]) R_z = np.sqrt(x**2 + y**2) #want to make sure that no somas are in the same place. cell_interdist = self.calc_min_cell_interdist(x, y, z) [u] = np.where(np.logical_or((R_z < minrz) != (R_z > r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.