Search is not available for this dataset
text
stringlengths
75
104k
def read(path, mode='tsv'): ''' Helper function to read Document in TTL-TXT format (i.e. ${docname}_*.txt) E.g. read('~/data/myfile') is the same as Document('myfile', '~/data/').read() ''' if mode == 'tsv': return TxtReader.from_path(path).read() elif mode == 'json': return read_jso...
def write(path, doc, mode=MODE_TSV, **kwargs): ''' Helper function to write doc to TTL-TXT format ''' if mode == MODE_TSV: with TxtWriter.from_path(path) as writer: writer.write_doc(doc) elif mode == MODE_JSON: write_json(path, doc, **kwargs)
def tcmap(self): ''' Create a tokens-concepts map ''' tcmap = dd(list) for concept in self.__concept_map.values(): for w in concept.tokens: tcmap[w].append(concept) return tcmap
def msw(self): ''' Return a generator of tokens with more than one sense. ''' return (t for t, c in self.tcmap().items() if len(c) > 1)
def surface(self, tag): ''' Get surface string that is associated with a tag object ''' if tag.cfrom is not None and tag.cto is not None and tag.cfrom >= 0 and tag.cto >= 0: return self.text[tag.cfrom:tag.cto] else: return ''
def new_tag(self, label, cfrom=-1, cto=-1, tagtype='', **kwargs): ''' Create a sentence-level tag ''' tag_obj = Tag(label, cfrom, cto, tagtype=tagtype, **kwargs) return self.add_tag(tag_obj)
def get_tag(self, tagtype): ''' Get the first tag of a particular type''' for tag in self.__tags: if tag.tagtype == tagtype: return tag return None
def get_tags(self, tagtype): ''' Get all tags of a type ''' return [t for t in self.__tags if t.tagtype == tagtype]
def add_token_object(self, token): ''' Add a token object into this sentence ''' token.sent = self # take ownership of given token self.__tokens.append(token) return token
def new_concept(self, tag, clemma="", tokens=None, cidx=None, **kwargs): ''' Create a new concept object and add it to concept list tokens can be a list of Token objects or token indices ''' if cidx is None: cidx = self.new_concept_id() if tokens: tokens =...
def add_concept(self, concept_obj): ''' Add a concept to current concept list ''' if concept_obj is None: raise Exception("Concept object cannot be None") elif concept_obj in self.__concepts: raise Exception("Concept object is already inside") elif concept_obj.cid...
def concept(self, cid, **kwargs): ''' Get concept by concept ID ''' if cid not in self.__concept_map: if 'default' in kwargs: return kwargs['default'] else: raise KeyError("Invalid cid") else: return self.__concept_map[cid]
def import_tokens(self, tokens, import_hook=None, ignorecase=True): ''' Import a list of string as tokens ''' text = self.text.lower() if ignorecase else self.text has_hooker = import_hook and callable(import_hook) cfrom = 0 if self.__tokens: for tk in self.__tokens: ...
def tag_map(self): ''' Build a map from tagtype to list of tags ''' tm = dd(list) for tag in self.__tags: tm[tag.tagtype].append(tag) return tm
def find(self, tagtype, **kwargs): '''Get the first tag with a type in this token ''' for t in self.__tags: if t.tagtype == tagtype: return t if 'default' in kwargs: return kwargs['default'] else: raise LookupError("Token {} is not tagg...
def find_all(self, tagtype): ''' Find all token-level tags with the specified tagtype ''' return [t for t in self.__tags if t.tagtype == tagtype]
def new_tag(self, label, cfrom=None, cto=None, tagtype=None, **kwargs): ''' Create a new tag on this token ''' if cfrom is None: cfrom = self.cfrom if cto is None: cto = self.cto tag = Tag(label=label, cfrom=cfrom, cto=cto, tagtype=tagtype, **kwargs) retur...
def get(self, sent_id, **kwargs): ''' If sent_id exists, remove and return the associated sentence object else return default. If no default is provided, KeyError will be raised.''' if sent_id is not None and not isinstance(sent_id, int): sent_id = int(sent_id) if sent_id is ...
def add_sent(self, sent_obj): ''' Add a ttl.Sentence object to this document ''' if sent_obj is None: raise Exception("Sentence object cannot be None") elif sent_obj.ID is None: # if sentID is None, create a new ID sent_obj.ID = next(self.__idgen) elif...
def new_sent(self, text, ID=None, **kwargs): ''' Create a new sentence and add it to this Document ''' if ID is None: ID = next(self.__idgen) return self.add_sent(Sentence(text, ID=ID, **kwargs))
def pop(self, sent_id, **kwargs): ''' If sent_id exists, remove and return the associated sentence object else return default. If no default is provided, KeyError will be raised.''' if sent_id is not None and not isinstance(sent_id, int): sent_id = int(sent_id) if not self.ha...
def read(self): ''' Read tagged doc from mutliple files (sents, tokens, concepts, links, tags) ''' warnings.warn("Document.read() is deprecated and will be removed in near future.", DeprecationWarning) with TxtReader.from_doc(self) as reader: reader.read(self) return self
def read_ttl(path): ''' Helper function to read Document in TTL-TXT format (i.e. ${docname}_*.txt) E.g. Document.read_ttl('~/data/myfile') is the same as Document('myfile', '~/data/').read() ''' warnings.warn("Document.read_ttl() is deprecated and will be removed in near future. Use read...
def read(self, doc=None): ''' Read tagged doc from mutliple files (sents, tokens, concepts, links, tags) ''' if not self.sent_stream: raise Exception("There is no sentence data stream available") if doc is None: doc = Document(name=self.doc_name, path=self.doc_path) ...
def format_page(text): """Format the text for output adding ASCII frame around the text. Args: text (str): Text that needs to be formatted. Returns: str: Formatted string. """ width = max(map(len, text.splitlines())) page = "+-" + "-" * width + "-+\n" for line in...
def table(text): """Format the text as a table. Text in format: first | second row 2 col 1 | 4 Will be formatted as:: +-------------+--------+ | first | second | +-------------+--------+ | row 2 col 1 | 4 | +-------------+--------+...
def print_page(text): """Format the text and prints it on stdout. Text is formatted by adding a ASCII frame around it and coloring the text. Colors can be added to text using color tags, for example: My [FG_BLUE]blue[NORMAL] text. My [BG_BLUE]blue background[NORMAL] text. """ ...
def wrap_text(text, width=80): """Wrap text lines to maximum *width* characters. Wrapped text is aligned against the left text border. Args: text (str): Text to wrap. width (int): Maximum number of characters per line. Returns: str: Wrapped text. """ text =...
def rjust_text(text, width=80, indent=0, subsequent=None): """Wrap text and adjust it to right border. Same as L{wrap_text} with the difference that the text is aligned against the right text border. Args: text (str): Text to wrap and align. width (int): Maximum number of chara...
def center_text(text, width=80): """Center all lines of the text. It is assumed that all lines width is smaller then B{width}, because the line width will not be checked. Args: text (str): Text to wrap. width (int): Maximum number of characters per line. Returns: ...
def check(qpi_or_h5file, checks=["attributes", "background"]): """Checks various properties of a :class:`qpimage.core.QPImage` instance Parameters ---------- qpi_or_h5file: qpimage.core.QPImage or str A QPImage object or a path to an hdf5 file checks: list of str Which checks to per...
def check_attributes(qpi): """Check QPimage attributes Parameters ---------- qpi: qpimage.core.QPImage Raises ------ IntegrityCheckError if the check fails """ missing_attrs = [] for key in DATA_KEYS: if key not in qpi.meta: missing_attrs.append(key)...
def check_background(qpi): """Check QPimage background data Parameters ---------- qpi: qpimage.core.QPImage Raises ------ IntegrityCheckError if the check fails """ for imdat in [qpi._amp, qpi._pha]: try: fit, attrs = imdat.get_bg(key="fit", ret_attrs=Tr...
def write_image_dataset(group, key, data, h5dtype=None): """Write an image to an hdf5 group as a dataset This convenience function sets all attributes such that the image can be visualized with HDFView, sets the compression and fletcher32 filters, and sets the chunk size to the image shape. Parame...
def info(self): """list of background correction parameters""" info = [] name = self.__class__.__name__.lower() # get bg information for key in VALID_BG_KEYS: if key in self.h5["bg_data"]: attrs = self.h5["bg_data"][key].attrs for akey ...
def del_bg(self, key): """Remove the background image data Parameters ---------- key: str One of :const:`VALID_BG_KEYS` """ if key not in VALID_BG_KEYS: raise ValueError("Invalid bg key: {}".format(key)) if key in self.h5["bg_data"]: ...
def estimate_bg(self, fit_offset="mean", fit_profile="tilt", border_px=0, from_mask=None, ret_mask=False): """Estimate image background Parameters ---------- fit_profile: str The type of background profile to fit: - "offset": offset only ...
def get_bg(self, key=None, ret_attrs=False): """Get the background data Parameters ---------- key: None or str A user-defined key that identifies the background data. Examples are "data" for experimental data, or "fit" for an estimated background corr...
def set_bg(self, bg, key="data", attrs={}): """Set the background data Parameters ---------- bg: numbers.Real, 2d ndarray, ImageData, or h5py.Dataset The background data. If `bg` is an `h5py.Dataset` object, it must exist in the same hdf5 file (a hard link is cre...
def _bg_combine(self, bgs): """Combine several background amplitude images""" out = np.ones(self.h5["raw"].shape, dtype=float) # bg is an h5py.DataSet for bg in bgs: out *= bg[:] return out
def git_tags() -> str: """ Calls ``git tag -l --sort=-v:refname`` (sorts output) and returns the output as a UTF-8 encoded string. Raises a NoGitTagsException if the repository doesn't contain any Git tags. """ try: subprocess.check_call(['git', 'fetch', '--tags']) except CalledProce...
def git_tag_to_semver(git_tag: str) -> SemVer: """ :git_tag: A string representation of a Git tag. Searches a Git tag's string representation for a SemVer, and returns that as a SemVer object. """ pattern = re.compile(r'[0-9]+\.[0-9]+\.[0-9]+$') match = pattern.search(git_tag) if match:...
def last_git_release_tag(git_tags: str) -> str: """ :git_tags: chronos.helpers.git_tags() function output. Returns the latest Git tag ending with a SemVer as a string. """ semver_re = re.compile(r'[0-9]+\.[0-9]+\.[0-9]+$') str_ver = [] for i in git_tags.split(): if semver_re.search(...
def git_commits_since_last_tag(last_tag: str) -> dict: """ :last_tag: The Git tag that should serve as the starting point for the commit log lookup. Calls ``git log <last_tag>.. --format='%H %s'`` and returns the output as a dict of hash-message pairs. """ try: cmd = ['git', 'log', ...
def parse_commit_log(commit_log: dict) -> str: """ :commit_log: chronos.helpers.git_commits_since_last_tag() output. Parse Git log and return either 'maj', 'min', or 'pat'. """ rv = 'pat' cc_patterns = patterns() for value in commit_log.values(): if re.search(cc_patterns['feat'], ...
def from_str(cls, version_str: str): """ Alternate constructor that accepts a string SemVer. """ o = cls() o.version = version_str return o
def major(self, major: int) -> None: """ param major Major version number property. Must be a non-negative integer. """ self.filter_negatives(major) self._major = major
def minor(self, minor: int) -> None: """ param minor Minor version number property. Must be a non-negative integer. """ self.filter_negatives(minor) self._minor = minor
def patch(self, patch: int) -> None: """ param patch Patch version number property. Must be a non-negative integer. """ self.filter_negatives(patch) self._patch = patch
def version(self) -> str: """ Version version number property. Must be a string consisting of three non-negative integers delimited by periods (eg. '1.0.1'). """ version: str = ( str(self._major) + '.' + str(self._minor) + '.' + str(self._patch...
def version(self, version_str: str) -> None: """ param version Version version number property. Must be a string consisting of three non-negative integers delimited by periods (eg. '1.0.1'). """ ver = [] for i in version_str.split('.'): ver.append(int...
def estimate(data, fit_offset="mean", fit_profile="tilt", border_px=0, from_mask=None, ret_mask=False): """Estimate the background value of an image Parameters ---------- data: np.ndarray Data from which to compute the background value fit_profile: str The type of backg...
def offset_gaussian(data): """Fit a gaussian model to `data` and return its center""" nbins = 2 * int(np.ceil(np.sqrt(data.size))) mind, maxd = data.min(), data.max() drange = (mind - (maxd - mind) / 2, maxd + (maxd - mind) / 2) histo = np.histogram(data, nbins, density=True, range=drange) dx = ...
def offset_mode(data): """Compute Mode using a histogram with `sqrt(data.size)` bins""" nbins = int(np.ceil(np.sqrt(data.size))) mind, maxd = data.min(), data.max() histo = np.histogram(data, nbins, density=True, range=(mind, maxd)) dx = abs(histo[1][1] - histo[1][2]) / 2 hx = histo[1][1:] - dx ...
def profile_tilt(data, mask): """Fit a 2D tilt to `data[mask]`""" params = lmfit.Parameters() params.add(name="mx", value=0) params.add(name="my", value=0) params.add(name="off", value=np.average(data[mask])) fr = lmfit.minimize(tilt_residual, params, args=(data, mask)) bg = tilt_model(fr.pa...
def profile_poly2o(data, mask): """Fit a 2D 2nd order polynomial to `data[mask]`""" # lmfit params = lmfit.Parameters() params.add(name="mx", value=0) params.add(name="my", value=0) params.add(name="mxy", value=0) params.add(name="ax", value=0) params.add(name="ay", value=0) params.a...
def poly2o_model(params, shape): """lmfit 2nd order polynomial model""" mx = params["mx"].value my = params["my"].value mxy = params["mxy"].value ax = params["ax"].value ay = params["ay"].value off = params["off"].value bg = np.zeros(shape, dtype=float) + off x = np.arange(bg.shape[0...
def poly2o_residual(params, data, mask): """lmfit 2nd order polynomial residuals""" bg = poly2o_model(params, shape=data.shape) res = (data - bg)[mask] return res.flatten()
def tilt_model(params, shape): """lmfit tilt model""" mx = params["mx"].value my = params["my"].value off = params["off"].value bg = np.zeros(shape, dtype=float) + off x = np.arange(bg.shape[0]) - bg.shape[0] // 2 y = np.arange(bg.shape[1]) - bg.shape[1] // 2 x = x.reshape(-1, 1) y =...
def tilt_residual(params, data, mask): """lmfit tilt residuals""" bg = tilt_model(params, shape=data.shape) res = (data - bg)[mask] return res.flatten()
def main(cmd_args: list = None) -> None: """ :cmd_args: An optional list of command line arguments. Main function of chronos CLI tool. """ parser = argparse.ArgumentParser(description='Auto-versioning utility.') subparsers = parser.add_subparsers() infer_parser = subparsers.add_parser('inf...
def infer(args: argparse.Namespace) -> None: """ :args: An argparse.Namespace object. This is the function called when the 'infer' sub-command is passed as an argument to the CLI. """ try: last_tag = last_git_release_tag(git_tags()) except NoGitTagsException: print(SemVer(0,...
def bump(args: argparse.Namespace) -> None: """ :args: An argparse.Namespace object. This function is bound to the 'bump' sub-command. It increments the version integer of the user's choice ('major', 'minor', or 'patch'). """ try: last_tag = last_git_release_tag(git_tags()) except N...
def find_sideband(ft_data, which=+1, copy=True): """Find the side band position of a hologram The hologram is Fourier-transformed and the side band is determined by finding the maximum amplitude in Fourier space. Parameters ---------- ft_data: 2d ndarray Fourier transform of the ho...
def fourier2dpad(data, zero_pad=True): """Compute the 2D Fourier transform with zero padding Parameters ---------- data: 2d fload ndarray real-valued image data zero_pad: bool perform zero-padding to next order of 2 """ if zero_pad: # zero padding size is next order ...
def get_field(hologram, sideband=+1, filter_name="disk", filter_size=1 / 3, subtract_mean=True, zero_pad=True, copy=True): """Compute the complex field from a hologram using Fourier analysis Parameters ---------- hologram: real-valued 2d ndarray hologram data sideband: +1, -1,...
def copyh5(inh5, outh5): """Recursively copy all hdf5 data from one group to another Data from links is copied. Parameters ---------- inh5: str, h5py.File, or h5py.Group The input hdf5 data. This can be either a file name or an hdf5 object. outh5: str, h5py.File, h5py.Group, or...
def _conv_which_data(which_data): """Convert which data to string or tuple This function improves user convenience, as `which_data` may be of several types (str, ,str with spaces and commas, list, tuple) which is internally handled by this method. """ if isinstan...
def _get_amp_pha(self, data, which_data): """Convert input data to phase and amplitude Parameters ---------- data: 2d ndarray (float or complex) or list The experimental data (see `which_data`) which_data: str String or comma-separated list of strings ind...
def info(self): """list of tuples with QPImage meta data""" info = [] # meta data meta = self.meta for key in meta: info.append((key, self.meta[key])) # background correction for imdat in [self._amp, self._pha]: info += imdat.info r...
def clear_bg(self, which_data=("amplitude", "phase"), keys="fit"): """Clear background correction Parameters ---------- which_data: str or list of str From which type of data to remove the background information. The list contains either "amplitude", ...
def compute_bg(self, which_data="phase", fit_offset="mean", fit_profile="tilt", border_m=0, border_perc=0, border_px=0, from_mask=None, ret_mask=False): """Compute background correction Parameters ---------- which_data: str or lis...
def copy(self, h5file=None): """Create a copy of the current instance This is done by recursively copying the underlying hdf5 data. Parameters ---------- h5file: str, h5py.File, h5py.Group, or None see `QPImage.__init__` """ h5 = copyh5(self.h5, h5fi...
def refocus(self, distance, method="helmholtz", h5file=None, h5mode="a"): """Compute a numerically refocused QPImage Parameters ---------- distance: float Focusing distance [m] method: str Refocusing method, one of ["helmholtz","fresnel"] h5file: ...
def set_bg_data(self, bg_data, which_data=None): """Set background amplitude and phase data Parameters ---------- bg_data: 2d ndarray (float or complex), list, QPImage, or `None` The background data (must be same type as `data`). If set to `None`, the background ...
def add_qpimage(self, qpi, identifier=None, bg_from_idx=None): """Add a QPImage instance to the QPSeries Parameters ---------- qpi: qpimage.QPImage The QPImage that is added to the series identifier: str Identifier key for `qpi` bg_from_idx: int o...
def get_qpimage(self, index): """Return a single QPImage of the series Parameters ---------- index: int or str Index or identifier of the QPImage Notes ----- Instead of ``qps.get_qpimage(index)``, it is possible to use the short-hand ``qps[in...
def main() -> int: """" Main routine """ parser = argparse.ArgumentParser() parser.add_argument( "--overwrite", help="Overwrites the unformatted source files with the well-formatted code in place. " "If not set, an exception is raised if any of the files do not conform to the...
def _collapse_invariants(bases: List[type], namespace: MutableMapping[str, Any]) -> None: """Collect invariants from the bases and merge them with the invariants in the namespace.""" invariants = [] # type: List[Contract] # Add invariants of the bases for base in bases: if hasattr(base, "__inv...
def _collapse_preconditions(base_preconditions: List[List[Contract]], bases_have_func: bool, preconditions: List[List[Contract]], func: Callable[..., Any]) -> List[List[Contract]]: """ Collapse function preconditions with the preconditions collected from the base classes. :param...
def _collapse_snapshots(base_snapshots: List[Snapshot], snapshots: List[Snapshot]) -> List[Snapshot]: """ Collapse snapshots of pre-invocation values with the snapshots collected from the base classes. :param base_snapshots: snapshots collected from the base classes :param snapshots: snapshots of the f...
def _collapse_postconditions(base_postconditions: List[Contract], postconditions: List[Contract]) -> List[Contract]: """ Collapse function postconditions with the postconditions collected from the base classes. :param base_postconditions: postconditions collected from the base classes :param postcondit...
def _decorate_namespace_function(bases: List[type], namespace: MutableMapping[str, Any], key: str) -> None: """Collect preconditions and postconditions from the bases and decorate the function at the ``key``.""" # pylint: disable=too-many-branches # pylint: disable=too-many-locals value = namespace[key...
def _decorate_namespace_property(bases: List[type], namespace: MutableMapping[str, Any], key: str) -> None: """Collect contracts for all getters/setters/deleters corresponding to ``key`` and decorate them.""" # pylint: disable=too-many-locals # pylint: disable=too-many-branches # pylint: disable=too-man...
def _dbc_decorate_namespace(bases: List[type], namespace: MutableMapping[str, Any]) -> None: """ Collect invariants, preconditions and postconditions from the bases and decorate all the methods. Instance methods are simply replaced with the decorated function/ Properties, class methods and static methods a...
def _representable(value: Any) -> bool: """ Check whether we want to represent the value in the error message on contract breach. We do not want to represent classes, methods, modules and functions. :param value: value related to an AST node :return: True if we want to represent it in the violatio...
def inspect_decorator(lines: List[str], lineno: int, filename: str) -> DecoratorInspection: """ Parse the file in which the decorator is called and figure out the corresponding call AST node. :param lines: lines of the source file corresponding to the decorator call :param lineno: line index (starting ...
def find_lambda_condition(decorator_inspection: DecoratorInspection) -> Optional[ConditionLambdaInspection]: """ Inspect the decorator and extract the condition as lambda. If the condition is not given as a lambda function, return None. """ call_node = decorator_inspection.node lambda_node = N...
def repr_values(condition: Callable[..., bool], lambda_inspection: Optional[ConditionLambdaInspection], condition_kwargs: Mapping[str, Any], a_repr: reprlib.Repr) -> List[str]: # pylint: disable=too-many-locals """ Represent function arguments and frame values in the error message on contrac...
def generate_message(contract: Contract, condition_kwargs: Mapping[str, Any]) -> str: """Generate the message upon contract violation.""" # pylint: disable=protected-access parts = [] # type: List[str] if contract.location is not None: parts.append("{}:\n".format(contract.location)) if co...
def visit_Name(self, node: ast.Name) -> None: """ Resolve the name from the variable look-up and the built-ins. Due to possible branching (e.g., If-expressions), some nodes might lack the recomputed values. These nodes are ignored. """ if node in self._recomputed_values:...
def visit_Attribute(self, node: ast.Attribute) -> None: """Represent the attribute by dumping its source code.""" if node in self._recomputed_values: value = self._recomputed_values[node] if _representable(value=value): text = self._atok.get_text(node) ...
def visit_Call(self, node: ast.Call) -> None: """Represent the call by dumping its source code.""" if node in self._recomputed_values: value = self._recomputed_values[node] text = self._atok.get_text(node) self.reprs[text] = value self.generic_visit(node=nod...
def visit_ListComp(self, node: ast.ListComp) -> None: """Represent the list comprehension by dumping its source code.""" if node in self._recomputed_values: value = self._recomputed_values[node] text = self._atok.get_text(node) self.reprs[text] = value self....
def visit_DictComp(self, node: ast.DictComp) -> None: """Represent the dictionary comprehension by dumping its source code.""" if node in self._recomputed_values: value = self._recomputed_values[node] text = self._atok.get_text(node) self.reprs[text] = value ...
def _walk_decorator_stack(func: CallableT) -> Iterable['CallableT']: """ Iterate through the stack of decorated functions until the original function. Assume that all decorators used functools.update_wrapper. """ while hasattr(func, "__wrapped__"): yield func func = getattr(func, "...
def find_checker(func: CallableT) -> Optional[CallableT]: """Iterate through the decorator stack till we find the contract checker.""" contract_checker = None # type: Optional[CallableT] for a_wrapper in _walk_decorator_stack(func): if hasattr(a_wrapper, "__preconditions__") or hasattr(a_wrapper, "...
def _kwargs_from_call(param_names: List[str], kwdefaults: Dict[str, Any], args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> MutableMapping[str, Any]: """ Inspect the input values received at the wrapper for the actual function call. :param param_names: parameter (*i.e.* argument) name...
def _assert_precondition(contract: Contract, resolved_kwargs: Mapping[str, Any]) -> None: """ Assert that the contract holds as a precondition. :param contract: contract to be verified :param resolved_kwargs: resolved keyword arguments (including the default values) :return: """ # Check tha...
def _assert_invariant(contract: Contract, instance: Any) -> None: """Assert that the contract holds as a class invariant given the instance of the class.""" if 'self' in contract.condition_arg_set: check = contract.condition(self=instance) else: check = contract.condition() if not check...