repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
noxdafox/clipspy
clips/agenda.py
Rule.watch_activations
def watch_activations(self, flag): """Whether or not the Rule Activations are being watched.""" lib.EnvSetDefruleWatchActivations(self._env, int(flag), self._rule)
python
def watch_activations(self, flag): """Whether or not the Rule Activations are being watched.""" lib.EnvSetDefruleWatchActivations(self._env, int(flag), self._rule)
[ "def", "watch_activations", "(", "self", ",", "flag", ")", ":", "lib", ".", "EnvSetDefruleWatchActivations", "(", "self", ".", "_env", ",", "int", "(", "flag", ")", ",", "self", ".", "_rule", ")" ]
Whether or not the Rule Activations are being watched.
[ "Whether", "or", "not", "the", "Rule", "Activations", "are", "being", "watched", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/agenda.py#L265-L267
train
35,300
noxdafox/clipspy
clips/agenda.py
Rule.matches
def matches(self, verbosity=Verbosity.TERSE): """Shows partial matches and activations. Returns a tuple containing the combined sum of the matches for each pattern, the combined sum of partial matches and the number of activations. The verbosity parameter controls how much to output: * Verbosity.VERBOSE: detailed matches are printed to stdout * Verbosity.SUCCINT: a brief description is printed to stdout * Verbosity.TERSE: (default) nothing is printed to stdout """ data = clips.data.DataObject(self._env) lib.EnvMatches(self._env, self._rule, verbosity, data.byref) return tuple(data.value)
python
def matches(self, verbosity=Verbosity.TERSE): """Shows partial matches and activations. Returns a tuple containing the combined sum of the matches for each pattern, the combined sum of partial matches and the number of activations. The verbosity parameter controls how much to output: * Verbosity.VERBOSE: detailed matches are printed to stdout * Verbosity.SUCCINT: a brief description is printed to stdout * Verbosity.TERSE: (default) nothing is printed to stdout """ data = clips.data.DataObject(self._env) lib.EnvMatches(self._env, self._rule, verbosity, data.byref) return tuple(data.value)
[ "def", "matches", "(", "self", ",", "verbosity", "=", "Verbosity", ".", "TERSE", ")", ":", "data", "=", "clips", ".", "data", ".", "DataObject", "(", "self", ".", "_env", ")", "lib", ".", "EnvMatches", "(", "self", ".", "_env", ",", "self", ".", "_...
Shows partial matches and activations. Returns a tuple containing the combined sum of the matches for each pattern, the combined sum of partial matches and the number of activations. The verbosity parameter controls how much to output: * Verbosity.VERBOSE: detailed matches are printed to stdout * Verbosity.SUCCINT: a brief description is printed to stdout * Verbosity.TERSE: (default) nothing is printed to stdout
[ "Shows", "partial", "matches", "and", "activations", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/agenda.py#L269-L287
train
35,301
noxdafox/clipspy
clips/agenda.py
Rule.refresh
def refresh(self): """Refresh the Rule. The Python equivalent of the CLIPS refresh command. """ if lib.EnvRefresh(self._env, self._rule) != 1: raise CLIPSError(self._env)
python
def refresh(self): """Refresh the Rule. The Python equivalent of the CLIPS refresh command. """ if lib.EnvRefresh(self._env, self._rule) != 1: raise CLIPSError(self._env)
[ "def", "refresh", "(", "self", ")", ":", "if", "lib", ".", "EnvRefresh", "(", "self", ".", "_env", ",", "self", ".", "_rule", ")", "!=", "1", ":", "raise", "CLIPSError", "(", "self", ".", "_env", ")" ]
Refresh the Rule. The Python equivalent of the CLIPS refresh command.
[ "Refresh", "the", "Rule", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/agenda.py#L289-L296
train
35,302
noxdafox/clipspy
clips/agenda.py
Rule.undefine
def undefine(self): """Undefine the Rule. Python equivalent of the CLIPS undefrule command. The object becomes unusable after this method has been called. """ if lib.EnvUndefrule(self._env, self._rule) != 1: raise CLIPSError(self._env) self._env = None
python
def undefine(self): """Undefine the Rule. Python equivalent of the CLIPS undefrule command. The object becomes unusable after this method has been called. """ if lib.EnvUndefrule(self._env, self._rule) != 1: raise CLIPSError(self._env) self._env = None
[ "def", "undefine", "(", "self", ")", ":", "if", "lib", ".", "EnvUndefrule", "(", "self", ".", "_env", ",", "self", ".", "_rule", ")", "!=", "1", ":", "raise", "CLIPSError", "(", "self", ".", "_env", ")", "self", ".", "_env", "=", "None" ]
Undefine the Rule. Python equivalent of the CLIPS undefrule command. The object becomes unusable after this method has been called.
[ "Undefine", "the", "Rule", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/agenda.py#L315-L326
train
35,303
noxdafox/clipspy
clips/agenda.py
Activation.name
def name(self): """Activation Rule name.""" return ffi.string( lib.EnvGetActivationName(self._env, self._act)).decode()
python
def name(self): """Activation Rule name.""" return ffi.string( lib.EnvGetActivationName(self._env, self._act)).decode()
[ "def", "name", "(", "self", ")", ":", "return", "ffi", ".", "string", "(", "lib", ".", "EnvGetActivationName", "(", "self", ".", "_env", ",", "self", ".", "_act", ")", ")", ".", "decode", "(", ")" ]
Activation Rule name.
[ "Activation", "Rule", "name", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/agenda.py#L355-L358
train
35,304
noxdafox/clipspy
clips/agenda.py
Activation.salience
def salience(self, salience): """Activation salience value.""" lib.EnvSetActivationSalience(self._env, self._act, salience)
python
def salience(self, salience): """Activation salience value.""" lib.EnvSetActivationSalience(self._env, self._act, salience)
[ "def", "salience", "(", "self", ",", "salience", ")", ":", "lib", ".", "EnvSetActivationSalience", "(", "self", ".", "_env", ",", "self", ".", "_act", ",", "salience", ")" ]
Activation salience value.
[ "Activation", "salience", "value", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/agenda.py#L366-L368
train
35,305
noxdafox/clipspy
clips/agenda.py
Activation.delete
def delete(self): """Remove the activation from the agenda.""" if lib.EnvDeleteActivation(self._env, self._act) != 1: raise CLIPSError(self._env) self._env = None
python
def delete(self): """Remove the activation from the agenda.""" if lib.EnvDeleteActivation(self._env, self._act) != 1: raise CLIPSError(self._env) self._env = None
[ "def", "delete", "(", "self", ")", ":", "if", "lib", ".", "EnvDeleteActivation", "(", "self", ".", "_env", ",", "self", ".", "_act", ")", "!=", "1", ":", "raise", "CLIPSError", "(", "self", ".", "_env", ")", "self", ".", "_env", "=", "None" ]
Remove the activation from the agenda.
[ "Remove", "the", "activation", "from", "the", "agenda", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/agenda.py#L370-L375
train
35,306
noxdafox/clipspy
clips/modules.py
Modules.globals_changed
def globals_changed(self): """True if any Global has changed.""" value = bool(lib.EnvGetGlobalsChanged(self._env)) lib.EnvSetGlobalsChanged(self._env, int(False)) return value
python
def globals_changed(self): """True if any Global has changed.""" value = bool(lib.EnvGetGlobalsChanged(self._env)) lib.EnvSetGlobalsChanged(self._env, int(False)) return value
[ "def", "globals_changed", "(", "self", ")", ":", "value", "=", "bool", "(", "lib", ".", "EnvGetGlobalsChanged", "(", "self", ".", "_env", ")", ")", "lib", ".", "EnvSetGlobalsChanged", "(", "self", ".", "_env", ",", "int", "(", "False", ")", ")", "retur...
True if any Global has changed.
[ "True", "if", "any", "Global", "has", "changed", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/modules.py#L78-L83
train
35,307
noxdafox/clipspy
clips/modules.py
Modules.find_global
def find_global(self, name): """Find the Global by its name.""" defglobal = lib.EnvFindDefglobal(self._env, name.encode()) if defglobal == ffi.NULL: raise LookupError("Global '%s' not found" % name) return Global(self._env, defglobal)
python
def find_global(self, name): """Find the Global by its name.""" defglobal = lib.EnvFindDefglobal(self._env, name.encode()) if defglobal == ffi.NULL: raise LookupError("Global '%s' not found" % name) return Global(self._env, defglobal)
[ "def", "find_global", "(", "self", ",", "name", ")", ":", "defglobal", "=", "lib", ".", "EnvFindDefglobal", "(", "self", ".", "_env", ",", "name", ".", "encode", "(", ")", ")", "if", "defglobal", "==", "ffi", ".", "NULL", ":", "raise", "LookupError", ...
Find the Global by its name.
[ "Find", "the", "Global", "by", "its", "name", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/modules.py#L94-L100
train
35,308
noxdafox/clipspy
clips/modules.py
Modules.modules
def modules(self): """Iterates over the defined Modules.""" defmodule = lib.EnvGetNextDefmodule(self._env, ffi.NULL) while defmodule != ffi.NULL: yield Module(self._env, defmodule) defmodule = lib.EnvGetNextDefmodule(self._env, defmodule)
python
def modules(self): """Iterates over the defined Modules.""" defmodule = lib.EnvGetNextDefmodule(self._env, ffi.NULL) while defmodule != ffi.NULL: yield Module(self._env, defmodule) defmodule = lib.EnvGetNextDefmodule(self._env, defmodule)
[ "def", "modules", "(", "self", ")", ":", "defmodule", "=", "lib", ".", "EnvGetNextDefmodule", "(", "self", ".", "_env", ",", "ffi", ".", "NULL", ")", "while", "defmodule", "!=", "ffi", ".", "NULL", ":", "yield", "Module", "(", "self", ".", "_env", ",...
Iterates over the defined Modules.
[ "Iterates", "over", "the", "defined", "Modules", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/modules.py#L102-L109
train
35,309
noxdafox/clipspy
clips/modules.py
Modules.find_module
def find_module(self, name): """Find the Module by its name.""" defmodule = lib.EnvFindDefmodule(self._env, name.encode()) if defmodule == ffi.NULL: raise LookupError("Module '%s' not found" % name) return Module(self._env, defmodule)
python
def find_module(self, name): """Find the Module by its name.""" defmodule = lib.EnvFindDefmodule(self._env, name.encode()) if defmodule == ffi.NULL: raise LookupError("Module '%s' not found" % name) return Module(self._env, defmodule)
[ "def", "find_module", "(", "self", ",", "name", ")", ":", "defmodule", "=", "lib", ".", "EnvFindDefmodule", "(", "self", ".", "_env", ",", "name", ".", "encode", "(", ")", ")", "if", "defmodule", "==", "ffi", ".", "NULL", ":", "raise", "LookupError", ...
Find the Module by its name.
[ "Find", "the", "Module", "by", "its", "name", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/modules.py#L111-L117
train
35,310
noxdafox/clipspy
clips/modules.py
Global.value
def value(self): """Global value.""" data = clips.data.DataObject(self._env) if lib.EnvGetDefglobalValue( self._env, self.name.encode(), data.byref) != 1: raise CLIPSError(self._env) return data.value
python
def value(self): """Global value.""" data = clips.data.DataObject(self._env) if lib.EnvGetDefglobalValue( self._env, self.name.encode(), data.byref) != 1: raise CLIPSError(self._env) return data.value
[ "def", "value", "(", "self", ")", ":", "data", "=", "clips", ".", "data", ".", "DataObject", "(", "self", ".", "_env", ")", "if", "lib", ".", "EnvGetDefglobalValue", "(", "self", ".", "_env", ",", "self", ".", "name", ".", "encode", "(", ")", ",", ...
Global value.
[ "Global", "value", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/modules.py#L151-L159
train
35,311
noxdafox/clipspy
clips/modules.py
Global.module
def module(self): """The module in which the Global is defined. Python equivalent of the CLIPS defglobal-module command. """ modname = ffi.string(lib.EnvDefglobalModule(self._env, self._glb)) defmodule = lib.EnvFindDefmodule(self._env, modname) return Module(self._env, defmodule)
python
def module(self): """The module in which the Global is defined. Python equivalent of the CLIPS defglobal-module command. """ modname = ffi.string(lib.EnvDefglobalModule(self._env, self._glb)) defmodule = lib.EnvFindDefmodule(self._env, modname) return Module(self._env, defmodule)
[ "def", "module", "(", "self", ")", ":", "modname", "=", "ffi", ".", "string", "(", "lib", ".", "EnvDefglobalModule", "(", "self", ".", "_env", ",", "self", ".", "_glb", ")", ")", "defmodule", "=", "lib", ".", "EnvFindDefmodule", "(", "self", ".", "_e...
The module in which the Global is defined. Python equivalent of the CLIPS defglobal-module command.
[ "The", "module", "in", "which", "the", "Global", "is", "defined", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/modules.py#L178-L187
train
35,312
noxdafox/clipspy
clips/modules.py
Global.watch
def watch(self, flag): """Whether or not the Global is being watched.""" lib.EnvSetDefglobalWatch(self._env, int(flag), self._glb)
python
def watch(self, flag): """Whether or not the Global is being watched.""" lib.EnvSetDefglobalWatch(self._env, int(flag), self._glb)
[ "def", "watch", "(", "self", ",", "flag", ")", ":", "lib", ".", "EnvSetDefglobalWatch", "(", "self", ".", "_env", ",", "int", "(", "flag", ")", ",", "self", ".", "_glb", ")" ]
Whether or not the Global is being watched.
[ "Whether", "or", "not", "the", "Global", "is", "being", "watched", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/modules.py#L200-L202
train
35,313
noxdafox/clipspy
clips/modules.py
Global.undefine
def undefine(self): """Undefine the Global. Python equivalent of the CLIPS undefglobal command. The object becomes unusable after this method has been called. """ if lib.EnvUndefglobal(self._env, self._glb) != 1: raise CLIPSError(self._env) self._env = None
python
def undefine(self): """Undefine the Global. Python equivalent of the CLIPS undefglobal command. The object becomes unusable after this method has been called. """ if lib.EnvUndefglobal(self._env, self._glb) != 1: raise CLIPSError(self._env) self._env = None
[ "def", "undefine", "(", "self", ")", ":", "if", "lib", ".", "EnvUndefglobal", "(", "self", ".", "_env", ",", "self", ".", "_glb", ")", "!=", "1", ":", "raise", "CLIPSError", "(", "self", ".", "_env", ")", "self", ".", "_env", "=", "None" ]
Undefine the Global. Python equivalent of the CLIPS undefglobal command. The object becomes unusable after this method has been called.
[ "Undefine", "the", "Global", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/modules.py#L204-L215
train
35,314
noxdafox/clipspy
clips/functions.py
Functions.find_function
def find_function(self, name): """Find the Function by its name.""" deffunction = lib.EnvFindDeffunction(self._env, name.encode()) if deffunction == ffi.NULL: raise LookupError("Function '%s' not found" % name) return Function(self._env, deffunction)
python
def find_function(self, name): """Find the Function by its name.""" deffunction = lib.EnvFindDeffunction(self._env, name.encode()) if deffunction == ffi.NULL: raise LookupError("Function '%s' not found" % name) return Function(self._env, deffunction)
[ "def", "find_function", "(", "self", ",", "name", ")", ":", "deffunction", "=", "lib", ".", "EnvFindDeffunction", "(", "self", ".", "_env", ",", "name", ".", "encode", "(", ")", ")", "if", "deffunction", "==", "ffi", ".", "NULL", ":", "raise", "LookupE...
Find the Function by its name.
[ "Find", "the", "Function", "by", "its", "name", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/functions.py#L70-L76
train
35,315
noxdafox/clipspy
clips/functions.py
Functions.generics
def generics(self): """Iterates over the defined Generics.""" defgeneric = lib.EnvGetNextDefgeneric(self._env, ffi.NULL) while defgeneric != ffi.NULL: yield Generic(self._env, defgeneric) defgeneric = lib.EnvGetNextDefgeneric(self._env, defgeneric)
python
def generics(self): """Iterates over the defined Generics.""" defgeneric = lib.EnvGetNextDefgeneric(self._env, ffi.NULL) while defgeneric != ffi.NULL: yield Generic(self._env, defgeneric) defgeneric = lib.EnvGetNextDefgeneric(self._env, defgeneric)
[ "def", "generics", "(", "self", ")", ":", "defgeneric", "=", "lib", ".", "EnvGetNextDefgeneric", "(", "self", ".", "_env", ",", "ffi", ".", "NULL", ")", "while", "defgeneric", "!=", "ffi", ".", "NULL", ":", "yield", "Generic", "(", "self", ".", "_env",...
Iterates over the defined Generics.
[ "Iterates", "over", "the", "defined", "Generics", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/functions.py#L78-L85
train
35,316
noxdafox/clipspy
clips/functions.py
Functions.find_generic
def find_generic(self, name): """Find the Generic by its name.""" defgeneric = lib.EnvFindDefgeneric(self._env, name.encode()) if defgeneric == ffi.NULL: raise LookupError("Generic '%s' not found" % name) return Generic(self._env, defgeneric)
python
def find_generic(self, name): """Find the Generic by its name.""" defgeneric = lib.EnvFindDefgeneric(self._env, name.encode()) if defgeneric == ffi.NULL: raise LookupError("Generic '%s' not found" % name) return Generic(self._env, defgeneric)
[ "def", "find_generic", "(", "self", ",", "name", ")", ":", "defgeneric", "=", "lib", ".", "EnvFindDefgeneric", "(", "self", ".", "_env", ",", "name", ".", "encode", "(", ")", ")", "if", "defgeneric", "==", "ffi", ".", "NULL", ":", "raise", "LookupError...
Find the Generic by its name.
[ "Find", "the", "Generic", "by", "its", "name", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/functions.py#L87-L93
train
35,317
noxdafox/clipspy
clips/functions.py
Function.name
def name(self): """Function name.""" return ffi.string( lib.EnvGetDeffunctionName(self._env, self._fnc)).decode()
python
def name(self): """Function name.""" return ffi.string( lib.EnvGetDeffunctionName(self._env, self._fnc)).decode()
[ "def", "name", "(", "self", ")", ":", "return", "ffi", ".", "string", "(", "lib", ".", "EnvGetDeffunctionName", "(", "self", ".", "_env", ",", "self", ".", "_fnc", ")", ")", ".", "decode", "(", ")" ]
Function name.
[ "Function", "name", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/functions.py#L142-L145
train
35,318
noxdafox/clipspy
clips/functions.py
Function.module
def module(self): """The module in which the Function is defined. Python equivalent of the CLIPS deffunction-module command. """ modname = ffi.string(lib.EnvDeffunctionModule(self._env, self._fnc)) defmodule = lib.EnvFindDefmodule(self._env, modname) return Module(self._env, defmodule)
python
def module(self): """The module in which the Function is defined. Python equivalent of the CLIPS deffunction-module command. """ modname = ffi.string(lib.EnvDeffunctionModule(self._env, self._fnc)) defmodule = lib.EnvFindDefmodule(self._env, modname) return Module(self._env, defmodule)
[ "def", "module", "(", "self", ")", ":", "modname", "=", "ffi", ".", "string", "(", "lib", ".", "EnvDeffunctionModule", "(", "self", ".", "_env", ",", "self", ".", "_fnc", ")", ")", "defmodule", "=", "lib", ".", "EnvFindDefmodule", "(", "self", ".", "...
The module in which the Function is defined. Python equivalent of the CLIPS deffunction-module command.
[ "The", "module", "in", "which", "the", "Function", "is", "defined", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/functions.py#L148-L157
train
35,319
noxdafox/clipspy
clips/functions.py
Function.watch
def watch(self, flag): """Whether or not the Function is being watched.""" lib.EnvSetDeffunctionWatch(self._env, int(flag), self._fnc)
python
def watch(self, flag): """Whether or not the Function is being watched.""" lib.EnvSetDeffunctionWatch(self._env, int(flag), self._fnc)
[ "def", "watch", "(", "self", ",", "flag", ")", ":", "lib", ".", "EnvSetDeffunctionWatch", "(", "self", ".", "_env", ",", "int", "(", "flag", ")", ",", "self", ".", "_fnc", ")" ]
Whether or not the Function is being watched.
[ "Whether", "or", "not", "the", "Function", "is", "being", "watched", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/functions.py#L170-L172
train
35,320
noxdafox/clipspy
clips/functions.py
Function.undefine
def undefine(self): """Undefine the Function. Python equivalent of the CLIPS undeffunction command. The object becomes unusable after this method has been called. """ if lib.EnvUndeffunction(self._env, self._fnc) != 1: raise CLIPSError(self._env) self._env = None
python
def undefine(self): """Undefine the Function. Python equivalent of the CLIPS undeffunction command. The object becomes unusable after this method has been called. """ if lib.EnvUndeffunction(self._env, self._fnc) != 1: raise CLIPSError(self._env) self._env = None
[ "def", "undefine", "(", "self", ")", ":", "if", "lib", ".", "EnvUndeffunction", "(", "self", ".", "_env", ",", "self", ".", "_fnc", ")", "!=", "1", ":", "raise", "CLIPSError", "(", "self", ".", "_env", ")", "self", ".", "_env", "=", "None" ]
Undefine the Function. Python equivalent of the CLIPS undeffunction command. The object becomes unusable after this method has been called.
[ "Undefine", "the", "Function", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/functions.py#L174-L185
train
35,321
noxdafox/clipspy
clips/functions.py
Generic.undefine
def undefine(self): """Undefine the Generic. Python equivalent of the CLIPS undefgeneric command. The object becomes unusable after this method has been called. """ if lib.EnvUndefgeneric(self._env, self._gnc) != 1: raise CLIPSError(self._env) self._env = None
python
def undefine(self): """Undefine the Generic. Python equivalent of the CLIPS undefgeneric command. The object becomes unusable after this method has been called. """ if lib.EnvUndefgeneric(self._env, self._gnc) != 1: raise CLIPSError(self._env) self._env = None
[ "def", "undefine", "(", "self", ")", ":", "if", "lib", ".", "EnvUndefgeneric", "(", "self", ".", "_env", ",", "self", ".", "_gnc", ")", "!=", "1", ":", "raise", "CLIPSError", "(", "self", ".", "_env", ")", "self", ".", "_env", "=", "None" ]
Undefine the Generic. Python equivalent of the CLIPS undefgeneric command. The object becomes unusable after this method has been called.
[ "Undefine", "the", "Generic", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/functions.py#L265-L276
train
35,322
noxdafox/clipspy
clips/functions.py
Method.undefine
def undefine(self): """Undefine the Method. Python equivalent of the CLIPS undefmethod command. The object becomes unusable after this method has been called. """ if lib.EnvUndefmethod(self._env, self._gnc, self._idx) != 1: raise CLIPSError(self._env) self._env = None
python
def undefine(self): """Undefine the Method. Python equivalent of the CLIPS undefmethod command. The object becomes unusable after this method has been called. """ if lib.EnvUndefmethod(self._env, self._gnc, self._idx) != 1: raise CLIPSError(self._env) self._env = None
[ "def", "undefine", "(", "self", ")", ":", "if", "lib", ".", "EnvUndefmethod", "(", "self", ".", "_env", ",", "self", ".", "_gnc", ",", "self", ".", "_idx", ")", "!=", "1", ":", "raise", "CLIPSError", "(", "self", ".", "_env", ")", "self", ".", "_...
Undefine the Method. Python equivalent of the CLIPS undefmethod command. The object becomes unusable after this method has been called.
[ "Undefine", "the", "Method", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/functions.py#L341-L352
train
35,323
taborlab/FlowCal
FlowCal/mef.py
selection_std
def selection_std(populations, low=None, high=None, n_std_low=2.5, n_std_high=2.5, scale='logicle'): """ Select populations if most of their elements are between two values. This function selects populations from `populations` if their means are more than `n_std_low` standard deviations greater than `low` and `n_std_high` standard deviations lower than `high`. Optionally, all elements in `populations` can be rescaled as specified by the `scale` argument before calculating means and standard deviations. Parameters ---------- populations : list of 1D arrays or 1-channel FCSData objects Populations to select or discard. low, high : int or float Low and high thresholds. Required if the elements in `populations` are numpy arrays. If not specified, and the elements in `populations` are FCSData objects, use 1.5% and 98.5% of the range in ``populations[0].range``. n_std_low, n_std_high : float, optional Number of standard deviations from `low` and `high`, respectively, that a population's mean has to be closer than to be discarded. scale : str, optional Rescaling applied to `populations` before calculating means and standard deviations. Can be either ``linear`` (no rescaling), ``log``, or ``logicle``. Returns ------- selected_mask : boolean array Flags indicating whether a population has been selected. """ # Generate scaling functions if scale == 'linear': # Identity function sf = lambda x: x elif scale == 'log': sf = np.log10 elif scale == 'logicle': # We need a transformation from "data value" to "display scale" # units. To do so, we use an inverse logicle transformation. t = FlowCal.plot._LogicleTransform(data=populations[0], channel=0).inverted() sf = lambda x: t.transform_non_affine(x, mask_out_of_range=False) else: raise ValueError("scale {} not supported".format(scale)) # If thresholds were provided, apply scaling function. Else, obtain and # rescale thresholds from range. if low is None: if hasattr(populations[0], 'hist_bins'): # Obtain default thresholds from range r = populations[0].range(channels=0) # If using log scale and the lower limit is non-positive, change to # a very small positive number. # The machine epsilon `eps` is the smallest number such that # `1.0 + eps != eps`. For a 64-bit floating point, `eps ~= 1e-15`. if scale == 'log' and r[0] <= 0: r[0] = 1e-15 low = sf(r[0]) + 0.015*(sf(r[1]) - sf(r[0])) else: raise TypeError("argument 'low' not specified") else: low = sf(low) if high is None: if hasattr(populations[0], 'hist_bins'): # Obtain default thresholds from range r = populations[0].range(channels=0) # If using log scale and the lower limit is non-positive, change to # a very small positive number. # The machine epsilon `eps` is the smallest number such that # `1.0 + eps != eps`. For a 64-bit floating point, `eps ~= 1e-15`. if scale == 'log' and r[0] <= 0: r[0] = 1e-15 high = sf(r[0]) + 0.985*(sf(r[1]) - sf(r[0])) else: raise TypeError("argument 'high' not specified") else: high = sf(high) # Copy events for i in range(len(populations)): populations[i] = populations[i].copy() # For log scaling, logarithm of zero and negatives is undefined. Therefore, # saturate any non-positives to a small positive value. # The machine epsilon `eps` is the smallest number such that # `1.0 + eps != eps`. For a 64-bit floating point, `eps ~= 1e-15`. if scale == 'log': for p in populations: p[p < 1e-15] = 1e-15 # Rescale events for i in range(len(populations)): populations[i] = sf(populations[i]) # Calculate means and standard deviations pop_mean = np.array([FlowCal.stats.mean(p) for p in populations]) pop_std = np.array([FlowCal.stats.std(p) for p in populations]) # Some populations, especially the highest ones when they are near # saturation, tend to aggregate mostly on one bin and give a standard # deviation of almost zero. This is an effect of the finite bin resolution # and probably gives a bad estimate of the standard deviation. We choose # to be conservative and overestimate the standard deviation in these # cases. Therefore, we set the minimum standard deviation to 0.005. min_std = 0.005 pop_std[pop_std < min_std] = min_std # Return populations that don't cross either threshold selected_mask = np.logical_and( (pop_mean - n_std_low*pop_std) > low, (pop_mean + n_std_high*pop_std) < high) return selected_mask
python
def selection_std(populations, low=None, high=None, n_std_low=2.5, n_std_high=2.5, scale='logicle'): """ Select populations if most of their elements are between two values. This function selects populations from `populations` if their means are more than `n_std_low` standard deviations greater than `low` and `n_std_high` standard deviations lower than `high`. Optionally, all elements in `populations` can be rescaled as specified by the `scale` argument before calculating means and standard deviations. Parameters ---------- populations : list of 1D arrays or 1-channel FCSData objects Populations to select or discard. low, high : int or float Low and high thresholds. Required if the elements in `populations` are numpy arrays. If not specified, and the elements in `populations` are FCSData objects, use 1.5% and 98.5% of the range in ``populations[0].range``. n_std_low, n_std_high : float, optional Number of standard deviations from `low` and `high`, respectively, that a population's mean has to be closer than to be discarded. scale : str, optional Rescaling applied to `populations` before calculating means and standard deviations. Can be either ``linear`` (no rescaling), ``log``, or ``logicle``. Returns ------- selected_mask : boolean array Flags indicating whether a population has been selected. """ # Generate scaling functions if scale == 'linear': # Identity function sf = lambda x: x elif scale == 'log': sf = np.log10 elif scale == 'logicle': # We need a transformation from "data value" to "display scale" # units. To do so, we use an inverse logicle transformation. t = FlowCal.plot._LogicleTransform(data=populations[0], channel=0).inverted() sf = lambda x: t.transform_non_affine(x, mask_out_of_range=False) else: raise ValueError("scale {} not supported".format(scale)) # If thresholds were provided, apply scaling function. Else, obtain and # rescale thresholds from range. if low is None: if hasattr(populations[0], 'hist_bins'): # Obtain default thresholds from range r = populations[0].range(channels=0) # If using log scale and the lower limit is non-positive, change to # a very small positive number. # The machine epsilon `eps` is the smallest number such that # `1.0 + eps != eps`. For a 64-bit floating point, `eps ~= 1e-15`. if scale == 'log' and r[0] <= 0: r[0] = 1e-15 low = sf(r[0]) + 0.015*(sf(r[1]) - sf(r[0])) else: raise TypeError("argument 'low' not specified") else: low = sf(low) if high is None: if hasattr(populations[0], 'hist_bins'): # Obtain default thresholds from range r = populations[0].range(channels=0) # If using log scale and the lower limit is non-positive, change to # a very small positive number. # The machine epsilon `eps` is the smallest number such that # `1.0 + eps != eps`. For a 64-bit floating point, `eps ~= 1e-15`. if scale == 'log' and r[0] <= 0: r[0] = 1e-15 high = sf(r[0]) + 0.985*(sf(r[1]) - sf(r[0])) else: raise TypeError("argument 'high' not specified") else: high = sf(high) # Copy events for i in range(len(populations)): populations[i] = populations[i].copy() # For log scaling, logarithm of zero and negatives is undefined. Therefore, # saturate any non-positives to a small positive value. # The machine epsilon `eps` is the smallest number such that # `1.0 + eps != eps`. For a 64-bit floating point, `eps ~= 1e-15`. if scale == 'log': for p in populations: p[p < 1e-15] = 1e-15 # Rescale events for i in range(len(populations)): populations[i] = sf(populations[i]) # Calculate means and standard deviations pop_mean = np.array([FlowCal.stats.mean(p) for p in populations]) pop_std = np.array([FlowCal.stats.std(p) for p in populations]) # Some populations, especially the highest ones when they are near # saturation, tend to aggregate mostly on one bin and give a standard # deviation of almost zero. This is an effect of the finite bin resolution # and probably gives a bad estimate of the standard deviation. We choose # to be conservative and overestimate the standard deviation in these # cases. Therefore, we set the minimum standard deviation to 0.005. min_std = 0.005 pop_std[pop_std < min_std] = min_std # Return populations that don't cross either threshold selected_mask = np.logical_and( (pop_mean - n_std_low*pop_std) > low, (pop_mean + n_std_high*pop_std) < high) return selected_mask
[ "def", "selection_std", "(", "populations", ",", "low", "=", "None", ",", "high", "=", "None", ",", "n_std_low", "=", "2.5", ",", "n_std_high", "=", "2.5", ",", "scale", "=", "'logicle'", ")", ":", "# Generate scaling functions", "if", "scale", "==", "'lin...
Select populations if most of their elements are between two values. This function selects populations from `populations` if their means are more than `n_std_low` standard deviations greater than `low` and `n_std_high` standard deviations lower than `high`. Optionally, all elements in `populations` can be rescaled as specified by the `scale` argument before calculating means and standard deviations. Parameters ---------- populations : list of 1D arrays or 1-channel FCSData objects Populations to select or discard. low, high : int or float Low and high thresholds. Required if the elements in `populations` are numpy arrays. If not specified, and the elements in `populations` are FCSData objects, use 1.5% and 98.5% of the range in ``populations[0].range``. n_std_low, n_std_high : float, optional Number of standard deviations from `low` and `high`, respectively, that a population's mean has to be closer than to be discarded. scale : str, optional Rescaling applied to `populations` before calculating means and standard deviations. Can be either ``linear`` (no rescaling), ``log``, or ``logicle``. Returns ------- selected_mask : boolean array Flags indicating whether a population has been selected.
[ "Select", "populations", "if", "most", "of", "their", "elements", "are", "between", "two", "values", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/mef.py#L215-L337
train
35,324
taborlab/FlowCal
FlowCal/mef.py
fit_beads_autofluorescence
def fit_beads_autofluorescence(fl_rfi, fl_mef): """ Fit a standard curve using a beads model with autofluorescence. Parameters ---------- fl_rfi : array Fluorescence values of bead populations in units of Relative Fluorescence Intensity (RFI). fl_mef : array Fluorescence values of bead populations in MEF units. Returns ------- std_crv : function Standard curve that transforms fluorescence values from RFI to MEF units. This function has the signature ``y = std_crv(x)``, where `x` is some fluorescence value in RFI and `y` is the same fluorescence expressed in MEF units. beads_model : function Fluorescence model of calibration beads. This function has the signature ``y = beads_model(x)``, where `x` is the fluorescence of some bead population in RFI units and `y` is the same fluorescence expressed in MEF units, without autofluorescence. beads_params : array Fitted parameters of the bead fluorescence model: ``[m, b, fl_mef_auto]``. beads_model_str : str String representation of the beads model used. beads_params_names : list of str Names of the parameters in a list, in the same order as they are given in `beads_params`. Notes ----- The following model is used to describe bead fluorescence:: m*log(fl_rfi[i]) + b = log(fl_mef_auto + fl_mef[i]) where ``fl_rfi[i]`` is the fluorescence of bead subpopulation ``i`` in RFI units and ``fl_mef[i]`` is the corresponding fluorescence in MEF units. The model includes 3 parameters: ``m`` (slope), ``b`` (intercept), and ``fl_mef_auto`` (bead autofluorescence). The last term is constrained to be greater or equal to zero. The bead fluorescence model is fit in log space using nonlinear least squares regression. In our experience, fitting in log space weights the residuals more evenly, whereas fitting in linear space vastly overvalues the brighter beads. A standard curve is constructed by solving for ``fl_mef``. As cell samples may not have the same autofluorescence as beads, the bead autofluorescence term (``fl_mef_auto``) is omitted from the standard curve; the user is expected to use an appropriate white cell sample to account for cellular autofluorescence if necessary. The returned standard curve mapping fluorescence in RFI units to MEF units is thus of the following form:: fl_mef = exp(m*log(fl_rfi) + b) This is equivalent to:: fl_mef = exp(b) * (fl_rfi**m) This works for positive ``fl_rfi`` values, but it is undefined for ``fl_rfi < 0`` and non-integer ``m`` (general case). To extend this standard curve to negative values of ``fl_rfi``, we define ``s(fl_rfi)`` to be equal to the standard curve above when ``fl_rfi >= 0``. Next, we require this function to be odd, that is, ``s(fl_rfi) = - s(-fl_rfi)``. This extends the domain to negative ``fl_rfi`` values and results in ``s(fl_rfi) < 0`` for any negative ``fl_rfi``. Finally, we make ``fl_mef = s(fl_rfi)`` our new standard curve. In this way,:: s(fl_rfi) = exp(b) * ( fl_rfi **m), fl_rfi >= 0 - exp(b) * ((-fl_rfi)**m), fl_rfi < 0 This satisfies the definition of an odd function. In addition, ``s(0) = 0``, and ``s(fl_rfi)`` converges to zero when ``fl_rfi -> 0`` from both sides. Therefore, the function is continuous at ``fl_rfi = 0``. The definition of ``s(fl_rfi)`` can be expressed more conveniently as:: s(fl_rfi) = sign(fl_rfi) * exp(b) * (abs(fl_rfi)**m) This is the equation implemented. """ # Check that the input data has consistent dimensions if len(fl_rfi) != len(fl_mef): raise ValueError("fl_rfi and fl_mef have different lengths") # Check that we have at least three points if len(fl_rfi) <= 2: raise ValueError("standard curve model requires at least three " "values") # Initialize parameters params = np.zeros(3) # Initial guesses: # 0: slope found by putting a line through the highest two points. # 1: y-intercept found by putting a line through highest two points. # 2: bead autofluorescence initialized using the first point. params[0] = (np.log(fl_mef[-1]) - np.log(fl_mef[-2])) / \ (np.log(fl_rfi[-1]) - np.log(fl_rfi[-2])) params[1] = np.log(fl_mef[-1]) - params[0] * np.log(fl_rfi[-1]) params[2] = np.exp(params[0]*np.log(fl_rfi[0]) + params[1]) - fl_mef[0] # Error function def err_fun(p, x, y): return np.sum((np.log(y + p[2]) - ( p[0] * np.log(x) + p[1] ))**2) # Bead model function def fit_fun(p,x): return np.exp(p[0] * np.log(x) + p[1]) - p[2] # RFI-to-MEF standard curve transformation function def sc_fun(p,x): return np.sign(x) * np.exp(p[1]) * (np.abs(x)**p[0]) # Fit parameters err_par = lambda p: err_fun(p, fl_rfi, fl_mef) res = minimize(err_par, params, bounds=((None, None), (None, None), (0, None)), options = {'gtol': 1e-10, 'ftol': 1e-10}) # Separate parameters beads_params = res.x # Beads model function beads_model = lambda x: fit_fun(beads_params, x) # Standard curve function std_crv = lambda x: sc_fun(beads_params, x) # Model string representation beads_model_str = 'm*log(fl_rfi) + b = log(fl_mef_auto + fl_mef)' # Parameter names beads_params_names = ['m', 'b', 'fl_mef_auto'] return (std_crv, beads_model, beads_params, beads_model_str, beads_params_names)
python
def fit_beads_autofluorescence(fl_rfi, fl_mef): """ Fit a standard curve using a beads model with autofluorescence. Parameters ---------- fl_rfi : array Fluorescence values of bead populations in units of Relative Fluorescence Intensity (RFI). fl_mef : array Fluorescence values of bead populations in MEF units. Returns ------- std_crv : function Standard curve that transforms fluorescence values from RFI to MEF units. This function has the signature ``y = std_crv(x)``, where `x` is some fluorescence value in RFI and `y` is the same fluorescence expressed in MEF units. beads_model : function Fluorescence model of calibration beads. This function has the signature ``y = beads_model(x)``, where `x` is the fluorescence of some bead population in RFI units and `y` is the same fluorescence expressed in MEF units, without autofluorescence. beads_params : array Fitted parameters of the bead fluorescence model: ``[m, b, fl_mef_auto]``. beads_model_str : str String representation of the beads model used. beads_params_names : list of str Names of the parameters in a list, in the same order as they are given in `beads_params`. Notes ----- The following model is used to describe bead fluorescence:: m*log(fl_rfi[i]) + b = log(fl_mef_auto + fl_mef[i]) where ``fl_rfi[i]`` is the fluorescence of bead subpopulation ``i`` in RFI units and ``fl_mef[i]`` is the corresponding fluorescence in MEF units. The model includes 3 parameters: ``m`` (slope), ``b`` (intercept), and ``fl_mef_auto`` (bead autofluorescence). The last term is constrained to be greater or equal to zero. The bead fluorescence model is fit in log space using nonlinear least squares regression. In our experience, fitting in log space weights the residuals more evenly, whereas fitting in linear space vastly overvalues the brighter beads. A standard curve is constructed by solving for ``fl_mef``. As cell samples may not have the same autofluorescence as beads, the bead autofluorescence term (``fl_mef_auto``) is omitted from the standard curve; the user is expected to use an appropriate white cell sample to account for cellular autofluorescence if necessary. The returned standard curve mapping fluorescence in RFI units to MEF units is thus of the following form:: fl_mef = exp(m*log(fl_rfi) + b) This is equivalent to:: fl_mef = exp(b) * (fl_rfi**m) This works for positive ``fl_rfi`` values, but it is undefined for ``fl_rfi < 0`` and non-integer ``m`` (general case). To extend this standard curve to negative values of ``fl_rfi``, we define ``s(fl_rfi)`` to be equal to the standard curve above when ``fl_rfi >= 0``. Next, we require this function to be odd, that is, ``s(fl_rfi) = - s(-fl_rfi)``. This extends the domain to negative ``fl_rfi`` values and results in ``s(fl_rfi) < 0`` for any negative ``fl_rfi``. Finally, we make ``fl_mef = s(fl_rfi)`` our new standard curve. In this way,:: s(fl_rfi) = exp(b) * ( fl_rfi **m), fl_rfi >= 0 - exp(b) * ((-fl_rfi)**m), fl_rfi < 0 This satisfies the definition of an odd function. In addition, ``s(0) = 0``, and ``s(fl_rfi)`` converges to zero when ``fl_rfi -> 0`` from both sides. Therefore, the function is continuous at ``fl_rfi = 0``. The definition of ``s(fl_rfi)`` can be expressed more conveniently as:: s(fl_rfi) = sign(fl_rfi) * exp(b) * (abs(fl_rfi)**m) This is the equation implemented. """ # Check that the input data has consistent dimensions if len(fl_rfi) != len(fl_mef): raise ValueError("fl_rfi and fl_mef have different lengths") # Check that we have at least three points if len(fl_rfi) <= 2: raise ValueError("standard curve model requires at least three " "values") # Initialize parameters params = np.zeros(3) # Initial guesses: # 0: slope found by putting a line through the highest two points. # 1: y-intercept found by putting a line through highest two points. # 2: bead autofluorescence initialized using the first point. params[0] = (np.log(fl_mef[-1]) - np.log(fl_mef[-2])) / \ (np.log(fl_rfi[-1]) - np.log(fl_rfi[-2])) params[1] = np.log(fl_mef[-1]) - params[0] * np.log(fl_rfi[-1]) params[2] = np.exp(params[0]*np.log(fl_rfi[0]) + params[1]) - fl_mef[0] # Error function def err_fun(p, x, y): return np.sum((np.log(y + p[2]) - ( p[0] * np.log(x) + p[1] ))**2) # Bead model function def fit_fun(p,x): return np.exp(p[0] * np.log(x) + p[1]) - p[2] # RFI-to-MEF standard curve transformation function def sc_fun(p,x): return np.sign(x) * np.exp(p[1]) * (np.abs(x)**p[0]) # Fit parameters err_par = lambda p: err_fun(p, fl_rfi, fl_mef) res = minimize(err_par, params, bounds=((None, None), (None, None), (0, None)), options = {'gtol': 1e-10, 'ftol': 1e-10}) # Separate parameters beads_params = res.x # Beads model function beads_model = lambda x: fit_fun(beads_params, x) # Standard curve function std_crv = lambda x: sc_fun(beads_params, x) # Model string representation beads_model_str = 'm*log(fl_rfi) + b = log(fl_mef_auto + fl_mef)' # Parameter names beads_params_names = ['m', 'b', 'fl_mef_auto'] return (std_crv, beads_model, beads_params, beads_model_str, beads_params_names)
[ "def", "fit_beads_autofluorescence", "(", "fl_rfi", ",", "fl_mef", ")", ":", "# Check that the input data has consistent dimensions", "if", "len", "(", "fl_rfi", ")", "!=", "len", "(", "fl_mef", ")", ":", "raise", "ValueError", "(", "\"fl_rfi and fl_mef have different l...
Fit a standard curve using a beads model with autofluorescence. Parameters ---------- fl_rfi : array Fluorescence values of bead populations in units of Relative Fluorescence Intensity (RFI). fl_mef : array Fluorescence values of bead populations in MEF units. Returns ------- std_crv : function Standard curve that transforms fluorescence values from RFI to MEF units. This function has the signature ``y = std_crv(x)``, where `x` is some fluorescence value in RFI and `y` is the same fluorescence expressed in MEF units. beads_model : function Fluorescence model of calibration beads. This function has the signature ``y = beads_model(x)``, where `x` is the fluorescence of some bead population in RFI units and `y` is the same fluorescence expressed in MEF units, without autofluorescence. beads_params : array Fitted parameters of the bead fluorescence model: ``[m, b, fl_mef_auto]``. beads_model_str : str String representation of the beads model used. beads_params_names : list of str Names of the parameters in a list, in the same order as they are given in `beads_params`. Notes ----- The following model is used to describe bead fluorescence:: m*log(fl_rfi[i]) + b = log(fl_mef_auto + fl_mef[i]) where ``fl_rfi[i]`` is the fluorescence of bead subpopulation ``i`` in RFI units and ``fl_mef[i]`` is the corresponding fluorescence in MEF units. The model includes 3 parameters: ``m`` (slope), ``b`` (intercept), and ``fl_mef_auto`` (bead autofluorescence). The last term is constrained to be greater or equal to zero. The bead fluorescence model is fit in log space using nonlinear least squares regression. In our experience, fitting in log space weights the residuals more evenly, whereas fitting in linear space vastly overvalues the brighter beads. A standard curve is constructed by solving for ``fl_mef``. As cell samples may not have the same autofluorescence as beads, the bead autofluorescence term (``fl_mef_auto``) is omitted from the standard curve; the user is expected to use an appropriate white cell sample to account for cellular autofluorescence if necessary. The returned standard curve mapping fluorescence in RFI units to MEF units is thus of the following form:: fl_mef = exp(m*log(fl_rfi) + b) This is equivalent to:: fl_mef = exp(b) * (fl_rfi**m) This works for positive ``fl_rfi`` values, but it is undefined for ``fl_rfi < 0`` and non-integer ``m`` (general case). To extend this standard curve to negative values of ``fl_rfi``, we define ``s(fl_rfi)`` to be equal to the standard curve above when ``fl_rfi >= 0``. Next, we require this function to be odd, that is, ``s(fl_rfi) = - s(-fl_rfi)``. This extends the domain to negative ``fl_rfi`` values and results in ``s(fl_rfi) < 0`` for any negative ``fl_rfi``. Finally, we make ``fl_mef = s(fl_rfi)`` our new standard curve. In this way,:: s(fl_rfi) = exp(b) * ( fl_rfi **m), fl_rfi >= 0 - exp(b) * ((-fl_rfi)**m), fl_rfi < 0 This satisfies the definition of an odd function. In addition, ``s(0) = 0``, and ``s(fl_rfi)`` converges to zero when ``fl_rfi -> 0`` from both sides. Therefore, the function is continuous at ``fl_rfi = 0``. The definition of ``s(fl_rfi)`` can be expressed more conveniently as:: s(fl_rfi) = sign(fl_rfi) * exp(b) * (abs(fl_rfi)**m) This is the equation implemented.
[ "Fit", "a", "standard", "curve", "using", "a", "beads", "model", "with", "autofluorescence", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/mef.py#L339-L485
train
35,325
taborlab/FlowCal
FlowCal/mef.py
plot_standard_curve
def plot_standard_curve(fl_rfi, fl_mef, beads_model, std_crv, xscale='linear', yscale='linear', xlim=None, ylim=(1.,1e8)): """ Plot a standard curve with fluorescence of calibration beads. Parameters ---------- fl_rfi : array_like Fluorescence of the calibration beads' subpopulations, in RFI units. fl_mef : array_like Fluorescence of the calibration beads' subpopulations, in MEF units. beads_model : function Fluorescence model of the calibration beads. std_crv : function The standard curve, mapping relative fluorescence (RFI) units to MEF units. Other Parameters ---------------- xscale : str, optional Scale of the x axis, either ``linear`` or ``log``. yscale : str, optional Scale of the y axis, either ``linear`` or ``log``. xlim : tuple, optional Limits for the x axis. ylim : tuple, optional Limits for the y axis. """ # Plot fluorescence of beads populations plt.plot(fl_rfi, fl_mef, 'o', label='Beads', color=standard_curve_colors[0]) # Generate points in x axis to plot beads model and standard curve. if xlim is None: xlim = plt.xlim() if xscale=='linear': xdata = np.linspace(xlim[0], xlim[1], 200) elif xscale=='log': xdata = np.logspace(np.log10(xlim[0]), np.log10(xlim[1]), 200) # Plot beads model and standard curve plt.plot(xdata, beads_model(xdata), label='Beads model', color=standard_curve_colors[1]) plt.plot(xdata, std_crv(xdata), label='Standard curve', color=standard_curve_colors[2]) plt.xscale(xscale) plt.yscale(yscale) plt.xlim(xlim) plt.ylim(ylim) plt.grid(True) plt.legend(loc = 'best')
python
def plot_standard_curve(fl_rfi, fl_mef, beads_model, std_crv, xscale='linear', yscale='linear', xlim=None, ylim=(1.,1e8)): """ Plot a standard curve with fluorescence of calibration beads. Parameters ---------- fl_rfi : array_like Fluorescence of the calibration beads' subpopulations, in RFI units. fl_mef : array_like Fluorescence of the calibration beads' subpopulations, in MEF units. beads_model : function Fluorescence model of the calibration beads. std_crv : function The standard curve, mapping relative fluorescence (RFI) units to MEF units. Other Parameters ---------------- xscale : str, optional Scale of the x axis, either ``linear`` or ``log``. yscale : str, optional Scale of the y axis, either ``linear`` or ``log``. xlim : tuple, optional Limits for the x axis. ylim : tuple, optional Limits for the y axis. """ # Plot fluorescence of beads populations plt.plot(fl_rfi, fl_mef, 'o', label='Beads', color=standard_curve_colors[0]) # Generate points in x axis to plot beads model and standard curve. if xlim is None: xlim = plt.xlim() if xscale=='linear': xdata = np.linspace(xlim[0], xlim[1], 200) elif xscale=='log': xdata = np.logspace(np.log10(xlim[0]), np.log10(xlim[1]), 200) # Plot beads model and standard curve plt.plot(xdata, beads_model(xdata), label='Beads model', color=standard_curve_colors[1]) plt.plot(xdata, std_crv(xdata), label='Standard curve', color=standard_curve_colors[2]) plt.xscale(xscale) plt.yscale(yscale) plt.xlim(xlim) plt.ylim(ylim) plt.grid(True) plt.legend(loc = 'best')
[ "def", "plot_standard_curve", "(", "fl_rfi", ",", "fl_mef", ",", "beads_model", ",", "std_crv", ",", "xscale", "=", "'linear'", ",", "yscale", "=", "'linear'", ",", "xlim", "=", "None", ",", "ylim", "=", "(", "1.", ",", "1e8", ")", ")", ":", "# Plot fl...
Plot a standard curve with fluorescence of calibration beads. Parameters ---------- fl_rfi : array_like Fluorescence of the calibration beads' subpopulations, in RFI units. fl_mef : array_like Fluorescence of the calibration beads' subpopulations, in MEF units. beads_model : function Fluorescence model of the calibration beads. std_crv : function The standard curve, mapping relative fluorescence (RFI) units to MEF units. Other Parameters ---------------- xscale : str, optional Scale of the x axis, either ``linear`` or ``log``. yscale : str, optional Scale of the y axis, either ``linear`` or ``log``. xlim : tuple, optional Limits for the x axis. ylim : tuple, optional Limits for the y axis.
[ "Plot", "a", "standard", "curve", "with", "fluorescence", "of", "calibration", "beads", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/mef.py#L487-L554
train
35,326
taborlab/FlowCal
FlowCal/excel_ui.py
read_table
def read_table(filename, sheetname, index_col=None): """ Return the contents of an Excel table as a pandas DataFrame. Parameters ---------- filename : str Name of the Excel file to read. sheetname : str or int Name or index of the sheet inside the Excel file to read. index_col : str, optional Column name or index to be used as row labels of the DataFrame. If None, default index will be used. Returns ------- table : DataFrame A DataFrame containing the data in the specified Excel table. If `index_col` is not None, rows in which their `index_col` field is empty will not be present in `table`. Raises ------ ValueError If `index_col` is specified and two rows contain the same `index_col` field. """ # Catch sheetname as list or None if sheetname is None or \ (hasattr(sheetname, '__iter__') \ and not isinstance(sheetname, six.string_types)): raise TypeError("sheetname should specify a single sheet") # Load excel table using pandas # Parameter specifying sheet name is slightly different depending on pandas' # version. if packaging.version.parse(pd.__version__) \ < packaging.version.parse('0.21'): table = pd.read_excel(filename, sheetname=sheetname, index_col=index_col) else: table = pd.read_excel(filename, sheet_name=sheetname, index_col=index_col) # Eliminate rows whose index are null if index_col is not None: table = table[pd.notnull(table.index)] # Check for duplicated rows if table.index.has_duplicates: raise ValueError("sheet {} on file {} contains duplicated values " "for column {}".format(sheetname, filename, index_col)) return table
python
def read_table(filename, sheetname, index_col=None): """ Return the contents of an Excel table as a pandas DataFrame. Parameters ---------- filename : str Name of the Excel file to read. sheetname : str or int Name or index of the sheet inside the Excel file to read. index_col : str, optional Column name or index to be used as row labels of the DataFrame. If None, default index will be used. Returns ------- table : DataFrame A DataFrame containing the data in the specified Excel table. If `index_col` is not None, rows in which their `index_col` field is empty will not be present in `table`. Raises ------ ValueError If `index_col` is specified and two rows contain the same `index_col` field. """ # Catch sheetname as list or None if sheetname is None or \ (hasattr(sheetname, '__iter__') \ and not isinstance(sheetname, six.string_types)): raise TypeError("sheetname should specify a single sheet") # Load excel table using pandas # Parameter specifying sheet name is slightly different depending on pandas' # version. if packaging.version.parse(pd.__version__) \ < packaging.version.parse('0.21'): table = pd.read_excel(filename, sheetname=sheetname, index_col=index_col) else: table = pd.read_excel(filename, sheet_name=sheetname, index_col=index_col) # Eliminate rows whose index are null if index_col is not None: table = table[pd.notnull(table.index)] # Check for duplicated rows if table.index.has_duplicates: raise ValueError("sheet {} on file {} contains duplicated values " "for column {}".format(sheetname, filename, index_col)) return table
[ "def", "read_table", "(", "filename", ",", "sheetname", ",", "index_col", "=", "None", ")", ":", "# Catch sheetname as list or None", "if", "sheetname", "is", "None", "or", "(", "hasattr", "(", "sheetname", ",", "'__iter__'", ")", "and", "not", "isinstance", "...
Return the contents of an Excel table as a pandas DataFrame. Parameters ---------- filename : str Name of the Excel file to read. sheetname : str or int Name or index of the sheet inside the Excel file to read. index_col : str, optional Column name or index to be used as row labels of the DataFrame. If None, default index will be used. Returns ------- table : DataFrame A DataFrame containing the data in the specified Excel table. If `index_col` is not None, rows in which their `index_col` field is empty will not be present in `table`. Raises ------ ValueError If `index_col` is specified and two rows contain the same `index_col` field.
[ "Return", "the", "contents", "of", "an", "Excel", "table", "as", "a", "pandas", "DataFrame", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/excel_ui.py#L118-L172
train
35,327
taborlab/FlowCal
FlowCal/excel_ui.py
write_workbook
def write_workbook(filename, table_list, column_width=None): """ Write an Excel workbook from a list of tables. Parameters ---------- filename : str Name of the Excel file to write. table_list : list of ``(str, DataFrame)`` tuples Tables to be saved as individual sheets in the Excel table. Each tuple contains two values: the name of the sheet to be saved as a string, and the contents of the table as a DataFrame. column_width: int, optional The column width to use when saving the spreadsheet. If None, calculate width automatically from the maximum number of characters in each column. """ # Modify default header format # Pandas' default header format is bold text with thin borders. Here we # use bold text only, without borders. # The header style structure is in pd.core.format in pandas<=0.18.0, # pd.formats.format in 0.18.1<=pandas<0.20, and pd.io.formats.excel in # pandas>=0.20. # Also, wrap in a try-except block in case style structure is not found. format_module_found = False try: # Get format module if packaging.version.parse(pd.__version__) \ <= packaging.version.parse('0.18'): format_module = pd.core.format elif packaging.version.parse(pd.__version__) \ < packaging.version.parse('0.20'): format_module = pd.formats.format else: import pandas.io.formats.excel as format_module # Save previous style, replace, and indicate that previous style should # be restored at the end old_header_style = format_module.header_style format_module.header_style = {"font": {"bold": True}} format_module_found = True except AttributeError as e: pass # Generate output writer object writer = pd.ExcelWriter(filename, engine='xlsxwriter') # Write tables for sheet_name, df in table_list: # Convert index names to regular columns df = df.reset_index() # Write to an Excel sheet df.to_excel(writer, sheet_name=sheet_name, index=False) # Set column width if column_width is None: for i, (col_name, column) in enumerate(six.iteritems(df)): # Get the maximum number of characters in a column max_chars_col = column.astype(str).str.len().max() max_chars_col = max(len(col_name), max_chars_col) # Write width writer.sheets[sheet_name].set_column( i, i, width=1.*max_chars_col) else: writer.sheets[sheet_name].set_column( 0, len(df.columns) - 1, width=column_width) # Write excel file writer.save() # Restore previous header format if format_module_found: format_module.header_style = old_header_style
python
def write_workbook(filename, table_list, column_width=None): """ Write an Excel workbook from a list of tables. Parameters ---------- filename : str Name of the Excel file to write. table_list : list of ``(str, DataFrame)`` tuples Tables to be saved as individual sheets in the Excel table. Each tuple contains two values: the name of the sheet to be saved as a string, and the contents of the table as a DataFrame. column_width: int, optional The column width to use when saving the spreadsheet. If None, calculate width automatically from the maximum number of characters in each column. """ # Modify default header format # Pandas' default header format is bold text with thin borders. Here we # use bold text only, without borders. # The header style structure is in pd.core.format in pandas<=0.18.0, # pd.formats.format in 0.18.1<=pandas<0.20, and pd.io.formats.excel in # pandas>=0.20. # Also, wrap in a try-except block in case style structure is not found. format_module_found = False try: # Get format module if packaging.version.parse(pd.__version__) \ <= packaging.version.parse('0.18'): format_module = pd.core.format elif packaging.version.parse(pd.__version__) \ < packaging.version.parse('0.20'): format_module = pd.formats.format else: import pandas.io.formats.excel as format_module # Save previous style, replace, and indicate that previous style should # be restored at the end old_header_style = format_module.header_style format_module.header_style = {"font": {"bold": True}} format_module_found = True except AttributeError as e: pass # Generate output writer object writer = pd.ExcelWriter(filename, engine='xlsxwriter') # Write tables for sheet_name, df in table_list: # Convert index names to regular columns df = df.reset_index() # Write to an Excel sheet df.to_excel(writer, sheet_name=sheet_name, index=False) # Set column width if column_width is None: for i, (col_name, column) in enumerate(six.iteritems(df)): # Get the maximum number of characters in a column max_chars_col = column.astype(str).str.len().max() max_chars_col = max(len(col_name), max_chars_col) # Write width writer.sheets[sheet_name].set_column( i, i, width=1.*max_chars_col) else: writer.sheets[sheet_name].set_column( 0, len(df.columns) - 1, width=column_width) # Write excel file writer.save() # Restore previous header format if format_module_found: format_module.header_style = old_header_style
[ "def", "write_workbook", "(", "filename", ",", "table_list", ",", "column_width", "=", "None", ")", ":", "# Modify default header format", "# Pandas' default header format is bold text with thin borders. Here we", "# use bold text only, without borders.", "# The header style structure ...
Write an Excel workbook from a list of tables. Parameters ---------- filename : str Name of the Excel file to write. table_list : list of ``(str, DataFrame)`` tuples Tables to be saved as individual sheets in the Excel table. Each tuple contains two values: the name of the sheet to be saved as a string, and the contents of the table as a DataFrame. column_width: int, optional The column width to use when saving the spreadsheet. If None, calculate width automatically from the maximum number of characters in each column.
[ "Write", "an", "Excel", "workbook", "from", "a", "list", "of", "tables", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/excel_ui.py#L174-L249
train
35,328
taborlab/FlowCal
FlowCal/excel_ui.py
generate_histograms_table
def generate_histograms_table(samples_table, samples, max_bins=1024): """ Generate a table of histograms as a DataFrame. Parameters ---------- samples_table : DataFrame Table specifying samples to analyze. For more information about the fields required in this table, please consult the module's documentation. samples : list FCSData objects from which to calculate histograms. ``samples[i]`` should correspond to ``samples_table.iloc[i]`` max_bins : int, optional Maximum number of bins to use. Returns ------- hist_table : DataFrame A multi-indexed DataFrame. Rows cotain the histogram bins and counts for every sample and channel specified in samples_table. `hist_table` is indexed by the sample's ID, the channel name, and whether the row corresponds to bins or counts. """ # Extract channels that require stats histograms headers = list(samples_table.columns) hist_headers = [h for h in headers if re_units.match(h)] hist_channels = [re_units.match(h).group(1) for h in hist_headers] # The number of columns in the DataFrame has to be set to the maximum # number of bins of any of the histograms about to be generated. # The following iterates through these histograms and finds the # largest. n_columns = 0 for sample_id, sample in zip(samples_table.index, samples): if isinstance(sample, ExcelUIException): continue for header, channel in zip(hist_headers, hist_channels): if pd.notnull(samples_table[header][sample_id]): if n_columns < sample.resolution(channel): n_columns = sample.resolution(channel) # Saturate at max_bins if n_columns > max_bins: n_columns = max_bins # Declare multi-indexed DataFrame index = pd.MultiIndex.from_arrays([[],[],[]], names = ['Sample ID', 'Channel', '']) columns = ['Bin {}'.format(i + 1) for i in range(n_columns)] hist_table = pd.DataFrame([], index=index, columns=columns) # Generate histograms for sample_id, sample in zip(samples_table.index, samples): if isinstance(sample, ExcelUIException): continue for header, channel in zip(hist_headers, hist_channels): if pd.notnull(samples_table[header][sample_id]): # Get units in which bins are being reported unit = samples_table[header][sample_id] # Decide which scale to use # Channel units result in linear scale. Otherwise, use logicle. if unit == 'Channel': scale = 'linear' else: scale = 'logicle' # Define number of bins nbins = min(sample.resolution(channel), max_bins) # Calculate bin edges and centers # We generate twice the necessary number of bins. We then take # every other value as the proper bin edges, and the remaining # values as the bin centers. bins_extended = sample.hist_bins(channel, 2*nbins, scale) bin_edges = bins_extended[::2] bin_centers = bins_extended[1::2] # Store bin centers hist_table.loc[(sample_id, channel, 'Bin Centers ({})'.format(unit)), columns[0:len(bin_centers)]] = bin_centers # Calculate and store histogram counts hist, __ = np.histogram(sample[:,channel], bins=bin_edges) hist_table.loc[(sample_id, channel, 'Counts'), columns[0:len(bin_centers)]] = hist return hist_table
python
def generate_histograms_table(samples_table, samples, max_bins=1024): """ Generate a table of histograms as a DataFrame. Parameters ---------- samples_table : DataFrame Table specifying samples to analyze. For more information about the fields required in this table, please consult the module's documentation. samples : list FCSData objects from which to calculate histograms. ``samples[i]`` should correspond to ``samples_table.iloc[i]`` max_bins : int, optional Maximum number of bins to use. Returns ------- hist_table : DataFrame A multi-indexed DataFrame. Rows cotain the histogram bins and counts for every sample and channel specified in samples_table. `hist_table` is indexed by the sample's ID, the channel name, and whether the row corresponds to bins or counts. """ # Extract channels that require stats histograms headers = list(samples_table.columns) hist_headers = [h for h in headers if re_units.match(h)] hist_channels = [re_units.match(h).group(1) for h in hist_headers] # The number of columns in the DataFrame has to be set to the maximum # number of bins of any of the histograms about to be generated. # The following iterates through these histograms and finds the # largest. n_columns = 0 for sample_id, sample in zip(samples_table.index, samples): if isinstance(sample, ExcelUIException): continue for header, channel in zip(hist_headers, hist_channels): if pd.notnull(samples_table[header][sample_id]): if n_columns < sample.resolution(channel): n_columns = sample.resolution(channel) # Saturate at max_bins if n_columns > max_bins: n_columns = max_bins # Declare multi-indexed DataFrame index = pd.MultiIndex.from_arrays([[],[],[]], names = ['Sample ID', 'Channel', '']) columns = ['Bin {}'.format(i + 1) for i in range(n_columns)] hist_table = pd.DataFrame([], index=index, columns=columns) # Generate histograms for sample_id, sample in zip(samples_table.index, samples): if isinstance(sample, ExcelUIException): continue for header, channel in zip(hist_headers, hist_channels): if pd.notnull(samples_table[header][sample_id]): # Get units in which bins are being reported unit = samples_table[header][sample_id] # Decide which scale to use # Channel units result in linear scale. Otherwise, use logicle. if unit == 'Channel': scale = 'linear' else: scale = 'logicle' # Define number of bins nbins = min(sample.resolution(channel), max_bins) # Calculate bin edges and centers # We generate twice the necessary number of bins. We then take # every other value as the proper bin edges, and the remaining # values as the bin centers. bins_extended = sample.hist_bins(channel, 2*nbins, scale) bin_edges = bins_extended[::2] bin_centers = bins_extended[1::2] # Store bin centers hist_table.loc[(sample_id, channel, 'Bin Centers ({})'.format(unit)), columns[0:len(bin_centers)]] = bin_centers # Calculate and store histogram counts hist, __ = np.histogram(sample[:,channel], bins=bin_edges) hist_table.loc[(sample_id, channel, 'Counts'), columns[0:len(bin_centers)]] = hist return hist_table
[ "def", "generate_histograms_table", "(", "samples_table", ",", "samples", ",", "max_bins", "=", "1024", ")", ":", "# Extract channels that require stats histograms", "headers", "=", "list", "(", "samples_table", ".", "columns", ")", "hist_headers", "=", "[", "h", "f...
Generate a table of histograms as a DataFrame. Parameters ---------- samples_table : DataFrame Table specifying samples to analyze. For more information about the fields required in this table, please consult the module's documentation. samples : list FCSData objects from which to calculate histograms. ``samples[i]`` should correspond to ``samples_table.iloc[i]`` max_bins : int, optional Maximum number of bins to use. Returns ------- hist_table : DataFrame A multi-indexed DataFrame. Rows cotain the histogram bins and counts for every sample and channel specified in samples_table. `hist_table` is indexed by the sample's ID, the channel name, and whether the row corresponds to bins or counts.
[ "Generate", "a", "table", "of", "histograms", "as", "a", "DataFrame", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/excel_ui.py#L1309-L1394
train
35,329
taborlab/FlowCal
FlowCal/excel_ui.py
generate_about_table
def generate_about_table(extra_info={}): """ Make a table with information about FlowCal and the current analysis. Parameters ---------- extra_info : dict, optional Additional keyword:value pairs to include in the table. Returns ------- about_table : DataFrame Table with information about FlowCal and the current analysis, as keyword:value pairs. The following keywords are included: FlowCal version, and date and time of analysis. Keywords and values from `extra_info` are also included. """ # Make keyword and value arrays keywords = [] values = [] # FlowCal version keywords.append('FlowCal version') values.append(FlowCal.__version__) # Analysis date and time keywords.append('Date of analysis') values.append(time.strftime("%Y/%m/%d")) keywords.append('Time of analysis') values.append(time.strftime("%I:%M:%S%p")) # Add additional keyword:value pairs for k, v in six.iteritems(extra_info): keywords.append(k) values.append(v) # Make table as data frame about_table = pd.DataFrame(values, index=keywords) # Set column names about_table.columns = ['Value'] about_table.index.name = 'Keyword' return about_table
python
def generate_about_table(extra_info={}): """ Make a table with information about FlowCal and the current analysis. Parameters ---------- extra_info : dict, optional Additional keyword:value pairs to include in the table. Returns ------- about_table : DataFrame Table with information about FlowCal and the current analysis, as keyword:value pairs. The following keywords are included: FlowCal version, and date and time of analysis. Keywords and values from `extra_info` are also included. """ # Make keyword and value arrays keywords = [] values = [] # FlowCal version keywords.append('FlowCal version') values.append(FlowCal.__version__) # Analysis date and time keywords.append('Date of analysis') values.append(time.strftime("%Y/%m/%d")) keywords.append('Time of analysis') values.append(time.strftime("%I:%M:%S%p")) # Add additional keyword:value pairs for k, v in six.iteritems(extra_info): keywords.append(k) values.append(v) # Make table as data frame about_table = pd.DataFrame(values, index=keywords) # Set column names about_table.columns = ['Value'] about_table.index.name = 'Keyword' return about_table
[ "def", "generate_about_table", "(", "extra_info", "=", "{", "}", ")", ":", "# Make keyword and value arrays", "keywords", "=", "[", "]", "values", "=", "[", "]", "# FlowCal version", "keywords", ".", "append", "(", "'FlowCal version'", ")", "values", ".", "appen...
Make a table with information about FlowCal and the current analysis. Parameters ---------- extra_info : dict, optional Additional keyword:value pairs to include in the table. Returns ------- about_table : DataFrame Table with information about FlowCal and the current analysis, as keyword:value pairs. The following keywords are included: FlowCal version, and date and time of analysis. Keywords and values from `extra_info` are also included.
[ "Make", "a", "table", "with", "information", "about", "FlowCal", "and", "the", "current", "analysis", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/excel_ui.py#L1396-L1437
train
35,330
taborlab/FlowCal
FlowCal/excel_ui.py
show_open_file_dialog
def show_open_file_dialog(filetypes): """ Show an open file dialog and return the path of the file selected. Parameters ---------- filetypes : list of tuples Types of file to show on the dialog. Each tuple on the list must have two elements associated with a filetype: the first element is a description, and the second is the associated extension. Returns ------- filename : str The path of the filename selected, or an empty string if no file was chosen. """ # The following line is used to Tk's main window is not shown Tk().withdraw() # OSX ONLY: Call bash script to prevent file select window from sticking # after use. if platform.system() == 'Darwin': subprocess.call("defaults write org.python.python " + "ApplePersistenceIgnoreState YES", shell=True) filename = askopenfilename(filetypes=filetypes) subprocess.call("defaults write org.python.python " + "ApplePersistenceIgnoreState NO", shell=True) else: filename = askopenfilename(filetypes=filetypes) return filename
python
def show_open_file_dialog(filetypes): """ Show an open file dialog and return the path of the file selected. Parameters ---------- filetypes : list of tuples Types of file to show on the dialog. Each tuple on the list must have two elements associated with a filetype: the first element is a description, and the second is the associated extension. Returns ------- filename : str The path of the filename selected, or an empty string if no file was chosen. """ # The following line is used to Tk's main window is not shown Tk().withdraw() # OSX ONLY: Call bash script to prevent file select window from sticking # after use. if platform.system() == 'Darwin': subprocess.call("defaults write org.python.python " + "ApplePersistenceIgnoreState YES", shell=True) filename = askopenfilename(filetypes=filetypes) subprocess.call("defaults write org.python.python " + "ApplePersistenceIgnoreState NO", shell=True) else: filename = askopenfilename(filetypes=filetypes) return filename
[ "def", "show_open_file_dialog", "(", "filetypes", ")", ":", "# The following line is used to Tk's main window is not shown", "Tk", "(", ")", ".", "withdraw", "(", ")", "# OSX ONLY: Call bash script to prevent file select window from sticking", "# after use.", "if", "platform", "....
Show an open file dialog and return the path of the file selected. Parameters ---------- filetypes : list of tuples Types of file to show on the dialog. Each tuple on the list must have two elements associated with a filetype: the first element is a description, and the second is the associated extension. Returns ------- filename : str The path of the filename selected, or an empty string if no file was chosen.
[ "Show", "an", "open", "file", "dialog", "and", "return", "the", "path", "of", "the", "file", "selected", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/excel_ui.py#L1439-L1471
train
35,331
taborlab/FlowCal
FlowCal/excel_ui.py
run
def run(input_path=None, output_path=None, verbose=True, plot=True, hist_sheet=False): """ Run the MS Excel User Interface. This function performs the following: 1. If `input_path` is not specified, show a dialog to choose an input Excel file. 2. Extract data from the Instruments, Beads, and Samples tables. 3. Process all the bead samples specified in the Beads table. 4. Generate statistics for each bead sample. 5. Process all the cell samples in the Samples table. 6. Generate statistics for each sample. 7. If requested, generate a histogram table for each fluorescent channel specified for each sample. 8. Generate a table with run time, date, FlowCal version, among others. 9. Save statistics and (if requested) histograms in an output Excel file. Parameters ---------- input_path : str Path to the Excel file to use as input. If None, show a dialog to select an input file. output_path : str Path to which to save the output Excel file. If None, use "<input_path>_output". verbose : bool, optional Whether to print information messages during the execution of this function. plot : bool, optional Whether to generate and save density/histogram plots of each sample, and each beads sample. hist_sheet : bool, optional Whether to generate a sheet in the output Excel file specifying histogram bin information. """ # If input file has not been specified, show open file dialog if input_path is None: input_path = show_open_file_dialog(filetypes=[('Excel files', '*.xlsx')]) if not input_path: if verbose: print("No input file selected.") return # Extract directory, filename, and filename with no extension from path input_dir, input_filename = os.path.split(input_path) input_filename_no_ext, __ = os.path.splitext(input_filename) # Read relevant tables from workbook if verbose: print("Reading {}...".format(input_filename)) instruments_table = read_table(input_path, sheetname='Instruments', index_col='ID') beads_table = read_table(input_path, sheetname='Beads', index_col='ID') samples_table = read_table(input_path, sheetname='Samples', index_col='ID') # Process beads samples beads_samples, mef_transform_fxns, mef_outputs = process_beads_table( beads_table, instruments_table, base_dir=input_dir, verbose=verbose, plot=plot, plot_dir='plot_beads', full_output=True) # Add stats to beads table if verbose: print("") print("Calculating statistics for beads...") add_beads_stats(beads_table, beads_samples, mef_outputs) # Process samples samples = process_samples_table( samples_table, instruments_table, mef_transform_fxns=mef_transform_fxns, beads_table=beads_table, base_dir=input_dir, verbose=verbose, plot=plot, plot_dir='plot_samples') # Add stats to samples table if verbose: print("") print("Calculating statistics for all samples...") add_samples_stats(samples_table, samples) # Generate histograms if hist_sheet: if verbose: print("Generating histograms table...") histograms_table = generate_histograms_table(samples_table, samples) # Generate about table about_table = generate_about_table({'Input file path': input_path}) # Generate list of tables to save table_list = [] table_list.append(('Instruments', instruments_table)) table_list.append(('Beads', beads_table)) table_list.append(('Samples', samples_table)) if hist_sheet: table_list.append(('Histograms', histograms_table)) table_list.append(('About Analysis', about_table)) # Write output excel file if verbose: print("Saving output Excel file...") if output_path is None: output_filename = "{}_output.xlsx".format(input_filename_no_ext) output_path = os.path.join(input_dir, output_filename) write_workbook(output_path, table_list) if verbose: print("\nDone.")
python
def run(input_path=None, output_path=None, verbose=True, plot=True, hist_sheet=False): """ Run the MS Excel User Interface. This function performs the following: 1. If `input_path` is not specified, show a dialog to choose an input Excel file. 2. Extract data from the Instruments, Beads, and Samples tables. 3. Process all the bead samples specified in the Beads table. 4. Generate statistics for each bead sample. 5. Process all the cell samples in the Samples table. 6. Generate statistics for each sample. 7. If requested, generate a histogram table for each fluorescent channel specified for each sample. 8. Generate a table with run time, date, FlowCal version, among others. 9. Save statistics and (if requested) histograms in an output Excel file. Parameters ---------- input_path : str Path to the Excel file to use as input. If None, show a dialog to select an input file. output_path : str Path to which to save the output Excel file. If None, use "<input_path>_output". verbose : bool, optional Whether to print information messages during the execution of this function. plot : bool, optional Whether to generate and save density/histogram plots of each sample, and each beads sample. hist_sheet : bool, optional Whether to generate a sheet in the output Excel file specifying histogram bin information. """ # If input file has not been specified, show open file dialog if input_path is None: input_path = show_open_file_dialog(filetypes=[('Excel files', '*.xlsx')]) if not input_path: if verbose: print("No input file selected.") return # Extract directory, filename, and filename with no extension from path input_dir, input_filename = os.path.split(input_path) input_filename_no_ext, __ = os.path.splitext(input_filename) # Read relevant tables from workbook if verbose: print("Reading {}...".format(input_filename)) instruments_table = read_table(input_path, sheetname='Instruments', index_col='ID') beads_table = read_table(input_path, sheetname='Beads', index_col='ID') samples_table = read_table(input_path, sheetname='Samples', index_col='ID') # Process beads samples beads_samples, mef_transform_fxns, mef_outputs = process_beads_table( beads_table, instruments_table, base_dir=input_dir, verbose=verbose, plot=plot, plot_dir='plot_beads', full_output=True) # Add stats to beads table if verbose: print("") print("Calculating statistics for beads...") add_beads_stats(beads_table, beads_samples, mef_outputs) # Process samples samples = process_samples_table( samples_table, instruments_table, mef_transform_fxns=mef_transform_fxns, beads_table=beads_table, base_dir=input_dir, verbose=verbose, plot=plot, plot_dir='plot_samples') # Add stats to samples table if verbose: print("") print("Calculating statistics for all samples...") add_samples_stats(samples_table, samples) # Generate histograms if hist_sheet: if verbose: print("Generating histograms table...") histograms_table = generate_histograms_table(samples_table, samples) # Generate about table about_table = generate_about_table({'Input file path': input_path}) # Generate list of tables to save table_list = [] table_list.append(('Instruments', instruments_table)) table_list.append(('Beads', beads_table)) table_list.append(('Samples', samples_table)) if hist_sheet: table_list.append(('Histograms', histograms_table)) table_list.append(('About Analysis', about_table)) # Write output excel file if verbose: print("Saving output Excel file...") if output_path is None: output_filename = "{}_output.xlsx".format(input_filename_no_ext) output_path = os.path.join(input_dir, output_filename) write_workbook(output_path, table_list) if verbose: print("\nDone.")
[ "def", "run", "(", "input_path", "=", "None", ",", "output_path", "=", "None", ",", "verbose", "=", "True", ",", "plot", "=", "True", ",", "hist_sheet", "=", "False", ")", ":", "# If input file has not been specified, show open file dialog", "if", "input_path", ...
Run the MS Excel User Interface. This function performs the following: 1. If `input_path` is not specified, show a dialog to choose an input Excel file. 2. Extract data from the Instruments, Beads, and Samples tables. 3. Process all the bead samples specified in the Beads table. 4. Generate statistics for each bead sample. 5. Process all the cell samples in the Samples table. 6. Generate statistics for each sample. 7. If requested, generate a histogram table for each fluorescent channel specified for each sample. 8. Generate a table with run time, date, FlowCal version, among others. 9. Save statistics and (if requested) histograms in an output Excel file. Parameters ---------- input_path : str Path to the Excel file to use as input. If None, show a dialog to select an input file. output_path : str Path to which to save the output Excel file. If None, use "<input_path>_output". verbose : bool, optional Whether to print information messages during the execution of this function. plot : bool, optional Whether to generate and save density/histogram plots of each sample, and each beads sample. hist_sheet : bool, optional Whether to generate a sheet in the output Excel file specifying histogram bin information.
[ "Run", "the", "MS", "Excel", "User", "Interface", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/excel_ui.py#L1473-L1602
train
35,332
taborlab/FlowCal
FlowCal/excel_ui.py
run_command_line
def run_command_line(args=None): """ Entry point for the FlowCal and flowcal console scripts. Parameters ---------- args: list of strings, optional Command line arguments. If None or not specified, get arguments from ``sys.argv``. See Also ---------- FlowCal.excel_ui.run() http://amir.rachum.com/blog/2017/07/28/python-entry-points/ """ # Get arguments from ``sys.argv`` if necessary. # ``sys.argv`` has the name of the script as its first element. We remove # this element because it will break ``parser.parse_args()`` later. In fact, # ``parser.parse_args()``, if provided with no arguments, will also use # ``sys.argv`` after removing the first element. if args is None: args = sys.argv[1:] import argparse # Read command line arguments parser = argparse.ArgumentParser( description="process flow cytometry files with FlowCal's Excel UI.") parser.add_argument( "-i", "--inputpath", type=str, nargs='?', help="input Excel file name. If not specified, show open file window") parser.add_argument( "-o", "--outputpath", type=str, nargs='?', help="output Excel file name. If not specified, use [INPUTPATH]_output") parser.add_argument( "-v", "--verbose", action="store_true", help="print information about individual processing steps") parser.add_argument( "-p", "--plot", action="store_true", help="generate and save density plots/histograms of beads and samples") parser.add_argument( "-H", "--histogram-sheet", action="store_true", help="generate sheet in output Excel file specifying histogram bins") args = parser.parse_args(args=args) # Run Excel UI run(input_path=args.inputpath, output_path=args.outputpath, verbose=args.verbose, plot=args.plot, hist_sheet=args.histogram_sheet)
python
def run_command_line(args=None): """ Entry point for the FlowCal and flowcal console scripts. Parameters ---------- args: list of strings, optional Command line arguments. If None or not specified, get arguments from ``sys.argv``. See Also ---------- FlowCal.excel_ui.run() http://amir.rachum.com/blog/2017/07/28/python-entry-points/ """ # Get arguments from ``sys.argv`` if necessary. # ``sys.argv`` has the name of the script as its first element. We remove # this element because it will break ``parser.parse_args()`` later. In fact, # ``parser.parse_args()``, if provided with no arguments, will also use # ``sys.argv`` after removing the first element. if args is None: args = sys.argv[1:] import argparse # Read command line arguments parser = argparse.ArgumentParser( description="process flow cytometry files with FlowCal's Excel UI.") parser.add_argument( "-i", "--inputpath", type=str, nargs='?', help="input Excel file name. If not specified, show open file window") parser.add_argument( "-o", "--outputpath", type=str, nargs='?', help="output Excel file name. If not specified, use [INPUTPATH]_output") parser.add_argument( "-v", "--verbose", action="store_true", help="print information about individual processing steps") parser.add_argument( "-p", "--plot", action="store_true", help="generate and save density plots/histograms of beads and samples") parser.add_argument( "-H", "--histogram-sheet", action="store_true", help="generate sheet in output Excel file specifying histogram bins") args = parser.parse_args(args=args) # Run Excel UI run(input_path=args.inputpath, output_path=args.outputpath, verbose=args.verbose, plot=args.plot, hist_sheet=args.histogram_sheet)
[ "def", "run_command_line", "(", "args", "=", "None", ")", ":", "# Get arguments from ``sys.argv`` if necessary.", "# ``sys.argv`` has the name of the script as its first element. We remove", "# this element because it will break ``parser.parse_args()`` later. In fact,", "# ``parser.parse_args(...
Entry point for the FlowCal and flowcal console scripts. Parameters ---------- args: list of strings, optional Command line arguments. If None or not specified, get arguments from ``sys.argv``. See Also ---------- FlowCal.excel_ui.run() http://amir.rachum.com/blog/2017/07/28/python-entry-points/
[ "Entry", "point", "for", "the", "FlowCal", "and", "flowcal", "console", "scripts", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/excel_ui.py#L1605-L1668
train
35,333
taborlab/FlowCal
FlowCal/io.py
read_fcs_header_segment
def read_fcs_header_segment(buf, begin=0): """ Read HEADER segment of FCS file. Parameters ---------- buf : file-like object Buffer containing data to interpret as HEADER segment. begin : int Offset (in bytes) to first byte of HEADER segment in `buf`. Returns ------- header : namedtuple Version information and byte offset values of other FCS segments (see FCS standards for more information) in the following order: - version : str - text_begin : int - text_end : int - data_begin : int - data_end : int - analysis_begin : int - analysis_end : int Notes ----- Blank ANALYSIS segment offsets are converted to zeros. OTHER segment offsets are ignored (see [1]_, [2]_, and [3]_). References ---------- .. [1] P.N. Dean, C.B. Bagwell, T. Lindmo, R.F. Murphy, G.C. Salzman, "Data file standard for flow cytometry. Data File Standards Committee of the Society for Analytical Cytology," Cytometry vol 11, pp 323-332, 1990, PMID 2340769. .. [2] L.C. Seamer, C.B. Bagwell, L. Barden, D. Redelman, G.C. Salzman, J.C. Wood, R.F. Murphy, "Proposed new data file standard for flow cytometry, version FCS 3.0," Cytometry vol 28, pp 118-122, 1997, PMID 9181300. .. [3] J. Spidlen, et al, "Data File Standard for Flow Cytometry, version FCS 3.1," Cytometry A vol 77A, pp 97-100, 2009, PMID 19937951. """ fields = [ 'version', 'text_begin', 'text_end', 'data_begin', 'data_end', 'analysis_begin', 'analysis_end'] FCSHeader = collections.namedtuple('FCSHeader', fields) field_values = [] buf.seek(begin) field_values.append(buf.read(10).decode(encoding).rstrip()) # version field_values.append(int(buf.read(8))) # text_begin field_values.append(int(buf.read(8))) # text_end field_values.append(int(buf.read(8))) # data_begin field_values.append(int(buf.read(8))) # data_end fv = buf.read(8).decode(encoding) # analysis_begin field_values.append(0 if fv == ' '*8 else int(fv)) fv = buf.read(8).decode(encoding) # analysis_end field_values.append(0 if fv == ' '*8 else int(fv)) header = FCSHeader._make(field_values) return header
python
def read_fcs_header_segment(buf, begin=0): """ Read HEADER segment of FCS file. Parameters ---------- buf : file-like object Buffer containing data to interpret as HEADER segment. begin : int Offset (in bytes) to first byte of HEADER segment in `buf`. Returns ------- header : namedtuple Version information and byte offset values of other FCS segments (see FCS standards for more information) in the following order: - version : str - text_begin : int - text_end : int - data_begin : int - data_end : int - analysis_begin : int - analysis_end : int Notes ----- Blank ANALYSIS segment offsets are converted to zeros. OTHER segment offsets are ignored (see [1]_, [2]_, and [3]_). References ---------- .. [1] P.N. Dean, C.B. Bagwell, T. Lindmo, R.F. Murphy, G.C. Salzman, "Data file standard for flow cytometry. Data File Standards Committee of the Society for Analytical Cytology," Cytometry vol 11, pp 323-332, 1990, PMID 2340769. .. [2] L.C. Seamer, C.B. Bagwell, L. Barden, D. Redelman, G.C. Salzman, J.C. Wood, R.F. Murphy, "Proposed new data file standard for flow cytometry, version FCS 3.0," Cytometry vol 28, pp 118-122, 1997, PMID 9181300. .. [3] J. Spidlen, et al, "Data File Standard for Flow Cytometry, version FCS 3.1," Cytometry A vol 77A, pp 97-100, 2009, PMID 19937951. """ fields = [ 'version', 'text_begin', 'text_end', 'data_begin', 'data_end', 'analysis_begin', 'analysis_end'] FCSHeader = collections.namedtuple('FCSHeader', fields) field_values = [] buf.seek(begin) field_values.append(buf.read(10).decode(encoding).rstrip()) # version field_values.append(int(buf.read(8))) # text_begin field_values.append(int(buf.read(8))) # text_end field_values.append(int(buf.read(8))) # data_begin field_values.append(int(buf.read(8))) # data_end fv = buf.read(8).decode(encoding) # analysis_begin field_values.append(0 if fv == ' '*8 else int(fv)) fv = buf.read(8).decode(encoding) # analysis_end field_values.append(0 if fv == ' '*8 else int(fv)) header = FCSHeader._make(field_values) return header
[ "def", "read_fcs_header_segment", "(", "buf", ",", "begin", "=", "0", ")", ":", "fields", "=", "[", "'version'", ",", "'text_begin'", ",", "'text_end'", ",", "'data_begin'", ",", "'data_end'", ",", "'analysis_begin'", ",", "'analysis_end'", "]", "FCSHeader", "...
Read HEADER segment of FCS file. Parameters ---------- buf : file-like object Buffer containing data to interpret as HEADER segment. begin : int Offset (in bytes) to first byte of HEADER segment in `buf`. Returns ------- header : namedtuple Version information and byte offset values of other FCS segments (see FCS standards for more information) in the following order: - version : str - text_begin : int - text_end : int - data_begin : int - data_end : int - analysis_begin : int - analysis_end : int Notes ----- Blank ANALYSIS segment offsets are converted to zeros. OTHER segment offsets are ignored (see [1]_, [2]_, and [3]_). References ---------- .. [1] P.N. Dean, C.B. Bagwell, T. Lindmo, R.F. Murphy, G.C. Salzman, "Data file standard for flow cytometry. Data File Standards Committee of the Society for Analytical Cytology," Cytometry vol 11, pp 323-332, 1990, PMID 2340769. .. [2] L.C. Seamer, C.B. Bagwell, L. Barden, D. Redelman, G.C. Salzman, J.C. Wood, R.F. Murphy, "Proposed new data file standard for flow cytometry, version FCS 3.0," Cytometry vol 28, pp 118-122, 1997, PMID 9181300. .. [3] J. Spidlen, et al, "Data File Standard for Flow Cytometry, version FCS 3.1," Cytometry A vol 77A, pp 97-100, 2009, PMID 19937951.
[ "Read", "HEADER", "segment", "of", "FCS", "file", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/io.py#L23-L97
train
35,334
taborlab/FlowCal
FlowCal/io.py
read_fcs_text_segment
def read_fcs_text_segment(buf, begin, end, delim=None, supplemental=False): """ Read TEXT segment of FCS file. Parameters ---------- buf : file-like object Buffer containing data to interpret as TEXT segment. begin : int Offset (in bytes) to first byte of TEXT segment in `buf`. end : int Offset (in bytes) to last byte of TEXT segment in `buf`. delim : str, optional 1-byte delimiter character which delimits key-value entries of TEXT segment. If None and ``supplemental==False``, will extract delimiter as first byte of TEXT segment. supplemental : bool, optional Flag specifying that segment is a supplemental TEXT segment (see FCS3.0 and FCS3.1), in which case a delimiter (``delim``) must be specified. Returns ------- text : dict Dictionary of key-value entries extracted from TEXT segment. delim : str or None String containing delimiter or None if TEXT segment is empty. Raises ------ ValueError If supplemental TEXT segment (``supplemental==True``) but ``delim`` is not specified. ValueError If primary TEXT segment (``supplemental==False``) does not start with delimiter. ValueError If first keyword starts with delimiter (e.g. a primary TEXT segment with the following contents: ///k1/v1/k2/v2/). ValueError If odd number of keys + values detected (indicating an unpaired key or value). ValueError If TEXT segment is ill-formed (unable to be parsed according to the FCS standards). Notes ----- ANALYSIS segments and supplemental TEXT segments are parsed the same way, so this function can also be used to parse ANALYSIS segments. This function does *not* automatically parse and accumulate additional TEXT-like segments (e.g. supplemental TEXT segments or ANALYSIS segments) referenced in the originally specified TEXT segment. References ---------- .. [1] P.N. Dean, C.B. Bagwell, T. Lindmo, R.F. Murphy, G.C. Salzman, "Data file standard for flow cytometry. Data File Standards Committee of the Society for Analytical Cytology," Cytometry vol 11, pp 323-332, 1990, PMID 2340769. .. [2] L.C. Seamer, C.B. Bagwell, L. Barden, D. Redelman, G.C. Salzman, J.C. Wood, R.F. Murphy, "Proposed new data file standard for flow cytometry, version FCS 3.0," Cytometry vol 28, pp 118-122, 1997, PMID 9181300. .. [3] J. Spidlen, et al, "Data File Standard for Flow Cytometry, version FCS 3.1," Cytometry A vol 77A, pp 97-100, 2009, PMID 19937951. """ if delim is None: if supplemental: raise ValueError("must specify ``delim`` if reading supplemental" + " TEXT segment") else: buf.seek(begin) delim = buf.read(1).decode(encoding) # The offsets are inclusive (meaning they specify first and last byte # WITHIN segment) and seeking is inclusive (read() after seek() reads the # byte which was seeked to). This means the length of the segment is # ((end+1) - begin). buf.seek(begin) raw = buf.read((end+1)-begin).decode(encoding) # If segment is empty, return empty dictionary as text if not raw: return {}, None if not supplemental: # Check that the first character of the TEXT segment is equal to the # delimiter. if raw[0] != delim: raise ValueError("primary TEXT segment should start with" + " delimiter") # The FCS standards indicate that keyword values must be flanked by the # delimiter character, but they do not require that the TEXT segment end # with the delimiter. As such, look for the last instance of the delimiter # in the segment and retain everything before it (potentially removing # TEXT segment characters which occur after the last instance of the # delimiter). end_index = raw.rfind(delim) if supplemental and end_index == -1: # Delimiter was not found. This should only be permitted for an empty # supplemental TEXT segment (primary TEXT segment should fail above # if first character doesn't match delimiter). return {}, delim else: raw = raw[:end_index] pairs_list = raw.split(delim) ### # Reconstruct Keys and Values By Aggregating Escaped Delimiters ### # According to the FCS standards, delimiter characters are permitted in # keywords and keyword values as long as they are escaped by being # immediately repeated. Delimiter characters are not permitted as the # first character of a keyword or keyword value, however. Null (zero # length) keywords or keyword values are also not permitted. According to # these restrictions, a delimiter character should manifest itself as an # empty element in ``pairs_list``. As such, scan through ``pairs_list`` # looking for empty elements and reconstruct keywords or keyword values # containing delimiters. ### # Start scanning from the end of the list since the end of the list is # well defined (i.e. doesn't depend on whether the TEXT segment is a # primary segment, which MUST start with the delimiter, or a supplemental # segment, which is not required to start with the delimiter). reconstructed_KV_accumulator = [] idx = len(pairs_list) - 1 while idx >= 0: if pairs_list[idx] == '': # Count the number of consecutive empty elements to determine how # many escaped delimiters exist and whether or not a true boundary # delimiter exists. num_empty_elements = 1 idx = idx - 1 while idx >=0 and pairs_list[idx] == '': num_empty_elements = num_empty_elements + 1 idx = idx - 1 # Need to differentiate between rolling off the bottom of the list # and hitting a non-empty element. Assessing pairs_list[-1] can # still be evaluated (by wrapping around the list, which is not # what we want to check) so check if we've finished scanning the # list first. if idx < 0: # We rolled off the bottom of the list. if num_empty_elements == 1: # If we only hit 1 empty element before rolling off the # list, then there were no escaped delimiters and the # segment started with a delimiter. break elif (num_empty_elements % 2) == 0: # Even number of empty elements. # # If this is a supplemental TEXT segment, this can be # interpreted as *not* starting the TEXT segment with the # delimiter (which is permitted for supplemental TEXT # segments) and starting the first keyword with one or # more delimiters, which is prohibited. if supplemental: raise ValueError("starting a TEXT segment keyword" + " with a delimiter is prohibited") # If this is a primary TEXT segment, this is an ill-formed # segment. Rationale: 1 empty element will always be # consumed as the initial delimiter which a primary TEXT # segment is required to start with. After that delimiter # is accounted for, you now have either an unescaped # delimiter, which is prohibited, or a boundary delimiter, # which would imply that the entire first keyword was # composed of delimiters, which is prohibited because # keywords are not allowed to start with the delimiter). raise ValueError("ill-formed TEXT segment") else: # Odd number of empty elements. This can be interpreted as # starting the segment with a delimiter and then having # one or more delimiters starting the first keyword, which # is prohibited. raise ValueError("starting a TEXT segment keyword with a" + " delimiter is prohibited") else: # We encountered a non-empty element. Calculate the number of # escaped delimiters and whether or not a true boundary # delimiter is present. num_delim = (num_empty_elements+1)//2 boundary_delim = (num_empty_elements % 2) == 0 if boundary_delim: # A boundary delimiter exists. We know that the boundary # has to be on the right side (end of the sequence), # because keywords and keyword values are prohibited from # starting with a delimiter, which would be the case if the # boundary delimiter was anywhere BUT the last character. # This means we need to postpend the appropriate number of # delim characters to the end of the non-empty list # element that ``idx`` currently points to. pairs_list[idx] = pairs_list[idx] + (num_delim*delim) # We can now add the reconstructed keyword or keyword # value to the accumulator and move on. It's possible that # this keyword or keyword value is incompletely # reconstructed (e.g. /key//1///value1/ # => {'key/1/':'value1'}; there are other delimiters in # this keyword or keyword value), but that case is now # handled independently of this case and just like any # other instance of escaped delimiters *without* a # boundary delimiter. reconstructed_KV_accumulator.append(pairs_list[idx]) idx = idx - 1 else: # No boundary delimiters exist, so we need to glue the # list elements before and after this sequence of # consecutive delimiters together with the appropriate # number of delimiters. if len(reconstructed_KV_accumulator) == 0: # Edge Case: The accumulator should always have at # least 1 element in it at this point. If it doesn't, # the last value ends with the delimiter, which will # result in two consecutive empty elements, which # won't fall into this case. Only 1 empty element # indicates an ill-formed TEXT segment with an # unpaired non-boundary delimiter (e.g. /k1/v1//), # which is not permitted. The ill-formed TEXT segment # implied by 1 empty element is recoverable, though, # and a use case which is known to exist, so throw a # warning and ignore the 2nd copy of the delimiter. warnings.warn("detected ill-formed TEXT segment (ends" + " with two delimiter characters)." + " Ignoring last delimiter character") reconstructed_KV_accumulator.append(pairs_list[idx]) else: reconstructed_KV_accumulator[-1] = pairs_list[idx] + \ (num_delim*delim) + reconstructed_KV_accumulator[-1] idx = idx - 1 else: # Non-empty element, just append reconstructed_KV_accumulator.append(pairs_list[idx]) idx = idx - 1 pairs_list_reconstructed = list(reversed(reconstructed_KV_accumulator)) # List length should be even since all key-value entries should be pairs if len(pairs_list_reconstructed) % 2 != 0: raise ValueError("odd # of (keys + values); unpaired key or value") text = dict(zip(pairs_list_reconstructed[0::2], pairs_list_reconstructed[1::2])) return text, delim
python
def read_fcs_text_segment(buf, begin, end, delim=None, supplemental=False): """ Read TEXT segment of FCS file. Parameters ---------- buf : file-like object Buffer containing data to interpret as TEXT segment. begin : int Offset (in bytes) to first byte of TEXT segment in `buf`. end : int Offset (in bytes) to last byte of TEXT segment in `buf`. delim : str, optional 1-byte delimiter character which delimits key-value entries of TEXT segment. If None and ``supplemental==False``, will extract delimiter as first byte of TEXT segment. supplemental : bool, optional Flag specifying that segment is a supplemental TEXT segment (see FCS3.0 and FCS3.1), in which case a delimiter (``delim``) must be specified. Returns ------- text : dict Dictionary of key-value entries extracted from TEXT segment. delim : str or None String containing delimiter or None if TEXT segment is empty. Raises ------ ValueError If supplemental TEXT segment (``supplemental==True``) but ``delim`` is not specified. ValueError If primary TEXT segment (``supplemental==False``) does not start with delimiter. ValueError If first keyword starts with delimiter (e.g. a primary TEXT segment with the following contents: ///k1/v1/k2/v2/). ValueError If odd number of keys + values detected (indicating an unpaired key or value). ValueError If TEXT segment is ill-formed (unable to be parsed according to the FCS standards). Notes ----- ANALYSIS segments and supplemental TEXT segments are parsed the same way, so this function can also be used to parse ANALYSIS segments. This function does *not* automatically parse and accumulate additional TEXT-like segments (e.g. supplemental TEXT segments or ANALYSIS segments) referenced in the originally specified TEXT segment. References ---------- .. [1] P.N. Dean, C.B. Bagwell, T. Lindmo, R.F. Murphy, G.C. Salzman, "Data file standard for flow cytometry. Data File Standards Committee of the Society for Analytical Cytology," Cytometry vol 11, pp 323-332, 1990, PMID 2340769. .. [2] L.C. Seamer, C.B. Bagwell, L. Barden, D. Redelman, G.C. Salzman, J.C. Wood, R.F. Murphy, "Proposed new data file standard for flow cytometry, version FCS 3.0," Cytometry vol 28, pp 118-122, 1997, PMID 9181300. .. [3] J. Spidlen, et al, "Data File Standard for Flow Cytometry, version FCS 3.1," Cytometry A vol 77A, pp 97-100, 2009, PMID 19937951. """ if delim is None: if supplemental: raise ValueError("must specify ``delim`` if reading supplemental" + " TEXT segment") else: buf.seek(begin) delim = buf.read(1).decode(encoding) # The offsets are inclusive (meaning they specify first and last byte # WITHIN segment) and seeking is inclusive (read() after seek() reads the # byte which was seeked to). This means the length of the segment is # ((end+1) - begin). buf.seek(begin) raw = buf.read((end+1)-begin).decode(encoding) # If segment is empty, return empty dictionary as text if not raw: return {}, None if not supplemental: # Check that the first character of the TEXT segment is equal to the # delimiter. if raw[0] != delim: raise ValueError("primary TEXT segment should start with" + " delimiter") # The FCS standards indicate that keyword values must be flanked by the # delimiter character, but they do not require that the TEXT segment end # with the delimiter. As such, look for the last instance of the delimiter # in the segment and retain everything before it (potentially removing # TEXT segment characters which occur after the last instance of the # delimiter). end_index = raw.rfind(delim) if supplemental and end_index == -1: # Delimiter was not found. This should only be permitted for an empty # supplemental TEXT segment (primary TEXT segment should fail above # if first character doesn't match delimiter). return {}, delim else: raw = raw[:end_index] pairs_list = raw.split(delim) ### # Reconstruct Keys and Values By Aggregating Escaped Delimiters ### # According to the FCS standards, delimiter characters are permitted in # keywords and keyword values as long as they are escaped by being # immediately repeated. Delimiter characters are not permitted as the # first character of a keyword or keyword value, however. Null (zero # length) keywords or keyword values are also not permitted. According to # these restrictions, a delimiter character should manifest itself as an # empty element in ``pairs_list``. As such, scan through ``pairs_list`` # looking for empty elements and reconstruct keywords or keyword values # containing delimiters. ### # Start scanning from the end of the list since the end of the list is # well defined (i.e. doesn't depend on whether the TEXT segment is a # primary segment, which MUST start with the delimiter, or a supplemental # segment, which is not required to start with the delimiter). reconstructed_KV_accumulator = [] idx = len(pairs_list) - 1 while idx >= 0: if pairs_list[idx] == '': # Count the number of consecutive empty elements to determine how # many escaped delimiters exist and whether or not a true boundary # delimiter exists. num_empty_elements = 1 idx = idx - 1 while idx >=0 and pairs_list[idx] == '': num_empty_elements = num_empty_elements + 1 idx = idx - 1 # Need to differentiate between rolling off the bottom of the list # and hitting a non-empty element. Assessing pairs_list[-1] can # still be evaluated (by wrapping around the list, which is not # what we want to check) so check if we've finished scanning the # list first. if idx < 0: # We rolled off the bottom of the list. if num_empty_elements == 1: # If we only hit 1 empty element before rolling off the # list, then there were no escaped delimiters and the # segment started with a delimiter. break elif (num_empty_elements % 2) == 0: # Even number of empty elements. # # If this is a supplemental TEXT segment, this can be # interpreted as *not* starting the TEXT segment with the # delimiter (which is permitted for supplemental TEXT # segments) and starting the first keyword with one or # more delimiters, which is prohibited. if supplemental: raise ValueError("starting a TEXT segment keyword" + " with a delimiter is prohibited") # If this is a primary TEXT segment, this is an ill-formed # segment. Rationale: 1 empty element will always be # consumed as the initial delimiter which a primary TEXT # segment is required to start with. After that delimiter # is accounted for, you now have either an unescaped # delimiter, which is prohibited, or a boundary delimiter, # which would imply that the entire first keyword was # composed of delimiters, which is prohibited because # keywords are not allowed to start with the delimiter). raise ValueError("ill-formed TEXT segment") else: # Odd number of empty elements. This can be interpreted as # starting the segment with a delimiter and then having # one or more delimiters starting the first keyword, which # is prohibited. raise ValueError("starting a TEXT segment keyword with a" + " delimiter is prohibited") else: # We encountered a non-empty element. Calculate the number of # escaped delimiters and whether or not a true boundary # delimiter is present. num_delim = (num_empty_elements+1)//2 boundary_delim = (num_empty_elements % 2) == 0 if boundary_delim: # A boundary delimiter exists. We know that the boundary # has to be on the right side (end of the sequence), # because keywords and keyword values are prohibited from # starting with a delimiter, which would be the case if the # boundary delimiter was anywhere BUT the last character. # This means we need to postpend the appropriate number of # delim characters to the end of the non-empty list # element that ``idx`` currently points to. pairs_list[idx] = pairs_list[idx] + (num_delim*delim) # We can now add the reconstructed keyword or keyword # value to the accumulator and move on. It's possible that # this keyword or keyword value is incompletely # reconstructed (e.g. /key//1///value1/ # => {'key/1/':'value1'}; there are other delimiters in # this keyword or keyword value), but that case is now # handled independently of this case and just like any # other instance of escaped delimiters *without* a # boundary delimiter. reconstructed_KV_accumulator.append(pairs_list[idx]) idx = idx - 1 else: # No boundary delimiters exist, so we need to glue the # list elements before and after this sequence of # consecutive delimiters together with the appropriate # number of delimiters. if len(reconstructed_KV_accumulator) == 0: # Edge Case: The accumulator should always have at # least 1 element in it at this point. If it doesn't, # the last value ends with the delimiter, which will # result in two consecutive empty elements, which # won't fall into this case. Only 1 empty element # indicates an ill-formed TEXT segment with an # unpaired non-boundary delimiter (e.g. /k1/v1//), # which is not permitted. The ill-formed TEXT segment # implied by 1 empty element is recoverable, though, # and a use case which is known to exist, so throw a # warning and ignore the 2nd copy of the delimiter. warnings.warn("detected ill-formed TEXT segment (ends" + " with two delimiter characters)." + " Ignoring last delimiter character") reconstructed_KV_accumulator.append(pairs_list[idx]) else: reconstructed_KV_accumulator[-1] = pairs_list[idx] + \ (num_delim*delim) + reconstructed_KV_accumulator[-1] idx = idx - 1 else: # Non-empty element, just append reconstructed_KV_accumulator.append(pairs_list[idx]) idx = idx - 1 pairs_list_reconstructed = list(reversed(reconstructed_KV_accumulator)) # List length should be even since all key-value entries should be pairs if len(pairs_list_reconstructed) % 2 != 0: raise ValueError("odd # of (keys + values); unpaired key or value") text = dict(zip(pairs_list_reconstructed[0::2], pairs_list_reconstructed[1::2])) return text, delim
[ "def", "read_fcs_text_segment", "(", "buf", ",", "begin", ",", "end", ",", "delim", "=", "None", ",", "supplemental", "=", "False", ")", ":", "if", "delim", "is", "None", ":", "if", "supplemental", ":", "raise", "ValueError", "(", "\"must specify ``delim`` i...
Read TEXT segment of FCS file. Parameters ---------- buf : file-like object Buffer containing data to interpret as TEXT segment. begin : int Offset (in bytes) to first byte of TEXT segment in `buf`. end : int Offset (in bytes) to last byte of TEXT segment in `buf`. delim : str, optional 1-byte delimiter character which delimits key-value entries of TEXT segment. If None and ``supplemental==False``, will extract delimiter as first byte of TEXT segment. supplemental : bool, optional Flag specifying that segment is a supplemental TEXT segment (see FCS3.0 and FCS3.1), in which case a delimiter (``delim``) must be specified. Returns ------- text : dict Dictionary of key-value entries extracted from TEXT segment. delim : str or None String containing delimiter or None if TEXT segment is empty. Raises ------ ValueError If supplemental TEXT segment (``supplemental==True``) but ``delim`` is not specified. ValueError If primary TEXT segment (``supplemental==False``) does not start with delimiter. ValueError If first keyword starts with delimiter (e.g. a primary TEXT segment with the following contents: ///k1/v1/k2/v2/). ValueError If odd number of keys + values detected (indicating an unpaired key or value). ValueError If TEXT segment is ill-formed (unable to be parsed according to the FCS standards). Notes ----- ANALYSIS segments and supplemental TEXT segments are parsed the same way, so this function can also be used to parse ANALYSIS segments. This function does *not* automatically parse and accumulate additional TEXT-like segments (e.g. supplemental TEXT segments or ANALYSIS segments) referenced in the originally specified TEXT segment. References ---------- .. [1] P.N. Dean, C.B. Bagwell, T. Lindmo, R.F. Murphy, G.C. Salzman, "Data file standard for flow cytometry. Data File Standards Committee of the Society for Analytical Cytology," Cytometry vol 11, pp 323-332, 1990, PMID 2340769. .. [2] L.C. Seamer, C.B. Bagwell, L. Barden, D. Redelman, G.C. Salzman, J.C. Wood, R.F. Murphy, "Proposed new data file standard for flow cytometry, version FCS 3.0," Cytometry vol 28, pp 118-122, 1997, PMID 9181300. .. [3] J. Spidlen, et al, "Data File Standard for Flow Cytometry, version FCS 3.1," Cytometry A vol 77A, pp 97-100, 2009, PMID 19937951.
[ "Read", "TEXT", "segment", "of", "FCS", "file", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/io.py#L99-L352
train
35,335
taborlab/FlowCal
FlowCal/io.py
FCSData.acquisition_time
def acquisition_time(self): """ Acquisition time, in seconds. The acquisition time is calculated using the 'time' channel by default (channel name is case independent). If the 'time' channel is not available, the acquisition_start_time and acquisition_end_time, extracted from the $BTIM and $ETIM keyword parameters will be used. If these are not found, None will be returned. """ # Get time channels indices time_channel_idx = [idx for idx, channel in enumerate(self.channels) if channel.lower() == 'time'] if len(time_channel_idx) > 1: raise KeyError("more than one time channel in data") # Check if the time channel is available elif len(time_channel_idx) == 1: # Use the event list time_channel = self.channels[time_channel_idx[0]] return (self[-1, time_channel] - self[0, time_channel]) \ * self.time_step elif (self._acquisition_start_time is not None and self._acquisition_end_time is not None): # Use start_time and end_time: dt = (self._acquisition_end_time - self._acquisition_start_time) return dt.total_seconds() else: return None
python
def acquisition_time(self): """ Acquisition time, in seconds. The acquisition time is calculated using the 'time' channel by default (channel name is case independent). If the 'time' channel is not available, the acquisition_start_time and acquisition_end_time, extracted from the $BTIM and $ETIM keyword parameters will be used. If these are not found, None will be returned. """ # Get time channels indices time_channel_idx = [idx for idx, channel in enumerate(self.channels) if channel.lower() == 'time'] if len(time_channel_idx) > 1: raise KeyError("more than one time channel in data") # Check if the time channel is available elif len(time_channel_idx) == 1: # Use the event list time_channel = self.channels[time_channel_idx[0]] return (self[-1, time_channel] - self[0, time_channel]) \ * self.time_step elif (self._acquisition_start_time is not None and self._acquisition_end_time is not None): # Use start_time and end_time: dt = (self._acquisition_end_time - self._acquisition_start_time) return dt.total_seconds() else: return None
[ "def", "acquisition_time", "(", "self", ")", ":", "# Get time channels indices", "time_channel_idx", "=", "[", "idx", "for", "idx", ",", "channel", "in", "enumerate", "(", "self", ".", "channels", ")", "if", "channel", ".", "lower", "(", ")", "==", "'time'",...
Acquisition time, in seconds. The acquisition time is calculated using the 'time' channel by default (channel name is case independent). If the 'time' channel is not available, the acquisition_start_time and acquisition_end_time, extracted from the $BTIM and $ETIM keyword parameters will be used. If these are not found, None will be returned.
[ "Acquisition", "time", "in", "seconds", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/io.py#L1160-L1190
train
35,336
taborlab/FlowCal
FlowCal/io.py
FCSData._parse_time_string
def _parse_time_string(time_str): """ Get a datetime.time object from a string time representation. The start and end of acquisition are stored in the optional keyword parameters $BTIM and $ETIM. The following formats are used according to the FCS standard: - FCS 2.0: 'hh:mm:ss' - FCS 3.0: 'hh:mm:ss[:tt]', where 'tt' is optional, and represents fractional seconds in 1/60ths. - FCS 3.1: 'hh:mm:ss[.cc]', where 'cc' is optional, and represents fractional seconds in 1/100ths. This function attempts to transform these formats to 'hh:mm:ss:ffffff', where 'ffffff' is in microseconds, and then parse it using the datetime module. Parameters: ----------- time_str : str, or None String representation of time, or None. Returns: -------- t : datetime.time, or None Time parsed from `time_str`. If parsing was not possible, return None. If `time_str` is None, return None """ # If input is None, return None if time_str is None: return None time_l = time_str.split(':') if len(time_l) == 3: # Either 'hh:mm:ss' or 'hh:mm:ss.cc' if '.' in time_l[2]: # 'hh:mm:ss.cc' format time_str = time_str.replace('.', ':') else: # 'hh:mm:ss' format time_str = time_str + ':0' # Attempt to parse string, return None if not possible try: t = datetime.datetime.strptime(time_str, '%H:%M:%S:%f').time() except: t = None elif len(time_l) == 4: # 'hh:mm:ss:tt' format time_l[3] = '{:06d}'.format(int(float(time_l[3])*1e6/60)) time_str = ':'.join(time_l) # Attempt to parse string, return None if not possible try: t = datetime.datetime.strptime(time_str, '%H:%M:%S:%f').time() except: t = None else: # Unknown format t = None return t
python
def _parse_time_string(time_str): """ Get a datetime.time object from a string time representation. The start and end of acquisition are stored in the optional keyword parameters $BTIM and $ETIM. The following formats are used according to the FCS standard: - FCS 2.0: 'hh:mm:ss' - FCS 3.0: 'hh:mm:ss[:tt]', where 'tt' is optional, and represents fractional seconds in 1/60ths. - FCS 3.1: 'hh:mm:ss[.cc]', where 'cc' is optional, and represents fractional seconds in 1/100ths. This function attempts to transform these formats to 'hh:mm:ss:ffffff', where 'ffffff' is in microseconds, and then parse it using the datetime module. Parameters: ----------- time_str : str, or None String representation of time, or None. Returns: -------- t : datetime.time, or None Time parsed from `time_str`. If parsing was not possible, return None. If `time_str` is None, return None """ # If input is None, return None if time_str is None: return None time_l = time_str.split(':') if len(time_l) == 3: # Either 'hh:mm:ss' or 'hh:mm:ss.cc' if '.' in time_l[2]: # 'hh:mm:ss.cc' format time_str = time_str.replace('.', ':') else: # 'hh:mm:ss' format time_str = time_str + ':0' # Attempt to parse string, return None if not possible try: t = datetime.datetime.strptime(time_str, '%H:%M:%S:%f').time() except: t = None elif len(time_l) == 4: # 'hh:mm:ss:tt' format time_l[3] = '{:06d}'.format(int(float(time_l[3])*1e6/60)) time_str = ':'.join(time_l) # Attempt to parse string, return None if not possible try: t = datetime.datetime.strptime(time_str, '%H:%M:%S:%f').time() except: t = None else: # Unknown format t = None return t
[ "def", "_parse_time_string", "(", "time_str", ")", ":", "# If input is None, return None", "if", "time_str", "is", "None", ":", "return", "None", "time_l", "=", "time_str", ".", "split", "(", "':'", ")", "if", "len", "(", "time_l", ")", "==", "3", ":", "# ...
Get a datetime.time object from a string time representation. The start and end of acquisition are stored in the optional keyword parameters $BTIM and $ETIM. The following formats are used according to the FCS standard: - FCS 2.0: 'hh:mm:ss' - FCS 3.0: 'hh:mm:ss[:tt]', where 'tt' is optional, and represents fractional seconds in 1/60ths. - FCS 3.1: 'hh:mm:ss[.cc]', where 'cc' is optional, and represents fractional seconds in 1/100ths. This function attempts to transform these formats to 'hh:mm:ss:ffffff', where 'ffffff' is in microseconds, and then parse it using the datetime module. Parameters: ----------- time_str : str, or None String representation of time, or None. Returns: -------- t : datetime.time, or None Time parsed from `time_str`. If parsing was not possible, return None. If `time_str` is None, return None
[ "Get", "a", "datetime", ".", "time", "object", "from", "a", "string", "time", "representation", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/io.py#L1765-L1824
train
35,337
taborlab/FlowCal
FlowCal/io.py
FCSData._parse_date_string
def _parse_date_string(date_str): """ Get a datetime.date object from a string date representation. The FCS standard includes an optional keyword parameter $DATE in which the acquistion date is stored. In FCS 2.0, the date is saved as 'dd-mmm-yy', whereas in FCS 3.0 and 3.1 the date is saved as 'dd-mmm-yyyy'. This function attempts to parse these formats, along with a couple of nonstandard ones, using the datetime module. Parameters: ----------- date_str : str, or None String representation of date, or None. Returns: -------- t : datetime.datetime, or None Date parsed from `date_str`. If parsing was not possible, return None. If `date_str` is None, return None """ # If input is None, return None if date_str is None: return None # Standard format for FCS2.0 try: return datetime.datetime.strptime(date_str, '%d-%b-%y') except ValueError: pass # Standard format for FCS3.0 try: return datetime.datetime.strptime(date_str, '%d-%b-%Y') except ValueError: pass # Nonstandard format 1 try: return datetime.datetime.strptime(date_str, '%y-%b-%d') except ValueError: pass # Nonstandard format 2 try: return datetime.datetime.strptime(date_str, '%Y-%b-%d') except ValueError: pass # If none of these formats work, return None return None
python
def _parse_date_string(date_str): """ Get a datetime.date object from a string date representation. The FCS standard includes an optional keyword parameter $DATE in which the acquistion date is stored. In FCS 2.0, the date is saved as 'dd-mmm-yy', whereas in FCS 3.0 and 3.1 the date is saved as 'dd-mmm-yyyy'. This function attempts to parse these formats, along with a couple of nonstandard ones, using the datetime module. Parameters: ----------- date_str : str, or None String representation of date, or None. Returns: -------- t : datetime.datetime, or None Date parsed from `date_str`. If parsing was not possible, return None. If `date_str` is None, return None """ # If input is None, return None if date_str is None: return None # Standard format for FCS2.0 try: return datetime.datetime.strptime(date_str, '%d-%b-%y') except ValueError: pass # Standard format for FCS3.0 try: return datetime.datetime.strptime(date_str, '%d-%b-%Y') except ValueError: pass # Nonstandard format 1 try: return datetime.datetime.strptime(date_str, '%y-%b-%d') except ValueError: pass # Nonstandard format 2 try: return datetime.datetime.strptime(date_str, '%Y-%b-%d') except ValueError: pass # If none of these formats work, return None return None
[ "def", "_parse_date_string", "(", "date_str", ")", ":", "# If input is None, return None", "if", "date_str", "is", "None", ":", "return", "None", "# Standard format for FCS2.0", "try", ":", "return", "datetime", ".", "datetime", ".", "strptime", "(", "date_str", ","...
Get a datetime.date object from a string date representation. The FCS standard includes an optional keyword parameter $DATE in which the acquistion date is stored. In FCS 2.0, the date is saved as 'dd-mmm-yy', whereas in FCS 3.0 and 3.1 the date is saved as 'dd-mmm-yyyy'. This function attempts to parse these formats, along with a couple of nonstandard ones, using the datetime module. Parameters: ----------- date_str : str, or None String representation of date, or None. Returns: -------- t : datetime.datetime, or None Date parsed from `date_str`. If parsing was not possible, return None. If `date_str` is None, return None
[ "Get", "a", "datetime", ".", "date", "object", "from", "a", "string", "date", "representation", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/io.py#L1827-L1877
train
35,338
taborlab/FlowCal
FlowCal/io.py
FCSData._name_to_index
def _name_to_index(self, channels): """ Return the channel indices for the specified channel names. Integers contained in `channel` are returned unmodified, if they are within the range of ``self.channels``. Parameters ---------- channels : int or str or list of int or list of str Name(s) of the channel(s) of interest. Returns ------- int or list of int Numerical index(ces) of the specified channels. """ # Check if list, then run recursively if hasattr(channels, '__iter__') \ and not isinstance(channels, six.string_types): return [self._name_to_index(ch) for ch in channels] if isinstance(channels, six.string_types): # channels is a string containing a channel name if channels in self.channels: return self.channels.index(channels) else: raise ValueError("{} is not a valid channel name." .format(channels)) if isinstance(channels, int): if (channels < len(self.channels) and channels >= -len(self.channels)): return channels else: raise ValueError("index out of range") else: raise TypeError("input argument should be an integer, string or " "list of integers or strings")
python
def _name_to_index(self, channels): """ Return the channel indices for the specified channel names. Integers contained in `channel` are returned unmodified, if they are within the range of ``self.channels``. Parameters ---------- channels : int or str or list of int or list of str Name(s) of the channel(s) of interest. Returns ------- int or list of int Numerical index(ces) of the specified channels. """ # Check if list, then run recursively if hasattr(channels, '__iter__') \ and not isinstance(channels, six.string_types): return [self._name_to_index(ch) for ch in channels] if isinstance(channels, six.string_types): # channels is a string containing a channel name if channels in self.channels: return self.channels.index(channels) else: raise ValueError("{} is not a valid channel name." .format(channels)) if isinstance(channels, int): if (channels < len(self.channels) and channels >= -len(self.channels)): return channels else: raise ValueError("index out of range") else: raise TypeError("input argument should be an integer, string or " "list of integers or strings")
[ "def", "_name_to_index", "(", "self", ",", "channels", ")", ":", "# Check if list, then run recursively", "if", "hasattr", "(", "channels", ",", "'__iter__'", ")", "and", "not", "isinstance", "(", "channels", ",", "six", ".", "string_types", ")", ":", "return", ...
Return the channel indices for the specified channel names. Integers contained in `channel` are returned unmodified, if they are within the range of ``self.channels``. Parameters ---------- channels : int or str or list of int or list of str Name(s) of the channel(s) of interest. Returns ------- int or list of int Numerical index(ces) of the specified channels.
[ "Return", "the", "channel", "indices", "for", "the", "specified", "channel", "names", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/io.py#L1880-L1920
train
35,339
taborlab/FlowCal
setup.py
find_version
def find_version(file_path): """ Scrape version information from specified file path. """ with open(file_path, 'r') as f: file_contents = f.read() version_match = re.search(r"^__version__\s*=\s*['\"]([^'\"]*)['\"]", file_contents, re.M) if version_match: return version_match.group(1) else: raise RuntimeError("unable to find version string")
python
def find_version(file_path): """ Scrape version information from specified file path. """ with open(file_path, 'r') as f: file_contents = f.read() version_match = re.search(r"^__version__\s*=\s*['\"]([^'\"]*)['\"]", file_contents, re.M) if version_match: return version_match.group(1) else: raise RuntimeError("unable to find version string")
[ "def", "find_version", "(", "file_path", ")", ":", "with", "open", "(", "file_path", ",", "'r'", ")", "as", "f", ":", "file_contents", "=", "f", ".", "read", "(", ")", "version_match", "=", "re", ".", "search", "(", "r\"^__version__\\s*=\\s*['\\\"]([^'\\\"]*...
Scrape version information from specified file path.
[ "Scrape", "version", "information", "from", "specified", "file", "path", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/setup.py#L14-L26
train
35,340
taborlab/FlowCal
FlowCal/gate.py
start_end
def start_end(data, num_start=250, num_end=100, full_output=False): """ Gate out first and last events. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). num_start, num_end : int, optional Number of events to gate out from beginning and end of `data`. Ignored if less than 0. full_output : bool, optional Flag specifying to return additional outputs. If true, the outputs are given as a namedtuple. Returns ------- gated_data : FCSData or numpy array Gated flow cytometry data of the same format as `data`. mask : numpy array of bool, only if ``full_output==True`` Boolean gate mask used to gate data such that ``gated_data = data[mask]``. Raises ------ ValueError If the number of events to discard is greater than the total number of events in `data`. """ if num_start < 0: num_start = 0 if num_end < 0: num_end = 0 if data.shape[0] < (num_start + num_end): raise ValueError('Number of events to discard greater than total' + ' number of events.') mask = np.ones(shape=data.shape[0],dtype=bool) mask[:num_start] = False if num_end > 0: # catch the edge case where `num_end=0` causes mask[-num_end:] to mask # off all events mask[-num_end:] = False gated_data = data[mask] if full_output: StartEndGateOutput = collections.namedtuple( 'StartEndGateOutput', ['gated_data', 'mask']) return StartEndGateOutput(gated_data=gated_data, mask=mask) else: return gated_data
python
def start_end(data, num_start=250, num_end=100, full_output=False): """ Gate out first and last events. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). num_start, num_end : int, optional Number of events to gate out from beginning and end of `data`. Ignored if less than 0. full_output : bool, optional Flag specifying to return additional outputs. If true, the outputs are given as a namedtuple. Returns ------- gated_data : FCSData or numpy array Gated flow cytometry data of the same format as `data`. mask : numpy array of bool, only if ``full_output==True`` Boolean gate mask used to gate data such that ``gated_data = data[mask]``. Raises ------ ValueError If the number of events to discard is greater than the total number of events in `data`. """ if num_start < 0: num_start = 0 if num_end < 0: num_end = 0 if data.shape[0] < (num_start + num_end): raise ValueError('Number of events to discard greater than total' + ' number of events.') mask = np.ones(shape=data.shape[0],dtype=bool) mask[:num_start] = False if num_end > 0: # catch the edge case where `num_end=0` causes mask[-num_end:] to mask # off all events mask[-num_end:] = False gated_data = data[mask] if full_output: StartEndGateOutput = collections.namedtuple( 'StartEndGateOutput', ['gated_data', 'mask']) return StartEndGateOutput(gated_data=gated_data, mask=mask) else: return gated_data
[ "def", "start_end", "(", "data", ",", "num_start", "=", "250", ",", "num_end", "=", "100", ",", "full_output", "=", "False", ")", ":", "if", "num_start", "<", "0", ":", "num_start", "=", "0", "if", "num_end", "<", "0", ":", "num_end", "=", "0", "if...
Gate out first and last events. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). num_start, num_end : int, optional Number of events to gate out from beginning and end of `data`. Ignored if less than 0. full_output : bool, optional Flag specifying to return additional outputs. If true, the outputs are given as a namedtuple. Returns ------- gated_data : FCSData or numpy array Gated flow cytometry data of the same format as `data`. mask : numpy array of bool, only if ``full_output==True`` Boolean gate mask used to gate data such that ``gated_data = data[mask]``. Raises ------ ValueError If the number of events to discard is greater than the total number of events in `data`.
[ "Gate", "out", "first", "and", "last", "events", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/gate.py#L31-L86
train
35,341
taborlab/FlowCal
FlowCal/gate.py
high_low
def high_low(data, channels=None, high=None, low=None, full_output=False): """ Gate out high and low values across all specified channels. Gate out events in `data` with values in the specified channels which are larger than or equal to `high` or less than or equal to `low`. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int, str, list of int, list of str, optional Channels on which to perform gating. If None, use all channels. high, low : int, float, optional High and low threshold values. If None, `high` and `low` will be taken from ``data.range`` if available, otherwise ``np.inf`` and ``-np.inf`` will be used. full_output : bool, optional Flag specifying to return additional outputs. If true, the outputs are given as a namedtuple. Returns ------- gated_data : FCSData or numpy array Gated flow cytometry data of the same format as `data`. mask : numpy array of bool, only if ``full_output==True`` Boolean gate mask used to gate data such that ``gated_data = data[mask]``. """ # Extract channels in which to gate if channels is None: data_ch = data else: data_ch = data[:,channels] if data_ch.ndim == 1: data_ch = data_ch.reshape((-1,1)) # Default values for high and low if high is None: if hasattr(data_ch, 'range'): high = [np.Inf if di is None else di[1] for di in data_ch.range()] high = np.array(high) else: high = np.Inf if low is None: if hasattr(data_ch, 'range'): low = [-np.Inf if di is None else di[0] for di in data_ch.range()] low = np.array(low) else: low = -np.Inf # Gate mask = np.all((data_ch < high) & (data_ch > low), axis = 1) gated_data = data[mask] if full_output: HighLowGateOutput = collections.namedtuple( 'HighLowGateOutput', ['gated_data', 'mask']) return HighLowGateOutput(gated_data=gated_data, mask=mask) else: return gated_data
python
def high_low(data, channels=None, high=None, low=None, full_output=False): """ Gate out high and low values across all specified channels. Gate out events in `data` with values in the specified channels which are larger than or equal to `high` or less than or equal to `low`. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int, str, list of int, list of str, optional Channels on which to perform gating. If None, use all channels. high, low : int, float, optional High and low threshold values. If None, `high` and `low` will be taken from ``data.range`` if available, otherwise ``np.inf`` and ``-np.inf`` will be used. full_output : bool, optional Flag specifying to return additional outputs. If true, the outputs are given as a namedtuple. Returns ------- gated_data : FCSData or numpy array Gated flow cytometry data of the same format as `data`. mask : numpy array of bool, only if ``full_output==True`` Boolean gate mask used to gate data such that ``gated_data = data[mask]``. """ # Extract channels in which to gate if channels is None: data_ch = data else: data_ch = data[:,channels] if data_ch.ndim == 1: data_ch = data_ch.reshape((-1,1)) # Default values for high and low if high is None: if hasattr(data_ch, 'range'): high = [np.Inf if di is None else di[1] for di in data_ch.range()] high = np.array(high) else: high = np.Inf if low is None: if hasattr(data_ch, 'range'): low = [-np.Inf if di is None else di[0] for di in data_ch.range()] low = np.array(low) else: low = -np.Inf # Gate mask = np.all((data_ch < high) & (data_ch > low), axis = 1) gated_data = data[mask] if full_output: HighLowGateOutput = collections.namedtuple( 'HighLowGateOutput', ['gated_data', 'mask']) return HighLowGateOutput(gated_data=gated_data, mask=mask) else: return gated_data
[ "def", "high_low", "(", "data", ",", "channels", "=", "None", ",", "high", "=", "None", ",", "low", "=", "None", ",", "full_output", "=", "False", ")", ":", "# Extract channels in which to gate", "if", "channels", "is", "None", ":", "data_ch", "=", "data",...
Gate out high and low values across all specified channels. Gate out events in `data` with values in the specified channels which are larger than or equal to `high` or less than or equal to `low`. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int, str, list of int, list of str, optional Channels on which to perform gating. If None, use all channels. high, low : int, float, optional High and low threshold values. If None, `high` and `low` will be taken from ``data.range`` if available, otherwise ``np.inf`` and ``-np.inf`` will be used. full_output : bool, optional Flag specifying to return additional outputs. If true, the outputs are given as a namedtuple. Returns ------- gated_data : FCSData or numpy array Gated flow cytometry data of the same format as `data`. mask : numpy array of bool, only if ``full_output==True`` Boolean gate mask used to gate data such that ``gated_data = data[mask]``.
[ "Gate", "out", "high", "and", "low", "values", "across", "all", "specified", "channels", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/gate.py#L88-L151
train
35,342
taborlab/FlowCal
FlowCal/gate.py
ellipse
def ellipse(data, channels, center, a, b, theta=0, log=False, full_output=False): """ Gate that preserves events inside an ellipse-shaped region. Events are kept if they satisfy the following relationship:: (x/a)**2 + (y/b)**2 <= 1 where `x` and `y` are the coordinates of the event list, after substracting `center` and rotating by -`theta`. This is mathematically equivalent to maintaining the events inside an ellipse with major axis `a`, minor axis `b`, center at `center`, and tilted by `theta`. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : list of int, list of str Two channels on which to perform gating. center, a, b, theta (optional) : float Ellipse parameters. `a` is the major axis, `b` is the minor axis. log : bool, optional Flag specifying that log10 transformation should be applied to `data` before gating. full_output : bool, optional Flag specifying to return additional outputs. If true, the outputs are given as a namedtuple. Returns ------- gated_data : FCSData or numpy array Gated flow cytometry data of the same format as `data`. mask : numpy array of bool, only if ``full_output==True`` Boolean gate mask used to gate data such that ``gated_data = data[mask]``. contour : list of 2D numpy arrays, only if ``full_output==True`` List of 2D numpy array(s) of x-y coordinates tracing out the edge of the gated region. Raises ------ ValueError If more or less than 2 channels are specified. """ # Extract channels in which to gate if len(channels) != 2: raise ValueError('2 channels should be specified.') data_ch = data[:,channels].view(np.ndarray) # Log if necessary if log: data_ch = np.log10(data_ch) # Center center = np.array(center) data_centered = data_ch - center # Rotate R = np.array([[np.cos(theta), np.sin(theta)], [-np.sin(theta), np.cos(theta)]]) data_rotated = np.dot(data_centered, R.T) # Generate mask mask = ((data_rotated[:,0]/a)**2 + (data_rotated[:,1]/b)**2 <= 1) # Gate data_gated = data[mask] if full_output: # Calculate contour t = np.linspace(0,1,100)*2*np.pi ci = np.array([a*np.cos(t), b*np.sin(t)]).T ci = np.dot(ci, R) + center if log: ci = 10**ci cntr = [ci] # Build output namedtuple EllipseGateOutput = collections.namedtuple( 'EllipseGateOutput', ['gated_data', 'mask', 'contour']) return EllipseGateOutput( gated_data=data_gated, mask=mask, contour=cntr) else: return data_gated
python
def ellipse(data, channels, center, a, b, theta=0, log=False, full_output=False): """ Gate that preserves events inside an ellipse-shaped region. Events are kept if they satisfy the following relationship:: (x/a)**2 + (y/b)**2 <= 1 where `x` and `y` are the coordinates of the event list, after substracting `center` and rotating by -`theta`. This is mathematically equivalent to maintaining the events inside an ellipse with major axis `a`, minor axis `b`, center at `center`, and tilted by `theta`. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : list of int, list of str Two channels on which to perform gating. center, a, b, theta (optional) : float Ellipse parameters. `a` is the major axis, `b` is the minor axis. log : bool, optional Flag specifying that log10 transformation should be applied to `data` before gating. full_output : bool, optional Flag specifying to return additional outputs. If true, the outputs are given as a namedtuple. Returns ------- gated_data : FCSData or numpy array Gated flow cytometry data of the same format as `data`. mask : numpy array of bool, only if ``full_output==True`` Boolean gate mask used to gate data such that ``gated_data = data[mask]``. contour : list of 2D numpy arrays, only if ``full_output==True`` List of 2D numpy array(s) of x-y coordinates tracing out the edge of the gated region. Raises ------ ValueError If more or less than 2 channels are specified. """ # Extract channels in which to gate if len(channels) != 2: raise ValueError('2 channels should be specified.') data_ch = data[:,channels].view(np.ndarray) # Log if necessary if log: data_ch = np.log10(data_ch) # Center center = np.array(center) data_centered = data_ch - center # Rotate R = np.array([[np.cos(theta), np.sin(theta)], [-np.sin(theta), np.cos(theta)]]) data_rotated = np.dot(data_centered, R.T) # Generate mask mask = ((data_rotated[:,0]/a)**2 + (data_rotated[:,1]/b)**2 <= 1) # Gate data_gated = data[mask] if full_output: # Calculate contour t = np.linspace(0,1,100)*2*np.pi ci = np.array([a*np.cos(t), b*np.sin(t)]).T ci = np.dot(ci, R) + center if log: ci = 10**ci cntr = [ci] # Build output namedtuple EllipseGateOutput = collections.namedtuple( 'EllipseGateOutput', ['gated_data', 'mask', 'contour']) return EllipseGateOutput( gated_data=data_gated, mask=mask, contour=cntr) else: return data_gated
[ "def", "ellipse", "(", "data", ",", "channels", ",", "center", ",", "a", ",", "b", ",", "theta", "=", "0", ",", "log", "=", "False", ",", "full_output", "=", "False", ")", ":", "# Extract channels in which to gate", "if", "len", "(", "channels", ")", "...
Gate that preserves events inside an ellipse-shaped region. Events are kept if they satisfy the following relationship:: (x/a)**2 + (y/b)**2 <= 1 where `x` and `y` are the coordinates of the event list, after substracting `center` and rotating by -`theta`. This is mathematically equivalent to maintaining the events inside an ellipse with major axis `a`, minor axis `b`, center at `center`, and tilted by `theta`. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : list of int, list of str Two channels on which to perform gating. center, a, b, theta (optional) : float Ellipse parameters. `a` is the major axis, `b` is the minor axis. log : bool, optional Flag specifying that log10 transformation should be applied to `data` before gating. full_output : bool, optional Flag specifying to return additional outputs. If true, the outputs are given as a namedtuple. Returns ------- gated_data : FCSData or numpy array Gated flow cytometry data of the same format as `data`. mask : numpy array of bool, only if ``full_output==True`` Boolean gate mask used to gate data such that ``gated_data = data[mask]``. contour : list of 2D numpy arrays, only if ``full_output==True`` List of 2D numpy array(s) of x-y coordinates tracing out the edge of the gated region. Raises ------ ValueError If more or less than 2 channels are specified.
[ "Gate", "that", "preserves", "events", "inside", "an", "ellipse", "-", "shaped", "region", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/gate.py#L153-L241
train
35,343
taborlab/FlowCal
FlowCal/transform.py
transform
def transform(data, channels, transform_fxn, def_channels = None): """ Apply some transformation function to flow cytometry data. This function is a template transformation function, intended to be used by other specific transformation functions. It performs basic checks on `channels` and `data`. It then applies `transform_fxn` to the specified channels. Finally, it rescales ``data.range`` and if necessary. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int, str, list of int, list of str, optional Channels on which to perform the transformation. If `channels` is None, use def_channels. transform_fxn : function Function that performs the actual transformation. def_channels : int, str, list of int, list of str, optional Default set of channels in which to perform the transformation. If `def_channels` is None, use all channels. Returns ------- data_t : FCSData or numpy array NxD transformed flow cytometry data. """ # Copy data array data_t = data.copy().astype(np.float64) # Default if channels is None: if def_channels is None: channels = range(data_t.shape[1]) else: channels = def_channels # Convert channels to iterable if not (hasattr(channels, '__iter__') \ and not isinstance(channels, six.string_types)): channels = [channels] # Apply transformation data_t[:,channels] = transform_fxn(data_t[:,channels]) # Apply transformation to ``data.range`` if hasattr(data_t, '_range'): for channel in channels: # Transform channel name to index if necessary channel_idx = data_t._name_to_index(channel) if data_t._range[channel_idx] is not None: data_t._range[channel_idx] = \ transform_fxn(data_t._range[channel_idx]) return data_t
python
def transform(data, channels, transform_fxn, def_channels = None): """ Apply some transformation function to flow cytometry data. This function is a template transformation function, intended to be used by other specific transformation functions. It performs basic checks on `channels` and `data`. It then applies `transform_fxn` to the specified channels. Finally, it rescales ``data.range`` and if necessary. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int, str, list of int, list of str, optional Channels on which to perform the transformation. If `channels` is None, use def_channels. transform_fxn : function Function that performs the actual transformation. def_channels : int, str, list of int, list of str, optional Default set of channels in which to perform the transformation. If `def_channels` is None, use all channels. Returns ------- data_t : FCSData or numpy array NxD transformed flow cytometry data. """ # Copy data array data_t = data.copy().astype(np.float64) # Default if channels is None: if def_channels is None: channels = range(data_t.shape[1]) else: channels = def_channels # Convert channels to iterable if not (hasattr(channels, '__iter__') \ and not isinstance(channels, six.string_types)): channels = [channels] # Apply transformation data_t[:,channels] = transform_fxn(data_t[:,channels]) # Apply transformation to ``data.range`` if hasattr(data_t, '_range'): for channel in channels: # Transform channel name to index if necessary channel_idx = data_t._name_to_index(channel) if data_t._range[channel_idx] is not None: data_t._range[channel_idx] = \ transform_fxn(data_t._range[channel_idx]) return data_t
[ "def", "transform", "(", "data", ",", "channels", ",", "transform_fxn", ",", "def_channels", "=", "None", ")", ":", "# Copy data array", "data_t", "=", "data", ".", "copy", "(", ")", ".", "astype", "(", "np", ".", "float64", ")", "# Default", "if", "chan...
Apply some transformation function to flow cytometry data. This function is a template transformation function, intended to be used by other specific transformation functions. It performs basic checks on `channels` and `data`. It then applies `transform_fxn` to the specified channels. Finally, it rescales ``data.range`` and if necessary. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int, str, list of int, list of str, optional Channels on which to perform the transformation. If `channels` is None, use def_channels. transform_fxn : function Function that performs the actual transformation. def_channels : int, str, list of int, list of str, optional Default set of channels in which to perform the transformation. If `def_channels` is None, use all channels. Returns ------- data_t : FCSData or numpy array NxD transformed flow cytometry data.
[ "Apply", "some", "transformation", "function", "to", "flow", "cytometry", "data", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/transform.py#L22-L79
train
35,344
taborlab/FlowCal
FlowCal/transform.py
to_mef
def to_mef(data, channels, sc_list, sc_channels = None): """ Transform flow cytometry data using a standard curve function. This function accepts a list of standard curves (`sc_list`) and a list of channels to which those standard curves should be applied (`sc_channels`). `to_mef` automatically checks whether a standard curve is available for each channel specified in `channels`, and throws an error otherwise. This function is intended to be reduced to the following signature:: to_mef_reduced(data, channels) by using ``functools.partial`` once a list of standard curves and their respective channels is available. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int, str, list of int, list of str Channels on which to perform the transformation. If `channels` is None, perform transformation in all channels specified on `sc_channels`. sc_list : list of functions Functions implementing the standard curves for each channel in `sc_channels`. sc_channels : list of int or list of str, optional List of channels corresponding to each function in `sc_list`. If None, use all channels in `data`. Returns ------- FCSData or numpy array NxD transformed flow cytometry data. Raises ------ ValueError If any channel specified in `channels` is not in `sc_channels`. """ # Default sc_channels if sc_channels is None: if data.ndim == 1: sc_channels = range(data.shape[0]) else: sc_channels = range(data.shape[1]) # Check that sc_channels and sc_list have the same length if len(sc_channels) != len(sc_list): raise ValueError("sc_channels and sc_list should have the same length") # Convert sc_channels to indices if hasattr(data, '_name_to_index'): sc_channels = data._name_to_index(sc_channels) # Default channels if channels is None: channels = sc_channels # Convert channels to iterable if not (hasattr(channels, '__iter__') \ and not isinstance(channels, six.string_types)): channels = [channels] # Convert channels to index if hasattr(data, '_name_to_index'): channels_ind = data._name_to_index(channels) else: channels_ind = channels # Check if every channel is in sc_channels for chi, chs in zip(channels_ind, channels): if chi not in sc_channels: raise ValueError("no standard curve for channel {}".format(chs)) # Copy data array data_t = data.copy().astype(np.float64) # Iterate over channels for chi, sc in zip(sc_channels, sc_list): if chi not in channels_ind: continue # Apply transformation data_t[:,chi] = sc(data_t[:,chi]) # Apply transformation to range if hasattr(data_t, '_range') and data_t._range[chi] is not None: data_t._range[chi] = [sc(data_t._range[chi][0]), sc(data_t._range[chi][1])] return data_t
python
def to_mef(data, channels, sc_list, sc_channels = None): """ Transform flow cytometry data using a standard curve function. This function accepts a list of standard curves (`sc_list`) and a list of channels to which those standard curves should be applied (`sc_channels`). `to_mef` automatically checks whether a standard curve is available for each channel specified in `channels`, and throws an error otherwise. This function is intended to be reduced to the following signature:: to_mef_reduced(data, channels) by using ``functools.partial`` once a list of standard curves and their respective channels is available. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int, str, list of int, list of str Channels on which to perform the transformation. If `channels` is None, perform transformation in all channels specified on `sc_channels`. sc_list : list of functions Functions implementing the standard curves for each channel in `sc_channels`. sc_channels : list of int or list of str, optional List of channels corresponding to each function in `sc_list`. If None, use all channels in `data`. Returns ------- FCSData or numpy array NxD transformed flow cytometry data. Raises ------ ValueError If any channel specified in `channels` is not in `sc_channels`. """ # Default sc_channels if sc_channels is None: if data.ndim == 1: sc_channels = range(data.shape[0]) else: sc_channels = range(data.shape[1]) # Check that sc_channels and sc_list have the same length if len(sc_channels) != len(sc_list): raise ValueError("sc_channels and sc_list should have the same length") # Convert sc_channels to indices if hasattr(data, '_name_to_index'): sc_channels = data._name_to_index(sc_channels) # Default channels if channels is None: channels = sc_channels # Convert channels to iterable if not (hasattr(channels, '__iter__') \ and not isinstance(channels, six.string_types)): channels = [channels] # Convert channels to index if hasattr(data, '_name_to_index'): channels_ind = data._name_to_index(channels) else: channels_ind = channels # Check if every channel is in sc_channels for chi, chs in zip(channels_ind, channels): if chi not in sc_channels: raise ValueError("no standard curve for channel {}".format(chs)) # Copy data array data_t = data.copy().astype(np.float64) # Iterate over channels for chi, sc in zip(sc_channels, sc_list): if chi not in channels_ind: continue # Apply transformation data_t[:,chi] = sc(data_t[:,chi]) # Apply transformation to range if hasattr(data_t, '_range') and data_t._range[chi] is not None: data_t._range[chi] = [sc(data_t._range[chi][0]), sc(data_t._range[chi][1])] return data_t
[ "def", "to_mef", "(", "data", ",", "channels", ",", "sc_list", ",", "sc_channels", "=", "None", ")", ":", "# Default sc_channels", "if", "sc_channels", "is", "None", ":", "if", "data", ".", "ndim", "==", "1", ":", "sc_channels", "=", "range", "(", "data"...
Transform flow cytometry data using a standard curve function. This function accepts a list of standard curves (`sc_list`) and a list of channels to which those standard curves should be applied (`sc_channels`). `to_mef` automatically checks whether a standard curve is available for each channel specified in `channels`, and throws an error otherwise. This function is intended to be reduced to the following signature:: to_mef_reduced(data, channels) by using ``functools.partial`` once a list of standard curves and their respective channels is available. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int, str, list of int, list of str Channels on which to perform the transformation. If `channels` is None, perform transformation in all channels specified on `sc_channels`. sc_list : list of functions Functions implementing the standard curves for each channel in `sc_channels`. sc_channels : list of int or list of str, optional List of channels corresponding to each function in `sc_list`. If None, use all channels in `data`. Returns ------- FCSData or numpy array NxD transformed flow cytometry data. Raises ------ ValueError If any channel specified in `channels` is not in `sc_channels`.
[ "Transform", "flow", "cytometry", "data", "using", "a", "standard", "curve", "function", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/transform.py#L250-L338
train
35,345
taborlab/FlowCal
FlowCal/plot.py
scatter3d_and_projections
def scatter3d_and_projections(data_list, channels=[0,1,2], xscale='logicle', yscale='logicle', zscale='logicle', xlabel=None, ylabel=None, zlabel=None, xlim=None, ylim=None, zlim=None, color=None, figsize=None, savefig=None, **kwargs): """ Plot a 3D scatter plot and 2D projections from FCSData objects. `scatter3d_and_projections` creates a 3D scatter plot and three 2D projected scatter plots in four different axes for each FCSData object in `data_list`, in the same figure. Parameters ---------- data_list : FCSData object, or list of FCSData objects Flow cytometry data to plot. channels : list of int, list of str Three channels to use for the plot. savefig : str, optional The name of the file to save the figure to. If None, do not save. Other parameters ---------------- xscale : str, optional Scale of the x axis, either ``linear``, ``log``, or ``logicle``. yscale : str, optional Scale of the y axis, either ``linear``, ``log``, or ``logicle``. zscale : str, optional Scale of the z axis, either ``linear``, ``log``, or ``logicle``. xlabel : str, optional Label to use on the x axis. If None, attempts to extract channel name from last data object. ylabel : str, optional Label to use on the y axis. If None, attempts to extract channel name from last data object. zlabel : str, optional Label to use on the z axis. If None, attempts to extract channel name from last data object. xlim : tuple, optional Limits for the x axis. If None, attempts to extract limits from the range of the last data object. ylim : tuple, optional Limits for the y axis. If None, attempts to extract limits from the range of the last data object. zlim : tuple, optional Limits for the z axis. If None, attempts to extract limits from the range of the last data object. color : matplotlib color or list of matplotlib colors, optional Color for the scatter plot. It can be a list with the same length as `data_list`. If `color` is not specified, elements from `data_list` are plotted with colors taken from the module-level variable `cmap_default`. figsize : tuple, optional Figure size. If None, use matplotlib's default. kwargs : dict, optional Additional parameters passed directly to matploblib's ``scatter``. Notes ----- `scatter3d_and_projections` uses matplotlib's ``scatter``, with the 3D scatter plot using a 3D projection. Additional keyword arguments provided to `scatter3d_and_projections` are passed directly to ``scatter``. """ # Check appropriate number of channels if len(channels) != 3: raise ValueError('three channels need to be specified') # Create figure plt.figure(figsize=figsize) # Axis 1: channel 0 vs channel 2 plt.subplot(221) scatter2d(data_list, channels=[channels[0], channels[2]], xscale=xscale, yscale=zscale, xlabel=xlabel, ylabel=zlabel, xlim=xlim, ylim=zlim, color=color, **kwargs) # Axis 2: 3d plot ax_3d = plt.gcf().add_subplot(222, projection='3d') scatter3d(data_list, channels=channels, xscale=xscale, yscale=yscale, zscale=zscale, xlabel=xlabel, ylabel=ylabel, zlabel=zlabel, xlim=xlim, ylim=ylim, zlim=zlim, color=color, **kwargs) # Axis 3: channel 0 vs channel 1 plt.subplot(223) scatter2d(data_list, channels=[channels[0], channels[1]], xscale=xscale, yscale=yscale, xlabel=xlabel, ylabel=ylabel, xlim=xlim, ylim=ylim, color=color, **kwargs) # Axis 4: channel 2 vs channel 1 plt.subplot(224) scatter2d(data_list, channels=[channels[2], channels[1]], xscale=zscale, yscale=yscale, xlabel=zlabel, ylabel=ylabel, xlim=zlim, ylim=ylim, color=color, **kwargs) # Save if necessary if savefig is not None: plt.tight_layout() plt.savefig(savefig, dpi=savefig_dpi) plt.close()
python
def scatter3d_and_projections(data_list, channels=[0,1,2], xscale='logicle', yscale='logicle', zscale='logicle', xlabel=None, ylabel=None, zlabel=None, xlim=None, ylim=None, zlim=None, color=None, figsize=None, savefig=None, **kwargs): """ Plot a 3D scatter plot and 2D projections from FCSData objects. `scatter3d_and_projections` creates a 3D scatter plot and three 2D projected scatter plots in four different axes for each FCSData object in `data_list`, in the same figure. Parameters ---------- data_list : FCSData object, or list of FCSData objects Flow cytometry data to plot. channels : list of int, list of str Three channels to use for the plot. savefig : str, optional The name of the file to save the figure to. If None, do not save. Other parameters ---------------- xscale : str, optional Scale of the x axis, either ``linear``, ``log``, or ``logicle``. yscale : str, optional Scale of the y axis, either ``linear``, ``log``, or ``logicle``. zscale : str, optional Scale of the z axis, either ``linear``, ``log``, or ``logicle``. xlabel : str, optional Label to use on the x axis. If None, attempts to extract channel name from last data object. ylabel : str, optional Label to use on the y axis. If None, attempts to extract channel name from last data object. zlabel : str, optional Label to use on the z axis. If None, attempts to extract channel name from last data object. xlim : tuple, optional Limits for the x axis. If None, attempts to extract limits from the range of the last data object. ylim : tuple, optional Limits for the y axis. If None, attempts to extract limits from the range of the last data object. zlim : tuple, optional Limits for the z axis. If None, attempts to extract limits from the range of the last data object. color : matplotlib color or list of matplotlib colors, optional Color for the scatter plot. It can be a list with the same length as `data_list`. If `color` is not specified, elements from `data_list` are plotted with colors taken from the module-level variable `cmap_default`. figsize : tuple, optional Figure size. If None, use matplotlib's default. kwargs : dict, optional Additional parameters passed directly to matploblib's ``scatter``. Notes ----- `scatter3d_and_projections` uses matplotlib's ``scatter``, with the 3D scatter plot using a 3D projection. Additional keyword arguments provided to `scatter3d_and_projections` are passed directly to ``scatter``. """ # Check appropriate number of channels if len(channels) != 3: raise ValueError('three channels need to be specified') # Create figure plt.figure(figsize=figsize) # Axis 1: channel 0 vs channel 2 plt.subplot(221) scatter2d(data_list, channels=[channels[0], channels[2]], xscale=xscale, yscale=zscale, xlabel=xlabel, ylabel=zlabel, xlim=xlim, ylim=zlim, color=color, **kwargs) # Axis 2: 3d plot ax_3d = plt.gcf().add_subplot(222, projection='3d') scatter3d(data_list, channels=channels, xscale=xscale, yscale=yscale, zscale=zscale, xlabel=xlabel, ylabel=ylabel, zlabel=zlabel, xlim=xlim, ylim=ylim, zlim=zlim, color=color, **kwargs) # Axis 3: channel 0 vs channel 1 plt.subplot(223) scatter2d(data_list, channels=[channels[0], channels[1]], xscale=xscale, yscale=yscale, xlabel=xlabel, ylabel=ylabel, xlim=xlim, ylim=ylim, color=color, **kwargs) # Axis 4: channel 2 vs channel 1 plt.subplot(224) scatter2d(data_list, channels=[channels[2], channels[1]], xscale=zscale, yscale=yscale, xlabel=zlabel, ylabel=ylabel, xlim=zlim, ylim=ylim, color=color, **kwargs) # Save if necessary if savefig is not None: plt.tight_layout() plt.savefig(savefig, dpi=savefig_dpi) plt.close()
[ "def", "scatter3d_and_projections", "(", "data_list", ",", "channels", "=", "[", "0", ",", "1", ",", "2", "]", ",", "xscale", "=", "'logicle'", ",", "yscale", "=", "'logicle'", ",", "zscale", "=", "'logicle'", ",", "xlabel", "=", "None", ",", "ylabel", ...
Plot a 3D scatter plot and 2D projections from FCSData objects. `scatter3d_and_projections` creates a 3D scatter plot and three 2D projected scatter plots in four different axes for each FCSData object in `data_list`, in the same figure. Parameters ---------- data_list : FCSData object, or list of FCSData objects Flow cytometry data to plot. channels : list of int, list of str Three channels to use for the plot. savefig : str, optional The name of the file to save the figure to. If None, do not save. Other parameters ---------------- xscale : str, optional Scale of the x axis, either ``linear``, ``log``, or ``logicle``. yscale : str, optional Scale of the y axis, either ``linear``, ``log``, or ``logicle``. zscale : str, optional Scale of the z axis, either ``linear``, ``log``, or ``logicle``. xlabel : str, optional Label to use on the x axis. If None, attempts to extract channel name from last data object. ylabel : str, optional Label to use on the y axis. If None, attempts to extract channel name from last data object. zlabel : str, optional Label to use on the z axis. If None, attempts to extract channel name from last data object. xlim : tuple, optional Limits for the x axis. If None, attempts to extract limits from the range of the last data object. ylim : tuple, optional Limits for the y axis. If None, attempts to extract limits from the range of the last data object. zlim : tuple, optional Limits for the z axis. If None, attempts to extract limits from the range of the last data object. color : matplotlib color or list of matplotlib colors, optional Color for the scatter plot. It can be a list with the same length as `data_list`. If `color` is not specified, elements from `data_list` are plotted with colors taken from the module-level variable `cmap_default`. figsize : tuple, optional Figure size. If None, use matplotlib's default. kwargs : dict, optional Additional parameters passed directly to matploblib's ``scatter``. Notes ----- `scatter3d_and_projections` uses matplotlib's ``scatter``, with the 3D scatter plot using a 3D projection. Additional keyword arguments provided to `scatter3d_and_projections` are passed directly to ``scatter``.
[ "Plot", "a", "3D", "scatter", "plot", "and", "2D", "projections", "from", "FCSData", "objects", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/plot.py#L1761-L1902
train
35,346
taborlab/FlowCal
FlowCal/plot.py
_InterpolatedInverseTransform.transform_non_affine
def transform_non_affine(self, x, mask_out_of_range=True): """ Transform a Nx1 numpy array. Parameters ---------- x : array Data to be transformed. mask_out_of_range : bool, optional Whether to mask input values out of range. Return ------ array or masked array Transformed data. """ # Mask out-of-range values if mask_out_of_range: x_masked = np.ma.masked_where((x < self._xmin) | (x > self._xmax), x) else: x_masked = x # Calculate s and return return np.interp(x_masked, self._x_range, self._s_range)
python
def transform_non_affine(self, x, mask_out_of_range=True): """ Transform a Nx1 numpy array. Parameters ---------- x : array Data to be transformed. mask_out_of_range : bool, optional Whether to mask input values out of range. Return ------ array or masked array Transformed data. """ # Mask out-of-range values if mask_out_of_range: x_masked = np.ma.masked_where((x < self._xmin) | (x > self._xmax), x) else: x_masked = x # Calculate s and return return np.interp(x_masked, self._x_range, self._s_range)
[ "def", "transform_non_affine", "(", "self", ",", "x", ",", "mask_out_of_range", "=", "True", ")", ":", "# Mask out-of-range values", "if", "mask_out_of_range", ":", "x_masked", "=", "np", ".", "ma", ".", "masked_where", "(", "(", "x", "<", "self", ".", "_xmi...
Transform a Nx1 numpy array. Parameters ---------- x : array Data to be transformed. mask_out_of_range : bool, optional Whether to mask input values out of range. Return ------ array or masked array Transformed data.
[ "Transform", "a", "Nx1", "numpy", "array", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/plot.py#L130-L154
train
35,347
taborlab/FlowCal
FlowCal/plot.py
_LogicleTransform.transform_non_affine
def transform_non_affine(self, s): """ Apply transformation to a Nx1 numpy array. Parameters ---------- s : array Data to be transformed in display scale units. Return ------ array or masked array Transformed data, in data value units. """ T = self._T M = self._M W = self._W p = self._p # Calculate x return T * 10**(-(M-W)) * (10**(s-W) - (p**2)*10**(-(s-W)/p) + p**2 - 1)
python
def transform_non_affine(self, s): """ Apply transformation to a Nx1 numpy array. Parameters ---------- s : array Data to be transformed in display scale units. Return ------ array or masked array Transformed data, in data value units. """ T = self._T M = self._M W = self._W p = self._p # Calculate x return T * 10**(-(M-W)) * (10**(s-W) - (p**2)*10**(-(s-W)/p) + p**2 - 1)
[ "def", "transform_non_affine", "(", "self", ",", "s", ")", ":", "T", "=", "self", ".", "_T", "M", "=", "self", ".", "_M", "W", "=", "self", ".", "_W", "p", "=", "self", ".", "_p", "# Calculate x", "return", "T", "*", "10", "**", "(", "-", "(", ...
Apply transformation to a Nx1 numpy array. Parameters ---------- s : array Data to be transformed in display scale units. Return ------ array or masked array Transformed data, in data value units.
[ "Apply", "transformation", "to", "a", "Nx1", "numpy", "array", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/plot.py#L349-L369
train
35,348
taborlab/FlowCal
FlowCal/plot.py
_LogicleLocator.set_params
def set_params(self, subs=None, numticks=None): """ Set parameters within this locator. Parameters ---------- subs : array, optional Subtick values, as multiples of the main ticks. numticks : array, optional Number of ticks. """ if numticks is not None: self.numticks = numticks if subs is not None: self._subs = subs
python
def set_params(self, subs=None, numticks=None): """ Set parameters within this locator. Parameters ---------- subs : array, optional Subtick values, as multiples of the main ticks. numticks : array, optional Number of ticks. """ if numticks is not None: self.numticks = numticks if subs is not None: self._subs = subs
[ "def", "set_params", "(", "self", ",", "subs", "=", "None", ",", "numticks", "=", "None", ")", ":", "if", "numticks", "is", "not", "None", ":", "self", ".", "numticks", "=", "numticks", "if", "subs", "is", "not", "None", ":", "self", ".", "_subs", ...
Set parameters within this locator. Parameters ---------- subs : array, optional Subtick values, as multiples of the main ticks. numticks : array, optional Number of ticks.
[ "Set", "parameters", "within", "this", "locator", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/plot.py#L407-L422
train
35,349
taborlab/FlowCal
FlowCal/plot.py
_LogicleLocator.view_limits
def view_limits(self, vmin, vmax): """ Try to choose the view limits intelligently. """ b = self._transform.base if vmax < vmin: vmin, vmax = vmax, vmin if not matplotlib.ticker.is_decade(abs(vmin), b): if vmin < 0: vmin = -matplotlib.ticker.decade_up(-vmin, b) else: vmin = matplotlib.ticker.decade_down(vmin, b) if not matplotlib.ticker.is_decade(abs(vmax), b): if vmax < 0: vmax = -matplotlib.ticker.decade_down(-vmax, b) else: vmax = matplotlib.ticker.decade_up(vmax, b) if vmin == vmax: if vmin < 0: vmin = -matplotlib.ticker.decade_up(-vmin, b) vmax = -matplotlib.ticker.decade_down(-vmax, b) else: vmin = matplotlib.ticker.decade_down(vmin, b) vmax = matplotlib.ticker.decade_up(vmax, b) result = matplotlib.transforms.nonsingular(vmin, vmax) return result
python
def view_limits(self, vmin, vmax): """ Try to choose the view limits intelligently. """ b = self._transform.base if vmax < vmin: vmin, vmax = vmax, vmin if not matplotlib.ticker.is_decade(abs(vmin), b): if vmin < 0: vmin = -matplotlib.ticker.decade_up(-vmin, b) else: vmin = matplotlib.ticker.decade_down(vmin, b) if not matplotlib.ticker.is_decade(abs(vmax), b): if vmax < 0: vmax = -matplotlib.ticker.decade_down(-vmax, b) else: vmax = matplotlib.ticker.decade_up(vmax, b) if vmin == vmax: if vmin < 0: vmin = -matplotlib.ticker.decade_up(-vmin, b) vmax = -matplotlib.ticker.decade_down(-vmax, b) else: vmin = matplotlib.ticker.decade_down(vmin, b) vmax = matplotlib.ticker.decade_up(vmax, b) result = matplotlib.transforms.nonsingular(vmin, vmax) return result
[ "def", "view_limits", "(", "self", ",", "vmin", ",", "vmax", ")", ":", "b", "=", "self", ".", "_transform", ".", "base", "if", "vmax", "<", "vmin", ":", "vmin", ",", "vmax", "=", "vmax", ",", "vmin", "if", "not", "matplotlib", ".", "ticker", ".", ...
Try to choose the view limits intelligently.
[ "Try", "to", "choose", "the", "view", "limits", "intelligently", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/plot.py#L611-L639
train
35,350
taborlab/FlowCal
FlowCal/plot.py
_LogicleScale.get_transform
def get_transform(self): """ Get a new object to perform the scaling transformation. """ return _InterpolatedInverseTransform(transform=self._transform, smin=0, smax=self._transform._M)
python
def get_transform(self): """ Get a new object to perform the scaling transformation. """ return _InterpolatedInverseTransform(transform=self._transform, smin=0, smax=self._transform._M)
[ "def", "get_transform", "(", "self", ")", ":", "return", "_InterpolatedInverseTransform", "(", "transform", "=", "self", ".", "_transform", ",", "smin", "=", "0", ",", "smax", "=", "self", ".", "_transform", ".", "_M", ")" ]
Get a new object to perform the scaling transformation.
[ "Get", "a", "new", "object", "to", "perform", "the", "scaling", "transformation", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/plot.py#L681-L688
train
35,351
taborlab/FlowCal
FlowCal/plot.py
_LogicleScale.set_default_locators_and_formatters
def set_default_locators_and_formatters(self, axis): """ Set up the locators and formatters for the scale. Parameters ---------- axis: matplotlib.axis Axis for which to set locators and formatters. """ axis.set_major_locator(_LogicleLocator(self._transform)) axis.set_minor_locator(_LogicleLocator(self._transform, subs=np.arange(2.0, 10.))) axis.set_major_formatter(matplotlib.ticker.LogFormatterSciNotation( labelOnlyBase=True))
python
def set_default_locators_and_formatters(self, axis): """ Set up the locators and formatters for the scale. Parameters ---------- axis: matplotlib.axis Axis for which to set locators and formatters. """ axis.set_major_locator(_LogicleLocator(self._transform)) axis.set_minor_locator(_LogicleLocator(self._transform, subs=np.arange(2.0, 10.))) axis.set_major_formatter(matplotlib.ticker.LogFormatterSciNotation( labelOnlyBase=True))
[ "def", "set_default_locators_and_formatters", "(", "self", ",", "axis", ")", ":", "axis", ".", "set_major_locator", "(", "_LogicleLocator", "(", "self", ".", "_transform", ")", ")", "axis", ".", "set_minor_locator", "(", "_LogicleLocator", "(", "self", ".", "_tr...
Set up the locators and formatters for the scale. Parameters ---------- axis: matplotlib.axis Axis for which to set locators and formatters.
[ "Set", "up", "the", "locators", "and", "formatters", "for", "the", "scale", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/plot.py#L690-L704
train
35,352
taborlab/FlowCal
FlowCal/plot.py
_LogicleScale.limit_range_for_scale
def limit_range_for_scale(self, vmin, vmax, minpos): """ Return minimum and maximum bounds for the logicle axis. Parameters ---------- vmin : float Minimum data value. vmax : float Maximum data value. minpos : float Minimum positive value in the data. Ignored by this function. Return ------ float Minimum axis bound. float Maximum axis bound. """ vmin_bound = self._transform.transform_non_affine(0) vmax_bound = self._transform.transform_non_affine(self._transform.M) vmin = max(vmin, vmin_bound) vmax = min(vmax, vmax_bound) return vmin, vmax
python
def limit_range_for_scale(self, vmin, vmax, minpos): """ Return minimum and maximum bounds for the logicle axis. Parameters ---------- vmin : float Minimum data value. vmax : float Maximum data value. minpos : float Minimum positive value in the data. Ignored by this function. Return ------ float Minimum axis bound. float Maximum axis bound. """ vmin_bound = self._transform.transform_non_affine(0) vmax_bound = self._transform.transform_non_affine(self._transform.M) vmin = max(vmin, vmin_bound) vmax = min(vmax, vmax_bound) return vmin, vmax
[ "def", "limit_range_for_scale", "(", "self", ",", "vmin", ",", "vmax", ",", "minpos", ")", ":", "vmin_bound", "=", "self", ".", "_transform", ".", "transform_non_affine", "(", "0", ")", "vmax_bound", "=", "self", ".", "_transform", ".", "transform_non_affine",...
Return minimum and maximum bounds for the logicle axis. Parameters ---------- vmin : float Minimum data value. vmax : float Maximum data value. minpos : float Minimum positive value in the data. Ignored by this function. Return ------ float Minimum axis bound. float Maximum axis bound.
[ "Return", "minimum", "and", "maximum", "bounds", "for", "the", "logicle", "axis", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/plot.py#L706-L731
train
35,353
taborlab/FlowCal
FlowCal/stats.py
mean
def mean(data, channels=None): """ Calculate the mean of the events in an FCSData object. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int or str or list of int or list of str, optional Channels on which to calculate the statistic. If None, use all channels. Returns ------- float or numpy array The mean of the events in the specified channels of `data`. """ # Slice data to take statistics from if channels is None: data_stats = data else: data_stats = data[:, channels] # Calculate and return statistic return np.mean(data_stats, axis=0)
python
def mean(data, channels=None): """ Calculate the mean of the events in an FCSData object. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int or str or list of int or list of str, optional Channels on which to calculate the statistic. If None, use all channels. Returns ------- float or numpy array The mean of the events in the specified channels of `data`. """ # Slice data to take statistics from if channels is None: data_stats = data else: data_stats = data[:, channels] # Calculate and return statistic return np.mean(data_stats, axis=0)
[ "def", "mean", "(", "data", ",", "channels", "=", "None", ")", ":", "# Slice data to take statistics from", "if", "channels", "is", "None", ":", "data_stats", "=", "data", "else", ":", "data_stats", "=", "data", "[", ":", ",", "channels", "]", "# Calculate a...
Calculate the mean of the events in an FCSData object. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int or str or list of int or list of str, optional Channels on which to calculate the statistic. If None, use all channels. Returns ------- float or numpy array The mean of the events in the specified channels of `data`.
[ "Calculate", "the", "mean", "of", "the", "events", "in", "an", "FCSData", "object", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/stats.py#L9-L35
train
35,354
taborlab/FlowCal
FlowCal/stats.py
gmean
def gmean(data, channels=None): """ Calculate the geometric mean of the events in an FCSData object. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int or str or list of int or list of str, optional Channels on which to calculate the statistic. If None, use all channels. Returns ------- float or numpy array The geometric mean of the events in the specified channels of `data`. """ # Slice data to take statistics from if channels is None: data_stats = data else: data_stats = data[:, channels] # Calculate and return statistic return scipy.stats.gmean(data_stats, axis=0)
python
def gmean(data, channels=None): """ Calculate the geometric mean of the events in an FCSData object. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int or str or list of int or list of str, optional Channels on which to calculate the statistic. If None, use all channels. Returns ------- float or numpy array The geometric mean of the events in the specified channels of `data`. """ # Slice data to take statistics from if channels is None: data_stats = data else: data_stats = data[:, channels] # Calculate and return statistic return scipy.stats.gmean(data_stats, axis=0)
[ "def", "gmean", "(", "data", ",", "channels", "=", "None", ")", ":", "# Slice data to take statistics from", "if", "channels", "is", "None", ":", "data_stats", "=", "data", "else", ":", "data_stats", "=", "data", "[", ":", ",", "channels", "]", "# Calculate ...
Calculate the geometric mean of the events in an FCSData object. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int or str or list of int or list of str, optional Channels on which to calculate the statistic. If None, use all channels. Returns ------- float or numpy array The geometric mean of the events in the specified channels of `data`.
[ "Calculate", "the", "geometric", "mean", "of", "the", "events", "in", "an", "FCSData", "object", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/stats.py#L37-L64
train
35,355
taborlab/FlowCal
FlowCal/stats.py
median
def median(data, channels=None): """ Calculate the median of the events in an FCSData object. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int or str or list of int or list of str, optional Channels on which to calculate the statistic. If None, use all channels. Returns ------- float or numpy array The median of the events in the specified channels of `data`. """ # Slice data to take statistics from if channels is None: data_stats = data else: data_stats = data[:, channels] # Calculate and return statistic return np.median(data_stats, axis=0)
python
def median(data, channels=None): """ Calculate the median of the events in an FCSData object. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int or str or list of int or list of str, optional Channels on which to calculate the statistic. If None, use all channels. Returns ------- float or numpy array The median of the events in the specified channels of `data`. """ # Slice data to take statistics from if channels is None: data_stats = data else: data_stats = data[:, channels] # Calculate and return statistic return np.median(data_stats, axis=0)
[ "def", "median", "(", "data", ",", "channels", "=", "None", ")", ":", "# Slice data to take statistics from", "if", "channels", "is", "None", ":", "data_stats", "=", "data", "else", ":", "data_stats", "=", "data", "[", ":", ",", "channels", "]", "# Calculate...
Calculate the median of the events in an FCSData object. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int or str or list of int or list of str, optional Channels on which to calculate the statistic. If None, use all channels. Returns ------- float or numpy array The median of the events in the specified channels of `data`.
[ "Calculate", "the", "median", "of", "the", "events", "in", "an", "FCSData", "object", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/stats.py#L66-L92
train
35,356
taborlab/FlowCal
FlowCal/stats.py
mode
def mode(data, channels=None): """ Calculate the mode of the events in an FCSData object. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int or str or list of int or list of str, optional Channels on which to calculate the statistic. If None, use all channels. Returns ------- float or numpy array The mode of the events in the specified channels of `data`. """ # Slice data to take statistics from if channels is None: data_stats = data else: data_stats = data[:, channels] # Calculate and return statistic # scipy.stats.mode returns two outputs, the first of which is an array # containing the modal values. This array has the same number of # dimensions as the input, and with only one element in the first # dimension. We extract this fist element to make it match the other # functions in this module. return scipy.stats.mode(data_stats, axis=0)[0][0]
python
def mode(data, channels=None): """ Calculate the mode of the events in an FCSData object. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int or str or list of int or list of str, optional Channels on which to calculate the statistic. If None, use all channels. Returns ------- float or numpy array The mode of the events in the specified channels of `data`. """ # Slice data to take statistics from if channels is None: data_stats = data else: data_stats = data[:, channels] # Calculate and return statistic # scipy.stats.mode returns two outputs, the first of which is an array # containing the modal values. This array has the same number of # dimensions as the input, and with only one element in the first # dimension. We extract this fist element to make it match the other # functions in this module. return scipy.stats.mode(data_stats, axis=0)[0][0]
[ "def", "mode", "(", "data", ",", "channels", "=", "None", ")", ":", "# Slice data to take statistics from", "if", "channels", "is", "None", ":", "data_stats", "=", "data", "else", ":", "data_stats", "=", "data", "[", ":", ",", "channels", "]", "# Calculate a...
Calculate the mode of the events in an FCSData object. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int or str or list of int or list of str, optional Channels on which to calculate the statistic. If None, use all channels. Returns ------- float or numpy array The mode of the events in the specified channels of `data`.
[ "Calculate", "the", "mode", "of", "the", "events", "in", "an", "FCSData", "object", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/stats.py#L94-L125
train
35,357
taborlab/FlowCal
FlowCal/stats.py
std
def std(data, channels=None): """ Calculate the standard deviation of the events in an FCSData object. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int or str or list of int or list of str, optional Channels on which to calculate the statistic. If None, use all channels. Returns ------- float or numpy array The standard deviation of the events in the specified channels of `data`. """ # Slice data to take statistics from if channels is None: data_stats = data else: data_stats = data[:, channels] # Calculate and return statistic return np.std(data_stats, axis=0)
python
def std(data, channels=None): """ Calculate the standard deviation of the events in an FCSData object. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int or str or list of int or list of str, optional Channels on which to calculate the statistic. If None, use all channels. Returns ------- float or numpy array The standard deviation of the events in the specified channels of `data`. """ # Slice data to take statistics from if channels is None: data_stats = data else: data_stats = data[:, channels] # Calculate and return statistic return np.std(data_stats, axis=0)
[ "def", "std", "(", "data", ",", "channels", "=", "None", ")", ":", "# Slice data to take statistics from", "if", "channels", "is", "None", ":", "data_stats", "=", "data", "else", ":", "data_stats", "=", "data", "[", ":", ",", "channels", "]", "# Calculate an...
Calculate the standard deviation of the events in an FCSData object. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int or str or list of int or list of str, optional Channels on which to calculate the statistic. If None, use all channels. Returns ------- float or numpy array The standard deviation of the events in the specified channels of `data`.
[ "Calculate", "the", "standard", "deviation", "of", "the", "events", "in", "an", "FCSData", "object", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/stats.py#L127-L154
train
35,358
taborlab/FlowCal
FlowCal/stats.py
cv
def cv(data, channels=None): """ Calculate the Coeff. of Variation of the events in an FCSData object. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int or str or list of int or list of str, optional Channels on which to calculate the statistic. If None, use all channels. Returns ------- float or numpy array The Coefficient of Variation of the events in the specified channels of `data`. Notes ----- The Coefficient of Variation (CV) of a dataset is defined as the standard deviation divided by the mean of such dataset. """ # Slice data to take statistics from if channels is None: data_stats = data else: data_stats = data[:, channels] # Calculate and return statistic return np.std(data_stats, axis=0) / np.mean(data_stats, axis=0)
python
def cv(data, channels=None): """ Calculate the Coeff. of Variation of the events in an FCSData object. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int or str or list of int or list of str, optional Channels on which to calculate the statistic. If None, use all channels. Returns ------- float or numpy array The Coefficient of Variation of the events in the specified channels of `data`. Notes ----- The Coefficient of Variation (CV) of a dataset is defined as the standard deviation divided by the mean of such dataset. """ # Slice data to take statistics from if channels is None: data_stats = data else: data_stats = data[:, channels] # Calculate and return statistic return np.std(data_stats, axis=0) / np.mean(data_stats, axis=0)
[ "def", "cv", "(", "data", ",", "channels", "=", "None", ")", ":", "# Slice data to take statistics from", "if", "channels", "is", "None", ":", "data_stats", "=", "data", "else", ":", "data_stats", "=", "data", "[", ":", ",", "channels", "]", "# Calculate and...
Calculate the Coeff. of Variation of the events in an FCSData object. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int or str or list of int or list of str, optional Channels on which to calculate the statistic. If None, use all channels. Returns ------- float or numpy array The Coefficient of Variation of the events in the specified channels of `data`. Notes ----- The Coefficient of Variation (CV) of a dataset is defined as the standard deviation divided by the mean of such dataset.
[ "Calculate", "the", "Coeff", ".", "of", "Variation", "of", "the", "events", "in", "an", "FCSData", "object", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/stats.py#L156-L188
train
35,359
taborlab/FlowCal
FlowCal/stats.py
gstd
def gstd(data, channels=None): """ Calculate the geometric std. dev. of the events in an FCSData object. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int or str or list of int or list of str, optional Channels on which to calculate the statistic. If None, use all channels. Returns ------- float or numpy array The geometric standard deviation of the events in the specified channels of `data`. """ # Slice data to take statistics from if channels is None: data_stats = data else: data_stats = data[:, channels] # Calculate and return statistic return np.exp(np.std(np.log(data_stats), axis=0))
python
def gstd(data, channels=None): """ Calculate the geometric std. dev. of the events in an FCSData object. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int or str or list of int or list of str, optional Channels on which to calculate the statistic. If None, use all channels. Returns ------- float or numpy array The geometric standard deviation of the events in the specified channels of `data`. """ # Slice data to take statistics from if channels is None: data_stats = data else: data_stats = data[:, channels] # Calculate and return statistic return np.exp(np.std(np.log(data_stats), axis=0))
[ "def", "gstd", "(", "data", ",", "channels", "=", "None", ")", ":", "# Slice data to take statistics from", "if", "channels", "is", "None", ":", "data_stats", "=", "data", "else", ":", "data_stats", "=", "data", "[", ":", ",", "channels", "]", "# Calculate a...
Calculate the geometric std. dev. of the events in an FCSData object. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int or str or list of int or list of str, optional Channels on which to calculate the statistic. If None, use all channels. Returns ------- float or numpy array The geometric standard deviation of the events in the specified channels of `data`.
[ "Calculate", "the", "geometric", "std", ".", "dev", ".", "of", "the", "events", "in", "an", "FCSData", "object", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/stats.py#L190-L217
train
35,360
taborlab/FlowCal
FlowCal/stats.py
gcv
def gcv(data, channels=None): """ Calculate the geometric CV of the events in an FCSData object. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int or str or list of int or list of str, optional Channels on which to calculate the statistic. If None, use all channels. Returns ------- float or numpy array The geometric coefficient of variation of the events in the specified channels of `data`. """ # Slice data to take statistics from if channels is None: data_stats = data else: data_stats = data[:, channels] # Calculate and return statistic return np.sqrt(np.exp(np.std(np.log(data_stats), axis=0)**2) - 1)
python
def gcv(data, channels=None): """ Calculate the geometric CV of the events in an FCSData object. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int or str or list of int or list of str, optional Channels on which to calculate the statistic. If None, use all channels. Returns ------- float or numpy array The geometric coefficient of variation of the events in the specified channels of `data`. """ # Slice data to take statistics from if channels is None: data_stats = data else: data_stats = data[:, channels] # Calculate and return statistic return np.sqrt(np.exp(np.std(np.log(data_stats), axis=0)**2) - 1)
[ "def", "gcv", "(", "data", ",", "channels", "=", "None", ")", ":", "# Slice data to take statistics from", "if", "channels", "is", "None", ":", "data_stats", "=", "data", "else", ":", "data_stats", "=", "data", "[", ":", ",", "channels", "]", "# Calculate an...
Calculate the geometric CV of the events in an FCSData object. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int or str or list of int or list of str, optional Channels on which to calculate the statistic. If None, use all channels. Returns ------- float or numpy array The geometric coefficient of variation of the events in the specified channels of `data`.
[ "Calculate", "the", "geometric", "CV", "of", "the", "events", "in", "an", "FCSData", "object", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/stats.py#L219-L246
train
35,361
taborlab/FlowCal
FlowCal/stats.py
iqr
def iqr(data, channels=None): """ Calculate the Interquartile Range of the events in an FCSData object. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int or str or list of int or list of str, optional Channels on which to calculate the statistic. If None, use all channels. Returns ------- float or numpy array The Interquartile Range of the events in the specified channels of `data`. Notes ----- The Interquartile Range (IQR) of a dataset is defined as the interval between the 25% and the 75% percentiles of such dataset. """ # Slice data to take statistics from if channels is None: data_stats = data else: data_stats = data[:, channels] # Calculate and return statistic q75, q25 = np.percentile(data_stats, [75 ,25], axis=0) return q75 - q25
python
def iqr(data, channels=None): """ Calculate the Interquartile Range of the events in an FCSData object. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int or str or list of int or list of str, optional Channels on which to calculate the statistic. If None, use all channels. Returns ------- float or numpy array The Interquartile Range of the events in the specified channels of `data`. Notes ----- The Interquartile Range (IQR) of a dataset is defined as the interval between the 25% and the 75% percentiles of such dataset. """ # Slice data to take statistics from if channels is None: data_stats = data else: data_stats = data[:, channels] # Calculate and return statistic q75, q25 = np.percentile(data_stats, [75 ,25], axis=0) return q75 - q25
[ "def", "iqr", "(", "data", ",", "channels", "=", "None", ")", ":", "# Slice data to take statistics from", "if", "channels", "is", "None", ":", "data_stats", "=", "data", "else", ":", "data_stats", "=", "data", "[", ":", ",", "channels", "]", "# Calculate an...
Calculate the Interquartile Range of the events in an FCSData object. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int or str or list of int or list of str, optional Channels on which to calculate the statistic. If None, use all channels. Returns ------- float or numpy array The Interquartile Range of the events in the specified channels of `data`. Notes ----- The Interquartile Range (IQR) of a dataset is defined as the interval between the 25% and the 75% percentiles of such dataset.
[ "Calculate", "the", "Interquartile", "Range", "of", "the", "events", "in", "an", "FCSData", "object", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/stats.py#L248-L281
train
35,362
taborlab/FlowCal
FlowCal/stats.py
rcv
def rcv(data, channels=None): """ Calculate the RCV of the events in an FCSData object. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int or str or list of int or list of str, optional Channels on which to calculate the statistic. If None, use all channels. Returns ------- float or numpy array The Robust Coefficient of Variation of the events in the specified channels of `data`. Notes ----- The Robust Coefficient of Variation (RCV) of a dataset is defined as the Interquartile Range (IQR) divided by the median of such dataset. """ # Slice data to take statistics from if channels is None: data_stats = data else: data_stats = data[:, channels] # Calculate and return statistic q75, q25 = np.percentile(data_stats, [75 ,25], axis=0) return (q75 - q25)/np.median(data_stats, axis=0)
python
def rcv(data, channels=None): """ Calculate the RCV of the events in an FCSData object. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int or str or list of int or list of str, optional Channels on which to calculate the statistic. If None, use all channels. Returns ------- float or numpy array The Robust Coefficient of Variation of the events in the specified channels of `data`. Notes ----- The Robust Coefficient of Variation (RCV) of a dataset is defined as the Interquartile Range (IQR) divided by the median of such dataset. """ # Slice data to take statistics from if channels is None: data_stats = data else: data_stats = data[:, channels] # Calculate and return statistic q75, q25 = np.percentile(data_stats, [75 ,25], axis=0) return (q75 - q25)/np.median(data_stats, axis=0)
[ "def", "rcv", "(", "data", ",", "channels", "=", "None", ")", ":", "# Slice data to take statistics from", "if", "channels", "is", "None", ":", "data_stats", "=", "data", "else", ":", "data_stats", "=", "data", "[", ":", ",", "channels", "]", "# Calculate an...
Calculate the RCV of the events in an FCSData object. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int or str or list of int or list of str, optional Channels on which to calculate the statistic. If None, use all channels. Returns ------- float or numpy array The Robust Coefficient of Variation of the events in the specified channels of `data`. Notes ----- The Robust Coefficient of Variation (RCV) of a dataset is defined as the Interquartile Range (IQR) divided by the median of such dataset.
[ "Calculate", "the", "RCV", "of", "the", "events", "in", "an", "FCSData", "object", "." ]
031a7af82acb1d46879a8e384a1a00f27f0bdc7a
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/stats.py#L283-L316
train
35,363
Roguelazer/muttdown
muttdown/main.py
convert_tree
def convert_tree(message, config, indent=0, wrap_alternative=True, charset=None): """Recursively convert a potentially-multipart tree. Returns a tuple of (the converted tree, whether any markdown was found) """ ct = message.get_content_type() cs = message.get_content_subtype() if charset is None: charset = get_charset_from_message_fragment(message) if not message.is_multipart(): # we're on a leaf converted = None disposition = message.get('Content-Disposition', 'inline') if disposition == 'inline' and ct in ('text/plain', 'text/markdown'): converted = convert_one(message, config, charset) if converted is not None: if wrap_alternative: new_tree = MIMEMultipart('alternative') _move_headers(message, new_tree) new_tree.attach(message) new_tree.attach(converted) return new_tree, True else: return converted, True return message, False else: if ct == 'multipart/signed': # if this is a multipart/signed message, then let's just # recurse into the non-signature part new_root = MIMEMultipart('alternative') if message.preamble: new_root.preamble = message.preamble _move_headers(message, new_root) converted = None for part in message.get_payload(): if part.get_content_type() != 'application/pgp-signature': converted, did_conversion = convert_tree(part, config, indent=indent + 1, wrap_alternative=False, charset=charset) if did_conversion: new_root.attach(converted) new_root.attach(message) return new_root, did_conversion else: did_conversion = False new_root = MIMEMultipart(cs, message.get_charset()) if message.preamble: new_root.preamble = message.preamble _move_headers(message, new_root) for part in message.get_payload(): part, did_this_conversion = convert_tree(part, config, indent=indent + 1, charset=charset) did_conversion |= did_this_conversion new_root.attach(part) return new_root, did_conversion
python
def convert_tree(message, config, indent=0, wrap_alternative=True, charset=None): """Recursively convert a potentially-multipart tree. Returns a tuple of (the converted tree, whether any markdown was found) """ ct = message.get_content_type() cs = message.get_content_subtype() if charset is None: charset = get_charset_from_message_fragment(message) if not message.is_multipart(): # we're on a leaf converted = None disposition = message.get('Content-Disposition', 'inline') if disposition == 'inline' and ct in ('text/plain', 'text/markdown'): converted = convert_one(message, config, charset) if converted is not None: if wrap_alternative: new_tree = MIMEMultipart('alternative') _move_headers(message, new_tree) new_tree.attach(message) new_tree.attach(converted) return new_tree, True else: return converted, True return message, False else: if ct == 'multipart/signed': # if this is a multipart/signed message, then let's just # recurse into the non-signature part new_root = MIMEMultipart('alternative') if message.preamble: new_root.preamble = message.preamble _move_headers(message, new_root) converted = None for part in message.get_payload(): if part.get_content_type() != 'application/pgp-signature': converted, did_conversion = convert_tree(part, config, indent=indent + 1, wrap_alternative=False, charset=charset) if did_conversion: new_root.attach(converted) new_root.attach(message) return new_root, did_conversion else: did_conversion = False new_root = MIMEMultipart(cs, message.get_charset()) if message.preamble: new_root.preamble = message.preamble _move_headers(message, new_root) for part in message.get_payload(): part, did_this_conversion = convert_tree(part, config, indent=indent + 1, charset=charset) did_conversion |= did_this_conversion new_root.attach(part) return new_root, did_conversion
[ "def", "convert_tree", "(", "message", ",", "config", ",", "indent", "=", "0", ",", "wrap_alternative", "=", "True", ",", "charset", "=", "None", ")", ":", "ct", "=", "message", ".", "get_content_type", "(", ")", "cs", "=", "message", ".", "get_content_s...
Recursively convert a potentially-multipart tree. Returns a tuple of (the converted tree, whether any markdown was found)
[ "Recursively", "convert", "a", "potentially", "-", "multipart", "tree", "." ]
5aeb514ba5c4eac00db8dc3690daba60f778076c
https://github.com/Roguelazer/muttdown/blob/5aeb514ba5c4eac00db8dc3690daba60f778076c/muttdown/main.py#L75-L128
train
35,364
Roguelazer/muttdown
muttdown/main.py
smtp_connection
def smtp_connection(c): """Create an SMTP connection from a Config object""" if c.smtp_ssl: klass = smtplib.SMTP_SSL else: klass = smtplib.SMTP conn = klass(c.smtp_host, c.smtp_port, timeout=c.smtp_timeout) if not c.smtp_ssl: conn.ehlo() conn.starttls() conn.ehlo() if c.smtp_username: conn.login(c.smtp_username, c.smtp_password) return conn
python
def smtp_connection(c): """Create an SMTP connection from a Config object""" if c.smtp_ssl: klass = smtplib.SMTP_SSL else: klass = smtplib.SMTP conn = klass(c.smtp_host, c.smtp_port, timeout=c.smtp_timeout) if not c.smtp_ssl: conn.ehlo() conn.starttls() conn.ehlo() if c.smtp_username: conn.login(c.smtp_username, c.smtp_password) return conn
[ "def", "smtp_connection", "(", "c", ")", ":", "if", "c", ".", "smtp_ssl", ":", "klass", "=", "smtplib", ".", "SMTP_SSL", "else", ":", "klass", "=", "smtplib", ".", "SMTP", "conn", "=", "klass", "(", "c", ".", "smtp_host", ",", "c", ".", "smtp_port", ...
Create an SMTP connection from a Config object
[ "Create", "an", "SMTP", "connection", "from", "a", "Config", "object" ]
5aeb514ba5c4eac00db8dc3690daba60f778076c
https://github.com/Roguelazer/muttdown/blob/5aeb514ba5c4eac00db8dc3690daba60f778076c/muttdown/main.py#L138-L151
train
35,365
mollie/mollie-api-python
mollie/api/objects/method.py
Method.issuers
def issuers(self): """Return the list of available issuers for this payment method.""" issuers = self._get_property('issuers') or [] result = { '_embedded': { 'issuers': issuers, }, 'count': len(issuers), } return List(result, Issuer)
python
def issuers(self): """Return the list of available issuers for this payment method.""" issuers = self._get_property('issuers') or [] result = { '_embedded': { 'issuers': issuers, }, 'count': len(issuers), } return List(result, Issuer)
[ "def", "issuers", "(", "self", ")", ":", "issuers", "=", "self", ".", "_get_property", "(", "'issuers'", ")", "or", "[", "]", "result", "=", "{", "'_embedded'", ":", "{", "'issuers'", ":", "issuers", ",", "}", ",", "'count'", ":", "len", "(", "issuer...
Return the list of available issuers for this payment method.
[ "Return", "the", "list", "of", "available", "issuers", "for", "this", "payment", "method", "." ]
307836b70f0439c066718f1e375fa333dc6e5d77
https://github.com/mollie/mollie-api-python/blob/307836b70f0439c066718f1e375fa333dc6e5d77/mollie/api/objects/method.py#L65-L74
train
35,366
mollie/mollie-api-python
mollie/api/resources/payments.py
Payments.delete
def delete(self, payment_id, data=None): """Cancel payment and return the payment object. Deleting a payment causes the payment status to change to canceled. The updated payment object is returned. """ if not payment_id or not payment_id.startswith(self.RESOURCE_ID_PREFIX): raise IdentifierError( "Invalid payment ID: '{id}'. A payment ID should start with '{prefix}'.".format( id=payment_id, prefix=self.RESOURCE_ID_PREFIX) ) result = super(Payments, self).delete(payment_id, data) return self.get_resource_object(result)
python
def delete(self, payment_id, data=None): """Cancel payment and return the payment object. Deleting a payment causes the payment status to change to canceled. The updated payment object is returned. """ if not payment_id or not payment_id.startswith(self.RESOURCE_ID_PREFIX): raise IdentifierError( "Invalid payment ID: '{id}'. A payment ID should start with '{prefix}'.".format( id=payment_id, prefix=self.RESOURCE_ID_PREFIX) ) result = super(Payments, self).delete(payment_id, data) return self.get_resource_object(result)
[ "def", "delete", "(", "self", ",", "payment_id", ",", "data", "=", "None", ")", ":", "if", "not", "payment_id", "or", "not", "payment_id", ".", "startswith", "(", "self", ".", "RESOURCE_ID_PREFIX", ")", ":", "raise", "IdentifierError", "(", "\"Invalid paymen...
Cancel payment and return the payment object. Deleting a payment causes the payment status to change to canceled. The updated payment object is returned.
[ "Cancel", "payment", "and", "return", "the", "payment", "object", "." ]
307836b70f0439c066718f1e375fa333dc6e5d77
https://github.com/mollie/mollie-api-python/blob/307836b70f0439c066718f1e375fa333dc6e5d77/mollie/api/resources/payments.py#L20-L32
train
35,367
mollie/mollie-api-python
mollie/api/objects/payment.py
Payment.mandate
def mandate(self): """Return the mandate for this payment.""" return self.client.customer_mandates.with_parent_id(self.customer_id).get(self.mandate_id)
python
def mandate(self): """Return the mandate for this payment.""" return self.client.customer_mandates.with_parent_id(self.customer_id).get(self.mandate_id)
[ "def", "mandate", "(", "self", ")", ":", "return", "self", ".", "client", ".", "customer_mandates", ".", "with_parent_id", "(", "self", ".", "customer_id", ")", ".", "get", "(", "self", ".", "mandate_id", ")" ]
Return the mandate for this payment.
[ "Return", "the", "mandate", "for", "this", "payment", "." ]
307836b70f0439c066718f1e375fa333dc6e5d77
https://github.com/mollie/mollie-api-python/blob/307836b70f0439c066718f1e375fa333dc6e5d77/mollie/api/objects/payment.py#L178-L180
train
35,368
mollie/mollie-api-python
mollie/api/objects/payment.py
Payment.subscription
def subscription(self): """Return the subscription for this payment.""" return self.client.customer_subscriptions.with_parent_id(self.customer_id).get(self.subscription_id)
python
def subscription(self): """Return the subscription for this payment.""" return self.client.customer_subscriptions.with_parent_id(self.customer_id).get(self.subscription_id)
[ "def", "subscription", "(", "self", ")", ":", "return", "self", ".", "client", ".", "customer_subscriptions", ".", "with_parent_id", "(", "self", ".", "customer_id", ")", ".", "get", "(", "self", ".", "subscription_id", ")" ]
Return the subscription for this payment.
[ "Return", "the", "subscription", "for", "this", "payment", "." ]
307836b70f0439c066718f1e375fa333dc6e5d77
https://github.com/mollie/mollie-api-python/blob/307836b70f0439c066718f1e375fa333dc6e5d77/mollie/api/objects/payment.py#L183-L185
train
35,369
mollie/mollie-api-python
mollie/api/objects/payment.py
Payment.order
def order(self): """Return the order for this payment. """ from ..resources.orders import Order url = self._get_link('order') if url: resp = self.client.orders.perform_api_call(self.client.orders.REST_READ, url) return Order(resp, self.client)
python
def order(self): """Return the order for this payment. """ from ..resources.orders import Order url = self._get_link('order') if url: resp = self.client.orders.perform_api_call(self.client.orders.REST_READ, url) return Order(resp, self.client)
[ "def", "order", "(", "self", ")", ":", "from", ".", ".", "resources", ".", "orders", "import", "Order", "url", "=", "self", ".", "_get_link", "(", "'order'", ")", "if", "url", ":", "resp", "=", "self", ".", "client", ".", "orders", ".", "perform_api_...
Return the order for this payment.
[ "Return", "the", "order", "for", "this", "payment", "." ]
307836b70f0439c066718f1e375fa333dc6e5d77
https://github.com/mollie/mollie-api-python/blob/307836b70f0439c066718f1e375fa333dc6e5d77/mollie/api/objects/payment.py#L193-L199
train
35,370
mollie/mollie-api-python
mollie/api/objects/order.py
Order.create_refund
def create_refund(self, data=None, **params): """Create a refund for the order. When no data arg is given, a refund for all order lines is assumed.""" if data is None: data = {'lines': []} refund = OrderRefunds(self.client).on(self).create(data, **params) return refund
python
def create_refund(self, data=None, **params): """Create a refund for the order. When no data arg is given, a refund for all order lines is assumed.""" if data is None: data = {'lines': []} refund = OrderRefunds(self.client).on(self).create(data, **params) return refund
[ "def", "create_refund", "(", "self", ",", "data", "=", "None", ",", "*", "*", "params", ")", ":", "if", "data", "is", "None", ":", "data", "=", "{", "'lines'", ":", "[", "]", "}", "refund", "=", "OrderRefunds", "(", "self", ".", "client", ")", "....
Create a refund for the order. When no data arg is given, a refund for all order lines is assumed.
[ "Create", "a", "refund", "for", "the", "order", ".", "When", "no", "data", "arg", "is", "given", "a", "refund", "for", "all", "order", "lines", "is", "assumed", "." ]
307836b70f0439c066718f1e375fa333dc6e5d77
https://github.com/mollie/mollie-api-python/blob/307836b70f0439c066718f1e375fa333dc6e5d77/mollie/api/objects/order.py#L153-L158
train
35,371
mollie/mollie-api-python
mollie/api/objects/order.py
Order.cancel_lines
def cancel_lines(self, data=None): """Cancel the lines given. When no lines are given, cancel all the lines. Canceling an order line causes the order line status to change to canceled. An empty dictionary will be returned. """ from ..resources.order_lines import OrderLines if data is None: data = {'lines': []} canceled = OrderLines(self.client).on(self).delete(data) return canceled
python
def cancel_lines(self, data=None): """Cancel the lines given. When no lines are given, cancel all the lines. Canceling an order line causes the order line status to change to canceled. An empty dictionary will be returned. """ from ..resources.order_lines import OrderLines if data is None: data = {'lines': []} canceled = OrderLines(self.client).on(self).delete(data) return canceled
[ "def", "cancel_lines", "(", "self", ",", "data", "=", "None", ")", ":", "from", ".", ".", "resources", ".", "order_lines", "import", "OrderLines", "if", "data", "is", "None", ":", "data", "=", "{", "'lines'", ":", "[", "]", "}", "canceled", "=", "Ord...
Cancel the lines given. When no lines are given, cancel all the lines. Canceling an order line causes the order line status to change to canceled. An empty dictionary will be returned.
[ "Cancel", "the", "lines", "given", ".", "When", "no", "lines", "are", "given", "cancel", "all", "the", "lines", "." ]
307836b70f0439c066718f1e375fa333dc6e5d77
https://github.com/mollie/mollie-api-python/blob/307836b70f0439c066718f1e375fa333dc6e5d77/mollie/api/objects/order.py#L160-L171
train
35,372
mollie/mollie-api-python
mollie/api/objects/order.py
Order.update_line
def update_line(self, resource_id, data): """Update a line for an order.""" return OrderLines(self.client).on(self).update(resource_id, data)
python
def update_line(self, resource_id, data): """Update a line for an order.""" return OrderLines(self.client).on(self).update(resource_id, data)
[ "def", "update_line", "(", "self", ",", "resource_id", ",", "data", ")", ":", "return", "OrderLines", "(", "self", ".", "client", ")", ".", "on", "(", "self", ")", ".", "update", "(", "resource_id", ",", "data", ")" ]
Update a line for an order.
[ "Update", "a", "line", "for", "an", "order", "." ]
307836b70f0439c066718f1e375fa333dc6e5d77
https://github.com/mollie/mollie-api-python/blob/307836b70f0439c066718f1e375fa333dc6e5d77/mollie/api/objects/order.py#L189-L191
train
35,373
mollie/mollie-api-python
mollie/api/objects/order.py
Order.create_shipment
def create_shipment(self, data=None): """Create a shipment for an order. When no data arg is given, a shipment for all order lines is assumed.""" if data is None: data = {'lines': []} return Shipments(self.client).on(self).create(data)
python
def create_shipment(self, data=None): """Create a shipment for an order. When no data arg is given, a shipment for all order lines is assumed.""" if data is None: data = {'lines': []} return Shipments(self.client).on(self).create(data)
[ "def", "create_shipment", "(", "self", ",", "data", "=", "None", ")", ":", "if", "data", "is", "None", ":", "data", "=", "{", "'lines'", ":", "[", "]", "}", "return", "Shipments", "(", "self", ".", "client", ")", ".", "on", "(", "self", ")", ".",...
Create a shipment for an order. When no data arg is given, a shipment for all order lines is assumed.
[ "Create", "a", "shipment", "for", "an", "order", ".", "When", "no", "data", "arg", "is", "given", "a", "shipment", "for", "all", "order", "lines", "is", "assumed", "." ]
307836b70f0439c066718f1e375fa333dc6e5d77
https://github.com/mollie/mollie-api-python/blob/307836b70f0439c066718f1e375fa333dc6e5d77/mollie/api/objects/order.py#L198-L202
train
35,374
mollie/mollie-api-python
mollie/api/objects/order.py
Order.get_shipment
def get_shipment(self, resource_id): """Retrieve a single shipment by a shipment's ID.""" return Shipments(self.client).on(self).get(resource_id)
python
def get_shipment(self, resource_id): """Retrieve a single shipment by a shipment's ID.""" return Shipments(self.client).on(self).get(resource_id)
[ "def", "get_shipment", "(", "self", ",", "resource_id", ")", ":", "return", "Shipments", "(", "self", ".", "client", ")", ".", "on", "(", "self", ")", ".", "get", "(", "resource_id", ")" ]
Retrieve a single shipment by a shipment's ID.
[ "Retrieve", "a", "single", "shipment", "by", "a", "shipment", "s", "ID", "." ]
307836b70f0439c066718f1e375fa333dc6e5d77
https://github.com/mollie/mollie-api-python/blob/307836b70f0439c066718f1e375fa333dc6e5d77/mollie/api/objects/order.py#L204-L206
train
35,375
mollie/mollie-api-python
mollie/api/objects/order.py
Order.update_shipment
def update_shipment(self, resource_id, data): """Update the tracking information of a shipment.""" return Shipments(self.client).on(self).update(resource_id, data)
python
def update_shipment(self, resource_id, data): """Update the tracking information of a shipment.""" return Shipments(self.client).on(self).update(resource_id, data)
[ "def", "update_shipment", "(", "self", ",", "resource_id", ",", "data", ")", ":", "return", "Shipments", "(", "self", ".", "client", ")", ".", "on", "(", "self", ")", ".", "update", "(", "resource_id", ",", "data", ")" ]
Update the tracking information of a shipment.
[ "Update", "the", "tracking", "information", "of", "a", "shipment", "." ]
307836b70f0439c066718f1e375fa333dc6e5d77
https://github.com/mollie/mollie-api-python/blob/307836b70f0439c066718f1e375fa333dc6e5d77/mollie/api/objects/order.py#L208-L210
train
35,376
mollie/mollie-api-python
mollie/api/objects/order.py
Order.create_payment
def create_payment(self, data): """ Creates a new payment object for an order. """ return OrderPayments(self.client).on(self).create(data)
python
def create_payment(self, data): """ Creates a new payment object for an order. """ return OrderPayments(self.client).on(self).create(data)
[ "def", "create_payment", "(", "self", ",", "data", ")", ":", "return", "OrderPayments", "(", "self", ".", "client", ")", ".", "on", "(", "self", ")", ".", "create", "(", "data", ")" ]
Creates a new payment object for an order.
[ "Creates", "a", "new", "payment", "object", "for", "an", "order", "." ]
307836b70f0439c066718f1e375fa333dc6e5d77
https://github.com/mollie/mollie-api-python/blob/307836b70f0439c066718f1e375fa333dc6e5d77/mollie/api/objects/order.py#L212-L214
train
35,377
mollie/mollie-api-python
mollie/api/resources/order_lines.py
OrderLines.delete
def delete(self, data, *args): """ Custom handling for deleting orderlines. Orderlines are deleted by issuing a DELETE on the orders/*/lines endpoint, with the orderline IDs and quantities in the request body. """ path = self.get_resource_name() result = self.perform_api_call(self.REST_DELETE, path, data=data) return result
python
def delete(self, data, *args): """ Custom handling for deleting orderlines. Orderlines are deleted by issuing a DELETE on the orders/*/lines endpoint, with the orderline IDs and quantities in the request body. """ path = self.get_resource_name() result = self.perform_api_call(self.REST_DELETE, path, data=data) return result
[ "def", "delete", "(", "self", ",", "data", ",", "*", "args", ")", ":", "path", "=", "self", ".", "get_resource_name", "(", ")", "result", "=", "self", ".", "perform_api_call", "(", "self", ".", "REST_DELETE", ",", "path", ",", "data", "=", "data", ")...
Custom handling for deleting orderlines. Orderlines are deleted by issuing a DELETE on the orders/*/lines endpoint, with the orderline IDs and quantities in the request body.
[ "Custom", "handling", "for", "deleting", "orderlines", "." ]
307836b70f0439c066718f1e375fa333dc6e5d77
https://github.com/mollie/mollie-api-python/blob/307836b70f0439c066718f1e375fa333dc6e5d77/mollie/api/resources/order_lines.py#L22-L31
train
35,378
mollie/mollie-api-python
mollie/api/resources/order_lines.py
OrderLines.update
def update(self, resource_id, data=None, **params): """ Custom handling for updating orderlines. The API returns an Order object. Since we are sending the request through an orderline object, it makes more sense to convert the returned object to to the updated orderline object. If you wish to retrieve the order object, you can do so by using the order_id property of the orderline. """ path = self.get_resource_name() + '/' + str(resource_id) result = self.perform_api_call(self.REST_UPDATE, path, data=data) for line in result['lines']: if line['id'] == resource_id: return self.get_resource_object(line) raise DataConsistencyError('Line id {resource_id} not found in response.'.format(resource_id=resource_id))
python
def update(self, resource_id, data=None, **params): """ Custom handling for updating orderlines. The API returns an Order object. Since we are sending the request through an orderline object, it makes more sense to convert the returned object to to the updated orderline object. If you wish to retrieve the order object, you can do so by using the order_id property of the orderline. """ path = self.get_resource_name() + '/' + str(resource_id) result = self.perform_api_call(self.REST_UPDATE, path, data=data) for line in result['lines']: if line['id'] == resource_id: return self.get_resource_object(line) raise DataConsistencyError('Line id {resource_id} not found in response.'.format(resource_id=resource_id))
[ "def", "update", "(", "self", ",", "resource_id", ",", "data", "=", "None", ",", "*", "*", "params", ")", ":", "path", "=", "self", ".", "get_resource_name", "(", ")", "+", "'/'", "+", "str", "(", "resource_id", ")", "result", "=", "self", ".", "pe...
Custom handling for updating orderlines. The API returns an Order object. Since we are sending the request through an orderline object, it makes more sense to convert the returned object to to the updated orderline object. If you wish to retrieve the order object, you can do so by using the order_id property of the orderline.
[ "Custom", "handling", "for", "updating", "orderlines", "." ]
307836b70f0439c066718f1e375fa333dc6e5d77
https://github.com/mollie/mollie-api-python/blob/307836b70f0439c066718f1e375fa333dc6e5d77/mollie/api/resources/order_lines.py#L33-L48
train
35,379
mollie/mollie-api-python
mollie/api/objects/list.py
List.get_next
def get_next(self): """Return the next set of objects in a list""" url = self._get_link('next') resource = self.object_type.get_resource_class(self.client) resp = resource.perform_api_call(resource.REST_READ, url) return List(resp, self.object_type, self.client)
python
def get_next(self): """Return the next set of objects in a list""" url = self._get_link('next') resource = self.object_type.get_resource_class(self.client) resp = resource.perform_api_call(resource.REST_READ, url) return List(resp, self.object_type, self.client)
[ "def", "get_next", "(", "self", ")", ":", "url", "=", "self", ".", "_get_link", "(", "'next'", ")", "resource", "=", "self", ".", "object_type", ".", "get_resource_class", "(", "self", ".", "client", ")", "resp", "=", "resource", ".", "perform_api_call", ...
Return the next set of objects in a list
[ "Return", "the", "next", "set", "of", "objects", "in", "a", "list" ]
307836b70f0439c066718f1e375fa333dc6e5d77
https://github.com/mollie/mollie-api-python/blob/307836b70f0439c066718f1e375fa333dc6e5d77/mollie/api/objects/list.py#L49-L54
train
35,380
mollie/mollie-api-python
mollie/api/resources/customer_subscriptions.py
CustomerSubscriptions.delete
def delete(self, subscription_id, data=None): """Cancel subscription and return the subscription object. Deleting a subscription causes the subscription status to changed to 'canceled'. The updated subscription object is returned. """ if not subscription_id or not subscription_id.startswith(self.RESOURCE_ID_PREFIX): raise IdentifierError( "Invalid subscription ID: '{id}'. A subscription ID should start with '{prefix}'.".format( id=subscription_id, prefix=self.RESOURCE_ID_PREFIX) ) result = super(CustomerSubscriptions, self).delete(subscription_id, data) return self.get_resource_object(result)
python
def delete(self, subscription_id, data=None): """Cancel subscription and return the subscription object. Deleting a subscription causes the subscription status to changed to 'canceled'. The updated subscription object is returned. """ if not subscription_id or not subscription_id.startswith(self.RESOURCE_ID_PREFIX): raise IdentifierError( "Invalid subscription ID: '{id}'. A subscription ID should start with '{prefix}'.".format( id=subscription_id, prefix=self.RESOURCE_ID_PREFIX) ) result = super(CustomerSubscriptions, self).delete(subscription_id, data) return self.get_resource_object(result)
[ "def", "delete", "(", "self", ",", "subscription_id", ",", "data", "=", "None", ")", ":", "if", "not", "subscription_id", "or", "not", "subscription_id", ".", "startswith", "(", "self", ".", "RESOURCE_ID_PREFIX", ")", ":", "raise", "IdentifierError", "(", "\...
Cancel subscription and return the subscription object. Deleting a subscription causes the subscription status to changed to 'canceled'. The updated subscription object is returned.
[ "Cancel", "subscription", "and", "return", "the", "subscription", "object", "." ]
307836b70f0439c066718f1e375fa333dc6e5d77
https://github.com/mollie/mollie-api-python/blob/307836b70f0439c066718f1e375fa333dc6e5d77/mollie/api/resources/customer_subscriptions.py#L21-L33
train
35,381
mollie/mollie-api-python
mollie/api/resources/chargebacks.py
Chargebacks.get
def get(self, chargeback_id, **params): """Verify the chargeback ID and retrieve the chargeback from the API.""" if not chargeback_id or not chargeback_id.startswith(self.RESOURCE_ID_PREFIX): raise IdentifierError( "Invalid chargeback ID: '{id}'. A chargeback ID should start with '{prefix}'.".format( id=chargeback_id, prefix=self.RESOURCE_ID_PREFIX) ) return super(Chargebacks, self).get(chargeback_id, **params)
python
def get(self, chargeback_id, **params): """Verify the chargeback ID and retrieve the chargeback from the API.""" if not chargeback_id or not chargeback_id.startswith(self.RESOURCE_ID_PREFIX): raise IdentifierError( "Invalid chargeback ID: '{id}'. A chargeback ID should start with '{prefix}'.".format( id=chargeback_id, prefix=self.RESOURCE_ID_PREFIX) ) return super(Chargebacks, self).get(chargeback_id, **params)
[ "def", "get", "(", "self", ",", "chargeback_id", ",", "*", "*", "params", ")", ":", "if", "not", "chargeback_id", "or", "not", "chargeback_id", ".", "startswith", "(", "self", ".", "RESOURCE_ID_PREFIX", ")", ":", "raise", "IdentifierError", "(", "\"Invalid c...
Verify the chargeback ID and retrieve the chargeback from the API.
[ "Verify", "the", "chargeback", "ID", "and", "retrieve", "the", "chargeback", "from", "the", "API", "." ]
307836b70f0439c066718f1e375fa333dc6e5d77
https://github.com/mollie/mollie-api-python/blob/307836b70f0439c066718f1e375fa333dc6e5d77/mollie/api/resources/chargebacks.py#L12-L19
train
35,382
mollie/mollie-api-python
mollie/api/client.py
generate_querystring
def generate_querystring(params): """ Generate a querystring suitable for use in the v2 api. The Requests library doesn't know how to generate querystrings that encode dictionaries using square brackets: https://api.mollie.com/v2/methods?amount[value]=100.00&amount[currency]=USD Note: we use `sorted()` to work around a difference in iteration behaviour between Python 2 and 3. This makes the output predictable, and ordering of querystring parameters shouldn't matter. """ if not params: return None parts = [] for param, value in sorted(params.items()): if not isinstance(value, dict): parts.append(urlencode({param: value})) else: # encode dictionary with square brackets for key, sub_value in sorted(value.items()): composed = '{param}[{key}]'.format(param=param, key=key) parts.append(urlencode({composed: sub_value})) if parts: return '&'.join(parts)
python
def generate_querystring(params): """ Generate a querystring suitable for use in the v2 api. The Requests library doesn't know how to generate querystrings that encode dictionaries using square brackets: https://api.mollie.com/v2/methods?amount[value]=100.00&amount[currency]=USD Note: we use `sorted()` to work around a difference in iteration behaviour between Python 2 and 3. This makes the output predictable, and ordering of querystring parameters shouldn't matter. """ if not params: return None parts = [] for param, value in sorted(params.items()): if not isinstance(value, dict): parts.append(urlencode({param: value})) else: # encode dictionary with square brackets for key, sub_value in sorted(value.items()): composed = '{param}[{key}]'.format(param=param, key=key) parts.append(urlencode({composed: sub_value})) if parts: return '&'.join(parts)
[ "def", "generate_querystring", "(", "params", ")", ":", "if", "not", "params", ":", "return", "None", "parts", "=", "[", "]", "for", "param", ",", "value", "in", "sorted", "(", "params", ".", "items", "(", ")", ")", ":", "if", "not", "isinstance", "(...
Generate a querystring suitable for use in the v2 api. The Requests library doesn't know how to generate querystrings that encode dictionaries using square brackets: https://api.mollie.com/v2/methods?amount[value]=100.00&amount[currency]=USD Note: we use `sorted()` to work around a difference in iteration behaviour between Python 2 and 3. This makes the output predictable, and ordering of querystring parameters shouldn't matter.
[ "Generate", "a", "querystring", "suitable", "for", "use", "in", "the", "v2", "api", "." ]
307836b70f0439c066718f1e375fa333dc6e5d77
https://github.com/mollie/mollie-api-python/blob/307836b70f0439c066718f1e375fa333dc6e5d77/mollie/api/client.py#L172-L194
train
35,383
mollie/mollie-api-python
mollie/api/client.py
Client.set_user_agent_component
def set_user_agent_component(self, key, value, sanitize=True): """Add or replace new user-agent component strings. Given strings are formatted along the format agreed upon by Mollie and implementers: - key and values are separated by a forward slash ("/"). - multiple key/values are separated by a space. - keys are camel-cased, and cannot contain spaces. - values cannot contain spaces. Note: When you set sanitize=false yuu need to make sure the formatting is correct yourself. """ if sanitize: key = ''.join(_x.capitalize() for _x in re.findall(r'\S+', key)) if re.search(r'\s+', value): value = '_'.join(re.findall(r'\S+', value)) self.user_agent_components[key] = value
python
def set_user_agent_component(self, key, value, sanitize=True): """Add or replace new user-agent component strings. Given strings are formatted along the format agreed upon by Mollie and implementers: - key and values are separated by a forward slash ("/"). - multiple key/values are separated by a space. - keys are camel-cased, and cannot contain spaces. - values cannot contain spaces. Note: When you set sanitize=false yuu need to make sure the formatting is correct yourself. """ if sanitize: key = ''.join(_x.capitalize() for _x in re.findall(r'\S+', key)) if re.search(r'\s+', value): value = '_'.join(re.findall(r'\S+', value)) self.user_agent_components[key] = value
[ "def", "set_user_agent_component", "(", "self", ",", "key", ",", "value", ",", "sanitize", "=", "True", ")", ":", "if", "sanitize", ":", "key", "=", "''", ".", "join", "(", "_x", ".", "capitalize", "(", ")", "for", "_x", "in", "re", ".", "findall", ...
Add or replace new user-agent component strings. Given strings are formatted along the format agreed upon by Mollie and implementers: - key and values are separated by a forward slash ("/"). - multiple key/values are separated by a space. - keys are camel-cased, and cannot contain spaces. - values cannot contain spaces. Note: When you set sanitize=false yuu need to make sure the formatting is correct yourself.
[ "Add", "or", "replace", "new", "user", "-", "agent", "component", "strings", "." ]
307836b70f0439c066718f1e375fa333dc6e5d77
https://github.com/mollie/mollie-api-python/blob/307836b70f0439c066718f1e375fa333dc6e5d77/mollie/api/client.py#L110-L125
train
35,384
mollie/mollie-api-python
mollie/api/client.py
Client.user_agent
def user_agent(self): """Return the formatted user agent string.""" components = ["/".join(x) for x in self.user_agent_components.items()] return " ".join(components)
python
def user_agent(self): """Return the formatted user agent string.""" components = ["/".join(x) for x in self.user_agent_components.items()] return " ".join(components)
[ "def", "user_agent", "(", "self", ")", ":", "components", "=", "[", "\"/\"", ".", "join", "(", "x", ")", "for", "x", "in", "self", ".", "user_agent_components", ".", "items", "(", ")", "]", "return", "\" \"", ".", "join", "(", "components", ")" ]
Return the formatted user agent string.
[ "Return", "the", "formatted", "user", "agent", "string", "." ]
307836b70f0439c066718f1e375fa333dc6e5d77
https://github.com/mollie/mollie-api-python/blob/307836b70f0439c066718f1e375fa333dc6e5d77/mollie/api/client.py#L128-L131
train
35,385
mollie/mollie-api-python
mollie/api/error.py
ResponseError.factory
def factory(resp): """ Return a ResponseError subclass based on the API payload. All errors are documented: https://docs.mollie.com/guides/handling-errors#all-possible-status-codes More exceptions should be added here when appropriate, and when useful examples of API errors are available. """ status = resp['status'] if status == 401: return UnauthorizedError(resp) elif status == 404: return NotFoundError(resp) elif status == 422: return UnprocessableEntityError(resp) else: # generic fallback return ResponseError(resp)
python
def factory(resp): """ Return a ResponseError subclass based on the API payload. All errors are documented: https://docs.mollie.com/guides/handling-errors#all-possible-status-codes More exceptions should be added here when appropriate, and when useful examples of API errors are available. """ status = resp['status'] if status == 401: return UnauthorizedError(resp) elif status == 404: return NotFoundError(resp) elif status == 422: return UnprocessableEntityError(resp) else: # generic fallback return ResponseError(resp)
[ "def", "factory", "(", "resp", ")", ":", "status", "=", "resp", "[", "'status'", "]", "if", "status", "==", "401", ":", "return", "UnauthorizedError", "(", "resp", ")", "elif", "status", "==", "404", ":", "return", "NotFoundError", "(", "resp", ")", "e...
Return a ResponseError subclass based on the API payload. All errors are documented: https://docs.mollie.com/guides/handling-errors#all-possible-status-codes More exceptions should be added here when appropriate, and when useful examples of API errors are available.
[ "Return", "a", "ResponseError", "subclass", "based", "on", "the", "API", "payload", "." ]
307836b70f0439c066718f1e375fa333dc6e5d77
https://github.com/mollie/mollie-api-python/blob/307836b70f0439c066718f1e375fa333dc6e5d77/mollie/api/error.py#L63-L79
train
35,386
mollie/mollie-api-python
mollie/api/resources/orders.py
Orders.delete
def delete(self, order_id, data=None): """Cancel order and return the order object. Deleting an order causes the order status to change to canceled. The updated order object is returned. """ if not order_id or not order_id.startswith(self.RESOURCE_ID_PREFIX): raise IdentifierError( "Invalid order ID: '{id}'. An order ID should start with '{prefix}'.".format( id=order_id, prefix=self.RESOURCE_ID_PREFIX) ) result = super(Orders, self).delete(order_id, data) return self.get_resource_object(result)
python
def delete(self, order_id, data=None): """Cancel order and return the order object. Deleting an order causes the order status to change to canceled. The updated order object is returned. """ if not order_id or not order_id.startswith(self.RESOURCE_ID_PREFIX): raise IdentifierError( "Invalid order ID: '{id}'. An order ID should start with '{prefix}'.".format( id=order_id, prefix=self.RESOURCE_ID_PREFIX) ) result = super(Orders, self).delete(order_id, data) return self.get_resource_object(result)
[ "def", "delete", "(", "self", ",", "order_id", ",", "data", "=", "None", ")", ":", "if", "not", "order_id", "or", "not", "order_id", ".", "startswith", "(", "self", ".", "RESOURCE_ID_PREFIX", ")", ":", "raise", "IdentifierError", "(", "\"Invalid order ID: '{...
Cancel order and return the order object. Deleting an order causes the order status to change to canceled. The updated order object is returned.
[ "Cancel", "order", "and", "return", "the", "order", "object", "." ]
307836b70f0439c066718f1e375fa333dc6e5d77
https://github.com/mollie/mollie-api-python/blob/307836b70f0439c066718f1e375fa333dc6e5d77/mollie/api/resources/orders.py#L20-L32
train
35,387
mollie/mollie-api-python
mollie/api/objects/subscription.py
Subscription.customer
def customer(self): """Return the customer for this subscription.""" url = self._get_link('customer') if url: resp = self.client.customers.perform_api_call(self.client.customers.REST_READ, url) return Customer(resp)
python
def customer(self): """Return the customer for this subscription.""" url = self._get_link('customer') if url: resp = self.client.customers.perform_api_call(self.client.customers.REST_READ, url) return Customer(resp)
[ "def", "customer", "(", "self", ")", ":", "url", "=", "self", ".", "_get_link", "(", "'customer'", ")", "if", "url", ":", "resp", "=", "self", ".", "client", ".", "customers", ".", "perform_api_call", "(", "self", ".", "client", ".", "customers", ".", ...
Return the customer for this subscription.
[ "Return", "the", "customer", "for", "this", "subscription", "." ]
307836b70f0439c066718f1e375fa333dc6e5d77
https://github.com/mollie/mollie-api-python/blob/307836b70f0439c066718f1e375fa333dc6e5d77/mollie/api/objects/subscription.py#L85-L90
train
35,388
mollie/mollie-api-python
mollie/api/objects/subscription.py
Subscription.payments
def payments(self): """Return a list of payments for this subscription.""" payments = self.client.subscription_payments.on(self).list() return payments
python
def payments(self): """Return a list of payments for this subscription.""" payments = self.client.subscription_payments.on(self).list() return payments
[ "def", "payments", "(", "self", ")", ":", "payments", "=", "self", ".", "client", ".", "subscription_payments", ".", "on", "(", "self", ")", ".", "list", "(", ")", "return", "payments" ]
Return a list of payments for this subscription.
[ "Return", "a", "list", "of", "payments", "for", "this", "subscription", "." ]
307836b70f0439c066718f1e375fa333dc6e5d77
https://github.com/mollie/mollie-api-python/blob/307836b70f0439c066718f1e375fa333dc6e5d77/mollie/api/objects/subscription.py#L93-L96
train
35,389
jhuapl-boss/intern
intern/service/boss/v1/project.py
ProjectService_1.list_permissions
def list_permissions(self, group_name=None, resource=None, url_prefix=None, auth=None, session=None, send_opts=None): """List the permission sets for the logged in user Optionally filter by resource or group. Args: group_name (string): Name of group to filter on resource (intern.resource.boss.BossResource): Identifies which data model object to filter on url_prefix (string): Protocol + host such as https://api.theboss.io auth (string): Token to send in the request header. session (requests.Session): HTTP session to use for request. send_opts (dictionary): Additional arguments to pass to session.send(). Returns: (list[dict]): List of dictionaries of permission sets """ filter_params = {} if group_name: filter_params["group"] = group_name if resource: filter_params.update(resource.get_dict_route()) req = self.get_permission_request('GET', 'application/json', url_prefix, auth, query_params=filter_params) prep = session.prepare_request(req) resp = session.send(prep, **send_opts) if resp.status_code != 200: msg = "Failed to get permission sets. " if group_name: msg = "{} Group: {}".format(msg, group_name) if resource: msg = "{} Resource: {}".format(msg, resource.name) msg = '{}, got HTTP response: ({}) - {}'.format(msg, resp.status_code, resp.text) raise HTTPError(msg, request=req, response=resp) else: return resp.json()["permission-sets"]
python
def list_permissions(self, group_name=None, resource=None, url_prefix=None, auth=None, session=None, send_opts=None): """List the permission sets for the logged in user Optionally filter by resource or group. Args: group_name (string): Name of group to filter on resource (intern.resource.boss.BossResource): Identifies which data model object to filter on url_prefix (string): Protocol + host such as https://api.theboss.io auth (string): Token to send in the request header. session (requests.Session): HTTP session to use for request. send_opts (dictionary): Additional arguments to pass to session.send(). Returns: (list[dict]): List of dictionaries of permission sets """ filter_params = {} if group_name: filter_params["group"] = group_name if resource: filter_params.update(resource.get_dict_route()) req = self.get_permission_request('GET', 'application/json', url_prefix, auth, query_params=filter_params) prep = session.prepare_request(req) resp = session.send(prep, **send_opts) if resp.status_code != 200: msg = "Failed to get permission sets. " if group_name: msg = "{} Group: {}".format(msg, group_name) if resource: msg = "{} Resource: {}".format(msg, resource.name) msg = '{}, got HTTP response: ({}) - {}'.format(msg, resp.status_code, resp.text) raise HTTPError(msg, request=req, response=resp) else: return resp.json()["permission-sets"]
[ "def", "list_permissions", "(", "self", ",", "group_name", "=", "None", ",", "resource", "=", "None", ",", "url_prefix", "=", "None", ",", "auth", "=", "None", ",", "session", "=", "None", ",", "send_opts", "=", "None", ")", ":", "filter_params", "=", ...
List the permission sets for the logged in user Optionally filter by resource or group. Args: group_name (string): Name of group to filter on resource (intern.resource.boss.BossResource): Identifies which data model object to filter on url_prefix (string): Protocol + host such as https://api.theboss.io auth (string): Token to send in the request header. session (requests.Session): HTTP session to use for request. send_opts (dictionary): Additional arguments to pass to session.send(). Returns: (list[dict]): List of dictionaries of permission sets
[ "List", "the", "permission", "sets", "for", "the", "logged", "in", "user" ]
d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed
https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/service/boss/v1/project.py#L381-L421
train
35,390
jhuapl-boss/intern
intern/service/boss/v1/project.py
ProjectService_1.list
def list(self, resource, url_prefix, auth, session, send_opts): """List all resources of the same type as the given resource. Args: resource (intern.resource.boss.BossResource): List resources of the same type as this.. url_prefix (string): Protocol + host such as https://api.theboss.io auth (string): Token to send in the request header. session (requests.Session): HTTP session to use for request. send_opts (dictionary): Additional arguments to pass to session.send(). Returns: (list): List of resources. Each resource is a dictionary. Raises: requests.HTTPError on failure. """ req = self.get_request( resource, 'GET', 'application/json', url_prefix, auth, proj_list_req=True) prep = session.prepare_request(req) resp = session.send(prep, **send_opts) if resp.status_code == 200: return self._get_resource_list(resp.json()) err = ('List failed on {}, got HTTP response: ({}) - {}'.format( resource.name, resp.status_code, resp.text)) raise HTTPError(err, request = req, response = resp)
python
def list(self, resource, url_prefix, auth, session, send_opts): """List all resources of the same type as the given resource. Args: resource (intern.resource.boss.BossResource): List resources of the same type as this.. url_prefix (string): Protocol + host such as https://api.theboss.io auth (string): Token to send in the request header. session (requests.Session): HTTP session to use for request. send_opts (dictionary): Additional arguments to pass to session.send(). Returns: (list): List of resources. Each resource is a dictionary. Raises: requests.HTTPError on failure. """ req = self.get_request( resource, 'GET', 'application/json', url_prefix, auth, proj_list_req=True) prep = session.prepare_request(req) resp = session.send(prep, **send_opts) if resp.status_code == 200: return self._get_resource_list(resp.json()) err = ('List failed on {}, got HTTP response: ({}) - {}'.format( resource.name, resp.status_code, resp.text)) raise HTTPError(err, request = req, response = resp)
[ "def", "list", "(", "self", ",", "resource", ",", "url_prefix", ",", "auth", ",", "session", ",", "send_opts", ")", ":", "req", "=", "self", ".", "get_request", "(", "resource", ",", "'GET'", ",", "'application/json'", ",", "url_prefix", ",", "auth", ","...
List all resources of the same type as the given resource. Args: resource (intern.resource.boss.BossResource): List resources of the same type as this.. url_prefix (string): Protocol + host such as https://api.theboss.io auth (string): Token to send in the request header. session (requests.Session): HTTP session to use for request. send_opts (dictionary): Additional arguments to pass to session.send(). Returns: (list): List of resources. Each resource is a dictionary. Raises: requests.HTTPError on failure.
[ "List", "all", "resources", "of", "the", "same", "type", "as", "the", "given", "resource", "." ]
d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed
https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/service/boss/v1/project.py#L711-L738
train
35,391
jhuapl-boss/intern
intern/service/boss/v1/project.py
ProjectService_1._get_resource_params
def _get_resource_params(self, resource, for_update=False): """Get dictionary containing all parameters for the given resource. When getting params for a coordinate frame update, only name and description are returned because they are the only fields that can be updated. Args: resource (intern.resource.boss.resource.BossResource): A sub-class whose parameters will be extracted into a dictionary. for_update (bool): True if params will be used for an update. Returns: (dictionary): A dictionary containing the resource's parameters as required by the Boss API. Raises: TypeError if resource is not a supported class. """ if isinstance(resource, CollectionResource): return self._get_collection_params(resource) if isinstance(resource, ExperimentResource): return self._get_experiment_params(resource, for_update) if isinstance(resource, CoordinateFrameResource): return self._get_coordinate_params(resource, for_update) if isinstance(resource, ChannelResource): return self._get_channel_params(resource, for_update) raise TypeError('resource is not supported type.')
python
def _get_resource_params(self, resource, for_update=False): """Get dictionary containing all parameters for the given resource. When getting params for a coordinate frame update, only name and description are returned because they are the only fields that can be updated. Args: resource (intern.resource.boss.resource.BossResource): A sub-class whose parameters will be extracted into a dictionary. for_update (bool): True if params will be used for an update. Returns: (dictionary): A dictionary containing the resource's parameters as required by the Boss API. Raises: TypeError if resource is not a supported class. """ if isinstance(resource, CollectionResource): return self._get_collection_params(resource) if isinstance(resource, ExperimentResource): return self._get_experiment_params(resource, for_update) if isinstance(resource, CoordinateFrameResource): return self._get_coordinate_params(resource, for_update) if isinstance(resource, ChannelResource): return self._get_channel_params(resource, for_update) raise TypeError('resource is not supported type.')
[ "def", "_get_resource_params", "(", "self", ",", "resource", ",", "for_update", "=", "False", ")", ":", "if", "isinstance", "(", "resource", ",", "CollectionResource", ")", ":", "return", "self", ".", "_get_collection_params", "(", "resource", ")", "if", "isin...
Get dictionary containing all parameters for the given resource. When getting params for a coordinate frame update, only name and description are returned because they are the only fields that can be updated. Args: resource (intern.resource.boss.resource.BossResource): A sub-class whose parameters will be extracted into a dictionary. for_update (bool): True if params will be used for an update. Returns: (dictionary): A dictionary containing the resource's parameters as required by the Boss API. Raises: TypeError if resource is not a supported class.
[ "Get", "dictionary", "containing", "all", "parameters", "for", "the", "given", "resource", "." ]
d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed
https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/service/boss/v1/project.py#L858-L889
train
35,392
jhuapl-boss/intern
intern/service/boss/v1/project.py
ProjectService_1._get_resource_list
def _get_resource_list(self, rsrc_dict): """Extracts list of resources from the HTTP response. Args: rsrc_dict (dict): HTTP response encoded in a dictionary. Returns: (list[string]): List of a type of resource (collections, experiments, etc). Raises: (RuntimeError): If rsrc_dict does not contain any known resources. """ if 'collections' in rsrc_dict: return rsrc_dict['collections'] if 'experiments' in rsrc_dict: return rsrc_dict['experiments'] if 'channels' in rsrc_dict: return rsrc_dict['channels'] if 'coords' in rsrc_dict: return rsrc_dict['coords'] raise RuntimeError('Invalid list response received from Boss. No known resource type returned.')
python
def _get_resource_list(self, rsrc_dict): """Extracts list of resources from the HTTP response. Args: rsrc_dict (dict): HTTP response encoded in a dictionary. Returns: (list[string]): List of a type of resource (collections, experiments, etc). Raises: (RuntimeError): If rsrc_dict does not contain any known resources. """ if 'collections' in rsrc_dict: return rsrc_dict['collections'] if 'experiments' in rsrc_dict: return rsrc_dict['experiments'] if 'channels' in rsrc_dict: return rsrc_dict['channels'] if 'coords' in rsrc_dict: return rsrc_dict['coords'] raise RuntimeError('Invalid list response received from Boss. No known resource type returned.')
[ "def", "_get_resource_list", "(", "self", ",", "rsrc_dict", ")", ":", "if", "'collections'", "in", "rsrc_dict", ":", "return", "rsrc_dict", "[", "'collections'", "]", "if", "'experiments'", "in", "rsrc_dict", ":", "return", "rsrc_dict", "[", "'experiments'", "]"...
Extracts list of resources from the HTTP response. Args: rsrc_dict (dict): HTTP response encoded in a dictionary. Returns: (list[string]): List of a type of resource (collections, experiments, etc). Raises: (RuntimeError): If rsrc_dict does not contain any known resources.
[ "Extracts", "list", "of", "resources", "from", "the", "HTTP", "response", "." ]
d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed
https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/service/boss/v1/project.py#L1024-L1045
train
35,393
jhuapl-boss/intern
intern/__init__.py
check_version
def check_version(): """ Tells you if you have an old version of intern. """ import requests r = requests.get('https://pypi.python.org/pypi/intern/json').json() r = r['info']['version'] if r != __version__: print("You are using version {}. A newer version of intern is available: {} ".format(__version__, r) + "\n\n'pip install -U intern' to update.") return r
python
def check_version(): """ Tells you if you have an old version of intern. """ import requests r = requests.get('https://pypi.python.org/pypi/intern/json').json() r = r['info']['version'] if r != __version__: print("You are using version {}. A newer version of intern is available: {} ".format(__version__, r) + "\n\n'pip install -U intern' to update.") return r
[ "def", "check_version", "(", ")", ":", "import", "requests", "r", "=", "requests", ".", "get", "(", "'https://pypi.python.org/pypi/intern/json'", ")", ".", "json", "(", ")", "r", "=", "r", "[", "'info'", "]", "[", "'version'", "]", "if", "r", "!=", "__ve...
Tells you if you have an old version of intern.
[ "Tells", "you", "if", "you", "have", "an", "old", "version", "of", "intern", "." ]
d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed
https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/__init__.py#L8-L18
train
35,394
jhuapl-boss/intern
intern/service/boss/volume.py
check_channel
def check_channel(fcn): """Decorator that ensures a valid channel passed in. Args: fcn (function): Function that has a ChannelResource as its second argument. Returns: (function): Wraps given function with one that checks for a valid channel. """ def wrapper(*args, **kwargs): if not isinstance(args[1], ChannelResource): raise RuntimeError('resource must be an instance of intern.resource.boss.ChannelResource.') if not args[1].cutout_ready: raise PartialChannelResourceError( 'ChannelResource not fully initialized. Use intern.remote.BossRemote.get_channel({}, {}, {})'.format( args[1].name, args[1].coll_name, args[1].exp_name)) return fcn(*args, **kwargs) return wrapper
python
def check_channel(fcn): """Decorator that ensures a valid channel passed in. Args: fcn (function): Function that has a ChannelResource as its second argument. Returns: (function): Wraps given function with one that checks for a valid channel. """ def wrapper(*args, **kwargs): if not isinstance(args[1], ChannelResource): raise RuntimeError('resource must be an instance of intern.resource.boss.ChannelResource.') if not args[1].cutout_ready: raise PartialChannelResourceError( 'ChannelResource not fully initialized. Use intern.remote.BossRemote.get_channel({}, {}, {})'.format( args[1].name, args[1].coll_name, args[1].exp_name)) return fcn(*args, **kwargs) return wrapper
[ "def", "check_channel", "(", "fcn", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "args", "[", "1", "]", ",", "ChannelResource", ")", ":", "raise", "RuntimeError", "(", "'resource must ...
Decorator that ensures a valid channel passed in. Args: fcn (function): Function that has a ChannelResource as its second argument. Returns: (function): Wraps given function with one that checks for a valid channel.
[ "Decorator", "that", "ensures", "a", "valid", "channel", "passed", "in", "." ]
d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed
https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/service/boss/volume.py#L20-L40
train
35,395
jhuapl-boss/intern
intern/service/boss/v1/metadata.py
MetadataService_1.create
def create(self, resource, keys_vals, url_prefix, auth, session, send_opts): """Create the given key-value pairs for the given resource. Will attempt to create all key-value pairs even if a failure is encountered. Args: resource (intern.resource.boss.BossResource): List keys associated with this resource. keys_vals (dictionary): The metadata to associate with the resource. url_prefix (string): Protocol + host such as https://api.theboss.io auth (string): Token to send in the request header. session (requests.Session): HTTP session to use for request. send_opts (dictionary): Additional arguments to pass to session.send(). Raises: HTTPErrorList on failure. """ success = True exc = HTTPErrorList('At least one key-value create failed.') for pair in keys_vals.items(): key = pair[0] value = pair[1] req = self.get_metadata_request( resource, 'POST', 'application/json', url_prefix, auth, key, value) prep = session.prepare_request(req) resp = session.send(prep, **send_opts) if resp.status_code == 201: continue err = ( 'Create failed for {}: {}:{}, got HTTP response: ({}) - {}' .format(resource.name, key, value, resp.status_code, resp.text)) exc.http_errors.append(HTTPError(err, request=req, response=resp)) success = False if not success: raise exc
python
def create(self, resource, keys_vals, url_prefix, auth, session, send_opts): """Create the given key-value pairs for the given resource. Will attempt to create all key-value pairs even if a failure is encountered. Args: resource (intern.resource.boss.BossResource): List keys associated with this resource. keys_vals (dictionary): The metadata to associate with the resource. url_prefix (string): Protocol + host such as https://api.theboss.io auth (string): Token to send in the request header. session (requests.Session): HTTP session to use for request. send_opts (dictionary): Additional arguments to pass to session.send(). Raises: HTTPErrorList on failure. """ success = True exc = HTTPErrorList('At least one key-value create failed.') for pair in keys_vals.items(): key = pair[0] value = pair[1] req = self.get_metadata_request( resource, 'POST', 'application/json', url_prefix, auth, key, value) prep = session.prepare_request(req) resp = session.send(prep, **send_opts) if resp.status_code == 201: continue err = ( 'Create failed for {}: {}:{}, got HTTP response: ({}) - {}' .format(resource.name, key, value, resp.status_code, resp.text)) exc.http_errors.append(HTTPError(err, request=req, response=resp)) success = False if not success: raise exc
[ "def", "create", "(", "self", ",", "resource", ",", "keys_vals", ",", "url_prefix", ",", "auth", ",", "session", ",", "send_opts", ")", ":", "success", "=", "True", "exc", "=", "HTTPErrorList", "(", "'At least one key-value create failed.'", ")", "for", "pair"...
Create the given key-value pairs for the given resource. Will attempt to create all key-value pairs even if a failure is encountered. Args: resource (intern.resource.boss.BossResource): List keys associated with this resource. keys_vals (dictionary): The metadata to associate with the resource. url_prefix (string): Protocol + host such as https://api.theboss.io auth (string): Token to send in the request header. session (requests.Session): HTTP session to use for request. send_opts (dictionary): Additional arguments to pass to session.send(). Raises: HTTPErrorList on failure.
[ "Create", "the", "given", "key", "-", "value", "pairs", "for", "the", "given", "resource", "." ]
d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed
https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/service/boss/v1/metadata.py#L61-L98
train
35,396
jhuapl-boss/intern
intern/service/boss/v1/volume.py
VolumeService_1.get_bit_width
def get_bit_width(self, resource): """Method to return the bit width for blosc based on the Resource""" datatype = resource.datatype if "uint" in datatype: bit_width = int(datatype.split("uint")[1]) else: raise ValueError("Unsupported datatype: {}".format(datatype)) return bit_width
python
def get_bit_width(self, resource): """Method to return the bit width for blosc based on the Resource""" datatype = resource.datatype if "uint" in datatype: bit_width = int(datatype.split("uint")[1]) else: raise ValueError("Unsupported datatype: {}".format(datatype)) return bit_width
[ "def", "get_bit_width", "(", "self", ",", "resource", ")", ":", "datatype", "=", "resource", ".", "datatype", "if", "\"uint\"", "in", "datatype", ":", "bit_width", "=", "int", "(", "datatype", ".", "split", "(", "\"uint\"", ")", "[", "1", "]", ")", "el...
Method to return the bit width for blosc based on the Resource
[ "Method", "to", "return", "the", "bit", "width", "for", "blosc", "based", "on", "the", "Resource" ]
d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed
https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/service/boss/v1/volume.py#L38-L47
train
35,397
falkr/stmpy
stmpy/__init__.py
get_graphviz_dot
def get_graphviz_dot(machine): """ Return the graph of the state machine. The format is the dot format for Graphviz, and can be directly used as input to Graphviz. To learn more about Graphviz, visit https://graphviz.gitlab.io. **Display in Jupyter Notebook** Install Python support for Graphviz via `pip install graphviz`. Install Graphviz. In a notebook, build a stmpy.Machine. Then, declare a cell with the following content: from graphviz import Source src = Source(stmpy.get_graphviz_dot(stm)) src **Using Graphviz on the Command Line** Write the graph file with the following code: with open("graph.gv", "w") as file: print(stmpy.get_graphviz_dot(stm), file=file) You can now use the command line tools from Graphviz to create a graphic file with the graph. For instance: dot -Tsvg graph.gv -o graph.svg """ s = [] s.append('digraph G {\n') s.append('node [shape=box style=rounded fontname=Helvetica];\n') s.append('edge [ fontname=Helvetica ];\n') # initial state s.append('initial [shape=point width=0.2];\n') # final states counter = 1 for t_id in machine._table: transition = machine._table[t_id] if not transition.internal: if transition.target is 'final': s.append('f{} [shape=doublecircle width=0.1 label="" style=filled fillcolor=black];\n'.format(counter)) counter = counter + 1 for state_name in machine._states: s.append(_print_state(machine._states[state_name])) # initial transition counter = 0 s.append(_print_transition(machine._intial_transition, counter)) counter = 1 for t_id in machine._table: transition = machine._table[t_id] if not transition.internal: s.append(_print_transition(transition, counter)) counter = counter + 1 s.append('}') return ''.join(s)
python
def get_graphviz_dot(machine): """ Return the graph of the state machine. The format is the dot format for Graphviz, and can be directly used as input to Graphviz. To learn more about Graphviz, visit https://graphviz.gitlab.io. **Display in Jupyter Notebook** Install Python support for Graphviz via `pip install graphviz`. Install Graphviz. In a notebook, build a stmpy.Machine. Then, declare a cell with the following content: from graphviz import Source src = Source(stmpy.get_graphviz_dot(stm)) src **Using Graphviz on the Command Line** Write the graph file with the following code: with open("graph.gv", "w") as file: print(stmpy.get_graphviz_dot(stm), file=file) You can now use the command line tools from Graphviz to create a graphic file with the graph. For instance: dot -Tsvg graph.gv -o graph.svg """ s = [] s.append('digraph G {\n') s.append('node [shape=box style=rounded fontname=Helvetica];\n') s.append('edge [ fontname=Helvetica ];\n') # initial state s.append('initial [shape=point width=0.2];\n') # final states counter = 1 for t_id in machine._table: transition = machine._table[t_id] if not transition.internal: if transition.target is 'final': s.append('f{} [shape=doublecircle width=0.1 label="" style=filled fillcolor=black];\n'.format(counter)) counter = counter + 1 for state_name in machine._states: s.append(_print_state(machine._states[state_name])) # initial transition counter = 0 s.append(_print_transition(machine._intial_transition, counter)) counter = 1 for t_id in machine._table: transition = machine._table[t_id] if not transition.internal: s.append(_print_transition(transition, counter)) counter = counter + 1 s.append('}') return ''.join(s)
[ "def", "get_graphviz_dot", "(", "machine", ")", ":", "s", "=", "[", "]", "s", ".", "append", "(", "'digraph G {\\n'", ")", "s", ".", "append", "(", "'node [shape=box style=rounded fontname=Helvetica];\\n'", ")", "s", ".", "append", "(", "'edge [ fontname=Helvetica...
Return the graph of the state machine. The format is the dot format for Graphviz, and can be directly used as input to Graphviz. To learn more about Graphviz, visit https://graphviz.gitlab.io. **Display in Jupyter Notebook** Install Python support for Graphviz via `pip install graphviz`. Install Graphviz. In a notebook, build a stmpy.Machine. Then, declare a cell with the following content: from graphviz import Source src = Source(stmpy.get_graphviz_dot(stm)) src **Using Graphviz on the Command Line** Write the graph file with the following code: with open("graph.gv", "w") as file: print(stmpy.get_graphviz_dot(stm), file=file) You can now use the command line tools from Graphviz to create a graphic file with the graph. For instance: dot -Tsvg graph.gv -o graph.svg
[ "Return", "the", "graph", "of", "the", "state", "machine", "." ]
78b016f7bf6fa7b6eba8dae58997fb99f7215bf7
https://github.com/falkr/stmpy/blob/78b016f7bf6fa7b6eba8dae58997fb99f7215bf7/stmpy/__init__.py#L80-L139
train
35,398
falkr/stmpy
stmpy/__init__.py
_parse_arg_list
def _parse_arg_list(arglist): """ Parses a list of arguments. Arguments are expected to be split by a comma, surrounded by any amount of whitespace. Arguments are then run through Python's eval() method. """ args = [] for arg in arglist.split(','): arg = arg.strip() if arg: # string is not empty args.append(eval(arg)) return args
python
def _parse_arg_list(arglist): """ Parses a list of arguments. Arguments are expected to be split by a comma, surrounded by any amount of whitespace. Arguments are then run through Python's eval() method. """ args = [] for arg in arglist.split(','): arg = arg.strip() if arg: # string is not empty args.append(eval(arg)) return args
[ "def", "_parse_arg_list", "(", "arglist", ")", ":", "args", "=", "[", "]", "for", "arg", "in", "arglist", ".", "split", "(", "','", ")", ":", "arg", "=", "arg", ".", "strip", "(", ")", "if", "arg", ":", "# string is not empty", "args", ".", "append",...
Parses a list of arguments. Arguments are expected to be split by a comma, surrounded by any amount of whitespace. Arguments are then run through Python's eval() method.
[ "Parses", "a", "list", "of", "arguments", "." ]
78b016f7bf6fa7b6eba8dae58997fb99f7215bf7
https://github.com/falkr/stmpy/blob/78b016f7bf6fa7b6eba8dae58997fb99f7215bf7/stmpy/__init__.py#L141-L153
train
35,399