def get_display(unicode_or_str, encoding='<STR_LIT:utf-8>', upper_is_rtl=False,<EOL>base_dir=None, debug=False):

storage = get_empty_storage()<EOL>if isinstance(unicode_or_str, six.text_type):<EOL><INDENT>text = unicode_or_str<EOL>decoded = False<EOL><DEDENT>else:<EOL><INDENT>text = unicode_or_str.decode(encoding)<EOL>decoded = True<EOL><DEDENT>if base_dir is None:<EOL><INDENT>base_level = get_base_level(text, upper_is_rtl)<EOL><DEDENT>else:<EOL><INDENT>base_level = PARAGRAPH_LEVELS[base_dir]<EOL><DEDENT>storage['<STR_LIT>'] = base_level<EOL>storage['<STR_LIT>'] = ('<STR_LIT:L>', '<STR_LIT:R>')[base_level]<EOL>get_embedding_levels(text, storage, upper_is_rtl, debug)<EOL>explicit_embed_and_overrides(storage, debug)<EOL>resolve_weak_types(storage, debug)<EOL>resolve_neutral_types(storage, debug)<EOL>resolve_implicit_levels(storage, debug)<EOL>reorder_resolved_levels(storage, debug)<EOL>apply_mirroring(storage, debug)<EOL>chars = storage['<STR_LIT>']<EOL>display = u'<STR_LIT>'.join([_ch['<STR_LIT>'] for _ch in chars])<EOL>if decoded:<EOL><INDENT>return display.encode(encoding)<EOL><DEDENT>else:<EOL><INDENT>return display<EOL><DEDENT>

Accepts unicode or string. In case it's a string, `encoding`
    is needed as it works on unicode ones (default:"utf-8").

    Set `upper_is_rtl` to True to treat upper case chars as strong 'R'
    for debugging (default: False).

    Set `base_dir` to 'L' or 'R' to override the calculated base_level.

    Set `debug` to True to display (using sys.stderr) the steps taken with the
    algorithm.

    Returns the display layout, either as unicode or `encoding` encoded
    string.


import optparse<EOL>import sys<EOL>import codecs<EOL>import locale<EOL>import six<EOL>from .algorithm import get_display<EOL>parser = optparse.OptionParser()<EOL>parser.add_option('<STR_LIT>', '<STR_LIT>',<EOL>dest='<STR_LIT>',<EOL>default='<STR_LIT:utf-8>',<EOL>type='<STR_LIT:string>',<EOL>help='<STR_LIT>')<EOL>parser.add_option('<STR_LIT>', '<STR_LIT>',<EOL>dest='<STR_LIT>',<EOL>default=False,<EOL>action='<STR_LIT:store_true>',<EOL>help="<STR_LIT>"<EOL>'<STR_LIT>')<EOL>parser.add_option('<STR_LIT>', '<STR_LIT>',<EOL>dest='<STR_LIT>',<EOL>default=False,<EOL>action='<STR_LIT:store_true>',<EOL>help="<STR_LIT>")<EOL>parser.add_option('<STR_LIT>', '<STR_LIT>',<EOL>dest='<STR_LIT>',<EOL>default=None,<EOL>type='<STR_LIT:string>',<EOL>help="<STR_LIT>")<EOL>options, rest = parser.parse_args()<EOL>if options.base_dir and options.base_dir not in '<STR_LIT>':<EOL><INDENT>parser.error('<STR_LIT>')<EOL><DEDENT>if six.PY2:<EOL><INDENT>sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout)<EOL><DEDENT>if rest:<EOL><INDENT>lines = rest<EOL><DEDENT>else:<EOL><INDENT>lines = sys.stdin<EOL><DEDENT>for line in lines:<EOL><INDENT>display = get_display(line, options.encoding, options.upper_is_rtl,<EOL>options.base_dir, options.debug)<EOL>if not isinstance(display, six.text_type):<EOL><INDENT>display = display.decode(options.encoding)<EOL><DEDENT>six.print_(display, end='<STR_LIT>')<EOL><DEDENT>

Will be used to create the console script


def gen(self, slug, name, dataobj, xfield, yfield, time_unit=None,<EOL>chart_type="<STR_LIT>", width=<NUM_LIT>,<EOL>height=<NUM_LIT>, color=Color(), size=Size(),<EOL>scale=Scale(zero=False), shape=Shape(), filepath=None,<EOL>html_before="<STR_LIT>", html_after="<STR_LIT>"):

chart_obj = self.serialize(dataobj, xfield, yfield, time_unit,<EOL>chart_type, width, height, color, size, scale, shape)<EOL>html = self.html(slug, name, chart_obj, filepath,<EOL>html_before, html_after)<EOL>return html<EOL>

Generates an html chart from either a pandas dataframe, a dictionnary,
a list or an Altair Data object and optionally write it to a file


def html(self, slug, name, chart_obj, filepath=None,<EOL>html_before="<STR_LIT>", html_after="<STR_LIT>"):

try:<EOL><INDENT>html = "<STR_LIT>"<EOL>if name:<EOL><INDENT>html = "<STR_LIT>" + name + "<STR_LIT>"<EOL><DEDENT>json_data = chart_obj.to_json()<EOL>json_data = self._patch_json(json_data)<EOL>html = html_before + html +self._json_to_html(slug, json_data) + html_after<EOL><DEDENT>except Exception as e:<EOL><INDENT>tr.new(e)<EOL>tr.check()<EOL><DEDENT>if filepath is not None:<EOL><INDENT>self._write_file(slug, filepath, html)<EOL>return None<EOL><DEDENT>else:<EOL><INDENT>return html<EOL><DEDENT>

Generate html from an Altair chart object and optionally write it to a file


def serialize(self, dataobj, xfield, yfield, time_unit=None,<EOL>chart_type="<STR_LIT>", width=<NUM_LIT>,<EOL>height=<NUM_LIT>, color=None, size=None,<EOL>scale=Scale(zero=False), shape=None, options={}):

dataset = dataobj<EOL>if self._is_dict(dataobj) is True:<EOL><INDENT>dataset = self._dict_to_df(dataobj, xfield, yfield)<EOL><DEDENT>elif isinstance(dataobj, list):<EOL><INDENT>dataset = Data(values=dataobj)<EOL><DEDENT>xencode, yencode = self._encode_fields(<EOL>xfield, yfield, time_unit)<EOL>opts = dict(x=xencode, y=yencode)<EOL>if color is not None:<EOL><INDENT>opts["<STR_LIT>"] = color<EOL><DEDENT>if size is not None:<EOL><INDENT>opts["<STR_LIT:size>"] = size<EOL><DEDENT>if shape is not None:<EOL><INDENT>opts["<STR_LIT>"] = shape<EOL><DEDENT>chart = self._chart_class(dataset, chart_type, **options).encode(<EOL>**opts<EOL>).configure_cell(<EOL>width=width,<EOL>height=height,<EOL>)<EOL>return chart<EOL>

Serialize to an Altair chart object from either a pandas dataframe, a dictionnary,
a list or an Altair Data object


return date.strftime("<STR_LIT>")<EOL>

Serializes a datetime object to Vega Lite format


json_data = json.loads(json_data)<EOL>json_data["<STR_LIT>"] = "<STR_LIT>"<EOL>json_data["<STR_LIT:width>"] = json_data["<STR_LIT>"]["<STR_LIT>"]["<STR_LIT:width>"]<EOL>json_data["<STR_LIT>"] = json_data["<STR_LIT>"]["<STR_LIT>"]["<STR_LIT>"]<EOL>del(json_data["<STR_LIT>"]["<STR_LIT>"])<EOL>return json.dumps(json_data)<EOL>

Patch the Altair generated json to the newest Vega Lite spec


def _json_to_html(self, slug, json_data):

html = '<STR_LIT>' + slug + '<STR_LIT>'<EOL>html += '<STR_LIT>'<EOL>html += '<STR_LIT>' + slug + '<STR_LIT>' + json_data + '<STR_LIT:;>'<EOL>html += '<STR_LIT>' + slug + '<STR_LIT>' + slug + '<STR_LIT>'<EOL>html += '<STR_LIT>'<EOL>return html<EOL>


def _dict_to_df(self, dictobj, xfield, yfield):

x = []<EOL>y = []<EOL>for datapoint in dictobj:<EOL><INDENT>x.append(datapoint)<EOL>y.append(dictobj[datapoint])<EOL><DEDENT>df = pd.DataFrame({xfield[<NUM_LIT:0>]: x, yfield[<NUM_LIT:0>]: y})<EOL>return df<EOL>

Converts a dictionnary to a pandas dataframe


if isinstance(dataobj, dict):<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

Check if the data object is a dictionnary


def _write_file(self, slug, folderpath, html):

<EOL>if not os.path.isdir(folderpath):<EOL><INDENT>try:<EOL><INDENT>os.makedirs(folderpath)<EOL><DEDENT>except Exception as e:<EOL><INDENT>tr.err(e)<EOL><DEDENT><DEDENT>filepath = folderpath + "<STR_LIT:/>" + slug + "<STR_LIT>"<EOL>try:<EOL><INDENT>filex = open(filepath, "<STR_LIT:w>")<EOL>filex.write(html)<EOL>filex.close()<EOL><DEDENT>except Exception as e:<EOL><INDENT>tr.err(e)<EOL><DEDENT>


def _chart_class(self, df, chart_type, **kwargs):

if chart_type == "<STR_LIT:bar>":<EOL><INDENT>return Chart(df).mark_bar(**kwargs)<EOL><DEDENT>elif chart_type == "<STR_LIT>":<EOL><INDENT>return Chart(df).mark_circle(**kwargs)<EOL><DEDENT>elif chart_type == "<STR_LIT>":<EOL><INDENT>return Chart(df).mark_line(**kwargs)<EOL><DEDENT>elif chart_type == "<STR_LIT>":<EOL><INDENT>return Chart(df).mark_point(**kwargs)<EOL><DEDENT>elif chart_type == "<STR_LIT>":<EOL><INDENT>return Chart(df).mark_area(**kwargs)<EOL><DEDENT>elif chart_type == "<STR_LIT>":<EOL><INDENT>return Chart(df).mark_tick(**kwargs)<EOL><DEDENT>elif chart_type == "<STR_LIT:text>":<EOL><INDENT>return Chart(df).mark_text(**kwargs)<EOL><DEDENT>elif chart_type == "<STR_LIT>":<EOL><INDENT>return Chart(df).mark_square(**kwargs)<EOL><DEDENT>elif chart_type == "<STR_LIT>":<EOL><INDENT>return Chart(df).mark_rule(**kwargs)<EOL><DEDENT>return None<EOL>


def _encode_fields(self, xfield, yfield, time_unit=None,<EOL>scale=Scale(zero=False)):

