text
stringlengths
81
112k
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() def read_ttl(path): ''' Helper function to read Document in TTL-TXT format (i.e. ${docname}_*.txt) E.g. Document.read_ttl('~/dat...
Read tagged doc from mutliple files (sents, tokens, concepts, links, tags) 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 No...
Format the text for output adding ASCII frame around the text. Args: text (str): Text that needs to be formatted. Returns: str: Formatted string. def format_page(text): """Format the text for output adding ASCII frame around the text. Args: text (str): Text that nee...
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 | +-------------+--------+ Args: te...
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 print_page(text): """Format th...
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. def wrap_text(text, width=80): """Wrap text lines to ...
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 characters per line. indent (int): Indentation of the first lin...
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: str: Centered text. def center_text(te...
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 perform ("attributes" and/or "background") Raises ------ Int...
Check QPimage attributes Parameters ---------- qpi: qpimage.core.QPImage Raises ------ IntegrityCheckError if the check fails def check_attributes(qpi): """Check QPimage attributes Parameters ---------- qpi: qpimage.core.QPImage Raises ------ IntegrityChe...
Check QPimage background data Parameters ---------- qpi: qpimage.core.QPImage Raises ------ IntegrityCheckError if the check fails def check_background(qpi): """Check QPimage background data Parameters ---------- qpi: qpimage.core.QPImage Raises ------ In...
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. Parameters ---------- group: h5py.Group HDF5 group to ...
list of background correction parameters 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_d...
Remove the background image data Parameters ---------- key: str One of :const:`VALID_BG_KEYS` def del_bg(self, key): """Remove the background image data Parameters ---------- key: str One of :const:`VALID_BG_KEYS` """ if ...
Estimate image background Parameters ---------- fit_profile: str The type of background profile to fit: - "offset": offset only - "poly2o": 2D 2nd order polynomial with mixed terms - "tilt": 2D linear tilt with offset (default) fit_offset...
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 correction (see :const:`VALID_BG_KEYS`). If set ...
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 created). If set to `None`, the data will be r...
Combine several background amplitude images 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
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. def git_tags() -> str: """ Calls ``git tag -l --sort=-v:refname`` (sorts output) and returns the output as a UTF-8 enco...
: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. 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,...
:git_tags: chronos.helpers.git_tags() function output. Returns the latest Git tag ending with a SemVer as a string. 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. """ semve...
: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. def git_commits_since_last_tag(last_tag: str) -> dict: """ :last_tag: The Git tag that should serve as t...
:commit_log: chronos.helpers.git_commits_since_last_tag() output. Parse Git log and return either 'maj', 'min', or 'pat'. 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'. ""...
Alternate constructor that accepts a string SemVer. def from_str(cls, version_str: str): """ Alternate constructor that accepts a string SemVer. """ o = cls() o.version = version_str return o
param major Major version number property. Must be a non-negative integer. 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
param minor Minor version number property. Must be a non-negative integer. 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
param patch Patch version number property. Must be a non-negative integer. 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
Version version number property. Must be a string consisting of three non-negative integers delimited by periods (eg. '1.0.1'). 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'). ...
param version Version version number property. Must be a string consisting of three non-negative integers delimited by periods (eg. '1.0.1'). def version(self, version_str: str) -> None: """ param version Version version number property. Must be a string consisting of three ...
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 background profile to fit: - "offset": offset only - "poly2o": 2D 2nd order polynomial with mixed terms ...
Fit a gaussian model to `data` and return its center 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.histog...
Compute Mode using a histogram with `sqrt(data.size)` bins 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 = ab...
Fit a 2D tilt to `data[mask]` 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, m...
Fit a 2D 2nd order polynomial to `data[mask]` 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) ...
lmfit 2nd order polynomial model 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) ...
lmfit 2nd order polynomial residuals 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()
lmfit tilt model 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.resh...
lmfit tilt residuals def tilt_residual(params, data, mask): """lmfit tilt residuals""" bg = tilt_model(params, shape=data.shape) res = (data - bg)[mask] return res.flatten()
:cmd_args: An optional list of command line arguments. Main function of chronos CLI tool. 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 ut...
:args: An argparse.Namespace object. This is the function called when the 'infer' sub-command is passed as an argument to the CLI. 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 arg...
: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'). def bump(args: argparse.Namespace) -> None: """ :args: An argparse.Namespace object. This function is bound to the 'bump' s...
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 hologram image which: +1 or -1 which sideband ...
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 def fourier2dpad(data, zero_pad=True): """Compute the 2D Fourier transform with zero padding Parameters...
Compute the complex field from a hologram using Fourier analysis Parameters ---------- hologram: real-valued 2d ndarray hologram data sideband: +1, -1, or tuple of (float, float) specifies the location of the sideband: - +1: sideband in the upper half in Fourier space, ...
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 None The output hdf5 da...
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. def _conv_which_data(which_data): """Convert which data to string o...
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 indicating the order and type of input data....
list of tuples with QPImage meta data 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]: ...
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", "phase", or both. keys: str or list of str Which type of b...
Compute 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", "phase", or both. fit_profile: str The type of backgroun...
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__` def copy(self, h5file=None): """Create a copy of the current instance ...
Compute a numerically refocused QPImage Parameters ---------- distance: float Focusing distance [m] method: str Refocusing method, one of ["helmholtz","fresnel"] h5file: str, h5py.Group, h5py.File, or None A path to an hdf5 data file where the...
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 data is reset. which_data: str String or...
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 or None Use the background data from the data stored in this in...
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[index]``. def get_qpimage(self, index): ...
Main routine 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 ...
Collect invariants from the bases and merge them with the invariants in the namespace. 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] ...
Collapse function preconditions with the preconditions collected from the base classes. :param base_preconditions: preconditions collected from the base classes (grouped by base class) :param bases_have_func: True if one of the base classes has the function :param preconditions: preconditions of the functi...
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 function (before the collapse) :return: collapsed sequence of snapshots def _collapse_snapshots(base_snapshots...
Collapse function postconditions with the postconditions collected from the base classes. :param base_postconditions: postconditions collected from the base classes :param postconditions: postconditions of the function (before the collapse) :return: collapsed sequence of postconditions def _collapse_postc...
Collect preconditions and postconditions from the bases and decorate the function at the ``key``. 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``.""" #...
Collect contracts for all getters/setters/deleters corresponding to ``key`` and decorate them. 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.""" # pylin...
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 are overridden with new instances of ``property``, ``classmethod`` and ``staticmethod``, respectively....
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 violation error def _representable(value: Any) -> bool: ...
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 with 0) of one of the lines in the decorator call :param filename: name of the file where decorator ...
Inspect the decorator and extract the condition as lambda. If the condition is not given as a lambda function, return None. def find_lambda_condition(decorator_inspection: DecoratorInspection) -> Optional[ConditionLambdaInspection]: """ Inspect the decorator and extract the condition as lambda. If th...
Represent function arguments and frame values in the error message on contract breach. :param condition: condition function of the contract :param lambda_inspection: inspected lambda AST node corresponding to the condition function (None if the condition was not given as a lambda function) ...
Generate the message upon contract violation. 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.appen...
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. def visit_Name(self, node: ast.Name) -> None: """ Resolve the name from the variable look-up and the bui...
Represent the attribute by dumping its source code. 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): ...
Represent the call by dumping its source code. 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[te...
Represent the list comprehension by dumping its source code. 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_t...
Represent the dictionary comprehension by dumping its source code. 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...
Iterate through the stack of decorated functions until the original function. Assume that all decorators used functools.update_wrapper. def _walk_decorator_stack(func: CallableT) -> Iterable['CallableT']: """ Iterate through the stack of decorated functions until the original function. Assume that al...
Iterate through the decorator stack till we find the contract checker. 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): ...
Inspect the input values received at the wrapper for the actual function call. :param param_names: parameter (*i.e.* argument) names of the original (decorated) function :param kwdefaults: default argument values of the original function :param args: arguments supplied to the call :param kwargs: keywor...
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: def _assert_precondition(contract: Contract, resolved_kwargs: Mapping[str, Any]) -> None: """ Assert that the contra...
Assert that the contract holds as a class invariant given the instance of the class. 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.con...
Capture the snapshot from the keyword arguments resolved before the function call (including the default values). :param a_snapshot: snapshot to be captured :param resolved_kwargs: resolved keyword arguments (including the default values) :return: captured value def _capture_snapshot(a_snapshot: Snapshot,...
Decorate the function with a checker that verifies the preconditions and postconditions. def decorate_with_checker(func: CallableT) -> CallableT: """Decorate the function with a checker that verifies the preconditions and postconditions.""" assert not hasattr(func, "__preconditions__"), \ "Expected fun...
Find the instance of ``self`` in the arguments. def _find_self(param_names: List[str], args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> Any: """Find the instance of ``self`` in the arguments.""" instance_i = param_names.index("self") if instance_i < len(args): instance = args[instance_i] else:...
Decorate the function ``func`` of the class ``cls`` with invariant checks. If the function has been already decorated with invariant checks, the function returns immediately. :param func: function to be wrapped :param is_init: True if the ``func`` is __init__ :return: function wrapped with invariant c...
Check if the function has been already decorated with an invariant check by going through its decorator stack. def _already_decorated_with_invariants(func: CallableT) -> bool: """Check if the function has been already decorated with an invariant check by going through its decorator stack.""" already_decorated ...
Decorate each of the class functions with invariant checks if not already decorated. def add_invariant_checks(cls: type) -> None: """Decorate each of the class functions with invariant checks if not already decorated.""" # Candidates for the decoration as list of (name, dir() value) init_name_func = None ...
Execute the main routine. def main() -> None: """"Execute the main routine.""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--module", help="name of the module to import", choices=[ "functions_100_with_no_contract", ...
Execute the main routine. def main() -> None: """"Execute the main routine.""" modules = [ "functions_100_with_no_contract", "functions_100_with_1_contract", "functions_100_with_5_contracts", "functions_100_with_10_contracts", "functions_100_with_1_disabled_contract", ...
Execute the main routine. def main() -> None: """"Execute the main routine.""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--outdir", help="output directory", default=os.path.dirname(__file__)) args = parser.parse_args() outdir = pathlib.Path(args.outdir) if not ...
Recompute the value as the number at the node. def visit_Num(self, node: ast.Num) -> Union[int, float]: """Recompute the value as the number at the node.""" result = node.n self.recomputed_values[node] = result return result
Recompute the value as the string at the node. def visit_Str(self, node: ast.Str) -> str: """Recompute the value as the string at the node.""" result = node.s self.recomputed_values[node] = result return result
Recompute the value as the bytes at the node. def visit_Bytes(self, node: ast.Bytes) -> bytes: """Recompute the value as the bytes at the node.""" result = node.s self.recomputed_values[node] = result return node.s
Visit the elements and assemble the results into a list. def visit_List(self, node: ast.List) -> List[Any]: """Visit the elements and assemble the results into a list.""" if isinstance(node.ctx, ast.Store): raise NotImplementedError("Can not compute the value of a Store on a list") ...
Visit the elements and assemble the results into a tuple. def visit_Tuple(self, node: ast.Tuple) -> Tuple[Any, ...]: """Visit the elements and assemble the results into a tuple.""" if isinstance(node.ctx, ast.Store): raise NotImplementedError("Can not compute the value of a Store on a tuple...
Visit the elements and assemble the results into a set. def visit_Set(self, node: ast.Set) -> Set[Any]: """Visit the elements and assemble the results into a set.""" result = set(self.visit(node=elt) for elt in node.elts) self.recomputed_values[node] = result return result
Visit keys and values and assemble a dictionary with the results. def visit_Dict(self, node: ast.Dict) -> Dict[Any, Any]: """Visit keys and values and assemble a dictionary with the results.""" recomputed_dict = dict() # type: Dict[Any, Any] for key, val in zip(node.keys, node.values): ...
Forward the node value as a result. def visit_NameConstant(self, node: ast.NameConstant) -> Any: """Forward the node value as a result.""" self.recomputed_values[node] = node.value return node.value
Load the variable by looking it up in the variable look-up and in the built-ins. def visit_Name(self, node: ast.Name) -> Any: """Load the variable by looking it up in the variable look-up and in the built-ins.""" if not isinstance(node.ctx, ast.Load): raise NotImplementedError("Can only com...
Visit the node's ``value``. def visit_Expr(self, node: ast.Expr) -> Any: """Visit the node's ``value``.""" result = self.visit(node=node.value) self.recomputed_values[node] = result return result
Visit the node operand and apply the operation on the result. def visit_UnaryOp(self, node: ast.UnaryOp) -> Any: """Visit the node operand and apply the operation on the result.""" if isinstance(node.op, ast.UAdd): result = +self.visit(node=node.operand) elif isinstance(node.op, ast...
Recursively visit the left and right operand, respectively, and apply the operation on the results. def visit_BinOp(self, node: ast.BinOp) -> Any: """Recursively visit the left and right operand, respectively, and apply the operation on the results.""" # pylint: disable=too-many-branches left =...
Recursively visit the operands and apply the operation on them. def visit_BoolOp(self, node: ast.BoolOp) -> Any: """Recursively visit the operands and apply the operation on them.""" values = [self.visit(value_node) for value_node in node.values] if isinstance(node.op, ast.And): re...