code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
hlog_obj = lambda y, x, b, r, d: hlog_inv(y, b, r, d) - x find_inv = vectorize(lambda x: brentq(hlog_obj, -2 * r, 2 * r, args=(x, b, r, d))) return find_inv
def _make_hlog_numeric(b, r, d)
Return a function that numerically computes the hlog transformation for given parameter values.
4.733253
4.378752
1.080959
hlog_fun = _make_hlog_numeric(b, r, d) if not hasattr(x, '__len__'): # if transforming a single number y = hlog_fun(x) else: n = len(x) if not n: # if transforming empty container return x else: y = hlog_fun(x) return y
def hlog(x, b=500, r=_display_max, d=_l_mmax)
Base 10 hyperlog transform. Parameters ---------- x : num | num iterable values to be transformed. b : num Parameter controling the location of the shift from linear to log transformation. r : num (default = 10**4) maximal transformed value. d : num (default = log10(2**18)) log10 of maximal possible measured value. hlog_inv(r) = 10**d Returns ------- Array of transformed values.
3.788109
4.183691
0.905447
if hasattr(transform, '__call__'): tfun = transform tname = None elif hasattr(transform, 'lower'): tname = _get_canonical_name(transform) if tname is None: raise ValueError('Unknown transform: %s' % transform) else: tfun = name_transforms[tname][direction] else: raise TypeError('Unsupported transform type: %s' % type(transform)) return tfun, tname
def parse_transform(transform, direction='forward')
direction : 'forward' | 'inverse'
3.0711
3.001133
1.023313
tfun, tname = parse_transform(transform, direction) columns = to_list(columns) if columns is None: columns = frame.columns if return_all: transformed = frame.copy() for c in columns: transformed[c] = tfun(frame[c], *args, **kwargs) else: transformed = frame.filter(columns).apply(tfun, *args, **kwargs) return transformed
def transform_frame(frame, transform, columns=None, direction='forward', return_all=True, args=(), **kwargs)
Apply transform to specified columns. direction: 'forward' | 'inverse' return_all: bool True - return all columns, with specified ones transformed. False - return only specified columns. .. warning:: deprecated
2.754071
2.960612
0.930237
x = asarray(x, dtype=float) if use_spln: if self.spln is None: self.set_spline(x.min(), x.max(), **kwargs) return apply_along_axis(self.spln, 0, x) else: return self.tfun(x, *self.args, **self.kwargs)
def transform(self, x, use_spln=False, **kwargs)
Apply transform to x Parameters ---------- x : float-array-convertible Data to be transformed. Should support conversion to an array of floats. use_spln: bool True - transform using the spline specified in self.slpn. If self.spln is None, set the spline. False - transform using self.tfun kwargs: Keyword arguments to be passed to self.set_spline. Only used if use_spln=True & self.spln=None. Returns ------- Array of transformed values.
3.121245
2.758626
1.131449
base_command = 'python setup.py register' if server == 'pypitest': command = base_command + ' -r https://testpypi.python.org/pypi' else: command = base_command _execute_setup_command(command)
def pypi_register(server='pypitest')
Register and prep user for PyPi upload. .. note:: May need to weak ~/.pypirc file per issue: http://stackoverflow.com/questions/1569315
3.076929
3.929091
0.783115
if isinstance(var, (list, tuple)): new_var = map(lambda x: apply_format(x, format_str), var) if isinstance(var, tuple): new_var = '(' + ', '.join(new_var) + ')' elif isinstance(var, list): new_var = '[' + ', '.join(new_var) + ']' return '{}'.format(new_var) else: return format_str.format(var)
def apply_format(var, format_str)
Format all non-iterables inside of the iterable var using the format_str Example: >>> print apply_format([2, [1, 4], 4, 1], '{:.1f}') will return ['2.0', ['1.0', '4.0'], '4.0', '1.0']
1.93749
1.993733
0.97179
if len(target_channels) != len(set(target_channels)): raise Exception('Spawn channels must be unique') return source_channels.issubset( set(target_channels))
def _check_spawnable(source_channels, target_channels)
Check whether gate is spawnable on the target channels.
4.773906
4.27902
1.115654
if event.key is None: return key = event.key.encode('ascii', 'ignore') if key in ['1']: toolbar.create_gate_widget(kind='poly') elif key in ['2', '3', '4']: kind = {'2': 'quad', '3': 'horizontal threshold', '4': 'vertical threshold'}[key] toolbar.create_gate_widget(kind=kind) elif key in ['9']: toolbar.remove_active_gate() elif key in ['0']: toolbar.load_fcs() elif key in ['a']: toolbar.set_axes(('d1', 'd2'), pl.gca()) elif key in ['b']: toolbar.set_axes(('d2', 'd1'), pl.gca()) elif key in ['c']: toolbar.set_axes(('d1', 'd3'), pl.gca()) elif key in ['8']: print(toolbar.get_generation_code())
def key_press_handler(event, canvas, toolbar=None)
Handles keyboard shortcuts for the FCToolbar.
3.563233
3.43984
1.035872
if func is None: return func_list = to_list(func) if not hasattr(self, 'callback_list'): self.callback_list = func_list else: self.callback_list.extend(func_list)
def add_callback(self, func)
Registers a call back function
2.959669
2.89706
1.021611
source_channels = set(self.coordinates.keys()) is_spawnable = _check_spawnable(source_channels, target_channels) if not is_spawnable: return None if len(target_channels) == 1: verts = self.coordinates.get(target_channels[0], None), None else: verts = tuple([self.coordinates.get(ch, None) for ch in target_channels]) def _callback(event): if event.type == Event.CHANGE: svertex = event.info['caller'] ch = svertex.channels coordinates = svertex.coordinates new_coordinates = {k: v for k, v in zip(ch, coordinates)} self.update_coordinates(new_coordinates) elif event.type == Event.VERTEX_REMOVED: svertex = event.info['caller'] self.spawn_list.remove(svertex) else: raise ValueError('Unrecognized event {}'.format(event)) spawned_vertex = SpawnableVertex(verts, ax, _callback) spawned_vertex.channels = target_channels if self.spawn_list is None: self.spawn_list = [] self.spawn_list.append(spawned_vertex) return spawned_vertex
def spawn(self, ax, target_channels)
'd1' can be shown on ('d1', 'd2') or ('d1') 'd1', 'd2' can be shown only on ('d1', 'd2') or on ('d2', 'd1') Parameters -------------- This means that the channels on which the vertex is defined has to be a subset of the channels channels : names of channels on which to spawn the vertex Returns ------------- spawnedvertex if successful otherwise None
3.086178
3.020952
1.021591
for k, v in new_coordinates.items(): if k in self.coordinates: self.coordinates[k] = v for svertex in self.spawn_list: verts = tuple([self.coordinates.get(ch, None) for ch in svertex.channels]) if len(svertex.channels) == 1: # This means a histogram svertex.update_position(verts[0], None) else: svertex.update_position(verts[0], verts[1]) self.callback(Event(Event.BASE_GATE_CHANGED))
def update_coordinates(self, new_coordinates)
new_coordinates : dict
5.599655
5.437194
1.02988
verts = self.coordinates if not self.tracky: trans = self.ax.get_xaxis_transform(which='grid') elif not self.trackx: trans = self.ax.get_yaxis_transform(which='grid') else: trans = self.ax.transData self.artist = pl.Line2D([verts[0]], [verts[1]], transform=trans, picker=15) self.update_looks('inactive') self.ax.add_artist(self.artist)
def create_artist(self)
decides whether the artist should be visible or not in the current axis current_axis : names of x, y axis
4.633094
4.238941
1.092984
if hasattr(event, 'inaxes'): if event.inaxes != self.ax: return True else: return False
def ignore(self, event)
Ignores events.
4.045356
4.440544
0.911005
if _check_spawnable(self.source_channels, channels): sgate = self.gate_type(self.verts, ax, channels) self.spawn_list.append(sgate) return sgate else: return None
def spawn(self, channels, ax)
Spawns a graphical gate that can be used to update the coordinates of the current gate.
7.618731
6.835893
1.114519
if spawn_gate is None: for sg in list(self.spawn_list): self.spawn_list.remove(sg) sg.remove() else: spawn_gate.remove() self.spawn_list.remove(spawn_gate)
def remove_spawned_gates(self, spawn_gate=None)
Removes all spawned gates.
2.388271
2.251531
1.060732
channels, verts = self.coordinates channels = ', '.join(["'{}'".format(ch) for ch in channels]) verts = list(verts) ## Formatting the vertexes # List level (must be first), used for gates that may have multiple vertexes like a polygon if len(verts) == 1: verts = verts[0] # Tuple level (must be second), used for catching the number of dimensions # on which a vertex is defined if len(verts) == 1: verts = verts[0] # Format vertices to include less sigfigs verts = apply_format(verts, '{:.3e}') gencode.setdefault('name', self.name) gencode.setdefault('region', self.region) gencode.setdefault('gate_type', self._gencode_gate_class) gencode.setdefault('verts', verts) gencode.setdefault('channels', channels) format_string = "{name} = {gate_type}({verts}, ({channels}), region='{region}', name='{name}')" return format_string.format(**gencode)
def get_generation_code(self, **gencode)
Generates python code that can create the gate.
6.018053
5.500548
1.094082
channels, verts = self.coordinates num_channels = len(channels) gate_type_name = self.gate_type.__name__ if gate_type_name == 'ThresholdGate' and num_channels == 2: gate_type_name = 'QuadGate' return gate_type_name
def _gencode_gate_class(self)
Returns the class name that generates this gate.
4.722641
4.08863
1.155067
source_channels = [v.coordinates.keys() for v in self.verts] return set(itertools.chain(*source_channels))
def source_channels(self)
Returns a set describing the source channels on which the gate is defined.
6.8473
5.61521
1.21942
if self.state == 'active': style = {'color': 'red', 'linestyle': 'solid', 'fill': False} else: style = {'color': 'black', 'fill': False} self.poly.update(style)
def update_looks(self)
Updates the looks of the gate depending on state.
5.349315
4.325674
1.236643
if self.state == 'active': style = {'color': 'red', 'linestyle': 'solid'} else: style = {'color': 'black'} for artist in self.artist_list: artist.update(style)
def update_looks(self)
Updates the looks of the gate depending on state.
4.981852
4.58454
1.086663
info = {'options': self.get_available_channels(), 'guiEvent': event.mouseevent.guiEvent, } if hasattr(self, 'xlabel_artist') and (event.artist == self.xlabel_artist): info['axis_num'] = 0 self.callback(Event('axis_click', info)) if hasattr(self, 'ylabel_artist') and (event.artist == self.ylabel_artist): info['axis_num'] = 1 self.callback(Event('axis_click', info))
def pick_event_handler(self, event)
Handles pick events
4.208971
4.170857
1.009138
current_channels = list(self.current_channels) if len(current_channels) == 1: if axis_num == 0: new_channels = channel_name, else: new_channels = current_channels[0], channel_name else: new_channels = list(current_channels) new_channels[axis_num] = channel_name self.set_axes(new_channels, self.ax)
def change_axis(self, axis_num, channel_name)
TODO: refactor that and set_axes what to do with ax? axis_num: int axis number channel_name: str new channel to plot on that axis
2.47906
2.408874
1.029136
# To make sure displayed as hist if len(set(channels)) == 1: channels = channels[0], self.current_channels = channels # Remove existing gates for gate in self.gates: gate.remove_spawned_gates() ## # Has a clear axis command inside!! # which will "force kill" spawned gates self.plot_data() for gate in self.gates: sgate = gate.spawn(channels, ax) gate._refresh_activation()
def set_axes(self, channels, ax)
channels : iterable of string each value corresponds to a channel names names must be unique
13.881756
14.019745
0.990158
# Clear the plot before plotting onto it self.ax.cla() if self.sample is None: return if self.current_channels is None: self.current_channels = self.sample.channel_names[:2] channels = self.current_channels channels_to_plot = channels[0] if len(channels) == 1 else channels self.sample.plot(channels_to_plot, ax=self.ax) xaxis = self.ax.get_xaxis() yaxis = self.ax.get_yaxis() self.xlabel_artist = xaxis.get_label() self.ylabel_artist = yaxis.get_label() self.xlabel_artist.set_picker(5) self.ylabel_artist.set_picker(5) self.fig.canvas.draw()
def plot_data(self)
Plots the loaded data
2.739569
2.772728
0.988041
if len(self.gates) < 1: code = '' else: import_list = set([gate._gencode_gate_class for gate in self.gates]) import_list = 'from FlowCytometryTools import ' + ', '.join(import_list) code_list = [gate.get_generation_code() for gate in self.gates] code_list.sort() code_list = '\n'.join(code_list) code = import_list + 2 * '\n' + code_list self.callback(Event('generated_code', {'code': code})) return code
def get_generation_code(self)
Return python code that generates all drawn gates.
4.077944
3.558744
1.145894
doc_dict = self.doc_dict.copy() for k, v in doc_dict.items(): if '{' and '}' in v: self.doc_dict[k] = v.format(**doc_dict)
def replace(self)
Reformat values inside the self.doc_dict using self.doc_dict TODO: Make support for partial_formatting
3.792273
2.683233
1.413322
if self.allow_partial_formatting: mapping = FormatDict(self.doc_dict) else: mapping = self.doc_dict formatter = string.Formatter() return formatter.vformat(doc, (), mapping)
def _format(self, doc)
Formats the docstring using self.doc_dict
5.589526
3.839787
1.455687
import wx.lib.agw.multidirdialog as MDD app = wx.App(0) dlg = MDD.MultiDirDialog(None, title="Select directories", defaultPath=os.getcwd(), agwStyle=MDD.DD_MULTIPLE | MDD.DD_DIR_MUST_EXIST) if dlg.ShowModal() != wx.ID_OK: dlg.Destroy() return paths = dlg.GetPaths() dlg.Destroy() app.MainLoop() return paths
def select_multi_directory_dialog()
Opens a directory selection dialog Style - specifies style of dialog (read wx documentation for information)
2.329451
2.563624
0.908655
app = wx.App(None) if style == None: style = wx.DD_DIR_MUST_EXIST dialog = wx.DirDialog(None, windowTitle, defaultPath=defaultPath, style=style) if dialog.ShowModal() == wx.ID_OK: path = dialog.GetPath() else: path = None dialog.Destroy() return path
def select_directory_dialog(windowTitle, defaultPath=os.getcwd(), style=None)
Opens a directory selection dialog Style - specifies style of dialog (read wx documentation for information)
1.986897
2.054646
0.967026
if parent == None: app = wx.App(None) if style == None: style = wx.OPEN | wx.CHANGE_DIR dialog = wx.FileDialog(parent, windowTitle, defaultDir=defaultDir, wildcard=wildcard, style=style) if dialog.ShowModal() == wx.ID_OK: path = dialog.GetPath() else: path = None dialog.Destroy() return path
def open_file_dialog(windowTitle, wildcard, defaultDir=os.getcwd(), style=None, parent=None)
Opens a wx widget file select dialog. Wild card specifies which kinds of files are allowed. Style - specifies style of dialog (read wx documentation for information)
1.895699
2.045095
0.926949
app = wx.App(None) # style = wx.FD_OPEN | wx.FD_FILE_MUST_EXIST dialog = wx.FileDialog(None, 'Save file as ...', defaultDir=os.getcwd(), defaultFile="", wildcard=wildcard, style=wx.SAVE) if dialog.ShowModal() == wx.ID_OK: path = dialog.GetPath() print("You chose the following filename: %s" % path) else: path = None dialog.Destroy() return path
def save_file_dialog(wildcard)
Show a save file dialog. TODO: This is not fully implemented.
2.392028
2.58453
0.925517
class OptionFrame(wx.Frame): selectedOption = None def __init__(self, windowTitle, optionList): wx.Frame.__init__(self, None, -1, windowTitle, size=(250, 200)) panel = wx.Panel(self, -1) listBox = wx.ListBox(panel, -1, (20, 20), (80, 120), optionList, wx.LB_SINGLE) listBox.SetSelection(0) self.Bind(wx.EVT_LISTBOX_DCLICK, self.doubleclick) self.optionList = optionList def doubleclick(self, event): index = event.GetSelection() value = self.optionList[index] OptionFrame.selectedOption = (index, value) self.Close() app = wx.PySimpleApp() OptionFrame(windowTitle, optionList).Show() app.MainLoop() return OptionFrame.selectedOption
def select_option_dialog(windowTitle, optionList)
Opens a select option dialog. Select the option by double clicking. TODO: Clean up this function TODO: Improve interface (i.e., add cancel, OK)
1.98604
2.035029
0.975927
'''Extracts the version''' with open(VERSION_FILE, "rt") as f: verstrline = f.read() VERSION = r"^version = ['\"]([^'\"]*)['\"]" results = re.search(VERSION, verstrline, re.M) if results: version = results.group(1) else: raise RuntimeError("Unable to find version string in {}.".format(path)) return version
def get_package_version(path)
Extracts the version
3.096208
3.213857
0.963393
sel1 = self.x_axis_list.GetSelection() sel2 = self.y_axis_list.GetSelection() if sel1 >= 0 and sel2 >= 0: channel_1 = self.x_axis_list.GetString(sel1) channel_2 = self.y_axis_list.GetString(sel2) self.fcgatemanager.set_axes((channel_1, channel_2), self.ax)
def update_widget_channels(self)
Parameters ------------- axis : 'x' or 'y' event : pick of list text
3.318615
3.185497
1.041789
if isinstance(parser, collections.Mapping): fparse = lambda x: parser[x] elif hasattr(parser, '__call__'): fparse = lambda x: parser(x, **kwargs) elif parser == 'name': kwargs.setdefault('pre', 'Well_') kwargs.setdefault('post', ['_', '\.', '$']) kwargs.setdefault('tagtype', str) fparse = lambda x: get_tag_value(os.path.basename(x), **kwargs) elif parser == 'number': fparse = lambda x: int(x.split('.')[-2]) elif parser == 'read': fparse = lambda x: measurement_class(ID='temporary', datafile=x).ID_from_data(**kwargs) else: raise ValueError('Encountered unsupported value "%s" for parser parameter.' % parser) d = dict((fparse(dfile), dfile) for dfile in datafiles) return d
def _assign_IDS_to_datafiles(datafiles, parser, measurement_class=None, **kwargs)
Assign measurement IDS to datafiles using specified parser. Parameters ---------- datafiles : iterable of str Path to datafiles. An ID will be assigned to each. Note that this function does not check for uniqueness of IDs! {_bases_filename_parser} measurement_class: object Used to create a temporary object when reading the ID from the datafile. The measurement class needs to have an `ID_from_data` method. Only used when parser='read'. kwargs: dict Additional parameters to be passed to parser is it is a callable, or 'read'. If parser is 'read', kwargs are passed to the measurement class's `ID_from_data` method. Returns ------- Dict of ID:datafile
4.099784
3.635669
1.127656
base = len(alphabet) if x < 0: raise ValueError('Only non-negative numbers are supported. Encounterd %s' % x) letters = [] quotient = x while quotient >= 0: quotient, remainder = divmod(quotient, base) quotient -= 1 letters.append(alphabet[remainder]) letters.reverse() return ''.join(letters)
def int2letters(x, alphabet)
Return the alphabet representation of a non-negative integer x. For example, with alphabet=['a','b'] 0 -> 'a' 1 -> 'b' 2 -> 'aa' 3 -> 'ab' 4 -> 'ba' Modified from: http://stackoverflow.com/questions/2267362/convert-integer-to-a-string-in-a-given-numeric-base-in-python
2.847434
3.154139
0.902761
''' Read data into memory, applying all actions in queue. Additionally, update queue and history. ''' if data is None: data = self.get_data(**kwargs) setattr(self, '_data', data) self.history += self.queue self.queue = []
def set_data(self, data=None, **kwargs)
Read data into memory, applying all actions in queue. Additionally, update queue and history.
7.399734
2.414952
3.064133
''' Assign values to self.meta. Meta is not returned ''' if meta is None: meta = self.get_meta(**kwargs) setattr(self, '_meta', meta)
def set_meta(self, meta=None, **kwargs)
Assign values to self.meta. Meta is not returned
7.037097
3.286433
2.141257
''' return values of attribute of self. Attribute values can the ones assigned already, or the read for the corresponding file. If read from file: i) the method used to read the file is 'self.read_[attr name]' (e.g. for an attribute named 'meta' 'self.read_meta' will be used). ii) the file path will be the one specified in an attribute named: '[attr name]file'. (e.g. for an attribute named 'meta' a 'metafile' attribute will be created). ''' current_value = getattr(self, '_' + name) if current_value is not None: value = current_value else: parser_kwargs = getattr(self, 'read%s_kwargs' % name, {}) value = getattr(self, 'read_%s' % name)(**parser_kwargs) return value
def _get_attr_from_file(self, name, **kwargs)
return values of attribute of self. Attribute values can the ones assigned already, or the read for the corresponding file. If read from file: i) the method used to read the file is 'self.read_[attr name]' (e.g. for an attribute named 'meta' 'self.read_meta' will be used). ii) the file path will be the one specified in an attribute named: '[attr name]file'. (e.g. for an attribute named 'meta' a 'metafile' attribute will be created).
7.428985
1.702388
4.363861
''' Get the measurement data. If data is not set, read from 'self.datafile' using 'self.read_data'. ''' if self.queue: new = self.apply_queued() return new.get_data() else: return self._get_attr_from_file('data', **kwargs)
def get_data(self, **kwargs)
Get the measurement data. If data is not set, read from 'self.datafile' using 'self.read_data'.
9.119967
4.126863
2.209903
applyto = applyto.lower() if applyto == 'data': if self.data is not None: data = self.data elif self.datafile is None: return noneval else: data = self.read_data() if setdata: self.data = data return func(data) elif applyto == 'measurement': return func(self) else: raise ValueError('Encountered unsupported value "%s" for applyto parameter.' % applyto)
def apply(self, func, applyto='measurement', noneval=nan, setdata=False)
Apply func either to self or to associated data. If data is not already parsed, try and read it. Parameters ---------- func : callable The function either accepts a measurement object or an FCS object. Does some calculation and returns the result. applyto : ['data' | 'measurement'] * 'data' : apply to associated data * 'measurement' : apply to measurement object itself. noneval : obj Value to return if `applyto` is 'data', but no data is available. setdata : bool Used only if data is not already set. If true parsed data will be assigned to self.data Otherwise data will be discarded at end of apply.
2.510619
2.614829
0.960147
d = _assign_IDS_to_datafiles(datafiles, parser, cls._measurement_class, **ID_kwargs) measurements = [] for sID, dfile in d.items(): try: measurements.append(cls._measurement_class(sID, datafile=dfile, readdata_kwargs=readdata_kwargs, readmeta_kwargs=readmeta_kwargs)) except: msg = 'Error occurred while trying to parse file: %s' % dfile raise IOError(msg) return cls(ID, measurements)
def from_files(cls, ID, datafiles, parser, readdata_kwargs={}, readmeta_kwargs={}, **ID_kwargs)
Create a Collection of measurements from a set of data files. Parameters ---------- {_bases_ID} {_bases_data_files} {_bases_filename_parser} {_bases_ID_kwargs}
3.612235
3.782561
0.954971
datafiles = get_files(datadir, pattern, recursive) return cls.from_files(ID, datafiles, parser, readdata_kwargs=readdata_kwargs, readmeta_kwargs=readmeta_kwargs, **ID_kwargs)
def from_dir(cls, ID, datadir, parser, pattern='*.fcs', recursive=False, readdata_kwargs={}, readmeta_kwargs={}, **ID_kwargs)
Create a Collection of measurements from data files contained in a directory. Parameters ---------- ID : hashable Collection ID datadir : str Path of directory containing the data files. pattern : str Only files matching the pattern will be used to create measurements. recursive : bool Recursively look for files matching pattern in subdirectories. {_bases_filename_parser} {_bases_ID_kwargs}
2.095903
2.613159
0.802057
''' Apply func to each of the specified measurements. Parameters ---------- func : callable Accepts a Measurement object or a DataFrame. ids : hashable| iterable of hashables | None Keys of measurements to which func will be applied. If None is given apply to all measurements. applyto : 'measurement' | 'data' * 'measurement' : apply to measurements objects themselves. * 'data' : apply to measurement associated data noneval : obj Value returned if applyto is 'data' but no data is available. setdata : bool Whether to set the data in the Measurement object. Used only if data is not already set. output_format : ['dict' | 'collection'] * collection : keeps result as collection WARNING: For collection, func should return a copy of the measurement instance rather than the original measurement instance. Returns ------- Dictionary keyed by measurement keys containing the corresponding output of func or returns a collection (if output_format='collection'). ''' if ids is None: ids = self.keys() else: ids = to_list(ids) result = dict((i, self[i].apply(func, applyto, noneval, setdata)) for i in ids) if output_format == 'collection': can_keep_as_collection = all( [isinstance(r, self._measurement_class) for r in result.values()]) if not can_keep_as_collection: raise TypeError( 'Cannot turn output into a collection. The provided func must return results of type {}'.format( self._measurement_class)) new_collection = self.copy() # Locate IDs to remove ids_to_remove = [x for x in self.keys() if x not in ids] # Remove data for these IDs for ids in ids_to_remove: new_collection.pop(ids) # Update keys with new values for k, v in new_collection.items(): new_collection[k] = result[k] if ID is not None: new_collection.ID = ID return new_collection else: # Return a dictionary return result
def apply(self, func, ids=None, applyto='measurement', noneval=nan, setdata=False, output_format='dict', ID=None, **kwargs)
Apply func to each of the specified measurements. Parameters ---------- func : callable Accepts a Measurement object or a DataFrame. ids : hashable| iterable of hashables | None Keys of measurements to which func will be applied. If None is given apply to all measurements. applyto : 'measurement' | 'data' * 'measurement' : apply to measurements objects themselves. * 'data' : apply to measurement associated data noneval : obj Value returned if applyto is 'data' but no data is available. setdata : bool Whether to set the data in the Measurement object. Used only if data is not already set. output_format : ['dict' | 'collection'] * collection : keeps result as collection WARNING: For collection, func should return a copy of the measurement instance rather than the original measurement instance. Returns ------- Dictionary keyed by measurement keys containing the corresponding output of func or returns a collection (if output_format='collection').
4.075404
1.851415
2.201237
fun = lambda x: x.set_data() self.apply(fun, ids=ids, applyto='measurement')
def set_data(self, ids=None)
Set the data for all specified measurements (all if None given).
10.55038
6.719936
1.570012
fields = to_list(fields) func = lambda x: x.get_meta_fields(fields) meta_d = self.apply(func, ids=ids, applyto='measurement', noneval=noneval, output_format='dict') if output_format is 'dict': return meta_d elif output_format is 'DataFrame': from pandas import DataFrame as DF meta_df = DF(meta_d, index=fields) return meta_df else: msg = ("The output_format must be either 'dict' or 'DataFrame'. " + "Encountered unsupported value %s." % repr(output_format)) raise Exception(msg)
def get_measurement_metadata(self, fields, ids=None, noneval=nan, output_format='DataFrame')
Get the metadata fields of specified measurements (all if None given). Parameters ---------- fields : str | iterable of str Names of metadata fields to be returned. ids : hashable| iterable of hashables | None Keys of measurements for which metadata will be returned. If None is given return metadata of all measurements. noneval : obj Value returned if applyto is 'data' but no data is available. output_format : 'DataFrame' | 'dict' 'DataFrame' : return DataFrame, 'dict' : return dictionary. Returns ------- Measurement metadata in specified output_format.
3.067699
3.387861
0.905497
fil = criteria new = self.copy() if isinstance(applyto, collections.Mapping): remove = (k for k, v in self.items() if not fil(applyto[k])) elif applyto == 'measurement': remove = (k for k, v in self.items() if not fil(v)) elif applyto == 'keys': remove = (k for k, v in self.items() if not fil(k)) elif applyto == 'data': remove = (k for k, v in self.items() if not fil(v.get_data())) else: raise ValueError('Unsupported value "%s" for applyto parameter.' % applyto) for r in remove: del new[r] if ID is None: ID = self.ID new.ID = ID return new
def filter(self, criteria, applyto='measurement', ID=None)
Filter measurements according to given criteria. Retain only Measurements for which criteria returns True. TODO: add support for multiple criteria Parameters ---------- criteria : callable Returns bool. applyto : 'measurement' | 'keys' | 'data' | mapping 'measurement' : criteria is applied to Measurement objects 'keys' : criteria is applied to the keys. 'data' : criteria is applied to the Measurement objects' data. mapping : for each key criteria is applied to mapping value with same key. ID : str ID of the filtered collection. If None is given, append '.filterd' to the current sample ID. Returns ------- Filtered Collection.
2.439126
2.331975
1.045949
keys = to_list(keys) fil = lambda x: x in keys if ID is None: ID = self.ID return self.filter(fil, applyto='keys', ID=ID)
def filter_by_key(self, keys, ID=None)
Keep only Measurements with given keys.
5.267912
5.014714
1.050491
fil = lambda x: x in ids return self.filter_by_attr('ID', fil, ID)
def filter_by_IDs(self, ids, ID=None)
Keep only Measurements with given IDs.
7.124024
6.860025
1.038484
rows = to_list(rows) fil = lambda x: x in rows applyto = {k: self._positions[k][0] for k in self.keys()} if ID is None: ID = self.ID return self.filter(fil, applyto=applyto, ID=ID)
def filter_by_rows(self, rows, ID=None)
Keep only Measurements in corresponding rows.
5.380557
5.016832
1.072501
rows = to_list(cols) fil = lambda x: x in rows applyto = {k: self._positions[k][1] for k in self.keys()} if ID is None: ID = self.ID + '.filtered_by_cols' return self.filter(fil, applyto=applyto, ID=ID)
def filter_by_cols(self, cols, ID=None)
Keep only Measurements in corresponding columns.
6.053407
5.7925
1.045042
if position_mapper is None: if isinstance(parser, six.string_types): position_mapper = parser else: msg = "When using a custom parser, you must specify the position_mapper keyword." raise ValueError(msg) d = _assign_IDS_to_datafiles(datafiles, parser, cls._measurement_class, **ID_kwargs) measurements = [] for sID, dfile in d.items(): try: measurements.append(cls._measurement_class(sID, datafile=dfile, readdata_kwargs=readdata_kwargs, readmeta_kwargs=readmeta_kwargs)) except: msg = 'Error occured while trying to parse file: %s' % dfile raise IOError(msg) return cls(ID, measurements, position_mapper, **kwargs)
def from_files(cls, ID, datafiles, parser='name', position_mapper=None, readdata_kwargs={}, readmeta_kwargs={}, ID_kwargs={}, **kwargs)
Create an OrderedCollection of measurements from a set of data files. Parameters ---------- {_bases_ID} {_bases_data_files} {_bases_filename_parser} {_bases_position_mapper} {_bases_ID_kwargs} kwargs : dict Additional key word arguments to be passed to constructor.
3.185144
3.440845
0.925687
datafiles = get_files(path, pattern, recursive) return cls.from_files(ID, datafiles, parser=parser, position_mapper=position_mapper, readdata_kwargs=readdata_kwargs, readmeta_kwargs=readmeta_kwargs, ID_kwargs=ID_kwargs, **kwargs)
def from_dir(cls, ID, path, parser='name', position_mapper=None, pattern='*.fcs', recursive=False, readdata_kwargs={}, readmeta_kwargs={}, ID_kwargs={}, **kwargs)
Create a Collection of measurements from data files contained in a directory. Parameters ---------- {_bases_ID} datadir : str Path of directory containing the data files. pattern : str Only files matching the pattern will be used to create measurements. recursive : bool Recursively look for files matching pattern in subdirectories. {_bases_filename_parser} {_bases_position_mapper} {_bases_ID_kwargs} kwargs : dict Additional key word arguments to be passed to constructor.
1.759903
2.296795
0.766243
''' Set the row/col labels. Note that this method doesn't check that enough labels were set for all the assigned positions. ''' if axis.lower() in ('rows', 'row', 'r', 0): assigned_pos = set(v[0] for v in self._positions.itervalues()) not_assigned = set(labels) - assigned_pos if len(not_assigned) > 0: msg = 'New labels must contain all assigned positions' raise ValueError(msg) self.row_labels = labels elif axis.lower() in ('cols', 'col', 'c', 1): self.col_labels = labels else: raise TypeError('Unsupported axis value %s' % axis)
def set_labels(self, labels, axis='rows')
Set the row/col labels. Note that this method doesn't check that enough labels were set for all the assigned positions.
3.805183
2.694678
1.41211
''' check if given position is valid for this collection ''' row, col = position valid_r = row in self.row_labels valid_c = col in self.col_labels return valid_r and valid_c
def _is_valid_position(self, position)
check if given position is valid for this collection
4.859385
3.474446
1.398607
''' Defines a position parser that is used to map between sample IDs and positions. Parameters -------------- {_bases_position_mapper} TODO: Fix the name to work with more than 26 letters of the alphabet. ''' def num_parser(x, order): i, j = unravel_index(int(x - 1), self.shape, order=order) return (self.row_labels[i], self.col_labels[j]) if hasattr(position_mapper, '__call__'): mapper = position_mapper elif isinstance(position_mapper, collections.Mapping): mapper = lambda x: position_mapper[x] elif position_mapper == 'name': mapper = lambda x: (x[0], int(x[1:])) elif position_mapper in ('row_first_enumerator', 'number'): mapper = lambda x: num_parser(x, 'F') elif position_mapper == 'col_first_enumerator': mapper = lambda x: num_parser(x, 'C') else: msg = '"{}" is not a known key_to_position_parser.'.format(position_mapper) raise ValueError(msg) return mapper
def _get_ID2position_mapper(self, position_mapper)
Defines a position parser that is used to map between sample IDs and positions. Parameters -------------- {_bases_position_mapper} TODO: Fix the name to work with more than 26 letters of the alphabet.
4.275948
2.621689
1.63099
''' checks for position validity & collisions, but not that all measurements are assigned. Parameters ----------- positions : is dict-like of measurement_key:(row,col) parser : callable - gets key and returns position mapping - key:pos 'name' - parses things like 'A1', 'G12' 'number' - converts number to positions, going over rows first. ids : parser will be applied to specified ids only. If None is given, parser will be applied to all measurements. TODO: output a more informative message for position collisions ''' if positions is None: if ids is None: ids = self.keys() else: ids = to_list(ids) mapper = self._get_ID2position_mapper(position_mapper) positions = dict((ID, mapper(ID)) for ID in ids) else: pass # check that resulting assignment is unique (one measurement per position) temp = self._positions.copy() temp.update(positions) if not len(temp.values()) == len(set(temp.values())): msg = 'A position can only be occupied by a single measurement' raise Exception(msg) for k, pos in positions.items(): if not self._is_valid_position(pos): msg = 'Position {} is not supported for this collection'.format(pos) raise ValueError(msg) self._positions[k] = pos self[k]._set_position(self.ID, pos)
def set_positions(self, positions=None, position_mapper='name', ids=None)
checks for position validity & collisions, but not that all measurements are assigned. Parameters ----------- positions : is dict-like of measurement_key:(row,col) parser : callable - gets key and returns position mapping - key:pos 'name' - parses things like 'A1', 'G12' 'number' - converts number to positions, going over rows first. ids : parser will be applied to specified ids only. If None is given, parser will be applied to all measurements. TODO: output a more informative message for position collisions
6.934192
2.384765
2.907704
''' Get a dictionary of measurement positions. ''' if copy: return self._positions.copy() else: return self._positions
def get_positions(self, copy=True)
Get a dictionary of measurement positions.
5.261229
3.030413
1.736142
''' Remove rows and cols that have no assigned measurements. Return new instance. ''' new = self.copy() tmp = self._dict2DF(self, nan, True) new.row_labels = list(tmp.index) new.col_labels = list(tmp.columns) return new
def dropna(self)
Remove rows and cols that have no assigned measurements. Return new instance.
8.799775
4.639197
1.896831
_output = 'collection' if output_format == 'collection' else 'dict' result = super(OrderedCollection, self).apply(func, ids, applyto, noneval, setdata, output_format=_output) # Note: result should be of type dict or collection for the code # below to work if output_format is 'dict': return result elif output_format is 'DataFrame': return self._dict2DF(result, noneval, dropna) elif output_format is 'collection': return result else: msg = ("output_format must be either 'dict' or 'DataFrame'. " + "Encountered unsupported value %s." % repr(output_format)) raise Exception(msg)
def apply(self, func, ids=None, applyto='measurement', output_format='DataFrame', noneval=nan, setdata=False, dropna=False, ID=None)
Apply func to each of the specified measurements. Parameters ---------- func : callable Accepts a Measurement object or a DataFrame. ids : hashable| iterable of hashables | None Keys of measurements to which func will be applied. If None is given apply to all measurements. applyto : 'measurement' | 'data' 'measurement' : apply to measurements objects themselves. 'data' : apply to measurement associated data output_format: ['DataFrame' | 'dict' | 'collection'] noneval : obj Value returned if applyto is 'data' but no data is available. setdata : bool Whether to set the data in the Measurement object. Used only if data is not already set. dropna : bool whether to remove rows/cols that contain no measurements. ID : [None | str | numeric] ID is used as the new ID for the collection. If None, then the old ID is retained. Note: Only applicable when output is a collection. Returns ------- DataFrame/Dictionary/Collection containing the output of func for each Measurement.
3.798953
4.353149
0.872691
# Acquire call arguments to be passed to create plate layout callArgs = locals().copy() # This statement must remain first. The copy is just defensive. [callArgs.pop(varname) for varname in ['self', 'func', 'applyto', 'ids', 'colorbar', 'xlim', 'ylim']] # pop args callArgs['rowNum'] = self.shape[0] callArgs['colNum'] = self.shape[1] subplots_adjust_args = {} subplots_adjust_args.setdefault('right', 0.85) subplots_adjust_args.setdefault('top', 0.85) pl.subplots_adjust(**subplots_adjust_args) # Uses plate default row/col labels if user does not override them by specifying row/col # labels if row_labels == None: callArgs['row_labels'] = self.row_labels if col_labels == None: callArgs['col_labels'] = self.col_labels ax_main, ax_subplots = graph.create_grid_layout(**callArgs) subplots_ax = DF(ax_subplots, index=self.row_labels, columns=self.col_labels) if ids is None: ids = self.keys() ids = to_list(ids) for ID in ids: measurement = self[ID] if not hasattr(measurement, 'data'): continue row, col = self._positions[ID] ax = subplots_ax[col][row] pl.sca(ax) # sets the current axis if applyto == 'measurement': func(measurement, ax) # reminder: pandas row/col order is reversed elif applyto == 'data': data = measurement.get_data() if data is not None: if func.func_code.co_argcount == 1: func(data) else: func(data, ax) else: raise ValueError('Encountered unsupported value {} for applyto parameter.'.format( applyto)) # Autoscaling axes graph.scale_subplots(ax_subplots, xlim=xlim, ylim=ylim) ##### # Placing ticks on the top left subplot ax_label = ax_subplots[0, -1] pl.sca(ax_label) if xlabel: xlim = ax_label.get_xlim() pl.xticks([xlim[0], xlim[1]], rotation=90) if ylabel: ylim = ax_label.get_ylim() pl.yticks([ylim[0], ylim[1]], rotation=0) pl.sca(ax_main) # sets to the main axis -- more intuitive return ax_main, ax_subplots
def grid_plot(self, func, applyto='measurement', ids=None, row_labels=None, col_labels=None, xlim='auto', ylim='auto', xlabel=None, ylabel=None, colorbar=True, row_label_xoffset=None, col_label_yoffset=None, hide_tick_labels=True, hide_tick_lines=True, hspace=0, wspace=0, row_labels_kwargs={}, col_labels_kwargs={})
Creates subplots for each well in the plate. Uses func to plot on each axis. Follow with a call to matplotlibs show() in order to see the plot. Parameters ---------- func : callable func is a callable that accepts a measurement object (with an optional axis reference) and plots on the current axis. Return values from func are ignored. .. note: if using applyto='measurement', the function when querying for data should make sure that the data actually exists applyto : 'measurement' | 'data' {_graph_grid_layout} {bases_OrderedCollection_grid_plot_pars} Returns ------- {_graph_grid_layout_returns} Examples --------- >>> def y(well, ax): >>> data = well.get_data() >>> if data is None: >>> return None >>> graph.plotFCM(data, 'Y2-A') >>> def z(data, ax): >>> plot(data[0:100, 1], data[0:100, 2]) >>> plate.plot(y, applyto='measurement'); >>> plate.plot(z, applyto='data');
3.722671
3.758831
0.99038
if self.vert[1] <= self.vert[0]: raise ValueError(u'{} must be larger than {}'.format(self.vert[1], self.vert[0]))
def validate_input(self)
Raise appropriate exception if gate was defined incorrectly.
5.715558
4.980902
1.147495
idx = ((dataframe[self.channels[0]] <= self.vert[1]) & (dataframe[self.channels[0]] >= self.vert[0])) if self.region == 'out': idx = ~idx return idx
def _identify(self, dataframe)
Return bool series which is True for indexes that 'pass' the gate
5.881871
5.206315
1.129757
if ax == None: ax = pl.gca() if ax_channels is not None: flip = self._find_orientation(ax_channels) plot_func = ax.axes.axhline if flip else ax.axes.axvline kwargs.setdefault('color', 'black') a1 = plot_func(self.vert[0], *args, **kwargs) a2 = plot_func(self.vert[1], *args, **kwargs) return (a1, a2)
def plot(self, flip=False, ax_channels=None, ax=None, *args, **kwargs)
{_gate_plot_doc}
3.253978
3.148211
1.033596
## # TODO Fix this implementation. (i.e., why not support just 'left') # At the moment this implementation won't work at all. # The logic here can be simplified. id1 = dataframe[self.channels[0]] >= self.vert[0] id2 = dataframe[self.channels[1]] >= self.vert[1] if 'left' in self.region: id1 = ~id1 if 'bottom' in self.region: id2 = ~id2 idx = id1 & id2 if 'out' in self.region: idx = ~idx return idx
def _identify(self, dataframe)
Returns a list of indexes containing only the points that pass the filter. Parameters ---------- dataframe : DataFrame
6.255476
6.30535
0.99209
if ax == None: ax = pl.gca() kwargs.setdefault('color', 'black') if ax_channels is not None: flip = self._find_orientation(ax_channels) if not flip: a1 = ax.axes.axvline(self.vert[0], *args, **kwargs) a2 = ax.axes.axhline(self.vert[1], *args, **kwargs) else: a1 = ax.axes.axvline(self.vert[1], *args, **kwargs) a2 = ax.axes.axhline(self.vert[0], *args, **kwargs) return (a1, a2)
def plot(self, flip=False, ax_channels=None, ax=None, *args, **kwargs)
{_gate_plot_doc}
2.317559
2.255374
1.027572
path = Path(self.vert) idx = path.contains_points(dataframe.filter(self.channels)) if self.region == 'out': idx = ~idx return idx
def _identify(self, dataframe)
Returns a list of indexes containing only the points that pass the filter. Parameters ---------- dataframe : DataFrame
15.839612
17.525509
0.903803
if ax == None: ax = pl.gca() if ax_channels is not None: flip = self._find_orientation(ax_channels) if flip: vert = [v[::-1] for v in self.vert] else: vert = self.vert kwargs.setdefault('fill', False) kwargs.setdefault('color', 'black') poly = pl.Polygon(vert, *args, **kwargs) return ax.add_artist(poly)
def plot(self, flip=False, ax_channels=None, ax=None, *args, **kwargs)
{_gate_plot_doc}
3.264069
3.204223
1.018677
for gate in self.gates: gate.plot(flip=flip, ax_channels=ax_channels, ax=ax, *args, **kwargs)
def plot(self, flip=False, ax_channels=None, ax=None, *args, **kwargs)
{_gate_plot_doc}
2.568868
1.813345
1.416646
import os base_path = os.path.dirname(os.path.abspath(__file__)) test_data_dir = os.path.join(base_path, 'tests', 'data', 'Plate01') test_data_file = os.path.join(test_data_dir, 'RFP_Well_A3.fcs') return test_data_dir, test_data_file
def _get_paths()
Generate paths to test data. Done in a function to protect namespace a bit.
3.250595
2.866093
1.134155
'push a copy of older release to appropriate version directory' local_dir = doc_root + 'build/html' remote_dir = '/usr/share/nginx/pandas/pandas-docs/version/%s/' % ver cmd = 'cd %s; rsync -avz . [email protected]:%s -essh' cmd = cmd % (local_dir, remote_dir) print cmd if os.system(cmd): raise SystemExit( 'Upload to %s from %s failed' % (remote_dir, local_dir)) local_dir = doc_root + 'build/latex' pdf_cmd = 'cd %s; scp pandas.pdf [email protected]:%s' pdf_cmd = pdf_cmd % (local_dir, remote_dir) if os.system(pdf_cmd): raise SystemExit('Upload PDF to %s from %s failed' % (ver, doc_root))
def upload_prev(ver, doc_root='./')
push a copy of older release to appropriate version directory
4.336771
3.616409
1.199193
if ax == None: ax = pl.gca() xlabel_kwargs.setdefault('size', 16) ylabel_kwargs.setdefault('size', 16) channel_names = to_list(channel_names) if len(channel_names) == 1: # 1D so histogram plot kwargs.setdefault('color', 'gray') kwargs.setdefault('histtype', 'stepfilled') kwargs.setdefault('bins', 200) # Do not move above x = data[channel_names[0]].values if len(x) >= 1: if (len(x) == 1) and isinstance(kwargs['bins'], int): # Only needed for hist (not hist2d) due to hist function doing # excessive input checking warnings.warn("One of the data sets only has a single event. " "This event won't be plotted unless the bin locations" " are explicitly provided to the plotting function. ") return None plot_output = ax.hist(x, **kwargs) else: return None elif len(channel_names) == 2: x = data[channel_names[0]].values # value of first channel y = data[channel_names[1]].values # value of second channel if len(x) == 0: # Don't draw a plot if there's no data return None if kind == 'scatter': kwargs.setdefault('edgecolor', 'none') plot_output = ax.scatter(x, y, **kwargs) elif kind == 'histogram': kwargs.setdefault('bins', 200) # Do not move above kwargs.setdefault('cmin', 1) kwargs.setdefault('cmap', pl.cm.copper) kwargs.setdefault('norm', matplotlib.colors.LogNorm()) plot_output = ax.hist2d(x, y, **kwargs) mappable = plot_output[-1] if colorbar: pl.colorbar(mappable, ax=ax) else: raise ValueError("Not a valid plot type. Must be 'scatter', 'histogram'") else: raise ValueError('Received an unexpected number of channels: "{}"'.format(channel_names)) pl.grid(grid) if autolabel: y_label_text = 'Counts' if len(channel_names) == 1 else channel_names[1] ax.set_xlabel(channel_names[0], **xlabel_kwargs) ax.set_ylabel(y_label_text, **ylabel_kwargs) return plot_output
def plotFCM(data, channel_names, kind='histogram', ax=None, autolabel=True, xlabel_kwargs={}, ylabel_kwargs={}, colorbar=False, grid=False, **kwargs)
Plots the sample on the current axis. Follow with a call to matplotlibs show() in order to see the plot. Parameters ---------- data : DataFrame {graph_plotFCM_pars} {common_plot_ax} Returns ------- The output of the plot command used
2.9274
3.010388
0.972433
axis_options = ('x', 'y', 'both', 'none', '', 'xy', 'yx') if axis.lower() not in axis_options: raise ValueError('axis must be in {0}'.format(axis_options)) if subplots is None: subplots = plt.gcf().axes data_limits = [(ax.xaxis.get_data_interval(), ax.yaxis.get_data_interval()) for loc, ax in numpy.ndenumerate(subplots)] # TODO: Make a proper iterator xlims, ylims = zip(*data_limits) xmins_list, xmaxs_list = zip(*xlims) ymins_list, ymaxs_list = zip(*ylims) xmin = numpy.min(xmins_list) xmax = numpy.max(xmaxs_list) ymin = numpy.min(ymins_list) ymax = numpy.max(ymaxs_list) for loc, ax in numpy.ndenumerate(subplots): if axis in ('x', 'both', 'xy', 'yx'): ax.set_xlim((xmin, xmax)) if axis in ('y', 'both', 'xy', 'yx'): ax.set_ylim((ymin, ymax))
def autoscale_subplots(subplots=None, axis='both')
Sets the x and y axis limits for each subplot to match the x and y axis limits of the most extreme data points encountered. The limits are set to the same values for all subplots. Parameters ----------- subplots : ndarray or list of matplotlib.axes.Axes axis : ['x' | 'y' | 'both' / 'xy' / 'yx' | 'none' / ''] 'x' : autoscales the x axis 'y' : autoscales the y axis 'both', 'xy', 'yx' : autoscales both axis 'none', '' : autoscales nothing
2.123954
2.105535
1.008748
auto_axis = '' if xlim == 'auto': auto_axis += 'x' if ylim == 'auto': auto_axis += 'y' autoscale_subplots(subplots, auto_axis) for loc, ax in numpy.ndenumerate(subplots): if 'x' not in auto_axis: ax.set_xlim(xlim) if 'y' not in auto_axis: ax.set_ylim(ylim)
def scale_subplots(subplots=None, xlim='auto', ylim='auto')
Set the x and y axis limits for a collection of subplots. Parameters ----------- subplots : ndarray or list of matplotlib.axes.Axes xlim : None | 'auto' | (xmin, xmax) 'auto' : sets the limits according to the most extreme values of data encountered. ylim : None | 'auto' | (ymin, ymax)
2.529016
3.315163
0.762863
shape = matrix.shape xtick_pos = numpy.arange(shape[1]) ytick_pos = numpy.arange(shape[0]) xtick_grid, ytick_grid = numpy.meshgrid(xtick_pos, ytick_pos) vmax = numpy.nanmax(matrix) vmin = numpy.nanmin(matrix) if not kwargs.get('color', None) and cmap is not None: use_cmap = True norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax, clip=False) else: use_cmap = False for (row, col), w in numpy.ndenumerate(matrix): x = xtick_grid[row, col] y = ytick_grid[row, col] if use_cmap: kwargs['color'] = cmap(norm(w)) plt.text(x, y, text_format.format(w), horizontalalignment='center', verticalalignment='center', transform=plt.gca().transData, **kwargs)
def _plot_table(matrix, text_format='{:.2f}', cmap=None, **kwargs)
Plot a numpy matrix as a table. Uses the current axis bounding box to decide on limits. text_format specifies the formatting to apply to the values. Parameters ---------- matrix : ndarray text_format : str Indicates how to format the the values text_format = {:.2} -> keeps all digits until the first 2 significant digits past the decimal text_format = {:.2f} -> keeps only 2 digits past the decimal cmap : None | colormap if a colormap is provided, this colormap will be used to choose the color of the text. **kwargs : all other arguments passed to plt.text function Examples ---------- plot_table(numpy.random.random((3,3)) plt.show()
2.016956
2.072611
0.973147
for i, thisAxis in enumerate((ax.get_xaxis(), ax.get_yaxis())): for thisItem in thisAxis.get_ticklines(): if isinstance(visible, list): thisItem.set_visible(visible[i]) else: thisItem.set_visible(visible)
def _set_tick_lines_visibility(ax, visible=True)
Set the visibility of the tick lines of the requested axis.
2.711022
2.597692
1.043627
for i, thisAxis in enumerate((ax.get_xaxis(), ax.get_yaxis())): for thisItem in thisAxis.get_ticklabels(): if isinstance(visible, list): thisItem.set_visible(visible[i]) else: thisItem.set_visible(visible)
def _set_tick_labels_visibility(ax, visible=True)
Set the visibility of the tick labels of the requested axis.
2.724815
2.581227
1.055628
xlabel = None xvalues = None ylabel = None yvalues = None if hasattr(data, 'minor_axis'): xvalues = data.minor_axis if hasattr(data.minor_axis, 'name'): xlabel = data.minor_axis.name if hasattr(data, 'columns'): xvalues = data.columns if hasattr(data.columns, 'name'): xlabel = data.columns.name if hasattr(data, 'major_axis'): yvalues = data.major_axis if hasattr(data.major_axis, 'name'): ylabel = data.major_axis.name if hasattr(data, 'index'): yvalues = data.index if hasattr(data.index, 'name'): ylabel = data.index.name return xlabel, xvalues, ylabel, yvalues
def extract_annotation(data)
Extract names and values of rows and columns. Parameter: data : DataFrame | Panel Returns: col_name, col_values, row_name, row_values
1.635898
1.665247
0.982376
# Copy the original sample new_sample = original_sample.copy() new_data = new_sample.data # Our transformation goes here new_data['Y2-A'] = log(new_data['Y2-A']) new_data = new_data.dropna() # Removes all NaN entries new_sample.data = new_data return new_sample
def transform_using_this_method(original_sample)
This function implements a log transformation on the data.
4.248016
4.133938
1.027596
''' Read the datafile specified in Sample.datafile and return the resulting object. Does NOT assign the data to self.data It's advised not to use this method, but instead to access the data through the FCMeasurement.data attribute. ''' meta, data = parse_fcs(self.datafile, **kwargs) return data
def read_data(self, **kwargs)
Read the datafile specified in Sample.datafile and return the resulting object. Does NOT assign the data to self.data It's advised not to use this method, but instead to access the data through the FCMeasurement.data attribute.
11.561003
2.189482
5.280245
''' Read only the annotation of the FCS file (without reading DATA segment). It's advised not to use this method, but instead to access the meta data through the FCMeasurement.meta attribute. ''' # TODO Try to rewrite the code to be more logical # The reason the equivalent statement is not in the read_data method # above is because self.readdata_kwargs are passed # as **kwargs to the read_data function. if 'channel_naming' in self.readdata_kwargs: kwargs['channel_naming'] = self.readdata_kwargs['channel_naming'] meta = parse_fcs(self.datafile, reformat_meta=True, meta_data_only=True, **kwargs) return meta
def read_meta(self, **kwargs)
Read only the annotation of the FCS file (without reading DATA segment). It's advised not to use this method, but instead to access the meta data through the FCMeasurement.meta attribute.
8.847241
4.270153
2.071879
''' Return a dictionary of metadata fields ''' fields = to_list(fields) meta = self.get_meta() return {field: meta.get(field) for field in fields}
def get_meta_fields(self, fields, kwargs={})
Return a dictionary of metadata fields
4.544494
3.571791
1.272329
''' Returns the well ID from the src keyword in the FCS file. (e.g., A2) This keyword may not appear in FCS files generated by other machines, in which case this function will raise an exception. ''' try: return self.get_meta_fields(ID_field)[ID_field] except KeyError: msg = "The keyword '{}' does not exist in the following FCS file: {}" msg = msg.format(ID_field, self.datafile) raise Exception(msg)
def ID_from_data(self, ID_field='$SRC')
Returns the well ID from the src keyword in the FCS file. (e.g., A2) This keyword may not appear in FCS files generated by other machines, in which case this function will raise an exception.
5.594303
2.210817
2.530423
ax = kwargs.get('ax') channel_names = to_list(channel_names) gates = to_list(gates) plot_output = graph.plotFCM(self.data, channel_names, kind=kind, **kwargs) if gates is not None: if gate_colors is None: gate_colors = cycle(('b', 'g', 'r', 'm', 'c', 'y')) if not isinstance(gate_lw, collections.Iterable): gate_lw = [gate_lw] gate_lw = cycle(gate_lw) for (g, c, lw) in zip(gates, gate_colors, gate_lw): g.plot(ax=ax, ax_channels=channel_names, color=c, lw=lw) return plot_output
def plot(self, channel_names, kind='histogram', gates=None, gate_colors=None, gate_lw=1, **kwargs)
Plot the flow cytometry data associated with the sample on the current axis. To produce the plot, follow up with a call to matplotlib's show() function. Parameters ---------- {graph_plotFCM_pars} {FCMeasurement_plot_pars} {common_plot_ax} gates : [None, Gate, list of Gate] Gate must be of type {_gate_available_classes}. gate_lw: float | iterable line width to use when drawing gates if float, uses the same line width for all gates if iterable, then cycles between the values kwargs : dict Additional keyword arguments to be passed to graph.plotFCM Returns ------- None : if no data is present plot_output : output of plot command used to draw (e.g., output of hist) Examples -------- >>> sample.plot('Y2-A', bins=100, alpha=0.7, color='green', normed=1) # 1d histogram >>> sample.plot(['B1-A', 'Y2-A'], cmap=cm.Oranges, colorbar=False) # 2d histogram
2.782012
2.876436
0.967173
if channel_names == 'auto': channel_names = list(self.channel_names) def plot_region(channels, **kwargs): if channels[0] == channels[1]: channels = channels[0] kind = 'histogram' self.plot(channels, kind=kind, gates=gates, gate_colors=gate_colors, autolabel=False) channel_list = np.array(list(channel_names), dtype=object) channel_mat = [[(x, y) for x in channel_list] for y in channel_list] channel_mat = DataFrame(channel_mat, columns=channel_list, index=channel_list) kwargs.setdefault('wspace', 0.1) kwargs.setdefault('hspace', 0.1) return plot_ndpanel(channel_mat, plot_region, **kwargs)
def view(self, channel_names='auto', gates=None, diag_kw={}, offdiag_kw={}, gate_colors=None, **kwargs)
Generates a matrix of subplots allowing for a quick way to examine how the sample looks in different channels. Parameters ---------- channel_names : [list | 'auto'] List of channel names to plot. offdiag_plot : ['histogram' | 'scatter'] Specifies the type of plot for the off-diagonal elements. diag_kw : dict Not implemented Returns ------------ axes references
3.319517
3.473454
0.955682
'''Loads the current sample in a graphical interface for drawing gates. Parameters ---------- backend: 'auto' | 'wx' | 'webagg' Specifies which backend should be used to view the sample. ''' if backend == 'auto': if matplotlib.__version__ >= '1.4.3': backend = 'WebAgg' else: backend = 'wx' if backend == 'wx': from FlowCytometryTools.gui.wx_backend import gui elif backend == 'webagg': from FlowCytometryTools.gui.webagg_backend import gui else: raise ValueError('No support for backend {}'.format(backend)) gui.GUILauncher(measurement=self)
def view_interactively(self, backend='wx')
Loads the current sample in a graphical interface for drawing gates. Parameters ---------- backend: 'auto' | 'wx' | 'webagg' Specifies which backend should be used to view the sample.
4.312677
2.610774
1.651877
# Create new measurement new = self.copy() data = new.data channels = to_list(channels) if channels is None: channels = data.columns ## create transformer if isinstance(transform, Transformation): transformer = transform else: if auto_range: # determine transformation range if 'd' in kwargs: warnings.warn( 'Encountered both auto_range=True and user-specified range value in ' 'parameter d.\n Range value specified in parameter d is used.') else: channel_meta = self.channels # the -1 below because the channel numbers begin from 1 instead of 0 # (this is fragile code) ranges = [float(r['$PnR']) for i, r in channel_meta.iterrows() if self.channel_names[i - 1] in channels] if not np.allclose(ranges, ranges[0]): raise Exception() if transform in {'hlog', 'tlog', 'hlog_inv', 'tlog_inv'}: # Hacky fix to make sure that 'd' is provided only # for hlog / tlog transformations kwargs['d'] = np.log10(ranges[0]) transformer = Transformation(transform, direction, args, **kwargs) ## create new data transformed = transformer(data[channels], use_spln) if return_all: new_data = data else: new_data = data.filter(channels) new_data[channels] = transformed ## update new Measurement new.data = new_data if ID is not None: new.ID = ID if get_transformer: return new, transformer else: return new
def transform(self, transform, direction='forward', channels=None, return_all=True, auto_range=True, use_spln=True, get_transformer=False, ID=None, apply_now=True, args=(), **kwargs)
Applies a transformation to the specified channels. The transformation parameters are shared between all transformed channels. If different parameters need to be applied to different channels, use several calls to `transform`. Parameters ---------- {FCMeasurement_transform_pars} ID : hashable | None ID for the resulting collection. If None is passed, the original ID is used. Returns ------- new : FCMeasurement New measurement containing the transformed data. transformer : Transformation The Transformation applied to the input measurement. Only returned if get_transformer=True. Examples -------- {FCMeasurement_transform_examples}
4.999109
5.182323
0.964646
data = self.get_data() num_events = data.shape[0] if isinstance(key, float): if (key > 1.0) or (key < 0.0): raise ValueError('If float, key must be between 0.0 and 1.0') key = int(num_events * key) elif isinstance(key, tuple): all_float = all([isinstance(x, float) for x in key]) if (len(key) > 2) or (not all_float): raise ValueError('Tuple must consist of two floats, each between 0.0 and 1.0') start = int(num_events * key[0]) stop = int(num_events * key[1]) key = slice(start, stop) # Convert to a slice try: if isinstance(key, slice): if auto_resize: stop = key.stop if key.stop < num_events else num_events start = key.start if key.start < num_events else num_events key = slice(start, stop, key.step) # Generate new slice newdata = data.iloc[key] elif isinstance(key, int): if auto_resize: if key > num_events: key = num_events if key < 1: # EDGE CAES: Must return an empty sample order = 'start' if order == 'random': newdata = data.loc[sample(list(data.index), key)] # Use loc not iloc here!! elif order == 'start': newdata = data.iloc[:key] elif order == 'end': newdata = data.iloc[-key:] else: raise ValueError("order must be in ('random', 'start', 'end')") else: raise TypeError("'key' must be of type int, float, tuple or slice.") except IndexError: print("If you're encountering an out-of-bounds error, " "try to setting 'auto_resize' to True.") raise newsample = self.copy() newsample.set_data(data=newdata) return newsample
def subsample(self, key, order='random', auto_resize=False)
Allows arbitrary slicing (subsampling) of the data. Parameters ---------- {FCMeasurement_subsample_parameters} Returns ------- FCMeasurement Sample with subsampled data.
2.81609
2.834348
0.993558
''' Apply given gate and return new gated sample (with assigned data). Parameters ---------- gate : {_gate_available_classes} Returns ------- FCMeasurement Sample with data that passes gates ''' data = self.get_data() newdata = gate(data) newsample = self.copy() newsample.data = newdata return newsample
def gate(self, gate, apply_now=True)
Apply given gate and return new gated sample (with assigned data). Parameters ---------- gate : {_gate_available_classes} Returns ------- FCMeasurement Sample with data that passes gates
10.914154
2.2524
4.845567
''' Apply transform to each Measurement in the Collection. Return a new Collection with transformed data. {_containers_held_in_memory_warning} Parameters ---------- {FCMeasurement_transform_pars} ID : hashable | None ID for the resulting collection. If None is passed, the original ID is used. Returns ------- new : FCCollection New collection containing the transformed measurements. transformer : Transformation The Transformation applied to the measurements. Only returned if get_transformer=True & share_transform=True. Examples -------- {FCMeasurement_transform_examples} ''' new = self.copy() if share_transform: channel_meta = list(self.values())[0].channels channel_names = list(self.values())[0].channel_names if channels is None: channels = list(channel_names) else: channels = to_list(channels) ## create transformer if isinstance(transform, Transformation): transformer = transform else: if auto_range: # determine transformation range if 'd' in kwargs: warnings.warn('Encountered both auto_range=True and user-specified range ' 'value in parameter d.\n ' 'Range value specified in parameter d is used.') else: # the -1 below because the channel numbers begin from 1 instead of 0 (this is fragile code) ranges = [float(r['$PnR']) for i, r in channel_meta.iterrows() if channel_names[i - 1] in channels] if not np.allclose(ranges, ranges[0]): raise Exception('Not all specified channels have the same ' 'data range, therefore they cannot be ' 'transformed together.') if transform in {'hlog', 'tlog', 'hlog_inv', 'tlog_inv'}: # Hacky fix to make sure that 'd' is provided only # for hlog / tlog transformations kwargs['d'] = np.log10(ranges[0]) transformer = Transformation(transform, direction, args, **kwargs) if use_spln: xmax = self.apply(lambda x: x[channels].max().max(), applyto='data').max().max() xmin = self.apply(lambda x: x[channels].min().min(), applyto='data').min().min() transformer.set_spline(xmin, xmax) ## transform all measurements for k, v in new.items(): new[k] = v.transform(transformer, channels=channels, return_all=return_all, use_spln=use_spln, apply_now=apply_now) else: for k, v in new.items(): new[k] = v.transform(transform, direction=direction, channels=channels, return_all=return_all, auto_range=auto_range, get_transformer=False, use_spln=use_spln, apply_now=apply_now, args=args, **kwargs) if ID is not None: new.ID = ID if share_transform and get_transformer: return new, transformer else: return new
def transform(self, transform, direction='forward', share_transform=True, channels=None, return_all=True, auto_range=True, use_spln=True, get_transformer=False, ID=None, apply_now=True, args=(), **kwargs)
Apply transform to each Measurement in the Collection. Return a new Collection with transformed data. {_containers_held_in_memory_warning} Parameters ---------- {FCMeasurement_transform_pars} ID : hashable | None ID for the resulting collection. If None is passed, the original ID is used. Returns ------- new : FCCollection New collection containing the transformed measurements. transformer : Transformation The Transformation applied to the measurements. Only returned if get_transformer=True & share_transform=True. Examples -------- {FCMeasurement_transform_examples}
4.098352
2.815966
1.455398
''' Applies the gate to each Measurement in the Collection, returning a new Collection with gated data. {_containers_held_in_memory_warning} Parameters ---------- gate : {_gate_available_classes} ID : [ str, numeric, None] New ID to be given to the output. If None, the ID of the current collection will be used. ''' def func(well): return well.gate(gate, apply_now=apply_now) return self.apply(func, output_format='collection', ID=ID)
def gate(self, gate, ID=None, apply_now=True)
Applies the gate to each Measurement in the Collection, returning a new Collection with gated data. {_containers_held_in_memory_warning} Parameters ---------- gate : {_gate_available_classes} ID : [ str, numeric, None] New ID to be given to the output. If None, the ID of the current collection will be used.
10.280985
2.156825
4.766723
def func(well): return well.subsample(key=key, order=order, auto_resize=auto_resize) return self.apply(func, output_format='collection', ID=ID)
def subsample(self, key, order='random', auto_resize=False, ID=None)
Allows arbitrary slicing (subsampling) of the data. .. note:: When using order='random', the sampling is random for each of the measurements in the collection. Parameters ---------- {FCMeasurement_subsample_parameters} Returns ------- FCCollection or a subclass new collection of subsampled event data.
5.099173
5.771478
0.883513
return self.apply(lambda x: x.counts, ids=ids, setdata=setdata, output_format=output_format)
def counts(self, ids=None, setdata=False, output_format='DataFrame')
Return the counts in each of the specified measurements. Parameters ---------- ids : [hashable | iterable of hashables | None] Keys of measurements to get counts of. If None is given get counts of all measurements. setdata : bool Whether to set the data in the Measurement object. Used only if data is not already set. output_format : DataFrame | dict Specifies the output format for that data. Returns ------- [DataFrame | Dictionary] Dictionary keys correspond to measurement keys.
2.962925
4.061555
0.729505
## # Note # ------- # The function assumes that grid_plot and FCMeasurement.plot use unique key words. # Any key word arguments that appear in both functions are passed only to grid_plot in the end. ## # Automatically figure out which of the kwargs should # be sent to grid_plot instead of two sample.plot # (May not be a robust solution, we'll see as the code evolves grid_arg_list = inspect.getargspec(OrderedCollection.grid_plot).args grid_plot_kwargs = {'ids': ids, 'row_labels': row_labels, 'col_labels': col_labels} for key, value in list(kwargs.items()): if key in grid_arg_list: kwargs.pop(key) grid_plot_kwargs[key] = value ## # Make sure channel names is a list to make the code simpler below channel_names = to_list(channel_names) ## # Determine data limits for binning # if kind == 'histogram': nbins = kwargs.get('bins', 200) if isinstance(nbins, int): min_list = [] max_list = [] for sample in self: min_list.append(self[sample].data[channel_names].min().values) max_list.append(self[sample].data[channel_names].max().values) min_list = list(zip(*min_list)) max_list = list(zip(*max_list)) bins = [] for i, c in enumerate(channel_names): min_v = min(min_list[i]) max_v = max(max_list[i]) bins.append(np.linspace(min_v, max_v, nbins)) # Check if 1d if len(channel_names) == 1: bins = bins[0] # bins should be an ndarray, not a list of ndarrays kwargs['bins'] = bins ########## # Defining the plotting function that will be used. # At the moment grid_plot handles the labeling # (rather than sample.plot or the base function # in GoreUtilities.graph def plot_sample(sample, ax): return sample.plot(channel_names, ax=ax, gates=gates, gate_colors=gate_colors, colorbar=False, kind=kind, autolabel=False, **kwargs) xlabel, ylabel = None, None if autolabel: cnames = to_list(channel_names) xlabel = cnames[0] if len(cnames) == 2: ylabel = cnames[1] return self.grid_plot(plot_sample, xlim=xlim, ylim=ylim, xlabel=xlabel, ylabel=ylabel, **grid_plot_kwargs)
def plot(self, channel_names, kind='histogram', gates=None, gate_colors=None, ids=None, row_labels=None, col_labels=None, xlim='auto', ylim='auto', autolabel=True, **kwargs)
Produces a grid plot with each subplot corresponding to the data at the given position. Parameters --------------- {FCMeasurement_plot_pars} {graph_plotFCM_pars} {_graph_grid_layout} Returns ------- {_graph_grid_layout_returns} Examples -------- Below, plate is an instance of FCOrderedCollection >>> plate.plot(['SSC-A', 'FSC-A'], kind='histogram', autolabel=True) >>> plate.plot(['SSC-A', 'FSC-A'], xlim=(0, 10000)) >>> plate.plot(['B1-A', 'Y2-A'], kind='scatter', color='red', s=1, alpha=0.3) >>> plate.plot(['B1-A', 'Y2-A'], bins=100, alpha=0.3) >>> plate.plot(['B1-A', 'Y2-A'], bins=[linspace(-1000, 10000, 100), linspace(-1000, 10000, 100)], alpha=0.3) .. note:: For more details see documentation for FCMeasurement.plot **kwargs passes arguments to both grid_plot and to FCMeasurement.plot.
3.990231
3.777588
1.056291
if isinstance(obj, unicode_type): return obj elif isinstance(obj, bytes_type): try: return unicode_type(obj, 'utf-8') except UnicodeDecodeError as strerror: sys.stderr.write("UnicodeDecodeError exception for string '%s': %s\n" % (obj, strerror)) return unicode_type(obj, 'utf-8', 'replace') else: return unicode_type(obj)
def obj2unicode(obj)
Return a unicode representation of a python object
2.340443
2.36466
0.989759
if isinstance(iterable, bytes_type) or isinstance(iterable, unicode_type): return sum([uchar_width(c) for c in obj2unicode(iterable)]) else: return iterable.__len__()
def len(iterable)
Redefining len here so it will be able to work with non-ASCII characters
6.746334
6.025426
1.119644
if len(array) != 4: raise ArraySizeError("array should contain 4 characters") array = [ x[:1] for x in [ str(s) for s in array ] ] (self._char_horiz, self._char_vert, self._char_corner, self._char_header) = array return self
def set_chars(self, array)
Set the characters used to draw lines between rows and columns - the array should contain 4 fields: [horizontal, vertical, corner, header] - default is set to: ['-', '|', '+', '=']
5.680732
4.263618
1.332374
self._check_row_size(array) self._header_align = array return self
def set_header_align(self, array)
Set the desired header alignment - the elements of the array should be either "l", "c" or "r": * "l": column flushed left * "c": column centered * "r": column flushed right
7.841752
8.062165
0.972661
self._check_row_size(array) self._align = array return self
def set_cols_align(self, array)
Set the desired columns alignment - the elements of the array should be either "l", "c" or "r": * "l": column flushed left * "c": column centered * "r": column flushed right
10.290493
11.546805
0.891198