if scale is None:<EOL><INDENT>scale = Scale()<EOL><DEDENT>xfieldtype = xfield[<NUM_LIT:1>]<EOL>yfieldtype = yfield[<NUM_LIT:1>]<EOL>x_options = None<EOL>if len(xfield) > <NUM_LIT:2>:<EOL><INDENT>x_options = xfield[<NUM_LIT:2>]<EOL><DEDENT>y_options = None<EOL>if len(yfield) > <NUM_LIT:2>:<EOL><INDENT>y_options = yfield[<NUM_LIT:2>]<EOL><DEDENT>if time_unit is not None:<EOL><INDENT>if x_options is None:<EOL><INDENT>xencode = X(xfieldtype, timeUnit=time_unit)<EOL><DEDENT>else:<EOL><INDENT>xencode = X(<EOL>xfieldtype,<EOL>axis=Axis(**x_options),<EOL>timeUnit=time_unit,<EOL>scale=scale<EOL>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if x_options is None:<EOL><INDENT>xencode = X(xfieldtype)<EOL><DEDENT>else:<EOL><INDENT>xencode = X(<EOL>xfieldtype,<EOL>axis=Axis(**x_options),<EOL>scale=scale<EOL>)<EOL><DEDENT><DEDENT>if y_options is None:<EOL><INDENT>yencode = Y(yfieldtype, scale=scale)<EOL><DEDENT>else:<EOL><INDENT>yencode = Y(<EOL>yfieldtype,<EOL>axis=Axis(**y_options),<EOL>scale=scale<EOL>)<EOL><DEDENT>return xencode, yencode<EOL>


pass<EOL>


from flask_migrate import (Migrate, init as migrate_init,<EOL>migrate as migrate_exec)<EOL>migrations_root = migrations_root or os.path.join(<EOL>os.environ.get('<STR_LIT>',<EOL>os.getcwd()),<EOL>'<STR_LIT>')<EOL>migrations_root = os.path.expanduser(migrations_root)<EOL>mig = Migrate(app, app.db, directory=migrations_root)<EOL>if not os.path.exists(migrations_root):<EOL><INDENT>migrate_init(migrations_root)<EOL>pass<EOL><DEDENT>models_file = os.path.join(migrations_root, '<STR_LIT>')<EOL>if not os.path.exists(models_file):<EOL><INDENT>with open(models_file, '<STR_LIT:w>') as fw:<EOL><INDENT>fw.write('<STR_LIT>')<EOL>pass<EOL><DEDENT>pass<EOL><DEDENT>with open(models_file, '<STR_LIT:r>') as fp:<EOL><INDENT>modules = fp.readlines()<EOL>pass<EOL><DEDENT>modules = filter(lambda x: x.strip("<STR_LIT:\n>"), modules)<EOL>modules = map(lambda x: x.strip("<STR_LIT:\n>").split("<STR_LIT:#>")[<NUM_LIT:0>].strip(), modules)<EOL>modules = list(filter(lambda x: x, modules))<EOL>if not modules:<EOL><INDENT>click.echo(<EOL>click.style('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>',<EOL>fg='<STR_LIT>'))<EOL>sys.exit(<NUM_LIT:0>)<EOL><DEDENT>for m in modules:<EOL><INDENT>importlib.import_module(m + '<STR_LIT>')<EOL>pass<EOL><DEDENT>migrate_exec(migrations_root)<EOL>mig.init_app(app, app.db)<EOL>pass<EOL>


from flask_migrate import Migrate, upgrade as migrate_upgrade<EOL>from flask_sqlalchemy import SQLAlchemy<EOL>from sqlalchemy.engine.url import make_url<EOL>from sqlalchemy_utils import database_exists, create_database<EOL>db = SQLAlchemy()<EOL>dsn = make_url(app.config['<STR_LIT>'])<EOL>if not database_exists(dsn):<EOL><INDENT>create_database(dsn)<EOL>pass<EOL><DEDENT>migrations_root = migrations_root or os.path.join(<EOL>os.environ.get('<STR_LIT>',<EOL>os.getcwd()),<EOL>'<STR_LIT>')<EOL>migrations_root = os.path.expanduser(migrations_root)<EOL>if os.path.exists(migrations_root):<EOL><INDENT>mig = Migrate(app, db, directory=migrations_root)<EOL>mig.init_app(app, db)<EOL>migrate_upgrade(migrations_root)<EOL><DEDENT>else:<EOL><INDENT>click.echo(<EOL>click.style('<STR_LIT>', fg='<STR_LIT>'))<EOL>sys.exit(-<NUM_LIT:1>)<EOL><DEDENT>pass<EOL>


import sys<EOL>sys.path.insert(<NUM_LIT:0>, hive_root)<EOL>hive_root = os.path.abspath(os.path.expanduser(hive_root))<EOL>work_dir = work_dir or os.path.join(<EOL>os.environ.get('<STR_LIT>',<EOL>os.getcwd()))<EOL>work_dir = os.path.expanduser(work_dir)<EOL>requirements_root = os.path.join(work_dir, '<STR_LIT>')<EOL>migrate_root = os.path.join(work_dir, '<STR_LIT>')<EOL>active_module_paths = []<EOL>active_module_list = []<EOL>if active_module_file:<EOL><INDENT>with open(active_module_file, '<STR_LIT:r>') as fp:<EOL><INDENT>for l in fp:<EOL><INDENT>pkg = l.split('<STR_LIT:#>')[<NUM_LIT:0>].strip()<EOL>if pkg:<EOL><INDENT>active_module_list.append(l.strip("<STR_LIT:\n>"))<EOL><DEDENT><DEDENT>pass<EOL><DEDENT><DEDENT>active_module_list += active_module<EOL>for m in active_module_list:<EOL><INDENT>try:<EOL><INDENT>mod = importlib.import_module(m)<EOL>active_module_paths.append(os.path.dirname(mod.__file__))<EOL><DEDENT>except ImportError:<EOL><INDENT>click.echo('<STR_LIT>' % m, color="<STR_LIT>")<EOL>pass<EOL><DEDENT>pass<EOL><DEDENT>def build_requirements():<EOL><INDENT>"""<STR_LIT>"""<EOL>if not os.path.exists(requirements_root):<EOL><INDENT>os.makedirs(requirements_root)<EOL>pass<EOL><DEDENT>click.echo(click.style("<STR_LIT>", fg="<STR_LIT>"))<EOL>shutil.copy(<EOL>os.path.join(hive_root, '<STR_LIT>'),<EOL>os.path.join(requirements_root, '<STR_LIT>')<EOL>)<EOL>click.echo(click.style("<STR_LIT>",<EOL>fg="<STR_LIT>"))<EOL>requirements_files = []<EOL>for m in active_module_paths:<EOL><INDENT>t = os.path.join(m, '<STR_LIT>')<EOL>if os.path.exists(t):<EOL><INDENT>requirements_files.append(t)<EOL><DEDENT>pass<EOL><DEDENT>module_packages = set()<EOL>with fileinput.input(requirements_files) as fp:<EOL><INDENT>for line in fp:<EOL><INDENT>pkg = line.split('<STR_LIT:#>')[<NUM_LIT:0>].strip()<EOL>if pkg:<EOL><INDENT>module_packages.add(pkg)<EOL><DEDENT><DEDENT>pass<EOL><DEDENT>with click.open_file(<EOL>os.path.join(requirements_root, '<STR_LIT>'),<EOL>'<STR_LIT:w>') as fp:<EOL><INDENT>for p in module_packages:<EOL><INDENT>fp.write("<STR_LIT>" % p)<EOL><DEDENT>pass<EOL><DEDENT>pass<EOL><DEDENT>def build_dockerfile():<EOL><INDENT>"""<STR_LIT>"""<EOL>modules_in_hive = map(<EOL>lambda x: x.replace(hive_root, '<STR_LIT>').lstrip('<STR_LIT:/>'),<EOL>filter(lambda x: x.startswith(hive_root),<EOL>active_module_paths))<EOL>modules_path = '<STR_LIT:U+0020>'.join(modules_in_hive)<EOL>docker_file = os.path.join(<EOL>os.path.dirname(requirements_root),<EOL>'<STR_LIT>'<EOL>)<EOL>if os.path.exists(docker_file):<EOL><INDENT>click.echo(click.style("<STR_LIT>",<EOL>fg="<STR_LIT>"))<EOL>with open(docker_file, '<STR_LIT:r>') as fp:<EOL><INDENT>buffer = fp.read()<EOL>pass<EOL><DEDENT>import re<EOL>replaced = re.sub('<STR_LIT>',<EOL>'<STR_LIT>' % modules_path,<EOL>buffer)<EOL>with open(docker_file, '<STR_LIT:w>') as fp:<EOL><INDENT>fp.write(replaced)<EOL>pass<EOL><DEDENT>pass<EOL><DEDENT>pass<EOL><DEDENT>def build_migrations():<EOL><INDENT>models_pairs = filter(<EOL>lambda pair: os.path.exists(pair[<NUM_LIT:0>]),<EOL>map(lambda x: (os.path.join(x[<NUM_LIT:0>], '<STR_LIT>'), x[<NUM_LIT:1>]),<EOL>[(v, active_module_list[i]) for i, v in<EOL>enumerate(active_module_paths)]))<EOL>try:<EOL><INDENT>_, models = zip(*models_pairs)<EOL><DEDENT>except ValueError:<EOL><INDENT>click.echo(click.style("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" %<EOL>'<STR_LIT:U+002C>'.join(active_module_list),<EOL>fg="<STR_LIT>"))<EOL>return<EOL><DEDENT>click.echo(click.style("<STR_LIT>",<EOL>fg="<STR_LIT>"))<EOL>with open(os.path.join(migrate_root, '<STR_LIT>'), '<STR_LIT:w>') as fp:<EOL><INDENT>for p in models:<EOL><INDENT>fp.write("<STR_LIT>" % p)<EOL><DEDENT>pass<EOL><DEDENT>pass<EOL><DEDENT>def build_tasks():<EOL><INDENT>tasks_pairs = filter(<EOL>lambda pair: os.path.exists(pair[<NUM_LIT:0>]),<EOL>map(lambda x: (os.path.join(x[<NUM_LIT:0>], '<STR_LIT>'), x[<NUM_LIT:1>]),<EOL>[(v, active_module_list[i]) for i, v in<EOL>enumerate(active_module_paths)]))<EOL>try:<EOL><INDENT>_, tasks = zip(*tasks_pairs)<EOL><DEDENT>except ValueError:<EOL><INDENT>click.echo(click.style("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" %<EOL>'<STR_LIT:U+002C>'.join(active_module_list),<EOL>fg="<STR_LIT>"))<EOL>return<EOL><DEDENT>click.echo(click.style("<STR_LIT>",<EOL>fg="<STR_LIT>"))<EOL>with open(os.path.join(migrate_root, '<STR_LIT>'), '<STR_LIT:w>') as fp:<EOL><INDENT>for p in tasks:<EOL><INDENT>fp.write("<STR_LIT>" % p)<EOL><DEDENT><DEDENT>pass<EOL><DEDENT>if with_requirements:<EOL><INDENT>build_requirements()<EOL><DEDENT>if with_dockerfile:<EOL><INDENT>build_dockerfile()<EOL><DEDENT>if os.path.exists(migrate_root):<EOL><INDENT>build_migrations()<EOL><DEDENT>if os.path.exists(migrate_root):<EOL><INDENT>build_tasks()<EOL><DEDENT>click.echo(click.style("<STR_LIT>", fg="<STR_LIT>"))<EOL>pass<EOL>


if not app.celery:<EOL><INDENT>return click.echo(<EOL>click.style('<STR_LIT>', fg='<STR_LIT>'))<EOL><DEDENT>celery = app.celery<EOL>celery.autodiscover_tasks()<EOL>argv = celery_arguments.split()<EOL>argv.insert(<NUM_LIT:0>, '<STR_LIT>')<EOL>argv.insert(<NUM_LIT:0>, '<STR_LIT>')<EOL>celery.worker_main(argv)<EOL>pass<EOL>


from sqlalchemy.engine.url import make_url<EOL>from sqlalchemy_utils import database_exists, create_database<EOL>dsn = make_url(app.config['<STR_LIT>'])<EOL>if not database_exists(dsn):<EOL><INDENT>create_database(dsn)<EOL>pass<EOL><DEDENT>pass<EOL>

尝试对数据库做初始化操作


db = app.db<EOL>if os.path.exists(migrations_root) andos.environ['<STR_LIT>'] != '<STR_LIT>':<EOL><INDENT>from flask_migrate import (Migrate,<EOL>upgrade as migrate_upgrade)<EOL>migrate = Migrate(app, db, directory=migrations_root)<EOL>migrate.init_app(app, db)<EOL>migrate_upgrade(migrations_root)<EOL>pass<EOL><DEDENT>pass<EOL>


if os.environ['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>return<EOL><DEDENT>from flask_security import SQLAlchemyUserDatastore, Security<EOL>account_module_name, account_class_name = os.environ[<EOL>'<STR_LIT>'].rsplit('<STR_LIT:.>', <NUM_LIT:1>)<EOL>account_module = importlib.import_module(account_module_name)<EOL>account_class = getattr(account_module, account_class_name)<EOL>role_module_name, role_class_name = os.environ[<EOL>'<STR_LIT>'].rsplit('<STR_LIT:.>', <NUM_LIT:1>)<EOL>role_module = importlib.import_module(role_module_name)<EOL>role_class = getattr(role_module, role_class_name)<EOL>r = True if os.environ[<EOL>'<STR_LIT>'] != '<STR_LIT>' else False<EOL>Security(app,<EOL>SQLAlchemyUserDatastore(<EOL>app.db, account_class, role_class),<EOL>register_blueprint=r)<EOL>pass<EOL>

尝试使用内置方式构建账户


import sys<EOL>from logging.config import dictConfig<EOL>dictConfig({<EOL>'<STR_LIT:version>': <NUM_LIT:1>,<EOL>'<STR_LIT>': {'<STR_LIT:default>': {<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>}},<EOL>'<STR_LIT>': {'<STR_LIT>': {<EOL>'<STR_LIT:class>': '<STR_LIT>',<EOL>'<STR_LIT>': sys.stdout,<EOL>'<STR_LIT>': '<STR_LIT:default>'<EOL>}},<EOL>'<STR_LIT:root>': {<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': ['<STR_LIT>']<EOL>},<EOL>'<STR_LIT>': {<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': ['<STR_LIT>']<EOL>}<EOL>})<EOL>pass<EOL>

..deprecated::

    弃用，应该通过类似run_app注入的方式来完成

:return:


from celery import Task<EOL>tasks_txt = os.path.join(os.path.dirname(entry_file), '<STR_LIT>',<EOL>'<STR_LIT>')<EOL>if not os.path.exists(tasks_txt):<EOL><INDENT>import sys<EOL>print('<STR_LIT>' % tasks_txt)<EOL>sys.exit(-<NUM_LIT:1>)<EOL><DEDENT>class ContextTask(Task):<EOL><INDENT>abstract = True<EOL>def __call__(self, *args, **kwargs):<EOL><INDENT>with app.app_context():<EOL><INDENT>return super().__call__(*args, **kwargs)<EOL><DEDENT><DEDENT><DEDENT>app.celery.config_from_object(app.config, namespace='<STR_LIT>')<EOL>app.celery.Task = ContextTask<EOL>with app.app_context():<EOL><INDENT>with open(tasks_txt, '<STR_LIT:r>') as f:<EOL><INDENT>for line in f:<EOL><INDENT>mod = line.strip('<STR_LIT:\n>')<EOL>if mod:<EOL><INDENT>importlib.import_module(mod + '<STR_LIT>')<EOL><DEDENT>pass<EOL><DEDENT>pass<EOL><DEDENT>pass<EOL><DEDENT>pass<EOL>

装载任务，解决celery无法自动装载的问题


def create_app(app_name, config={}, db=None, celery=None):

track_mode = os.environ['<STR_LIT>'] == '<STR_LIT:yes>'<EOL>if track_mode:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>active_db = os.environ['<STR_LIT>'] == '<STR_LIT:yes>'<EOL>if track_mode:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>from webargs.flaskparser import parser<EOL>from . import error_handler, hacker, cli<EOL>hacker.hack_webargs()<EOL>migrations_root = os.path.join(<EOL>os.environ.get('<STR_LIT>',<EOL>os.getcwd()),<EOL>'<STR_LIT>')<EOL>if track_mode:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>mod = importlib.import_module(app_name)<EOL>app = FantasyFlask(__name__, root_path=os.path.dirname(mod.__file__))<EOL>if track_mode:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>if config:<EOL><INDENT>app.config.update(config)<EOL><DEDENT>config_module = os.environ.get('<STR_LIT>', None)<EOL>if track_mode:<EOL><INDENT>print("<STR_LIT>" % config_module)<EOL><DEDENT>if config_module:<EOL><INDENT>app.config.from_object(config_module)<EOL><DEDENT>if track_mode:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>if celery:<EOL><INDENT>app.celery = celery<EOL>pass<EOL><DEDENT>if track_mode:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>with app.app_context():<EOL><INDENT>if track_mode:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>if db is None:<EOL><INDENT>global _db<EOL>app.db = _db<EOL><DEDENT>else:<EOL><INDENT>app.db = db<EOL><DEDENT>if track_mode:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>if os.environ['<STR_LIT>'] != '<STR_LIT>':<EOL><INDENT>from flask_caching import Cache<EOL>app.cache = Cache(app, config=app.config)<EOL>pass<EOL><DEDENT>if track_mode:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>if os.environ.get('<STR_LIT>') != '<STR_LIT>':<EOL><INDENT>from raven.contrib.flask import Sentry<EOL>Sentry(app)<EOL>pass<EOL><DEDENT>if track_mode:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>if hasattr(mod, '<STR_LIT>'):<EOL><INDENT>run_app = getattr(mod, '<STR_LIT>')<EOL>try:<EOL><INDENT>run_app(app)<EOL><DEDENT>except Exception as e:<EOL><INDENT>if hasattr(app, '<STR_LIT>'):<EOL><INDENT>app.sentry.handle_exception(e)<EOL>pass<EOL><DEDENT>import sys<EOL>import traceback<EOL>traceback.print_exc()<EOL>sys.exit(-<NUM_LIT:1>)<EOL><DEDENT>pass<EOL><DEDENT>if active_db and app.db:<EOL><INDENT>if track_mode:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>smart_database(app)<EOL>smart_migrate(app, migrations_root)<EOL>smart_account(app)<EOL>app.db.init_app(app)<EOL>@app.teardown_request<EOL>def session_clear(exception=None):<EOL><INDENT>if exception and app.db.session.is_active:<EOL><INDENT>app.db.session.rollback()<EOL>app.db.session.remove()<EOL><DEDENT><DEDENT>pass<EOL><DEDENT>if track_mode:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>@parser.error_handler<EOL>def h_webargs(error):<EOL><INDENT>return error_handler.webargs_error(error)<EOL><DEDENT>@app.errorhandler(<NUM_LIT>)<EOL>def h_422(error):<EOL><INDENT>return error_handler.http422(error)<EOL><DEDENT>@app.errorhandler(<NUM_LIT>)<EOL>def h_500(error):<EOL><INDENT>return error_handler.http500(error)<EOL><DEDENT>if hasattr(mod, '<STR_LIT>'):<EOL><INDENT>error_handle = getattr(mod, '<STR_LIT>')<EOL>error_handle(app)<EOL>pass<EOL><DEDENT>if track_mode:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>if hasattr(mod, '<STR_LIT>'):<EOL><INDENT>import flask_admin<EOL>admin = flask_admin.Admin(name=os.environ.get('<STR_LIT>',<EOL>'<STR_LIT>'),<EOL>template_mode=os.environ.get(<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'))<EOL>run_admin = getattr(mod, '<STR_LIT>')<EOL>run_admin(admin)<EOL>admin.init_app(app)<EOL>pass<EOL><DEDENT>pass<EOL><DEDENT>if track_mode:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>app.cli.add_command(cli.ff)<EOL>if track_mode:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>if hasattr(mod, '<STR_LIT>'):<EOL><INDENT>run_cli = getattr(mod, '<STR_LIT>')<EOL>run_cli(app)<EOL>pass<EOL><DEDENT>return app<EOL>

App Factory 工具

策略是：
    - 初始化app
    - 根据app_name,装载指定的模块
    - 尝试装载app.run_app
    - 如果指定了`FANTASY_PRIMARY_NODE`，则尝试进行migrate操作
    - 装载error handler

:return:


items = app.config.items()<EOL>prefix = prefix.upper()<EOL>def strip_prefix(tup):<EOL><INDENT>return (tup[<NUM_LIT:0>].replace(prefix, '<STR_LIT>'), tup[<NUM_LIT:1>])<EOL><DEDENT>return dict([strip_prefix(i) for i in items if i[<NUM_LIT:0>].startswith(prefix)])<EOL>

Conveniently get the security configuration for the specified
    application without the annoying 'SECURITY_' prefix.

    :param app: The application to inspect


def config_value(key, app=None, default=None, prefix='<STR_LIT>'):

app = app or current_app<EOL>return get_config(app, prefix=prefix).get(key.upper(), default)<EOL>

Get a Flask-Security configuration value.

    :param key: The configuration key without the prefix `SECURITY_`
    :param app: An optional specific application to inspect. Defaults to
                Flask's `current_app`
    :param default: An optional default value if the value is not set


choices = string.digits<EOL>if not only_digits:<EOL><INDENT>choices += string.ascii_uppercase<EOL><DEDENT>return '<STR_LIT>'.join(random.SystemRandom().choice(choices)<EOL>for _ in range(length))<EOL>


units_opts = ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]<EOL>type_opts = ["<STR_LIT>", "<STR_LIT:S>", "<STR_LIT:Y>", "<STR_LIT>", "<STR_LIT:H>", "<STR_LIT>"]<EOL>format_opts = ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]<EOL>z0_opts = ["<STR_LIT>", "<STR_LIT:R>", "<STR_LIT>"]<EOL>return itertools.product(units_opts, type_opts, format_opts, z0_opts)<EOL>


with open(fname, "<STR_LIT:r>") as fobj:<EOL><INDENT>lines = "<STR_LIT>".join(fobj.readlines())<EOL><DEDENT>assert lines == ref<EOL>


options = dict(units="<STR_LIT>", ptype="<STR_LIT:Y>", pformat="<STR_LIT>", z0=<NUM_LIT>)<EOL>nums_per_freq = <NUM_LIT:2> * (nports ** <NUM_LIT:2>)<EOL>rdata = np.arange(<NUM_LIT:1>, <NUM_LIT:1> + (points * nums_per_freq))<EOL>cdata = rdata[::<NUM_LIT:2>] + <NUM_LIT> * rdata[<NUM_LIT:1>::<NUM_LIT:2>]<EOL>data = dict(<EOL>points=points,<EOL>freq=np.arange(<NUM_LIT:1>, points + <NUM_LIT:1>),<EOL>pars=np.resize(cdata, (points, nports, nports)),<EOL>)<EOL>ndata = dict(<EOL>points=points,<EOL>freq=np.arange(<NUM_LIT:1>, points + <NUM_LIT:1>),<EOL>nf=np.array([<NUM_LIT>, <NUM_LIT>, <NUM_LIT>]),<EOL>rc=np.array([<NUM_LIT:1> + <NUM_LIT>, <NUM_LIT:2> + <NUM_LIT>, <NUM_LIT:3> + <NUM_LIT>]),<EOL>res=np.array([<NUM_LIT>, <NUM_LIT>, <NUM_LIT>]),<EOL>)<EOL>return nports, options, data, ndata<EOL>

Create reference data for write_touchstone function.


def roundtrip_touchstone(nports, options, data, noise=None):

with TmpFile(nports) as fname:<EOL><INDENT>peng.write_touchstone(fname, options, data, noise, frac_length=<NUM_LIT:10>, exp_length=<NUM_LIT:2>)<EOL>idict = peng.read_touchstone(fname)<EOL><DEDENT>assert idict["<STR_LIT>"] == nports<EOL>assert idict["<STR_LIT>"] == options<EOL>idata = idict["<STR_LIT:data>"]<EOL>npoints = data["<STR_LIT>"].size<EOL>assert npoints == idata["<STR_LIT>"]<EOL>rsdata = np.resize(np.copy(data["<STR_LIT>"]), (npoints, nports, nports))<EOL>assert np.allclose(idata["<STR_LIT>"], data["<STR_LIT>"], FP_RTOL, FP_ATOL)<EOL>assert np.allclose(idata["<STR_LIT>"], rsdata, FP_RTOL, FP_ATOL)<EOL>idata = idict["<STR_LIT>"]<EOL>if idata:<EOL><INDENT>assert idata["<STR_LIT>"].size == noise["<STR_LIT>"]<EOL>assert np.allclose(idata["<STR_LIT>"], noise["<STR_LIT>"], FP_RTOL, FP_ATOL)<EOL>assert np.allclose(idata["<STR_LIT>"], noise["<STR_LIT>"], FP_RTOL, FP_ATOL)<EOL>assert np.allclose(idata["<STR_LIT>"], noise["<STR_LIT>"], FP_RTOL, FP_ATOL)<EOL>assert np.allclose(idata["<STR_LIT>"], noise["<STR_LIT>"], FP_RTOL, FP_ATOL)<EOL><DEDENT>

Check write_touchstone function by saving data and then reading it back.


def write_file(fobj, opts=None, data=None, eopts=None):

lines = []<EOL>lines.append("<STR_LIT>")<EOL>if opts:<EOL><INDENT>lines.append("<STR_LIT>" + "<STR_LIT:U+0020>".join(opts))<EOL><DEDENT>if eopts:<EOL><INDENT>lines.append("<STR_LIT>" + eopts)<EOL><DEDENT>if not data:<EOL><INDENT>data = [[<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>]]<EOL><DEDENT>for row in data:<EOL><INDENT>lines.append("<STR_LIT:U+0020>".join([str(item) for item in row]))<EOL><DEDENT>lines = [item + "<STR_LIT:\n>" for item in lines]<EOL>fobj.writelines(lines)<EOL>


with open(<EOL>os.path.join(os.environ["<STR_LIT>"], "<STR_LIT>"), "<STR_LIT:a>" if append else "<STR_LIT:w>"<EOL>) as fobj:<EOL><INDENT>fobj.write("<STR_LIT>".format(line))<EOL><DEDENT>


mant, exp = peng.functions._to_eng_tuple(number)<EOL>return "<STR_LIT>".format(<EOL>mant=mant, exp_sign="<STR_LIT:->" if exp < <NUM_LIT:0> else "<STR_LIT:+>", exp=abs(exp)<EOL>)<EOL>

Return string with the number formatted in scientific notation.

This function does not have all the configurability of the public function
to_scientific_string, it is a convenience function to test _to_eng_tuple


ystart = <NUM_LIT:3><EOL>ystop = <NUM_LIT:5><EOL>xinterp = <NUM_LIT><EOL>xstop = <NUM_LIT:50><EOL>xstart = <NUM_LIT:30><EOL>yinterp = ystart + ((ystop - ystart) / (math.log10(xstop) - math.log10(xstart))) * (<EOL>math.log10(xinterp) - math.log10(xstart)<EOL>)<EOL>cases = [<EOL>{<EOL>"<STR_LIT>": array([<NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:3>, <NUM_LIT:4>]),<EOL>"<STR_LIT>": array([<NUM_LIT:10>, <NUM_LIT:20>, <NUM_LIT:30>, <NUM_LIT>]),<EOL>"<STR_LIT>": array([<NUM_LIT:1>, <NUM_LIT>, <NUM_LIT:2>, <NUM_LIT>, <NUM_LIT:3>, <NUM_LIT>, <NUM_LIT:4>]),<EOL>"<STR_LIT>": array([<NUM_LIT:10>, <NUM_LIT:15>, <NUM_LIT:20>, <NUM_LIT>, <NUM_LIT:30>, <NUM_LIT>, <NUM_LIT>]),<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>},<EOL>{<EOL>"<STR_LIT>": array([<NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:3>, <NUM_LIT:4>]),<EOL>"<STR_LIT>": array([<NUM_LIT:10>, <NUM_LIT:20>, <NUM_LIT:30>, <NUM_LIT>]),<EOL>"<STR_LIT>": array([<NUM_LIT:1>, <NUM_LIT>, <NUM_LIT:2>, <NUM_LIT>, <NUM_LIT:3>, <NUM_LIT>, <NUM_LIT:4>]),<EOL>"<STR_LIT>": array([<NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:20>, <NUM_LIT:20>, <NUM_LIT:30>, <NUM_LIT:30>, <NUM_LIT>]),<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>},<EOL>{<EOL>"<STR_LIT>": array([<NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:3>, <NUM_LIT:4>]),<EOL>"<STR_LIT>": array([<NUM_LIT:10>, <NUM_LIT:20>, <NUM_LIT:30>, <NUM_LIT>]),<EOL>"<STR_LIT>": array([<NUM_LIT>, <NUM_LIT:2>, <NUM_LIT>, <NUM_LIT:3>, <NUM_LIT>]),<EOL>"<STR_LIT>": array([<NUM_LIT:10>, <NUM_LIT:20>, <NUM_LIT:20>, <NUM_LIT:30>, <NUM_LIT:30>]),<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>},<EOL>{<EOL>"<STR_LIT>": array([<NUM_LIT:10>, <NUM_LIT:20>, <NUM_LIT:30>, <NUM_LIT:50>]),<EOL>"<STR_LIT>": array([<NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:3>, <NUM_LIT:5>]),<EOL>"<STR_LIT>": array([<NUM_LIT:10>, <NUM_LIT:20>, <NUM_LIT:30>, <NUM_LIT>, <NUM_LIT:50>]),<EOL>"<STR_LIT>": array([<NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:3>, yinterp, <NUM_LIT:5>]),<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>},<EOL>{<EOL>"<STR_LIT>": array([<NUM_LIT:1>, <NUM_LIT:3>, <NUM_LIT:4>]),<EOL>"<STR_LIT>": array([<NUM_LIT:1> + <NUM_LIT>, <NUM_LIT:3> + <NUM_LIT>, <NUM_LIT:4> + <NUM_LIT>]),<EOL>"<STR_LIT>": array([<NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:3>, <NUM_LIT:4>]),<EOL>"<STR_LIT>": array([<NUM_LIT:1> + <NUM_LIT>, <NUM_LIT:2> + <NUM_LIT>, <NUM_LIT:3> + <NUM_LIT>, <NUM_LIT:4> + <NUM_LIT>]),<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>},<EOL>{<EOL>"<STR_LIT>": array([<NUM_LIT:1>, <NUM_LIT:3>, <NUM_LIT:4>]),<EOL>"<STR_LIT>": array([<NUM_LIT:1> + <NUM_LIT>, <NUM_LIT:3> + <NUM_LIT>, <NUM_LIT:4> + <NUM_LIT>]),<EOL>"<STR_LIT>": array([<NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:3>, <NUM_LIT:4>]),<EOL>"<STR_LIT>": array([<NUM_LIT:1> + <NUM_LIT>, <NUM_LIT:1> + <NUM_LIT>, <NUM_LIT:3> + <NUM_LIT>, <NUM_LIT:4> + <NUM_LIT>]),<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>},<EOL>{<EOL>"<STR_LIT>": array([<NUM_LIT:10>, <NUM_LIT:20>, <NUM_LIT:30>, <NUM_LIT:50>]),<EOL>"<STR_LIT>": array([<NUM_LIT:1> + <NUM_LIT>, <NUM_LIT:2> + <NUM_LIT>, <NUM_LIT:3> + <NUM_LIT>, <NUM_LIT:5> + <NUM_LIT>]),<EOL>"<STR_LIT>": array([<NUM_LIT:10>, <NUM_LIT:20>, <NUM_LIT:30>, <NUM_LIT>, <NUM_LIT:50>]),<EOL>"<STR_LIT>": array([<NUM_LIT:1> + <NUM_LIT>, <NUM_LIT:2> + <NUM_LIT>, <NUM_LIT:3> + <NUM_LIT>, yinterp + (yinterp * <NUM_LIT>), <NUM_LIT:5> + <NUM_LIT>]),<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>},<EOL>]<EOL>for case in cases:<EOL><INDENT>yield case<EOL><DEDENT>

Test values for dependent axis interpolator.


wobj, fsample, finc = fft_wave()<EOL>npoints = len(wobj.indep_vector)<EOL>ret_indep_vector = barange(-fsample / <NUM_LIT>, +fsample / <NUM_LIT>, finc)<EOL>ret_dep_vector = fft(wobj.dep_vector, npoints)<EOL>return npoints, wobj, ret_indep_vector, ret_dep_vector<EOL>

FFT of waveform where independent axis is evenly spaced and a power of 2.


<EOL>freqs = [<NUM_LIT>, <NUM_LIT>]<EOL>tend = <NUM_LIT:4> / float(min(freqs))<EOL>tsample = <NUM_LIT:1> / (<NUM_LIT> * max(freqs))<EOL>npoints = <NUM_LIT:2> ** (math.ceil(math.log(tend / tsample, <NUM_LIT:2>)))<EOL>fsample = <NUM_LIT:1> / (tend / (npoints - <NUM_LIT:1>))<EOL>tinc = <NUM_LIT:1> / float(fsample)<EOL>indep_vector = barange(<NUM_LIT:0>, tend, tinc)<EOL>finc = fsample / (npoints - <NUM_LIT:1>)<EOL>dep_vector = np.zeros(indep_vector.size)<EOL>for freq in freqs:<EOL><INDENT>dep_vector += np.cos(<NUM_LIT:2> * math.pi * freq * indep_vector)<EOL><DEDENT>wobj = peng.Waveform(indep_vector, dep_vector, "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>")<EOL>return wobj, fsample, finc<EOL>


wobj, _, _ = fft_wave()<EOL>npoints = <NUM_LIT:3> * len(wobj.indep_vector)<EOL>tend = wobj.indep_vector[-<NUM_LIT:1>]<EOL>fsample = <NUM_LIT:1> / (tend / (npoints - <NUM_LIT:1>))<EOL>finc = fsample / (npoints - <NUM_LIT:1>)<EOL>ret_indep_vector = barange(-fsample / <NUM_LIT>, +fsample / <NUM_LIT>, finc)<EOL>ret_dep_vector = fft(wobj.dep_vector, int(npoints))<EOL>return npoints, wobj, ret_indep_vector, ret_dep_vector<EOL>


return np.array(<EOL>[<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>]<EOL>)<EOL>


<EOL>wobj = rfunc(<EOL>std_wobj(dep_name="<STR_LIT>", indep_vector=indep_vector, dep_vector=dep_vector)<EOL>)<EOL>ref = std_wobj(<EOL>dep_name="<STR_LIT>".format(rdesc),<EOL>indep_vector=indep_vector,<EOL>dep_vector=(<EOL>copy.copy(wobj.dep_vector)<EOL>if dep_vector is None<EOL>else (nobj if isinstance(nobj, np.ndarray) else nobj(dep_vector))<EOL>),<EOL>dep_units=dep_units,<EOL>)<EOL>assert wobj == ref<EOL>assert wobj.dep_name == ref.dep_name<EOL>


<EOL>wobj, _, _ = fft_wave()<EOL>npoints = int(round(wobj.indep_vector.size / <NUM_LIT>))<EOL>tend = wobj.indep_vector[-<NUM_LIT:1>]<EOL>fsample = <NUM_LIT:1> / (tend / (npoints - <NUM_LIT:1>))<EOL>finc = fsample / (npoints - <NUM_LIT:1>)<EOL>ret_indep_vector = barange(-fsample / <NUM_LIT>, +fsample / <NUM_LIT>, finc)<EOL>ret_dep_vector = fft(wobj.dep_vector, int(npoints))<EOL>return npoints, wobj, ret_indep_vector, ret_dep_vector<EOL>


return np.array(<EOL>[<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> + <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>-<NUM_LIT> - <NUM_LIT>,<EOL>+<NUM_LIT> - <NUM_LIT>,<EOL>]<EOL>)<EOL>


def cmp_vectors(vector_a, vector_b, rtol=None, atol=None):

<EOL>def _vtype(vector, name):<EOL><INDENT>num_types = ["<STR_LIT:int>", "<STR_LIT:float>", "<STR_LIT>"]<EOL>for num_type in num_types:<EOL><INDENT>if vector.dtype.name.startswith(num_type):<EOL><INDENT>return num_type<EOL><DEDENT><DEDENT>pytest.fail("<STR_LIT>".format(name))<EOL><DEDENT>def _snum(item, vtype):<EOL><INDENT>if vtype == "<STR_LIT>":<EOL><INDENT>snum = "<STR_LIT>".format(<EOL>peng.to_scientific_string(item.real, <NUM_LIT:10>, <NUM_LIT:3>, True),<EOL>peng.to_scientific_string(item.imag, <NUM_LIT:10>, <NUM_LIT:3>, True),<EOL>)<EOL><DEDENT>else:<EOL><INDENT>snum = peng.to_scientific_string(item, <NUM_LIT:10>, <NUM_LIT:3>, True)<EOL><DEDENT>return snum<EOL><DEDENT>rtol = rtol or FP_RTOL<EOL>atol = atol or FP_ATOL<EOL>if vector_a.shape != vector_b.shape:<EOL><INDENT>print("<STR_LIT>".format(vector_a.shape))<EOL>print("<STR_LIT>".format(vector_b.shape))<EOL>pytest.fail("<STR_LIT>")<EOL><DEDENT>if len(vector_a.shape) != <NUM_LIT:1>:<EOL><INDENT>pytest.fail("<STR_LIT>")<EOL><DEDENT>if vector_a.size != vector_b.size:<EOL><INDENT>print("<STR_LIT>".format(vector_a.size))<EOL>print("<STR_LIT>".format(vector_b.size))<EOL>pytest.fail("<STR_LIT>")<EOL><DEDENT>atype = _vtype(vector_a, "<STR_LIT:A>")<EOL>btype = _vtype(vector_b, "<STR_LIT:B>")<EOL>flag = np.all(np.isclose(vector_a, vector_b, rtol, atol))<EOL>if not flag:<EOL><INDENT>il = len(str(vector_a.size))<EOL>template = "<STR_LIT>" + str(il) + "<STR_LIT>"<EOL>header = "<STR_LIT:#>".center(il + <NUM_LIT:1>) + "<STR_LIT:U+0020>"<EOL>header += "<STR_LIT>".center(<NUM_LIT> if atype == "<STR_LIT>" else <NUM_LIT>) + "<STR_LIT:U+0020>"<EOL>header += "<STR_LIT>".center(<NUM_LIT> if btype == "<STR_LIT>" else <NUM_LIT>) + "<STR_LIT:U+0020>"<EOL>header += "<STR_LIT>".center(<NUM_LIT>) + "<STR_LIT:U+0020>"<EOL>header += "<STR_LIT>".center(<NUM_LIT>)<EOL>print("<STR_LIT:\n>" + header + "<STR_LIT:\n>" + ("<STR_LIT:->" * len(header)))<EOL>for num, (item_a, item_b) in enumerate(zip(vector_a, vector_b)):<EOL><INDENT>ab_items = abs(item_a - item_b)<EOL>lim = atol + rtol * abs(item_b)<EOL>if ab_items > lim:<EOL><INDENT>sidx = template.format(num)<EOL>anum = _snum(item_a, atype)<EOL>bnum = _snum(item_b, btype)<EOL>ab_num = peng.to_scientific_string(ab_items, <NUM_LIT:10>, <NUM_LIT:3>, True)<EOL>slim = peng.to_scientific_string(lim, <NUM_LIT:10>, <NUM_LIT:3>, True)<EOL>print(sidx + anum + "<STR_LIT:U+0020>" + bnum + "<STR_LIT:U+0020>" + ab_num + "<STR_LIT:U+0020>" + slim)<EOL><DEDENT><DEDENT>pytest.fail("<STR_LIT>")<EOL><DEDENT>

Compare two floating point vectors to a given precision.


<EOL>indep_vector = np.array([<NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:3>]) if indep_vector is None else indep_vector<EOL>dep_vector = np.array([<NUM_LIT:6>, <NUM_LIT:5>, <NUM_LIT:4>]) if dep_vector is None else dep_vector<EOL>return peng.Waveform(<EOL>indep_vector=indep_vector,<EOL>dep_vector=dep_vector,<EOL>dep_name=dep_name,<EOL>indep_scale=indep_scale,<EOL>dep_scale="<STR_LIT>",<EOL>indep_units="<STR_LIT>",<EOL>dep_units=dep_units,<EOL>interp=interp,<EOL>)<EOL>

Return a waveform with fixed parameters and given name.


def _make_version(major, minor, micro, level, serial):

level_dict = {"<STR_LIT>": "<STR_LIT:a>", "<STR_LIT>": "<STR_LIT:b>", "<STR_LIT>": "<STR_LIT>", "<STR_LIT>": "<STR_LIT>"}<EOL>if level not in level_dict:<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>version = "<STR_LIT>".format(major, minor)<EOL>if micro:<EOL><INDENT>version += "<STR_LIT>".format(micro)<EOL><DEDENT>if level != "<STR_LIT>":<EOL><INDENT>version += "<STR_LIT>".format(level_dict[level], serial)<EOL><DEDENT>return version<EOL>

Generate version string from tuple (almost entirely from coveragepy).


data = zip(<EOL>noise["<STR_LIT>"],<EOL>noise["<STR_LIT>"],<EOL>np.abs(noise["<STR_LIT>"]),<EOL>np.angle(noise["<STR_LIT>"]),<EOL>noise["<STR_LIT>"],<EOL>)<EOL>for freq, nf, rcmag, rcangle, res in data:<EOL><INDENT>yield freq, nf, rcmag, rcangle, res<EOL><DEDENT>

Chunk input noise data into valid Touchstone file rows.


def _chunk_pars(freq_vector, data_matrix, pformat):

pformat = pformat.upper()<EOL>length = <NUM_LIT:4><EOL>for freq, data in zip(freq_vector, data_matrix):<EOL><INDENT>data = data.flatten()<EOL>for index in range(<NUM_LIT:0>, data.size, length):<EOL><INDENT>fpoint = [freq] if not index else [None]<EOL>cdata = data[index : index + length]<EOL>if pformat == "<STR_LIT>":<EOL><INDENT>vector1 = np.abs(cdata)<EOL>vector2 = np.rad2deg(np.angle(cdata))<EOL><DEDENT>elif pformat == "<STR_LIT>":<EOL><INDENT>vector1 = np.real(cdata)<EOL>vector2 = np.imag(cdata)<EOL><DEDENT>else:  <EOL><INDENT>vector1 = <NUM_LIT> * np.log10(np.abs(cdata))<EOL>vector2 = np.rad2deg(np.angle(cdata))<EOL><DEDENT>sep_data = np.array([])<EOL>for item1, item2 in zip(vector1, vector2):<EOL><INDENT>sep_data = np.concatenate((sep_data, np.array([item1, item2])))<EOL><DEDENT>ret = np.concatenate((np.array(fpoint), sep_data))<EOL>yield ret<EOL><DEDENT><DEDENT>

Chunk input data into valid Touchstone file rows.


<EOL>exnports = pexdoc.exh.addex(<EOL>RuntimeError, "<STR_LIT>"<EOL>)<EOL>exnoopt = pexdoc.exh.addex(<EOL>RuntimeError, "<STR_LIT>"<EOL>)<EOL>exopt = pexdoc.exh.addex(RuntimeError, "<STR_LIT>")<EOL>exline = pexdoc.exh.addex(RuntimeError, "<STR_LIT>")<EOL>exnodata = pexdoc.exh.addex(RuntimeError, "<STR_LIT>")<EOL>exdata = pexdoc.exh.addex(RuntimeError, "<STR_LIT>")<EOL>exndata = pexdoc.exh.addex(RuntimeError, "<STR_LIT>")<EOL>exfreq = pexdoc.exh.addex(RuntimeError, "<STR_LIT>")<EOL>exnfreq = pexdoc.exh.addex(RuntimeError, "<STR_LIT>")<EOL>_, ext = os.path.splitext(fname)<EOL>ext = ext.lower()<EOL>nports_regexp = re.compile(r"<STR_LIT>")<EOL>match = nports_regexp.match(ext)<EOL>exnports(not match, edata={"<STR_LIT>": "<STR_LIT>", "<STR_LIT:value>": fname})<EOL>nports = int(match.groups()[<NUM_LIT:0>])<EOL>opt_line = False<EOL>units_dict = {"<STR_LIT>": "<STR_LIT>", "<STR_LIT>": "<STR_LIT>", "<STR_LIT>": "<STR_LIT>", "<STR_LIT>": "<STR_LIT>"}<EOL>scale_dict = {"<STR_LIT>": <NUM_LIT>, "<STR_LIT>": <NUM_LIT>, "<STR_LIT>": <NUM_LIT>, "<STR_LIT>": <NUM_LIT:1.0>}<EOL>units_opts = ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]<EOL>type_opts = ["<STR_LIT:S>", "<STR_LIT:Y>", "<STR_LIT>", "<STR_LIT:H>", "<STR_LIT>"]<EOL>format_opts = ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]<EOL>opts = dict(units=None, ptype=None, pformat=None, z0=None)<EOL>data = []<EOL>with open(fname, "<STR_LIT:r>") as fobj:<EOL><INDENT>for num, line in enumerate(fobj):<EOL><INDENT>line = line.strip().upper()<EOL>if line.startswith("<STR_LIT:!>"):<EOL><INDENT>continue<EOL><DEDENT>if (not opt_line) and (not line.startswith("<STR_LIT:#>")):<EOL><INDENT>exnoopt(True)<EOL><DEDENT>if not opt_line:<EOL><INDENT>opt_line = True<EOL>tokens = line[<NUM_LIT:1>:].split()  <EOL>if "<STR_LIT:R>" in tokens:<EOL><INDENT>idx = tokens.index("<STR_LIT:R>")<EOL>add = <NUM_LIT:1><EOL>if len(tokens) > idx + <NUM_LIT:1>:<EOL><INDENT>try:<EOL><INDENT>opts["<STR_LIT>"] = float(tokens[idx + <NUM_LIT:1>])<EOL>add = <NUM_LIT:2><EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>tokens = tokens[:idx] + tokens[idx + add :]<EOL><DEDENT>matches = <NUM_LIT:0><EOL>for token in tokens:<EOL><INDENT>if (token in format_opts) and (not opts["<STR_LIT>"]):<EOL><INDENT>matches += <NUM_LIT:1><EOL>opts["<STR_LIT>"] = token<EOL><DEDENT>elif (token in units_opts) and (not opts["<STR_LIT>"]):<EOL><INDENT>matches += <NUM_LIT:1><EOL>opts["<STR_LIT>"] = units_dict[token]<EOL><DEDENT>elif (token in type_opts) and (not opts["<STR_LIT>"]):<EOL><INDENT>matches += <NUM_LIT:1><EOL>opts["<STR_LIT>"] = token<EOL><DEDENT><DEDENT>exopt(matches != len(tokens))<EOL><DEDENT>if opt_line and line.startswith("<STR_LIT:#>"):<EOL><INDENT>continue<EOL><DEDENT>try:<EOL><INDENT>if "<STR_LIT:!>" in line:<EOL><INDENT>idx = line.index("<STR_LIT:!>")<EOL>line = line[:idx]<EOL><DEDENT>tokens = [float(item) for item in line.split()]<EOL>data.append(tokens)<EOL><DEDENT>except:<EOL><INDENT>exline(True, edata={"<STR_LIT>": "<STR_LIT>", "<STR_LIT:value>": num + <NUM_LIT:1>})<EOL><DEDENT><DEDENT><DEDENT>data = np.concatenate(data)<EOL>exnodata(not data.size, edata={"<STR_LIT>": "<STR_LIT>", "<STR_LIT:value>": fname})<EOL>opts["<STR_LIT>"] = opts["<STR_LIT>"] or "<STR_LIT>"<EOL>opts["<STR_LIT>"] = opts["<STR_LIT>"] or "<STR_LIT:S>"<EOL>opts["<STR_LIT>"] = opts["<STR_LIT>"] or "<STR_LIT>"<EOL>opts["<STR_LIT>"] = opts["<STR_LIT>"] or <NUM_LIT:50><EOL>data_dict = {}<EOL>nums_per_freq = <NUM_LIT:1> + (<NUM_LIT:2> * (nports ** <NUM_LIT:2>))<EOL>fslice = slice(<NUM_LIT:0>, data.size, nums_per_freq)<EOL>freq = data[fslice]<EOL>ndiff = np.diff(freq)<EOL>ndict = {}<EOL>if (nports == <NUM_LIT:2>) and ndiff.size and (min(ndiff) <= <NUM_LIT:0>):<EOL><INDENT>npoints = np.where(ndiff <= <NUM_LIT:0>)[<NUM_LIT:0>][<NUM_LIT:0>] + <NUM_LIT:1><EOL>freq = freq[:npoints]<EOL>ndata = data[<NUM_LIT:9> * npoints :]<EOL>nfpoints = int(ndata.size / <NUM_LIT>)<EOL>exndata(ndata.size % <NUM_LIT:5> != <NUM_LIT:0>)<EOL>data = data[: <NUM_LIT:9> * npoints]<EOL>ndiff = <NUM_LIT:1><EOL>nfslice = slice(<NUM_LIT:0>, ndata.size, <NUM_LIT:5>)<EOL>nfreq = ndata[nfslice]<EOL>ndiff = np.diff(nfreq)<EOL>exnfreq(bool(ndiff.size and (min(ndiff) <= <NUM_LIT:0>)))<EOL>nfig_slice = slice(<NUM_LIT:1>, ndata.size, <NUM_LIT:5>)<EOL>rlmag_slice = slice(<NUM_LIT:2>, ndata.size, <NUM_LIT:5>)<EOL>rlphase_slice = slice(<NUM_LIT:3>, ndata.size, <NUM_LIT:5>)<EOL>res_slice = slice(<NUM_LIT:4>, ndata.size, <NUM_LIT:5>)<EOL>ndict["<STR_LIT>"] = scale_dict[opts["<STR_LIT>"].upper()] * nfreq<EOL>ndict["<STR_LIT>"] = ndata[nfig_slice]<EOL>ndict["<STR_LIT>"] = ndata[rlmag_slice] * np.exp(<NUM_LIT> * ndata[rlphase_slice])<EOL>ndict["<STR_LIT>"] = ndata[res_slice]<EOL>ndict["<STR_LIT>"] = nfpoints<EOL><DEDENT>exdata(data.size % nums_per_freq != <NUM_LIT:0>)<EOL>npoints = int(data.size / nums_per_freq)<EOL>exfreq(bool(ndiff.size and (min(ndiff) <= <NUM_LIT:0>)))<EOL>data_dict["<STR_LIT>"] = scale_dict[opts["<STR_LIT>"].upper()] * freq<EOL>d1slice = slice(<NUM_LIT:0>, data.size, <NUM_LIT:2>)<EOL>d2slice = slice(<NUM_LIT:1>, data.size, <NUM_LIT:2>)<EOL>data = np.delete(data, fslice)<EOL>if opts["<STR_LIT>"] == "<STR_LIT>":<EOL><INDENT>data = data[d1slice] * np.exp(<NUM_LIT> * np.deg2rad(data[d2slice]))<EOL><DEDENT>elif opts["<STR_LIT>"] == "<STR_LIT>":<EOL><INDENT>data = data[d1slice] + (<NUM_LIT> * data[d2slice])<EOL><DEDENT>else:  <EOL><INDENT>data = (<NUM_LIT:10> ** (data[d1slice] / <NUM_LIT>)) * np.exp(<NUM_LIT> * np.deg2rad(data[d2slice]))<EOL><DEDENT>if nports > <NUM_LIT:1>:<EOL><INDENT>data_dict["<STR_LIT>"] = np.resize(data, (npoints, nports, nports))<EOL><DEDENT>else:<EOL><INDENT>data_dict["<STR_LIT>"] = copy.copy(data)<EOL><DEDENT>del data<EOL>data_dict["<STR_LIT>"] = npoints<EOL>if nports == <NUM_LIT:2>:<EOL><INDENT>data_dict["<STR_LIT>"] = np.transpose(data_dict["<STR_LIT>"], (<NUM_LIT:0>, <NUM_LIT:2>, <NUM_LIT:1>))<EOL><DEDENT>return dict(nports=nports, opts=opts, data=data_dict, noise=ndict)<EOL>

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


