INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Attempt to acquire lock.
def tryAcquire(self, lockID, callback=None, sync=False, timeout=None): """Attempt to acquire lock. :param lockID: unique lock identifier. :type lockID: str :param sync: True - to wait until lock is acquired or failed to acquire. :type sync: bool :param callback: if sync ...
Check if lock is acquired by ourselves.
def isAcquired(self, lockID): """Check if lock is acquired by ourselves. :param lockID: unique lock identifier. :type lockID: str :return True if lock is acquired by ourselves. """ return self.__lockImpl.isAcquired(lockID, self.__selfID, time.time())
Release previously - acquired lock.
def release(self, lockID, callback=None, sync=False, timeout=None): """ Release previously-acquired lock. :param lockID: unique lock identifier. :type lockID: str :param sync: True - to wait until lock is released or failed to release. :type sync: bool :param ca...
Decorator which wraps checks and returns an error response on failure.
def check(func): """ Decorator which wraps checks and returns an error response on failure. """ def wrapped(*args, **kwargs): check_name = func.__name__ arg_name = None if args: arg_name = args[0] try: if arg_name: logger.debug("Che...
Decorator which ensures that one of the WATCHMAN_TOKENS is provided if set.
def token_required(view_func): """ Decorator which ensures that one of the WATCHMAN_TOKENS is provided if set. WATCHMAN_TOKEN_NAME can also be set if the token GET parameter must be customized. """ def _parse_auth_header(auth_header): """ Parse the `Authorization` header ...
Sets the Elasticsearch hosts to use
def set_hosts(hosts, use_ssl=False, ssl_cert_path=None): """ Sets the Elasticsearch hosts to use Args: hosts (str): A single hostname or URL, or list of hostnames or URLs use_ssl (bool): Use a HTTPS connection to the server ssl_cert_path (str): Path to the certificate chain """ ...
Create Elasticsearch indexes
def create_indexes(names, settings=None): """ Create Elasticsearch indexes Args: names (list): A list of index names settings (dict): Index settings """ for name in names: index = Index(name) try: if not index.exists(): logger.debug("Crea...
Updates index mappings
def migrate_indexes(aggregate_indexes=None, forensic_indexes=None): """ Updates index mappings Args: aggregate_indexes (list): A list of aggregate index names forensic_indexes (list): A list of forensic index names """ version = 2 if aggregate_indexes is None: aggregate_...
Saves a parsed DMARC aggregate report to ElasticSearch
def save_aggregate_report_to_elasticsearch(aggregate_report, index_suffix=None, monthly_indexes=False): """ Saves a parsed DMARC aggregate report to ElasticSearch Args: aggregate_report (OrderedDict): A parsed for...
Saves a parsed DMARC forensic report to ElasticSearch
def save_forensic_report_to_elasticsearch(forensic_report, index_suffix=None, monthly_indexes=False): """ Saves a parsed DMARC forensic report to ElasticSearch Args: forensic_report (OrderedDict): A pars...
Duplicates org_name org_email and report_id into JSON root and removes report_metadata key to bring it more inline with Elastic output.
def strip_metadata(report): """ Duplicates org_name, org_email and report_id into JSON root and removes report_metadata key to bring it more inline with Elastic output. """ report['org_name'] = report['report_metadata']['org_name'] report['org_email'] = repo...
Creates a date_range timestamp with format YYYY - MM - DD - T - HH: MM: SS based on begin and end dates for easier parsing in Kibana.
def generate_daterange(report): """ Creates a date_range timestamp with format YYYY-MM-DD-T-HH:MM:SS based on begin and end dates for easier parsing in Kibana. Move to utils to avoid duplication w/ elastic? """ metadata = report["report_metadata"] begin_date = h...
Saves aggregate DMARC reports to Kafka
def save_aggregate_reports_to_kafka(self, aggregate_reports, aggregate_topic): """ Saves aggregate DMARC reports to Kafka Args: aggregate_reports (list): A list of aggregate report dictionaries to save to Kafka aggrega...
Saves forensic DMARC reports to Kafka sends individual records ( slices ) since Kafka requires messages to be < = 1MB by default.
def save_forensic_reports_to_kafka(self, forensic_reports, forensic_topic): """ Saves forensic DMARC reports to Kafka, sends individual records (slices) since Kafka requires messages to be <= 1MB by default. Args: forensic_reports (list): A list of forensic report d...
Converts a record from a DMARC aggregate report into a more consistent format
def _parse_report_record(record, nameservers=None, dns_timeout=2.0, parallel=False): """ Converts a record from a DMARC aggregate report into a more consistent format Args: record (OrderedDict): The record to convert nameservers (list): A list of one or more nam...
Parses a DMARC XML report string and returns a consistent OrderedDict
def parse_aggregate_report_xml(xml, nameservers=None, timeout=2.0, parallel=False): """Parses a DMARC XML report string and returns a consistent OrderedDict Args: xml (str): A string of DMARC aggregate report XML nameservers (list): A list of one or more nameserve...
Extracts xml from a zip or gzip file at the given path file - like object or bytes.
def extract_xml(input_): """ Extracts xml from a zip or gzip file at the given path, file-like object, or bytes. Args: input_: A path to a file, a file like object, or bytes Returns: str: The extracted XML """ if type(input_) == str: file_object = open(input_, "rb"...
Parses a file at the given path a file - like object. or bytes as a aggregate DMARC report
def parse_aggregate_report_file(_input, nameservers=None, dns_timeout=2.0, parallel=False): """Parses a file at the given path, a file-like object. or bytes as a aggregate DMARC report Args: _input: A path to a file, a file like object, or bytes nameservers (...
Converts one or more parsed aggregate reports to flat CSV format including headers
def parsed_aggregate_reports_to_csv(reports): """ Converts one or more parsed aggregate reports to flat CSV format, including headers Args: reports: A parsed aggregate report or list of parsed aggregate reports Returns: str: Parsed aggregate report data in flat CSV format, includin...
Converts a DMARC forensic report and sample to a OrderedDict
def parse_forensic_report(feedback_report, sample, msg_date, nameservers=None, dns_timeout=2.0, strip_attachment_payloads=False, parallel=False): """ Converts a DMARC forensic report and sample to a ``OrderedDict`` Args: ...
Converts one or more parsed forensic reports to flat CSV format including headers
def parsed_forensic_reports_to_csv(reports): """ Converts one or more parsed forensic reports to flat CSV format, including headers Args: reports: A parsed forensic report or list of parsed forensic reports Returns: str: Parsed forensic report data in flat CSV format, including hea...
Parses a DMARC report from an email
def parse_report_email(input_, nameservers=None, dns_timeout=2.0, strip_attachment_payloads=False, parallel=False): """ Parses a DMARC report from an email Args: input_: An emailed DMARC report in RFC 822 format, as bytes or a string nameservers (list): A list of one ...
Parses a DMARC aggregate or forensic file at the given path a file - like object. or bytes
def parse_report_file(input_, nameservers=None, dns_timeout=2.0, strip_attachment_payloads=False, parallel=False): """Parses a DMARC aggregate or forensic file at the given path, a file-like object. or bytes Args: input_: A path to a file, a file like object, or bytes ...
Returns a list of an IMAP server s capabilities
def get_imap_capabilities(server): """ Returns a list of an IMAP server's capabilities Args: server (imapclient.IMAPClient): An instance of imapclient.IMAPClient Returns (list): A list of capabilities """ capabilities = list(map(str, list(server.capabilities()))) for i in range(le...
Fetches and parses DMARC reports from sn inbox
def get_dmarc_reports_from_inbox(host=None, user=None, password=None, connection=None, port=None, ssl=True, ssl_context=No...
Save report data in the given directory
def save_output(results, output_directory="output"): """ Save report data in the given directory Args: results (OrderedDict): Parsing results output_directory: The patch to the directory to save in """ aggregate_reports = results["aggregate_reports"] forensic_reports = results[...
Creates a zip file of parsed report output
def get_report_zip(results): """ Creates a zip file of parsed report output Args: results (OrderedDict): The parsed results Returns: bytes: zip file bytes """ def add_subdir(root_path, subdir): subdir_path = os.path.join(root_path, subdir) for subdir_root, subdi...
Emails parsing results as a zip file
def email_results(results, host, mail_from, mail_to, port=0, ssl=False, user=None, password=None, subject=None, attachment_filename=None, message=None, ssl_context=None): """ Emails parsing results as a zip file Args: results (OrderedDict): Parsing results ...
Use an IDLE IMAP connection to parse incoming emails and pass the results to a callback function
def watch_inbox(host, username, password, callback, port=None, ssl=True, ssl_context=None, reports_folder="INBOX", archive_folder="Archive", delete=False, test=False, wait=30, nameservers=None, dns_timeout=6.0, strip_attachment_payloads=False): """ ...
Saves aggregate DMARC reports to Splunk
def save_aggregate_reports_to_splunk(self, aggregate_reports): """ Saves aggregate DMARC reports to Splunk Args: aggregate_reports: A list of aggregate report dictionaries to save in Splunk """ logger.debug("Saving aggregate reports to Splunk") i...
Saves forensic DMARC reports to Splunk
def save_forensic_reports_to_splunk(self, forensic_reports): """ Saves forensic DMARC reports to Splunk Args: forensic_reports (list): A list of forensic report dictionaries to save in Splunk """ logger.debug("Saving forensic reports to Splunk") ...
Decodes a base64 string with padding being optional
def decode_base64(data): """ Decodes a base64 string, with padding being optional Args: data: A base64 encoded string Returns: bytes: The decoded bytes """ data = bytes(data, encoding="ascii") missing_padding = len(data) % 4 if missing_padding != 0: data += b'=...
Gets the base domain name for the given domain
def get_base_domain(domain, use_fresh_psl=False): """ Gets the base domain name for the given domain .. note:: Results are based on a list of public domain suffixes at https://publicsuffix.org/list/public_suffix_list.dat. Args: domain (str): A domain or subdomain use_fr...
Queries DNS
def query_dns(domain, record_type, cache=None, nameservers=None, timeout=2.0): """ Queries DNS Args: domain (str): The domain or subdomain to query about record_type (str): The record type to query for cache (ExpiringDict): Cache storage nameservers (list): A list of one or ...
Resolves an IP address to a hostname using a reverse DNS query
def get_reverse_dns(ip_address, cache=None, nameservers=None, timeout=2.0): """ Resolves an IP address to a hostname using a reverse DNS query Args: ip_address (str): The IP address to resolve cache (ExpiringDict): Cache storage nameservers (list): A list of one or more nameservers ...
Converts a human - readable timestamp into a Python DateTime object
def human_timestamp_to_datetime(human_timestamp, to_utc=False): """ Converts a human-readable timestamp into a Python ``DateTime`` object Args: human_timestamp (str): A timestamp string to_utc (bool): Convert the timestamp to UTC Returns: DateTime: The converted timestamp "...
Uses the MaxMind Geolite2 Country database to return the ISO code for the country associated with the given IPv4 or IPv6 address
def get_ip_address_country(ip_address, parallel=False): """ Uses the MaxMind Geolite2 Country database to return the ISO code for the country associated with the given IPv4 or IPv6 address Args: ip_address (str): The IP address to query for parallel (bool): Parallel processing Retu...
Returns reverse DNS and country information for the given IP address
def get_ip_address_info(ip_address, cache=None, nameservers=None, timeout=2.0, parallel=False): """ Returns reverse DNS and country information for the given IP address Args: ip_address (str): The IP address to check cache (ExpiringDict): Cache storage namese...
Converts a string to a string that is safe for a filename Args: string ( str ): A string to make safe for a filename
def get_filename_safe_string(string): """ Converts a string to a string that is safe for a filename Args: string (str): A string to make safe for a filename Returns: str: A string safe for a filename """ invalid_filename_chars = ['\\', '/', ':', '"', '*', '?', '|', '\n', ...
Uses the msgconvert Perl utility to convert an Outlook MS file to standard RFC 822 format
def convert_outlook_msg(msg_bytes): """ Uses the ``msgconvert`` Perl utility to convert an Outlook MS file to standard RFC 822 format Args: msg_bytes (bytes): the content of the .msg file Returns: A RFC 822 string """ if not is_outlook_msg(msg_bytes): raise ValueErr...
A simplified email parser
def parse_email(data, strip_attachment_payloads=False): """ A simplified email parser Args: data: The RFC 822 message string, or MSG binary strip_attachment_payloads (bool): Remove attachment payloads Returns (dict): Parsed email data """ if type(data) == bytes: if is_...
Converts a comma separated string to a list
def _str_to_list(s): """Converts a comma separated string to a list""" _list = s.split(",") return list(map(lambda i: i.lstrip(), _list))
Separated this function for multiprocessing
def cli_parse(file_path, sa, nameservers, dns_timeout, parallel=False): """Separated this function for multiprocessing""" try: file_results = parse_report_file(file_path, nameservers=nameservers, dns_timeout=dns_timeout, ...
Called when the module is executed
def _main(): """Called when the module is executed""" def process_reports(reports_): output_str = "{0}\n".format(json.dumps(reports_, ensure_ascii=False, indent=2)) if not opts.silent: print...
Drain will put a connection into a drain state. All subscriptions will immediately be put into a drain state. Upon completion the publishers will be drained and can not publish any additional messages. Upon draining of the publishers the connection will be closed. Use the closed_cb option to know when the connection ha...
def drain(self, sid=None): """ Drain will put a connection into a drain state. All subscriptions will immediately be put into a drain state. Upon completion, the publishers will be drained and can not publish any additional messages. Upon draining of the publishers, the connectio...
Sends a PUB command to the server on the specified subject.
def publish(self, subject, payload): """ Sends a PUB command to the server on the specified subject. ->> PUB hello 5 ->> MSG_PAYLOAD: world <<- MSG hello 2 5 """ if self.is_closed: raise ErrConnectionClosed if self.is_draining_pubs: ...
Publishes a message tagging it with a reply subscription which can be used by those receiving the message to respond.
def publish_request(self, subject, reply, payload): """ Publishes a message tagging it with a reply subscription which can be used by those receiving the message to respond. ->> PUB hello _INBOX.2007314fe0fcb2cdc2a2914c1 5 ->> MSG_PAYLOAD: world <<- MSG hello ...
Sends PUB command to the NATS server.
def _publish(self, subject, reply, payload, payload_size): """ Sends PUB command to the NATS server. """ if subject == "": # Avoid sending messages with empty replies. raise ErrBadSubject payload_size_bytes = ("%d" % payload_size).encode() pub_cmd...
Takes a subject string and optional queue string to send a SUB cmd and a callback which to which messages ( Msg ) will be dispatched to be processed sequentially by default.
def subscribe(self, subject, queue="", cb=None, future=None, max_msgs=0, is_async=False, pending_msgs_limit=DEFAULT_SUB_PENDING_MSGS_LIMIT, pending_bytes_limit=DEFAULT_SUB_PENDING_BYTES_LIMIT, ...
Sets the subcription to use a task per message to be processed.
def subscribe_async(self, subject, **kwargs): """ Sets the subcription to use a task per message to be processed. ..deprecated:: 7.0 Will be removed 9.0. """ kwargs["is_async"] = True sid = yield from self.subscribe(subject, **kwargs) return sid
Takes a subscription sequence id and removes the subscription from the client optionally after receiving more than max_msgs.
def unsubscribe(self, ssid, max_msgs=0): """ Takes a subscription sequence id and removes the subscription from the client, optionally after receiving more than max_msgs. """ if self.is_closed: raise ErrConnectionClosed if self.is_draining: raise E...
Implements the request/ response pattern via pub/ sub using a single wildcard subscription that handles the responses.
def request(self, subject, payload, timeout=0.5, expected=1, cb=None): """ Implements the request/response pattern via pub/sub using a single wildcard subscription that handles the responses. """ if self.is_draining_pubs: raise ErrConnectionDraining ...
Implements the request/ response pattern via pub/ sub using an ephemeral subscription which will be published with a limited interest of 1 reply returning the response or raising a Timeout error.
def timed_request(self, subject, payload, timeout=0.5): """ Implements the request/response pattern via pub/sub using an ephemeral subscription which will be published with a limited interest of 1 reply returning the response or raising a Timeout error. ->> SUB _INBOX....
Sends a ping to the server expecting a pong back ensuring what we have written so far has made it to the server and also enabling measuring of roundtrip time. In case a pong is not returned within the allowed timeout then it will raise ErrTimeout.
def flush(self, timeout=60): """ Sends a ping to the server expecting a pong back ensuring what we have written so far has made it to the server and also enabling measuring of roundtrip time. In case a pong is not returned within the allowed timeout, then it will raise Er...
Looks up in the server pool for an available server and attempts to connect.
def _select_next_server(self): """ Looks up in the server pool for an available server and attempts to connect. """ while True: if len(self._server_pool) == 0: self._current_server = None raise ErrNoServers now = time.mono...
Processes the raw error message sent by the server and close connection with current server.
def _process_err(self, err_msg): """ Processes the raw error message sent by the server and close connection with current server. """ if STALE_CONNECTION in err_msg: yield from self._process_op_err(ErrStaleConnection) return if AUTHORIZATION_VIOLA...
Process errors which occured while reading or parsing the protocol. If allow_reconnect is enabled it will try to switch the server to which it is currently connected otherwise it will disconnect.
def _process_op_err(self, e): """ Process errors which occured while reading or parsing the protocol. If allow_reconnect is enabled it will try to switch the server to which it is currently connected otherwise it will disconnect. """ if self.is_connecting or self....
Generates a JSON string with the params to be used when sending CONNECT to the server.
def _connect_command(self): ''' Generates a JSON string with the params to be used when sending CONNECT to the server. ->> CONNECT {"lang": "python3"} ''' options = { "verbose": self.options["verbose"], "pedantic": self.options["pedantic"], ...
Process PONG sent by server.
def _process_pong(self): """ Process PONG sent by server. """ if len(self._pongs) > 0: future = self._pongs.pop(0) future.set_result(True) self._pongs_received += 1 self._pings_outstanding -= 1
Process MSG sent by server.
def _process_msg(self, sid, subject, reply, data): """ Process MSG sent by server. """ payload_size = len(data) self.stats['in_msgs'] += 1 self.stats['in_bytes'] += payload_size sub = self._subs.get(sid) if sub is None: # Skip in case no subsc...
Process INFO lines sent by the server to reconfigure client with latest updates from cluster to enable server discovery.
def _process_info(self, info): """ Process INFO lines sent by the server to reconfigure client with latest updates from cluster to enable server discovery. """ if 'connect_urls' in info: if info['connect_urls']: connect_urls = [] for co...
Process INFO received from the server and CONNECT to the server with authentication. It is also responsible of setting up the reading and ping interval tasks from the client.
def _process_connect_init(self): """ Process INFO received from the server and CONNECT to the server with authentication. It is also responsible of setting up the reading and ping interval tasks from the client. """ self._status = Client.CONNECTING connection_co...
Coroutine which continuously tries to consume pending commands and then flushes them to the socket.
def _flusher(self): """ Coroutine which continuously tries to consume pending commands and then flushes them to the socket. """ while True: if not self.is_connected or self.is_connecting: break try: yield from self._flush_q...
Coroutine which gathers bytes sent by the server and feeds them to the protocol parser. In case of error while reading it will stop running and its task has to be rescheduled.
def _read_loop(self): """ Coroutine which gathers bytes sent by the server and feeds them to the protocol parser. In case of error while reading, it will stop running and its task has to be rescheduled. """ while True: try: should_bail ...
Compute and save coactivation map given input image as seed.
def coactivation(dataset, seed, threshold=0.0, output_dir='.', prefix='', r=6): """ Compute and save coactivation map given input image as seed. This is essentially just a wrapper for a meta-analysis defined by the contrast between those studies that activate within the seed and those that don't. ...
Decodes a set of images.
def decode(self, images, save=None, round=4, names=None, **kwargs): """ Decodes a set of images. Args: images: The images to decode. Can be: - A single String specifying the filename of the image to decode - A list of filenames - A single NumPy array contai...
Load features from current Dataset instance or a list of files. Args: features: List containing paths to or names of features to extract. Each element in the list must be a string containing either a path to an image or the name of a feature ( as named in the current Dataset ). Mixing of paths and feature names within ...
def load_features(self, features, image_type=None, from_array=False, threshold=0.001): """ Load features from current Dataset instance or a list of files. Args: features: List containing paths to, or names of, features to extract. Each element in the lis...
Load feature data from a 2D ndarray on disk.
def _load_features_from_array(self, features): """ Load feature data from a 2D ndarray on disk. """ self.feature_images = np.load(features) self.feature_names = range(self.feature_images.shape[1])
Load feature image data from the current Dataset instance. See load_features () for documentation.
def _load_features_from_dataset(self, features=None, image_type=None, threshold=0.001): """ Load feature image data from the current Dataset instance. See load_features() for documentation. """ self.feature_names = self.dataset.feature_table.feature_na...
Load feature image data from image files.
def _load_features_from_images(self, images, names=None): """ Load feature image data from image files. Args: images: A list of image filenames. names: An optional list of strings to use as the feature names. Must be in the same order as the images. """ i...
Decode images using Pearson s r.
def _pearson_correlation(self, imgs_to_decode): """ Decode images using Pearson's r. Computes the correlation between each input image and each feature image across voxels. Args: imgs_to_decode: An ndarray of images to decode, with voxels in rows and images ...
Decoding using the dot product.
def _dot_product(self, imgs_to_decode): """ Decoding using the dot product. """ return np.dot(imgs_to_decode.T, self.feature_images).T
Computes the strength of association between activation in a mask and presence/ absence of a semantic feature. This is essentially a generalization of the voxel - wise reverse inference z - score to the multivoxel case.
def _roi_association(self, imgs_to_decode, value='z', binarize=None): """ Computes the strength of association between activation in a mask and presence/absence of a semantic feature. This is essentially a generalization of the voxel-wise reverse inference z-score to the multivoxel case....
Implements various kinds of feature selection
def feature_selection(feat_select, X, y): """" Implements various kinds of feature selection """ # K-best if re.match('.*-best', feat_select) is not None: n = int(feat_select.split('-')[0]) selector = SelectKBest(k=n) import warnings with warnings.catch_warnings(): ...
Set up data for a classification task given a set of masks
def get_studies_by_regions(dataset, masks, threshold=0.08, remove_overlap=True, studies=None, features=None, regularization="scale"): """ Set up data for a classification task given a set of masks Given a set of masks, this function retrieves studies as...
Returns a list with the order that features requested appear in dataset
def get_feature_order(dataset, features): """ Returns a list with the order that features requested appear in dataset """ all_features = dataset.get_feature_names() i = [all_features.index(f) for f in features] return i
Perform classification on specified regions
def classify_regions(dataset, masks, method='ERF', threshold=0.08, remove_overlap=True, regularization='scale', output='summary', studies=None, features=None, class_weight='auto', classifier=None, cross_val='4-Fold', param_grid=None, sc...
Wrapper for scikit - learn classification functions Imlements various types of classification and cross validation
def classify(X, y, clf_method='ERF', classifier=None, output='summary_clf', cross_val=None, class_weight=None, regularization=None, param_grid=None, scoring='accuracy', refit_all=True, feat_select=None): """ Wrapper for scikit-learn classification functions Imlements vario...
Fits X to outcomes y using clf
def fit(self, X, y, cv=None, class_weight='auto'): """ Fits X to outcomes y, using clf """ # Incorporate error checking such as : # if isinstance(self.classifier, ScikitClassifier): # do one thingNone # otherwiseNone. self.X = X self.y = y self.set_...
Sets the class_weight of the classifier to match y
def set_class_weight(self, class_weight='auto', y=None): """ Sets the class_weight of the classifier to match y """ if class_weight is None: cw = None try: self.clf.set_params(class_weight=cw) except ValueError: pass elif cla...
Fits X to outcomes y using clf and cv_method
def cross_val_fit(self, X, y, cross_val='4-Fold', scoring='accuracy', feat_select=None, class_weight='auto'): """ Fits X to outcomes y, using clf and cv_method """ from sklearn import cross_validation self.X = X self.y = y self.set_class_weight(class_weig...
Returns cross validated scores ( just like cross_val_score ) but includes feature selection as part of the cross validation loop
def feat_select_cvs(self, scoring=None, feat_select=None): """ Returns cross validated scores (just like cross_val_score), but includes feature selection as part of the cross validation loop """ scores = [] self.predictions = [] for train, test in self.cver: X_train...
Given a dataset fits either features or voxels to y
def fit_dataset(self, dataset, y, features=None, feature_type='features'): """ Given a dataset, fits either features or voxels to y """ # Get data from dataset if feature_type == 'features': X = np.rot90(dataset.feature_table.data.toarray()) elif feature...
list: list ANDNOT list
def p_list_andnot(self, p): 'list : list ANDNOT list' p[0] = p[1].loc[set(p[1].index) - set(p[3].index)]
list: list AND list
def p_list_and(self, p): 'list : list AND list' p[0] = pd.concat( [p[1], p[3]], axis=1).dropna().apply(self.func, axis=1)
list: list OR list
def p_list_or(self, p): 'list : list OR list' p[0] = pd.concat( [p[1], p[3]], axis=1).fillna(0.0).apply(self.func, axis=1)
list: feature | WORD
def p_list_feature(self, p): '''list : feature | WORD ''' p[0] = self.dataset.get_studies( features=p[1], frequency_threshold=self.threshold, func=self.func, return_type='weights')
Aggregates over all voxels within each ROI in the input image.
def average_within_regions(dataset, regions, masker=None, threshold=None, remove_zero=True): """ Aggregates over all voxels within each ROI in the input image. Takes a Dataset and a Nifti image that defines distinct regions, and returns a numpy matrix of ROIs x mappables, where ...
Imposes a 3D grid on the brain volume and averages across all voxels that fall within each cell. Args: dataset: Data to apply grid to. Either a Dataset instance or a numpy array with voxels in rows and features in columns. masker: Optional Masker instance used to map between the created grid and the dataset. This is on...
def apply_grid(dataset, masker=None, scale=5, threshold=None): """ Imposes a 3D grid on the brain volume and averages across all voxels that fall within each cell. Args: dataset: Data to apply grid to. Either a Dataset instance, or a numpy array with voxels in rows and features in column...
Returns mappable data for a random subset of voxels.
def get_random_voxels(dataset, n_voxels): """ Returns mappable data for a random subset of voxels. May be useful as a baseline in predictive analyses--e.g., to compare performance of a more principled feature selection method with simple random selection. Args: dataset: A Dataset instance ...
Return top forty words from each topic in trained topic model.
def _get_top_words(model, feature_names, n_top_words=40): """ Return top forty words from each topic in trained topic model. """ topic_words = [] for topic in model.components_: top_words = [feature_names[i] for i in topic.argsort()[:-n_top_words-1:-1]] topic_words += [top_words] ret...
Perform topic modeling using Latent Dirichlet Allocation with the Java toolbox MALLET.
def run_lda(abstracts, n_topics=50, n_words=31, n_iters=1000, alpha=None, beta=0.001): """ Perform topic modeling using Latent Dirichlet Allocation with the Java toolbox MALLET. Args: abstracts: A pandas DataFrame with two columns ('pmid' and 'abstract') containing ...
Correlates row vector x with each row vector in 2D array y.
def pearson(x, y): """ Correlates row vector x with each row vector in 2D array y. """ data = np.vstack((x, y)) ms = data.mean(axis=1)[(slice(None, None, None), None)] datam = data - ms datass = np.sqrt(np.sum(datam**2, axis=1)) temp = np.dot(datam[1:], datam[0].T) rs = temp / (datass[1:] * ...
Two - way chi - square test of independence. Takes a 3D array as input: N ( voxels ) x 2 x 2 where the last two dimensions are the contingency table for each of N voxels. Returns an array of p - values.
def two_way(cells): """ Two-way chi-square test of independence. Takes a 3D array as input: N(voxels) x 2 x 2, where the last two dimensions are the contingency table for each of N voxels. Returns an array of p-values. """ # Mute divide-by-zero warning for bad voxels since we account for that ...
One - way chi - square test of independence. Takes a 1D array as input and compares activation at each voxel to proportion expected under a uniform distribution throughout the array. Note that if you re testing activation with this make sure that only valid voxels ( e. g. in - mask gray matter voxels ) are included in ...
def one_way(data, n): """ One-way chi-square test of independence. Takes a 1D array as input and compares activation at each voxel to proportion expected under a uniform distribution throughout the array. Note that if you're testing activation with this, make sure that only valid voxels (e.g., in-ma...
Determine FDR threshold given a p value array and desired false discovery rate q.
def fdr(p, q=.05): """ Determine FDR threshold given a p value array and desired false discovery rate q. """ s = np.sort(p) nvox = p.shape[0] null = np.array(range(1, nvox + 1), dtype='float') * q / nvox below = np.where(s <= null)[0] return s[max(below)] if len(below) else -1
Download the latest data files. Args: path ( str ): Location to save the retrieved data files. Defaults to current directory. unpack ( bool ): If True unzips the data file post - download.
def download(path='.', url=None, unpack=False): """ Download the latest data files. Args: path (str): Location to save the retrieved data files. Defaults to current directory. unpack (bool): If True, unzips the data file post-download. """ if url is None: url = 'http...
Download the abstracts for a dataset/ list of pmids
def download_abstracts(dataset, path='.', email=None, out_file=None): """ Download the abstracts for a dataset/list of pmids """ try: from Bio import Entrez, Medline except: raise Exception( 'Module biopython is required for downloading abstracts from PubMed.') if email ...
Load activation data from a text file.
def _load_activations(self, filename): """ Load activation data from a text file. Args: filename (str): a string pointing to the location of the txt file to read from. """ logger.info("Loading activation data from %s..." % filename) activations = pd....
Create and store a new ImageTable instance based on the current Dataset. Will generally be called privately but may be useful as a convenience method in cases where the user wants to re - generate the table with a new smoothing kernel of different radius.
def create_image_table(self, r=None): """ Create and store a new ImageTable instance based on the current Dataset. Will generally be called privately, but may be useful as a convenience method in cases where the user wants to re-generate the table with a new smoothing kernel of different...