code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
level = 0 parent = wrapper.parent while parent: print_test_msg(parent.name, level, TestStatus.FAIL, self.use_color) level += 1 parent = parent.parent print_test_msg(wrapper.name, level, TestStatus.FAIL, self.use_color) print_test_args...
def print_error(self, wrapper)
A crude way of output the errors for now. This needs to be cleaned up into something better.
3.128774
3.033989
1.031241
if isinstance(structure, Element): return structure elif isinstance(structure, str): return String(content=structure) elif isinstance(structure, bool): return Boolean(content=structure) elif isinstance(structure, (int, float)): return Number(content=structure) e...
def refract(structure) -> Element
Refracts the given value. >>> refract('string') String(content='string') >>> refract(1) Number(content=1) >>> refract(True) Boolean(content=True) >>> refract(None) Null() >>> refract([1, 2]) Array(content=[Number(content=1), Number(content=2)]) >>> refract({'name': 'Doe...
2.358473
1.741014
1.354654
return json.dumps(self.serialise_dict(element), **kwargs)
def serialise(self, element: Element, **kwargs) -> str
Serialises the given element into JSON. >>> JSONSerialiser().serialise(String(content='Hello')) '{"element": "string", "content": "Hello"}'
6.461917
5.854051
1.103837
return self.deserialise_dict(json.loads(element_json))
def deserialise(self, element_json: str) -> Element
Deserialises the given JSON into an element. >>> json = '{"element": "string", "content": "Hello"' >>> JSONDeserialiser().deserialise(json) String(content='Hello')
5.478853
8.953588
0.611917
return json.dumps(self.serialise_element(element))
def serialise(self, element: Element) -> str
Serialises the given element into Compact JSON. >>> CompactJSONSerialiser().serialise(String(content='Hello')) '["string", null, null, "Hello"]'
7.436305
6.610098
1.124992
content = json.loads(content) if not isinstance(content, list): raise ValueError('Given content was not compact JSON refract') return self.deserialise_element(content)
def deserialise(self, content) -> Element
Deserialises the given compact JSON into an element. >>> deserialiser = CompactJSONDeserialiser() >>> deserialiser.deserialise('["string", null, null, "Hi"]') String(content='Hi')
9.10972
8.082947
1.12703
tmp_cov = coverage.coverage(omit=omit, data_suffix=parallel) tmp_cov.load() tmp_cov.combine() tmp_cov.save()
def combine_coverage_reports(self, omit, parallel)
Method to force the combination of parallel coverage reports.
4.150184
3.767502
1.101574
try: return getattr(self.__class__, "transform")._transforms except AttributeError: return {}
def transforms(self) -> Mapping[Type, Iterable[Type]]
The available data transformers.
7.977432
6.626563
1.203857
pass
def transform(self, target_type: Type[T], value: F, context: PipelineContext = None) -> T
Transforms an object to a new type. Args: target_type: The type to be converted to. value: The object to be transformed. context: The context of the transformation (mutable).
221,268.609375
45,232.242188
4.891834
expects = [exp.serialize() for exp in self.expects] converted_dict = { 'id': self.id, 'name': self.pretty_name, 'raw_name': self.name, 'doc': self.doc, 'error': self.error, 'skipped': self.skipped, 'skip_reason'...
def serialize(self)
Serializes the CaseWrapper object for collection. Warning, this will only grab the available information. It is strongly that you only call this once all specs and tests have completed.
3.470579
3.504006
0.99046
cases = [case.serialize() for key, case in six.iteritems(self.cases)] specs = [spec.serialize() for spec in self.describes] converted_dict = { 'id': self.id, 'name': self.name, 'class_path': self.real_class_path, 'doc': self.doc, ...
def serialize(self)
Serializes the Spec/Describe object for collection. Warning, this will only grab the available information. It is strongly that you only call this once all specs and tests have completed.
4.182195
3.534106
1.183381
for hook in self.hooks: getattr(self, hook)(self._state)
def _run_hooks(self)
Calls any registered hooks providing the current state.
6.993452
5.265272
1.328222
from refract.refraction import refract self.content.append(refract(element))
def append(self, element)
Append an element onto the array. >>> array = Array() >>> array.append('test')
16.535475
23.350443
0.708144
from refract.refraction import refract self.content.insert(index, refract(element))
def insert(self, index: int, element)
Insert an element at a given position. >>> array = Array() >>> array.insert(0, Element())
15.512998
23.489098
0.660434
from refract.refraction import refract return self.content.index(refract(element))
def index(self, element: Element) -> int
Return the index in the array of the first item whose value is element. It is an error if there is no such item. >>> element = String('hello') >>> array = Array(content=[element]) >>> array.index(element) 0
18.463337
16.262009
1.135366
types.update(getattr(self.__class__, "get")._provides) any_dispatch = True except AttributeError: pass try: types.update(getattr(self.__class__, "get_many")._provides) any_dispatch = True except AttributeError: pass ...
def provides(self): # type: Union[Iterable[Type[T]], Type[Any]] types = set() any_dispatch = False try
The types of objects the data store provides.
3.874977
3.675126
1.05438
pass
def get(self, type: Type[T], query: Mapping[str, Any], context: PipelineContext = None) -> T
Gets a query from the data source. Args: query: The query being requested. context: The context for the extraction (mutable). Returns: The requested object.
164,515.234375
93,724.546875
1.755306
pass
def get_many(self, type: Type[T], query: Mapping[str, Any], context: PipelineContext = None) -> Iterable[T]
Gets a query from the data source, which contains a request for multiple objects. Args: query: The query being requested (contains a request for multiple objects). context: The context for the extraction (mutable). Returns: The requested objects.
23,654.802734
36,918.851563
0.640724
for reporter in self.reporters: if self.can_use_reporter(reporter, self.parallel): reporter.subscribe_to_spec(spec)
def subscribe_all_to_spec(self, spec)
Will automatically not subscribe reporters that are not parallel or serial depending on the current mode.
5.900587
3.800607
1.552538
color = None if self.use_color: color = get_color_from_status(status) print_indent_msg(msg, indent, color)
def output(self, msg, indent, status=None)
Alias for print_indent_msg with color determined by status.
4.761889
2.743256
1.735853
traceback_blocks = [] _n, _n, exc_traceback = sys.exc_info() tb_list = get_all_tracebacks(exc_traceback)[1:] # Remove already captured tracebacks # TODO(jmv): This must be a better way of doing this. Need to revisit. tb_list = [tb for tb in tb_list if tb not in CAPTURED_TRACEBACKS] CAP...
def get_real_last_traceback(exception)
An unfortunate evil... All because Python's traceback cannot determine where my executed code is coming from...
3.951584
3.92077
1.007859
return list(filter(is_element(Asset), self.content))
def assets(self) -> List[Asset]
Returns the assets in the transaction.
19.394489
18.159334
1.068018
decompiler = Decompiler( indentation=indentation, line_length=line_length, starting_indentation=starting_indentation, ) return decompiler.run(ast)
def decompile(ast, indentation=4, line_length=100, starting_indentation=0)
Decompiles an AST into Python code. Arguments: - ast: code to decompile, using AST objects as generated by the standard library ast module - indentation: indentation level of lines - line_length: if lines become longer than this length, ast_decompiler will try to break them up (but it will not ne...
2.307314
3.298016
0.699607
first = True last_line = len(self.lines) current_line = list(self.current_line) for node in nodes: if first: first = False else: self.write(separator) self.visit(node) if allow_newlines and (self.cur...
def write_expression_list(self, nodes, separator=', ', allow_newlines=True, need_parens=True, final_separator_if_multiline=True)
Writes a list of nodes, separated by separator. If allow_newlines, will write the expression over multiple lines if necessary to say within max_line_length. If need_parens, will surround the expression with parentheses in this case. If final_separator_if_multiline, will write a separator at the...
2.873249
2.87507
0.999367
from refract.elements.object import Object def get_value(item): if isinstance(item, KeyValuePair): return (get_value(item.key), get_value(item.value)) elif isinstance(item, list): return [get_value(element) for element in item] ...
def defract(self)
Returns the underlying (unrefracted) value of element >>> Element(content='Hello').defract 'Hello' >>> Element(content=Element(content='Hello')).defract 'Hello' >>> Element(content=[Element(content='Hello')]).defract ['Hello']
3.343926
3.134132
1.066938
if isinstance(self.content, list): return self.content elif isinstance(self.content, Element): return [self.content] else: return []
def children(self)
Returns all of the children elements.
3.718199
2.768966
1.342811
for child in self.children: yield child for recursive_child in child.recursive_children: yield recursive_child
def recursive_children(self)
Generator returning all recursive children elements.
3.774687
2.826801
1.335321
line, module = get_module_and_line('__spec__') src_params = ExpectParams(line, module) expect_obj = ExpectAssert( obj, src_params=src_params, caller_args=caller_args ) _add_expect_to_wrapper(expect_obj) return expect_obj
def expect(obj, caller_args=[])
Primary method for test assertions in Specter :param obj: The evaluated target object :param caller_args: Is only used when using expecting a raised Exception
6.278471
7.840406
0.800784
line, module = get_module_and_line('__spec__') src_params = ExpectParams(line, module) require_obj = RequireAssert( obj, src_params=src_params, caller_args=caller_args ) _add_expect_to_wrapper(require_obj) return require_obj
def require(obj, caller_args=[])
Primary method for test assertions in Specter :param obj: The evaluated target object :param caller_args: Is only used when using expecting a raised Exception
7.504286
8.678361
0.864712
def decorator(test_func): if not isinstance(test_func, (type, ClassObjType)): func_data = None if test_func.__name__ == 'DECORATOR_ONCALL': # Call down and save the results func_data = test_func() @functools.wraps(test_func) ...
def skip(reason)
The skip decorator allows for you to always bypass a test. :param reason: Expects a string
4.231591
4.370657
0.968182
if condition: return skip(reason) def wrapper(func): return func return wrapper
def skip_if(condition, reason=None)
The skip_if decorator allows for you to bypass a test on conditions :param condition: Expects a boolean :param reason: Expects a string
4.867493
10.922278
0.445648
if not isinstance(test_func, (type, ClassObjType)): @functools.wraps(test_func) def skip_wrapper(*args, **kwargs): raise TestIncompleteException(test_func, _('Test is incomplete')) return skip_wrapper
def incomplete(test_func)
The incomplete decorator behaves much like a normal skip; however, tests that are marked as incomplete get tracked under a different metric. This allows for you to create a skeleton around all of your features and specifications, and track what tests have been written and what tests are left outstanding...
4.594723
6.129773
0.749575
def onTestFunc(func): def DECORATOR_ONCALL(*args, **kwargs): return (func, key_value_pairs) return DECORATOR_ONCALL return onTestFunc
def metadata(**key_value_pairs)
The metadata decorator allows for you to tag specific tests with key/value data for run-time processing or reporting. The common use case is to use metadata to tag a test as a positive or negative test type. .. code-block:: python # Example of using the metadata decorator @metadata(type='n...
6.811258
9.280231
0.733953
converted_dict = { 'success': self.success, 'assertion': str(self), 'required': self.required } return converted_dict
def serialize(self)
Serializes the ExpectAssert object for collection. Warning, this will only grab the available information. It is strongly that you only call this once all specs and tests have completed.
8.129173
6.183108
1.314739
types.update(getattr(self.__class__, "put")._accepts) any_dispatch = True except AttributeError: pass try: types.update(getattr(self.__class__, "put_many")._accepts) any_dispatch = True except AttributeError: pass re...
def accepts(self): # type: Union[Iterable[Type[T]], Type[Any]] types = set() any_dispatch = False try
The types of objects the data sink can store.
3.861789
3.703814
1.042652
pass
def put_many(self, type: Type[T], items: Iterable[T], context: PipelineContext = None) -> None
Puts multiple objects of the same type into the data sink. Args: type: The type of the objects being inserted. items: The objects to be inserted. context: The context of the insertion (mutable).
547,562.625
17,126.441406
31.971769
if format == "auto" or format == None: format = detect_format(filename) if format == "warc": return WARCFile(filename, mode) elif format == "arc": return ARCFile(filename, mode) else: raise IOError("Don't know how to open '%s' files"%format)
def open(filename, mode="rb", format = None)
Shorthand for WARCFile(filename, mode). Auto detects file and opens it.
2.791992
2.477863
1.126774
if "WARC-Record-ID" not in self: self['WARC-Record-ID'] = "<urn:uuid:%s>" % uuid.uuid1() if "WARC-Date" not in self: self['WARC-Date'] = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ') if "Content-Type" not in self: self['Content-Type'] = WA...
def init_defaults(self)
Initializes important headers to default values, if not already specified. The WARC-Record-ID header is set to a newly generated UUID. The WARC-Date header is set to the current datetime. The Content-Type is set based on the WARC-Type header. The Content-Length is initialized to...
2.324721
1.910454
1.216842
f.write(self.version + "\r\n") for name, value in self.items(): name = name.title() # Use standard forms for commonly used patterns name = name.replace("Warc-", "WARC-").replace("-Ip-", "-IP-").replace("-Id", "-ID").replace("-Uri", "-URI") f.write...
def write_to(self, f)
Writes this header to a file, in the format specified by WARC.
4.663958
3.936986
1.184652
# Get the httplib.HTTPResponse object http_response = response.raw._original_response # HTTP status line, headers and body as strings status_line = "HTTP/1.1 %d %s" % (http_response.status, http_response.reason) headers = str(http_response.msg) body = ht...
def from_response(response)
Creates a WARCRecord from given response object. This must be called before reading the response. The response can be read after this method is called. :param response: An instance of :class:`requests.models.Response`.
3.806463
3.657928
1.040606
warc_record.write_to(self.fileobj) # Each warc record is written as separate member in the gzip file # so that each record can be read independetly. if isinstance(self.fileobj, gzip2.GzipFile): self.fileobj.close_member()
def write_record(self, warc_record)
Adds a warc record to this WARC file.
7.334243
6.629625
1.106283
offset = 0 for record in self.reader: # Just read the first 1MB of the payload. # This will make sure memory consuption is under control and it # is possible to look at the first MB of the payload, which is # typically sufficient to read http he...
def browse(self)
Utility to browse through the records in the warc file. This returns an iterator over (record, offset, size) for each record in the file. If the file is gzip compressed, the offset and size will corresponds to the compressed file. The payload of each record is limite...
7.5635
5.503243
1.374371
if isinstance(self.fileobj, gzip2.GzipFile): return self.fileobj.fileobj.tell() else: return self.fileobj.tell()
def tell(self)
Returns the file offset. If this is a compressed file, then the offset in the compressed file is returned.
4.090053
3.00745
1.359974
# The new member is not yet started, no need to close if self._new_member: return self.fileobj.write(self.compress.flush()) write32u(self.fileobj, self.crc) # self.size may exceed 2GB, or even 4GB write32u(self.fileobj, self.size & 0xffff...
def close_member(self)
Closes the current member being written.
4.30822
4.018563
1.07208
if self._new_member: self._init_write(self.name) self._write_gzip_header() self._new_member = False
def _start_member(self)
Starts writing a new member if required.
7.343404
5.181868
1.417135
if self.fileobj is None: return if self.mode == WRITE: self.close_member() self.fileobj = None elif self.mode == READ: self.fileobj = None if self.myfileobj: self.myfileobj.close() self.myfileob...
def close(self)
Closes the gzip with care to handle multiple members.
3.603613
3.005308
1.199083
if self._member_lock is False: self._member_lock = True if self._new_member: try: # Read one byte to move to the next member BaseGzipFile._read(self, 1) assert self._new_member is False except EOFError: ...
def read_member(self)
Returns a file-like object to read one member from the gzip file.
7.445472
5.64111
1.319859
if isinstance(data, basestring): self.write(data) else: for text in data: self.write(text) self.close_member()
def write_member(self, data)
Writes the given data as one gzip member. The data can be a string, an iterator that gives strings or a file-like object.
3.335475
2.761351
1.207914
if not version: version = self.version if version == 1: header = "%(url)s %(ip_address)s %(date)s %(content_type)s %(length)s" elif version == 2: header = "%(url)s %(ip_address)s %(date)s %(content_type)s %(result_code)s %(checksum)s %(location)s %(of...
def write_to(self, f, version = None)
Writes out the arc header to the file like object `f`. If the version field is 1, it writes out an arc v1 header, otherwise (and this is default), it outputs a v2 header.
2.182414
2.188303
0.997309
header, payload = string.split("\n",1) if payload[0] == '\n': # There's an extra payload = payload[1:] if int(version) == 1: arc_header_re = ARC1_HEADER_RE elif int(version) == 2: arc_header_re = ARC2_HEADER_RE matches = arc_header_re...
def from_string(cls, string, version)
Constructs an ARC record from a string and returns it. TODO: It might be best to merge this with the _read_arc_record function rather than reimplement the functionality here.
3.442588
3.036306
1.133808
"Writes out an ARC header" if "org" not in self.file_headers: warnings.warn("Using 'unknown' for Archiving organisation name") self.file_headers['org'] = "Unknown" if "date" not in self.file_headers: now = datetime.datetime.utcnow() warnings.warn("...
def _write_header(self)
Writes out an ARC header
3.862737
3.783664
1.020899
"Writes out the given arc record to the file" if not self.version: self.version = 2 if not self.header_written: self.header_written = True self._write_header() arc_record.write_to(self.fileobj, self.version) self.fileobj.write("\n")
def write(self, arc_record)
Writes out the given arc record to the file
3.681751
3.477965
1.058594
header = self.fileobj.readline() payload1 = self.fileobj.readline() payload2 = self.fileobj.readline() version, reserved, organisation = payload1.split(None, 2) self.fileobj.readline() # Lose the separator newline self.header_read = True # print "--------...
def _read_file_header(self)
Reads out the file header for the arc file. If version was not provided, this will autopopulate it.
3.277273
3.086504
1.061807
"Reads out an arc record, formats it and returns it" #XXX:Noufal Stream payload here rather than just read it # r = self.fileobj.readline() # Drop the initial newline # if r == "": # return None # header = self.fileobj.readline() # Strip the initial new lines...
def _read_arc_record(self)
Reads out an arc record, formats it and returns it
4.956353
4.669919
1.061336
try: return cls(registry.get('bank_code')[(country_code, bank_code)]['bic']) except KeyError: raise ValueError("Invalid bank code {!r} for country {!r}".format(bank_code, country_code))
def from_bank_code(cls, country_code, bank_code)
Create a new BIC object from country- and bank-code. Examples: >>> bic = BIC.from_bank_code('DE', '20070000') >>> bic.country_code 'DE' >>> bic.bank_code 'DEUT' >>> bic.location_code 'HH' >>> BIC.from_bank_code('DE...
4.199496
3.878213
1.082843
formatted = ' '.join([self.bank_code, self.country_code, self.location_code]) if self.branch_code: formatted += ' ' + self.branch_code return formatted
def formatted(self)
str: The BIC separated in the blocks bank-, country- and location-code.
4.256084
2.18766
1.945496
entry = registry.get('bic').get(self.compact) if entry: return entry.get('bank_code')
def country_bank_code(self)
str or None: The country specific bank-code associated with the BIC.
14.052873
9.608434
1.462556
entry = registry.get('bic').get(self.compact) if entry: return entry.get('name')
def bank_name(self)
str or None: The name of the bank associated with the BIC.
16.061853
10.81549
1.485079
entry = registry.get('bic').get(self.compact) if entry: return entry.get('short_name')
def bank_short_name(self)
str or None: The short name of the bank associated with the BIC.
13.470011
9.673143
1.392516
spec = _get_iban_spec(country_code) bank_code_length = code_length(spec, 'bank_code') branch_code_length = code_length(spec, 'branch_code') bank_and_branch_code_length = bank_code_length + branch_code_length account_code_length = code_length(spec, 'account_code') ...
def generate(cls, country_code, bank_code, account_code)
Generate an IBAN from it's components. If the bank-code and/or account-number have less digits than required by their country specific representation, the respective component is padded with zeros. Examples: To generate an IBAN do the following:: >>> bank_code = '...
1.938932
1.908916
1.015724
return ' '.join(self.compact[i:i + 4] for i in range(0, len(self.compact), 4))
def formatted(self)
str: The IBAN formatted in blocks of 4 digits.
4.550421
3.009768
1.511885
parser = tdms2rtdc_parser() args = parser.parse_args() path_tdms = pathlib.Path(args.tdms_path).resolve() path_rtdc = pathlib.Path(args.rtdc_path) # Determine whether input path is a tdms file or a directory if path_tdms.is_dir(): files_tdms = fmt_tdms.get_tdms_files(path_tdms) ...
def tdms2rtdc()
Convert .tdms datasets to the hdf5-based .rtdc file format
3.328794
3.268444
1.018464
parser = verify_dataset_parser() args = parser.parse_args() path_in = pathlib.Path(args.path).resolve() viol, aler, info = load.check_dataset(path_in) print_info("Checking {}".format(path_in)) for inf in info: print_info(inf) for ale in aler: print_alert(ale) for vio...
def verify_dataset()
Perform checks on experimental datasets
4.154029
4.177497
0.994382
path = pathlib.Path(cfg_file).resolve() with path.open('r') as f: code = f.readlines() cfg = CaseInsensitiveDict() for line in code: # We deal with comments and empty lines # We need to check line length first and then we look for # a hash. line = line.split...
def load_from_file(cfg_file)
Load the configuration from a file Parameters ---------- cfg_file: str Path to configuration file Returns ------- cfg : CaseInsensitiveDict Dictionary with configuration parameters
4.319993
4.259887
1.01411
if not (isinstance(val, str_types)): # already a type: return var.strip(), val var = var.strip().lower() val = val.strip() # Find values if len(var) != 0 and len(val) != 0: # check for float if val.startswith("[") and val.endswith("]"): if len(val.str...
def keyval_str2typ(var, val)
Convert a variable from a string to its correct type Parameters ---------- var: str The variable name val: str The value of the variable represented as a string Returns ------- varout: str Stripped lowercase `var` valout: any type The value converted fro...
3.098262
3.195347
0.969617
varout = var.strip() if isinstance(val, list): data = ", ".join([keyval_typ2str(var, it)[1] for it in val]) valout = "["+data+"]" elif isinstance(val, float): valout = "{:.12f}".format(val) else: valout = "{}".format(val) return varout, valout
def keyval_typ2str(var, val)
Convert a variable to a string Parameters ---------- var: str The variable name val: any type The value of the variable Returns ------- varout: str Stripped lowercase `var` valout: any type The value converted to a useful string representation See A...
2.925235
2.995573
0.97652
# Do not filter out invalid event values self["filtering"]["remove invalid events"] = False # Enable filters switch is mandatory self["filtering"]["enable filters"] = True # Limit events integer to downsample output data self["filtering"]["limit events"] = 0 ...
def _init_default_values(self)
Set default initial values The default values are hard-coded for backwards compatibility and for several functionalities in dclab.
11.567266
11.544471
1.001975
filename = pathlib.Path(filename) out = [] keys = sorted(list(self.keys())) for key in keys: out.append("[{}]".format(key)) section = self[key] ikeys = list(section.keys()) ikeys.sort() for ikey in ikeys: ...
def save(self, filename)
Save the configuration to a file
3.408122
3.27712
1.039975
for key in newcfg.keys(): if key not in self._cfg: self._cfg[key] = CaseInsensitiveDict() for skey in newcfg[key]: self._cfg[key][skey] = newcfg[key][skey]
def update(self, newcfg)
Update current config with a dictionary
2.666254
2.61162
1.020919
copy = not inplace # make sure area_um_corr is not an integer array area_um_corr = np.array(area_um, dtype=float, copy=copy) deform_corr = np.array(deform, copy=copy) emodulus_corr = np.array(emodulus, copy=copy) if channel_width_in != channel_width_out: area_um_corr *= (channel_wi...
def convert(area_um, deform, emodulus, channel_width_in, channel_width_out, flow_rate_in, flow_rate_out, viscosity_in, viscosity_out, inplace=False)
convert area-deformation-emodulus triplet The conversion formula is described in :cite:`Mietke2015`. Parameters ---------- area_um: ndarray Convex cell area [µm²] deform: ndarray Deformation emodulus: ndarray Young's Modulus [kPa] channel_width_in: float Ori...
1.965798
1.948779
1.008733
# A triple-exponential decay can be used to correct for pixelation # for apparent cell areas between 10 and 1250µm². # For 99 different radii between 0.4 μm and 20 μm circular objects were # simulated on a pixel grid with the pixel resolution of 340 nm/pix. At # each radius 1000 random starting...
def corrpix_deform_delta(area_um, px_um=0.34)
Deformation correction term for pixelation effects The contour in RT-DC measurements is computed on a pixelated grid. Due to sampling problems, the measured deformation is overestimated and must be corrected. The correction formula is described in :cite:`Herold2017`. Parameters ---------- ...
8.741393
7.995672
1.093266
x = e.details() name = x[:x.find(':')].split('.')[-1] if name in globals(): cls = globals()[name] else: cls = UnknownRpcException # noqa return cls(method, e.code(), e.details())
def make_exception(method, e)
Creates an exception for a given method, and RpcError.
5.678771
4.740656
1.197887
if text.startswith("0x"): value = int(text[2:], 16) elif text.startswith("$"): value = int(text[1:], 16) elif text.startswith("#"): value = int(text[1:], 10) elif text.startswith("%"): value = int(text[1:], 2) else: if default_base == "dec": v...
def text_to_int(text, default_base="hex")
Convert text to int, raising exeception on invalid input
1.735575
1.72619
1.005437
num = len(sector_list) order = self.reserve_space(num) if len(order) != num: raise errors.InvalidFile("VTOC reserved space for %d sectors. Sectors needed: %d" % (len(order), num)) file_length = 0 last_sector = None for sector, sector_num in zip(sector...
def assign_sector_numbers(self, dirent, sector_list)
Map out the sectors and link the sectors together raises NotEnoughSpaceOnDisk if the whole file won't fit. It will not allow partial writes.
3.275504
3.105522
1.054735
# fixed random state for this method rs = np.random.RandomState(seed=47).get_state() np.random.set_state(rs) samples = int(samples) if remove_invalid: # slice out nans and infs bad = np.isnan(a) | np.isinf(a) pool = a[~bad] else: pool = a if samples an...
def downsample_rand(a, samples, remove_invalid=False, ret_idx=False)
Downsampling by randomly removing points Parameters ---------- a: 1d ndarray The input array to downsample samples: int The desired number of samples remove_invalid: bool Remove nan and inf values before downsampling ret_idx: bool Also return a boolean array that...
2.818462
2.695953
1.045442
# fixed random state for this method rs = np.random.RandomState(seed=47).get_state() samples = int(samples) if samples and samples < a.size: # The events to keep keep = np.zeros_like(a, dtype=bool) # 1. Produce evenly distributed samples # Choosing grid-size: ...
def downsample_grid(a, b, samples, ret_idx=False)
Content-based downsampling for faster visualization The arrays `a` and `b` make up a 2D scatter plot with high and low density values. This method takes out points at indices with high density. Parameters ---------- a, b: 1d ndarrays The input arrays to downsample samples: int ...
3.552018
3.506379
1.013016
return ~(np.isnan(a) | np.isinf(a) | np.isnan(b) | np.isinf(b))
def valid(a, b)
Check whether `a` and `b` are not inf or nan
2.552115
2.111381
1.208742
ref = ref1[valid(ref1, ref2)] return (a-ref.min())/(ref.max()-ref.min())
def norm(a, ref1, ref2)
Normalize `a` with min/max values of `ref1`, using all elements of `ref1` where the `ref1` and `ref2` are not nan or inf
4.487026
4.31624
1.039568
return (1. / np.sqrt(2 * np.pi)) * np.exp(-(Xi - x)**2 / (h**2 * 2.))
def gaussian(h, Xi, x)
Gaussian Kernel for continuous variables Parameters ---------- h : 1-D ndarray, shape (K,) The bandwidths used to estimate the value of the kernel function. Xi : 1-D ndarray, shape (K,) The value of the training set. x : 1-D ndarray, shape (K,) The value at which the kernel d...
3.014089
4.787929
0.629518
with h5py.File(h5path, mode="r") as fh5: h5attrs = dict(fh5.attrs) # Convert byte strings to unicode strings # https://github.com/h5py/h5py/issues/379 for key in h5attrs: if isinstance(h5attrs[key], bytes): h5attrs[key] = h5attrs[key].dec...
def parse_config(h5path)
Parse the RT-DC configuration of an hdf5 file
3.041429
3.082764
0.986591
if self._hash is None: tohash = [self.path.name] # Hash a maximum of ~1MB of the hdf5 file tohash.append(hashfile(self.path, blocksize=65536, count=20)) self._hash = hashobj(tohash) return self._hash
def hash(self)
Hash value based on file name and content
6.652791
6.233806
1.067212
bad = np.isnan(a) | np.isinf(a) data = a[~bad] acc = bin_width_doane(a) num = np.int(np.round((data.max() - data.min()) / acc)) return num
def bin_num_doane(a)
Compute number of bins based on Doane's formula
4.352742
4.031079
1.079796
bad = np.isnan(a) | np.isinf(a) data = a[~bad] n = data.size g1 = skew(data) sigma_g1 = np.sqrt(6 * (n - 2) / ((n + 1) * (n + 3))) k = 1 + np.log2(n) + np.log2(1 + np.abs(g1) / sigma_g1) acc = (data.max() - data.min()) / k return acc
def bin_width_doane(a)
Compute accuracy (bin width) based on Doane's formula References ---------- - `<https://en.wikipedia.org/wiki/Histogram#Number_of_bins_and_width>`_ - `<https://stats.stackexchange.com/questions/55134/ doanes-formula-for-histogram-binning>`_
3.612694
3.75222
0.962815
def new_kde_method(events_x, events_y, xout=None, yout=None, *args, **kwargs): bad_in = get_bad_vals(events_x, events_y) if xout is None: density = np.zeros_like(events_x, dtype=float) bad_out = bad_in xo = yo = None else: ...
def ignore_nan_inf(kde_method)
Ignores nans and infs from the input data Invalid positions in the resulting density are set to nan.
2.689363
2.688411
1.000354
valid_combi = ((xout is None and yout is None) or (xout is not None and yout is not None) ) if not valid_combi: raise ValueError("Both `xout` and `yout` must be (un)set.") if yout is None and yout is None: xout = events_x yout = events_y ...
def kde_gauss(events_x, events_y, xout=None, yout=None)
Gaussian Kernel Density Estimation Parameters ---------- events_x, events_y: 1D ndarray The input points for kernel density estimation. Input is flattened automatically. xout, yout: ndarray The coordinates at which the KDE should be computed. If set to none, input coordi...
3.156168
3.367106
0.937353
valid_combi = ((xout is None and yout is None) or (xout is not None and yout is not None) ) if not valid_combi: raise ValueError("Both `xout` and `yout` must be (un)set.") if yout is None and yout is None: xout = events_x yout = events_y ...
def kde_histogram(events_x, events_y, xout=None, yout=None, bins=None)
Histogram-based Kernel Density Estimation Parameters ---------- events_x, events_y: 1D ndarray The input points for kernel density estimation. Input is flattened automatically. xout, yout: ndarray The coordinates at which the KDE should be computed. If set to none, input...
2.537439
2.586757
0.980934
valid_combi = ((xout is None and yout is None) or (xout is not None and yout is not None) ) if not valid_combi: raise ValueError("Both `xout` and `yout` must be (un)set.") if yout is None and yout is None: xout = events_x yout = events_y ...
def kde_none(events_x, events_y, xout=None, yout=None)
No Kernel Density Estimation Parameters ---------- events_x, events_y: 1D ndarray The input points for kernel density estimation. Input is flattened automatically. xout, yout: ndarray The coordinates at which the KDE should be computed. If set to none, input coordinates ...
3.335994
3.324749
1.003382
valid_combi = ((xout is None and yout is None) or (xout is not None and yout is not None) ) if not valid_combi: raise ValueError("Both `xout` and `yout` must be (un)set.") if yout is None and yout is None: xout = events_x yout = events_y ...
def kde_multivariate(events_x, events_y, xout=None, yout=None, bw=None)
Multivariate Kernel Density Estimation Parameters ---------- events_x, events_y: 1D ndarray The input points for kernel density estimation. Input is flattened automatically. bw: tuple (bwx, bwy) or None The bandwith for kernel density estimation. xout, yout: ndarray ...
3.46878
3.561396
0.973994
routing_args = request.matchdict objid = routing_args['objid'] objver = routing_args.get('objver') filename = routing_args.get('filename') id, version = _convert_legacy_id(objid, objver) if not id: raise httpexceptions.HTTPNotFound() # We always use 301 redirects (HTTPMovedPe...
def redirect_legacy_content(request)
Redirect from legacy /content/id/version to new /contents/uuid@version. Handles collection context (book) as well.
5.049673
4.850581
1.041045
self._data[method][col1][col2]["isoelastics"] = isoel self._data[method][col1][col2]["meta"] = meta # Use advanced slicing to flip the data columns isoel_flip = [iso[:, [1, 0, 2]] for iso in isoel] self._data[method][col2][col1]["isoelastics"] = isoel_flip self....
def _add(self, isoel, col1, col2, method, meta)
Convenience method for population self._data
3.394997
3.164804
1.072735
if method not in VALID_METHODS: validstr = ",".join(VALID_METHODS) raise ValueError("`method` must be one of {}!".format(validstr)) for col in [col1, col2]: if col not in dfn.scalar_feature_names: raise ValueError("Not a valid feature name: {}...
def add(self, isoel, col1, col2, channel_width, flow_rate, viscosity, method)
Add isoelastics Parameters ---------- isoel: list of ndarrays Each list item resembles one isoelastic line stored as an array of shape (N,3). The last column contains the emodulus data. col1: str Name of the first feature of all isoelastic...
3.217643
2.980588
1.079533
Isoelastics.check_col12(col1, col2) if "deform" in [col1, col2]: # add error for deformation sign = +1 else: # subtract error for circularity sign = -1 if col1 == "area_um": area_ax = 0 deci_ax = 1 e...
def add_px_err(isoel, col1, col2, px_um, inplace=False)
Undo pixelation correction Isoelasticity lines are already corrected for pixelation effects as described in Mapping of Deformation to Apparent Young's Modulus in Real-Time Deformability Cytometry Christoph Herold, arXiv:1704.00572 [cond-mat.soft] (2017) https://arxiv.or...
5.646657
4.834225
1.168058
Isoelastics.check_col12(col1, col2) if col1 == "area_um": area_ax = 0 defo_ax = 1 else: area_ax = 1 defo_ax = 0 new_isoel = [] for iso in isoel: iso = np.array(iso, copy=not inplace) feat_emod.conv...
def convert(isoel, col1, col2, channel_width_in, channel_width_out, flow_rate_in, flow_rate_out, viscosity_in, viscosity_out, inplace=False)
Convert isoelastics in area_um-deform space Parameters ---------- isoel: list of 2d ndarrays of shape (N, 3) Each item in the list corresponds to one isoelasticity line. The first column is defined by `col1`, the second by `col2`, and the third column is the ...
3.025991
2.361831
1.281206
if method not in VALID_METHODS: validstr = ",".join(VALID_METHODS) raise ValueError("`method` must be one of {}!".format(validstr)) for col in [col1, col2]: if col not in dfn.scalar_feature_names: raise ValueError("Not a valid feature name: {}...
def get(self, col1, col2, method, channel_width, flow_rate=None, viscosity=None, add_px_err=False, px_um=None)
Get isoelastics Parameters ---------- col1: str Name of the first feature of all isoelastics (e.g. isoel[0][:,0]) col2: str Name of the second feature of all isoelastics (e.g. isoel[0][:,1]) method: str The method used ...
2.6808
2.41903
1.108213
cfg = dataset.config return self.get(col1=col1, col2=col2, method=method, channel_width=cfg["setup"]["channel width"], flow_rate=cfg["setup"]["flow rate"], viscosity=viscosity...
def get_with_rtdcbase(self, col1, col2, method, dataset, viscosity=None, add_px_err=False)
Convenience method that extracts the metadata from RTDCBase Parameters ---------- col1: str Name of the first feature of all isoelastics (e.g. isoel[0][:,0]) col2: str Name of the second feature of all isoelastics (e.g. isoel[0][:,1]) ...
3.794575
4.29027
0.884461
path = pathlib.Path(path).resolve() # Get metadata meta = {} with path.open() as fd: while True: line = fd.readline().strip() if line.startswith("# - "): line = line.strip("#- ") var, val = line....
def load_data(self, path)
Load isoelastics from a text file The text file is loaded with `numpy.loadtxt` and must have three columns, representing the two data columns and the elastic modulus with units defined in `definitions.py`. The file header must have a section defining meta data of the content lik...
4.003314
3.062689
1.307124
resp = request.response resp.status = '200 OK' resp.content_type = 'text/plain' resp.body = return resp
def robots(request)
Return a simple "don't index me" robots.txt file.
3.686711
3.5641
1.034402
ct11 = 1 ct22 = 1 ct33 = 1 if ct21 < 0: raise ValueError("ct21 matrix element must not be negative!") if ct31 < 0: raise ValueError("ct31 matrix element must not be negative!") if ct12 < 0: raise ValueError("ct12 matrix element must not be negative!") if ct32...
def get_compensation_matrix(ct21, ct31, ct12, ct32, ct13, ct23)
Compute crosstalk inversion matrix The spillover matrix is | | c11 c12 c13 | | | c21 c22 c23 | | | c31 c32 c33 | The diagonal elements are set to 1, i.e. ct11 = c22 = c33 = 1 Parameters ---------- cij: float Spill from channel i to channel j Returns ------- ...
1.633496
1.680345
0.972119
fl_channel = int(fl_channel) if fl_channel not in [1, 2, 3]: raise ValueError("`fl_channel` must be 1, 2, or 3!") minv = get_compensation_matrix(ct21=ct21, ct31=ct31, ct12=ct12, ct32=ct32, ct13=ct13, ct23=ct23) col = minv[:, fl_channel - 1].flatten() ...
def correct_crosstalk(fl1, fl2, fl3, fl_channel, ct21=0, ct31=0, ct12=0, ct32=0, ct13=0, ct23=0)
Perform crosstalk correction Parameters ---------- fli: int, float, or np.ndarray Measured fluorescence signals fl_channel: int (1, 2, or 3) The channel number for which the crosstalk-corrected signal should be computed cij: float Spill (crosstalk or bleed-through) f...
2.401535
2.289721
1.048833
if isinstance(cont, np.ndarray): # If cont is an array, it is not a list of contours, # because contours can have different lengths. cont = [cont] ret_list = False else: ret_list = True length = len(cont) inert_ratio_cvx = np.zeros(length, dtype=float) * np...
def get_inert_ratio_cvx(cont)
Compute the inertia ratio of the convex hull of a contour The inertia ratio is computed from the central second order of moments along x (mu20) and y (mu02) via `sqrt(mu20/mu02)`. Parameters ---------- cont: ndarray or list of ndarrays of shape (N,2) A 2D array that holds the contour of an...
2.770022
2.843548
0.974143