<EOL>exnports = pexdoc.exh.addex(<EOL>RuntimeError, "<STR_LIT>"<EOL>)<EOL>exnoise = pexdoc.exh.addex(<EOL>RuntimeError, "<STR_LIT>"<EOL>)<EOL>expoints = pexdoc.exh.addex(RuntimeError, "<STR_LIT>")<EOL>_, ext = os.path.splitext(fname)<EOL>ext = ext.lower()<EOL>nports_regexp = re.compile(r"<STR_LIT>")<EOL>match = nports_regexp.match(ext)<EOL>exnports(not match, edata={"<STR_LIT>": "<STR_LIT>", "<STR_LIT:value>": fname})<EOL>nports = int(match.groups()[<NUM_LIT:0>])<EOL>exnoise(bool((nports != <NUM_LIT:2>) and noise))<EOL>nums_per_freq = nports ** <NUM_LIT:2><EOL>expoints(data["<STR_LIT>"] * nums_per_freq != data["<STR_LIT>"].size)<EOL>npoints = data["<STR_LIT>"]<EOL>par_data = np.resize(np.copy(data["<STR_LIT>"]), (npoints, nports, nports))<EOL>if nports == <NUM_LIT:2>:<EOL><INDENT>par_data = np.transpose(par_data, (<NUM_LIT:0>, <NUM_LIT:2>, <NUM_LIT:1>))<EOL><DEDENT>units_dict = {"<STR_LIT>": "<STR_LIT>", "<STR_LIT>": "<STR_LIT>", "<STR_LIT>": "<STR_LIT>", "<STR_LIT>": "<STR_LIT>"}<EOL>options["<STR_LIT>"] = units_dict[options["<STR_LIT>"].lower()]<EOL>fspace = <NUM_LIT:2> + frac_length + (exp_length + <NUM_LIT:2>)<EOL>with open(fname, "<STR_LIT:w>") as fobj:<EOL><INDENT>fobj.write(<EOL>"<STR_LIT>".format(<EOL>units=options["<STR_LIT>"],<EOL>ptype=options["<STR_LIT>"],<EOL>pformat=options["<STR_LIT>"],<EOL>z0=options["<STR_LIT>"],<EOL>)<EOL>)<EOL>for row in _chunk_pars(data["<STR_LIT>"], par_data, options["<STR_LIT>"]):<EOL><INDENT>row_data = [<EOL>to_scientific_string(item, frac_length, exp_length, bool(num != <NUM_LIT:0>))<EOL>if item is not None<EOL>else fspace * "<STR_LIT:U+0020>"<EOL>for num, item in enumerate(row)<EOL>]<EOL>fobj.write("<STR_LIT:U+0020>".join(row_data) + "<STR_LIT:\n>")<EOL><DEDENT>if (nports == <NUM_LIT:2>) and noise:<EOL><INDENT>fobj.write("<STR_LIT>")<EOL>for row in _chunk_noise(noise):<EOL><INDENT>row_data = [<EOL>to_scientific_string(item, frac_length, exp_length, bool(num != <NUM_LIT:0>))<EOL>for num, item in enumerate(row)<EOL>]<EOL>fobj.write("<STR_LIT:U+0020>".join(row_data) + "<STR_LIT:\n>")<EOL><DEDENT><DEDENT><DEDENT>

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]]]


