partition
stringclasses 3
values | func_name
stringlengths 1
134
| docstring
stringlengths 1
46.9k
| path
stringlengths 4
223
| original_string
stringlengths 75
104k
| code
stringlengths 75
104k
| docstring_tokens
listlengths 1
1.97k
| repo
stringlengths 7
55
| language
stringclasses 1
value | url
stringlengths 87
315
| code_tokens
listlengths 19
28.4k
| sha
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|
test
|
run_trace
|
Run module tracing.
|
docs/support/trace_support.py
|
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)
|
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)
|
[
"Run",
"module",
"tracing",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/docs/support/trace_support.py#L51-L108
|
[
"def",
"run_trace",
"(",
"mname",
",",
"fname",
",",
"module_prefix",
",",
"callable_names",
",",
"no_print",
",",
"module_exclude",
"=",
"None",
",",
"callable_exclude",
"=",
"None",
",",
"debug",
"=",
"False",
",",
")",
":",
"# 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",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
YOURLSAPIMixin.shorten
|
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.
|
yourls/core.py
|
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
|
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
|
[
"Shorten",
"URL",
"with",
"optional",
"keyword",
"and",
"title",
"."
] |
RazerM/yourls-python
|
python
|
https://github.com/RazerM/yourls-python/blob/716845562a2bbb430de3c379c9481b195e451ccf/yourls/core.py#L38-L81
|
[
"def",
"shorten",
"(",
"self",
",",
"url",
",",
"keyword",
"=",
"None",
",",
"title",
"=",
"None",
")",
":",
"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"
] |
716845562a2bbb430de3c379c9481b195e451ccf
|
test
|
YOURLSAPIMixin.expand
|
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.
|
yourls/core.py
|
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']
|
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']
|
[
"Expand",
"short",
"URL",
"or",
"keyword",
"to",
"long",
"URL",
"."
] |
RazerM/yourls-python
|
python
|
https://github.com/RazerM/yourls-python/blob/716845562a2bbb430de3c379c9481b195e451ccf/yourls/core.py#L83-L100
|
[
"def",
"expand",
"(",
"self",
",",
"short",
")",
":",
"data",
"=",
"dict",
"(",
"action",
"=",
"'expand'",
",",
"shorturl",
"=",
"short",
")",
"jsondata",
"=",
"self",
".",
"_api_request",
"(",
"params",
"=",
"data",
")",
"return",
"jsondata",
"[",
"'longurl'",
"]"
] |
716845562a2bbb430de3c379c9481b195e451ccf
|
test
|
YOURLSAPIMixin.url_stats
|
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.
|
yourls/core.py
|
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'])
|
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",
"for",
"short",
"URL",
"or",
"keyword",
"."
] |
RazerM/yourls-python
|
python
|
https://github.com/RazerM/yourls-python/blob/716845562a2bbb430de3c379c9481b195e451ccf/yourls/core.py#L102-L119
|
[
"def",
"url_stats",
"(",
"self",
",",
"short",
")",
":",
"data",
"=",
"dict",
"(",
"action",
"=",
"'url-stats'",
",",
"shorturl",
"=",
"short",
")",
"jsondata",
"=",
"self",
".",
"_api_request",
"(",
"params",
"=",
"data",
")",
"return",
"_json_to_shortened_url",
"(",
"jsondata",
"[",
"'link'",
"]",
")"
] |
716845562a2bbb430de3c379c9481b195e451ccf
|
test
|
YOURLSAPIMixin.stats
|
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
|
yourls/core.py
|
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
|
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",
"stats",
"about",
"links",
"."
] |
RazerM/yourls-python
|
python
|
https://github.com/RazerM/yourls-python/blob/716845562a2bbb430de3c379c9481b195e451ccf/yourls/core.py#L121-L164
|
[
"def",
"stats",
"(",
"self",
",",
"filter",
",",
"limit",
",",
"start",
"=",
"None",
")",
":",
"# 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"
] |
716845562a2bbb430de3c379c9481b195e451ccf
|
test
|
YOURLSAPIMixin.db_stats
|
Get database statistics.
Returns:
DBStats: Total clicks and links statistics.
Raises:
requests.exceptions.HTTPError: Generic HTTP Error
|
yourls/core.py
|
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
|
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
|
[
"Get",
"database",
"statistics",
"."
] |
RazerM/yourls-python
|
python
|
https://github.com/RazerM/yourls-python/blob/716845562a2bbb430de3c379c9481b195e451ccf/yourls/core.py#L166-L181
|
[
"def",
"db_stats",
"(",
"self",
")",
":",
"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"
] |
716845562a2bbb430de3c379c9481b195e451ccf
|
test
|
ste
|
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]
...
.. ]]]
|
docs/support/term_echo.py
|
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,
)
|
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,
)
|
[
"r",
"Echo",
"terminal",
"output",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/docs/support/term_echo.py#L15-L65
|
[
"def",
"ste",
"(",
"command",
",",
"nindent",
",",
"mdir",
",",
"fpointer",
")",
":",
"term_echo",
"(",
"\"${{PMISC_DIR}}{sep}pypkg{sep}{cmd}\"",
".",
"format",
"(",
"sep",
"=",
"os",
".",
"path",
".",
"sep",
",",
"cmd",
"=",
"command",
")",
",",
"nindent",
",",
"{",
"\"PMISC_DIR\"",
":",
"mdir",
"}",
",",
"fpointer",
",",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
term_echo
|
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
|
docs/support/term_echo.py
|
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)
|
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)
|
[
"Print",
"STDOUT",
"resulting",
"from",
"a",
"Bash",
"shell",
"command",
"formatted",
"in",
"reStructuredText",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/docs/support/term_echo.py#L68-L124
|
[
"def",
"term_echo",
"(",
"command",
",",
"nindent",
"=",
"0",
",",
"env",
"=",
"None",
",",
"fpointer",
"=",
"None",
",",
"cols",
"=",
"60",
")",
":",
"# 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",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
Command.log
|
Small log helper
|
systemjs/management/commands/systemjs_bundle.py
|
def log(self, msg, level=2):
"""
Small log helper
"""
if self.verbosity >= level:
self.stdout.write(msg)
|
def log(self, msg, level=2):
"""
Small log helper
"""
if self.verbosity >= level:
self.stdout.write(msg)
|
[
"Small",
"log",
"helper"
] |
sergei-maertens/django-systemjs
|
python
|
https://github.com/sergei-maertens/django-systemjs/blob/efd4a3862a39d9771609a25a5556f36023cf6e5c/systemjs/management/commands/systemjs_bundle.py#L26-L31
|
[
"def",
"log",
"(",
"self",
",",
"msg",
",",
"level",
"=",
"2",
")",
":",
"if",
"self",
".",
"verbosity",
">=",
"level",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"msg",
")"
] |
efd4a3862a39d9771609a25a5556f36023cf6e5c
|
test
|
cached
|
alternative to reify and property decorators. caches the value when it's
generated. It cashes it as instance._name_of_the_property.
|
libaaron/libaaron.py
|
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
|
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
|
[
"alternative",
"to",
"reify",
"and",
"property",
"decorators",
".",
"caches",
"the",
"value",
"when",
"it",
"s",
"generated",
".",
"It",
"cashes",
"it",
"as",
"instance",
".",
"_name_of_the_property",
"."
] |
ninjaaron/libaaron
|
python
|
https://github.com/ninjaaron/libaaron/blob/a2ee417b784ca72c89c05bddb2e3e815a6b95154/libaaron/libaaron.py#L42-L57
|
[
"def",
"cached",
"(",
"method",
")",
"->",
"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"
] |
a2ee417b784ca72c89c05bddb2e3e815a6b95154
|
test
|
chunkiter
|
break an iterable into chunks and yield those chunks as lists
until there's nothing left to yeild.
|
libaaron/libaaron.py
|
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
|
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
|
[
"break",
"an",
"iterable",
"into",
"chunks",
"and",
"yield",
"those",
"chunks",
"as",
"lists",
"until",
"there",
"s",
"nothing",
"left",
"to",
"yeild",
"."
] |
ninjaaron/libaaron
|
python
|
https://github.com/ninjaaron/libaaron/blob/a2ee417b784ca72c89c05bddb2e3e815a6b95154/libaaron/libaaron.py#L66-L72
|
[
"def",
"chunkiter",
"(",
"iterable",
",",
"chunksize",
")",
":",
"iterator",
"=",
"iter",
"(",
"iterable",
")",
"for",
"chunk",
"in",
"iter",
"(",
"lambda",
":",
"list",
"(",
"itertools",
".",
"islice",
"(",
"iterator",
",",
"chunksize",
")",
")",
",",
"[",
"]",
")",
":",
"yield",
"chunk"
] |
a2ee417b784ca72c89c05bddb2e3e815a6b95154
|
test
|
chunkprocess
|
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.
|
libaaron/libaaron.py
|
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
|
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
|
[
"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",
"."
] |
ninjaaron/libaaron
|
python
|
https://github.com/ninjaaron/libaaron/blob/a2ee417b784ca72c89c05bddb2e3e815a6b95154/libaaron/libaaron.py#L75-L87
|
[
"def",
"chunkprocess",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"iterable",
",",
"chunksize",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"chunk",
"in",
"chunkiter",
"(",
"iterable",
",",
"chunksize",
")",
":",
"yield",
"func",
"(",
"chunk",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapper"
] |
a2ee417b784ca72c89c05bddb2e3e815a6b95154
|
test
|
flatten
|
recursively flatten nested objects
|
libaaron/libaaron.py
|
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)
|
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)
|
[
"recursively",
"flatten",
"nested",
"objects"
] |
ninjaaron/libaaron
|
python
|
https://github.com/ninjaaron/libaaron/blob/a2ee417b784ca72c89c05bddb2e3e815a6b95154/libaaron/libaaron.py#L112-L121
|
[
"def",
"flatten",
"(",
"iterable",
",",
"map2iter",
"=",
"None",
")",
":",
"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",
")"
] |
a2ee417b784ca72c89c05bddb2e3e815a6b95154
|
test
|
deepupdate
|
update one dictionary from another recursively. Only individual
values will be overwritten--not entire branches of nested
dictionaries.
|
libaaron/libaaron.py
|
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, ())
|
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, ())
|
[
"update",
"one",
"dictionary",
"from",
"another",
"recursively",
".",
"Only",
"individual",
"values",
"will",
"be",
"overwritten",
"--",
"not",
"entire",
"branches",
"of",
"nested",
"dictionaries",
"."
] |
ninjaaron/libaaron
|
python
|
https://github.com/ninjaaron/libaaron/blob/a2ee417b784ca72c89c05bddb2e3e815a6b95154/libaaron/libaaron.py#L124-L155
|
[
"def",
"deepupdate",
"(",
"mapping",
":",
"abc",
".",
"MutableMapping",
",",
"other",
":",
"abc",
".",
"Mapping",
",",
"listextend",
"=",
"False",
")",
":",
"def",
"inner",
"(",
"other",
",",
"previouskeys",
")",
":",
"\"\"\"previouskeys is a tuple that stores all the names of keys\n we've recursed into so far so it can they can be looked up\n recursively on the pimary mapping when a value needs updateing.\n \"\"\"",
"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",
",",
"(",
")",
")"
] |
a2ee417b784ca72c89c05bddb2e3e815a6b95154
|
test
|
quietinterrupt
|
add a handler for SIGINT that optionally prints a given message.
For stopping scripts without having to see the stacktrace.
|
libaaron/libaaron.py
|
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)
|
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)
|
[
"add",
"a",
"handler",
"for",
"SIGINT",
"that",
"optionally",
"prints",
"a",
"given",
"message",
".",
"For",
"stopping",
"scripts",
"without",
"having",
"to",
"see",
"the",
"stacktrace",
"."
] |
ninjaaron/libaaron
|
python
|
https://github.com/ninjaaron/libaaron/blob/a2ee417b784ca72c89c05bddb2e3e815a6b95154/libaaron/libaaron.py#L158-L168
|
[
"def",
"quietinterrupt",
"(",
"msg",
"=",
"None",
")",
":",
"def",
"handler",
"(",
")",
":",
"if",
"msg",
":",
"print",
"(",
"msg",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"handler",
")"
] |
a2ee417b784ca72c89c05bddb2e3e815a6b95154
|
test
|
printtsv
|
stupidly print an iterable of iterables in TSV format
|
libaaron/libaaron.py
|
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)
|
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)
|
[
"stupidly",
"print",
"an",
"iterable",
"of",
"iterables",
"in",
"TSV",
"format"
] |
ninjaaron/libaaron
|
python
|
https://github.com/ninjaaron/libaaron/blob/a2ee417b784ca72c89c05bddb2e3e815a6b95154/libaaron/libaaron.py#L236-L239
|
[
"def",
"printtsv",
"(",
"table",
",",
"sep",
"=",
"\"\\t\"",
",",
"file",
"=",
"sys",
".",
"stdout",
")",
":",
"for",
"record",
"in",
"table",
":",
"print",
"(",
"*",
"record",
",",
"sep",
"=",
"sep",
",",
"file",
"=",
"file",
")"
] |
a2ee417b784ca72c89c05bddb2e3e815a6b95154
|
test
|
mkdummy
|
Make a placeholder object that uses its own name for its repr
|
libaaron/libaaron.py
|
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)
)()
|
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)
)()
|
[
"Make",
"a",
"placeholder",
"object",
"that",
"uses",
"its",
"own",
"name",
"for",
"its",
"repr"
] |
ninjaaron/libaaron
|
python
|
https://github.com/ninjaaron/libaaron/blob/a2ee417b784ca72c89c05bddb2e3e815a6b95154/libaaron/libaaron.py#L242-L246
|
[
"def",
"mkdummy",
"(",
"name",
",",
"*",
"*",
"attrs",
")",
":",
"return",
"type",
"(",
"name",
",",
"(",
")",
",",
"dict",
"(",
"__repr__",
"=",
"(",
"lambda",
"self",
":",
"\"<%s>\"",
"%",
"name",
")",
",",
"*",
"*",
"attrs",
")",
")",
"(",
")"
] |
a2ee417b784ca72c89c05bddb2e3e815a6b95154
|
test
|
pipe
|
pipe(value, f, g, h) == h(g(f(value)))
|
libaaron/libaaron.py
|
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
|
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
|
[
"pipe",
"(",
"value",
"f",
"g",
"h",
")",
"==",
"h",
"(",
"g",
"(",
"f",
"(",
"value",
")))"
] |
ninjaaron/libaaron
|
python
|
https://github.com/ninjaaron/libaaron/blob/a2ee417b784ca72c89c05bddb2e3e815a6b95154/libaaron/libaaron.py#L249-L255
|
[
"def",
"pipe",
"(",
"value",
",",
"*",
"functions",
",",
"funcs",
"=",
"None",
")",
":",
"if",
"funcs",
":",
"functions",
"=",
"funcs",
"for",
"function",
"in",
"functions",
":",
"value",
"=",
"function",
"(",
"value",
")",
"return",
"value"
] |
a2ee417b784ca72c89c05bddb2e3e815a6b95154
|
test
|
pipeline
|
like pipe, but curried:
pipline(f, g, h)(*args, **kwargs) == h(g(f(*args, **kwargs)))
|
libaaron/libaaron.py
|
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)
|
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)
|
[
"like",
"pipe",
"but",
"curried",
":"
] |
ninjaaron/libaaron
|
python
|
https://github.com/ninjaaron/libaaron/blob/a2ee417b784ca72c89c05bddb2e3e815a6b95154/libaaron/libaaron.py#L258-L266
|
[
"def",
"pipeline",
"(",
"*",
"functions",
",",
"funcs",
"=",
"None",
")",
":",
"if",
"funcs",
":",
"functions",
"=",
"funcs",
"head",
",",
"",
"*",
"tail",
"=",
"functions",
"return",
"lambda",
"*",
"args",
",",
"*",
"*",
"kwargs",
":",
"pipe",
"(",
"head",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
",",
"funcs",
"=",
"tail",
")"
] |
a2ee417b784ca72c89c05bddb2e3e815a6b95154
|
test
|
PBytes.human_readable
|
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.
|
libaaron/libaaron.py
|
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()
|
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()
|
[
"returns",
"the",
"size",
"of",
"size",
"as",
"a",
"tuple",
"of",
":"
] |
ninjaaron/libaaron
|
python
|
https://github.com/ninjaaron/libaaron/blob/a2ee417b784ca72c89c05bddb2e3e815a6b95154/libaaron/libaaron.py#L194-L209
|
[
"def",
"human_readable",
"(",
"self",
",",
"decimal",
"=",
"False",
")",
":",
"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",
"(",
")"
] |
a2ee417b784ca72c89c05bddb2e3e815a6b95154
|
test
|
PBytes.from_str
|
attempt to parse a size in bytes from a human-readable string.
|
libaaron/libaaron.py
|
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()]))
|
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()]))
|
[
"attempt",
"to",
"parse",
"a",
"size",
"in",
"bytes",
"from",
"a",
"human",
"-",
"readable",
"string",
"."
] |
ninjaaron/libaaron
|
python
|
https://github.com/ninjaaron/libaaron/blob/a2ee417b784ca72c89c05bddb2e3e815a6b95154/libaaron/libaaron.py#L212-L228
|
[
"def",
"from_str",
"(",
"cls",
",",
"human_readable_str",
",",
"decimal",
"=",
"False",
",",
"bits",
"=",
"False",
")",
":",
"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",
"(",
")",
"]",
")",
")"
] |
a2ee417b784ca72c89c05bddb2e3e815a6b95154
|
test
|
cli
|
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
|
yourls/__main__.py
|
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'")
|
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'")
|
[
"Command",
"line",
"interface",
"for",
"YOURLS",
"."
] |
RazerM/yourls-python
|
python
|
https://github.com/RazerM/yourls-python/blob/716845562a2bbb430de3c379c9481b195e451ccf/yourls/__main__.py#L105-L134
|
[
"def",
"cli",
"(",
"ctx",
",",
"apiurl",
",",
"signature",
",",
"username",
",",
"password",
")",
":",
"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'\"",
")"
] |
716845562a2bbb430de3c379c9481b195e451ccf
|
test
|
trace_module
|
Trace eng wave module exceptions.
|
docs/support/trace_ex_eng_wave_core.py
|
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
)
|
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
)
|
[
"Trace",
"eng",
"wave",
"module",
"exceptions",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/docs/support/trace_ex_eng_wave_core.py#L9-L17
|
[
"def",
"trace_module",
"(",
"no_print",
"=",
"True",
")",
":",
"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",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
def_links
|
Define Sphinx requirements links.
|
docs/support/requirements_to_rst.py
|
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))
|
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))
|
[
"Define",
"Sphinx",
"requirements",
"links",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/docs/support/requirements_to_rst.py#L22-L37
|
[
"def",
"def_links",
"(",
"mobj",
")",
":",
"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",
")",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
make_common_entry
|
Generate Python interpreter version entries for 2.x or 3.x series.
|
docs/support/requirements_to_rst.py
|
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)))
|
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",
"for",
"2",
".",
"x",
"or",
"3",
".",
"x",
"series",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/docs/support/requirements_to_rst.py#L40-L43
|
[
"def",
"make_common_entry",
"(",
"plist",
",",
"pyver",
",",
"suffix",
",",
"req_ver",
")",
":",
"prefix",
"=",
"\"Python {pyver}.x{suffix}\"",
".",
"format",
"(",
"pyver",
"=",
"pyver",
",",
"suffix",
"=",
"suffix",
")",
"plist",
".",
"append",
"(",
"\"{prefix}{ver}\"",
".",
"format",
"(",
"prefix",
"=",
"prefix",
",",
"ver",
"=",
"ops_to_words",
"(",
"req_ver",
")",
")",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
make_multi_entry
|
Generate Python interpreter version entries.
|
docs/support/requirements_to_rst.py
|
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])))
|
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])))
|
[
"Generate",
"Python",
"interpreter",
"version",
"entries",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/docs/support/requirements_to_rst.py#L46-L50
|
[
"def",
"make_multi_entry",
"(",
"plist",
",",
"pkg_pyvers",
",",
"ver_dict",
")",
":",
"for",
"pyver",
"in",
"pkg_pyvers",
":",
"pver",
"=",
"pyver",
"[",
"2",
"]",
"+",
"\".\"",
"+",
"pyver",
"[",
"3",
":",
"]",
"plist",
".",
"append",
"(",
"\"Python {0}: {1}\"",
".",
"format",
"(",
"pver",
",",
"ops_to_words",
"(",
"ver_dict",
"[",
"pyver",
"]",
")",
")",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
op_to_words
|
Translate >=, ==, <= to words.
|
docs/support/requirements_to_rst.py
|
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")
|
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",
">",
"=",
"==",
"<",
"=",
"to",
"words",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/docs/support/requirements_to_rst.py#L53-L74
|
[
"def",
"op_to_words",
"(",
"item",
")",
":",
"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\"",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
ops_to_words
|
Translate requirement specification to words.
|
docs/support/requirements_to_rst.py
|
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])
|
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])
|
[
"Translate",
"requirement",
"specification",
"to",
"words",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/docs/support/requirements_to_rst.py#L77-L102
|
[
"def",
"ops_to_words",
"(",
"item",
")",
":",
"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",
"]",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
proc_requirements
|
Get requirements in reStructuredText format.
|
docs/support/requirements_to_rst.py
|
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")
|
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")
|
[
"Get",
"requirements",
"in",
"reStructuredText",
"format",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/docs/support/requirements_to_rst.py#L105-L207
|
[
"def",
"proc_requirements",
"(",
"mobj",
")",
":",
"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\"",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
_make_version
|
Generate version string from tuple (almost entirely from coveragepy).
|
peng/pkgdata.py
|
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
|
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
|
[
"Generate",
"version",
"string",
"from",
"tuple",
"(",
"almost",
"entirely",
"from",
"coveragepy",
")",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/pkgdata.py#L121-L131
|
[
"def",
"_make_version",
"(",
"major",
",",
"minor",
",",
"micro",
",",
"level",
",",
"serial",
")",
":",
"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"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
_chunk_noise
|
Chunk input noise data into valid Touchstone file rows.
|
peng/touchstone.py
|
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
|
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",
"noise",
"data",
"into",
"valid",
"Touchstone",
"file",
"rows",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/touchstone.py#L40-L50
|
[
"def",
"_chunk_noise",
"(",
"noise",
")",
":",
"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"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
_chunk_pars
|
Chunk input data into valid Touchstone file rows.
|
peng/touchstone.py
|
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
|
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
|
[
"Chunk",
"input",
"data",
"into",
"valid",
"Touchstone",
"file",
"rows",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/touchstone.py#L53-L75
|
[
"def",
"_chunk_pars",
"(",
"freq_vector",
",",
"data_matrix",
",",
"pformat",
")",
":",
"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"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
read_touchstone
|
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
|
peng/touchstone.py
|
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)
|
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",
"Read",
"a",
"Touchstone",
"<https",
":",
"//",
"ibis",
".",
"org",
"/",
"connector",
"/",
"touchstone_spec11",
".",
"pdf",
">",
"_",
"file",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/touchstone.py#L79-L278
|
[
"def",
"read_touchstone",
"(",
"fname",
")",
":",
"# 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",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
write_touchstone
|
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]]]
|
peng/touchstone.py
|
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")
|
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")
|
[
"r",
"Write",
"a",
"Touchstone",
"_",
"file",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/touchstone.py#L289-L395
|
[
"def",
"write_touchstone",
"(",
"fname",
",",
"options",
",",
"data",
",",
"noise",
"=",
"None",
",",
"frac_length",
"=",
"10",
",",
"exp_length",
"=",
"2",
")",
":",
"# 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\"",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
_bound_waveform
|
Add independent variable vector bounds if they are not in vector.
|
peng/wave_functions.py
|
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]
|
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]
|
[
"Add",
"independent",
"variable",
"vector",
"bounds",
"if",
"they",
"are",
"not",
"in",
"vector",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L48-L64
|
[
"def",
"_bound_waveform",
"(",
"wave",
",",
"indep_min",
",",
"indep_max",
")",
":",
"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",
"]"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
_build_units
|
Build unit math operations.
|
peng/wave_functions.py
|
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))
|
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))
|
[
"Build",
"unit",
"math",
"operations",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L67-L79
|
[
"def",
"_build_units",
"(",
"indep_units",
",",
"dep_units",
",",
"op",
")",
":",
"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",
")",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
_operation
|
Perform generic operation on a waveform object.
|
peng/wave_functions.py
|
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
|
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
|
[
"Perform",
"generic",
"operation",
"on",
"a",
"waveform",
"object",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L82-L88
|
[
"def",
"_operation",
"(",
"wave",
",",
"desc",
",",
"units",
",",
"fpointer",
")",
":",
"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"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
_running_area
|
Calculate running area under curve.
|
peng/wave_functions.py
|
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)))
|
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)))
|
[
"Calculate",
"running",
"area",
"under",
"curve",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L91-L98
|
[
"def",
"_running_area",
"(",
"indep_vector",
",",
"dep_vector",
")",
":",
"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",
")",
")",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
_validate_min_max
|
Validate min and max bounds are within waveform's independent variable vector.
|
peng/wave_functions.py
|
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
|
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
|
[
"Validate",
"min",
"and",
"max",
"bounds",
"are",
"within",
"waveform",
"s",
"independent",
"variable",
"vector",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L101-L130
|
[
"def",
"_validate_min_max",
"(",
"wave",
",",
"indep_min",
",",
"indep_max",
")",
":",
"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"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
acos
|
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]]]
|
peng/wave_functions.py
|
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)
|
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",
"arc",
"cosine",
"of",
"a",
"waveform",
"s",
"dependent",
"variable",
"vector",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L134-L159
|
[
"def",
"acos",
"(",
"wave",
")",
":",
"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",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
acosh
|
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]]]
|
peng/wave_functions.py
|
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)
|
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",
"hyperbolic",
"arc",
"cosine",
"of",
"a",
"waveform",
"s",
"dependent",
"variable",
"vector",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L163-L184
|
[
"def",
"acosh",
"(",
"wave",
")",
":",
"pexdoc",
".",
"exh",
".",
"addex",
"(",
"ValueError",
",",
"\"Math domain error\"",
",",
"bool",
"(",
"min",
"(",
"wave",
".",
"_dep_vector",
")",
"<",
"1",
")",
")",
"return",
"_operation",
"(",
"wave",
",",
"\"acosh\"",
",",
"\"\"",
",",
"np",
".",
"arccosh",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
asin
|
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]]]
|
peng/wave_functions.py
|
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)
|
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",
"arc",
"sine",
"of",
"a",
"waveform",
"s",
"dependent",
"variable",
"vector",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L188-L213
|
[
"def",
"asin",
"(",
"wave",
")",
":",
"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",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
atanh
|
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]]]
|
peng/wave_functions.py
|
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)
|
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",
"hyperbolic",
"arc",
"tangent",
"of",
"a",
"waveform",
"s",
"dependent",
"variable",
"vector",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L259-L284
|
[
"def",
"atanh",
"(",
"wave",
")",
":",
"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",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
average
|
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]]]
|
peng/wave_functions.py
|
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
|
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",
"the",
"running",
"average",
"of",
"a",
"waveform",
"s",
"dependent",
"variable",
"vector",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L290-L329
|
[
"def",
"average",
"(",
"wave",
",",
"indep_min",
"=",
"None",
",",
"indep_max",
"=",
"None",
")",
":",
"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"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
db
|
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]]]
|
peng/wave_functions.py
|
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
|
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",
"a",
"waveform",
"s",
"dependent",
"variable",
"vector",
"expressed",
"in",
"decibels",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L395-L421
|
[
"def",
"db",
"(",
"wave",
")",
":",
"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"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
derivative
|
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]]]
|
peng/wave_functions.py
|
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
|
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",
"numerical",
"derivative",
"of",
"a",
"waveform",
"s",
"dependent",
"variable",
"vector",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L427-L471
|
[
"def",
"derivative",
"(",
"wave",
",",
"indep_min",
"=",
"None",
",",
"indep_max",
"=",
"None",
")",
":",
"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"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
fft
|
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]]]
|
peng/wave_functions.py
|
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="",
)
|
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",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L500-L562
|
[
"def",
"fft",
"(",
"wave",
",",
"npoints",
"=",
"None",
",",
"indep_min",
"=",
"None",
",",
"indep_max",
"=",
"None",
")",
":",
"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",
"=",
"\"\"",
",",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
fftdb
|
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]]]
|
peng/wave_functions.py
|
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))
|
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",
"Fast",
"Fourier",
"Transform",
"of",
"a",
"waveform",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L571-L615
|
[
"def",
"fftdb",
"(",
"wave",
",",
"npoints",
"=",
"None",
",",
"indep_min",
"=",
"None",
",",
"indep_max",
"=",
"None",
")",
":",
"return",
"db",
"(",
"fft",
"(",
"wave",
",",
"npoints",
",",
"indep_min",
",",
"indep_max",
")",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
ffti
|
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]]]
|
peng/wave_functions.py
|
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))
|
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",
"imaginary",
"part",
"of",
"the",
"Fast",
"Fourier",
"Transform",
"of",
"a",
"waveform",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L624-L666
|
[
"def",
"ffti",
"(",
"wave",
",",
"npoints",
"=",
"None",
",",
"indep_min",
"=",
"None",
",",
"indep_max",
"=",
"None",
")",
":",
"return",
"imag",
"(",
"fft",
"(",
"wave",
",",
"npoints",
",",
"indep_min",
",",
"indep_max",
")",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
fftm
|
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]]]
|
peng/wave_functions.py
|
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))
|
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",
"magnitude",
"of",
"the",
"Fast",
"Fourier",
"Transform",
"of",
"a",
"waveform",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L675-L717
|
[
"def",
"fftm",
"(",
"wave",
",",
"npoints",
"=",
"None",
",",
"indep_min",
"=",
"None",
",",
"indep_max",
"=",
"None",
")",
":",
"return",
"abs",
"(",
"fft",
"(",
"wave",
",",
"npoints",
",",
"indep_min",
",",
"indep_max",
")",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
fftp
|
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]]]
|
peng/wave_functions.py
|
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)
|
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",
"phase",
"of",
"the",
"Fast",
"Fourier",
"Transform",
"of",
"a",
"waveform",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L728-L782
|
[
"def",
"fftp",
"(",
"wave",
",",
"npoints",
"=",
"None",
",",
"indep_min",
"=",
"None",
",",
"indep_max",
"=",
"None",
",",
"unwrap",
"=",
"True",
",",
"rad",
"=",
"True",
")",
":",
"return",
"phase",
"(",
"fft",
"(",
"wave",
",",
"npoints",
",",
"indep_min",
",",
"indep_max",
")",
",",
"unwrap",
"=",
"unwrap",
",",
"rad",
"=",
"rad",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
fftr
|
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]]]
|
peng/wave_functions.py
|
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))
|
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",
"real",
"part",
"of",
"the",
"Fast",
"Fourier",
"Transform",
"of",
"a",
"waveform",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L791-L833
|
[
"def",
"fftr",
"(",
"wave",
",",
"npoints",
"=",
"None",
",",
"indep_min",
"=",
"None",
",",
"indep_max",
"=",
"None",
")",
":",
"return",
"real",
"(",
"fft",
"(",
"wave",
",",
"npoints",
",",
"indep_min",
",",
"indep_max",
")",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
find
|
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]]]
|
peng/wave_functions.py
|
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
|
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",
"independent",
"variable",
"point",
"associated",
"with",
"a",
"dependent",
"variable",
"point",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L844-L960
|
[
"def",
"find",
"(",
"wave",
",",
"dep_var",
",",
"der",
"=",
"None",
",",
"inst",
"=",
"1",
",",
"indep_min",
"=",
"None",
",",
"indep_max",
"=",
"None",
")",
":",
"# 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"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
ifftdb
|
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]]]
|
peng/wave_functions.py
|
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))
|
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",
"inverse",
"Fast",
"Fourier",
"Transform",
"of",
"a",
"waveform",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L1062-L1106
|
[
"def",
"ifftdb",
"(",
"wave",
",",
"npoints",
"=",
"None",
",",
"indep_min",
"=",
"None",
",",
"indep_max",
"=",
"None",
")",
":",
"return",
"db",
"(",
"ifft",
"(",
"wave",
",",
"npoints",
",",
"indep_min",
",",
"indep_max",
")",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
iffti
|
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]]]
|
peng/wave_functions.py
|
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))
|
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",
"imaginary",
"part",
"of",
"the",
"inverse",
"Fast",
"Fourier",
"Transform",
"of",
"a",
"waveform",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L1115-L1157
|
[
"def",
"iffti",
"(",
"wave",
",",
"npoints",
"=",
"None",
",",
"indep_min",
"=",
"None",
",",
"indep_max",
"=",
"None",
")",
":",
"return",
"imag",
"(",
"ifft",
"(",
"wave",
",",
"npoints",
",",
"indep_min",
",",
"indep_max",
")",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
ifftm
|
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]]]
|
peng/wave_functions.py
|
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))
|
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",
"magnitude",
"of",
"the",
"inverse",
"Fast",
"Fourier",
"Transform",
"of",
"a",
"waveform",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L1166-L1208
|
[
"def",
"ifftm",
"(",
"wave",
",",
"npoints",
"=",
"None",
",",
"indep_min",
"=",
"None",
",",
"indep_max",
"=",
"None",
")",
":",
"return",
"abs",
"(",
"ifft",
"(",
"wave",
",",
"npoints",
",",
"indep_min",
",",
"indep_max",
")",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
ifftp
|
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]]]
|
peng/wave_functions.py
|
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)
|
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",
"phase",
"of",
"the",
"inverse",
"Fast",
"Fourier",
"Transform",
"of",
"a",
"waveform",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L1219-L1273
|
[
"def",
"ifftp",
"(",
"wave",
",",
"npoints",
"=",
"None",
",",
"indep_min",
"=",
"None",
",",
"indep_max",
"=",
"None",
",",
"unwrap",
"=",
"True",
",",
"rad",
"=",
"True",
")",
":",
"return",
"phase",
"(",
"ifft",
"(",
"wave",
",",
"npoints",
",",
"indep_min",
",",
"indep_max",
")",
",",
"unwrap",
"=",
"unwrap",
",",
"rad",
"=",
"rad",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
ifftr
|
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]]]
|
peng/wave_functions.py
|
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))
|
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",
"real",
"part",
"of",
"the",
"inverse",
"Fast",
"Fourier",
"Transform",
"of",
"a",
"waveform",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L1282-L1324
|
[
"def",
"ifftr",
"(",
"wave",
",",
"npoints",
"=",
"None",
",",
"indep_min",
"=",
"None",
",",
"indep_max",
"=",
"None",
")",
":",
"return",
"real",
"(",
"ifft",
"(",
"wave",
",",
"npoints",
",",
"indep_min",
",",
"indep_max",
")",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
integral
|
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]]]
|
peng/wave_functions.py
|
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
|
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",
"running",
"integral",
"of",
"a",
"waveform",
"s",
"dependent",
"variable",
"vector",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L1351-L1390
|
[
"def",
"integral",
"(",
"wave",
",",
"indep_min",
"=",
"None",
",",
"indep_max",
"=",
"None",
")",
":",
"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"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
group_delay
|
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]]]
|
peng/wave_functions.py
|
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
|
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",
"group",
"delay",
"of",
"a",
"waveform",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L1394-L1414
|
[
"def",
"group_delay",
"(",
"wave",
")",
":",
"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"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
log
|
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]]]
|
peng/wave_functions.py
|
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)
|
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",
"natural",
"logarithm",
"of",
"a",
"waveform",
"s",
"dependent",
"variable",
"vector",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L1418-L1440
|
[
"def",
"log",
"(",
"wave",
")",
":",
"pexdoc",
".",
"exh",
".",
"addex",
"(",
"ValueError",
",",
"\"Math domain error\"",
",",
"bool",
"(",
"(",
"min",
"(",
"wave",
".",
"_dep_vector",
")",
"<=",
"0",
")",
")",
")",
"return",
"_operation",
"(",
"wave",
",",
"\"log\"",
",",
"\"\"",
",",
"np",
".",
"log",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
naverage
|
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]]]
|
peng/wave_functions.py
|
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
|
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",
"average",
"of",
"a",
"waveform",
"s",
"dependent",
"variable",
"vector",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L1473-L1507
|
[
"def",
"naverage",
"(",
"wave",
",",
"indep_min",
"=",
"None",
",",
"indep_max",
"=",
"None",
")",
":",
"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"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
nintegral
|
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]]]
|
peng/wave_functions.py
|
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)
|
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",
"numerical",
"integral",
"of",
"a",
"waveform",
"s",
"dependent",
"variable",
"vector",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L1513-L1549
|
[
"def",
"nintegral",
"(",
"wave",
",",
"indep_min",
"=",
"None",
",",
"indep_max",
"=",
"None",
")",
":",
"ret",
"=",
"copy",
".",
"copy",
"(",
"wave",
")",
"_bound_waveform",
"(",
"ret",
",",
"indep_min",
",",
"indep_max",
")",
"return",
"np",
".",
"trapz",
"(",
"ret",
".",
"_dep_vector",
",",
"ret",
".",
"_indep_vector",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
nmax
|
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]]]
|
peng/wave_functions.py
|
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)
|
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",
"maximum",
"of",
"a",
"waveform",
"s",
"dependent",
"variable",
"vector",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L1555-L1588
|
[
"def",
"nmax",
"(",
"wave",
",",
"indep_min",
"=",
"None",
",",
"indep_max",
"=",
"None",
")",
":",
"ret",
"=",
"copy",
".",
"copy",
"(",
"wave",
")",
"_bound_waveform",
"(",
"ret",
",",
"indep_min",
",",
"indep_max",
")",
"return",
"np",
".",
"max",
"(",
"ret",
".",
"_dep_vector",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
nmin
|
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]]]
|
peng/wave_functions.py
|
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)
|
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",
"minimum",
"of",
"a",
"waveform",
"s",
"dependent",
"variable",
"vector",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L1594-L1627
|
[
"def",
"nmin",
"(",
"wave",
",",
"indep_min",
"=",
"None",
",",
"indep_max",
"=",
"None",
")",
":",
"ret",
"=",
"copy",
".",
"copy",
"(",
"wave",
")",
"_bound_waveform",
"(",
"ret",
",",
"indep_min",
",",
"indep_max",
")",
"return",
"np",
".",
"min",
"(",
"ret",
".",
"_dep_vector",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
phase
|
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]]]
|
peng/wave_functions.py
|
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
|
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",
"Return",
"the",
"phase",
"of",
"a",
"waveform",
"s",
"dependent",
"variable",
"vector",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L1631-L1669
|
[
"def",
"phase",
"(",
"wave",
",",
"unwrap",
"=",
"True",
",",
"rad",
"=",
"True",
")",
":",
"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"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
round
|
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]]]
|
peng/wave_functions.py
|
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
|
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",
"Round",
"a",
"waveform",
"s",
"dependent",
"variable",
"vector",
"to",
"a",
"given",
"number",
"of",
"decimal",
"places",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L1694-L1726
|
[
"def",
"round",
"(",
"wave",
",",
"decimals",
"=",
"0",
")",
":",
"# 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"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
sqrt
|
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]]]
|
peng/wave_functions.py
|
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)
|
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",
"the",
"square",
"root",
"of",
"a",
"waveform",
"s",
"dependent",
"variable",
"vector",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L1771-L1789
|
[
"def",
"sqrt",
"(",
"wave",
")",
":",
"dep_units",
"=",
"\"{0}**0.5\"",
".",
"format",
"(",
"wave",
".",
"dep_units",
")",
"return",
"_operation",
"(",
"wave",
",",
"\"sqrt\"",
",",
"dep_units",
",",
"np",
".",
"sqrt",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
subwave
|
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]]]
|
peng/wave_functions.py
|
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
|
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",
"Return",
"a",
"waveform",
"that",
"is",
"a",
"sub",
"-",
"set",
"of",
"a",
"waveform",
"potentially",
"re",
"-",
"sampled",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L1799-L1860
|
[
"def",
"subwave",
"(",
"wave",
",",
"dep_name",
"=",
"None",
",",
"indep_min",
"=",
"None",
",",
"indep_max",
"=",
"None",
",",
"indep_step",
"=",
"None",
")",
":",
"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"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
wcomplex
|
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]]]
|
peng/wave_functions.py
|
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
|
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",
"complex",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L1905-L1924
|
[
"def",
"wcomplex",
"(",
"wave",
")",
":",
"ret",
"=",
"copy",
".",
"copy",
"(",
"wave",
")",
"ret",
".",
"_dep_vector",
"=",
"ret",
".",
"_dep_vector",
".",
"astype",
"(",
"np",
".",
"complex",
")",
"return",
"ret"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
wfloat
|
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]]]
|
peng/wave_functions.py
|
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
|
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",
"float",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L1928-L1955
|
[
"def",
"wfloat",
"(",
"wave",
")",
":",
"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"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
wint
|
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]]]
|
peng/wave_functions.py
|
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
|
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",
"Convert",
"a",
"waveform",
"s",
"dependent",
"variable",
"vector",
"to",
"integer",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L1959-L1986
|
[
"def",
"wint",
"(",
"wave",
")",
":",
"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"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
wvalue
|
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]]]
|
peng/wave_functions.py
|
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])
|
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])
|
[
"r",
"Return",
"the",
"dependent",
"variable",
"value",
"at",
"a",
"given",
"independent",
"variable",
"point",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L1990-L2038
|
[
"def",
"wvalue",
"(",
"wave",
",",
"indep_var",
")",
":",
"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",
"]",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
SystemFinder.find
|
Only allow lookups for jspm_packages.
# TODO: figure out the 'jspm_packages' dir from packag.json.
|
systemjs/finders.py
|
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)
|
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)
|
[
"Only",
"allow",
"lookups",
"for",
"jspm_packages",
"."
] |
sergei-maertens/django-systemjs
|
python
|
https://github.com/sergei-maertens/django-systemjs/blob/efd4a3862a39d9771609a25a5556f36023cf6e5c/systemjs/finders.py#L17-L27
|
[
"def",
"find",
"(",
"self",
",",
"path",
",",
"all",
"=",
"False",
")",
":",
"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",
")"
] |
efd4a3862a39d9771609a25a5556f36023cf6e5c
|
test
|
get_short_desc
|
Get first sentence of first paragraph of long description.
|
setup.py
|
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 ""
|
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 ""
|
[
"Get",
"first",
"sentence",
"of",
"first",
"paragraph",
"of",
"long",
"description",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/setup.py#L69-L79
|
[
"def",
"get_short_desc",
"(",
"long_desc",
")",
":",
"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",
"\"\""
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
TemplateDiscoveryMixin.find_apps
|
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.
|
systemjs/management/commands/_mixins.py
|
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
|
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
|
[
"Crawls",
"the",
"(",
"specified",
")",
"template",
"files",
"and",
"extracts",
"the",
"apps",
"."
] |
sergei-maertens/django-systemjs
|
python
|
https://github.com/sergei-maertens/django-systemjs/blob/efd4a3862a39d9771609a25a5556f36023cf6e5c/systemjs/management/commands/_mixins.py#L75-L118
|
[
"def",
"find_apps",
"(",
"self",
",",
"templates",
"=",
"None",
")",
":",
"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"
] |
efd4a3862a39d9771609a25a5556f36023cf6e5c
|
test
|
SystemImportNode.render
|
Build the filepath by appending the extension.
|
systemjs/templatetags/system_tags.py
|
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)
)
|
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)
)
|
[
"Build",
"the",
"filepath",
"by",
"appending",
"the",
"extension",
"."
] |
sergei-maertens/django-systemjs
|
python
|
https://github.com/sergei-maertens/django-systemjs/blob/efd4a3862a39d9771609a25a5556f36023cf6e5c/systemjs/templatetags/system_tags.py#L27-L56
|
[
"def",
"render",
"(",
"self",
",",
"context",
")",
":",
"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",
")",
")"
] |
efd4a3862a39d9771609a25a5556f36023cf6e5c
|
test
|
engineering_notation_number
|
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
|
docs/support/ptypes.py
|
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())
|
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",
":",
"EngineeringNotationNumber",
"pseudo",
"-",
"type",
"object",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/docs/support/ptypes.py#L72-L93
|
[
"def",
"engineering_notation_number",
"(",
"obj",
")",
":",
"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",
"(",
")",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
touchstone_data
|
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
|
docs/support/ptypes.py
|
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())
|
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",
":",
"TouchstoneData",
"pseudo",
"-",
"type",
"object",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/docs/support/ptypes.py#L171-L202
|
[
"def",
"touchstone_data",
"(",
"obj",
")",
":",
"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",
"(",
")",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
touchstone_noise_data
|
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
|
docs/support/ptypes.py
|
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
|
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",
":",
"TouchstoneNoiseData",
"pseudo",
"-",
"type",
"object",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/docs/support/ptypes.py#L206-L244
|
[
"def",
"touchstone_noise_data",
"(",
"obj",
")",
":",
"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"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
touchstone_options
|
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
|
docs/support/ptypes.py
|
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())
|
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",
"an",
":",
"ref",
":",
"TouchstoneOptions",
"pseudo",
"-",
"type",
"object",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/docs/support/ptypes.py#L248-L273
|
[
"def",
"touchstone_options",
"(",
"obj",
")",
":",
"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",
"(",
")",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
wave_interp_option
|
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
|
docs/support/ptypes.py
|
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)
|
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",
":",
"WaveInterpOption",
"pseudo",
"-",
"type",
"object",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/docs/support/ptypes.py#L277-L295
|
[
"def",
"wave_interp_option",
"(",
"obj",
")",
":",
"exdesc",
"=",
"pexdoc",
".",
"pcontracts",
".",
"get_exdesc",
"(",
")",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"str",
")",
":",
"raise",
"ValueError",
"(",
"exdesc",
")",
"if",
"obj",
".",
"upper",
"(",
")",
"in",
"[",
"\"CONTINUOUS\"",
",",
"\"STAIRCASE\"",
"]",
":",
"return",
"None",
"raise",
"ValueError",
"(",
"exdesc",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
wave_vectors
|
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
|
docs/support/ptypes.py
|
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)
|
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)
|
[
"r",
"Validate",
"if",
"an",
"object",
"is",
"a",
":",
"ref",
":",
"WaveVectors",
"pseudo",
"-",
"type",
"object",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/docs/support/ptypes.py#L321-L343
|
[
"def",
"wave_vectors",
"(",
"obj",
")",
":",
"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",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
_build_expr
|
Build mathematical expression from hierarchical list.
|
peng/functions.py
|
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
|
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
|
[
"Build",
"mathematical",
"expression",
"from",
"hierarchical",
"list",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/functions.py#L85-L105
|
[
"def",
"_build_expr",
"(",
"tokens",
",",
"higher_oplevel",
"=",
"-",
"1",
",",
"ldelim",
"=",
"\"(\"",
",",
"rdelim",
"=",
"\")\"",
")",
":",
"# 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"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
_next_rdelim
|
Return position of next matching closing delimiter.
|
peng/functions.py
|
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
|
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
|
[
"Return",
"position",
"of",
"next",
"matching",
"closing",
"delimiter",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/functions.py#L128-L136
|
[
"def",
"_next_rdelim",
"(",
"items",
",",
"pos",
")",
":",
"for",
"num",
",",
"item",
"in",
"enumerate",
"(",
"items",
")",
":",
"if",
"item",
">",
"pos",
":",
"break",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"Mismatched delimiters\"",
")",
"del",
"items",
"[",
"num",
"]",
"return",
"item"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
_get_functions
|
Parse function calls.
|
peng/functions.py
|
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
|
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
|
[
"Parse",
"function",
"calls",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/functions.py#L139-L164
|
[
"def",
"_get_functions",
"(",
"expr",
",",
"ldelim",
"=",
"\"(\"",
",",
"rdelim",
"=",
"\")\"",
")",
":",
"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"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
_pair_delims
|
Pair delimiters.
|
peng/functions.py
|
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]
|
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]
|
[
"Pair",
"delimiters",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/functions.py#L167-L173
|
[
"def",
"_pair_delims",
"(",
"expr",
",",
"ldelim",
"=",
"\"(\"",
",",
"rdelim",
"=",
"\")\"",
")",
":",
"# 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",
"]"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
_parse_expr
|
Parse mathematical expression using PyParsing.
|
peng/functions.py
|
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]
|
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]
|
[
"Parse",
"mathematical",
"expression",
"using",
"PyParsing",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/functions.py#L176-L203
|
[
"def",
"_parse_expr",
"(",
"text",
",",
"ldelim",
"=",
"\"(\"",
",",
"rdelim",
"=",
"\")\"",
")",
":",
"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",
"]"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
_remove_consecutive_delims
|
Remove consecutive delimiters.
|
peng/functions.py
|
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
|
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",
"consecutive",
"delimiters",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/functions.py#L206-L219
|
[
"def",
"_remove_consecutive_delims",
"(",
"expr",
",",
"ldelim",
"=",
"\"(\"",
",",
"rdelim",
"=",
"\")\"",
")",
":",
"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"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
_remove_extra_delims
|
Remove unnecessary delimiters (parenthesis, brackets, etc.).
Internal function that can be recursed
|
peng/functions.py
|
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
|
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
|
[
"Remove",
"unnecessary",
"delimiters",
"(",
"parenthesis",
"brackets",
"etc",
".",
")",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/functions.py#L222-L249
|
[
"def",
"_remove_extra_delims",
"(",
"expr",
",",
"ldelim",
"=",
"\"(\"",
",",
"rdelim",
"=",
"\")\"",
",",
"fcount",
"=",
"None",
")",
":",
"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"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
_split_every
|
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
|
peng/functions.py
|
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)
|
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",
"list",
"of",
"the",
"words",
"in",
"the",
"string",
"using",
"count",
"of",
"a",
"separator",
"as",
"delimiter",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/functions.py#L252-L281
|
[
"def",
"_split_every",
"(",
"text",
",",
"sep",
",",
"count",
",",
"lstrip",
"=",
"False",
",",
"rstrip",
"=",
"False",
")",
":",
"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",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
_to_eng_tuple
|
Return tuple with mantissa and exponent of number formatted in engineering notation.
:param number: Number
:type number: integer or float
:rtype: tuple
|
peng/functions.py
|
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)
|
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)
|
[
"Return",
"tuple",
"with",
"mantissa",
"and",
"exponent",
"of",
"number",
"formatted",
"in",
"engineering",
"notation",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/functions.py#L284-L305
|
[
"def",
"_to_eng_tuple",
"(",
"number",
")",
":",
"# 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",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
no_exp
|
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]]]
|
peng/functions.py
|
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
|
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",
"number",
"to",
"string",
"guaranteeing",
"result",
"is",
"not",
"in",
"scientific",
"notation",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/functions.py#L309-L337
|
[
"def",
"no_exp",
"(",
"number",
")",
":",
"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"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
peng
|
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'
|
peng/functions.py
|
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
|
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",
"Convert",
"a",
"number",
"to",
"engineering",
"notation",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/functions.py#L343-L480
|
[
"def",
"peng",
"(",
"number",
",",
"frac_length",
",",
"rjust",
"=",
"True",
")",
":",
"# 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"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
peng_float
|
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
|
peng/functions.py
|
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
|
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",
"floating",
"point",
"equivalent",
"of",
"a",
"number",
"represented",
"in",
"engineering",
"notation",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/functions.py#L484-L511
|
[
"def",
"peng_float",
"(",
"snum",
")",
":",
"# 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"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
peng_frac
|
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
|
peng/functions.py
|
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])
|
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",
"fractional",
"part",
"of",
"a",
"number",
"represented",
"in",
"engineering",
"notation",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/functions.py#L515-L542
|
[
"def",
"peng_frac",
"(",
"snum",
")",
":",
"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",
"]",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
peng_mant
|
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
|
peng/functions.py
|
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])
|
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",
"the",
"mantissa",
"of",
"a",
"number",
"represented",
"in",
"engineering",
"notation",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/functions.py#L571-L595
|
[
"def",
"peng_mant",
"(",
"snum",
")",
":",
"snum",
"=",
"snum",
".",
"rstrip",
"(",
")",
"return",
"float",
"(",
"snum",
"if",
"snum",
"[",
"-",
"1",
"]",
".",
"isdigit",
"(",
")",
"else",
"snum",
"[",
":",
"-",
"1",
"]",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
peng_power
|
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)
|
peng/functions.py
|
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])
|
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",
"and",
"its",
"floating",
"point",
"equivalent",
"of",
"a",
"number",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/functions.py#L599-L629
|
[
"def",
"peng_power",
"(",
"snum",
")",
":",
"suffix",
"=",
"\" \"",
"if",
"snum",
"[",
"-",
"1",
"]",
".",
"isdigit",
"(",
")",
"else",
"snum",
"[",
"-",
"1",
"]",
"return",
"EngPower",
"(",
"suffix",
",",
"_SUFFIX_POWER_DICT",
"[",
"suffix",
"]",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
peng_suffix_math
|
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'
|
peng/functions.py
|
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)
|
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",
"Return",
"engineering",
"suffix",
"from",
"a",
"starting",
"suffix",
"and",
"an",
"number",
"of",
"suffixes",
"offset",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/functions.py#L661-L697
|
[
"def",
"peng_suffix_math",
"(",
"suffix",
",",
"offset",
")",
":",
"# 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",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
test
|
remove_extra_delims
|
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)
|
peng/functions.py
|
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)
|
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)
|
[
"r",
"Remove",
"unnecessary",
"delimiters",
"in",
"mathematical",
"expressions",
"."
] |
pmacosta/peng
|
python
|
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/functions.py#L700-L761
|
[
"def",
"remove_extra_delims",
"(",
"expr",
",",
"ldelim",
"=",
"\"(\"",
",",
"rdelim",
"=",
"\")\"",
")",
":",
"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",
")"
] |
976935377adaa3de26fc5677aceb2cdfbd6f93a7
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.