sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
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...
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()
entailment
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)
Helper function to write doc to TTL-TXT format
entailment
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
Create a tokens-concepts map
entailment
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)
Return a generator of tokens with more than one sense.
entailment
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 ''
Get surface string that is associated with a tag object
entailment
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)
Create a sentence-level tag
entailment
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
Get the first tag of a particular type
entailment
def get_tags(self, tagtype): ''' Get all tags of a type ''' return [t for t in self.__tags if t.tagtype == tagtype]
Get all tags of a type
entailment
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
Add a token object into this sentence
entailment
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 =...
Create a new concept object and add it to concept list tokens can be a list of Token objects or token indices
entailment
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...
Add a concept to current concept list
entailment
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]
Get concept by concept ID
entailment
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: ...
Import a list of string as tokens
entailment
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
Build a map from tagtype to list of tags
entailment
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...
Get the first tag with a type in this token
entailment
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]
Find all token-level tags with the specified tagtype
entailment
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...
Create a new tag on this token
entailment
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 ...
If sent_id exists, remove and return the associated sentence object else return default. If no default is provided, KeyError will be raised.
entailment
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...
Add a ttl.Sentence object to this document
entailment
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))
Create a new sentence and add it to this Document
entailment
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...
If sent_id exists, remove and return the associated sentence object else return default. If no default is provided, KeyError will be raised.
entailment
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
Read tagged doc from mutliple files (sents, tokens, concepts, links, tags)
entailment
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...
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()
entailment
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) ...
Read tagged doc from mutliple files (sents, tokens, concepts, links, tags)
entailment
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...
Format the text for output adding ASCII frame around the text. Args: text (str): Text that needs to be formatted. Returns: str: Formatted string.
entailment
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 | +-------------+--------+...
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...
entailment
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. """ ...
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.
entailment
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 =...
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.
entailment
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...
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...
entailment
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: ...
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.
entailment
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...
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...
entailment
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)...
Check QPimage attributes Parameters ---------- qpi: qpimage.core.QPImage Raises ------ IntegrityCheckError if the check fails
entailment
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...
Check QPimage background data Parameters ---------- qpi: qpimage.core.QPImage Raises ------ IntegrityCheckError if the check fails
entailment
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...
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 ...
entailment
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 ...
list of background correction parameters
entailment
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"]: ...
Remove the background image data Parameters ---------- key: str One of :const:`VALID_BG_KEYS`
entailment
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 ...
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...
entailment
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...
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 ...
entailment
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...
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...
entailment
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
Combine several background amplitude images
entailment
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...
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.
entailment
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:...
: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.
entailment
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(...
:git_tags: chronos.helpers.git_tags() function output. Returns the latest Git tag ending with a SemVer as a string.
entailment
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', ...
: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.
entailment
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'], ...
:commit_log: chronos.helpers.git_commits_since_last_tag() output. Parse Git log and return either 'maj', 'min', or 'pat'.
entailment
def from_str(cls, version_str: str): """ Alternate constructor that accepts a string SemVer. """ o = cls() o.version = version_str return o
Alternate constructor that accepts a string SemVer.
entailment
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 major Major version number property. Must be a non-negative integer.
entailment
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 minor Minor version number property. Must be a non-negative integer.
entailment
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
param patch Patch version number property. Must be a non-negative integer.
entailment
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...
Version version number property. Must be a string consisting of three non-negative integers delimited by periods (eg. '1.0.1').
entailment
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...
param version Version version number property. Must be a string consisting of three non-negative integers delimited by periods (eg. '1.0.1').
entailment
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...
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 ...
entailment
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 = ...
Fit a gaussian model to `data` and return its center
entailment
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 ...
Compute Mode using a histogram with `sqrt(data.size)` bins
entailment
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...
Fit a 2D tilt to `data[mask]`
entailment
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...
Fit a 2D 2nd order polynomial to `data[mask]`
entailment
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...
lmfit 2nd order polynomial model
entailment
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 2nd order polynomial residuals
entailment
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 =...
lmfit tilt model
entailment
def tilt_residual(params, data, mask): """lmfit tilt residuals""" bg = tilt_model(params, shape=data.shape) res = (data - bg)[mask] return res.flatten()
lmfit tilt residuals
entailment
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...
:cmd_args: An optional list of command line arguments. Main function of chronos CLI tool.
entailment
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,...
:args: An argparse.Namespace object. This is the function called when the 'infer' sub-command is passed as an argument to the CLI.
entailment
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...
: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').
entailment
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...
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 ...
entailment
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 ...
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
entailment
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,...
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, ...
entailment
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...
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...
entailment
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...
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.
entailment
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...
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....
entailment
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...
list of tuples with QPImage meta data
entailment
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", ...
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...
entailment
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...
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...
entailment
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...
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__`
entailment
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: ...
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...
entailment
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 ...
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...
entailment
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...
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...
entailment
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...
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]``.
entailment
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...
Main routine
entailment
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...
Collect invariants from the bases and merge them with the invariants in the namespace.
entailment
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...
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...
entailment
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...
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
entailment
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...
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
entailment
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...
Collect preconditions and postconditions from the bases and decorate the function at the ``key``.
entailment
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...
Collect contracts for all getters/setters/deleters corresponding to ``key`` and decorate them.
entailment
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...
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.
entailment
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...
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
entailment
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 ...
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 ...
entailment
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...
Inspect the decorator and extract the condition as lambda. If the condition is not given as a lambda function, return None.
entailment
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...
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) ...
entailment
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...
Generate the message upon contract violation.
entailment
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:...
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.
entailment
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) ...
Represent the attribute by dumping its source code.
entailment
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...
Represent the call by dumping its source code.
entailment
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....
Represent the list comprehension by dumping its source code.
entailment
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 ...
Represent the dictionary comprehension by dumping its source code.
entailment
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, "...
Iterate through the stack of decorated functions until the original function. Assume that all decorators used functools.update_wrapper.
entailment
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, "...
Iterate through the decorator stack till we find the contract checker.
entailment
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...
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...
entailment
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...
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:
entailment
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...
Assert that the contract holds as a class invariant given the instance of the class.
entailment