INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Go back to where you once were.
def popd(): """Go back to where you once were. :return: saved directory stack """ try: directory = _saved_paths.pop(0) except IndexError: return [os.getcwd()] os.chdir(directory) return [directory] + _saved_paths
Know the best python implantation of ls? It s just to subprocess ls... ( uses dir on windows ).
def ls(params="", directory=".", printed=True): """Know the best python implantation of ls? It's just to subprocess ls... (uses dir on windows). :param params: options to pass to ls or dir :param directory: if not this directory :param printed: If you're using this, you probably wanted it just prin...
Designed for the interactive interpreter by making default order of find_files faster.
def find(name=None, ext=None, directory=".", match_case=False, disable_glob=False, depth=None): """ Designed for the interactive interpreter by making default order of find_files faster. :param name: Part of the file name :param ext: Extensions of the file you are looking for :param direct...
Read the first N lines of a file defaults to 10
def head(file_path, lines=10, encoding="utf-8", printed=True, errors='strict'): """ Read the first N lines of a file, defaults to 10 :param file_path: Path to file to read :param lines: Number of lines to read in :param encoding: defaults to utf-8 to decode as, will fail on binary :par...
A really silly way to get the last N lines defaults to 10.
def tail(file_path, lines=10, encoding="utf-8", printed=True, errors='strict'): """ A really silly way to get the last N lines, defaults to 10. :param file_path: Path to file to read :param lines: Number of lines to read in :param encoding: defaults to utf-8 to decode as, will fail on bin...
Copy files to a new location.
def cp(src, dst, overwrite=False): """ Copy files to a new location. :param src: list (or string) of paths of files to copy :param dst: file or folder to copy item(s) to :param overwrite: IF the file already exists, should I overwrite it? """ if not isinstance(src, list): src = [sr...
Split a string into a list of N characters each.
def cut(string, characters=2, trailing="normal"): """ Split a string into a list of N characters each. .. code:: python reusables.cut("abcdefghi") # ['ab', 'cd', 'ef', 'gh', 'i'] trailing gives you the following options: * normal: leaves remaining characters in their own last pos...
Convert an integer into a string of roman numbers.
def int_to_roman(integer): """ Convert an integer into a string of roman numbers. .. code: python reusables.int_to_roman(445) # 'CDXLV' :param integer: :return: roman string """ if not isinstance(integer, int): raise ValueError("Input integer must be of type int")...
Converts a string of roman numbers into an integer.
def roman_to_int(roman_string): """ Converts a string of roman numbers into an integer. .. code: python reusables.roman_to_int("XXXVI") # 36 :param roman_string: XVI or similar :return: parsed integer """ roman_string = roman_string.upper().strip() if "IIII" in roman_...
Converts an integer or float to words.
def int_to_words(number, european=False): """ Converts an integer or float to words. .. code: python reusables.int_to_number(445) # 'four hundred forty-five' reusables.int_to_number(1.45) # 'one and forty-five hundredths' :param number: String, integer, or float to co...
Downloads ( and compiles ) osmfilter tool from web and calls that osmfilter to only filter out only the road elements.
def filter_osm_file(): """ Downloads (and compiles) osmfilter tool from web and calls that osmfilter to only filter out only the road elements. """ print_info('Filtering OSM file...') start_time = time.time() if check_osmfilter(): # params = '--keep="highway=motorway =motorway...
Scans the modules set in RQ_JOBS_MODULES for RQ jobs decorated with
def task_list(): """ Scans the modules set in RQ_JOBS_MODULES for RQ jobs decorated with @task Compiles a readable list for Job model task choices """ try: jobs_module = settings.RQ_JOBS_MODULE except AttributeError: raise ImproperlyConfigured(_("You have to define RQ_JOBS_MODULE...
The last RQ Job this ran on
def rq_job(self): """The last RQ Job this ran on""" if not self.rq_id or not self.rq_origin: return try: return RQJob.fetch(self.rq_id, connection=get_connection(self.rq_origin)) except NoSuchJobError: return
Link to Django - RQ status page for this job
def rq_link(self): """Link to Django-RQ status page for this job""" if self.rq_job: url = reverse('rq_job_detail', kwargs={'job_id': self.rq_id, 'queue_index': queue_index_by_name(self.rq_origin)}) return '<a href="{}">{}</a>'.format(url, self.rq_id)
The function to call for this task. Config errors are caught by tasks_list () already.
def rq_task(self): """ The function to call for this task. Config errors are caught by tasks_list() already. """ task_path = self.task.split('.') module_name = '.'.join(task_path[:-1]) task_name = task_path[-1] module = importlib.import_module(module_name...
Fix for tasks without a module. Provides backwards compatibility with < 0. 1. 5
def fix_module(job): """ Fix for tasks without a module. Provides backwards compatibility with < 0.1.5 """ modules = settings.RQ_JOBS_MODULE if not type(modules) == tuple: modules = [modules] for module in modules: try: module_match = importlib.import_module(module) ...
Drop tables for all given models ( in the right order ).
async def drop_model_tables(models, **drop_table_kwargs): """Drop tables for all given models (in the right order).""" for m in reversed(sort_models_topologically(models)): await m.drop_table(**drop_table_kwargs)
Convert a model instance ( and any related objects ) to a dictionary.: param bool recurse: Whether foreign - keys should be recursed.: param bool backrefs: Whether lists of related objects should be recursed.: param only: A list ( or set ) of field instances indicating which fields should be included.: param exclude: A...
async def model_to_dict(model, recurse=True, backrefs=False, only=None, exclude=None, seen=None, extra_attrs=None, fields_from_query=None, max_depth=None): """ Convert a model instance (and any related objects) to a dictionary. :param bool recurse: Whether for...
Extract self. sample_size rows from the CSV file and analyze their data - types.: param str file_or_name: A string filename or a file handle.: param reader_kwargs: Arbitrary parameters to pass to the CSV reader.: returns: A 2 - tuple containing a list of headers and list of rows read from the CSV file.
async def extract_rows(self, file_or_name, **reader_kwargs): """ Extract `self.sample_size` rows from the CSV file and analyze their data-types. :param str file_or_name: A string filename or a file handle. :param reader_kwargs: Arbitrary parameters to pass to the CSV reader. ...
Return a list of functions to use when testing values.
def get_checks(self): """Return a list of functions to use when testing values.""" return [ self.is_date, self.is_datetime, self.is_integer, self.is_float, self.default]
Analyze the given rows and try to determine the type of value stored.: param list rows: A list - of - lists containing one or more rows from a csv file.: returns: A list of peewee Field objects for each column in the CSV.
def analyze(self, rows): """ Analyze the given rows and try to determine the type of value stored. :param list rows: A list-of-lists containing one or more rows from a csv file. :returns: A list of peewee Field objects for each column in the CSV. """ ...
Clean text using bleach.
def clean_text(self, text): '''Clean text using bleach.''' if text is None: return '' text = re.sub(ILLEGAL_CHARACTERS_RE, '', text) if '<' in text or '&lt' in text: text = clean(text, tags=self.tags, strip=self.strip) return unescape(text)
Constructs the path to categories images and features.
def path(self, category = None, image = None, feature = None): """ Constructs the path to categories, images and features. This path function assumes that the following storage scheme is used on the hard disk to access categories, images and features: - categories: /impath/categor...
Loads an image from disk.
def get_image(self, cat, img): """ Loads an image from disk. """ filename = self.path(cat, img) data = [] if filename.endswith('mat'): data = loadmat(filename)['output'] else: data = imread(filename) if self.size is not None: return imr...
Load a feature from disk.
def get_feature(self, cat, img, feature): """ Load a feature from disk. """ filename = self.path(cat, img, feature) data = loadmat(filename) name = [k for k in list(data.keys()) if not k.startswith('__')] if self.size is not None: return imresize(data[...
Saves a new image.
def save_image(self, cat, img, data): """Saves a new image.""" filename = self.path(cat, img) mkdir(filename) if type(data) == np.ndarray: data = Image.fromarray(data).convert('RGB') data.save(filename)
Saves a new feature.
def save_feature(self, cat, img, feature, data): """Saves a new feature.""" filename = self.path(cat, img, feature) mkdir(filename) savemat(filename, {'output':data})
This removes a common beginning from the data of the fields placing the common element in a parameter and the different endings in the fields. if parameter_name is None then it will be <field_name > _common. So far it s probably only useful for the file_name. TODO: remove field entirely if no unique elements exist.
def factorise_field(dm, field_name, boundary_char = None, parameter_name=None): """This removes a common beginning from the data of the fields, placing the common element in a parameter and the different endings in the fields. if parameter_name is None, then it will be <field_name>_common. So ...
Draws nr_samples random samples from vec.
def randsample(vec, nr_samples, with_replacement = False): """ Draws nr_samples random samples from vec. """ if not with_replacement: return np.random.permutation(vec)[0:nr_samples] else: return np.asarray(vec)[np.random.randint(0, len(vec), nr_samples)]
Calculates how much prediction. shape and image_size differ.
def calc_resize_factor(prediction, image_size): """ Calculates how much prediction.shape and image_size differ. """ resize_factor_x = prediction.shape[1] / float(image_size[1]) resize_factor_y = prediction.shape[0] / float(image_size[0]) if abs(resize_factor_x - resize_factor_y) > 1.0/image_size...
Creates a NumPy array from a dictionary with only integers as keys and NumPy arrays as values. Dimension 0 of the resulting array is formed from data. keys (). Missing values in keys can be filled up with np. nan ( default ) or ignored.
def dict_2_mat(data, fill = True): """ Creates a NumPy array from a dictionary with only integers as keys and NumPy arrays as values. Dimension 0 of the resulting array is formed from data.keys(). Missing values in keys can be filled up with np.nan (default) or ignored. Parameters ---------...
Apply a function to all values in a dictionary return a dictionary with results.
def dict_fun(data, function): """ Apply a function to all values in a dictionary, return a dictionary with results. Parameters ---------- data : dict a dictionary whose values are adequate input to the second argument of this function. function : function a function...
>>> snip_string_middle ( this is long 8 ) th... ong >>> snip_string_middle ( this is long 12 ) this is long >>> snip_string_middle ( this is long 8 ~ ) thi~long
def snip_string_middle(string, max_len=20, snip_string='...'): """ >>> snip_string_middle('this is long', 8) 'th...ong' >>> snip_string_middle('this is long', 12) 'this is long' >>> snip_string_middle('this is long', 8, '~') 'thi~long' """ #warn('use snip_string() instead', Dep...
Snips a string so that it is no longer than max_len replacing deleted characters with the snip_string. The snip is done at snip_point which is a fraction between 0 and 1 indicating relatively where along the string to snip. snip_point of 0. 5 would be the middle. >>> snip_string ( this is long 8 ) this... >>> snip_stri...
def snip_string(string, max_len=20, snip_string='...', snip_point=0.5): """ Snips a string so that it is no longer than max_len, replacing deleted characters with the snip_string. The snip is done at snip_point, which is a fraction between 0 and 1, indicating relatively where along the string to sni...
Given a list of strings finds finds the longest string that is common to the * beginning * of all strings in the list. boundary_char defines a boundary that must be preserved so that the common string removed must end with this char.
def find_common_beginning(string_list, boundary_char = None): """Given a list of strings, finds finds the longest string that is common to the *beginning* of all strings in the list. boundary_char defines a boundary that must be preserved, so that the common string removed must end with this char. ...
Given a list of strings finds the longest string that is common to the * beginning * of all strings in the list and returns a new list whose elements lack this common beginning. boundary_char defines a boundary that must be preserved so that the common string removed must end with this char. >>> cmn = something/ to/ be...
def factorise_strings (string_list, boundary_char=None): """Given a list of strings, finds the longest string that is common to the *beginning* of all strings in the list and returns a new list whose elements lack this common beginning. boundary_char defines a boundary that must be preserved, so th...
Load datamat at path.
def load(path, variable='Datamat'): """ Load datamat at path. Parameters: path : string Absolute path of the file to load from. """ f = h5py.File(path,'r') try: dm = fromhdf5(f[variable]) finally: f.close() return dm
Creates a datamat from a dictionary that contains lists/ arrays as values.
def VectorFactory(fields, parameters, categories = None): ''' Creates a datamat from a dictionary that contains lists/arrays as values. Input: fields: Dictionary The values will be used as fields of the datamat and the keys as field names. parameters: Dictionary ...
Filters a datamat by different aspects.
def filter(self, index): #@ReservedAssignment """ Filters a datamat by different aspects. This function is a device to filter the datamat by certain logical conditions. It takes as input a logical array (contains only True or False for every datapoint) and kicks out all datapoin...
Returns a copy of the datamat.
def copy(self): """ Returns a copy of the datamat. """ return self.filter(np.ones(self._num_fix).astype(bool))
Saves Datamat to path.
def save(self, path): """ Saves Datamat to path. Parameters: path : string Absolute path of the file to save to. """ f = h5py.File(path, 'w') try: fm_group = f.create_group('Datamat') for field in self.fieldnames(): ...
Set the value of a parameter.
def set_param(self, key, value): """ Set the value of a parameter. """ self.__dict__[key] = value self._parameters[key] = value
Returns an iterator that iterates over unique values of field
def by_field(self, field): """ Returns an iterator that iterates over unique values of field Parameters: field : string Filters the datamat for every unique value in field and yields the filtered datamat. Returns: datamat : Datamat...
Iterates over categories and returns a filtered datamat.
def by_cat(self): """ Iterates over categories and returns a filtered datamat. If a categories object is attached, the images object for the given category is returned as well (else None is returned). Returns: (datamat, categories) : A tuple that contains first the ...
Iterates over categories and returns a filtered datamat.
def by_filenumber(self): """ Iterates over categories and returns a filtered datamat. If a categories object is attached, the images object for the given category is returned as well (else None is returned). Returns: (datamat, categories) : A tuple that contains fir...
Add a new field to the datamat.
def add_field(self, name, data): """ Add a new field to the datamat. Parameters: name : string Name of the new field data : list Data for the new field, must be same length as all other fields. """ if name in self._fields: ...
Add a new field to the Datamat with the dtype of the like_array and the shape of the like_array except for the first dimension which will be instead the field - length of this Datamat.
def add_field_like(self, name, like_array): """ Add a new field to the Datamat with the dtype of the like_array and the shape of the like_array except for the first dimension which will be instead the field-length of this Datamat. """ new_shape = list(like_array.shape) ...
Adds a new field ( data_field ) to the Datamat with data from the corresponding field of another Datamat ( src_dm ).
def annotate (self, src_dm, data_field, key_field, take_first=True): """ Adds a new field (data_field) to the Datamat with data from the corresponding field of another Datamat (src_dm). This is accomplished through the use of a key_field, which is used to determine how the data is c...
Remove a field from the datamat.
def rm_field(self, name): """ Remove a field from the datamat. Parameters: name : string Name of the field to be removed """ if not name in self._fields: raise ValueError self._fields.remove(name) del self.__dict__[name]
Adds a parameter to the existing Datamat.
def add_parameter(self, name, value): """ Adds a parameter to the existing Datamat. Fails if parameter with same name already exists or if name is otherwise in this objects ___dict__ dictionary. """ if name in self._parameters: raise ValueError("'%s' is alrea...
Removes a parameter to the existing Datamat.
def rm_parameter(self, name): """ Removes a parameter to the existing Datamat. Fails if parameter doesn't exist. """ if name not in self._parameters: raise ValueError("no '%s' parameter found" % (name)) del self._parameters[name] del self.__dict__[na...
Promotes a parameter to a field by creating a new array of same size as the other existing fields filling it with the current value of the parameter and then removing that parameter.
def parameter_to_field(self, name): """ Promotes a parameter to a field by creating a new array of same size as the other existing fields, filling it with the current value of the parameter, and then removing that parameter. """ if name not in self._parameters: ...
Adds content of a new Datamat to this Datamat.
def join(self, fm_new, minimal_subset=True): """ Adds content of a new Datamat to this Datamat. If a parameter of the Datamats is not equal or does not exist in one, it is promoted to a field. If the two Datamats have different fields then the elements for the Datamats ...
Histograms and performs a spline fit on the given data usually angle and length differences. Parameters: ad: array The data to be histogrammed along the x - axis. May range from - 180 to 180. ld: array The data to be histogrammed along the y - axis. May range from - 36 to 36. collapse: boolean If true the histogrammed ...
def makeAngLenHist(ad, ld, fm = None, collapse=True, fit=spline_base.fit2d): """ Histograms and performs a spline fit on the given data, usually angle and length differences. Parameters: ad : array The data to be histogrammed along the x-axis. May range from -180 t...
Constructs a ( fitted ) histogram of the given data. Parameters: x_val: array The data to be histogrammed along the x - axis. y_val: array The data to be histogrammed along the y - axis. fit: function or None optional The function to use in order to fit the data. If no fit should be applied set to None bins: touple of ...
def makeHist(x_val, y_val, fit=spline_base.fit2d, bins=[np.linspace(-36.5,36.5,74),np.linspace(-180,180,361)]): """ Constructs a (fitted) histogram of the given data. Parameters: x_val : array The data to be histogrammed along the x-axis. y_val : array ...
Computes the distribution of angle and length combinations that were made as first saccades Parameters: fm: ocupy. fixmat The fixation data to be analysed
def firstSacDist(fm): """ Computes the distribution of angle and length combinations that were made as first saccades Parameters: fm : ocupy.fixmat The fixation data to be analysed """ ang, leng, ad, ld = anglendiff(fm, return_abs=True) ...
Computes the distribution of trajectory lengths i. e. the number of saccades that were made as a part of one trajectory Parameters: fm: ocupy. fixmat The fixation data to be analysed
def trajLenDist(fm): """ Computes the distribution of trajectory lengths, i.e. the number of saccades that were made as a part of one trajectory Parameters: fm : ocupy.fixmat The fixation data to be analysed """ trajLen = np.roll(fm.fix, 1...
Transforms the given number element into a range of [ - 180 180 ] which covers all possible angle differences. This method reshifts larger or smaller numbers that might be the output of other angular calculations into that range by adding or subtracting 360 respectively. To make sure that angular data ranges between - ...
def reshift(I): """ Transforms the given number element into a range of [-180, 180], which covers all possible angle differences. This method reshifts larger or smaller numbers that might be the output of other angular calculations into that range by adding or subtracting 360, respectively. To...
Prepares the data to be replicated. Calculates the second - order length and angle dependencies between saccades and stores them in a fitted histogram. Parameters: fit: function optional The method to use for fitting the histogram full_H1: twodimensional numpy. ndarray optional Where applicable the distribution of angl...
def initializeData(self, fit = None, full_H1=None, max_length = 40, in_deg = True): """ Prepares the data to be replicated. Calculates the second-order length and angle dependencies between saccades and stores them in a fitted histogram. Parameters: ...
Calculates the coordinates after a specific saccade was made. Parameters: ( x y ): tuple of floats or ints The coordinates before the saccade was made angle: float or int The angle that the next saccade encloses with the horizontal display border length: float or int The length of the next saccade
def _calc_xy(self, xxx_todo_changeme, angle, length): """ Calculates the coordinates after a specific saccade was made. Parameters: (x,y) : tuple of floats or ints The coordinates before the saccade was made angle : float or int Th...
Draws a new length - and angle - difference pair and calculates length and angle absolutes matching the last saccade drawn.
def _draw(self, prev_angle = None, prev_length = None): """ Draws a new length- and angle-difference pair and calculates length and angle absolutes matching the last saccade drawn. Parameters: prev_angle : float, optional The last angle that was drawn in the ...
Generates a given number of trajectories using the method sample (). Returns a fixmat with the generated data. Parameters: num_samples: int optional The number of trajectories that shall be generated.
def sample_many(self, num_samples = 2000): """ Generates a given number of trajectories, using the method sample(). Returns a fixmat with the generated data. Parameters: num_samples : int, optional The number of trajectories that shall be generated. ...
Draws a trajectory length first coordinates lengths angles and length - angle - difference pairs according to the empirical distribution. Each call creates one complete trajectory.
def sample(self): """ Draws a trajectory length, first coordinates, lengths, angles and length-angle-difference pairs according to the empirical distribution. Each call creates one complete trajectory. """ lenghts = [] angles = [] coordinates = [] ...
Draws a value from a cumulative sum. Parameters: cumsum: array Cumulative sum from which shall be drawn.
def drawFrom(self, cumsum, r): """ Draws a value from a cumulative sum. Parameters: cumsum : array Cumulative sum from which shall be drawn. Returns: int : Index of the cumulative sum element drawn. """ a = cumsum.rsplit(...
Load fixmat at path. Parameters: path: string Absolute path of the file to load from.
def load(path): """ Load fixmat at path. Parameters: path : string Absolute path of the file to load from. """ f = h5py.File(path,'r') if 'Fixmat' in f: fm_group = f['Fixmat'] else: fm_group = f['Datamat'] fields = {} params = {} for field, va...
Computes a fixation density map for the calling fixmat. Creates a map the size of the image fixations were recorded on. Every pixel contains the frequency of fixations for this image. The fixation map is smoothed by convolution with a Gaussian kernel to approximate the area with highest processing ( usually 2 deg. visu...
def compute_fdm(fixmat, fwhm=2, scale_factor=1): """ Computes a fixation density map for the calling fixmat. Creates a map the size of the image fixations were recorded on. Every pixel contains the frequency of fixations for this image. The fixation map is smoothed by convolution with a ...
Computes the relative bias i. e. the distribution of saccade angles and amplitudes.
def relative_bias(fm, scale_factor = 1, estimator = None): """ Computes the relative bias, i.e. the distribution of saccade angles and amplitudes. Parameters: fm : DataMat The fixation data to use scale_factor : double Returns: 2D probability distribution of s...
Concatenates all fixmats in dir and returns the resulting single fixmat. Parameters: directory: string Path from which the fixmats should be loaded categories: instance of stimuli. Categories optional If given the resulting fixmat provides direct access to the data in the categories object. glob_str: string A regular e...
def DirectoryFixmatFactory(directory, categories = None, glob_str = '*.mat', var_name = 'fixmat'): """ Concatenates all fixmats in dir and returns the resulting single fixmat. Parameters: directory : string Path from which the fixmats should be loaded categories : instan...
Loads a single fixmat ( fixmatfile ). Parameters: fixmatfile: string The matlab fixmat that should be loaded. categories: instance of stimuli. Categories optional Links data in categories to data in fixmat.
def FixmatFactory(fixmatfile, categories = None, var_name = 'fixmat', field_name='x'): """ Loads a single fixmat (fixmatfile). Parameters: fixmatfile : string The matlab fixmat that should be loaded. categories : instance of stimuli.Categories, optional Links dat...
Adds feature values of feature feature to all fixations in the calling fixmat. For fixations out of the image boundaries NaNs are returned. The function generates a new attribute field named with the string in features that contains an np. array listing feature values for every fixation in the fixmat... note:: The call...
def add_feature_values(self, features): """ Adds feature values of feature 'feature' to all fixations in the calling fixmat. For fixations out of the image boundaries, NaNs are returned. The function generates a new attribute field named with the string in featu...
Generates two M x N matrices with M feature values at fixations for N features. Controls are a random sample out of all non - fixated regions of an image or fixations of the same subject group on a randomly chosen image. Fixations are pooled over all subjects in the calling fixmat. Parameters: all_controls: bool if Tru...
def make_reg_data(self, feature_list=None, all_controls=False): """ Generates two M x N matrices with M feature values at fixations for N features. Controls are a random sample out of all non-fixated regions of an image or fixations of the same subject group on a randomly chosen ...
Compute velocity of eye - movements.
def get_velocity(samplemat, Hz, blinks=None): ''' Compute velocity of eye-movements. Samplemat must contain fields 'x' and 'y', specifying the x,y coordinates of gaze location. The function assumes that the values in x,y are sampled continously at a rate specified by 'Hz'. ''' Hz = float(Hz...
Detect saccades in a stream of gaze location samples.
def saccade_detection(samplemat, Hz=200, threshold=30, acc_thresh=2000, min_duration=21, min_movement=.35, ignore_blinks=False): ''' Detect saccades in a stream of gaze location samples. Coordinates in samplemat are assumed to be in degrees. Saccades are det...
Detect Fixation from saccades.
def fixation_detection(samplemat, saccades, Hz=200, samples2fix=None, respect_trial_borders=False, sample_times=None): ''' Detect Fixation from saccades. Fixations are defined as intervals between saccades. This function also calcuates start and end times (in ms) for each fixatio...
Parse a subscription list and return a dict containing the results.
def parse(parse_obj, agent=None, etag=None, modified=None, inject=False): """Parse a subscription list and return a dict containing the results. :param parse_obj: A file-like object or a string containing a URL, an absolute or relative filename, or an XML document. :type parse_obj: str or file ...
Constructs an categories object for all image/ category combinations in the fixmat. Parameters: fm: FixMat Used for extracting valid category/ image combination. loader: loader Loader that accesses the stimuli for this fixmat Returns: Categories object
def FixmatStimuliFactory(fm, loader): """ Constructs an categories object for all image / category combinations in the fixmat. Parameters: fm: FixMat Used for extracting valid category/image combination. loader: loader Loader that accesses the stimuli for th...
Takes an input path to the images folder of an experiment and generates automatically the category - filenumber list needed to construct an appropriate _categories object. Parameters: loader: Loader object which contains impath: string path to the input i. e. image - files of the experiment. All subfolders in that path...
def DirectoryStimuliFactory(loader): """ Takes an input path to the images folder of an experiment and generates automatically the category - filenumber list needed to construct an appropriate _categories object. Parameters : loader : Loader object which contains impath : s...
Filter the fixmat such that it only contains fixations on images in categories that are also in the categories object
def fixations(self): ''' Filter the fixmat such that it only contains fixations on images in categories that are also in the categories object''' if not self._fixations: raise RuntimeError('This Images object does not have' +' an associated fixmat') if len(lis...
Saves a new image to disk
def data(self, value): """ Saves a new image to disk """ self.loader.save_image(self.category, self.image, value)
Returns all fixations that are on this image. A precondition for this to work is that a fixmat is associated with this Image object.
def fixations(self): """ Returns all fixations that are on this image. A precondition for this to work is that a fixmat is associated with this Image object. """ if not self._fixations: raise RuntimeError('This Images object does not have' +' ...
Generator for creating the cross - validation slices.
def generate(self): """ Generator for creating the cross-validation slices. Returns A tuple of that contains two fixmats (training and test) and two Category objects (test and train). """ for _ in range(0, self.num_slices): #1. separate fixm...
Computes angle and length differences up to given order and deletes suspiciously long fixations.
def prepare_data(fm, max_back, dur_cap=700): ''' Computes angle and length differences up to given order and deletes suspiciously long fixations. Input fm: Fixmat Fixmat for which to comput angle and length differences max_back: Int Computes delta angle and ampli...
Computes the mean fixation duration at forward angles.
def saccadic_momentum_effect(durations, forward_angle, summary_stat=nanmean): """ Computes the mean fixation duration at forward angles. """ durations_per_da = np.nan * np.ones((len(e_angle) - 1,)) for i, (bo, b1) in enumerate(zip(e_angle[:-1], e_angle[1:])): idx...
Computes a measure of fixation durations at delta angle and delta length combinations.
def ior_effect(durations, angle_diffs, length_diffs, summary_stat=np.mean, parallel=True, min_samples=20): """ Computes a measure of fixation durations at delta angle and delta length combinations. """ raster = np.empty((len(e_dist) - 1, len(e_angle) - 1), dtype=object) for a, (a_...
Fits a non - linear piecewise regression to fixtaion durations for a fixmat.
def predict_fixation_duration( durations, angles, length_diffs, dataset=None, params=None): """ Fits a non-linear piecewise regression to fixtaion durations for a fixmat. Returns corrected fixation durations. """ if dataset is None: dataset = np.ones(durations.shape) corrected_d...
Calculates the saccadic momentum effect for individual subjects.
def subject_predictions(fm, field='SUBJECTINDEX', method=predict_fixation_duration, data=None): ''' Calculates the saccadic momentum effect for individual subjects. Removes any effect of amplitude differences. The parameters are fitted on unbinned data. The effects are comp...
Calculates how well the fixations from a set of subjects on a set of images can be predicted with the fixations from another set of subjects on another set of images.
def intersubject_scores(fm, category, predicting_filenumbers, predicting_subjects, predicted_filenumbers, predicted_subjects, controls = True, scale_factor = 1): """ Calculates how well the fixations from a set of subjects on a set of images can be predicted w...
Calculates how well the fixations of n random subjects on one image can be predicted with the fixations of m other random subjects.
def intersubject_scores_random_subjects(fm, category, filenumber, n_train, n_predict, controls=True, scale_factor = 1): """ Calculates how well the fixations of n random subjects on one image can be predicted with the fixations ...
compute the inter - subject consistency upper bound for a fixmat.
def upper_bound(fm, nr_subs = None, scale_factor = 1): """ compute the inter-subject consistency upper bound for a fixmat. Input: fm : a fixmat instance nr_subs : the number of subjects used for the prediction. Defaults to the total number of subjects in the fixmat minus 1...
Compute the spatial bias lower bound for a fixmat.
def lower_bound(fm, nr_subs = None, nr_imgs = None, scale_factor = 1): """ Compute the spatial bias lower bound for a fixmat. Input: fm : a fixmat instance nr_subs : the number of subjects used for the prediction. Defaults to the total number of subjects in the fixmat minu...
Calculates subscripts for indices into regularly spaced matrixes.
def ind2sub(ind, dimensions): """ Calculates subscripts for indices into regularly spaced matrixes. """ # check that the index is within range if ind >= np.prod(dimensions): raise RuntimeError("ind2sub: index exceeds array size") cum_dims = list(dimensions) cum_dims.reverse() m =...
An exemplary sub2ind implementation to create randomization scripts.
def sub2ind(indices, dimensions): """ An exemplary sub2ind implementation to create randomization scripts. This function calculates indices from subscripts into regularly spaced matrixes. """ # check that none of the indices exceeds the size of the array if any([i > j for i, j in zip(...
Restores a task store from file.
def RestoreTaskStoreFactory(store_class, chunk_size, restore_file, save_file): """ Restores a task store from file. """ intm_results = np.load(restore_file) intm = intm_results[intm_results.files[0]] idx = np.isnan(intm).flatten().nonzero()[0] partitions = math.ceil(len(idx) / float(chunk_si...
Reschedule all running tasks.
def xmlrpc_reschedule(self): """ Reschedule all running tasks. """ if not len(self.scheduled_tasks) == 0: self.reschedule = list(self.scheduled_tasks.items()) self.scheduled_tasks = {} return True
Return a new task description: ID and necessary parameters all are given in a dictionary
def xmlrpc_get_task(self): """ Return a new task description: ID and necessary parameters, all are given in a dictionary """ try: if len(self.reschedule) == 0: (task_id, cur_task) = next(self.task_iterator) else: (task_id, ...
Take the results of a computation and put it into the results list.
def xmlrpc_task_done(self, result): """ Take the results of a computation and put it into the results list. """ (task_id, task_results) = result del self.scheduled_tasks[task_id] self.task_store.update_results(task_id, task_results) self.results += 1 retur...
Return a status message
def xmlrpc_status(self): """ Return a status message """ return (""" %i Jobs are still wating for execution %i Jobs are being processed %i Jobs are done """ %(self.task_store.partitions - self.results - len(self.scheduled_...
Save results and own state into file.
def xmlrpc_save2file(self, filename): """ Save results and own state into file. """ savefile = open(filename,'wb') try: pickle.dump({'scheduled':self.scheduled_tasks, 'reschedule':self.reschedule},savefile) except pickle.PicklingError...
This function needs to be called to start the computation.
def run(self): """This function needs to be called to start the computation.""" (task_id, tasks) = self.server.get_task() self.task_store.from_dict(tasks) for (index, task) in self.task_store: result = self.compute(index, task) self.results.append(result) ...
Configures the task store to be the task_store described in description
def from_dict(self, description): """Configures the task store to be the task_store described in description""" assert(self.ident == description['ident']) self.partitions = description['partitions'] self.indices = description['indices']