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 = lo...
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[tnam...
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 =...
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 i...
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_va...
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=ki...
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: ...
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 ...
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 ...
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]]...
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: ...
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)) ...
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_chann...
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 insid...
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...
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] ...
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 path...
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(...
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...
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...
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...
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), se...
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.setdefaul...
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 U...
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...
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...
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' w...
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: ...
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...
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, ...
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 us...
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. I...
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 appl...
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 'D...
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 retur...
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': ...
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 ...
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_...
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 ...
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. ...
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(la...
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): ...
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 ...
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' -...
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) # N...
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 appl...
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 ca...
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...
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 refer...
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) ...
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] ...
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.v...
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.setdef...
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 . pandas@pandas.pydata.org:%s -essh' cmd = cmd % (local_dir, remote_dir) print cmd if os.system(cm...
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', 'stepfill...
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()) fo...
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...
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: ...
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, y...
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 = ...
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 dig...
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(d...
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_...
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 ...
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] ...
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',...
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, li...
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, ...
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...
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....
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 e...
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_transf...
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): ...
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() ...
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 col...
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 ...
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 ...
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...
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 ------- F...
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 da...
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 shoul...
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 ...
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)) r...
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