try:<EOL><INDENT>obj = obj.rstrip()<EOL>float(obj[:-<NUM_LIT:1>] if obj[-<NUM_LIT:1>] in _SUFFIX_TUPLE else obj)<EOL>return None<EOL><DEDENT>except (AttributeError, IndexError, ValueError):<EOL><INDENT>raise ValueError(pexdoc.pcontracts.get_exdesc())<EOL><DEDENT>

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:<EOL><INDENT>assert obj in _SUFFIX_TUPLE<EOL><DEDENT>except AssertionError:<EOL><INDENT>raise ValueError(pexdoc.pcontracts.get_exdesc())<EOL><DEDENT>

r"""
    Validate if an object is an :ref:`EngineeringNotationSuffix` 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 _check_increasing_real_numpy_vector(obj):<EOL><INDENT>raise ValueError(pexdoc.pcontracts.get_exdesc())<EOL><DEDENT>

r"""
    Validate if an object is :ref:`IncreasingRealNumpyVector` 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 _check_number_numpy_vector(obj):<EOL><INDENT>raise ValueError(pexdoc.pcontracts.get_exdesc())<EOL><DEDENT>

r"""
    Validate if an object is a :ref:`NumberNumpyVector` 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 _check_real_numpy_vector(obj):<EOL><INDENT>raise ValueError(pexdoc.pcontracts.get_exdesc())<EOL><DEDENT>

r"""
    Validate if an object is a :ref:`RealNumpyVector` 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 (<EOL>isinstance(obj, dict)<EOL>and (sorted(obj.keys()) != sorted(["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]))<EOL>):<EOL><INDENT>raise ValueError(pexdoc.pcontracts.get_exdesc())<EOL><DEDENT>if not (isinstance(obj["<STR_LIT>"], int) and (obj["<STR_LIT>"] > <NUM_LIT:0>)):<EOL><INDENT>raise ValueError(pexdoc.pcontracts.get_exdesc())<EOL><DEDENT>if _check_increasing_real_numpy_vector(obj["<STR_LIT>"]):<EOL><INDENT>raise ValueError(pexdoc.pcontracts.get_exdesc())<EOL><DEDENT>if not isinstance(obj["<STR_LIT>"], np.ndarray):<EOL><INDENT>raise ValueError(pexdoc.pcontracts.get_exdesc())<EOL><DEDENT>vdata = ["<STR_LIT:int>", "<STR_LIT:float>", "<STR_LIT>"]<EOL>if not any([obj["<STR_LIT>"].dtype.name.startswith(item) for item in vdata]):<EOL><INDENT>raise ValueError(pexdoc.pcontracts.get_exdesc())<EOL><DEDENT>if obj["<STR_LIT>"].size != obj["<STR_LIT>"]:<EOL><INDENT>raise ValueError(pexdoc.pcontracts.get_exdesc())<EOL><DEDENT>nports = int(math.sqrt(obj["<STR_LIT>"].size / obj["<STR_LIT>"].size))<EOL>if obj["<STR_LIT>"] * (nports ** <NUM_LIT:2>) != obj["<STR_LIT>"].size:<EOL><INDENT>raise ValueError(pexdoc.pcontracts.get_exdesc())<EOL><DEDENT>

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 isinstance(obj, dict) and (not obj):<EOL><INDENT>return None<EOL><DEDENT>if (not isinstance(obj, dict)) or (<EOL>isinstance(obj, dict)<EOL>and (sorted(obj.keys()) != sorted(["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]))<EOL>):<EOL><INDENT>raise ValueError(pexdoc.pcontracts.get_exdesc())<EOL><DEDENT>if not (isinstance(obj["<STR_LIT>"], int) and (obj["<STR_LIT>"] > <NUM_LIT:0>)):<EOL><INDENT>raise ValueError(pexdoc.pcontracts.get_exdesc())<EOL><DEDENT>if _check_increasing_real_numpy_vector(obj["<STR_LIT>"]):<EOL><INDENT>raise ValueError(pexdoc.pcontracts.get_exdesc())<EOL><DEDENT>if _check_real_numpy_vector(obj["<STR_LIT>"]):<EOL><INDENT>raise ValueError(pexdoc.pcontracts.get_exdesc())<EOL><DEDENT>if _check_number_numpy_vector(obj["<STR_LIT>"]):<EOL><INDENT>raise ValueError(pexdoc.pcontracts.get_exdesc())<EOL><DEDENT>if not (<EOL>isinstance(obj["<STR_LIT>"], np.ndarray)<EOL>and (len(obj["<STR_LIT>"].shape) == <NUM_LIT:1>)<EOL>and (obj["<STR_LIT>"].shape[<NUM_LIT:0>] > <NUM_LIT:0>)<EOL>and np.all(obj["<STR_LIT>"] >= <NUM_LIT:0>)<EOL>):<EOL><INDENT>raise ValueError(pexdoc.pcontracts.get_exdesc())<EOL><DEDENT>sizes = [obj["<STR_LIT>"].size, obj["<STR_LIT>"].size, obj["<STR_LIT>"].size, obj["<STR_LIT>"].size]<EOL>if set(sizes) != set([obj["<STR_LIT>"]]):<EOL><INDENT>raise ValueError(pexdoc.pcontracts.get_exdesc())<EOL><DEDENT>return None<EOL>

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 (not isinstance(obj, dict)) or (<EOL>isinstance(obj, dict)<EOL>and (sorted(obj.keys()) != sorted(["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]))<EOL>):<EOL><INDENT>raise ValueError(pexdoc.pcontracts.get_exdesc())<EOL><DEDENT>if not (<EOL>(obj["<STR_LIT>"].lower() in ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"])<EOL>and (obj["<STR_LIT>"].lower() in ["<STR_LIT:s>", "<STR_LIT:y>", "<STR_LIT:z>", "<STR_LIT:h>", "<STR_LIT:g>"])<EOL>and (obj["<STR_LIT>"].lower() in ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"])<EOL>and isinstance(obj["<STR_LIT>"], float)<EOL>and (obj["<STR_LIT>"] >= <NUM_LIT:0>)<EOL>):<EOL><INDENT>raise ValueError(pexdoc.pcontracts.get_exdesc())<EOL><DEDENT>

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


exdesc = pexdoc.pcontracts.get_exdesc()<EOL>if not isinstance(obj, str):<EOL><INDENT>raise ValueError(exdesc)<EOL><DEDENT>if obj.upper() in ["<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>return None<EOL><DEDENT>raise ValueError(exdesc)<EOL>

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


r"""
    Validate if an object is a :ref:`WaveScaleOption` 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()<EOL>if not isinstance(obj, list) or (isinstance(obj, list) and not obj):<EOL><INDENT>raise ValueError(exdesc)<EOL><DEDENT>if any([not (isinstance(item, tuple) and len(item) == <NUM_LIT:2>) for item in obj]):<EOL><INDENT>raise ValueError(exdesc)<EOL><DEDENT>indep_vector, dep_vector = zip(*obj)<EOL>if _check_increasing_real_numpy_vector(np.array(indep_vector)):<EOL><INDENT>raise ValueError(exdesc)<EOL><DEDENT>if _check_real_numpy_vector(np.array(dep_vector)):<EOL><INDENT>raise ValueError(exdesc)<EOL><DEDENT>

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


def _build_expr(tokens, higher_oplevel=-<NUM_LIT:1>, ldelim="<STR_LIT:(>", rdelim="<STR_LIT:)>"):

<EOL>if isinstance(tokens, str):<EOL><INDENT>return tokens<EOL><DEDENT>if len(tokens) == <NUM_LIT:2>:<EOL><INDENT>return "<STR_LIT>".join(tokens)<EOL><DEDENT>oplevel = _get_op_level(tokens[<NUM_LIT:1>])<EOL>stoken = "<STR_LIT>"<EOL>for num, item in enumerate(tokens):<EOL><INDENT>if num % <NUM_LIT:2> == <NUM_LIT:0>:<EOL><INDENT>stoken += _build_expr(item, oplevel, ldelim=ldelim, rdelim=rdelim)<EOL><DEDENT>else:<EOL><INDENT>stoken += item<EOL><DEDENT><DEDENT>if (oplevel < higher_oplevel) or (<EOL>(oplevel == higher_oplevel) and (oplevel in _OP_PREC_PAR)<EOL>):<EOL><INDENT>stoken = ldelim + stoken + rdelim<EOL><DEDENT>return stoken<EOL>

Build mathematical expression from hierarchical list.


for num, item in enumerate(items):<EOL><INDENT>if item > pos:<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>del items[num]<EOL>return item<EOL>

Return position of next matching closing delimiter.


def _get_functions(expr, ldelim="<STR_LIT:(>", rdelim="<STR_LIT:)>"):

tpars = _pair_delims(expr, ldelim=ldelim, rdelim=rdelim)<EOL>alphas = "<STR_LIT>" "<STR_LIT>"<EOL>fchars = "<STR_LIT>" "<STR_LIT>" "<STR_LIT>" "<STR_LIT:_>"<EOL>tfuncs = []<EOL>for lnum, rnum in tpars:<EOL><INDENT>if lnum and expr[lnum - <NUM_LIT:1>] in fchars:<EOL><INDENT>for cnum, char in enumerate(reversed(expr[:lnum])):<EOL><INDENT>if char not in fchars:<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>cnum = lnum<EOL><DEDENT>tfuncs.append(<EOL>{<EOL>"<STR_LIT>": expr[lnum - cnum : lnum],<EOL>"<STR_LIT>": expr[lnum + <NUM_LIT:1> : rnum],<EOL>"<STR_LIT:start>": lnum - cnum,<EOL>"<STR_LIT>": rnum,<EOL>}<EOL>)<EOL>if expr[lnum - cnum] not in alphas:<EOL><INDENT>raise RuntimeError(<EOL>"<STR_LIT>".format(expr[lnum - cnum : lnum])<EOL>)<EOL><DEDENT><DEDENT><DEDENT>return tfuncs<EOL>


def _pair_delims(expr, ldelim="<STR_LIT:(>", rdelim="<STR_LIT:)>"):

<EOL>lindex = reversed([num for num, item in enumerate(expr) if item == ldelim])<EOL>rindex = [num for num, item in enumerate(expr) if item == rdelim]<EOL>return [(lpos, _next_rdelim(rindex, lpos)) for lpos in lindex][::-<NUM_LIT:1>]<EOL>


def _parse_expr(text, ldelim="<STR_LIT:(>", rdelim="<STR_LIT:)>"):

var = pyparsing.Word(pyparsing.alphas + "<STR_LIT:_>", pyparsing.alphanums + "<STR_LIT:_>")<EOL>point = pyparsing.Literal("<STR_LIT:.>")<EOL>exp = pyparsing.CaselessLiteral("<STR_LIT:E>")<EOL>number = pyparsing.Combine(<EOL>pyparsing.Word("<STR_LIT>" + pyparsing.nums, pyparsing.nums)<EOL>+ pyparsing.Optional(point + pyparsing.Optional(pyparsing.Word(pyparsing.nums)))<EOL>+ pyparsing.Optional(<EOL>exp + pyparsing.Word("<STR_LIT>" + pyparsing.nums, pyparsing.nums)<EOL>)<EOL>)<EOL>atom = var | number<EOL>oplist = [<EOL>(pyparsing.Literal("<STR_LIT>"), <NUM_LIT:2>, pyparsing.opAssoc.RIGHT),<EOL>(pyparsing.oneOf("<STR_LIT>"), <NUM_LIT:1>, pyparsing.opAssoc.RIGHT),<EOL>(pyparsing.oneOf("<STR_LIT>"), <NUM_LIT:2>, pyparsing.opAssoc.LEFT),<EOL>(pyparsing.oneOf("<STR_LIT>"), <NUM_LIT:2>, pyparsing.opAssoc.LEFT),<EOL>(pyparsing.oneOf("<STR_LIT>"), <NUM_LIT:2>, pyparsing.opAssoc.LEFT),<EOL>(pyparsing.Literal("<STR_LIT:&>"), <NUM_LIT:2>, pyparsing.opAssoc.LEFT),<EOL>(pyparsing.Literal("<STR_LIT>"), <NUM_LIT:2>, pyparsing.opAssoc.LEFT),<EOL>(pyparsing.Literal("<STR_LIT:|>"), <NUM_LIT:2>, pyparsing.opAssoc.LEFT),<EOL>]<EOL>expr = pyparsing.infixNotation(<EOL>atom, oplist, lpar=pyparsing.Suppress(ldelim), rpar=pyparsing.Suppress(rdelim)<EOL>)<EOL>return expr.parseString(text)[<NUM_LIT:0>]<EOL>

Parse mathematical expression using PyParsing.


def _remove_consecutive_delims(expr, ldelim="<STR_LIT:(>", rdelim="<STR_LIT:)>"):

tpars = _pair_delims(expr, ldelim=ldelim, rdelim=rdelim)<EOL>ddelim = []<EOL>for ctuple, ntuple in zip(tpars, tpars[<NUM_LIT:1>:]):<EOL><INDENT>if ctuple == (ntuple[<NUM_LIT:0>] - <NUM_LIT:1>, ntuple[<NUM_LIT:1>] + <NUM_LIT:1>):<EOL><INDENT>ddelim.extend(ntuple)<EOL><DEDENT><DEDENT>ddelim.sort()<EOL>for num, item in enumerate(ddelim):<EOL><INDENT>expr = expr[: item - num] + expr[item - num + <NUM_LIT:1> :]<EOL><DEDENT>return expr<EOL>


def _remove_extra_delims(expr, ldelim="<STR_LIT:(>", rdelim="<STR_LIT:)>", fcount=None):

if not expr.strip():<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>fcount = [<NUM_LIT:0>] if fcount is None else fcount<EOL>tfuncs = _get_functions(expr, ldelim=ldelim, rdelim=rdelim)<EOL>for fdict in reversed(tfuncs):<EOL><INDENT>fcount[<NUM_LIT:0>] += <NUM_LIT:1><EOL>fdict["<STR_LIT>"] = "<STR_LIT>" + str(fcount[<NUM_LIT:0>])<EOL>expr = expr[: fdict["<STR_LIT:start>"]] + fdict["<STR_LIT>"] + expr[fdict["<STR_LIT>"] + <NUM_LIT:1> :]<EOL>fdict["<STR_LIT>"] = _remove_extra_delims(<EOL>fdict["<STR_LIT>"], ldelim=ldelim, rdelim=rdelim, fcount=fcount<EOL>)<EOL><DEDENT>expr = _build_expr(<EOL>_parse_expr(expr, ldelim=ldelim, rdelim=rdelim), ldelim=ldelim, rdelim=rdelim<EOL>)<EOL>for fdict in tfuncs:<EOL><INDENT>expr = expr.replace(<EOL>fdict["<STR_LIT>"], fdict["<STR_LIT>"] + ldelim + fdict["<STR_LIT>"] + rdelim<EOL>)<EOL><DEDENT>return expr<EOL>

Remove unnecessary delimiters (parenthesis, brackets, etc.).

Internal function that can be recursed


def _split_every(text, sep, count, lstrip=False, rstrip=False):

ltr = "<STR_LIT>"[<NUM_LIT:2> * lstrip + rstrip].strip()<EOL>func = lambda x: getattr(x, ltr + "<STR_LIT>")() if ltr != "<STR_LIT:_>" else x<EOL>items = text.split(sep)<EOL>groups = zip_longest(*[iter(items)] * count, fillvalue="<STR_LIT>")<EOL>joints = (sep.join(group).rstrip(sep) for group in groups)<EOL>return tuple(func(joint) for joint in joints)<EOL>

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


<EOL>split = lambda x, p: (x.ljust(<NUM_LIT:3> + neg, "<STR_LIT:0>")[:p], x[p:].rstrip("<STR_LIT:0>"))<EOL>mant, exp = to_scientific_tuple(number)<EOL>mant, neg = mant.replace("<STR_LIT:.>", "<STR_LIT>"), mant.startswith("<STR_LIT:->")<EOL>new_mant = "<STR_LIT:.>".join(filter(None, split(mant, <NUM_LIT:1> + (exp % <NUM_LIT:3>) + neg)))<EOL>new_exp = int(<NUM_LIT:3> * math.floor(exp / <NUM_LIT:3>))<EOL>return NumComp(new_mant, new_exp)<EOL>

Return tuple with mantissa and exponent of number formatted in engineering notation.

:param number: Number
:type  number: integer or float

:rtype: tuple


mant, exp = to_scientific_tuple(number)<EOL>if not exp:<EOL><INDENT>return str(number)<EOL><DEDENT>floating_mant = "<STR_LIT:.>" in mant<EOL>mant = mant.replace("<STR_LIT:.>", "<STR_LIT>")<EOL>if exp < <NUM_LIT:0>:<EOL><INDENT>return "<STR_LIT>" + "<STR_LIT:0>" * (-exp - <NUM_LIT:1>) + mant<EOL><DEDENT>if not floating_mant:<EOL><INDENT>return mant + "<STR_LIT:0>" * exp + ("<STR_LIT>" if isinstance(number, float) else "<STR_LIT>")<EOL><DEDENT>lfpart = len(mant) - <NUM_LIT:1><EOL>if lfpart < exp:<EOL><INDENT>return (mant + "<STR_LIT:0>" * (exp - lfpart)).rstrip("<STR_LIT:.>")<EOL><DEDENT>return mant<EOL>

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]]]


@pexdoc.pcontracts.contract(<EOL>number="<STR_LIT>", frac_length="<STR_LIT>", rjust=bool<EOL>)<EOL>def peng(number, frac_length, rjust=True):

<EOL>if number == <NUM_LIT:0>:<EOL><INDENT>number = "<STR_LIT>".format(zrs="<STR_LIT:0>" * frac_length) if frac_length else "<STR_LIT:0>"<EOL>return "<STR_LIT>".format(number.rjust(<NUM_LIT:5> + frac_length)) if rjust else number<EOL><DEDENT>sign = +<NUM_LIT:1> if number >= <NUM_LIT:0> else -<NUM_LIT:1><EOL>ssign = "<STR_LIT:->" if sign == -<NUM_LIT:1> else "<STR_LIT>"<EOL>anumber = abs(number)<EOL>if anumber < <NUM_LIT>:<EOL><INDENT>anumber = <NUM_LIT><EOL>number = sign * <NUM_LIT><EOL><DEDENT>exp = <NUM_LIT> * math.floor(math.floor(math.log10(anumber)) / <NUM_LIT>)<EOL>mant = number / <NUM_LIT:10> ** exp<EOL>smant = str(mant)<EOL>ppos = smant.find("<STR_LIT:.>")<EOL>if len(smant) - ppos - <NUM_LIT:1> > frac_length:<EOL><INDENT>mant += sign * <NUM_LIT:5> * <NUM_LIT:10> ** (-frac_length - <NUM_LIT:1>)<EOL>if abs(mant) >= <NUM_LIT:1000>:<EOL><INDENT>exp += <NUM_LIT:3><EOL>mant = mant / <NUM_LIT><EOL><DEDENT>smant = str(mant)<EOL>ppos = smant.find("<STR_LIT:.>")<EOL><DEDENT>bfrac_length = bool(frac_length)<EOL>flength = ppos - (not bfrac_length) + frac_length + <NUM_LIT:1><EOL>new_mant = smant[:flength].ljust(flength, "<STR_LIT:0>")<EOL>if exp > <NUM_LIT>:<EOL><INDENT>new_mant, exp = (<EOL>"<STR_LIT>".format(sign=ssign, frac="<STR_LIT>" * frac_length),<EOL><NUM_LIT>,<EOL>)<EOL><DEDENT>new_mant = new_mant.rjust(rjust * (<NUM_LIT:4> + bfrac_length + frac_length))<EOL>num = "<STR_LIT>".format(<EOL>mant=new_mant, suffix=_POWER_TO_SUFFIX_DICT[exp] if exp else "<STR_LIT:U+0020>" * bool(rjust)<EOL>)<EOL>return num<EOL>

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'


<EOL>snum = snum.rstrip()<EOL>power = _SUFFIX_POWER_DICT["<STR_LIT:U+0020>" if snum[-<NUM_LIT:1>].isdigit() else snum[-<NUM_LIT:1>]]<EOL>return float(snum if snum[-<NUM_LIT:1>].isdigit() else snum[:-<NUM_LIT:1>]) * power<EOL>

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


snum = snum.rstrip()<EOL>pindex = snum.find("<STR_LIT:.>")<EOL>if pindex == -<NUM_LIT:1>:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>return int(snum[pindex + <NUM_LIT:1> :] if snum[-<NUM_LIT:1>].isdigit() else snum[pindex + <NUM_LIT:1> : -<NUM_LIT:1>])<EOL>

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


return int(peng_mant(snum))<EOL>

r"""
    Return the integer 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_int

    :raises: RuntimeError (Argument \`snum\` is not valid)

    .. [[[end]]]

    For example:

        >>> import peng
        >>> peng.peng_int(peng.peng(1235.6789E3, 3, False))
        1


snum = snum.rstrip()<EOL>return float(snum if snum[-<NUM_LIT:1>].isdigit() else snum[:-<NUM_LIT:1>])<EOL>

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


suffix = "<STR_LIT:U+0020>" if snum[-<NUM_LIT:1>].isdigit() else snum[-<NUM_LIT:1>]<EOL>return EngPower(suffix, _SUFFIX_POWER_DICT[suffix])<EOL>

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)


snum = snum.rstrip()<EOL>return "<STR_LIT:U+0020>" if snum[-<NUM_LIT:1>].isdigit() else snum[-<NUM_LIT:1>]<EOL>

r"""
    Return the suffix 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_suffix

    :raises: RuntimeError (Argument \`snum\` is not valid)

    .. [[[end]]]

    For example:

        >>> import peng
        >>> peng.peng_suffix(peng.peng(1235.6789E3, 3, False))
        'M'


@pexdoc.pcontracts.contract(suffix="<STR_LIT>", offset=int)<EOL>def peng_suffix_math(suffix, offset):

<EOL>eobj = pexdoc.exh.addex(ValueError, "<STR_LIT>")<EOL>try:<EOL><INDENT>return _POWER_TO_SUFFIX_DICT[_SUFFIX_TO_POWER_DICT[suffix] + <NUM_LIT:3> * offset]<EOL><DEDENT>except KeyError:<EOL><INDENT>eobj(True)<EOL><DEDENT>

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'


def remove_extra_delims(expr, ldelim="<STR_LIT:(>", rdelim="<STR_LIT:)>"):

op_group = "<STR_LIT>"<EOL>for item1 in _OP_PREC:<EOL><INDENT>if isinstance(item1, list):<EOL><INDENT>for item2 in item1:<EOL><INDENT>op_group += item2<EOL><DEDENT><DEDENT>else:<EOL><INDENT>op_group += item1<EOL><DEDENT><DEDENT>iobj = zip([expr, ldelim, rdelim], ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"])<EOL>for item, desc in iobj:<EOL><INDENT>if not isinstance(item, str):<EOL><INDENT>raise RuntimeError("<STR_LIT>".format(desc))<EOL><DEDENT><DEDENT>if (len(ldelim) != <NUM_LIT:1>) or ((len(ldelim) == <NUM_LIT:1>) and (ldelim in op_group)):<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>if (len(rdelim) != <NUM_LIT:1>) or ((len(rdelim) == <NUM_LIT:1>) and (rdelim in op_group)):<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>if expr.count(ldelim) != expr.count(rdelim):<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>if not expr:<EOL><INDENT>return expr<EOL><DEDENT>vchars = (<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>r"<STR_LIT>" + rdelim + ldelim + op_group<EOL>)<EOL>if any([item not in vchars for item in expr]) or ("<STR_LIT>" in expr):<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>expr = _remove_consecutive_delims(expr, ldelim=ldelim, rdelim=rdelim)<EOL>expr = expr.replace(ldelim + rdelim, "<STR_LIT>")<EOL>return _remove_extra_delims(expr, ldelim=ldelim, rdelim=rdelim)<EOL>

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)


if arg is None:<EOL><INDENT>return arg<EOL><DEDENT>if isinstance(arg, np.ndarray):<EOL><INDENT>foi = [isinstance(item, int) for item in arg]<EOL>return np.array(<EOL>[<EOL>item if isint else float(to_scientific_string(item, decimals))<EOL>for isint, item in zip(foi, arg)<EOL>]<EOL>)<EOL><DEDENT>if isinstance(arg, int):<EOL><INDENT>return arg<EOL><DEDENT>return float(to_scientific_string(arg, decimals))<EOL>

Round floating point number(s) mantissa to given number of digits.

Integers are not altered. The mantissa used is that of the floating point
number(s) when expressed in `normalized scientific notation
<https://en.wikipedia.org/wiki/Scientific_notation#Normalized_notation>`_

:param arg: Input data
:type  arg: integer, float, Numpy vector of integers or floats, or None

:param decimals: Number of digits to round the fractional part of the
                 mantissa to.
:type  decimals: integer

:rtype: same as **arg**

For example::

    >>> import peng
    >>> peng.round_mantissa(012345678E-6, 3)
    12.35
    >>> peng.round_mantissa(5, 3)
    5


def pprint_vector(vector, limit=False, width=None, indent=<NUM_LIT:0>, eng=False, frac_length=<NUM_LIT:3>):

<EOL>num_digits = <NUM_LIT:12><EOL>approx = lambda x: float(x) if "<STR_LIT:.>" not in x else round(float(x), num_digits)<EOL>def limstr(value):<EOL><INDENT>str1 = str(value)<EOL>iscomplex = isinstance(value, complex)<EOL>str1 = str1.lstrip("<STR_LIT:(>").rstrip("<STR_LIT:)>")<EOL>if "<STR_LIT:.>" not in str1:<EOL><INDENT>return str1<EOL><DEDENT>if iscomplex:<EOL><INDENT>sign = "<STR_LIT:+>" if value.imag >= <NUM_LIT:0> else "<STR_LIT:->"<EOL>regexp = re.compile(<EOL>r"<STR_LIT>"<EOL>+ (r"<STR_LIT>" if sign == "<STR_LIT:+>" else "<STR_LIT:->")<EOL>+ r"<STR_LIT>"<EOL>)<EOL>rvalue, ivalue = regexp.match(str1).groups()<EOL>return (<EOL>str(complex(approx(rvalue), approx(sign + ivalue.strip("<STR_LIT>"))))<EOL>.lstrip("<STR_LIT:(>")<EOL>.rstrip("<STR_LIT:)>")<EOL>)<EOL><DEDENT>str2 = str(round(value, num_digits))<EOL>return str2 if len(str1) > len(str2) else str1<EOL><DEDENT>def _str(*args):<EOL><INDENT>"""<STR_LIT>"""<EOL>ret = [<EOL>(limstr(element) if not eng else peng(element, frac_length, True))<EOL>if not isinstance(element, complex)<EOL>else (<EOL>limstr(element)<EOL>if not eng<EOL>else "<STR_LIT>".format(<EOL>real=peng(element.real, frac_length, True),<EOL>imag=peng(abs(element.imag), frac_length, True),<EOL>sign="<STR_LIT:+>" if element.imag >= <NUM_LIT:0> else "<STR_LIT:->",<EOL>)<EOL>)<EOL>for element in args<EOL>]<EOL>return ret[<NUM_LIT:0>] if len(ret) == <NUM_LIT:1> else ret<EOL><DEDENT>if vector is None:<EOL><INDENT>return "<STR_LIT:None>"<EOL><DEDENT>lvector = len(vector)<EOL>if (not limit) or (limit and (lvector < <NUM_LIT:7>)):<EOL><INDENT>items = _str(*vector)<EOL>uret = "<STR_LIT>".format("<STR_LIT:U+002CU+0020>".join(items))<EOL><DEDENT>else:<EOL><INDENT>items = _str(*(vector[:<NUM_LIT:3>] + vector[-<NUM_LIT:3>:]))<EOL>uret = "<STR_LIT>".format("<STR_LIT:U+002CU+0020>".join(items[:<NUM_LIT:3>]), "<STR_LIT:U+002CU+0020>".join(items[-<NUM_LIT:3>:]))<EOL><DEDENT>if (width is None) or (len(uret) < width):<EOL><INDENT>return uret<EOL><DEDENT>if any([len(item) > width - <NUM_LIT:4> for item in items]):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>wobj = textwrap.TextWrapper(initial_indent="<STR_LIT>", width=width)<EOL>rlist = wobj.wrap(uret[<NUM_LIT:2>:])<EOL>first_line = rlist[<NUM_LIT:0>]<EOL>first_line_elements = first_line.count("<STR_LIT:U+002C>")<EOL>uret_left = ("<STR_LIT:U+002C>".join(uret.split("<STR_LIT:U+002C>")[first_line_elements:])).replace("<STR_LIT>", "<STR_LIT>")<EOL>wobj = textwrap.TextWrapper(width=width - <NUM_LIT:2>)<EOL>wrapped_text = wobj.wrap(uret_left.lstrip())<EOL>rlist = [first_line] + [<EOL>("<STR_LIT:U+0020>" * (indent + <NUM_LIT:2>)) + item.rstrip() for item in wrapped_text<EOL>]<EOL>last_line = rlist[-<NUM_LIT:1>]<EOL>last_line_elements = last_line.count("<STR_LIT:U+002C>") + <NUM_LIT:1><EOL>if limit and (lvector > <NUM_LIT:6>):<EOL><INDENT>if (first_line_elements < <NUM_LIT:3>) or (<EOL>(first_line_elements == <NUM_LIT:3>) and (last_line_elements < <NUM_LIT:3>)<EOL>):<EOL><INDENT>rlist = [<EOL>"<STR_LIT>".format(_str(vector[<NUM_LIT:0>])),<EOL>_str(vector[<NUM_LIT:1>]),<EOL>_str(vector[<NUM_LIT:2>]),<EOL>"<STR_LIT>",<EOL>_str(vector[-<NUM_LIT:3>]),<EOL>_str(vector[-<NUM_LIT:2>]),<EOL>"<STR_LIT>".format(_str(vector[-<NUM_LIT:1>])),<EOL>]<EOL>first_line_elements = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>rlist = [<EOL>"<STR_LIT>".format("<STR_LIT:U+002CU+0020>".join(_str(*vector[:<NUM_LIT:3>]))),<EOL>"<STR_LIT>",<EOL>"<STR_LIT>".format("<STR_LIT:U+002CU+0020>".join(_str(*vector[-<NUM_LIT:3>:]))),<EOL>]<EOL><DEDENT>first_line = rlist[<NUM_LIT:0>]<EOL><DEDENT>elif limit:<EOL><INDENT>rlist = [item.lstrip() for item in rlist]<EOL><DEDENT>first_comma_index = first_line.find("<STR_LIT:U+002C>")<EOL>actual_width = len(first_line) - <NUM_LIT:2><EOL>if not eng:<EOL><INDENT>if not limit:<EOL><INDENT>return "<STR_LIT:\n>".join(rlist)<EOL><DEDENT>num_elements = len(rlist)<EOL>return "<STR_LIT:\n>".join(<EOL>[<EOL>"<STR_LIT>".format(<EOL>spaces=("<STR_LIT:U+0020>" * (indent + <NUM_LIT:2>)) if num > <NUM_LIT:0> else "<STR_LIT>",<EOL>line=(<EOL>line.center(actual_width).rstrip()<EOL>if line.strip() == "<STR_LIT>"<EOL>else line<EOL>),<EOL>comma=(<EOL>"<STR_LIT:U+002C>"<EOL>if (<EOL>(num < num_elements - <NUM_LIT:1>)<EOL>and (not line.endswith("<STR_LIT:U+002C>"))<EOL>and (line.strip() != "<STR_LIT>")<EOL>)<EOL>else "<STR_LIT>"<EOL>),<EOL>)<EOL>if num > <NUM_LIT:0><EOL>else line<EOL>for num, line in enumerate(rlist)<EOL>]<EOL>)<EOL><DEDENT>if limit:<EOL><INDENT>remainder_list = [line.lstrip() for line in rlist[<NUM_LIT:1>:]]<EOL><DEDENT>else:<EOL><INDENT>remainder_list = _split_every(<EOL>text=uret[len(first_line) :],<EOL>sep="<STR_LIT:U+002C>",<EOL>count=first_line_elements,<EOL>lstrip=True,<EOL>)<EOL><DEDENT>new_wrapped_lines_list = [first_line]<EOL>for line in remainder_list[:-<NUM_LIT:1>]:<EOL><INDENT>new_wrapped_lines_list.append(<EOL>"<STR_LIT>".format(line).rjust(actual_width)<EOL>if line != "<STR_LIT>"<EOL>else line.center(actual_width).rstrip()<EOL>)<EOL><DEDENT>if remainder_list[-<NUM_LIT:1>].find("<STR_LIT:U+002C>") == -<NUM_LIT:1>:<EOL><INDENT>marker = len(remainder_list[-<NUM_LIT:1>]) - <NUM_LIT:2><EOL><DEDENT>else:<EOL><INDENT>marker = remainder_list[-<NUM_LIT:1>].find("<STR_LIT:U+002C>")<EOL><DEDENT>new_wrapped_lines_list.append(<EOL>"<STR_LIT>".format((first_comma_index - marker - <NUM_LIT:2>) * "<STR_LIT:U+0020>", remainder_list[-<NUM_LIT:1>])<EOL>)<EOL>return "<STR_LIT:\n>".join(<EOL>[<EOL>"<STR_LIT>".format(spaces="<STR_LIT:U+0020>" * (indent + <NUM_LIT:2>), line=line)<EOL>if num > <NUM_LIT:0><EOL>else line<EOL>for num, line in enumerate(new_wrapped_lines_list)<EOL>]<EOL>)<EOL>

r"""
    Format a list of numbers (vector) or a Numpy vector for printing.

    If the argument **vector** is :code:`None` the string :code:`'None'` is
    returned

    :param vector: Vector to pretty print or None
    :type  vector: list of integers or floats, Numpy vector or None

    :param limit: Flag that indicates whether at most 6 vector items are
                  printed (all vector items if its length is equal or less
                  than 6, first and last 3 vector items if it is not) (True),
                  or the entire vector is printed (False)
    :type  limit: boolean

    :param width: Number of available characters per line. If None the vector
                  is printed in one line
    :type  width: integer or None

    :param indent: Flag that indicates whether all subsequent lines after the
                   first one are indented (True) or not (False). Only relevant
                   if **width** is not None
    :type  indent: boolean

    :param eng: Flag that indicates whether engineering notation is used
                (True) or not (False)
    :type  eng: boolean

    :param frac_length: Number of digits of fractional part (only applicable
                        if **eng** is True)
    :type  frac_length: integer

    :raises: ValueError (Argument \`width\` is too small)

    :rtype: string

    For example:

        >>> from __future__ import print_function
        >>> import peng
        >>> header = 'Vector: '
        >>> data = [1e-3, 20e-6, 300e+6, 4e-12, 5.25e3, -6e-9, 700, 8, 9]
        >>> print(
        ...     header+peng.pprint_vector(
        ...         data,
        ...         width=30,
        ...         eng=True,
        ...         frac_length=1,
        ...         limit=True,
        ...         indent=len(header)
        ...     )
        ... )
        Vector: [    1.0m,   20.0u,  300.0M,
                             ...
                   700.0 ,    8.0 ,    9.0  ]
        >>> print(
        ...     header+peng.pprint_vector(
        ...         data,
        ...         width=30,
        ...         eng=True,
        ...         frac_length=0,
        ...         indent=len(header)
        ...     )
        ... )
        Vector: [    1m,   20u,  300M,    4p,
                     5k,   -6n,  700 ,    8 ,
                     9  ]
        >>> print(peng.pprint_vector(data, eng=True, frac_length=0))
        [    1m,   20u,  300M,    4p,    5k,   -6n,  700 ,    8 ,    9  ]
        >>> print(peng.pprint_vector(data, limit=True))
        [ 0.001, 2e-05, 300000000.0, ..., 700, 8, 9 ]


def to_scientific_string(number, frac_length=None, exp_length=None, sign_always=False):

<EOL>try:<EOL><INDENT>number = -<NUM_LIT> if np.isneginf(number) else number<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>number = +<NUM_LIT> if np.isposinf(number) else number<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>exp_length = <NUM_LIT:0> if not exp_length else exp_length<EOL>mant, exp = to_scientific_tuple(number)<EOL>fmant = float(mant)<EOL>if (not frac_length) or (fmant == int(fmant)):<EOL><INDENT>return "<STR_LIT>".format(<EOL>sign="<STR_LIT:+>" if sign_always and (fmant >= <NUM_LIT:0>) else "<STR_LIT>",<EOL>mant=mant,<EOL>period="<STR_LIT:.>" if frac_length else "<STR_LIT>",<EOL>zeros="<STR_LIT:0>" * frac_length if frac_length else "<STR_LIT>",<EOL>exp_sign="<STR_LIT:->" if exp < <NUM_LIT:0> else "<STR_LIT:+>",<EOL>exp=str(abs(exp)).rjust(exp_length, "<STR_LIT:0>"),<EOL>)<EOL><DEDENT>rounded_mant = round(fmant, frac_length)<EOL>if abs(rounded_mant) == <NUM_LIT:10>:<EOL><INDENT>rounded_mant = fmant = -<NUM_LIT:1.0> if number < <NUM_LIT:0> else <NUM_LIT:1.0><EOL>frac_length = <NUM_LIT:1><EOL>exp = exp + <NUM_LIT:1><EOL><DEDENT>zeros = <NUM_LIT:2> + (<NUM_LIT:1> if (fmant < <NUM_LIT:0>) else <NUM_LIT:0>) + frac_length - len(str(rounded_mant))<EOL>return "<STR_LIT>".format(<EOL>sign="<STR_LIT:+>" if sign_always and (fmant >= <NUM_LIT:0>) else "<STR_LIT>",<EOL>mant=rounded_mant,<EOL>zeros="<STR_LIT:0>" * zeros,<EOL>exp_sign="<STR_LIT:->" if exp < <NUM_LIT:0> else "<STR_LIT:+>",<EOL>exp=str(abs(exp)).rjust(exp_length, "<STR_LIT:0>"),<EOL>)<EOL>

Convert number or number string to a number string in scientific notation.

Full precision is maintained if the number is represented as a string

:param number: Number to convert
:type  number: number or string

:param frac_length: Number of digits of fractional part, None indicates
                    that the fractional part of the number should not be
                    limited
:type  frac_length: integer or None

:param exp_length: Number of digits of the exponent; the actual length of
                   the exponent takes precedence if it is longer
:type  exp_length: integer or None

:param sign_always: Flag that indicates whether the sign always
                    precedes the number for both non-negative and negative
                    numbers (True) or only for negative numbers (False)
:type  sign_always: boolean

:rtype: string

For example:

    >>> import peng
    >>> peng.to_scientific_string(333)
    '3.33E+2'
    >>> peng.to_scientific_string(0.00101)
    '1.01E-3'
    >>> peng.to_scientific_string(99.999, 1, 2, True)
    '+1.0E+02'


<EOL>convert = not isinstance(number, str)<EOL>if (convert and (number == <NUM_LIT:0>)) or (<EOL>(not convert) and (not number.strip("<STR_LIT:0>").strip("<STR_LIT:.>"))<EOL>):<EOL><INDENT>return ("<STR_LIT:0>", <NUM_LIT:0>)<EOL><DEDENT>sign, digits, exp = Decimal(str(number) if convert else number).as_tuple()<EOL>mant = (<EOL>"<STR_LIT>".format(<EOL>sign="<STR_LIT:->" if sign else "<STR_LIT>",<EOL>itg=digits[<NUM_LIT:0>],<EOL>frac=(<EOL>"<STR_LIT>".format(frac="<STR_LIT>".join([str(num) for num in digits[<NUM_LIT:1>:]]))<EOL>if len(digits) > <NUM_LIT:1><EOL>else "<STR_LIT>"<EOL>),<EOL>)<EOL>.rstrip("<STR_LIT:0>")<EOL>.rstrip("<STR_LIT:.>")<EOL>)<EOL>exp += len(digits) - <NUM_LIT:1><EOL>return NumComp(mant, exp)<EOL>

Return mantissa and exponent of a number in scientific notation.

Full precision is maintained if the number is represented as a string

:param number: Number
:type  number: integer, float or string

:rtype: named tuple in which the first item is the mantissa (*string*)
        and the second item is the exponent (*integer*) of the number
        when expressed in scientific notation

For example:

    >>> import peng
    >>> peng.to_scientific_tuple('135.56E-8')
    NumComp(mant='1.3556', exp=-6)
    >>> peng.to_scientific_tuple(0.0000013556)
    NumComp(mant='1.3556', exp=-6)


indep_vector = _get_indep_vector(wave_a, wave_b)<EOL>dep_vector_a = _interp_dep_vector(wave_a, indep_vector)<EOL>dep_vector_b = _interp_dep_vector(wave_b, indep_vector)<EOL>return (indep_vector, dep_vector_a, dep_vector_b)<EOL>

Generate combined independent variable vector.

The combination is from two waveforms and the (possibly interpolated)
dependent variable vectors of these two waveforms