INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Run module tracing.
def run_trace( mname, fname, module_prefix, callable_names, no_print, module_exclude=None, callable_exclude=None, debug=False, ): """Run module tracing.""" # pylint: disable=R0913 module_exclude = [] if module_exclude is None else module_exclude callable_exclude = [] if callable_exclude is None else callable_exclude par = trace_pars(mname) start_time = datetime.datetime.now() with pexdoc.exdoc.ExDocCxt( exclude=par.exclude + module_exclude, pickle_fname=par.pickle_fname, in_callables_fname=par.in_callables_fname, out_callables_fname=par.out_callables_fname, _no_print=no_print, ) as exdoc_obj: fname = os.path.realpath( os.path.join( os.path.dirname(__file__), "..", "..", "tests", "test_{0}.py".format(fname), ) ) test_cmd = ( ["--color=yes"] + (["-s", "-vv"] if debug else ["-q", "-q", "-q"]) + ["--disable-warnings"] + ["-x"] + ([par.noption] if par.noption else []) + ["-m " + mname] + [fname] ) with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=PytestWarning) if pytest.main(test_cmd): raise RuntimeError("Tracing did not complete successfully") stop_time = datetime.datetime.now() if not no_print: print( "Auto-generation of exceptions documentation time: {0}".format( pmisc.elapsed_time_string(start_time, stop_time) ) ) for callable_name in callable_names: callable_name = module_prefix + callable_name print("\nCallable: {0}".format(callable_name)) print(exdoc_obj.get_sphinx_doc(callable_name, exclude=callable_exclude)) print("\n") return copy.copy(exdoc_obj)
Shorten URL with optional keyword and title.
def shorten(self, url, keyword=None, title=None): """Shorten URL with optional keyword and title. Parameters: url: URL to shorten. keyword: Optionally choose keyword for short URL, otherwise automatic. title: Optionally choose title, otherwise taken from web page. Returns: ShortenedURL: Shortened URL and associated data. Raises: ~yourls.exceptions.YOURLSKeywordExistsError: The passed keyword already exists. .. note:: This exception has a ``keyword`` attribute. ~yourls.exceptions.YOURLSURLExistsError: The URL has already been shortened. .. note:: This exception has a ``url`` attribute, which is an instance of :py:class:`ShortenedURL` for the existing short URL. ~yourls.exceptions.YOURLSNoURLError: URL missing. ~yourls.exceptions.YOURLSNoLoopError: Cannot shorten a shortened URL. ~yourls.exceptions.YOURLSAPIError: Unhandled API error. ~yourls.exceptions.YOURLSHTTPError: HTTP error with response from YOURLS API. requests.exceptions.HTTPError: Generic HTTP error. """ data = dict(action='shorturl', url=url, keyword=keyword, title=title) jsondata = self._api_request(params=data) url = _json_to_shortened_url(jsondata['url'], jsondata['shorturl']) return url
Expand short URL or keyword to long URL.
def expand(self, short): """Expand short URL or keyword to long URL. Parameters: short: Short URL (``http://example.com/abc``) or keyword (abc). :return: Expanded/long URL, e.g. ``https://www.youtube.com/watch?v=dQw4w9WgXcQ`` Raises: ~yourls.exceptions.YOURLSHTTPError: HTTP error with response from YOURLS API. requests.exceptions.HTTPError: Generic HTTP error. """ data = dict(action='expand', shorturl=short) jsondata = self._api_request(params=data) return jsondata['longurl']
Get stats for short URL or keyword.
def url_stats(self, short): """Get stats for short URL or keyword. Parameters: short: Short URL (http://example.com/abc) or keyword (abc). Returns: ShortenedURL: Shortened URL and associated data. Raises: ~yourls.exceptions.YOURLSHTTPError: HTTP error with response from YOURLS API. requests.exceptions.HTTPError: Generic HTTP error. """ data = dict(action='url-stats', shorturl=short) jsondata = self._api_request(params=data) return _json_to_shortened_url(jsondata['link'])
Get stats about links.
def stats(self, filter, limit, start=None): """Get stats about links. Parameters: filter: 'top', 'bottom', 'rand', or 'last'. limit: Number of links to return from filter. start: Optional start number. Returns: Tuple containing list of ShortenedURLs and DBStats. Example: .. code-block:: python links, stats = yourls.stats(filter='top', limit=10) Raises: ValueError: Incorrect value for filter parameter. requests.exceptions.HTTPError: Generic HTTP Error """ # Normalise random to rand, even though it's accepted by API. if filter == 'random': filter = 'rand' valid_filters = ('top', 'bottom', 'rand', 'last') if filter not in valid_filters: msg = 'filter must be one of {}'.format(', '.join(valid_filters)) raise ValueError(msg) data = dict(action='stats', filter=filter, limit=limit, start=start) jsondata = self._api_request(params=data) stats = DBStats(total_clicks=int(jsondata['stats']['total_clicks']), total_links=int(jsondata['stats']['total_links'])) links = [] if 'links' in jsondata: for i in range(1, limit + 1): key = 'link_{}'.format(i) links.append(_json_to_shortened_url(jsondata['links'][key])) return links, stats
Get database statistics.
def db_stats(self): """Get database statistics. Returns: DBStats: Total clicks and links statistics. Raises: requests.exceptions.HTTPError: Generic HTTP Error """ data = dict(action='db-stats') jsondata = self._api_request(params=data) stats = DBStats(total_clicks=int(jsondata['db-stats']['total_clicks']), total_links=int(jsondata['db-stats']['total_links'])) return stats
r Echo terminal output.
def ste(command, nindent, mdir, fpointer): r""" Echo terminal output. Print STDOUT resulting from a given Bash shell command (relative to the package :code:`pypkg` directory) formatted in reStructuredText :param command: Bash shell command, relative to :bash:`${PMISC_DIR}/pypkg` :type command: string :param nindent: Indentation level :type nindent: integer :param mdir: Module directory :type mdir: string :param fpointer: Output function pointer. Normally is :code:`cog.out` but :code:`print` or other functions can be used for debugging :type fpointer: function object For example:: .. This is a reStructuredText file snippet .. [[[cog .. import os, sys .. from docs.support.term_echo import term_echo .. file_name = sys.modules['docs.support.term_echo'].__file__ .. mdir = os.path.realpath( .. os.path.dirname( .. os.path.dirname(os.path.dirname(file_name)) .. ) .. ) .. [[[cog ste('build_docs.py -h', 0, mdir, cog.out) ]]] .. code-block:: bash $ ${PMISC_DIR}/pypkg/build_docs.py -h usage: build_docs.py [-h] [-d DIRECTORY] [-n NUM_CPUS] ... .. ]]] """ term_echo( "${{PMISC_DIR}}{sep}pypkg{sep}{cmd}".format(sep=os.path.sep, cmd=command), nindent, {"PMISC_DIR": mdir}, fpointer, )
Print STDOUT resulting from a Bash shell command formatted in reStructuredText.
def term_echo(command, nindent=0, env=None, fpointer=None, cols=60): """ Print STDOUT resulting from a Bash shell command formatted in reStructuredText. :param command: Bash shell command :type command: string :param nindent: Indentation level :type nindent: integer :param env: Environment variable replacement dictionary. The Bash command is pre-processed and any environment variable represented in the full notation (:bash:`${...}`) is replaced. The dictionary key is the environment variable name and the dictionary value is the replacement value. For example, if **command** is :code:`'${PYTHON_CMD} -m "x=5"'` and **env** is :code:`{'PYTHON_CMD':'python3'}` the actual command issued is :code:`'python3 -m "x=5"'` :type env: dictionary :param fpointer: Output function pointer. Normally is :code:`cog.out` but :code:`print` or other functions can be used for debugging :type fpointer: function object :param cols: Number of columns of output :type cols: integer """ # pylint: disable=R0204 # Set argparse width so that output does not need horizontal scroll # bar in narrow windows or displays os.environ["COLUMNS"] = str(cols) command_int = command if env: for var, repl in env.items(): command_int = command_int.replace("${" + var + "}", repl) tokens = command_int.split(" ") # Add Python interpreter executable for Python scripts on Windows since # the shebang does not work if (platform.system().lower() == "windows") and (tokens[0].endswith(".py")): tokens = [sys.executable] + tokens proc = subprocess.Popen(tokens, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout = proc.communicate()[0] if sys.hexversion >= 0x03000000: stdout = stdout.decode("utf-8") stdout = stdout.split("\n") indent = nindent * " " fpointer("\n", dedent=False) fpointer("{0}.. code-block:: bash\n".format(indent), dedent=False) fpointer("\n", dedent=False) fpointer("{0} $ {1}\n".format(indent, command), dedent=False) for line in stdout: if line.strip(): fpointer(indent + " " + line.replace("\t", " ") + "\n", dedent=False) else: fpointer("\n", dedent=False) fpointer("\n", dedent=False)
Small log helper
def log(self, msg, level=2): """ Small log helper """ if self.verbosity >= level: self.stdout.write(msg)
alternative to reify and property decorators. caches the value when it s generated. It cashes it as instance. _name_of_the_property.
def cached(method) -> property: """alternative to reify and property decorators. caches the value when it's generated. It cashes it as instance._name_of_the_property. """ name = "_" + method.__name__ @property def wrapper(self): try: return getattr(self, name) except AttributeError: val = method(self) setattr(self, name, val) return val return wrapper
break an iterable into chunks and yield those chunks as lists until there s nothing left to yeild.
def chunkiter(iterable, chunksize): """break an iterable into chunks and yield those chunks as lists until there's nothing left to yeild. """ iterator = iter(iterable) for chunk in iter(lambda: list(itertools.islice(iterator, chunksize)), []): yield chunk
take a function that taks an iterable as the first argument. return a wrapper that will break an iterable into chunks using chunkiter and run each chunk in function yielding the value of each function call as an iterator.
def chunkprocess(func): """take a function that taks an iterable as the first argument. return a wrapper that will break an iterable into chunks using chunkiter and run each chunk in function, yielding the value of each function call as an iterator. """ @functools.wraps(func) def wrapper(iterable, chunksize, *args, **kwargs): for chunk in chunkiter(iterable, chunksize): yield func(chunk, *args, **kwargs) return wrapper
recursively flatten nested objects
def flatten(iterable, map2iter=None): """recursively flatten nested objects""" if map2iter and isinstance(iterable): iterable = map2iter(iterable) for item in iterable: if isinstance(item, str) or not isinstance(item, abc.Iterable): yield item else: yield from flatten(item, map2iter)
update one dictionary from another recursively. Only individual values will be overwritten -- not entire branches of nested dictionaries.
def deepupdate( mapping: abc.MutableMapping, other: abc.Mapping, listextend=False ): """update one dictionary from another recursively. Only individual values will be overwritten--not entire branches of nested dictionaries. """ def inner(other, previouskeys): """previouskeys is a tuple that stores all the names of keys we've recursed into so far so it can they can be looked up recursively on the pimary mapping when a value needs updateing. """ for key, value in other.items(): if isinstance(value, abc.Mapping): inner(value, (*previouskeys, key)) else: node = mapping for previouskey in previouskeys: node = node.setdefault(previouskey, {}) target = node.get(key) if ( listextend and isinstance(target, abc.MutableSequence) and isinstance(value, abc.Sequence) ): target.extend(value) else: node[key] = value inner(other, ())
add a handler for SIGINT that optionally prints a given message. For stopping scripts without having to see the stacktrace.
def quietinterrupt(msg=None): """add a handler for SIGINT that optionally prints a given message. For stopping scripts without having to see the stacktrace. """ def handler(): if msg: print(msg, file=sys.stderr) sys.exit(1) signal.signal(signal.SIGINT, handler)
stupidly print an iterable of iterables in TSV format
def printtsv(table, sep="\t", file=sys.stdout): """stupidly print an iterable of iterables in TSV format""" for record in table: print(*record, sep=sep, file=file)
Make a placeholder object that uses its own name for its repr
def mkdummy(name, **attrs): """Make a placeholder object that uses its own name for its repr""" return type( name, (), dict(__repr__=(lambda self: "<%s>" % name), **attrs) )()
pipe ( value f g h ) == h ( g ( f ( value )))
def pipe(value, *functions, funcs=None): """pipe(value, f, g, h) == h(g(f(value)))""" if funcs: functions = funcs for function in functions: value = function(value) return value
like pipe but curried:
def pipeline(*functions, funcs=None): """like pipe, but curried: pipline(f, g, h)(*args, **kwargs) == h(g(f(*args, **kwargs))) """ if funcs: functions = funcs head, *tail = functions return lambda *args, **kwargs: pipe(head(*args, **kwargs), funcs=tail)
returns the size of size as a tuple of:
def human_readable(self, decimal=False): """returns the size of size as a tuple of: (number, single-letter-unit) If the decimal flag is set to true, units 1000 is used as the divisor, rather than 1024. """ divisor = 1000 if decimal else 1024 number = int(self) unit = "" for unit in self.units: if number < divisor: break number /= divisor return number, unit.upper()
attempt to parse a size in bytes from a human - readable string.
def from_str(cls, human_readable_str, decimal=False, bits=False): """attempt to parse a size in bytes from a human-readable string.""" divisor = 1000 if decimal else 1024 num = [] c = "" for c in human_readable_str: if c not in cls.digits: break num.append(c) num = "".join(num) try: num = int(num) except ValueError: num = float(num) if bits: num /= 8 return cls(round(num * divisor ** cls.key[c.lower()]))
Command line interface for YOURLS.
def cli(ctx, apiurl, signature, username, password): """Command line interface for YOURLS. Configuration parameters can be passed as switches or stored in .yourls or ~/.yourls. If your YOURLS server requires authentication, please provide one of the following: \b • apiurl and signature • apiurl, username, and password Configuration file format: \b [yourls] apiurl = http://example.com/yourls-api.php signature = abcdefghij """ if apiurl is None: raise click.UsageError("apiurl missing. See 'yourls --help'") auth_params = dict(signature=signature, username=username, password=password) try: ctx.obj = YOURLSClient(apiurl=apiurl, **auth_params) except TypeError: raise click.UsageError("authentication paremeters overspecified. " "See 'yourls --help'")
Trace eng wave module exceptions.
def trace_module(no_print=True): """Trace eng wave module exceptions.""" mname = "wave_core" fname = "peng" module_prefix = "peng.{0}.Waveform.".format(mname) callable_names = ("__init__",) return docs.support.trace_support.run_trace( mname, fname, module_prefix, callable_names, no_print )
Define Sphinx requirements links.
def def_links(mobj): """Define Sphinx requirements links.""" fdict = json_load(os.path.join("data", "requirements.json")) sdeps = sorted(fdict.keys()) olines = [] for item in sdeps: olines.append( ".. _{name}: {url}\n".format( name=fdict[item]["name"], url=fdict[item]["url"] ) ) ret = [] for line in olines: wobj = textwrap.wrap(line, width=LINE_WIDTH, subsequent_indent=" ") ret.append("\n".join([item for item in wobj])) mobj.out("\n".join(ret))
Generate Python interpreter version entries for 2. x or 3. x series.
def make_common_entry(plist, pyver, suffix, req_ver): """Generate Python interpreter version entries for 2.x or 3.x series.""" prefix = "Python {pyver}.x{suffix}".format(pyver=pyver, suffix=suffix) plist.append("{prefix}{ver}".format(prefix=prefix, ver=ops_to_words(req_ver)))
Generate Python interpreter version entries.
def make_multi_entry(plist, pkg_pyvers, ver_dict): """Generate Python interpreter version entries.""" for pyver in pkg_pyvers: pver = pyver[2] + "." + pyver[3:] plist.append("Python {0}: {1}".format(pver, ops_to_words(ver_dict[pyver])))
Translate > = == < = to words.
def op_to_words(item): """Translate >=, ==, <= to words.""" sdicts = [ {"==": ""}, {">=": " or newer"}, {">": "newer than "}, {"<=": " or older"}, {"<": "older than "}, {"!=": "except "}, ] for sdict in sdicts: prefix = list(sdict.keys())[0] suffix = sdict[prefix] if item.startswith(prefix): if prefix == "==": return item[2:] if prefix == "!=": return suffix + item[2:] if prefix in [">", "<"]: return suffix + item[1:] return item[2:] + suffix raise RuntimeError("Inequality not supported")
Translate requirement specification to words.
def ops_to_words(item): """Translate requirement specification to words.""" unsupp_ops = ["~=", "==="] # Ordered for "pleasant" word specification supp_ops = [">=", ">", "==", "<=", "<", "!="] tokens = sorted(item.split(","), reverse=True) actual_tokens = [] for req in tokens: for op in unsupp_ops: if req.startswith(op): raise RuntimeError("Unsupported version specification: {0}".format(op)) for op in supp_ops: if req.startswith(op): actual_tokens.append(op) break else: raise RuntimeError("Illegal comparison operator: {0}".format(op)) if len(list(set(actual_tokens))) != len(actual_tokens): raise RuntimeError("Multiple comparison operators of the same type") if "!=" in actual_tokens: return ( " and ".join([op_to_words(token) for token in tokens[:-1]]) + " " + op_to_words(tokens[-1]) ) return " and ".join([op_to_words(token) for token in tokens])
Get requirements in reStructuredText format.
def proc_requirements(mobj): """Get requirements in reStructuredText format.""" pyvers = ["py{0}".format(item.replace(".", "")) for item in get_supported_interps()] py2vers = sorted([item for item in pyvers if item.startswith("py2")]) py3vers = sorted([item for item in pyvers if item.startswith("py3")]) fdict = json_load(os.path.join("data", "requirements.json")) olines = [""] sdict = dict([(item["name"], item) for item in fdict.values()]) for real_name in sorted(sdict.keys()): pkg_dict = sdict[real_name] if pkg_dict["cat"] == ["rtd"]: continue plist = [] if not pkg_dict["optional"] else ["optional"] # Convert instances that have a single version for all Python # interpreters into a full dictionary of Python interpreter and # package versions # so as to apply the same algorithm in all cases if isinstance(pkg_dict["ver"], str): pkg_dict["ver"] = dict([(pyver, pkg_dict["ver"]) for pyver in pyvers]) pkg_pyvers = sorted(pkg_dict["ver"].keys()) pkg_py2vers = sorted( [item for item in pkg_dict["ver"].keys() if item.startswith("py2")] ) req_vers = list(set(pkg_dict["ver"].values())) req_py2vers = list( set([pkg_dict["ver"][item] for item in py2vers if item in pkg_dict["ver"]]) ) req_py3vers = list( set([pkg_dict["ver"][item] for item in py3vers if item in pkg_dict["ver"]]) ) if (len(req_vers) == 1) and (pkg_pyvers == pyvers): plist.append(ops_to_words(req_vers[0])) elif ( (pkg_pyvers == pyvers) and (len(req_py2vers) == 1) and (len(req_py3vers) == 1) ): make_common_entry(plist, "2", ": ", req_py2vers[0]) make_common_entry(plist, "3", ": ", req_py3vers[0]) elif ( (pkg_pyvers == pyvers) and (len(req_py2vers) == len(py2vers)) and (len(req_py3vers) == 1) and (pkg_dict["ver"][pkg_py2vers[-1]] == req_py3vers[0]) ): py2dict = dict( [ (key, value) for key, value in pkg_dict["ver"].items() if key.startswith("py2") and (key != pkg_py2vers[-1]) ] ) make_multi_entry(plist, py2vers[:-1], py2dict) pver = pkg_py2vers[-1][2] + "." + pkg_py2vers[-1][3:] plist.append( "Python {pyver} or newer: {ver}".format( pyver=pver, ver=ops_to_words(req_py3vers[0]) ) ) elif ( (pkg_pyvers == pyvers) and (len(req_py2vers) == len(py2vers)) and (len(req_py3vers) == 1) ): py2dict = dict( [ (key, value) for key, value in pkg_dict["ver"].items() if key.startswith("py2") ] ) make_multi_entry(plist, py2vers, py2dict) make_common_entry(plist, "3", ": ", req_py3vers[0]) elif ( (pkg_pyvers == pyvers) and (len(req_py3vers) == len(py3vers)) and (len(req_py2vers) == 1) ): py3dict = dict( [ (key, value) for key, value in pkg_dict["ver"].items() if key.startswith("py3") ] ) make_common_entry(plist, "2", ": ", req_py2vers[0]) make_multi_entry(plist, py3vers, py3dict) elif (len(req_vers) == 1) and (pkg_pyvers == py2vers): make_common_entry(plist, "2", " only, ", req_vers[0]) elif (len(req_vers) == 1) and (pkg_pyvers == py3vers): make_common_entry(plist, "3", " only, ", req_vers[0]) else: make_multi_entry(plist, pkg_pyvers, pkg_dict["ver"]) olines.append( " * `{name}`_ ({par})".format( name=pkg_dict["name"], par=", ".join(plist) ) ) ret = [] for line in olines: wobj = textwrap.wrap(line, width=LINE_WIDTH, subsequent_indent=" ") ret.append("\n".join([item for item in wobj])) mobj.out("\n\n".join(ret) + "\n\n")
Generate version string from tuple ( almost entirely from coveragepy ).
def _make_version(major, minor, micro, level, serial): """Generate version string from tuple (almost entirely from coveragepy).""" level_dict = {"alpha": "a", "beta": "b", "candidate": "rc", "final": ""} if level not in level_dict: raise RuntimeError("Invalid release level") version = "{0:d}.{1:d}".format(major, minor) if micro: version += ".{0:d}".format(micro) if level != "final": version += "{0}{1:d}".format(level_dict[level], serial) return version
Chunk input noise data into valid Touchstone file rows.
def _chunk_noise(noise): """Chunk input noise data into valid Touchstone file rows.""" data = zip( noise["freq"], noise["nf"], np.abs(noise["rc"]), np.angle(noise["rc"]), noise["res"], ) for freq, nf, rcmag, rcangle, res in data: yield freq, nf, rcmag, rcangle, res
Chunk input data into valid Touchstone file rows.
def _chunk_pars(freq_vector, data_matrix, pformat): """Chunk input data into valid Touchstone file rows.""" pformat = pformat.upper() length = 4 for freq, data in zip(freq_vector, data_matrix): data = data.flatten() for index in range(0, data.size, length): fpoint = [freq] if not index else [None] cdata = data[index : index + length] if pformat == "MA": vector1 = np.abs(cdata) vector2 = np.rad2deg(np.angle(cdata)) elif pformat == "RI": vector1 = np.real(cdata) vector2 = np.imag(cdata) else: # elif pformat == 'DB': vector1 = 20.0 * np.log10(np.abs(cdata)) vector2 = np.rad2deg(np.angle(cdata)) sep_data = np.array([]) for item1, item2 in zip(vector1, vector2): sep_data = np.concatenate((sep_data, np.array([item1, item2]))) ret = np.concatenate((np.array(fpoint), sep_data)) yield ret
r Read a Touchstone <https:// ibis. org/ connector/ touchstone_spec11. pdf > _ file.
def read_touchstone(fname): r""" Read a `Touchstone <https://ibis.org/connector/touchstone_spec11.pdf>`_ file. According to the specification a data line can have at most values for four complex parameters (plus potentially the frequency point), however this function is able to process malformed files as long as they have the correct number of data points (:code:`points` x :code:`nports` x :code:`nports` where :code:`points` represents the number of frequency points and :code:`nports` represents the number of ports in the file). Per the Touchstone specification noise data is only supported for two-port files :param fname: Touchstone file name :type fname: `FileNameExists <https://pexdoc.readthedocs.io/en/stable/ ptypes.html#filenameexists>`_ :rtype: dictionary with the following structure: * **nports** (*integer*) -- number of ports * **opts** (:ref:`TouchstoneOptions`) -- File options * **data** (:ref:`TouchstoneData`) -- Parameter data * **noise** (:ref:`TouchstoneNoiseData`) -- Noise data, per the Touchstone specification only supported in 2-port files .. [[[cog cog.out(exobj.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. peng.touchstone.read_touchstone :raises: * OSError (File *[fname]* could not be found) * RuntimeError (Argument \`fname\` is not valid) * RuntimeError (File *[fname]* does not have a valid extension) * RuntimeError (File *[fname]* has no data) * RuntimeError (First non-comment line is not the option line) * RuntimeError (Frequency must increase) * RuntimeError (Illegal data in line *[lineno]*) * RuntimeError (Illegal option line) * RuntimeError (Malformed data) * RuntimeError (Malformed noise data) * RuntimeError (Noise frequency must increase) .. [[[end]]] .. note:: The returned parameter(s) are complex numbers in real and imaginary format regardless of the format used in the Touchstone file. Similarly, the returned frequency vector unit is Hertz regardless of the unit used in the Touchstone file """ # pylint: disable=R0912,R0915,W0702 # Exceptions definitions exnports = pexdoc.exh.addex( RuntimeError, "File *[fname]* does not have a valid extension" ) exnoopt = pexdoc.exh.addex( RuntimeError, "First non-comment line is not the option line" ) exopt = pexdoc.exh.addex(RuntimeError, "Illegal option line") exline = pexdoc.exh.addex(RuntimeError, "Illegal data in line *[lineno]*") exnodata = pexdoc.exh.addex(RuntimeError, "File *[fname]* has no data") exdata = pexdoc.exh.addex(RuntimeError, "Malformed data") exndata = pexdoc.exh.addex(RuntimeError, "Malformed noise data") exfreq = pexdoc.exh.addex(RuntimeError, "Frequency must increase") exnfreq = pexdoc.exh.addex(RuntimeError, "Noise frequency must increase") # Verify that file has correct extension format _, ext = os.path.splitext(fname) ext = ext.lower() nports_regexp = re.compile(r"\.s(\d+)p") match = nports_regexp.match(ext) exnports(not match, edata={"field": "fname", "value": fname}) nports = int(match.groups()[0]) opt_line = False units_dict = {"GHZ": "GHz", "MHZ": "MHz", "KHZ": "KHz", "HZ": "Hz"} scale_dict = {"GHZ": 1e9, "MHZ": 1e6, "KHZ": 1e3, "HZ": 1.0} units_opts = ["GHZ", "MHZ", "KHZ", "HZ"] type_opts = ["S", "Y", "Z", "H", "G"] format_opts = ["DB", "MA", "RI"] opts = dict(units=None, ptype=None, pformat=None, z0=None) data = [] with open(fname, "r") as fobj: for num, line in enumerate(fobj): line = line.strip().upper() # Comment line if line.startswith("!"): continue # Options line if (not opt_line) and (not line.startswith("#")): exnoopt(True) if not opt_line: # Each Touchstone data file must contain an option line # (additional option lines after the first one will be ignored) opt_line = True tokens = line[1:].split() # Remove initial hash if "R" in tokens: idx = tokens.index("R") add = 1 if len(tokens) > idx + 1: try: opts["z0"] = float(tokens[idx + 1]) add = 2 except: pass tokens = tokens[:idx] + tokens[idx + add :] matches = 0 for token in tokens: if (token in format_opts) and (not opts["pformat"]): matches += 1 opts["pformat"] = token elif (token in units_opts) and (not opts["units"]): matches += 1 opts["units"] = units_dict[token] elif (token in type_opts) and (not opts["ptype"]): matches += 1 opts["ptype"] = token exopt(matches != len(tokens)) if opt_line and line.startswith("#"): continue # Data lines try: if "!" in line: idx = line.index("!") line = line[:idx] tokens = [float(item) for item in line.split()] data.append(tokens) except: exline(True, edata={"field": "lineno", "value": num + 1}) data = np.concatenate(data) exnodata(not data.size, edata={"field": "fname", "value": fname}) # Set option defaults opts["units"] = opts["units"] or "GHz" opts["ptype"] = opts["ptype"] or "S" opts["pformat"] = opts["pformat"] or "MA" opts["z0"] = opts["z0"] or 50 # Format data data_dict = {} nums_per_freq = 1 + (2 * (nports ** 2)) fslice = slice(0, data.size, nums_per_freq) freq = data[fslice] ndiff = np.diff(freq) ndict = {} if (nports == 2) and ndiff.size and (min(ndiff) <= 0): # Extract noise data npoints = np.where(ndiff <= 0)[0][0] + 1 freq = freq[:npoints] ndata = data[9 * npoints :] nfpoints = int(ndata.size / 5.0) exndata(ndata.size % 5 != 0) data = data[: 9 * npoints] ndiff = 1 nfslice = slice(0, ndata.size, 5) nfreq = ndata[nfslice] ndiff = np.diff(nfreq) exnfreq(bool(ndiff.size and (min(ndiff) <= 0))) nfig_slice = slice(1, ndata.size, 5) rlmag_slice = slice(2, ndata.size, 5) rlphase_slice = slice(3, ndata.size, 5) res_slice = slice(4, ndata.size, 5) ndict["freq"] = scale_dict[opts["units"].upper()] * nfreq ndict["nf"] = ndata[nfig_slice] ndict["rc"] = ndata[rlmag_slice] * np.exp(1j * ndata[rlphase_slice]) ndict["res"] = ndata[res_slice] ndict["points"] = nfpoints exdata(data.size % nums_per_freq != 0) npoints = int(data.size / nums_per_freq) exfreq(bool(ndiff.size and (min(ndiff) <= 0))) data_dict["freq"] = scale_dict[opts["units"].upper()] * freq d1slice = slice(0, data.size, 2) d2slice = slice(1, data.size, 2) data = np.delete(data, fslice) # For format that has angle information, the angle is given in degrees if opts["pformat"] == "MA": data = data[d1slice] * np.exp(1j * np.deg2rad(data[d2slice])) elif opts["pformat"] == "RI": data = data[d1slice] + (1j * data[d2slice]) else: # if opts['pformat'] == 'DB': data = (10 ** (data[d1slice] / 20.0)) * np.exp(1j * np.deg2rad(data[d2slice])) if nports > 1: data_dict["pars"] = np.resize(data, (npoints, nports, nports)) else: data_dict["pars"] = copy.copy(data) del data data_dict["points"] = npoints if nports == 2: # The order of data for a two-port file is N11, N21, N12, N22 but for # m ports where m > 2, the order is N11, N12, N13, ..., N1m data_dict["pars"] = np.transpose(data_dict["pars"], (0, 2, 1)) return dict(nports=nports, opts=opts, data=data_dict, noise=ndict)
r Write a Touchstone _ file.
def write_touchstone(fname, options, data, noise=None, frac_length=10, exp_length=2): r""" Write a `Touchstone`_ file. Parameter data is first resized to an :code:`points` x :code:`nports` x :code:`nports` where :code:`points` represents the number of frequency points and :code:`nports` represents the number of ports in the file; then parameter data is written to file in scientific notation :param fname: Touchstone file name :type fname: `FileNameExists <https://pexdoc.readthedocs.io/en/stable/ ptypes.html#filenameexists>`_ :param options: Touchstone file options :type options: :ref:`TouchstoneOptions` :param data: Touchstone file parameter data :type data: :ref:`TouchstoneData` :param noise: Touchstone file parameter noise data (only supported in two-port files) :type noise: :ref:`TouchstoneNoiseData` :param frac_length: Number of digits to use in fractional part of data :type frac_length: non-negative integer :param exp_length: Number of digits to use in exponent :type exp_length: positive integer .. [[[cog cog.out(exobj.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. peng.touchstone.write_touchstone :raises: * RuntimeError (Argument \`data\` is not valid) * RuntimeError (Argument \`exp_length\` is not valid) * RuntimeError (Argument \`fname\` is not valid) * RuntimeError (Argument \`frac_length\` is not valid) * RuntimeError (Argument \`noise\` is not valid) * RuntimeError (Argument \`options\` is not valid) * RuntimeError (File *[fname]* does not have a valid extension) * RuntimeError (Malformed data) * RuntimeError (Noise data only supported in two-port files) .. [[[end]]] """ # pylint: disable=R0913 # Exceptions definitions exnports = pexdoc.exh.addex( RuntimeError, "File *[fname]* does not have a valid extension" ) exnoise = pexdoc.exh.addex( RuntimeError, "Noise data only supported in two-port files" ) expoints = pexdoc.exh.addex(RuntimeError, "Malformed data") # Data validation _, ext = os.path.splitext(fname) ext = ext.lower() nports_regexp = re.compile(r"\.s(\d+)p") match = nports_regexp.match(ext) exnports(not match, edata={"field": "fname", "value": fname}) nports = int(match.groups()[0]) exnoise(bool((nports != 2) and noise)) nums_per_freq = nports ** 2 expoints(data["points"] * nums_per_freq != data["pars"].size) # npoints = data["points"] par_data = np.resize(np.copy(data["pars"]), (npoints, nports, nports)) if nports == 2: par_data = np.transpose(par_data, (0, 2, 1)) units_dict = {"ghz": "GHz", "mhz": "MHz", "khz": "KHz", "hz": "Hz"} options["units"] = units_dict[options["units"].lower()] fspace = 2 + frac_length + (exp_length + 2) # Format data with open(fname, "w") as fobj: fobj.write( "# {units} {ptype} {pformat} R {z0}\n".format( units=options["units"], ptype=options["ptype"], pformat=options["pformat"], z0=options["z0"], ) ) for row in _chunk_pars(data["freq"], par_data, options["pformat"]): row_data = [ to_scientific_string(item, frac_length, exp_length, bool(num != 0)) if item is not None else fspace * " " for num, item in enumerate(row) ] fobj.write(" ".join(row_data) + "\n") if (nports == 2) and noise: fobj.write("! Noise data\n") for row in _chunk_noise(noise): row_data = [ to_scientific_string(item, frac_length, exp_length, bool(num != 0)) for num, item in enumerate(row) ] fobj.write(" ".join(row_data) + "\n")
Add independent variable vector bounds if they are not in vector.
def _bound_waveform(wave, indep_min, indep_max): """Add independent variable vector bounds if they are not in vector.""" indep_min, indep_max = _validate_min_max(wave, indep_min, indep_max) indep_vector = copy.copy(wave._indep_vector) if ( isinstance(indep_min, float) or isinstance(indep_max, float) ) and indep_vector.dtype.name.startswith("int"): indep_vector = indep_vector.astype(float) min_pos = np.searchsorted(indep_vector, indep_min) if not np.isclose(indep_min, indep_vector[min_pos], FP_RTOL, FP_ATOL): indep_vector = np.insert(indep_vector, min_pos, indep_min) max_pos = np.searchsorted(indep_vector, indep_max) if not np.isclose(indep_max, indep_vector[max_pos], FP_RTOL, FP_ATOL): indep_vector = np.insert(indep_vector, max_pos, indep_max) dep_vector = _interp_dep_vector(wave, indep_vector) wave._indep_vector = indep_vector[min_pos : max_pos + 1] wave._dep_vector = dep_vector[min_pos : max_pos + 1]
Build unit math operations.
def _build_units(indep_units, dep_units, op): """Build unit math operations.""" if (not dep_units) and (not indep_units): return "" if dep_units and (not indep_units): return dep_units if (not dep_units) and indep_units: return ( remove_extra_delims("1{0}({1})".format(op, indep_units)) if op == "/" else remove_extra_delims("({0})".format(indep_units)) ) return remove_extra_delims("({0}){1}({2})".format(dep_units, op, indep_units))
Perform generic operation on a waveform object.
def _operation(wave, desc, units, fpointer): """Perform generic operation on a waveform object.""" ret = copy.copy(wave) ret.dep_units = units ret.dep_name = "{0}({1})".format(desc, ret.dep_name) ret._dep_vector = fpointer(ret._dep_vector) return ret
Calculate running area under curve.
def _running_area(indep_vector, dep_vector): """Calculate running area under curve.""" rect_height = np.minimum(dep_vector[:-1], dep_vector[1:]) rect_base = np.diff(indep_vector) rect_area = np.multiply(rect_height, rect_base) triang_height = np.abs(np.diff(dep_vector)) triang_area = 0.5 * np.multiply(triang_height, rect_base) return np.cumsum(np.concatenate((np.array([0.0]), triang_area + rect_area)))
Validate min and max bounds are within waveform s independent variable vector.
def _validate_min_max(wave, indep_min, indep_max): """Validate min and max bounds are within waveform's independent variable vector.""" imin, imax = False, False if indep_min is None: indep_min = wave._indep_vector[0] imin = True if indep_max is None: indep_max = wave._indep_vector[-1] imax = True if imin and imax: return indep_min, indep_max exminmax = pexdoc.exh.addex( RuntimeError, "Incongruent `indep_min` and `indep_max` arguments" ) exmin = pexdoc.exh.addai("indep_min") exmax = pexdoc.exh.addai("indep_max") exminmax(bool(indep_min >= indep_max)) exmin( bool( (indep_min < wave._indep_vector[0]) and (not np.isclose(indep_min, wave._indep_vector[0], FP_RTOL, FP_ATOL)) ) ) exmax( bool( (indep_max > wave._indep_vector[-1]) and (not np.isclose(indep_max, wave._indep_vector[-1], FP_RTOL, FP_ATOL)) ) ) return indep_min, indep_max
r Return the arc cosine of a waveform s dependent variable vector.
def acos(wave): r""" Return the arc cosine of a waveform's dependent variable vector. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. peng.wave_functions.acos :raises: * RuntimeError (Argument \`wave\` is not valid) * ValueError (Math domain error) .. [[[end]]] """ pexdoc.exh.addex( ValueError, "Math domain error", bool((min(wave._dep_vector) < -1) or (max(wave._dep_vector) > 1)), ) return _operation(wave, "acos", "rad", np.arccos)
r Return the hyperbolic arc cosine of a waveform s dependent variable vector.
def acosh(wave): r""" Return the hyperbolic arc cosine of a waveform's dependent variable vector. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. peng.wave_functions.acosh :raises: * RuntimeError (Argument \`wave\` is not valid) * ValueError (Math domain error) .. [[[end]]] """ pexdoc.exh.addex(ValueError, "Math domain error", bool(min(wave._dep_vector) < 1)) return _operation(wave, "acosh", "", np.arccosh)
r Return the arc sine of a waveform s dependent variable vector.
def asin(wave): r""" Return the arc sine of a waveform's dependent variable vector. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. peng.wave_functions.asin :raises: * RuntimeError (Argument \`wave\` is not valid) * ValueError (Math domain error) .. [[[end]]] """ pexdoc.exh.addex( ValueError, "Math domain error", bool((min(wave._dep_vector) < -1) or (max(wave._dep_vector) > 1)), ) return _operation(wave, "asin", "rad", np.arcsin)
r Return the hyperbolic arc tangent of a waveform s dependent variable vector.
def atanh(wave): r""" Return the hyperbolic arc tangent of a waveform's dependent variable vector. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. peng.wave_functions.atanh :raises: * RuntimeError (Argument \`wave\` is not valid) * ValueError (Math domain error) .. [[[end]]] """ pexdoc.exh.addex( ValueError, "Math domain error", bool((min(wave._dep_vector) < -1) or (max(wave._dep_vector) > 1)), ) return _operation(wave, "atanh", "", np.arctanh)
r Return the running average of a waveform s dependent variable vector.
def average(wave, indep_min=None, indep_max=None): r""" Return the running average of a waveform's dependent variable vector. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :param indep_min: Independent vector start point of computation :type indep_min: integer or float :param indep_max: Independent vector stop point of computation :type indep_max: integer or float :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]] .. Auto-generated exceptions documentation for .. peng.wave_functions.average :raises: * RuntimeError (Argument \`indep_max\` is not valid) * RuntimeError (Argument \`indep_min\` is not valid) * RuntimeError (Argument \`wave\` is not valid) * RuntimeError (Incongruent \`indep_min\` and \`indep_max\` arguments) .. [[[end]]] """ ret = copy.copy(wave) _bound_waveform(ret, indep_min, indep_max) area = _running_area(ret._indep_vector, ret._dep_vector) area[0] = ret._dep_vector[0] deltas = ret._indep_vector - ret._indep_vector[0] deltas[0] = 1.0 ret._dep_vector = np.divide(area, deltas) ret.dep_name = "average({0})".format(ret._dep_name) return ret
r Return a waveform s dependent variable vector expressed in decibels.
def db(wave): r""" Return a waveform's dependent variable vector expressed in decibels. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for peng.wave_functions.db :raises: * RuntimeError (Argument \`wave\` is not valid) * ValueError (Math domain error) .. [[[end]]] """ pexdoc.exh.addex( ValueError, "Math domain error", bool((np.min(np.abs(wave._dep_vector)) <= 0)) ) ret = copy.copy(wave) ret.dep_units = "dB" ret.dep_name = "db({0})".format(ret.dep_name) ret._dep_vector = 20.0 * np.log10(np.abs(ret._dep_vector)) return ret
r Return the numerical derivative of a waveform s dependent variable vector.
def derivative(wave, indep_min=None, indep_max=None): r""" Return the numerical derivative of a waveform's dependent variable vector. The method used is the `backwards differences <https://en.wikipedia.org/wiki/ Finite_difference#Forward.2C_backward.2C_and_central_differences>`_ method :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :param indep_min: Independent vector start point of computation :type indep_min: integer or float :param indep_max: Independent vector stop point of computation :type indep_max: integer or float :rtype: float .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]] .. Auto-generated exceptions documentation for .. peng.wave_functions.derivative :raises: * RuntimeError (Argument \`indep_max\` is not valid) * RuntimeError (Argument \`indep_min\` is not valid) * RuntimeError (Argument \`wave\` is not valid) * RuntimeError (Incongruent \`indep_min\` and \`indep_max\` arguments) .. [[[end]]] """ ret = copy.copy(wave) _bound_waveform(ret, indep_min, indep_max) delta_indep = np.diff(ret._indep_vector) delta_dep = np.diff(ret._dep_vector) delta_indep = np.concatenate((np.array([delta_indep[0]]), delta_indep)) delta_dep = np.concatenate((np.array([delta_dep[0]]), delta_dep)) ret._dep_vector = np.divide(delta_dep, delta_indep) ret.dep_name = "derivative({0})".format(ret._dep_name) ret.dep_units = _build_units(ret.indep_units, ret.dep_units, "/") return ret
r Return the Fast Fourier Transform of a waveform.
def fft(wave, npoints=None, indep_min=None, indep_max=None): r""" Return the Fast Fourier Transform of a waveform. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :param npoints: Number of points to use in the transform. If **npoints** is less than the size of the independent variable vector the waveform is truncated; if **npoints** is greater than the size of the independent variable vector, the waveform is zero-padded :type npoints: positive integer :param indep_min: Independent vector start point of computation :type indep_min: integer or float :param indep_max: Independent vector stop point of computation :type indep_max: integer or float :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]] .. Auto-generated exceptions documentation for peng.wave_functions.fft :raises: * RuntimeError (Argument \`indep_max\` is not valid) * RuntimeError (Argument \`indep_min\` is not valid) * RuntimeError (Argument \`npoints\` is not valid) * RuntimeError (Argument \`wave\` is not valid) * RuntimeError (Incongruent \`indep_min\` and \`indep_max\` arguments) * RuntimeError (Non-uniform sampling) .. [[[end]]] """ ret = copy.copy(wave) _bound_waveform(ret, indep_min, indep_max) npoints = npoints or ret._indep_vector.size fs = (npoints - 1) / float(ret._indep_vector[-1]) spoints = min(ret._indep_vector.size, npoints) sdiff = np.diff(ret._indep_vector[:spoints]) cond = not np.all( np.isclose(sdiff, sdiff[0] * np.ones(spoints - 1), FP_RTOL, FP_ATOL) ) pexdoc.addex(RuntimeError, "Non-uniform sampling", cond) finc = fs / float(npoints - 1) indep_vector = _barange(-fs / 2.0, +fs / 2.0, finc) dep_vector = np.fft.fft(ret._dep_vector, npoints) return Waveform( indep_vector=indep_vector, dep_vector=dep_vector, dep_name="fft({0})".format(ret.dep_name), indep_scale="LINEAR", dep_scale="LINEAR", indep_units="Hz", dep_units="", )
r Return the Fast Fourier Transform of a waveform.
def fftdb(wave, npoints=None, indep_min=None, indep_max=None): r""" Return the Fast Fourier Transform of a waveform. The dependent variable vector of the returned waveform is expressed in decibels :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :param npoints: Number of points to use in the transform. If **npoints** is less than the size of the independent variable vector the waveform is truncated; if **npoints** is greater than the size of the independent variable vector, the waveform is zero-padded :type npoints: positive integer :param indep_min: Independent vector start point of computation :type indep_min: integer or float :param indep_max: Independent vector stop point of computation :type indep_max: integer or float :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]] .. Auto-generated exceptions documentation for .. peng.wave_functions.fftdb :raises: * RuntimeError (Argument \`indep_max\` is not valid) * RuntimeError (Argument \`indep_min\` is not valid) * RuntimeError (Argument \`npoints\` is not valid) * RuntimeError (Argument \`wave\` is not valid) * RuntimeError (Incongruent \`indep_min\` and \`indep_max\` arguments) * RuntimeError (Non-uniform sampling) .. [[[end]]] """ return db(fft(wave, npoints, indep_min, indep_max))
r Return the imaginary part of the Fast Fourier Transform of a waveform.
def ffti(wave, npoints=None, indep_min=None, indep_max=None): r""" Return the imaginary part of the Fast Fourier Transform of a waveform. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :param npoints: Number of points to use in the transform. If **npoints** is less than the size of the independent variable vector the waveform is truncated; if **npoints** is greater than the size of the independent variable vector, the waveform is zero-padded :type npoints: positive integer :param indep_min: Independent vector start point of computation :type indep_min: integer or float :param indep_max: Independent vector stop point of computation :type indep_max: integer or float :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]] .. Auto-generated exceptions documentation for .. peng.wave_functions.ffti :raises: * RuntimeError (Argument \`indep_max\` is not valid) * RuntimeError (Argument \`indep_min\` is not valid) * RuntimeError (Argument \`npoints\` is not valid) * RuntimeError (Argument \`wave\` is not valid) * RuntimeError (Incongruent \`indep_min\` and \`indep_max\` arguments) * RuntimeError (Non-uniform sampling) .. [[[end]]] """ return imag(fft(wave, npoints, indep_min, indep_max))
r Return the magnitude of the Fast Fourier Transform of a waveform.
def fftm(wave, npoints=None, indep_min=None, indep_max=None): r""" Return the magnitude of the Fast Fourier Transform of a waveform. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :param npoints: Number of points to use in the transform. If **npoints** is less than the size of the independent variable vector the waveform is truncated; if **npoints** is greater than the size of the independent variable vector, the waveform is zero-padded :type npoints: positive integer :param indep_min: Independent vector start point of computation :type indep_min: integer or float :param indep_max: Independent vector stop point of computation :type indep_max: integer or float :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]] .. Auto-generated exceptions documentation for .. peng.wave_functions.fftm :raises: * RuntimeError (Argument \`indep_max\` is not valid) * RuntimeError (Argument \`indep_min\` is not valid) * RuntimeError (Argument \`npoints\` is not valid) * RuntimeError (Argument \`wave\` is not valid) * RuntimeError (Incongruent \`indep_min\` and \`indep_max\` arguments) * RuntimeError (Non-uniform sampling) .. [[[end]]] """ return abs(fft(wave, npoints, indep_min, indep_max))
r Return the phase of the Fast Fourier Transform of a waveform.
def fftp(wave, npoints=None, indep_min=None, indep_max=None, unwrap=True, rad=True): r""" Return the phase of the Fast Fourier Transform of a waveform. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :param npoints: Number of points to use in the transform. If **npoints** is less than the size of the independent variable vector the waveform is truncated; if **npoints** is greater than the size of the independent variable vector, the waveform is zero-padded :type npoints: positive integer :param indep_min: Independent vector start point of computation :type indep_min: integer or float :param indep_max: Independent vector stop point of computation :type indep_max: integer or float :param unwrap: Flag that indicates whether phase should change phase shifts to their :code:`2*pi` complement (True) or not (False) :type unwrap: boolean :param rad: Flag that indicates whether phase should be returned in radians (True) or degrees (False) :type rad: boolean :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]] .. Auto-generated exceptions documentation for .. peng.wave_functions.fftp :raises: * RuntimeError (Argument \`indep_max\` is not valid) * RuntimeError (Argument \`indep_min\` is not valid) * RuntimeError (Argument \`npoints\` is not valid) * RuntimeError (Argument \`rad\` is not valid) * RuntimeError (Argument \`unwrap\` is not valid) * RuntimeError (Argument \`wave\` is not valid) * RuntimeError (Incongruent \`indep_min\` and \`indep_max\` arguments) * RuntimeError (Non-uniform sampling) .. [[[end]]] """ return phase(fft(wave, npoints, indep_min, indep_max), unwrap=unwrap, rad=rad)
r Return the real part of the Fast Fourier Transform of a waveform.
def fftr(wave, npoints=None, indep_min=None, indep_max=None): r""" Return the real part of the Fast Fourier Transform of a waveform. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :param npoints: Number of points to use in the transform. If **npoints** is less than the size of the independent variable vector the waveform is truncated; if **npoints** is greater than the size of the independent variable vector, the waveform is zero-padded :type npoints: positive integer :param indep_min: Independent vector start point of computation :type indep_min: integer or float :param indep_max: Independent vector stop point of computation :type indep_max: integer or float :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]] .. Auto-generated exceptions documentation for .. peng.wave_functions.fftr :raises: * RuntimeError (Argument \`indep_max\` is not valid) * RuntimeError (Argument \`indep_min\` is not valid) * RuntimeError (Argument \`npoints\` is not valid) * RuntimeError (Argument \`wave\` is not valid) * RuntimeError (Incongruent \`indep_min\` and \`indep_max\` arguments) * RuntimeError (Non-uniform sampling) .. [[[end]]] """ return real(fft(wave, npoints, indep_min, indep_max))
r Return the independent variable point associated with a dependent variable point.
def find(wave, dep_var, der=None, inst=1, indep_min=None, indep_max=None): r""" Return the independent variable point associated with a dependent variable point. If the dependent variable point is not in the dependent variable vector the independent variable vector point is obtained by linear interpolation :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :param dep_var: Dependent vector value to search for :type dep_var: integer, float or complex :param der: Dependent vector derivative filter. If +1 only independent vector points that have positive derivatives when crossing the requested dependent vector point are returned; if -1 only independent vector points that have negative derivatives when crossing the requested dependent vector point are returned; if 0 only independent vector points that have null derivatives when crossing the requested dependent vector point are returned; otherwise if None all independent vector points are returned regardless of the dependent vector derivative. The derivative of the first and last point of the waveform is assumed to be null :type der: integer, float or complex :param inst: Instance number filter. If, for example, **inst** equals 3, then the independent variable vector point at which the dependent variable vector equals the requested value for the third time is returned :type inst: positive integer :param indep_min: Independent vector start point of computation :type indep_min: integer or float :param indep_max: Independent vector stop point of computation :type indep_max: integer or float :rtype: integer, float or None if the dependent variable point is not found .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]] .. Auto-generated exceptions documentation for .. peng.wave_functions.find :raises: * RuntimeError (Argument \`dep_var\` is not valid) * RuntimeError (Argument \`der\` is not valid) * RuntimeError (Argument \`indep_max\` is not valid) * RuntimeError (Argument \`indep_min\` is not valid) * RuntimeError (Argument \`inst\` is not valid) * RuntimeError (Argument \`wave\` is not valid) * RuntimeError (Incongruent \`indep_min\` and \`indep_max\` arguments) .. [[[end]]] """ # pylint: disable=C0325,R0914,W0613 ret = copy.copy(wave) _bound_waveform(ret, indep_min, indep_max) close_min = np.isclose(min(ret._dep_vector), dep_var, FP_RTOL, FP_ATOL) close_max = np.isclose(max(ret._dep_vector), dep_var, FP_RTOL, FP_ATOL) if ((np.amin(ret._dep_vector) > dep_var) and (not close_min)) or ( (np.amax(ret._dep_vector) < dep_var) and (not close_max) ): return None cross_wave = ret._dep_vector - dep_var sign_wave = np.sign(cross_wave) exact_idx = np.where(np.isclose(ret._dep_vector, dep_var, FP_RTOL, FP_ATOL))[0] # Locations where dep_vector crosses dep_var or it is equal to it left_idx = np.where(np.diff(sign_wave))[0] # Remove elements to the left of exact matches left_idx = np.setdiff1d(left_idx, exact_idx) left_idx = np.setdiff1d(left_idx, exact_idx - 1) right_idx = left_idx + 1 if left_idx.size else np.array([]) indep_var = ret._indep_vector[exact_idx] if exact_idx.size else np.array([]) dvector = np.zeros(exact_idx.size).astype(int) if exact_idx.size else np.array([]) if left_idx.size and (ret.interp == "STAIRCASE"): idvector = ( 2.0 * (ret._dep_vector[right_idx] > ret._dep_vector[left_idx]).astype(int) - 1 ) if indep_var.size: indep_var = np.concatenate((indep_var, ret._indep_vector[right_idx])) dvector = np.concatenate((dvector, idvector)) sidx = np.argsort(indep_var) indep_var = indep_var[sidx] dvector = dvector[sidx] else: indep_var = ret._indep_vector[right_idx] dvector = idvector elif left_idx.size: y_left = ret._dep_vector[left_idx] y_right = ret._dep_vector[right_idx] x_left = ret._indep_vector[left_idx] x_right = ret._indep_vector[right_idx] slope = ((y_left - y_right) / (x_left - x_right)).astype(float) # y = y0+slope*(x-x0) => x0+(y-y0)/slope if indep_var.size: indep_var = np.concatenate( (indep_var, x_left + ((dep_var - y_left) / slope)) ) dvector = np.concatenate((dvector, np.where(slope > 0, 1, -1))) sidx = np.argsort(indep_var) indep_var = indep_var[sidx] dvector = dvector[sidx] else: indep_var = x_left + ((dep_var - y_left) / slope) dvector = np.where(slope > 0, +1, -1) if der is not None: indep_var = np.extract(dvector == der, indep_var) return indep_var[inst - 1] if inst <= indep_var.size else None
r Return the inverse Fast Fourier Transform of a waveform.
def ifftdb(wave, npoints=None, indep_min=None, indep_max=None): r""" Return the inverse Fast Fourier Transform of a waveform. The dependent variable vector of the returned waveform is expressed in decibels :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :param npoints: Number of points to use in the transform. If **npoints** is less than the size of the independent variable vector the waveform is truncated; if **npoints** is greater than the size of the independent variable vector, the waveform is zero-padded :type npoints: positive integer :param indep_min: Independent vector start point of computation :type indep_min: integer or float :param indep_max: Independent vector stop point of computation :type indep_max: integer or float :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]] .. Auto-generated exceptions documentation for .. peng.wave_functions.ifftdb :raises: * RuntimeError (Argument \`indep_max\` is not valid) * RuntimeError (Argument \`indep_min\` is not valid) * RuntimeError (Argument \`npoints\` is not valid) * RuntimeError (Argument \`wave\` is not valid) * RuntimeError (Incongruent \`indep_min\` and \`indep_max\` arguments) * RuntimeError (Non-uniform frequency spacing) .. [[[end]]] """ return db(ifft(wave, npoints, indep_min, indep_max))
r Return the imaginary part of the inverse Fast Fourier Transform of a waveform.
def iffti(wave, npoints=None, indep_min=None, indep_max=None): r""" Return the imaginary part of the inverse Fast Fourier Transform of a waveform. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :param npoints: Number of points to use in the transform. If **npoints** is less than the size of the independent variable vector the waveform is truncated; if **npoints** is greater than the size of the independent variable vector, the waveform is zero-padded :type npoints: positive integer :param indep_min: Independent vector start point of computation :type indep_min: integer or float :param indep_max: Independent vector stop point of computation :type indep_max: integer or float :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]] .. Auto-generated exceptions documentation for .. peng.wave_functions.iffti :raises: * RuntimeError (Argument \`indep_max\` is not valid) * RuntimeError (Argument \`indep_min\` is not valid) * RuntimeError (Argument \`npoints\` is not valid) * RuntimeError (Argument \`wave\` is not valid) * RuntimeError (Incongruent \`indep_min\` and \`indep_max\` arguments) * RuntimeError (Non-uniform frequency spacing) .. [[[end]]] """ return imag(ifft(wave, npoints, indep_min, indep_max))
r Return the magnitude of the inverse Fast Fourier Transform of a waveform.
def ifftm(wave, npoints=None, indep_min=None, indep_max=None): r""" Return the magnitude of the inverse Fast Fourier Transform of a waveform. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :param npoints: Number of points to use in the transform. If **npoints** is less than the size of the independent variable vector the waveform is truncated; if **npoints** is greater than the size of the independent variable vector, the waveform is zero-padded :type npoints: positive integer :param indep_min: Independent vector start point of computation :type indep_min: integer or float :param indep_max: Independent vector stop point of computation :type indep_max: integer or float :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]] .. Auto-generated exceptions documentation for .. peng.wave_functions.ifftm :raises: * RuntimeError (Argument \`indep_max\` is not valid) * RuntimeError (Argument \`indep_min\` is not valid) * RuntimeError (Argument \`npoints\` is not valid) * RuntimeError (Argument \`wave\` is not valid) * RuntimeError (Incongruent \`indep_min\` and \`indep_max\` arguments) * RuntimeError (Non-uniform frequency spacing) .. [[[end]]] """ return abs(ifft(wave, npoints, indep_min, indep_max))
r Return the phase of the inverse Fast Fourier Transform of a waveform.
def ifftp(wave, npoints=None, indep_min=None, indep_max=None, unwrap=True, rad=True): r""" Return the phase of the inverse Fast Fourier Transform of a waveform. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :param npoints: Number of points to use in the transform. If **npoints** is less than the size of the independent variable vector the waveform is truncated; if **npoints** is greater than the size of the independent variable vector, the waveform is zero-padded :type npoints: positive integer :param indep_min: Independent vector start point of computation :type indep_min: integer or float :param indep_max: Independent vector stop point of computation :type indep_max: integer or float :param unwrap: Flag that indicates whether phase should change phase shifts to their :code:`2*pi` complement (True) or not (False) :type unwrap: boolean :param rad: Flag that indicates whether phase should be returned in radians (True) or degrees (False) :type rad: boolean :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]] .. Auto-generated exceptions documentation for .. peng.wave_functions.ifftp :raises: * RuntimeError (Argument \`indep_max\` is not valid) * RuntimeError (Argument \`indep_min\` is not valid) * RuntimeError (Argument \`npoints\` is not valid) * RuntimeError (Argument \`rad\` is not valid) * RuntimeError (Argument \`unwrap\` is not valid) * RuntimeError (Argument \`wave\` is not valid) * RuntimeError (Incongruent \`indep_min\` and \`indep_max\` arguments) * RuntimeError (Non-uniform frequency spacing) .. [[[end]]] """ return phase(ifft(wave, npoints, indep_min, indep_max), unwrap=unwrap, rad=rad)
r Return the real part of the inverse Fast Fourier Transform of a waveform.
def ifftr(wave, npoints=None, indep_min=None, indep_max=None): r""" Return the real part of the inverse Fast Fourier Transform of a waveform. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :param npoints: Number of points to use in the transform. If **npoints** is less than the size of the independent variable vector the waveform is truncated; if **npoints** is greater than the size of the independent variable vector, the waveform is zero-padded :type npoints: positive integer :param indep_min: Independent vector start point of computation :type indep_min: integer or float :param indep_max: Independent vector stop point of computation :type indep_max: integer or float :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]] .. Auto-generated exceptions documentation for .. peng.wave_functions.ifftr :raises: * RuntimeError (Argument \`indep_max\` is not valid) * RuntimeError (Argument \`indep_min\` is not valid) * RuntimeError (Argument \`npoints\` is not valid) * RuntimeError (Argument \`wave\` is not valid) * RuntimeError (Incongruent \`indep_min\` and \`indep_max\` arguments) * RuntimeError (Non-uniform frequency spacing) .. [[[end]]] """ return real(ifft(wave, npoints, indep_min, indep_max))
r Return the running integral of a waveform s dependent variable vector.
def integral(wave, indep_min=None, indep_max=None): r""" Return the running integral of a waveform's dependent variable vector. The method used is the `trapezoidal <https://en.wikipedia.org/wiki/Trapezoidal_rule>`_ method :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :param indep_min: Independent vector start point of computation :type indep_min: integer or float :param indep_max: Independent vector stop point of computation :type indep_max: integer or float :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]] .. Auto-generated exceptions documentation for .. peng.wave_functions.integral :raises: * RuntimeError (Argument \`indep_max\` is not valid) * RuntimeError (Argument \`indep_min\` is not valid) * RuntimeError (Argument \`wave\` is not valid) * RuntimeError (Incongruent \`indep_min\` and \`indep_max\` arguments) .. [[[end]]] """ ret = copy.copy(wave) _bound_waveform(ret, indep_min, indep_max) ret._dep_vector = _running_area(ret._indep_vector, ret._dep_vector) ret.dep_name = "integral({0})".format(ret._dep_name) ret.dep_units = _build_units(ret.indep_units, ret.dep_units, "*") return ret
r Return the group delay of a waveform.
def group_delay(wave): r""" Return the group delay of a waveform. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]] .. Auto-generated exceptions documentation for .. peng.wave_functions.group_delay :raises: RuntimeError (Argument \`wave\` is not valid) .. [[[end]]] """ ret = -derivative(phase(wave, unwrap=True) / (2 * math.pi)) ret.dep_name = "group_delay({0})".format(wave.dep_name) ret.dep_units = "sec" return ret
r Return the natural logarithm of a waveform s dependent variable vector.
def log(wave): r""" Return the natural logarithm of a waveform's dependent variable vector. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for peng.wave_functions.log :raises: * RuntimeError (Argument \`wave\` is not valid) * ValueError (Math domain error) .. [[[end]]] """ pexdoc.exh.addex( ValueError, "Math domain error", bool((min(wave._dep_vector) <= 0)) ) return _operation(wave, "log", "", np.log)
r Return the numerical average of a waveform s dependent variable vector.
def naverage(wave, indep_min=None, indep_max=None): r""" Return the numerical average of a waveform's dependent variable vector. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :param indep_min: Independent vector start point of computation :type indep_min: integer or float :param indep_max: Independent vector stop point of computation :type indep_max: integer or float :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]] .. Auto-generated exceptions documentation for .. peng.wave_functions.naverage :raises: * RuntimeError (Argument \`indep_max\` is not valid) * RuntimeError (Argument \`indep_min\` is not valid) * RuntimeError (Argument \`wave\` is not valid) * RuntimeError (Incongruent \`indep_min\` and \`indep_max\` arguments) .. [[[end]]] """ ret = copy.copy(wave) _bound_waveform(ret, indep_min, indep_max) delta_x = ret._indep_vector[-1] - ret._indep_vector[0] return np.trapz(ret._dep_vector, x=ret._indep_vector) / delta_x
r Return the numerical integral of a waveform s dependent variable vector.
def nintegral(wave, indep_min=None, indep_max=None): r""" Return the numerical integral of a waveform's dependent variable vector. The method used is the `trapezoidal <https://en.wikipedia.org/wiki/Trapezoidal_rule>`_ method :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :param indep_min: Independent vector start point of computation :type indep_min: integer or float :param indep_max: Independent vector stop point of computation :type indep_max: integer or float :rtype: float .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]] .. Auto-generated exceptions documentation for .. peng.wave_functions.nintegral :raises: * RuntimeError (Argument \`indep_max\` is not valid) * RuntimeError (Argument \`indep_min\` is not valid) * RuntimeError (Argument \`wave\` is not valid) * RuntimeError (Incongruent \`indep_min\` and \`indep_max\` arguments) .. [[[end]]] """ ret = copy.copy(wave) _bound_waveform(ret, indep_min, indep_max) return np.trapz(ret._dep_vector, ret._indep_vector)
r Return the maximum of a waveform s dependent variable vector.
def nmax(wave, indep_min=None, indep_max=None): r""" Return the maximum of a waveform's dependent variable vector. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :param indep_min: Independent vector start point of computation :type indep_min: integer or float :param indep_max: Independent vector stop point of computation :type indep_max: integer or float :rtype: float .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]] .. Auto-generated exceptions documentation for .. peng.wave_functions.nmax :raises: * RuntimeError (Argument \`indep_max\` is not valid) * RuntimeError (Argument \`indep_min\` is not valid) * RuntimeError (Argument \`wave\` is not valid) * RuntimeError (Incongruent \`indep_min\` and \`indep_max\` arguments) .. [[[end]]] """ ret = copy.copy(wave) _bound_waveform(ret, indep_min, indep_max) return np.max(ret._dep_vector)
r Return the minimum of a waveform s dependent variable vector.
def nmin(wave, indep_min=None, indep_max=None): r""" Return the minimum of a waveform's dependent variable vector. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :param indep_min: Independent vector start point of computation :type indep_min: integer or float :param indep_max: Independent vector stop point of computation :type indep_max: integer or float :rtype: float .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]] .. Auto-generated exceptions documentation for .. peng.wave_functions.nmin :raises: * RuntimeError (Argument \`indep_max\` is not valid) * RuntimeError (Argument \`indep_min\` is not valid) * RuntimeError (Argument \`wave\` is not valid) * RuntimeError (Incongruent \`indep_min\` and \`indep_max\` arguments) .. [[[end]]] """ ret = copy.copy(wave) _bound_waveform(ret, indep_min, indep_max) return np.min(ret._dep_vector)
r Return the phase of a waveform s dependent variable vector.
def phase(wave, unwrap=True, rad=True): r""" Return the phase of a waveform's dependent variable vector. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :param unwrap: Flag that indicates whether phase should change phase shifts to their :code:`2*pi` complement (True) or not (False) :type unwrap: boolean :param rad: Flag that indicates whether phase should be returned in radians (True) or degrees (False) :type rad: boolean :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. peng.wave_functions.phase :raises: * RuntimeError (Argument \`rad\` is not valid) * RuntimeError (Argument \`unwrap\` is not valid) * RuntimeError (Argument \`wave\` is not valid) .. [[[end]]] """ ret = copy.copy(wave) ret.dep_units = "rad" if rad else "deg" ret.dep_name = "phase({0})".format(ret.dep_name) ret._dep_vector = ( np.unwrap(np.angle(ret._dep_vector)) if unwrap else np.angle(ret._dep_vector) ) if not rad: ret._dep_vector = np.rad2deg(ret._dep_vector) return ret
r Round a waveform s dependent variable vector to a given number of decimal places.
def round(wave, decimals=0): r""" Round a waveform's dependent variable vector to a given number of decimal places. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :param decimals: Number of decimals to round to :type decimals: integer :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. peng.wave_functions.round :raises: * RuntimeError (Argument \`decimals\` is not valid) * RuntimeError (Argument \`wave\` is not valid) .. [[[end]]] """ # pylint: disable=W0622 pexdoc.exh.addex( TypeError, "Cannot convert complex to integer", wave._dep_vector.dtype.name.startswith("complex"), ) ret = copy.copy(wave) ret.dep_name = "round({0}, {1})".format(ret.dep_name, decimals) ret._dep_vector = np.round(wave._dep_vector, decimals) return ret
r Return the square root of a waveform s dependent variable vector.
def sqrt(wave): r""" Return the square root of a waveform's dependent variable vector. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. peng.wave_functions.sqrt :raises: RuntimeError (Argument \`wave\` is not valid) .. [[[end]]] """ dep_units = "{0}**0.5".format(wave.dep_units) return _operation(wave, "sqrt", dep_units, np.sqrt)
r Return a waveform that is a sub - set of a waveform potentially re - sampled.
def subwave(wave, dep_name=None, indep_min=None, indep_max=None, indep_step=None): r""" Return a waveform that is a sub-set of a waveform, potentially re-sampled. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :param dep_name: Independent variable name :type dep_name: `NonNullString <https://pexdoc.readthedocs.io/en/stable/ ptypes.html#nonnullstring>`_ :param indep_min: Independent vector start point of computation :type indep_min: integer or float :param indep_max: Independent vector stop point of computation :type indep_max: integer or float :param indep_step: Independent vector step :type indep_step: integer or float :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]] .. Auto-generated exceptions documentation for .. peng.wave_functions.subwave :raises: * RuntimeError (Argument \`dep_name\` is not valid) * RuntimeError (Argument \`indep_max\` is not valid) * RuntimeError (Argument \`indep_min\` is not valid) * RuntimeError (Argument \`indep_step\` is greater than independent vector range) * RuntimeError (Argument \`indep_step\` is not valid) * RuntimeError (Argument \`wave\` is not valid) * RuntimeError (Incongruent \`indep_min\` and \`indep_max\` arguments) .. [[[end]]] """ ret = copy.copy(wave) if dep_name is not None: ret.dep_name = dep_name _bound_waveform(ret, indep_min, indep_max) pexdoc.addai("indep_step", bool((indep_step is not None) and (indep_step <= 0))) exmsg = "Argument `indep_step` is greater than independent vector range" cond = bool( (indep_step is not None) and (indep_step > ret._indep_vector[-1] - ret._indep_vector[0]) ) pexdoc.addex(RuntimeError, exmsg, cond) if indep_step: indep_vector = _barange(indep_min, indep_max, indep_step) dep_vector = _interp_dep_vector(ret, indep_vector) ret._set_indep_vector(indep_vector, check=False) ret._set_dep_vector(dep_vector, check=False) return ret
r Convert a waveform s dependent variable vector to complex.
def wcomplex(wave): r""" Convert a waveform's dependent variable vector to complex. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. peng.wave_functions.wcomplex :raises: RuntimeError (Argument \`wave\` is not valid) .. [[[end]]] """ ret = copy.copy(wave) ret._dep_vector = ret._dep_vector.astype(np.complex) return ret
r Convert a waveform s dependent variable vector to float.
def wfloat(wave): r""" Convert a waveform's dependent variable vector to float. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. peng.wave_functions.wfloat :raises: * RuntimeError (Argument \`wave\` is not valid) * TypeError (Cannot convert complex to float) .. [[[end]]] """ pexdoc.exh.addex( TypeError, "Cannot convert complex to float", wave._dep_vector.dtype.name.startswith("complex"), ) ret = copy.copy(wave) ret._dep_vector = ret._dep_vector.astype(np.float) return ret
r Convert a waveform s dependent variable vector to integer.
def wint(wave): r""" Convert a waveform's dependent variable vector to integer. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. peng.wave_functions.wint :raises: * RuntimeError (Argument \`wave\` is not valid) * TypeError (Cannot convert complex to integer) .. [[[end]]] """ pexdoc.exh.addex( TypeError, "Cannot convert complex to integer", wave._dep_vector.dtype.name.startswith("complex"), ) ret = copy.copy(wave) ret._dep_vector = ret._dep_vector.astype(np.int) return ret
r Return the dependent variable value at a given independent variable point.
def wvalue(wave, indep_var): r""" Return the dependent variable value at a given independent variable point. If the independent variable point is not in the independent variable vector the dependent variable value is obtained by linear interpolation :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :param indep_var: Independent variable point for which the dependent variable is to be obtained :type indep_var: integer or float :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. peng.wave_functions.wvalue :raises: * RuntimeError (Argument \`indep_var\` is not valid) * RuntimeError (Argument \`wave\` is not valid) * ValueError (Argument \`indep_var\` is not in the independent variable vector range) .. [[[end]]] """ close_min = np.isclose(indep_var, wave._indep_vector[0], FP_RTOL, FP_ATOL) close_max = np.isclose(indep_var, wave._indep_vector[-1], FP_RTOL, FP_ATOL) pexdoc.exh.addex( ValueError, "Argument `indep_var` is not in the independent variable vector range", bool( ((indep_var < wave._indep_vector[0]) and (not close_min)) or ((indep_var > wave._indep_vector[-1]) and (not close_max)) ), ) if close_min: return wave._dep_vector[0] if close_max: return wave._dep_vector[-1] idx = np.searchsorted(wave._indep_vector, indep_var) xdelta = wave._indep_vector[idx] - wave._indep_vector[idx - 1] ydelta = wave._dep_vector[idx] - wave._dep_vector[idx - 1] slope = ydelta / float(xdelta) return wave._dep_vector[idx - 1] + slope * (indep_var - wave._indep_vector[idx - 1])
Only allow lookups for jspm_packages.
def find(self, path, all=False): """ Only allow lookups for jspm_packages. # TODO: figure out the 'jspm_packages' dir from packag.json. """ bits = path.split('/') dirs_to_serve = ['jspm_packages', settings.SYSTEMJS_OUTPUT_DIR] if not bits or bits[0] not in dirs_to_serve: return [] return super(SystemFinder, self).find(path, all=all)
Get first sentence of first paragraph of long description.
def get_short_desc(long_desc): """Get first sentence of first paragraph of long description.""" found = False olines = [] for line in [item.rstrip() for item in long_desc.split("\n")]: if found and (((not line) and (not olines)) or (line and olines)): olines.append(line) elif found and olines and (not line): return (" ".join(olines).split(".")[0]).strip() found = line == ".. [[[end]]]" if not found else found return ""
Crawls the ( specified ) template files and extracts the apps.
def find_apps(self, templates=None): """ Crawls the (specified) template files and extracts the apps. If `templates` is specified, the template loader is used and the template is tokenized to extract the SystemImportNode. An empty context is used to resolve the node variables. """ all_apps = OrderedDict() if not templates: all_files = self.discover_templates() for tpl_name, fp in all_files: # this is the most performant - a testcase that used the loader with tpl_name # was about 8x slower for a project with ~5 apps in different templates :( with io.open(fp, 'r', encoding=settings.FILE_CHARSET) as template_file: src_data = template_file.read() for t in Lexer(src_data).tokenize(): if t.token_type == TOKEN_BLOCK: imatch = SYSTEMJS_TAG_RE.match(t.contents) if imatch: all_apps.setdefault(tpl_name, []) all_apps[tpl_name].append(imatch.group('app')) else: for tpl_name in templates: try: template = loader.get_template(tpl_name) except TemplateDoesNotExist: raise CommandError('Template \'%s\' does not exist' % tpl_name) import_nodes = template.template.nodelist.get_nodes_by_type(SystemImportNode) for node in import_nodes: app = node.path.resolve(RESOLVE_CONTEXT) if not app: self.stdout.write(self.style.WARNING( '{tpl}: Could not resolve path with context {ctx}, skipping.'.format( tpl=tpl_name, ctx=RESOLVE_CONTEXT) )) continue all_apps.setdefault(tpl_name, []) all_apps[tpl_name].append(app) return all_apps
Build the filepath by appending the extension.
def render(self, context): """ Build the filepath by appending the extension. """ module_path = self.path.resolve(context) if not settings.SYSTEMJS_ENABLED: if settings.SYSTEMJS_DEFAULT_JS_EXTENSIONS: name, ext = posixpath.splitext(module_path) if not ext: module_path = '{}.js'.format(module_path) if settings.SYSTEMJS_SERVER_URL: tpl = """<script src="{url}{app}" type="text/javascript"></script>""" else: tpl = """<script type="text/javascript">System.import('{app}');</script>""" return tpl.format(app=module_path, url=settings.SYSTEMJS_SERVER_URL) # else: create a bundle rel_path = System.get_bundle_path(module_path) url = staticfiles_storage.url(rel_path) tag_attrs = {'type': 'text/javascript'} for key, value in self.tag_attrs.items(): if not isinstance(value, bool): value = value.resolve(context) tag_attrs[key] = value return """<script{attrs} src="{url}"></script>""".format( url=url, attrs=flatatt(tag_attrs) )
r Validate if an object is an: ref: EngineeringNotationNumber pseudo - type object.
def engineering_notation_number(obj): r""" Validate if an object is an :ref:`EngineeringNotationNumber` pseudo-type object. :param obj: Object :type obj: any :raises: RuntimeError (Argument \`*[argument_name]*\` is not valid). The token \*[argument_name]\* is replaced by the name of the argument the contract is attached to :rtype: None """ try: obj = obj.rstrip() float(obj[:-1] if obj[-1] in _SUFFIX_TUPLE else obj) return None except (AttributeError, IndexError, ValueError): # AttributeError: obj.rstrip(), object could not be a string # IndexError: obj[-1], when an empty string # ValueError: float(), when not a string representing a number raise ValueError(pexdoc.pcontracts.get_exdesc())
r Validate if an object is an: ref: TouchstoneData pseudo - type object.
def touchstone_data(obj): r""" Validate if an object is an :ref:`TouchstoneData` pseudo-type object. :param obj: Object :type obj: any :raises: RuntimeError (Argument \`*[argument_name]*\` is not valid). The token \*[argument_name]\* is replaced by the name of the argument the contract is attached to :rtype: None """ if (not isinstance(obj, dict)) or ( isinstance(obj, dict) and (sorted(obj.keys()) != sorted(["points", "freq", "pars"])) ): raise ValueError(pexdoc.pcontracts.get_exdesc()) if not (isinstance(obj["points"], int) and (obj["points"] > 0)): raise ValueError(pexdoc.pcontracts.get_exdesc()) if _check_increasing_real_numpy_vector(obj["freq"]): raise ValueError(pexdoc.pcontracts.get_exdesc()) if not isinstance(obj["pars"], np.ndarray): raise ValueError(pexdoc.pcontracts.get_exdesc()) vdata = ["int", "float", "complex"] if not any([obj["pars"].dtype.name.startswith(item) for item in vdata]): raise ValueError(pexdoc.pcontracts.get_exdesc()) if obj["freq"].size != obj["points"]: raise ValueError(pexdoc.pcontracts.get_exdesc()) nports = int(math.sqrt(obj["pars"].size / obj["freq"].size)) if obj["points"] * (nports ** 2) != obj["pars"].size: raise ValueError(pexdoc.pcontracts.get_exdesc())
r Validate if an object is an: ref: TouchstoneNoiseData pseudo - type object.
def touchstone_noise_data(obj): r""" Validate if an object is an :ref:`TouchstoneNoiseData` pseudo-type object. :param obj: Object :type obj: any :raises: RuntimeError (Argument \`*[argument_name]*\` is not valid). The token \*[argument_name]\* is replaced by the name of the argument the contract is attached to :rtype: None """ if isinstance(obj, dict) and (not obj): return None if (not isinstance(obj, dict)) or ( isinstance(obj, dict) and (sorted(obj.keys()) != sorted(["points", "freq", "nf", "rc", "res"])) ): raise ValueError(pexdoc.pcontracts.get_exdesc()) if not (isinstance(obj["points"], int) and (obj["points"] > 0)): raise ValueError(pexdoc.pcontracts.get_exdesc()) if _check_increasing_real_numpy_vector(obj["freq"]): raise ValueError(pexdoc.pcontracts.get_exdesc()) if _check_real_numpy_vector(obj["nf"]): raise ValueError(pexdoc.pcontracts.get_exdesc()) if _check_number_numpy_vector(obj["rc"]): raise ValueError(pexdoc.pcontracts.get_exdesc()) if not ( isinstance(obj["res"], np.ndarray) and (len(obj["res"].shape) == 1) and (obj["res"].shape[0] > 0) and np.all(obj["res"] >= 0) ): raise ValueError(pexdoc.pcontracts.get_exdesc()) sizes = [obj["freq"].size, obj["nf"].size, obj["rc"].size, obj["res"].size] if set(sizes) != set([obj["points"]]): raise ValueError(pexdoc.pcontracts.get_exdesc()) return None
r Validate if an object is an: ref: TouchstoneOptions pseudo - type object.
def touchstone_options(obj): r""" Validate if an object is an :ref:`TouchstoneOptions` pseudo-type object. :param obj: Object :type obj: any :raises: RuntimeError (Argument \`*[argument_name]*\` is not valid). The token \*[argument_name]\* is replaced by the name of the argument the contract is attached to :rtype: None """ if (not isinstance(obj, dict)) or ( isinstance(obj, dict) and (sorted(obj.keys()) != sorted(["units", "ptype", "pformat", "z0"])) ): raise ValueError(pexdoc.pcontracts.get_exdesc()) if not ( (obj["units"].lower() in ["ghz", "mhz", "khz", "hz"]) and (obj["ptype"].lower() in ["s", "y", "z", "h", "g"]) and (obj["pformat"].lower() in ["db", "ma", "ri"]) and isinstance(obj["z0"], float) and (obj["z0"] >= 0) ): raise ValueError(pexdoc.pcontracts.get_exdesc())
r Validate if an object is a: ref: WaveInterpOption pseudo - type object.
def wave_interp_option(obj): r""" Validate if an object is a :ref:`WaveInterpOption` pseudo-type object. :param obj: Object :type obj: any :raises: RuntimeError (Argument \`*[argument_name]*\` is not valid). The token \*[argument_name]\* is replaced by the name of the argument the contract is attached to :rtype: None """ exdesc = pexdoc.pcontracts.get_exdesc() if not isinstance(obj, str): raise ValueError(exdesc) if obj.upper() in ["CONTINUOUS", "STAIRCASE"]: return None raise ValueError(exdesc)
r Validate if an object is a: ref: WaveVectors pseudo - type object.
def wave_vectors(obj): r""" Validate if an object is a :ref:`WaveVectors` pseudo-type object. :param obj: Object :type obj: any :raises: RuntimeError (Argument \`*[argument_name]*\` is not valid). The token \*[argument_name]\* is replaced by the name of the argument the contract is attached to :rtype: None """ exdesc = pexdoc.pcontracts.get_exdesc() if not isinstance(obj, list) or (isinstance(obj, list) and not obj): raise ValueError(exdesc) if any([not (isinstance(item, tuple) and len(item) == 2) for item in obj]): raise ValueError(exdesc) indep_vector, dep_vector = zip(*obj) if _check_increasing_real_numpy_vector(np.array(indep_vector)): raise ValueError(exdesc) if _check_real_numpy_vector(np.array(dep_vector)): raise ValueError(exdesc)
Build mathematical expression from hierarchical list.
def _build_expr(tokens, higher_oplevel=-1, ldelim="(", rdelim=")"): """Build mathematical expression from hierarchical list.""" # Numbers if isinstance(tokens, str): return tokens # Unary operators if len(tokens) == 2: return "".join(tokens) # Multi-term operators oplevel = _get_op_level(tokens[1]) stoken = "" for num, item in enumerate(tokens): if num % 2 == 0: stoken += _build_expr(item, oplevel, ldelim=ldelim, rdelim=rdelim) else: stoken += item if (oplevel < higher_oplevel) or ( (oplevel == higher_oplevel) and (oplevel in _OP_PREC_PAR) ): stoken = ldelim + stoken + rdelim return stoken
Return position of next matching closing delimiter.
def _next_rdelim(items, pos): """Return position of next matching closing delimiter.""" for num, item in enumerate(items): if item > pos: break else: raise RuntimeError("Mismatched delimiters") del items[num] return item
Parse function calls.
def _get_functions(expr, ldelim="(", rdelim=")"): """Parse function calls.""" tpars = _pair_delims(expr, ldelim=ldelim, rdelim=rdelim) alphas = "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" fchars = "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789" "_" tfuncs = [] for lnum, rnum in tpars: if lnum and expr[lnum - 1] in fchars: for cnum, char in enumerate(reversed(expr[:lnum])): if char not in fchars: break else: cnum = lnum tfuncs.append( { "fname": expr[lnum - cnum : lnum], "expr": expr[lnum + 1 : rnum], "start": lnum - cnum, "stop": rnum, } ) if expr[lnum - cnum] not in alphas: raise RuntimeError( "Function name `{0}` is not valid".format(expr[lnum - cnum : lnum]) ) return tfuncs
Pair delimiters.
def _pair_delims(expr, ldelim="(", rdelim=")"): """Pair delimiters.""" # Find where remaining delimiters are lindex = reversed([num for num, item in enumerate(expr) if item == ldelim]) rindex = [num for num, item in enumerate(expr) if item == rdelim] # Pair remaining delimiters return [(lpos, _next_rdelim(rindex, lpos)) for lpos in lindex][::-1]
Parse mathematical expression using PyParsing.
def _parse_expr(text, ldelim="(", rdelim=")"): """Parse mathematical expression using PyParsing.""" var = pyparsing.Word(pyparsing.alphas + "_", pyparsing.alphanums + "_") point = pyparsing.Literal(".") exp = pyparsing.CaselessLiteral("E") number = pyparsing.Combine( pyparsing.Word("+-" + pyparsing.nums, pyparsing.nums) + pyparsing.Optional(point + pyparsing.Optional(pyparsing.Word(pyparsing.nums))) + pyparsing.Optional( exp + pyparsing.Word("+-" + pyparsing.nums, pyparsing.nums) ) ) atom = var | number oplist = [ (pyparsing.Literal("**"), 2, pyparsing.opAssoc.RIGHT), (pyparsing.oneOf("+ - ~"), 1, pyparsing.opAssoc.RIGHT), (pyparsing.oneOf("* / // %"), 2, pyparsing.opAssoc.LEFT), (pyparsing.oneOf("+ -"), 2, pyparsing.opAssoc.LEFT), (pyparsing.oneOf("<< >>"), 2, pyparsing.opAssoc.LEFT), (pyparsing.Literal("&"), 2, pyparsing.opAssoc.LEFT), (pyparsing.Literal("^"), 2, pyparsing.opAssoc.LEFT), (pyparsing.Literal("|"), 2, pyparsing.opAssoc.LEFT), ] # Get functions expr = pyparsing.infixNotation( atom, oplist, lpar=pyparsing.Suppress(ldelim), rpar=pyparsing.Suppress(rdelim) ) return expr.parseString(text)[0]
Remove consecutive delimiters.
def _remove_consecutive_delims(expr, ldelim="(", rdelim=")"): """Remove consecutive delimiters.""" tpars = _pair_delims(expr, ldelim=ldelim, rdelim=rdelim) # Flag superfluous delimiters ddelim = [] for ctuple, ntuple in zip(tpars, tpars[1:]): if ctuple == (ntuple[0] - 1, ntuple[1] + 1): ddelim.extend(ntuple) ddelim.sort() # Actually remove delimiters from expression for num, item in enumerate(ddelim): expr = expr[: item - num] + expr[item - num + 1 :] # Get functions return expr
Remove unnecessary delimiters ( parenthesis brackets etc. ).
def _remove_extra_delims(expr, ldelim="(", rdelim=")", fcount=None): """ Remove unnecessary delimiters (parenthesis, brackets, etc.). Internal function that can be recursed """ if not expr.strip(): return "" fcount = [0] if fcount is None else fcount tfuncs = _get_functions(expr, ldelim=ldelim, rdelim=rdelim) # Replace function call with tokens for fdict in reversed(tfuncs): fcount[0] += 1 fdict["token"] = "__" + str(fcount[0]) expr = expr[: fdict["start"]] + fdict["token"] + expr[fdict["stop"] + 1 :] fdict["expr"] = _remove_extra_delims( fdict["expr"], ldelim=ldelim, rdelim=rdelim, fcount=fcount ) # Parse expression with function calls removed expr = _build_expr( _parse_expr(expr, ldelim=ldelim, rdelim=rdelim), ldelim=ldelim, rdelim=rdelim ) # Insert cleaned-up function calls for fdict in tfuncs: expr = expr.replace( fdict["token"], fdict["fname"] + ldelim + fdict["expr"] + rdelim ) return expr
Return list of the words in the string using count of a separator as delimiter.
def _split_every(text, sep, count, lstrip=False, rstrip=False): """ Return list of the words in the string, using count of a separator as delimiter. :param text: String to split :type text: string :param sep: Separator :type sep: string :param count: Number of separators to use as delimiter :type count: integer :param lstrip: Flag that indicates whether whitespace is removed from the beginning of each list item (True) or not (False) :type lstrip: boolean :param rstrip: Flag that indicates whether whitespace is removed from the end of each list item (True) or not (False) :type rstrip: boolean :rtype: tuple """ ltr = "_rl "[2 * lstrip + rstrip].strip() func = lambda x: getattr(x, ltr + "strip")() if ltr != "_" else x items = text.split(sep) groups = zip_longest(*[iter(items)] * count, fillvalue="") joints = (sep.join(group).rstrip(sep) for group in groups) return tuple(func(joint) for joint in joints)
Return tuple with mantissa and exponent of number formatted in engineering notation.
def _to_eng_tuple(number): """ Return tuple with mantissa and exponent of number formatted in engineering notation. :param number: Number :type number: integer or float :rtype: tuple """ # pylint: disable=W0141 # Helper function: split integer and fractional part of mantissa # + ljust ensures that integer part in engineering notation has # at most 3 digits (say if number given is 1E4) # + rstrip ensures that there is no empty fractional part split = lambda x, p: (x.ljust(3 + neg, "0")[:p], x[p:].rstrip("0")) # Convert number to scientific notation, a "constant" format mant, exp = to_scientific_tuple(number) mant, neg = mant.replace(".", ""), mant.startswith("-") # New values new_mant = ".".join(filter(None, split(mant, 1 + (exp % 3) + neg))) new_exp = int(3 * math.floor(exp / 3)) return NumComp(new_mant, new_exp)
r Convert number to string guaranteeing result is not in scientific notation.
def no_exp(number): r""" Convert number to string guaranteeing result is not in scientific notation. :param number: Number to convert :type number: integer or float :rtype: string .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for peng.functions.no_exp :raises: RuntimeError (Argument \`number\` is not valid) .. [[[end]]] """ mant, exp = to_scientific_tuple(number) if not exp: return str(number) floating_mant = "." in mant mant = mant.replace(".", "") if exp < 0: return "0." + "0" * (-exp - 1) + mant if not floating_mant: return mant + "0" * exp + (".0" if isinstance(number, float) else "") lfpart = len(mant) - 1 if lfpart < exp: return (mant + "0" * (exp - lfpart)).rstrip(".") return mant
r Convert a number to engineering notation.
def peng(number, frac_length, rjust=True): r""" Convert a number to engineering notation. The absolute value of the number (if it is not exactly zero) is bounded to the interval [1E-24, 1E+24) :param number: Number to convert :type number: integer or float :param frac_length: Number of digits of fractional part :type frac_length: `NonNegativeInteger <https://pexdoc.readthedocs.io/en/stable/ ptypes.html#nonnegativeinteger>`_ :param rjust: Flag that indicates whether the number is right-justified (True) or not (False) :type rjust: boolean :rtype: string .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for peng.functions.peng :raises: * RuntimeError (Argument \`frac_length\` is not valid) * RuntimeError (Argument \`number\` is not valid) * RuntimeError (Argument \`rjust\` is not valid) .. [[[end]]] The supported engineering suffixes are: +----------+-------+--------+ | Exponent | Name | Suffix | +==========+=======+========+ | 1E-24 | yocto | y | +----------+-------+--------+ | 1E-21 | zepto | z | +----------+-------+--------+ | 1E-18 | atto | a | +----------+-------+--------+ | 1E-15 | femto | f | +----------+-------+--------+ | 1E-12 | pico | p | +----------+-------+--------+ | 1E-9 | nano | n | +----------+-------+--------+ | 1E-6 | micro | u | +----------+-------+--------+ | 1E-3 | milli | m | +----------+-------+--------+ | 1E+0 | | | +----------+-------+--------+ | 1E+3 | kilo | k | +----------+-------+--------+ | 1E+6 | mega | M | +----------+-------+--------+ | 1E+9 | giga | G | +----------+-------+--------+ | 1E+12 | tera | T | +----------+-------+--------+ | 1E+15 | peta | P | +----------+-------+--------+ | 1E+18 | exa | E | +----------+-------+--------+ | 1E+21 | zetta | Z | +----------+-------+--------+ | 1E+24 | yotta | Y | +----------+-------+--------+ For example: >>> import peng >>> peng.peng(1235.6789E3, 3, False) '1.236M' """ # The decimal module has a to_eng_string() function, but it does not seem # to work well in all cases. For example: # >>> decimal.Decimal('34.5712233E8').to_eng_string() # '3.45712233E+9' # >>> decimal.Decimal('34.57122334E8').to_eng_string() # '3457122334' # It seems that the conversion function does not work in all cases # # Return formatted zero if number is zero, easier to not deal with this # special case through the rest of the algorithm if number == 0: number = "0.{zrs}".format(zrs="0" * frac_length) if frac_length else "0" # Engineering notation numbers can have a sign, a 3-digit integer part, # a period, and a fractional part of length frac_length, so the # length of the number to the left of, and including, the period is 5 return "{0} ".format(number.rjust(5 + frac_length)) if rjust else number # Low-bound number sign = +1 if number >= 0 else -1 ssign = "-" if sign == -1 else "" anumber = abs(number) if anumber < 1e-24: anumber = 1e-24 number = sign * 1e-24 # Round fractional part if requested frac_length is less than length # of fractional part. Rounding method is to add a '5' at the decimal # position just after the end of frac_length digits exp = 3.0 * math.floor(math.floor(math.log10(anumber)) / 3.0) mant = number / 10 ** exp # Because exponent is a float, mantissa is a float and its string # representation always includes a period smant = str(mant) ppos = smant.find(".") if len(smant) - ppos - 1 > frac_length: mant += sign * 5 * 10 ** (-frac_length - 1) if abs(mant) >= 1000: exp += 3 mant = mant / 1e3 smant = str(mant) ppos = smant.find(".") # Make fractional part have frac_length digits bfrac_length = bool(frac_length) flength = ppos - (not bfrac_length) + frac_length + 1 new_mant = smant[:flength].ljust(flength, "0") # Upper-bound number if exp > 24: new_mant, exp = ( "{sign}999.{frac}".format(sign=ssign, frac="9" * frac_length), 24, ) # Right-justify number, engineering notation numbers can have a sign, # a 3-digit integer part and a period, and a fractional part of length # frac_length, so the length of the number to the left of the # period is 4 new_mant = new_mant.rjust(rjust * (4 + bfrac_length + frac_length)) # Format number num = "{mant}{suffix}".format( mant=new_mant, suffix=_POWER_TO_SUFFIX_DICT[exp] if exp else " " * bool(rjust) ) return num
r Return floating point equivalent of a number represented in engineering notation.
def peng_float(snum): r""" Return floating point equivalent of a number represented in engineering notation. :param snum: Number :type snum: :ref:`EngineeringNotationNumber` :rtype: string .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. peng.functions.peng_float :raises: RuntimeError (Argument \`snum\` is not valid) .. [[[end]]] For example: >>> import peng >>> peng.peng_float(peng.peng(1235.6789E3, 3, False)) 1236000.0 """ # This can be coded as peng_mant(snum)*(peng_power(snum)[1]), but the # "function unrolling" is about 4x faster snum = snum.rstrip() power = _SUFFIX_POWER_DICT[" " if snum[-1].isdigit() else snum[-1]] return float(snum if snum[-1].isdigit() else snum[:-1]) * power
r Return the fractional part of a number represented in engineering notation.
def peng_frac(snum): r""" Return the fractional part of a number represented in engineering notation. :param snum: Number :type snum: :ref:`EngineeringNotationNumber` :rtype: integer .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. peng.functions.peng_frac :raises: RuntimeError (Argument \`snum\` is not valid) .. [[[end]]] For example: >>> import peng >>> peng.peng_frac(peng.peng(1235.6789E3, 3, False)) 236 """ snum = snum.rstrip() pindex = snum.find(".") if pindex == -1: return 0 return int(snum[pindex + 1 :] if snum[-1].isdigit() else snum[pindex + 1 : -1])
r Return the mantissa of a number represented in engineering notation.
def peng_mant(snum): r""" Return the mantissa of a number represented in engineering notation. :param snum: Number :type snum: :ref:`EngineeringNotationNumber` :rtype: float .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. peng.functions.peng_mant :raises: RuntimeError (Argument \`snum\` is not valid) .. [[[end]]] For example: >>> import peng >>> peng.peng_mant(peng.peng(1235.6789E3, 3, False)) 1.236 """ snum = snum.rstrip() return float(snum if snum[-1].isdigit() else snum[:-1])
r Return engineering suffix and its floating point equivalent of a number.
def peng_power(snum): r""" Return engineering suffix and its floating point equivalent of a number. :py:func:`peng.peng` lists the correspondence between suffix and floating point exponent. :param snum: Number :type snum: :ref:`EngineeringNotationNumber` :rtype: named tuple in which the first item is the engineering suffix and the second item is the floating point equivalent of the suffix when the number is represented in engineering notation. .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. peng.functions.peng_power :raises: RuntimeError (Argument \`snum\` is not valid) .. [[[end]]] For example: >>> import peng >>> peng.peng_power(peng.peng(1235.6789E3, 3, False)) EngPower(suffix='M', exp=1000000.0) """ suffix = " " if snum[-1].isdigit() else snum[-1] return EngPower(suffix, _SUFFIX_POWER_DICT[suffix])
r Return engineering suffix from a starting suffix and an number of suffixes offset.
def peng_suffix_math(suffix, offset): r""" Return engineering suffix from a starting suffix and an number of suffixes offset. :param suffix: Engineering suffix :type suffix: :ref:`EngineeringNotationSuffix` :param offset: Engineering suffix offset :type offset: integer :rtype: string .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. peng.functions.peng_suffix_math :raises: * RuntimeError (Argument \`offset\` is not valid) * RuntimeError (Argument \`suffix\` is not valid) * ValueError (Argument \`offset\` is not valid) .. [[[end]]] For example: >>> import peng >>> peng.peng_suffix_math('u', 6) 'T' """ # pylint: disable=W0212 eobj = pexdoc.exh.addex(ValueError, "Argument `offset` is not valid") try: return _POWER_TO_SUFFIX_DICT[_SUFFIX_TO_POWER_DICT[suffix] + 3 * offset] except KeyError: eobj(True)
r Remove unnecessary delimiters in mathematical expressions.
def remove_extra_delims(expr, ldelim="(", rdelim=")"): r""" Remove unnecessary delimiters in mathematical expressions. Delimiters (parenthesis, brackets, etc.) may be removed either because there are multiple consecutive delimiters enclosing a single expressions or because the delimiters are implied by operator precedence rules. Function names must start with a letter and then can contain alphanumeric characters and a maximum of one underscore :param expr: Mathematical expression :type expr: string :param ldelim: Single character left delimiter :type ldelim: string :param rdelim: Single character right delimiter :type rdelim: string :rtype: string :raises: * RuntimeError (Argument \`expr\` is not valid) * RuntimeError (Argument \`ldelim\` is not valid) * RuntimeError (Argument \`rdelim\` is not valid) * RuntimeError (Function name `*[function_name]*` is not valid) * RuntimeError (Mismatched delimiters) """ op_group = "" for item1 in _OP_PREC: if isinstance(item1, list): for item2 in item1: op_group += item2 else: op_group += item1 iobj = zip([expr, ldelim, rdelim], ["expr", "ldelim", "rdelim"]) for item, desc in iobj: if not isinstance(item, str): raise RuntimeError("Argument `{0}` is not valid".format(desc)) if (len(ldelim) != 1) or ((len(ldelim) == 1) and (ldelim in op_group)): raise RuntimeError("Argument `ldelim` is not valid") if (len(rdelim) != 1) or ((len(rdelim) == 1) and (rdelim in op_group)): raise RuntimeError("Argument `rdelim` is not valid") if expr.count(ldelim) != expr.count(rdelim): raise RuntimeError("Mismatched delimiters") if not expr: return expr vchars = ( "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ".0123456789" r"_()[]\{\}" + rdelim + ldelim + op_group ) if any([item not in vchars for item in expr]) or ("__" in expr): raise RuntimeError("Argument `expr` is not valid") expr = _remove_consecutive_delims(expr, ldelim=ldelim, rdelim=rdelim) expr = expr.replace(ldelim + rdelim, "") return _remove_extra_delims(expr, ldelim=ldelim, rdelim=rdelim)