signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def setup_signals(): | signal.signal(signal.SIGINT, shutit_util.ctrl_c_signal_handler)<EOL>signal.signal(signal.SIGQUIT, shutit_util.ctrl_quit_signal_handler)<EOL> | Set up the signal handlers. | f10350:m0 |
def get_shutit_pexpect_sessions(): | sessions = []<EOL>for shutit_object in shutit_global_object.shutit_objects:<EOL><INDENT>for key in shutit_object.shutit_pexpect_sessions:<EOL><INDENT>sessions.append(shutit_object.shutit_pexpect_sessions[key])<EOL><DEDENT><DEDENT>return sessions<EOL> | Returns all the shutit_pexpect sessions in existence. | f10350:m1 |
def __init__(self): | self.shutit_objects = []<EOL>assert self.only_one is None, shutit_util.print_debug()<EOL>self.only_one = True<EOL>self.owd = os.getcwd()<EOL>self.ispy3 = (sys.version_info[<NUM_LIT:0>] >= <NUM_LIT:3>)<EOL>self.global_thread_lock = threading.Lock()<EOL>self.globa... | Constructor. | f10350:c0:m0 |
def determine_interactive(self): | try:<EOL><INDENT>if not sys.stdout.isatty() or os.getpgrp() != os.tcgetpgrp(sys.stdout.fileno()):<EOL><INDENT>self.interactive = <NUM_LIT:0><EOL>return False<EOL><DEDENT><DEDENT>except Exception:<EOL><INDENT>self.interactive = <NUM_LIT:0><EOL>return False<EOL><DEDENT>if self.interactive == <NUM_LIT:0>:<EOL><INDENT>retu... | Determine whether we're in an interactive shell.
Sets interactivity off if appropriate.
cf http://stackoverflow.com/questions/24861351/how-to-detect-if-python-script-is-being-run-as-a-background-process | f10350:c0:m4 |
def shutit_print(self, msg): | if self.pane_manager is None:<EOL><INDENT>print(msg)<EOL><DEDENT> | Handles simple printing of a msg at the global level. | f10350:c0:m8 |
def __init__(self, shutit_global_object): | assert self.only_one is None<EOL>self.only_one is True<EOL>self.shutit_global = shutit_global_object<EOL>self.top_left_session_pane = SessionPane('<STR_LIT>')<EOL>self.top_right_session_pane = SessionPane('<STR_LIT>')<EOL>self.bottom_left_session_pane = SessionPane('<STR_LIT>')<EOL>self.bottom_right... | only_one - singleton insurance | f10350:c1:m0 |
def create_session(docker_image=None,<EOL>docker_rm=None,<EOL>echo=False,<EOL>loglevel='<STR_LIT>',<EOL>nocolor=False,<EOL>session_type='<STR_LIT>',<EOL>vagrant_session_name=None,<EOL>vagrant_image='<STR_LIT>',<EOL>vagrant_gui=False,<EOL>vagrant_memory='<STR_LIT>',<EOL>vagrant_num_machines='<STR_LIT:1>',<EOL>vagrant_pr... | assert session_type in ('<STR_LIT>','<STR_LIT>','<STR_LIT>'), shutit_util.print_debug()<EOL>shutit_global_object = shutit_global.shutit_global_object<EOL>if video != -<NUM_LIT:1> and video > <NUM_LIT:0>:<EOL><INDENT>walkthrough = True<EOL><DEDENT>if session_type in ('<STR_LIT>','<STR_LIT>'):<EOL><INDENT>return shutit_g... | Creates a distinct ShutIt session. Sessions can be of type:
bash - a bash shell is spawned and
vagrant - a Vagrantfile is created and 'vagrant up'ped | f10351:m0 |
def main(): | <EOL>shutit = shutit_global.shutit_global_object.shutit_objects[<NUM_LIT:0>]<EOL>if sys.version_info[<NUM_LIT:0>] == <NUM_LIT:2>:<EOL><INDENT>if sys.version_info[<NUM_LIT:1>] < <NUM_LIT:7>:<EOL><INDENT>shutit.fail('<STR_LIT>') <EOL><DEDENT><DEDENT>try:<EOL><INDENT>shutit.setup_shutit_obj()<EOL><DEDENT>except KeyboardIn... | Main ShutIt function.
Handles the configured actions:
- skeleton - create skeleton module
- list_configs - output computed configuration
- depgraph - output digraph of module dependencies | f10351:m2 |
def map_package(shutit_pexpect_session, package, install_type): | if package in PACKAGE_MAP.keys():<EOL><INDENT>for itype in PACKAGE_MAP[package].keys():<EOL><INDENT>if itype == install_type:<EOL><INDENT>ret = PACKAGE_MAP[package][install_type]<EOL>if isinstance(ret,str):<EOL><INDENT>return ret<EOL><DEDENT>if callable(ret):<EOL><INDENT>ret(shutit_pexpect_session)<EOL>return '<STR_LIT... | If package mapping exists, then return it, else return package. | f10352:m2 |
def is_file_secure(file_name): | if not os.path.isfile(file_name):<EOL><INDENT>return True<EOL><DEDENT>file_mode = os.stat(file_name).st_mode<EOL>if file_mode & (stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IWOTH | stat.S_IXOTH):<EOL><INDENT>return False<EOL><DEDENT>return True<EOL> | Returns false if file is considered insecure, true if secure.
If file doesn't exist, it's considered secure! | f10353:m0 |
def colorise(code, msg): | return '<STR_LIT>' % (code, msg) if code else msg<EOL> | Colorize the given string for a terminal.
See https://misc.flogisoft.com/bash/tip_colors_and_formatting | f10353:m1 |
def emblinken(msg): | return '<STR_LIT>' % msg<EOL> | Blink the message for a terminal | f10353:m2 |
def random_id(size=<NUM_LIT:8>, chars=string.ascii_letters + string.digits): | return '<STR_LIT>'.join(random.choice(chars) for _ in range(size))<EOL> | Generates a random string of given size from the given chars.
@param size: The size of the random string.
@param chars: Constituent pool of characters to draw random characters from.
@type size: number
@type chars: string
@rtype: string
@return: The string of random characters. | f10353:m3 |
def random_word(size=<NUM_LIT:6>): | words = shutit_assets.get_words().splitlines()<EOL>word = '<STR_LIT>'<EOL>while len(word) != size or "<STR_LIT:'>" in word:<EOL><INDENT>word = words[int(random.random() * (len(words) - <NUM_LIT:1>))]<EOL><DEDENT>return word.lower()<EOL> | Returns a random word in lower case. | f10353:m4 |
def get_hash(string_to_hash): | return abs(binascii.crc32(string_to_hash.encode()))<EOL> | Helper function to get preceding integer
eg com.openbet == 1003189494
>>> import binascii
>>> abs(binascii.crc32(b'shutit.tk'))
782914092
Recommended means of determining run order integer part. | f10353:m5 |
def ctrl_c_signal_handler(_, frame): | global ctrl_c_calls<EOL>ctrl_c_calls += <NUM_LIT:1><EOL>if ctrl_c_calls > <NUM_LIT:10>:<EOL><INDENT>shutit_global.shutit_global_object.handle_exit(exit_code=<NUM_LIT:1>)<EOL><DEDENT>shutit_frame = get_shutit_frame(frame)<EOL>if in_ctrlc:<EOL><INDENT>msg = '<STR_LIT>'<EOL>if shutit_frame:<EOL><INDENT>shutit_global.shuti... | CTRL-c signal handler - enters a pause point if it can. | f10353:m9 |
def sendline(child, line): | child.sendline(line)<EOL> | Handles sending of line to pexpect object. | f10353:m13 |
def util_raw_input(prompt='<STR_LIT>', default=None, ispass=False, use_readline=True): | if use_readline:<EOL><INDENT>try:<EOL><INDENT>readline.read_init_file('<STR_LIT>')<EOL><DEDENT>except IOError:<EOL><INDENT>pass<EOL><DEDENT>readline.parse_and_bind('<STR_LIT>')<EOL><DEDENT>prompt = '<STR_LIT:\r\n>' + prompt<EOL>if ispass:<EOL><INDENT>prompt += '<STR_LIT>'<EOL><DEDENT>sanitize_terminal()<EOL>if shutit_g... | Handles raw_input calls, and switches off interactivity if there is apparently
no controlling terminal (or there are any other problems) | f10353:m16 |
def get_input(msg, default='<STR_LIT>', valid=None, boolean=False, ispass=False, color=None): | <EOL>log_trace_when_idle_original_value = shutit_global.shutit_global_object.log_trace_when_idle<EOL>shutit_global.shutit_global_object.log_trace_when_idle = False<EOL>if boolean and valid is None:<EOL><INDENT>valid = ('<STR_LIT:yes>','<STR_LIT:y>','<STR_LIT:Y>','<STR_LIT:1>','<STR_LIT:true>','<STR_LIT>','<STR_LIT:n>',... | Gets input from the user, and returns the answer.
@param msg: message to send to user
@param default: default value if nothing entered
@param valid: valid input values (default == empty list == anything allowed)
@param boolean: whether return value should be boolean
@param ispass: ... | f10353:m17 |
def managing_thread_main_simple(): | import shutit_global<EOL>last_msg = '<STR_LIT>'<EOL>while True:<EOL><INDENT>printed_anything = False<EOL>if shutit_global.shutit_global_object.log_trace_when_idle and time.time() - shutit_global.shutit_global_object.last_log_time > <NUM_LIT:10>:<EOL><INDENT>this_msg = '<STR_LIT>'<EOL>this_header = '<STR_LIT>'<EOL>for t... | Simpler thread to track whether main thread has been quiet for long enough
that a thread dump should be printed. | f10354:m2 |
def parse_shutitfile_args(args_str): | ret = []<EOL>if args_str == '<STR_LIT>':<EOL><INDENT>return ret<EOL><DEDENT>if args_str[<NUM_LIT:0>] == '<STR_LIT:[>' and args_str[-<NUM_LIT:1>] == '<STR_LIT:]>':<EOL><INDENT>ret = eval(args_str)<EOL>assert isinstance(ret, list)<EOL><DEDENT>else:<EOL><INDENT>ret = args_str.split()<EOL><DEDENT>nv_pairs = True<EOL>for it... | Parse shutitfile args (eg in the line 'RUN some args', the passed-in args_str would be 'some args').
If the string is bounded by square brackets, then it's treated in the form: ['arg1','arg2'], and the returned list looks the same.
If the string composed entirely of name-value pairs (eg RUN a=b c=d) then it's r... | f10358:m2 |
def scan_text(text): | while True:<EOL><INDENT>match = re.match("<STR_LIT>", text)<EOL>if match:<EOL><INDENT>before = match.group(<NUM_LIT:1>)<EOL>name = match.group(<NUM_LIT:2>)<EOL>after = match.group(<NUM_LIT:3>)<EOL>text = before + """<STR_LIT>""" + name + """<STR_LIT>""" + after<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>re... | Scan text, and replace items that match shutit's pattern format, ie:
{{ shutit.THING }} | f10358:m8 |
def conn_module(): | return [<EOL>ConnDocker('<STR_LIT>', -<NUM_LIT:0.1>, description='<STR_LIT>'),<EOL>ConnBash ('<STR_LIT>', -<NUM_LIT:0.1>, description='<STR_LIT>'),<EOL>]<EOL> | Connects ShutIt to something | f10361:m0 |
def is_installed(self, shutit): | return False<EOL> | Always considered false for ShutIt setup. | f10361:c1:m0 |
def build(self, shutit): | target_child = self.start_container(shutit, '<STR_LIT>')<EOL>self.setup_host_child(shutit)<EOL>self.setup_target_child(shutit, target_child)<EOL>shutit.send('<STR_LIT>' + shutit_global.shutit_global_object.shutit_state_dir + '<STR_LIT>' + shutit_global.shutit_global_object.shutit_state_dir_build_db_dir + '<STR_LIT:/>' ... | Sets up the target ready for building. | f10361:c1:m3 |
def finalize(self, shutit): | <EOL>target_child_pexpect_session = shutit.get_shutit_pexpect_session_from_id('<STR_LIT>')<EOL>assert not target_child_pexpect_session.sendline(ShutItSendSpec(target_child_pexpect_session,'<STR_LIT>',ignore_background=True)), shutit_util.print_debug()<EOL>host_child_pexpect_session = shutit.get_shutit_pexpect_session_f... | Finalizes the target, exiting for us back to the original shell
and performing any repository work required. | f10361:c1:m4 |
def is_installed(self, shutit): | return False<EOL> | Always considered false for ShutIt setup. | f10361:c2:m0 |
def build(self, shutit): | shutit_pexpect_session = ShutItPexpectSession(shutit, '<STR_LIT>','<STR_LIT>')<EOL>target_child = shutit_pexpect_session.pexpect_child<EOL>shutit_pexpect_session.expect(shutit_global.shutit_global_object.base_prompt.strip(), timeout=<NUM_LIT:10>)<EOL>self.setup_host_child(shutit)<EOL>self.setup_target_child(shutit, tar... | Sets up the machine ready for building. | f10361:c2:m2 |
def finalize(self, shutit): | <EOL>target_child_pexpect_session = shutit.get_shutit_pexpect_session_from_id('<STR_LIT>')<EOL>assert not target_child_pexpect_session.sendline(ShutItSendSpec(target_child_pexpect_session,'<STR_LIT>',ignore_background=True)), shutit_util.print_debug()<EOL>return True<EOL> | Finalizes the target, exiting for us back to the original shell
and performing any repository work required. | f10361:c2:m3 |
def is_installed(self, shutit): | return False<EOL> | Always considered false for ShutIt setup. | f10361:c3:m0 |
def build(self, shutit): | if shutit.build['<STR_LIT>'] in ('<STR_LIT>','<STR_LIT>'):<EOL><INDENT>if shutit.get_current_shutit_pexpect_session_environment().install_type == '<STR_LIT>':<EOL><INDENT>shutit.add_to_bashrc('<STR_LIT>')<EOL>if not shutit.command_available('<STR_LIT>'):<EOL><INDENT>shutit.install('<STR_LIT>')<EOL><DEDENT>shutit.lsb_re... | Initializes target ready for build and updating package management if in container. | f10361:c3:m1 |
def remove(self, shutit): | return True<EOL> | Removes anything performed as part of build. | f10361:c3:m2 |
def get_config(self, shutit): | return True<EOL> | Gets the configured core pacakges, and whether to perform the package
management update. | f10361:c3:m3 |
def __init__(self,<EOL>shutit_pexpect_child,<EOL>send=None,<EOL>send_dict=None,<EOL>expect=None,<EOL>timeout=None,<EOL>check_exit=None,<EOL>fail_on_empty_before=True,<EOL>record_command=True,<EOL>exit_values=None,<EOL>echo=None,<EOL>escape=False,<EOL>check_sudo=True,<EOL>retry=<NUM_LIT:3>,<EOL>note=None,<EOL>assume_gnu... | self.send = send<EOL>self.original_send = send<EOL>self.send_dict = send_dict<EOL>self.expect = expect<EOL>self.shutit_pexpect_child = shutit_pexpect_child<EOL>self.timeout = timeout<EOL>self.check_exit = check_exit<EOL>self.fai... | Specification for arguments to send to shutit functions.
@param send: String to send, ie the command being issued. If set to
None, we consume up to the expect string, which is useful if we
just mat... | f10362:c0:m0 |
def __init__(self,<EOL>prefix): | if prefix == '<STR_LIT>':<EOL><INDENT>self.environment_id = prefix<EOL><DEDENT>else:<EOL><INDENT>self.environment_id = shutit_util.random_id()<EOL><DEDENT>self.module_root_dir = '<STR_LIT:/>'<EOL>self.modules_installed = [] <EOL>self.modules_not_installed = [] <EOL>self.modules_ready ... | Represents a new 'environment' in ShutIt, which corresponds to a host or any
machine-like location (eg docker container, ssh'd to host, or even a chroot jail
with a /tmp folder that has not been touched by shutit. | f10363:c0:m0 |
def has_blocking_background_send(self): | for background_object in self.background_objects:<EOL><INDENT>if background_object.block_other_commands and background_object.run_state in ('<STR_LIT:S>','<STR_LIT:N>'):<EOL><INDENT>self.shutit_obj.log('<STR_LIT>' + str(self),level=logging.DEBUG)<EOL>self.shutit_obj.log('<STR_LIT>' + str(background_object),level=loggin... | Check whether any blocking background commands are waiting to run.
If any are, return True. If none are, return False. | f10365:c1:m2 |
def check_background_commands_complete(self): | unstarted_command_exists = False<EOL>self.shutit_obj.log('<STR_LIT>' + str(self.background_objects),level=logging.DEBUG)<EOL>self.shutit_obj.log('<STR_LIT>' + str(self.login_id),level=logging.DEBUG)<EOL>for background_object in self.background_objects:<EOL><INDENT>self.shutit_obj.log('<STR_LIT>' + str(background_objec... | Check whether any background commands are running or to be run.
If none are, return True. If any are, return False. | f10365:c1:m3 |
def __init__( self, cfg_section, shutit): | self.shutit = shutit<EOL>self.config = {}<EOL>self.__set_config(cfg_section)<EOL>self.lines = []<EOL>self.attaches = []<EOL> | Initialise the emailer object
cfg_section - section in shutit config to look for email configuration items, allowing easier config according to shutit_module.
e.g. 'com.my_module','shutit.core.alerting.emailer.subject': My Module Build Failed!
Config Items:
shutit.core.alerting.emailer.m... | f10369:c0:m0 |
def __set_config(self, cfg_section): | defaults = [<EOL>'<STR_LIT>', None,<EOL>'<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT:localhost>',<EOL>'<STR_LIT>', <NUM_LIT>,<EOL>'<STR_LIT>', True,<EOL>'<STR_LIT>', True,<EOL>'<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', True,<EOL>'<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>... | Set a local config array up according to
defaults and main shutit configuration
cfg_section - see __init__ | f10369:c0:m1 |
@staticmethod<EOL><INDENT>def __gzip(filename):<DEDENT> | zipname = filename + '<STR_LIT>'<EOL>file_pointer = open(filename,'<STR_LIT:rb>')<EOL>zip_pointer = gzip.open(zipname,'<STR_LIT:wb>')<EOL>zip_pointer.writelines(file_pointer)<EOL>file_pointer.close()<EOL>zip_pointer.close()<EOL>return zipname<EOL> | Compress a file returning the new filename (.gz) | f10369:c0:m2 |
def __get_smtp(self): | use_tls = self.config['<STR_LIT>']<EOL>if use_tls:<EOL><INDENT>smtp = SMTP(self.config['<STR_LIT>'], self.config['<STR_LIT>'])<EOL>smtp.starttls()<EOL><DEDENT>else:<EOL><INDENT>smtp = SMTP_SSL(self.config['<STR_LIT>'], self.config['<STR_LIT>'])<EOL><DEDENT>return smtp<EOL> | Return the appropraite smtplib depending on wherther we're using TLS | f10369:c0:m3 |
def add_line(self, line): | self.lines.append(line)<EOL> | Add a single line to the email body | f10369:c0:m4 |
def add_body(self, msg): | self.lines = msg.rsplit('<STR_LIT:\n>')<EOL> | Add an entire email body as a string, will be split on newlines
and overwrite anything currently in the body (e.g added by add_lines) | f10369:c0:m5 |
def attach(self, filename, filetype="<STR_LIT>"): | shutit = self.shutit<EOL>host_path = '<STR_LIT>'<EOL>host_fn = shutit.get_file(filename, host_path)<EOL>if self.config['<STR_LIT>']:<EOL><INDENT>filetype = '<STR_LIT>'<EOL>filename = self.__gzip(host_fn)<EOL>host_fn = os.path.join(host_path, os.path.basename(filename))<EOL><DEDENT>file_pointer = open(host_fn, '<STR_LIT... | Attach a file - currently needs to be entered as root (shutit)
Filename - absolute path, relative to the target host!
filetype - MIMEApplication._subtype | f10369:c0:m6 |
def __compose(self): | msg = MIMEMultipart()<EOL>msg['<STR_LIT>'] = self.config['<STR_LIT>']<EOL>msg['<STR_LIT>'] = self.config['<STR_LIT>']<EOL>msg['<STR_LIT>'] = self.config['<STR_LIT>']<EOL>if self.config['<STR_LIT>']:<EOL><INDENT>msg['<STR_LIT>'] = self.config['<STR_LIT>']<EOL><DEDENT>if self.config['<STR_LIT>'] != '<STR_LIT>':<... | Compose the message, pulling together body, attachments etc | f10369:c0:m7 |
def send(self, attachment_failure=False): | if not self.config['<STR_LIT>']:<EOL><INDENT>self.shutit.log('<STR_LIT>',level=logging.INFO)<EOL>return True<EOL><DEDENT>msg = self.__compose()<EOL>mailto = [self.config['<STR_LIT>']]<EOL>smtp = self.__get_smtp()<EOL>if self.config['<STR_LIT>'] != '<STR_LIT>':<EOL><INDENT>smtp.login(self.config['<STR_LIT>'], self.confi... | Send the email according to the configured setup
attachment_failure - used to indicate a recursive call after the
smtp server has refused based on file size.
Should not be used externally | f10369:c0:m8 |
def cut_levels(nodes, start_level): | final = []<EOL>removed = []<EOL>for node in nodes:<EOL><INDENT>if not hasattr(node, '<STR_LIT>'):<EOL><INDENT>remove(node, removed)<EOL>continue<EOL><DEDENT>if node.attr.get('<STR_LIT>', False):<EOL><INDENT>remove(node, removed)<EOL>continue<EOL><DEDENT>if node.level == start_level:<EOL><INDENT>final.append(node)<EOL>n... | cutting nodes away from menus | f10371:m0 |
def ci(data, statfunction=None, alpha=<NUM_LIT>, n_samples=<NUM_LIT>,<EOL>method='<STR_LIT>', output='<STR_LIT>', epsilon=<NUM_LIT>, multi=None,<EOL>_iter=True): | <EOL>if np.iterable(alpha):<EOL><INDENT>alphas = np.array(alpha)<EOL><DEDENT>else:<EOL><INDENT>alphas = np.array([alpha/<NUM_LIT:2>, <NUM_LIT:1>-alpha/<NUM_LIT:2>])<EOL><DEDENT>if multi is None:<EOL><INDENT>if isinstance(data, tuple):<EOL><INDENT>multi = True<EOL><DEDENT>else:<EOL><INDENT>multi = False<EOL><DEDENT><DED... | Given a set of data ``data``, and a statistics function ``statfunction`` that
applies to that data, computes the bootstrap confidence interval for
``statfunction`` on that data. Data points are assumed to be delineated by
axis 0.
Parameters
----------
data: array_like, shape (N, ...) OR tuple of array_like all with sh... | f10373:m2 |
def bootstrap_indexes(data, n_samples=<NUM_LIT>): | for _ in xrange(n_samples):<EOL><INDENT>yield randint(data.shape[<NUM_LIT:0>], size=(data.shape[<NUM_LIT:0>],))<EOL><DEDENT> | Given data points data, where axis 0 is considered to delineate points, return
an generator for sets of bootstrap indexes. This can be used as a list
of bootstrap indexes (with list(bootstrap_indexes(data))) as well. | f10373:m3 |
def jackknife_indexes(data): | base = np.arange(<NUM_LIT:0>,len(data))<EOL>return (np.delete(base,i) for i in base)<EOL> | Given data points data, where axis 0 is considered to delineate points, return
a list of arrays where each array is a set of jackknife indexes.
For a given set of data Y, the jackknife sample J[i] is defined as the data set
Y with the ith data point deleted. | f10373:m5 |
def subsample_indexes(data, n_samples=<NUM_LIT:1000>, size=<NUM_LIT:0.5>): | if size == -<NUM_LIT:1>:<EOL><INDENT>size = len(data)<EOL><DEDENT>elif (size < <NUM_LIT:1>) and (size > <NUM_LIT:0>):<EOL><INDENT>size = int(round(size*len(data)))<EOL><DEDENT>elif size > <NUM_LIT:1>:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>".format(size))<EOL><DEDENT>base = np.tile(np... | Given data points data, where axis 0 is considered to delineate points, return
a list of arrays where each array is indexes a subsample of the data of size
``size``. If size is >= 1, then it will be taken to be an absolute size. If
size < 1, it will be taken to be a fraction of the data size. If size == -1, it
will be ... | f10373:m6 |
def bootstrap_indexes_moving_block(data, n_samples=<NUM_LIT>,<EOL>block_length=<NUM_LIT:3>, wrap=False): | n_obs = data.shape[<NUM_LIT:0>]<EOL>n_blocks = int(ceil(n_obs / block_length))<EOL>nexts = np.repeat(np.arange(<NUM_LIT:0>, block_length)[None, :], n_blocks, axis=<NUM_LIT:0>)<EOL>if wrap:<EOL><INDENT>last_block = n_obs<EOL><DEDENT>else:<EOL><INDENT>last_block = n_obs - block_length<EOL><DEDENT>for _ in xrange(n_sample... | Generate moving-block bootstrap samples.
Given data points `data`, where axis 0 is considered to delineate points,
return a generator for sets of bootstrap indexes. This can be used as a
list of bootstrap indexes (with list(bootstrap_indexes_moving_block(data))) as
well.
Parameters
----------
n_samples [default 1000... | f10373:m7 |
def __init__(self, signal, events, event_names = [], covariates = None, durations = None, sample_frequency = <NUM_LIT:1.0>, deconvolution_interval = [-<NUM_LIT:0.5>, <NUM_LIT:5>], deconvolution_frequency = None): | self.logger = logging.getLogger('<STR_LIT>')<EOL>ch = logging.StreamHandler()<EOL>ch.setLevel(logging.DEBUG)<EOL>formatter = logging.Formatter('<STR_LIT>')<EOL>ch.setFormatter(formatter)<EOL>self.logger.addHandler(ch)<EOL>self.logger.debug('<STR_LIT>' % (sample_frequency))<EOL>self.signal = signal <EOL>if len(self.sign... | FIRDeconvolution takes a signal and events in order to perform FIR fitting of the event-related responses in the signal.
Most settings for the analysis are set here.
:param signal: input signal.
:type signal: numpy array, (nr_signals x nr_samples)
:param events: event occ... | f10378:c0:m0 |
def create_event_regressors(self, event_times_indices, covariates = None, durations = None): | <EOL>if covariates is None:<EOL><INDENT>covariates = np.ones(self.event_times_indices.shape)<EOL><DEDENT>if durations is None:<EOL><INDENT>durations = np.ones(self.event_times_indices.shape)<EOL><DEDENT>else:<EOL><INDENT>durations = np.round(durations*self.deconvolution_frequency).astype(int)<EOL><DEDENT>mean_duration ... | create_event_regressors creates the part of the design matrix corresponding to one event type.
:param event_times_indices: indices in the resampled data, on which the events occurred.
:type event_times_indices: numpy array, (nr_events)
:param covariates: covariates belonging to thi... | f10378:c0:m1 |
def create_design_matrix(self, demean = False, intercept = True): | self.design_matrix = np.zeros((int(self.number_of_event_types*self.deconvolution_interval_size), self.resampled_signal_size))<EOL>for i, covariate in enumerate(self.covariates.keys()):<EOL><INDENT>self.logger.debug('<STR_LIT>' + covariate)<EOL>indices = np.arange(i*self.deconvolution_interval_size,(i+<NUM_LIT:1>)*self.... | create_design_matrix calls create_event_regressors for each of the covariates in the self.covariates dict. self.designmatrix is created and is shaped (nr_regressors, self.resampled_signal.shape[-1]) | f10378:c0:m2 |
def add_continuous_regressors_to_design_matrix(self, regressors): | previous_design_matrix_shape = self.design_matrix.shape<EOL>if len(regressors.shape) == <NUM_LIT:1>:<EOL><INDENT>regressors = regressors[np.newaxis, :]<EOL><DEDENT>if regressors.shape[<NUM_LIT:1>] != self.resampled_signal.shape[<NUM_LIT:1>]:<EOL><INDENT>self.logger.warning('<STR_LIT>' % (regressors.shape, self.resample... | add_continuous_regressors_to_design_matrix appends continuously sampled regressors to the existing design matrix. One uses this addition to the design matrix when one expects the data to contain nuisance factors that aren't tied to the moments of specific events. For instance, in fMRI analysis this allows us to add car... | f10378:c0:m3 |
def regress(self, method = '<STR_LIT>'): | if method is '<STR_LIT>':<EOL><INDENT>self.betas, residuals_sum, rank, s = LA.lstsq(self.design_matrix.T, self.resampled_signal.T)<EOL>self.residuals = self.resampled_signal - self.predict_from_design_matrix(self.design_matrix)<EOL><DEDENT>elif method is '<STR_LIT>':<EOL><INDENT>import statsmodels.api as sm<EOL>assert ... | regress performs linear least squares regression of the designmatrix on the data.
:param method: method, or backend to be used for the regression analysis.
:type method: string, one of ['lstsq', 'sm_ols']
:returns: instance variables 'betas' (nr_betas x nr_signals) and 'residuals' ... | f10378:c0:m4 |
def ridge_regress(self, cv = <NUM_LIT:20>, alphas = None ): | if alphas is None:<EOL><INDENT>alphas = np.logspace(<NUM_LIT:7>, <NUM_LIT:0>, <NUM_LIT:20>)<EOL><DEDENT>self.rcv = linear_model.RidgeCV(alphas=alphas, <EOL>fit_intercept=False, <EOL>cv=cv) <EOL>self.rcv.fit(self.design_matrix.T, self.resampled_signal.T)<EOL>self.betas = self.rcv.coef_.T<EOL>self.residuals = self.resamp... | perform k-folds cross-validated ridge regression on the design_matrix. To be used when the design matrix contains very collinear regressors. For cross-validation and ridge fitting, we use sklearn's RidgeCV functionality. Note: intercept is not fit, and data are not prenormalized.
:param cv: cross-validate... | f10378:c0:m5 |
def betas_for_cov(self, covariate = '<STR_LIT:0>'): | <EOL>this_covariate_index = list(self.covariates.keys()).index(covariate)<EOL>return self.betas[int(this_covariate_index*self.deconvolution_interval_size):int((this_covariate_index+<NUM_LIT:1>)*self.deconvolution_interval_size)]<EOL> | betas_for_cov returns the beta values (i.e. IRF) associated with a specific covariate.
:param covariate: name of covariate.
:type covariate: string | f10378:c0:m6 |
def betas_for_events(self): | self.betas_per_event_type = np.zeros((len(self.covariates), self.deconvolution_interval_size, self.resampled_signal.shape[<NUM_LIT:0>]))<EOL>for i, covariate in enumerate(self.covariates.keys()):<EOL><INDENT>self.betas_per_event_type[i] = self.betas_for_cov(covariate)<EOL><DEDENT> | betas_for_events creates an internal self.betas_per_event_type array, of (nr_covariates x self.devonvolution_interval_size),
which holds the outcome betas per event type,in the order generated by self.covariates.keys() | f10378:c0:m7 |
def predict_from_design_matrix(self, design_matrix): | <EOL>assert hasattr(self, '<STR_LIT>'), '<STR_LIT>'<EOL>assert design_matrix.shape[<NUM_LIT:0>] == self.betas.shape[<NUM_LIT:0>],'<STR_LIT>'<EOL>prediction = np.dot(self.betas.astype(np.float32).T, design_matrix.astype(np.float32))<EOL>return prediction<EOL> | predict_from_design_matrix predicts signals given a design matrix.
:param design_matrix: design matrix from which to predict a signal.
:type design_matrix: numpy array, (nr_samples x betas.shape)
:returns: predicted signal(s)
:rtype: numpy array (nr_signals x nr_samples... | f10378:c0:m8 |
def calculate_rsq(self): | assert hasattr(self, '<STR_LIT>'), '<STR_LIT>'<EOL>explained_times = self.design_matrix.sum(axis = <NUM_LIT:0>) != <NUM_LIT:0><EOL>explained_signal = self.predict_from_design_matrix(self.design_matrix)<EOL>self.rsq = <NUM_LIT:1.0> - np.sum((explained_signal[:,explained_times] - self.resampled_signal[:,explained_times])... | calculate_rsq calculates coefficient of determination, or r-squared, defined here as 1.0 - SS_res / SS_tot. rsq is only calculated for those timepoints in the data for which the design matrix is non-zero. | f10378:c0:m9 |
def bootstrap_on_residuals(self, nr_repetitions = <NUM_LIT:1000>): | assert self.resampled_signal.shape[<NUM_LIT:0>] == <NUM_LIT:1>,'<STR_LIT>' % str(self.resampled_signal.shape)<EOL>assert hasattr(self, '<STR_LIT>'), '<STR_LIT>'<EOL>bootstrap_data = np.zeros((self.resampled_signal_size, nr_repetitions))<EOL>explained_signal = self.predict_from_design_matrix(self.design_matrix).T<EOL>fo... | bootstrap_on_residuals bootstraps, by shuffling the residuals. bootstrap_on_residuals should only be used on single-channel data, as otherwise the memory load might increase too much. This uses the lstsq backend regression for a single-pass fit across repetitions. Please note that shuffling the residuals may change the... | f10378:c0:m10 |
def infomax(data, weights=None, l_rate=None, block=None, w_change=<NUM_LIT>,<EOL>anneal_deg=<NUM_LIT>, anneal_step=<NUM_LIT>, extended=False, n_subgauss=<NUM_LIT:1>,<EOL>kurt_size=<NUM_LIT>, ext_blocks=<NUM_LIT:1>, max_iter=<NUM_LIT:200>,<EOL>random_state=None, verbose=None): | rng = check_random_state(random_state)<EOL>max_weight = <NUM_LIT><EOL>restart_fac = <NUM_LIT><EOL>min_l_rate = <NUM_LIT><EOL>blowup = <NUM_LIT><EOL>blowup_fac = <NUM_LIT:0.5><EOL>n_small_angle = <NUM_LIT:20><EOL>degconst = <NUM_LIT> / np.pi<EOL>extmomentum = <NUM_LIT:0.5><EOL>signsbias = <NUM_LIT><EOL>signcount_thresho... | Run the (extended) Infomax ICA decomposition on raw data
based on the publications of Bell & Sejnowski 1995 (Infomax)
and Lee, Girolami & Sejnowski, 1999 (extended Infomax)
Parameters
----------
data : np.ndarray, shape (n_samples, n_features)
The data to unmix.
w_init : np.ndarray, sh... | f10381:m0 |
def loadmat(filename): | data = sploadmat(filename, struct_as_record=False, squeeze_me=True)<EOL>return _check_keys(data)<EOL> | This function should be called instead of direct spio.loadmat
as it cures the problem of not properly recovering python dictionaries
from mat files. It calls the function check keys to cure all entries
which are still mat-objects | f10384:m0 |
def _check_keys(dictionary): | for key in dictionary:<EOL><INDENT>if isinstance(dictionary[key], matlab.mio5_params.mat_struct):<EOL><INDENT>dictionary[key] = _todict(dictionary[key])<EOL><DEDENT><DEDENT>return dictionary<EOL> | checks if entries in dictionary are mat-objects. If yes
todict is called to change them to nested dictionaries | f10384:m1 |
def _todict(matobj): | dictionary = {}<EOL>for strg in matobj._fieldnames:<EOL><INDENT>elem = matobj.__dict__[strg]<EOL>if isinstance(elem, matlab.mio5_params.mat_struct):<EOL><INDENT>dictionary[strg] = _todict(elem)<EOL><DEDENT>else:<EOL><INDENT>dictionary[strg] = elem<EOL><DEDENT><DEDENT>return dictionary<EOL> | a recursive function which constructs from matobjects nested dictionaries | f10384:m2 |
def generate_covsig(covmat, n): | global randn_index<EOL>global randn<EOL>covmat = np.atleast_2d(covmat)<EOL>m = covmat.shape[<NUM_LIT:0>]<EOL>l = np.linalg.cholesky(covmat)<EOL>x = []<EOL>while len(x) < n * m:<EOL><INDENT>to_go = min(randn_index + n * m - len(x), len(randn))<EOL>x.extend(randn[randn_index:to_go])<EOL>randn_index = to_go % len(randn)<E... | generate pseudorandom stochastic signals with covariance matrix covmat | f10391:m0 |
def singletrial(num_trials, skipstep=<NUM_LIT:1>): | for t in range(<NUM_LIT:0>, num_trials, skipstep):<EOL><INDENT>trainset = [t]<EOL>testset = [i for i in range(trainset[<NUM_LIT:0>])] +[i for i in range(trainset[-<NUM_LIT:1>] + <NUM_LIT:1>, num_trials)]<EOL>testset = sort([t % num_trials for t in testset])<EOL>yield trainset, testset<EOL><DEDENT> | Single-trial cross-validation schema
Use one trial for training, all others for testing.
Parameters
----------
num_trials : int
Total number of trials
skipstep : int
only use every `skipstep` trial for training
Returns
-------
gen : generator object
the generat... | f10406:m0 |
def multitrial(num_trials, skipstep=<NUM_LIT:1>): | for t in range(<NUM_LIT:0>, num_trials, skipstep):<EOL><INDENT>testset = [t]<EOL>trainset = [i for i in range(testset[<NUM_LIT:0>])] +[i for i in range(testset[-<NUM_LIT:1>] + <NUM_LIT:1>, num_trials)]<EOL>trainset = sort([t % num_trials for t in trainset])<EOL>yield trainset, testset<EOL><DEDENT> | Multi-trial cross-validation schema
Use one trial for testing, all others for training.
Parameters
----------
num_trials : int
Total number of trials
skipstep : int
only use every `skipstep` trial for testing
Returns
-------
gen : generator object
the generator... | f10406:m1 |
def splitset(num_trials, skipstep=None): | split = num_trials // <NUM_LIT:2><EOL>a = list(range(<NUM_LIT:0>, split))<EOL>b = list(range(split, num_trials))<EOL>yield a, b<EOL>yield b, a<EOL> | Split-set cross validation
Use half the trials for training, and the other half for testing. Then
repeat the other way round.
Parameters
----------
num_trials : int
Total number of trials
skipstep : int
unused
Returns
-------
gen : generator object
the gene... | f10406:m2 |
def make_nfold(n): | return partial(_nfold, n=n)<EOL> | n-fold cross validation
Use each of n blocks for testing once.
Parameters
----------
n : int
number of blocks
Returns
-------
gengen : func
a function that returns the generator | f10406:m3 |
def plainica(x, reducedim=<NUM_LIT>, backend=None, random_state=None): | x = atleast_3d(x)<EOL>t, m, l = np.shape(x)<EOL>if backend is None:<EOL><INDENT>backend = scotbackend<EOL><DEDENT>if reducedim == '<STR_LIT>':<EOL><INDENT>c = np.eye(m)<EOL>d = np.eye(m)<EOL>xpca = x<EOL><DEDENT>else:<EOL><INDENT>c, d, xpca = backend['<STR_LIT>'](x, reducedim)<EOL><DEDENT>mx, ux = backend['<STR_LIT>'](... | Source decomposition with ICA.
Apply ICA to the data x, with optional PCA dimensionality reduction.
Parameters
----------
x : array, shape (n_trials, n_channels, n_samples) or (n_channels, n_samples)
data set
reducedim : {int, float, 'no_pca'}, optional
A number of less than 1 in i... | f10407:m0 |
def parallel_loop(func, n_jobs=<NUM_LIT:1>, verbose=<NUM_LIT:1>): | if n_jobs:<EOL><INDENT>try:<EOL><INDENT>from joblib import Parallel, delayed<EOL><DEDENT>except ImportError:<EOL><INDENT>try:<EOL><INDENT>from sklearn.externals.joblib import Parallel, delayed<EOL><DEDENT>except ImportError:<EOL><INDENT>n_jobs = None<EOL><DEDENT><DEDENT><DEDENT>if not n_jobs:<EOL><INDENT>if verbose:<EO... | run loops in parallel, if joblib is available.
Parameters
----------
func : function
function to be executed in parallel
n_jobs : int | None
Number of jobs. If set to None, do not attempt to use joblib.
verbose : int
verbosity level
Notes
-----
Execution of the ... | f10409:m0 |
def prepare_topoplots(topo, values): | values = np.atleast_2d(values)<EOL>topomaps = []<EOL>for i in range(values.shape[<NUM_LIT:0>]):<EOL><INDENT>topo.set_values(values[i, :])<EOL>topo.create_map()<EOL>topomaps.append(topo.get_map())<EOL><DEDENT>return topomaps<EOL> | Prepare multiple topo maps for cached plotting.
.. note:: Parameter `topo` is modified by the function by calling :func:`~eegtopo.topoplot.Topoplot.set_values`.
Parameters
----------
topo : :class:`~eegtopo.topoplot.Topoplot`
Scalp maps are created with this class
values : array, shape = [... | f10410:m4 |
def plot_topo(axis, topo, topomap, crange=None, offset=(<NUM_LIT:0>,<NUM_LIT:0>),<EOL>plot_locations=True, plot_head=True): | topo.set_map(topomap)<EOL>h = topo.plot_map(axis, crange=crange, offset=offset)<EOL>if plot_locations:<EOL><INDENT>topo.plot_locations(axis, offset=offset)<EOL><DEDENT>if plot_head:<EOL><INDENT>topo.plot_head(axis, offset=offset)<EOL><DEDENT>return h<EOL> | Draw a topoplot in given axis.
.. note:: Parameter `topo` is modified by the function by calling :func:`~eegtopo.topoplot.Topoplot.set_map`.
Parameters
----------
axis : axis
Axis to draw into.
topo : :class:`~eegtopo.topoplot.Topoplot`
This object draws the topo plot
topomap :... | f10410:m5 |
def plot_sources(topo, mixmaps, unmixmaps, global_scale=None, fig=None): | urange, mrange = None, None<EOL>m = len(mixmaps)<EOL>if global_scale:<EOL><INDENT>tmp = np.asarray(unmixmaps)<EOL>tmp = tmp[np.logical_not(np.isnan(tmp))]<EOL>umax = np.percentile(np.abs(tmp), global_scale)<EOL>umin = -umax<EOL>urange = [umin, umax]<EOL>tmp = np.asarray(mixmaps)<EOL>tmp = tmp[np.logical_not(np.isnan(tm... | Plot all scalp projections of mixing- and unmixing-maps.
.. note:: Parameter `topo` is modified by the function by calling :func:`~eegtopo.topoplot.Topoplot.set_map`.
Parameters
----------
topo : :class:`~eegtopo.topoplot.Topoplot`
This object draws the topo plot
mixmaps : array, shape = [... | f10410:m6 |
def plot_connectivity_topos(layout='<STR_LIT>', topo=None, topomaps=None, fig=None): | m = len(topomaps)<EOL>if fig is None:<EOL><INDENT>fig = new_figure()<EOL><DEDENT>if layout == '<STR_LIT>':<EOL><INDENT>for i in range(m):<EOL><INDENT>ax = fig.add_subplot(m, m, i*(<NUM_LIT:1>+m) + <NUM_LIT:1>)<EOL>plot_topo(ax, topo, topomaps[i])<EOL>ax.set_yticks([])<EOL>ax.set_xticks([])<EOL>ax.set_frame_on(False)<EO... | Place topo plots in a figure suitable for connectivity visualization.
.. note:: Parameter `topo` is modified by the function by calling :func:`~eegtopo.topoplot.Topoplot.set_map`.
Parameters
----------
layout : str
'diagonal' -> place topo plots on diagonal.
otherwise -> place topo plo... | f10410:m7 |
def plot_connectivity_spectrum(a, fs=<NUM_LIT:2>, freq_range=(-np.inf, np.inf), diagonal=<NUM_LIT:0>, border=False, fig=None): | a = np.atleast_3d(a)<EOL>if a.ndim == <NUM_LIT:3>:<EOL><INDENT>[_, m, f] = a.shape<EOL>l = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>[l, _, m, f] = a.shape<EOL><DEDENT>freq = np.linspace(<NUM_LIT:0>, fs / <NUM_LIT:2>, f)<EOL>lowest, highest = np.inf, <NUM_LIT:0><EOL>left = max(freq_range[<NUM_LIT:0>], freq[<NUM_LIT:0>]... | Draw connectivity plots.
Parameters
----------
a : array, shape (n_channels, n_channels, n_fft) or (1 or 3, n_channels, n_channels, n_fft)
If a.ndim == 3, normal plots are created,
If a.ndim == 4 and a.shape[0] == 1, the area between the curve and y=0 is filled transparently,
If a.n... | f10410:m8 |
def plot_connectivity_significance(s, fs=<NUM_LIT:2>, freq_range=(-np.inf, np.inf), diagonal=<NUM_LIT:0>, border=False, fig=None): | a = np.atleast_3d(s)<EOL>[_, m, f] = a.shape<EOL>freq = np.linspace(<NUM_LIT:0>, fs / <NUM_LIT:2>, f)<EOL>left = max(freq_range[<NUM_LIT:0>], freq[<NUM_LIT:0>])<EOL>right = min(freq_range[<NUM_LIT:1>], freq[-<NUM_LIT:1>])<EOL>imext = (freq[<NUM_LIT:0>], freq[-<NUM_LIT:1>], -<NUM_LIT>, <NUM_LIT>)<EOL>if fig is None:<EOL... | Plot significance.
Significance is drawn as a background image where dark vertical stripes indicate freuquencies where a evaluates to
True.
Parameters
----------
a : array, shape (n_channels, n_channels, n_fft), dtype bool
Significance
fs : float
Sampling frequency
freq_ran... | f10410:m9 |
def plot_connectivity_timespectrum(a, fs=<NUM_LIT:2>, crange=None, freq_range=(-np.inf, np.inf), time_range=None, diagonal=<NUM_LIT:0>, border=False, fig=None): | a = np.asarray(a)<EOL>[_, m, _, t] = a.shape<EOL>if crange is None:<EOL><INDENT>crange = [np.min(a), np.max(a)]<EOL><DEDENT>if time_range is None:<EOL><INDENT>t0 = <NUM_LIT:0><EOL>t1 = t<EOL><DEDENT>else:<EOL><INDENT>t0, t1 = time_range<EOL><DEDENT>f0, f1 = fs / <NUM_LIT:2>, <NUM_LIT:0><EOL>extent = [t0, t1, f0, f1]<EO... | Draw time/frequency connectivity plots.
Parameters
----------
a : array, shape (n_channels, n_channels, n_fft, n_timesteps)
Values to draw
fs : float
Sampling frequency
crange : [int, int], optional
Range of values covered by the colormap.
If set to None, [min(a), ma... | f10410:m10 |
def plot_circular(widths, colors, curviness=<NUM_LIT>, mask=True, topo=None, topomaps=None, axes=None, order=None): | colors = np.asarray(colors)<EOL>widths = np.asarray(widths)<EOL>mask = np.asarray(mask)<EOL>colors = np.maximum(colors, <NUM_LIT:0>)<EOL>colors = np.minimum(colors, <NUM_LIT:1>)<EOL>if len(widths.shape) > <NUM_LIT:2>:<EOL><INDENT>[n, m] = widths.shape<EOL><DEDENT>elif len(colors.shape) > <NUM_LIT:3>:<EOL><INDENT>[n, m,... | Circluar connectivity plot.
Topos are arranged in a circle, with arrows indicating connectivity
Parameters
----------
widths : float or array, shape (n_channels, n_channels)
Width of each arrow. Can be a scalar to assign the same width to all arrows.
colors : array, shape (n_channels, n_ch... | f10410:m11 |
def plot_whiteness(var, h, repeats=<NUM_LIT:1000>, axis=None): | pr, q0, q = var.test_whiteness(h, repeats, True)<EOL>if axis is None:<EOL><INDENT>axis = current_axis()<EOL><DEDENT>pdf, _, _ = axis.hist(q0, <NUM_LIT:30>, normed=True, label='<STR_LIT>')<EOL>axis.plot([q,q], [<NUM_LIT:0>,np.max(pdf)], '<STR_LIT>', label='<STR_LIT>')<EOL>axis.set_title('<STR_LIT>'%pr)<EOL>axis.set_xlab... | Draw distribution of the Portmanteu whiteness test.
Parameters
----------
var : :class:`~scot.var.VARBase`-like object
Vector autoregressive model (VAR) object whose residuals are tested for whiteness.
h : int
Maximum lag to include in the test.
repeats : int, optional
Numbe... | f10410:m12 |
def _construct_var_eqns(data, p, delta=None): | t, m, l = np.shape(data)<EOL>n = (l - p) * t <EOL>rows = n if delta is None else n + m * p<EOL>x = np.zeros((rows, m * p))<EOL>for i in range(m):<EOL><INDENT>for k in range(<NUM_LIT:1>, p + <NUM_LIT:1>):<EOL><INDENT>x[:n, i * p + k - <NUM_LIT:1>] = np.reshape(data[:, i, p - k:-k].T, n)<EOL><DEDENT><DEDENT>if delta is ... | Construct VAR equation system (optionally with RLS constraint). | f10411:m0 |
def _calc_q_statistic(x, h, nt): | t, m, n = x.shape<EOL>c0 = acm(x, <NUM_LIT:0>)<EOL>c0f = sp.linalg.lu_factor(c0, overwrite_a=False, check_finite=True)<EOL>q = np.zeros((<NUM_LIT:3>, h + <NUM_LIT:1>))<EOL>for l in range(<NUM_LIT:1>, h + <NUM_LIT:1>):<EOL><INDENT>cl = acm(x, l)<EOL>a = sp.linalg.lu_solve(c0f, cl)<EOL>b = sp.linalg.lu_solve(c0f, cl.T)<E... | Calculate Portmanteau statistics up to a lag of h. | f10411:m2 |
def _calc_q_h0(n, x, h, nt, n_jobs=<NUM_LIT:1>, verbose=<NUM_LIT:0>, random_state=None): | rng = check_random_state(random_state)<EOL>par, func = parallel_loop(_calc_q_statistic, n_jobs, verbose)<EOL>q = par(func(rng.permutation(x.T).T, h, nt) for _ in range(n))<EOL>return np.array(q)<EOL> | Calculate q under the null hypothesis of whiteness. | f10411:m3 |
def copy(self): | other = self.__class__(self.p)<EOL>other.coef = self.coef.copy()<EOL>other.residuals = self.residuals.copy()<EOL>other.rescov = self.rescov.copy()<EOL>return other<EOL> | Create a copy of the VAR model. | f10411:c1:m1 |
def fit(self, data): | raise NotImplementedError('<STR_LIT>' +<EOL>str(self))<EOL> | Fit VAR model to data.
.. warning:: This function must be implemented by derived classes.
Parameters
----------
data : array, shape (trials, channels, samples) or (channels, samples)
Epoched or continuous data set.
Returns
-------
self : :class:`VAR... | f10411:c1:m2 |
def optimize(self, data): | raise NotImplementedError('<STR_LIT>' +<EOL>str(self))<EOL> | Optimize model fitting hyperparameters (e.g. regularization).
.. warning:: This function must be implemented by derived classes.
Parameters
----------
data : array, shape (trials, channels, samples) or (channels, samples)
Epoched or continuous data set. | f10411:c1:m3 |
def from_yw(self, acms): | if len(acms) != self.p + <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>".format(len(acms),<EOL>self.p))<EOL><DEDENT>n_channels = acms[<NUM_LIT:0>].shape[<NUM_LIT:0>]<EOL>acm = lambda l: acms[l] if l >= <NUM_LIT:0> else acms[-l].T<EOL>r = np.concatenate(acms[<NUM_LIT:1>:], <NUM_LIT:0>)<EOL>rr = np.... | Determine VAR model from autocorrelation matrices by solving the
Yule-Walker equations.
Parameters
----------
acms : array, shape (n_lags, n_channels, n_channels)
acms[l] contains the autocorrelation matrix at lag l. The highest
lag must equal the model order.
... | f10411:c1:m4 |
def simulate(self, l, noisefunc=None, random_state=None): | m, n = np.shape(self.coef)<EOL>p = n // m<EOL>try:<EOL><INDENT>l, t = l<EOL><DEDENT>except TypeError:<EOL><INDENT>t = <NUM_LIT:1><EOL><DEDENT>if noisefunc is None:<EOL><INDENT>rng = check_random_state(random_state)<EOL>noisefunc = lambda: rng.normal(size=(<NUM_LIT:1>, m))<EOL><DEDENT>n = l + <NUM_LIT:10> * p<EOL>y = np... | Simulate vector autoregressive (VAR) model.
This function generates data from the VAR model.
Parameters
----------
l : int or [int, int]
Number of samples to generate. Can be a tuple or list, where l[0]
is the number of samples and l[1] is the number of trials.
... | f10411:c1:m5 |
def predict(self, data): | data = atleast_3d(data)<EOL>t, m, l = data.shape<EOL>p = int(np.shape(self.coef)[<NUM_LIT:1>] / m)<EOL>y = np.zeros(data.shape)<EOL>if t > l - p: <EOL><INDENT>for k in range(<NUM_LIT:1>, p + <NUM_LIT:1>):<EOL><INDENT>bp = self.coef[:, (k - <NUM_LIT:1>)::p]<EOL>for n in range(p, l):<EOL><INDENT>y[:, :, n] += np.dot(dat... | Predict samples on actual data.
The result of this function is used for calculating the residuals.
Parameters
----------
data : array, shape (trials, channels, samples) or (channels, samples)
Epoched or continuous data set.
Returns
-------
predicted... | f10411:c1:m6 |
def is_stable(self): | m, mp = self.coef.shape<EOL>p = mp // m<EOL>assert(mp == m * p) <EOL>top_block = []<EOL>for i in range(p):<EOL><INDENT>top_block.append(self.coef[:, i::p])<EOL><DEDENT>top_block = np.hstack(top_block)<EOL>im = np.eye(m)<EOL>eye_block = im<EOL>for i in range(p - <NUM_LIT:2>):<EOL><INDENT>eye_block = sp.linalg.block_dia... | Test if VAR model is stable.
This function tests stability of the VAR model as described in [1]_.
Returns
-------
out : bool
True if the model is stable.
References
----------
.. [1] H. Lütkepohl, "New Introduction to Multiple Time Series
... | f10411:c1:m7 |
def _construct_eqns(self, data): | return _construct_var_eqns(data, self.p)<EOL> | Construct VAR equation system. | f10411:c1:m9 |
def set_locations(self, locations): | self.locations_ = locations<EOL>return self<EOL> | Set sensor locations.
Parameters
----------
locations : array_like
3D Electrode locations. Each row holds the x, y, and z coordinates of an electrode.
Returns
-------
self : Workspace
The Workspace object. | f10412:c0:m2 |
def set_premixing(self, premixing): | self.premixing_ = premixing<EOL>return self<EOL> | Set premixing matrix.
The premixing matrix maps data to physical channels. If the data is actual channel data,
the premixing matrix can be set to identity. Use this functionality if the data was pre-
transformed with e.g. PCA.
Parameters
----------
premixing : array_lik... | f10412:c0:m3 |
def set_data(self, data, cl=None, time_offset=<NUM_LIT:0>): | self.data_ = atleast_3d(data)<EOL>self.cl_ = np.asarray(cl if cl is not None else [None]*self.data_.shape[<NUM_LIT:0>])<EOL>self.time_offset_ = time_offset<EOL>self.var_model_ = None<EOL>self.var_cov_ = None<EOL>self.connectivity_ = None<EOL>self.trial_mask_ = np.ones(self.cl_.size, dtype=bool)<EOL>if self.unmixing_ is... | Assign data to the workspace.
This function assigns a new data set to the workspace. Doing so invalidates currently fitted VAR models,
connectivity estimates, and activations.
Parameters
----------
data : array-like, shape = [n_trials, n_channels, n_samples] or [n_channels, n_s... | f10412:c0:m4 |
def set_used_labels(self, labels): | mask = np.zeros(self.cl_.size, dtype=bool)<EOL>for l in labels:<EOL><INDENT>mask = np.logical_or(mask, self.cl_ == l)<EOL><DEDENT>self.trial_mask_ = mask<EOL>return self<EOL> | Specify which trials to use in subsequent analysis steps.
This function masks trials based on their class labels.
Parameters
----------
labels : list of class labels
Marks all trials that have a label that is in the `labels` list for further processing.
Returns
... | f10412:c0:m5 |
def do_mvarica(self, varfit='<STR_LIT>', random_state=None): | if self.data_ is None:<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>result = mvarica(x=self.data_[self.trial_mask_, :, :],<EOL>cl=self.cl_[self.trial_mask_], var=self.var_,<EOL>reducedim=self.reducedim_, backend=self.backend_,<EOL>varfit=varfit, random_state=random_state)<EOL>self.mixing_ = result.mixing<EOL... | Perform MVARICA
Perform MVARICA source decomposition and VAR model fitting.
Parameters
----------
varfit : string
Determines how to calculate the residuals for source decomposition.
'ensemble' (default) fits one model to the whole data set,
'class' f... | f10412:c0:m6 |
def do_cspvarica(self, varfit='<STR_LIT>', random_state=None): | if self.data_ is None:<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>try:<EOL><INDENT>sorted(self.cl_)<EOL>for c in self.cl_:<EOL><INDENT>assert(c is not None)<EOL><DEDENT><DEDENT>except (TypeError, AssertionError):<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>result = cspvarica(x=self.data_, var=s... | Perform CSPVARICA
Perform CSPVARICA source decomposition and VAR model fitting.
Parameters
----------
varfit : string
Determines how to calculate the residuals for source decomposition.
'ensemble' (default) fits one model to the whole data set,
'clas... | f10412:c0:m7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.