repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
OCA/openupgradelib | openupgradelib/openupgrade.py | update_workflow_workitems | def update_workflow_workitems(cr, pool, ref_spec_actions):
"""Find all the workflow items from the target state to set them to
the wanted state.
When a workflow action is removed, from model, the objects whose states
are in these actions need to be set to another to be able to continue the
workflow properly.
Run in pre-migration
:param ref_spec_actions: list of tuples with couple of workflow.action's
external ids. The first id is replaced with the second.
:return: None
.. versionadded:: 7.0
"""
workflow_workitems = pool['workflow.workitem']
ir_model_data_model = pool['ir.model.data']
for (target_external_id, fallback_external_id) in ref_spec_actions:
target_activity = ir_model_data_model.get_object(
cr, SUPERUSER_ID,
target_external_id.split(".")[0],
target_external_id.split(".")[1],
)
fallback_activity = ir_model_data_model.get_object(
cr, SUPERUSER_ID,
fallback_external_id.split(".")[0],
fallback_external_id.split(".")[1],
)
ids = workflow_workitems.search(
cr, SUPERUSER_ID, [('act_id', '=', target_activity.id)]
)
if ids:
logger.info(
"Moving %d items in the removed workflow action (%s) to a "
"fallback action (%s): %s",
len(ids), target_activity.name, fallback_activity.name, ids
)
workflow_workitems.write(
cr, SUPERUSER_ID, ids, {'act_id': fallback_activity.id}
) | python | def update_workflow_workitems(cr, pool, ref_spec_actions):
"""Find all the workflow items from the target state to set them to
the wanted state.
When a workflow action is removed, from model, the objects whose states
are in these actions need to be set to another to be able to continue the
workflow properly.
Run in pre-migration
:param ref_spec_actions: list of tuples with couple of workflow.action's
external ids. The first id is replaced with the second.
:return: None
.. versionadded:: 7.0
"""
workflow_workitems = pool['workflow.workitem']
ir_model_data_model = pool['ir.model.data']
for (target_external_id, fallback_external_id) in ref_spec_actions:
target_activity = ir_model_data_model.get_object(
cr, SUPERUSER_ID,
target_external_id.split(".")[0],
target_external_id.split(".")[1],
)
fallback_activity = ir_model_data_model.get_object(
cr, SUPERUSER_ID,
fallback_external_id.split(".")[0],
fallback_external_id.split(".")[1],
)
ids = workflow_workitems.search(
cr, SUPERUSER_ID, [('act_id', '=', target_activity.id)]
)
if ids:
logger.info(
"Moving %d items in the removed workflow action (%s) to a "
"fallback action (%s): %s",
len(ids), target_activity.name, fallback_activity.name, ids
)
workflow_workitems.write(
cr, SUPERUSER_ID, ids, {'act_id': fallback_activity.id}
) | [
"def",
"update_workflow_workitems",
"(",
"cr",
",",
"pool",
",",
"ref_spec_actions",
")",
":",
"workflow_workitems",
"=",
"pool",
"[",
"'workflow.workitem'",
"]",
"ir_model_data_model",
"=",
"pool",
"[",
"'ir.model.data'",
"]",
"for",
"(",
"target_external_id",
",",... | Find all the workflow items from the target state to set them to
the wanted state.
When a workflow action is removed, from model, the objects whose states
are in these actions need to be set to another to be able to continue the
workflow properly.
Run in pre-migration
:param ref_spec_actions: list of tuples with couple of workflow.action's
external ids. The first id is replaced with the second.
:return: None
.. versionadded:: 7.0 | [
"Find",
"all",
"the",
"workflow",
"items",
"from",
"the",
"target",
"state",
"to",
"set",
"them",
"to",
"the",
"wanted",
"state",
"."
] | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L726-L767 | train | 24,600 |
OCA/openupgradelib | openupgradelib/openupgrade.py | logged_query | def logged_query(cr, query, args=None, skip_no_result=False):
"""
Logs query and affected rows at level DEBUG.
:param query: a query string suitable to pass to cursor.execute()
:param args: a list, tuple or dictionary passed as substitution values
to cursor.execute().
:param skip_no_result: If True, then logging details are only shown
if there are affected records.
"""
if args is None:
args = ()
args = tuple(args) if type(args) == list else args
try:
cr.execute(query, args)
except (ProgrammingError, IntegrityError):
logger.error('Error running %s' % cr.mogrify(query, args))
raise
if not skip_no_result or cr.rowcount:
logger.debug('Running %s', query % args)
logger.debug('%s rows affected', cr.rowcount)
return cr.rowcount | python | def logged_query(cr, query, args=None, skip_no_result=False):
"""
Logs query and affected rows at level DEBUG.
:param query: a query string suitable to pass to cursor.execute()
:param args: a list, tuple or dictionary passed as substitution values
to cursor.execute().
:param skip_no_result: If True, then logging details are only shown
if there are affected records.
"""
if args is None:
args = ()
args = tuple(args) if type(args) == list else args
try:
cr.execute(query, args)
except (ProgrammingError, IntegrityError):
logger.error('Error running %s' % cr.mogrify(query, args))
raise
if not skip_no_result or cr.rowcount:
logger.debug('Running %s', query % args)
logger.debug('%s rows affected', cr.rowcount)
return cr.rowcount | [
"def",
"logged_query",
"(",
"cr",
",",
"query",
",",
"args",
"=",
"None",
",",
"skip_no_result",
"=",
"False",
")",
":",
"if",
"args",
"is",
"None",
":",
"args",
"=",
"(",
")",
"args",
"=",
"tuple",
"(",
"args",
")",
"if",
"type",
"(",
"args",
")... | Logs query and affected rows at level DEBUG.
:param query: a query string suitable to pass to cursor.execute()
:param args: a list, tuple or dictionary passed as substitution values
to cursor.execute().
:param skip_no_result: If True, then logging details are only shown
if there are affected records. | [
"Logs",
"query",
"and",
"affected",
"rows",
"at",
"level",
"DEBUG",
"."
] | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L959-L980 | train | 24,601 |
OCA/openupgradelib | openupgradelib/openupgrade.py | update_module_names | def update_module_names(cr, namespec, merge_modules=False):
"""Deal with changed module names, making all the needed changes on the
related tables, like XML-IDs, translations, and so on.
:param namespec: list of tuples of (old name, new name)
:param merge_modules: Specify if the operation should be a merge instead
of just a renaming.
"""
for (old_name, new_name) in namespec:
if merge_modules:
# Delete meta entries, that will avoid the entry removal
# They will be recreated by the new module anyhow.
query = "SELECT id FROM ir_module_module WHERE name = %s"
cr.execute(query, [old_name])
row = cr.fetchone()
if row:
old_id = row[0]
query = "DELETE FROM ir_model_constraint WHERE module = %s"
logged_query(cr, query, [old_id])
query = "DELETE FROM ir_model_relation WHERE module = %s"
logged_query(cr, query, [old_id])
else:
query = "UPDATE ir_module_module SET name = %s WHERE name = %s"
logged_query(cr, query, (new_name, old_name))
query = ("UPDATE ir_model_data SET name = %s "
"WHERE name = %s AND module = 'base' AND "
"model='ir.module.module' ")
logged_query(cr, query,
("module_%s" % new_name, "module_%s" % old_name))
# The subselect allows to avoid duplicated XML-IDs
query = ("UPDATE ir_model_data SET module = %s "
"WHERE module = %s AND name NOT IN "
"(SELECT name FROM ir_model_data WHERE module = %s)")
logged_query(cr, query, (new_name, old_name, new_name))
# Rename the remaining occurrences for let Odoo's update process
# to auto-remove related resources
query = ("UPDATE ir_model_data "
"SET name = name || '_openupgrade_' || id, "
"module = %s "
"WHERE module = %s")
logged_query(cr, query, (new_name, old_name))
query = ("UPDATE ir_module_module_dependency SET name = %s "
"WHERE name = %s")
logged_query(cr, query, (new_name, old_name))
if version_info[0] > 7:
query = ("UPDATE ir_translation SET module = %s "
"WHERE module = %s")
logged_query(cr, query, (new_name, old_name))
if merge_modules:
# Conserve old_name's state if new_name is uninstalled
logged_query(
cr,
"UPDATE ir_module_module m1 SET state=m2.state "
"FROM ir_module_module m2 WHERE m1.name=%s AND "
"m2.name=%s AND m1.state='uninstalled'",
(new_name, old_name),
)
query = "DELETE FROM ir_module_module WHERE name = %s"
logged_query(cr, query, [old_name])
logged_query(
cr,
"DELETE FROM ir_model_data WHERE module = 'base' "
"AND model='ir.module.module' AND name = %s",
('module_%s' % old_name,),
) | python | def update_module_names(cr, namespec, merge_modules=False):
"""Deal with changed module names, making all the needed changes on the
related tables, like XML-IDs, translations, and so on.
:param namespec: list of tuples of (old name, new name)
:param merge_modules: Specify if the operation should be a merge instead
of just a renaming.
"""
for (old_name, new_name) in namespec:
if merge_modules:
# Delete meta entries, that will avoid the entry removal
# They will be recreated by the new module anyhow.
query = "SELECT id FROM ir_module_module WHERE name = %s"
cr.execute(query, [old_name])
row = cr.fetchone()
if row:
old_id = row[0]
query = "DELETE FROM ir_model_constraint WHERE module = %s"
logged_query(cr, query, [old_id])
query = "DELETE FROM ir_model_relation WHERE module = %s"
logged_query(cr, query, [old_id])
else:
query = "UPDATE ir_module_module SET name = %s WHERE name = %s"
logged_query(cr, query, (new_name, old_name))
query = ("UPDATE ir_model_data SET name = %s "
"WHERE name = %s AND module = 'base' AND "
"model='ir.module.module' ")
logged_query(cr, query,
("module_%s" % new_name, "module_%s" % old_name))
# The subselect allows to avoid duplicated XML-IDs
query = ("UPDATE ir_model_data SET module = %s "
"WHERE module = %s AND name NOT IN "
"(SELECT name FROM ir_model_data WHERE module = %s)")
logged_query(cr, query, (new_name, old_name, new_name))
# Rename the remaining occurrences for let Odoo's update process
# to auto-remove related resources
query = ("UPDATE ir_model_data "
"SET name = name || '_openupgrade_' || id, "
"module = %s "
"WHERE module = %s")
logged_query(cr, query, (new_name, old_name))
query = ("UPDATE ir_module_module_dependency SET name = %s "
"WHERE name = %s")
logged_query(cr, query, (new_name, old_name))
if version_info[0] > 7:
query = ("UPDATE ir_translation SET module = %s "
"WHERE module = %s")
logged_query(cr, query, (new_name, old_name))
if merge_modules:
# Conserve old_name's state if new_name is uninstalled
logged_query(
cr,
"UPDATE ir_module_module m1 SET state=m2.state "
"FROM ir_module_module m2 WHERE m1.name=%s AND "
"m2.name=%s AND m1.state='uninstalled'",
(new_name, old_name),
)
query = "DELETE FROM ir_module_module WHERE name = %s"
logged_query(cr, query, [old_name])
logged_query(
cr,
"DELETE FROM ir_model_data WHERE module = 'base' "
"AND model='ir.module.module' AND name = %s",
('module_%s' % old_name,),
) | [
"def",
"update_module_names",
"(",
"cr",
",",
"namespec",
",",
"merge_modules",
"=",
"False",
")",
":",
"for",
"(",
"old_name",
",",
"new_name",
")",
"in",
"namespec",
":",
"if",
"merge_modules",
":",
"# Delete meta entries, that will avoid the entry removal",
"# Th... | Deal with changed module names, making all the needed changes on the
related tables, like XML-IDs, translations, and so on.
:param namespec: list of tuples of (old name, new name)
:param merge_modules: Specify if the operation should be a merge instead
of just a renaming. | [
"Deal",
"with",
"changed",
"module",
"names",
"making",
"all",
"the",
"needed",
"changes",
"on",
"the",
"related",
"tables",
"like",
"XML",
"-",
"IDs",
"translations",
"and",
"so",
"on",
"."
] | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L983-L1047 | train | 24,602 |
OCA/openupgradelib | openupgradelib/openupgrade.py | add_ir_model_fields | def add_ir_model_fields(cr, columnspec):
"""
Typically, new columns on ir_model_fields need to be added in a very
early stage in the upgrade process of the base module, in raw sql
as they need to be in place before any model gets initialized.
Do not use for fields with additional SQL constraints, such as a
reference to another table or the cascade constraint, but craft your
own statement taking them into account.
:param columnspec: tuple of (column name, column type)
"""
for column in columnspec:
query = 'ALTER TABLE ir_model_fields ADD COLUMN %s %s' % (
column)
logged_query(cr, query, []) | python | def add_ir_model_fields(cr, columnspec):
"""
Typically, new columns on ir_model_fields need to be added in a very
early stage in the upgrade process of the base module, in raw sql
as they need to be in place before any model gets initialized.
Do not use for fields with additional SQL constraints, such as a
reference to another table or the cascade constraint, but craft your
own statement taking them into account.
:param columnspec: tuple of (column name, column type)
"""
for column in columnspec:
query = 'ALTER TABLE ir_model_fields ADD COLUMN %s %s' % (
column)
logged_query(cr, query, []) | [
"def",
"add_ir_model_fields",
"(",
"cr",
",",
"columnspec",
")",
":",
"for",
"column",
"in",
"columnspec",
":",
"query",
"=",
"'ALTER TABLE ir_model_fields ADD COLUMN %s %s'",
"%",
"(",
"column",
")",
"logged_query",
"(",
"cr",
",",
"query",
",",
"[",
"]",
")"... | Typically, new columns on ir_model_fields need to be added in a very
early stage in the upgrade process of the base module, in raw sql
as they need to be in place before any model gets initialized.
Do not use for fields with additional SQL constraints, such as a
reference to another table or the cascade constraint, but craft your
own statement taking them into account.
:param columnspec: tuple of (column name, column type) | [
"Typically",
"new",
"columns",
"on",
"ir_model_fields",
"need",
"to",
"be",
"added",
"in",
"a",
"very",
"early",
"stage",
"in",
"the",
"upgrade",
"process",
"of",
"the",
"base",
"module",
"in",
"raw",
"sql",
"as",
"they",
"need",
"to",
"be",
"in",
"place... | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L1050-L1064 | train | 24,603 |
OCA/openupgradelib | openupgradelib/openupgrade.py | m2o_to_m2m | def m2o_to_m2m(cr, model, table, field, source_field):
"""
Recreate relations in many2many fields that were formerly
many2one fields. Use rename_columns in your pre-migrate
script to retain the column's old value, then call m2o_to_m2m
in your post-migrate script.
:param model: The target model registry object
:param table: The source table
:param field: The field name of the target model
:param source_field: the many2one column on the source table.
.. versionadded:: 7.0
.. deprecated:: 8.0
Use :func:`m2o_to_x2m` instead.
"""
return m2o_to_x2m(cr, model, table, field, source_field) | python | def m2o_to_m2m(cr, model, table, field, source_field):
"""
Recreate relations in many2many fields that were formerly
many2one fields. Use rename_columns in your pre-migrate
script to retain the column's old value, then call m2o_to_m2m
in your post-migrate script.
:param model: The target model registry object
:param table: The source table
:param field: The field name of the target model
:param source_field: the many2one column on the source table.
.. versionadded:: 7.0
.. deprecated:: 8.0
Use :func:`m2o_to_x2m` instead.
"""
return m2o_to_x2m(cr, model, table, field, source_field) | [
"def",
"m2o_to_m2m",
"(",
"cr",
",",
"model",
",",
"table",
",",
"field",
",",
"source_field",
")",
":",
"return",
"m2o_to_x2m",
"(",
"cr",
",",
"model",
",",
"table",
",",
"field",
",",
"source_field",
")"
] | Recreate relations in many2many fields that were formerly
many2one fields. Use rename_columns in your pre-migrate
script to retain the column's old value, then call m2o_to_m2m
in your post-migrate script.
:param model: The target model registry object
:param table: The source table
:param field: The field name of the target model
:param source_field: the many2one column on the source table.
.. versionadded:: 7.0
.. deprecated:: 8.0
Use :func:`m2o_to_x2m` instead. | [
"Recreate",
"relations",
"in",
"many2many",
"fields",
"that",
"were",
"formerly",
"many2one",
"fields",
".",
"Use",
"rename_columns",
"in",
"your",
"pre",
"-",
"migrate",
"script",
"to",
"retain",
"the",
"column",
"s",
"old",
"value",
"then",
"call",
"m2o_to_m... | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L1154-L1170 | train | 24,604 |
OCA/openupgradelib | openupgradelib/openupgrade.py | message | def message(cr, module, table, column,
message, *args, **kwargs):
"""
Log handler for non-critical notifications about the upgrade.
To be extended with logging to a table for reporting purposes.
:param module: the module name that the message concerns
:param table: the model that this message concerns (may be False, \
but preferably not if 'column' is defined)
:param column: the column that this message concerns (may be False)
.. versionadded:: 7.0
"""
argslist = list(args or [])
prefix = ': '
if column:
argslist.insert(0, column)
prefix = ', column %s' + prefix
if table:
argslist.insert(0, table)
prefix = ', table %s' + prefix
argslist.insert(0, module)
prefix = 'Module %s' + prefix
logger.warn(prefix + message, *argslist, **kwargs) | python | def message(cr, module, table, column,
message, *args, **kwargs):
"""
Log handler for non-critical notifications about the upgrade.
To be extended with logging to a table for reporting purposes.
:param module: the module name that the message concerns
:param table: the model that this message concerns (may be False, \
but preferably not if 'column' is defined)
:param column: the column that this message concerns (may be False)
.. versionadded:: 7.0
"""
argslist = list(args or [])
prefix = ': '
if column:
argslist.insert(0, column)
prefix = ', column %s' + prefix
if table:
argslist.insert(0, table)
prefix = ', table %s' + prefix
argslist.insert(0, module)
prefix = 'Module %s' + prefix
logger.warn(prefix + message, *argslist, **kwargs) | [
"def",
"message",
"(",
"cr",
",",
"module",
",",
"table",
",",
"column",
",",
"message",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"argslist",
"=",
"list",
"(",
"args",
"or",
"[",
"]",
")",
"prefix",
"=",
"': '",
"if",
"column",
":",
... | Log handler for non-critical notifications about the upgrade.
To be extended with logging to a table for reporting purposes.
:param module: the module name that the message concerns
:param table: the model that this message concerns (may be False, \
but preferably not if 'column' is defined)
:param column: the column that this message concerns (may be False)
.. versionadded:: 7.0 | [
"Log",
"handler",
"for",
"non",
"-",
"critical",
"notifications",
"about",
"the",
"upgrade",
".",
"To",
"be",
"extended",
"with",
"logging",
"to",
"a",
"table",
"for",
"reporting",
"purposes",
"."
] | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L1271-L1295 | train | 24,605 |
OCA/openupgradelib | openupgradelib/openupgrade.py | reactivate_workflow_transitions | def reactivate_workflow_transitions(cr, transition_conditions):
"""
Reactivate workflow transition previously deactivated by
deactivate_workflow_transitions.
:param transition_conditions: a dictionary returned by \
deactivate_workflow_transitions
.. versionadded:: 7.0
.. deprecated:: 11.0
Workflows were removed from Odoo as of version 11.0
"""
for transition_id, condition in transition_conditions.iteritems():
cr.execute(
'update wkf_transition set condition = %s where id = %s',
(condition, transition_id)) | python | def reactivate_workflow_transitions(cr, transition_conditions):
"""
Reactivate workflow transition previously deactivated by
deactivate_workflow_transitions.
:param transition_conditions: a dictionary returned by \
deactivate_workflow_transitions
.. versionadded:: 7.0
.. deprecated:: 11.0
Workflows were removed from Odoo as of version 11.0
"""
for transition_id, condition in transition_conditions.iteritems():
cr.execute(
'update wkf_transition set condition = %s where id = %s',
(condition, transition_id)) | [
"def",
"reactivate_workflow_transitions",
"(",
"cr",
",",
"transition_conditions",
")",
":",
"for",
"transition_id",
",",
"condition",
"in",
"transition_conditions",
".",
"iteritems",
"(",
")",
":",
"cr",
".",
"execute",
"(",
"'update wkf_transition set condition = %s w... | Reactivate workflow transition previously deactivated by
deactivate_workflow_transitions.
:param transition_conditions: a dictionary returned by \
deactivate_workflow_transitions
.. versionadded:: 7.0
.. deprecated:: 11.0
Workflows were removed from Odoo as of version 11.0 | [
"Reactivate",
"workflow",
"transition",
"previously",
"deactivated",
"by",
"deactivate_workflow_transitions",
"."
] | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L1342-L1357 | train | 24,606 |
OCA/openupgradelib | openupgradelib/openupgrade.py | convert_field_to_html | def convert_field_to_html(cr, table, field_name, html_field_name):
"""
Convert field value to HTML value.
.. versionadded:: 7.0
"""
if version_info[0] < 7:
logger.error("You cannot use this method in an OpenUpgrade version "
"prior to 7.0.")
return
cr.execute(
"SELECT id, %(field)s FROM %(table)s WHERE %(field)s IS NOT NULL" % {
'field': field_name,
'table': table,
}
)
for row in cr.fetchall():
logged_query(
cr, "UPDATE %(table)s SET %(field)s = %%s WHERE id = %%s" % {
'field': html_field_name,
'table': table,
}, (plaintext2html(row[1]), row[0])
) | python | def convert_field_to_html(cr, table, field_name, html_field_name):
"""
Convert field value to HTML value.
.. versionadded:: 7.0
"""
if version_info[0] < 7:
logger.error("You cannot use this method in an OpenUpgrade version "
"prior to 7.0.")
return
cr.execute(
"SELECT id, %(field)s FROM %(table)s WHERE %(field)s IS NOT NULL" % {
'field': field_name,
'table': table,
}
)
for row in cr.fetchall():
logged_query(
cr, "UPDATE %(table)s SET %(field)s = %%s WHERE id = %%s" % {
'field': html_field_name,
'table': table,
}, (plaintext2html(row[1]), row[0])
) | [
"def",
"convert_field_to_html",
"(",
"cr",
",",
"table",
",",
"field_name",
",",
"html_field_name",
")",
":",
"if",
"version_info",
"[",
"0",
"]",
"<",
"7",
":",
"logger",
".",
"error",
"(",
"\"You cannot use this method in an OpenUpgrade version \"",
"\"prior to 7.... | Convert field value to HTML value.
.. versionadded:: 7.0 | [
"Convert",
"field",
"value",
"to",
"HTML",
"value",
"."
] | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L1623-L1645 | train | 24,607 |
OCA/openupgradelib | openupgradelib/openupgrade.py | lift_constraints | def lift_constraints(cr, table, column):
"""Lift all constraints on column in table.
Typically, you use this in a pre-migrate script where you adapt references
for many2one fields with changed target objects.
If everything went right, the constraints will be recreated"""
cr.execute(
'select relname, array_agg(conname) from '
'(select t1.relname, c.conname '
'from pg_constraint c '
'join pg_attribute a '
'on c.confrelid=a.attrelid and a.attnum=any(c.conkey) '
'join pg_class t on t.oid=a.attrelid '
'join pg_class t1 on t1.oid=c.conrelid '
'where t.relname=%(table)s and attname=%(column)s '
'union select t.relname, c.conname '
'from pg_constraint c '
'join pg_attribute a '
'on c.conrelid=a.attrelid and a.attnum=any(c.conkey) '
'join pg_class t on t.oid=a.attrelid '
'where relname=%(table)s and attname=%(column)s) in_out '
'group by relname',
{
'table': table,
'column': column,
})
for table, constraints in cr.fetchall():
cr.execute(
'alter table %s drop constraint %s',
(AsIs(table), AsIs(', drop constraint '.join(constraints)))
) | python | def lift_constraints(cr, table, column):
"""Lift all constraints on column in table.
Typically, you use this in a pre-migrate script where you adapt references
for many2one fields with changed target objects.
If everything went right, the constraints will be recreated"""
cr.execute(
'select relname, array_agg(conname) from '
'(select t1.relname, c.conname '
'from pg_constraint c '
'join pg_attribute a '
'on c.confrelid=a.attrelid and a.attnum=any(c.conkey) '
'join pg_class t on t.oid=a.attrelid '
'join pg_class t1 on t1.oid=c.conrelid '
'where t.relname=%(table)s and attname=%(column)s '
'union select t.relname, c.conname '
'from pg_constraint c '
'join pg_attribute a '
'on c.conrelid=a.attrelid and a.attnum=any(c.conkey) '
'join pg_class t on t.oid=a.attrelid '
'where relname=%(table)s and attname=%(column)s) in_out '
'group by relname',
{
'table': table,
'column': column,
})
for table, constraints in cr.fetchall():
cr.execute(
'alter table %s drop constraint %s',
(AsIs(table), AsIs(', drop constraint '.join(constraints)))
) | [
"def",
"lift_constraints",
"(",
"cr",
",",
"table",
",",
"column",
")",
":",
"cr",
".",
"execute",
"(",
"'select relname, array_agg(conname) from '",
"'(select t1.relname, c.conname '",
"'from pg_constraint c '",
"'join pg_attribute a '",
"'on c.confrelid=a.attrelid and a.attnum=... | Lift all constraints on column in table.
Typically, you use this in a pre-migrate script where you adapt references
for many2one fields with changed target objects.
If everything went right, the constraints will be recreated | [
"Lift",
"all",
"constraints",
"on",
"column",
"in",
"table",
".",
"Typically",
"you",
"use",
"this",
"in",
"a",
"pre",
"-",
"migrate",
"script",
"where",
"you",
"adapt",
"references",
"for",
"many2one",
"fields",
"with",
"changed",
"target",
"objects",
".",
... | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L1704-L1733 | train | 24,608 |
OCA/openupgradelib | openupgradelib/openupgrade.py | savepoint | def savepoint(cr):
"""return a context manager wrapping postgres savepoints"""
if hasattr(cr, 'savepoint'):
with cr.savepoint():
yield
else:
name = uuid.uuid1().hex
cr.execute('SAVEPOINT "%s"' % name)
try:
yield
cr.execute('RELEASE SAVEPOINT "%s"' % name)
except:
cr.execute('ROLLBACK TO SAVEPOINT "%s"' % name) | python | def savepoint(cr):
"""return a context manager wrapping postgres savepoints"""
if hasattr(cr, 'savepoint'):
with cr.savepoint():
yield
else:
name = uuid.uuid1().hex
cr.execute('SAVEPOINT "%s"' % name)
try:
yield
cr.execute('RELEASE SAVEPOINT "%s"' % name)
except:
cr.execute('ROLLBACK TO SAVEPOINT "%s"' % name) | [
"def",
"savepoint",
"(",
"cr",
")",
":",
"if",
"hasattr",
"(",
"cr",
",",
"'savepoint'",
")",
":",
"with",
"cr",
".",
"savepoint",
"(",
")",
":",
"yield",
"else",
":",
"name",
"=",
"uuid",
".",
"uuid1",
"(",
")",
".",
"hex",
"cr",
".",
"execute",... | return a context manager wrapping postgres savepoints | [
"return",
"a",
"context",
"manager",
"wrapping",
"postgres",
"savepoints"
] | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L1737-L1749 | train | 24,609 |
OCA/openupgradelib | openupgradelib/openupgrade.py | rename_property | def rename_property(cr, model, old_name, new_name):
"""Rename property old_name owned by model to new_name. This should happen
in a pre-migration script."""
cr.execute(
"update ir_model_fields f set name=%s "
"from ir_model m "
"where m.id=f.model_id and m.model=%s and f.name=%s "
"returning f.id",
(new_name, model, old_name))
field_ids = tuple(i for i, in cr.fetchall())
cr.execute(
"update ir_model_data set name=%s where model='ir.model.fields' and "
"res_id in %s",
('%s,%s' % (model, new_name), field_ids))
cr.execute(
"update ir_property set name=%s where fields_id in %s",
(new_name, field_ids)) | python | def rename_property(cr, model, old_name, new_name):
"""Rename property old_name owned by model to new_name. This should happen
in a pre-migration script."""
cr.execute(
"update ir_model_fields f set name=%s "
"from ir_model m "
"where m.id=f.model_id and m.model=%s and f.name=%s "
"returning f.id",
(new_name, model, old_name))
field_ids = tuple(i for i, in cr.fetchall())
cr.execute(
"update ir_model_data set name=%s where model='ir.model.fields' and "
"res_id in %s",
('%s,%s' % (model, new_name), field_ids))
cr.execute(
"update ir_property set name=%s where fields_id in %s",
(new_name, field_ids)) | [
"def",
"rename_property",
"(",
"cr",
",",
"model",
",",
"old_name",
",",
"new_name",
")",
":",
"cr",
".",
"execute",
"(",
"\"update ir_model_fields f set name=%s \"",
"\"from ir_model m \"",
"\"where m.id=f.model_id and m.model=%s and f.name=%s \"",
"\"returning f.id\"",
",",... | Rename property old_name owned by model to new_name. This should happen
in a pre-migration script. | [
"Rename",
"property",
"old_name",
"owned",
"by",
"model",
"to",
"new_name",
".",
"This",
"should",
"happen",
"in",
"a",
"pre",
"-",
"migration",
"script",
"."
] | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L1752-L1768 | train | 24,610 |
OCA/openupgradelib | openupgradelib/openupgrade.py | delete_records_safely_by_xml_id | def delete_records_safely_by_xml_id(env, xml_ids):
"""This removes in the safest possible way the records whose XML-IDs are
passed as argument.
:param xml_ids: List of XML-ID string identifiers of the records to remove.
"""
for xml_id in xml_ids:
logger.debug('Deleting record for XML-ID %s', xml_id)
try:
with env.cr.savepoint():
env.ref(xml_id).exists().unlink()
except Exception as e:
logger.error('Error deleting XML-ID %s: %s', xml_id, repr(e)) | python | def delete_records_safely_by_xml_id(env, xml_ids):
"""This removes in the safest possible way the records whose XML-IDs are
passed as argument.
:param xml_ids: List of XML-ID string identifiers of the records to remove.
"""
for xml_id in xml_ids:
logger.debug('Deleting record for XML-ID %s', xml_id)
try:
with env.cr.savepoint():
env.ref(xml_id).exists().unlink()
except Exception as e:
logger.error('Error deleting XML-ID %s: %s', xml_id, repr(e)) | [
"def",
"delete_records_safely_by_xml_id",
"(",
"env",
",",
"xml_ids",
")",
":",
"for",
"xml_id",
"in",
"xml_ids",
":",
"logger",
".",
"debug",
"(",
"'Deleting record for XML-ID %s'",
",",
"xml_id",
")",
"try",
":",
"with",
"env",
".",
"cr",
".",
"savepoint",
... | This removes in the safest possible way the records whose XML-IDs are
passed as argument.
:param xml_ids: List of XML-ID string identifiers of the records to remove. | [
"This",
"removes",
"in",
"the",
"safest",
"possible",
"way",
"the",
"records",
"whose",
"XML",
"-",
"IDs",
"are",
"passed",
"as",
"argument",
"."
] | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L2034-L2046 | train | 24,611 |
OCA/openupgradelib | openupgradelib/openupgrade.py | chunked | def chunked(records, single=True):
""" Memory and performance friendly method to iterate over a potentially
large number of records. Yields either a whole chunk or a single record
at the time. Don't nest calls to this method. """
if version_info[0] > 10:
invalidate = records.env.cache.invalidate
elif version_info[0] > 7:
invalidate = records.env.invalidate_all
else:
raise Exception('Not supported Odoo version for this method.')
size = core.models.PREFETCH_MAX
model = records._name
ids = records.with_context(prefetch_fields=False).ids
for i in range(0, len(ids), size):
invalidate()
chunk = records.env[model].browse(ids[i:i + size])
if single:
for record in chunk:
yield record
continue
yield chunk | python | def chunked(records, single=True):
""" Memory and performance friendly method to iterate over a potentially
large number of records. Yields either a whole chunk or a single record
at the time. Don't nest calls to this method. """
if version_info[0] > 10:
invalidate = records.env.cache.invalidate
elif version_info[0] > 7:
invalidate = records.env.invalidate_all
else:
raise Exception('Not supported Odoo version for this method.')
size = core.models.PREFETCH_MAX
model = records._name
ids = records.with_context(prefetch_fields=False).ids
for i in range(0, len(ids), size):
invalidate()
chunk = records.env[model].browse(ids[i:i + size])
if single:
for record in chunk:
yield record
continue
yield chunk | [
"def",
"chunked",
"(",
"records",
",",
"single",
"=",
"True",
")",
":",
"if",
"version_info",
"[",
"0",
"]",
">",
"10",
":",
"invalidate",
"=",
"records",
".",
"env",
".",
"cache",
".",
"invalidate",
"elif",
"version_info",
"[",
"0",
"]",
">",
"7",
... | Memory and performance friendly method to iterate over a potentially
large number of records. Yields either a whole chunk or a single record
at the time. Don't nest calls to this method. | [
"Memory",
"and",
"performance",
"friendly",
"method",
"to",
"iterate",
"over",
"a",
"potentially",
"large",
"number",
"of",
"records",
".",
"Yields",
"either",
"a",
"whole",
"chunk",
"or",
"a",
"single",
"record",
"at",
"the",
"time",
".",
"Don",
"t",
"nes... | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L2049-L2069 | train | 24,612 |
OCA/openupgradelib | openupgradelib/openupgrade_80.py | get_last_post_for_model | def get_last_post_for_model(cr, uid, ids, model_pool):
"""
Given a set of ids and a model pool, return a dict of each object ids with
their latest message date as a value.
To be called in post-migration scripts
:param cr: database cursor
:param uid: user id, assumed to be openerp.SUPERUSER_ID
:param ids: ids of the model in question to retrieve ids
:param model_pool: orm model pool, assumed to be from pool.get()
:return: a dict with ids as keys and with dates as values
"""
if type(ids) is not list:
ids = [ids]
res = {}
for obj in model_pool.browse(cr, uid, ids):
message_ids = obj.message_ids
if message_ids:
res[obj.id] = sorted(
message_ids, key=lambda x: x.date, reverse=True)[0].date
else:
res[obj.id] = False
return res | python | def get_last_post_for_model(cr, uid, ids, model_pool):
"""
Given a set of ids and a model pool, return a dict of each object ids with
their latest message date as a value.
To be called in post-migration scripts
:param cr: database cursor
:param uid: user id, assumed to be openerp.SUPERUSER_ID
:param ids: ids of the model in question to retrieve ids
:param model_pool: orm model pool, assumed to be from pool.get()
:return: a dict with ids as keys and with dates as values
"""
if type(ids) is not list:
ids = [ids]
res = {}
for obj in model_pool.browse(cr, uid, ids):
message_ids = obj.message_ids
if message_ids:
res[obj.id] = sorted(
message_ids, key=lambda x: x.date, reverse=True)[0].date
else:
res[obj.id] = False
return res | [
"def",
"get_last_post_for_model",
"(",
"cr",
",",
"uid",
",",
"ids",
",",
"model_pool",
")",
":",
"if",
"type",
"(",
"ids",
")",
"is",
"not",
"list",
":",
"ids",
"=",
"[",
"ids",
"]",
"res",
"=",
"{",
"}",
"for",
"obj",
"in",
"model_pool",
".",
"... | Given a set of ids and a model pool, return a dict of each object ids with
their latest message date as a value.
To be called in post-migration scripts
:param cr: database cursor
:param uid: user id, assumed to be openerp.SUPERUSER_ID
:param ids: ids of the model in question to retrieve ids
:param model_pool: orm model pool, assumed to be from pool.get()
:return: a dict with ids as keys and with dates as values | [
"Given",
"a",
"set",
"of",
"ids",
"and",
"a",
"model",
"pool",
"return",
"a",
"dict",
"of",
"each",
"object",
"ids",
"with",
"their",
"latest",
"message",
"date",
"as",
"a",
"value",
".",
"To",
"be",
"called",
"in",
"post",
"-",
"migration",
"scripts"
... | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade_80.py#L34-L56 | train | 24,613 |
OCA/openupgradelib | openupgradelib/openupgrade_80.py | set_message_last_post | def set_message_last_post(cr, uid, pool, models):
"""
Given a list of models, set their 'message_last_post' fields to an
estimated last post datetime.
To be called in post-migration scripts
:param cr: database cursor
:param uid: user id, assumed to be openerp.SUPERUSER_ID
:param pool: orm pool, assumed to be openerp.pooler.get_pool(cr.dbname)
:param models: a list of model names for which 'message_last_post' needs \
to be filled
:return:
"""
if type(models) is not list:
models = [models]
for model in models:
model_pool = pool[model]
cr.execute(
"UPDATE {table} "
"SET message_last_post=(SELECT max(mm.date) "
"FROM mail_message mm "
"WHERE mm.model=%s "
"AND mm.date IS NOT NULL "
"AND mm.res_id={table}.id)".format(
table=model_pool._table), (model,)
) | python | def set_message_last_post(cr, uid, pool, models):
"""
Given a list of models, set their 'message_last_post' fields to an
estimated last post datetime.
To be called in post-migration scripts
:param cr: database cursor
:param uid: user id, assumed to be openerp.SUPERUSER_ID
:param pool: orm pool, assumed to be openerp.pooler.get_pool(cr.dbname)
:param models: a list of model names for which 'message_last_post' needs \
to be filled
:return:
"""
if type(models) is not list:
models = [models]
for model in models:
model_pool = pool[model]
cr.execute(
"UPDATE {table} "
"SET message_last_post=(SELECT max(mm.date) "
"FROM mail_message mm "
"WHERE mm.model=%s "
"AND mm.date IS NOT NULL "
"AND mm.res_id={table}.id)".format(
table=model_pool._table), (model,)
) | [
"def",
"set_message_last_post",
"(",
"cr",
",",
"uid",
",",
"pool",
",",
"models",
")",
":",
"if",
"type",
"(",
"models",
")",
"is",
"not",
"list",
":",
"models",
"=",
"[",
"models",
"]",
"for",
"model",
"in",
"models",
":",
"model_pool",
"=",
"pool"... | Given a list of models, set their 'message_last_post' fields to an
estimated last post datetime.
To be called in post-migration scripts
:param cr: database cursor
:param uid: user id, assumed to be openerp.SUPERUSER_ID
:param pool: orm pool, assumed to be openerp.pooler.get_pool(cr.dbname)
:param models: a list of model names for which 'message_last_post' needs \
to be filled
:return: | [
"Given",
"a",
"list",
"of",
"models",
"set",
"their",
"message_last_post",
"fields",
"to",
"an",
"estimated",
"last",
"post",
"datetime",
".",
"To",
"be",
"called",
"in",
"post",
"-",
"migration",
"scripts"
] | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade_80.py#L59-L84 | train | 24,614 |
OCA/openupgradelib | openupgradelib/openupgrade_tools.py | column_exists | def column_exists(cr, table, column):
""" Check whether a certain column exists """
cr.execute(
'SELECT count(attname) FROM pg_attribute '
'WHERE attrelid = '
'( SELECT oid FROM pg_class WHERE relname = %s ) '
'AND attname = %s',
(table, column))
return cr.fetchone()[0] == 1 | python | def column_exists(cr, table, column):
""" Check whether a certain column exists """
cr.execute(
'SELECT count(attname) FROM pg_attribute '
'WHERE attrelid = '
'( SELECT oid FROM pg_class WHERE relname = %s ) '
'AND attname = %s',
(table, column))
return cr.fetchone()[0] == 1 | [
"def",
"column_exists",
"(",
"cr",
",",
"table",
",",
"column",
")",
":",
"cr",
".",
"execute",
"(",
"'SELECT count(attname) FROM pg_attribute '",
"'WHERE attrelid = '",
"'( SELECT oid FROM pg_class WHERE relname = %s ) '",
"'AND attname = %s'",
",",
"(",
"table",
",",
"c... | Check whether a certain column exists | [
"Check",
"whether",
"a",
"certain",
"column",
"exists"
] | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade_tools.py#L32-L40 | train | 24,615 |
crossbario/txaio | txaio/aio.py | start_logging | def start_logging(out=_stdout, level='info'):
"""
Begin logging.
:param out: if provided, a file-like object to log to. By default, this is
stdout.
:param level: the maximum log-level to emit (a string)
"""
global _log_level, _loggers, _started_logging
if level not in log_levels:
raise RuntimeError(
"Invalid log level '{0}'; valid are: {1}".format(
level, ', '.join(log_levels)
)
)
if _started_logging:
return
_started_logging = True
_log_level = level
handler = _TxaioFileHandler(out)
logging.getLogger().addHandler(handler)
# note: Don't need to call basicConfig() or similar, because we've
# now added at least one handler to the root logger
logging.raiseExceptions = True # FIXME
level_to_stdlib = {
'critical': logging.CRITICAL,
'error': logging.ERROR,
'warn': logging.WARNING,
'info': logging.INFO,
'debug': logging.DEBUG,
'trace': logging.DEBUG,
}
logging.getLogger().setLevel(level_to_stdlib[level])
# make sure any loggers we created before now have their log-level
# set (any created after now will get it from _log_level
for logger in _loggers:
logger._set_log_level(level) | python | def start_logging(out=_stdout, level='info'):
"""
Begin logging.
:param out: if provided, a file-like object to log to. By default, this is
stdout.
:param level: the maximum log-level to emit (a string)
"""
global _log_level, _loggers, _started_logging
if level not in log_levels:
raise RuntimeError(
"Invalid log level '{0}'; valid are: {1}".format(
level, ', '.join(log_levels)
)
)
if _started_logging:
return
_started_logging = True
_log_level = level
handler = _TxaioFileHandler(out)
logging.getLogger().addHandler(handler)
# note: Don't need to call basicConfig() or similar, because we've
# now added at least one handler to the root logger
logging.raiseExceptions = True # FIXME
level_to_stdlib = {
'critical': logging.CRITICAL,
'error': logging.ERROR,
'warn': logging.WARNING,
'info': logging.INFO,
'debug': logging.DEBUG,
'trace': logging.DEBUG,
}
logging.getLogger().setLevel(level_to_stdlib[level])
# make sure any loggers we created before now have their log-level
# set (any created after now will get it from _log_level
for logger in _loggers:
logger._set_log_level(level) | [
"def",
"start_logging",
"(",
"out",
"=",
"_stdout",
",",
"level",
"=",
"'info'",
")",
":",
"global",
"_log_level",
",",
"_loggers",
",",
"_started_logging",
"if",
"level",
"not",
"in",
"log_levels",
":",
"raise",
"RuntimeError",
"(",
"\"Invalid log level '{0}'; ... | Begin logging.
:param out: if provided, a file-like object to log to. By default, this is
stdout.
:param level: the maximum log-level to emit (a string) | [
"Begin",
"logging",
"."
] | 29c77ff1210cabd4cc03f16f34672612e7eef704 | https://github.com/crossbario/txaio/blob/29c77ff1210cabd4cc03f16f34672612e7eef704/txaio/aio.py#L283-L322 | train | 24,616 |
crossbario/txaio | txaio/aio.py | _AsyncioApi.create_failure | def create_failure(self, exception=None):
"""
This returns an object implementing IFailedFuture.
If exception is None (the default) we MUST be called within an
"except" block (such that sys.exc_info() returns useful
information).
"""
if exception:
return FailedFuture(type(exception), exception, None)
return FailedFuture(*sys.exc_info()) | python | def create_failure(self, exception=None):
"""
This returns an object implementing IFailedFuture.
If exception is None (the default) we MUST be called within an
"except" block (such that sys.exc_info() returns useful
information).
"""
if exception:
return FailedFuture(type(exception), exception, None)
return FailedFuture(*sys.exc_info()) | [
"def",
"create_failure",
"(",
"self",
",",
"exception",
"=",
"None",
")",
":",
"if",
"exception",
":",
"return",
"FailedFuture",
"(",
"type",
"(",
"exception",
")",
",",
"exception",
",",
"None",
")",
"return",
"FailedFuture",
"(",
"*",
"sys",
".",
"exc_... | This returns an object implementing IFailedFuture.
If exception is None (the default) we MUST be called within an
"except" block (such that sys.exc_info() returns useful
information). | [
"This",
"returns",
"an",
"object",
"implementing",
"IFailedFuture",
"."
] | 29c77ff1210cabd4cc03f16f34672612e7eef704 | https://github.com/crossbario/txaio/blob/29c77ff1210cabd4cc03f16f34672612e7eef704/txaio/aio.py#L495-L505 | train | 24,617 |
crossbario/txaio | txaio/aio.py | _AsyncioApi.gather | def gather(self, futures, consume_exceptions=True):
"""
This returns a Future that waits for all the Futures in the list
``futures``
:param futures: a list of Futures (or coroutines?)
:param consume_exceptions: if True, any errors are eaten and
returned in the result list.
"""
# from the asyncio docs: "If return_exceptions is True, exceptions
# in the tasks are treated the same as successful results, and
# gathered in the result list; otherwise, the first raised
# exception will be immediately propagated to the returned
# future."
return asyncio.gather(*futures, return_exceptions=consume_exceptions) | python | def gather(self, futures, consume_exceptions=True):
"""
This returns a Future that waits for all the Futures in the list
``futures``
:param futures: a list of Futures (or coroutines?)
:param consume_exceptions: if True, any errors are eaten and
returned in the result list.
"""
# from the asyncio docs: "If return_exceptions is True, exceptions
# in the tasks are treated the same as successful results, and
# gathered in the result list; otherwise, the first raised
# exception will be immediately propagated to the returned
# future."
return asyncio.gather(*futures, return_exceptions=consume_exceptions) | [
"def",
"gather",
"(",
"self",
",",
"futures",
",",
"consume_exceptions",
"=",
"True",
")",
":",
"# from the asyncio docs: \"If return_exceptions is True, exceptions",
"# in the tasks are treated the same as successful results, and",
"# gathered in the result list; otherwise, the first ra... | This returns a Future that waits for all the Futures in the list
``futures``
:param futures: a list of Futures (or coroutines?)
:param consume_exceptions: if True, any errors are eaten and
returned in the result list. | [
"This",
"returns",
"a",
"Future",
"that",
"waits",
"for",
"all",
"the",
"Futures",
"in",
"the",
"list",
"futures"
] | 29c77ff1210cabd4cc03f16f34672612e7eef704 | https://github.com/crossbario/txaio/blob/29c77ff1210cabd4cc03f16f34672612e7eef704/txaio/aio.py#L522-L538 | train | 24,618 |
crossbario/txaio | txaio/__init__.py | _use_framework | def _use_framework(module):
"""
Internal helper, to set this modules methods to a specified
framework helper-methods.
"""
import txaio
for method_name in __all__:
if method_name in ['use_twisted', 'use_asyncio']:
continue
setattr(txaio, method_name,
getattr(module, method_name)) | python | def _use_framework(module):
"""
Internal helper, to set this modules methods to a specified
framework helper-methods.
"""
import txaio
for method_name in __all__:
if method_name in ['use_twisted', 'use_asyncio']:
continue
setattr(txaio, method_name,
getattr(module, method_name)) | [
"def",
"_use_framework",
"(",
"module",
")",
":",
"import",
"txaio",
"for",
"method_name",
"in",
"__all__",
":",
"if",
"method_name",
"in",
"[",
"'use_twisted'",
",",
"'use_asyncio'",
"]",
":",
"continue",
"setattr",
"(",
"txaio",
",",
"method_name",
",",
"g... | Internal helper, to set this modules methods to a specified
framework helper-methods. | [
"Internal",
"helper",
"to",
"set",
"this",
"modules",
"methods",
"to",
"a",
"specified",
"framework",
"helper",
"-",
"methods",
"."
] | 29c77ff1210cabd4cc03f16f34672612e7eef704 | https://github.com/crossbario/txaio/blob/29c77ff1210cabd4cc03f16f34672612e7eef704/txaio/__init__.py#L130-L140 | train | 24,619 |
crossbario/txaio | txaio/tx.py | start_logging | def start_logging(out=_stdout, level='info'):
"""
Start logging to the file-like object in ``out``. By default, this
is stdout.
"""
global _loggers, _observer, _log_level, _started_logging
if level not in log_levels:
raise RuntimeError(
"Invalid log level '{0}'; valid are: {1}".format(
level, ', '.join(log_levels)
)
)
if _started_logging:
return
_started_logging = True
_log_level = level
set_global_log_level(_log_level)
if out:
_observer = _LogObserver(out)
if _NEW_LOGGER:
_observers = []
if _observer:
_observers.append(_observer)
globalLogBeginner.beginLoggingTo(_observers)
else:
assert out, "out needs to be given a value if using Twisteds before 15.2"
from twisted.python import log
log.startLogging(out) | python | def start_logging(out=_stdout, level='info'):
"""
Start logging to the file-like object in ``out``. By default, this
is stdout.
"""
global _loggers, _observer, _log_level, _started_logging
if level not in log_levels:
raise RuntimeError(
"Invalid log level '{0}'; valid are: {1}".format(
level, ', '.join(log_levels)
)
)
if _started_logging:
return
_started_logging = True
_log_level = level
set_global_log_level(_log_level)
if out:
_observer = _LogObserver(out)
if _NEW_LOGGER:
_observers = []
if _observer:
_observers.append(_observer)
globalLogBeginner.beginLoggingTo(_observers)
else:
assert out, "out needs to be given a value if using Twisteds before 15.2"
from twisted.python import log
log.startLogging(out) | [
"def",
"start_logging",
"(",
"out",
"=",
"_stdout",
",",
"level",
"=",
"'info'",
")",
":",
"global",
"_loggers",
",",
"_observer",
",",
"_log_level",
",",
"_started_logging",
"if",
"level",
"not",
"in",
"log_levels",
":",
"raise",
"RuntimeError",
"(",
"\"Inv... | Start logging to the file-like object in ``out``. By default, this
is stdout. | [
"Start",
"logging",
"to",
"the",
"file",
"-",
"like",
"object",
"in",
"out",
".",
"By",
"default",
"this",
"is",
"stdout",
"."
] | 29c77ff1210cabd4cc03f16f34672612e7eef704 | https://github.com/crossbario/txaio/blob/29c77ff1210cabd4cc03f16f34672612e7eef704/txaio/tx.py#L332-L365 | train | 24,620 |
crossbario/txaio | txaio/tx.py | Logger.set_log_level | def set_log_level(self, level, keep=True):
"""
Set the log level. If keep is True, then it will not change along with
global log changes.
"""
self._set_log_level(level)
self._log_level_set_explicitly = keep | python | def set_log_level(self, level, keep=True):
"""
Set the log level. If keep is True, then it will not change along with
global log changes.
"""
self._set_log_level(level)
self._log_level_set_explicitly = keep | [
"def",
"set_log_level",
"(",
"self",
",",
"level",
",",
"keep",
"=",
"True",
")",
":",
"self",
".",
"_set_log_level",
"(",
"level",
")",
"self",
".",
"_log_level_set_explicitly",
"=",
"keep"
] | Set the log level. If keep is True, then it will not change along with
global log changes. | [
"Set",
"the",
"log",
"level",
".",
"If",
"keep",
"is",
"True",
"then",
"it",
"will",
"not",
"change",
"along",
"with",
"global",
"log",
"changes",
"."
] | 29c77ff1210cabd4cc03f16f34672612e7eef704 | https://github.com/crossbario/txaio/blob/29c77ff1210cabd4cc03f16f34672612e7eef704/txaio/tx.py#L203-L209 | train | 24,621 |
crossbario/txaio | txaio/tx.py | _TxApi.sleep | def sleep(self, delay):
"""
Inline sleep for use in co-routines.
:param delay: Time to sleep in seconds.
:type delay: float
"""
d = Deferred()
self._get_loop().callLater(delay, d.callback, None)
return d | python | def sleep(self, delay):
"""
Inline sleep for use in co-routines.
:param delay: Time to sleep in seconds.
:type delay: float
"""
d = Deferred()
self._get_loop().callLater(delay, d.callback, None)
return d | [
"def",
"sleep",
"(",
"self",
",",
"delay",
")",
":",
"d",
"=",
"Deferred",
"(",
")",
"self",
".",
"_get_loop",
"(",
")",
".",
"callLater",
"(",
"delay",
",",
"d",
".",
"callback",
",",
"None",
")",
"return",
"d"
] | Inline sleep for use in co-routines.
:param delay: Time to sleep in seconds.
:type delay: float | [
"Inline",
"sleep",
"for",
"use",
"in",
"co",
"-",
"routines",
"."
] | 29c77ff1210cabd4cc03f16f34672612e7eef704 | https://github.com/crossbario/txaio/blob/29c77ff1210cabd4cc03f16f34672612e7eef704/txaio/tx.py#L530-L539 | train | 24,622 |
crossbario/txaio | txaio/_common.py | _BatchedTimer._notify_bucket | def _notify_bucket(self, real_time):
"""
Internal helper. This 'does' the callbacks in a particular bucket.
:param real_time: the bucket to do callbacks on
"""
(delayed_call, calls) = self._buckets[real_time]
del self._buckets[real_time]
errors = []
def notify_one_chunk(calls, chunk_size, chunk_delay_ms):
for call in calls[:chunk_size]:
try:
call()
except Exception as e:
errors.append(e)
calls = calls[chunk_size:]
if calls:
self._create_delayed_call(
chunk_delay_ms / 1000.0,
notify_one_chunk, calls, chunk_size, chunk_delay_ms,
)
else:
# done all calls; make sure there were no errors
if len(errors):
msg = u"Error(s) processing call_later bucket:\n"
for e in errors:
msg += u"{}\n".format(e)
raise RuntimeError(msg)
# ceil()ing because we want the number of chunks, and a
# partial chunk is still a chunk
delay_ms = self._bucket_milliseconds / math.ceil(float(len(calls)) / self._chunk_size)
# I can't imagine any scenario in which chunk_delay_ms is
# actually less than zero, but just being safe here
notify_one_chunk(calls, self._chunk_size, max(0.0, delay_ms)) | python | def _notify_bucket(self, real_time):
"""
Internal helper. This 'does' the callbacks in a particular bucket.
:param real_time: the bucket to do callbacks on
"""
(delayed_call, calls) = self._buckets[real_time]
del self._buckets[real_time]
errors = []
def notify_one_chunk(calls, chunk_size, chunk_delay_ms):
for call in calls[:chunk_size]:
try:
call()
except Exception as e:
errors.append(e)
calls = calls[chunk_size:]
if calls:
self._create_delayed_call(
chunk_delay_ms / 1000.0,
notify_one_chunk, calls, chunk_size, chunk_delay_ms,
)
else:
# done all calls; make sure there were no errors
if len(errors):
msg = u"Error(s) processing call_later bucket:\n"
for e in errors:
msg += u"{}\n".format(e)
raise RuntimeError(msg)
# ceil()ing because we want the number of chunks, and a
# partial chunk is still a chunk
delay_ms = self._bucket_milliseconds / math.ceil(float(len(calls)) / self._chunk_size)
# I can't imagine any scenario in which chunk_delay_ms is
# actually less than zero, but just being safe here
notify_one_chunk(calls, self._chunk_size, max(0.0, delay_ms)) | [
"def",
"_notify_bucket",
"(",
"self",
",",
"real_time",
")",
":",
"(",
"delayed_call",
",",
"calls",
")",
"=",
"self",
".",
"_buckets",
"[",
"real_time",
"]",
"del",
"self",
".",
"_buckets",
"[",
"real_time",
"]",
"errors",
"=",
"[",
"]",
"def",
"notif... | Internal helper. This 'does' the callbacks in a particular bucket.
:param real_time: the bucket to do callbacks on | [
"Internal",
"helper",
".",
"This",
"does",
"the",
"callbacks",
"in",
"a",
"particular",
"bucket",
"."
] | 29c77ff1210cabd4cc03f16f34672612e7eef704 | https://github.com/crossbario/txaio/blob/29c77ff1210cabd4cc03f16f34672612e7eef704/txaio/_common.py#L77-L111 | train | 24,623 |
empymod/empymod | empymod/utils.py | check_ab | def check_ab(ab, verb):
r"""Check source-receiver configuration.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
ab : int
Source-receiver configuration.
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
ab_calc : int
Adjusted source-receiver configuration using reciprocity.
msrc, mrec : bool
If True, src/rec is magnetic; if False, src/rec is electric.
"""
# Try to cast ab into an integer
try:
ab = int(ab)
except VariableCatch:
print('* ERROR :: <ab> must be an integer')
raise
# Check src and rec orientation (<ab> for alpha-beta)
# pab: all possible values that <ab> can take
pab = [11, 12, 13, 14, 15, 16, 21, 22, 23, 24, 25, 26,
31, 32, 33, 34, 35, 36, 41, 42, 43, 44, 45, 46,
51, 52, 53, 54, 55, 56, 61, 62, 63, 64, 65, 66]
if ab not in pab:
print('* ERROR :: <ab> must be one of: ' + str(pab) + ';' +
' <ab> provided: ' + str(ab))
raise ValueError('ab')
# Print input <ab>
if verb > 2:
print(" Input ab : ", ab)
# Check if src and rec are magnetic or electric
msrc = ab % 10 > 3 # If True: magnetic src
mrec = ab // 10 > 3 # If True: magnetic rec
# If rec is magnetic, switch <ab> using reciprocity.
if mrec:
if msrc:
# G^mm_ab(s, r, e, z) = -G^ee_ab(s, r, -z, -e)
ab_calc = ab - 33 # -30 : mrec->erec; -3: msrc->esrc
else:
# G^me_ab(s, r, e, z) = -G^em_ba(r, s, e, z)
ab_calc = ab % 10*10 + ab // 10 # Swap alpha/beta
else:
ab_calc = ab
# Print actual calculated <ab>
if verb > 2:
if ab in [36, 63]:
print("\n> <ab> IS "+str(ab)+" WHICH IS ZERO; returning")
else:
print(" Calculated ab : ", ab_calc)
return ab_calc, msrc, mrec | python | def check_ab(ab, verb):
r"""Check source-receiver configuration.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
ab : int
Source-receiver configuration.
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
ab_calc : int
Adjusted source-receiver configuration using reciprocity.
msrc, mrec : bool
If True, src/rec is magnetic; if False, src/rec is electric.
"""
# Try to cast ab into an integer
try:
ab = int(ab)
except VariableCatch:
print('* ERROR :: <ab> must be an integer')
raise
# Check src and rec orientation (<ab> for alpha-beta)
# pab: all possible values that <ab> can take
pab = [11, 12, 13, 14, 15, 16, 21, 22, 23, 24, 25, 26,
31, 32, 33, 34, 35, 36, 41, 42, 43, 44, 45, 46,
51, 52, 53, 54, 55, 56, 61, 62, 63, 64, 65, 66]
if ab not in pab:
print('* ERROR :: <ab> must be one of: ' + str(pab) + ';' +
' <ab> provided: ' + str(ab))
raise ValueError('ab')
# Print input <ab>
if verb > 2:
print(" Input ab : ", ab)
# Check if src and rec are magnetic or electric
msrc = ab % 10 > 3 # If True: magnetic src
mrec = ab // 10 > 3 # If True: magnetic rec
# If rec is magnetic, switch <ab> using reciprocity.
if mrec:
if msrc:
# G^mm_ab(s, r, e, z) = -G^ee_ab(s, r, -z, -e)
ab_calc = ab - 33 # -30 : mrec->erec; -3: msrc->esrc
else:
# G^me_ab(s, r, e, z) = -G^em_ba(r, s, e, z)
ab_calc = ab % 10*10 + ab // 10 # Swap alpha/beta
else:
ab_calc = ab
# Print actual calculated <ab>
if verb > 2:
if ab in [36, 63]:
print("\n> <ab> IS "+str(ab)+" WHICH IS ZERO; returning")
else:
print(" Calculated ab : ", ab_calc)
return ab_calc, msrc, mrec | [
"def",
"check_ab",
"(",
"ab",
",",
"verb",
")",
":",
"# Try to cast ab into an integer",
"try",
":",
"ab",
"=",
"int",
"(",
"ab",
")",
"except",
"VariableCatch",
":",
"print",
"(",
"'* ERROR :: <ab> must be an integer'",
")",
"raise",
"# Check src and rec orientat... | r"""Check source-receiver configuration.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
ab : int
Source-receiver configuration.
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
ab_calc : int
Adjusted source-receiver configuration using reciprocity.
msrc, mrec : bool
If True, src/rec is magnetic; if False, src/rec is electric. | [
"r",
"Check",
"source",
"-",
"receiver",
"configuration",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/utils.py#L142-L211 | train | 24,624 |
empymod/empymod | empymod/utils.py | check_dipole | def check_dipole(inp, name, verb):
r"""Check dipole parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
inp : list of floats or arrays
Pole coordinates (m): [pole-x, pole-y, pole-z].
name : str, {'src', 'rec'}
Pole-type.
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
inp : list
List of pole coordinates [x, y, z].
ninp : int
Number of inp-elements
"""
# Check inp for x, y, and z; x & y must have same length, z is a float
_check_shape(np.squeeze(inp), name, (3,))
inp[0] = _check_var(inp[0], float, 1, name+'-x')
inp[1] = _check_var(inp[1], float, 1, name+'-y', inp[0].shape)
inp[2] = _check_var(inp[2], float, 1, name+'-z', (1,))
# Print spatial parameters
if verb > 2:
# Pole-type: src or rec
if name == 'src':
longname = ' Source(s) : '
else:
longname = ' Receiver(s) : '
print(longname, str(inp[0].size), 'dipole(s)')
tname = ['x ', 'y ', 'z ']
for i in range(3):
text = " > " + tname[i] + " [m] : "
_prnt_min_max_val(inp[i], text, verb)
return inp, inp[0].size | python | def check_dipole(inp, name, verb):
r"""Check dipole parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
inp : list of floats or arrays
Pole coordinates (m): [pole-x, pole-y, pole-z].
name : str, {'src', 'rec'}
Pole-type.
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
inp : list
List of pole coordinates [x, y, z].
ninp : int
Number of inp-elements
"""
# Check inp for x, y, and z; x & y must have same length, z is a float
_check_shape(np.squeeze(inp), name, (3,))
inp[0] = _check_var(inp[0], float, 1, name+'-x')
inp[1] = _check_var(inp[1], float, 1, name+'-y', inp[0].shape)
inp[2] = _check_var(inp[2], float, 1, name+'-z', (1,))
# Print spatial parameters
if verb > 2:
# Pole-type: src or rec
if name == 'src':
longname = ' Source(s) : '
else:
longname = ' Receiver(s) : '
print(longname, str(inp[0].size), 'dipole(s)')
tname = ['x ', 'y ', 'z ']
for i in range(3):
text = " > " + tname[i] + " [m] : "
_prnt_min_max_val(inp[i], text, verb)
return inp, inp[0].size | [
"def",
"check_dipole",
"(",
"inp",
",",
"name",
",",
"verb",
")",
":",
"# Check inp for x, y, and z; x & y must have same length, z is a float",
"_check_shape",
"(",
"np",
".",
"squeeze",
"(",
"inp",
")",
",",
"name",
",",
"(",
"3",
",",
")",
")",
"inp",
"[",
... | r"""Check dipole parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
inp : list of floats or arrays
Pole coordinates (m): [pole-x, pole-y, pole-z].
name : str, {'src', 'rec'}
Pole-type.
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
inp : list
List of pole coordinates [x, y, z].
ninp : int
Number of inp-elements | [
"r",
"Check",
"dipole",
"parameters",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/utils.py#L317-L365 | train | 24,625 |
empymod/empymod | empymod/utils.py | check_frequency | def check_frequency(freq, res, aniso, epermH, epermV, mpermH, mpermV, verb):
r"""Calculate frequency-dependent parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
freq : array_like
Frequencies f (Hz).
res : array_like
Horizontal resistivities rho_h (Ohm.m); #res = #depth + 1.
aniso : array_like
Anisotropies lambda = sqrt(rho_v/rho_h) (-); #aniso = #res.
epermH, epermV : array_like
Relative horizontal/vertical electric permittivities
epsilon_h/epsilon_v (-);
#epermH = #epermV = #res.
mpermH, mpermV : array_like
Relative horizontal/vertical magnetic permeabilities mu_h/mu_v (-);
#mpermH = #mpermV = #res.
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
freq : float
Frequency, checked for size and assured min_freq.
etaH, etaV : array
Parameters etaH/etaV, same size as provided resistivity.
zetaH, zetaV : array
Parameters zetaH/zetaV, same size as provided resistivity.
"""
global _min_freq
# Check if the user provided a model for etaH/etaV/zetaH/zetaV
if isinstance(res, dict):
res = res['res']
# Check frequency
freq = _check_var(freq, float, 1, 'freq')
# Minimum frequency to avoid division by zero at freq = 0 Hz.
# => min_freq can be set with utils.set_min
freq = _check_min(freq, _min_freq, 'Frequencies', 'Hz', verb)
if verb > 2:
_prnt_min_max_val(freq, " frequency [Hz] : ", verb)
# Calculate eta and zeta (horizontal and vertical)
c = 299792458 # Speed of light m/s
mu_0 = 4e-7*np.pi # Magn. permeability of free space [H/m]
epsilon_0 = 1./(mu_0*c*c) # Elec. permittivity of free space [F/m]
etaH = 1/res + np.outer(2j*np.pi*freq, epermH*epsilon_0)
etaV = 1/(res*aniso*aniso) + np.outer(2j*np.pi*freq, epermV*epsilon_0)
zetaH = np.outer(2j*np.pi*freq, mpermH*mu_0)
zetaV = np.outer(2j*np.pi*freq, mpermV*mu_0)
return freq, etaH, etaV, zetaH, zetaV | python | def check_frequency(freq, res, aniso, epermH, epermV, mpermH, mpermV, verb):
r"""Calculate frequency-dependent parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
freq : array_like
Frequencies f (Hz).
res : array_like
Horizontal resistivities rho_h (Ohm.m); #res = #depth + 1.
aniso : array_like
Anisotropies lambda = sqrt(rho_v/rho_h) (-); #aniso = #res.
epermH, epermV : array_like
Relative horizontal/vertical electric permittivities
epsilon_h/epsilon_v (-);
#epermH = #epermV = #res.
mpermH, mpermV : array_like
Relative horizontal/vertical magnetic permeabilities mu_h/mu_v (-);
#mpermH = #mpermV = #res.
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
freq : float
Frequency, checked for size and assured min_freq.
etaH, etaV : array
Parameters etaH/etaV, same size as provided resistivity.
zetaH, zetaV : array
Parameters zetaH/zetaV, same size as provided resistivity.
"""
global _min_freq
# Check if the user provided a model for etaH/etaV/zetaH/zetaV
if isinstance(res, dict):
res = res['res']
# Check frequency
freq = _check_var(freq, float, 1, 'freq')
# Minimum frequency to avoid division by zero at freq = 0 Hz.
# => min_freq can be set with utils.set_min
freq = _check_min(freq, _min_freq, 'Frequencies', 'Hz', verb)
if verb > 2:
_prnt_min_max_val(freq, " frequency [Hz] : ", verb)
# Calculate eta and zeta (horizontal and vertical)
c = 299792458 # Speed of light m/s
mu_0 = 4e-7*np.pi # Magn. permeability of free space [H/m]
epsilon_0 = 1./(mu_0*c*c) # Elec. permittivity of free space [F/m]
etaH = 1/res + np.outer(2j*np.pi*freq, epermH*epsilon_0)
etaV = 1/(res*aniso*aniso) + np.outer(2j*np.pi*freq, epermV*epsilon_0)
zetaH = np.outer(2j*np.pi*freq, mpermH*mu_0)
zetaV = np.outer(2j*np.pi*freq, mpermV*mu_0)
return freq, etaH, etaV, zetaH, zetaV | [
"def",
"check_frequency",
"(",
"freq",
",",
"res",
",",
"aniso",
",",
"epermH",
",",
"epermV",
",",
"mpermH",
",",
"mpermV",
",",
"verb",
")",
":",
"global",
"_min_freq",
"# Check if the user provided a model for etaH/etaV/zetaH/zetaV",
"if",
"isinstance",
"(",
"r... | r"""Calculate frequency-dependent parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
freq : array_like
Frequencies f (Hz).
res : array_like
Horizontal resistivities rho_h (Ohm.m); #res = #depth + 1.
aniso : array_like
Anisotropies lambda = sqrt(rho_v/rho_h) (-); #aniso = #res.
epermH, epermV : array_like
Relative horizontal/vertical electric permittivities
epsilon_h/epsilon_v (-);
#epermH = #epermV = #res.
mpermH, mpermV : array_like
Relative horizontal/vertical magnetic permeabilities mu_h/mu_v (-);
#mpermH = #mpermV = #res.
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
freq : float
Frequency, checked for size and assured min_freq.
etaH, etaV : array
Parameters etaH/etaV, same size as provided resistivity.
zetaH, zetaV : array
Parameters zetaH/zetaV, same size as provided resistivity. | [
"r",
"Calculate",
"frequency",
"-",
"dependent",
"parameters",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/utils.py#L368-L436 | train | 24,626 |
empymod/empymod | empymod/utils.py | check_opt | def check_opt(opt, loop, ht, htarg, verb):
r"""Check optimization parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
opt : {None, 'parallel'}
Optimization flag; use ``numexpr`` or not.
loop : {None, 'freq', 'off'}
Loop flag.
ht : str
Flag to choose the Hankel transform.
htarg : array_like,
Depends on the value for ``ht``.
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
use_ne_eval : bool
Boolean if to use ``numexpr``.
loop_freq : bool
Boolean if to loop over frequencies.
loop_off : bool
Boolean if to loop over offsets.
"""
# Check optimization flag
use_ne_eval = False
if opt == 'parallel':
if numexpr:
use_ne_eval = numexpr.evaluate
elif verb > 0:
print(numexpr_msg)
# Define if to loop over frequencies or over offsets
lagged_splined_fht = False
if ht == 'fht':
if htarg[1] != 0:
lagged_splined_fht = True
if ht in ['hqwe', 'hquad'] or lagged_splined_fht:
loop_freq = True
loop_off = False
else:
loop_off = loop == 'off'
loop_freq = loop == 'freq'
# If verbose, print optimization information
if verb > 2:
if use_ne_eval:
print(" Kernel Opt. : Use parallel")
else:
print(" Kernel Opt. : None")
if loop_off:
print(" Loop over : Offsets")
elif loop_freq:
print(" Loop over : Frequencies")
else:
print(" Loop over : None (all vectorized)")
return use_ne_eval, loop_freq, loop_off | python | def check_opt(opt, loop, ht, htarg, verb):
r"""Check optimization parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
opt : {None, 'parallel'}
Optimization flag; use ``numexpr`` or not.
loop : {None, 'freq', 'off'}
Loop flag.
ht : str
Flag to choose the Hankel transform.
htarg : array_like,
Depends on the value for ``ht``.
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
use_ne_eval : bool
Boolean if to use ``numexpr``.
loop_freq : bool
Boolean if to loop over frequencies.
loop_off : bool
Boolean if to loop over offsets.
"""
# Check optimization flag
use_ne_eval = False
if opt == 'parallel':
if numexpr:
use_ne_eval = numexpr.evaluate
elif verb > 0:
print(numexpr_msg)
# Define if to loop over frequencies or over offsets
lagged_splined_fht = False
if ht == 'fht':
if htarg[1] != 0:
lagged_splined_fht = True
if ht in ['hqwe', 'hquad'] or lagged_splined_fht:
loop_freq = True
loop_off = False
else:
loop_off = loop == 'off'
loop_freq = loop == 'freq'
# If verbose, print optimization information
if verb > 2:
if use_ne_eval:
print(" Kernel Opt. : Use parallel")
else:
print(" Kernel Opt. : None")
if loop_off:
print(" Loop over : Offsets")
elif loop_freq:
print(" Loop over : Frequencies")
else:
print(" Loop over : None (all vectorized)")
return use_ne_eval, loop_freq, loop_off | [
"def",
"check_opt",
"(",
"opt",
",",
"loop",
",",
"ht",
",",
"htarg",
",",
"verb",
")",
":",
"# Check optimization flag",
"use_ne_eval",
"=",
"False",
"if",
"opt",
"==",
"'parallel'",
":",
"if",
"numexpr",
":",
"use_ne_eval",
"=",
"numexpr",
".",
"evaluate... | r"""Check optimization parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
opt : {None, 'parallel'}
Optimization flag; use ``numexpr`` or not.
loop : {None, 'freq', 'off'}
Loop flag.
ht : str
Flag to choose the Hankel transform.
htarg : array_like,
Depends on the value for ``ht``.
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
use_ne_eval : bool
Boolean if to use ``numexpr``.
loop_freq : bool
Boolean if to loop over frequencies.
loop_off : bool
Boolean if to loop over offsets. | [
"r",
"Check",
"optimization",
"parameters",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/utils.py#L824-L897 | train | 24,627 |
empymod/empymod | empymod/utils.py | check_time_only | def check_time_only(time, signal, verb):
r"""Check time and signal parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
time : array_like
Times t (s).
signal : {None, 0, 1, -1}
Source signal:
- None: Frequency-domain response
- -1 : Switch-off time-domain response
- 0 : Impulse time-domain response
- +1 : Switch-on time-domain response
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
time : float
Time, checked for size and assured min_time.
"""
global _min_time
# Check input signal
if int(signal) not in [-1, 0, 1]:
print("* ERROR :: <signal> must be one of: [None, -1, 0, 1]; " +
"<signal> provided: "+str(signal))
raise ValueError('signal')
# Check time
time = _check_var(time, float, 1, 'time')
# Minimum time to avoid division by zero at time = 0 s.
# => min_time can be set with utils.set_min
time = _check_min(time, _min_time, 'Times', 's', verb)
if verb > 2:
_prnt_min_max_val(time, " time [s] : ", verb)
return time | python | def check_time_only(time, signal, verb):
r"""Check time and signal parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
time : array_like
Times t (s).
signal : {None, 0, 1, -1}
Source signal:
- None: Frequency-domain response
- -1 : Switch-off time-domain response
- 0 : Impulse time-domain response
- +1 : Switch-on time-domain response
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
time : float
Time, checked for size and assured min_time.
"""
global _min_time
# Check input signal
if int(signal) not in [-1, 0, 1]:
print("* ERROR :: <signal> must be one of: [None, -1, 0, 1]; " +
"<signal> provided: "+str(signal))
raise ValueError('signal')
# Check time
time = _check_var(time, float, 1, 'time')
# Minimum time to avoid division by zero at time = 0 s.
# => min_time can be set with utils.set_min
time = _check_min(time, _min_time, 'Times', 's', verb)
if verb > 2:
_prnt_min_max_val(time, " time [s] : ", verb)
return time | [
"def",
"check_time_only",
"(",
"time",
",",
"signal",
",",
"verb",
")",
":",
"global",
"_min_time",
"# Check input signal",
"if",
"int",
"(",
"signal",
")",
"not",
"in",
"[",
"-",
"1",
",",
"0",
",",
"1",
"]",
":",
"print",
"(",
"\"* ERROR :: <signal> ... | r"""Check time and signal parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
time : array_like
Times t (s).
signal : {None, 0, 1, -1}
Source signal:
- None: Frequency-domain response
- -1 : Switch-off time-domain response
- 0 : Impulse time-domain response
- +1 : Switch-on time-domain response
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
time : float
Time, checked for size and assured min_time. | [
"r",
"Check",
"time",
"and",
"signal",
"parameters",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/utils.py#L1221-L1267 | train | 24,628 |
empymod/empymod | empymod/utils.py | check_solution | def check_solution(solution, signal, ab, msrc, mrec):
r"""Check required solution with parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
solution : str
String to define analytical solution.
signal : {None, 0, 1, -1}
Source signal:
- None: Frequency-domain response
- -1 : Switch-off time-domain response
- 0 : Impulse time-domain response
- +1 : Switch-on time-domain response
msrc, mrec : bool
True if src/rec is magnetic, else False.
"""
# Ensure valid solution.
if solution not in ['fs', 'dfs', 'dhs', 'dsplit', 'dtetm']:
print("* ERROR :: Solution must be one of ['fs', 'dfs', 'dhs', " +
"'dsplit', 'dtetm']; <solution> provided: " + solution)
raise ValueError('solution')
# If diffusive solution is required, ensure EE-field.
if solution[0] == 'd' and (msrc or mrec):
print('* ERROR :: Diffusive solution is only implemented for ' +
'electric sources and electric receivers, <ab> provided: ' +
str(ab))
raise ValueError('ab')
# If full solution is required, ensure frequency-domain.
if solution == 'fs' and signal is not None:
print('* ERROR :: Full fullspace solution is only implemented for ' +
'the frequency domain, <signal> provided: ' + str(signal))
raise ValueError('signal') | python | def check_solution(solution, signal, ab, msrc, mrec):
r"""Check required solution with parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
solution : str
String to define analytical solution.
signal : {None, 0, 1, -1}
Source signal:
- None: Frequency-domain response
- -1 : Switch-off time-domain response
- 0 : Impulse time-domain response
- +1 : Switch-on time-domain response
msrc, mrec : bool
True if src/rec is magnetic, else False.
"""
# Ensure valid solution.
if solution not in ['fs', 'dfs', 'dhs', 'dsplit', 'dtetm']:
print("* ERROR :: Solution must be one of ['fs', 'dfs', 'dhs', " +
"'dsplit', 'dtetm']; <solution> provided: " + solution)
raise ValueError('solution')
# If diffusive solution is required, ensure EE-field.
if solution[0] == 'd' and (msrc or mrec):
print('* ERROR :: Diffusive solution is only implemented for ' +
'electric sources and electric receivers, <ab> provided: ' +
str(ab))
raise ValueError('ab')
# If full solution is required, ensure frequency-domain.
if solution == 'fs' and signal is not None:
print('* ERROR :: Full fullspace solution is only implemented for ' +
'the frequency domain, <signal> provided: ' + str(signal))
raise ValueError('signal') | [
"def",
"check_solution",
"(",
"solution",
",",
"signal",
",",
"ab",
",",
"msrc",
",",
"mrec",
")",
":",
"# Ensure valid solution.",
"if",
"solution",
"not",
"in",
"[",
"'fs'",
",",
"'dfs'",
",",
"'dhs'",
",",
"'dsplit'",
",",
"'dtetm'",
"]",
":",
"print"... | r"""Check required solution with parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
solution : str
String to define analytical solution.
signal : {None, 0, 1, -1}
Source signal:
- None: Frequency-domain response
- -1 : Switch-off time-domain response
- 0 : Impulse time-domain response
- +1 : Switch-on time-domain response
msrc, mrec : bool
True if src/rec is magnetic, else False. | [
"r",
"Check",
"required",
"solution",
"with",
"parameters",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/utils.py#L1270-L1311 | train | 24,629 |
empymod/empymod | empymod/utils.py | get_abs | def get_abs(msrc, mrec, srcazm, srcdip, recazm, recdip, verb):
r"""Get required ab's for given angles.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
msrc, mrec : bool
True if src/rec is magnetic, else False.
srcazm, recazm : float
Horizontal source/receiver angle (azimuth).
srcdip, recdip : float
Vertical source/receiver angle (dip).
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
ab_calc : array of int
ab's to calculate for this bipole.
"""
# Get required ab's (9 at most)
ab_calc = np.array([[11, 12, 13], [21, 22, 23], [31, 32, 33]])
if msrc:
ab_calc += 3
if mrec:
ab_calc += 30
# Switch <ab> using reciprocity.
if msrc:
# G^mm_ab(s, r, e, z) = -G^ee_ab(s, r, -z, -e)
ab_calc -= 33 # -30 : mrec->erec; -3: msrc->esrc
else:
# G^me_ab(s, r, e, z) = -G^em_ba(r, s, e, z)
ab_calc = ab_calc % 10*10 + ab_calc // 10 # Swap alpha/beta
# Remove unnecessary ab's
bab = np.asarray(ab_calc*0+1, dtype=bool)
# Remove if source is x- or y-directed
check = np.atleast_1d(srcazm)[0]
if np.allclose(srcazm % (np.pi/2), 0): # if all angles are multiples of 90
if np.isclose(check // (np.pi/2) % 2, 0): # Multiples of pi (180)
bab[:, 1] *= False # x-directed source, remove y
else: # Multiples of pi/2 (90)
bab[:, 0] *= False # y-directed source, remove x
# Remove if source is vertical
check = np.atleast_1d(srcdip)[0]
if np.allclose(srcdip % (np.pi/2), 0): # if all angles are multiples of 90
if np.isclose(check // (np.pi/2) % 2, 0): # Multiples of pi (180)
bab[:, 2] *= False # Horizontal, remove z
else: # Multiples of pi/2 (90)
bab[:, :2] *= False # Vertical, remove x/y
# Remove if receiver is x- or y-directed
check = np.atleast_1d(recazm)[0]
if np.allclose(recazm % (np.pi/2), 0): # if all angles are multiples of 90
if np.isclose(check // (np.pi/2) % 2, 0): # Multiples of pi (180)
bab[1, :] *= False # x-directed receiver, remove y
else: # Multiples of pi/2 (90)
bab[0, :] *= False # y-directed receiver, remove x
# Remove if receiver is vertical
check = np.atleast_1d(recdip)[0]
if np.allclose(recdip % (np.pi/2), 0): # if all angles are multiples of 90
if np.isclose(check // (np.pi/2) % 2, 0): # Multiples of pi (180)
bab[2, :] *= False # Horizontal, remove z
else: # Multiples of pi/2 (90)
bab[:2, :] *= False # Vertical, remove x/y
# Reduce
ab_calc = ab_calc[bab].ravel()
# Print actual calculated <ab>
if verb > 2:
print(" Required ab's : ", _strvar(ab_calc))
return ab_calc | python | def get_abs(msrc, mrec, srcazm, srcdip, recazm, recdip, verb):
r"""Get required ab's for given angles.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
msrc, mrec : bool
True if src/rec is magnetic, else False.
srcazm, recazm : float
Horizontal source/receiver angle (azimuth).
srcdip, recdip : float
Vertical source/receiver angle (dip).
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
ab_calc : array of int
ab's to calculate for this bipole.
"""
# Get required ab's (9 at most)
ab_calc = np.array([[11, 12, 13], [21, 22, 23], [31, 32, 33]])
if msrc:
ab_calc += 3
if mrec:
ab_calc += 30
# Switch <ab> using reciprocity.
if msrc:
# G^mm_ab(s, r, e, z) = -G^ee_ab(s, r, -z, -e)
ab_calc -= 33 # -30 : mrec->erec; -3: msrc->esrc
else:
# G^me_ab(s, r, e, z) = -G^em_ba(r, s, e, z)
ab_calc = ab_calc % 10*10 + ab_calc // 10 # Swap alpha/beta
# Remove unnecessary ab's
bab = np.asarray(ab_calc*0+1, dtype=bool)
# Remove if source is x- or y-directed
check = np.atleast_1d(srcazm)[0]
if np.allclose(srcazm % (np.pi/2), 0): # if all angles are multiples of 90
if np.isclose(check // (np.pi/2) % 2, 0): # Multiples of pi (180)
bab[:, 1] *= False # x-directed source, remove y
else: # Multiples of pi/2 (90)
bab[:, 0] *= False # y-directed source, remove x
# Remove if source is vertical
check = np.atleast_1d(srcdip)[0]
if np.allclose(srcdip % (np.pi/2), 0): # if all angles are multiples of 90
if np.isclose(check // (np.pi/2) % 2, 0): # Multiples of pi (180)
bab[:, 2] *= False # Horizontal, remove z
else: # Multiples of pi/2 (90)
bab[:, :2] *= False # Vertical, remove x/y
# Remove if receiver is x- or y-directed
check = np.atleast_1d(recazm)[0]
if np.allclose(recazm % (np.pi/2), 0): # if all angles are multiples of 90
if np.isclose(check // (np.pi/2) % 2, 0): # Multiples of pi (180)
bab[1, :] *= False # x-directed receiver, remove y
else: # Multiples of pi/2 (90)
bab[0, :] *= False # y-directed receiver, remove x
# Remove if receiver is vertical
check = np.atleast_1d(recdip)[0]
if np.allclose(recdip % (np.pi/2), 0): # if all angles are multiples of 90
if np.isclose(check // (np.pi/2) % 2, 0): # Multiples of pi (180)
bab[2, :] *= False # Horizontal, remove z
else: # Multiples of pi/2 (90)
bab[:2, :] *= False # Vertical, remove x/y
# Reduce
ab_calc = ab_calc[bab].ravel()
# Print actual calculated <ab>
if verb > 2:
print(" Required ab's : ", _strvar(ab_calc))
return ab_calc | [
"def",
"get_abs",
"(",
"msrc",
",",
"mrec",
",",
"srcazm",
",",
"srcdip",
",",
"recazm",
",",
"recdip",
",",
"verb",
")",
":",
"# Get required ab's (9 at most)",
"ab_calc",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"11",
",",
"12",
",",
"13",
"]",
",",... | r"""Get required ab's for given angles.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
msrc, mrec : bool
True if src/rec is magnetic, else False.
srcazm, recazm : float
Horizontal source/receiver angle (azimuth).
srcdip, recdip : float
Vertical source/receiver angle (dip).
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
ab_calc : array of int
ab's to calculate for this bipole. | [
"r",
"Get",
"required",
"ab",
"s",
"for",
"given",
"angles",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/utils.py#L1316-L1402 | train | 24,630 |
empymod/empymod | empymod/utils.py | get_geo_fact | def get_geo_fact(ab, srcazm, srcdip, recazm, recdip, msrc, mrec):
r"""Get required geometrical scaling factor for given angles.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
ab : int
Source-receiver configuration.
srcazm, recazm : float
Horizontal source/receiver angle.
srcdip, recdip : float
Vertical source/receiver angle.
Returns
-------
fact : float
Geometrical scaling factor.
"""
global _min_angle
# Get current direction for source and receiver
fis = ab % 10
fir = ab // 10
# If rec is magnetic and src not, swap directions (reciprocity).
# (They have been swapped in get_abs, but the original scaling applies.)
if mrec and not msrc:
fis, fir = fir, fis
def gfact(bp, azm, dip):
r"""Geometrical factor of source or receiver."""
if bp in [1, 4]: # x-directed
return np.cos(azm)*np.cos(dip)
elif bp in [2, 5]: # y-directed
return np.sin(azm)*np.cos(dip)
else: # z-directed
return np.sin(dip)
# Calculate src-rec-factor
fsrc = gfact(fis, srcazm, srcdip)
frec = gfact(fir, recazm, recdip)
fact = np.outer(fsrc, frec).ravel()
# Set very small angles to proper zero (because e.g. sin(pi/2) != exact 0)
# => min_angle can be set with utils.set_min
fact[np.abs(fact) < _min_angle] = 0
return fact | python | def get_geo_fact(ab, srcazm, srcdip, recazm, recdip, msrc, mrec):
r"""Get required geometrical scaling factor for given angles.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
ab : int
Source-receiver configuration.
srcazm, recazm : float
Horizontal source/receiver angle.
srcdip, recdip : float
Vertical source/receiver angle.
Returns
-------
fact : float
Geometrical scaling factor.
"""
global _min_angle
# Get current direction for source and receiver
fis = ab % 10
fir = ab // 10
# If rec is magnetic and src not, swap directions (reciprocity).
# (They have been swapped in get_abs, but the original scaling applies.)
if mrec and not msrc:
fis, fir = fir, fis
def gfact(bp, azm, dip):
r"""Geometrical factor of source or receiver."""
if bp in [1, 4]: # x-directed
return np.cos(azm)*np.cos(dip)
elif bp in [2, 5]: # y-directed
return np.sin(azm)*np.cos(dip)
else: # z-directed
return np.sin(dip)
# Calculate src-rec-factor
fsrc = gfact(fis, srcazm, srcdip)
frec = gfact(fir, recazm, recdip)
fact = np.outer(fsrc, frec).ravel()
# Set very small angles to proper zero (because e.g. sin(pi/2) != exact 0)
# => min_angle can be set with utils.set_min
fact[np.abs(fact) < _min_angle] = 0
return fact | [
"def",
"get_geo_fact",
"(",
"ab",
",",
"srcazm",
",",
"srcdip",
",",
"recazm",
",",
"recdip",
",",
"msrc",
",",
"mrec",
")",
":",
"global",
"_min_angle",
"# Get current direction for source and receiver",
"fis",
"=",
"ab",
"%",
"10",
"fir",
"=",
"ab",
"//",
... | r"""Get required geometrical scaling factor for given angles.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
ab : int
Source-receiver configuration.
srcazm, recazm : float
Horizontal source/receiver angle.
srcdip, recdip : float
Vertical source/receiver angle.
Returns
-------
fact : float
Geometrical scaling factor. | [
"r",
"Get",
"required",
"geometrical",
"scaling",
"factor",
"for",
"given",
"angles",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/utils.py#L1405-L1459 | train | 24,631 |
empymod/empymod | empymod/utils.py | get_layer_nr | def get_layer_nr(inp, depth):
r"""Get number of layer in which inp resides.
Note:
If zinp is on a layer interface, the layer above the interface is chosen.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
inp : list of floats or arrays
Dipole coordinates (m)
depth : array
Depths of layer interfaces.
Returns
-------
linp : int or array_like of int
Layer number(s) in which inp resides (plural only if bipole).
zinp : float or array
inp[2] (depths).
"""
zinp = inp[2]
# depth = [-infty : last interface]; create additional depth-array
# pdepth = [fist interface : +infty]
pdepth = np.concatenate((depth[1:], np.array([np.infty])))
# Broadcast arrays
b_zinp = np.atleast_1d(zinp)[:, None]
# Get layers
linp = np.where((depth[None, :] < b_zinp)*(pdepth[None, :] >= b_zinp))[1]
# Return; squeeze in case of only one inp-depth
return np.squeeze(linp), zinp | python | def get_layer_nr(inp, depth):
r"""Get number of layer in which inp resides.
Note:
If zinp is on a layer interface, the layer above the interface is chosen.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
inp : list of floats or arrays
Dipole coordinates (m)
depth : array
Depths of layer interfaces.
Returns
-------
linp : int or array_like of int
Layer number(s) in which inp resides (plural only if bipole).
zinp : float or array
inp[2] (depths).
"""
zinp = inp[2]
# depth = [-infty : last interface]; create additional depth-array
# pdepth = [fist interface : +infty]
pdepth = np.concatenate((depth[1:], np.array([np.infty])))
# Broadcast arrays
b_zinp = np.atleast_1d(zinp)[:, None]
# Get layers
linp = np.where((depth[None, :] < b_zinp)*(pdepth[None, :] >= b_zinp))[1]
# Return; squeeze in case of only one inp-depth
return np.squeeze(linp), zinp | [
"def",
"get_layer_nr",
"(",
"inp",
",",
"depth",
")",
":",
"zinp",
"=",
"inp",
"[",
"2",
"]",
"# depth = [-infty : last interface]; create additional depth-array",
"# pdepth = [fist interface : +infty]",
"pdepth",
"=",
"np",
".",
"concatenate",
"(",
"(",
"depth",
"["... | r"""Get number of layer in which inp resides.
Note:
If zinp is on a layer interface, the layer above the interface is chosen.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
inp : list of floats or arrays
Dipole coordinates (m)
depth : array
Depths of layer interfaces.
Returns
-------
linp : int or array_like of int
Layer number(s) in which inp resides (plural only if bipole).
zinp : float or array
inp[2] (depths). | [
"r",
"Get",
"number",
"of",
"layer",
"in",
"which",
"inp",
"resides",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/utils.py#L1462-L1503 | train | 24,632 |
empymod/empymod | empymod/utils.py | get_off_ang | def get_off_ang(src, rec, nsrc, nrec, verb):
r"""Get depths, offsets, angles, hence spatial input parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
src, rec : list of floats or arrays
Source/receiver dipole coordinates x, y, and z (m).
nsrc, nrec : int
Number of sources/receivers (-).
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
off : array of floats
Offsets
angle : array of floats
Angles
"""
global _min_off
# Pre-allocate off and angle
off = np.empty((nrec*nsrc,))
angle = np.empty((nrec*nsrc,))
# Coordinates
# Loop over sources, append them one after another.
for i in range(nsrc):
xco = rec[0] - src[0][i] # X-coordinates [m]
yco = rec[1] - src[1][i] # Y-coordinates [m]
off[i*nrec:(i+1)*nrec] = np.sqrt(xco*xco + yco*yco) # Offset [m]
angle[i*nrec:(i+1)*nrec] = np.arctan2(yco, xco) # Angle [rad]
# Note: One could achieve a potential speed-up using np.unique to sort out
# src-rec configurations that have the same offset and angle. Very unlikely
# for real data.
# Minimum offset to avoid singularities at off = 0 m.
# => min_off can be set with utils.set_min
angle[np.where(off < _min_off)] = np.nan
off = _check_min(off, _min_off, 'Offsets', 'm', verb)
return off, angle | python | def get_off_ang(src, rec, nsrc, nrec, verb):
r"""Get depths, offsets, angles, hence spatial input parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
src, rec : list of floats or arrays
Source/receiver dipole coordinates x, y, and z (m).
nsrc, nrec : int
Number of sources/receivers (-).
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
off : array of floats
Offsets
angle : array of floats
Angles
"""
global _min_off
# Pre-allocate off and angle
off = np.empty((nrec*nsrc,))
angle = np.empty((nrec*nsrc,))
# Coordinates
# Loop over sources, append them one after another.
for i in range(nsrc):
xco = rec[0] - src[0][i] # X-coordinates [m]
yco = rec[1] - src[1][i] # Y-coordinates [m]
off[i*nrec:(i+1)*nrec] = np.sqrt(xco*xco + yco*yco) # Offset [m]
angle[i*nrec:(i+1)*nrec] = np.arctan2(yco, xco) # Angle [rad]
# Note: One could achieve a potential speed-up using np.unique to sort out
# src-rec configurations that have the same offset and angle. Very unlikely
# for real data.
# Minimum offset to avoid singularities at off = 0 m.
# => min_off can be set with utils.set_min
angle[np.where(off < _min_off)] = np.nan
off = _check_min(off, _min_off, 'Offsets', 'm', verb)
return off, angle | [
"def",
"get_off_ang",
"(",
"src",
",",
"rec",
",",
"nsrc",
",",
"nrec",
",",
"verb",
")",
":",
"global",
"_min_off",
"# Pre-allocate off and angle",
"off",
"=",
"np",
".",
"empty",
"(",
"(",
"nrec",
"*",
"nsrc",
",",
")",
")",
"angle",
"=",
"np",
"."... | r"""Get depths, offsets, angles, hence spatial input parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
src, rec : list of floats or arrays
Source/receiver dipole coordinates x, y, and z (m).
nsrc, nrec : int
Number of sources/receivers (-).
verb : {0, 1, 2, 3, 4}
Level of verbosity.
Returns
-------
off : array of floats
Offsets
angle : array of floats
Angles | [
"r",
"Get",
"depths",
"offsets",
"angles",
"hence",
"spatial",
"input",
"parameters",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/utils.py#L1506-L1557 | train | 24,633 |
empymod/empymod | empymod/utils.py | printstartfinish | def printstartfinish(verb, inp=None, kcount=None):
r"""Print start and finish with time measure and kernel count."""
if inp:
if verb > 1:
ttxt = str(timedelta(seconds=default_timer() - inp))
ktxt = ' '
if kcount:
ktxt += str(kcount) + ' kernel call(s)'
print('\n:: empymod END; runtime = ' + ttxt + ' ::' + ktxt + '\n')
else:
t0 = default_timer()
if verb > 2:
print("\n:: empymod START ::\n")
return t0 | python | def printstartfinish(verb, inp=None, kcount=None):
r"""Print start and finish with time measure and kernel count."""
if inp:
if verb > 1:
ttxt = str(timedelta(seconds=default_timer() - inp))
ktxt = ' '
if kcount:
ktxt += str(kcount) + ' kernel call(s)'
print('\n:: empymod END; runtime = ' + ttxt + ' ::' + ktxt + '\n')
else:
t0 = default_timer()
if verb > 2:
print("\n:: empymod START ::\n")
return t0 | [
"def",
"printstartfinish",
"(",
"verb",
",",
"inp",
"=",
"None",
",",
"kcount",
"=",
"None",
")",
":",
"if",
"inp",
":",
"if",
"verb",
">",
"1",
":",
"ttxt",
"=",
"str",
"(",
"timedelta",
"(",
"seconds",
"=",
"default_timer",
"(",
")",
"-",
"inp",
... | r"""Print start and finish with time measure and kernel count. | [
"r",
"Print",
"start",
"and",
"finish",
"with",
"time",
"measure",
"and",
"kernel",
"count",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/utils.py#L1763-L1776 | train | 24,634 |
empymod/empymod | empymod/utils.py | set_minimum | def set_minimum(min_freq=None, min_time=None, min_off=None, min_res=None,
min_angle=None):
r"""
Set minimum values of parameters.
The given parameters are set to its minimum value if they are smaller.
Parameters
----------
min_freq : float, optional
Minimum frequency [Hz] (default 1e-20 Hz).
min_time : float, optional
Minimum time [s] (default 1e-20 s).
min_off : float, optional
Minimum offset [m] (default 1e-3 m).
Also used to round src- & rec-coordinates.
min_res : float, optional
Minimum horizontal and vertical resistivity [Ohm.m] (default 1e-20).
min_angle : float, optional
Minimum angle [-] (default 1e-10).
Note
----
set_minimum and get_minimum are derived after set_printoptions and
get_printoptions from arrayprint.py in numpy.
"""
global _min_freq, _min_time, _min_off, _min_res, _min_angle
if min_freq is not None:
_min_freq = min_freq
if min_time is not None:
_min_time = min_time
if min_off is not None:
_min_off = min_off
if min_res is not None:
_min_res = min_res
if min_angle is not None:
_min_angle = min_angle | python | def set_minimum(min_freq=None, min_time=None, min_off=None, min_res=None,
min_angle=None):
r"""
Set minimum values of parameters.
The given parameters are set to its minimum value if they are smaller.
Parameters
----------
min_freq : float, optional
Minimum frequency [Hz] (default 1e-20 Hz).
min_time : float, optional
Minimum time [s] (default 1e-20 s).
min_off : float, optional
Minimum offset [m] (default 1e-3 m).
Also used to round src- & rec-coordinates.
min_res : float, optional
Minimum horizontal and vertical resistivity [Ohm.m] (default 1e-20).
min_angle : float, optional
Minimum angle [-] (default 1e-10).
Note
----
set_minimum and get_minimum are derived after set_printoptions and
get_printoptions from arrayprint.py in numpy.
"""
global _min_freq, _min_time, _min_off, _min_res, _min_angle
if min_freq is not None:
_min_freq = min_freq
if min_time is not None:
_min_time = min_time
if min_off is not None:
_min_off = min_off
if min_res is not None:
_min_res = min_res
if min_angle is not None:
_min_angle = min_angle | [
"def",
"set_minimum",
"(",
"min_freq",
"=",
"None",
",",
"min_time",
"=",
"None",
",",
"min_off",
"=",
"None",
",",
"min_res",
"=",
"None",
",",
"min_angle",
"=",
"None",
")",
":",
"global",
"_min_freq",
",",
"_min_time",
",",
"_min_off",
",",
"_min_res"... | r"""
Set minimum values of parameters.
The given parameters are set to its minimum value if they are smaller.
Parameters
----------
min_freq : float, optional
Minimum frequency [Hz] (default 1e-20 Hz).
min_time : float, optional
Minimum time [s] (default 1e-20 s).
min_off : float, optional
Minimum offset [m] (default 1e-3 m).
Also used to round src- & rec-coordinates.
min_res : float, optional
Minimum horizontal and vertical resistivity [Ohm.m] (default 1e-20).
min_angle : float, optional
Minimum angle [-] (default 1e-10).
Note
----
set_minimum and get_minimum are derived after set_printoptions and
get_printoptions from arrayprint.py in numpy. | [
"r",
"Set",
"minimum",
"values",
"of",
"parameters",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/utils.py#L1789-L1828 | train | 24,635 |
empymod/empymod | empymod/utils.py | get_minimum | def get_minimum():
r"""
Return the current minimum values.
Returns
-------
min_vals : dict
Dictionary of current minimum values with keys
- min_freq : float
- min_time : float
- min_off : float
- min_res : float
- min_angle : float
For a full description of these options, see `set_minimum`.
Note
----
set_minimum and get_minimum are derived after set_printoptions and
get_printoptions from arrayprint.py in numpy.
"""
d = dict(min_freq=_min_freq,
min_time=_min_time,
min_off=_min_off,
min_res=_min_res,
min_angle=_min_angle)
return d | python | def get_minimum():
r"""
Return the current minimum values.
Returns
-------
min_vals : dict
Dictionary of current minimum values with keys
- min_freq : float
- min_time : float
- min_off : float
- min_res : float
- min_angle : float
For a full description of these options, see `set_minimum`.
Note
----
set_minimum and get_minimum are derived after set_printoptions and
get_printoptions from arrayprint.py in numpy.
"""
d = dict(min_freq=_min_freq,
min_time=_min_time,
min_off=_min_off,
min_res=_min_res,
min_angle=_min_angle)
return d | [
"def",
"get_minimum",
"(",
")",
":",
"d",
"=",
"dict",
"(",
"min_freq",
"=",
"_min_freq",
",",
"min_time",
"=",
"_min_time",
",",
"min_off",
"=",
"_min_off",
",",
"min_res",
"=",
"_min_res",
",",
"min_angle",
"=",
"_min_angle",
")",
"return",
"d"
] | r"""
Return the current minimum values.
Returns
-------
min_vals : dict
Dictionary of current minimum values with keys
- min_freq : float
- min_time : float
- min_off : float
- min_res : float
- min_angle : float
For a full description of these options, see `set_minimum`.
Note
----
set_minimum and get_minimum are derived after set_printoptions and
get_printoptions from arrayprint.py in numpy. | [
"r",
"Return",
"the",
"current",
"minimum",
"values",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/utils.py#L1831-L1859 | train | 24,636 |
empymod/empymod | empymod/utils.py | _check_var | def _check_var(var, dtype, ndmin, name, shape=None, shape2=None):
r"""Return variable as array of dtype, ndmin; shape-checked."""
if var is None:
raise ValueError
var = np.array(var, dtype=dtype, copy=True, ndmin=ndmin)
if shape:
_check_shape(var, name, shape, shape2)
return var | python | def _check_var(var, dtype, ndmin, name, shape=None, shape2=None):
r"""Return variable as array of dtype, ndmin; shape-checked."""
if var is None:
raise ValueError
var = np.array(var, dtype=dtype, copy=True, ndmin=ndmin)
if shape:
_check_shape(var, name, shape, shape2)
return var | [
"def",
"_check_var",
"(",
"var",
",",
"dtype",
",",
"ndmin",
",",
"name",
",",
"shape",
"=",
"None",
",",
"shape2",
"=",
"None",
")",
":",
"if",
"var",
"is",
"None",
":",
"raise",
"ValueError",
"var",
"=",
"np",
".",
"array",
"(",
"var",
",",
"dt... | r"""Return variable as array of dtype, ndmin; shape-checked. | [
"r",
"Return",
"variable",
"as",
"array",
"of",
"dtype",
"ndmin",
";",
"shape",
"-",
"checked",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/utils.py#L1880-L1887 | train | 24,637 |
empymod/empymod | empymod/utils.py | _strvar | def _strvar(a, prec='{:G}'):
r"""Return variable as a string to print, with given precision."""
return ' '.join([prec.format(i) for i in np.atleast_1d(a)]) | python | def _strvar(a, prec='{:G}'):
r"""Return variable as a string to print, with given precision."""
return ' '.join([prec.format(i) for i in np.atleast_1d(a)]) | [
"def",
"_strvar",
"(",
"a",
",",
"prec",
"=",
"'{:G}'",
")",
":",
"return",
"' '",
".",
"join",
"(",
"[",
"prec",
".",
"format",
"(",
"i",
")",
"for",
"i",
"in",
"np",
".",
"atleast_1d",
"(",
"a",
")",
"]",
")"
] | r"""Return variable as a string to print, with given precision. | [
"r",
"Return",
"variable",
"as",
"a",
"string",
"to",
"print",
"with",
"given",
"precision",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/utils.py#L1890-L1892 | train | 24,638 |
empymod/empymod | empymod/utils.py | _check_min | def _check_min(par, minval, name, unit, verb):
r"""Check minimum value of parameter."""
scalar = False
if par.shape == ():
scalar = True
par = np.atleast_1d(par)
if minval is not None:
ipar = np.where(par < minval)
par[ipar] = minval
if verb > 0 and np.size(ipar) != 0:
print('* WARNING :: ' + name + ' < ' + str(minval) + ' ' + unit +
' are set to ' + str(minval) + ' ' + unit + '!')
if scalar:
return np.squeeze(par)
else:
return par | python | def _check_min(par, minval, name, unit, verb):
r"""Check minimum value of parameter."""
scalar = False
if par.shape == ():
scalar = True
par = np.atleast_1d(par)
if minval is not None:
ipar = np.where(par < minval)
par[ipar] = minval
if verb > 0 and np.size(ipar) != 0:
print('* WARNING :: ' + name + ' < ' + str(minval) + ' ' + unit +
' are set to ' + str(minval) + ' ' + unit + '!')
if scalar:
return np.squeeze(par)
else:
return par | [
"def",
"_check_min",
"(",
"par",
",",
"minval",
",",
"name",
",",
"unit",
",",
"verb",
")",
":",
"scalar",
"=",
"False",
"if",
"par",
".",
"shape",
"==",
"(",
")",
":",
"scalar",
"=",
"True",
"par",
"=",
"np",
".",
"atleast_1d",
"(",
"par",
")",
... | r"""Check minimum value of parameter. | [
"r",
"Check",
"minimum",
"value",
"of",
"parameter",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/utils.py#L1906-L1921 | train | 24,639 |
empymod/empymod | empymod/utils.py | spline_backwards_hankel | def spline_backwards_hankel(ht, htarg, opt):
r"""Check opt if deprecated 'spline' is used.
Returns corrected htarg, opt.
r"""
# Ensure ht is all lowercase
ht = ht.lower()
# Only relevant for 'fht' and 'hqwe', not for 'quad'
if ht in ['fht', 'qwe', 'hqwe']:
# Get corresponding htarg
if ht == 'fht':
htarg = _check_targ(htarg, ['fhtfilt', 'pts_per_dec'])
elif ht in ['qwe', 'hqwe']:
htarg = _check_targ(htarg, ['rtol', 'atol', 'nquad', 'maxint',
'pts_per_dec', 'diff_quad', 'a', 'b', 'limit'])
# If spline (qwe, fht) or lagged (fht)
if opt == 'spline':
# Issue warning
mesg = ("\n The use of `opt='spline'` is deprecated and will " +
"be removed\n in v2.0.0; use the corresponding " +
"setting in `htarg`.")
warnings.warn(mesg, DeprecationWarning)
# Reset opt
opt = None
# Check pts_per_dec; set to old default values if not given
if 'pts_per_dec' not in htarg:
if ht == 'fht':
htarg['pts_per_dec'] = -1 # Lagged Convolution DLF
elif ht in ['qwe', 'hqwe']:
htarg['pts_per_dec'] = 80 # Splined QWE; old default value
return htarg, opt | python | def spline_backwards_hankel(ht, htarg, opt):
r"""Check opt if deprecated 'spline' is used.
Returns corrected htarg, opt.
r"""
# Ensure ht is all lowercase
ht = ht.lower()
# Only relevant for 'fht' and 'hqwe', not for 'quad'
if ht in ['fht', 'qwe', 'hqwe']:
# Get corresponding htarg
if ht == 'fht':
htarg = _check_targ(htarg, ['fhtfilt', 'pts_per_dec'])
elif ht in ['qwe', 'hqwe']:
htarg = _check_targ(htarg, ['rtol', 'atol', 'nquad', 'maxint',
'pts_per_dec', 'diff_quad', 'a', 'b', 'limit'])
# If spline (qwe, fht) or lagged (fht)
if opt == 'spline':
# Issue warning
mesg = ("\n The use of `opt='spline'` is deprecated and will " +
"be removed\n in v2.0.0; use the corresponding " +
"setting in `htarg`.")
warnings.warn(mesg, DeprecationWarning)
# Reset opt
opt = None
# Check pts_per_dec; set to old default values if not given
if 'pts_per_dec' not in htarg:
if ht == 'fht':
htarg['pts_per_dec'] = -1 # Lagged Convolution DLF
elif ht in ['qwe', 'hqwe']:
htarg['pts_per_dec'] = 80 # Splined QWE; old default value
return htarg, opt | [
"def",
"spline_backwards_hankel",
"(",
"ht",
",",
"htarg",
",",
"opt",
")",
":",
"# Ensure ht is all lowercase",
"ht",
"=",
"ht",
".",
"lower",
"(",
")",
"# Only relevant for 'fht' and 'hqwe', not for 'quad'",
"if",
"ht",
"in",
"[",
"'fht'",
",",
"'qwe'",
",",
"... | r"""Check opt if deprecated 'spline' is used.
Returns corrected htarg, opt.
r | [
"r",
"Check",
"opt",
"if",
"deprecated",
"spline",
"is",
"used",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/utils.py#L1937-L1975 | train | 24,640 |
empymod/empymod | empymod/model.py | gpr | def gpr(src, rec, depth, res, freqtime, cf, gain=None, ab=11, aniso=None,
epermH=None, epermV=None, mpermH=None, mpermV=None, xdirect=False,
ht='quad', htarg=None, ft='fft', ftarg=None, opt=None, loop=None,
verb=2):
r"""Return the Ground-Penetrating Radar signal.
THIS FUNCTION IS EXPERIMENTAL, USE WITH CAUTION.
It is rather an example how you can calculate GPR responses; however, DO
NOT RELY ON IT! It works only well with QUAD or QWE (``quad``, ``qwe``) for
the Hankel transform, and with FFT (``fft``) for the Fourier transform.
It calls internally ``dipole`` for the frequency-domain calculation. It
subsequently convolves the response with a Ricker wavelet with central
frequency ``cf``. If signal!=None, it carries out the Fourier transform and
applies a gain to the response.
For input parameters see the function ``dipole``, except for:
Parameters
----------
cf : float
Centre frequency of GPR-signal, in Hz. Sensible values are between
10 MHz and 3000 MHz.
gain : float
Power of gain function. If None, no gain is applied. Only used if
signal!=None.
Returns
-------
EM : ndarray
GPR response
"""
if verb > 2:
print(" GPR : EXPERIMENTAL, USE WITH CAUTION")
print(" > centre freq : " + str(cf))
print(" > gain : " + str(gain))
# === 1. CHECK TIME ============
# Check times and Fourier Transform arguments, get required frequencies
time, freq, ft, ftarg = check_time(freqtime, 0, ft, ftarg, verb)
# === 2. CALL DIPOLE ============
EM = dipole(src, rec, depth, res, freq, None, ab, aniso, epermH, epermV,
mpermH, mpermV, xdirect, ht, htarg, ft, ftarg, opt, loop, verb)
# === 3. GPR STUFF
# Get required parameters
src, nsrc = check_dipole(src, 'src', 0)
rec, nrec = check_dipole(rec, 'rec', 0)
off, _ = get_off_ang(src, rec, nsrc, nrec, 0)
# Reshape output from dipole
EM = EM.reshape((-1, nrec*nsrc), order='F')
# Multiply with ricker wavelet
cfc = -(np.r_[0, freq[:-1]]/cf)**2
fwave = cfc*np.exp(cfc)
EM *= fwave[:, None]
# Do f->t transform
EM, conv = tem(EM, off, freq, time, 0, ft, ftarg)
# In case of QWE/QUAD, print Warning if not converged
conv_warning(conv, ftarg, 'Fourier', verb)
# Apply gain; make pure real
EM *= (1 + np.abs((time*10**9)**gain))[:, None]
EM = EM.real
# Reshape for number of sources
EM = np.squeeze(EM.reshape((-1, nrec, nsrc), order='F'))
return EM | python | def gpr(src, rec, depth, res, freqtime, cf, gain=None, ab=11, aniso=None,
epermH=None, epermV=None, mpermH=None, mpermV=None, xdirect=False,
ht='quad', htarg=None, ft='fft', ftarg=None, opt=None, loop=None,
verb=2):
r"""Return the Ground-Penetrating Radar signal.
THIS FUNCTION IS EXPERIMENTAL, USE WITH CAUTION.
It is rather an example how you can calculate GPR responses; however, DO
NOT RELY ON IT! It works only well with QUAD or QWE (``quad``, ``qwe``) for
the Hankel transform, and with FFT (``fft``) for the Fourier transform.
It calls internally ``dipole`` for the frequency-domain calculation. It
subsequently convolves the response with a Ricker wavelet with central
frequency ``cf``. If signal!=None, it carries out the Fourier transform and
applies a gain to the response.
For input parameters see the function ``dipole``, except for:
Parameters
----------
cf : float
Centre frequency of GPR-signal, in Hz. Sensible values are between
10 MHz and 3000 MHz.
gain : float
Power of gain function. If None, no gain is applied. Only used if
signal!=None.
Returns
-------
EM : ndarray
GPR response
"""
if verb > 2:
print(" GPR : EXPERIMENTAL, USE WITH CAUTION")
print(" > centre freq : " + str(cf))
print(" > gain : " + str(gain))
# === 1. CHECK TIME ============
# Check times and Fourier Transform arguments, get required frequencies
time, freq, ft, ftarg = check_time(freqtime, 0, ft, ftarg, verb)
# === 2. CALL DIPOLE ============
EM = dipole(src, rec, depth, res, freq, None, ab, aniso, epermH, epermV,
mpermH, mpermV, xdirect, ht, htarg, ft, ftarg, opt, loop, verb)
# === 3. GPR STUFF
# Get required parameters
src, nsrc = check_dipole(src, 'src', 0)
rec, nrec = check_dipole(rec, 'rec', 0)
off, _ = get_off_ang(src, rec, nsrc, nrec, 0)
# Reshape output from dipole
EM = EM.reshape((-1, nrec*nsrc), order='F')
# Multiply with ricker wavelet
cfc = -(np.r_[0, freq[:-1]]/cf)**2
fwave = cfc*np.exp(cfc)
EM *= fwave[:, None]
# Do f->t transform
EM, conv = tem(EM, off, freq, time, 0, ft, ftarg)
# In case of QWE/QUAD, print Warning if not converged
conv_warning(conv, ftarg, 'Fourier', verb)
# Apply gain; make pure real
EM *= (1 + np.abs((time*10**9)**gain))[:, None]
EM = EM.real
# Reshape for number of sources
EM = np.squeeze(EM.reshape((-1, nrec, nsrc), order='F'))
return EM | [
"def",
"gpr",
"(",
"src",
",",
"rec",
",",
"depth",
",",
"res",
",",
"freqtime",
",",
"cf",
",",
"gain",
"=",
"None",
",",
"ab",
"=",
"11",
",",
"aniso",
"=",
"None",
",",
"epermH",
"=",
"None",
",",
"epermV",
"=",
"None",
",",
"mpermH",
"=",
... | r"""Return the Ground-Penetrating Radar signal.
THIS FUNCTION IS EXPERIMENTAL, USE WITH CAUTION.
It is rather an example how you can calculate GPR responses; however, DO
NOT RELY ON IT! It works only well with QUAD or QWE (``quad``, ``qwe``) for
the Hankel transform, and with FFT (``fft``) for the Fourier transform.
It calls internally ``dipole`` for the frequency-domain calculation. It
subsequently convolves the response with a Ricker wavelet with central
frequency ``cf``. If signal!=None, it carries out the Fourier transform and
applies a gain to the response.
For input parameters see the function ``dipole``, except for:
Parameters
----------
cf : float
Centre frequency of GPR-signal, in Hz. Sensible values are between
10 MHz and 3000 MHz.
gain : float
Power of gain function. If None, no gain is applied. Only used if
signal!=None.
Returns
-------
EM : ndarray
GPR response | [
"r",
"Return",
"the",
"Ground",
"-",
"Penetrating",
"Radar",
"signal",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/model.py#L1187-L1266 | train | 24,641 |
empymod/empymod | empymod/model.py | dipole_k | def dipole_k(src, rec, depth, res, freq, wavenumber, ab=11, aniso=None,
epermH=None, epermV=None, mpermH=None, mpermV=None, verb=2):
r"""Return the electromagnetic wavenumber-domain field.
Calculate the electromagnetic wavenumber-domain field due to infinitesimal
small electric or magnetic dipole source(s), measured by infinitesimal
small electric or magnetic dipole receiver(s); sources and receivers are
directed along the principal directions x, y, or z, and all sources are at
the same depth, as well as all receivers are at the same depth.
See Also
--------
dipole : Electromagnetic field due to an electromagnetic source (dipoles).
bipole : Electromagnetic field due to an electromagnetic source (bipoles).
fem : Electromagnetic frequency-domain response.
tem : Electromagnetic time-domain response.
Parameters
----------
src, rec : list of floats or arrays
Source and receiver coordinates (m): [x, y, z].
The x- and y-coordinates can be arrays, z is a single value.
The x- and y-coordinates must have the same dimension.
The x- and y-coordinates only matter for the angle-dependent factor.
Sources or receivers placed on a layer interface are considered in the
upper layer.
depth : list
Absolute layer interfaces z (m); #depth = #res - 1
(excluding +/- infinity).
res : array_like
Horizontal resistivities rho_h (Ohm.m); #res = #depth + 1.
freq : array_like
Frequencies f (Hz), used to calculate etaH/V and zetaH/V.
wavenumber : array
Wavenumbers lambda (1/m)
ab : int, optional
Source-receiver configuration, defaults to 11.
+---------------+-------+------+------+------+------+------+------+
| | electric source | magnetic source |
+===============+=======+======+======+======+======+======+======+
| | **x**| **y**| **z**| **x**| **y**| **z**|
+---------------+-------+------+------+------+------+------+------+
| | **x** | 11 | 12 | 13 | 14 | 15 | 16 |
+ **electric** +-------+------+------+------+------+------+------+
| | **y** | 21 | 22 | 23 | 24 | 25 | 26 |
+ **receiver** +-------+------+------+------+------+------+------+
| | **z** | 31 | 32 | 33 | 34 | 35 | 36 |
+---------------+-------+------+------+------+------+------+------+
| | **x** | 41 | 42 | 43 | 44 | 45 | 46 |
+ **magnetic** +-------+------+------+------+------+------+------+
| | **y** | 51 | 52 | 53 | 54 | 55 | 56 |
+ **receiver** +-------+------+------+------+------+------+------+
| | **z** | 61 | 62 | 63 | 64 | 65 | 66 |
+---------------+-------+------+------+------+------+------+------+
aniso : array_like, optional
Anisotropies lambda = sqrt(rho_v/rho_h) (-); #aniso = #res.
Defaults to ones.
epermH, epermV : array_like, optional
Relative horizontal/vertical electric permittivities
epsilon_h/epsilon_v (-);
#epermH = #epermV = #res. Default is ones.
mpermH, mpermV : array_like, optional
Relative horizontal/vertical magnetic permeabilities mu_h/mu_v (-);
#mpermH = #mpermV = #res. Default is ones.
verb : {0, 1, 2, 3, 4}, optional
Level of verbosity, default is 2:
- 0: Print nothing.
- 1: Print warnings.
- 2: Print additional runtime and kernel calls
- 3: Print additional start/stop, condensed parameter information.
- 4: Print additional full parameter information
Returns
-------
PJ0, PJ1 : array
Wavenumber-domain EM responses:
- PJ0: Wavenumber-domain solution for the kernel with a Bessel
function of the first kind of order zero.
- PJ1: Wavenumber-domain solution for the kernel with a Bessel
function of the first kind of order one.
Examples
--------
>>> import numpy as np
>>> from empymod.model import dipole_k
>>> src = [0, 0, 100]
>>> rec = [5000, 0, 200]
>>> depth = [0, 300, 1000, 1050]
>>> res = [1e20, .3, 1, 50, 1]
>>> freq = 1
>>> wavenrs = np.logspace(-3.7, -3.6, 10)
>>> PJ0, PJ1 = dipole_k(src, rec, depth, res, freq, wavenrs, verb=0)
>>> print(PJ0)
[ -1.02638329e-08 +4.91531529e-09j -1.05289724e-08 +5.04222413e-09j
-1.08009148e-08 +5.17238608e-09j -1.10798310e-08 +5.30588284e-09j
-1.13658957e-08 +5.44279805e-09j -1.16592877e-08 +5.58321732e-09j
-1.19601897e-08 +5.72722830e-09j -1.22687889e-08 +5.87492067e-09j
-1.25852765e-08 +6.02638626e-09j -1.29098481e-08 +6.18171904e-09j]
>>> print(PJ1)
[ 1.79483705e-10 -6.59235332e-10j 1.88672497e-10 -6.93749344e-10j
1.98325814e-10 -7.30068377e-10j 2.08466693e-10 -7.68286748e-10j
2.19119282e-10 -8.08503709e-10j 2.30308887e-10 -8.50823701e-10j
2.42062030e-10 -8.95356636e-10j 2.54406501e-10 -9.42218177e-10j
2.67371420e-10 -9.91530051e-10j 2.80987292e-10 -1.04342036e-09j]
"""
# === 1. LET'S START ============
t0 = printstartfinish(verb)
# === 2. CHECK INPUT ============
# Check layer parameters (isfullspace not required)
modl = check_model(depth, res, aniso, epermH, epermV, mpermH, mpermV,
False, verb)
depth, res, aniso, epermH, epermV, mpermH, mpermV, _ = modl
# Check frequency => get etaH, etaV, zetaH, and zetaV
f = check_frequency(freq, res, aniso, epermH, epermV, mpermH, mpermV, verb)
freq, etaH, etaV, zetaH, zetaV = f
# Check src-rec configuration
# => Get flags if src or rec or both are magnetic (msrc, mrec)
ab_calc, msrc, mrec = check_ab(ab, verb)
# Check src and rec
src, nsrc = check_dipole(src, 'src', verb)
rec, nrec = check_dipole(rec, 'rec', verb)
# Get angle-dependent factor
off, angle = get_off_ang(src, rec, nsrc, nrec, verb)
factAng = kernel.angle_factor(angle, ab, msrc, mrec)
# Get layer number in which src and rec reside (lsrc/lrec)
lsrc, zsrc = get_layer_nr(src, depth)
lrec, zrec = get_layer_nr(rec, depth)
# === 3. EM-FIELD CALCULATION ============
# Pre-allocate
if off.size == 1 and np.ndim(wavenumber) == 2:
PJ0 = np.zeros((freq.size, wavenumber.shape[0], wavenumber.shape[1]),
dtype=complex)
PJ1 = np.zeros((freq.size, wavenumber.shape[0], wavenumber.shape[1]),
dtype=complex)
else:
PJ0 = np.zeros((freq.size, off.size, wavenumber.size), dtype=complex)
PJ1 = np.zeros((freq.size, off.size, wavenumber.size), dtype=complex)
# If <ab> = 36 (or 63), field is zero
# In `bipole` and in `dipole`, this is taken care of in `fem`. Here we
# have to take care of it separately
if ab_calc not in [36, ]:
# Calculate wavenumber response
J0, J1, J0b = kernel.wavenumber(zsrc, zrec, lsrc, lrec, depth, etaH,
etaV, zetaH, zetaV,
np.atleast_2d(wavenumber), ab_calc,
False, msrc, mrec, False)
# Collect output
if J1 is not None:
PJ1 += factAng[:, np.newaxis]*J1
if ab in [11, 12, 21, 22, 14, 24, 15, 25]: # Because of J2
# J2(kr) = 2/(kr)*J1(kr) - J0(kr)
PJ1 /= off[:, None]
if J0 is not None:
PJ0 += J0
if J0b is not None:
PJ0 += factAng[:, np.newaxis]*J0b
# === 4. FINISHED ============
printstartfinish(verb, t0, 1)
return np.squeeze(PJ0), np.squeeze(PJ1) | python | def dipole_k(src, rec, depth, res, freq, wavenumber, ab=11, aniso=None,
epermH=None, epermV=None, mpermH=None, mpermV=None, verb=2):
r"""Return the electromagnetic wavenumber-domain field.
Calculate the electromagnetic wavenumber-domain field due to infinitesimal
small electric or magnetic dipole source(s), measured by infinitesimal
small electric or magnetic dipole receiver(s); sources and receivers are
directed along the principal directions x, y, or z, and all sources are at
the same depth, as well as all receivers are at the same depth.
See Also
--------
dipole : Electromagnetic field due to an electromagnetic source (dipoles).
bipole : Electromagnetic field due to an electromagnetic source (bipoles).
fem : Electromagnetic frequency-domain response.
tem : Electromagnetic time-domain response.
Parameters
----------
src, rec : list of floats or arrays
Source and receiver coordinates (m): [x, y, z].
The x- and y-coordinates can be arrays, z is a single value.
The x- and y-coordinates must have the same dimension.
The x- and y-coordinates only matter for the angle-dependent factor.
Sources or receivers placed on a layer interface are considered in the
upper layer.
depth : list
Absolute layer interfaces z (m); #depth = #res - 1
(excluding +/- infinity).
res : array_like
Horizontal resistivities rho_h (Ohm.m); #res = #depth + 1.
freq : array_like
Frequencies f (Hz), used to calculate etaH/V and zetaH/V.
wavenumber : array
Wavenumbers lambda (1/m)
ab : int, optional
Source-receiver configuration, defaults to 11.
+---------------+-------+------+------+------+------+------+------+
| | electric source | magnetic source |
+===============+=======+======+======+======+======+======+======+
| | **x**| **y**| **z**| **x**| **y**| **z**|
+---------------+-------+------+------+------+------+------+------+
| | **x** | 11 | 12 | 13 | 14 | 15 | 16 |
+ **electric** +-------+------+------+------+------+------+------+
| | **y** | 21 | 22 | 23 | 24 | 25 | 26 |
+ **receiver** +-------+------+------+------+------+------+------+
| | **z** | 31 | 32 | 33 | 34 | 35 | 36 |
+---------------+-------+------+------+------+------+------+------+
| | **x** | 41 | 42 | 43 | 44 | 45 | 46 |
+ **magnetic** +-------+------+------+------+------+------+------+
| | **y** | 51 | 52 | 53 | 54 | 55 | 56 |
+ **receiver** +-------+------+------+------+------+------+------+
| | **z** | 61 | 62 | 63 | 64 | 65 | 66 |
+---------------+-------+------+------+------+------+------+------+
aniso : array_like, optional
Anisotropies lambda = sqrt(rho_v/rho_h) (-); #aniso = #res.
Defaults to ones.
epermH, epermV : array_like, optional
Relative horizontal/vertical electric permittivities
epsilon_h/epsilon_v (-);
#epermH = #epermV = #res. Default is ones.
mpermH, mpermV : array_like, optional
Relative horizontal/vertical magnetic permeabilities mu_h/mu_v (-);
#mpermH = #mpermV = #res. Default is ones.
verb : {0, 1, 2, 3, 4}, optional
Level of verbosity, default is 2:
- 0: Print nothing.
- 1: Print warnings.
- 2: Print additional runtime and kernel calls
- 3: Print additional start/stop, condensed parameter information.
- 4: Print additional full parameter information
Returns
-------
PJ0, PJ1 : array
Wavenumber-domain EM responses:
- PJ0: Wavenumber-domain solution for the kernel with a Bessel
function of the first kind of order zero.
- PJ1: Wavenumber-domain solution for the kernel with a Bessel
function of the first kind of order one.
Examples
--------
>>> import numpy as np
>>> from empymod.model import dipole_k
>>> src = [0, 0, 100]
>>> rec = [5000, 0, 200]
>>> depth = [0, 300, 1000, 1050]
>>> res = [1e20, .3, 1, 50, 1]
>>> freq = 1
>>> wavenrs = np.logspace(-3.7, -3.6, 10)
>>> PJ0, PJ1 = dipole_k(src, rec, depth, res, freq, wavenrs, verb=0)
>>> print(PJ0)
[ -1.02638329e-08 +4.91531529e-09j -1.05289724e-08 +5.04222413e-09j
-1.08009148e-08 +5.17238608e-09j -1.10798310e-08 +5.30588284e-09j
-1.13658957e-08 +5.44279805e-09j -1.16592877e-08 +5.58321732e-09j
-1.19601897e-08 +5.72722830e-09j -1.22687889e-08 +5.87492067e-09j
-1.25852765e-08 +6.02638626e-09j -1.29098481e-08 +6.18171904e-09j]
>>> print(PJ1)
[ 1.79483705e-10 -6.59235332e-10j 1.88672497e-10 -6.93749344e-10j
1.98325814e-10 -7.30068377e-10j 2.08466693e-10 -7.68286748e-10j
2.19119282e-10 -8.08503709e-10j 2.30308887e-10 -8.50823701e-10j
2.42062030e-10 -8.95356636e-10j 2.54406501e-10 -9.42218177e-10j
2.67371420e-10 -9.91530051e-10j 2.80987292e-10 -1.04342036e-09j]
"""
# === 1. LET'S START ============
t0 = printstartfinish(verb)
# === 2. CHECK INPUT ============
# Check layer parameters (isfullspace not required)
modl = check_model(depth, res, aniso, epermH, epermV, mpermH, mpermV,
False, verb)
depth, res, aniso, epermH, epermV, mpermH, mpermV, _ = modl
# Check frequency => get etaH, etaV, zetaH, and zetaV
f = check_frequency(freq, res, aniso, epermH, epermV, mpermH, mpermV, verb)
freq, etaH, etaV, zetaH, zetaV = f
# Check src-rec configuration
# => Get flags if src or rec or both are magnetic (msrc, mrec)
ab_calc, msrc, mrec = check_ab(ab, verb)
# Check src and rec
src, nsrc = check_dipole(src, 'src', verb)
rec, nrec = check_dipole(rec, 'rec', verb)
# Get angle-dependent factor
off, angle = get_off_ang(src, rec, nsrc, nrec, verb)
factAng = kernel.angle_factor(angle, ab, msrc, mrec)
# Get layer number in which src and rec reside (lsrc/lrec)
lsrc, zsrc = get_layer_nr(src, depth)
lrec, zrec = get_layer_nr(rec, depth)
# === 3. EM-FIELD CALCULATION ============
# Pre-allocate
if off.size == 1 and np.ndim(wavenumber) == 2:
PJ0 = np.zeros((freq.size, wavenumber.shape[0], wavenumber.shape[1]),
dtype=complex)
PJ1 = np.zeros((freq.size, wavenumber.shape[0], wavenumber.shape[1]),
dtype=complex)
else:
PJ0 = np.zeros((freq.size, off.size, wavenumber.size), dtype=complex)
PJ1 = np.zeros((freq.size, off.size, wavenumber.size), dtype=complex)
# If <ab> = 36 (or 63), field is zero
# In `bipole` and in `dipole`, this is taken care of in `fem`. Here we
# have to take care of it separately
if ab_calc not in [36, ]:
# Calculate wavenumber response
J0, J1, J0b = kernel.wavenumber(zsrc, zrec, lsrc, lrec, depth, etaH,
etaV, zetaH, zetaV,
np.atleast_2d(wavenumber), ab_calc,
False, msrc, mrec, False)
# Collect output
if J1 is not None:
PJ1 += factAng[:, np.newaxis]*J1
if ab in [11, 12, 21, 22, 14, 24, 15, 25]: # Because of J2
# J2(kr) = 2/(kr)*J1(kr) - J0(kr)
PJ1 /= off[:, None]
if J0 is not None:
PJ0 += J0
if J0b is not None:
PJ0 += factAng[:, np.newaxis]*J0b
# === 4. FINISHED ============
printstartfinish(verb, t0, 1)
return np.squeeze(PJ0), np.squeeze(PJ1) | [
"def",
"dipole_k",
"(",
"src",
",",
"rec",
",",
"depth",
",",
"res",
",",
"freq",
",",
"wavenumber",
",",
"ab",
"=",
"11",
",",
"aniso",
"=",
"None",
",",
"epermH",
"=",
"None",
",",
"epermV",
"=",
"None",
",",
"mpermH",
"=",
"None",
",",
"mpermV... | r"""Return the electromagnetic wavenumber-domain field.
Calculate the electromagnetic wavenumber-domain field due to infinitesimal
small electric or magnetic dipole source(s), measured by infinitesimal
small electric or magnetic dipole receiver(s); sources and receivers are
directed along the principal directions x, y, or z, and all sources are at
the same depth, as well as all receivers are at the same depth.
See Also
--------
dipole : Electromagnetic field due to an electromagnetic source (dipoles).
bipole : Electromagnetic field due to an electromagnetic source (bipoles).
fem : Electromagnetic frequency-domain response.
tem : Electromagnetic time-domain response.
Parameters
----------
src, rec : list of floats or arrays
Source and receiver coordinates (m): [x, y, z].
The x- and y-coordinates can be arrays, z is a single value.
The x- and y-coordinates must have the same dimension.
The x- and y-coordinates only matter for the angle-dependent factor.
Sources or receivers placed on a layer interface are considered in the
upper layer.
depth : list
Absolute layer interfaces z (m); #depth = #res - 1
(excluding +/- infinity).
res : array_like
Horizontal resistivities rho_h (Ohm.m); #res = #depth + 1.
freq : array_like
Frequencies f (Hz), used to calculate etaH/V and zetaH/V.
wavenumber : array
Wavenumbers lambda (1/m)
ab : int, optional
Source-receiver configuration, defaults to 11.
+---------------+-------+------+------+------+------+------+------+
| | electric source | magnetic source |
+===============+=======+======+======+======+======+======+======+
| | **x**| **y**| **z**| **x**| **y**| **z**|
+---------------+-------+------+------+------+------+------+------+
| | **x** | 11 | 12 | 13 | 14 | 15 | 16 |
+ **electric** +-------+------+------+------+------+------+------+
| | **y** | 21 | 22 | 23 | 24 | 25 | 26 |
+ **receiver** +-------+------+------+------+------+------+------+
| | **z** | 31 | 32 | 33 | 34 | 35 | 36 |
+---------------+-------+------+------+------+------+------+------+
| | **x** | 41 | 42 | 43 | 44 | 45 | 46 |
+ **magnetic** +-------+------+------+------+------+------+------+
| | **y** | 51 | 52 | 53 | 54 | 55 | 56 |
+ **receiver** +-------+------+------+------+------+------+------+
| | **z** | 61 | 62 | 63 | 64 | 65 | 66 |
+---------------+-------+------+------+------+------+------+------+
aniso : array_like, optional
Anisotropies lambda = sqrt(rho_v/rho_h) (-); #aniso = #res.
Defaults to ones.
epermH, epermV : array_like, optional
Relative horizontal/vertical electric permittivities
epsilon_h/epsilon_v (-);
#epermH = #epermV = #res. Default is ones.
mpermH, mpermV : array_like, optional
Relative horizontal/vertical magnetic permeabilities mu_h/mu_v (-);
#mpermH = #mpermV = #res. Default is ones.
verb : {0, 1, 2, 3, 4}, optional
Level of verbosity, default is 2:
- 0: Print nothing.
- 1: Print warnings.
- 2: Print additional runtime and kernel calls
- 3: Print additional start/stop, condensed parameter information.
- 4: Print additional full parameter information
Returns
-------
PJ0, PJ1 : array
Wavenumber-domain EM responses:
- PJ0: Wavenumber-domain solution for the kernel with a Bessel
function of the first kind of order zero.
- PJ1: Wavenumber-domain solution for the kernel with a Bessel
function of the first kind of order one.
Examples
--------
>>> import numpy as np
>>> from empymod.model import dipole_k
>>> src = [0, 0, 100]
>>> rec = [5000, 0, 200]
>>> depth = [0, 300, 1000, 1050]
>>> res = [1e20, .3, 1, 50, 1]
>>> freq = 1
>>> wavenrs = np.logspace(-3.7, -3.6, 10)
>>> PJ0, PJ1 = dipole_k(src, rec, depth, res, freq, wavenrs, verb=0)
>>> print(PJ0)
[ -1.02638329e-08 +4.91531529e-09j -1.05289724e-08 +5.04222413e-09j
-1.08009148e-08 +5.17238608e-09j -1.10798310e-08 +5.30588284e-09j
-1.13658957e-08 +5.44279805e-09j -1.16592877e-08 +5.58321732e-09j
-1.19601897e-08 +5.72722830e-09j -1.22687889e-08 +5.87492067e-09j
-1.25852765e-08 +6.02638626e-09j -1.29098481e-08 +6.18171904e-09j]
>>> print(PJ1)
[ 1.79483705e-10 -6.59235332e-10j 1.88672497e-10 -6.93749344e-10j
1.98325814e-10 -7.30068377e-10j 2.08466693e-10 -7.68286748e-10j
2.19119282e-10 -8.08503709e-10j 2.30308887e-10 -8.50823701e-10j
2.42062030e-10 -8.95356636e-10j 2.54406501e-10 -9.42218177e-10j
2.67371420e-10 -9.91530051e-10j 2.80987292e-10 -1.04342036e-09j] | [
"r",
"Return",
"the",
"electromagnetic",
"wavenumber",
"-",
"domain",
"field",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/model.py#L1269-L1457 | train | 24,642 |
empymod/empymod | empymod/model.py | wavenumber | def wavenumber(src, rec, depth, res, freq, wavenumber, ab=11, aniso=None,
epermH=None, epermV=None, mpermH=None, mpermV=None, verb=2):
r"""Depreciated. Use `dipole_k` instead."""
# Issue warning
mesg = ("\n The use of `model.wavenumber` is deprecated and will " +
"be removed;\n use `model.dipole_k` instead.")
warnings.warn(mesg, DeprecationWarning)
return dipole_k(src, rec, depth, res, freq, wavenumber, ab, aniso, epermH,
epermV, mpermH, mpermV, verb) | python | def wavenumber(src, rec, depth, res, freq, wavenumber, ab=11, aniso=None,
epermH=None, epermV=None, mpermH=None, mpermV=None, verb=2):
r"""Depreciated. Use `dipole_k` instead."""
# Issue warning
mesg = ("\n The use of `model.wavenumber` is deprecated and will " +
"be removed;\n use `model.dipole_k` instead.")
warnings.warn(mesg, DeprecationWarning)
return dipole_k(src, rec, depth, res, freq, wavenumber, ab, aniso, epermH,
epermV, mpermH, mpermV, verb) | [
"def",
"wavenumber",
"(",
"src",
",",
"rec",
",",
"depth",
",",
"res",
",",
"freq",
",",
"wavenumber",
",",
"ab",
"=",
"11",
",",
"aniso",
"=",
"None",
",",
"epermH",
"=",
"None",
",",
"epermV",
"=",
"None",
",",
"mpermH",
"=",
"None",
",",
"mper... | r"""Depreciated. Use `dipole_k` instead. | [
"r",
"Depreciated",
".",
"Use",
"dipole_k",
"instead",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/model.py#L1460-L1470 | train | 24,643 |
empymod/empymod | empymod/model.py | tem | def tem(fEM, off, freq, time, signal, ft, ftarg, conv=True):
r"""Return the time-domain response of the frequency-domain response fEM.
This function is called from one of the above modelling routines. No
input-check is carried out here. See the main description of :mod:`model`
for information regarding input and output parameters.
This function can be directly used if you are sure the provided input is in
the correct format. This is useful for inversion routines and similar, as
it can speed-up the calculation by omitting input-checks.
"""
# 1. Scale frequencies if switch-on/off response
# Step function for causal times is like a unit fct, therefore an impulse
# in frequency domain
if signal in [-1, 1]:
# Divide by signal/(2j*pi*f) to obtain step response
fact = signal/(2j*np.pi*freq)
else:
fact = 1
# 2. f->t transform
tEM = np.zeros((time.size, off.size))
for i in range(off.size):
out = getattr(transform, ft)(fEM[:, i]*fact, time, freq, ftarg)
tEM[:, i] += out[0]
conv *= out[1]
return tEM*2/np.pi, conv | python | def tem(fEM, off, freq, time, signal, ft, ftarg, conv=True):
r"""Return the time-domain response of the frequency-domain response fEM.
This function is called from one of the above modelling routines. No
input-check is carried out here. See the main description of :mod:`model`
for information regarding input and output parameters.
This function can be directly used if you are sure the provided input is in
the correct format. This is useful for inversion routines and similar, as
it can speed-up the calculation by omitting input-checks.
"""
# 1. Scale frequencies if switch-on/off response
# Step function for causal times is like a unit fct, therefore an impulse
# in frequency domain
if signal in [-1, 1]:
# Divide by signal/(2j*pi*f) to obtain step response
fact = signal/(2j*np.pi*freq)
else:
fact = 1
# 2. f->t transform
tEM = np.zeros((time.size, off.size))
for i in range(off.size):
out = getattr(transform, ft)(fEM[:, i]*fact, time, freq, ftarg)
tEM[:, i] += out[0]
conv *= out[1]
return tEM*2/np.pi, conv | [
"def",
"tem",
"(",
"fEM",
",",
"off",
",",
"freq",
",",
"time",
",",
"signal",
",",
"ft",
",",
"ftarg",
",",
"conv",
"=",
"True",
")",
":",
"# 1. Scale frequencies if switch-on/off response",
"# Step function for causal times is like a unit fct, therefore an impulse",
... | r"""Return the time-domain response of the frequency-domain response fEM.
This function is called from one of the above modelling routines. No
input-check is carried out here. See the main description of :mod:`model`
for information regarding input and output parameters.
This function can be directly used if you are sure the provided input is in
the correct format. This is useful for inversion routines and similar, as
it can speed-up the calculation by omitting input-checks. | [
"r",
"Return",
"the",
"time",
"-",
"domain",
"response",
"of",
"the",
"frequency",
"-",
"domain",
"response",
"fEM",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/model.py#L1565-L1593 | train | 24,644 |
empymod/empymod | empymod/scripts/fdesign.py | save_filter | def save_filter(name, filt, full=None, path='filters'):
r"""Save DLF-filter and inversion output to plain text files."""
# First we'll save the filter using its internal routine.
# This will create the directory ./filters if it doesn't exist already.
filt.tofile(path)
# If full, we store the inversion output
if full:
# Get file name
path = os.path.abspath(path)
if len(name.split('.')) == 2:
suffix = '.gz'
else:
suffix = ''
fullfile = os.path.join(path, name.split('.')[0]+'_full.txt' + suffix)
# Get number of spacing and shift values
nspace, nshift = full[3].shape
# Create header
header = 'Full inversion output from empymod.fdesign.design\n'
header += 'Line 11: Nr of spacing values\n'
header += 'Line 12: Nr of shift values\n'
header += 'Line 13: Best spacing value\n'
header += 'Line 14: Best shift value\n'
header += 'Line 15: Min amplitude or max offset\n'
header += 'Lines 16-{}: Spacing matrix '.format(nspace+15)
header += '({} x {})\n'.format(nspace, nshift)
header += 'Lines {}-{}: Spacing matrix '.format(nspace+16, 2*nspace+15)
header += '({} x {})\n'.format(nspace, nshift)
header += 'Lines {}-{}: Spacing '.format(2*nspace+16, 3*nspace+15)
header += 'matrix ({} x {})\n'.format(nspace, nshift)
header += 'Line {}: Integer: 0: min amp, 1: max r'.format(3*nspace+16)
# Create arrays; put single values in arrays of nshift values
nr_spacing = np.r_[nspace, np.zeros(nshift-1)]
nr_shift = np.r_[nshift, np.zeros(nshift-1)]
best_spacing = np.r_[full[0][0], np.zeros(nshift-1)]
best_shift = np.r_[full[0][1], np.zeros(nshift-1)]
min_value = np.r_[np.atleast_1d(full[1]), np.zeros(nshift-1)]
min_max = np.r_[full[4], np.zeros(nshift-1)]
# Collect all in one array
fullsave = np.vstack((nr_spacing, nr_shift, best_spacing, best_shift,
min_value, full[2][0], full[2][1], full[3],
min_max))
# Save array
np.savetxt(fullfile, fullsave, header=header) | python | def save_filter(name, filt, full=None, path='filters'):
r"""Save DLF-filter and inversion output to plain text files."""
# First we'll save the filter using its internal routine.
# This will create the directory ./filters if it doesn't exist already.
filt.tofile(path)
# If full, we store the inversion output
if full:
# Get file name
path = os.path.abspath(path)
if len(name.split('.')) == 2:
suffix = '.gz'
else:
suffix = ''
fullfile = os.path.join(path, name.split('.')[0]+'_full.txt' + suffix)
# Get number of spacing and shift values
nspace, nshift = full[3].shape
# Create header
header = 'Full inversion output from empymod.fdesign.design\n'
header += 'Line 11: Nr of spacing values\n'
header += 'Line 12: Nr of shift values\n'
header += 'Line 13: Best spacing value\n'
header += 'Line 14: Best shift value\n'
header += 'Line 15: Min amplitude or max offset\n'
header += 'Lines 16-{}: Spacing matrix '.format(nspace+15)
header += '({} x {})\n'.format(nspace, nshift)
header += 'Lines {}-{}: Spacing matrix '.format(nspace+16, 2*nspace+15)
header += '({} x {})\n'.format(nspace, nshift)
header += 'Lines {}-{}: Spacing '.format(2*nspace+16, 3*nspace+15)
header += 'matrix ({} x {})\n'.format(nspace, nshift)
header += 'Line {}: Integer: 0: min amp, 1: max r'.format(3*nspace+16)
# Create arrays; put single values in arrays of nshift values
nr_spacing = np.r_[nspace, np.zeros(nshift-1)]
nr_shift = np.r_[nshift, np.zeros(nshift-1)]
best_spacing = np.r_[full[0][0], np.zeros(nshift-1)]
best_shift = np.r_[full[0][1], np.zeros(nshift-1)]
min_value = np.r_[np.atleast_1d(full[1]), np.zeros(nshift-1)]
min_max = np.r_[full[4], np.zeros(nshift-1)]
# Collect all in one array
fullsave = np.vstack((nr_spacing, nr_shift, best_spacing, best_shift,
min_value, full[2][0], full[2][1], full[3],
min_max))
# Save array
np.savetxt(fullfile, fullsave, header=header) | [
"def",
"save_filter",
"(",
"name",
",",
"filt",
",",
"full",
"=",
"None",
",",
"path",
"=",
"'filters'",
")",
":",
"# First we'll save the filter using its internal routine.",
"# This will create the directory ./filters if it doesn't exist already.",
"filt",
".",
"tofile",
... | r"""Save DLF-filter and inversion output to plain text files. | [
"r",
"Save",
"DLF",
"-",
"filter",
"and",
"inversion",
"output",
"to",
"plain",
"text",
"files",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/scripts/fdesign.py#L469-L523 | train | 24,645 |
empymod/empymod | empymod/scripts/fdesign.py | load_filter | def load_filter(name, full=False, path='filters'):
r"""Load saved DLF-filter and inversion output from text files."""
# First we'll get the filter using its internal routine.
filt = DigitalFilter(name.split('.')[0])
filt.fromfile(path)
# If full, we get the inversion output
if full:
# Try to get the inversion result. If files are not found, most likely
# because they were not stored, we only return the filter
try:
# Get file name
path = os.path.abspath(path)
if len(name.split('.')) == 2:
suffix = '.gz'
else:
suffix = ''
fullfile = os.path.join(path, name.split('.')[0] +
'_full.txt' + suffix)
# Read data
out = np.loadtxt(fullfile)
except IOError:
return filt
# Collect inversion-result tuple
nspace = int(out[0][0])
nshift = int(out[1][0])
space_shift_matrix = np.zeros((2, nspace, nshift))
space_shift_matrix[0, :, :] = out[5:nspace+5, :]
space_shift_matrix[1, :, :] = out[nspace+5:2*nspace+5, :]
out = (np.array([out[2][0], out[3][0]]), out[4][0], space_shift_matrix,
out[2*nspace+5:3*nspace+5, :], int(out[3*nspace+5, 0]))
return filt, out
else:
return filt | python | def load_filter(name, full=False, path='filters'):
r"""Load saved DLF-filter and inversion output from text files."""
# First we'll get the filter using its internal routine.
filt = DigitalFilter(name.split('.')[0])
filt.fromfile(path)
# If full, we get the inversion output
if full:
# Try to get the inversion result. If files are not found, most likely
# because they were not stored, we only return the filter
try:
# Get file name
path = os.path.abspath(path)
if len(name.split('.')) == 2:
suffix = '.gz'
else:
suffix = ''
fullfile = os.path.join(path, name.split('.')[0] +
'_full.txt' + suffix)
# Read data
out = np.loadtxt(fullfile)
except IOError:
return filt
# Collect inversion-result tuple
nspace = int(out[0][0])
nshift = int(out[1][0])
space_shift_matrix = np.zeros((2, nspace, nshift))
space_shift_matrix[0, :, :] = out[5:nspace+5, :]
space_shift_matrix[1, :, :] = out[nspace+5:2*nspace+5, :]
out = (np.array([out[2][0], out[3][0]]), out[4][0], space_shift_matrix,
out[2*nspace+5:3*nspace+5, :], int(out[3*nspace+5, 0]))
return filt, out
else:
return filt | [
"def",
"load_filter",
"(",
"name",
",",
"full",
"=",
"False",
",",
"path",
"=",
"'filters'",
")",
":",
"# First we'll get the filter using its internal routine.",
"filt",
"=",
"DigitalFilter",
"(",
"name",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
")",
"... | r"""Load saved DLF-filter and inversion output from text files. | [
"r",
"Load",
"saved",
"DLF",
"-",
"filter",
"and",
"inversion",
"output",
"from",
"text",
"files",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/scripts/fdesign.py#L526-L566 | train | 24,646 |
empymod/empymod | empymod/scripts/fdesign.py | plot_result | def plot_result(filt, full, prntres=True):
r"""QC the inversion result.
Parameters
----------
- filt, full as returned from fdesign.design with full_output=True
- If prntres is True, it calls fdesign.print_result as well.
r"""
# Check matplotlib (soft dependency)
if not plt:
print(plt_msg)
return
if prntres:
print_result(filt, full)
# Get spacing and shift values from full output of brute
spacing = full[2][0, :, 0]
shift = full[2][1, 0, :]
# Get minimum field values from full output of brute
minfield = np.squeeze(full[3])
plt.figure("Brute force result", figsize=(9.5, 4.5))
plt.subplots_adjust(wspace=.4, bottom=0.2)
# Figure 1: Only if more than 1 spacing or more than 1 shift
# Figure of minfield, depending if spacing/shift are vectors or floats
if spacing.size > 1 or shift.size > 1:
plt.subplot(121)
if full[4] == 0: # Min amp
plt.title("Minimal recovered fields")
ylabel = 'Minimal recovered amplitude (log10)'
field = np.log10(minfield)
cmap = plt.cm.viridis
else: # Max r
plt.title("Maximum recovered r")
ylabel = 'Maximum recovered r'
field = 1/minfield
cmap = plt.cm.viridis_r
if shift.size == 1: # (a) if only one shift value,
plt.plot(spacing, field)
plt.xlabel('Spacing')
plt.ylabel(ylabel)
elif spacing.size == 1: # (b) if only one spacing value
plt.plot(shift, field)
plt.xlabel('Shift')
plt.ylabel(ylabel)
else: # (c) if several spacing and several shift values
field = np.ma.masked_where(np.isinf(minfield), field)
plt.pcolormesh(shift, spacing, field, cmap=cmap)
plt.ylabel('Spacing')
plt.xlabel('Shift')
plt.colorbar()
# Figure 2: Filter values
if spacing.size > 1 or shift.size > 1:
plt.subplot(122)
plt.title('Filter values of best filter')
for attr in ['j0', 'j1', 'sin', 'cos']:
if hasattr(filt, attr):
plt.plot(np.log10(filt.base),
np.log10(np.abs(getattr(filt, attr))), '.-', lw=.5,
label='abs('+attr+')')
plt.plot(np.log10(filt.base), np.log10(-getattr(filt, attr)), '.',
color='k', ms=4)
plt.plot(np.inf, 0, '.', color='k', ms=4, label='Neg. values')
plt.xlabel('Base (log10)')
plt.ylabel('Abs(Amplitude) (log10)')
plt.legend(loc='best')
plt.gcf().canvas.draw() # To force draw in notebook while running
plt.show() | python | def plot_result(filt, full, prntres=True):
r"""QC the inversion result.
Parameters
----------
- filt, full as returned from fdesign.design with full_output=True
- If prntres is True, it calls fdesign.print_result as well.
r"""
# Check matplotlib (soft dependency)
if not plt:
print(plt_msg)
return
if prntres:
print_result(filt, full)
# Get spacing and shift values from full output of brute
spacing = full[2][0, :, 0]
shift = full[2][1, 0, :]
# Get minimum field values from full output of brute
minfield = np.squeeze(full[3])
plt.figure("Brute force result", figsize=(9.5, 4.5))
plt.subplots_adjust(wspace=.4, bottom=0.2)
# Figure 1: Only if more than 1 spacing or more than 1 shift
# Figure of minfield, depending if spacing/shift are vectors or floats
if spacing.size > 1 or shift.size > 1:
plt.subplot(121)
if full[4] == 0: # Min amp
plt.title("Minimal recovered fields")
ylabel = 'Minimal recovered amplitude (log10)'
field = np.log10(minfield)
cmap = plt.cm.viridis
else: # Max r
plt.title("Maximum recovered r")
ylabel = 'Maximum recovered r'
field = 1/minfield
cmap = plt.cm.viridis_r
if shift.size == 1: # (a) if only one shift value,
plt.plot(spacing, field)
plt.xlabel('Spacing')
plt.ylabel(ylabel)
elif spacing.size == 1: # (b) if only one spacing value
plt.plot(shift, field)
plt.xlabel('Shift')
plt.ylabel(ylabel)
else: # (c) if several spacing and several shift values
field = np.ma.masked_where(np.isinf(minfield), field)
plt.pcolormesh(shift, spacing, field, cmap=cmap)
plt.ylabel('Spacing')
plt.xlabel('Shift')
plt.colorbar()
# Figure 2: Filter values
if spacing.size > 1 or shift.size > 1:
plt.subplot(122)
plt.title('Filter values of best filter')
for attr in ['j0', 'j1', 'sin', 'cos']:
if hasattr(filt, attr):
plt.plot(np.log10(filt.base),
np.log10(np.abs(getattr(filt, attr))), '.-', lw=.5,
label='abs('+attr+')')
plt.plot(np.log10(filt.base), np.log10(-getattr(filt, attr)), '.',
color='k', ms=4)
plt.plot(np.inf, 0, '.', color='k', ms=4, label='Neg. values')
plt.xlabel('Base (log10)')
plt.ylabel('Abs(Amplitude) (log10)')
plt.legend(loc='best')
plt.gcf().canvas.draw() # To force draw in notebook while running
plt.show() | [
"def",
"plot_result",
"(",
"filt",
",",
"full",
",",
"prntres",
"=",
"True",
")",
":",
"# Check matplotlib (soft dependency)",
"if",
"not",
"plt",
":",
"print",
"(",
"plt_msg",
")",
"return",
"if",
"prntres",
":",
"print_result",
"(",
"filt",
",",
"full",
... | r"""QC the inversion result.
Parameters
----------
- filt, full as returned from fdesign.design with full_output=True
- If prntres is True, it calls fdesign.print_result as well.
r | [
"r",
"QC",
"the",
"inversion",
"result",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/scripts/fdesign.py#L573-L648 | train | 24,647 |
empymod/empymod | empymod/scripts/fdesign.py | print_result | def print_result(filt, full=None):
r"""Print best filter information.
Parameters
----------
- filt, full as returned from fdesign.design with full_output=True
"""
print(' Filter length : %d' % filt.base.size)
print(' Best filter')
if full: # If full provided, we have more information
if full[4] == 0: # Min amp
print(' > Min field : %g' % full[1])
else: # Max amp
r = 1/full[1]
print(' > Max r : %g' % r)
spacing = full[0][0]
shift = full[0][1]
else: # Print what we can without full
n = filt.base.size
a = filt.base[-1]
b = filt.base[-2]
spacing = np.log(a)-np.log(b)
shift = np.log(a)-spacing*(n//2)
print(' > Spacing : %1.10g' % spacing)
print(' > Shift : %1.10g' % shift)
print(' > Base min/max : %e / %e' % (filt.base.min(), filt.base.max())) | python | def print_result(filt, full=None):
r"""Print best filter information.
Parameters
----------
- filt, full as returned from fdesign.design with full_output=True
"""
print(' Filter length : %d' % filt.base.size)
print(' Best filter')
if full: # If full provided, we have more information
if full[4] == 0: # Min amp
print(' > Min field : %g' % full[1])
else: # Max amp
r = 1/full[1]
print(' > Max r : %g' % r)
spacing = full[0][0]
shift = full[0][1]
else: # Print what we can without full
n = filt.base.size
a = filt.base[-1]
b = filt.base[-2]
spacing = np.log(a)-np.log(b)
shift = np.log(a)-spacing*(n//2)
print(' > Spacing : %1.10g' % spacing)
print(' > Shift : %1.10g' % shift)
print(' > Base min/max : %e / %e' % (filt.base.min(), filt.base.max())) | [
"def",
"print_result",
"(",
"filt",
",",
"full",
"=",
"None",
")",
":",
"print",
"(",
"' Filter length : %d'",
"%",
"filt",
".",
"base",
".",
"size",
")",
"print",
"(",
"' Best filter'",
")",
"if",
"full",
":",
"# If full provided, we have more information... | r"""Print best filter information.
Parameters
----------
- filt, full as returned from fdesign.design with full_output=True | [
"r",
"Print",
"best",
"filter",
"information",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/scripts/fdesign.py#L651-L678 | train | 24,648 |
empymod/empymod | empymod/scripts/fdesign.py | _call_qc_transform_pairs | def _call_qc_transform_pairs(n, ispacing, ishift, fI, fC, r, r_def, reim):
r"""QC the input transform pairs."""
print('* QC: Input transform-pairs:')
print(' fC: x-range defined through ``n``, ``spacing``, ``shift``, and ' +
'``r``-parameters; b-range defined through ``r``-parameter.')
print(' fI: x- and b-range defined through ``n``, ``spacing``' +
', ``shift``, and ``r_def``-parameters.')
# Calculate min/max k, from minimum and maximum spacing/shift
minspace = np.arange(*ispacing).min()
maxspace = np.arange(*ispacing).max()
minshift = np.arange(*ishift).min()
maxshift = np.arange(*ishift).max()
maxbase = np.exp(maxspace*(n//2) + maxshift)
minbase = np.exp(maxspace*(-n//2+1) + minshift)
# For fC-r (k defined with same amount of points as r)
kmax = maxbase/r.min()
kmin = minbase/r.max()
k = np.logspace(np.log10(kmin), np.log10(kmax) + minspace, r.size)
# For fI-r
rI = np.logspace(np.log10(1/maxbase) - r_def[0],
np.log10(1/minbase) + r_def[1], r_def[2]*n)
kmaxI = maxbase/rI.min()
kminI = minbase/rI.max()
kI = np.logspace(np.log10(kminI), np.log10(kmaxI) + minspace,
r_def[2]*n)
# Plot QC
fig, axs = plt.subplots(figsize=(9.5, 6), nrows=2, ncols=2,
num="Transform pairs")
axs = axs.ravel()
plt.subplots_adjust(wspace=.3, hspace=.4)
_plot_transform_pairs(fC, r, k, axs[:2], 'fC')
if reim == np.real:
tit = 'RE(fI)'
else:
tit = 'IM(fI)'
_plot_transform_pairs(fI, rI, kI, axs[2:], tit)
fig.canvas.draw() # To force draw in notebook while running
plt.show() | python | def _call_qc_transform_pairs(n, ispacing, ishift, fI, fC, r, r_def, reim):
r"""QC the input transform pairs."""
print('* QC: Input transform-pairs:')
print(' fC: x-range defined through ``n``, ``spacing``, ``shift``, and ' +
'``r``-parameters; b-range defined through ``r``-parameter.')
print(' fI: x- and b-range defined through ``n``, ``spacing``' +
', ``shift``, and ``r_def``-parameters.')
# Calculate min/max k, from minimum and maximum spacing/shift
minspace = np.arange(*ispacing).min()
maxspace = np.arange(*ispacing).max()
minshift = np.arange(*ishift).min()
maxshift = np.arange(*ishift).max()
maxbase = np.exp(maxspace*(n//2) + maxshift)
minbase = np.exp(maxspace*(-n//2+1) + minshift)
# For fC-r (k defined with same amount of points as r)
kmax = maxbase/r.min()
kmin = minbase/r.max()
k = np.logspace(np.log10(kmin), np.log10(kmax) + minspace, r.size)
# For fI-r
rI = np.logspace(np.log10(1/maxbase) - r_def[0],
np.log10(1/minbase) + r_def[1], r_def[2]*n)
kmaxI = maxbase/rI.min()
kminI = minbase/rI.max()
kI = np.logspace(np.log10(kminI), np.log10(kmaxI) + minspace,
r_def[2]*n)
# Plot QC
fig, axs = plt.subplots(figsize=(9.5, 6), nrows=2, ncols=2,
num="Transform pairs")
axs = axs.ravel()
plt.subplots_adjust(wspace=.3, hspace=.4)
_plot_transform_pairs(fC, r, k, axs[:2], 'fC')
if reim == np.real:
tit = 'RE(fI)'
else:
tit = 'IM(fI)'
_plot_transform_pairs(fI, rI, kI, axs[2:], tit)
fig.canvas.draw() # To force draw in notebook while running
plt.show() | [
"def",
"_call_qc_transform_pairs",
"(",
"n",
",",
"ispacing",
",",
"ishift",
",",
"fI",
",",
"fC",
",",
"r",
",",
"r_def",
",",
"reim",
")",
":",
"print",
"(",
"'* QC: Input transform-pairs:'",
")",
"print",
"(",
"' fC: x-range defined through ``n``, ``spacing``,... | r"""QC the input transform pairs. | [
"r",
"QC",
"the",
"input",
"transform",
"pairs",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/scripts/fdesign.py#L683-L727 | train | 24,649 |
empymod/empymod | empymod/scripts/fdesign.py | _plot_transform_pairs | def _plot_transform_pairs(fCI, r, k, axes, tit):
r"""Plot the input transform pairs."""
# Plot lhs
plt.sca(axes[0])
plt.title('|' + tit + ' lhs|')
for f in fCI:
if f.name == 'j2':
lhs = f.lhs(k)
plt.loglog(k, np.abs(lhs[0]), lw=2, label='j0')
plt.loglog(k, np.abs(lhs[1]), lw=2, label='j1')
else:
plt.loglog(k, np.abs(f.lhs(k)), lw=2, label=f.name)
if tit != 'fC':
plt.xlabel('l')
plt.legend(loc='best')
# Plot rhs
plt.sca(axes[1])
plt.title('|' + tit + ' rhs|')
# Transform pair rhs
for f in fCI:
if tit == 'fC':
plt.loglog(r, np.abs(f.rhs), lw=2, label=f.name)
else:
plt.loglog(r, np.abs(f.rhs(r)), lw=2, label=f.name)
# Transform with Key
for f in fCI:
if f.name[1] in ['0', '1', '2']:
filt = j0j1filt()
else:
filt = sincosfilt()
kk = filt.base/r[:, None]
if f.name == 'j2':
lhs = f.lhs(kk)
kr0 = np.dot(lhs[0], getattr(filt, 'j0'))/r
kr1 = np.dot(lhs[1], getattr(filt, 'j1'))/r**2
kr = kr0+kr1
else:
kr = np.dot(f.lhs(kk), getattr(filt, f.name))/r
plt.loglog(r, np.abs(kr), '-.', lw=2, label=filt.name)
if tit != 'fC':
plt.xlabel('r')
plt.legend(loc='best') | python | def _plot_transform_pairs(fCI, r, k, axes, tit):
r"""Plot the input transform pairs."""
# Plot lhs
plt.sca(axes[0])
plt.title('|' + tit + ' lhs|')
for f in fCI:
if f.name == 'j2':
lhs = f.lhs(k)
plt.loglog(k, np.abs(lhs[0]), lw=2, label='j0')
plt.loglog(k, np.abs(lhs[1]), lw=2, label='j1')
else:
plt.loglog(k, np.abs(f.lhs(k)), lw=2, label=f.name)
if tit != 'fC':
plt.xlabel('l')
plt.legend(loc='best')
# Plot rhs
plt.sca(axes[1])
plt.title('|' + tit + ' rhs|')
# Transform pair rhs
for f in fCI:
if tit == 'fC':
plt.loglog(r, np.abs(f.rhs), lw=2, label=f.name)
else:
plt.loglog(r, np.abs(f.rhs(r)), lw=2, label=f.name)
# Transform with Key
for f in fCI:
if f.name[1] in ['0', '1', '2']:
filt = j0j1filt()
else:
filt = sincosfilt()
kk = filt.base/r[:, None]
if f.name == 'j2':
lhs = f.lhs(kk)
kr0 = np.dot(lhs[0], getattr(filt, 'j0'))/r
kr1 = np.dot(lhs[1], getattr(filt, 'j1'))/r**2
kr = kr0+kr1
else:
kr = np.dot(f.lhs(kk), getattr(filt, f.name))/r
plt.loglog(r, np.abs(kr), '-.', lw=2, label=filt.name)
if tit != 'fC':
plt.xlabel('r')
plt.legend(loc='best') | [
"def",
"_plot_transform_pairs",
"(",
"fCI",
",",
"r",
",",
"k",
",",
"axes",
",",
"tit",
")",
":",
"# Plot lhs",
"plt",
".",
"sca",
"(",
"axes",
"[",
"0",
"]",
")",
"plt",
".",
"title",
"(",
"'|'",
"+",
"tit",
"+",
"' lhs|'",
")",
"for",
"f",
"... | r"""Plot the input transform pairs. | [
"r",
"Plot",
"the",
"input",
"transform",
"pairs",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/scripts/fdesign.py#L730-L778 | train | 24,650 |
empymod/empymod | empymod/scripts/fdesign.py | _plot_inversion | def _plot_inversion(f, rhs, r, k, imin, spacing, shift, cvar):
r"""QC the resulting filter."""
# Check matplotlib (soft dependency)
if not plt:
print(plt_msg)
return
plt.figure("Inversion result "+f.name, figsize=(9.5, 4))
plt.subplots_adjust(wspace=.3, bottom=0.2)
plt.clf()
tk = np.logspace(np.log10(k.min()), np.log10(k.max()), r.size)
plt.suptitle(f.name+'; Spacing ::'+str(spacing)+'; Shift ::'+str(shift))
# Plot lhs
plt.subplot(121)
plt.title('|lhs|')
if f.name == 'j2':
lhs = f.lhs(tk)
plt.loglog(tk, np.abs(lhs[0]), lw=2, label='Theoretical J0')
plt.loglog(tk, np.abs(lhs[1]), lw=2, label='Theoretical J1')
else:
plt.loglog(tk, np.abs(f.lhs(tk)), lw=2, label='Theoretical')
plt.xlabel('l')
plt.legend(loc='best')
# Plot rhs
plt.subplot(122)
plt.title('|rhs|')
# Transform pair rhs
plt.loglog(r, np.abs(f.rhs), lw=2, label='Theoretical')
# Transform with filter
plt.loglog(r, np.abs(rhs), '-.', lw=2, label='This filter')
# Plot minimum amplitude or max r, respectively
if cvar == 'amp':
label = 'Min. Amp'
else:
label = 'Max. r'
plt.loglog(r[imin], np.abs(rhs[imin]), 'go', label=label)
plt.xlabel('r')
plt.legend(loc='best')
plt.gcf().canvas.draw() # To force draw in notebook while running
plt.show() | python | def _plot_inversion(f, rhs, r, k, imin, spacing, shift, cvar):
r"""QC the resulting filter."""
# Check matplotlib (soft dependency)
if not plt:
print(plt_msg)
return
plt.figure("Inversion result "+f.name, figsize=(9.5, 4))
plt.subplots_adjust(wspace=.3, bottom=0.2)
plt.clf()
tk = np.logspace(np.log10(k.min()), np.log10(k.max()), r.size)
plt.suptitle(f.name+'; Spacing ::'+str(spacing)+'; Shift ::'+str(shift))
# Plot lhs
plt.subplot(121)
plt.title('|lhs|')
if f.name == 'j2':
lhs = f.lhs(tk)
plt.loglog(tk, np.abs(lhs[0]), lw=2, label='Theoretical J0')
plt.loglog(tk, np.abs(lhs[1]), lw=2, label='Theoretical J1')
else:
plt.loglog(tk, np.abs(f.lhs(tk)), lw=2, label='Theoretical')
plt.xlabel('l')
plt.legend(loc='best')
# Plot rhs
plt.subplot(122)
plt.title('|rhs|')
# Transform pair rhs
plt.loglog(r, np.abs(f.rhs), lw=2, label='Theoretical')
# Transform with filter
plt.loglog(r, np.abs(rhs), '-.', lw=2, label='This filter')
# Plot minimum amplitude or max r, respectively
if cvar == 'amp':
label = 'Min. Amp'
else:
label = 'Max. r'
plt.loglog(r[imin], np.abs(rhs[imin]), 'go', label=label)
plt.xlabel('r')
plt.legend(loc='best')
plt.gcf().canvas.draw() # To force draw in notebook while running
plt.show() | [
"def",
"_plot_inversion",
"(",
"f",
",",
"rhs",
",",
"r",
",",
"k",
",",
"imin",
",",
"spacing",
",",
"shift",
",",
"cvar",
")",
":",
"# Check matplotlib (soft dependency)",
"if",
"not",
"plt",
":",
"print",
"(",
"plt_msg",
")",
"return",
"plt",
".",
"... | r"""QC the resulting filter. | [
"r",
"QC",
"the",
"resulting",
"filter",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/scripts/fdesign.py#L781-L829 | train | 24,651 |
empymod/empymod | empymod/scripts/fdesign.py | empy_hankel | def empy_hankel(ftype, zsrc, zrec, res, freqtime, depth=None, aniso=None,
epermH=None, epermV=None, mpermH=None, mpermV=None,
htarg=None, verblhs=0, verbrhs=0):
r"""Numerical transform pair with empymod.
All parameters except ``ftype``, ``verblhs``, and ``verbrhs`` correspond to
the input parameters to ``empymod.dipole``. See there for more information.
Note that if depth=None or [], the analytical full-space solutions will be
used (much faster).
Parameters
----------
ftype : str or list of strings
Either of: {'j0', 'j1', 'j2', ['j0', 'j1']}
- 'j0': Analyze J0-term with ab=11, angle=45°
- 'j1': Analyze J1-term with ab=31, angle=0°
- 'j2': Analyze J0- and J1-terms jointly with ab=12, angle=45°
- ['j0', 'j1']: Same as calling empy_hankel twice, once with 'j0' and
one with 'j1'; can be provided like this to
fdesign.design.
verblhs, verbrhs: int
verb-values provided to empymod for lhs and rhs.
Note that ftype='j2' only works for fC, not for fI.
"""
# Loop over ftypes, if there are several
if isinstance(ftype, list):
out = []
for f in ftype:
out.append(empy_hankel(f, zsrc, zrec, res, freqtime, depth, aniso,
epermH, epermV, mpermH, mpermV, htarg,
verblhs, verbrhs))
return out
# Collect model
model = {'src': [0, 0, zsrc],
'depth': depth,
'res': res,
'aniso': aniso,
'epermH': epermH,
'epermV': epermV,
'mpermH': mpermH,
'mpermV': mpermV}
# Finalize model depending on ftype
if ftype == 'j0': # J0: 11, 45°
model['ab'] = 11
x = 1/np.sqrt(2)
y = 1/np.sqrt(2)
elif ftype == 'j1': # J1: 31, 0°
model['ab'] = 31
x = 1
y = 0
elif ftype == 'j2': # J2: 12, 45°
model['ab'] = 12
x = 1/np.sqrt(2)
y = 1/np.sqrt(2)
# rhs: empymod.model.dipole
# If depth=[], the analytical full-space solution will be used internally
def rhs(r):
out = dipole(rec=[r*x, r*y, zrec], ht='qwe', xdirect=True,
verb=verbrhs, htarg=htarg, freqtime=freqtime, **model)
return out
# lhs: empymod.model.dipole_k
def lhs(k):
lhs0, lhs1 = dipole_k(rec=[x, y, zrec], wavenumber=k, verb=verblhs,
freq=freqtime, **model)
if ftype == 'j0':
return lhs0
elif ftype == 'j1':
return lhs1
elif ftype == 'j2':
return (lhs0, lhs1)
return Ghosh(ftype, lhs, rhs) | python | def empy_hankel(ftype, zsrc, zrec, res, freqtime, depth=None, aniso=None,
epermH=None, epermV=None, mpermH=None, mpermV=None,
htarg=None, verblhs=0, verbrhs=0):
r"""Numerical transform pair with empymod.
All parameters except ``ftype``, ``verblhs``, and ``verbrhs`` correspond to
the input parameters to ``empymod.dipole``. See there for more information.
Note that if depth=None or [], the analytical full-space solutions will be
used (much faster).
Parameters
----------
ftype : str or list of strings
Either of: {'j0', 'j1', 'j2', ['j0', 'j1']}
- 'j0': Analyze J0-term with ab=11, angle=45°
- 'j1': Analyze J1-term with ab=31, angle=0°
- 'j2': Analyze J0- and J1-terms jointly with ab=12, angle=45°
- ['j0', 'j1']: Same as calling empy_hankel twice, once with 'j0' and
one with 'j1'; can be provided like this to
fdesign.design.
verblhs, verbrhs: int
verb-values provided to empymod for lhs and rhs.
Note that ftype='j2' only works for fC, not for fI.
"""
# Loop over ftypes, if there are several
if isinstance(ftype, list):
out = []
for f in ftype:
out.append(empy_hankel(f, zsrc, zrec, res, freqtime, depth, aniso,
epermH, epermV, mpermH, mpermV, htarg,
verblhs, verbrhs))
return out
# Collect model
model = {'src': [0, 0, zsrc],
'depth': depth,
'res': res,
'aniso': aniso,
'epermH': epermH,
'epermV': epermV,
'mpermH': mpermH,
'mpermV': mpermV}
# Finalize model depending on ftype
if ftype == 'j0': # J0: 11, 45°
model['ab'] = 11
x = 1/np.sqrt(2)
y = 1/np.sqrt(2)
elif ftype == 'j1': # J1: 31, 0°
model['ab'] = 31
x = 1
y = 0
elif ftype == 'j2': # J2: 12, 45°
model['ab'] = 12
x = 1/np.sqrt(2)
y = 1/np.sqrt(2)
# rhs: empymod.model.dipole
# If depth=[], the analytical full-space solution will be used internally
def rhs(r):
out = dipole(rec=[r*x, r*y, zrec], ht='qwe', xdirect=True,
verb=verbrhs, htarg=htarg, freqtime=freqtime, **model)
return out
# lhs: empymod.model.dipole_k
def lhs(k):
lhs0, lhs1 = dipole_k(rec=[x, y, zrec], wavenumber=k, verb=verblhs,
freq=freqtime, **model)
if ftype == 'j0':
return lhs0
elif ftype == 'j1':
return lhs1
elif ftype == 'j2':
return (lhs0, lhs1)
return Ghosh(ftype, lhs, rhs) | [
"def",
"empy_hankel",
"(",
"ftype",
",",
"zsrc",
",",
"zrec",
",",
"res",
",",
"freqtime",
",",
"depth",
"=",
"None",
",",
"aniso",
"=",
"None",
",",
"epermH",
"=",
"None",
",",
"epermV",
"=",
"None",
",",
"mpermH",
"=",
"None",
",",
"mpermV",
"=",... | r"""Numerical transform pair with empymod.
All parameters except ``ftype``, ``verblhs``, and ``verbrhs`` correspond to
the input parameters to ``empymod.dipole``. See there for more information.
Note that if depth=None or [], the analytical full-space solutions will be
used (much faster).
Parameters
----------
ftype : str or list of strings
Either of: {'j0', 'j1', 'j2', ['j0', 'j1']}
- 'j0': Analyze J0-term with ab=11, angle=45°
- 'j1': Analyze J1-term with ab=31, angle=0°
- 'j2': Analyze J0- and J1-terms jointly with ab=12, angle=45°
- ['j0', 'j1']: Same as calling empy_hankel twice, once with 'j0' and
one with 'j1'; can be provided like this to
fdesign.design.
verblhs, verbrhs: int
verb-values provided to empymod for lhs and rhs.
Note that ftype='j2' only works for fC, not for fI. | [
"r",
"Numerical",
"transform",
"pair",
"with",
"empymod",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/scripts/fdesign.py#L1109-L1192 | train | 24,652 |
empymod/empymod | empymod/scripts/fdesign.py | _get_min_val | def _get_min_val(spaceshift, *params):
r"""Calculate minimum resolved amplitude or maximum r."""
# Get parameters from tuples
spacing, shift = spaceshift
n, fI, fC, r, r_def, error, reim, cvar, verb, plot, log = params
# Get filter for these parameters
dlf = _calculate_filter(n, spacing, shift, fI, r_def, reim, 'filt')
# Calculate rhs-response with this filter
k = dlf.base/r[:, None]
# Loop over transforms
for i, f in enumerate(fC):
# Calculate lhs and rhs; rhs depends on ftype
lhs = f.lhs(k)
if f.name == 'j2':
rhs0 = np.dot(lhs[0], getattr(dlf, 'j0'))/r
rhs1 = np.dot(lhs[1], getattr(dlf, 'j1'))/r**2
rhs = rhs0 + rhs1
else:
rhs = np.dot(lhs, getattr(dlf, f.name))/r
# Get relative error
rel_error = np.abs((rhs - f.rhs)/f.rhs)
# Get indices where relative error is bigger than error
imin0 = np.where(rel_error > error)[0]
# Find first occurrence of failure
if np.all(rhs == 0) or np.all(np.isnan(rhs)):
# if all rhs are zeros or nans, the filter is useless
imin0 = 0
elif imin0.size == 0:
# if imin0.size == 0: # empty array, all rel_error < error.
imin0 = rhs.size-1 # set to last r
if verb > 0 and log['warn-r'] == 0:
print('* WARNING :: all data have error < ' + str(error) +
'; choose larger r or set error-level higher.')
log['warn-r'] = 1 # Only do this once
else:
# Kind of a dirty hack: Permit to jump up to four bad values,
# resulting for instance from high rel_error from zero crossings
# of the transform pair. Should be made an input argument or
# generally improved.
if imin0.size > 4:
imin0 = np.max([0, imin0[4]-5])
else: # just take the first one (no jumping allowed; normal case)
imin0 = np.max([0, imin0[0]-1])
# Note that both version yield the same result if the failure is
# consistent.
# Depending on cvar, store minimum amplitude or 1/maxr
if cvar == 'amp':
min_val0 = np.abs(rhs[imin0])
else:
min_val0 = 1/r[imin0]
# Check if this inversion is better than previous ones
if i == 0: # First run, store these values
imin = dc(imin0)
min_val = dc(min_val0)
else: # Replace imin, min_val if this one is better
if min_val0 > min_val:
min_val = dc(min_val0)
imin = dc(imin0)
# QC plot
if plot > 2:
_plot_inversion(f, rhs, r, k, imin0, spacing, shift, cvar)
# If verbose, print progress
if verb > 1:
log = _print_count(log)
# If there is no point with rel_error < error (imin=0) it returns np.inf.
return np.where(imin == 0, np.inf, min_val) | python | def _get_min_val(spaceshift, *params):
r"""Calculate minimum resolved amplitude or maximum r."""
# Get parameters from tuples
spacing, shift = spaceshift
n, fI, fC, r, r_def, error, reim, cvar, verb, plot, log = params
# Get filter for these parameters
dlf = _calculate_filter(n, spacing, shift, fI, r_def, reim, 'filt')
# Calculate rhs-response with this filter
k = dlf.base/r[:, None]
# Loop over transforms
for i, f in enumerate(fC):
# Calculate lhs and rhs; rhs depends on ftype
lhs = f.lhs(k)
if f.name == 'j2':
rhs0 = np.dot(lhs[0], getattr(dlf, 'j0'))/r
rhs1 = np.dot(lhs[1], getattr(dlf, 'j1'))/r**2
rhs = rhs0 + rhs1
else:
rhs = np.dot(lhs, getattr(dlf, f.name))/r
# Get relative error
rel_error = np.abs((rhs - f.rhs)/f.rhs)
# Get indices where relative error is bigger than error
imin0 = np.where(rel_error > error)[0]
# Find first occurrence of failure
if np.all(rhs == 0) or np.all(np.isnan(rhs)):
# if all rhs are zeros or nans, the filter is useless
imin0 = 0
elif imin0.size == 0:
# if imin0.size == 0: # empty array, all rel_error < error.
imin0 = rhs.size-1 # set to last r
if verb > 0 and log['warn-r'] == 0:
print('* WARNING :: all data have error < ' + str(error) +
'; choose larger r or set error-level higher.')
log['warn-r'] = 1 # Only do this once
else:
# Kind of a dirty hack: Permit to jump up to four bad values,
# resulting for instance from high rel_error from zero crossings
# of the transform pair. Should be made an input argument or
# generally improved.
if imin0.size > 4:
imin0 = np.max([0, imin0[4]-5])
else: # just take the first one (no jumping allowed; normal case)
imin0 = np.max([0, imin0[0]-1])
# Note that both version yield the same result if the failure is
# consistent.
# Depending on cvar, store minimum amplitude or 1/maxr
if cvar == 'amp':
min_val0 = np.abs(rhs[imin0])
else:
min_val0 = 1/r[imin0]
# Check if this inversion is better than previous ones
if i == 0: # First run, store these values
imin = dc(imin0)
min_val = dc(min_val0)
else: # Replace imin, min_val if this one is better
if min_val0 > min_val:
min_val = dc(min_val0)
imin = dc(imin0)
# QC plot
if plot > 2:
_plot_inversion(f, rhs, r, k, imin0, spacing, shift, cvar)
# If verbose, print progress
if verb > 1:
log = _print_count(log)
# If there is no point with rel_error < error (imin=0) it returns np.inf.
return np.where(imin == 0, np.inf, min_val) | [
"def",
"_get_min_val",
"(",
"spaceshift",
",",
"*",
"params",
")",
":",
"# Get parameters from tuples",
"spacing",
",",
"shift",
"=",
"spaceshift",
"n",
",",
"fI",
",",
"fC",
",",
"r",
",",
"r_def",
",",
"error",
",",
"reim",
",",
"cvar",
",",
"verb",
... | r"""Calculate minimum resolved amplitude or maximum r. | [
"r",
"Calculate",
"minimum",
"resolved",
"amplitude",
"or",
"maximum",
"r",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/scripts/fdesign.py#L1197-L1276 | train | 24,653 |
empymod/empymod | empymod/scripts/fdesign.py | _calculate_filter | def _calculate_filter(n, spacing, shift, fI, r_def, reim, name):
r"""Calculate filter for this spacing, shift, n."""
# Base :: For this n/spacing/shift
base = np.exp(spacing*(np.arange(n)-n//2) + shift)
# r :: Start/end is defined by base AND r_def[0]/r_def[1]
# Overdetermined system if r_def[2] > 1
r = np.logspace(np.log10(1/np.max(base)) - r_def[0],
np.log10(1/np.min(base)) + r_def[1], r_def[2]*n)
# k :: Get required k-values (matrix of shape (r.size, base.size))
k = base/r[:, None]
# Create filter instance
dlf = DigitalFilter(name.split('.')[0])
dlf.base = base
dlf.factor = np.around(np.average(base[1:]/base[:-1]), 15)
# Loop over transforms
for f in fI:
# Calculate lhs and rhs for inversion
lhs = reim(f.lhs(k))
rhs = reim(f.rhs(r)*r)
# Calculate filter values: Solve lhs*J=rhs using linalg.qr.
# If factoring fails (qr) or if matrix is singular or square (solve) it
# will raise a LinAlgError. Error is ignored and zeros are returned
# instead.
try:
qq, rr = np.linalg.qr(lhs)
J = np.linalg.solve(rr, rhs.dot(qq))
except np.linalg.LinAlgError:
J = np.zeros((base.size,))
setattr(dlf, f.name, J)
return dlf | python | def _calculate_filter(n, spacing, shift, fI, r_def, reim, name):
r"""Calculate filter for this spacing, shift, n."""
# Base :: For this n/spacing/shift
base = np.exp(spacing*(np.arange(n)-n//2) + shift)
# r :: Start/end is defined by base AND r_def[0]/r_def[1]
# Overdetermined system if r_def[2] > 1
r = np.logspace(np.log10(1/np.max(base)) - r_def[0],
np.log10(1/np.min(base)) + r_def[1], r_def[2]*n)
# k :: Get required k-values (matrix of shape (r.size, base.size))
k = base/r[:, None]
# Create filter instance
dlf = DigitalFilter(name.split('.')[0])
dlf.base = base
dlf.factor = np.around(np.average(base[1:]/base[:-1]), 15)
# Loop over transforms
for f in fI:
# Calculate lhs and rhs for inversion
lhs = reim(f.lhs(k))
rhs = reim(f.rhs(r)*r)
# Calculate filter values: Solve lhs*J=rhs using linalg.qr.
# If factoring fails (qr) or if matrix is singular or square (solve) it
# will raise a LinAlgError. Error is ignored and zeros are returned
# instead.
try:
qq, rr = np.linalg.qr(lhs)
J = np.linalg.solve(rr, rhs.dot(qq))
except np.linalg.LinAlgError:
J = np.zeros((base.size,))
setattr(dlf, f.name, J)
return dlf | [
"def",
"_calculate_filter",
"(",
"n",
",",
"spacing",
",",
"shift",
",",
"fI",
",",
"r_def",
",",
"reim",
",",
"name",
")",
":",
"# Base :: For this n/spacing/shift",
"base",
"=",
"np",
".",
"exp",
"(",
"spacing",
"*",
"(",
"np",
".",
"arange",
"(",
"n... | r"""Calculate filter for this spacing, shift, n. | [
"r",
"Calculate",
"filter",
"for",
"this",
"spacing",
"shift",
"n",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/scripts/fdesign.py#L1279-L1316 | train | 24,654 |
empymod/empymod | empymod/scripts/fdesign.py | _print_count | def _print_count(log):
r"""Print run-count information."""
log['cnt2'] += 1 # Current number
cp = log['cnt2']/log['totnr']*100 # Percentage
if log['cnt2'] == 0: # Not sure about this; brute seems to call the
pass # function with the first arguments twice...
elif log['cnt2'] > log['totnr']: # fmin-status
print(" fmin fct calls : %d" % (log['cnt2']-log['totnr']), end='\r')
elif int(cp) > log['cnt1'] or cp < 1 or log['cnt2'] == log['totnr']:
# Get seconds since start
sec = int(default_timer() - log['time'])
# Get estimate of remaining time, as string
tleft = str(timedelta(seconds=int(100*sec/cp - sec)))
# Print progress
pstr = (" brute fct calls : %d/%d"
% (log['cnt2'], log['totnr']))
if log['totnr'] > 100:
pstr += (" (%d %%); est: %s " % (cp, tleft))
print(pstr, end='\r')
if log['cnt2'] == log['totnr']:
# Empty previous line
print(" "*len(pstr), end='\r')
# Print final brute-message
print(" brute fct calls : %d" % log['totnr'])
# Update percentage cnt1
log['cnt1'] = cp
return log | python | def _print_count(log):
r"""Print run-count information."""
log['cnt2'] += 1 # Current number
cp = log['cnt2']/log['totnr']*100 # Percentage
if log['cnt2'] == 0: # Not sure about this; brute seems to call the
pass # function with the first arguments twice...
elif log['cnt2'] > log['totnr']: # fmin-status
print(" fmin fct calls : %d" % (log['cnt2']-log['totnr']), end='\r')
elif int(cp) > log['cnt1'] or cp < 1 or log['cnt2'] == log['totnr']:
# Get seconds since start
sec = int(default_timer() - log['time'])
# Get estimate of remaining time, as string
tleft = str(timedelta(seconds=int(100*sec/cp - sec)))
# Print progress
pstr = (" brute fct calls : %d/%d"
% (log['cnt2'], log['totnr']))
if log['totnr'] > 100:
pstr += (" (%d %%); est: %s " % (cp, tleft))
print(pstr, end='\r')
if log['cnt2'] == log['totnr']:
# Empty previous line
print(" "*len(pstr), end='\r')
# Print final brute-message
print(" brute fct calls : %d" % log['totnr'])
# Update percentage cnt1
log['cnt1'] = cp
return log | [
"def",
"_print_count",
"(",
"log",
")",
":",
"log",
"[",
"'cnt2'",
"]",
"+=",
"1",
"# Current number",
"cp",
"=",
"log",
"[",
"'cnt2'",
"]",
"/",
"log",
"[",
"'totnr'",
"]",
"*",
"100",
"# Percentage",
"if",
"log",
"[",
"'cnt2'",
"]",
"==",
"0",
":... | r"""Print run-count information. | [
"r",
"Print",
"run",
"-",
"count",
"information",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/scripts/fdesign.py#L1345-L1380 | train | 24,655 |
empymod/empymod | empymod/kernel.py | wavenumber | def wavenumber(zsrc, zrec, lsrc, lrec, depth, etaH, etaV, zetaH, zetaV, lambd,
ab, xdirect, msrc, mrec, use_ne_eval):
r"""Calculate wavenumber domain solution.
Return the wavenumber domain solutions ``PJ0``, ``PJ1``, and ``PJ0b``,
which have to be transformed with a Hankel transform to the frequency
domain. ``PJ0``/``PJ0b`` and ``PJ1`` have to be transformed with Bessel
functions of order 0 (:math:`J_0`) and 1 (:math:`J_1`), respectively.
This function corresponds loosely to equations 105--107, 111--116,
119--121, and 123--128 in [HuTS15]_, and equally loosely to the file
``kxwmod.c``.
[HuTS15]_ uses Bessel functions of orders 0, 1, and 2 (:math:`J_0, J_1,
J_2`). The implementations of the *Fast Hankel Transform* and the
*Quadrature-with-Extrapolation* in ``transform`` are set-up with Bessel
functions of order 0 and 1 only. This is achieved by applying the
recurrence formula
.. math:: J_2(kr) = \frac{2}{kr} J_1(kr) - J_0(kr) \ .
.. note::
``PJ0`` and ``PJ0b`` could theoretically be added here into one, and
then be transformed in one go. However, ``PJ0b`` has to be multiplied
by ``factAng`` later. This has to be done after the Hankel transform
for methods which make use of spline interpolation, in order to work
for offsets that are not in line with each other.
This function is called from one of the Hankel functions in
:mod:`transform`. Consult the modelling routines in :mod:`model` for a
description of the input and output parameters.
If you are solely interested in the wavenumber-domain solution you can call
this function directly. However, you have to make sure all input arguments
are correct, as no checks are carried out here.
"""
# ** CALCULATE GREEN'S FUNCTIONS
# Shape of PTM, PTE: (nfreq, noffs, nfilt)
PTM, PTE = greenfct(zsrc, zrec, lsrc, lrec, depth, etaH, etaV, zetaH,
zetaV, lambd, ab, xdirect, msrc, mrec, use_ne_eval)
# ** AB-SPECIFIC COLLECTION OF PJ0, PJ1, AND PJ0b
# Pre-allocate output
PJ0 = None
PJ1 = None
PJ0b = None
# Calculate Ptot which is used in all cases
Ptot = (PTM + PTE)/(4*np.pi)
# If rec is magnetic switch sign (reciprocity MM/ME => EE/EM).
if mrec:
sign = -1
else:
sign = 1
# Group into PJ0 and PJ1 for J0/J1 Hankel Transform
if ab in [11, 12, 21, 22, 14, 24, 15, 25]: # Eqs 105, 106, 111, 112,
# J2(kr) = 2/(kr)*J1(kr) - J0(kr) # 119, 120, 123, 124
if ab in [14, 22]:
sign *= -1
PJ0b = sign/2*Ptot*lambd
PJ1 = -sign*Ptot
if ab in [11, 22, 24, 15]:
if ab in [22, 24]:
sign *= -1
PJ0 = sign*(PTM - PTE)/(8*np.pi)*lambd
elif ab in [13, 23, 31, 32, 34, 35, 16, 26]: # Eqs 107, 113, 114, 115,
PJ1 = sign*Ptot*lambd*lambd # . 121, 125, 126, 127
if ab in [34, 26]:
PJ1 *= -1
elif ab in [33, ]: # Eq 116
PJ0 = sign*Ptot*lambd*lambd*lambd
# Return PJ0, PJ1, PJ0b
return PJ0, PJ1, PJ0b | python | def wavenumber(zsrc, zrec, lsrc, lrec, depth, etaH, etaV, zetaH, zetaV, lambd,
ab, xdirect, msrc, mrec, use_ne_eval):
r"""Calculate wavenumber domain solution.
Return the wavenumber domain solutions ``PJ0``, ``PJ1``, and ``PJ0b``,
which have to be transformed with a Hankel transform to the frequency
domain. ``PJ0``/``PJ0b`` and ``PJ1`` have to be transformed with Bessel
functions of order 0 (:math:`J_0`) and 1 (:math:`J_1`), respectively.
This function corresponds loosely to equations 105--107, 111--116,
119--121, and 123--128 in [HuTS15]_, and equally loosely to the file
``kxwmod.c``.
[HuTS15]_ uses Bessel functions of orders 0, 1, and 2 (:math:`J_0, J_1,
J_2`). The implementations of the *Fast Hankel Transform* and the
*Quadrature-with-Extrapolation* in ``transform`` are set-up with Bessel
functions of order 0 and 1 only. This is achieved by applying the
recurrence formula
.. math:: J_2(kr) = \frac{2}{kr} J_1(kr) - J_0(kr) \ .
.. note::
``PJ0`` and ``PJ0b`` could theoretically be added here into one, and
then be transformed in one go. However, ``PJ0b`` has to be multiplied
by ``factAng`` later. This has to be done after the Hankel transform
for methods which make use of spline interpolation, in order to work
for offsets that are not in line with each other.
This function is called from one of the Hankel functions in
:mod:`transform`. Consult the modelling routines in :mod:`model` for a
description of the input and output parameters.
If you are solely interested in the wavenumber-domain solution you can call
this function directly. However, you have to make sure all input arguments
are correct, as no checks are carried out here.
"""
# ** CALCULATE GREEN'S FUNCTIONS
# Shape of PTM, PTE: (nfreq, noffs, nfilt)
PTM, PTE = greenfct(zsrc, zrec, lsrc, lrec, depth, etaH, etaV, zetaH,
zetaV, lambd, ab, xdirect, msrc, mrec, use_ne_eval)
# ** AB-SPECIFIC COLLECTION OF PJ0, PJ1, AND PJ0b
# Pre-allocate output
PJ0 = None
PJ1 = None
PJ0b = None
# Calculate Ptot which is used in all cases
Ptot = (PTM + PTE)/(4*np.pi)
# If rec is magnetic switch sign (reciprocity MM/ME => EE/EM).
if mrec:
sign = -1
else:
sign = 1
# Group into PJ0 and PJ1 for J0/J1 Hankel Transform
if ab in [11, 12, 21, 22, 14, 24, 15, 25]: # Eqs 105, 106, 111, 112,
# J2(kr) = 2/(kr)*J1(kr) - J0(kr) # 119, 120, 123, 124
if ab in [14, 22]:
sign *= -1
PJ0b = sign/2*Ptot*lambd
PJ1 = -sign*Ptot
if ab in [11, 22, 24, 15]:
if ab in [22, 24]:
sign *= -1
PJ0 = sign*(PTM - PTE)/(8*np.pi)*lambd
elif ab in [13, 23, 31, 32, 34, 35, 16, 26]: # Eqs 107, 113, 114, 115,
PJ1 = sign*Ptot*lambd*lambd # . 121, 125, 126, 127
if ab in [34, 26]:
PJ1 *= -1
elif ab in [33, ]: # Eq 116
PJ0 = sign*Ptot*lambd*lambd*lambd
# Return PJ0, PJ1, PJ0b
return PJ0, PJ1, PJ0b | [
"def",
"wavenumber",
"(",
"zsrc",
",",
"zrec",
",",
"lsrc",
",",
"lrec",
",",
"depth",
",",
"etaH",
",",
"etaV",
",",
"zetaH",
",",
"zetaV",
",",
"lambd",
",",
"ab",
",",
"xdirect",
",",
"msrc",
",",
"mrec",
",",
"use_ne_eval",
")",
":",
"# ** CALC... | r"""Calculate wavenumber domain solution.
Return the wavenumber domain solutions ``PJ0``, ``PJ1``, and ``PJ0b``,
which have to be transformed with a Hankel transform to the frequency
domain. ``PJ0``/``PJ0b`` and ``PJ1`` have to be transformed with Bessel
functions of order 0 (:math:`J_0`) and 1 (:math:`J_1`), respectively.
This function corresponds loosely to equations 105--107, 111--116,
119--121, and 123--128 in [HuTS15]_, and equally loosely to the file
``kxwmod.c``.
[HuTS15]_ uses Bessel functions of orders 0, 1, and 2 (:math:`J_0, J_1,
J_2`). The implementations of the *Fast Hankel Transform* and the
*Quadrature-with-Extrapolation* in ``transform`` are set-up with Bessel
functions of order 0 and 1 only. This is achieved by applying the
recurrence formula
.. math:: J_2(kr) = \frac{2}{kr} J_1(kr) - J_0(kr) \ .
.. note::
``PJ0`` and ``PJ0b`` could theoretically be added here into one, and
then be transformed in one go. However, ``PJ0b`` has to be multiplied
by ``factAng`` later. This has to be done after the Hankel transform
for methods which make use of spline interpolation, in order to work
for offsets that are not in line with each other.
This function is called from one of the Hankel functions in
:mod:`transform`. Consult the modelling routines in :mod:`model` for a
description of the input and output parameters.
If you are solely interested in the wavenumber-domain solution you can call
this function directly. However, you have to make sure all input arguments
are correct, as no checks are carried out here. | [
"r",
"Calculate",
"wavenumber",
"domain",
"solution",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/kernel.py#L47-L129 | train | 24,656 |
empymod/empymod | empymod/kernel.py | reflections | def reflections(depth, e_zH, Gam, lrec, lsrc, use_ne_eval):
r"""Calculate Rp, Rm.
.. math:: R^\pm_n, \bar{R}^\pm_n
This function corresponds to equations 64/65 and A-11/A-12 in
[HuTS15]_, and loosely to the corresponding files ``Rmin.F90`` and
``Rplus.F90``.
This function is called from the function :mod:`kernel.greenfct`.
"""
# Loop over Rp, Rm
for plus in [True, False]:
# Switches depending if plus or minus
if plus:
pm = 1
layer_count = np.arange(depth.size-2, min(lrec, lsrc)-1, -1)
izout = abs(lsrc-lrec)
minmax = max(lrec, lsrc)
else:
pm = -1
layer_count = np.arange(1, max(lrec, lsrc)+1, 1)
izout = 0
minmax = -min(lrec, lsrc)
# If rec in last and rec below src (plus) or
# if rec in first and rec above src (minus), shift izout
shiftplus = lrec < lsrc and lrec == 0 and not plus
shiftminus = lrec > lsrc and lrec == depth.size-1 and plus
if shiftplus or shiftminus:
izout -= pm
# Pre-allocate Ref
Ref = np.zeros((Gam.shape[0], Gam.shape[1], abs(lsrc-lrec)+1,
Gam.shape[3]), dtype=complex)
# Calculate the reflection
for iz in layer_count:
# Eqs 65, A-12
e_zHa = e_zH[:, None, iz+pm, None]
Gama = Gam[:, :, iz, :]
e_zHb = e_zH[:, None, iz, None]
Gamb = Gam[:, :, iz+pm, :]
if use_ne_eval:
rlocstr = "(e_zHa*Gama - e_zHb*Gamb)/(e_zHa*Gama + e_zHb*Gamb)"
rloc = use_ne_eval(rlocstr)
else:
rloca = e_zHa*Gama
rlocb = e_zHb*Gamb
rloc = (rloca - rlocb)/(rloca + rlocb)
# In first layer tRef = rloc
if iz == layer_count[0]:
tRef = rloc.copy()
else:
ddepth = depth[iz+1+pm]-depth[iz+pm]
# Eqs 64, A-11
if use_ne_eval:
term = use_ne_eval("tRef*exp(-2*Gamb*ddepth)")
tRef = use_ne_eval("(rloc + term)/(1 + rloc*term)")
else:
term = tRef*np.exp(-2*Gamb*ddepth) # NOQA
tRef = (rloc + term)/(1 + rloc*term)
# The global reflection coefficient is given back for all layers
# between and including src- and rec-layer
if lrec != lsrc and pm*iz <= minmax:
Ref[:, :, izout, :] = tRef[:]
izout -= pm
# If lsrc = lrec, we just store the last values
if lsrc == lrec and layer_count.size > 0:
Ref = tRef
# Store Ref in Rm/Rp
if plus:
Rm = Ref
else:
Rp = Ref
# Return reflections (minus and plus)
return Rm, Rp | python | def reflections(depth, e_zH, Gam, lrec, lsrc, use_ne_eval):
r"""Calculate Rp, Rm.
.. math:: R^\pm_n, \bar{R}^\pm_n
This function corresponds to equations 64/65 and A-11/A-12 in
[HuTS15]_, and loosely to the corresponding files ``Rmin.F90`` and
``Rplus.F90``.
This function is called from the function :mod:`kernel.greenfct`.
"""
# Loop over Rp, Rm
for plus in [True, False]:
# Switches depending if plus or minus
if plus:
pm = 1
layer_count = np.arange(depth.size-2, min(lrec, lsrc)-1, -1)
izout = abs(lsrc-lrec)
minmax = max(lrec, lsrc)
else:
pm = -1
layer_count = np.arange(1, max(lrec, lsrc)+1, 1)
izout = 0
minmax = -min(lrec, lsrc)
# If rec in last and rec below src (plus) or
# if rec in first and rec above src (minus), shift izout
shiftplus = lrec < lsrc and lrec == 0 and not plus
shiftminus = lrec > lsrc and lrec == depth.size-1 and plus
if shiftplus or shiftminus:
izout -= pm
# Pre-allocate Ref
Ref = np.zeros((Gam.shape[0], Gam.shape[1], abs(lsrc-lrec)+1,
Gam.shape[3]), dtype=complex)
# Calculate the reflection
for iz in layer_count:
# Eqs 65, A-12
e_zHa = e_zH[:, None, iz+pm, None]
Gama = Gam[:, :, iz, :]
e_zHb = e_zH[:, None, iz, None]
Gamb = Gam[:, :, iz+pm, :]
if use_ne_eval:
rlocstr = "(e_zHa*Gama - e_zHb*Gamb)/(e_zHa*Gama + e_zHb*Gamb)"
rloc = use_ne_eval(rlocstr)
else:
rloca = e_zHa*Gama
rlocb = e_zHb*Gamb
rloc = (rloca - rlocb)/(rloca + rlocb)
# In first layer tRef = rloc
if iz == layer_count[0]:
tRef = rloc.copy()
else:
ddepth = depth[iz+1+pm]-depth[iz+pm]
# Eqs 64, A-11
if use_ne_eval:
term = use_ne_eval("tRef*exp(-2*Gamb*ddepth)")
tRef = use_ne_eval("(rloc + term)/(1 + rloc*term)")
else:
term = tRef*np.exp(-2*Gamb*ddepth) # NOQA
tRef = (rloc + term)/(1 + rloc*term)
# The global reflection coefficient is given back for all layers
# between and including src- and rec-layer
if lrec != lsrc and pm*iz <= minmax:
Ref[:, :, izout, :] = tRef[:]
izout -= pm
# If lsrc = lrec, we just store the last values
if lsrc == lrec and layer_count.size > 0:
Ref = tRef
# Store Ref in Rm/Rp
if plus:
Rm = Ref
else:
Rp = Ref
# Return reflections (minus and plus)
return Rm, Rp | [
"def",
"reflections",
"(",
"depth",
",",
"e_zH",
",",
"Gam",
",",
"lrec",
",",
"lsrc",
",",
"use_ne_eval",
")",
":",
"# Loop over Rp, Rm",
"for",
"plus",
"in",
"[",
"True",
",",
"False",
"]",
":",
"# Switches depending if plus or minus",
"if",
"plus",
":",
... | r"""Calculate Rp, Rm.
.. math:: R^\pm_n, \bar{R}^\pm_n
This function corresponds to equations 64/65 and A-11/A-12 in
[HuTS15]_, and loosely to the corresponding files ``Rmin.F90`` and
``Rplus.F90``.
This function is called from the function :mod:`kernel.greenfct`. | [
"r",
"Calculate",
"Rp",
"Rm",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/kernel.py#L316-L402 | train | 24,657 |
empymod/empymod | empymod/kernel.py | angle_factor | def angle_factor(angle, ab, msrc, mrec):
r"""Return the angle-dependent factor.
The whole calculation in the wavenumber domain is only a function of the
distance between the source and the receiver, it is independent of the
angel. The angle-dependency is this factor, which can be applied to the
corresponding parts in the wavenumber or in the frequency domain.
The ``angle_factor`` corresponds to the sine and cosine-functions in Eqs
105-107, 111-116, 119-121, 123-128.
This function is called from one of the Hankel functions in
:mod:`transform`. Consult the modelling routines in :mod:`model` for a
description of the input and output parameters.
"""
# 33/66 are completely symmetric and hence independent of angle
if ab in [33, ]:
return np.ones(angle.size)
# Evaluation angle
eval_angle = angle.copy()
# Add pi if receiver is magnetic (reciprocity), but not if source is
# electric, because then source and receiver are swapped, ME => EM:
# G^me_ab(s, r, e, z) = -G^em_ba(r, s, e, z).
if mrec and not msrc:
eval_angle += np.pi
# Define fct (cos/sin) and angles to be tested
if ab in [11, 22, 15, 24, 13, 31, 26, 35]:
fct = np.cos
test_ang_1 = np.pi/2
test_ang_2 = 3*np.pi/2
else:
fct = np.sin
test_ang_1 = np.pi
test_ang_2 = 2*np.pi
if ab in [11, 22, 15, 24, 12, 21, 14, 25]:
eval_angle *= 2
# Get factor
factAng = fct(eval_angle)
# Ensure cos([pi/2, 3pi/2]) and sin([pi, 2pi]) are zero (floating pt issue)
factAng[np.isclose(np.abs(eval_angle), test_ang_1, 1e-10, 1e-14)] = 0
factAng[np.isclose(np.abs(eval_angle), test_ang_2, 1e-10, 1e-14)] = 0
return factAng | python | def angle_factor(angle, ab, msrc, mrec):
r"""Return the angle-dependent factor.
The whole calculation in the wavenumber domain is only a function of the
distance between the source and the receiver, it is independent of the
angel. The angle-dependency is this factor, which can be applied to the
corresponding parts in the wavenumber or in the frequency domain.
The ``angle_factor`` corresponds to the sine and cosine-functions in Eqs
105-107, 111-116, 119-121, 123-128.
This function is called from one of the Hankel functions in
:mod:`transform`. Consult the modelling routines in :mod:`model` for a
description of the input and output parameters.
"""
# 33/66 are completely symmetric and hence independent of angle
if ab in [33, ]:
return np.ones(angle.size)
# Evaluation angle
eval_angle = angle.copy()
# Add pi if receiver is magnetic (reciprocity), but not if source is
# electric, because then source and receiver are swapped, ME => EM:
# G^me_ab(s, r, e, z) = -G^em_ba(r, s, e, z).
if mrec and not msrc:
eval_angle += np.pi
# Define fct (cos/sin) and angles to be tested
if ab in [11, 22, 15, 24, 13, 31, 26, 35]:
fct = np.cos
test_ang_1 = np.pi/2
test_ang_2 = 3*np.pi/2
else:
fct = np.sin
test_ang_1 = np.pi
test_ang_2 = 2*np.pi
if ab in [11, 22, 15, 24, 12, 21, 14, 25]:
eval_angle *= 2
# Get factor
factAng = fct(eval_angle)
# Ensure cos([pi/2, 3pi/2]) and sin([pi, 2pi]) are zero (floating pt issue)
factAng[np.isclose(np.abs(eval_angle), test_ang_1, 1e-10, 1e-14)] = 0
factAng[np.isclose(np.abs(eval_angle), test_ang_2, 1e-10, 1e-14)] = 0
return factAng | [
"def",
"angle_factor",
"(",
"angle",
",",
"ab",
",",
"msrc",
",",
"mrec",
")",
":",
"# 33/66 are completely symmetric and hence independent of angle",
"if",
"ab",
"in",
"[",
"33",
",",
"]",
":",
"return",
"np",
".",
"ones",
"(",
"angle",
".",
"size",
")",
... | r"""Return the angle-dependent factor.
The whole calculation in the wavenumber domain is only a function of the
distance between the source and the receiver, it is independent of the
angel. The angle-dependency is this factor, which can be applied to the
corresponding parts in the wavenumber or in the frequency domain.
The ``angle_factor`` corresponds to the sine and cosine-functions in Eqs
105-107, 111-116, 119-121, 123-128.
This function is called from one of the Hankel functions in
:mod:`transform`. Consult the modelling routines in :mod:`model` for a
description of the input and output parameters. | [
"r",
"Return",
"the",
"angle",
"-",
"dependent",
"factor",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/kernel.py#L570-L620 | train | 24,658 |
empymod/empymod | empymod/scripts/printinfo.py | versions | def versions(mode=None, add_pckg=None, ncol=4):
r"""Old func-way of class `Versions`, here for backwards compatibility.
``mode`` is not used any longer, dummy here.
"""
# Issue warning
mesg = ("\n Func `versions` is deprecated and will " +
"be removed; use Class `Versions` instead.")
warnings.warn(mesg, DeprecationWarning)
return Versions(add_pckg, ncol) | python | def versions(mode=None, add_pckg=None, ncol=4):
r"""Old func-way of class `Versions`, here for backwards compatibility.
``mode`` is not used any longer, dummy here.
"""
# Issue warning
mesg = ("\n Func `versions` is deprecated and will " +
"be removed; use Class `Versions` instead.")
warnings.warn(mesg, DeprecationWarning)
return Versions(add_pckg, ncol) | [
"def",
"versions",
"(",
"mode",
"=",
"None",
",",
"add_pckg",
"=",
"None",
",",
"ncol",
"=",
"4",
")",
":",
"# Issue warning",
"mesg",
"=",
"(",
"\"\\n Func `versions` is deprecated and will \"",
"+",
"\"be removed; use Class `Versions` instead.\"",
")",
"warnings"... | r"""Old func-way of class `Versions`, here for backwards compatibility.
``mode`` is not used any longer, dummy here. | [
"r",
"Old",
"func",
"-",
"way",
"of",
"class",
"Versions",
"here",
"for",
"backwards",
"compatibility",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/scripts/printinfo.py#L254-L264 | train | 24,659 |
empymod/empymod | empymod/scripts/printinfo.py | Versions._repr_html_ | def _repr_html_(self):
"""HTML-rendered versions information."""
# Check ncol
ncol = int(self.ncol)
# Define html-styles
border = "border: 2px solid #fff;'"
def colspan(html, txt, ncol, nrow):
r"""Print txt in a row spanning whole table."""
html += " <tr>\n"
html += " <td style='text-align: center; "
if nrow == 0:
html += "font-weight: bold; font-size: 1.2em; "
elif nrow % 2 == 0:
html += "background-color: #ddd;"
html += border + " colspan='"
html += str(2*ncol)+"'>%s</td>\n" % txt
html += " </tr>\n"
return html
def cols(html, version, name, ncol, i):
r"""Print package information in two cells."""
# Check if we have to start a new row
if i > 0 and i % ncol == 0:
html += " </tr>\n"
html += " <tr>\n"
html += " <td style='text-align: right; background-color: "
html += "#ccc; " + border + ">%s</td>\n" % version
html += " <td style='text-align: left; "
html += border + ">%s</td>\n" % name
return html, i+1
# Start html-table
html = "<table style='border: 3px solid #ddd;'>\n"
# Date and time info as title
html = colspan(html, time.strftime('%a %b %d %H:%M:%S %Y %Z'), ncol, 0)
# OS and CPUs
html += " <tr>\n"
html, i = cols(html, platform.system(), 'OS', ncol, 0)
html, i = cols(html, multiprocessing.cpu_count(), 'CPU(s)', ncol, i)
# Loop over packages
for pckg in self._get_packages(self.add_pckg):
html, i = cols(html, pckg.__version__, pckg.__name__, ncol, i)
# Fill up the row
while i % ncol != 0:
html += " <td style= " + border + "></td>\n"
html += " <td style= " + border + "></td>\n"
i += 1
# Finish row
html += " </tr>\n"
# sys.version
html = colspan(html, sys.version, ncol, 1)
# mkl version
if mklinfo:
html = colspan(html, mklinfo, ncol, 2)
# Finish table
html += "</table>"
return html | python | def _repr_html_(self):
"""HTML-rendered versions information."""
# Check ncol
ncol = int(self.ncol)
# Define html-styles
border = "border: 2px solid #fff;'"
def colspan(html, txt, ncol, nrow):
r"""Print txt in a row spanning whole table."""
html += " <tr>\n"
html += " <td style='text-align: center; "
if nrow == 0:
html += "font-weight: bold; font-size: 1.2em; "
elif nrow % 2 == 0:
html += "background-color: #ddd;"
html += border + " colspan='"
html += str(2*ncol)+"'>%s</td>\n" % txt
html += " </tr>\n"
return html
def cols(html, version, name, ncol, i):
r"""Print package information in two cells."""
# Check if we have to start a new row
if i > 0 and i % ncol == 0:
html += " </tr>\n"
html += " <tr>\n"
html += " <td style='text-align: right; background-color: "
html += "#ccc; " + border + ">%s</td>\n" % version
html += " <td style='text-align: left; "
html += border + ">%s</td>\n" % name
return html, i+1
# Start html-table
html = "<table style='border: 3px solid #ddd;'>\n"
# Date and time info as title
html = colspan(html, time.strftime('%a %b %d %H:%M:%S %Y %Z'), ncol, 0)
# OS and CPUs
html += " <tr>\n"
html, i = cols(html, platform.system(), 'OS', ncol, 0)
html, i = cols(html, multiprocessing.cpu_count(), 'CPU(s)', ncol, i)
# Loop over packages
for pckg in self._get_packages(self.add_pckg):
html, i = cols(html, pckg.__version__, pckg.__name__, ncol, i)
# Fill up the row
while i % ncol != 0:
html += " <td style= " + border + "></td>\n"
html += " <td style= " + border + "></td>\n"
i += 1
# Finish row
html += " </tr>\n"
# sys.version
html = colspan(html, sys.version, ncol, 1)
# mkl version
if mklinfo:
html = colspan(html, mklinfo, ncol, 2)
# Finish table
html += "</table>"
return html | [
"def",
"_repr_html_",
"(",
"self",
")",
":",
"# Check ncol",
"ncol",
"=",
"int",
"(",
"self",
".",
"ncol",
")",
"# Define html-styles",
"border",
"=",
"\"border: 2px solid #fff;'\"",
"def",
"colspan",
"(",
"html",
",",
"txt",
",",
"ncol",
",",
"nrow",
")",
... | HTML-rendered versions information. | [
"HTML",
"-",
"rendered",
"versions",
"information",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/scripts/printinfo.py#L155-L224 | train | 24,660 |
empymod/empymod | empymod/scripts/printinfo.py | Versions._get_packages | def _get_packages(add_pckg):
r"""Create list of packages."""
# Mandatory packages
pckgs = [numpy, scipy, empymod]
# Optional packages
for module in [IPython, numexpr, matplotlib]:
if module:
pckgs += [module]
# Cast and add add_pckg
if add_pckg is not None:
# Cast add_pckg
if isinstance(add_pckg, tuple):
add_pckg = list(add_pckg)
if not isinstance(add_pckg, list):
add_pckg = [add_pckg, ]
# Add add_pckg
pckgs += add_pckg
return pckgs | python | def _get_packages(add_pckg):
r"""Create list of packages."""
# Mandatory packages
pckgs = [numpy, scipy, empymod]
# Optional packages
for module in [IPython, numexpr, matplotlib]:
if module:
pckgs += [module]
# Cast and add add_pckg
if add_pckg is not None:
# Cast add_pckg
if isinstance(add_pckg, tuple):
add_pckg = list(add_pckg)
if not isinstance(add_pckg, list):
add_pckg = [add_pckg, ]
# Add add_pckg
pckgs += add_pckg
return pckgs | [
"def",
"_get_packages",
"(",
"add_pckg",
")",
":",
"# Mandatory packages",
"pckgs",
"=",
"[",
"numpy",
",",
"scipy",
",",
"empymod",
"]",
"# Optional packages",
"for",
"module",
"in",
"[",
"IPython",
",",
"numexpr",
",",
"matplotlib",
"]",
":",
"if",
"module... | r"""Create list of packages. | [
"r",
"Create",
"list",
"of",
"packages",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/scripts/printinfo.py#L227-L251 | train | 24,661 |
empymod/empymod | empymod/filters.py | DigitalFilter.tofile | def tofile(self, path='filters'):
r"""Save filter values to ascii-files.
Store the filter base and the filter coefficients in separate files
in the directory `path`; `path` can be a relative or absolute path.
Examples
--------
>>> import empymod
>>> # Load a filter
>>> filt = empymod.filters.wer_201_2018()
>>> # Save it to pure ascii-files
>>> filt.tofile()
>>> # This will save the following three files:
>>> # ./filters/wer_201_2018_base.txt
>>> # ./filters/wer_201_2018_j0.txt
>>> # ./filters/wer_201_2018_j1.txt
"""
# Get name of filter
name = self.savename
# Get absolute path, create if it doesn't exist
path = os.path.abspath(path)
os.makedirs(path, exist_ok=True)
# Save filter base
basefile = os.path.join(path, name + '_base.txt')
with open(basefile, 'w') as f:
self.base.tofile(f, sep="\n")
# Save filter coefficients
for val in ['j0', 'j1', 'sin', 'cos']:
if hasattr(self, val):
attrfile = os.path.join(path, name + '_' + val + '.txt')
with open(attrfile, 'w') as f:
getattr(self, val).tofile(f, sep="\n") | python | def tofile(self, path='filters'):
r"""Save filter values to ascii-files.
Store the filter base and the filter coefficients in separate files
in the directory `path`; `path` can be a relative or absolute path.
Examples
--------
>>> import empymod
>>> # Load a filter
>>> filt = empymod.filters.wer_201_2018()
>>> # Save it to pure ascii-files
>>> filt.tofile()
>>> # This will save the following three files:
>>> # ./filters/wer_201_2018_base.txt
>>> # ./filters/wer_201_2018_j0.txt
>>> # ./filters/wer_201_2018_j1.txt
"""
# Get name of filter
name = self.savename
# Get absolute path, create if it doesn't exist
path = os.path.abspath(path)
os.makedirs(path, exist_ok=True)
# Save filter base
basefile = os.path.join(path, name + '_base.txt')
with open(basefile, 'w') as f:
self.base.tofile(f, sep="\n")
# Save filter coefficients
for val in ['j0', 'j1', 'sin', 'cos']:
if hasattr(self, val):
attrfile = os.path.join(path, name + '_' + val + '.txt')
with open(attrfile, 'w') as f:
getattr(self, val).tofile(f, sep="\n") | [
"def",
"tofile",
"(",
"self",
",",
"path",
"=",
"'filters'",
")",
":",
"# Get name of filter",
"name",
"=",
"self",
".",
"savename",
"# Get absolute path, create if it doesn't exist",
"path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
"os",
".",... | r"""Save filter values to ascii-files.
Store the filter base and the filter coefficients in separate files
in the directory `path`; `path` can be a relative or absolute path.
Examples
--------
>>> import empymod
>>> # Load a filter
>>> filt = empymod.filters.wer_201_2018()
>>> # Save it to pure ascii-files
>>> filt.tofile()
>>> # This will save the following three files:
>>> # ./filters/wer_201_2018_base.txt
>>> # ./filters/wer_201_2018_j0.txt
>>> # ./filters/wer_201_2018_j1.txt | [
"r",
"Save",
"filter",
"values",
"to",
"ascii",
"-",
"files",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/filters.py#L77-L114 | train | 24,662 |
empymod/empymod | empymod/filters.py | DigitalFilter.fromfile | def fromfile(self, path='filters'):
r"""Load filter values from ascii-files.
Load filter base and filter coefficients from ascii files in the
directory `path`; `path` can be a relative or absolute path.
Examples
--------
>>> import empymod
>>> # Create an empty filter;
>>> # Name has to be the base of the text files
>>> filt = empymod.filters.DigitalFilter('my-filter')
>>> # Load the ascii-files
>>> filt.fromfile()
>>> # This will load the following three files:
>>> # ./filters/my-filter_base.txt
>>> # ./filters/my-filter_j0.txt
>>> # ./filters/my-filter_j1.txt
>>> # and store them in filt.base, filt.j0, and filt.j1.
"""
# Get name of filter
name = self.savename
# Get absolute path
path = os.path.abspath(path)
# Get filter base
basefile = os.path.join(path, name + '_base.txt')
with open(basefile, 'r') as f:
self.base = np.fromfile(f, sep="\n")
# Get filter coefficients
for val in ['j0', 'j1', 'sin', 'cos']:
attrfile = os.path.join(path, name + '_' + val + '.txt')
if os.path.isfile(attrfile):
with open(attrfile, 'r') as f:
setattr(self, val, np.fromfile(f, sep="\n"))
# Add factor
self.factor = np.around(np.average(self.base[1:]/self.base[:-1]), 15) | python | def fromfile(self, path='filters'):
r"""Load filter values from ascii-files.
Load filter base and filter coefficients from ascii files in the
directory `path`; `path` can be a relative or absolute path.
Examples
--------
>>> import empymod
>>> # Create an empty filter;
>>> # Name has to be the base of the text files
>>> filt = empymod.filters.DigitalFilter('my-filter')
>>> # Load the ascii-files
>>> filt.fromfile()
>>> # This will load the following three files:
>>> # ./filters/my-filter_base.txt
>>> # ./filters/my-filter_j0.txt
>>> # ./filters/my-filter_j1.txt
>>> # and store them in filt.base, filt.j0, and filt.j1.
"""
# Get name of filter
name = self.savename
# Get absolute path
path = os.path.abspath(path)
# Get filter base
basefile = os.path.join(path, name + '_base.txt')
with open(basefile, 'r') as f:
self.base = np.fromfile(f, sep="\n")
# Get filter coefficients
for val in ['j0', 'j1', 'sin', 'cos']:
attrfile = os.path.join(path, name + '_' + val + '.txt')
if os.path.isfile(attrfile):
with open(attrfile, 'r') as f:
setattr(self, val, np.fromfile(f, sep="\n"))
# Add factor
self.factor = np.around(np.average(self.base[1:]/self.base[:-1]), 15) | [
"def",
"fromfile",
"(",
"self",
",",
"path",
"=",
"'filters'",
")",
":",
"# Get name of filter",
"name",
"=",
"self",
".",
"savename",
"# Get absolute path",
"path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
"# Get filter base",
"basefile",
"... | r"""Load filter values from ascii-files.
Load filter base and filter coefficients from ascii files in the
directory `path`; `path` can be a relative or absolute path.
Examples
--------
>>> import empymod
>>> # Create an empty filter;
>>> # Name has to be the base of the text files
>>> filt = empymod.filters.DigitalFilter('my-filter')
>>> # Load the ascii-files
>>> filt.fromfile()
>>> # This will load the following three files:
>>> # ./filters/my-filter_base.txt
>>> # ./filters/my-filter_j0.txt
>>> # ./filters/my-filter_j1.txt
>>> # and store them in filt.base, filt.j0, and filt.j1. | [
"r",
"Load",
"filter",
"values",
"from",
"ascii",
"-",
"files",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/filters.py#L116-L157 | train | 24,663 |
empymod/empymod | empymod/transform.py | fht | def fht(zsrc, zrec, lsrc, lrec, off, factAng, depth, ab, etaH, etaV, zetaH,
zetaV, xdirect, fhtarg, use_ne_eval, msrc, mrec):
r"""Hankel Transform using the Digital Linear Filter method.
The *Digital Linear Filter* method was introduced to geophysics by
[Ghos70]_, and made popular and wide-spread by [Ande75]_, [Ande79]_,
[Ande82]_. The DLF is sometimes referred to as the *Fast Hankel Transform*
FHT, from which this routine has its name.
This implementation of the DLF follows [Key12]_, equation 6. Without going
into the mathematical details (which can be found in any of the above
papers) and following [Key12]_, the DLF method rewrites the Hankel
transform of the form
.. math:: F(r) = \int^\infty_0 f(\lambda)J_v(\lambda r)\
\mathrm{d}\lambda
as
.. math:: F(r) = \sum^n_{i=1} f(b_i/r)h_i/r \ ,
where :math:`h` is the digital filter.The Filter abscissae b is given by
.. math:: b_i = \lambda_ir = e^{ai}, \qquad i = -l, -l+1, \cdots, l \ ,
with :math:`l=(n-1)/2`, and :math:`a` is the spacing coefficient.
This function is loosely based on ``get_CSEM1D_FD_FHT.m`` from the source
code distributed with [Key12]_.
The function is called from one of the modelling routines in :mod:`model`.
Consult these modelling routines for a description of the input and output
parameters.
Returns
-------
fEM : array
Returns frequency-domain EM response.
kcount : int
Kernel count. For DLF, this is 1.
conv : bool
Only relevant for QWE/QUAD.
"""
# 1. Get fhtargs
fhtfilt = fhtarg[0]
pts_per_dec = fhtarg[1]
lambd = fhtarg[2]
int_pts = fhtarg[3]
# 2. Call the kernel
PJ = kernel.wavenumber(zsrc, zrec, lsrc, lrec, depth, etaH, etaV, zetaH,
zetaV, lambd, ab, xdirect, msrc, mrec, use_ne_eval)
# 3. Carry out the dlf
fEM = dlf(PJ, lambd, off, fhtfilt, pts_per_dec, factAng=factAng, ab=ab,
int_pts=int_pts)
return fEM, 1, True | python | def fht(zsrc, zrec, lsrc, lrec, off, factAng, depth, ab, etaH, etaV, zetaH,
zetaV, xdirect, fhtarg, use_ne_eval, msrc, mrec):
r"""Hankel Transform using the Digital Linear Filter method.
The *Digital Linear Filter* method was introduced to geophysics by
[Ghos70]_, and made popular and wide-spread by [Ande75]_, [Ande79]_,
[Ande82]_. The DLF is sometimes referred to as the *Fast Hankel Transform*
FHT, from which this routine has its name.
This implementation of the DLF follows [Key12]_, equation 6. Without going
into the mathematical details (which can be found in any of the above
papers) and following [Key12]_, the DLF method rewrites the Hankel
transform of the form
.. math:: F(r) = \int^\infty_0 f(\lambda)J_v(\lambda r)\
\mathrm{d}\lambda
as
.. math:: F(r) = \sum^n_{i=1} f(b_i/r)h_i/r \ ,
where :math:`h` is the digital filter.The Filter abscissae b is given by
.. math:: b_i = \lambda_ir = e^{ai}, \qquad i = -l, -l+1, \cdots, l \ ,
with :math:`l=(n-1)/2`, and :math:`a` is the spacing coefficient.
This function is loosely based on ``get_CSEM1D_FD_FHT.m`` from the source
code distributed with [Key12]_.
The function is called from one of the modelling routines in :mod:`model`.
Consult these modelling routines for a description of the input and output
parameters.
Returns
-------
fEM : array
Returns frequency-domain EM response.
kcount : int
Kernel count. For DLF, this is 1.
conv : bool
Only relevant for QWE/QUAD.
"""
# 1. Get fhtargs
fhtfilt = fhtarg[0]
pts_per_dec = fhtarg[1]
lambd = fhtarg[2]
int_pts = fhtarg[3]
# 2. Call the kernel
PJ = kernel.wavenumber(zsrc, zrec, lsrc, lrec, depth, etaH, etaV, zetaH,
zetaV, lambd, ab, xdirect, msrc, mrec, use_ne_eval)
# 3. Carry out the dlf
fEM = dlf(PJ, lambd, off, fhtfilt, pts_per_dec, factAng=factAng, ab=ab,
int_pts=int_pts)
return fEM, 1, True | [
"def",
"fht",
"(",
"zsrc",
",",
"zrec",
",",
"lsrc",
",",
"lrec",
",",
"off",
",",
"factAng",
",",
"depth",
",",
"ab",
",",
"etaH",
",",
"etaV",
",",
"zetaH",
",",
"zetaV",
",",
"xdirect",
",",
"fhtarg",
",",
"use_ne_eval",
",",
"msrc",
",",
"mre... | r"""Hankel Transform using the Digital Linear Filter method.
The *Digital Linear Filter* method was introduced to geophysics by
[Ghos70]_, and made popular and wide-spread by [Ande75]_, [Ande79]_,
[Ande82]_. The DLF is sometimes referred to as the *Fast Hankel Transform*
FHT, from which this routine has its name.
This implementation of the DLF follows [Key12]_, equation 6. Without going
into the mathematical details (which can be found in any of the above
papers) and following [Key12]_, the DLF method rewrites the Hankel
transform of the form
.. math:: F(r) = \int^\infty_0 f(\lambda)J_v(\lambda r)\
\mathrm{d}\lambda
as
.. math:: F(r) = \sum^n_{i=1} f(b_i/r)h_i/r \ ,
where :math:`h` is the digital filter.The Filter abscissae b is given by
.. math:: b_i = \lambda_ir = e^{ai}, \qquad i = -l, -l+1, \cdots, l \ ,
with :math:`l=(n-1)/2`, and :math:`a` is the spacing coefficient.
This function is loosely based on ``get_CSEM1D_FD_FHT.m`` from the source
code distributed with [Key12]_.
The function is called from one of the modelling routines in :mod:`model`.
Consult these modelling routines for a description of the input and output
parameters.
Returns
-------
fEM : array
Returns frequency-domain EM response.
kcount : int
Kernel count. For DLF, this is 1.
conv : bool
Only relevant for QWE/QUAD. | [
"r",
"Hankel",
"Transform",
"using",
"the",
"Digital",
"Linear",
"Filter",
"method",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/transform.py#L47-L107 | train | 24,664 |
empymod/empymod | empymod/transform.py | hquad | def hquad(zsrc, zrec, lsrc, lrec, off, factAng, depth, ab, etaH, etaV, zetaH,
zetaV, xdirect, quadargs, use_ne_eval, msrc, mrec):
r"""Hankel Transform using the ``QUADPACK`` library.
This routine uses the ``scipy.integrate.quad`` module, which in turn makes
use of the Fortran library ``QUADPACK`` (``qagse``).
It is massively (orders of magnitudes) slower than either ``fht`` or
``hqwe``, and is mainly here for completeness and comparison purposes. It
always uses interpolation in the wavenumber domain, hence it generally will
not be as precise as the other methods. However, it might work in some
areas where the others fail.
The function is called from one of the modelling routines in :mod:`model`.
Consult these modelling routines for a description of the input and output
parameters.
Returns
-------
fEM : array
Returns frequency-domain EM response.
kcount : int
Kernel count. For HQUAD, this is 1.
conv : bool
If true, QUAD converged. If not, <htarg> might have to be adjusted.
"""
# Get quadargs
rtol, atol, limit, a, b, pts_per_dec = quadargs
# Get required lambdas
la = np.log10(a)
lb = np.log10(b)
ilambd = np.logspace(la, lb, (lb-la)*pts_per_dec + 1)
# Call the kernel
PJ0, PJ1, PJ0b = kernel.wavenumber(zsrc, zrec, lsrc, lrec, depth, etaH,
etaV, zetaH, zetaV,
np.atleast_2d(ilambd), ab, xdirect,
msrc, mrec, use_ne_eval)
# Interpolation in wavenumber domain: Has to be done separately on each PJ,
# in order to work with multiple offsets which have different angles.
# We check if the kernels are zero, to avoid unnecessary calculations.
if PJ0 is not None:
sPJ0r = iuSpline(np.log(ilambd), PJ0.real)
sPJ0i = iuSpline(np.log(ilambd), PJ0.imag)
else:
sPJ0r = None
sPJ0i = None
if PJ1 is not None:
sPJ1r = iuSpline(np.log(ilambd), PJ1.real)
sPJ1i = iuSpline(np.log(ilambd), PJ1.imag)
else:
sPJ1r = None
sPJ1i = None
if PJ0b is not None:
sPJ0br = iuSpline(np.log(ilambd), PJ0b.real)
sPJ0bi = iuSpline(np.log(ilambd), PJ0b.imag)
else:
sPJ0br = None
sPJ0bi = None
# Pre-allocate output array
fEM = np.zeros(off.size, dtype=complex)
conv = True
# Input-dictionary for quad
iinp = {'a': a, 'b': b, 'epsabs': atol, 'epsrel': rtol, 'limit': limit}
# Loop over offsets
for i in range(off.size):
fEM[i], tc = quad(sPJ0r, sPJ0i, sPJ1r, sPJ1i, sPJ0br, sPJ0bi, ab,
off[i], factAng[i], iinp)
conv *= tc
# Return the electromagnetic field
# Second argument (1) is the kernel count, last argument is only for QWE.
return fEM, 1, conv | python | def hquad(zsrc, zrec, lsrc, lrec, off, factAng, depth, ab, etaH, etaV, zetaH,
zetaV, xdirect, quadargs, use_ne_eval, msrc, mrec):
r"""Hankel Transform using the ``QUADPACK`` library.
This routine uses the ``scipy.integrate.quad`` module, which in turn makes
use of the Fortran library ``QUADPACK`` (``qagse``).
It is massively (orders of magnitudes) slower than either ``fht`` or
``hqwe``, and is mainly here for completeness and comparison purposes. It
always uses interpolation in the wavenumber domain, hence it generally will
not be as precise as the other methods. However, it might work in some
areas where the others fail.
The function is called from one of the modelling routines in :mod:`model`.
Consult these modelling routines for a description of the input and output
parameters.
Returns
-------
fEM : array
Returns frequency-domain EM response.
kcount : int
Kernel count. For HQUAD, this is 1.
conv : bool
If true, QUAD converged. If not, <htarg> might have to be adjusted.
"""
# Get quadargs
rtol, atol, limit, a, b, pts_per_dec = quadargs
# Get required lambdas
la = np.log10(a)
lb = np.log10(b)
ilambd = np.logspace(la, lb, (lb-la)*pts_per_dec + 1)
# Call the kernel
PJ0, PJ1, PJ0b = kernel.wavenumber(zsrc, zrec, lsrc, lrec, depth, etaH,
etaV, zetaH, zetaV,
np.atleast_2d(ilambd), ab, xdirect,
msrc, mrec, use_ne_eval)
# Interpolation in wavenumber domain: Has to be done separately on each PJ,
# in order to work with multiple offsets which have different angles.
# We check if the kernels are zero, to avoid unnecessary calculations.
if PJ0 is not None:
sPJ0r = iuSpline(np.log(ilambd), PJ0.real)
sPJ0i = iuSpline(np.log(ilambd), PJ0.imag)
else:
sPJ0r = None
sPJ0i = None
if PJ1 is not None:
sPJ1r = iuSpline(np.log(ilambd), PJ1.real)
sPJ1i = iuSpline(np.log(ilambd), PJ1.imag)
else:
sPJ1r = None
sPJ1i = None
if PJ0b is not None:
sPJ0br = iuSpline(np.log(ilambd), PJ0b.real)
sPJ0bi = iuSpline(np.log(ilambd), PJ0b.imag)
else:
sPJ0br = None
sPJ0bi = None
# Pre-allocate output array
fEM = np.zeros(off.size, dtype=complex)
conv = True
# Input-dictionary for quad
iinp = {'a': a, 'b': b, 'epsabs': atol, 'epsrel': rtol, 'limit': limit}
# Loop over offsets
for i in range(off.size):
fEM[i], tc = quad(sPJ0r, sPJ0i, sPJ1r, sPJ1i, sPJ0br, sPJ0bi, ab,
off[i], factAng[i], iinp)
conv *= tc
# Return the electromagnetic field
# Second argument (1) is the kernel count, last argument is only for QWE.
return fEM, 1, conv | [
"def",
"hquad",
"(",
"zsrc",
",",
"zrec",
",",
"lsrc",
",",
"lrec",
",",
"off",
",",
"factAng",
",",
"depth",
",",
"ab",
",",
"etaH",
",",
"etaV",
",",
"zetaH",
",",
"zetaV",
",",
"xdirect",
",",
"quadargs",
",",
"use_ne_eval",
",",
"msrc",
",",
... | r"""Hankel Transform using the ``QUADPACK`` library.
This routine uses the ``scipy.integrate.quad`` module, which in turn makes
use of the Fortran library ``QUADPACK`` (``qagse``).
It is massively (orders of magnitudes) slower than either ``fht`` or
``hqwe``, and is mainly here for completeness and comparison purposes. It
always uses interpolation in the wavenumber domain, hence it generally will
not be as precise as the other methods. However, it might work in some
areas where the others fail.
The function is called from one of the modelling routines in :mod:`model`.
Consult these modelling routines for a description of the input and output
parameters.
Returns
-------
fEM : array
Returns frequency-domain EM response.
kcount : int
Kernel count. For HQUAD, this is 1.
conv : bool
If true, QUAD converged. If not, <htarg> might have to be adjusted. | [
"r",
"Hankel",
"Transform",
"using",
"the",
"QUADPACK",
"library",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/transform.py#L399-L482 | train | 24,665 |
empymod/empymod | empymod/transform.py | ffht | def ffht(fEM, time, freq, ftarg):
r"""Fourier Transform using the Digital Linear Filter method.
It follows the Filter methodology [Ande75]_, using Cosine- and
Sine-filters; see ``fht`` for more information.
The function is called from one of the modelling routines in :mod:`model`.
Consult these modelling routines for a description of the input and output
parameters.
This function is based on ``get_CSEM1D_TD_FHT.m`` from the source code
distributed with [Key12]_.
Returns
-------
tEM : array
Returns time-domain EM response of ``fEM`` for given ``time``.
conv : bool
Only relevant for QWE/QUAD.
"""
# Get ffhtargs
ffhtfilt = ftarg[0]
pts_per_dec = ftarg[1]
kind = ftarg[2] # Sine (`sin`) or cosine (`cos`)
# Cast into Standard DLF format
if pts_per_dec == 0:
fEM = fEM.reshape(time.size, -1)
# Carry out DLF
tEM = dlf(fEM, 2*np.pi*freq, time, ffhtfilt, pts_per_dec, kind=kind)
# Return the electromagnetic time domain field
# (Second argument is only for QWE)
return tEM, True | python | def ffht(fEM, time, freq, ftarg):
r"""Fourier Transform using the Digital Linear Filter method.
It follows the Filter methodology [Ande75]_, using Cosine- and
Sine-filters; see ``fht`` for more information.
The function is called from one of the modelling routines in :mod:`model`.
Consult these modelling routines for a description of the input and output
parameters.
This function is based on ``get_CSEM1D_TD_FHT.m`` from the source code
distributed with [Key12]_.
Returns
-------
tEM : array
Returns time-domain EM response of ``fEM`` for given ``time``.
conv : bool
Only relevant for QWE/QUAD.
"""
# Get ffhtargs
ffhtfilt = ftarg[0]
pts_per_dec = ftarg[1]
kind = ftarg[2] # Sine (`sin`) or cosine (`cos`)
# Cast into Standard DLF format
if pts_per_dec == 0:
fEM = fEM.reshape(time.size, -1)
# Carry out DLF
tEM = dlf(fEM, 2*np.pi*freq, time, ffhtfilt, pts_per_dec, kind=kind)
# Return the electromagnetic time domain field
# (Second argument is only for QWE)
return tEM, True | [
"def",
"ffht",
"(",
"fEM",
",",
"time",
",",
"freq",
",",
"ftarg",
")",
":",
"# Get ffhtargs",
"ffhtfilt",
"=",
"ftarg",
"[",
"0",
"]",
"pts_per_dec",
"=",
"ftarg",
"[",
"1",
"]",
"kind",
"=",
"ftarg",
"[",
"2",
"]",
"# Sine (`sin`) or cosine (`cos`)",
... | r"""Fourier Transform using the Digital Linear Filter method.
It follows the Filter methodology [Ande75]_, using Cosine- and
Sine-filters; see ``fht`` for more information.
The function is called from one of the modelling routines in :mod:`model`.
Consult these modelling routines for a description of the input and output
parameters.
This function is based on ``get_CSEM1D_TD_FHT.m`` from the source code
distributed with [Key12]_.
Returns
-------
tEM : array
Returns time-domain EM response of ``fEM`` for given ``time``.
conv : bool
Only relevant for QWE/QUAD. | [
"r",
"Fourier",
"Transform",
"using",
"the",
"Digital",
"Linear",
"Filter",
"method",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/transform.py#L487-L524 | train | 24,666 |
empymod/empymod | empymod/transform.py | fft | def fft(fEM, time, freq, ftarg):
r"""Fourier Transform using the Fast Fourier Transform.
The function is called from one of the modelling routines in :mod:`model`.
Consult these modelling routines for a description of the input and output
parameters.
Returns
-------
tEM : array
Returns time-domain EM response of ``fEM`` for given ``time``.
conv : bool
Only relevant for QWE/QUAD.
"""
# Get ftarg values
dfreq, nfreq, ntot, pts_per_dec = ftarg
# If pts_per_dec, we have first to interpolate fEM to required freqs
if pts_per_dec:
sfEMr = iuSpline(np.log(freq), fEM.real)
sfEMi = iuSpline(np.log(freq), fEM.imag)
freq = np.arange(1, nfreq+1)*dfreq
fEM = sfEMr(np.log(freq)) + 1j*sfEMi(np.log(freq))
# Pad the frequency result
fEM = np.pad(fEM, (0, ntot-nfreq), 'linear_ramp')
# Carry out FFT
ifftEM = fftpack.ifft(np.r_[fEM[1:], 0, fEM[::-1].conj()]).real
stEM = 2*ntot*fftpack.fftshift(ifftEM*dfreq, 0)
# Interpolate in time domain
dt = 1/(2*ntot*dfreq)
ifEM = iuSpline(np.linspace(-ntot, ntot-1, 2*ntot)*dt, stEM)
tEM = ifEM(time)/2*np.pi # (Multiplication of 2/pi in model.tem)
# Return the electromagnetic time domain field
# (Second argument is only for QWE)
return tEM, True | python | def fft(fEM, time, freq, ftarg):
r"""Fourier Transform using the Fast Fourier Transform.
The function is called from one of the modelling routines in :mod:`model`.
Consult these modelling routines for a description of the input and output
parameters.
Returns
-------
tEM : array
Returns time-domain EM response of ``fEM`` for given ``time``.
conv : bool
Only relevant for QWE/QUAD.
"""
# Get ftarg values
dfreq, nfreq, ntot, pts_per_dec = ftarg
# If pts_per_dec, we have first to interpolate fEM to required freqs
if pts_per_dec:
sfEMr = iuSpline(np.log(freq), fEM.real)
sfEMi = iuSpline(np.log(freq), fEM.imag)
freq = np.arange(1, nfreq+1)*dfreq
fEM = sfEMr(np.log(freq)) + 1j*sfEMi(np.log(freq))
# Pad the frequency result
fEM = np.pad(fEM, (0, ntot-nfreq), 'linear_ramp')
# Carry out FFT
ifftEM = fftpack.ifft(np.r_[fEM[1:], 0, fEM[::-1].conj()]).real
stEM = 2*ntot*fftpack.fftshift(ifftEM*dfreq, 0)
# Interpolate in time domain
dt = 1/(2*ntot*dfreq)
ifEM = iuSpline(np.linspace(-ntot, ntot-1, 2*ntot)*dt, stEM)
tEM = ifEM(time)/2*np.pi # (Multiplication of 2/pi in model.tem)
# Return the electromagnetic time domain field
# (Second argument is only for QWE)
return tEM, True | [
"def",
"fft",
"(",
"fEM",
",",
"time",
",",
"freq",
",",
"ftarg",
")",
":",
"# Get ftarg values",
"dfreq",
",",
"nfreq",
",",
"ntot",
",",
"pts_per_dec",
"=",
"ftarg",
"# If pts_per_dec, we have first to interpolate fEM to required freqs",
"if",
"pts_per_dec",
":",
... | r"""Fourier Transform using the Fast Fourier Transform.
The function is called from one of the modelling routines in :mod:`model`.
Consult these modelling routines for a description of the input and output
parameters.
Returns
-------
tEM : array
Returns time-domain EM response of ``fEM`` for given ``time``.
conv : bool
Only relevant for QWE/QUAD. | [
"r",
"Fourier",
"Transform",
"using",
"the",
"Fast",
"Fourier",
"Transform",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/transform.py#L766-L806 | train | 24,667 |
empymod/empymod | empymod/transform.py | quad | def quad(sPJ0r, sPJ0i, sPJ1r, sPJ1i, sPJ0br, sPJ0bi, ab, off, factAng, iinp):
r"""Quadrature for Hankel transform.
This is the kernel of the QUAD method, used for the Hankel transforms
``hquad`` and ``hqwe`` (where the integral is not suited for QWE).
"""
# Define the quadrature kernels
def quad_PJ0(klambd, sPJ0, koff):
r"""Quadrature for PJ0."""
return sPJ0(np.log(klambd))*special.j0(koff*klambd)
def quad_PJ1(klambd, sPJ1, ab, koff, kang):
r"""Quadrature for PJ1."""
tP1 = kang*sPJ1(np.log(klambd))
if ab in [11, 12, 21, 22, 14, 24, 15, 25]: # Because of J2
# J2(kr) = 2/(kr)*J1(kr) - J0(kr)
tP1 /= koff
return tP1*special.j1(koff*klambd)
def quad_PJ0b(klambd, sPJ0b, koff, kang):
r"""Quadrature for PJ0b."""
return kang*sPJ0b(np.log(klambd))*special.j0(koff*klambd)
# Pre-allocate output
conv = True
out = np.array(0.0+0.0j)
# Carry out quadrature for required kernels
iinp['full_output'] = 1
if sPJ0r is not None:
re = integrate.quad(quad_PJ0, args=(sPJ0r, off), **iinp)
im = integrate.quad(quad_PJ0, args=(sPJ0i, off), **iinp)
out += re[0] + 1j*im[0]
# If there is a fourth output from QUAD, it means it did not converge
if (len(re) or len(im)) > 3:
conv = False
if sPJ1r is not None:
re = integrate.quad(quad_PJ1, args=(sPJ1r, ab, off, factAng), **iinp)
im = integrate.quad(quad_PJ1, args=(sPJ1i, ab, off, factAng), **iinp)
out += re[0] + 1j*im[0]
# If there is a fourth output from QUAD, it means it did not converge
if (len(re) or len(im)) > 3:
conv = False
if sPJ0br is not None:
re = integrate.quad(quad_PJ0b, args=(sPJ0br, off, factAng), **iinp)
im = integrate.quad(quad_PJ0b, args=(sPJ0bi, off, factAng), **iinp)
out += re[0] + 1j*im[0]
# If there is a fourth output from QUAD, it means it did not converge
if (len(re) or len(im)) > 3:
conv = False
# Collect the results
return out, conv | python | def quad(sPJ0r, sPJ0i, sPJ1r, sPJ1i, sPJ0br, sPJ0bi, ab, off, factAng, iinp):
r"""Quadrature for Hankel transform.
This is the kernel of the QUAD method, used for the Hankel transforms
``hquad`` and ``hqwe`` (where the integral is not suited for QWE).
"""
# Define the quadrature kernels
def quad_PJ0(klambd, sPJ0, koff):
r"""Quadrature for PJ0."""
return sPJ0(np.log(klambd))*special.j0(koff*klambd)
def quad_PJ1(klambd, sPJ1, ab, koff, kang):
r"""Quadrature for PJ1."""
tP1 = kang*sPJ1(np.log(klambd))
if ab in [11, 12, 21, 22, 14, 24, 15, 25]: # Because of J2
# J2(kr) = 2/(kr)*J1(kr) - J0(kr)
tP1 /= koff
return tP1*special.j1(koff*klambd)
def quad_PJ0b(klambd, sPJ0b, koff, kang):
r"""Quadrature for PJ0b."""
return kang*sPJ0b(np.log(klambd))*special.j0(koff*klambd)
# Pre-allocate output
conv = True
out = np.array(0.0+0.0j)
# Carry out quadrature for required kernels
iinp['full_output'] = 1
if sPJ0r is not None:
re = integrate.quad(quad_PJ0, args=(sPJ0r, off), **iinp)
im = integrate.quad(quad_PJ0, args=(sPJ0i, off), **iinp)
out += re[0] + 1j*im[0]
# If there is a fourth output from QUAD, it means it did not converge
if (len(re) or len(im)) > 3:
conv = False
if sPJ1r is not None:
re = integrate.quad(quad_PJ1, args=(sPJ1r, ab, off, factAng), **iinp)
im = integrate.quad(quad_PJ1, args=(sPJ1i, ab, off, factAng), **iinp)
out += re[0] + 1j*im[0]
# If there is a fourth output from QUAD, it means it did not converge
if (len(re) or len(im)) > 3:
conv = False
if sPJ0br is not None:
re = integrate.quad(quad_PJ0b, args=(sPJ0br, off, factAng), **iinp)
im = integrate.quad(quad_PJ0b, args=(sPJ0bi, off, factAng), **iinp)
out += re[0] + 1j*im[0]
# If there is a fourth output from QUAD, it means it did not converge
if (len(re) or len(im)) > 3:
conv = False
# Collect the results
return out, conv | [
"def",
"quad",
"(",
"sPJ0r",
",",
"sPJ0i",
",",
"sPJ1r",
",",
"sPJ1i",
",",
"sPJ0br",
",",
"sPJ0bi",
",",
"ab",
",",
"off",
",",
"factAng",
",",
"iinp",
")",
":",
"# Define the quadrature kernels",
"def",
"quad_PJ0",
"(",
"klambd",
",",
"sPJ0",
",",
"k... | r"""Quadrature for Hankel transform.
This is the kernel of the QUAD method, used for the Hankel transforms
``hquad`` and ``hqwe`` (where the integral is not suited for QWE). | [
"r",
"Quadrature",
"for",
"Hankel",
"transform",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/transform.py#L1097-L1156 | train | 24,668 |
empymod/empymod | empymod/transform.py | get_spline_values | def get_spline_values(filt, inp, nr_per_dec=None):
r"""Return required calculation points."""
# Standard DLF
if nr_per_dec == 0:
return filt.base/inp[:, None], inp
# Get min and max required out-values (depends on filter and inp-value)
outmax = filt.base[-1]/inp.min()
outmin = filt.base[0]/inp.max()
# Get pts_per_dec and define number of out-values, depending on pts_per_dec
if nr_per_dec < 0: # Lagged Convolution DLF
pts_per_dec = 1/np.log(filt.factor)
# Calculate number of output values
nout = int(np.ceil(np.log(outmax/outmin)*pts_per_dec) + 1)
else: # Splined DLF
pts_per_dec = nr_per_dec
# Calculate number of output values
nout = int(np.ceil(np.log10(outmax/outmin)*pts_per_dec) + 1)
# Min-nout check, becaus the cubic InterpolatedUnivariateSpline needs at
# least 4 points.
if nr_per_dec < 0: # Lagged Convolution DLF
# Lagged Convolution DLF interpolates in output domain, so `new_inp`
# needs to have at least 4 points.
if nout-filt.base.size < 3:
nout = filt.base.size+3
else: # Splined DLF
# Splined DLF interpolates in input domain, so `out` needs to have at
# least 4 points. This should always be the case, we're just overly
# cautious here.
if nout < 4:
nout = 4
if nr_per_dec < 0:
# Calculate output values
out = np.exp(np.arange(np.log(outmin), np.log(outmin) +
nout/pts_per_dec, 1/pts_per_dec))
# If lagged convolution is used, we calculate the new input values, as
# spline is carried out in the input domain.
new_inp = inp.max()*np.exp(-np.arange(nout - filt.base.size + 1) /
pts_per_dec)
else:
# Calculate output values
out = 10**np.arange(np.log10(outmin), np.log10(outmin) +
nout/pts_per_dec, 1/pts_per_dec)
# If spline is used, interpolation is carried out in output domain and
# we calculate the intermediate values.
new_inp = filt.base/inp[:, None]
# Return output values
return np.atleast_2d(out), new_inp | python | def get_spline_values(filt, inp, nr_per_dec=None):
r"""Return required calculation points."""
# Standard DLF
if nr_per_dec == 0:
return filt.base/inp[:, None], inp
# Get min and max required out-values (depends on filter and inp-value)
outmax = filt.base[-1]/inp.min()
outmin = filt.base[0]/inp.max()
# Get pts_per_dec and define number of out-values, depending on pts_per_dec
if nr_per_dec < 0: # Lagged Convolution DLF
pts_per_dec = 1/np.log(filt.factor)
# Calculate number of output values
nout = int(np.ceil(np.log(outmax/outmin)*pts_per_dec) + 1)
else: # Splined DLF
pts_per_dec = nr_per_dec
# Calculate number of output values
nout = int(np.ceil(np.log10(outmax/outmin)*pts_per_dec) + 1)
# Min-nout check, becaus the cubic InterpolatedUnivariateSpline needs at
# least 4 points.
if nr_per_dec < 0: # Lagged Convolution DLF
# Lagged Convolution DLF interpolates in output domain, so `new_inp`
# needs to have at least 4 points.
if nout-filt.base.size < 3:
nout = filt.base.size+3
else: # Splined DLF
# Splined DLF interpolates in input domain, so `out` needs to have at
# least 4 points. This should always be the case, we're just overly
# cautious here.
if nout < 4:
nout = 4
if nr_per_dec < 0:
# Calculate output values
out = np.exp(np.arange(np.log(outmin), np.log(outmin) +
nout/pts_per_dec, 1/pts_per_dec))
# If lagged convolution is used, we calculate the new input values, as
# spline is carried out in the input domain.
new_inp = inp.max()*np.exp(-np.arange(nout - filt.base.size + 1) /
pts_per_dec)
else:
# Calculate output values
out = 10**np.arange(np.log10(outmin), np.log10(outmin) +
nout/pts_per_dec, 1/pts_per_dec)
# If spline is used, interpolation is carried out in output domain and
# we calculate the intermediate values.
new_inp = filt.base/inp[:, None]
# Return output values
return np.atleast_2d(out), new_inp | [
"def",
"get_spline_values",
"(",
"filt",
",",
"inp",
",",
"nr_per_dec",
"=",
"None",
")",
":",
"# Standard DLF",
"if",
"nr_per_dec",
"==",
"0",
":",
"return",
"filt",
".",
"base",
"/",
"inp",
"[",
":",
",",
"None",
"]",
",",
"inp",
"# Get min and max req... | r"""Return required calculation points. | [
"r",
"Return",
"required",
"calculation",
"points",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/transform.py#L1159-L1216 | train | 24,669 |
empymod/empymod | empymod/transform.py | fhti | def fhti(rmin, rmax, n, q, mu):
r"""Return parameters required for FFTLog."""
# Central point log10(r_c) of periodic interval
logrc = (rmin + rmax)/2
# Central index (1/2 integral if n is even)
nc = (n + 1)/2.
# Log spacing of points
dlogr = (rmax - rmin)/n
dlnr = dlogr*np.log(10.)
# Get low-ringing kr
y = 1j*np.pi/(2.0*dlnr)
zp = special.loggamma((mu + 1.0 + q)/2.0 + y)
zm = special.loggamma((mu + 1.0 - q)/2.0 + y)
arg = np.log(2.0)/dlnr + (zp.imag + zm.imag)/np.pi
kr = np.exp((arg - np.round(arg))*dlnr)
# Calculate required input x-values (freq); angular freq -> freq
freq = 10**(logrc + (np.arange(1, n+1) - nc)*dlogr)/(2*np.pi)
# Calculate tcalc with adjusted kr
logkc = np.log10(kr) - logrc
tcalc = 10**(logkc + (np.arange(1, n+1) - nc)*dlogr)
# rk = r_c/k_r; adjust for Fourier transform scaling
rk = 10**(logrc - logkc)*np.pi/2
return freq, tcalc, dlnr, kr, rk | python | def fhti(rmin, rmax, n, q, mu):
r"""Return parameters required for FFTLog."""
# Central point log10(r_c) of periodic interval
logrc = (rmin + rmax)/2
# Central index (1/2 integral if n is even)
nc = (n + 1)/2.
# Log spacing of points
dlogr = (rmax - rmin)/n
dlnr = dlogr*np.log(10.)
# Get low-ringing kr
y = 1j*np.pi/(2.0*dlnr)
zp = special.loggamma((mu + 1.0 + q)/2.0 + y)
zm = special.loggamma((mu + 1.0 - q)/2.0 + y)
arg = np.log(2.0)/dlnr + (zp.imag + zm.imag)/np.pi
kr = np.exp((arg - np.round(arg))*dlnr)
# Calculate required input x-values (freq); angular freq -> freq
freq = 10**(logrc + (np.arange(1, n+1) - nc)*dlogr)/(2*np.pi)
# Calculate tcalc with adjusted kr
logkc = np.log10(kr) - logrc
tcalc = 10**(logkc + (np.arange(1, n+1) - nc)*dlogr)
# rk = r_c/k_r; adjust for Fourier transform scaling
rk = 10**(logrc - logkc)*np.pi/2
return freq, tcalc, dlnr, kr, rk | [
"def",
"fhti",
"(",
"rmin",
",",
"rmax",
",",
"n",
",",
"q",
",",
"mu",
")",
":",
"# Central point log10(r_c) of periodic interval",
"logrc",
"=",
"(",
"rmin",
"+",
"rmax",
")",
"/",
"2",
"# Central index (1/2 integral if n is even)",
"nc",
"=",
"(",
"n",
"+... | r"""Return parameters required for FFTLog. | [
"r",
"Return",
"parameters",
"required",
"for",
"FFTLog",
"."
] | 4a78ca4191ed4b4d42d019ce715a9a3889dba1bc | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/transform.py#L1219-L1249 | train | 24,670 |
workhorsy/py-cpuinfo | cpuinfo/cpuinfo.py | _actual_get_cpu_info_from_cpuid | def _actual_get_cpu_info_from_cpuid(queue):
'''
Warning! This function has the potential to crash the Python runtime.
Do not call it directly. Use the _get_cpu_info_from_cpuid function instead.
It will safely call this function in another process.
'''
# Pipe all output to nothing
sys.stdout = open(os.devnull, 'w')
sys.stderr = open(os.devnull, 'w')
# Get the CPU arch and bits
arch, bits = _parse_arch(DataSource.arch_string_raw)
# Return none if this is not an X86 CPU
if not arch in ['X86_32', 'X86_64']:
queue.put(_obj_to_b64({}))
return
# Return none if SE Linux is in enforcing mode
cpuid = CPUID()
if cpuid.is_selinux_enforcing:
queue.put(_obj_to_b64({}))
return
# Get the cpu info from the CPUID register
max_extension_support = cpuid.get_max_extension_support()
cache_info = cpuid.get_cache(max_extension_support)
info = cpuid.get_info()
processor_brand = cpuid.get_processor_brand(max_extension_support)
# Get the Hz and scale
hz_actual = cpuid.get_raw_hz()
hz_actual = _to_decimal_string(hz_actual)
# Get the Hz and scale
hz_advertised, scale = _parse_cpu_brand_string(processor_brand)
info = {
'vendor_id_raw' : cpuid.get_vendor_id(),
'hardware_raw' : '',
'brand_raw' : processor_brand,
'hz_advertised_friendly' : _hz_short_to_friendly(hz_advertised, scale),
'hz_actual_friendly' : _hz_short_to_friendly(hz_actual, 0),
'hz_advertised' : _hz_short_to_full(hz_advertised, scale),
'hz_actual' : _hz_short_to_full(hz_actual, 0),
'l2_cache_size' : _to_friendly_bytes(cache_info['size_kb']),
'l2_cache_line_size' : cache_info['line_size_b'],
'l2_cache_associativity' : hex(cache_info['associativity']),
'stepping' : info['stepping'],
'model' : info['model'],
'family' : info['family'],
'processor_type' : info['processor_type'],
'extended_model' : info['extended_model'],
'extended_family' : info['extended_family'],
'flags' : cpuid.get_flags(max_extension_support)
}
info = {k: v for k, v in info.items() if v}
queue.put(_obj_to_b64(info)) | python | def _actual_get_cpu_info_from_cpuid(queue):
'''
Warning! This function has the potential to crash the Python runtime.
Do not call it directly. Use the _get_cpu_info_from_cpuid function instead.
It will safely call this function in another process.
'''
# Pipe all output to nothing
sys.stdout = open(os.devnull, 'w')
sys.stderr = open(os.devnull, 'w')
# Get the CPU arch and bits
arch, bits = _parse_arch(DataSource.arch_string_raw)
# Return none if this is not an X86 CPU
if not arch in ['X86_32', 'X86_64']:
queue.put(_obj_to_b64({}))
return
# Return none if SE Linux is in enforcing mode
cpuid = CPUID()
if cpuid.is_selinux_enforcing:
queue.put(_obj_to_b64({}))
return
# Get the cpu info from the CPUID register
max_extension_support = cpuid.get_max_extension_support()
cache_info = cpuid.get_cache(max_extension_support)
info = cpuid.get_info()
processor_brand = cpuid.get_processor_brand(max_extension_support)
# Get the Hz and scale
hz_actual = cpuid.get_raw_hz()
hz_actual = _to_decimal_string(hz_actual)
# Get the Hz and scale
hz_advertised, scale = _parse_cpu_brand_string(processor_brand)
info = {
'vendor_id_raw' : cpuid.get_vendor_id(),
'hardware_raw' : '',
'brand_raw' : processor_brand,
'hz_advertised_friendly' : _hz_short_to_friendly(hz_advertised, scale),
'hz_actual_friendly' : _hz_short_to_friendly(hz_actual, 0),
'hz_advertised' : _hz_short_to_full(hz_advertised, scale),
'hz_actual' : _hz_short_to_full(hz_actual, 0),
'l2_cache_size' : _to_friendly_bytes(cache_info['size_kb']),
'l2_cache_line_size' : cache_info['line_size_b'],
'l2_cache_associativity' : hex(cache_info['associativity']),
'stepping' : info['stepping'],
'model' : info['model'],
'family' : info['family'],
'processor_type' : info['processor_type'],
'extended_model' : info['extended_model'],
'extended_family' : info['extended_family'],
'flags' : cpuid.get_flags(max_extension_support)
}
info = {k: v for k, v in info.items() if v}
queue.put(_obj_to_b64(info)) | [
"def",
"_actual_get_cpu_info_from_cpuid",
"(",
"queue",
")",
":",
"# Pipe all output to nothing",
"sys",
".",
"stdout",
"=",
"open",
"(",
"os",
".",
"devnull",
",",
"'w'",
")",
"sys",
".",
"stderr",
"=",
"open",
"(",
"os",
".",
"devnull",
",",
"'w'",
")",
... | Warning! This function has the potential to crash the Python runtime.
Do not call it directly. Use the _get_cpu_info_from_cpuid function instead.
It will safely call this function in another process. | [
"Warning!",
"This",
"function",
"has",
"the",
"potential",
"to",
"crash",
"the",
"Python",
"runtime",
".",
"Do",
"not",
"call",
"it",
"directly",
".",
"Use",
"the",
"_get_cpu_info_from_cpuid",
"function",
"instead",
".",
"It",
"will",
"safely",
"call",
"this",... | c15afb770c1139bf76215852e17eb4f677ca3d2f | https://github.com/workhorsy/py-cpuinfo/blob/c15afb770c1139bf76215852e17eb4f677ca3d2f/cpuinfo/cpuinfo.py#L1294-L1356 | train | 24,671 |
workhorsy/py-cpuinfo | cpuinfo/cpuinfo.py | get_cpu_info_json | def get_cpu_info_json():
'''
Returns the CPU info by using the best sources of information for your OS.
Returns the result in a json string
'''
import json
output = None
# If running under pyinstaller, run normally
if getattr(sys, 'frozen', False):
info = _get_cpu_info_internal()
output = json.dumps(info)
output = "{0}".format(output)
# if not running under pyinstaller, run in another process.
# This is done because multiprocesing has a design flaw that
# causes non main programs to run multiple times on Windows.
else:
from subprocess import Popen, PIPE
command = [sys.executable, __file__, '--json']
p1 = Popen(command, stdout=PIPE, stderr=PIPE, stdin=PIPE)
output = p1.communicate()[0]
if p1.returncode != 0:
return "{}"
if not IS_PY2:
output = output.decode(encoding='UTF-8')
return output | python | def get_cpu_info_json():
'''
Returns the CPU info by using the best sources of information for your OS.
Returns the result in a json string
'''
import json
output = None
# If running under pyinstaller, run normally
if getattr(sys, 'frozen', False):
info = _get_cpu_info_internal()
output = json.dumps(info)
output = "{0}".format(output)
# if not running under pyinstaller, run in another process.
# This is done because multiprocesing has a design flaw that
# causes non main programs to run multiple times on Windows.
else:
from subprocess import Popen, PIPE
command = [sys.executable, __file__, '--json']
p1 = Popen(command, stdout=PIPE, stderr=PIPE, stdin=PIPE)
output = p1.communicate()[0]
if p1.returncode != 0:
return "{}"
if not IS_PY2:
output = output.decode(encoding='UTF-8')
return output | [
"def",
"get_cpu_info_json",
"(",
")",
":",
"import",
"json",
"output",
"=",
"None",
"# If running under pyinstaller, run normally",
"if",
"getattr",
"(",
"sys",
",",
"'frozen'",
",",
"False",
")",
":",
"info",
"=",
"_get_cpu_info_internal",
"(",
")",
"output",
"... | Returns the CPU info by using the best sources of information for your OS.
Returns the result in a json string | [
"Returns",
"the",
"CPU",
"info",
"by",
"using",
"the",
"best",
"sources",
"of",
"information",
"for",
"your",
"OS",
".",
"Returns",
"the",
"result",
"in",
"a",
"json",
"string"
] | c15afb770c1139bf76215852e17eb4f677ca3d2f | https://github.com/workhorsy/py-cpuinfo/blob/c15afb770c1139bf76215852e17eb4f677ca3d2f/cpuinfo/cpuinfo.py#L2275-L2306 | train | 24,672 |
workhorsy/py-cpuinfo | cpuinfo/cpuinfo.py | get_cpu_info | def get_cpu_info():
'''
Returns the CPU info by using the best sources of information for your OS.
Returns the result in a dict
'''
import json
output = get_cpu_info_json()
# Convert JSON to Python with non unicode strings
output = json.loads(output, object_hook = _utf_to_str)
return output | python | def get_cpu_info():
'''
Returns the CPU info by using the best sources of information for your OS.
Returns the result in a dict
'''
import json
output = get_cpu_info_json()
# Convert JSON to Python with non unicode strings
output = json.loads(output, object_hook = _utf_to_str)
return output | [
"def",
"get_cpu_info",
"(",
")",
":",
"import",
"json",
"output",
"=",
"get_cpu_info_json",
"(",
")",
"# Convert JSON to Python with non unicode strings",
"output",
"=",
"json",
".",
"loads",
"(",
"output",
",",
"object_hook",
"=",
"_utf_to_str",
")",
"return",
"o... | Returns the CPU info by using the best sources of information for your OS.
Returns the result in a dict | [
"Returns",
"the",
"CPU",
"info",
"by",
"using",
"the",
"best",
"sources",
"of",
"information",
"for",
"your",
"OS",
".",
"Returns",
"the",
"result",
"in",
"a",
"dict"
] | c15afb770c1139bf76215852e17eb4f677ca3d2f | https://github.com/workhorsy/py-cpuinfo/blob/c15afb770c1139bf76215852e17eb4f677ca3d2f/cpuinfo/cpuinfo.py#L2308-L2321 | train | 24,673 |
empirical-org/Quill-NLP-Tools-and-Datasets | utils/qmangle/qmangle/__init__.py | _verbs_with_subjects | def _verbs_with_subjects(doc):
"""Given a spacy document return the verbs that have subjects"""
# TODO: UNUSED
verb_subj = []
for possible_subject in doc:
if (possible_subject.dep_ == 'nsubj' and possible_subject.head.pos_ ==
'VERB'):
verb_subj.append([possible_subject.head, possible_subject])
return verb_subj | python | def _verbs_with_subjects(doc):
"""Given a spacy document return the verbs that have subjects"""
# TODO: UNUSED
verb_subj = []
for possible_subject in doc:
if (possible_subject.dep_ == 'nsubj' and possible_subject.head.pos_ ==
'VERB'):
verb_subj.append([possible_subject.head, possible_subject])
return verb_subj | [
"def",
"_verbs_with_subjects",
"(",
"doc",
")",
":",
"# TODO: UNUSED",
"verb_subj",
"=",
"[",
"]",
"for",
"possible_subject",
"in",
"doc",
":",
"if",
"(",
"possible_subject",
".",
"dep_",
"==",
"'nsubj'",
"and",
"possible_subject",
".",
"head",
".",
"pos_",
... | Given a spacy document return the verbs that have subjects | [
"Given",
"a",
"spacy",
"document",
"return",
"the",
"verbs",
"that",
"have",
"subjects"
] | f2ff579ddf3a556d9cdc47c5f702422fa06863d9 | https://github.com/empirical-org/Quill-NLP-Tools-and-Datasets/blob/f2ff579ddf3a556d9cdc47c5f702422fa06863d9/utils/qmangle/qmangle/__init__.py#L19-L27 | train | 24,674 |
empirical-org/Quill-NLP-Tools-and-Datasets | utils/qmangle/qmangle/__init__.py | mangle_agreement | def mangle_agreement(correct_sentence):
"""Given a correct sentence, return a sentence or sentences with a subject
verb agreement error"""
# # Examples
#
# Back in the 1800s, people were much shorter and much stronger.
# This sentence begins with the introductory phrase, 'back in the 1800s'
# which means that it should have the past tense verb. Any other verb would
# be incorrect.
#
#
# Jack and jill went up the hill.
# This sentence is different; 'go' would also be correct. If it began with
# 'Yesterday', a single-word introductory phrase requiring no comma, only
# 'went' would be acceptable.
#
#
# The man in the checkered shirt danced his warrior dance to show that
# he was the most dominant male in the room.
# This sentence has multiple verbs. If the sentence ended at the word dance,
# changing 'danced' to 'dances' would be acceptable, but since the sentence
# continues we cannot make this change -- 'was' agrees with 'danced' but not
# with 'dances'. This is a shifty tense error, a classic subject verb
# agreement error.
#
# # Our Method
#
# Right now, we will assume that any change in verb form of a single verb in
# a sentence is incorrect. As demonstrated above, this is not always true.
# We hope that since any model created off of this data will use a
# confidence interval to determine likelihood of a subject-verb agreement
# error, that some number can be found for which the model excels.
#
# It would also be possible to use a rule based learner to evaluate single
# verb sentences, and only evaluating more complex sentences with the
# tensorflow model.
bad_sents = []
doc = nlp(correct_sentence)
verbs = [(i, v) for (i, v) in enumerate(doc) if v.tag_.startswith('VB')]
for i, v in verbs:
for alt_verb in lexeme(doc[i].text):
if alt_verb == doc[i].text:
continue # Same as the original, skip it
if (tenses(alt_verb) == tenses(v.text) or
(alt_verb.startswith(v.text) and alt_verb.endswith("n't"))):
continue # Negated version of the original, skip it
new_sent = str(doc[:i]) + " {} ".format(alt_verb) + str(doc[i+1:])
new_sent = new_sent.replace(' ,', ',') # fix space before comma
bad_sents.append(new_sent)
return bad_sents | python | def mangle_agreement(correct_sentence):
"""Given a correct sentence, return a sentence or sentences with a subject
verb agreement error"""
# # Examples
#
# Back in the 1800s, people were much shorter and much stronger.
# This sentence begins with the introductory phrase, 'back in the 1800s'
# which means that it should have the past tense verb. Any other verb would
# be incorrect.
#
#
# Jack and jill went up the hill.
# This sentence is different; 'go' would also be correct. If it began with
# 'Yesterday', a single-word introductory phrase requiring no comma, only
# 'went' would be acceptable.
#
#
# The man in the checkered shirt danced his warrior dance to show that
# he was the most dominant male in the room.
# This sentence has multiple verbs. If the sentence ended at the word dance,
# changing 'danced' to 'dances' would be acceptable, but since the sentence
# continues we cannot make this change -- 'was' agrees with 'danced' but not
# with 'dances'. This is a shifty tense error, a classic subject verb
# agreement error.
#
# # Our Method
#
# Right now, we will assume that any change in verb form of a single verb in
# a sentence is incorrect. As demonstrated above, this is not always true.
# We hope that since any model created off of this data will use a
# confidence interval to determine likelihood of a subject-verb agreement
# error, that some number can be found for which the model excels.
#
# It would also be possible to use a rule based learner to evaluate single
# verb sentences, and only evaluating more complex sentences with the
# tensorflow model.
bad_sents = []
doc = nlp(correct_sentence)
verbs = [(i, v) for (i, v) in enumerate(doc) if v.tag_.startswith('VB')]
for i, v in verbs:
for alt_verb in lexeme(doc[i].text):
if alt_verb == doc[i].text:
continue # Same as the original, skip it
if (tenses(alt_verb) == tenses(v.text) or
(alt_verb.startswith(v.text) and alt_verb.endswith("n't"))):
continue # Negated version of the original, skip it
new_sent = str(doc[:i]) + " {} ".format(alt_verb) + str(doc[i+1:])
new_sent = new_sent.replace(' ,', ',') # fix space before comma
bad_sents.append(new_sent)
return bad_sents | [
"def",
"mangle_agreement",
"(",
"correct_sentence",
")",
":",
"# # Examples",
"#",
"# Back in the 1800s, people were much shorter and much stronger.",
"# This sentence begins with the introductory phrase, 'back in the 1800s'",
"# which means that it should have the past tense verb. Any other ver... | Given a correct sentence, return a sentence or sentences with a subject
verb agreement error | [
"Given",
"a",
"correct",
"sentence",
"return",
"a",
"sentence",
"or",
"sentences",
"with",
"a",
"subject",
"verb",
"agreement",
"error"
] | f2ff579ddf3a556d9cdc47c5f702422fa06863d9 | https://github.com/empirical-org/Quill-NLP-Tools-and-Datasets/blob/f2ff579ddf3a556d9cdc47c5f702422fa06863d9/utils/qmangle/qmangle/__init__.py#L83-L133 | train | 24,675 |
empirical-org/Quill-NLP-Tools-and-Datasets | utils/qfragment/qfragment/__init__.py | _build_trigram_indices | def _build_trigram_indices(trigram_index):
"""Build a dictionary of trigrams and their indices from a csv"""
result = {}
trigram_count = 0
for key, val in csv.reader(open(trigram_index)):
result[key] = int(val)
trigram_count += 1
return result, trigram_count | python | def _build_trigram_indices(trigram_index):
"""Build a dictionary of trigrams and their indices from a csv"""
result = {}
trigram_count = 0
for key, val in csv.reader(open(trigram_index)):
result[key] = int(val)
trigram_count += 1
return result, trigram_count | [
"def",
"_build_trigram_indices",
"(",
"trigram_index",
")",
":",
"result",
"=",
"{",
"}",
"trigram_count",
"=",
"0",
"for",
"key",
",",
"val",
"in",
"csv",
".",
"reader",
"(",
"open",
"(",
"trigram_index",
")",
")",
":",
"result",
"[",
"key",
"]",
"=",... | Build a dictionary of trigrams and their indices from a csv | [
"Build",
"a",
"dictionary",
"of",
"trigrams",
"and",
"their",
"indices",
"from",
"a",
"csv"
] | f2ff579ddf3a556d9cdc47c5f702422fa06863d9 | https://github.com/empirical-org/Quill-NLP-Tools-and-Datasets/blob/f2ff579ddf3a556d9cdc47c5f702422fa06863d9/utils/qfragment/qfragment/__init__.py#L48-L55 | train | 24,676 |
empirical-org/Quill-NLP-Tools-and-Datasets | utils/qfragment/qfragment/__init__.py | _begins_with_one_of | def _begins_with_one_of(sentence, parts_of_speech):
"""Return True if the sentence or fragment begins with one of the parts of
speech in the list, else False"""
doc = nlp(sentence)
if doc[0].tag_ in parts_of_speech:
return True
return False | python | def _begins_with_one_of(sentence, parts_of_speech):
"""Return True if the sentence or fragment begins with one of the parts of
speech in the list, else False"""
doc = nlp(sentence)
if doc[0].tag_ in parts_of_speech:
return True
return False | [
"def",
"_begins_with_one_of",
"(",
"sentence",
",",
"parts_of_speech",
")",
":",
"doc",
"=",
"nlp",
"(",
"sentence",
")",
"if",
"doc",
"[",
"0",
"]",
".",
"tag_",
"in",
"parts_of_speech",
":",
"return",
"True",
"return",
"False"
] | Return True if the sentence or fragment begins with one of the parts of
speech in the list, else False | [
"Return",
"True",
"if",
"the",
"sentence",
"or",
"fragment",
"begins",
"with",
"one",
"of",
"the",
"parts",
"of",
"speech",
"in",
"the",
"list",
"else",
"False"
] | f2ff579ddf3a556d9cdc47c5f702422fa06863d9 | https://github.com/empirical-org/Quill-NLP-Tools-and-Datasets/blob/f2ff579ddf3a556d9cdc47c5f702422fa06863d9/utils/qfragment/qfragment/__init__.py#L102-L108 | train | 24,677 |
empirical-org/Quill-NLP-Tools-and-Datasets | utils/qfragment/qfragment/__init__.py | get_language_tool_feedback | def get_language_tool_feedback(sentence):
"""Get matches from languagetool"""
payload = {'language':'en-US', 'text':sentence}
try:
r = requests.post(LT_SERVER, data=payload)
except requests.exceptions.ConnectionError as e:
raise requests.exceptions.ConnectionError('''The languagetool server is
not running. Try starting it with "ltserver" ''')
if r.status_code >= 200 and r.status_code < 300:
return r.json().get('matches', [])
return [] | python | def get_language_tool_feedback(sentence):
"""Get matches from languagetool"""
payload = {'language':'en-US', 'text':sentence}
try:
r = requests.post(LT_SERVER, data=payload)
except requests.exceptions.ConnectionError as e:
raise requests.exceptions.ConnectionError('''The languagetool server is
not running. Try starting it with "ltserver" ''')
if r.status_code >= 200 and r.status_code < 300:
return r.json().get('matches', [])
return [] | [
"def",
"get_language_tool_feedback",
"(",
"sentence",
")",
":",
"payload",
"=",
"{",
"'language'",
":",
"'en-US'",
",",
"'text'",
":",
"sentence",
"}",
"try",
":",
"r",
"=",
"requests",
".",
"post",
"(",
"LT_SERVER",
",",
"data",
"=",
"payload",
")",
"ex... | Get matches from languagetool | [
"Get",
"matches",
"from",
"languagetool"
] | f2ff579ddf3a556d9cdc47c5f702422fa06863d9 | https://github.com/empirical-org/Quill-NLP-Tools-and-Datasets/blob/f2ff579ddf3a556d9cdc47c5f702422fa06863d9/utils/qfragment/qfragment/__init__.py#L134-L144 | train | 24,678 |
empirical-org/Quill-NLP-Tools-and-Datasets | utils/qfragment/qfragment/__init__.py | is_participle_clause_fragment | def is_participle_clause_fragment(sentence):
"""Supply a sentence or fragment and recieve a confidence interval"""
# short circuit if sentence or fragment doesn't start with a participle
# past participles can sometimes look like adjectives -- ie, Tired
if not _begins_with_one_of(sentence, ['VBG', 'VBN', 'JJ']):
return 0.0
if _begins_with_one_of(sentence, ['JJ']):
doc = nlp(sentence)
fw = [w for w in doc][0]
# Beautiful toy birds
if fw.dep_ == 'amod':
return 0.0
# short circuit if sentence starts with a gerund and the gerund is the
# subject.
if _begins_with_one_of(sentence, ['VBG']):
doc = nlp(sentence)
fw = [w for w in doc][0]
# Running is fun
if fw.dep_.endswith('subj'):
return 0.0
fc = [c for c in doc.noun_chunks]
# Dancing boys can never sing
if str(fw) in str(fc):
return 0.0
positive_prob = models['participle'].predict([_text_to_vector(sentence,
trigram2idx['participle'], trigram_count['participle'])])[0][1]
return float(positive_prob) | python | def is_participle_clause_fragment(sentence):
"""Supply a sentence or fragment and recieve a confidence interval"""
# short circuit if sentence or fragment doesn't start with a participle
# past participles can sometimes look like adjectives -- ie, Tired
if not _begins_with_one_of(sentence, ['VBG', 'VBN', 'JJ']):
return 0.0
if _begins_with_one_of(sentence, ['JJ']):
doc = nlp(sentence)
fw = [w for w in doc][0]
# Beautiful toy birds
if fw.dep_ == 'amod':
return 0.0
# short circuit if sentence starts with a gerund and the gerund is the
# subject.
if _begins_with_one_of(sentence, ['VBG']):
doc = nlp(sentence)
fw = [w for w in doc][0]
# Running is fun
if fw.dep_.endswith('subj'):
return 0.0
fc = [c for c in doc.noun_chunks]
# Dancing boys can never sing
if str(fw) in str(fc):
return 0.0
positive_prob = models['participle'].predict([_text_to_vector(sentence,
trigram2idx['participle'], trigram_count['participle'])])[0][1]
return float(positive_prob) | [
"def",
"is_participle_clause_fragment",
"(",
"sentence",
")",
":",
"# short circuit if sentence or fragment doesn't start with a participle",
"# past participles can sometimes look like adjectives -- ie, Tired",
"if",
"not",
"_begins_with_one_of",
"(",
"sentence",
",",
"[",
"'VBG'",
... | Supply a sentence or fragment and recieve a confidence interval | [
"Supply",
"a",
"sentence",
"or",
"fragment",
"and",
"recieve",
"a",
"confidence",
"interval"
] | f2ff579ddf3a556d9cdc47c5f702422fa06863d9 | https://github.com/empirical-org/Quill-NLP-Tools-and-Datasets/blob/f2ff579ddf3a556d9cdc47c5f702422fa06863d9/utils/qfragment/qfragment/__init__.py#L147-L178 | train | 24,679 |
empirical-org/Quill-NLP-Tools-and-Datasets | utils/qfragment/qfragment/__init__.py | check | def check(sentence):
"""Supply a sentence or fragment and recieve feedback"""
# How we decide what to put as the human readable feedback
#
# Our order of prefence is,
#
# 1. Spelling errors.
# - A spelling error can change the sentence meaning
# 2. Subject-verb agreement errors
# 3. Subordinate conjunction starting a sentence
# 4. Participle phrase fragment
# 5. Other errors
result = Feedback()
is_missing_verb = detect_missing_verb(sentence)
is_infinitive = detect_infinitive_phrase(sentence)
is_participle = is_participle_clause_fragment(sentence)
lang_tool_feedback = get_language_tool_feedback(sentence)
subject_and_verb_agree = get_subject_verb_agreement_feedback(sentence)
####
if is_missing_verb: # Lowest priority
result.matches['missing_verb'] = True
result.human_readable = MISSING_VERB_ADVICE.replace('\n', '')
result.primary_error = 'MISSING_VERB_ERROR'
result.specific_error = 'MISSING_VERB'
if is_participle > .5:
result.matches['participle_phrase'] = is_participle
result.human_readable = PARTICIPLE_FRAGMENT_ADVICE.replace('\n', '')
result.primary_error = 'FRAGMENT_ERROR'
result.specific_error = 'PARTICIPLE_PHRASE'
if lang_tool_feedback:
result.matches['lang_tool'] = lang_tool_feedback
for ltf in lang_tool_feedback:
if ltf['rule']['id'] == 'SENTENCE_FRAGMENT':
result.human_readable = lang_tool_feedback[0]['message']
result.primary_error = 'FRAGMENT_ERROR'
result.specific_error = 'SUBORDINATE_CLAUSE'
if is_infinitive:
result.matches['infinitive_phrase'] = True
result.human_readable = INFINITIVE_PHRASE_ADVICE.replace('\n', '')
result.primary_error = 'INFINITIVE_PHRASE_ERROR'
result.specific_error = 'INFINITIVE_PHRASE'
if not subject_and_verb_agree:
result.matches['subject_verb_agreement'] = subject_and_verb_agree
result.human_readable = SUBJECT_VERB_AGREEMENT_ADVICE.replace('\n', '')
result.primary_error = 'SUBJECT_VERB_AGREEMENT_ERROR'
result.specific_error = 'SUBJECT_VERB_AGREEMENT'
if lang_tool_feedback: # Highest priority (spelling, other lang tool errors)
result.matches['lang_tool'] = lang_tool_feedback
for ltf in lang_tool_feedback:
if ltf['rule']['id'] == 'MORFOLOGIK_RULE_EN_US':
result.human_readable = ltf['message']
result.primary_error = 'SPELLING_ERROR'
result.specific_error = 'SPELLING_ERROR'
if not result.primary_error:
result.human_readable = ltf['message']
result.primary_error = 'OTHER_ERROR'
result.specific_error = ltf['rule']['id']
####
if not result.matches:
result.human_readable = STRONG_SENTENCE_ADVICE.replace('\n', '')
return result | python | def check(sentence):
"""Supply a sentence or fragment and recieve feedback"""
# How we decide what to put as the human readable feedback
#
# Our order of prefence is,
#
# 1. Spelling errors.
# - A spelling error can change the sentence meaning
# 2. Subject-verb agreement errors
# 3. Subordinate conjunction starting a sentence
# 4. Participle phrase fragment
# 5. Other errors
result = Feedback()
is_missing_verb = detect_missing_verb(sentence)
is_infinitive = detect_infinitive_phrase(sentence)
is_participle = is_participle_clause_fragment(sentence)
lang_tool_feedback = get_language_tool_feedback(sentence)
subject_and_verb_agree = get_subject_verb_agreement_feedback(sentence)
####
if is_missing_verb: # Lowest priority
result.matches['missing_verb'] = True
result.human_readable = MISSING_VERB_ADVICE.replace('\n', '')
result.primary_error = 'MISSING_VERB_ERROR'
result.specific_error = 'MISSING_VERB'
if is_participle > .5:
result.matches['participle_phrase'] = is_participle
result.human_readable = PARTICIPLE_FRAGMENT_ADVICE.replace('\n', '')
result.primary_error = 'FRAGMENT_ERROR'
result.specific_error = 'PARTICIPLE_PHRASE'
if lang_tool_feedback:
result.matches['lang_tool'] = lang_tool_feedback
for ltf in lang_tool_feedback:
if ltf['rule']['id'] == 'SENTENCE_FRAGMENT':
result.human_readable = lang_tool_feedback[0]['message']
result.primary_error = 'FRAGMENT_ERROR'
result.specific_error = 'SUBORDINATE_CLAUSE'
if is_infinitive:
result.matches['infinitive_phrase'] = True
result.human_readable = INFINITIVE_PHRASE_ADVICE.replace('\n', '')
result.primary_error = 'INFINITIVE_PHRASE_ERROR'
result.specific_error = 'INFINITIVE_PHRASE'
if not subject_and_verb_agree:
result.matches['subject_verb_agreement'] = subject_and_verb_agree
result.human_readable = SUBJECT_VERB_AGREEMENT_ADVICE.replace('\n', '')
result.primary_error = 'SUBJECT_VERB_AGREEMENT_ERROR'
result.specific_error = 'SUBJECT_VERB_AGREEMENT'
if lang_tool_feedback: # Highest priority (spelling, other lang tool errors)
result.matches['lang_tool'] = lang_tool_feedback
for ltf in lang_tool_feedback:
if ltf['rule']['id'] == 'MORFOLOGIK_RULE_EN_US':
result.human_readable = ltf['message']
result.primary_error = 'SPELLING_ERROR'
result.specific_error = 'SPELLING_ERROR'
if not result.primary_error:
result.human_readable = ltf['message']
result.primary_error = 'OTHER_ERROR'
result.specific_error = ltf['rule']['id']
####
if not result.matches:
result.human_readable = STRONG_SENTENCE_ADVICE.replace('\n', '')
return result | [
"def",
"check",
"(",
"sentence",
")",
":",
"# How we decide what to put as the human readable feedback",
"#",
"# Our order of prefence is,",
"#",
"# 1. Spelling errors.",
"# - A spelling error can change the sentence meaning",
"# 2. Subject-verb agreement errors",
"# 3. Subordinate conju... | Supply a sentence or fragment and recieve feedback | [
"Supply",
"a",
"sentence",
"or",
"fragment",
"and",
"recieve",
"feedback"
] | f2ff579ddf3a556d9cdc47c5f702422fa06863d9 | https://github.com/empirical-org/Quill-NLP-Tools-and-Datasets/blob/f2ff579ddf3a556d9cdc47c5f702422fa06863d9/utils/qfragment/qfragment/__init__.py#L181-L246 | train | 24,680 |
empirical-org/Quill-NLP-Tools-and-Datasets | utils/qfragment/examples/porcupine/app.py | list_submissions | def list_submissions():
"""List the past submissions with information about them"""
submissions = []
try:
submissions = session.query(Submission).all()
except SQLAlchemyError as e:
session.rollback()
return render_template('list_submissions.html', submissions=submissions) | python | def list_submissions():
"""List the past submissions with information about them"""
submissions = []
try:
submissions = session.query(Submission).all()
except SQLAlchemyError as e:
session.rollback()
return render_template('list_submissions.html', submissions=submissions) | [
"def",
"list_submissions",
"(",
")",
":",
"submissions",
"=",
"[",
"]",
"try",
":",
"submissions",
"=",
"session",
".",
"query",
"(",
"Submission",
")",
".",
"all",
"(",
")",
"except",
"SQLAlchemyError",
"as",
"e",
":",
"session",
".",
"rollback",
"(",
... | List the past submissions with information about them | [
"List",
"the",
"past",
"submissions",
"with",
"information",
"about",
"them"
] | f2ff579ddf3a556d9cdc47c5f702422fa06863d9 | https://github.com/empirical-org/Quill-NLP-Tools-and-Datasets/blob/f2ff579ddf3a556d9cdc47c5f702422fa06863d9/utils/qfragment/examples/porcupine/app.py#L49-L56 | train | 24,681 |
empirical-org/Quill-NLP-Tools-and-Datasets | utils/qfragment/examples/porcupine/app.py | get_submissions | def get_submissions():
"""API endpoint to get submissions in JSON format"""
print(request.args.to_dict())
print(request.args.get('search[value]'))
print(request.args.get('draw', 1))
# submissions = session.query(Submission).all()
if request.args.get('correct_filter', 'all') == 'all':
correct_filter = [True, False]
elif request.args['correct_filter'] == 'correct':
correct_filter = [True]
else:
correct_filter = [False]
if request.args.get('order[0][column]', '0') == '0':
column = 'id'
elif request.args['order[0][column]'] == '1':
column = 'text'
else:
column = 'primary_error'
order_str = "{} {}".format(column, request.args.get('order[0][dir]', 'desc'))
search_val = request.args.get('search[value]')
draw = request.args.get('draw', 1)
filtered_len = session.query(Submission)\
.filter(Submission.text.startswith(search_val))\
.filter(Submission.correct.in_(correct_filter))\
.count()
subs = \
session.query(Submission).filter(Submission.text.startswith(search_val))\
.filter(Submission.correct.in_(correct_filter))\
.order_by(order_str)\
.offset(request.args.get('start', 0))\
.limit(request.args.get('length', 10))\
.all()
submissions = {'draw': draw, 'recordsTotal':0, 'recordsFiltered':0, 'data':[]}
i = 0
for i, submission in enumerate(subs):
submissions['data'].append([submission.id, submission.text,
submission.primary_error, submission.correct])
submissions['recordsTotal'] = session.query(Submission).count()
submissions['recordsFiltered'] = filtered_len
return jsonify(submissions) | python | def get_submissions():
"""API endpoint to get submissions in JSON format"""
print(request.args.to_dict())
print(request.args.get('search[value]'))
print(request.args.get('draw', 1))
# submissions = session.query(Submission).all()
if request.args.get('correct_filter', 'all') == 'all':
correct_filter = [True, False]
elif request.args['correct_filter'] == 'correct':
correct_filter = [True]
else:
correct_filter = [False]
if request.args.get('order[0][column]', '0') == '0':
column = 'id'
elif request.args['order[0][column]'] == '1':
column = 'text'
else:
column = 'primary_error'
order_str = "{} {}".format(column, request.args.get('order[0][dir]', 'desc'))
search_val = request.args.get('search[value]')
draw = request.args.get('draw', 1)
filtered_len = session.query(Submission)\
.filter(Submission.text.startswith(search_val))\
.filter(Submission.correct.in_(correct_filter))\
.count()
subs = \
session.query(Submission).filter(Submission.text.startswith(search_val))\
.filter(Submission.correct.in_(correct_filter))\
.order_by(order_str)\
.offset(request.args.get('start', 0))\
.limit(request.args.get('length', 10))\
.all()
submissions = {'draw': draw, 'recordsTotal':0, 'recordsFiltered':0, 'data':[]}
i = 0
for i, submission in enumerate(subs):
submissions['data'].append([submission.id, submission.text,
submission.primary_error, submission.correct])
submissions['recordsTotal'] = session.query(Submission).count()
submissions['recordsFiltered'] = filtered_len
return jsonify(submissions) | [
"def",
"get_submissions",
"(",
")",
":",
"print",
"(",
"request",
".",
"args",
".",
"to_dict",
"(",
")",
")",
"print",
"(",
"request",
".",
"args",
".",
"get",
"(",
"'search[value]'",
")",
")",
"print",
"(",
"request",
".",
"args",
".",
"get",
"(",
... | API endpoint to get submissions in JSON format | [
"API",
"endpoint",
"to",
"get",
"submissions",
"in",
"JSON",
"format"
] | f2ff579ddf3a556d9cdc47c5f702422fa06863d9 | https://github.com/empirical-org/Quill-NLP-Tools-and-Datasets/blob/f2ff579ddf3a556d9cdc47c5f702422fa06863d9/utils/qfragment/examples/porcupine/app.py#L59-L102 | train | 24,682 |
empirical-org/Quill-NLP-Tools-and-Datasets | utils/qfragment/examples/porcupine/app.py | check_sentence | def check_sentence():
"""Sole porcupine endpoint"""
text = ''
if request.method == 'POST':
text = request.form['text']
if not text:
error = 'No input'
flash_message = error
else:
fb = check(request.form['text'])
correct = False
if request.form.get('is_correct') and not fb.primary_error:
correct = True
elif not request.form.get('is_correct') and fb.primary_error:
correct = True
sub = Submission(text=text, correct=correct, primary_error=fb.primary_error,
specific_error=fb.specific_error)
session.add(sub)
session.commit()
# TODO: remove the hack below
if not fb.primary_error:
fb.human_readable = "No errors were found."
flash_message = fb.human_readable
flash(flash_message)
return render_template('check_sentence.html', text=text) | python | def check_sentence():
"""Sole porcupine endpoint"""
text = ''
if request.method == 'POST':
text = request.form['text']
if not text:
error = 'No input'
flash_message = error
else:
fb = check(request.form['text'])
correct = False
if request.form.get('is_correct') and not fb.primary_error:
correct = True
elif not request.form.get('is_correct') and fb.primary_error:
correct = True
sub = Submission(text=text, correct=correct, primary_error=fb.primary_error,
specific_error=fb.specific_error)
session.add(sub)
session.commit()
# TODO: remove the hack below
if not fb.primary_error:
fb.human_readable = "No errors were found."
flash_message = fb.human_readable
flash(flash_message)
return render_template('check_sentence.html', text=text) | [
"def",
"check_sentence",
"(",
")",
":",
"text",
"=",
"''",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"text",
"=",
"request",
".",
"form",
"[",
"'text'",
"]",
"if",
"not",
"text",
":",
"error",
"=",
"'No input'",
"flash_message",
"=",
"error"... | Sole porcupine endpoint | [
"Sole",
"porcupine",
"endpoint"
] | f2ff579ddf3a556d9cdc47c5f702422fa06863d9 | https://github.com/empirical-org/Quill-NLP-Tools-and-Datasets/blob/f2ff579ddf3a556d9cdc47c5f702422fa06863d9/utils/qfragment/examples/porcupine/app.py#L106-L131 | train | 24,683 |
empirical-org/Quill-NLP-Tools-and-Datasets | utils/qfragment/qfragment/sva_rb2.py | raise_double_modal_error | def raise_double_modal_error(verb_phrase_doc):
"""A modal auxilary verb should not follow another modal auxilary verb"""
prev_word = None
for word in verb_phrase:
if word.tag_ == 'MD' and prev_word.tag == 'MD':
raise('DoubleModalError')
prev_word = word | python | def raise_double_modal_error(verb_phrase_doc):
"""A modal auxilary verb should not follow another modal auxilary verb"""
prev_word = None
for word in verb_phrase:
if word.tag_ == 'MD' and prev_word.tag == 'MD':
raise('DoubleModalError')
prev_word = word | [
"def",
"raise_double_modal_error",
"(",
"verb_phrase_doc",
")",
":",
"prev_word",
"=",
"None",
"for",
"word",
"in",
"verb_phrase",
":",
"if",
"word",
".",
"tag_",
"==",
"'MD'",
"and",
"prev_word",
".",
"tag",
"==",
"'MD'",
":",
"raise",
"(",
"'DoubleModalErr... | A modal auxilary verb should not follow another modal auxilary verb | [
"A",
"modal",
"auxilary",
"verb",
"should",
"not",
"follow",
"another",
"modal",
"auxilary",
"verb"
] | f2ff579ddf3a556d9cdc47c5f702422fa06863d9 | https://github.com/empirical-org/Quill-NLP-Tools-and-Datasets/blob/f2ff579ddf3a556d9cdc47c5f702422fa06863d9/utils/qfragment/qfragment/sva_rb2.py#L97-L103 | train | 24,684 |
empirical-org/Quill-NLP-Tools-and-Datasets | utils/qfragment/qfragment/sva_rb2.py | raise_modal_error | def raise_modal_error(verb_phrase_doc):
"""Given a verb phrase, raise an error if the modal auxilary has an issue
with it"""
verb_phrase = verb_phrase_doc.text.lower()
bad_strings = ['should had', 'should has', 'could had', 'could has', 'would '
'had', 'would has'] ["should", "could", "would"]
for bs in bad_strings:
if bs in verb_phrase:
raise('ShouldCouldWouldError') | python | def raise_modal_error(verb_phrase_doc):
"""Given a verb phrase, raise an error if the modal auxilary has an issue
with it"""
verb_phrase = verb_phrase_doc.text.lower()
bad_strings = ['should had', 'should has', 'could had', 'could has', 'would '
'had', 'would has'] ["should", "could", "would"]
for bs in bad_strings:
if bs in verb_phrase:
raise('ShouldCouldWouldError') | [
"def",
"raise_modal_error",
"(",
"verb_phrase_doc",
")",
":",
"verb_phrase",
"=",
"verb_phrase_doc",
".",
"text",
".",
"lower",
"(",
")",
"bad_strings",
"=",
"[",
"'should had'",
",",
"'should has'",
",",
"'could had'",
",",
"'could has'",
",",
"'would '",
"'had... | Given a verb phrase, raise an error if the modal auxilary has an issue
with it | [
"Given",
"a",
"verb",
"phrase",
"raise",
"an",
"error",
"if",
"the",
"modal",
"auxilary",
"has",
"an",
"issue",
"with",
"it"
] | f2ff579ddf3a556d9cdc47c5f702422fa06863d9 | https://github.com/empirical-org/Quill-NLP-Tools-and-Datasets/blob/f2ff579ddf3a556d9cdc47c5f702422fa06863d9/utils/qfragment/qfragment/sva_rb2.py#L106-L114 | train | 24,685 |
empirical-org/Quill-NLP-Tools-and-Datasets | utils/qfragment/qfragment/sva_rb2.py | split_infinitive_warning | def split_infinitive_warning(sentence_str):
"""Return a warning for a split infinitive, else, None"""
sent_doc = textacy.Doc(sentence_str, lang='en_core_web_lg')
inf_pattern = r'<PART><ADV><VERB>' # To aux/auxpass* csubj
infinitives = textacy.extract.pos_regex_matches(sent_doc, inf_pattern)
for inf in infinitives:
if inf[0].text.lower() != 'to':
continue
if inf[-1].tag_ != 'VB':
continue
return 'SplitInfinitiveWarning' | python | def split_infinitive_warning(sentence_str):
"""Return a warning for a split infinitive, else, None"""
sent_doc = textacy.Doc(sentence_str, lang='en_core_web_lg')
inf_pattern = r'<PART><ADV><VERB>' # To aux/auxpass* csubj
infinitives = textacy.extract.pos_regex_matches(sent_doc, inf_pattern)
for inf in infinitives:
if inf[0].text.lower() != 'to':
continue
if inf[-1].tag_ != 'VB':
continue
return 'SplitInfinitiveWarning' | [
"def",
"split_infinitive_warning",
"(",
"sentence_str",
")",
":",
"sent_doc",
"=",
"textacy",
".",
"Doc",
"(",
"sentence_str",
",",
"lang",
"=",
"'en_core_web_lg'",
")",
"inf_pattern",
"=",
"r'<PART><ADV><VERB>'",
"# To aux/auxpass* csubj",
"infinitives",
"=",
"textac... | Return a warning for a split infinitive, else, None | [
"Return",
"a",
"warning",
"for",
"a",
"split",
"infinitive",
"else",
"None"
] | f2ff579ddf3a556d9cdc47c5f702422fa06863d9 | https://github.com/empirical-org/Quill-NLP-Tools-and-Datasets/blob/f2ff579ddf3a556d9cdc47c5f702422fa06863d9/utils/qfragment/qfragment/sva_rb2.py#L234-L244 | train | 24,686 |
empirical-org/Quill-NLP-Tools-and-Datasets | utils/qfragment/qfragment/sva_rb2.py | raise_infinitive_error | def raise_infinitive_error(sentence_str):
"""Given a string, check that all infinitives are properly formatted"""
sent_doc = textacy.Doc(sentence_str, lang='en_core_web_lg')
inf_pattern = r'<PART|ADP><VERB>' # To aux/auxpass* csubj
infinitives = textacy.extract.pos_regex_matches(sent_doc, inf_pattern)
for inf in infinitives:
if inf[0].text.lower() != 'to':
continue
if inf[-1].tag_ != 'VB':
raise Exception('InfinitivePhraseError') | python | def raise_infinitive_error(sentence_str):
"""Given a string, check that all infinitives are properly formatted"""
sent_doc = textacy.Doc(sentence_str, lang='en_core_web_lg')
inf_pattern = r'<PART|ADP><VERB>' # To aux/auxpass* csubj
infinitives = textacy.extract.pos_regex_matches(sent_doc, inf_pattern)
for inf in infinitives:
if inf[0].text.lower() != 'to':
continue
if inf[-1].tag_ != 'VB':
raise Exception('InfinitivePhraseError') | [
"def",
"raise_infinitive_error",
"(",
"sentence_str",
")",
":",
"sent_doc",
"=",
"textacy",
".",
"Doc",
"(",
"sentence_str",
",",
"lang",
"=",
"'en_core_web_lg'",
")",
"inf_pattern",
"=",
"r'<PART|ADP><VERB>'",
"# To aux/auxpass* csubj",
"infinitives",
"=",
"textacy",... | Given a string, check that all infinitives are properly formatted | [
"Given",
"a",
"string",
"check",
"that",
"all",
"infinitives",
"are",
"properly",
"formatted"
] | f2ff579ddf3a556d9cdc47c5f702422fa06863d9 | https://github.com/empirical-org/Quill-NLP-Tools-and-Datasets/blob/f2ff579ddf3a556d9cdc47c5f702422fa06863d9/utils/qfragment/qfragment/sva_rb2.py#L246-L255 | train | 24,687 |
empirical-org/Quill-NLP-Tools-and-Datasets | utils/qfragment/qfragment/sva_rb2.py | drop_modifiers | def drop_modifiers(sentence_str):
"""Given a string, drop the modifiers and return a string
without them"""
tdoc = textacy.Doc(sentence_str, lang='en_core_web_lg')
new_sent = tdoc.text
unusual_char = '形'
for tag in tdoc:
if tag.dep_.endswith('mod'):
# Replace the tag
new_sent = new_sent[:tag.idx] + unusual_char * len(tag.text) +\
new_sent[tag.idx + len(tag.text):]
new_sent = new_sent.replace(unusual_char, '')
new_sent = textacy.preprocess.normalize_whitespace(new_sent)
return new_sent | python | def drop_modifiers(sentence_str):
"""Given a string, drop the modifiers and return a string
without them"""
tdoc = textacy.Doc(sentence_str, lang='en_core_web_lg')
new_sent = tdoc.text
unusual_char = '形'
for tag in tdoc:
if tag.dep_.endswith('mod'):
# Replace the tag
new_sent = new_sent[:tag.idx] + unusual_char * len(tag.text) +\
new_sent[tag.idx + len(tag.text):]
new_sent = new_sent.replace(unusual_char, '')
new_sent = textacy.preprocess.normalize_whitespace(new_sent)
return new_sent | [
"def",
"drop_modifiers",
"(",
"sentence_str",
")",
":",
"tdoc",
"=",
"textacy",
".",
"Doc",
"(",
"sentence_str",
",",
"lang",
"=",
"'en_core_web_lg'",
")",
"new_sent",
"=",
"tdoc",
".",
"text",
"unusual_char",
"=",
"'形'",
"for",
"tag",
"in",
"tdoc",
":",
... | Given a string, drop the modifiers and return a string
without them | [
"Given",
"a",
"string",
"drop",
"the",
"modifiers",
"and",
"return",
"a",
"string",
"without",
"them"
] | f2ff579ddf3a556d9cdc47c5f702422fa06863d9 | https://github.com/empirical-org/Quill-NLP-Tools-and-Datasets/blob/f2ff579ddf3a556d9cdc47c5f702422fa06863d9/utils/qfragment/qfragment/sva_rb2.py#L258-L271 | train | 24,688 |
empirical-org/Quill-NLP-Tools-and-Datasets | quillnlp/cluster.py | cluster | def cluster(list_of_texts, num_clusters=3):
"""
Cluster a list of texts into a predefined number of clusters.
:param list_of_texts: a list of untokenized texts
:param num_clusters: the predefined number of clusters
:return: a list with the cluster id for each text, e.g. [0,1,0,0,2,2,1]
"""
pipeline = Pipeline([
("vect", CountVectorizer()),
("tfidf", TfidfTransformer()),
("clust", KMeans(n_clusters=num_clusters))
])
try:
clusters = pipeline.fit_predict(list_of_texts)
except ValueError:
clusters = list(range(len(list_of_texts)))
return clusters | python | def cluster(list_of_texts, num_clusters=3):
"""
Cluster a list of texts into a predefined number of clusters.
:param list_of_texts: a list of untokenized texts
:param num_clusters: the predefined number of clusters
:return: a list with the cluster id for each text, e.g. [0,1,0,0,2,2,1]
"""
pipeline = Pipeline([
("vect", CountVectorizer()),
("tfidf", TfidfTransformer()),
("clust", KMeans(n_clusters=num_clusters))
])
try:
clusters = pipeline.fit_predict(list_of_texts)
except ValueError:
clusters = list(range(len(list_of_texts)))
return clusters | [
"def",
"cluster",
"(",
"list_of_texts",
",",
"num_clusters",
"=",
"3",
")",
":",
"pipeline",
"=",
"Pipeline",
"(",
"[",
"(",
"\"vect\"",
",",
"CountVectorizer",
"(",
")",
")",
",",
"(",
"\"tfidf\"",
",",
"TfidfTransformer",
"(",
")",
")",
",",
"(",
"\"... | Cluster a list of texts into a predefined number of clusters.
:param list_of_texts: a list of untokenized texts
:param num_clusters: the predefined number of clusters
:return: a list with the cluster id for each text, e.g. [0,1,0,0,2,2,1] | [
"Cluster",
"a",
"list",
"of",
"texts",
"into",
"a",
"predefined",
"number",
"of",
"clusters",
"."
] | f2ff579ddf3a556d9cdc47c5f702422fa06863d9 | https://github.com/empirical-org/Quill-NLP-Tools-and-Datasets/blob/f2ff579ddf3a556d9cdc47c5f702422fa06863d9/quillnlp/cluster.py#L6-L25 | train | 24,689 |
empirical-org/Quill-NLP-Tools-and-Datasets | quillnlp/topics.py | find_topics | def find_topics(token_lists, num_topics=10):
""" Find the topics in a list of texts with Latent Dirichlet Allocation. """
dictionary = Dictionary(token_lists)
print('Number of unique words in original documents:', len(dictionary))
dictionary.filter_extremes(no_below=2, no_above=0.7)
print('Number of unique words after removing rare and common words:', len(dictionary))
corpus = [dictionary.doc2bow(tokens) for tokens in token_lists]
model = LdaModel(corpus=corpus, id2word=dictionary, num_topics=num_topics, chunksize=100, passes=5, random_state=1)
print_topics(model)
return model, dictionary | python | def find_topics(token_lists, num_topics=10):
""" Find the topics in a list of texts with Latent Dirichlet Allocation. """
dictionary = Dictionary(token_lists)
print('Number of unique words in original documents:', len(dictionary))
dictionary.filter_extremes(no_below=2, no_above=0.7)
print('Number of unique words after removing rare and common words:', len(dictionary))
corpus = [dictionary.doc2bow(tokens) for tokens in token_lists]
model = LdaModel(corpus=corpus, id2word=dictionary, num_topics=num_topics, chunksize=100, passes=5, random_state=1)
print_topics(model)
return model, dictionary | [
"def",
"find_topics",
"(",
"token_lists",
",",
"num_topics",
"=",
"10",
")",
":",
"dictionary",
"=",
"Dictionary",
"(",
"token_lists",
")",
"print",
"(",
"'Number of unique words in original documents:'",
",",
"len",
"(",
"dictionary",
")",
")",
"dictionary",
".",... | Find the topics in a list of texts with Latent Dirichlet Allocation. | [
"Find",
"the",
"topics",
"in",
"a",
"list",
"of",
"texts",
"with",
"Latent",
"Dirichlet",
"Allocation",
"."
] | f2ff579ddf3a556d9cdc47c5f702422fa06863d9 | https://github.com/empirical-org/Quill-NLP-Tools-and-Datasets/blob/f2ff579ddf3a556d9cdc47c5f702422fa06863d9/quillnlp/topics.py#L14-L27 | train | 24,690 |
empirical-org/Quill-NLP-Tools-and-Datasets | scrapers/gutenfetch/gutenfetch/__init__.py | fetch_bookshelf | def fetch_bookshelf(start_url, output_dir):
"""Fetch all the books off of a gutenberg project bookshelf page
example bookshelf page,
http://www.gutenberg.org/wiki/Children%27s_Fiction_(Bookshelf)
"""
# make output directory
try:
os.mkdir(OUTPUT_DIR + output_dir)
except OSError as e:
raise(e)
# fetch page
r = requests.get(start_url)
# extract links
soup = bs(r.text, 'html.parser')
book_links = soup.find_all(class_=re.compile("extiw"))
new_links = []
for el in book_links:
link = el['href']
title = el.text
bookid = link.split('/')[-1]
if bookid.isdigit():
new_link = NEW_LINK_BASE.format(bookid, bookid)
new_links.append([title, new_link])
# save links as books
for link_tup in new_links:
time.sleep(.10) # be nice to project gutenberg
r1 = requests.get(link_tup[1])
new_filename = link_tup[0].lower().replace(' ', '-').replace('\n',
'-')
new_new_filename = ''
for char in new_filename:
if char in 'abcdefghijklmnopqrstuvwxyz-':
new_new_filename += char
new_filename = new_new_filename[:MAX_FILENAME_LEN] + '.txt'
with open(OUTPUT_DIR + output_dir + '/' + new_filename, 'w+') as output_file:
output_file.write(r1.text)
return None | python | def fetch_bookshelf(start_url, output_dir):
"""Fetch all the books off of a gutenberg project bookshelf page
example bookshelf page,
http://www.gutenberg.org/wiki/Children%27s_Fiction_(Bookshelf)
"""
# make output directory
try:
os.mkdir(OUTPUT_DIR + output_dir)
except OSError as e:
raise(e)
# fetch page
r = requests.get(start_url)
# extract links
soup = bs(r.text, 'html.parser')
book_links = soup.find_all(class_=re.compile("extiw"))
new_links = []
for el in book_links:
link = el['href']
title = el.text
bookid = link.split('/')[-1]
if bookid.isdigit():
new_link = NEW_LINK_BASE.format(bookid, bookid)
new_links.append([title, new_link])
# save links as books
for link_tup in new_links:
time.sleep(.10) # be nice to project gutenberg
r1 = requests.get(link_tup[1])
new_filename = link_tup[0].lower().replace(' ', '-').replace('\n',
'-')
new_new_filename = ''
for char in new_filename:
if char in 'abcdefghijklmnopqrstuvwxyz-':
new_new_filename += char
new_filename = new_new_filename[:MAX_FILENAME_LEN] + '.txt'
with open(OUTPUT_DIR + output_dir + '/' + new_filename, 'w+') as output_file:
output_file.write(r1.text)
return None | [
"def",
"fetch_bookshelf",
"(",
"start_url",
",",
"output_dir",
")",
":",
"# make output directory",
"try",
":",
"os",
".",
"mkdir",
"(",
"OUTPUT_DIR",
"+",
"output_dir",
")",
"except",
"OSError",
"as",
"e",
":",
"raise",
"(",
"e",
")",
"# fetch page",
"r",
... | Fetch all the books off of a gutenberg project bookshelf page
example bookshelf page,
http://www.gutenberg.org/wiki/Children%27s_Fiction_(Bookshelf) | [
"Fetch",
"all",
"the",
"books",
"off",
"of",
"a",
"gutenberg",
"project",
"bookshelf",
"page"
] | f2ff579ddf3a556d9cdc47c5f702422fa06863d9 | https://github.com/empirical-org/Quill-NLP-Tools-and-Datasets/blob/f2ff579ddf3a556d9cdc47c5f702422fa06863d9/scrapers/gutenfetch/gutenfetch/__init__.py#L23-L64 | train | 24,691 |
empirical-org/Quill-NLP-Tools-and-Datasets | quillnlp/preprocess.py | lemmatize | def lemmatize(text, lowercase=True, remove_stopwords=True):
""" Return the lemmas of the tokens in a text. """
doc = nlp(text)
if lowercase and remove_stopwords:
lemmas = [t.lemma_.lower() for t in doc if not (t.is_stop or t.orth_.lower() in STOPWORDS)]
elif lowercase:
lemmas = [t.lemma_.lower() for t in doc]
elif remove_stopwords:
lemmas = [t.lemma_ for t in doc if not (t.is_stop or t.orth_.lower() in STOPWORDS)]
else:
lemmas = [t.lemma_ for t in doc]
return lemmas | python | def lemmatize(text, lowercase=True, remove_stopwords=True):
""" Return the lemmas of the tokens in a text. """
doc = nlp(text)
if lowercase and remove_stopwords:
lemmas = [t.lemma_.lower() for t in doc if not (t.is_stop or t.orth_.lower() in STOPWORDS)]
elif lowercase:
lemmas = [t.lemma_.lower() for t in doc]
elif remove_stopwords:
lemmas = [t.lemma_ for t in doc if not (t.is_stop or t.orth_.lower() in STOPWORDS)]
else:
lemmas = [t.lemma_ for t in doc]
return lemmas | [
"def",
"lemmatize",
"(",
"text",
",",
"lowercase",
"=",
"True",
",",
"remove_stopwords",
"=",
"True",
")",
":",
"doc",
"=",
"nlp",
"(",
"text",
")",
"if",
"lowercase",
"and",
"remove_stopwords",
":",
"lemmas",
"=",
"[",
"t",
".",
"lemma_",
".",
"lower"... | Return the lemmas of the tokens in a text. | [
"Return",
"the",
"lemmas",
"of",
"the",
"tokens",
"in",
"a",
"text",
"."
] | f2ff579ddf3a556d9cdc47c5f702422fa06863d9 | https://github.com/empirical-org/Quill-NLP-Tools-and-Datasets/blob/f2ff579ddf3a556d9cdc47c5f702422fa06863d9/quillnlp/preprocess.py#L8-L20 | train | 24,692 |
empirical-org/Quill-NLP-Tools-and-Datasets | utils/qfragment/qfragment/sva.py | inflate | def inflate(deflated_vector):
"""Given a defalated vector, inflate it into a np array and return it"""
dv = json.loads(deflated_vector)
#result = np.zeros(dv['reductions']) # some claim vector length 5555, others
#5530. this could have occurred doing remote computations? or something.
# anyhow, we will use 5555. Let's just hard code it. Gosh darnit.
result = np.zeros(5555) # some claim vector length 5555, others
for n in dv['indices']:
result[int(n)] = dv['indices'][n]
#print("Inflated vector. Length", len(result))
return result | python | def inflate(deflated_vector):
"""Given a defalated vector, inflate it into a np array and return it"""
dv = json.loads(deflated_vector)
#result = np.zeros(dv['reductions']) # some claim vector length 5555, others
#5530. this could have occurred doing remote computations? or something.
# anyhow, we will use 5555. Let's just hard code it. Gosh darnit.
result = np.zeros(5555) # some claim vector length 5555, others
for n in dv['indices']:
result[int(n)] = dv['indices'][n]
#print("Inflated vector. Length", len(result))
return result | [
"def",
"inflate",
"(",
"deflated_vector",
")",
":",
"dv",
"=",
"json",
".",
"loads",
"(",
"deflated_vector",
")",
"#result = np.zeros(dv['reductions']) # some claim vector length 5555, others",
"#5530. this could have occurred doing remote computations? or something.",
"# anyhow, we ... | Given a defalated vector, inflate it into a np array and return it | [
"Given",
"a",
"defalated",
"vector",
"inflate",
"it",
"into",
"a",
"np",
"array",
"and",
"return",
"it"
] | f2ff579ddf3a556d9cdc47c5f702422fa06863d9 | https://github.com/empirical-org/Quill-NLP-Tools-and-Datasets/blob/f2ff579ddf3a556d9cdc47c5f702422fa06863d9/utils/qfragment/qfragment/sva.py#L25-L35 | train | 24,693 |
empirical-org/Quill-NLP-Tools-and-Datasets | utils/qfragment/qfragment/sva.py | text_to_vector | def text_to_vector(sent_str):
"""Given a string, get it's defalted vector, inflate it, then return the
inflated vector"""
r = requests.get("{}/sva/vector".format(VECTORIZE_API), params={'s':sent_str})
return inflate(r.text) | python | def text_to_vector(sent_str):
"""Given a string, get it's defalted vector, inflate it, then return the
inflated vector"""
r = requests.get("{}/sva/vector".format(VECTORIZE_API), params={'s':sent_str})
return inflate(r.text) | [
"def",
"text_to_vector",
"(",
"sent_str",
")",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"\"{}/sva/vector\"",
".",
"format",
"(",
"VECTORIZE_API",
")",
",",
"params",
"=",
"{",
"'s'",
":",
"sent_str",
"}",
")",
"return",
"inflate",
"(",
"r",
".",
"te... | Given a string, get it's defalted vector, inflate it, then return the
inflated vector | [
"Given",
"a",
"string",
"get",
"it",
"s",
"defalted",
"vector",
"inflate",
"it",
"then",
"return",
"the",
"inflated",
"vector"
] | f2ff579ddf3a556d9cdc47c5f702422fa06863d9 | https://github.com/empirical-org/Quill-NLP-Tools-and-Datasets/blob/f2ff579ddf3a556d9cdc47c5f702422fa06863d9/utils/qfragment/qfragment/sva.py#L37-L41 | train | 24,694 |
empirical-org/Quill-NLP-Tools-and-Datasets | utils/qfragment/qfragment/infinitive_phrase_detect.py | detect_missing_verb | def detect_missing_verb(sentence):
"""Return True if the sentence appears to be missing a main verb"""
# TODO: should this be relocated?
doc = nlp(sentence)
for w in doc:
if w.tag_.startswith('VB') and w.dep_ == 'ROOT':
return False # looks like there is at least 1 main verb
return True | python | def detect_missing_verb(sentence):
"""Return True if the sentence appears to be missing a main verb"""
# TODO: should this be relocated?
doc = nlp(sentence)
for w in doc:
if w.tag_.startswith('VB') and w.dep_ == 'ROOT':
return False # looks like there is at least 1 main verb
return True | [
"def",
"detect_missing_verb",
"(",
"sentence",
")",
":",
"# TODO: should this be relocated?",
"doc",
"=",
"nlp",
"(",
"sentence",
")",
"for",
"w",
"in",
"doc",
":",
"if",
"w",
".",
"tag_",
".",
"startswith",
"(",
"'VB'",
")",
"and",
"w",
".",
"dep_",
"==... | Return True if the sentence appears to be missing a main verb | [
"Return",
"True",
"if",
"the",
"sentence",
"appears",
"to",
"be",
"missing",
"a",
"main",
"verb"
] | f2ff579ddf3a556d9cdc47c5f702422fa06863d9 | https://github.com/empirical-org/Quill-NLP-Tools-and-Datasets/blob/f2ff579ddf3a556d9cdc47c5f702422fa06863d9/utils/qfragment/qfragment/infinitive_phrase_detect.py#L12-L19 | train | 24,695 |
empirical-org/Quill-NLP-Tools-and-Datasets | utils/qfragment/qfragment/infinitive_phrase_detect.py | detect_infinitive_phrase | def detect_infinitive_phrase(sentence):
"""Given a string, return true if it is an infinitive phrase fragment"""
# eliminate sentences without to
if not 'to' in sentence.lower():
return False
doc = nlp(sentence)
prev_word = None
for w in doc:
# if statement will execute exactly once
if prev_word == 'to':
if w.dep_ == 'ROOT' and w.tag_.startswith('VB'):
return True # this is quite likely to be an infinitive phrase
else:
return False
prev_word = w.text.lower() | python | def detect_infinitive_phrase(sentence):
"""Given a string, return true if it is an infinitive phrase fragment"""
# eliminate sentences without to
if not 'to' in sentence.lower():
return False
doc = nlp(sentence)
prev_word = None
for w in doc:
# if statement will execute exactly once
if prev_word == 'to':
if w.dep_ == 'ROOT' and w.tag_.startswith('VB'):
return True # this is quite likely to be an infinitive phrase
else:
return False
prev_word = w.text.lower() | [
"def",
"detect_infinitive_phrase",
"(",
"sentence",
")",
":",
"# eliminate sentences without to",
"if",
"not",
"'to'",
"in",
"sentence",
".",
"lower",
"(",
")",
":",
"return",
"False",
"doc",
"=",
"nlp",
"(",
"sentence",
")",
"prev_word",
"=",
"None",
"for",
... | Given a string, return true if it is an infinitive phrase fragment | [
"Given",
"a",
"string",
"return",
"true",
"if",
"it",
"is",
"an",
"infinitive",
"phrase",
"fragment"
] | f2ff579ddf3a556d9cdc47c5f702422fa06863d9 | https://github.com/empirical-org/Quill-NLP-Tools-and-Datasets/blob/f2ff579ddf3a556d9cdc47c5f702422fa06863d9/utils/qfragment/qfragment/infinitive_phrase_detect.py#L21-L37 | train | 24,696 |
empirical-org/Quill-NLP-Tools-and-Datasets | quillnlp/srl.py | perform_srl | def perform_srl(responses, prompt):
""" Perform semantic role labeling on a list of responses, given a prompt."""
predictor = Predictor.from_path("https://s3-us-west-2.amazonaws.com/allennlp/models/srl-model-2018.05.25.tar.gz")
sentences = [{"sentence": prompt + " " + response} for response in responses]
output = predictor.predict_batch_json(sentences)
full_output = [{"sentence": prompt + response,
"response": response,
"srl": srl} for (response, srl) in zip(responses, output)]
return full_output | python | def perform_srl(responses, prompt):
""" Perform semantic role labeling on a list of responses, given a prompt."""
predictor = Predictor.from_path("https://s3-us-west-2.amazonaws.com/allennlp/models/srl-model-2018.05.25.tar.gz")
sentences = [{"sentence": prompt + " " + response} for response in responses]
output = predictor.predict_batch_json(sentences)
full_output = [{"sentence": prompt + response,
"response": response,
"srl": srl} for (response, srl) in zip(responses, output)]
return full_output | [
"def",
"perform_srl",
"(",
"responses",
",",
"prompt",
")",
":",
"predictor",
"=",
"Predictor",
".",
"from_path",
"(",
"\"https://s3-us-west-2.amazonaws.com/allennlp/models/srl-model-2018.05.25.tar.gz\"",
")",
"sentences",
"=",
"[",
"{",
"\"sentence\"",
":",
"prompt",
"... | Perform semantic role labeling on a list of responses, given a prompt. | [
"Perform",
"semantic",
"role",
"labeling",
"on",
"a",
"list",
"of",
"responses",
"given",
"a",
"prompt",
"."
] | f2ff579ddf3a556d9cdc47c5f702422fa06863d9 | https://github.com/empirical-org/Quill-NLP-Tools-and-Datasets/blob/f2ff579ddf3a556d9cdc47c5f702422fa06863d9/quillnlp/srl.py#L4-L16 | train | 24,697 |
empirical-org/Quill-NLP-Tools-and-Datasets | quillnlp/utils.py | detokenize | def detokenize(s):
""" Detokenize a string by removing spaces before punctuation."""
print(s)
s = re.sub("\s+([;:,\.\?!])", "\\1", s)
s = re.sub("\s+(n't)", "\\1", s)
return s | python | def detokenize(s):
""" Detokenize a string by removing spaces before punctuation."""
print(s)
s = re.sub("\s+([;:,\.\?!])", "\\1", s)
s = re.sub("\s+(n't)", "\\1", s)
return s | [
"def",
"detokenize",
"(",
"s",
")",
":",
"print",
"(",
"s",
")",
"s",
"=",
"re",
".",
"sub",
"(",
"\"\\s+([;:,\\.\\?!])\"",
",",
"\"\\\\1\"",
",",
"s",
")",
"s",
"=",
"re",
".",
"sub",
"(",
"\"\\s+(n't)\"",
",",
"\"\\\\1\"",
",",
"s",
")",
"return"... | Detokenize a string by removing spaces before punctuation. | [
"Detokenize",
"a",
"string",
"by",
"removing",
"spaces",
"before",
"punctuation",
"."
] | f2ff579ddf3a556d9cdc47c5f702422fa06863d9 | https://github.com/empirical-org/Quill-NLP-Tools-and-Datasets/blob/f2ff579ddf3a556d9cdc47c5f702422fa06863d9/quillnlp/utils.py#L4-L9 | train | 24,698 |
ejeschke/ginga | ginga/misc/Task.py | Task.start | def start(self):
"""This method starts a task executing and returns immediately.
Subclass should override this method, if it has an asynchronous
way to start the task and return immediately.
"""
if self.threadPool:
self.threadPool.addTask(self)
# Lets other threads have a chance to run
time.sleep(0)
else:
raise TaskError("start(): nothing to start for task %s" % self) | python | def start(self):
"""This method starts a task executing and returns immediately.
Subclass should override this method, if it has an asynchronous
way to start the task and return immediately.
"""
if self.threadPool:
self.threadPool.addTask(self)
# Lets other threads have a chance to run
time.sleep(0)
else:
raise TaskError("start(): nothing to start for task %s" % self) | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"threadPool",
":",
"self",
".",
"threadPool",
".",
"addTask",
"(",
"self",
")",
"# Lets other threads have a chance to run",
"time",
".",
"sleep",
"(",
"0",
")",
"else",
":",
"raise",
"TaskError",
"... | This method starts a task executing and returns immediately.
Subclass should override this method, if it has an asynchronous
way to start the task and return immediately. | [
"This",
"method",
"starts",
"a",
"task",
"executing",
"and",
"returns",
"immediately",
".",
"Subclass",
"should",
"override",
"this",
"method",
"if",
"it",
"has",
"an",
"asynchronous",
"way",
"to",
"start",
"the",
"task",
"and",
"return",
"immediately",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/misc/Task.py#L114-L125 | train | 24,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.