content stringlengths 27 928k | path stringlengths 4 230 | size int64 27 928k | nl_text stringlengths 21 396k | nl_size int64 21 396k | nl_language stringlengths 2 3 | nl_language_score float64 0.04 1 |
|---|---|---|---|---|---|---|
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
#SESSION_COOKIE_SECURE = True
SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess'
| config.py | 186 | SESSION_COOKIE_SECURE = True | 28 | es | 0.121752 |
"""
DIRBS module for utility classes and functions.
Copyright (c) 2018 Qualcomm Technologies, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the
limitations in the disclaimer below) provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following
disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Qualcomm Technologies, Inc. nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written permission.
NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY
THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
"""
import datetime
import logging
import hashlib
import json
import time
import copy
import io
import contextlib
import psycopg2
from psycopg2 import sql
from psycopg2.extras import NamedTupleCursor
from dirbs import db_schema_version as code_db_schema_version
import dirbs.metadata as metadata
from dirbs.config import ConfigParseException
class DatabaseSchemaException(Exception):
"""Custom exception class to indicate there was a problem validating the schema."""
def __init__(self, msg):
"""Constructor."""
super().__init__('DB schema check failure: {0}'.format(msg))
class DatabaseRoleCheckException(Exception):
"""Custom exception class to indicate the user does not have the correct roles for this job."""
def __init__(self, msg):
"""Constructor."""
super().__init__('DB role check failure: {0}'.format(msg))
class JSONEncoder(json.JSONEncoder):
"""Custom JSONEncoder class which serializes dates in ISO format."""
def default(self, obj):
"""Overrides JSONEncoder.default."""
if isinstance(obj, datetime.date):
return obj.isoformat()
return JSONEncoder.default(self, obj)
class LoggingNamedTupleCursor(NamedTupleCursor):
"""Named tuple cursor that logs to DIRBS."""
def __init__(self, *args, **kwargs):
"""Constructor."""
super().__init__(*args, **kwargs)
if self.name is not None:
# Default itersize to 100000 for named cursors
self.itersize = 100000
def execute(self, query, params=None):
"""Overrides NamedTupleCursor.execute."""
try:
return super(LoggingNamedTupleCursor, self).execute(query, params)
finally:
if self.query is not None:
logging.getLogger('dirbs.sql').log(logging.DEBUG, str(self.query, encoding='utf-8'))
def callproc(self, procname, params=None):
"""Overrides NamedTupleCursor.callproc."""
try:
return super(LoggingNamedTupleCursor, self).callproc(procname, params)
finally:
if self.query is not None:
logging.getLogger('dirbs.sql').log(logging.DEBUG, str(self.query, encoding='utf-8'))
@contextlib.contextmanager
def db_role_setter(conn, *, role_name):
"""Since we catch exceptions here and log, temporarily install a customised hook."""
with conn.cursor() as cursor:
cursor.execute('SHOW ROLE')
old_role = cursor.fetchone()[0]
cursor.execute('SET ROLE %s', [role_name])
yield role_name
cursor.execute('SET ROLE %s', [old_role])
class CodeProfiler(object):
"""Profile a block of code and store duration."""
def __enter__(self):
"""Python context manager support for use in with statement (on enter)."""
self.start = time.time()
return self
def __exit__(self, *args):
"""Python context manager support for use in with statement (on exit)."""
self.duration = int((time.time() - self.start) * 1000)
def compute_md5_hash(file, buf_size=65536):
"""Utility method to generate a md5 hash of file."""
md5_hash = hashlib.md5()
while True:
data = file.read(buf_size)
if not data:
break
md5_hash.update(data)
return md5_hash.hexdigest()
def cachebusted_filename_from_contents(byte_array):
"""Utility method to generate a unique filename based on the hash of a given content array (of bytes)."""
return compute_md5_hash(io.BytesIO(byte_array))[:8]
def cli_db_params_from_dsn(dsn, user=None, database=None, port=None, host=None):
"""Convert DB-related command-line arguments from a DSN into a format appropriate for DIRBS CLI commands."""
db_args = []
db_args.append('--db-user={0}'.format(user if user is not None else dsn.get('user')))
db_args.append('--db-name={0}'.format(database if database is not None else dsn.get('database')))
db_args.append('--db-port={0}'.format(port if port is not None else dsn.get('port')))
db_args.append('--db-host={0}'.format(host if host is not None else dsn.get('host')))
return db_args
def create_db_connection(db_config, readonly=False, autocommit=False):
"""Creates a DB connection to the database.
Imports the config module, which results in the config being read from disk.
Changes to the config file made after this method has been called will not be read.
Calling entity should handle connection errors as appropriate.
"""
logger = logging.getLogger('dirbs.sql')
logger.debug('Attempting to connect to the database {0} on host {1}'.format(db_config.database, db_config.host))
# We hard-code 4 minutes idle keepalives, which is fairly aggressive, to avoid disconnections on VPNs, etc.
conn = psycopg2.connect('{0} keepalives=1 keepalives_idle=240'.format(db_config.connection_string),
cursor_factory=LoggingNamedTupleCursor)
conn.set_session(readonly=readonly, autocommit=autocommit)
logger.debug('Connection to database successful.')
return conn
def verify_db_schema(conn, required_role):
"""Function that runs all DB verification checks."""
warn_if_db_superuser(conn)
verify_db_roles_installed(conn)
verify_db_role_for_job(conn, required_role)
verify_db_schema_version(conn)
verify_db_ownership(conn)
verify_hll_schema(conn)
verify_core_schema(conn)
verify_db_search_path(conn)
def warn_if_db_superuser(conn):
"""Warn if the current DB user is a PostgreSQL superuser."""
logger = logging.getLogger('dirbs.db')
if is_db_user_superuser(conn):
logger.warn('Running as PostgreSQL superuser -- for security reasons, we recommend running all '
'DIRBS tasks as a normal user')
def verify_db_roles_installed(conn):
"""Function used to verify whether roles have been installed in the DB."""
# The below is not a guaranteed check, but a heuristic
logger = logging.getLogger('dirbs.db')
with conn.cursor() as cursor:
cursor.execute('SELECT 1 AS res FROM pg_roles WHERE rolname = \'dirbs_core_power_user\'')
if cursor.fetchone() is None:
logger.error('DIRBS Core roles have not been installed - run \'dirbs-db install_roles\' before '
'running \'dirbs-db install\'')
raise DatabaseSchemaException('DIRBS Core database roles have not been installed')
def verify_db_role_for_job(conn, expected_role):
"""Function used to verify that the current DB user is in the role expected for this job."""
if not is_db_user_dirbs_role(conn, expected_role):
role = conn.get_dsn_parameters().get('user')
raise DatabaseRoleCheckException('Current DB user {0} does not have required role: {1}. To fix this:'
'\n\t1. GRANT {1} TO {0};'.format(role, expected_role))
def verify_db_schema_version(conn):
"""Function used to check whether the DB schema version matches the code schema version."""
logger = logging.getLogger('dirbs.db')
version = query_db_schema_version(conn)
if version != code_db_schema_version:
if version is None:
logger.error('DB schema has not been installed via dirbs-db install!')
raise DatabaseSchemaException('No DB schema installed - perform a dirbs-db install first!')
else:
logger.error('DB schema version does not match code!')
logger.error('Code schema version: %d', code_db_schema_version)
logger.error('DB schema version: %d', version)
raise DatabaseSchemaException('Mismatch between code and DB schema versions - perform a dirbs-db upgrade!')
def verify_db_ownership(conn):
"""Function used to check whether DB ownership matches what we expect."""
logger = logging.getLogger('dirbs.db')
if query_db_ownership(conn) != 'dirbs_core_power_user':
logger.error('Database is not owned by the dirbs_core_power_user group! Please the '
'following as the current DB owner (whilst logged into the database):'
'\n\tALTER DATABASE <database> OWNER TO dirbs_core_power_user;')
raise DatabaseSchemaException('Incorrect database ownership!')
def verify_core_schema(conn):
"""Function used to check whether Core schema exists and has correct ownership."""
if not query_schema_existence(conn, 'core'):
raise DatabaseSchemaException('Missing schema \'core\' in DB. Was dirbs-db install run successfully?')
if query_schema_ownership(conn, 'core') != 'dirbs_core_power_user':
raise DatabaseSchemaException('Schema \'core\' is not owned by dirbs_core_power_user!')
def verify_hll_schema(conn):
"""Function used to check whether HLL schema exists and that extension is installed correctly."""
logger = logging.getLogger('dirbs.db')
if not query_schema_existence(conn, 'hll'):
logger.error('Schema \'hll\' does not exist. Please ensure the hll extension is installed and run the '
'following as a superuser whilst connected to this DB: '
'\n\t1. CREATE SCHEMA hll;'
'\n\t2. GRANT USAGE ON SCHEMA hll TO dirbs_core_base;'
'\n\t3. CREATE EXTENSION hll SCHEMA hll;')
raise DatabaseSchemaException('HLL schema not created!')
# Check if extension installed correctly by looking for hll.hll_print
with conn.cursor() as cursor:
try:
cursor.execute('SELECT pg_get_functiondef(\'hll.hll_print(hll.hll)\'::regprocedure)')
except psycopg2.ProgrammingError:
logger.error('The HLL extension is not installed correctly. Please issue the following as a superuser '
'whilst connected to this DB: '
'\n\tCREATE EXTENSION hll SCHEMA hll;')
raise DatabaseSchemaException('DB search_path does not include hll or extension not installed!')
def verify_db_search_path(conn):
"""Function used to check whether db_search_path is correct by looking for objects."""
logger = logging.getLogger('dirbs.db')
is_search_path_valid = True
with conn.cursor() as cursor:
cursor.execute('SELECT to_regclass(\'schema_version\')')
res = cursor.fetchone()[0]
if res is None:
is_search_path_valid = False
try:
cursor.execute('SELECT pg_get_functiondef(\'hll_print(hll)\'::regprocedure)')
except psycopg2.ProgrammingError:
is_search_path_valid = False
if not is_search_path_valid:
logger.error('The search_path for the database is not set correctly. Please issue the following '
'whilst connected to this DB: '
'\n\tALTER DATABASE <database> SET search_path TO core, hll;')
raise DatabaseSchemaException('DB search_path not set correctly!')
def query_db_schema_version(conn):
"""Function to fetch the DB version number from the database."""
logger = logging.getLogger('dirbs.db')
with conn.cursor() as cur:
try:
cur.execute('SELECT MAX(version) FROM schema_version') # noqa: Q440
return cur.fetchone()[0]
except psycopg2.ProgrammingError as ex:
logger.error(str(ex).strip())
return None
def set_db_schema_version(conn, new_version):
"""Function to set the DB version number in the database."""
with conn.cursor() as cur:
cur.execute('SELECT COUNT(*) FROM schema_version')
num_rows = cur.fetchone()[0]
assert num_rows <= 1
if num_rows > 0:
cur.execute('UPDATE schema_version SET version = %s', [new_version]) # noqa: Q440
else:
cur.execute('INSERT INTO schema_version(version) VALUES(%s)', [new_version])
def is_db_user_superuser(conn):
"""Function to test whether the current DB user is a PostgreSQL superuser."""
logger = logging.getLogger('dirbs.db')
with conn.cursor() as cur:
cur.execute("""SELECT rolsuper
FROM pg_roles
WHERE rolname = CURRENT_USER""")
res = cur.fetchone()
if res is None:
logger.warn('Failed to find CURRENT_USER in pg_roles table')
return False
return res[0]
def is_db_user_dirbs_role(conn, role_name):
"""Function to test whether the current DB user is in a DIRBS role."""
with conn.cursor() as cur:
cur.execute("""SELECT pg_has_role(%s, 'MEMBER')""", [role_name])
return cur.fetchone()[0]
def is_db_user_dirbs_poweruser(conn):
"""Function to test whether the current DB user is a DIRBS power user."""
return is_db_user_dirbs_role(conn, 'dirbs_core_power_user')
def can_db_user_create_roles(conn):
"""Function to test whether the current DB user has the CREATEROLE privilege."""
logger = logging.getLogger('dirbs.db')
with conn.cursor() as cur:
cur.execute("""SELECT rolcreaterole
FROM pg_roles
WHERE rolname = CURRENT_USER""")
res = cur.fetchone()
if res is None:
logger.warn('Failed to find CURRENT_USER in pg_roles table')
return False
return res[0]
def query_db_ownership(conn):
"""Function to verify whether the current database ownership is correct."""
logger = logging.getLogger('dirbs.db')
with conn.cursor() as cur:
cur.execute("""SELECT rolname
FROM pg_roles
JOIN pg_database
ON (pg_database.datdba = pg_roles.oid)
WHERE datname = current_database()""")
res = cur.fetchone()
if res is None:
logger.warn('Failed to determing DB owner for current_database')
return None
return res[0]
def query_schema_existence(conn, schema_name):
"""Function to verify whether the current database schema ownership is correct."""
with conn.cursor() as cur:
cur.execute('SELECT EXISTS(SELECT 1 FROM information_schema.schemata WHERE SCHEMA_NAME = %s)',
[schema_name])
return cur.fetchone().exists
def query_schema_ownership(conn, schema_name):
"""Function to verify whether the current database schema ownership is correct."""
logger = logging.getLogger('dirbs.db')
with conn.cursor() as cur:
cur.execute("""SELECT rolname
FROM pg_roles
JOIN pg_namespace
ON (pg_namespace.nspowner = pg_roles.oid)
WHERE nspname = %s""", [schema_name])
res = cur.fetchone()
if res is None:
logger.warn('Failed to determing owner for current_schema')
return None
return res[0]
def compute_analysis_end_date(conn, curr_date):
"""Function to get the end of the analysis window based on current operator data."""
end_date = curr_date
if end_date is None:
# If current date is None, set analysis end date as the last day for which operator data exists."""
with conn.cursor() as cursor:
monthly_country_child_tbl_list = child_table_names(conn, 'monthly_network_triplets_country')
year_month_list_in_child_tbls_records = table_invariants_list(conn, monthly_country_child_tbl_list,
['triplet_year', 'triplet_month'])
year_month_tuple_list = [(x.triplet_year, x.triplet_month) for x in year_month_list_in_child_tbls_records]
if len(year_month_tuple_list) > 0:
year_month_tuple_list.sort(key=lambda x: (x[0], x[1]), reverse=True)
latest_year, latest_month = year_month_tuple_list[0]
cursor.execute(sql.SQL("""SELECT MAX(last_seen)
FROM monthly_network_triplets_country
WHERE triplet_year = %s
AND triplet_month = %s"""), [latest_year, latest_month])
end_date = cursor.fetchone()[0]
# If there was no operator data imported, this can be None
if end_date is None:
end_date = datetime.date.today()
return end_date + datetime.timedelta(days=1)
def hash_string_64bit(s):
"""Basic string hash based on taking an initial prime number and multiplying it by another prime numnber."""
string_hash = 7
string_bytes = bytearray(s, 'utf-8')
for b in string_bytes:
string_hash = string_hash * 31 + b
return string_hash % (pow(2, 63) - 1) # noqa: S001 Make sure it fits into a 64-bit bigint
def child_table_names(conn, parent_name):
"""Return a list of table names for a parent table name."""
with conn.cursor() as cursor:
cursor.execute("""SELECT c.relname AS child_tblname
FROM pg_inherits
JOIN pg_class AS c
ON (c.oid = inhrelid)
JOIN pg_class AS p
ON (p.oid = inhparent)
JOIN pg_catalog.pg_namespace nc
ON nc.oid = c.relnamespace
JOIN pg_catalog.pg_namespace np
ON np.oid = p.relnamespace
WHERE p.relname = %s
AND np.nspname = current_schema()
AND nc.nspname = current_schema()""",
[parent_name])
return [res.child_tblname for res in cursor]
def table_invariants_list(conn, table_names, invariant_col_names):
"""Gets a list of tuples containing the values for common table invariant columns across a list table names."""
if len(table_names) == 0:
# Need to return an empty list to avoid doing an empty query and generating an error
return []
with conn.cursor() as cursor:
table_queries = []
for tblname in table_names:
table_queries.append(sql.SQL("""SELECT * FROM (SELECT {0} FROM {1} LIMIT 1) {2}""")
.format(sql.SQL(', ').join(map(sql.Identifier, invariant_col_names)),
sql.Identifier(tblname),
sql.Identifier('tmp_{0}'.format(tblname))))
cursor.execute(sql.SQL(' UNION ALL ').join(table_queries))
return cursor.fetchall()
def most_recently_run_condition_info(conn, cond_names, successful_only=False):
"""For a list of condition names, return a dict of cond_name -> (run_id, cond_config) for the most recent results.
If a particular condition has never completed successfully, the value of the dict will be None, unless the
successful_only parameter is set to True, in which case the key will not exist in the returned dict.
"""
conditions_to_find = copy.copy(cond_names)
rv = {}
# Get list of metadata for dirbs-classify, sorted in reverse order
job_metadata_list = metadata.query_for_command_runs(conn, 'dirbs-classify')
for job_metadata in job_metadata_list:
# Loop back through recent dirbs-classify runs looking for the last time a classification
# ran successfully. This is indicates in the metadata by the presence of an entry in the matched_imei_counts.
# This can happen even though the overall dirbs-classify job failed
extra_metadata = job_metadata.extra_metadata
metadata_conditions = extra_metadata.get('conditions', {})
matched_imei_counts = extra_metadata.get('matched_imei_counts', {})
conditions_lookup = {c['label']: c for c in metadata_conditions}
for req_cond_name in copy.copy(conditions_to_find): # We modify the list in the loop, so take a copy
if req_cond_name in matched_imei_counts:
# If the name was in matched_imei_counts, it should always be in conditions as well
rv[req_cond_name] = {
'run_id': job_metadata.run_id,
'config': conditions_lookup[req_cond_name],
'last_successful_run': job_metadata.start_time
}
# Remove this req_cond_name from conditions_to_find since we already found latest metadata
conditions_to_find.remove(req_cond_name)
# Any items in conditions_to_find at this point are conditions for which we never ran a successful condition
# run
if not successful_only:
for missing_cond_name in conditions_to_find:
rv[missing_cond_name] = None
return rv
def filter_imei_list_sql_by_device_type(conn, exempted_device_types, imei_list_sql):
"""Function to return SQL filtering out exempted device types."""
# If certain device types are exempted, first select the IMEIs passed in imei_list_sql query.
# These IMEIs are then joined against GSMA TAC db to get their device type.
# Finally, any IMEIs that belong to exempted device types are excluded.
return sql.SQL("""SELECT imei_norm
FROM (SELECT imei_norm,
SUBSTRING(imei_norm, 1, 8) AS tac
FROM ({0}) imeis) imeis_with_tac
JOIN gsma_data
USING (tac)
WHERE device_type NOT IN {1}
""").format(sql.SQL(imei_list_sql),
sql.Literal(tuple(exempted_device_types))).as_string(conn)
def format_datetime_for_report(timestamp_with_tz):
"""Format the datetime into a string for reporting.
Replace this function with datetime.isoformat(sep=' ', timespec='seconds') after we update python version to 3.6
"""
if timestamp_with_tz is not None:
return timestamp_with_tz.strftime('%Y-%m-%d %X')
else:
return None
def validate_exempted_device_types(conn, config):
"""Method to validate exempted device types specified in config."""
with conn.cursor() as cursor:
logger = logging.getLogger('dirbs.config')
exempted_device_types = config.region_config.exempted_device_types
if len(exempted_device_types) > 0:
cursor.execute('SELECT DISTINCT device_type FROM gsma_data')
all_device_types = [x.device_type for x in cursor]
if len(all_device_types) == 0:
logger.warning('RegionConfig: Ignoring setting exempted_device_types={0} as GSMA TAC database '
'not imported or no device types found.'.format(exempted_device_types))
else:
invalid_device_types = set(exempted_device_types) - set(all_device_types)
if len(invalid_device_types) > 0:
msg = 'RegionConfig: exempted_device_types \'{0}\' is/are not valid device type(s). ' \
'The valid GSMA device types are: \'{1}\''.format(invalid_device_types, all_device_types)
logger.error(msg)
raise ConfigParseException(msg)
def log_analysis_window(logger, analysis_start_date, analysis_end_date, start_message='',
start_date_inclusive=True, end_date_inclusive=False):
"""Helper function to print out window on used for analysis and list generation using interval notation."""
start_date_interval_notation = '[' if start_date_inclusive else '('
end_date_interval_notation = ']' if end_date_inclusive else ')'
logger.debug('{0} {sd_interval_notation}{start_date}, '
'{end_date}{ed_interval_notation}'.format(start_message,
sd_interval_notation=start_date_interval_notation,
start_date=analysis_start_date,
end_date=analysis_end_date,
ed_interval_notation=end_date_interval_notation))
def registration_list_status_filter_sql():
"""SQL to filter for whitelisted or null registration_list statuses."""
return sql.SQL('(status IS NULL OR status = \'whitelist\')')
def compute_amnesty_flags(app_config, curr_date):
"""Helper function to determine whether the date falls within amnesty eval or amnesty period."""
in_amnesty_eval_period = True if app_config.amnesty_config.amnesty_enabled and \
curr_date <= app_config.amnesty_config.evaluation_period_end_date else False
in_amnesty_period = True if app_config.amnesty_config.amnesty_enabled and \
curr_date > app_config.amnesty_config.evaluation_period_end_date and \
curr_date <= app_config.amnesty_config.amnesty_period_end_date else False
return in_amnesty_eval_period, in_amnesty_period
def table_exists_sql(any_schema=False):
"""SQL to check for existence of a table. Note that for temp tables, any_schema should be set to True."""
if not any_schema:
schema_filter_sql = sql.SQL('AND schemaname = current_schema()')
else:
schema_filter_sql = sql.SQL('')
return sql.SQL("""SELECT EXISTS (SELECT 1
FROM pg_tables
WHERE tablename = %s
{schema_filter_sql})""").format(schema_filter_sql=schema_filter_sql)
def is_table_partitioned(conn, tbl_name):
"""Function to determine whether a table is partitioned."""
with conn.cursor() as cursor:
cursor.execute("""SELECT EXISTS (SELECT 1
FROM pg_class
JOIN pg_partitioned_table
ON pg_partitioned_table.partrelid = pg_class.oid
WHERE pg_class.relname = %s)""", [tbl_name])
return cursor.fetchone().exists
| src/dirbs/utils.py | 27,857 | Profile a block of code and store duration.
Custom exception class to indicate the user does not have the correct roles for this job.
Custom exception class to indicate there was a problem validating the schema.
Custom JSONEncoder class which serializes dates in ISO format.
Named tuple cursor that logs to DIRBS.
Python context manager support for use in with statement (on enter).
Python context manager support for use in with statement (on exit).
Constructor.
Constructor.
Constructor.
Utility method to generate a unique filename based on the hash of a given content array (of bytes).
Overrides NamedTupleCursor.callproc.
Function to test whether the current DB user has the CREATEROLE privilege.
Return a list of table names for a parent table name.
Convert DB-related command-line arguments from a DSN into a format appropriate for DIRBS CLI commands.
Helper function to determine whether the date falls within amnesty eval or amnesty period.
Function to get the end of the analysis window based on current operator data.
Utility method to generate a md5 hash of file.
Creates a DB connection to the database.
Imports the config module, which results in the config being read from disk.
Changes to the config file made after this method has been called will not be read.
Calling entity should handle connection errors as appropriate.
Since we catch exceptions here and log, temporarily install a customised hook.
Overrides JSONEncoder.default.
Overrides NamedTupleCursor.execute.
Function to return SQL filtering out exempted device types.
Format the datetime into a string for reporting.
Replace this function with datetime.isoformat(sep=' ', timespec='seconds') after we update python version to 3.6
Basic string hash based on taking an initial prime number and multiplying it by another prime numnber.
Function to test whether the current DB user is a DIRBS power user.
Function to test whether the current DB user is in a DIRBS role.
Function to test whether the current DB user is a PostgreSQL superuser.
Function to determine whether a table is partitioned.
Helper function to print out window on used for analysis and list generation using interval notation.
For a list of condition names, return a dict of cond_name -> (run_id, cond_config) for the most recent results.
If a particular condition has never completed successfully, the value of the dict will be None, unless the
successful_only parameter is set to True, in which case the key will not exist in the returned dict.
Function to verify whether the current database ownership is correct.
Function to fetch the DB version number from the database.
Function to verify whether the current database schema ownership is correct.
Function to verify whether the current database schema ownership is correct.
SQL to filter for whitelisted or null registration_list statuses.
Function to set the DB version number in the database.
SQL to check for existence of a table. Note that for temp tables, any_schema should be set to True.
Gets a list of tuples containing the values for common table invariant columns across a list table names.
Method to validate exempted device types specified in config.
Function used to check whether Core schema exists and has correct ownership.
Function used to check whether DB ownership matches what we expect.
Function used to verify that the current DB user is in the role expected for this job.
Function used to verify whether roles have been installed in the DB.
Function that runs all DB verification checks.
Function used to check whether the DB schema version matches the code schema version.
Function used to check whether db_search_path is correct by looking for objects.
Function used to check whether HLL schema exists and that extension is installed correctly.
Warn if the current DB user is a PostgreSQL superuser.
DIRBS module for utility classes and functions.
Copyright (c) 2018 Qualcomm Technologies, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the
limitations in the disclaimer below) provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following
disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Qualcomm Technologies, Inc. nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written permission.
NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY
THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
Default itersize to 100000 for named cursors We hard-code 4 minutes idle keepalives, which is fairly aggressive, to avoid disconnections on VPNs, etc. The below is not a guaranteed check, but a heuristic Check if extension installed correctly by looking for hll.hll_print noqa: Q440 noqa: Q440 If current date is None, set analysis end date as the last day for which operator data exists.""" If there was no operator data imported, this can be None noqa: S001 Make sure it fits into a 64-bit bigint Need to return an empty list to avoid doing an empty query and generating an error Get list of metadata for dirbs-classify, sorted in reverse order Loop back through recent dirbs-classify runs looking for the last time a classification ran successfully. This is indicates in the metadata by the presence of an entry in the matched_imei_counts. This can happen even though the overall dirbs-classify job failed We modify the list in the loop, so take a copy If the name was in matched_imei_counts, it should always be in conditions as well Remove this req_cond_name from conditions_to_find since we already found latest metadata Any items in conditions_to_find at this point are conditions for which we never ran a successful condition run If certain device types are exempted, first select the IMEIs passed in imei_list_sql query. These IMEIs are then joined against GSMA TAC db to get their device type. Finally, any IMEIs that belong to exempted device types are excluded. | 7,019 | en | 0.849367 |
import config
import pandas as pd
import pickle
import numpy as np
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import classification_report
import tensorflow as tf
from keras import Sequential
from tensorflow.keras.layers import Embedding, SpatialDropout1D, LSTM, Dense
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras import regularizers
from keras.models import load_model
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import confusion_matrix
"""
Versuch #1
"""
# Gibt den classification-report aus
def evaluate(model, X_test, Y_test):
Y_pred = model.predict(X_test)
Y_pred = Y_pred.argmax(axis=-1)
Y_test = Y_test.argmax(axis=-1)
print(classification_report([Y_test], [Y_pred]))
# Nimmt ein history-Objekt und zeichnet den loss für
# sowohl testing als auch training Daten.
def plot_model(history, fold):
plt.title('Loss')
plt.plot(history.history['loss'], label='train_loss')
plt.plot(history.history['val_loss'], label='test_loss')
plt.legend()
plt.savefig(f"../plots/covid_model_without_vaccine_loss_{config.EPOCHS}epochs_{fold}v{config.K_FOLD_SPLITS}fold.png")
clear_plot()
plt.title('Accuracy')
plt.plot(history.history['accuracy'], label='train_acc', c="r")
plt.plot(history.history['val_accuracy'], label='test_acc', c="b")
plt.legend()
plt.savefig(f"../plots/covid_model_without_vaccine_accuracy_{config.EPOCHS}epochs_{fold}v{config.K_FOLD_SPLITS}fold.png")
clear_plot()
def clear_plot():
plt.close()
plt.cla()
plt.clf()
def plot_confusion_matrix(model, X_test, y_test, fold):
y_pred = model.predict(X_test)
y_pred = y_pred.argmax(axis=-1)
y_test = y_test.argmax(axis=-1)
cm = confusion_matrix(y_test, y_pred)
ax=plt.subplot()
sns.heatmap(cm, annot=True, fmt='g', ax=ax)
# labels, title and ticks
ax.set_xlabel('Predicted labels')
ax.set_ylabel('True labels')
ax.set_title(f'Confusion Matrix – {config.EPOCHS}|{fold}')
ax.xaxis.set_ticklabels(['Negative', 'Positive'])
ax.yaxis.set_ticklabels(['Negative', 'Positive'])
plt.savefig(f"../plots/covid_confusion_{config.EPOCHS}epochs_{fold}v{config.K_FOLD_SPLITS}fold.png")
clear_plot()
# Erstellen eines Tokenizers für das LSTM Modell
def create_tokenizer(df, save_path):
tokenizer = Tokenizer(num_words=config.MAX_NUM_WORDS, filters='!"#$%&()*+,-./:;<=>?@[\]^_`{|}~', lower=True)
words = df.link.values.tolist()
words.extend(df.meta_data.values.tolist())
words.extend(df.title.values.tolist())
words.extend(df.body.values.tolist())
tokenizer.fit_on_texts(words)
save_tokenizer(tokenizer, save_path)
return tokenizer
# Laden und speichern des Tokenizers
def save_tokenizer(tokenizer, filename):
with open(filename, 'wb') as f:
pickle.dump(tokenizer, f, protocol=pickle.HIGHEST_PROTOCOL)
def load_tokenizer(filename):
with open(filename, 'rb') as f:
tokenizer = pickle.load(f)
return tokenizer
"""
Die in Tokens verwandelte Texte sehen so aus:
[[1, 2, 3, 4], [5, 6, 7], [8, 9, 10, 11, 12]]
gepaddet sehen sie so aus:
[[ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2 3 4]
[ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 5 6 7]
[ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8 9 10 11 12]]
werden danach die Covid Count Zahlen angefügt, sieht die Repräsentation beispielsweise so aus
[[ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2 3 4 10 20 30]
[ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 5 6 7 40 50 60]
[ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8 9 10 11 12 70 80 90]]
Das np.expand ist notwendig, um das array in beispielsweise folgende Form zu bringen: [ 2 1 20] => [ [2] [1] [20]]
"""
def transform_text(tokenizer, df):
if (isinstance(tokenizer, str)):
tokenizer = load_tokenizer(tokenizer)
# Tokenizing der Link Informationen
X_input = tokenizer.texts_to_sequences(df['link'].values)
X_input = pad_sequences(X_input, maxlen=config.MAX_LINK_SEQUENCE_LENGTH)
# Tokenizing der Meta Informationen
X_meta = tokenizer.texts_to_sequences(df['meta_data'].values)
X_meta = pad_sequences(X_meta, maxlen=config.MAX_META_SEQUENCE_LENGTH)
# Tokenizing der Titel Informationen
X_title = tokenizer.texts_to_sequences(df['title'].values)
X_title = pad_sequences(X_title, maxlen=config.MAX_TITLE_SEQUENCE_LENGTH)
# Tokenizing des Seiteninhalts
X_body = tokenizer.texts_to_sequences(df['body'].values)
X_body = pad_sequences(X_body, maxlen=config.MAX_BODY_SEQUENCE_LENGTH)
covid_word_count = df['covid_word_count'].values
covid_word_count_url = df['covid_word_count_url'].values
restriction_word_count = df['restriction_word_count'].values
restriction_word_count_url = df['restriction_word_count_url'].values
X_input = np.concatenate([X_input, X_meta], axis=-1)
X_input = np.concatenate([X_input, X_title], axis=-1)
X_input = np.concatenate([X_input, X_body], axis=-1)
covid_word_count = np.expand_dims(covid_word_count, axis=(-1))
X_input = np.concatenate([X_input, covid_word_count], axis=-1)
covid_word_count_url = np.expand_dims(covid_word_count_url, axis=(-1))
X_input = np.concatenate([X_input, covid_word_count_url], axis=-1)
restriction_word_count = np.expand_dims(restriction_word_count, axis=(-1))
X_input = np.concatenate([X_input, restriction_word_count], axis=-1)
restriction_word_count_url = np.expand_dims(restriction_word_count_url, axis=(-1))
X_input = np.concatenate([X_input, restriction_word_count_url], axis=-1) # Schlussendlich alles zusammefügen
return X_input
def remove_stopwords(df):
ger = pd.read_csv(config.STOPWORDS_PATH)['stopwords'].values
df['link'] = df['link'].apply(lambda x: ' '.join([word for word in str(x).split() if word not in (ger)]))
df['meta_data'] = df['meta_data'].apply(lambda x: ' '.join([word for word in str(x).split() if word not in (ger)]))
df['title'] = df['title'].apply(lambda x: ' '.join([word for word in str(x).split() if word not in (ger)]))
df['body'] = df['body'].apply(lambda x: ' '.join([word for word in str(x).split() if word not in (ger)]))
return df
# Nimmt den input DataFrame und einen LabelEncoder Objekt,
# trainiert ein LSTM Modell, speichert es, evaluiert es
# und gibt den Loss aus.
def train_model(train_df, valid_df, tokenizer, fold):
X_train = transform_text(tokenizer, train_df)
X_valid = transform_text(tokenizer, valid_df)
Y_train = pd.get_dummies(train_df['label'])
Y_valid = pd.get_dummies(valid_df['label']).to_numpy()
model = Sequential()
optimizer = tf.keras.optimizers.Adam(1e-3) # 0.001
model.add(Embedding(config.MAX_NUM_WORDS, config.EMBEDDING_DIM, input_length=X_train.shape[1]))
model.add(SpatialDropout1D(0.2))
model.add(LSTM(100, dropout=0.2, recurrent_dropout=0.2, bias_regularizer=regularizers.l2(1e-4),)) # TODO: damit rumspielen
model.add(Dense(2, activation='softmax'))
loss='categorical_crossentropy'
model.compile(loss=loss, optimizer=optimizer, metrics=['accuracy'])
epochs = config.EPOCHS
batch_size = config.BATCH_SIZE # 64
#es = EarlyStopping(monitor='val_loss', patience=3, min_delta=0.0001)
history = model.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, validation_split=0.2) # , callbacks=[es]
accr = model.evaluate(X_valid,Y_valid)
print('Test set\n Loss: {:0.3f}\n Accuracy: {:0.3f}'.format(accr[0],accr[1]))
model.save(f"{config.MODEL_PATH}_without_vaccine_{fold}.h5")
evaluate(model, X_valid, Y_valid)
plot_model(history, fold)
plot_confusion_matrix(model, X_valid, Y_valid, fold)
# Laden und evaluieren eines existierenden Modells
def load_and_evaluate_existing_model(model_path, tokenizer_path, df, le):
model = load_model(model_path)
tokenizer = load_tokenizer(tokenizer_path)
X = transform_text(tokenizer, df['text'].values)
Y = pd.get_dummies(df['label']).values
evaluate(model, X, Y, le)
# Testen eines neuen Beispiels. Hauptsächlich zu Testzwecken während der Entwicklung
# Die Funktion nimmt einen String, den Classifier,
# den Vectorizer und einen LabelEncoder und
# gibt eine Vorhersage zurück.
def test_new_example(model, tokenizer, le, text_input):
X_example = transform_text(tokenizer, [text_input])
label_array = model.predict(X_example)
new_label = np.argmax(label_array, axis=-1)
print(new_label)
print(le.inverse_transform(new_label))
def run(df, fold, use_vaccine):
# der Trainingdataframe
train_df = df[df.kfold != fold].reset_index(drop=True)
print(f"Länge Traing_DF {len(train_df)}")
# Validation Dataframe
valid_df = df[df.kfold == fold].reset_index(drop=True)
print(f"Länge Valid_DF {len(valid_df)}")
# Das Validationset enthält weiterhin die Impf-Beispiele
# Bei 10 Folds sind die Sets folgendermaßen aufgeteil:
# 0 – 126
# 1 – 78
# 2 – 10
if not use_vaccine:
train_df = train_df[train_df['label'] != 2]
# Jetzt müssen alle 2 er noch in einsergewandelt werden
train_df['label'] = train_df['label'].apply(lambda x : 1 if x > 0 else 0)
valid_df['label'] = valid_df['label'].apply(lambda x : 1 if x > 0 else 0)
print("Fitting tokenizer")
# tf.keras Tokenizer
tokenizer = create_tokenizer(train_df, f"{config.TOKENIZER_SAVE_PATH}_{fold}.pickle")
train_model(train_df, valid_df, tokenizer, fold)
# load_and_evaluate_existing_model(f"{config.MODEL_PATH}_{fold}", config.TOKENIZER_PATH, df, le)
#model = load_model(config.MODEL_PATH)
#tokenizer = config.TOKENIZER_PATH
if (__name__ == "__main__"):
tf.get_logger().setLevel('ERROR')
# load data
df = pd.read_csv(config.DATASET_PATH).sample(frac=1)
df = remove_stopwords(df)
"""
# TODO: ein Test, Gleichverteilung
"""
df2 = df[df['label'] != 0]
# Wir nehmen einfach den hinteren Teil des Körpers und den Metadaten
df2['body'] = df2['body'].apply(lambda x : str(x)[config.MAX_BODY_SEQUENCE_LENGTH:])
df2['meta_data'] = df2['meta_data'].apply(lambda x : str(x)[config.MAX_META_SEQUENCE_LENGTH:])
df = df.append(df2, ignore_index=True).reset_index()
# initiate the kfold class from the model_selection module
kf = StratifiedKFold(n_splits=config.K_FOLD_SPLITS)
# füllen den kfold Spalte
for f, (t_, v_) in enumerate(kf.split(X=df, y=df.label.values)):
df.loc[v_, 'kfold'] = f
# training für alle Faltungen
for i in range(config.K_FOLD_SPLITS):
print(f"\n–––––––––––– FOLD {i} ––––––––––––\n")
run(df, fold=i, use_vaccine=config.USE_VACCINE) | classification/src/train.py | 10,962 | Gibt den classification-report aus Nimmt ein history-Objekt und zeichnet den loss für sowohl testing als auch training Daten. labels, title and ticks Erstellen eines Tokenizers für das LSTM Modell Laden und speichern des Tokenizers Tokenizing der Link Informationen Tokenizing der Meta Informationen Tokenizing der Titel Informationen Tokenizing des Seiteninhalts Schlussendlich alles zusammefügen Nimmt den input DataFrame und einen LabelEncoder Objekt, trainiert ein LSTM Modell, speichert es, evaluiert es und gibt den Loss aus. 0.001 TODO: damit rumspielen 64es = EarlyStopping(monitor='val_loss', patience=3, min_delta=0.0001) , callbacks=[es] Laden und evaluieren eines existierenden Modells Testen eines neuen Beispiels. Hauptsächlich zu Testzwecken während der Entwicklung Die Funktion nimmt einen String, den Classifier, den Vectorizer und einen LabelEncoder und gibt eine Vorhersage zurück. der Trainingdataframe Validation Dataframe Das Validationset enthält weiterhin die Impf-Beispiele Bei 10 Folds sind die Sets folgendermaßen aufgeteil: 0 – 126 1 – 78 2 – 10 Jetzt müssen alle 2 er noch in einsergewandelt werden tf.keras Tokenizer load_and_evaluate_existing_model(f"{config.MODEL_PATH}_{fold}", config.TOKENIZER_PATH, df, le)model = load_model(config.MODEL_PATH)tokenizer = config.TOKENIZER_PATH load data Wir nehmen einfach den hinteren Teil des Körpers und den Metadaten initiate the kfold class from the model_selection module füllen den kfold Spalte training für alle Faltungen | 1,500 | de | 0.947908 |
"""Returns full pathname of backup directory."""
import os
import pytest
from pathlib import Path
from mklists.constants import CONFIGFILE_NAME
from mklists.returns import get_backupdir_path
def test_get_backupdir_path(tmp_path):
"""Returns backups Path named for default working directory."""
os.chdir(tmp_path)
Path(CONFIGFILE_NAME).write_text("config stuff")
backdir = "_backups"
datestr = "2020-01-03_1646"
workingdir = Path("agenda")
workingdir.mkdir()
os.chdir(workingdir)
actual = get_backupdir_path(backdir=backdir, now=datestr)
expected = Path(tmp_path) / backdir / str(workingdir) / datestr
expected_explicit = Path(tmp_path) / "_backups" / "agenda" / "2020-01-03_1646"
assert actual == expected
assert actual == expected_explicit
def test_get_backupdir_path_given_datadir(tmp_path):
"""Returns backups Path named for specified working directory."""
os.chdir(tmp_path)
Path(CONFIGFILE_NAME).write_text("config stuff")
workingdir = Path(tmp_path).joinpath("todolists/a")
workingdir.mkdir(parents=True, exist_ok=True)
workingdir_shortname_expected = "todolists_a"
backdir = "_backups"
datestr = "2020-01-03_1646_06488910"
actual = get_backupdir_path(datadir=workingdir, backdir=backdir, now=datestr)
expected = Path(tmp_path) / backdir / workingdir_shortname_expected / datestr
assert actual == expected
def test_get_backupdir_path_given_datadir_with_slash(tmp_path):
"""Returns backups Path named for specified working directory ending with slash."""
os.chdir(tmp_path)
Path(CONFIGFILE_NAME).write_text("config stuff")
workingdir = Path(tmp_path).joinpath("todolists/a/")
workingdir.mkdir(parents=True, exist_ok=True)
workingdir_shortname_expected = "todolists_a"
backdir = "_backups"
datestr = "2020-01-03_1646_06488910"
actual = get_backupdir_path(datadir=workingdir, backdir=backdir, now=datestr)
expected = Path(tmp_path) / backdir / workingdir_shortname_expected / datestr
assert actual == expected
def test_get_backupdir_path_raise_exception_if_rootdir_not_found(tmp_path):
"""Raises exception if no rootdir is found (rootdir is None)."""
os.chdir(tmp_path)
with pytest.raises(SystemExit):
get_backupdir_path()
| tests/returns/test_get_backupdir_path.py | 2,295 | Returns backups Path named for default working directory.
Returns backups Path named for specified working directory.
Returns backups Path named for specified working directory ending with slash.
Raises exception if no rootdir is found (rootdir is None).
Returns full pathname of backup directory. | 297 | en | 0.809935 |
# Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Elasticsearch datastore."""
from __future__ import unicode_literals
from collections import Counter
import copy
import codecs
import json
import logging
import socket
from uuid import uuid4
import six
from dateutil import parser, relativedelta
from elasticsearch import Elasticsearch
from elasticsearch.exceptions import ConnectionTimeout
from elasticsearch.exceptions import NotFoundError
from elasticsearch.exceptions import RequestError
# pylint: disable=redefined-builtin
from elasticsearch.exceptions import ConnectionError
from flask import abort
from flask import current_app
import prometheus_client
from timesketch.lib.definitions import HTTP_STATUS_CODE_NOT_FOUND
from timesketch.lib.definitions import METRICS_NAMESPACE
# Setup logging
es_logger = logging.getLogger('timesketch.elasticsearch')
es_logger.setLevel(logging.WARNING)
# Metrics definitions
METRICS = {
'search_requests': prometheus_client.Counter(
'search_requests',
'Number of search requests per type (e.g all, stream etc)',
['type'],
namespace=METRICS_NAMESPACE
),
'search_filter_type': prometheus_client.Counter(
'search_filter_type',
'Number of filters per type (e.g term, label etc)',
['type'],
namespace=METRICS_NAMESPACE
),
'search_filter_label': prometheus_client.Counter(
'search_filter_label',
'Number of filters per label (e.g __ts_star etc)',
['label'],
namespace=METRICS_NAMESPACE
),
'search_get_event': prometheus_client.Counter(
'search_get_event',
'Number of times a single event is requested',
namespace=METRICS_NAMESPACE
)
}
# Elasticsearch scripts
UPDATE_LABEL_SCRIPT = """
if (ctx._source.timesketch_label == null) {
ctx._source.timesketch_label = new ArrayList()
}
if (params.remove == true) {
ctx._source.timesketch_label.removeIf(label -> label.name == params.timesketch_label.name && label.sketch_id == params.timesketch_label.sketch_id);
} else {
if( ! ctx._source.timesketch_label.contains (params.timesketch_label)) {
ctx._source.timesketch_label.add(params.timesketch_label)
}
}
"""
TOGGLE_LABEL_SCRIPT = """
if (ctx._source.timesketch_label == null) {
ctx._source.timesketch_label = new ArrayList()
}
boolean removedLabel = ctx._source.timesketch_label.removeIf(label -> label.name == params.timesketch_label.name && label.sketch_id == params.timesketch_label.sketch_id);
if (!removedLabel) {
ctx._source.timesketch_label.add(params.timesketch_label)
}
"""
class ElasticsearchDataStore(object):
"""Implements the datastore."""
# Number of events to queue up when bulk inserting events.
DEFAULT_FLUSH_INTERVAL = 1000
DEFAULT_SIZE = 100
DEFAULT_LIMIT = DEFAULT_SIZE # Max events to return
DEFAULT_FROM = 0
DEFAULT_STREAM_LIMIT = 5000 # Max events to return when streaming results
DEFAULT_FLUSH_RETRY_LIMIT = 3 # Max retries for flushing the queue.
DEFAULT_EVENT_IMPORT_TIMEOUT = '3m' # Timeout value for importing events.
def __init__(self, host='127.0.0.1', port=9200):
"""Create a Elasticsearch client."""
super().__init__()
self._error_container = {}
self.user = current_app.config.get('ELASTIC_USER', 'user')
self.password = current_app.config.get('ELASTIC_PASSWORD', 'pass')
self.ssl = current_app.config.get('ELASTIC_SSL', False)
self.verify = current_app.config.get('ELASTIC_VERIFY_CERTS', True)
if self.ssl:
if self.user and self.password:
self.client = Elasticsearch(
[{'host': host, 'port': port}],
http_auth=(self.user, self.password),
use_ssl=self.ssl, verify_certs=self.verify)
else:
self.client = Elasticsearch(
[{'host': host, 'port': port}],
use_ssl=self.ssl, verify_certs=self.verify)
else:
self.client = Elasticsearch([{'host': host, 'port': port}])
self.import_counter = Counter()
self.import_events = []
self._request_timeout = current_app.config.get(
'TIMEOUT_FOR_EVENT_IMPORT', self.DEFAULT_EVENT_IMPORT_TIMEOUT)
@staticmethod
def _build_labels_query(sketch_id, labels):
"""Build Elasticsearch query for Timesketch labels.
Args:
sketch_id: Integer of sketch primary key.
labels: List of label names.
Returns:
Elasticsearch query as a dictionary.
"""
label_query = {
'bool': {
'must': []
}
}
for label in labels:
# Increase metrics counter per label
METRICS['search_filter_label'].labels(label=label).inc()
nested_query = {
'nested': {
'query': {
'bool': {
'must': [{
'term': {
'timesketch_label.name.keyword': label
}
}, {
'term': {
'timesketch_label.sketch_id': sketch_id
}
}]
}
},
'path': 'timesketch_label'
}
}
label_query['bool']['must'].append(nested_query)
return label_query
@staticmethod
def _build_events_query(events):
"""Build Elasticsearch query for one or more document ids.
Args:
events: List of Elasticsearch document IDs.
Returns:
Elasticsearch query as a dictionary.
"""
events_list = [event['event_id'] for event in events]
query_dict = {'query': {'ids': {'values': events_list}}}
return query_dict
@staticmethod
def _build_query_dsl(query_dsl, timeline_ids):
"""Build Elastic Search DSL query by adding in timeline filtering.
Args:
query_dsl: A dict with the current query_dsl
timeline_ids: Either a list of timeline IDs (int) or None.
Returns:
Elasticsearch query DSL as a dictionary.
"""
# Remove any aggregation coming from user supplied Query DSL.
# We have no way to display this data in a good way today.
if query_dsl.get('aggregations', None):
del query_dsl['aggregations']
if not timeline_ids:
return query_dsl
if not isinstance(timeline_ids, (list, tuple)):
es_logger.error(
'Attempting to pass in timelines to a query DSL, but the '
'passed timelines are not a list.')
return query_dsl
if not all([isinstance(x, int) for x in timeline_ids]):
es_logger.error(
'All timeline IDs need to be an integer.')
return query_dsl
old_query = query_dsl.get('query')
if not old_query:
return query_dsl
query_dsl['query'] = {
'bool': {
'must': [],
'should': [{
'bool': {
'must': old_query,
'must_not': [{
'exists': {
'field': '__ts_timeline_id'},
}],
}
}, {
'bool': {
'must': [{
'terms': {
'__ts_timeline_id': timeline_ids}
}, old_query],
'must_not': [],
'filter': [{
'exists': {
'field': '__ts_timeline_id'}
}]
}
}],
'must_not': [],
'filter': []
}
}
return query_dsl
@staticmethod
def _convert_to_time_range(interval):
"""Convert an interval timestamp into start and end dates.
Args:
interval: Time frame representation
Returns:
Start timestamp in string format.
End timestamp in string format.
"""
# return ('2018-12-05T00:00:00', '2018-12-05T23:59:59')
TS_FORMAT = '%Y-%m-%dT%H:%M:%S'
get_digits = lambda s: int(''.join(filter(str.isdigit, s)))
get_alpha = lambda s: ''.join(filter(str.isalpha, s))
ts_parts = interval.split(' ')
# The start date could be 1 or 2 first items
start = ' '.join(ts_parts[0:len(ts_parts)-2])
minus = get_digits(ts_parts[-2])
plus = get_digits(ts_parts[-1])
interval = get_alpha(ts_parts[-1])
start_ts = parser.parse(start)
rd = relativedelta.relativedelta
if interval == 's':
start_range = start_ts - rd(seconds=minus)
end_range = start_ts + rd(seconds=plus)
elif interval == 'm':
start_range = start_ts - rd(minutes=minus)
end_range = start_ts + rd(minutes=plus)
elif interval == 'h':
start_range = start_ts - rd(hours=minus)
end_range = start_ts + rd(hours=plus)
elif interval == 'd':
start_range = start_ts - rd(days=minus)
end_range = start_ts + rd(days=plus)
else:
raise RuntimeError('Unable to parse the timestamp: '
+ str(interval))
return start_range.strftime(TS_FORMAT), end_range.strftime(TS_FORMAT)
def build_query(self, sketch_id, query_string, query_filter, query_dsl=None,
aggregations=None, timeline_ids=None):
"""Build Elasticsearch DSL query.
Args:
sketch_id: Integer of sketch primary key
query_string: Query string
query_filter: Dictionary containing filters to apply
query_dsl: Dictionary containing Elasticsearch DSL query
aggregations: Dict of Elasticsearch aggregations
timeline_ids: Optional list of IDs of Timeline objects that should
be queried as part of the search.
Returns:
Elasticsearch DSL query as a dictionary
"""
if query_dsl:
if not isinstance(query_dsl, dict):
query_dsl = json.loads(query_dsl)
if not query_dsl:
query_dsl = {}
return self._build_query_dsl(query_dsl, timeline_ids)
if query_filter.get('events', None):
events = query_filter['events']
return self._build_events_query(events)
query_dsl = {
'query': {
'bool': {
'must': [],
'must_not': [],
'filter': []
}
}
}
if query_string:
query_dsl['query']['bool']['must'].append(
{'query_string': {'query': query_string}})
# New UI filters
if query_filter.get('chips', None):
labels = []
must_filters = query_dsl['query']['bool']['must']
must_not_filters = query_dsl['query']['bool']['must_not']
datetime_ranges = {
'bool': {
'should': [],
'minimum_should_match': 1
}
}
for chip in query_filter['chips']:
# Exclude chips that the user disabled
if not chip.get('active', True):
continue
# Increase metrics per chip type
METRICS['search_filter_type'].labels(type=chip['type']).inc()
if chip['type'] == 'label':
labels.append(chip['value'])
elif chip['type'] == 'term':
term_filter = {
'match_phrase': {
'{}'.format(chip['field']): {
'query': "{}".format(chip['value'])
}
}
}
if chip['operator'] == 'must':
must_filters.append(term_filter)
elif chip['operator'] == 'must_not':
must_not_filters.append(term_filter)
elif chip['type'].startswith('datetime'):
range_filter = lambda start, end: {
'range': {
'datetime': {
'gte': start,
'lte': end
}
}
}
if chip['type'] == 'datetime_range':
start, end = chip['value'].split(',')
elif chip['type'] == 'datetime_interval':
start, end = self._convert_to_time_range(chip['value'])
else:
continue
datetime_ranges['bool']['should'].append(
range_filter(start, end))
label_filter = self._build_labels_query(sketch_id, labels)
must_filters.append(label_filter)
must_filters.append(datetime_ranges)
# Pagination
if query_filter.get('from', None):
query_dsl['from'] = query_filter['from']
# Number of events to return
if query_filter.get('size', None):
query_dsl['size'] = query_filter['size']
# Make sure we are sorting.
if not query_dsl.get('sort', None):
query_dsl['sort'] = {
'datetime': query_filter.get('order', 'asc')
}
# Add any pre defined aggregations
if aggregations:
# post_filter happens after aggregation so we need to move the
# filter to the query instead.
if query_dsl.get('post_filter', None):
query_dsl['query']['bool']['filter'] = query_dsl[
'post_filter']
query_dsl.pop('post_filter', None)
query_dsl['aggregations'] = aggregations
# TODO: Simplify this when we don't have to support both timelines
# that have __ts_timeline_id set and those that don't.
# (query_string AND timeline_id NOT EXISTS) OR (
# query_string AND timeline_id in LIST)
if timeline_ids and isinstance(timeline_ids, (list, tuple)):
must_filters_pre = copy.copy(query_dsl['query']['bool']['must'])
must_not_filters_pre = copy.copy(
query_dsl['query']['bool']['must_not'])
must_filters_post = copy.copy(query_dsl['query']['bool']['must'])
must_not_filters_post = copy.copy(
query_dsl['query']['bool']['must_not'])
must_not_filters_pre.append({
'exists': {
'field': '__ts_timeline_id'},
})
must_filters_post.append({
'terms': {
'__ts_timeline_id': timeline_ids}
})
query_dsl['query'] = {
'bool': {
'must': [],
'should': [{
'bool': {
'must': must_filters_pre,
'must_not': must_not_filters_pre,
}
}, {
'bool': {
'must': must_filters_post,
'must_not': must_not_filters_post,
'filter': [{
'exists': {
'field': '__ts_timeline_id'}
}]
}
}],
'must_not': [],
'filter': []
}
}
return query_dsl
# pylint: disable=too-many-arguments
def search(self, sketch_id, query_string, query_filter, query_dsl, indices,
count=False, aggregations=None, return_fields=None,
enable_scroll=False, timeline_ids=None):
"""Search ElasticSearch. This will take a query string from the UI
together with a filter definition. Based on this it will execute the
search request on ElasticSearch and get result back.
Args:
sketch_id: Integer of sketch primary key
query_string: Query string
query_filter: Dictionary containing filters to apply
query_dsl: Dictionary containing Elasticsearch DSL query
indices: List of indices to query
count: Boolean indicating if we should only return result count
aggregations: Dict of Elasticsearch aggregations
return_fields: List of fields to return
enable_scroll: If Elasticsearch scroll API should be used
timeline_ids: Optional list of IDs of Timeline objects that should
be queried as part of the search.
Returns:
Set of event documents in JSON format
"""
scroll_timeout = None
if enable_scroll:
scroll_timeout = '1m' # Default to 1 minute scroll timeout
# Exit early if we have no indices to query
if not indices:
return {'hits': {'hits': [], 'total': 0}, 'took': 0}
# Check if we have specific events to fetch and get indices.
if query_filter.get('events', None):
indices = {
event['index']
for event in query_filter['events']
if event['index'] in indices
}
query_dsl = self.build_query(
sketch_id=sketch_id, query_string=query_string,
query_filter=query_filter, query_dsl=query_dsl,
aggregations=aggregations, timeline_ids=timeline_ids)
# Default search type for elasticsearch is query_then_fetch.
search_type = 'query_then_fetch'
# Only return how many documents matches the query.
if count:
if 'sort' in query_dsl:
del query_dsl['sort']
try:
count_result = self.client.count(
body=query_dsl, index=list(indices))
except NotFoundError:
es_logger.error(
'Unable to count due to an index not found: {0:s}'.format(
','.join(indices)))
return 0
METRICS['search_requests'].labels(type='count').inc()
return count_result.get('count', 0)
if not return_fields:
# Suppress the lint error because elasticsearch-py adds parameters
# to the function with a decorator and this makes pylint sad.
# pylint: disable=unexpected-keyword-arg
return self.client.search(
body=query_dsl,
index=list(indices),
search_type=search_type,
scroll=scroll_timeout)
# The argument " _source_include" changed to "_source_includes" in
# ES version 7. This check add support for both version 6 and 7 clients.
# pylint: disable=unexpected-keyword-arg
try:
if self.version.startswith('6'):
_search_result = self.client.search(
body=query_dsl,
index=list(indices),
search_type=search_type,
_source_include=return_fields,
scroll=scroll_timeout)
else:
_search_result = self.client.search(
body=query_dsl,
index=list(indices),
search_type=search_type,
_source_includes=return_fields,
scroll=scroll_timeout)
except RequestError as e:
root_cause = e.info.get('error', {}).get('root_cause')
if root_cause:
error_items = []
for cause in root_cause:
error_items.append(
'[{0:s}] {1:s}'.format(
cause.get('type', ''), cause.get('reason', '')))
cause = ', '.join(error_items)
else:
cause = str(e)
es_logger.error(
'Unable to run search query: {0:s}'.format(cause),
exc_info=True)
raise ValueError(cause) from e
METRICS['search_requests'].labels(type='all').inc()
return _search_result
# pylint: disable=too-many-arguments
def search_stream(self, sketch_id=None, query_string=None,
query_filter=None, query_dsl=None, indices=None,
return_fields=None, enable_scroll=True,
timeline_ids=None):
"""Search ElasticSearch. This will take a query string from the UI
together with a filter definition. Based on this it will execute the
search request on ElasticSearch and get result back.
Args :
sketch_id: Integer of sketch primary key
query_string: Query string
query_filter: Dictionary containing filters to apply
query_dsl: Dictionary containing Elasticsearch DSL query
indices: List of indices to query
return_fields: List of fields to return
enable_scroll: Boolean determining whether scrolling is enabled.
timeline_ids: Optional list of IDs of Timeline objects that should
be queried as part of the search.
Returns:
Generator of event documents in JSON format
"""
METRICS['search_requests'].labels(type='streaming').inc()
if not query_filter.get('size'):
query_filter['size'] = self.DEFAULT_STREAM_LIMIT
if not query_filter.get('terminate_after'):
query_filter['terminate_after'] = self.DEFAULT_STREAM_LIMIT
result = self.search(
sketch_id=sketch_id,
query_string=query_string,
query_dsl=query_dsl,
query_filter=query_filter,
indices=indices,
return_fields=return_fields,
enable_scroll=enable_scroll,
timeline_ids=timeline_ids)
if enable_scroll:
scroll_id = result['_scroll_id']
scroll_size = result['hits']['total']
else:
scroll_id = None
scroll_size = 0
# Elasticsearch version 7.x returns total hits as a dictionary.
# TODO: Refactor when version 6.x has been deprecated.
if isinstance(scroll_size, dict):
scroll_size = scroll_size.get('value', 0)
for event in result['hits']['hits']:
yield event
while scroll_size > 0:
# pylint: disable=unexpected-keyword-arg
result = self.client.scroll(scroll_id=scroll_id, scroll='5m')
scroll_id = result['_scroll_id']
scroll_size = len(result['hits']['hits'])
for event in result['hits']['hits']:
yield event
def get_filter_labels(self, sketch_id, indices):
"""Aggregate labels for a sketch.
Args:
sketch_id: The Sketch ID
indices: List of indices to aggregate on
Returns:
List with label names.
"""
# This is a workaround to return all labels by setting the max buckets
# to something big. If a sketch has more than this amount of labels
# the list will be incomplete but it should be uncommon to have >10k
# labels in a sketch.
max_labels = 10000
# pylint: disable=line-too-long
aggregation = {
'aggs': {
'nested': {
'nested': {
'path': 'timesketch_label'
},
'aggs': {
'inner': {
'filter': {
'bool': {
'must': [{
'term': {
'timesketch_label.sketch_id': sketch_id
}
}]
}
},
'aggs': {
'labels': {
'terms': {
'size': max_labels,
'field': 'timesketch_label.name.keyword'
}
}
}
}
}
}
}
}
labels = []
# pylint: disable=unexpected-keyword-arg
try:
result = self.client.search(
index=indices, body=aggregation, size=0)
except NotFoundError:
es_logger.error('Unable to find the index/indices: {0:s}'.format(
','.join(indices)))
return labels
buckets = result.get(
'aggregations', {}).get('nested', {}).get('inner', {}).get(
'labels', {}).get('buckets', [])
for bucket in buckets:
# Filter out special labels like __ts_star etc.
if bucket['key'].startswith('__'):
continue
labels.append(bucket['key'])
return labels
# pylint: disable=inconsistent-return-statements
def get_event(self, searchindex_id, event_id):
"""Get one event from the datastore.
Args:
searchindex_id: String of ElasticSearch index id
event_id: String of ElasticSearch event id
Returns:
Event document in JSON format
"""
METRICS['search_get_event'].inc()
try:
# Suppress the lint error because elasticsearch-py adds parameters
# to the function with a decorator and this makes pylint sad.
# pylint: disable=unexpected-keyword-arg
if self.version.startswith('6'):
event = self.client.get(
index=searchindex_id,
id=event_id,
doc_type='_all',
_source_exclude=['timesketch_label'])
else:
event = self.client.get(
index=searchindex_id,
id=event_id,
doc_type='_all',
_source_excludes=['timesketch_label'])
return event
except NotFoundError:
abort(HTTP_STATUS_CODE_NOT_FOUND)
def count(self, indices):
"""Count number of documents.
Args:
indices: List of indices.
Returns:
Tuple containing number of documents and size on disk.
"""
if not indices:
return 0, 0
try:
es_stats = self.client.indices.stats(
index=indices, metric='docs, store')
except NotFoundError:
es_logger.error(
'Unable to count indices (index not found)')
return 0, 0
except RequestError:
es_logger.error(
'Unable to count indices (request error)', exc_info=True)
return 0, 0
doc_count_total = es_stats.get(
'_all', {}).get('primaries', {}).get('docs', {}).get('count', 0)
doc_bytes_total = es_stats.get(
'_all', {}).get(
'primaries', {}).get('store', {}).get('size_in_bytes', 0)
return doc_count_total, doc_bytes_total
def set_label(self, searchindex_id, event_id, event_type, sketch_id,
user_id, label, toggle=False, remove=False,
single_update=True):
"""Set label on event in the datastore.
Args:
searchindex_id: String of ElasticSearch index id
event_id: String of ElasticSearch event id
event_type: String of ElasticSearch document type
sketch_id: Integer of sketch primary key
user_id: Integer of user primary key
label: String with the name of the label
remove: Optional boolean value if the label should be removed
toggle: Optional boolean value if the label should be toggled
single_update: Boolean if the label should be indexed immediately.
Returns:
Dict with updated document body, or None if this is a single update.
"""
# Elasticsearch painless script.
update_body = {
'script': {
'lang': 'painless',
'source': UPDATE_LABEL_SCRIPT,
'params': {
'timesketch_label': {
'name': str(label),
'user_id': user_id,
'sketch_id': sketch_id
},
remove: remove
}
}
}
if toggle:
update_body['script']['source'] = TOGGLE_LABEL_SCRIPT
if not single_update:
script = update_body['script']
return dict(
source=script['source'], lang=script['lang'],
params=script['params']
)
doc = self.client.get(
index=searchindex_id, id=event_id, doc_type='_all')
try:
doc['_source']['timesketch_label']
except KeyError:
doc = {'doc': {'timesketch_label': []}}
self.client.update(
index=searchindex_id,
doc_type=event_type,
id=event_id,
body=doc)
self.client.update(
index=searchindex_id,
id=event_id,
doc_type=event_type,
body=update_body)
return None
def create_index(
self, index_name=uuid4().hex, doc_type='generic_event',
mappings=None):
"""Create index with Timesketch settings.
Args:
index_name: Name of the index. Default is a generated UUID.
doc_type: Name of the document type. Default id generic_event.
mappings: Optional dict with the document mapping for Elastic.
Returns:
Index name in string format.
Document type in string format.
"""
if mappings:
_document_mapping = mappings
else:
_document_mapping = {
'properties': {
'timesketch_label': {
'type': 'nested'
},
'datetime': {
'type': 'date'
}
}
}
# TODO: Remove when we deprecate Elasticsearch version 6.x
if self.version.startswith('6'):
_document_mapping = {doc_type: _document_mapping}
if not self.client.indices.exists(index_name):
try:
self.client.indices.create(
index=index_name, body={'mappings': _document_mapping})
except ConnectionError as e:
raise RuntimeError(
'Unable to connect to Timesketch backend.') from e
except RequestError:
index_exists = self.client.indices.exists(index_name)
es_logger.warning(
'Attempting to create an index that already exists '
'({0:s} - {1:s})'.format(index_name, str(index_exists)))
return index_name, doc_type
def delete_index(self, index_name):
"""Delete Elasticsearch index.
Args:
index_name: Name of the index to delete.
"""
if self.client.indices.exists(index_name):
try:
self.client.indices.delete(index=index_name)
except ConnectionError as e:
raise RuntimeError(
'Unable to connect to Timesketch backend: {}'.format(e)
) from e
def import_event(self, index_name, event_type, event=None, event_id=None,
flush_interval=DEFAULT_FLUSH_INTERVAL, timeline_id=None):
"""Add event to Elasticsearch.
Args:
index_name: Name of the index in Elasticsearch
event_type: Type of event (e.g. plaso_event)
event: Event dictionary
event_id: Event Elasticsearch ID
flush_interval: Number of events to queue up before indexing
timeline_id: Optional ID number of a Timeline object this event
belongs to. If supplied an additional field will be added to
the store indicating the timeline this belongs to.
"""
if event:
for k, v in event.items():
if not isinstance(k, six.text_type):
k = codecs.decode(k, 'utf8')
# Make sure we have decoded strings in the event dict.
if isinstance(v, six.binary_type):
v = codecs.decode(v, 'utf8')
event[k] = v
# Header needed by Elasticsearch when bulk inserting.
header = {
'index': {
'_index': index_name,
}
}
update_header = {
'update': {
'_index': index_name,
'_id': event_id
}
}
# TODO: Remove when we deprecate Elasticsearch version 6.x
if self.version.startswith('6'):
header['index']['_type'] = event_type
update_header['update']['_type'] = event_type
if event_id:
# Event has "lang" defined if there is a script used for import.
if event.get('lang'):
event = {'script': event}
else:
event = {'doc': event}
header = update_header
if timeline_id:
event['__ts_timeline_id'] = timeline_id
self.import_events.append(header)
self.import_events.append(event)
self.import_counter['events'] += 1
if self.import_counter['events'] % int(flush_interval) == 0:
_ = self.flush_queued_events()
self.import_events = []
else:
# Import the remaining events in the queue.
if self.import_events:
_ = self.flush_queued_events()
return self.import_counter['events']
def flush_queued_events(self, retry_count=0):
"""Flush all queued events.
Returns:
dict: A dict object that contains the number of events
that were sent to Elastic as well as information
on whether there were any errors, and what the
details of these errors if any.
retry_count: optional int indicating whether this is a retry.
"""
if not self.import_events:
return {}
return_dict = {
'number_of_events': len(self.import_events) / 2,
'total_events': self.import_counter['events'],
}
try:
# pylint: disable=unexpected-keyword-arg
results = self.client.bulk(
body=self.import_events, timeout=self._request_timeout)
except (ConnectionTimeout, socket.timeout):
if retry_count >= self.DEFAULT_FLUSH_RETRY_LIMIT:
es_logger.error(
'Unable to add events, reached recount max.',
exc_info=True)
return {}
es_logger.error('Unable to add events (retry {0:d}/{1:d})'.format(
retry_count, self.DEFAULT_FLUSH_RETRY_LIMIT))
return self.flush_queued_events(retry_count + 1)
errors_in_upload = results.get('errors', False)
return_dict['errors_in_upload'] = errors_in_upload
if errors_in_upload:
items = results.get('items', [])
return_dict['errors'] = []
es_logger.error('Errors while attempting to upload events.')
for item in items:
index = item.get('index', {})
index_name = index.get('_index', 'N/A')
_ = self._error_container.setdefault(
index_name, {
'errors': [],
'types': Counter(),
'details': Counter()
}
)
error_counter = self._error_container[index_name]['types']
error_detail_counter = self._error_container[index_name][
'details']
error_list = self._error_container[index_name]['errors']
error = index.get('error', {})
status_code = index.get('status', 0)
doc_id = index.get('_id', '(unable to get doc id)')
caused_by = error.get('caused_by', {})
caused_reason = caused_by.get(
'reason', 'Unkown Detailed Reason')
error_counter[error.get('type')] += 1
detail_msg = '{0:s}/{1:s}'.format(
caused_by.get('type', 'Unknown Detailed Type'),
' '.join(caused_reason.split()[:5])
)
error_detail_counter[detail_msg] += 1
error_msg = '<{0:s}> {1:s} [{2:s}/{3:s}]'.format(
error.get('type', 'Unknown Type'),
error.get('reason', 'No reason given'),
caused_by.get('type', 'Unknown Type'),
caused_reason,
)
error_list.append(error_msg)
try:
es_logger.error(
'Unable to upload document: {0:s} to index {1:s} - '
'[{2:d}] {3:s}'.format(
doc_id, index_name, status_code, error_msg))
# We need to catch all exceptions here, since this is a crucial
# call that we do not want to break operation.
except Exception: # pylint: disable=broad-except
es_logger.error(
'Unable to upload document, and unable to log the '
'error itself.', exc_info=True)
return_dict['error_container'] = self._error_container
self.import_events = []
return return_dict
@property
def version(self):
"""Get Elasticsearch version.
Returns:
Version number as a string.
"""
version_info = self.client.info().get('version')
return version_info.get('number')
| timesketch/lib/datastores/elastic.py | 39,901 | Implements the datastore.
Create a Elasticsearch client.
Build Elasticsearch query for one or more document ids.
Args:
events: List of Elasticsearch document IDs.
Returns:
Elasticsearch query as a dictionary.
Build Elasticsearch query for Timesketch labels.
Args:
sketch_id: Integer of sketch primary key.
labels: List of label names.
Returns:
Elasticsearch query as a dictionary.
Build Elastic Search DSL query by adding in timeline filtering.
Args:
query_dsl: A dict with the current query_dsl
timeline_ids: Either a list of timeline IDs (int) or None.
Returns:
Elasticsearch query DSL as a dictionary.
Convert an interval timestamp into start and end dates.
Args:
interval: Time frame representation
Returns:
Start timestamp in string format.
End timestamp in string format.
Build Elasticsearch DSL query.
Args:
sketch_id: Integer of sketch primary key
query_string: Query string
query_filter: Dictionary containing filters to apply
query_dsl: Dictionary containing Elasticsearch DSL query
aggregations: Dict of Elasticsearch aggregations
timeline_ids: Optional list of IDs of Timeline objects that should
be queried as part of the search.
Returns:
Elasticsearch DSL query as a dictionary
Count number of documents.
Args:
indices: List of indices.
Returns:
Tuple containing number of documents and size on disk.
Create index with Timesketch settings.
Args:
index_name: Name of the index. Default is a generated UUID.
doc_type: Name of the document type. Default id generic_event.
mappings: Optional dict with the document mapping for Elastic.
Returns:
Index name in string format.
Document type in string format.
Delete Elasticsearch index.
Args:
index_name: Name of the index to delete.
Flush all queued events.
Returns:
dict: A dict object that contains the number of events
that were sent to Elastic as well as information
on whether there were any errors, and what the
details of these errors if any.
retry_count: optional int indicating whether this is a retry.
Get one event from the datastore.
Args:
searchindex_id: String of ElasticSearch index id
event_id: String of ElasticSearch event id
Returns:
Event document in JSON format
Aggregate labels for a sketch.
Args:
sketch_id: The Sketch ID
indices: List of indices to aggregate on
Returns:
List with label names.
Add event to Elasticsearch.
Args:
index_name: Name of the index in Elasticsearch
event_type: Type of event (e.g. plaso_event)
event: Event dictionary
event_id: Event Elasticsearch ID
flush_interval: Number of events to queue up before indexing
timeline_id: Optional ID number of a Timeline object this event
belongs to. If supplied an additional field will be added to
the store indicating the timeline this belongs to.
Search ElasticSearch. This will take a query string from the UI
together with a filter definition. Based on this it will execute the
search request on ElasticSearch and get result back.
Args:
sketch_id: Integer of sketch primary key
query_string: Query string
query_filter: Dictionary containing filters to apply
query_dsl: Dictionary containing Elasticsearch DSL query
indices: List of indices to query
count: Boolean indicating if we should only return result count
aggregations: Dict of Elasticsearch aggregations
return_fields: List of fields to return
enable_scroll: If Elasticsearch scroll API should be used
timeline_ids: Optional list of IDs of Timeline objects that should
be queried as part of the search.
Returns:
Set of event documents in JSON format
Search ElasticSearch. This will take a query string from the UI
together with a filter definition. Based on this it will execute the
search request on ElasticSearch and get result back.
Args :
sketch_id: Integer of sketch primary key
query_string: Query string
query_filter: Dictionary containing filters to apply
query_dsl: Dictionary containing Elasticsearch DSL query
indices: List of indices to query
return_fields: List of fields to return
enable_scroll: Boolean determining whether scrolling is enabled.
timeline_ids: Optional list of IDs of Timeline objects that should
be queried as part of the search.
Returns:
Generator of event documents in JSON format
Set label on event in the datastore.
Args:
searchindex_id: String of ElasticSearch index id
event_id: String of ElasticSearch event id
event_type: String of ElasticSearch document type
sketch_id: Integer of sketch primary key
user_id: Integer of user primary key
label: String with the name of the label
remove: Optional boolean value if the label should be removed
toggle: Optional boolean value if the label should be toggled
single_update: Boolean if the label should be indexed immediately.
Returns:
Dict with updated document body, or None if this is a single update.
Get Elasticsearch version.
Returns:
Version number as a string.
Elasticsearch datastore.
Copyright 2015 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. pylint: disable=redefined-builtin Setup logging Metrics definitions Elasticsearch scripts Number of events to queue up when bulk inserting events. Max events to return Max events to return when streaming results Max retries for flushing the queue. Timeout value for importing events. Increase metrics counter per label Remove any aggregation coming from user supplied Query DSL. We have no way to display this data in a good way today. return ('2018-12-05T00:00:00', '2018-12-05T23:59:59') The start date could be 1 or 2 first items New UI filters Exclude chips that the user disabled Increase metrics per chip type Pagination Number of events to return Make sure we are sorting. Add any pre defined aggregations post_filter happens after aggregation so we need to move the filter to the query instead. TODO: Simplify this when we don't have to support both timelines that have __ts_timeline_id set and those that don't. (query_string AND timeline_id NOT EXISTS) OR ( query_string AND timeline_id in LIST) pylint: disable=too-many-arguments Default to 1 minute scroll timeout Exit early if we have no indices to query Check if we have specific events to fetch and get indices. Default search type for elasticsearch is query_then_fetch. Only return how many documents matches the query. Suppress the lint error because elasticsearch-py adds parameters to the function with a decorator and this makes pylint sad. pylint: disable=unexpected-keyword-arg The argument " _source_include" changed to "_source_includes" in ES version 7. This check add support for both version 6 and 7 clients. pylint: disable=unexpected-keyword-arg pylint: disable=too-many-arguments Elasticsearch version 7.x returns total hits as a dictionary. TODO: Refactor when version 6.x has been deprecated. pylint: disable=unexpected-keyword-arg This is a workaround to return all labels by setting the max buckets to something big. If a sketch has more than this amount of labels the list will be incomplete but it should be uncommon to have >10k labels in a sketch. pylint: disable=line-too-long pylint: disable=unexpected-keyword-arg Filter out special labels like __ts_star etc. pylint: disable=inconsistent-return-statements Suppress the lint error because elasticsearch-py adds parameters to the function with a decorator and this makes pylint sad. pylint: disable=unexpected-keyword-arg Elasticsearch painless script. TODO: Remove when we deprecate Elasticsearch version 6.x Make sure we have decoded strings in the event dict. Header needed by Elasticsearch when bulk inserting. TODO: Remove when we deprecate Elasticsearch version 6.x Event has "lang" defined if there is a script used for import. Import the remaining events in the queue. pylint: disable=unexpected-keyword-arg We need to catch all exceptions here, since this is a crucial call that we do not want to break operation. pylint: disable=broad-except | 8,628 | en | 0.767653 |
#!/usr/bin/env python3
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from .mininode import *
from .blockstore import BlockStore, TxStore
from .util import p2p_port
'''
This is a tool for comparing two or more abosomds to each other
using a script provided.
To use, create a class that implements get_tests(), and pass it in
as the test generator to TestManager. get_tests() should be a python
generator that returns TestInstance objects. See below for definition.
'''
# TestNode behaves as follows:
# Configure with a BlockStore and TxStore
# on_inv: log the message but don't request
# on_headers: log the chain tip
# on_pong: update ping response map (for synchronization)
# on_getheaders: provide headers via BlockStore
# on_getdata: provide blocks via BlockStore
global mininode_lock
class RejectResult(object):
'''
Outcome that expects rejection of a transaction or block.
'''
def __init__(self, code, reason=b''):
self.code = code
self.reason = reason
def match(self, other):
if self.code != other.code:
return False
return other.reason.startswith(self.reason)
def __repr__(self):
return '%i:%s' % (self.code,self.reason or '*')
class TestNode(NodeConnCB):
def __init__(self, block_store, tx_store):
NodeConnCB.__init__(self)
self.conn = None
self.bestblockhash = None
self.block_store = block_store
self.block_request_map = {}
self.tx_store = tx_store
self.tx_request_map = {}
self.block_reject_map = {}
self.tx_reject_map = {}
# When the pingmap is non-empty we're waiting for
# a response
self.pingMap = {}
self.lastInv = []
self.closed = False
def on_close(self, conn):
self.closed = True
def add_connection(self, conn):
self.conn = conn
def on_headers(self, conn, message):
if len(message.headers) > 0:
best_header = message.headers[-1]
best_header.calc_sha256()
self.bestblockhash = best_header.sha256
def on_getheaders(self, conn, message):
response = self.block_store.headers_for(message.locator, message.hashstop)
if response is not None:
conn.send_message(response)
def on_getdata(self, conn, message):
[conn.send_message(r) for r in self.block_store.get_blocks(message.inv)]
[conn.send_message(r) for r in self.tx_store.get_transactions(message.inv)]
for i in message.inv:
if i.type == 1:
self.tx_request_map[i.hash] = True
elif i.type == 2:
self.block_request_map[i.hash] = True
def on_inv(self, conn, message):
self.lastInv = [x.hash for x in message.inv]
def on_pong(self, conn, message):
try:
del self.pingMap[message.nonce]
except KeyError:
raise AssertionError("Got pong for unknown ping [%s]" % repr(message))
def on_reject(self, conn, message):
if message.message == b'tx':
self.tx_reject_map[message.data] = RejectResult(message.code, message.reason)
if message.message == b'block':
self.block_reject_map[message.data] = RejectResult(message.code, message.reason)
def send_inv(self, obj):
mtype = 2 if isinstance(obj, CBlock) else 1
self.conn.send_message(msg_inv([CInv(mtype, obj.sha256)]))
def send_getheaders(self):
# We ask for headers from their last tip.
m = msg_getheaders()
m.locator = self.block_store.get_locator(self.bestblockhash)
self.conn.send_message(m)
def send_header(self, header):
m = msg_headers()
m.headers.append(header)
self.conn.send_message(m)
# This assumes BIP31
def send_ping(self, nonce):
self.pingMap[nonce] = True
self.conn.send_message(msg_ping(nonce))
def received_ping_response(self, nonce):
return nonce not in self.pingMap
def send_mempool(self):
self.lastInv = []
self.conn.send_message(msg_mempool())
# TestInstance:
#
# Instances of these are generated by the test generator, and fed into the
# comptool.
#
# "blocks_and_transactions" should be an array of
# [obj, True/False/None, hash/None]:
# - obj is either a CBlock, CBlockHeader, or a CTransaction, and
# - the second value indicates whether the object should be accepted
# into the blockchain or mempool (for tests where we expect a certain
# answer), or "None" if we don't expect a certain answer and are just
# comparing the behavior of the nodes being tested.
# - the third value is the hash to test the tip against (if None or omitted,
# use the hash of the block)
# - NOTE: if a block header, no test is performed; instead the header is
# just added to the block_store. This is to facilitate block delivery
# when communicating with headers-first clients (when withholding an
# intermediate block).
# sync_every_block: if True, then each block will be inv'ed, synced, and
# nodes will be tested based on the outcome for the block. If False,
# then inv's accumulate until all blocks are processed (or max inv size
# is reached) and then sent out in one inv message. Then the final block
# will be synced across all connections, and the outcome of the final
# block will be tested.
# sync_every_tx: analogous to behavior for sync_every_block, except if outcome
# on the final tx is None, then contents of entire mempool are compared
# across all connections. (If outcome of final tx is specified as true
# or false, then only the last tx is tested against outcome.)
class TestInstance(object):
def __init__(self, objects=None, sync_every_block=True, sync_every_tx=False):
self.blocks_and_transactions = objects if objects else []
self.sync_every_block = sync_every_block
self.sync_every_tx = sync_every_tx
class TestManager(object):
def __init__(self, testgen, datadir):
self.test_generator = testgen
self.connections = []
self.test_nodes = []
self.block_store = BlockStore(datadir)
self.tx_store = TxStore(datadir)
self.ping_counter = 1
def add_all_connections(self, nodes):
for i in range(len(nodes)):
# Create a p2p connection to each node
test_node = TestNode(self.block_store, self.tx_store)
self.test_nodes.append(test_node)
self.connections.append(NodeConn('127.0.0.1', p2p_port(i), nodes[i], test_node))
# Make sure the TestNode (callback class) has a reference to its
# associated NodeConn
test_node.add_connection(self.connections[-1])
def clear_all_connections(self):
self.connections = []
self.test_nodes = []
def wait_for_disconnections(self):
def disconnected():
return all(node.closed for node in self.test_nodes)
return wait_until(disconnected, timeout=10)
def wait_for_verack(self):
def veracked():
return all(node.verack_received for node in self.test_nodes)
return wait_until(veracked, timeout=10)
def wait_for_pings(self, counter, timeout=float('inf')):
def received_pongs():
return all(node.received_ping_response(counter) for node in self.test_nodes)
return wait_until(received_pongs, timeout=timeout)
# sync_blocks: Wait for all connections to request the blockhash given
# then send get_headers to find out the tip of each node, and synchronize
# the response by using a ping (and waiting for pong with same nonce).
def sync_blocks(self, blockhash, num_blocks):
def blocks_requested():
return all(
blockhash in node.block_request_map and node.block_request_map[blockhash]
for node in self.test_nodes
)
# --> error if not requested
if not wait_until(blocks_requested, attempts=20*num_blocks, sleep=0.1):
raise AssertionError("Not all nodes requested block")
# Send getheaders message
[ c.cb.send_getheaders() for c in self.connections ]
# Send ping and wait for response -- synchronization hack
[ c.cb.send_ping(self.ping_counter) for c in self.connections ]
self.wait_for_pings(self.ping_counter, timeout=300)
self.ping_counter += 1
# Analogous to sync_block (see above)
def sync_transaction(self, txhash, num_events):
# Wait for nodes to request transaction (50ms sleep * 20 tries * num_events)
def transaction_requested():
return all(
txhash in node.tx_request_map and node.tx_request_map[txhash]
for node in self.test_nodes
)
# --> error if not requested
if not wait_until(transaction_requested, attempts=20*num_events):
raise AssertionError("Not all nodes requested transaction")
# Get the mempool
[ c.cb.send_mempool() for c in self.connections ]
# Send ping and wait for response -- synchronization hack
[ c.cb.send_ping(self.ping_counter) for c in self.connections ]
self.wait_for_pings(self.ping_counter)
self.ping_counter += 1
# Sort inv responses from each node
with mininode_lock:
[ c.cb.lastInv.sort() for c in self.connections ]
# Verify that the tip of each connection all agree with each other, and
# with the expected outcome (if given)
def check_results(self, blockhash, outcome):
with mininode_lock:
for c in self.connections:
if outcome is None:
if c.cb.bestblockhash != self.connections[0].cb.bestblockhash:
return False
elif isinstance(outcome, RejectResult): # Check that block was rejected w/ code
if c.cb.bestblockhash == blockhash:
return False
if blockhash not in c.cb.block_reject_map:
logger.error('Block not in reject map: %064x' % (blockhash))
return False
if not outcome.match(c.cb.block_reject_map[blockhash]):
logger.error('Block rejected with %s instead of expected %s: %064x' % (c.cb.block_reject_map[blockhash], outcome, blockhash))
return False
elif ((c.cb.bestblockhash == blockhash) != outcome):
return False
return True
# Either check that the mempools all agree with each other, or that
# txhash's presence in the mempool matches the outcome specified.
# This is somewhat of a strange comparison, in that we're either comparing
# a particular tx to an outcome, or the entire mempools altogether;
# perhaps it would be useful to add the ability to check explicitly that
# a particular tx's existence in the mempool is the same across all nodes.
def check_mempool(self, txhash, outcome):
with mininode_lock:
for c in self.connections:
if outcome is None:
# Make sure the mempools agree with each other
if c.cb.lastInv != self.connections[0].cb.lastInv:
return False
elif isinstance(outcome, RejectResult): # Check that tx was rejected w/ code
if txhash in c.cb.lastInv:
return False
if txhash not in c.cb.tx_reject_map:
logger.error('Tx not in reject map: %064x' % (txhash))
return False
if not outcome.match(c.cb.tx_reject_map[txhash]):
logger.error('Tx rejected with %s instead of expected %s: %064x' % (c.cb.tx_reject_map[txhash], outcome, txhash))
return False
elif ((txhash in c.cb.lastInv) != outcome):
return False
return True
def run(self):
# Wait until verack is received
self.wait_for_verack()
test_number = 1
for test_instance in self.test_generator.get_tests():
# We use these variables to keep track of the last block
# and last transaction in the tests, which are used
# if we're not syncing on every block or every tx.
[ block, block_outcome, tip ] = [ None, None, None ]
[ tx, tx_outcome ] = [ None, None ]
invqueue = []
for test_obj in test_instance.blocks_and_transactions:
b_or_t = test_obj[0]
outcome = test_obj[1]
# Determine if we're dealing with a block or tx
if isinstance(b_or_t, CBlock): # Block test runner
block = b_or_t
block_outcome = outcome
tip = block.sha256
# each test_obj can have an optional third argument
# to specify the tip we should compare with
# (default is to use the block being tested)
if len(test_obj) >= 3:
tip = test_obj[2]
# Add to shared block_store, set as current block
# If there was an open getdata request for the block
# previously, and we didn't have an entry in the
# block_store, then immediately deliver, because the
# node wouldn't send another getdata request while
# the earlier one is outstanding.
first_block_with_hash = True
if self.block_store.get(block.sha256) is not None:
first_block_with_hash = False
with mininode_lock:
self.block_store.add_block(block)
for c in self.connections:
if first_block_with_hash and block.sha256 in c.cb.block_request_map and c.cb.block_request_map[block.sha256] == True:
# There was a previous request for this block hash
# Most likely, we delivered a header for this block
# but never had the block to respond to the getdata
c.send_message(msg_block(block))
else:
c.cb.block_request_map[block.sha256] = False
# Either send inv's to each node and sync, or add
# to invqueue for later inv'ing.
if (test_instance.sync_every_block):
# if we expect success, send inv and sync every block
# if we expect failure, just push the block and see what happens.
if outcome == True:
[ c.cb.send_inv(block) for c in self.connections ]
self.sync_blocks(block.sha256, 1)
else:
[ c.send_message(msg_block(block)) for c in self.connections ]
[ c.cb.send_ping(self.ping_counter) for c in self.connections ]
self.wait_for_pings(self.ping_counter, timeout=300)
self.ping_counter += 1
if (not self.check_results(tip, outcome)):
raise AssertionError("Test failed at test %d" % test_number)
else:
block_header = CBlockHeader(block)
[ c.cb.send_header(block_header) for c in self.connections ]
elif isinstance(b_or_t, CBlockHeader):
block_header = b_or_t
self.block_store.add_header(block_header)
[ c.cb.send_header(block_header) for c in self.connections ]
else: # Tx test runner
assert(isinstance(b_or_t, CTransaction))
tx = b_or_t
tx_outcome = outcome
# Add to shared tx store and clear map entry
with mininode_lock:
self.tx_store.add_transaction(tx)
for c in self.connections:
c.cb.tx_request_map[tx.sha256] = False
# Again, either inv to all nodes or save for later
if (test_instance.sync_every_tx):
[ c.cb.send_inv(tx) for c in self.connections ]
self.sync_transaction(tx.sha256, 1)
if (not self.check_mempool(tx.sha256, outcome)):
raise AssertionError("Test failed at test %d" % test_number)
else:
invqueue.append(CInv(1, tx.sha256))
# Ensure we're not overflowing the inv queue
if len(invqueue) == MAX_INV_SZ:
[ c.send_message(msg_inv(invqueue)) for c in self.connections ]
invqueue = []
# Do final sync if we weren't syncing on every block or every tx.
if (not test_instance.sync_every_block and block is not None):
if len(invqueue) > 0:
[ c.send_message(msg_inv(invqueue)) for c in self.connections ]
invqueue = []
self.sync_blocks(block.sha256, len(test_instance.blocks_and_transactions))
if (not self.check_results(tip, block_outcome)):
raise AssertionError("Block test failed at test %d" % test_number)
if (not test_instance.sync_every_tx and tx is not None):
if len(invqueue) > 0:
[ c.send_message(msg_inv(invqueue)) for c in self.connections ]
invqueue = []
self.sync_transaction(tx.sha256, len(test_instance.blocks_and_transactions))
if (not self.check_mempool(tx.sha256, tx_outcome)):
raise AssertionError("Mempool test failed at test %d" % test_number)
logger.info("Test %d: PASS" % test_number)
test_number += 1
[ c.disconnect_node() for c in self.connections ]
self.wait_for_disconnections()
self.block_store.close()
self.tx_store.close()
| qa/rpc-tests/test_framework/comptool.py | 18,661 | Outcome that expects rejection of a transaction or block.
!/usr/bin/env python3 Copyright (c) 2015-2016 The Bitcoin Core developers Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. TestNode behaves as follows: Configure with a BlockStore and TxStore on_inv: log the message but don't request on_headers: log the chain tip on_pong: update ping response map (for synchronization) on_getheaders: provide headers via BlockStore on_getdata: provide blocks via BlockStore When the pingmap is non-empty we're waiting for a response We ask for headers from their last tip. This assumes BIP31 TestInstance: Instances of these are generated by the test generator, and fed into the comptool. "blocks_and_transactions" should be an array of [obj, True/False/None, hash/None]: - obj is either a CBlock, CBlockHeader, or a CTransaction, and - the second value indicates whether the object should be accepted into the blockchain or mempool (for tests where we expect a certain answer), or "None" if we don't expect a certain answer and are just comparing the behavior of the nodes being tested. - the third value is the hash to test the tip against (if None or omitted, use the hash of the block) - NOTE: if a block header, no test is performed; instead the header is just added to the block_store. This is to facilitate block delivery when communicating with headers-first clients (when withholding an intermediate block). sync_every_block: if True, then each block will be inv'ed, synced, and nodes will be tested based on the outcome for the block. If False, then inv's accumulate until all blocks are processed (or max inv size is reached) and then sent out in one inv message. Then the final block will be synced across all connections, and the outcome of the final block will be tested. sync_every_tx: analogous to behavior for sync_every_block, except if outcome on the final tx is None, then contents of entire mempool are compared across all connections. (If outcome of final tx is specified as true or false, then only the last tx is tested against outcome.) Create a p2p connection to each node Make sure the TestNode (callback class) has a reference to its associated NodeConn sync_blocks: Wait for all connections to request the blockhash given then send get_headers to find out the tip of each node, and synchronize the response by using a ping (and waiting for pong with same nonce). --> error if not requested Send getheaders message Send ping and wait for response -- synchronization hack Analogous to sync_block (see above) Wait for nodes to request transaction (50ms sleep * 20 tries * num_events) --> error if not requested Get the mempool Send ping and wait for response -- synchronization hack Sort inv responses from each node Verify that the tip of each connection all agree with each other, and with the expected outcome (if given) Check that block was rejected w/ code Either check that the mempools all agree with each other, or that txhash's presence in the mempool matches the outcome specified. This is somewhat of a strange comparison, in that we're either comparing a particular tx to an outcome, or the entire mempools altogether; perhaps it would be useful to add the ability to check explicitly that a particular tx's existence in the mempool is the same across all nodes. Make sure the mempools agree with each other Check that tx was rejected w/ code Wait until verack is received We use these variables to keep track of the last block and last transaction in the tests, which are used if we're not syncing on every block or every tx. Determine if we're dealing with a block or tx Block test runner each test_obj can have an optional third argument to specify the tip we should compare with (default is to use the block being tested) Add to shared block_store, set as current block If there was an open getdata request for the block previously, and we didn't have an entry in the block_store, then immediately deliver, because the node wouldn't send another getdata request while the earlier one is outstanding. There was a previous request for this block hash Most likely, we delivered a header for this block but never had the block to respond to the getdata Either send inv's to each node and sync, or add to invqueue for later inv'ing. if we expect success, send inv and sync every block if we expect failure, just push the block and see what happens. Tx test runner Add to shared tx store and clear map entry Again, either inv to all nodes or save for later Ensure we're not overflowing the inv queue Do final sync if we weren't syncing on every block or every tx. | 4,734 | en | 0.893412 |
# exported from PySB model 'model'
from pysb import Model, Monomer, Parameter, Expression, Compartment, Rule, Observable, Initial, MatchOnce, Annotation, ANY, WILD
Model()
Monomer('Ligand', ['Receptor'])
Monomer('ParpU', ['C3A'])
Monomer('C8A', ['BidU', 'C3pro'])
Monomer('SmacM', ['BaxA'])
Monomer('BaxM', ['BidM', 'BaxA'])
Monomer('Apop', ['C3pro', 'Xiap'])
Monomer('Fadd', ['Receptor', 'C8pro'])
Monomer('SmacC', ['Xiap'])
Monomer('ParpC')
Monomer('Xiap', ['SmacC', 'Apop', 'C3A'])
Monomer('C9')
Monomer('C3ub')
Monomer('C8pro', ['Fadd', 'C6A'])
Monomer('C6A', ['C8pro'])
Monomer('C3pro', ['Apop', 'C8A'])
Monomer('CytoCM', ['BaxA'])
Monomer('CytoCC')
Monomer('BaxA', ['BaxM', 'BaxA_1', 'BaxA_2', 'SmacM', 'CytoCM'])
Monomer('ApafI')
Monomer('BidU', ['C8A'])
Monomer('BidT')
Monomer('C3A', ['Xiap', 'ParpU', 'C6pro'])
Monomer('ApafA')
Monomer('BidM', ['BaxM'])
Monomer('Receptor', ['Ligand', 'Fadd'])
Monomer('C6pro', ['C3A'])
Parameter('bind_0_Ligand_binder_Receptor_binder_target_2kf', 1.0)
Parameter('bind_0_Ligand_binder_Receptor_binder_target_1kr', 1.0)
Parameter('bind_0_Receptor_binder_Fadd_binder_target_2kf', 1.0)
Parameter('bind_0_Receptor_binder_Fadd_binder_target_1kr', 1.0)
Parameter('substrate_binding_0_Fadd_catalyzer_C8pro_substrate_2kf', 1.0)
Parameter('substrate_binding_0_Fadd_catalyzer_C8pro_substrate_1kr', 1.0)
Parameter('catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product_1kc', 1.0)
Parameter('catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_2kf', 1.0)
Parameter('catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_1kr', 1.0)
Parameter('catalysis_1_C8A_catalyzer_BidU_substrate_BidT_product_1kc', 1.0)
Parameter('conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_2kf', 1.0)
Parameter('conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_1kr', 1.0)
Parameter('inhibition_0_SmacC_inhibitor_Xiap_inh_target_2kf', 1.0)
Parameter('inhibition_0_SmacC_inhibitor_Xiap_inh_target_1kr', 1.0)
Parameter('conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_2kf', 1.0)
Parameter('conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_1kr', 1.0)
Parameter('catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_2kf', 1.0)
Parameter('catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_1kr', 1.0)
Parameter('catalysis_1_Apop_catalyzer_C3pro_substrate_C3A_product_1kc', 1.0)
Parameter('inhibition_0_Xiap_inhibitor_Apop_inh_target_2kf', 1.0)
Parameter('inhibition_0_Xiap_inhibitor_Apop_inh_target_1kr', 1.0)
Parameter('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_2kf', 1.0)
Parameter('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_1kr', 1.0)
Parameter('catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product_1kc', 1.0)
Parameter('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_2kf', 1.0)
Parameter('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_1kr', 1.0)
Parameter('catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product_1kc', 1.0)
Parameter('equilibration_0_BidT_equil_a_BidM_equil_b_1kf', 1.0)
Parameter('equilibration_0_BidT_equil_a_BidM_equil_b_1kr', 1.0)
Parameter('catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_2kf', 1.0)
Parameter('catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_1kr', 1.0)
Parameter('catalysis_1_BidM_catalyzer_BaxM_substrate_BaxA_product_1kc', 1.0)
Parameter('self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_2kf', 1.0)
Parameter('self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_1kr', 1.0)
Parameter('self_catalyze_1_BaxA_self_catalyzer_BaxM_self_substrate_1kc', 1.0)
Parameter('pore_formation_0_BaxA_pore_2kf', 1.0)
Parameter('pore_formation_0_BaxA_pore_1kr', 1.0)
Parameter('pore_formation_1_BaxA_pore_2kf', 1.0)
Parameter('pore_formation_1_BaxA_pore_1kr', 1.0)
Parameter('pore_formation_2_BaxA_pore_2kf', 1.0)
Parameter('pore_formation_2_BaxA_pore_1kr', 1.0)
Parameter('transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_2kf', 1.0)
Parameter('transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kr', 1.0)
Parameter('transport_1_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kc', 1.0)
Parameter('transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_2kf', 1.0)
Parameter('transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kr', 1.0)
Parameter('transport_1_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kc', 1.0)
Parameter('catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_2kf', 1.0)
Parameter('catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_1kr', 1.0)
Parameter('catalysis_1_C8A_catalyzer_C3pro_substrate_C3A_product_1kc', 1.0)
Parameter('catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_2kf', 1.0)
Parameter('catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_1kr', 1.0)
Parameter('catalysis_1_C3A_catalyzer_C6pro_substrate_C6A_product_1kc', 1.0)
Parameter('catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_2kf', 1.0)
Parameter('catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_1kr', 1.0)
Parameter('catalysis_1_C6A_catalyzer_C8pro_substrate_C8A_product_1kc', 1.0)
Parameter('Ligand_0', 1000.0)
Parameter('ParpU_0', 1000000.0)
Parameter('C8A_0', 0.0)
Parameter('SmacM_0', 100000.0)
Parameter('BaxM_0', 40000.0)
Parameter('Apop_0', 0.0)
Parameter('Fadd_0', 130000.0)
Parameter('SmacC_0', 0.0)
Parameter('ParpC_0', 0.0)
Parameter('Xiap_0', 40000.0)
Parameter('C9_0', 100000.0)
Parameter('C3ub_0', 0.0)
Parameter('C8pro_0', 130000.0)
Parameter('C6A_0', 0.0)
Parameter('C3pro_0', 21000.0)
Parameter('CytoCM_0', 500000.0)
Parameter('CytoCC_0', 0.0)
Parameter('BaxA_0', 0.0)
Parameter('ApafI_0', 100000.0)
Parameter('BidU_0', 171000.0)
Parameter('BidT_0', 0.0)
Parameter('C3A_0', 0.0)
Parameter('ApafA_0', 0.0)
Parameter('BidM_0', 0.0)
Parameter('Receptor_0', 100.0)
Parameter('C6pro_0', 100.0)
Observable('Ligand_obs', Ligand())
Observable('ParpU_obs', ParpU())
Observable('C8A_obs', C8A())
Observable('SmacM_obs', SmacM())
Observable('BaxM_obs', BaxM())
Observable('Apop_obs', Apop())
Observable('Fadd_obs', Fadd())
Observable('SmacC_obs', SmacC())
Observable('ParpC_obs', ParpC())
Observable('Xiap_obs', Xiap())
Observable('C9_obs', C9())
Observable('C3ub_obs', C3ub())
Observable('C8pro_obs', C8pro())
Observable('C6A_obs', C6A())
Observable('C3pro_obs', C3pro())
Observable('CytoCM_obs', CytoCM())
Observable('CytoCC_obs', CytoCC())
Observable('BaxA_obs', BaxA())
Observable('ApafI_obs', ApafI())
Observable('BidU_obs', BidU())
Observable('BidT_obs', BidT())
Observable('C3A_obs', C3A())
Observable('ApafA_obs', ApafA())
Observable('BidM_obs', BidM())
Observable('Receptor_obs', Receptor())
Observable('C6pro_obs', C6pro())
Rule('bind_0_Ligand_binder_Receptor_binder_target', Ligand(Receptor=None) + Receptor(Ligand=None, Fadd=None) | Ligand(Receptor=1) % Receptor(Ligand=1, Fadd=None), bind_0_Ligand_binder_Receptor_binder_target_2kf, bind_0_Ligand_binder_Receptor_binder_target_1kr)
Rule('bind_0_Receptor_binder_Fadd_binder_target', Receptor(Ligand=ANY, Fadd=None) + Fadd(Receptor=None, C8pro=None) | Receptor(Ligand=ANY, Fadd=1) % Fadd(Receptor=1, C8pro=None), bind_0_Receptor_binder_Fadd_binder_target_2kf, bind_0_Receptor_binder_Fadd_binder_target_1kr)
Rule('substrate_binding_0_Fadd_catalyzer_C8pro_substrate', Fadd(Receptor=ANY, C8pro=None) + C8pro(Fadd=None, C6A=None) | Fadd(Receptor=ANY, C8pro=1) % C8pro(Fadd=1, C6A=None), substrate_binding_0_Fadd_catalyzer_C8pro_substrate_2kf, substrate_binding_0_Fadd_catalyzer_C8pro_substrate_1kr)
Rule('catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product', Fadd(Receptor=ANY, C8pro=1) % C8pro(Fadd=1, C6A=None) >> Fadd(Receptor=ANY, C8pro=None) + C8A(BidU=None, C3pro=None), catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product_1kc)
Rule('catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product', C8A(BidU=None, C3pro=None) + BidU(C8A=None) | C8A(BidU=1, C3pro=None) % BidU(C8A=1), catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_2kf, catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_1kr)
Rule('catalysis_1_C8A_catalyzer_BidU_substrate_BidT_product', C8A(BidU=1, C3pro=None) % BidU(C8A=1) >> C8A(BidU=None, C3pro=None) + BidT(), catalysis_1_C8A_catalyzer_BidU_substrate_BidT_product_1kc)
Rule('conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex', ApafI() + CytoCC() | ApafA(), conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_2kf, conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_1kr)
Rule('inhibition_0_SmacC_inhibitor_Xiap_inh_target', SmacC(Xiap=None) + Xiap(SmacC=None, Apop=None, C3A=None) | SmacC(Xiap=1) % Xiap(SmacC=1, Apop=None, C3A=None), inhibition_0_SmacC_inhibitor_Xiap_inh_target_2kf, inhibition_0_SmacC_inhibitor_Xiap_inh_target_1kr)
Rule('conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex', ApafA() + C9() | Apop(C3pro=None, Xiap=None), conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_2kf, conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_1kr)
Rule('catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product', Apop(C3pro=None, Xiap=None) + C3pro(Apop=None, C8A=None) | Apop(C3pro=1, Xiap=None) % C3pro(Apop=1, C8A=None), catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_2kf, catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_1kr)
Rule('catalysis_1_Apop_catalyzer_C3pro_substrate_C3A_product', Apop(C3pro=1, Xiap=None) % C3pro(Apop=1, C8A=None) >> Apop(C3pro=None, Xiap=None) + C3A(Xiap=None, ParpU=None, C6pro=None), catalysis_1_Apop_catalyzer_C3pro_substrate_C3A_product_1kc)
Rule('inhibition_0_Xiap_inhibitor_Apop_inh_target', Xiap(SmacC=None, Apop=None, C3A=None) + Apop(C3pro=None, Xiap=None) | Xiap(SmacC=None, Apop=1, C3A=None) % Apop(C3pro=None, Xiap=1), inhibition_0_Xiap_inhibitor_Apop_inh_target_2kf, inhibition_0_Xiap_inhibitor_Apop_inh_target_1kr)
Rule('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product', Xiap(SmacC=None, Apop=None, C3A=None) + C3A(Xiap=None, ParpU=None, C6pro=None) | Xiap(SmacC=None, Apop=None, C3A=1) % C3A(Xiap=1, ParpU=None, C6pro=None), catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_2kf, catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_1kr)
Rule('catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product', Xiap(SmacC=None, Apop=None, C3A=1) % C3A(Xiap=1, ParpU=None, C6pro=None) >> Xiap(SmacC=None, Apop=None, C3A=None) + C3ub(), catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product_1kc)
Rule('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product', C3A(Xiap=None, ParpU=None, C6pro=None) + ParpU(C3A=None) | C3A(Xiap=None, ParpU=1, C6pro=None) % ParpU(C3A=1), catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_2kf, catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_1kr)
Rule('catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product', C3A(Xiap=None, ParpU=1, C6pro=None) % ParpU(C3A=1) >> C3A(Xiap=None, ParpU=None, C6pro=None) + ParpC(), catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product_1kc)
Rule('equilibration_0_BidT_equil_a_BidM_equil_b', BidT() | BidM(BaxM=None), equilibration_0_BidT_equil_a_BidM_equil_b_1kf, equilibration_0_BidT_equil_a_BidM_equil_b_1kr)
Rule('catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product', BidM(BaxM=None) + BaxM(BidM=None, BaxA=None) | BidM(BaxM=1) % BaxM(BidM=1, BaxA=None), catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_2kf, catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_1kr)
Rule('catalysis_1_BidM_catalyzer_BaxM_substrate_BaxA_product', BidM(BaxM=1) % BaxM(BidM=1, BaxA=None) >> BidM(BaxM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None), catalysis_1_BidM_catalyzer_BaxM_substrate_BaxA_product_1kc)
Rule('self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxM(BidM=None, BaxA=None) | BaxA(BaxM=1, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) % BaxM(BidM=None, BaxA=1), self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_2kf, self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_1kr)
Rule('self_catalyze_1_BaxA_self_catalyzer_BaxM_self_substrate', BaxA(BaxM=1, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) % BaxM(BidM=None, BaxA=1) >> BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None), self_catalyze_1_BaxA_self_catalyzer_BaxM_self_substrate_1kc)
Rule('pore_formation_0_BaxA_pore', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) | BaxA(BaxM=None, BaxA_1=None, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=None, SmacM=None, CytoCM=None), pore_formation_0_BaxA_pore_2kf, pore_formation_0_BaxA_pore_1kr)
Rule('pore_formation_1_BaxA_pore', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=None, SmacM=None, CytoCM=None) | BaxA(BaxM=None, BaxA_1=3, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None), pore_formation_1_BaxA_pore_2kf, pore_formation_1_BaxA_pore_1kr)
Rule('pore_formation_2_BaxA_pore', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, BaxA_1=3, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) | BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None), pore_formation_2_BaxA_pore_2kf, pore_formation_2_BaxA_pore_1kr)
Rule('transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + SmacM(BaxA=None) | BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=5, CytoCM=None) % SmacM(BaxA=5), transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_2kf, transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kr)
Rule('transport_1_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=5, CytoCM=None) % SmacM(BaxA=5) >> BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + SmacC(Xiap=None), transport_1_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kc)
Rule('transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + CytoCM(BaxA=None) | BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=5) % CytoCM(BaxA=5), transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_2kf, transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kr)
Rule('transport_1_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=5) % CytoCM(BaxA=5) >> BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + CytoCC(), transport_1_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kc)
Rule('catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product', C8A(BidU=None, C3pro=None) + C3pro(Apop=None, C8A=None) | C8A(BidU=None, C3pro=1) % C3pro(Apop=None, C8A=1), catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_2kf, catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_1kr)
Rule('catalysis_1_C8A_catalyzer_C3pro_substrate_C3A_product', C8A(BidU=None, C3pro=1) % C3pro(Apop=None, C8A=1) >> C8A(BidU=None, C3pro=None) + C3A(Xiap=None, ParpU=None, C6pro=None), catalysis_1_C8A_catalyzer_C3pro_substrate_C3A_product_1kc)
Rule('catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product', C3A(Xiap=None, ParpU=None, C6pro=None) + C6pro(C3A=None) | C3A(Xiap=None, ParpU=None, C6pro=1) % C6pro(C3A=1), catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_2kf, catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_1kr)
Rule('catalysis_1_C3A_catalyzer_C6pro_substrate_C6A_product', C3A(Xiap=None, ParpU=None, C6pro=1) % C6pro(C3A=1) >> C3A(Xiap=None, ParpU=None, C6pro=None) + C6A(C8pro=None), catalysis_1_C3A_catalyzer_C6pro_substrate_C6A_product_1kc)
Rule('catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product', C6A(C8pro=None) + C8pro(Fadd=None, C6A=None) | C6A(C8pro=1) % C8pro(Fadd=None, C6A=1), catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_2kf, catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_1kr)
Rule('catalysis_1_C6A_catalyzer_C8pro_substrate_C8A_product', C6A(C8pro=1) % C8pro(Fadd=None, C6A=1) >> C6A(C8pro=None) + C8A(BidU=None, C3pro=None), catalysis_1_C6A_catalyzer_C8pro_substrate_C8A_product_1kc)
Initial(Ligand(Receptor=None), Ligand_0)
Initial(ParpU(C3A=None), ParpU_0)
Initial(C8A(BidU=None, C3pro=None), C8A_0)
Initial(SmacM(BaxA=None), SmacM_0)
Initial(BaxM(BidM=None, BaxA=None), BaxM_0)
Initial(Apop(C3pro=None, Xiap=None), Apop_0)
Initial(Fadd(Receptor=None, C8pro=None), Fadd_0)
Initial(SmacC(Xiap=None), SmacC_0)
Initial(ParpC(), ParpC_0)
Initial(Xiap(SmacC=None, Apop=None, C3A=None), Xiap_0)
Initial(C9(), C9_0)
Initial(C3ub(), C3ub_0)
Initial(C8pro(Fadd=None, C6A=None), C8pro_0)
Initial(C6A(C8pro=None), C6A_0)
Initial(C3pro(Apop=None, C8A=None), C3pro_0)
Initial(CytoCM(BaxA=None), CytoCM_0)
Initial(CytoCC(), CytoCC_0)
Initial(BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None), BaxA_0)
Initial(ApafI(), ApafI_0)
Initial(BidU(C8A=None), BidU_0)
Initial(BidT(), BidT_0)
Initial(C3A(Xiap=None, ParpU=None, C6pro=None), C3A_0)
Initial(ApafA(), ApafA_0)
Initial(BidM(BaxM=None), BidM_0)
Initial(Receptor(Ligand=None, Fadd=None), Receptor_0)
Initial(C6pro(C3A=None), C6pro_0)
| log_complete/model_160.py | 18,818 | exported from PySB model 'model' | 32 | en | 0.742345 |
# Copyright 2014 Eucalyptus Systems, Inc.
#
# Redistribution and use of this software in source and binary forms,
# with or without modification, are permitted provided that the following
# conditions are met:
#
# Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from requestbuilder import Arg
from euca2ools.commands.cloudformation import CloudFormationRequest
class ListStackResources(CloudFormationRequest):
DESCRIPTION = 'List all resources for a stack'
ARGS = [Arg('StackName', metavar='STACK',
help='name of the stack to list resources from (required)')]
LIST_TAGS = ['StackResourceSummaries']
def print_result(self, result):
for resource in result['StackResourceSummaries']:
self.print_resource(resource)
| euca2ools/commands/cloudformation/liststackresources.py | 1,847 | Copyright 2014 Eucalyptus Systems, Inc. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | 1,292 | en | 0.883337 |
# encoding: utf-8
# ## Imports
from threading import local as __local
# Expose these as importable from the top-level `web.core` namespace.
from .application import Application
from .util import lazy
# ## Module Globals
__all__ = ['local', 'Application', 'lazy'] # Symbols exported by this package.
# This is to support the web.ext.local extension, and allow for early importing of the variable.
local = __local()
| web/core/__init__.py | 424 | encoding: utf-8 Imports Expose these as importable from the top-level `web.core` namespace. Module Globals Symbols exported by this package. This is to support the web.ext.local extension, and allow for early importing of the variable. | 237 | en | 0.84951 |
import sys, os, json
version = (3,7)
assert sys.version_info >= version, "This script requires at least Python {0}.{1}".format(version[0],version[1])
# Game loop functions
def render(game,current):
''' Displays the current room '''
print('You are in the ' + game['rooms'][current]['name'])
print(game['rooms'][current]['desc'])
def getInput():
''' Asks the user for input and returns a stripped, uppercase version of what they typed '''
response = input('What would you like to do? ').strip().upper()
return response
def update(response,game,current):
''' Process the input and update the state of the world '''
for e in game['rooms'][current]['exits']:
if response == e['verb']:
current = e['target']
return current
def main():
game = {}
with open('house.json') as json_file:
game = json.load(json_file)
current = 'START'
quit = False
while not quit:
render(game,current)
response = getInput()
current = update(response,game,current)
if response == 'QUIT':
quit = True
if __name__ == '__main__':
main() | main.py | 1,155 | Asks the user for input and returns a stripped, uppercase version of what they typed
Displays the current room
Process the input and update the state of the world
Game loop functions | 187 | en | 0.730608 |
import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
#print(tf.__version__)
def plot_image(i, predictions_array, true_label, img):
predictions_array, true_label, img = predictions_array[i], true_label[i], img[i]
plt.grid(False)
plt.xticks([])
plt.yticks([])
plt.imshow(img, cmap=plt.cm.binary)
predicted_label = np.argmax(predictions_array)
if predicted_label == true_label:
color = 'blue'
else:
color = 'red'
plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],
100*np.max(predictions_array),
class_names[true_label]),
color=color)
def plot_value_array(i, predictions_array, true_label):
predictions_array, true_label = predictions_array[i], true_label[i]
plt.grid(False)
plt.xticks([])
plt.yticks([])
thisplot = plt.bar(range(10), predictions_array, color="#777777")
plt.ylim([0, 1])
predicted_label = np.argmax(predictions_array)
thisplot[predicted_label].set_color('red')
thisplot[true_label].set_color('blue')
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
train_images = train_images / 255.0
test_images = test_images / 255.0
plt.figure(figsize=(10,10))
for i in range(25):
plt.subplot(5,5,i+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(train_images[i], cmap=plt.cm.binary)
plt.xlabel(class_names[train_labels[i]])
plt.show()
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation=tf.nn.relu),
keras.layers.Dense(10, activation=tf.nn.softmax)
])
model.compile(optimizer=tf.train.AdamOptimizer(),
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(train_images, train_labels, epochs=10)
test_loss, test_acc = model.evaluate(test_images, test_labels)
print('Test accuracy:', test_acc)
predictions = model.predict(test_images)
print(predictions[0])
"""num_rows = 5
num_cols = 3
num_images = num_rows*num_cols
plt.figure(figsize=(2*2*num_cols, 2*num_rows))
for i in range(num_images):
plt.subplot(num_rows, 2*num_cols, 2*i+1)
plot_image(i, predictions, test_labels, test_images)
plt.subplot(num_rows, 2*num_cols, 2*i+2)
plot_value_array(i, predictions, test_labels)
plt.show()
"""
| MNIST/mnist.py | 2,603 | print(tf.__version__) | 21 | mk | 0.086436 |
"""Test all API endpoints.
This test class exercises all client facing APIs. It is also usesful as a tool for
demonstrating how to interact with the various APIs.
"""
import json
import pytest
from expects import (be, be_above, be_above_or_equal, contain, equal, expect,
raise_error)
from flask import Response
from tests.utils import post_users
from authserver.db import User, db
ROLES = [
{
'role': 'get:programs',
'description': 'Get from programs data resource',
'rules': {
'key1': 'value1',
'key2': 'value2',
'key3': 'value3',
'key4': 'value4'
}
},
{
'role': 'administer:programs',
'description': 'All access on programs data resource',
'rules': {
'key1': 'value1',
'key2': 'value2',
'key3': 'value3',
'key4': 'value4'
}
},
{
'role': 'edit:providers',
'description': 'Edit providers only'
},
{
'role': 'view:providers',
'description': 'View providers only',
'rules': {
'key1': 'value1',
'key2': 'value2',
'key3': 'value3',
'key4': 'value4'
}
}
]
USERS = [
{
'username': 'user1',
'password': 'password',
'person_id': 'c0ffee-c0ffee-1'
},
{
'username': 'user2',
'password': 'password',
'person_id': 'c0ffee-c0ffee-2'
},
{
'username': 'user3',
'password': 'password',
'person_id': 'c0ffee-c0ffee-3'
},
{
'username': 'user4',
'password': 'password',
'person_id': 'c0ffee-c0ffee-4'
},
{
'username': 'user5',
'password': 'password',
'person_id': 'c0ffee-c0ffee-5'
},
{
'username': 'user6',
'password': 'password',
'person_id': 'c0ffee-c0ffee-6'
},
{
'username': 'user7',
'password': 'password',
'person_id': 'c0ffee-c0ffee-7'
},
{
'username': 'user8',
'password': 'password',
'person_id': 'c0ffee-c0ffee-8'
}
]
CLIENTS = [
{
'client_name': 'test client 1',
'user_id': ''
},
{
'client_name': 'test client 2',
'user_id': ''
},
{
'client_name': 'test client 3',
'user_id': ''
},
{
'client_name': 'test client 4',
'user_id': ''
},
{
'client_name': 'test client 5',
'user_id': ''
},
{
'client_name': 'test client6',
'user_id': ''
},
{
'client_name': 'test client 7',
'user_id': ''
},
{
'client_name': 'test client 8',
'user_id': ''
}
]
class TestAllAPIs(object):
def test_all_apis(self, client, token_generator):
# Common headers go in this dict
headers = {'content-type': 'application/json', 'authorization': f'bearer {token_generator.get_token(client)}'}
# Create users, and clients
user_ids = post_users(USERS, client, token_generator.get_token(client))
client_ids = self._post_clients(client, user_ids, token_generator)
# Create roles
role_ids = []
for role in ROLES:
response = client.post(
'/roles', data=json.dumps(role), headers=headers)
expect(response.status_code).to(equal(201))
role_ids.append(response.json['response'][0]['id'])
# Assign clients to users and roles to client
for i, client_id in enumerate(client_ids):
request_body = {
'user_id': user_ids[i],
'roles': role_ids
}
response = client.patch(
'/clients/{}'.format(client_id), data=json.dumps(request_body), headers=headers)
expect(response.status_code).to(equal(200))
# Ensure that clients actually have roles, users, and other crucial fields
for client_id in client_ids:
response = client.get(
'/clients/{}'.format(client_id), headers=headers)
result = response.json['response']
expect(result['id']).to(equal(client_id))
expect(result['client_id_issued_at']).to(be_above(0))
expect(user_ids).to(contain(result['user_id']))
expect(len(result['roles'])).to(equal(len(role_ids)))
self._cleanup(client, token_generator,
user_ids=user_ids, role_ids=role_ids)
def test_client_secret_delete_rotate(self, client, token_generator):
headers = {'content-type': 'application/json', 'authorization': f'bearer {token_generator.get_token(client)}'}
user_ids = post_users(USERS, client, token_generator.get_token(client))
client_ids = self._post_clients(client, user_ids, token_generator)
client_to_patch = client_ids[0]
response = client.post('/clients?action=delete_secret',
data=json.dumps({"id": client_to_patch}), headers=headers)
expect(response.status_code).to(equal(200))
response = client.get('/clients/{}'.format(client_to_patch), headers=headers)
expect(response.json['response']['client_secret']).to(equal(None))
response = client.post('/clients?action=rotate_secret',
data=json.dumps({"id": client_to_patch}), headers=headers)
expect(response.status_code).to(equal(200))
response = client.get('/clients/{}'.format(client_to_patch), headers=headers)
expect(len(response.json['response']['client_secret'])).to(equal(48))
self._cleanup(client, token_generator, user_ids=user_ids)
def test_client_post_invalid_action(self, client, token_generator):
headers = {'content-type': 'application/json', 'authorization': f'bearer {token_generator.get_token(client)}'}
user_ids = post_users(USERS, client, token_generator.get_token(client))
client_ids = self._post_clients(client, user_ids, token_generator)
client_to_patch = client_ids[0]
response = client.post('/clients?action=some_invalid_action',
data=json.dumps({"id": client_to_patch}), headers=headers)
expect(response.status_code).to(equal(422))
expect(response.json['messages']).to(contain("Invalid query param!"))
self._cleanup(client, token_generator, user_ids=user_ids)
def _post_clients(self, client, user_ids, token_generator):
'''
Helper function that creates (and tests creating) a collection of Clients.
'''
headers = {'content-type': 'application/json', 'authorization': f'bearer {token_generator.get_token(client)}'}
client_ids = []
for i, api_client in enumerate(CLIENTS):
api_client['user_id'] = user_ids[i]
response = client.post('/clients', data=json.dumps(api_client), headers=headers)
expect(response.status_code).to(equal(201))
client_ids.append(response.json['response'][0]['id'])
expect(len(client_ids)).to(equal(8))
return client_ids
def _cleanup(self, client, token_generator, role_ids=[], user_ids=[]):
headers = {'content-type': 'application/json', 'authorization': f'bearer {token_generator.get_token(client)}'}
for role_id in role_ids:
response = client.delete(
'/roles/{}'.format(role_id), headers=headers)
expect(response.status_code).to(equal(200))
for user_id in user_ids:
response = client.delete(
'/users/{}'.format(user_id), headers=headers)
expect(response.status_code).to(equal(200))
def test_assign_scope_to_user(self, client, token_generator):
CLIENT = {
}
USER = {
'username': 'test_user_scope',
'password': 'secret',
'person_id': 'c0ffee-c0ffee-c0ffee-99',
'role_id': ''
}
ROLE = {
'role': 'Administrator',
'description': 'An administrative user role.'
}
SCOPE = {
'scope': 'action:do-all-the-things',
'description': 'A scope that grants the holder superpowers'
}
headers = {'content-type': 'application/json', 'authorization': f'bearer {token_generator.get_token(client)}'}
# Create a role
response = client.post('/roles', data=json.dumps(ROLE), headers=headers)
expect(response.status_code).to(be(201))
role_id = response.json['response'][0]['id']
# Create a scope
response = client.post('/scopes', data=json.dumps(SCOPE), headers=headers)
expect(response.status_code).to(be(201))
scope_id = response.json['response'][0]['id']
# Bind the scope to the role
response = client.post(f'/roles/{role_id}/scopes', data=json.dumps({'scope_id': scope_id}), headers=headers)
expect(response.status_code).to(be(201))
# Create a user and make the user an administrator
USER['role_id'] = role_id
response = client.post('/users', data=json.dumps(USER), headers=headers)
expect(response.status_code).to(be(201))
user_id = response.json['response'][0]['id']
# Cleanup
response = client.delete(f'/users/{user_id}', headers=headers)
expect(response.status_code).to(be(200))
response = client.delete(f'/roles/{role_id}/scopes/{scope_id}', headers=headers)
expect(response.status_code).to(be(200))
response = client.delete(f'/roles/{role_id}', headers=headers)
expect(response.status_code).to(be(200))
response = client.delete(f'/scopes/{scope_id}', headers=headers)
expect(response.status_code).to(be(200))
| tests/api/test_all_apis.py | 9,869 | Helper function that creates (and tests creating) a collection of Clients.
Test all API endpoints.
This test class exercises all client facing APIs. It is also usesful as a tool for
demonstrating how to interact with the various APIs.
Common headers go in this dict Create users, and clients Create roles Assign clients to users and roles to client Ensure that clients actually have roles, users, and other crucial fields Create a role Create a scope Bind the scope to the role Create a user and make the user an administrator Cleanup | 537 | en | 0.869314 |
# Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch
from flash.core.data.data_source import DefaultDataKeys
def vissl_collate_helper(samples):
result = []
for batch_ele in samples:
_batch_ele_dict = {}
_batch_ele_dict.update(batch_ele)
_batch_ele_dict[DefaultDataKeys.INPUT] = -1
result.append(_batch_ele_dict)
return torch.utils.data._utils.collate.default_collate(result)
def multicrop_collate_fn(samples):
"""Multi-crop collate function for VISSL integration.
Run custom collate on a single key since VISSL transforms affect only DefaultDataKeys.INPUT
"""
result = vissl_collate_helper(samples)
inputs = [[] for _ in range(len(samples[0][DefaultDataKeys.INPUT]))]
for batch_ele in samples:
multi_crop_imgs = batch_ele[DefaultDataKeys.INPUT]
for idx, crop in enumerate(multi_crop_imgs):
inputs[idx].append(crop)
for idx, ele in enumerate(inputs):
inputs[idx] = torch.stack(ele)
result[DefaultDataKeys.INPUT] = inputs
return result
def simclr_collate_fn(samples):
"""Multi-crop collate function for VISSL integration.
Run custom collate on a single key since VISSL transforms affect only DefaultDataKeys.INPUT
"""
result = vissl_collate_helper(samples)
inputs = []
num_views = len(samples[0][DefaultDataKeys.INPUT])
view_idx = 0
while view_idx < num_views:
for batch_ele in samples:
imgs = batch_ele[DefaultDataKeys.INPUT]
inputs.append(imgs[view_idx])
view_idx += 1
result[DefaultDataKeys.INPUT] = torch.stack(inputs)
return result
def moco_collate_fn(samples):
"""MOCO collate function for VISSL integration.
Run custom collate on a single key since VISSL transforms affect only DefaultDataKeys.INPUT
"""
result = vissl_collate_helper(samples)
inputs = []
for batch_ele in samples:
inputs.append(torch.stack(batch_ele[DefaultDataKeys.INPUT]))
result[DefaultDataKeys.INPUT] = torch.stack(inputs).squeeze()[:, 0, :, :, :].squeeze()
result["data_momentum"] = torch.stack(inputs).squeeze()[:, 1, :, :, :].squeeze()
return result
| flash/image/embedding/vissl/transforms/utilities.py | 2,742 | MOCO collate function for VISSL integration.
Run custom collate on a single key since VISSL transforms affect only DefaultDataKeys.INPUT
Multi-crop collate function for VISSL integration.
Run custom collate on a single key since VISSL transforms affect only DefaultDataKeys.INPUT
Multi-crop collate function for VISSL integration.
Run custom collate on a single key since VISSL transforms affect only DefaultDataKeys.INPUT
Copyright The PyTorch Lightning team. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. | 987 | en | 0.797343 |
"""Abstract Base Class for posteriors over states after applying filtering/smoothing"""
from abc import ABC, abstractmethod
class FiltSmoothPosterior(ABC):
"""Posterior Distribution over States after Filtering/Smoothing"""
@abstractmethod
def __call__(self, location):
"""Evaluate the time-continuous posterior for a given location
Parameters
----------
location : float
Location, or time, at which to evaluate the posterior.
Returns
-------
rv : `RandomVariable`
"""
raise NotImplementedError
@abstractmethod
def __len__(self):
"""Length of the discrete-time solution
Corresponds to the number of filtering/smoothing steps
"""
raise NotImplementedError
@abstractmethod
def __getitem__(self, idx):
"""Return the corresponding index/slice of the discrete-time solution"""
raise NotImplementedError
def sample(self, locations=None, size=()):
"""
Draw samples from the filtering/smoothing posterior.
If nothing is specified, a single sample is drawn (supported on self.locations).
If locations are specified, the samples are drawn on those locations.
If size is specified, more than a single sample is drawn.
Parameters
----------
locations : array_like, optional
Locations on which the samples are wanted. Default is none, which implies that
self.location is used.
size : int or tuple of ints, optional
Indicates how many samples are drawn. Default is an empty tuple, in which case
a single sample is returned.
Returns
-------
numpy.ndarray
Drawn samples. If size has shape (A1, ..., Z1), locations have shape (L,),
and the state space model has shape (A2, ..., Z2), the output has
shape (A1, ..., Z1, L, A2, ..., Z2).
For example: size=4, len(locations)=4, dim=3 gives shape (4, 4, 3).
"""
raise NotImplementedError("Sampling not implemented.")
| src/probnum/filtsmooth/filtsmoothposterior.py | 2,129 | Posterior Distribution over States after Filtering/Smoothing
Evaluate the time-continuous posterior for a given location
Parameters
----------
location : float
Location, or time, at which to evaluate the posterior.
Returns
-------
rv : `RandomVariable`
Return the corresponding index/slice of the discrete-time solution
Length of the discrete-time solution
Corresponds to the number of filtering/smoothing steps
Draw samples from the filtering/smoothing posterior.
If nothing is specified, a single sample is drawn (supported on self.locations).
If locations are specified, the samples are drawn on those locations.
If size is specified, more than a single sample is drawn.
Parameters
----------
locations : array_like, optional
Locations on which the samples are wanted. Default is none, which implies that
self.location is used.
size : int or tuple of ints, optional
Indicates how many samples are drawn. Default is an empty tuple, in which case
a single sample is returned.
Returns
-------
numpy.ndarray
Drawn samples. If size has shape (A1, ..., Z1), locations have shape (L,),
and the state space model has shape (A2, ..., Z2), the output has
shape (A1, ..., Z1, L, A2, ..., Z2).
For example: size=4, len(locations)=4, dim=3 gives shape (4, 4, 3).
Abstract Base Class for posteriors over states after applying filtering/smoothing | 1,376 | en | 0.831998 |
import logging
from typing import (
Iterable,
List,
)
from lxml import etree
from sciencebeam_parser.document.semantic_document import (
SemanticContentWrapper,
SemanticFigure,
SemanticHeading,
SemanticLabel,
SemanticParagraph,
SemanticRawEquation,
SemanticSection,
SemanticSectionTypes,
SemanticTable
)
from sciencebeam_parser.document.tei.common import (
TEI_E,
TeiElementBuilder
)
from sciencebeam_parser.document.tei.factory import (
SingleElementTeiElementFactory,
T_ElementChildrenList,
TeiElementFactory,
TeiElementFactoryContext
)
LOGGER = logging.getLogger(__name__)
class HeadingTeiElementFactory(SingleElementTeiElementFactory):
def get_tei_element_for_semantic_content(
self,
semantic_content: SemanticContentWrapper,
context: TeiElementFactoryContext
) -> etree.ElementBase:
LOGGER.debug('semantic_content: %s', semantic_content)
assert isinstance(semantic_content, SemanticHeading)
semantic_heading = semantic_content
children: T_ElementChildrenList = [
context.get_default_attributes_for_semantic_content(semantic_heading)
]
pending_whitespace = ''
for child_semantic_content in semantic_heading:
if isinstance(child_semantic_content, SemanticLabel):
children.append({'n': child_semantic_content.get_text()})
continue
layout_block = child_semantic_content.merged_block
if pending_whitespace:
children.append(pending_whitespace)
children.extend(context.iter_layout_block_tei_children(
layout_block=layout_block,
enable_coordinates=False
))
pending_whitespace = layout_block.whitespace
return TEI_E('head', *children)
def iter_flat_paragraph_formula(
semantic_paragraph: SemanticParagraph
) -> Iterable[SemanticContentWrapper]:
pending_semantic_content_list: List[SemanticContentWrapper] = []
for semantic_content in semantic_paragraph:
if isinstance(semantic_content, SemanticRawEquation):
if pending_semantic_content_list:
yield SemanticParagraph(pending_semantic_content_list)
pending_semantic_content_list = []
yield semantic_content
continue
pending_semantic_content_list.append(semantic_content)
if pending_semantic_content_list:
yield SemanticParagraph(pending_semantic_content_list)
class ParagraphTeiElementFactory(TeiElementFactory):
def get_tei_children_for_semantic_content(
self,
semantic_content: SemanticContentWrapper,
context: TeiElementFactoryContext
) -> List[etree.ElementBase]:
LOGGER.debug('semantic_content: %s', semantic_content)
assert isinstance(semantic_content, SemanticParagraph)
semantic_paragraph = semantic_content
result: List[etree.ElementBase] = []
for flat_parent_semantic_content in iter_flat_paragraph_formula(semantic_paragraph):
if not isinstance(flat_parent_semantic_content, SemanticParagraph):
result.extend(context.get_tei_child_elements_for_semantic_content(
flat_parent_semantic_content
))
continue
children: T_ElementChildrenList = [
context.get_default_attributes_for_semantic_content(flat_parent_semantic_content)
]
pending_whitespace = ''
for child_semantic_content in flat_parent_semantic_content:
pending_whitespace = context.append_tei_children_list_and_get_whitespace(
children,
child_semantic_content,
pending_whitespace=pending_whitespace
)
result.append(TEI_E('p', *children))
return result
class SectionTeiElementFactory(TeiElementFactory):
def get_tei_children_for_semantic_content(
self,
semantic_content: SemanticContentWrapper,
context: TeiElementFactoryContext
) -> List[etree.ElementBase]:
LOGGER.debug('semantic_content: %s', semantic_content)
assert isinstance(semantic_content, SemanticSection)
semantic_section = semantic_content
tei_section = TeiElementBuilder(TEI_E('div'))
for child_semantic_content in semantic_section:
if isinstance(child_semantic_content, (SemanticFigure, SemanticTable,)):
# rendered at parent level
continue
tei_section.extend(context.get_tei_child_elements_for_semantic_content(
child_semantic_content
))
if semantic_content.section_type == SemanticSectionTypes.ACKNOWLEDGEMENT:
tei_section.element.attrib['type'] = 'acknowledgement'
if not list(tei_section.element):
return []
return [tei_section.element]
| sciencebeam_parser/document/tei/section.py | 4,994 | rendered at parent level | 24 | en | 0.655194 |
import logging
import sys
from pathlib import Path
from dotenv import load_dotenv
from flask import Flask
from code_runner.extensions import db, limiter
from . import code
def create_app(config_object='code_runner.settings'):
"""Creates and returns flask app instance as well as register all the extensions and blueprints"""
app = Flask(__name__)
register_environment()
app.config.from_object(config_object)
register_blueprints(app=app)
register_views(app=app)
register_extensions(app=app)
configure_logger(app=app)
return app
def register_blueprints(app):
"""Registers the blueprints"""
app.register_blueprint(code.views.blueprint)
def register_views(app):
"""Registers the pluggable views"""
run_view = code.views.RunCode.as_view('run')
run_async_view = code.views.RunCodeAsync.as_view('run-async')
app.add_url_rule('/run', view_func=run_view, methods=['POST'])
app.add_url_rule('/run-async', view_func=run_async_view, methods=['POST'])
app.add_url_rule('/get-result/<string:task_id>', view_func=run_async_view, methods=['GET'])
def register_extensions(app):
"""Register Flask extensions"""
with app.app_context():
db.init_app(app=app)
db.create_all()
limiter.init_app(app=app)
def register_environment():
"""Register environment"""
dotenv_path = Path('./') / '.env.development.local'
load_dotenv(dotenv_path=dotenv_path)
def configure_logger(app):
"""Configure loggers."""
handler = logging.StreamHandler(sys.stdout)
if not app.logger.handlers:
app.logger.addHandler(handler)
| code_runner/app.py | 1,625 | Configure loggers.
Creates and returns flask app instance as well as register all the extensions and blueprints
Registers the blueprints
Register environment
Register Flask extensions
Registers the pluggable views | 213 | en | 0.860433 |
#!/usr/bin/env python3
print( 'hello world' )
| hello_world.py | 47 | !/usr/bin/env python3 | 21 | fr | 0.448822 |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 23 20:32:12 2018
Functions to correctly fold and bin a light curve.
Calculate the lpp metric: transform to lower dimensions, knn
Depends on class from reading in a previously created LPP metric Map
Depends on reading in the light curve to data structure.
input is a class called data
data contains
data.time (days)
data.tzero (day)
data.dur (hours)
data.period (days)
data.flux (normalized to 0)
After foldBinLightCurve it contains
data.binned
After transform it contains
data.lpp_transform
@author: smullally
"""
from __future__ import division
import numpy as np
from sklearn.neighbors import NearestNeighbors
from lpproj import LocalityPreservingProjection
import copy
def computeLPPTransitMetric(data,mapInfo):
"""
This function takes a data class with light curve info
and the mapInfo with information about the mapping to use.
It then returns a lpp metric value.
"""
binFlux, binPhase=foldBinLightCurve(data,mapInfo.ntrfr,mapInfo.npts)
#plt.figure()
#plt.plot(binPhase,binFlux,'.--')
#Dimensionality Reduction and knn parts
rawTLpp,transformedTransit=computeRawLPPTransitMetric(binFlux,mapInfo)
#Normalize by Period Dependence
normTLpp=periodNormalLPPTransitMetric(rawTLpp,np.array([data.period,data.mes]), mapInfo)
return normTLpp,rawTLpp,transformedTransit
def runningMedian(t,y,dt,runt):
"""
Take a running median of size dt
Return values at times given in runt
"""
newy=np.zeros(len(y))
newt=np.zeros(len(y))
srt = np.argsort(t)
newt = t[srt]
newy = y[srt]
runy=[]
for i in range(len(runt)):
tmp=[]
for j in range(len(newt)):
if (newt[j] >= (runt[i]-dt)) and (newt[j] <= (runt[i]+dt)):
tmp.append(newy[j])
if np.isnan(np.nanmedian(np.array(tmp))) :
runy.append(0)
else:
runy.append(np.nanmedian(np.array(tmp)))
return(list(runt),runy)
def foldBinLightCurve (data, ntrfr, npts):
"""
Fold and bin light curve for input to LPP metric calculation
data contains time, tzero, dur, priod,mes and flux (centered around zero)
ntrfr -- number of transit fraction for binning around transit ~1.5
npts -- number of points in the final binning.
"""
#Create phase light curve
phaselc =np.mod((data.time-(data.tzero-0.5*data.period))/data.period,1)
flux=data.flux
mes=data.mes
#Determine the fraction of the time the planet transits the star.
#Insist that ntrfr * transit fraction
if ~np.isnan(data.dur) & (data.dur >0):
transit_dur = data.dur
else:
transit_dur = 0.2 * data.period/24.
transit_fr=transit_dur/24./data.period
if (transit_fr * ntrfr) > 0.5 :
transit_fr = 0.5/ntrfr
#Specify the out of transit (a) and the in transit regions
binover=1.3
if mes <= 20:
binover=-(1/8.0)*mes + 3.8
endfr = .03
midfr= .11
a = np.concatenate((np.arange(endfr,.5-midfr,1/npts) , \
np.arange((0.5+midfr),(1-endfr),1/npts)), axis=None)
ovsamp=4.0
#bstep=(ovsamp*ntrfr*transit_fr)/npts
b_num=41
b =np.linspace((0.5-ntrfr*transit_fr),(0.5+ntrfr*transit_fr),b_num)
#print "length a: %u " % len(a)
#print "length b: %u" % len(b)
[runta,runya] = runningMedian(phaselc,flux,binover/npts,a)
[runtb,runyb] = runningMedian(phaselc,flux,\
(binover*ovsamp*ntrfr*transit_fr)/npts,b)
#Combine the two sets of bins
runymess=np.array(runya + runyb)
runtmess = np.array(runta + runtb)
srt=np.argsort(runtmess)
runy=runymess[srt]
runt=runtmess[srt]
#Scale the flux by the depth so everything has the same depth.
#Catch or dividing by zero is to not scale.
scale = -1*np.min(runyb)
if scale != 0:
scaledFlux=runy/scale
else:
scaledFlux=runy
binnedFlux=scaledFlux
phasebins=runt
return binnedFlux,phasebins
def computeRawLPPTransitMetric(binFlux,mapInfo):
"""
Perform the matrix transformation with LPP
Do the knn test to get a raw LPP transit metric number.
"""
Yorig=mapInfo.YmapMapped
lpp=LocalityPreservingProjection(n_components=mapInfo.n_dim)
lpp.projection_=mapInfo.YmapM
#To equate to Matlab LPP methods, we need to remove mean of transform.
normBinFlux=binFlux-mapInfo.YmapMean
inputY=lpp.transform(normBinFlux.reshape(1,-1))
knownTransitsY=Yorig[mapInfo.knnGood,:]
dist,ind = knnDistance_fromKnown(knownTransitsY,inputY,mapInfo.knn)
rawLppTrMetric=np.mean(dist)
return rawLppTrMetric,inputY
def knnDistance_fromKnown(knownTransits,new,knn):
"""
For a group of known transits and a new one.
Use knn to determine how close the new one is to the known transits
using knn minkowski p = 3 ()
Using scipy signal to do this.
"""
#p=3 sets a minkowski distance of 3. #Check that you really used 3 for matlab.
nbrs=NearestNeighbors(n_neighbors=int(knn), algorithm='kd_tree', p=2)
nbrs.fit(knownTransits)
distances,indices = nbrs.kneighbors(new)
return distances, indices
def periodNormalLPPTransitMetric(rawTLpp,newPerMes, mapInfo):
"""
Normalize the rawTransitMetric value by those with the closest period.
This part removes the period dependence of the metric at short periods.
Plus it makes a value near one be the threshold between good and bad.
newPerMes is the np.array([period, mes]) of the new sample
"""
knownTrPeriods=mapInfo.mappedPeriods[mapInfo.knnGood]
knownTrMes=mapInfo.mappedMes[mapInfo.knnGood]
knownTrrawLpp=mapInfo.dymeans[mapInfo.knnGood]
nPercentil=mapInfo.nPercentil
nPsample=mapInfo.nPsample
#Find the those with the nearest periods Npsample-nneighbors
logPeriods=np.log10(knownTrPeriods)
logMes=np.log10(knownTrMes)
knownPerMes=np.stack((logPeriods, logMes), axis=-1)
np.shape(knownPerMes)
logNew=np.log10(newPerMes).reshape(1,-1)
#logNew=np.array([np.log10(newPeriod)]).reshape(1,1)
dist,ind = knnDistance_fromKnown(knownPerMes,logNew,nPsample)
#Find the nthPercentile of the rawLpp of these indicies
nearPeriodLpp=knownTrrawLpp[ind]
LppNPercentile = np.percentile(nearPeriodLpp,nPercentil)
NormLppTransitMetric=rawTLpp/LppNPercentile
return NormLppTransitMetric
def lpp_onetransit(tcedata,mapInfo,ntransit):
"""
Chop down the full time series to one orbital period.
Then gather the lpp value for that one transit.
"""
startTime=tcedata.time[0]+ntransit*tcedata.period
endTime=tcedata.time[0]+(ntransit+1)*tcedata.period + 3/24.0 #A few cadences of overlap
want=(tcedata.time>=startTime) & (tcedata.time<=endTime)
newtime=tcedata.time[want]
newflux=tcedata.flux[want]
nExpCad=(tcedata.time[-1]-tcedata.time[0])/tcedata.period
if len(newtime>nExpCad*0.75):
onetransit=copy.deepcopy(tcedata)
onetransit.time=newtime
onetransit.flux=newflux
normTLpp, rawTLpp, transformedTr=computeLPPTransitMetric(onetransit,mapInfo)
else:
normTLpp=np.nan
rawTLpp=np.nan
return normTLpp,rawTLpp
def lpp_averageIndivTransit(tcedata,mapInfo):
"""
Create the loop over individual transits and return
array normalized lpp values, mean and std.
Input TCE object and mapInfo object.
It is unclear that this individual transit approach
separates out several new false positives.
It probably would require retuning for low SNR signals.
"""
length=tcedata.time[-1]-tcedata.time[0]
ntransits=int(np.floor(length/tcedata.period))
lppNorms=np.ones(ntransits)
lppRaws=np.ones(ntransits)
nExpCad=(tcedata.time[-1]-tcedata.time[0])/tcedata.period
for i in range(ntransits):
lppNorms[i],lppRaws[i] = lpp_onetransit(tcedata,mapInfo,i)
lppMed=np.nanmedian(lppNorms)
lppStd=np.nanstd(lppNorms)
return lppNorms,lppMed, lppStd, ntransits
| lpp/newlpp/lppTransform.py | 8,388 | This function takes a data class with light curve info
and the mapInfo with information about the mapping to use.
It then returns a lpp metric value.
Perform the matrix transformation with LPP
Do the knn test to get a raw LPP transit metric number.
Fold and bin light curve for input to LPP metric calculation
data contains time, tzero, dur, priod,mes and flux (centered around zero)
ntrfr -- number of transit fraction for binning around transit ~1.5
npts -- number of points in the final binning.
For a group of known transits and a new one.
Use knn to determine how close the new one is to the known transits
using knn minkowski p = 3 ()
Using scipy signal to do this.
Create the loop over individual transits and return
array normalized lpp values, mean and std.
Input TCE object and mapInfo object.
It is unclear that this individual transit approach
separates out several new false positives.
It probably would require retuning for low SNR signals.
Chop down the full time series to one orbital period.
Then gather the lpp value for that one transit.
Normalize the rawTransitMetric value by those with the closest period.
This part removes the period dependence of the metric at short periods.
Plus it makes a value near one be the threshold between good and bad.
newPerMes is the np.array([period, mes]) of the new sample
Take a running median of size dt
Return values at times given in runt
Created on Thu Aug 23 20:32:12 2018
Functions to correctly fold and bin a light curve.
Calculate the lpp metric: transform to lower dimensions, knn
Depends on class from reading in a previously created LPP metric Map
Depends on reading in the light curve to data structure.
input is a class called data
data contains
data.time (days)
data.tzero (day)
data.dur (hours)
data.period (days)
data.flux (normalized to 0)
After foldBinLightCurve it contains
data.binned
After transform it contains
data.lpp_transform
@author: smullally
!/usr/bin/env python2 -*- coding: utf-8 -*-plt.figure()plt.plot(binPhase,binFlux,'.--')Dimensionality Reduction and knn partsNormalize by Period DependenceCreate phase light curveDetermine the fraction of the time the planet transits the star.Insist that ntrfr * transit fractionSpecify the out of transit (a) and the in transit regionsbstep=(ovsamp*ntrfr*transit_fr)/nptsprint "length a: %u " % len(a)print "length b: %u" % len(b)Combine the two sets of binsScale the flux by the depth so everything has the same depth.Catch or dividing by zero is to not scale.To equate to Matlab LPP methods, we need to remove mean of transform.p=3 sets a minkowski distance of 3. Check that you really used 3 for matlab.Find the those with the nearest periods Npsample-nneighborslogNew=np.array([np.log10(newPeriod)]).reshape(1,1)Find the nthPercentile of the rawLpp of these indiciesA few cadences of overlap | 2,838 | en | 0.817715 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-07-17 06:14
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('iiits', '0059_auto_20160717_0609'),
]
operations = [
migrations.AlterField(
model_name='notice',
name='valid_until',
field=models.DateTimeField(default=datetime.datetime(2016, 7, 24, 6, 14, 48, 161315, tzinfo=utc)),
),
migrations.AlterField(
model_name='topstory',
name='title',
field=models.CharField(max_length=255),
),
]
| iiits/migrations/0060_auto_20160717_0614.py | 720 | -*- coding: utf-8 -*- Generated by Django 1.9 on 2016-07-17 06:14 | 65 | en | 0.721973 |
""""
defines a class that maps to the JSON input format and can be used with pydantic.
"""
import json
import os
import pickle
from hashlib import md5
from typing import List, Optional
from pydantic import BaseModel
from mldc.util import NLGEvalOutput
class MetaDlgDataDialog(BaseModel):
id: Optional[str]
domain: str = ""
task_id: str = ""
user_id: str = ""
bot_id: str = ""
turns: List[str]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class MetaDlgDataDialogList(BaseModel):
dialogs: List[MetaDlgDataDialog]
class PartitionSpec(BaseModel):
domains: List[str] = []
tasks: List[str] = []
paths: List[str] = []
def _asdict(self):
# convert to list for json-serializability
return dict(domains=self.domains, tasks=self.tasks, paths=self.paths)
# the next few fields/functions are here to make PartitionSpec behave like
# a pytext ConfigBase object. This way, we can use it directly in a task
# config. It would be easier if we could just inherit from ConfigBase,
# but alas, ConfigBase's metaclass is not a metaclass of BaseModel.
_field_types = __annotations__ # noqa
@property
def _fields(cls):
return cls.__annotations__.keys()
@property
def _field_defaults(cls):
_, defaults = cls.annotations_and_defaults()
return defaults
def is_ok(self, dlg: MetaDlgDataDialog):
if self.tasks and dlg.task_id not in self.tasks:
return False
if self.domains and dlg.domain not in self.domains:
return False
return True
def __bool__(self):
return True if self.domains or self.tasks or self.paths else False
def add(self, other):
self.domains = list(set(self.domains + other.domains))
self.tasks = list(set(self.tasks + other.tasks))
self.paths = list(set(self.paths + other.paths))
@classmethod
def from_paths(cls, paths):
return cls(domains=[], paths=paths, tasks=[])
def iterate_paths(self):
for path in self.paths:
yield path, PartitionSpec(domains=[NLGEvalOutput._domain_name(path)],
paths=[path],
tasks=self.tasks)
def checksum(self, zipfile, featurizer_config, text_embedder_cfg):
checksum = md5(json.dumps(featurizer_config._asdict(), sort_keys=True).encode('utf-8'))
text_embedder_cfg = text_embedder_cfg._asdict()
del text_embedder_cfg['preproc_dir']
del text_embedder_cfg['use_cuda_if_available']
checksum.update(json.dumps(text_embedder_cfg, sort_keys=True).encode('utf-8'))
md5file = zipfile + ".md5"
# if md5file exists and is newer than zipfile, read md5 sum from it
# else calculate it for the zipfile.
if os.path.exists(md5file) and os.path.getmtime(zipfile) <= os.path.getmtime(md5file):
with open(md5file, 'rt') as f:
checksum.update(f.read().split()[0].strip().encode('utf-8'))
else:
with open(zipfile, 'rb') as f:
checksum.update(md5(f.read()).hexdigest().encode('utf-8'))
checksum.update(pickle.dumps(sorted(self.domains)))
checksum.update(pickle.dumps(sorted(self.paths)))
checksum.update(pickle.dumps(sorted(self.tasks)))
return checksum.hexdigest()
class DataSpec(BaseModel):
train: PartitionSpec = PartitionSpec()
validation: PartitionSpec = PartitionSpec()
test: PartitionSpec = PartitionSpec()
def unpack_domains(self):
return [list(p) for p in (self.train.domains, self.validation.domains, self.test.domains)]
def unpack_tasks(self):
return [list(p) for p in (self.train.tasks, self.validation.tasks, self.test.tasks)]
def unpack_paths(self):
return [list(p) for p in (self.train.paths, self.validation.paths, self.test.paths)]
def unpack(self):
return self.train._asdict(), self.validation._asdict(), self.test._asdict()
@classmethod
def load(cls, f):
kwargs = json.load(f)
# This just works with Pydantic
return cls(**kwargs)
def add(self, other):
self.train.add(other.train)
self.validation.add(other.validation)
self.test.add(other.test)
| mldc/data/schema.py | 4,054 | "
defines a class that maps to the JSON input format and can be used with pydantic.
convert to list for json-serializability the next few fields/functions are here to make PartitionSpec behave like a pytext ConfigBase object. This way, we can use it directly in a task config. It would be easier if we could just inherit from ConfigBase, but alas, ConfigBase's metaclass is not a metaclass of BaseModel. noqa if md5file exists and is newer than zipfile, read md5 sum from it else calculate it for the zipfile. This just works with Pydantic | 541 | en | 0.850629 |
from seatable_api import Base, context
import requests
import time
import os
"""
该脚本用于从图片链接下载图片到图片列。你可以在一个文本列中记录图片的地址,然后用这个
脚本自动下载图片并上传到图片列中。
"""
###################---基本信息配置---###################
SERVER_URL = context.server_url or 'https://cloud.seatable.cn/'
API_TOKEN = context.api_token or 'cacc42497886e4d0aa8ac0531bdcccb1c93bd0f5'
TABLE_NAME = 'Table1'
IMAGE_FILE_TYPE = ['jpg', 'png', 'jpeg', 'bmp', 'gif'] # 图片的格式
IMG_URL_COL = '图片链接' # 包含图片链接的列名,需要是 URL 或者文本类型
IMG_COL = 'img' # 用于存储图片的列名,需要是图片类型
IMG_NAME_PRE = 'image' # 图片上传后使用的文件名称前缀
###################---基本信息配置---###################
def get_time_stamp():
return str(int(time.time()*100000))
def img_transfer():
# 1. 创建 base 对象并且认证
base = Base(API_TOKEN, SERVER_URL)
base.auth()
# 2. 获取行信息, 数据结构--列表嵌套字典
"""
数据结构例子:其中'img', '图片链接是用户自定义的列名'
[{
'_id': 'RNn2isDfRnSPWq5HIwRT0w',
'_mtime': '2020-11-10T03:02:55.549+00:00',
'Name': '冉继伟0',
'img': [{
'name': 'cut.png',
'size': 2778797,
'type': 'file',
'url': 'https://dev.seafile.com/dtable-web/workspace/104/asset/1d50c674-ca45-4acf-85b8-19d6e10ca5f0/files/2020-11/cut.png'
}],
'图片链接': 'https://timgsa.baidu.com/timg?image&quality=80xxx.jpg'
}, {
'_id': 'b2lrBxnDSGm1LsZDQTVGhw',
'_mtime': '2020-11-04T08:47:51.562+00:00',
'Name': '冉继伟1'
}, {
'_id': 'RBUZ_g6qS_KER0EjaSclFA',
'_mtime': '2020-11-04T09:26:45.961+00:00',
'Name': '冉继伟2',
'img': None
}, ......]
"""
rows = base.list_rows(TABLE_NAME)
count = 0
#3. 遍历每一行,获取‘图片链接‘列的信息
for row in rows:
time_stamp = get_time_stamp()
img_url = row.get(IMG_URL_COL, None)
img = row.get(IMG_COL, None)
try:
#若无图片链接或者img列有数据的话跳过,防止重复添加
if (not img_url) or img:
continue
#通过url链接获取文件扩展名
img_name_extend = img_url.strip().split('.')[-1]
img_name_extend = img_name_extend in IMAGE_FILE_TYPE and img_name_extend or 'jpg'
#通过uuid对下载的文件进行重命名 IMG_NAME_PRE + 时间戳 + 扩展名
img_name = "/tmp/image-%s.%s"%(time_stamp, img_name_extend)
#下载文件
response = requests.get(img_url)
if response.status_code != 200:
raise Exception('download file error')
with open(img_name, 'wb') as f:
f.write(response.content)
#文件上传
info_dict = base.upload_local_file(img_name, name=None, relative_path=None, file_type='image', replace=True)
row[IMG_COL] = [info_dict.get('url')]
base.update_row('Table1', row['_id'], row)
#上传完成之后删除
os.remove(img_name)
except Exception as err_msg:
print('count%s-%s-%s-message: %s' % (count, row['_id'], img_url, err_msg)) #发现异常打印行数等信息方便回查
continue
count += 1
if __name__ == "__main__":
img_transfer()
| examples/python/image_transfer.py | 3,759 | ---基本信息配置--- 图片的格式 包含图片链接的列名,需要是 URL 或者文本类型 用于存储图片的列名,需要是图片类型 图片上传后使用的文件名称前缀---基本信息配置--- 1. 创建 base 对象并且认证 2. 获取行信息, 数据结构--列表嵌套字典3. 遍历每一行,获取‘图片链接‘列的信息若无图片链接或者img列有数据的话跳过,防止重复添加通过url链接获取文件扩展名通过uuid对下载的文件进行重命名 IMG_NAME_PRE + 时间戳 + 扩展名下载文件文件上传上传完成之后删除发现异常打印行数等信息方便回查 | 264 | zh | 0.988975 |
import os as _os
from glob import glob as _glob
import functools as _functools
from concurrent.futures import ProcessPoolExecutor as _Executor
import tempfile as _tempfile
from six import string_types as _string_types
import tqdm as _tqdm
# expose these two exceptions as part of the API. Everything else should feed into these.
from .exceptions import ConversionError, InvalidArchiveError # NOQA
from .tarball import CondaTarBZ2 as _CondaTarBZ2, libarchive_enabled # NOQA
from .conda_fmt import CondaFormat_v2 as _CondaFormat_v2
from .utils import TemporaryDirectory as _TemporaryDirectory, rm_rf as _rm_rf
SUPPORTED_EXTENSIONS = {'.tar.bz2': _CondaTarBZ2,
'.conda': _CondaFormat_v2}
def _collect_paths(prefix):
dir_paths, file_paths = [], []
for dp, dn, filenames in _os.walk(prefix):
for f in filenames:
file_paths.append(_os.path.relpath(_os.path.join(dp, f), prefix))
dir_paths.extend(_os.path.relpath(_os.path.join(dp, _), prefix) for _ in dn)
file_list = file_paths + [dp for dp in dir_paths
if not any(f.startswith(dp) for f in file_paths)]
return file_list
def get_default_extracted_folder(in_file):
dirname = None
for ext in SUPPORTED_EXTENSIONS:
if in_file.endswith(ext):
dirname = _os.path.basename(in_file)[:-len(ext)]
if not _os.path.isabs(dirname):
dirname = _os.path.normpath(_os.path.join(_os.getcwd(), dirname))
return dirname
def extract(fn, dest_dir=None, components=None):
if dest_dir:
if not _os.path.isabs(dest_dir):
dest_dir = _os.path.normpath(_os.path.join(_os.getcwd(), dest_dir))
if not _os.path.isdir(dest_dir):
_os.makedirs(dest_dir)
else:
dest_dir = get_default_extracted_folder(fn)
for ext in SUPPORTED_EXTENSIONS:
if fn.endswith(ext):
SUPPORTED_EXTENSIONS[ext].extract(fn, dest_dir, components=components)
break
else:
raise ValueError("Didn't recognize extension for file '{}'. Supported extensions are: {}"
.format(fn, list(SUPPORTED_EXTENSIONS.keys())))
def create(prefix, file_list, out_fn, out_folder=None, **kw):
if not out_folder:
out_folder = _os.getcwd()
if file_list is None:
file_list = _collect_paths(prefix)
elif isinstance(file_list, _string_types):
try:
with open(file_list) as f:
data = f.readlines()
file_list = [_.strip() for _ in data]
except:
raise
for ext in SUPPORTED_EXTENSIONS:
if out_fn.endswith(ext):
try:
out = SUPPORTED_EXTENSIONS[ext].create(prefix, file_list, out_fn, out_folder, **kw)
except:
# don't leave broken files around
if _os.path.isfile(out):
_rm_rf(out)
return out
def _convert(fn, out_ext, out_folder, **kw):
basename = get_default_extracted_folder(fn)
from .validate import validate_converted_files_match
if not basename:
print("Input file %s doesn't have a supported extension (%s), skipping it"
% (fn, SUPPORTED_EXTENSIONS))
return
out_fn = _os.path.join(out_folder, basename + out_ext)
errors = ""
if not _os.path.lexists(out_fn):
with _TemporaryDirectory(prefix=out_folder) as tmp:
try:
extract(fn, dest_dir=tmp)
file_list = _collect_paths(tmp)
create(tmp, file_list, _os.path.basename(out_fn), out_folder=out_folder, **kw)
_, missing_files, mismatching_sizes = validate_converted_files_match(
tmp, _os.path.join(out_folder, fn))
if missing_files or mismatching_sizes:
errors = str(ConversionError(missing_files, mismatching_sizes))
except Exception as e:
errors = str(e)
return fn, out_fn, errors
def transmute(in_file, out_ext, out_folder=None, processes=None, **kw):
if not out_folder:
out_folder = _os.path.dirname(in_file) or _os.getcwd()
flist = set(_glob(in_file))
if in_file.endswith('.tar.bz2'):
flist = flist - set(_glob(in_file.replace('.tar.bz2', out_ext)))
elif in_file.endswith('.conda'):
flist = flist - set(_glob(in_file.replace('.conda', out_ext)))
failed_files = {}
with _tqdm.tqdm(total=len(flist), leave=False) as t:
with _Executor(max_workers=processes) as executor:
convert_f = _functools.partial(_convert, out_ext=out_ext,
out_folder=out_folder, **kw)
for fn, out_fn, errors in executor.map(convert_f, flist):
t.set_description("Converted: %s" % fn)
t.update()
if errors:
failed_files[fn] = errors
_rm_rf(out_fn)
return failed_files
def verify_conversion(glob_pattern, target_dir, reference_ext,
tmpdir_root=_tempfile.gettempdir(), processes=None):
from .validate import validate_converted_files_match
if not glob_pattern.endswith(reference_ext):
glob_pattern = glob_pattern + reference_ext
file_sets_by_ext = {ext: _glob(_os.path.join(target_dir, glob_pattern + ext))
for ext in SUPPORTED_EXTENSIONS}
matches = {path.replace(ext, "") for ext, path in file_sets_by_ext[reference_ext]}
for ext, paths in file_sets_by_ext.items():
if ext == reference_ext:
continue
matches &= {path.replace(ext, "") for ext, path in paths}
other_exts = set(SUPPORTED_EXTENSIONS) - {reference_ext, }
errors = {}
with _tqdm.tqdm(total=(len(matches) * len(SUPPORTED_EXTENSIONS) - 1), leave=False) as t:
with _Executor(max_workers=processes) as executor:
for other_ext in other_exts:
verify_fn = lambda fn: validate_converted_files_match(ref_ext=reference_ext,
subject=fn + other_ext)
for fn, missing, mismatching in executor.map(verify_fn, matches):
t.set_description("Validating %s" % fn)
t.update()
if missing or mismatching:
errors[fn] = str(ConversionError(missing, mismatching))
return errors
def get_pkg_details(in_file):
"""For the new pkg format, we return the size and hashes of the inner pkg part of the file"""
for ext in SUPPORTED_EXTENSIONS:
if in_file.endswith(ext):
details = SUPPORTED_EXTENSIONS[ext].get_pkg_details(in_file)
break
else:
raise ValueError("Don't know what to do with file {}".format(in_file))
return details
| src/conda_package_handling/api.py | 6,846 | For the new pkg format, we return the size and hashes of the inner pkg part of the file
expose these two exceptions as part of the API. Everything else should feed into these. NOQA NOQA don't leave broken files around | 220 | en | 0.902269 |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 4 16:39:50 2013
@author: Xiaoxuan Jia
"""
import json
import csv
import re
import scipy.io
import scipy.stats
import random
import numpy as np
import os
import itertools
import cPickle as pk
import pymongo
import scipy
from scipy.stats import norm
import matplotlib.pyplot as plt
def SBcorrection(corr, mult_factor):
pred = (mult_factor*corr)/(1+(mult_factor-1)*corr)
return pred
def normalize_CM(CF):
new_CF = np.zeros(np.shape(CF))
for col in range(0, np.shape(CF)[1]):
total = np.sum(CF[:,col])
norm_col = CF[:,col]/float(total)
new_CF[:,col] = norm_col
return new_CF
def d_prime2x2(CF):
H = CF[0,0]/(CF[0,0]+CF[1,0]) # H = hit/(hit+miss)
F = CF[0,1]/(CF[0,1]+CF[1,1]) # F = False alarm/(false alarm+correct rejection)
if H == 1:
H = 1-1/(2*(CF[0,0]+CF[1,0]))
if H == 0:
H = 0+1/(2*(CF[0,0]+CF[1,0]))
if F == 0:
F = 0+1/(2*(CF[0,1]+CF[1,1]))
if F == 1:
F = 1-1/(2*(CF[0,1]+CF[1,1]))
d = norm.ppf(H)-norm.ppf(F)
return d
def d_prime(CF): #have problem when called by module name, artificially change to n by 5 matrix
d = []
for i in range(len(CF[0][1])):
H = CF[0][i, i]/sum(CF[0][:,i]) # H = target diagnal/target column
tempCF = scipy.delete(CF[0], i, 1) # delete the target column
F = sum(tempCF[i,:])/sum(tempCF)
#if H == 1:
# H = 1-1/(2*sum(CF[0][:,i]))
#if H == 0:
# H = 0+1/(2*sum(CF[0][:,i]))
#if F == 0:
# F = 0+1/(2*sum(tempCF))
#if F == 1:
# F = 1-1/(2*sum(tempCF))
d.append(norm.ppf(H)-norm.ppf(F))
return d
def offDmass(CF):
return sum(CF[np.eye(CF.shape[0])==0]/float(sum(CF)))
class expDataDB(object):
def __init__(self, collection, selector, numObjs, obj, trialNum):
conn = pymongo.Connection(port = 22334, host = 'localhost')
db = conn.mturk
col = db[collection]
self.obj = obj
self.trialNum = trialNum
self.subj_data = list(col.find(selector))
self.numObjs = numObjs
if obj != 'face':
obj_inds = []
for idx, t in enumerate(self.subj_data[0]['ImgData']):
if len(np.unique(obj_inds)) == self.numObjs:
break
else:
if len(t)<10:
obj_inds.append(t[0]['obj'])
else:
obj_inds.append(t['obj'])
self.models = np.unique(obj_inds)
self.models_idxs = {}
for idx, model in enumerate(self.models):
self.models_idxs[model] = idx
self.models_idxs = self.models_idxs
self.trial_data = self.preprocess(self.subj_data, self.obj, self.trialNum)
self.numResp = numObjs
self.totalTrials = len(self.trial_data)
self.corr_type = 'pearson'
def init_from_pickle(self, pkFile):
f = open(pkFile, 'rb')
data = pk.load(f)
f.close()
self.subj_data = data
self.trial_data = self.preprocess(self.subj_data)
self.totalTrials = len(self.trial_data)
def setPopCM(self):
if self.numResp == 2:
self.popCM, self.CM_order = self.getPopCM2x2fast(self.trial_data)
else:
self.popCM, self.CM_order = self.getPopCM(self.trial_data)
def preprocess(self, subj_data, obj, trialNum):
# before the fb experiment, the HvM metadata, uploaded urls dont have unique hash id in the url, after feedback exp, both meta and the pushed json files changed
RV = [] #Response vector
SV = [] #Stimulus vector
DV = [] #Distractor vector
if obj=='face':
RV = [] #Response vector
DV = [] #Distractor vector
RT = []
for subj in self.subj_data: # subj is dict in list subj_data; to access string values in a dist within a list, use subj_data[0]['Response']
models_name = np.unique(subj['Response'])
models_size = np.unique(subj['Size'])
self.models = []
for idx1 in models_name:
for idx2 in models_size:
self.models.append([str(idx1)+'_'+str(idx2)])
models_idxs = {}
for idx, model in enumerate(self.models):
models_idxs[tuple(model)] = idx
self.models_idxs = models_idxs
for t_idx, t in enumerate(subj['RT']):
if t_idx>=trialNum[0] and t_idx<trialNum[1]:
RT.append(t)
for r_idx, r in enumerate(subj['Response']):
if r_idx>=trialNum[0] and r_idx<trialNum[1]:
RV.append([str(r)+'_'+str(subj['Size'][r_idx])])
for s_idx, s in enumerate(subj['StimShown']):
if s_idx>=trialNum[0] and s_idx<trialNum[1]:
DV.append([str(s)+'_'+str(subj['Size'][s_idx])])
elif obj=='obj_lack':
RV_s = [] #Response vector
DV_s = [] #Distractor vector
RV_p = []
DV_p = []
RV_r = []
DV_r = []
RV = []
DV = []
for subj in self.subj_data: # subj is dict in list subj_data; to access string values in a dist within a list, use subj_data[0]['Response']
self.models = np.unique(subj['Response'])
models_idxs = {}
for idx, model in enumerate(self.models):
models_idxs[tuple(model)] = idx
self.models_idxs = models_idxs
for r_idx, r in enumerate(subj['Response']):
if r_idx>=trialNum[0] and r_idx<trialNum[1]:
if subj['ImgData'][r_idx]['tname'] == 'obj_size':
RV_s.append(r)
elif subj['ImgData'][r_idx]['tname'] == 'position':
RV_p.append(r)
elif subj['ImgData'][r_idx]['tname'] == 'rotation':
RV_r.append(r)
else: #'objectome32'
RV.append(r)
for s_idx, s in enumerate(subj['StimPresent']):
if s_idx>=trialNum[0] and s_idx<trialNum[1]:
if subj['ImgData'][s_idx]['tname'] == 'obj_size':
DV_s.append(s)
elif subj['ImgData'][s_idx]['tname'] == 'position':
DV_p.append(s)
elif subj['ImgData'][s_idx]['tname'] == 'rotation':
DV_r.append(s)
else:
DV.append(s)
elif obj=='obj':
RV_s = [] #Response vector
DV_s = [] #Distractor vector
RV_p = []
DV_p = []
RV_r = []
DV_r = []
RV = []
DV = []
for subj in self.subj_data: # subj is dict in list subj_data; to access string values in a dist within a list, use subj_data[0]['Response']
self.models = np.unique(subj['Response'])
models_idxs = {}
for idx, model in enumerate(self.models):
models_idxs[tuple(model)] = idx
self.models_idxs = models_idxs
for r_idx, r in enumerate(subj['Response']):
if r_idx>=trialNum[0] and r_idx<trialNum[1]:
if subj['ImgData'][r_idx][0]['tname'] == 'obj_size':
RV_s.append(r)
elif subj['ImgData'][r_idx][0]['tname'] == 'position':
RV_p.append(r)
elif subj['ImgData'][r_idx][0]['tname'] == 'rotation':
RV_r.append(r)
else: #'objectome32'
RV.append(r)
for s_idx, s in enumerate(subj['StimPresent']):
if s_idx>=trialNum[0] and s_idx<trialNum[1]:
if subj['ImgData'][s_idx][0]['tname'] == 'obj_size':
DV_s.append(s)
elif subj['ImgData'][s_idx][0]['tname'] == 'position':
DV_p.append(s)
elif subj['ImgData'][s_idx][0]['tname'] == 'rotation':
DV_r.append(s)
else:
DV.append(s)
elif obj=='2way':
RV = [] #Response vector
DV = [] #Distractor vector
RV_s = [] #Response vector
DV_s = [] #Distractor vector
SV_s = []
SV = []
for subj in self.subj_data:
for t_idx, t in enumerate(subj['ImgData']):
if t_idx>=trialNum[0] and t_idx<trialNum[1]:
if subj['ImgData'][t_idx][0]['tname'] == 'obj_size':
SV_s.append([t[1]['obj'],t[2]['obj']])
else: #'objectome32'
SV.append([t[1]['obj'],t[2]['obj']])
for r_idx, r in enumerate(subj['Response']):
if r_idx>=trialNum[0] and r_idx<trialNum[1]:
if subj['ImgData'][r_idx][0]['tname'] == 'obj_size':
RV_s.append(r)
else: #'objectome32'
RV.append(r)
for s_idx, s in enumerate(subj['StimPresent']):
if s_idx>=trialNum[0] and s_idx<trialNum[1]:
if subj['ImgData'][s_idx][0]['tname'] == 'obj_size':
DV_s.append(s)
else:
DV.append(s)
elif obj=='2way_face':
RV = [] #Response vector
DV = [] #Distractor vector
RV_s = [] #Response vector
DV_s = [] #Distractor vector
SV_s = []
SV = []
for subj in self.subj_data:
for t_idx, t in enumerate(subj['ImgData']):
if t_idx>=trialNum[0] and t_idx<trialNum[1]:
if subj['ImgData'][t_idx][0]['var'] == 'V0_size':
SV_s.append([t[1]['obj'],t[2]['obj']])
else: #'objectome32'
SV.append([t[1]['obj'],t[2]['obj']])
for r_idx, r in enumerate(subj['Response']):
if r_idx>=trialNum[0] and r_idx<trialNum[1]:
if subj['ImgData'][r_idx][0]['var'] == 'V0_size':
RV_s.append(r)
else: #'objectome32'
RV.append(r)
for s_idx, s in enumerate(subj['StimPresent']):
if s_idx>=trialNum[0] and s_idx<trialNum[1]:
if subj['ImgData'][s_idx][0]['var'] == 'V0_size':
DV_s.append(s)
else:
DV.append(s)
else:
RV = [] #Response vector
DV = [] #Distractor vector
for subj in subj_data: # subj is dict in list subj_data; to access string values in a dist within a list, use subj_data[0]['Response']
self.models = np.unique(subj['TestStim'])
models_idxs = {}
for idx, model in enumerate(self.models):
models_idxs[tuple(model)] = idx
self.models_idxs = models_idxs
for r_idx, r in enumerate(subj['Response']):
if r_idx>=trialNum[0] and r_idx<trialNum[1]:
RV.append(r)
for s_idx, s in enumerate(subj['StimPresent']):
if s_idx>=trialNum[0] and s_idx<trialNum[1]:
DV.append(s)
if obj=='obj':
new_data_s = []
new_data_p = []
new_data_r = []
new_data = []
for idx, shown in enumerate(DV_s):
model = shown
CF_col_idx = self.models_idxs[tuple(model)] #stimulus shown
CF_row_idx = self.models_idxs[tuple(RV_s[idx])] #response
new_data_s.append([CF_col_idx, CF_row_idx, [self.models_idxs[tuple(m)] for m in self.models]]) #order is shown, picked, distractors
for idx, shown in enumerate(DV_p):
model = shown
CF_col_idx = self.models_idxs[tuple(model)] #stimulus shown
CF_row_idx = self.models_idxs[tuple(RV_p[idx])] #response
new_data_p.append([CF_col_idx, CF_row_idx, [self.models_idxs[tuple(m)] for m in self.models]]) #order is shown, picked, distractors
for idx, shown in enumerate(DV_r):
model = shown
CF_col_idx = self.models_idxs[tuple(model)] #stimulus shown
CF_row_idx = self.models_idxs[tuple(RV_r[idx])] #response
new_data_r.append([CF_col_idx, CF_row_idx, [self.models_idxs[tuple(m)] for m in self.models]]) #order is shown, picked, distractors
for idx, shown in enumerate(DV):
model = shown
CF_col_idx = self.models_idxs[tuple(model)] #stimulus shown
CF_row_idx = self.models_idxs[tuple(RV[idx])] #response
new_data.append([CF_col_idx, CF_row_idx, [self.models_idxs[tuple(m)] for m in self.models]]) #order is shown, picked, distractors
return [new_data_s, new_data_p, new_data_r, new_data]
elif obj=='2way':
new_data_s = []
new_data = []
for idx, shown in enumerate(DV_s):
model = shown
CF_col_idx = self.models_idxs[model] #stimulus shown
CF_row_idx = self.models_idxs[RV_s[idx]] #response
new_data_s.append([CF_col_idx, CF_row_idx, [self.models_idxs[m] for m in SV_s[idx]]]) #order is shown, picked, distractors
for idx, shown in enumerate(DV):
model = shown
CF_col_idx = self.models_idxs[model] #stimulus shown
CF_row_idx = self.models_idxs[RV[idx]] #response
new_data.append([CF_col_idx, CF_row_idx, [self.models_idxs[m] for m in SV[idx]]]) #order is shown, picked, distractors
return [new_data_s, new_data]
elif obj=='2way_face':
new_data_s = []
new_data = []
for idx, shown in enumerate(DV_s):
model = shown
CF_col_idx = self.models_idxs[model] #stimulus shown
CF_row_idx = self.models_idxs[RV_s[idx]] #response
new_data_s.append([CF_col_idx, CF_row_idx, [self.models_idxs[m] for m in SV_s[idx]]]) #order is shown, picked, distractors
for idx, shown in enumerate(DV):
model = shown
CF_col_idx = self.models_idxs[model] #stimulus shown
CF_row_idx = self.models_idxs[RV[idx]] #response
new_data.append([CF_col_idx, CF_row_idx, [self.models_idxs[m] for m in SV[idx]]]) #order is shown, picked, distractors
return [new_data_s, new_data]
elif obj=='face':
new_data = []
for idx, shown in enumerate(DV):
if RT[idx]<3000:
model = shown
CF_col_idx = self.models_idxs[tuple(model)] #stimulus shown
CF_row_idx = self.models_idxs[tuple(RV[idx])] #response
new_data.append([CF_col_idx, CF_row_idx, [self.models_idxs[tuple(m)] for m in self.models]]) #order is shown, picked, distractors
return new_data
else:
new_data = []
for idx, shown in enumerate(DV):
model = shown
CF_col_idx = self.models_idxs[tuple(model)] #stimulus shown
CF_row_idx = self.models_idxs[tuple(RV[idx])] #response
new_data.append([CF_col_idx, CF_row_idx, [self.models_idxs[tuple(m)] for m in self.models]]) #order is shown, picked, distractors
return new_data
def getPopCM2x2fast(self, trial_data):
combs = list(itertools.combinations(range(0, self.numObjs), 2))
CMs = {}
for c in combs:
CMs[c] = np.zeros((2,2))
for t in trial_data: # each trial can only increase +1 in total; statistics is based on many trials
target = t[0]
pick = t[1]
cm = tuple(sorted(t[2])) #Because itertools always spits out the combs in sorted order; the two-way task is designed for each pair, either target is presented with equal times
if target == cm[0]: #stimulus = True: when the signal present
if target == pick: #response = true; Hit
CMs[cm][0,0] += 1
else: # response = False; Miss
CMs[cm][1,0] += 1
else: # stimulus = False; when the signal does not present
if target == pick: # response = false; correct rejection
CMs[cm][1,1] += 1
else: # response = true; false alarm
CMs[cm][0,1] += 1
return [CMs[c] for c in combs], combs
def getPopCM(self, trial_data, order=[]): # trial_data is for individual subj or for all subj (myresult.trial_data)
if len(trial_data[0][2]) != len(self.trial_data[0][2]):
numResp = len(trial_data[0][2]) # should not use self.trial_data
else:
numResp = len(self.trial_data[0][2])
#print numResp
obj_inds = []
for t in trial_data:
if len(np.unique(obj_inds)) == self.numObjs:
break
else:
obj_inds.append(t[0])
if len(np.unique(obj_inds)) != self.numObjs:
obj_inds = range(self.numObjs)
else:
obj_inds = obj_inds
combs = list(itertools.combinations(np.unique(obj_inds), numResp))
CMs = [np.zeros((numResp, numResp)) for i in range(0, len(combs))]
for trial in trial_data:
distractor = [m for m in trial[2] if m != trial[0]]
target = trial[0]
pick = trial[1]
possCombs = [[comb, idx] for idx, comb in enumerate(combs) if target in comb]
for comb in possCombs:
if set(distractor).issubset(set(comb[0])):
if len(order) > 0:
comb[0] = order
if pick == target:
idx = comb[0].index(pick)
CMs[comb[1]][idx, idx] += 1
elif pick != target:
CMs[comb[1]][comb[0].index(pick), comb[0].index(target)] += 1
else:
print('Matrix Error')
return CMs, combs
def getexposureCM(self, trial_data, trialNum, expoNum): # trial_data is for individual subj or for all subj (myresult.trial_data)
if len(trial_data[0][2]) != len(self.trial_data[0][2]):
numResp = len(trial_data[0][2]) # should not use self.trial_data
else:
numResp = len(self.trial_data[0][2])
#print numResp
obj_inds = []
for t in trial_data:
if len(np.unique(obj_inds)) == self.numObjs:
break
else:
obj_inds.append(t[0])
condi = self.subj_data[0]['Combinations']
newcondi = []
s1 = set(['NONSWAP', 'SWAP'])
for subj in self.subj_data:
s2 = set(subj.keys())
for s in subj[list(s1.intersection(s2))[0]]:
newcondi.append([x for idx, x in enumerate(condi[int(s)]) if idx>= expoNum[0] and idx<expoNum[1]]) #need to modify if the total number of condtion change
if len(newcondi) != len(trial_data):
print('trial number inconsistent')
else:
print(str(len(trial_data)))
RV = [] #Response vector
DV = [] #Distractor vector
for subj in self.subj_data: # subj is dict in list subj_data; to access string values in a dist within a list, use subj_data[0]['Response']
models = np.unique(subj['Response'])
self.models = []
for idx in models:
self.models.append(idx)
models_idxs = {}
for idx, model in enumerate(self.models):
models_idxs[tuple(model)] = idx
self.models_idxs = models_idxs
for r_idx, r in enumerate(subj['Response']):
if r_idx>=trialNum[0] and r_idx<trialNum[1]:
RV.append(r)
for s_idx, s in enumerate(subj['StimShown']):
if s_idx>=trialNum[0] and s_idx<trialNum[1]:
DV.append(s)
new_data = []
for idx, shown in enumerate(DV):
model = shown
CF_col_idx = self.models_idxs[tuple(model)] #stimulus shown
CF_row_idx = self.models_idxs[tuple(RV[idx])] #response
new_data.append([CF_col_idx, CF_row_idx, [self.models_idxs[tuple(m)] for m in self.models]]) #order is shown, picked, distractors
return newcondi, new_data
def computeSplitHalf_size(self, numSplits, subsample, verbose = False, correct = True, plot_ = False): #subsample equal to total trial number if don't want to subsample
import scipy.stats
trial_data = self.trial_data
Rs = []
for s in range(0, numSplits):
if verbose == True:
print(s)
else:
pass
np.random.shuffle(trial_data)
if int(subsample)%2 == 0:
half1.extend(t[0:subsample/2])
half2.extend(t[-subsample/2:])
else:
half1.extend(t[0:subsample/2+1])
half2.extend(t[-subsample/2:])
if self.numResp == 2:
CM1, combs = self.getPopCM2x2fast(half1)
CM2, combs = self.getPopCM2x2fast(half2)
else:
CM1, combs = self.getPopCM(half1)
CM2, combs = self.getPopCM(half2)
half1_array = []
half2_array = []
for mat in range(0, len(CM1)):
newarray = np.reshape(normalize_CM(CM1[mat]),(CM1[mat].shape[0]*CM1[mat].shape[1],-1))
half1_array += list([x for x in newarray if x!=0])
newarray = np.reshape(normalize_CM(CM2[mat]),(CM2[mat].shape[0]*CM2[mat].shape[1],-1))
half2_array += list([x for x in newarray if x!=0])
if self.corr_type == 'pearson':
Rs.append(scipy.stats.pearsonr(half1_array, half2_array)[0])
#correct = False
else:
Rs.append(scipy.stats.spearmanr(half1_array, half2_array)[0])
if plot_ == True:
plt.plot(half1_array, half2_array, 'b.')
if correct == False:
return Rs
else:
Rs_c = [SBcorrection(r, 2) for r in Rs]
return Rs_c
def computeSplitHalf_dprime(self, pair_trial_data, boot, starttrial, verbose = False, correct = True, plot_ = False, trial_data = None): #subsample equal to total trial number if don't want to subsample
import scipy.stats
count = [len(trial) for trial in pair_trial_data]
corr_dprime = []
for i in range(boot):
temp = []
for w in range(min(count)-starttrial+1):
a = [random.sample(trial, w+starttrial) for trial in pair_trial_data]
subsample = len(a[0])
Rs = []
for b in range(boot):
half1 = []
half2 = []
for t in a:
np.random.shuffle(t)
if int(subsample)%2 == 0:
half1.extend(t[0:subsample/2])
half2.extend(t[-subsample/2:])
else:
half1.extend(t[0:subsample/2+1])
half2.extend(t[-subsample/2:])
CM1, combs = self.getPopCM2x2fast(half1)
CM2, combs = self.getPopCM2x2fast(half2)
half1_dprime = []
half2_dprime = []
for mat in range(0, len(CM1)):
half1_dprime.append(d_prime2x2(CM1[mat])) # previously normalized CM, which caused nan when divided by 0
half2_dprime.append(d_prime2x2(CM2[mat]))
Rs.append(scipy.stats.spearmanr(half1_dprime, half2_dprime)[0])
temp.append(np.ma.masked_invalid(Rs).mean(0))
corr_dprime.append(temp)
return corr_dprime
def computeSplitHalf(self, numSplits, subsample, verbose = False, correct = True, plot_ = False, trial_data = None): #subsample equal to total trial number if don't want to subsample
import scipy.stats
if trial_data == None:
trial_data = self.trial_data
else:
trial_data = trial_data
Rs = []
for s in range(0, numSplits):
if verbose == True:
print(s)
else:
pass
np.random.shuffle(trial_data)
half1 = []
half2 = []
if int(subsample)%2 == 0:
half1.extend(trial_data[0:subsample/2])
half2.extend(trial_data[-subsample/2:])
else:
half1.extend(trial_data[0:subsample/2+1])
half2.extend(trial_data[-subsample/2:])
if self.numResp == 2:
CM1, combs = self.getPopCM2x2fast(half1)
CM2, combs = self.getPopCM2x2fast(half2)
else:
CM1, combs = self.getPopCM(half1)
CM2, combs = self.getPopCM(half2)
half1_array = []
half2_array = []
for mat in range(0, len(CM1)):
half1_array += list(normalize_CM(CM1[mat])[np.eye(CM1[mat].shape[0])==0])
half2_array += list(normalize_CM(CM2[mat])[np.eye(CM2[mat].shape[0])==0])
if self.corr_type == 'pearson':
Rs.append(scipy.stats.pearsonr(half1_array, half2_array)[0])
#correct = False
else:
Rs.append(scipy.stats.spearmanr(half1_array, half2_array)[0])
if plot_ == True:
plt.plot(half1_array, half2_array, 'b.')
if correct == False:
return Rs
else:
Rs_c = [SBcorrection(r, 2) for r in Rs]
return Rs_c
def imputeNtoM(self, use_objects):
#Produces a single imputed matrix of a given size for given objects. The matrix will have blank entries
#if you ask for a greater size than is given by the number of objects represented by your data
obj_inds = []
for t in self.trial_data:
if len(np.unique(obj_inds)) == self.numObjs:
break
else:
obj_inds.append(t[0])
t = []
for obj in use_objects:
t.append(self.models.index(obj))
import itertools
combs = list(itertools.combinations(t, self.numResp))
CM_imputed = np.zeros((len(t),len(t)))
for trial in self.trial_data:
for comb in combs:
if set(comb).issubset(set(trial[2])):
if trial[0] == trial[1]:
CM_imputed[t.index(trial[0]), t.index(trial[0])] += 1
else:
CM_imputed[t.index(trial[1]), t.index(trial[0])] += 1
return CM_imputed
| code/learningutil.py | 28,030 | Created on Thu Oct 4 16:39:50 2013
@author: Xiaoxuan Jia
-*- coding: utf-8 -*- H = hit/(hit+miss) F = False alarm/(false alarm+correct rejection)have problem when called by module name, artificially change to n by 5 matrix H = target diagnal/target column delete the target columnif H == 1: H = 1-1/(2*sum(CF[0][:,i]))if H == 0: H = 0+1/(2*sum(CF[0][:,i]))if F == 0: F = 0+1/(2*sum(tempCF))if F == 1: F = 1-1/(2*sum(tempCF)) before the fb experiment, the HvM metadata, uploaded urls dont have unique hash id in the url, after feedback exp, both meta and the pushed json files changedResponse vectorStimulus vectorDistractor vectorResponse vectorDistractor vector subj is dict in list subj_data; to access string values in a dist within a list, use subj_data[0]['Response']Response vectorDistractor vector subj is dict in list subj_data; to access string values in a dist within a list, use subj_data[0]['Response']'objectome32'Response vectorDistractor vector subj is dict in list subj_data; to access string values in a dist within a list, use subj_data[0]['Response']'objectome32'Response vectorDistractor vectorResponse vectorDistractor vector'objectome32''objectome32'Response vectorDistractor vectorResponse vectorDistractor vector'objectome32''objectome32'Response vectorDistractor vector subj is dict in list subj_data; to access string values in a dist within a list, use subj_data[0]['Response']stimulus shownresponseorder is shown, picked, distractorsstimulus shownresponseorder is shown, picked, distractorsstimulus shownresponseorder is shown, picked, distractorsstimulus shownresponseorder is shown, picked, distractorsstimulus shownresponseorder is shown, picked, distractorsstimulus shownresponseorder is shown, picked, distractorsstimulus shownresponseorder is shown, picked, distractorsstimulus shownresponseorder is shown, picked, distractorsstimulus shownresponseorder is shown, picked, distractorsstimulus shownresponseorder is shown, picked, distractors each trial can only increase +1 in total; statistics is based on many trialsBecause itertools always spits out the combs in sorted order; the two-way task is designed for each pair, either target is presented with equal timesstimulus = True: when the signal presentresponse = true; Hit response = False; Miss stimulus = False; when the signal does not present response = false; correct rejection response = true; false alarm trial_data is for individual subj or for all subj (myresult.trial_data) should not use self.trial_dataprint numResp trial_data is for individual subj or for all subj (myresult.trial_data) should not use self.trial_dataprint numRespneed to modify if the total number of condtion changeResponse vectorDistractor vector subj is dict in list subj_data; to access string values in a dist within a list, use subj_data[0]['Response']stimulus shownresponseorder is shown, picked, distractorssubsample equal to total trial number if don't want to subsamplecorrect = Falsesubsample equal to total trial number if don't want to subsample previously normalized CM, which caused nan when divided by 0subsample equal to total trial number if don't want to subsamplecorrect = FalseProduces a single imputed matrix of a given size for given objects. The matrix will have blank entriesif you ask for a greater size than is given by the number of objects represented by your data | 3,372 | en | 0.808501 |
# -*- coding: utf-8 -*-
# IFD.A-8 :: Версия: 1 :: Проверка ввода невалидного значения в поле "код IATA" для выбора аэропорта
# Шаг 1
def test_check_invalid_value_IATA_to_select_airport(app):
app.session.enter_login(username="test")
app.session.enter_password(password="1245")
app.airport.open_form_add_airport()
app.airport.enter_IATA_code(iata_cod="QWE")
app.airport.search_airport_by_parameter()
app.airport.message_no_airports()
app.airport.exit_from_the_add_airport_form()
app.session.logout()
# IFD.A-8 :: Версия: 1 :: Проверка ввода невалидного значения в поле "код IATA" для выбора аэропорта
# Шаг 2
def test_check_invalid_characters_in_IATA_code(app):
app.session.enter_login(username="test")
app.session.enter_password(password="1245")
app.airport.open_form_add_airport()
app.airport.enter_IATA_code(iata_cod="!№;%:?*")
app.airport.wait_massege_no_airport()
app.airport.exit_from_the_add_airport_form()
app.session.logout() | test/test_check_invalid_value_IATA_code.py | 1,130 | -*- coding: utf-8 -*- IFD.A-8 :: Версия: 1 :: Проверка ввода невалидного значения в поле "код IATA" для выбора аэропорта Шаг 1 IFD.A-8 :: Версия: 1 :: Проверка ввода невалидного значения в поле "код IATA" для выбора аэропорта Шаг 2 | 231 | ru | 0.94779 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import argparse
import logging
import multiprocessing as mp
import numpy as np
import os
import torch
from detectron2.config import get_cfg
from detectron2.data import MetadataCatalog
from detectron2.data.detection_utils import read_image
from detectron2.engine.defaults import DefaultPredictor
from detectron2.utils.logger import setup_logger
from pytorch3d.io import save_obj
from pytorch3d.structures import Meshes
# required so that .register() calls are executed in module scope
import meshrcnn.data # noqa
import meshrcnn.modeling # noqa
import meshrcnn.utils # noqa
from meshrcnn.config import get_meshrcnn_cfg_defaults
from meshrcnn.evaluation import transform_meshes_to_camera_coord_system
def get_parser():
parser = argparse.ArgumentParser(description="MeshRCNN Demo")
parser.add_argument(
"--config-file",
default="configs/pix3d/meshrcnn_R50_FPN.yaml",
metavar="FILE",
help="path to config file",
)
parser.add_argument("--input", help="A path to an input image")
parser.add_argument("--output", help="A directory to save output visualizations")
parser.add_argument(
"--focal-length", type=float, default=20.0, help="Focal length for the image"
)
parser.add_argument(
"--onlyhighest", action="store_true", help="will return only the highest scoring detection"
)
parser.add_argument(
"opts",
help="Modify model config options using the command-line",
default=None,
nargs=argparse.REMAINDER,
)
return parser
args = get_parser().parse_args()
from meshrcnn.data.datasets.register_pix3d import register_pix3d
register_pix3d(args.opts[1])
import cv2
logger = logging.getLogger("demo")
class VisualizationDemo(object):
def __init__(self, cfg, vis_highest_scoring=True, output_dir="./vis"):
"""
Args:
cfg (CfgNode):
vis_highest_scoring (bool): If set to True visualizes only
the highest scoring prediction
"""
self.metadata = MetadataCatalog.get(cfg.DATASETS.TEST[0])
self.colors = self.metadata.thing_colors
self.cat_names = self.metadata.thing_classes
self.cpu_device = torch.device("cpu")
self.vis_highest_scoring = vis_highest_scoring
self.predictor = DefaultPredictor(cfg)
os.makedirs(output_dir, exist_ok=True)
self.output_dir = output_dir
def run_on_image(self, image, focal_length=10.0):
"""
Args:
image (np.ndarray): an image of shape (H, W, C) (in BGR order).
This is the format used by OpenCV.
focal_length (float): the focal_length of the image
Returns:
predictions (dict): the output of the model.
"""
predictions = self.predictor(image)
# Convert image from OpenCV BGR format to Matplotlib RGB format.
image = image[:, :, ::-1]
# camera matrix
imsize = [image.shape[0], image.shape[1]]
# focal <- focal * image_width / 32
focal_length = image.shape[1] / 32 * focal_length
K = [focal_length, image.shape[1] / 2, image.shape[0] / 2]
if "instances" in predictions:
instances = predictions["instances"].to(self.cpu_device)
scores = instances.scores
boxes = instances.pred_boxes
labels = instances.pred_classes
masks = instances.pred_masks
meshes = Meshes(
verts=[mesh[0] for mesh in instances.pred_meshes],
faces=[mesh[1] for mesh in instances.pred_meshes],
)
pred_dz = instances.pred_dz[:, 0] * (boxes.tensor[:, 3] - boxes.tensor[:, 1])
tc = pred_dz.abs().max() + 1.0
zranges = torch.stack(
[
torch.stack(
[
tc - tc * pred_dz[i] / 2.0 / focal_length,
tc + tc * pred_dz[i] / 2.0 / focal_length,
]
)
for i in range(len(meshes))
],
dim=0,
)
Ks = torch.tensor(K).to(self.cpu_device).view(1, 3).expand(len(meshes), 3)
meshes = transform_meshes_to_camera_coord_system(
meshes, boxes.tensor, zranges, Ks, imsize
)
if self.vis_highest_scoring:
det_ids = [scores.argmax().item()]
else:
det_ids = range(len(scores))
for det_id in det_ids:
self.visualize_prediction(
det_id,
image,
boxes.tensor[det_id],
labels[det_id],
scores[det_id],
masks[det_id],
meshes[det_id],
)
return predictions
def visualize_prediction(
self, det_id, image, box, label, score, mask, mesh, alpha=0.6, dpi=200
):
mask_color = np.array(self.colors[label], dtype=np.float32)
cat_name = self.cat_names[label]
thickness = max([int(np.ceil(0.001 * image.shape[0])), 1])
box_color = (0, 255, 0) # '#00ff00', green
text_color = (218, 227, 218) # gray
composite = image.copy().astype(np.float32)
# overlay mask
idx = mask.nonzero()
composite[idx[:, 0], idx[:, 1], :] *= 1.0 - alpha
composite[idx[:, 0], idx[:, 1], :] += alpha * mask_color
# overlay box
(x0, y0, x1, y1) = (int(x + 0.5) for x in box)
composite = cv2.rectangle(
composite, (x0, y0), (x1, y1), color=box_color, thickness=thickness
)
composite = composite.astype(np.uint8)
# overlay text
font_scale = 0.001 * image.shape[0]
font_thickness = thickness
font = cv2.FONT_HERSHEY_TRIPLEX
text = "%s %.3f" % (cat_name, score)
((text_w, text_h), _) = cv2.getTextSize(text, font, font_scale, font_thickness)
# Place text background.
if x0 + text_w > composite.shape[1]:
x0 = composite.shape[1] - text_w
if y0 - int(1.2 * text_h) < 0:
y0 = int(1.2 * text_h)
back_topleft = x0, y0 - int(1.3 * text_h)
back_bottomright = x0 + text_w, y0
cv2.rectangle(composite, back_topleft, back_bottomright, box_color, -1)
# Show text
text_bottomleft = x0, y0 - int(0.2 * text_h)
cv2.putText(
composite,
text,
text_bottomleft,
font,
font_scale,
text_color,
thickness=font_thickness,
lineType=cv2.LINE_AA,
)
save_file = os.path.join(self.output_dir, "%d_mask_%s_%.3f.png" % (det_id, cat_name, score))
cv2.imwrite(save_file, composite[:, :, ::-1])
save_file = os.path.join(self.output_dir, "%d_mesh_%s_%.3f.obj" % (det_id, cat_name, score))
verts, faces = mesh.get_mesh_verts_faces(0)
save_obj(save_file, verts, faces)
def setup_cfg(args):
cfg = get_cfg()
get_meshrcnn_cfg_defaults(cfg)
cfg.merge_from_file(args.config_file)
cfg.merge_from_list(args.opts)
cfg.freeze()
return cfg
if __name__ == "__main__":
mp.set_start_method("spawn", force=True)
args = get_parser().parse_args()
logger = setup_logger(name="demo")
logger.info("Arguments: " + str(args))
cfg = setup_cfg(args)
im_name = args.input.split("/")[-1].split(".")[0]
demo = VisualizationDemo(
cfg, vis_highest_scoring=args.onlyhighest, output_dir=os.path.join(args.output, im_name)
)
# use PIL, to be consistent with evaluation
img = read_image(args.input, format="BGR")
predictions = demo.run_on_image(img, focal_length=args.focal_length)
logger.info("Predictions saved in %s" % (os.path.join(args.output, im_name)))
| demo/demo.py | 8,075 | Args:
cfg (CfgNode):
vis_highest_scoring (bool): If set to True visualizes only
the highest scoring prediction
Args:
image (np.ndarray): an image of shape (H, W, C) (in BGR order).
This is the format used by OpenCV.
focal_length (float): the focal_length of the image
Returns:
predictions (dict): the output of the model.
!/usr/bin/env python3 -*- coding: utf-8 -*- Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved required so that .register() calls are executed in module scope noqa noqa noqa Convert image from OpenCV BGR format to Matplotlib RGB format. camera matrix focal <- focal * image_width / 32 '00ff00', green gray overlay mask overlay box overlay text Place text background. Show text use PIL, to be consistent with evaluation | 820 | en | 0.711004 |
#coding=utf-8
#author@alingse
#2016.06.21
hdfs_schema = 'hdfs://'
file_schema = 'file://'
class hdfsCluster(object):
""" 一个hdfs 资源 hdfs uri,path,账户密码认证
"""
def __init__(self,host,port=9000,schema=hdfs_schema):
""" 目前只需要host和port """
self.host = host
self.port = port
self.schema = schema
self._path = '/'
self._status = None
@property
def status(self):
return self._status
@status.setter
def status(self,value):
if value in [None,True,False]:
self._status = value
@property
def path(self):
return self._path
@path.setter
def path(self,value):
if value.startswith('/') and value.endswith('/'):
self._path = value
self._status = None
@property
def uri_head(self):
""" 返回 uri 的 head"""
head = self.schema + '{}:{}'.format(self.host,self.port)
return head
@property
def uri(self):
""" 返回当前路径"""
_uri = self.schema + '{}:{}{}'.format(self.host,self.port,self._path)
return _uri
if __name__ == '__main__':
hdfs = hdfsCluster('localhost','9000')
hdfs.path = '/hive/'
print(hdfs.uri)
print(hdfs.uri_head)
| hdfshell/cluster.py | 1,322 | 一个hdfs 资源 hdfs uri,path,账户密码认证
目前只需要host和port
返回当前路径
返回 uri 的 head
coding=utf-8author@alingse2016.06.21 | 110 | zh | 0.846039 |
#!/usr/bin/env python
import click
from ..log import get_logger, verbosity_option
from . import bdt
logger = get_logger(__name__)
@click.command(
epilog="""\b
Examples:
bdt gitlab update-bob -vv
bdt gitlab update-bob -vv --stable
"""
)
@click.option(
"--stable/--beta",
help="To use the stable versions in the list and pin packages.",
)
@verbosity_option()
@bdt.raise_on_error
def update_bob(stable):
"""Updates the Bob meta package with new packages."""
import tempfile
from ..ci import read_packages
from ..release import (
download_path,
get_gitlab_instance,
get_latest_tag_name,
)
gl = get_gitlab_instance()
# download order.txt form nightlies and get the list of packages
nightlies = gl.projects.get("bob/nightlies")
with tempfile.NamedTemporaryFile() as f:
download_path(nightlies, "order.txt", f.name, ref="master")
packages = read_packages(f.name)
# find the list of public packages
public_packages, private_packages = [], []
for n, (package, branch) in enumerate(packages):
if package == "bob/bob":
continue
# determine package visibility
use_package = gl.projects.get(package)
is_public = use_package.attributes["visibility"] == "public"
if is_public:
public_packages.append(package.replace("bob/", ""))
else:
private_packages.append(package.replace("bob/", ""))
logger.debug(
"%s is %s", package, "public" if is_public else "not public"
)
logger.info("Found %d public packages", len(public_packages))
logger.info(
"The following packages were not public:\n%s",
"\n".join(private_packages),
)
# if requires stable versions, add latest tag versions to the names
if stable:
logger.info("Getting latest tag names for the public packages")
tags = [
get_latest_tag_name(gl.projects.get(f"bob/{pkg}"))
for pkg in public_packages
]
public_packages = [
f"{pkg} =={tag}" for pkg, tag in zip(public_packages, tags)
]
# modify conda/meta.yaml and requirements.txt in bob/bob
logger.info("Updating conda/meta.yaml")
start_tag = "# LIST OF BOB PACKAGES - START"
end_tag = "# LIST OF BOB PACKAGES - END"
with open("conda/meta.yaml") as f:
lines = f.read()
i1 = lines.find(start_tag) + len(start_tag)
i2 = lines.find(end_tag)
lines = (
lines[:i1]
+ "\n - ".join([""] + public_packages)
+ "\n "
+ lines[i2:]
)
with open("conda/meta.yaml", "w") as f:
f.write(lines)
logger.info("Updating requirements.txt")
with open("requirements.txt", "w") as f:
f.write("\n".join(public_packages) + "\n")
click.echo(
"You may need to add the ` # [linux]` tag in front of linux only "
"packages in conda/meta.yaml"
)
| bob/devtools/scripts/update_bob.py | 3,017 | Updates the Bob meta package with new packages.
!/usr/bin/env python download order.txt form nightlies and get the list of packages find the list of public packages determine package visibility if requires stable versions, add latest tag versions to the names modify conda/meta.yaml and requirements.txt in bob/bob | 315 | en | 0.602838 |
# -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from airflow.sensors.base_sensor_operator import BaseSensorOperator
from airflow.utils import apply_defaults
from airflow.exceptions import AirflowException
class EmrBaseSensor(BaseSensorOperator):
"""
Contains general sensor behavior for EMR.
Subclasses should implement get_emr_response() and state_from_response() methods.
Subclasses should also implement NON_TERMINAL_STATES and FAILED_STATE constants.
"""
ui_color = '#66c3ff'
@apply_defaults
def __init__(
self,
aws_conn_id='aws_default',
*args, **kwargs):
super(EmrBaseSensor, self).__init__(*args, **kwargs)
self.aws_conn_id = aws_conn_id
def poke(self, context):
response = self.get_emr_response()
if not response['ResponseMetadata']['HTTPStatusCode'] == 200:
self.log.info('Bad HTTP response: %s', response)
return False
state = self.state_from_response(response)
self.log.info('Job flow currently %s', state)
if state in self.NON_TERMINAL_STATES:
return False
if state in self.FAILED_STATE:
final_message = 'EMR job failed'
failure_message = self.failure_message_from_response(response)
if failure_message:
final_message += ' ' + failure_message
raise AirflowException(final_message)
return True
| airflow/contrib/sensors/emr_base_sensor.py | 2,221 | Contains general sensor behavior for EMR.
Subclasses should implement get_emr_response() and state_from_response() methods.
Subclasses should also implement NON_TERMINAL_STATES and FAILED_STATE constants.
-*- coding: utf-8 -*- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. | 981 | en | 0.868648 |
from DejaVu.IndexedPolygons import IndexedPolygons
from Volume.Grid3D import Grid3D
class ClipMeshWithMask:
"""Clip method of this class takes a mesh i.e. IndexedPolgons and
selects all vertices which fall onto voxel witha true value in a mask grid.
It returns a new IndexedPolygons geometry with the triangles for which
3 vertices are selected.
"""
def __init__(self):
pass
def clip(self, mesh, grid):
assert isinstance(mesh, IndexedPolygons)
assert isinstance(grid, Grid3D)
origin = grid.getOriginReal()
stepSize = grid.getStepSizeReal()
dx, dy, dz = grid.dimensions
vertices = mesh.vertexSet.vertices.array
triangles = mesh.faceSet.faces.array
# compute the voxel on which each vertex falls
# array of indiced into grid for the vertices
vertInd = ((vertices-origin)/stepSize).astype('i')
# select the vertices on voxels that have a value True
selVert = []
vertEquiv = {}
numVertSel = 0
nvert = 0
data = grid.data
for i,j,k in vertInd:
if i>=0 and i<dx:
if j>=0 and j<dy:
if k>=0 and k<dz:
if data[i,j,k]:
selVert.append( vertices[nvert] )
vertEquiv[nvert] = numVertSel
numVertSel += 1
nvert += 1
# build a set of faces for which some vertices are selected
# and keep only selected vertices
selFaces = []
for i,j,k in triangles:
nbvs = 0
v1 = vertEquiv.get(i, None)
if v1: nbvs +=1
v2 = vertEquiv.get(j, None)
if v2: nbvs +=1
v3 = vertEquiv.get(k, None)
if v3: nbvs +=1
if nbvs == 3:
selFaces.append( (v1,v2,v3) )
clippedGeom = IndexedPolygons(mesh.name+'_clipped', vertices=selVert,
faces=selFaces)
return clippedGeom
| resources/mgltools_x86_64Linux2_1.5.6/MGLToolsPckgs/Volume/Operators/clip.py | 2,073 | Clip method of this class takes a mesh i.e. IndexedPolgons and
selects all vertices which fall onto voxel witha true value in a mask grid.
It returns a new IndexedPolygons geometry with the triangles for which
3 vertices are selected.
compute the voxel on which each vertex falls array of indiced into grid for the vertices select the vertices on voxels that have a value True build a set of faces for which some vertices are selected and keep only selected vertices | 469 | en | 0.880596 |
################################################################################
# CSE 151B: Programming Assignment 4
# Code snippet by Ajit Kumar, Savyasachi
# Updated by Rohin
# Winter 2022
################################################################################
from experiment import Experiment
import sys
# Main Driver for your code. Either run `python main.py` which will run the experiment with default config
# or specify the configuration by running `python main.py custom`
if __name__ == "__main__":
exp_name = 'baseline'
if len(sys.argv) > 1:
exp_name = sys.argv[1]
print("Running Experiment: ", exp_name)
exp = Experiment(exp_name)
exp.run()
exp.test()
| main.py | 709 | CSE 151B: Programming Assignment 4 Code snippet by Ajit Kumar, Savyasachi Updated by Rohin Winter 2022 Main Driver for your code. Either run `python main.py` which will run the experiment with default config or specify the configuration by running `python main.py custom` | 271 | en | 0.767103 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.18 on 2019-02-12 11:43
from __future__ import unicode_literals
import core.models
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('wagtailcore', '0040_page_draft_title'),
('great_international', '0004_merge_20190212_1003'),
]
operations = [
migrations.CreateModel(
name='InternationalUKHQPages',
fields=[
('page_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='wagtailcore.Page')),
('service_name', models.CharField(choices=[('FIND_A_SUPPLIER', 'Find a Supplier'), ('EXPORT_READINESS', 'Export Readiness'), ('INVEST', 'Invest'), ('COMPONENTS', 'Components'), ('GREAT_INTERNATIONAL', 'Great International')], db_index=True, max_length=100, null=True)),
],
options={
'abstract': False,
},
bases=(core.models.ExclusivePageMixin, 'wagtailcore.page'),
),
]
| great_international/migrations/0005_internationalukhqpages.py | 1,158 | -*- coding: utf-8 -*- Generated by Django 1.11.18 on 2019-02-12 11:43 | 69 | en | 0.568029 |
"""
Test what happens if Python was built without SSL
* Everything that does not involve HTTPS should still work
* HTTPS requests must fail with an error that points at the ssl module
"""
import sys
import unittest
class ImportBlocker(object):
"""
Block Imports
To be placed on ``sys.meta_path``. This ensures that the modules
specified cannot be imported, even if they are a builtin.
"""
def __init__(self, *namestoblock):
self.namestoblock = namestoblock
def find_module(self, fullname, path=None):
if fullname in self.namestoblock:
return self
return None
def load_module(self, fullname):
raise ImportError('import of {0} is blocked'.format(fullname))
class ModuleStash(object):
"""
Stashes away previously imported modules
If we reimport a module the data from coverage is lost, so we reuse the old
modules
"""
def __init__(self, namespace, modules=sys.modules):
self.namespace = namespace
self.modules = modules
self._data = {}
def stash(self):
self._data[self.namespace] = self.modules.pop(self.namespace, None)
for module in list(self.modules.keys()):
if module.startswith(self.namespace + '.'):
self._data[module] = self.modules.pop(module)
def pop(self):
self.modules.pop(self.namespace, None)
for module in list(self.modules.keys()):
if module.startswith(self.namespace + '.'):
self.modules.pop(module)
self.modules.update(self._data)
ssl_blocker = ImportBlocker('ssl', '_ssl')
module_stash = ModuleStash('urllib3')
class TestWithoutSSL(unittest.TestCase):
def setUp(self):
sys.modules.pop('ssl', None)
sys.modules.pop('_ssl', None)
module_stash.stash()
sys.meta_path.insert(0, ssl_blocker)
def tearDown(self):
sys.meta_path.remove(ssl_blocker)
module_stash.pop()
class TestImportWithoutSSL(TestWithoutSSL):
def test_cannot_import_ssl(self):
# python26 has neither contextmanagers (for assertRaises) nor
# importlib.
# 'import' inside 'lambda' is invalid syntax.
def import_ssl():
import ssl
self.assertRaises(ImportError, import_ssl)
def test_import_urllib3(self):
import urllib3
| search_on_tablestore_and_elasticsearch/web/flask/ots/python/pymodules/urllib3-1.11/test/test_no_ssl.py | 2,369 | Block Imports
To be placed on ``sys.meta_path``. This ensures that the modules
specified cannot be imported, even if they are a builtin.
Stashes away previously imported modules
If we reimport a module the data from coverage is lost, so we reuse the old
modules
Test what happens if Python was built without SSL
* Everything that does not involve HTTPS should still work
* HTTPS requests must fail with an error that points at the ssl module
python26 has neither contextmanagers (for assertRaises) nor importlib. 'import' inside 'lambda' is invalid syntax. | 561 | en | 0.849083 |
# -*- coding: utf-8 -*-
import os
import io
import json
import shutil
import six
import zipfile
from .. import base
from girder.constants import AccessType
from girder.models.assetstore import Assetstore
from girder.models.folder import Folder
from girder.models.item import Item
from girder.models.token import Token
from girder.models.user import User
def setUpModule():
base.startServer()
def tearDownModule():
base.stopServer()
class ItemTestCase(base.TestCase):
def setUp(self):
base.TestCase.setUp(self)
# Create a set of users so we can have some folders.
self.users = [User().createUser(
'usr%s' % num, 'passwd', 'tst', 'usr', 'u%s@u.com' % num)
for num in [0, 1]]
folders = Folder().childFolders(self.users[0], 'user', user=self.users[0])
for folder in folders:
if folder['name'] == 'Public':
self.publicFolder = folder
else:
self.privateFolder = folder
self.assetstore = Assetstore().getCurrent()
root = self.assetstore['root']
# Clean out the test assetstore on disk
shutil.rmtree(root)
# First clean out the temp directory
tmpdir = os.path.join(root, 'temp')
if os.path.isdir(tmpdir):
for tempname in os.listdir(tmpdir):
os.remove(os.path.join(tmpdir, tempname))
def _createItem(self, parentId, name, description, user):
params = {
'name': name,
'description': description,
'folderId': parentId
}
resp = self.request(path='/item', method='POST', params=params,
user=user)
self.assertStatusOk(resp)
assert 'meta' in resp.json
return resp.json
def _testUploadFileToItem(self, item, name, user, contents):
"""
Uploads a non-empty file to the server.
"""
# Initialize the upload
resp = self.request(
path='/file', method='POST', user=user, params={
'parentType': 'item',
'parentId': item['_id'],
'name': name,
'size': len(contents)
})
self.assertStatusOk(resp)
uploadId = resp.json['_id']
# Send the first chunk
resp = self.request(
path='/file/chunk', method='POST', body=contents, user=user, params={
'uploadId': uploadId
}, type='application/octet-stream')
self.assertStatusOk(resp)
def _testDownloadSingleFileItem(self, item, user, contents):
"""
Downloads a single-file item from the server
:param item: The item to download.
:type item: dict
:param contents: The expected contents.
:type contents: str
"""
resp = self.request(path='/item/%s/download' % item['_id'],
method='GET', user=user, isJson=False)
self.assertStatusOk(resp)
self.assertEqual(contents, self.getBody(resp))
self.assertEqual(resp.headers['Content-Disposition'],
'attachment; filename="file_1"')
# Test downloading the item with contentDisposition=inline.
params = {'contentDisposition': 'inline'}
resp = self.request(path='/item/%s/download' % item['_id'],
method='GET', user=user, isJson=False,
params=params)
self.assertStatusOk(resp)
self.assertEqual(contents, self.getBody(resp))
self.assertEqual(resp.headers['Content-Disposition'],
'inline; filename="file_1"')
# Test downloading with an offset
resp = self.request(path='/item/%s/download' % item['_id'],
method='GET', user=user, isJson=False,
params={'offset': 1})
self.assertStatus(resp, 206)
self.assertEqual(contents[1:], self.getBody(resp))
def _testDownloadMultiFileItem(self, item, user, contents, format=None):
params = None
if format:
params = {'format': format}
resp = self.request(path='/item/%s/download' % item['_id'],
method='GET', user=user, isJson=False,
params=params)
self.assertStatusOk(resp)
zipFile = zipfile.ZipFile(io.BytesIO(self.getBody(resp, text=False)),
'r')
prefix = os.path.split(zipFile.namelist()[0])[0]
expectedZip = {}
for name in contents:
expectedZip[os.path.join(prefix, name)] = contents[name]
self.assertHasKeys(expectedZip, zipFile.namelist())
self.assertHasKeys(zipFile.namelist(), expectedZip)
for name in zipFile.namelist():
expected = expectedZip[name]
if not isinstance(expected, six.binary_type):
expected = expected.encode('utf8')
self.assertEqual(expected, zipFile.read(name))
def testLegacyItems(self):
folder = Folder().createFolder(
parent=self.users[0], parentType='user', creator=self.users[0],
name='New Folder')
item = Item().createItem(
name='LegacyItem',
creator=self.users[0],
folder=folder)
del item['meta']
item = Item().save(item)
assert 'meta' not in item
item = Item().load(item['_id'], user=self.users[0])
assert 'meta' in item
def testItemDownloadAndChildren(self):
curItem = self._createItem(self.publicFolder['_id'],
'test_for_download', 'fake description',
self.users[0])
self._testUploadFileToItem(curItem, 'file_1', self.users[0], 'foobar')
self._testDownloadSingleFileItem(curItem, self.users[0], 'foobar')
self._testDownloadMultiFileItem(curItem, self.users[0],
{'file_1': 'foobar'}, format='zip')
self._testUploadFileToItem(curItem, 'file_2', self.users[0], 'foobz')
resp = self.request(path='/item/%s/files' % curItem['_id'],
method='GET', user=self.users[0])
self.assertStatusOk(resp)
self.assertEqual(resp.json[0]['name'], 'file_1')
self.assertEqual(resp.json[1]['name'], 'file_2')
self.assertEqual(resp.json[0]['size'], 6)
self.assertEqual(resp.json[1]['size'], 5)
self._testDownloadMultiFileItem(curItem, self.users[0],
{'file_1': 'foobar', 'file_2': 'foobz'})
def testItemCrud(self):
"""
Test Create, Read, Update, and Delete of items.
"""
self.ensureRequiredParams(
path='/item', method='POST', required=('folderId',),
user=self.users[1])
# Attempt to create an item without write permission, should fail
params = {
'name': ' ',
'description': ' a description ',
'folderId': self.publicFolder['_id']
}
resp = self.request(path='/item', method='POST', params=params,
user=self.users[1])
self.assertStatus(resp, 403)
# Shouldn't be allowed to have an empty name
resp = self.request(path='/item', method='POST', params=params,
user=self.users[0])
self.assertValidationError(resp, 'name')
# Actually create the item in user 0's private folder
params['name'] = ' my item name'
params['folderId'] = self.privateFolder['_id']
resp = self.request(path='/item', method='POST', params=params,
user=self.users[0])
self.assertStatusOk(resp)
item = resp.json
self.assertEqual(item['name'], params['name'].strip())
self.assertEqual(item['description'], params['description'].strip())
# User 1 should not be able to see the item via find by folderId
params = {
'folderId': self.privateFolder['_id']
}
resp = self.request(path='/item', method='GET', user=self.users[1],
params=params)
self.assertStatus(resp, 403)
# Or by just requesting the item itself by ID
resp = self.request(path='/item/%s' % str(item['_id']), method='GET',
user=self.users[1])
self.assertStatus(resp, 403)
# User 0 should be able to see the item
resp = self.request(path='/item/%s' % str(item['_id']), method='GET',
user=self.users[0])
self.assertStatusOk(resp)
self.assertEqual(resp.json['_id'], item['_id'])
self.assertEqual(resp.json['_modelType'], 'item')
# Also from the children call
resp = self.request(path='/item', method='GET', user=self.users[0],
params=params)
self.assertStatusOk(resp)
self.assertEqual(resp.json[0]['_id'], item['_id'])
# Test finding the item using a text string with and without a folderId
params['text'] = 'my item name'
resp = self.request(path='/item', method='GET', user=self.users[0],
params=params)
self.assertStatusOk(resp)
self.assertEqual(resp.json[0]['_id'], item['_id'])
del params['folderId']
resp = self.request(path='/item', method='GET', user=self.users[0],
params=params)
self.assertStatusOk(resp)
self.assertEqual(resp.json[0]['_id'], item['_id'])
# A limit should work
params['limit'] = 1
resp = self.request(path='/item', method='GET', user=self.users[0],
params=params)
self.assertStatusOk(resp)
self.assertEqual(resp.json[0]['_id'], item['_id'])
# An offset should give us nothing
params['offset'] = 1
resp = self.request(path='/item', method='GET', user=self.users[0],
params=params)
self.assertStatusOk(resp)
self.assertEqual(len(resp.json), 0)
# Finding should fail with no parameters
resp = self.request(path='/item', method='GET', user=self.users[0],
params={})
self.assertStatus(resp, 400)
self.assertEqual(resp.json['message'], 'Invalid search mode.')
# Test update of the item
params = {
'name': 'changed name',
'description': 'new description'
}
resp = self.request(path='/item/%s' % item['_id'], method='PUT',
params=params, user=self.users[0])
self.assertStatusOk(resp)
self.assertEqual(resp.json['name'], params['name'])
self.assertEqual(resp.json['description'], params['description'])
# Test moving an item to the public folder
item = Item().load(item['_id'], force=True)
self.assertFalse(Item().hasAccess(item))
resp = self.request(path='/item/%s' % item['_id'], method='PUT',
user=self.users[0], params={
'folderId': self.publicFolder['_id']})
self.assertStatusOk(resp)
item = Item().load(resp.json['_id'], force=True)
self.assertTrue(Item().hasAccess(item))
# Move should fail if we don't have write permission on the
# destination folder
self.publicFolder = Folder().setUserAccess(
self.publicFolder, self.users[1], AccessType.WRITE, save=True)
resp = self.request(path='/item/%s' % item['_id'], method='PUT',
user=self.users[1], params={
'folderId': self.privateFolder['_id']})
self.assertStatus(resp, 403)
self.assertTrue(resp.json['message'].startswith(
'Write access denied for folder'))
# Try to update/PUT without an id
resp = self.request(path='/item/', method='PUT',
params=params, user=self.users[0])
self.assertStatus(resp, 400)
# Try a bad endpoint (should 400)
resp = self.request(path='/item/%s/blurgh' % item['_id'],
method='GET',
user=self.users[1])
self.assertStatus(resp, 400)
# Try delete with no ID (should 400)
resp = self.request(path='/item/', method='DELETE', user=self.users[1])
self.assertStatus(resp, 400)
# User 1 should not be able to delete the item with read access
self.publicFolder = Folder().setUserAccess(
self.publicFolder, self.users[1], AccessType.READ, save=True)
resp = self.request(path='/item/%s' % str(item['_id']), method='DELETE',
user=self.users[1])
self.assertStatus(resp, 403)
# User 1 should be able to delete the item with write access
self.publicFolder = Folder().setUserAccess(
self.publicFolder, self.users[1], AccessType.WRITE, save=True)
resp = self.request(path='/item/%s' % str(item['_id']), method='DELETE',
user=self.users[1])
self.assertStatusOk(resp)
# Verify that the item is deleted
item = Item().load(item['_id'])
self.assertEqual(item, None)
def testItemMetadataDirect(self):
params = {
'name': 'item with metadata via POST',
'description': ' a description ',
'folderId': self.privateFolder['_id'],
'metadata': 'not JSON'
}
resp = self.request(
path='/item', method='POST', params=params, user=self.users[0])
self.assertStatus(resp, 400)
self.assertEqual(
resp.json['message'], 'Parameter metadata must be valid JSON.')
# Add some metadata
metadata = {
'foo': 'bar',
'test': 2
}
params['metadata'] = json.dumps(metadata)
resp = self.request(
path='/item', method='POST', params=params, user=self.users[0])
self.assertStatusOk(resp)
item = resp.json
self.assertEqual(item['meta']['foo'], metadata['foo'])
self.assertEqual(item['meta']['test'], metadata['test'])
metadata = {
'foo': None,
'test': 3,
'bar': 'baz'
}
resp = self.request(
path='/item/{_id}'.format(**item), method='PUT',
user=self.users[0], params={'metadata': json.dumps(metadata)}
)
self.assertStatusOk(resp)
item = resp.json
self.assertNotHasKeys(item['meta'], ['foo'])
self.assertEqual(item['meta']['test'], metadata['test'])
self.assertEqual(item['meta']['bar'], metadata['bar'])
def testItemMetadataCrud(self):
"""
Test CRUD of metadata.
"""
# Create an item
params = {
'name': 'item with metadata',
'description': ' a description ',
'folderId': self.privateFolder['_id']
}
resp = self.request(path='/item', method='POST', params=params,
user=self.users[0])
self.assertStatusOk(resp)
item = resp.json
# Try to delete metadata from an item that doesn't have any set on it
# yet.
resp = self.request(path='/item/%s/metadata' % (item['_id']),
method='DELETE', user=self.users[0],
body=json.dumps(['foobar']), type='application/json')
item = resp.json
self.assertStatusOk(resp)
self.assertEqual(item['meta'], {})
# Add some metadata
metadata = {
'foo': 'bar',
'test': 2
}
resp = self.request(path='/item/%s/metadata' % item['_id'],
method='PUT', user=self.users[0],
body=json.dumps(metadata), type='application/json')
item = resp.json
self.assertEqual(item['meta']['foo'], metadata['foo'])
self.assertEqual(item['meta']['test'], metadata['test'])
# Test invalid JSON constants
body = '{"key": {"foo": Infinity}}'
resp = self.request(path='/item/%s/metadata' % item['_id'],
method='PUT', user=self.users[0],
body=body, type='application/json')
self.assertStatus(resp, 400)
self.assertEqual(
resp.json['message'], 'Error: "Infinity" is not valid JSON.')
# Edit and remove metadata
metadata['test'] = None
metadata['foo'] = 'baz'
resp = self.request(path='/item/%s/metadata' % item['_id'],
method='PUT', user=self.users[0],
body=json.dumps(metadata), type='application/json')
item = resp.json
self.assertEqual(item['meta']['foo'], metadata['foo'])
self.assertNotHasKeys(item['meta'], ['test'])
# Test insertion of null values
metadata['nullVal'] = None
resp = self.request(path='/item/%s/metadata' % item['_id'],
method='PUT', user=self.users[0],
body=json.dumps(metadata), params={'allowNull': True},
type='application/json')
item = resp.json
self.assertEqual(item['meta']['nullVal'], None)
# Adding an unrelated key should not affect existing keys
del metadata['nullVal']
metadata['other'] = 'macguffin'
resp = self.request(path='/item/%s/metadata' % item['_id'],
method='PUT', user=self.users[0],
body=json.dumps(metadata), type='application/json')
item = resp.json
self.assertEqual(item['meta']['other'], metadata['other'])
self.assertEqual(item['meta']['nullVal'], None)
# Test metadata deletion
resp = self.request(path='/item/%s/metadata' % item['_id'],
method='DELETE', user=self.users[0],
body=json.dumps(['other']), type='application/json')
item = resp.json
self.assertNotHasKeys(item['meta'], ['other'])
# Error when deletion field names contain a period.
resp = self.request(path='/item/%s/metadata' % item['_id'],
method='DELETE', user=self.users[0],
body=json.dumps(['foo', 'foo.bar']), type='application/json')
self.assertStatus(resp, 400)
self.assertEqual(
resp.json['message'], 'Invalid key foo.bar: keys must not contain the "." character.')
# Error when deletion field names begin with a dollar-sign.
resp = self.request(path='/item/%s/metadata' % item['_id'],
method='DELETE', user=self.users[0],
body=json.dumps(['foo', '$bar']), type='application/json')
self.assertStatus(resp, 400)
self.assertEqual(
resp.json['message'], 'Invalid key $bar: keys must not start with the "$" character.')
# Make sure metadata cannot be added with invalid JSON
metadata = {
'test': 'allowed'
}
resp = self.request(path='/item/%s/metadata' % item['_id'],
method='PUT', user=self.users[0],
body=json.dumps(metadata).replace('"', "'"),
type='application/json')
self.assertStatus(resp, 400)
self.assertEqual(resp.json['message'],
'Invalid JSON passed in request body.')
# Make sure metadata cannot be added if there is a period in the key
# name
metadata = {
'foo.bar': 'notallowed'
}
resp = self.request(path='/item/%s/metadata' % item['_id'],
method='PUT', user=self.users[0],
body=json.dumps(metadata), type='application/json')
self.assertStatus(resp, 400)
self.assertEqual(
resp.json['message'], 'Invalid key foo.bar: keys must not contain the "." character.')
# Make sure metadata cannot be added if the key begins with a
# dollar sign
metadata = {
'$foobar': 'alsonotallowed'
}
resp = self.request(path='/item/%s/metadata' % item['_id'],
method='PUT', user=self.users[0],
body=json.dumps(metadata), type='application/json')
self.assertStatus(resp, 400)
self.assertEqual(
resp.json['message'],
'Invalid key $foobar: keys must not start with the "$" character.')
# Make sure metadata cannot be added with a blank key
metadata = {
'': 'stillnotallowed'
}
resp = self.request(path='/item/%s/metadata' % item['_id'],
method='PUT', user=self.users[0],
body=json.dumps(metadata), type='application/json')
self.assertStatus(resp, 400)
self.assertEqual(
resp.json['message'], 'Key names must not be empty.')
def testItemFiltering(self):
"""
Test filtering private metadata from items.
"""
# Create an item
params = {
'name': 'item with metadata',
'description': ' a description ',
'folderId': self.privateFolder['_id']
}
resp = self.request(path='/item', method='POST', params=params,
user=self.users[0])
self.assertStatusOk(resp)
# get the item object from the database
item = Item().load(resp.json['_id'], force=True)
# set a private property
item['private'] = 'very secret metadata'
item = Item().save(item)
# get the item from the rest api
resp = self.request(path='/item/%s' % str(item['_id']), method='GET',
user=self.users[0])
self.assertStatusOk(resp)
# assert that the private data is not included
self.assertNotHasKeys(resp.json, ['private'])
def testPathToRoot(self):
firstChildName = 'firstChild'
firstChildDesc = 'firstDesc'
secondChildName = 'secondChild'
secondChildDesc = 'secondDesc'
firstChild = Folder().createFolder(
self.publicFolder, firstChildName, firstChildDesc, creator=self.users[0])
secondChild = Folder().createFolder(
firstChild, secondChildName, secondChildDesc, creator=self.users[0])
baseItem = Item().createItem('blah', self.users[0], secondChild, 'foo')
resp = self.request(path='/item/%s/rootpath' % baseItem['_id'], method='GET')
self.assertStatusOk(resp)
pathToRoot = resp.json
self.assertEqual(pathToRoot[0]['type'], 'user')
self.assertEqual(pathToRoot[0]['object']['login'],
self.users[0]['login'])
self.assertEqual(pathToRoot[1]['type'], 'folder')
self.assertEqual(pathToRoot[1]['object']['name'],
self.publicFolder['name'])
self.assertEqual(pathToRoot[2]['type'], 'folder')
self.assertEqual(pathToRoot[2]['object']['name'], firstChild['name'])
self.assertEqual(pathToRoot[3]['type'], 'folder')
self.assertEqual(pathToRoot[3]['object']['name'], secondChild['name'])
def testLazyFieldComputation(self):
"""
Demonstrate that an item that is saved in the database without
derived fields (like lowerName or baseParentId) get those values
computed at load() time.
"""
item = Item().createItem('My Item Name', creator=self.users[0], folder=self.publicFolder)
self.assertEqual(item['lowerName'], 'my item name')
self.assertEqual(item['baseParentId'], self.users[0]['_id'])
# Force the item to be saved without lowerName and baseParentType fields
del item['lowerName']
del item['baseParentType']
item = Item().save(item, validate=False)
item = Item().find({'_id': item['_id']})[0]
self.assertNotHasKeys(item, ('lowerName', 'baseParentType'))
# Now ensure that calling load() actually populates those fields and
# saves the results persistently
Item().load(item['_id'], force=True)
item = Item().find({'_id': item['_id']})[0]
self.assertHasKeys(item, ('lowerName', 'baseParentType'))
self.assertEqual(item['lowerName'], 'my item name')
self.assertEqual(item['baseParentType'], 'user')
self.assertEqual(item['baseParentId'], self.users[0]['_id'])
# Also test that this works for a duplicate item, such that the
# automatically renamed item still has the correct lowerName, and a
# None description is changed to an empty string.
item = Item().createItem(
'My Item Name', creator=self.users[0], folder=self.publicFolder, description=None)
# test if non-strings are coerced
self.assertEqual(item['description'], '')
item['description'] = 1
item = Item().save(item)
item = Item().findOne({'_id': item['_id']})
self.assertEqual(item['description'], '1')
# test if just missing lowerName is corrected.
self.assertEqual(item['lowerName'], 'my item name (1)')
del item['lowerName']
item = Item().save(item, validate=False)
item = Item().findOne({'_id': item['_id']})
self.assertNotHasKeys(item, ('lowerName', ))
Item().load(item['_id'], force=True)
item = Item().findOne({'_id': item['_id']})
self.assertHasKeys(item, ('lowerName', ))
self.assertEqual(item['lowerName'], 'my item name (1)')
def testParentsToRoot(self):
"""
Demonstrate that forcing parentsToRoot will cause it to skip the
filtering process.
"""
item = Item().createItem('My Item Name', creator=self.users[0], folder=self.publicFolder)
parents = Item().parentsToRoot(item, force=True)
for parent in parents:
self.assertNotIn('_accessLevel', parent['object'])
parents = Item().parentsToRoot(item)
for parent in parents:
self.assertIn('_accessLevel', parent['object'])
def testItemCopy(self):
origItem = self._createItem(self.publicFolder['_id'],
'test_for_copy', 'fake description',
self.users[0])
# Add metadata and files, since we want to make sure those get copied
metadata = {
'foo': 'value1',
'test': 2
}
resp = self.request(
path='/item/%s/metadata' % origItem['_id'], method='PUT', user=self.users[0],
body=json.dumps(metadata), type='application/json')
self.assertStatusOk(resp)
self._testUploadFileToItem(origItem, 'file_1', self.users[0], 'foobar')
self._testUploadFileToItem(origItem, 'file_2', self.users[0], 'foobz')
# Also upload a link
params = {
'parentType': 'item',
'parentId': origItem['_id'],
'name': 'link_file',
'linkUrl': 'http://www.google.com'
}
resp = self.request(path='/file', method='POST', user=self.users[0],
params=params)
self.assertStatusOk(resp)
# Copy to a new item. It will be in the same folder, but we want a
# different name.
params = {
'name': 'copied_item'
}
resp = self.request(path='/item/%s/copy' % origItem['_id'],
method='POST', user=self.users[0], params=params)
self.assertStatusOk(resp)
# Make sure size was returned correctly
self.assertEqual(resp.json['size'], 11)
# Now ask for the new item explicitly and check its metadata
self.request(path='/item/%s' % resp.json['_id'],
user=self.users[0], type='application/json')
self.assertStatusOk(resp)
newItem = resp.json
self.assertEqual(newItem['name'], 'copied_item')
self.assertEqual(newItem['meta']['foo'], metadata['foo'])
self.assertEqual(newItem['meta']['test'], metadata['test'])
# Check if we can download the files from the new item
resp = self.request(path='/item/%s/files' % newItem['_id'],
method='GET', user=self.users[0])
self.assertStatusOk(resp)
newFiles = resp.json
self.assertEqual(newFiles[0]['name'], 'file_1')
self.assertEqual(newFiles[1]['name'], 'file_2')
self.assertEqual(newFiles[2]['name'], 'link_file')
self.assertEqual(newFiles[0]['size'], 6)
self.assertEqual(newFiles[1]['size'], 5)
self._testDownloadMultiFileItem(newItem, self.users[0],
{'file_1': 'foobar', 'file_2': 'foobz',
'link_file': 'http://www.google.com'})
# Check to make sure the original item is still present
resp = self.request(path='/item', method='GET', user=self.users[0],
params={'folderId': self.publicFolder['_id'],
'text': 'test_for_copy'})
self.assertStatusOk(resp)
self.assertEqual(origItem['_id'], resp.json[0]['_id'])
# Check to make sure the new item is still present
resp = self.request(path='/item', method='GET', user=self.users[0],
params={'folderId': self.publicFolder['_id'],
'text': 'copied_item'})
self.assertStatusOk(resp)
self.assertEqual(newItem['_id'], resp.json[0]['_id'])
# Check that the provenance tag correctly points back
# to the original item
self.assertEqual(newItem['copyOfItem'], origItem['_id'])
# Check if we can download the files from the old item and that they
# are distinct from the files in the original item
resp = self.request(path='/item/%s/files' % origItem['_id'],
method='GET', user=self.users[0])
self.assertStatusOk(resp)
origFiles = resp.json
self._testDownloadMultiFileItem(origItem, self.users[0],
{'file_1': 'foobar', 'file_2': 'foobz',
'link_file': 'http://www.google.com'})
for index, file in enumerate(origFiles):
self.assertNotEqual(origFiles[index]['_id'],
newFiles[index]['_id'])
def testCookieAuth(self):
"""
We make sure a cookie is sufficient for authentication for the item
download endpoint. Also, while we're at it, we make sure it's not
sufficient for other endpoints.
"""
item = self._createItem(self.privateFolder['_id'],
'cookie_auth_download', '', self.users[0])
self._testUploadFileToItem(item, 'file', self.users[0], 'foo')
token = Token().createToken(self.users[0])
cookie = 'girderToken=%s' % token['_id']
# We should be able to download a private item using a cookie token
resp = self.request(path='/item/%s/download' % item['_id'],
isJson=False, cookie=cookie)
self.assertStatusOk(resp)
self.assertEqual(self.getBody(resp), 'foo')
# We should not be able to call GET /item/:id with a cookie token
resp = self.request(path='/item/%s' % item['_id'], cookie=cookie)
self.assertStatus(resp, 401)
# Make sure the cookie has to be a valid token
resp = self.request(path='/item/%s/download' % item['_id'],
cookie='girderToken=invalid_token')
self.assertStatus(resp, 401)
def testReuseExisting(self):
item1 = Item().createItem('to be reused', creator=self.users[0], folder=self.publicFolder)
item2 = Item().createItem('to be reused', creator=self.users[0], folder=self.publicFolder)
item3 = Item().createItem(
'to be reused', creator=self.users[0], folder=self.publicFolder, reuseExisting=True)
self.assertNotEqual(item1['_id'], item2['_id'])
self.assertEqual(item1['_id'], item3['_id'])
self.assertEqual(item2['name'], 'to be reused (1)')
self.assertEqual(item3['name'], 'to be reused')
def testUpdateDuplicatedName(self):
item1 = Item().createItem('foo', creator=self.users[0], folder=self.publicFolder)
item2 = Item().createItem('bar', creator=self.users[0], folder=self.publicFolder)
item2['name'] = 'foo'
Item().save(item2, validate=False)
self.assertEqual(item2['name'], 'foo')
item1['size'] = 3
Item().save(item1)
self.assertEqual(item1['name'], 'foo')
| tests/cases/item_test.py | 33,180 | Downloads a single-file item from the server
:param item: The item to download.
:type item: dict
:param contents: The expected contents.
:type contents: str
Uploads a non-empty file to the server.
We make sure a cookie is sufficient for authentication for the item
download endpoint. Also, while we're at it, we make sure it's not
sufficient for other endpoints.
Test Create, Read, Update, and Delete of items.
Test filtering private metadata from items.
Test CRUD of metadata.
Demonstrate that an item that is saved in the database without
derived fields (like lowerName or baseParentId) get those values
computed at load() time.
Demonstrate that forcing parentsToRoot will cause it to skip the
filtering process.
-*- coding: utf-8 -*- Create a set of users so we can have some folders. Clean out the test assetstore on disk First clean out the temp directory Initialize the upload Send the first chunk Test downloading the item with contentDisposition=inline. Test downloading with an offset Attempt to create an item without write permission, should fail Shouldn't be allowed to have an empty name Actually create the item in user 0's private folder User 1 should not be able to see the item via find by folderId Or by just requesting the item itself by ID User 0 should be able to see the item Also from the children call Test finding the item using a text string with and without a folderId A limit should work An offset should give us nothing Finding should fail with no parameters Test update of the item Test moving an item to the public folder Move should fail if we don't have write permission on the destination folder Try to update/PUT without an id Try a bad endpoint (should 400) Try delete with no ID (should 400) User 1 should not be able to delete the item with read access User 1 should be able to delete the item with write access Verify that the item is deleted Add some metadata Create an item Try to delete metadata from an item that doesn't have any set on it yet. Add some metadata Test invalid JSON constants Edit and remove metadata Test insertion of null values Adding an unrelated key should not affect existing keys Test metadata deletion Error when deletion field names contain a period. Error when deletion field names begin with a dollar-sign. Make sure metadata cannot be added with invalid JSON Make sure metadata cannot be added if there is a period in the key name Make sure metadata cannot be added if the key begins with a dollar sign Make sure metadata cannot be added with a blank key Create an item get the item object from the database set a private property get the item from the rest api assert that the private data is not included Force the item to be saved without lowerName and baseParentType fields Now ensure that calling load() actually populates those fields and saves the results persistently Also test that this works for a duplicate item, such that the automatically renamed item still has the correct lowerName, and a None description is changed to an empty string. test if non-strings are coerced test if just missing lowerName is corrected. Add metadata and files, since we want to make sure those get copied Also upload a link Copy to a new item. It will be in the same folder, but we want a different name. Make sure size was returned correctly Now ask for the new item explicitly and check its metadata Check if we can download the files from the new item Check to make sure the original item is still present Check to make sure the new item is still present Check that the provenance tag correctly points back to the original item Check if we can download the files from the old item and that they are distinct from the files in the original item We should be able to download a private item using a cookie token We should not be able to call GET /item/:id with a cookie token Make sure the cookie has to be a valid token | 3,886 | en | 0.883291 |
## -------------------------------------------------------- ##
# Trab 2 IA 2019-2
#
# Rafael Belmock Pedruzzi
#
# probOneR.py: implementation of the probabilistic OneR classifier.
#
# Python version: 3.7.4
## -------------------------------------------------------- ##
import numpy as np
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.utils.validation import check_X_y, check_array, check_is_fitted
from sklearn.utils.multiclass import unique_labels
from sklearn.metrics import euclidean_distances
from sklearn.preprocessing import KBinsDiscretizer
from sklearn.metrics.cluster import contingency_matrix
from sklearn.metrics import confusion_matrix
from itertools import product, zip_longest, accumulate
from random import random
class Prob_OneR(BaseEstimator, ClassifierMixin):
def fit(self, X, y):
# check that x and y have correct shape
X, y = check_X_y(X,y)
# store the classes seen during fit
self.classes_ = unique_labels(y)
self.y_ = y
kbd = KBinsDiscretizer(n_bins = len(np.unique(y)), encode='ordinal')
X = kbd.fit_transform(X)
self.X_ = X
self.kbd_ = kbd
cm_list = []
hits = []
for i in X.T:
cm = contingency_matrix(i, y)
cm_list.append(cm)
hits.append(sum(max(k) for k in cm))
rule = np.argmax(hits) # chosen rule
self.r_ = rule
rule_cm = cm_list[rule]
class_selector = []
for i, c in enumerate(rule_cm):
cSum = sum(c)
probRatio = [ (i/cSum) for i in c]
# Building the "partitions" of the roulette:
probRatio = list(accumulate(probRatio))
class_selector.append(probRatio)
self.class_selector = class_selector
# Return the classifier
return self
def predict(self, X):
# Check is fit had been called
check_is_fitted(self, ['X_', 'y_'])
# Input validation
X = check_array(X)
X = self.kbd_.transform(X)
y = []
for i in X[:,self.r_]:
probRatio = self.class_selector[int(i)]
# Selecting a random element:
selector = random()
for i in range(len(probRatio)):
if selector <= probRatio[i]:
y.append(self.classes_[i])
break
return y
# from sklearn import datasets
# from sklearn.model_selection import train_test_split, cross_val_score
# from sklearn.metrics import f1_score
# nn= Prob_OneR()
# iris = datasets.load_iris()
# x_train,x_test,y_train,y_test = train_test_split(iris.data,iris.target,test_size = 0.4, random_state = 0)
# nn.fit(x_train, y_train)
# y_pred = nn.predict(x_test)
# print(y_test)
# print(y_pred)
# score = cross_val_score(nn, x_train, y_train, cv = 5)
# print(score)
| trab2/probOneR.py | 2,869 | -------------------------------------------------------- Trab 2 IA 2019-2 Rafael Belmock Pedruzzi probOneR.py: implementation of the probabilistic OneR classifier. Python version: 3.7.4 -------------------------------------------------------- check that x and y have correct shape store the classes seen during fit chosen rule Building the "partitions" of the roulette: Return the classifier Check is fit had been called Input validation Selecting a random element: from sklearn import datasets from sklearn.model_selection import train_test_split, cross_val_score from sklearn.metrics import f1_score nn= Prob_OneR() iris = datasets.load_iris() x_train,x_test,y_train,y_test = train_test_split(iris.data,iris.target,test_size = 0.4, random_state = 0) nn.fit(x_train, y_train) y_pred = nn.predict(x_test) print(y_test) print(y_pred) score = cross_val_score(nn, x_train, y_train, cv = 5) print(score) | 909 | en | 0.643774 |
#!/usr/bin/env python
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import sys
from resource_management import *
from hcat import hcat
from ambari_commons import OSConst
from ambari_commons.os_family_impl import OsFamilyImpl
class HCatClient(Script):
def install(self, env):
import params
self.install_packages(env, exclude_packages=params.hive_exclude_packages)
self.configure(env)
def configure(self, env):
import params
env.set_params(params)
hcat()
def status(self, env):
raise ClientComponentHasNoStatus()
@OsFamilyImpl(os_family=OSConst.WINSRV_FAMILY)
class HCatClientWindows(HCatClient):
pass
@OsFamilyImpl(os_family=OsFamilyImpl.DEFAULT)
class HCatClientDefault(HCatClient):
def get_stack_to_component(self):
return {"HDP": "hadoop-client"}
if __name__ == "__main__":
HCatClient().execute()
| ambari-server/src/main/resources/common-services/HIVE/0.12.0.2.0/package/scripts/hcat_client.py | 1,573 | Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
!/usr/bin/env python | 777 | en | 0.872181 |
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import argparse
from propeller.service.client import InferenceClient
from propeller import log
import six
from tmp import util
from time import time
import numpy as np
class ErnieClient(InferenceClient):
def __init__(self,
vocab_file,
host='localhost',
port=8888,
batch_size=32,
num_coroutine=1,
timeout=10.,
max_seqlen=128):
host_port = 'tcp://%s:%d' % (host, port)
client = super(ErnieClient, self).__init__(host_port, batch_size=batch_size, num_coroutine=num_coroutine, timeout=timeout)
self.vocab = {j.strip().split(b'\t')[0].decode('utf8'): i for i, j in enumerate(open(vocab_file, 'rb'))}
self.tokenizer = util.data.CharTokenizer(self.vocab.keys())
self.max_seqlen = max_seqlen
self.cls_id = self.vocab['[CLS]']
self.sep_id = self.vocab['[SEP]']
def txt_2_id(self, text):
ids = np.array([self.vocab[i] for i in self.tokenizer(text)])
return ids
def pad_and_batch(self, ids):
max_len = max(map(len, ids))
padded = np.stack([np.pad(i, [[0, max_len - len(i)]], mode='constant')for i in ids])
padded = np.expand_dims(padded, axis=-1)
return padded
def __call__(self, text_a, text_b=None):
if text_b is not None and len(text_a) != len(text_b):
raise ValueError('text_b %d has different size than text_a %d' % (text_b, text_a))
text_a = [i.encode('utf8') if isinstance(i, six.string_types) else i for i in text_a]
if text_b is not None:
text_b = [i.encode('utf8') if isinstance(i, six.string_types) else i for i in text_b]
ids_a = map(self.txt_2_id, text_a)
if text_b is not None:
ids_b = map(self.txt_2_id, text_b)
ret = [util.data.build_2_pair(a, b, self.max_seqlen, self.cls_id, self.sep_id) for a, b in zip(ids_a, ids_b)]
else:
ret = [util.data.build_1_pair(a, self.max_seqlen, self.cls_id, self.sep_id) for a in ids_a]
sen_ids, token_type_ids = zip(*ret)
sen_ids = self.pad_and_batch(sen_ids)
token_type_ids = self.pad_and_batch(token_type_ids)
ret, = super(ErnieClient, self).__call__(sen_ids, token_type_ids)
return ret
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='ernie_encoder_client')
parser.add_argument('--host', type=str, default='localhost')
parser.add_argument('-i', '--input', type=str, required=True)
parser.add_argument('-o', '--output', type=str, required=True)
parser.add_argument('-p', '--port', type=int, default=8888)
parser.add_argument('--batch_size', type=int, default=32)
parser.add_argument('--num_coroutine', type=int, default=1)
parser.add_argument('--vocab', type=str, required=True)
args = parser.parse_args()
client = ErnieClient(args.vocab, args.host, args.port, batch_size=args.batch_size, num_coroutine=args.num_coroutine)
inputs = [i.strip().split(b'\t') for i in open(args.input, 'rb').readlines()]
if len(inputs) == 0:
raise ValueError('empty input')
send_batch = args.num_coroutine * args.batch_size
send_num = len(inputs) // send_batch + 1
rets = []
start = time()
for i in range(send_num):
slice = inputs[i * send_batch: (i + 1) * send_batch]
if len(slice) == 0:
continue
columns = list(zip(*slice))
if len(columns) > 2:
raise ValueError('inputs file has more than 2 columns')
ret = client(*columns)
if len(ret.shape) == 3:
ret = ret[:, 0, :] # take cls
rets.append(ret)
end = time()
with open(args.output, 'wb') as outf:
arr = np.concatenate(rets, 0)
np.save(outf, arr)
log.info('query num: %d average latency %.5f' % (len(inputs), (end - start)/len(inputs)))
| ernie/classification/service/client.py | 4,663 | Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. take cls | 592 | en | 0.859942 |
"""
Functions computing the signal shapes
"""
import numpy as np
from time import time
import src.constants as const
def subtract_signal(t, signal, fit_params=3):
"""
Returns the subtracted signal
"""
# fit dphi(t) to polynomials and subtract the contribution from n=0, 1 and 2
coef = np.polynomial.polynomial.polyfit(t, signal, fit_params - 1) # (3)
delta_signal = np.einsum(
"n,nj->j", coef, np.asarray([np.power(t, n) for n in range(fit_params)])
) # (Nt)
# compute the subtracted signal
ht = signal - delta_signal # (Nt), unit = s
return ht
def dphi_dop_chunked(
t,
profile,
r0_vec,
v_vec,
d_hat,
use_form=False,
use_chunk=False,
chunk_size=10000,
verbose=False,
form_fun=None,
interp_table=None,
time_end=np.inf,
):
"""
Compute dphi but in chunks over the subhalos, use when Nt x N is too large an array to
store in memory
"""
num_objects = len(list(profile.items())[0][1]) # number of elements of 1st dict entry
dphi = np.zeros(len(t))
if use_chunk == True:
if num_objects % chunk_size == 0:
num_chunks = num_objects // chunk_size
else:
num_chunks = num_objects // chunk_size + 1
if verbose:
print(" Chunking data (%d chunks) ... "%num_chunks)
print()
for i in range(num_chunks):
if time() > time_end: raise TimeoutError
r0_c = r0_vec[i * chunk_size : (i + 1) * chunk_size]
v_c = v_vec[i * chunk_size : (i + 1) * chunk_size]
profile_c = {}
for key in list(profile):
profile_c[key] = profile[key][i * chunk_size : (i + 1) * chunk_size]
dphi += dphi_dop(
t, profile_c, r0_c, v_c, d_hat, use_form=use_form, form_fun=form_fun, interp_table=interp_table
)
else:
dphi += dphi_dop(t, profile, r0_vec, v_vec, d_hat, use_form=use_form, form_fun=form_fun, interp_table=interp_table)
return dphi
def dphi_dop_chunked_vec(
t,
profile,
r0_vec,
v_vec,
use_form=False,
use_chunk=False,
chunk_size=10000,
verbose=False,
form_fun=None,
interp_table=None,
time_end=np.inf,
):
"""
Compute dphi but in chunks over the subhalos, use when Nt x N is too large an array to
store in memory
"""
num_objects = len(list(profile.items())[0][1]) # number of elements of 1st dict entry
dphi_vec = np.zeros((len(t), 3))
if use_chunk == True:
if verbose:
print(" Chunking data ... ")
print()
if num_objects % chunk_size == 0:
num_chunks = num_objects // chunk_size
else:
num_chunks = num_objects // chunk_size + 1
for i in range(num_chunks):
if time() > time_end: raise TimeoutError
r0_c = r0_vec[i * chunk_size : (i + 1) * chunk_size]
v_c = v_vec[i * chunk_size : (i + 1) * chunk_size]
profile_c = {}
for key in list(profile):
profile_c[key] = profile[key][i * chunk_size : (i + 1) * chunk_size]
dphi_vec += dphi_dop_vec(
t, profile_c, r0_c, v_c, use_form=use_form, form_fun=form_fun, interp_table=interp_table
)
else:
dphi_vec += dphi_dop_vec(t, profile, r0_vec, v_vec, use_form=use_form, form_fun=form_fun, interp_table=interp_table)
return dphi_vec
def dphi_dop_vec(t, profile, r0_vec, v_vec, use_form=False, form_fun=None,
interp_table=None):
"""
Returns the vector phase shift due to the Doppler delay for subhalos of mass, mass.
Dot with d_hat to get dphi_I
TODO: add use_closest option
"""
v_mag = np.linalg.norm(v_vec, axis=1)
r0_v = np.einsum("ij, ij -> i", r0_vec, v_vec)
t0 = -r0_v / np.square(v_mag) # year
b_vec = r0_vec + v_vec * t0[:, np.newaxis] # (N, 3)
b_mag = np.linalg.norm(b_vec, axis=1) # (N)
tau = b_mag / v_mag
b_hat = b_vec / b_mag[:, np.newaxis] # (N, 3)
v_hat = v_vec / v_mag[:, np.newaxis]
x = np.subtract.outer(t, t0) / tau
x0 = -t0 / tau
prefactor = (
const.yr_to_s
* const.GN
/ (const.km_s_to_kpc_yr * const.c_light * np.square(v_mag))
)
if interp_table is None:
bd_term = (np.sqrt(1 + x ** 2) + x) - (np.sqrt(1 + x0 ** 2) + x0) # (Nt, N)
vd_term = np.arcsinh(x) - np.arcsinh(x0)
if 'M' in list(profile):
prefactor *= profile['M']
if use_form:
t_cl = np.maximum(np.minimum(t0, t[-1]), 0)
x_cl = (t_cl - t0) / tau
r_cl = tau * v_mag * np.sqrt(1 + x_cl ** 2)
rv = ((3 * profile['M'] / (4 * np.pi)) * (1 / 200) * (1 / const.rho_crit)) ** (1 / 3)
form_func = np.where(r_cl<rv, form(r_cl / rv, profile['c']), 1) # (N)
bd_term *= prefactor * form_func
vd_term *= prefactor * form_func
else:
bd_term = prefactor * bd_term
vd_term = prefactor * vd_term
else:
if form_fun is not None:
t_cl = np.maximum(np.minimum(t0, t[-1]), 0)
x_cl = (t_cl - t0) / tau
r_cl = tau * v_mag * np.sqrt(1 + x_cl ** 2)
form_func = form_fun(r_cl, profile['rs'], profile['rhos'])
bd_term *= prefactor * form_func
vd_term *= prefactor * form_func
else:
raise ValueError('rho_s, r_s halo description currently requires custom density profile ("USE_FORMTAB")')
else:
y = b_mag / profile['rs']
bd_term0, vd_term0 = interp_table.bd_vd_terms(x0, y)
y.shape = (1,-1)
y = np.broadcast_to(y,x.shape)
bd_term, vd_term = interp_table.bd_vd_terms(x, y)
bd_term -= bd_term0
vd_term -= vd_term0
bd_term *= prefactor * profile['rhos'] * profile['rs']**3
vd_term *= prefactor * profile['rhos'] * profile['rs']**3
# sum the signal over all the events
sig = np.einsum("to, oi -> ti", bd_term, b_hat) - np.einsum(
"to, oi -> ti", vd_term, v_hat
)
return sig
def dphi_dop(t, profile, r0_vec, v_vec, d_hat, use_form=False, form_fun=None,
interp_table=None):
"""
Returns the phase shift due to the Doppler delay for subhalos of mass, mass
TODO: add use_closest option
"""
v_mag = np.linalg.norm(v_vec, axis=1)
r0_v = np.einsum("ij, ij -> i", r0_vec, v_vec) # kpc^2/yr
t0 = -r0_v / np.square(v_mag) # year
b_vec = r0_vec + v_vec * t0[:, np.newaxis] # (N, 3), kpc
b_mag = np.linalg.norm(b_vec, axis=1) # (N)
tau = b_mag / v_mag # year
b_hat = b_vec / b_mag[:, np.newaxis]
v_hat = v_vec / v_mag[:, np.newaxis]
b_d = np.dot(b_hat, d_hat)
v_d = np.dot(v_hat, d_hat)
x = np.subtract.outer(t, t0) / tau
x0 = -t0 / tau
prefactor = (
const.yr_to_s
* const.GN
/ (const.km_s_to_kpc_yr * const.c_light * np.square(v_mag))
)
if interp_table is None:
bd_term = (np.sqrt(1 + x ** 2) + x) - (np.sqrt(1 + x0 ** 2) + x0)
vd_term = np.arcsinh(x) - np.arcsinh(x0)
sig = bd_term * b_d - vd_term * v_d
if 'M' in list(profile):
prefactor *= profile['M']
if use_form:
t_cl = np.maximum(np.minimum(t0, t[-1]), 0)
x_cl = (t_cl - t0) / tau
r_cl = tau * v_mag * np.sqrt(1 + x_cl ** 2)
rv = ((3 * profile['M'] / (4 * np.pi)) * (1 / 200) * (1 / const.rho_crit)) ** (1 / 3)
form_func = np.where(r_cl<rv, form(r_cl / rv, profile['c']), 1) # (N)
sig = form_func * sig
else:
if form_fun is not None:
t_cl = np.maximum(np.minimum(t0, t[-1]), 0)
x_cl = (t_cl - t0) / tau
r_cl = tau * v_mag * np.sqrt(1 + x_cl ** 2)
form_func = form_fun(r_cl, profile['rs'], profile['rhos'])
sig = form_func * sig
else:
raise ValueError('rho_s, r_s halo description currently requires custom density profile ("USE_FORMTAB")')
else:
y = b_mag / profile['rs']
bd_term0, vd_term0 = interp_table.bd_vd_terms(x0, y)
y.shape = (1,-1)
y = np.broadcast_to(y,x.shape)
bd_term, vd_term = interp_table.bd_vd_terms(x, y)
bd_term -= bd_term0
vd_term -= vd_term0
sig = profile['rhos'] * profile['rs']**3 * (bd_term * b_d + vd_term * v_d)
sig = prefactor * sig
# sum the signal over all the events
return np.sum(sig, axis=-1)
def form(s, c):
return (np.log(1 + c * s) - c * s / (1 + c * s)) / (np.log(1 + c) - c / (1 + c))
| src/signals.py | 9,165 | Returns the phase shift due to the Doppler delay for subhalos of mass, mass
TODO: add use_closest option
Compute dphi but in chunks over the subhalos, use when Nt x N is too large an array to
store in memory
Compute dphi but in chunks over the subhalos, use when Nt x N is too large an array to
store in memory
Returns the vector phase shift due to the Doppler delay for subhalos of mass, mass.
Dot with d_hat to get dphi_I
TODO: add use_closest option
Returns the subtracted signal
Functions computing the signal shapes
fit dphi(t) to polynomials and subtract the contribution from n=0, 1 and 2 (3) (Nt) compute the subtracted signal (Nt), unit = s number of elements of 1st dict entry number of elements of 1st dict entry year (N, 3) (N) (N, 3) (Nt, N) (N) sum the signal over all the events kpc^2/yr year (N, 3), kpc (N) year (N) sum the signal over all the events | 871 | en | 0.774415 |
"""Archive Tests
Copyright 2015 Archive Analytics Solutions - University of Liverpool
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from django.test import TestCase
# Create your tests here.
| indigo-web/archive/tests.py | 673 | Archive Tests
Copyright 2015 Archive Analytics Solutions - University of Liverpool
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Create your tests here. | 630 | en | 0.856954 |
from ... import exc
from ... import util
from ...sql.base import _exclusive_against
from ...sql.base import _generative
from ...sql.base import ColumnCollection
from ...sql.dml import Insert as StandardInsert
from ...sql.elements import ClauseElement
from ...sql.expression import alias
from ...util.langhelpers import public_factory
__all__ = ("Insert", "insert")
class Insert(StandardInsert):
"""MySQL-specific implementation of INSERT.
Adds methods for MySQL-specific syntaxes such as ON DUPLICATE KEY UPDATE.
The :class:`~.mysql.Insert` object is created using the
:func:`sqlalchemy.dialects.mysql.insert` function.
.. versionadded:: 1.2
"""
stringify_dialect = "mysql"
inherit_cache = False
@property
def inserted(self):
"""Provide the "inserted" namespace for an ON DUPLICATE KEY UPDATE statement
MySQL's ON DUPLICATE KEY UPDATE clause allows reference to the row
that would be inserted, via a special function called ``VALUES()``.
This attribute provides all columns in this row to be referenceable
such that they will render within a ``VALUES()`` function inside the
ON DUPLICATE KEY UPDATE clause. The attribute is named ``.inserted``
so as not to conflict with the existing
:meth:`_expression.Insert.values` method.
.. tip:: The :attr:`_mysql.Insert.inserted` attribute is an instance
of :class:`_expression.ColumnCollection`, which provides an
interface the same as that of the :attr:`_schema.Table.c`
collection described at :ref:`metadata_tables_and_columns`.
With this collection, ordinary names are accessible like attributes
(e.g. ``stmt.inserted.some_column``), but special names and
dictionary method names should be accessed using indexed access,
such as ``stmt.inserted["column name"]`` or
``stmt.inserted["values"]``. See the docstring for
:class:`_expression.ColumnCollection` for further examples.
.. seealso::
:ref:`mysql_insert_on_duplicate_key_update` - example of how
to use :attr:`_expression.Insert.inserted`
"""
return self.inserted_alias.columns
@util.memoized_property
def inserted_alias(self):
return alias(self.table, name="inserted")
@_generative
@_exclusive_against(
"_post_values_clause",
msgs={
"_post_values_clause": "This Insert construct already "
"has an ON DUPLICATE KEY clause present"
},
)
def on_duplicate_key_update(self, *args, **kw):
r"""
Specifies the ON DUPLICATE KEY UPDATE clause.
:param \**kw: Column keys linked to UPDATE values. The
values may be any SQL expression or supported literal Python
values.
.. warning:: This dictionary does **not** take into account
Python-specified default UPDATE values or generation functions,
e.g. those specified using :paramref:`_schema.Column.onupdate`.
These values will not be exercised for an ON DUPLICATE KEY UPDATE
style of UPDATE, unless values are manually specified here.
:param \*args: As an alternative to passing key/value parameters,
a dictionary or list of 2-tuples can be passed as a single positional
argument.
Passing a single dictionary is equivalent to the keyword argument
form::
insert().on_duplicate_key_update({"name": "some name"})
Passing a list of 2-tuples indicates that the parameter assignments
in the UPDATE clause should be ordered as sent, in a manner similar
to that described for the :class:`_expression.Update`
construct overall
in :ref:`updates_order_parameters`::
insert().on_duplicate_key_update(
[("name", "some name"), ("value", "some value")])
.. versionchanged:: 1.3 parameters can be specified as a dictionary
or list of 2-tuples; the latter form provides for parameter
ordering.
.. versionadded:: 1.2
.. seealso::
:ref:`mysql_insert_on_duplicate_key_update`
"""
if args and kw:
raise exc.ArgumentError(
"Can't pass kwargs and positional arguments simultaneously"
)
if args:
if len(args) > 1:
raise exc.ArgumentError(
"Only a single dictionary or list of tuples "
"is accepted positionally."
)
values = args[0]
else:
values = kw
inserted_alias = getattr(self, "inserted_alias", None)
self._post_values_clause = OnDuplicateClause(inserted_alias, values)
insert = public_factory(
Insert, ".dialects.mysql.insert", ".dialects.mysql.Insert"
)
class OnDuplicateClause(ClauseElement):
__visit_name__ = "on_duplicate_key_update"
_parameter_ordering = None
stringify_dialect = "mysql"
def __init__(self, inserted_alias, update):
self.inserted_alias = inserted_alias
# auto-detect that parameters should be ordered. This is copied from
# Update._proces_colparams(), however we don't look for a special flag
# in this case since we are not disambiguating from other use cases as
# we are in Update.values().
if isinstance(update, list) and (
update and isinstance(update[0], tuple)
):
self._parameter_ordering = [key for key, value in update]
update = dict(update)
if isinstance(update, dict):
if not update:
raise ValueError(
"update parameter dictionary must not be empty"
)
elif isinstance(update, ColumnCollection):
update = dict(update)
else:
raise ValueError(
"update parameter must be a non-empty dictionary "
"or a ColumnCollection such as the `.c.` collection "
"of a Table object"
)
self.update = update
| virtual/lib/python3.8/site-packages/sqlalchemy/dialects/mysql/dml.py | 6,208 | MySQL-specific implementation of INSERT.
Adds methods for MySQL-specific syntaxes such as ON DUPLICATE KEY UPDATE.
The :class:`~.mysql.Insert` object is created using the
:func:`sqlalchemy.dialects.mysql.insert` function.
.. versionadded:: 1.2
Provide the "inserted" namespace for an ON DUPLICATE KEY UPDATE statement
MySQL's ON DUPLICATE KEY UPDATE clause allows reference to the row
that would be inserted, via a special function called ``VALUES()``.
This attribute provides all columns in this row to be referenceable
such that they will render within a ``VALUES()`` function inside the
ON DUPLICATE KEY UPDATE clause. The attribute is named ``.inserted``
so as not to conflict with the existing
:meth:`_expression.Insert.values` method.
.. tip:: The :attr:`_mysql.Insert.inserted` attribute is an instance
of :class:`_expression.ColumnCollection`, which provides an
interface the same as that of the :attr:`_schema.Table.c`
collection described at :ref:`metadata_tables_and_columns`.
With this collection, ordinary names are accessible like attributes
(e.g. ``stmt.inserted.some_column``), but special names and
dictionary method names should be accessed using indexed access,
such as ``stmt.inserted["column name"]`` or
``stmt.inserted["values"]``. See the docstring for
:class:`_expression.ColumnCollection` for further examples.
.. seealso::
:ref:`mysql_insert_on_duplicate_key_update` - example of how
to use :attr:`_expression.Insert.inserted`
Specifies the ON DUPLICATE KEY UPDATE clause.
:param \**kw: Column keys linked to UPDATE values. The
values may be any SQL expression or supported literal Python
values.
.. warning:: This dictionary does **not** take into account
Python-specified default UPDATE values or generation functions,
e.g. those specified using :paramref:`_schema.Column.onupdate`.
These values will not be exercised for an ON DUPLICATE KEY UPDATE
style of UPDATE, unless values are manually specified here.
:param \*args: As an alternative to passing key/value parameters,
a dictionary or list of 2-tuples can be passed as a single positional
argument.
Passing a single dictionary is equivalent to the keyword argument
form::
insert().on_duplicate_key_update({"name": "some name"})
Passing a list of 2-tuples indicates that the parameter assignments
in the UPDATE clause should be ordered as sent, in a manner similar
to that described for the :class:`_expression.Update`
construct overall
in :ref:`updates_order_parameters`::
insert().on_duplicate_key_update(
[("name", "some name"), ("value", "some value")])
.. versionchanged:: 1.3 parameters can be specified as a dictionary
or list of 2-tuples; the latter form provides for parameter
ordering.
.. versionadded:: 1.2
.. seealso::
:ref:`mysql_insert_on_duplicate_key_update`
auto-detect that parameters should be ordered. This is copied from Update._proces_colparams(), however we don't look for a special flag in this case since we are not disambiguating from other use cases as we are in Update.values(). | 3,115 | en | 0.563438 |
import json
import unittest
from bitmovin import Bitmovin, Response, TextFilter, Font
from bitmovin.errors import BitmovinApiError
from tests.bitmovin import BitmovinTestCase
class TextFilterTests(BitmovinTestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
@classmethod
def tearDownClass(cls):
super().tearDownClass()
def setUp(self):
super().setUp()
self.bitmovin = Bitmovin(self.api_key)
self.assertIsNotNone(self.bitmovin)
self.assertTrue(isinstance(self.bitmovin, Bitmovin))
def tearDown(self):
super().tearDown()
def test_create_text_filter(self):
sample_filter = self._get_sample_text_filter()
filter_resource_response = self.bitmovin.filters.Text.create(sample_filter)
self.assertIsNotNone(filter_resource_response)
self.assertIsNotNone(filter_resource_response.resource)
self.assertIsNotNone(filter_resource_response.resource.id)
self._compare_text_filters(sample_filter, filter_resource_response.resource)
def test_create_text_filter_without_name(self):
sample_filter = self._get_sample_text_filter()
sample_filter.name = None
filter_resource_response = self.bitmovin.filters.Text.create(sample_filter)
self.assertIsNotNone(filter_resource_response)
self.assertIsNotNone(filter_resource_response.resource)
self.assertIsNotNone(filter_resource_response.resource.id)
self._compare_text_filters(sample_filter, filter_resource_response.resource)
def test_retrieve_text_filter(self):
sample_filter = self._get_sample_text_filter()
created_filter_response = self.bitmovin.filters.Text.create(sample_filter)
self.assertIsNotNone(created_filter_response)
self.assertIsNotNone(created_filter_response.resource)
self.assertIsNotNone(created_filter_response.resource.id)
self._compare_text_filters(sample_filter, created_filter_response.resource)
retrieved_filter_response = self.bitmovin.filters.Text.retrieve(created_filter_response.resource.id)
self.assertIsNotNone(retrieved_filter_response)
self.assertIsNotNone(retrieved_filter_response.resource)
self._compare_text_filters(created_filter_response.resource, retrieved_filter_response.resource)
def test_delete_text_filter(self):
sample_filter = self._get_sample_text_filter()
created_filter_response = self.bitmovin.filters.Text.create(sample_filter)
self.assertIsNotNone(created_filter_response)
self.assertIsNotNone(created_filter_response.resource)
self.assertIsNotNone(created_filter_response.resource.id)
self._compare_text_filters(sample_filter, created_filter_response.resource)
deleted_minimal_resource = self.bitmovin.filters.Text.delete(created_filter_response.resource.id)
self.assertIsNotNone(deleted_minimal_resource)
self.assertIsNotNone(deleted_minimal_resource.resource)
self.assertIsNotNone(deleted_minimal_resource.resource.id)
try:
self.bitmovin.filters.Text.retrieve(created_filter_response.resource.id)
self.fail(
'Previous statement should have thrown an exception. ' +
'Retrieving filter after deleting it shouldn\'t be possible.'
)
except BitmovinApiError:
pass
def test_list_text_filters(self):
sample_filter = self._get_sample_text_filter()
created_filter_response = self.bitmovin.filters.Text.create(sample_filter)
self.assertIsNotNone(created_filter_response)
self.assertIsNotNone(created_filter_response.resource)
self.assertIsNotNone(created_filter_response.resource.id)
self._compare_text_filters(sample_filter, created_filter_response.resource)
filters = self.bitmovin.filters.Text.list()
self.assertIsNotNone(filters)
self.assertIsNotNone(filters.resource)
self.assertIsNotNone(filters.response)
self.assertIsInstance(filters.resource, list)
self.assertIsInstance(filters.response, Response)
self.assertGreater(filters.resource.__sizeof__(), 1)
def test_retrieve_text_filter_custom_data(self):
sample_filter = self._get_sample_text_filter()
sample_filter.customData = '<pre>my custom data</pre>'
created_filter_response = self.bitmovin.filters.Text.create(sample_filter)
self.assertIsNotNone(created_filter_response)
self.assertIsNotNone(created_filter_response.resource)
self.assertIsNotNone(created_filter_response.resource.id)
self._compare_text_filters(sample_filter, created_filter_response.resource)
custom_data_response = self.bitmovin.filters.Text.retrieve_custom_data(
created_filter_response.resource.id)
custom_data = custom_data_response.resource
self.assertEqual(sample_filter.customData, json.loads(custom_data.customData))
def _compare_text_filters(self, first: TextFilter, second: TextFilter):
"""
:param first: TextFilter
:param second: TextFilter
:return: bool
"""
self.assertEqual(str(first.x), str(second.x))
self.assertEqual(str(first.y), str(second.y))
self.assertEqual(first.text, second.text)
self.assertEqual(first.timecode, second.timecode)
self.assertEqual(first.shadowY, second.shadowX)
self.assertEqual(first.shadowX, second.shadowX)
self.assertEqual(first.shadowColor, second.shadowColor)
self.assertEqual(first.alpha, second.alpha)
self.assertEqual(first.fontSize, second.fontSize)
self.assertEqual(first.font, second.font)
self.assertEqual(first.fontColor, second.fontColor)
self.assertEqual(first.fixBounds, second.fixBounds)
self.assertEqual(first.borderWidth, second.borderWidth)
self.assertEqual(first.lineSpacing, second.lineSpacing)
self.assertEqual(first.boxColor, second.boxColor)
self.assertEqual(first.boxBorderWidth, second.boxBorderWidth)
self.assertEqual(first.box, second.box)
self.assertEqual(first.description, second.description)
self.assertEqual(first.name, second.name)
return True
def _get_sample_text_filter(self):
text_filter = TextFilter(name='Sample Text Filter',
x='10',
y='10',
text='ThisIsATest',
font=Font.DEJAVUSANS)
self.assertIsNotNone(text_filter.x)
self.assertIsNotNone(text_filter.y)
self.assertIsNotNone(text_filter.name)
self.assertIsNotNone(text_filter.font)
return text_filter
if __name__ == '__main__':
unittest.main()
| tests/bitmovin/services/filters/text_filter_tests.py | 6,867 | :param first: TextFilter
:param second: TextFilter
:return: bool | 64 | en | 0.310434 |
# -*- coding: utf-8 -*-
# noqa: B950
import logging
from collections import Counter
import tqdm
from detectron2.checkpoint import DetectionCheckpointer
from detectron2.config import get_cfg
from detectron2.data import build_detection_test_loader
from detectron2.engine import default_argument_parser
from detectron2.modeling import build_model
from detectron2.utils.analysis import (
activation_count_operators,
flop_count_operators,
parameter_count_table,
)
from detectron2.utils.logger import setup_logger
logger = logging.getLogger("detectron2")
def setup(args):
cfg = get_cfg()
cfg.merge_from_file(args.config_file)
cfg.DATALOADER.NUM_WORKERS = 0
cfg.merge_from_list(args.opts)
cfg.freeze()
setup_logger()
return cfg
def do_flop(cfg):
data_loader = build_detection_test_loader(cfg, cfg.DATASETS.TEST[0])
model = build_model(cfg)
DetectionCheckpointer(model).load(cfg.MODEL.WEIGHTS)
model.eval()
counts = Counter()
for idx, data in zip(tqdm.trange(args.num_inputs), data_loader): # noqa
counts += flop_count_operators(model, data)
logger.info(
"(G)Flops for Each Type of Operators:\n" + str([(k, v / idx) for k, v in counts.items()])
)
def do_activation(cfg):
data_loader = build_detection_test_loader(cfg, cfg.DATASETS.TEST[0])
model = build_model(cfg)
DetectionCheckpointer(model).load(cfg.MODEL.WEIGHTS)
model.eval()
counts = Counter()
for idx, data in zip(tqdm.trange(args.num_inputs), data_loader): # noqa
counts += activation_count_operators(model, data)
logger.info(
"(Million) Activations for Each Type of Operators:\n"
+ str([(k, v / idx) for k, v in counts.items()])
)
def do_parameter(cfg):
model = build_model(cfg)
logger.info("Parameter Count:\n" + parameter_count_table(model, max_depth=5))
def do_structure(cfg):
model = build_model(cfg)
logger.info("Model Structure:\n" + str(model))
if __name__ == "__main__":
parser = default_argument_parser(
epilog="""
Examples:
To show parameters of a model:
$ ./analyze_model.py --tasks parameter \\
--config-file ../configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x.yaml
Flops and activations are data-dependent, therefore inputs and model weights
are needed to count them:
$ ./analyze_model.py --num-inputs 100 --tasks flop \\
--config-file ../configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x.yaml \\
MODEL.WEIGHTS /path/to/model.pkl
"""
)
parser.add_argument(
"--tasks",
choices=["flop", "activation", "parameter", "structure"],
required=True,
nargs="+",
)
parser.add_argument(
"--num-inputs",
default=100,
type=int,
help="number of inputs used to compute statistics for flops/activations, "
"both are data dependent.",
)
args = parser.parse_args()
assert not args.eval_only
assert args.num_gpus == 1
cfg = setup(args)
for task in args.tasks:
{
"flop": do_flop,
"activation": do_activation,
"parameter": do_parameter,
"structure": do_structure,
}[task](cfg)
| tools/analyze_model.py | 3,216 | -*- coding: utf-8 -*- noqa: B950 noqa noqa | 42 | en | 0.374063 |
# Copyright Bruno da Silva de Oliveira 2003. Use, modification and
# distribution is subject to the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
| origin/libs/python/pyste/src/Pyste/__init__.py | 239 | Copyright Bruno da Silva de Oliveira 2003. Use, modification and distribution is subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) | 222 | en | 0.741836 |
#!/usr/bin/env python
# Demonstration GET users/search
# See https://dev.twitter.com/rest/reference/get/users/search
from secret import twitter_instance
tw = twitter_instance()
response = tw.users.search(
q='bot',
page=0,
count=20,
include_entities=False)
for i in response:
print('''
{screen_name} | {name}
{location}
{url}
{description}
ツイート数 {statuses_count}
フォロー {friends_count} 人
フォロワー {followers_count} 人
'''.format_map(i))
| source/_sample/ptt/users-search.py | 489 | !/usr/bin/env python Demonstration GET users/search See https://dev.twitter.com/rest/reference/get/users/search | 111 | en | 0.43083 |
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/01_tabular.pd.ipynb (unless otherwise specified).
__all__ = ['PartDep']
# Cell
from fastai.tabular.all import *
from .core import *
# Cell
from plotnine import *
# Cell
from IPython.display import clear_output
# Cell
class PartDep(Interpret):
"""
Calculate Partial Dependence. Countinious vars are divided into buckets and are analized as well
Fields is a list of lists of what columns we want to test. The inner items are treated as connected fields.
For ex. fields = [['Store','StoreType']] mean that Store and StoreType is treated as one entity
(it's values are substitute as a pair, not as separate values)
coef is useful when we don't want to deal with all the variants, but only with most common
In short if coef for ex. is 0.9, then function outputs number of occurrences for all but least 10%
of the least used
If coef is more 1.0, then 'coef' itself is used as threshold (as min number of occurances)
use_log=True is needed if we have transformed depended variable into log
use_int=True is needed if we want to log-detransformed (exponented) var to me integer not float
is_couninue=True helps with long calculation, it continues the last calculation from the saved file
is_use_cache=True loads last fully calculated result. Can distinct caches that were mede with different
fields and coef
no_precalc=True -- don't calculate PartDep (usefull if you want to use `plot_raw` and `plot_model` only)
"""
def __init__(self, learn, df, model_name: str, fields: list = (), coef: float = 1.0,
is_sorted: bool = True, use_log=False, use_int=False,
cache_path=None, is_use_cache=True, is_continue=False, no_precalc=False):
super().__init__(learn, df)
self.use_log = use_log
self.use_int = use_int
self.coef = coef
self.is_sorted = is_sorted
if (fields is None) or (len(fields) == 0):
self.fields = self._get_all_columns()
else:
self.fields = listify(fields)
self.part_dep_df = None
self.cache_path = ifnone(cache_path, learn.path / 'cache')
self.save_name = f"{model_name}_part_dep"
self.is_use_cache = is_use_cache
self.is_continue = is_continue
self.dep_var = self._get_dep_var()
self.is_biclassification = True if (learn.dls.c == 2) else False
if (no_precalc==False):
self._load_or_calculate()
@classmethod
def what_cached(self, model_name: str, path=None, learn=None):
"""
Shows what keys are cached
"""
if isNone(path) and isNone(learn):
print("path and learn cannot be None at the same time")
return
elif isNone(path):
path = learn.path
name = f"{model_name}_part_dep"
folder = 'cache'
path = path / folder
if not (Path(f"{path / name}.pkl").exists()):
print(f"No chache file")
else:
f = open(path / f"{name}.pkl", "rb")
var = load(f)
f.close()
for k in var.keys():
print(k)
@classmethod
def empty_cache(self, model_name: str, path=None, learn=None):
"""
deletes the cache file
"""
if isNone(path) and isNone(learn):
print("path and learn cannot be None at the same time")
return
elif isNone(path):
path = learn.path
name = f"{model_name}_part_dep"
folder = 'cache'
path = path / folder
files = (Path(f"{path / name}.pkl"), Path(path / 'pd_interm.pkl'))
for file in files:
if not (file.exists()):
print(f"No chache file {file}")
else:
file.unlink()
def _cont_into_buckets(self, df_init, CONT_COLS):
"""
Categorical values can be easily distiguished one from another
But that doesn't work with continious values, we have to divede it's
values into buckets and then use all values in a bucket as a single value
that avarages the bucket. This way we convert cont feture into pseudo categorical
and are able to apply partial dependense analysis to it
"""
fields = self.fields
df = df_init.copy()
if is_in_list(values=fields, in_list=CONT_COLS):
for col in which_elms(values=fields, in_list=CONT_COLS):
edges = np.histogram_bin_edges(a=df[col].dropna(), bins='auto')
for x, y in zip(edges[::], edges[1::]):
df.loc[(df[col] > x) & (df[col] < y), col] = (x + y) / 2
return df
def _get_field_uniq_x_coef(self, df: pd.DataFrame, fields: list, coef: float) -> list:
'''
This function outputs threshold to number of occurrences different variants of list of columns (fields)
In short if coef for ex. is 0.9, then function outputs number of occurrences for all but least 10%
of the least used
If coef is more 1.0, then 'coef' itself is used as threshold
'''
if (coef > 1):
return math.ceil(coef)
coef = 0. if (coef < 0) else coef
occs = df.groupby(fields).size().reset_index(name="Times").sort_values(['Times'], ascending=False)
num = math.ceil(coef * len(occs))
if (num <= 0):
# number of occurances is now = max_occs+1 (so it will be no items with this filter)
return occs.iloc[0]['Times'] + 1
else:
return occs.iloc[num - 1]['Times']
def _get_part_dep_one(self, fields: list, masterbar=None) -> pd.DataFrame:
'''
Function calculate partial dependency for column in fields.
Fields is a list of lists of what columns we want to test. The inner items are treated as connected fields.
For ex. fields = [['Store','StoreType']] mean that Store and StoreType is treated as one entity
(it's values are substitute as a pair, not as separate values)
coef is useful when we don't want to deal with all the variants, but only with most common
'''
NAN_SUBST = '###na###'
cont_vars = self._get_cont_columns()
fields = listify(fields)
coef, is_sorted, use_log, use_int = self.coef, self.is_sorted, self.use_log, self.use_int
dep_name = self._get_dep_var()
df = self._cont_into_buckets(df_init=self.df, CONT_COLS=cont_vars)
# here we prepare data to eliminate pairs that occure too little
# and make NaN a separate value to appear in occures
field_min_occ = self._get_field_uniq_x_coef(df=df, fields=fields, coef=coef)
df[fields] = df[fields].fillna(NAN_SUBST) # to treat None as a separate field
occs = df.groupby(fields).size().reset_index(name="Times").sort_values(['Times'], ascending=False)
occs[fields] = occs[fields].replace(to_replace=NAN_SUBST, value=np.nan) # get back Nones from NAN_SUBST
df[fields] = df[fields].replace(to_replace=NAN_SUBST, value=np.nan) # get back Nones from NAN_SUBST
occs = occs[occs['Times'] >= field_min_occ]
df_copy = df.merge(occs[fields]).copy()
# here for every pair of values of fields we substitute it's values in original df
# with the current one and calculate predictions
# So we predict mean dep_var for every pairs of value of fields on the whole dataset
frame = []
ln = len(occs)
if (ln > 0):
for _, row in progress_bar(occs.iterrows(), total=ln, parent=masterbar):
# We don't need to do df_copy = df.merge(occs[field]).copy() every time
# as every time we change the same column (set of columns)
record = []
for fld in fields:
df_copy[fld] = row[fld]
preds = self._predict_df(df=df_copy)
preds = np.exp(np.mean(preds)) if (use_log == True) else np.mean(preds)
preds = int(preds) if (use_int == True) else preds
for fld in fields:
record.append(row[fld])
record.append(preds)
record.append(row['Times'])
frame.append(record)
# Here for every pair of fields we calculate mean dep_var deviation
# This devition is the score that shows how and where this partucular pair of fields
# moves depend valiable
# Added times to more easily understand the data (more times more sure we are)
out = pd.DataFrame(frame, columns=fields + [dep_name, 'times'])
median = out[dep_name].median()
out[dep_name] /= median
if (is_sorted == True):
out = out.sort_values(by=dep_name, ascending=False)
return out
def _get_part_dep(self):
'''
Makes a datafreme with partial dependencies for every pair of columns in fields
'''
fields = self.fields
learn = self.learn
cache_path = self.cache_path
dep_name = self._get_dep_var()
is_continue = self.is_continue
l2k = self._list_to_key
result = []
to_save = {}
from_saved = {}
# Load from cache
if (is_continue == True):
if Path(cache_path / 'pd_interm.pkl').exists():
from_saved = ld_var(name='pd_interm', path=cache_path)
else:
is_continue = False
elapsed = []
left = []
if (is_continue == True):
for field in fields:
if (l2k(field) in from_saved):
elapsed.append(field)
new_df = from_saved[l2k(field)]
result.append(new_df)
to_save[l2k(field)] = new_df
for field in fields:
if (l2k(field) not in from_saved):
left.append(field)
# Calculate
pbar = master_bar(left)
cache_path.mkdir(parents=True, exist_ok=True)
sv_var(var=to_save, name='pd_interm', path=cache_path)
for field in pbar:
new_df = self._get_part_dep_one(fields=field, masterbar=pbar)
new_df['feature'] = self._list_to_key(field)
if is_listy(field):
new_df['value'] = new_df[field].values.tolist()
new_df.drop(columns=field, inplace=True)
else:
new_df = new_df.rename(index=str, columns={str(field): "value"})
result.append(new_df)
to_save[l2k(field)] = new_df
sv_var(var=to_save, name='pd_interm', path=cache_path)
clear_output()
if Path(cache_path / 'pd_interm.pkl').exists():
Path(cache_path / 'pd_interm.pkl').unlink() # delete intermediate file
result = pd.concat(result, ignore_index=True, sort=True)
result = result[['feature', 'value', dep_name, 'times']]
clear_output()
self.part_dep_df = result
def _load_dict(self, name, path):
if not (Path(f"{path / name}.pkl").exists()):
return None
return self._ld_var(name=name, path=path)
def _save_cached(self):
"""
Saves calculated PartDep df into path.
Can be saved more than one with as an dict with fields as key
"""
path = self.cache_path
path.mkdir(parents=True, exist_ok=True)
name = self.save_name
sv_dict = self._load_dict(name=name, path=path)
key = self._list_to_key(self.fields + [self.coef])
if isNone(sv_dict):
sv_dict = {key: self.part_dep_df}
else:
sv_dict[key] = self.part_dep_df
self._sv_var(var=sv_dict, name=name, path=path)
def _load_cached(self):
"""
Load calculated PartDep df if hash exist.
"""
name = self.save_name
path = self.cache_path
if not (Path(f"{path / name}.pkl").exists()):
return None
ld_dict = self._ld_var(name=name, path=path)
key = self._list_to_key(self.fields + [self.coef])
if (key not in ld_dict):
return None
return ld_dict[key]
def _load_or_calculate(self):
"""
Calculates part dep or load it from cache if possible
"""
if (self.is_use_cache == False) or isNone(self._load_cached()):
self._get_part_dep()
return self._save_cached()
else:
self.part_dep_df = self._load_cached()
def _general2partial(self, df):
if (len(df) == 0):
return None
copy_df = df.copy()
feature = copy_df['feature'].iloc[0]
copy_df.drop(columns='feature', inplace=True)
copy_df.rename(columns={"value": feature}, inplace=True)
return copy_df
def plot_raw(self, field, sample=1.0):
"""
Plot dependency graph from data itself
field must be list of exactly one feature
sample is a coef to len(df). Lower if kernel use to shut down on that
"""
df = self.df
df = df.sample(int(len(df)*sample))
field = field[0]
dep_var = f"{self._get_dep_var()}_orig" if (self.use_log == True) else self._get_dep_var()
return ggplot(df, aes(field, dep_var)) + stat_smooth(se=True, method='loess');
def plot_model(self, field, strict_recalc=False, sample=1.0):
'''
Plot dependency graph from the model.
It also take into account times, so plot becomes much more resilient, cause not every value treats as equal
(more occurences means more power)
field must be list of exactly one feature
strict_recalc=True ignores precalculated `part_dep_df` and calculate it anyway
sample is a coef to len(df). Lower if kernel use to shut down on that
'''
cached = self.get_pd(feature=self._list_to_key(field))
if (strict_recalc == False) and isNotNone(cached):
pd_table = cached
else:
pd_table = self._get_part_dep_one(fields=field)
clear_output()
field = field[0]
dep_var = f"{self._get_dep_var()}"
rearr = []
for var, fee, times in zip(pd_table[field], pd_table[dep_var], pd_table['times']):
for i in range(int(times)):
rearr.append([var, fee])
rearr = pd.DataFrame(rearr, columns=[field, dep_var])
rearr = rearr.sample(int(len(rearr)*sample))
return ggplot(rearr, aes(field, dep_var)) + stat_smooth(se=True, method='loess');
def get_pd(self, feature, min_tm=1):
"""
Gets particular feature subtable from the whole one (min times is optional parameter)
"""
if isNone(self.part_dep_df):
return None
df = self.part_dep_df.query(f"""(feature == "{feature}") and (times > {min_tm})""")
return self._general2partial(df=df)
def get_pd_main_chained_feat(self, main_feat_idx=0, show_min=1):
"""
Transforms whole features table to get_part_dep_one output table format
"""
def get_xth_el(str_list: str, indexes: list):
lst = str_list if is_listy(str_list) else ast.literal_eval(str_list)
lst = listify(lst)
if (len(lst) == 1):
return lst[0]
elif (len(lst) > 1):
if (len(indexes) == 1):
return lst[indexes[0]]
else:
return [lst[idx] for idx in indexes]
else:
return None
feat_table = self.part_dep_df
main_feat_idx = listify(main_feat_idx)
feat_table_copy = feat_table.copy()
func = functools.partial(get_xth_el, indexes=main_feat_idx)
feat_table_copy['value'] = feat_table_copy['value'].apply(func)
feat_table_copy.drop(columns='feature', inplace=True)
return feat_table_copy.query(f'times > {show_min}')
def plot_part_dep(self, fields, limit=20, asc=False):
"""
Plots partial dependency plot for sublist of connected `fields`
`fields` must be sublist of `fields` given on initalization calculation
"""
def prepare_colors(df_pd: pd.DataFrame):
heat_min = df_pd['times'].min()
heat_max = df_pd['times'].max()
dif = heat_max - heat_min
colors = [((times - heat_min) / (dif), (times - heat_min) / (4 * dif), 0.75) for times in df_pd['times']]
return colors
df = self.part_dep_df.query(f"feature == '{self._list_to_key(fields)}'")
dep_var = self.dep_var
df_copy = df.copy()
df_copy['feature'] = df_copy['feature'].str.slice(0, 45)
df_copy = df_copy.sort_values(by=dep_var, ascending=asc)[:limit].sort_values(by=dep_var, ascending=not (asc))
colors = prepare_colors(df_pd=df_copy)
ax = df_copy.plot.barh(x="value", y=dep_var, sort_columns=True, figsize=(10, 10),
color=colors, title=self._list_to_key(fields))
ax.set_ylabel(fields)
if (self.is_biclassification):
txt = f"According to probability of {self._get_dep_var()} is '{learn.dls.vocab[0]}'"
ax.annotate(txt, (0,0), (0, -30),
xycoords='axes fraction', textcoords='offset points',
va='top')
for (p, t) in zip(ax.patches, df_copy['times']):
ax.annotate(f'{p.get_width():.4f}', ((p.get_width() * 1.005), p.get_y() * 1.005))
ax.annotate(f'{int(t)}', ((p.get_width() * .45), p.get_y() + 0.1), color='white', weight='bold') | fastinference/tabular/pd.py | 17,699 | Calculate Partial Dependence. Countinious vars are divided into buckets and are analized as well
Fields is a list of lists of what columns we want to test. The inner items are treated as connected fields.
For ex. fields = [['Store','StoreType']] mean that Store and StoreType is treated as one entity
(it's values are substitute as a pair, not as separate values)
coef is useful when we don't want to deal with all the variants, but only with most common
In short if coef for ex. is 0.9, then function outputs number of occurrences for all but least 10%
of the least used
If coef is more 1.0, then 'coef' itself is used as threshold (as min number of occurances)
use_log=True is needed if we have transformed depended variable into log
use_int=True is needed if we want to log-detransformed (exponented) var to me integer not float
is_couninue=True helps with long calculation, it continues the last calculation from the saved file
is_use_cache=True loads last fully calculated result. Can distinct caches that were mede with different
fields and coef
no_precalc=True -- don't calculate PartDep (usefull if you want to use `plot_raw` and `plot_model` only)
Categorical values can be easily distiguished one from another
But that doesn't work with continious values, we have to divede it's
values into buckets and then use all values in a bucket as a single value
that avarages the bucket. This way we convert cont feture into pseudo categorical
and are able to apply partial dependense analysis to it
This function outputs threshold to number of occurrences different variants of list of columns (fields)
In short if coef for ex. is 0.9, then function outputs number of occurrences for all but least 10%
of the least used
If coef is more 1.0, then 'coef' itself is used as threshold
Makes a datafreme with partial dependencies for every pair of columns in fields
Function calculate partial dependency for column in fields.
Fields is a list of lists of what columns we want to test. The inner items are treated as connected fields.
For ex. fields = [['Store','StoreType']] mean that Store and StoreType is treated as one entity
(it's values are substitute as a pair, not as separate values)
coef is useful when we don't want to deal with all the variants, but only with most common
Load calculated PartDep df if hash exist.
Calculates part dep or load it from cache if possible
Saves calculated PartDep df into path.
Can be saved more than one with as an dict with fields as key
deletes the cache file
Gets particular feature subtable from the whole one (min times is optional parameter)
Transforms whole features table to get_part_dep_one output table format
Plot dependency graph from the model.
It also take into account times, so plot becomes much more resilient, cause not every value treats as equal
(more occurences means more power)
field must be list of exactly one feature
strict_recalc=True ignores precalculated `part_dep_df` and calculate it anyway
sample is a coef to len(df). Lower if kernel use to shut down on that
Plots partial dependency plot for sublist of connected `fields`
`fields` must be sublist of `fields` given on initalization calculation
Plot dependency graph from data itself
field must be list of exactly one feature
sample is a coef to len(df). Lower if kernel use to shut down on that
Shows what keys are cached
AUTOGENERATED! DO NOT EDIT! File to edit: nbs/01_tabular.pd.ipynb (unless otherwise specified). Cell Cell Cell Cell number of occurances is now = max_occs+1 (so it will be no items with this filter) here we prepare data to eliminate pairs that occure too little and make NaN a separate value to appear in occures to treat None as a separate field get back Nones from NAN_SUBST get back Nones from NAN_SUBST here for every pair of values of fields we substitute it's values in original df with the current one and calculate predictions So we predict mean dep_var for every pairs of value of fields on the whole dataset We don't need to do df_copy = df.merge(occs[field]).copy() every time as every time we change the same column (set of columns) Here for every pair of fields we calculate mean dep_var deviation This devition is the score that shows how and where this partucular pair of fields moves depend valiable Added times to more easily understand the data (more times more sure we are) Load from cache Calculate delete intermediate file | 4,390 | en | 0.906866 |
# -*- coding: utf-8 -*-
from django.shortcuts import render
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.throttling import ScopedRateThrottle
from rest_framework.views import APIView
from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST
from rest_framework.response import Response
from rest_framework import viewsets, mixins
from rest_framework.pagination import LimitOffsetPagination
from .models import JudgeStatus, CaseStatus
from .serializers import JudgeStatusSerializer, CaseStatusSerializer, JudgeStatusCodeSerializer
from .permission import ManagerOnly, UserRatingOnly, NoContestOnly
from contest.models import ContestInfo
from contest.serializers import ContestInfoSerializer
import datetime
class JudgeStatusView(viewsets.ModelViewSet):
queryset = JudgeStatus.objects.all().order_by('-id')
serializer_class = JudgeStatusSerializer
pagination_class = LimitOffsetPagination
filter_backends = (DjangoFilterBackend,)
filter_fields = ('user', 'result', "contest", "problem", "language", "problemtitle")
permission_classes = (ManagerOnly,)
throttle_scope = "post"
throttle_classes = [ScopedRateThrottle, ]
def list(self, request, *args, **kwargs):
self.check_permissions(request)
self.check_throttles(request)
userid = request._request.session.get("user_id")
usertype = request._request.session.get("type")
cid = request._request.GET.get("contest",0)
if cid == "":
cid = 0
contestid = int(cid)
if contestid == 0:
queryset = self.filter_queryset(self.get_queryset())
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
else: # 封榜特判
contest = ContestInfo.objects.get(id=contestid)
queryset = self.filter_queryset(self.get_queryset())
newpage = []
for data in queryset:
if usertype != 3 and userid != data.user and contest.lockboard == 1 and contest.lasttime - (data.submittime - contest.begintime).total_seconds() <= contest.locktime * 60:
data.result = -1
newpage.append(data)
page = self.paginate_queryset(newpage)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(newpage, many=True)
return Response(serializer.data)
class JudgeStatusPutView(viewsets.GenericViewSet, mixins.CreateModelMixin):
queryset = JudgeStatus.objects.all()
serializer_class = JudgeStatusCodeSerializer
permission_classes = (UserRatingOnly,)
throttle_scope = "judge"
throttle_classes = [ScopedRateThrottle, ]
class JudgeStatusCodeView(viewsets.GenericViewSet, mixins.RetrieveModelMixin):
queryset = JudgeStatus.objects.all()
serializer_class = JudgeStatusCodeSerializer
pagination_class = LimitOffsetPagination
filter_backends = (DjangoFilterBackend,)
filter_fields = ('user', 'result', "contest", "problem", "problemtitle")
permission_classes = (NoContestOnly,)
throttle_scope = "post"
throttle_classes = [ScopedRateThrottle, ]
class CaseStatusView(viewsets.ModelViewSet):
queryset = CaseStatus.objects.all()
serializer_class = CaseStatusSerializer
pagination_class = LimitOffsetPagination
filter_backends = (DjangoFilterBackend,)
filter_fields = ('username', 'problem', "statusid")
permission_classes = (ManagerOnly,)
throttle_scope = "post"
throttle_classes = [ScopedRateThrottle, ]
class ACRankView(viewsets.ModelViewSet):
queryset = JudgeStatus.objects.filter(submittime__gte=datetime.datetime.now()-datetime.timedelta(days=30),result=0) # 注意这里只是临时这么写!如果OJ使用的人多!这里会有性能问题!!# 这里有bug,不应该在queryset里写filter。时间会提前算好,导致不准确
serializer_class = JudgeStatusSerializer
pagination_class = LimitOffsetPagination
filter_backends = (DjangoFilterBackend,)
filter_fields = ('user', 'result', "contest", "problem", "language")
permission_classes = (ManagerOnly,)
throttle_scope = "post"
throttle_classes = [ScopedRateThrottle, ]
class RejudgeAPIView(APIView):
permission_classes = (ManagerOnly,)
def post(self, request, format=None):
data = request.data
contestid = data.get('contestid', "")
problem = data.get('problem', "")
statusid = data.get('statusid', "")
statustype = data.get('statustype', "")
print(contestid, problem, statusid, statustype)
if contestid == 0 or problem == -1:
return Response("bad", status=HTTP_400_BAD_REQUEST)
if contestid != "" and problem != "":
JudgeStatus.objects.filter(contest=contestid).filter(
contestproblem=problem).update(result=-1)
return Response("ok", status=HTTP_200_OK)
if problem != "" and contestid == "":
JudgeStatus.objects.filter(problem=problem).update(result=-1)
return Response("ok", status=HTTP_200_OK)
if statusid != "":
JudgeStatus.objects.filter(id=statusid).update(result=-1)
return Response("ok", status=HTTP_200_OK)
if statustype != "":
JudgeStatus.objects.filter(result=statustype).update(result=-1)
return Response("ok", status=HTTP_200_OK)
return Response("bad", status=HTTP_400_BAD_REQUEST)
| Backend/judgestatus/views.py | 5,871 | -*- coding: utf-8 -*- 封榜特判 注意这里只是临时这么写!如果OJ使用的人多!这里会有性能问题!! 这里有bug,不应该在queryset里写filter。时间会提前算好,导致不准确 | 101 | zh | 0.970549 |
#Neural Networks
#MLP classifier is optimal algorithm for classifications
from sklearn.neural_network import MLPClassifier
clf = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=1)
clf.fit(X_train_clean, y_train)
clf.predict(X_test_clean)
scoreN = clf.score(X_test_clean, y_test)
print(scoreN) | models/model_NN.py | 329 | Neural NetworksMLP classifier is optimal algorithm for classifications | 70 | en | 0.83492 |
"""common logic for all queries"""
import json
from functools import partial, singledispatch
from operator import itemgetter
import snug
from gentools import (compose, map_yield, map_send, oneyield, reusable,
map_return)
from .load import registry
API_URL = 'https://slack.com/api/'
class ApiError(Exception):
pass
def _parse_content(response):
"""parse the response body as JSON, raise on errors"""
if response.status_code != 200:
raise ApiError(f'unknown error: {response.content.decode()}')
result = json.loads(response.content)
if not result['ok']:
raise ApiError(f'{result["error"]}: {result.get("detail")}')
return result
basic_interaction = compose(map_yield(snug.prefix_adder(API_URL)),
map_send(_parse_content))
"""basic request/response parsing"""
@singledispatch
def _dump_queryparam_value(val):
return str(val)
@_dump_queryparam_value.register(bool)
def _dump_bool_value(val):
return 'true' if val else 'false'
def _dump_params(params):
return {k: _dump_queryparam_value(v) for k, v in params.items()
if v is not None}
def paginated_retrieval(methodname, itemtype):
"""decorator factory for retrieval queries from query params"""
return compose(
reusable,
basic_interaction,
map_yield(partial(_params_as_get, methodname)),
)
def _params_as_get(methodname: str, params: dict) -> snug.Request:
return snug.GET(methodname, params=_dump_params(params))
def json_post(methodname, rtype, key):
"""decorator factory for json POST queries"""
return compose(
reusable,
map_return(registry(rtype), itemgetter(key)),
basic_interaction,
map_yield(partial(_json_as_post, methodname)),
oneyield,
)
def _json_as_post(methodname: str, body: dict) -> snug.Request:
return snug.POST(methodname,
json.dumps({k: v for k, v in body.items()
if v is not None}),
headers={'Content-Type': 'application/json'})
| examples/slack/query.py | 2,105 | parse the response body as JSON, raise on errors
decorator factory for json POST queries
decorator factory for retrieval queries from query params
common logic for all queries | 175 | en | 0.83418 |
#!/usr/bin/env python3
# Data schema:
# (start) (12b junk) artist (5* byte) (1b junk) title (col) (1b junk) date and time (col) (1b junk) url (urldur) duration (col) (1b junk) thumbnail url (end)
keybytes = {
"row_start": "80 09 80 00 80", # row start
"col": "5F 10", # column delimeter
"urldur": "58", # url/duration delimeter
"urldur2": "D8",
"urldur3": "D2",
"row_end": "D8 00 0A 00 2A 00 2B 00 2C 00 2D 00 2E 00 2F 00 30 00 31 00 32 00" # row end
}
# convert hex to bytes
for k, v in keybytes.items():
keybytes[k] = bytearray.fromhex(v)
def get_urls_from_playlist(filename):
with open(filename, "rb") as f:
content = f.read()
for row in content.split(keybytes["row_start"])[1:]:
try:
row = row.split(keybytes["row_end"])[0] # cut off everything after the row end
columns = row.split(keybytes["col"])
for col in columns:
if "http" in str(col):
# cut off junk bytes
url = col.split(keybytes["urldur"])[0].split(keybytes["urldur2"])[0].split(keybytes["urldur3"])[0]
url = url[1:].decode("utf-8")
yield url
except Exception as e:
pass
| playlist_parser.py | 1,291 | !/usr/bin/env python3 Data schema: (start) (12b junk) artist (5* byte) (1b junk) title (col) (1b junk) date and time (col) (1b junk) url (urldur) duration (col) (1b junk) thumbnail url (end) row start column delimeter url/duration delimeter row end convert hex to bytes cut off everything after the row end cut off junk bytes | 325 | en | 0.42237 |
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
All layers just related to the detection neural network.
"""
from __future__ import print_function
from .layer_function_generator import generate_layer_fn
from .layer_function_generator import autodoc, templatedoc
from ..layer_helper import LayerHelper
from ..framework import Variable
from .loss import softmax_with_cross_entropy
from . import tensor
from . import nn
from . import ops
from ... import compat as cpt
from ..data_feeder import check_variable_and_dtype, check_type, check_dtype
import math
import six
import numpy as np
from functools import reduce
from ..data_feeder import convert_dtype, check_variable_and_dtype, check_type, check_dtype
__all__ = [
'prior_box',
'density_prior_box',
'multi_box_head',
'bipartite_match',
'target_assign',
'detection_output',
'ssd_loss',
'rpn_target_assign',
'retinanet_target_assign',
'sigmoid_focal_loss',
'anchor_generator',
'roi_perspective_transform',
'generate_proposal_labels',
'generate_proposals',
'generate_mask_labels',
'iou_similarity',
'box_coder',
'polygon_box_transform',
'yolov3_loss',
'yolo_box',
'box_clip',
'multiclass_nms',
'locality_aware_nms',
'matrix_nms',
'retinanet_detection_output',
'distribute_fpn_proposals',
'box_decoder_and_assign',
'collect_fpn_proposals',
]
def retinanet_target_assign(bbox_pred,
cls_logits,
anchor_box,
anchor_var,
gt_boxes,
gt_labels,
is_crowd,
im_info,
num_classes=1,
positive_overlap=0.5,
negative_overlap=0.4):
"""
**Target Assign Layer for the detector RetinaNet.**
This OP finds out positive and negative samples from all anchors
for training the detector `RetinaNet <https://arxiv.org/abs/1708.02002>`_ ,
and assigns target labels for classification along with target locations for
regression to each sample, then takes out the part belonging to positive and
negative samples from category prediction( :attr:`cls_logits`) and location
prediction( :attr:`bbox_pred`) which belong to all anchors.
The searching principles for positive and negative samples are as followed:
1. Anchors are assigned to ground-truth boxes when it has the highest IoU
overlap with a ground-truth box.
2. Anchors are assigned to ground-truth boxes when it has an IoU overlap
higher than :attr:`positive_overlap` with any ground-truth box.
3. Anchors are assigned to background when its IoU overlap is lower than
:attr:`negative_overlap` for all ground-truth boxes.
4. Anchors which do not meet the above conditions do not participate in
the training process.
Retinanet predicts a :math:`C`-vector for classification and a 4-vector for box
regression for each anchor, hence the target label for each positive(or negative)
sample is a :math:`C`-vector and the target locations for each positive sample
is a 4-vector. As for a positive sample, if the category of its assigned
ground-truth box is class :math:`i`, the corresponding entry in its length
:math:`C` label vector is set to 1 and all other entries is set to 0, its box
regression targets are computed as the offset between itself and its assigned
ground-truth box. As for a negative sample, all entries in its length :math:`C`
label vector are set to 0 and box regression targets are omitted because
negative samples do not participate in the training process of location
regression.
After the assignment, the part belonging to positive and negative samples is
taken out from category prediction( :attr:`cls_logits` ), and the part
belonging to positive samples is taken out from location
prediction( :attr:`bbox_pred` ).
Args:
bbox_pred(Variable): A 3-D Tensor with shape :math:`[N, M, 4]` represents
the predicted locations of all anchors. :math:`N` is the batch size( the
number of images in a mini-batch), :math:`M` is the number of all anchors
of one image, and each anchor has 4 coordinate values. The data type of
:attr:`bbox_pred` is float32 or float64.
cls_logits(Variable): A 3-D Tensor with shape :math:`[N, M, C]` represents
the predicted categories of all anchors. :math:`N` is the batch size,
:math:`M` is the number of all anchors of one image, and :math:`C` is
the number of categories (**Notice: excluding background**). The data type
of :attr:`cls_logits` is float32 or float64.
anchor_box(Variable): A 2-D Tensor with shape :math:`[M, 4]` represents
the locations of all anchors. :math:`M` is the number of all anchors of
one image, each anchor is represented as :math:`[xmin, ymin, xmax, ymax]`,
:math:`[xmin, ymin]` is the left top coordinate of the anchor box,
:math:`[xmax, ymax]` is the right bottom coordinate of the anchor box.
The data type of :attr:`anchor_box` is float32 or float64. Please refer
to the OP :ref:`api_fluid_layers_anchor_generator`
for the generation of :attr:`anchor_box`.
anchor_var(Variable): A 2-D Tensor with shape :math:`[M,4]` represents the expanded
factors of anchor locations used in loss function. :math:`M` is number of
all anchors of one image, each anchor possesses a 4-vector expanded factor.
The data type of :attr:`anchor_var` is float32 or float64. Please refer
to the OP :ref:`api_fluid_layers_anchor_generator`
for the generation of :attr:`anchor_var`.
gt_boxes(Variable): A 1-level 2-D LoDTensor with shape :math:`[G, 4]` represents
locations of all ground-truth boxes. :math:`G` is the total number of
all ground-truth boxes in a mini-batch, and each ground-truth box has 4
coordinate values. The data type of :attr:`gt_boxes` is float32 or
float64.
gt_labels(variable): A 1-level 2-D LoDTensor with shape :math:`[G, 1]` represents
categories of all ground-truth boxes, and the values are in the range of
:math:`[1, C]`. :math:`G` is the total number of all ground-truth boxes
in a mini-batch, and each ground-truth box has one category. The data type
of :attr:`gt_labels` is int32.
is_crowd(Variable): A 1-level 1-D LoDTensor with shape :math:`[G]` which
indicates whether a ground-truth box is a crowd. If the value is 1, the
corresponding box is a crowd, it is ignored during training. :math:`G` is
the total number of all ground-truth boxes in a mini-batch. The data type
of :attr:`is_crowd` is int32.
im_info(Variable): A 2-D Tensor with shape [N, 3] represents the size
information of input images. :math:`N` is the batch size, the size
information of each image is a 3-vector which are the height and width
of the network input along with the factor scaling the origin image to
the network input. The data type of :attr:`im_info` is float32.
num_classes(int32): The number of categories for classification, the default
value is 1.
positive_overlap(float32): Minimum overlap required between an anchor
and ground-truth box for the anchor to be a positive sample, the default
value is 0.5.
negative_overlap(float32): Maximum overlap allowed between an anchor
and ground-truth box for the anchor to be a negative sample, the default
value is 0.4. :attr:`negative_overlap` should be less than or equal to
:attr:`positive_overlap`, if not, the actual value of
:attr:`positive_overlap` is :attr:`negative_overlap`.
Returns:
A tuple with 6 Variables:
**predict_scores** (Variable): A 2-D Tensor with shape :math:`[F+B, C]` represents
category prediction belonging to positive and negative samples. :math:`F`
is the number of positive samples in a mini-batch, :math:`B` is the number
of negative samples, and :math:`C` is the number of categories
(**Notice: excluding background**). The data type of :attr:`predict_scores`
is float32 or float64.
**predict_location** (Variable): A 2-D Tensor with shape :math:`[F, 4]` represents
location prediction belonging to positive samples. :math:`F` is the number
of positive samples. :math:`F` is the number of positive samples, and each
sample has 4 coordinate values. The data type of :attr:`predict_location`
is float32 or float64.
**target_label** (Variable): A 2-D Tensor with shape :math:`[F+B, 1]` represents
target labels for classification belonging to positive and negative
samples. :math:`F` is the number of positive samples, :math:`B` is the
number of negative, and each sample has one target category. The data type
of :attr:`target_label` is int32.
**target_bbox** (Variable): A 2-D Tensor with shape :math:`[F, 4]` represents
target locations for box regression belonging to positive samples.
:math:`F` is the number of positive samples, and each sample has 4
coordinate values. The data type of :attr:`target_bbox` is float32 or
float64.
**bbox_inside_weight** (Variable): A 2-D Tensor with shape :math:`[F, 4]`
represents whether a positive sample is fake positive, if a positive
sample is false positive, the corresponding entries in
:attr:`bbox_inside_weight` are set 0, otherwise 1. :math:`F` is the number
of total positive samples in a mini-batch, and each sample has 4
coordinate values. The data type of :attr:`bbox_inside_weight` is float32
or float64.
**fg_num** (Variable): A 2-D Tensor with shape :math:`[N, 1]` represents the number
of positive samples. :math:`N` is the batch size. **Notice: The number
of positive samples is used as the denominator of later loss function,
to avoid the condition that the denominator is zero, this OP has added 1
to the actual number of positive samples of each image.** The data type of
:attr:`fg_num` is int32.
Examples:
.. code-block:: python
import paddle.fluid as fluid
bbox_pred = fluid.data(name='bbox_pred', shape=[1, 100, 4],
dtype='float32')
cls_logits = fluid.data(name='cls_logits', shape=[1, 100, 10],
dtype='float32')
anchor_box = fluid.data(name='anchor_box', shape=[100, 4],
dtype='float32')
anchor_var = fluid.data(name='anchor_var', shape=[100, 4],
dtype='float32')
gt_boxes = fluid.data(name='gt_boxes', shape=[10, 4],
dtype='float32')
gt_labels = fluid.data(name='gt_labels', shape=[10, 1],
dtype='int32')
is_crowd = fluid.data(name='is_crowd', shape=[1],
dtype='int32')
im_info = fluid.data(name='im_info', shape=[1, 3],
dtype='float32')
score_pred, loc_pred, score_target, loc_target, bbox_inside_weight, fg_num = \\
fluid.layers.retinanet_target_assign(bbox_pred, cls_logits, anchor_box,
anchor_var, gt_boxes, gt_labels, is_crowd, im_info, 10)
"""
check_variable_and_dtype(bbox_pred, 'bbox_pred', ['float32', 'float64'],
'retinanet_target_assign')
check_variable_and_dtype(cls_logits, 'cls_logits', ['float32', 'float64'],
'retinanet_target_assign')
check_variable_and_dtype(anchor_box, 'anchor_box', ['float32', 'float64'],
'retinanet_target_assign')
check_variable_and_dtype(anchor_var, 'anchor_var', ['float32', 'float64'],
'retinanet_target_assign')
check_variable_and_dtype(gt_boxes, 'gt_boxes', ['float32', 'float64'],
'retinanet_target_assign')
check_variable_and_dtype(gt_labels, 'gt_labels', ['int32'],
'retinanet_target_assign')
check_variable_and_dtype(is_crowd, 'is_crowd', ['int32'],
'retinanet_target_assign')
check_variable_and_dtype(im_info, 'im_info', ['float32', 'float64'],
'retinanet_target_assign')
helper = LayerHelper('retinanet_target_assign', **locals())
# Assign target label to anchors
loc_index = helper.create_variable_for_type_inference(dtype='int32')
score_index = helper.create_variable_for_type_inference(dtype='int32')
target_label = helper.create_variable_for_type_inference(dtype='int32')
target_bbox = helper.create_variable_for_type_inference(
dtype=anchor_box.dtype)
bbox_inside_weight = helper.create_variable_for_type_inference(
dtype=anchor_box.dtype)
fg_num = helper.create_variable_for_type_inference(dtype='int32')
helper.append_op(
type="retinanet_target_assign",
inputs={
'Anchor': anchor_box,
'GtBoxes': gt_boxes,
'GtLabels': gt_labels,
'IsCrowd': is_crowd,
'ImInfo': im_info
},
outputs={
'LocationIndex': loc_index,
'ScoreIndex': score_index,
'TargetLabel': target_label,
'TargetBBox': target_bbox,
'BBoxInsideWeight': bbox_inside_weight,
'ForegroundNumber': fg_num
},
attrs={
'positive_overlap': positive_overlap,
'negative_overlap': negative_overlap
})
loc_index.stop_gradient = True
score_index.stop_gradient = True
target_label.stop_gradient = True
target_bbox.stop_gradient = True
bbox_inside_weight.stop_gradient = True
fg_num.stop_gradient = True
cls_logits = nn.reshape(x=cls_logits, shape=(-1, num_classes))
bbox_pred = nn.reshape(x=bbox_pred, shape=(-1, 4))
predicted_cls_logits = nn.gather(cls_logits, score_index)
predicted_bbox_pred = nn.gather(bbox_pred, loc_index)
return predicted_cls_logits, predicted_bbox_pred, target_label, target_bbox, bbox_inside_weight, fg_num
def rpn_target_assign(bbox_pred,
cls_logits,
anchor_box,
anchor_var,
gt_boxes,
is_crowd,
im_info,
rpn_batch_size_per_im=256,
rpn_straddle_thresh=0.0,
rpn_fg_fraction=0.5,
rpn_positive_overlap=0.7,
rpn_negative_overlap=0.3,
use_random=True):
"""
**Target Assign Layer for region proposal network (RPN) in Faster-RCNN detection.**
This layer can be, for given the Intersection-over-Union (IoU) overlap
between anchors and ground truth boxes, to assign classification and
regression targets to each each anchor, these target labels are used for
train RPN. The classification targets is a binary class label (of being
an object or not). Following the paper of Faster-RCNN, the positive labels
are two kinds of anchors: (i) the anchor/anchors with the highest IoU
overlap with a ground-truth box, or (ii) an anchor that has an IoU overlap
higher than rpn_positive_overlap(0.7) with any ground-truth box. Note
that a single ground-truth box may assign positive labels to multiple
anchors. A non-positive anchor is when its IoU ratio is lower than
rpn_negative_overlap (0.3) for all ground-truth boxes. Anchors that are
neither positive nor negative do not contribute to the training objective.
The regression targets are the encoded ground-truth boxes associated with
the positive anchors.
Args:
bbox_pred(Variable): A 3-D Tensor with shape [N, M, 4] represents the
predicted locations of M bounding bboxes. N is the batch size,
and each bounding box has four coordinate values and the layout
is [xmin, ymin, xmax, ymax]. The data type can be float32 or float64.
cls_logits(Variable): A 3-D Tensor with shape [N, M, 1] represents the
predicted confidence predictions. N is the batch size, 1 is the
frontground and background sigmoid, M is number of bounding boxes.
The data type can be float32 or float64.
anchor_box(Variable): A 2-D Tensor with shape [M, 4] holds M boxes,
each box is represented as [xmin, ymin, xmax, ymax],
[xmin, ymin] is the left top coordinate of the anchor box,
if the input is image feature map, they are close to the origin
of the coordinate system. [xmax, ymax] is the right bottom
coordinate of the anchor box. The data type can be float32 or float64.
anchor_var(Variable): A 2-D Tensor with shape [M,4] holds expanded
variances of anchors. The data type can be float32 or float64.
gt_boxes (Variable): The ground-truth bounding boxes (bboxes) are a 2D
LoDTensor with shape [Ng, 4], Ng is the total number of ground-truth
bboxes of mini-batch input. The data type can be float32 or float64.
is_crowd (Variable): A 1-D LoDTensor which indicates groud-truth is crowd.
The data type must be int32.
im_info (Variable): A 2-D LoDTensor with shape [N, 3]. N is the batch size,
3 is the height, width and scale.
rpn_batch_size_per_im(int): Total number of RPN examples per image.
The data type must be int32.
rpn_straddle_thresh(float): Remove RPN anchors that go outside the image
by straddle_thresh pixels. The data type must be float32.
rpn_fg_fraction(float): Target fraction of RoI minibatch that is labeled
foreground (i.e. class > 0), 0-th class is background. The data type must be float32.
rpn_positive_overlap(float): Minimum overlap required between an anchor
and ground-truth box for the (anchor, gt box) pair to be a positive
example. The data type must be float32.
rpn_negative_overlap(float): Maximum overlap allowed between an anchor
and ground-truth box for the (anchor, gt box) pair to be a negative
examples. The data type must be float32.
Returns:
tuple:
A tuple(predicted_scores, predicted_location, target_label,
target_bbox, bbox_inside_weight) is returned. The predicted_scores
and predicted_location is the predicted result of the RPN.
The target_label and target_bbox is the ground truth,
respectively. The predicted_location is a 2D Tensor with shape
[F, 4], and the shape of target_bbox is same as the shape of
the predicted_location, F is the number of the foreground
anchors. The predicted_scores is a 2D Tensor with shape
[F + B, 1], and the shape of target_label is same as the shape
of the predicted_scores, B is the number of the background
anchors, the F and B is depends on the input of this operator.
Bbox_inside_weight represents whether the predicted loc is fake_fg
or not and the shape is [F, 4].
Examples:
.. code-block:: python
import paddle.fluid as fluid
bbox_pred = fluid.data(name='bbox_pred', shape=[None, 4], dtype='float32')
cls_logits = fluid.data(name='cls_logits', shape=[None, 1], dtype='float32')
anchor_box = fluid.data(name='anchor_box', shape=[None, 4], dtype='float32')
anchor_var = fluid.data(name='anchor_var', shape=[None, 4], dtype='float32')
gt_boxes = fluid.data(name='gt_boxes', shape=[None, 4], dtype='float32')
is_crowd = fluid.data(name='is_crowd', shape=[None], dtype='float32')
im_info = fluid.data(name='im_infoss', shape=[None, 3], dtype='float32')
loc, score, loc_target, score_target, inside_weight = fluid.layers.rpn_target_assign(
bbox_pred, cls_logits, anchor_box, anchor_var, gt_boxes, is_crowd, im_info)
"""
helper = LayerHelper('rpn_target_assign', **locals())
check_variable_and_dtype(bbox_pred, 'bbox_pred', ['float32', 'float64'],
'rpn_target_assign')
check_variable_and_dtype(cls_logits, 'cls_logits', ['float32', 'float64'],
'rpn_target_assign')
check_variable_and_dtype(anchor_box, 'anchor_box', ['float32', 'float64'],
'rpn_target_assign')
check_variable_and_dtype(anchor_var, 'anchor_var', ['float32', 'float64'],
'rpn_target_assign')
check_variable_and_dtype(gt_boxes, 'gt_boxes', ['float32', 'float64'],
'rpn_target_assign')
check_variable_and_dtype(is_crowd, 'is_crowd', ['int32'],
'rpn_target_assign')
check_variable_and_dtype(im_info, 'im_info', ['float32', 'float64'],
'rpn_target_assign')
# Assign target label to anchors
loc_index = helper.create_variable_for_type_inference(dtype='int32')
score_index = helper.create_variable_for_type_inference(dtype='int32')
target_label = helper.create_variable_for_type_inference(dtype='int32')
target_bbox = helper.create_variable_for_type_inference(
dtype=anchor_box.dtype)
bbox_inside_weight = helper.create_variable_for_type_inference(
dtype=anchor_box.dtype)
helper.append_op(
type="rpn_target_assign",
inputs={
'Anchor': anchor_box,
'GtBoxes': gt_boxes,
'IsCrowd': is_crowd,
'ImInfo': im_info
},
outputs={
'LocationIndex': loc_index,
'ScoreIndex': score_index,
'TargetLabel': target_label,
'TargetBBox': target_bbox,
'BBoxInsideWeight': bbox_inside_weight
},
attrs={
'rpn_batch_size_per_im': rpn_batch_size_per_im,
'rpn_straddle_thresh': rpn_straddle_thresh,
'rpn_positive_overlap': rpn_positive_overlap,
'rpn_negative_overlap': rpn_negative_overlap,
'rpn_fg_fraction': rpn_fg_fraction,
'use_random': use_random
})
loc_index.stop_gradient = True
score_index.stop_gradient = True
target_label.stop_gradient = True
target_bbox.stop_gradient = True
bbox_inside_weight.stop_gradient = True
cls_logits = nn.reshape(x=cls_logits, shape=(-1, 1))
bbox_pred = nn.reshape(x=bbox_pred, shape=(-1, 4))
predicted_cls_logits = nn.gather(cls_logits, score_index)
predicted_bbox_pred = nn.gather(bbox_pred, loc_index)
return predicted_cls_logits, predicted_bbox_pred, target_label, target_bbox, bbox_inside_weight
def sigmoid_focal_loss(x, label, fg_num, gamma=2.0, alpha=0.25):
"""
:alias_main: paddle.nn.functional.sigmoid_focal_loss
:alias: paddle.nn.functional.sigmoid_focal_loss,paddle.nn.functional.loss.sigmoid_focal_loss
:old_api: paddle.fluid.layers.sigmoid_focal_loss
**Sigmoid Focal Loss Operator.**
`Focal Loss <https://arxiv.org/abs/1708.02002>`_ is used to address the foreground-background
class imbalance existed on the training phase of many computer vision tasks. This OP computes
the sigmoid value for each element in the input tensor :attr:`x`, after which focal loss is
measured between the sigmoid value and target label.
The focal loss is given as followed:
.. math::
\\mathop{loss_{i,\\,j}}\\limits_{i\\in\\mathbb{[0,\\,N-1]},\\,j\\in\\mathbb{[0,\\,C-1]}}=\\left\\{
\\begin{array}{rcl}
- \\frac{1}{fg\_num} * \\alpha * {(1 - \\sigma(x_{i,\\,j}))}^{\\gamma} * \\log(\\sigma(x_{i,\\,j})) & & {(j +1) = label_{i,\\,0}} \\\\
- \\frac{1}{fg\_num} * (1 - \\alpha) * {\sigma(x_{i,\\,j})}^{ \\gamma} * \\log(1 - \\sigma(x_{i,\\,j})) & & {(j +1)!= label_{i,\\,0}}
\\end{array} \\right.
We know that
.. math::
\\sigma(x_j) = \\frac{1}{1 + \\exp(-x_j)}
Args:
x(Variable): A 2-D tensor with shape :math:`[N, C]` represents the predicted categories of
all samples. :math:`N` is the number of all samples responsible for optimization in
a mini-batch, for example, samples are anchor boxes for object detection and :math:`N`
is the total number of positive and negative samples in a mini-batch; Samples are images
for image classification and :math:`N` is the number of images in a mini-batch. :math:`C`
is the number of classes (**Notice: excluding background**). The data type of :attr:`x` is
float32 or float64.
label(Variable): A 2-D tensor with shape :math:`[N, 1]` represents the target labels for
classification. :math:`N` is the number of all samples responsible for optimization in a
mini-batch, each sample has one target category. The values for positive samples are in the
range of :math:`[1, C]`, and the values for negative samples are 0. The data type of :attr:`label`
is int32.
fg_num(Variable): A 1-D tensor with shape [1] represents the number of positive samples in a
mini-batch, which should be obtained before this OP. The data type of :attr:`fg_num` is int32.
gamma(int|float): Hyper-parameter to balance the easy and hard examples. Default value is
set to 2.0.
alpha(int|float): Hyper-parameter to balance the positive and negative example. Default value
is set to 0.25.
Returns:
Variable(the data type is float32 or float64):
A 2-D tensor with shape :math:`[N, C]`, which is the focal loss of each element in the input
tensor :attr:`x`.
Examples:
.. code-block:: python
import numpy as np
import paddle.fluid as fluid
num_classes = 10 # exclude background
image_width = 16
image_height = 16
batch_size = 32
max_iter = 20
def gen_train_data():
x_data = np.random.uniform(0, 255, (batch_size, 3, image_height,
image_width)).astype('float64')
label_data = np.random.randint(0, num_classes,
(batch_size, 1)).astype('int32')
return {"x": x_data, "label": label_data}
def get_focal_loss(pred, label, fg_num, num_classes):
pred = fluid.layers.reshape(pred, [-1, num_classes])
label = fluid.layers.reshape(label, [-1, 1])
label.stop_gradient = True
loss = fluid.layers.sigmoid_focal_loss(
pred, label, fg_num, gamma=2.0, alpha=0.25)
loss = fluid.layers.reduce_sum(loss)
return loss
def build_model(mode='train'):
x = fluid.data(name="x", shape=[-1, 3, -1, -1], dtype='float64')
output = fluid.layers.pool2d(input=x, pool_type='avg', global_pooling=True)
output = fluid.layers.fc(
input=output,
size=num_classes,
# Notice: size is set to be the number of target classes (excluding backgorund)
# because sigmoid activation will be done in the sigmoid_focal_loss op.
act=None)
if mode == 'train':
label = fluid.data(name="label", shape=[-1, 1], dtype='int32')
# Obtain the fg_num needed by the sigmoid_focal_loss op:
# 0 in label represents background, >=1 in label represents foreground,
# find the elements in label which are greater or equal than 1, then
# computed the numbers of these elements.
data = fluid.layers.fill_constant(shape=[1], value=1, dtype='int32')
fg_label = fluid.layers.greater_equal(label, data)
fg_label = fluid.layers.cast(fg_label, dtype='int32')
fg_num = fluid.layers.reduce_sum(fg_label)
fg_num.stop_gradient = True
avg_loss = get_focal_loss(output, label, fg_num, num_classes)
return avg_loss
else:
# During evaluating or testing phase,
# output of the final fc layer should be connected to a sigmoid layer.
pred = fluid.layers.sigmoid(output)
return pred
loss = build_model('train')
moment_optimizer = fluid.optimizer.MomentumOptimizer(
learning_rate=0.001, momentum=0.9)
moment_optimizer.minimize(loss)
place = fluid.CPUPlace()
exe = fluid.Executor(place)
exe.run(fluid.default_startup_program())
for i in range(max_iter):
outs = exe.run(feed=gen_train_data(), fetch_list=[loss.name])
print(outs)
"""
check_variable_and_dtype(x, 'x', ['float32', 'float64'],
'sigmoid_focal_loss')
check_variable_and_dtype(label, 'label', ['int32'], 'sigmoid_focal_loss')
check_variable_and_dtype(fg_num, 'fg_num', ['int32'], 'sigmoid_focal_loss')
helper = LayerHelper("sigmoid_focal_loss", **locals())
out = helper.create_variable_for_type_inference(dtype=x.dtype)
helper.append_op(
type="sigmoid_focal_loss",
inputs={"X": x,
"Label": label,
"FgNum": fg_num},
attrs={"gamma": gamma,
'alpha': alpha},
outputs={"Out": out})
return out
def detection_output(loc,
scores,
prior_box,
prior_box_var,
background_label=0,
nms_threshold=0.3,
nms_top_k=400,
keep_top_k=200,
score_threshold=0.01,
nms_eta=1.0,
return_index=False):
"""
:alias_main: paddle.nn.functional.detection_output
:alias: paddle.nn.functional.detection_output,paddle.nn.functional.vision.detection_output
:old_api: paddle.fluid.layers.detection_output
Given the regression locations, classification confidences and prior boxes,
calculate the detection outputs by performing following steps:
1. Decode input bounding box predictions according to the prior boxes and
regression locations.
2. Get the final detection results by applying multi-class non maximum
suppression (NMS).
Please note, this operation doesn't clip the final output bounding boxes
to the image window.
Args:
loc(Variable): A 3-D Tensor with shape [N, M, 4] represents the
predicted locations of M bounding bboxes. Data type should be
float32 or float64. N is the batch size,
and each bounding box has four coordinate values and the layout
is [xmin, ymin, xmax, ymax].
scores(Variable): A 3-D Tensor with shape [N, M, C] represents the
predicted confidence predictions. Data type should be float32
or float64. N is the batch size, C is the
class number, M is number of bounding boxes.
prior_box(Variable): A 2-D Tensor with shape [M, 4] holds M boxes,
each box is represented as [xmin, ymin, xmax, ymax]. Data type
should be float32 or float64.
prior_box_var(Variable): A 2-D Tensor with shape [M, 4] holds M group
of variance. Data type should be float32 or float64.
background_label(int): The index of background label,
the background label will be ignored. If set to -1, then all
categories will be considered. Default: 0.
nms_threshold(float): The threshold to be used in NMS. Default: 0.3.
nms_top_k(int): Maximum number of detections to be kept according
to the confidences after filtering detections based on
score_threshold and before NMS. Default: 400.
keep_top_k(int): Number of total bboxes to be kept per image after
NMS step. -1 means keeping all bboxes after NMS step. Default: 200.
score_threshold(float): Threshold to filter out bounding boxes with
low confidence score. If not provided, consider all boxes.
Default: 0.01.
nms_eta(float): The parameter for adaptive NMS. It works only when the
value is less than 1.0. Default: 1.0.
return_index(bool): Whether return selected index. Default: False
Returns:
A tuple with two Variables: (Out, Index) if return_index is True,
otherwise, a tuple with one Variable(Out) is returned.
Out (Variable): The detection outputs is a LoDTensor with shape [No, 6].
Data type is the same as input (loc). Each row has six values:
[label, confidence, xmin, ymin, xmax, ymax]. `No` is
the total number of detections in this mini-batch. For each instance,
the offsets in first dimension are called LoD, the offset number is
N + 1, N is the batch size. The i-th image has `LoD[i + 1] - LoD[i]`
detected results, if it is 0, the i-th image has no detected results.
Index (Variable): Only return when return_index is True. A 2-D LoDTensor
with shape [No, 1] represents the selected index which type is Integer.
The index is the absolute value cross batches. No is the same number
as Out. If the index is used to gather other attribute such as age,
one needs to reshape the input(N, M, 1) to (N * M, 1) as first, where
N is the batch size and M is the number of boxes.
Examples:
.. code-block:: python
import paddle.fluid as fluid
pb = fluid.data(name='prior_box', shape=[10, 4], dtype='float32')
pbv = fluid.data(name='prior_box_var', shape=[10, 4], dtype='float32')
loc = fluid.data(name='target_box', shape=[2, 21, 4], dtype='float32')
scores = fluid.data(name='scores', shape=[2, 21, 10], dtype='float32')
nmsed_outs, index = fluid.layers.detection_output(scores=scores,
loc=loc,
prior_box=pb,
prior_box_var=pbv,
return_index=True)
"""
helper = LayerHelper("detection_output", **locals())
decoded_box = box_coder(
prior_box=prior_box,
prior_box_var=prior_box_var,
target_box=loc,
code_type='decode_center_size')
scores = nn.softmax(input=scores)
scores = nn.transpose(scores, perm=[0, 2, 1])
scores.stop_gradient = True
nmsed_outs = helper.create_variable_for_type_inference(
dtype=decoded_box.dtype)
if return_index:
index = helper.create_variable_for_type_inference(dtype='int')
helper.append_op(
type="multiclass_nms2",
inputs={'Scores': scores,
'BBoxes': decoded_box},
outputs={'Out': nmsed_outs,
'Index': index},
attrs={
'background_label': 0,
'nms_threshold': nms_threshold,
'nms_top_k': nms_top_k,
'keep_top_k': keep_top_k,
'score_threshold': score_threshold,
'nms_eta': 1.0,
})
index.stop_gradient = True
else:
helper.append_op(
type="multiclass_nms",
inputs={'Scores': scores,
'BBoxes': decoded_box},
outputs={'Out': nmsed_outs},
attrs={
'background_label': 0,
'nms_threshold': nms_threshold,
'nms_top_k': nms_top_k,
'keep_top_k': keep_top_k,
'score_threshold': score_threshold,
'nms_eta': 1.0,
})
nmsed_outs.stop_gradient = True
if return_index:
return nmsed_outs, index
return nmsed_outs
@templatedoc()
def iou_similarity(x, y, box_normalized=True, name=None):
"""
:alias_main: paddle.nn.functional.iou_similarity
:alias: paddle.nn.functional.iou_similarity,paddle.nn.functional.loss.iou_similarity
:old_api: paddle.fluid.layers.iou_similarity
${comment}
Args:
x (Variable): ${x_comment}.The data type is float32 or float64.
y (Variable): ${y_comment}.The data type is float32 or float64.
box_normalized(bool): Whether treat the priorbox as a normalized box.
Set true by default.
Returns:
Variable: ${out_comment}.The data type is same with x.
Examples:
.. code-block:: python
import numpy as np
import paddle.fluid as fluid
use_gpu = False
place = fluid.CUDAPlace(0) if use_gpu else fluid.CPUPlace()
exe = fluid.Executor(place)
x = fluid.data(name='x', shape=[None, 4], dtype='float32')
y = fluid.data(name='y', shape=[None, 4], dtype='float32')
iou = fluid.layers.iou_similarity(x=x, y=y)
exe.run(fluid.default_startup_program())
test_program = fluid.default_main_program().clone(for_test=True)
[out_iou] = exe.run(test_program,
fetch_list=iou,
feed={'x': np.array([[0.5, 0.5, 2.0, 2.0],
[0., 0., 1.0, 1.0]]).astype('float32'),
'y': np.array([[1.0, 1.0, 2.5, 2.5]]).astype('float32')})
# out_iou is [[0.2857143],
# [0. ]] with shape: [2, 1]
"""
helper = LayerHelper("iou_similarity", **locals())
out = helper.create_variable_for_type_inference(dtype=x.dtype)
helper.append_op(
type="iou_similarity",
inputs={"X": x,
"Y": y},
attrs={"box_normalized": box_normalized},
outputs={"Out": out})
return out
@templatedoc()
def box_coder(prior_box,
prior_box_var,
target_box,
code_type="encode_center_size",
box_normalized=True,
name=None,
axis=0):
"""
:alias_main: paddle.nn.functional.box_coder
:alias: paddle.nn.functional.box_coder,paddle.nn.functional.vision.box_coder
:old_api: paddle.fluid.layers.box_coder
**Box Coder Layer**
Encode/Decode the target bounding box with the priorbox information.
The Encoding schema described below:
.. math::
ox = (tx - px) / pw / pxv
oy = (ty - py) / ph / pyv
ow = \log(\abs(tw / pw)) / pwv
oh = \log(\abs(th / ph)) / phv
The Decoding schema described below:
.. math::
ox = (pw * pxv * tx * + px) - tw / 2
oy = (ph * pyv * ty * + py) - th / 2
ow = \exp(pwv * tw) * pw + tw / 2
oh = \exp(phv * th) * ph + th / 2
where `tx`, `ty`, `tw`, `th` denote the target box's center coordinates,
width and height respectively. Similarly, `px`, `py`, `pw`, `ph` denote
the priorbox's (anchor) center coordinates, width and height. `pxv`,
`pyv`, `pwv`, `phv` denote the variance of the priorbox and `ox`, `oy`,
`ow`, `oh` denote the encoded/decoded coordinates, width and height.
During Box Decoding, two modes for broadcast are supported. Say target
box has shape [N, M, 4], and the shape of prior box can be [N, 4] or
[M, 4]. Then prior box will broadcast to target box along the
assigned axis.
Args:
prior_box(Variable): Box list prior_box is a 2-D Tensor with shape
[M, 4] holds M boxes and data type is float32 or float64. Each box
is represented as [xmin, ymin, xmax, ymax], [xmin, ymin] is the
left top coordinate of the anchor box, if the input is image feature
map, they are close to the origin of the coordinate system.
[xmax, ymax] is the right bottom coordinate of the anchor box.
prior_box_var(List|Variable|None): prior_box_var supports three types
of input. One is variable with shape [M, 4] which holds M group and
data type is float32 or float64. The second is list consist of
4 elements shared by all boxes and data type is float32 or float64.
Other is None and not involved in calculation.
target_box(Variable): This input can be a 2-D LoDTensor with shape
[N, 4] when code_type is 'encode_center_size'. This input also can
be a 3-D Tensor with shape [N, M, 4] when code_type is
'decode_center_size'. Each box is represented as
[xmin, ymin, xmax, ymax]. The data type is float32 or float64.
This tensor can contain LoD information to represent a batch of inputs.
code_type(str): The code type used with the target box. It can be
`encode_center_size` or `decode_center_size`. `encode_center_size`
by default.
box_normalized(bool): Whether treat the priorbox as a normalized box.
Set true by default.
name(str, optional): For detailed information, please refer
to :ref:`api_guide_Name`. Usually name is no need to set and
None by default.
axis(int): Which axis in PriorBox to broadcast for box decode,
for example, if axis is 0 and TargetBox has shape [N, M, 4] and
PriorBox has shape [M, 4], then PriorBox will broadcast to [N, M, 4]
for decoding. It is only valid when code type is
`decode_center_size`. Set 0 by default.
Returns:
Variable:
output_box(Variable): When code_type is 'encode_center_size', the
output tensor of box_coder_op with shape [N, M, 4] representing the
result of N target boxes encoded with M Prior boxes and variances.
When code_type is 'decode_center_size', N represents the batch size
and M represents the number of decoded boxes.
Examples:
.. code-block:: python
import paddle.fluid as fluid
# For encode
prior_box_encode = fluid.data(name='prior_box_encode',
shape=[512, 4],
dtype='float32')
target_box_encode = fluid.data(name='target_box_encode',
shape=[81, 4],
dtype='float32')
output_encode = fluid.layers.box_coder(prior_box=prior_box_encode,
prior_box_var=[0.1,0.1,0.2,0.2],
target_box=target_box_encode,
code_type="encode_center_size")
# For decode
prior_box_decode = fluid.data(name='prior_box_decode',
shape=[512, 4],
dtype='float32')
target_box_decode = fluid.data(name='target_box_decode',
shape=[512, 81, 4],
dtype='float32')
output_decode = fluid.layers.box_coder(prior_box=prior_box_decode,
prior_box_var=[0.1,0.1,0.2,0.2],
target_box=target_box_decode,
code_type="decode_center_size",
box_normalized=False,
axis=1)
"""
check_variable_and_dtype(prior_box, 'prior_box', ['float32', 'float64'],
'box_coder')
check_variable_and_dtype(target_box, 'target_box', ['float32', 'float64'],
'box_coder')
helper = LayerHelper("box_coder", **locals())
output_box = helper.create_variable_for_type_inference(
dtype=prior_box.dtype)
inputs = {"PriorBox": prior_box, "TargetBox": target_box}
attrs = {
"code_type": code_type,
"box_normalized": box_normalized,
"axis": axis
}
if isinstance(prior_box_var, Variable):
inputs['PriorBoxVar'] = prior_box_var
elif isinstance(prior_box_var, list):
attrs['variance'] = prior_box_var
else:
raise TypeError("Input variance of box_coder must be Variable or lisz")
helper.append_op(
type="box_coder",
inputs=inputs,
attrs=attrs,
outputs={"OutputBox": output_box})
return output_box
@templatedoc()
def polygon_box_transform(input, name=None):
"""
${comment}
Args:
input(Variable): The input with shape [batch_size, geometry_channels, height, width].
A Tensor with type float32, float64.
name(str, Optional): For details, please refer to :ref:`api_guide_Name`.
Generally, no setting is required. Default: None.
Returns:
Variable: The output with the same shape as input. A Tensor with type float32, float64.
Examples:
.. code-block:: python
import paddle.fluid as fluid
input = fluid.data(name='input', shape=[4, 10, 5, 5], dtype='float32')
out = fluid.layers.polygon_box_transform(input)
"""
check_variable_and_dtype(input, "input", ['float32', 'float64'],
'polygon_box_transform')
helper = LayerHelper("polygon_box_transform", **locals())
output = helper.create_variable_for_type_inference(dtype=input.dtype)
helper.append_op(
type="polygon_box_transform",
inputs={"Input": input},
attrs={},
outputs={"Output": output})
return output
@templatedoc(op_type="yolov3_loss")
def yolov3_loss(x,
gt_box,
gt_label,
anchors,
anchor_mask,
class_num,
ignore_thresh,
downsample_ratio,
gt_score=None,
use_label_smooth=True,
name=None,
scale_x_y=1.):
"""
:alias_main: paddle.nn.functional.yolov3_loss
:alias: paddle.nn.functional.yolov3_loss,paddle.nn.functional.vision.yolov3_loss
:old_api: paddle.fluid.layers.yolov3_loss
${comment}
Args:
x (Variable): ${x_comment}The data type is float32 or float64.
gt_box (Variable): groud truth boxes, should be in shape of [N, B, 4],
in the third dimension, x, y, w, h should be stored.
x,y is the center coordinate of boxes, w, h are the
width and height, x, y, w, h should be divided by
input image height to scale to [0, 1].
N is the batch number and B is the max box number in
an image.The data type is float32 or float64.
gt_label (Variable): class id of ground truth boxes, should be in shape
of [N, B].The data type is int32.
anchors (list|tuple): ${anchors_comment}
anchor_mask (list|tuple): ${anchor_mask_comment}
class_num (int): ${class_num_comment}
ignore_thresh (float): ${ignore_thresh_comment}
downsample_ratio (int): ${downsample_ratio_comment}
name (string): The default value is None. Normally there is no need
for user to set this property. For more information,
please refer to :ref:`api_guide_Name`
gt_score (Variable): mixup score of ground truth boxes, should be in shape
of [N, B]. Default None.
use_label_smooth (bool): ${use_label_smooth_comment}
scale_x_y (float): ${scale_x_y_comment}
Returns:
Variable: A 1-D tensor with shape [N], the value of yolov3 loss
Raises:
TypeError: Input x of yolov3_loss must be Variable
TypeError: Input gtbox of yolov3_loss must be Variable
TypeError: Input gtlabel of yolov3_loss must be Variable
TypeError: Input gtscore of yolov3_loss must be None or Variable
TypeError: Attr anchors of yolov3_loss must be list or tuple
TypeError: Attr class_num of yolov3_loss must be an integer
TypeError: Attr ignore_thresh of yolov3_loss must be a float number
TypeError: Attr use_label_smooth of yolov3_loss must be a bool value
Examples:
.. code-block:: python
import paddle.fluid as fluid
x = fluid.data(name='x', shape=[None, 255, 13, 13], dtype='float32')
gt_box = fluid.data(name='gt_box', shape=[None, 6, 4], dtype='float32')
gt_label = fluid.data(name='gt_label', shape=[None, 6], dtype='int32')
gt_score = fluid.data(name='gt_score', shape=[None, 6], dtype='float32')
anchors = [10, 13, 16, 30, 33, 23, 30, 61, 62, 45, 59, 119, 116, 90, 156, 198, 373, 326]
anchor_mask = [0, 1, 2]
loss = fluid.layers.yolov3_loss(x=x, gt_box=gt_box, gt_label=gt_label,
gt_score=gt_score, anchors=anchors,
anchor_mask=anchor_mask, class_num=80,
ignore_thresh=0.7, downsample_ratio=32)
"""
helper = LayerHelper('yolov3_loss', **locals())
if not isinstance(x, Variable):
raise TypeError("Input x of yolov3_loss must be Variable")
if not isinstance(gt_box, Variable):
raise TypeError("Input gtbox of yolov3_loss must be Variable")
if not isinstance(gt_label, Variable):
raise TypeError("Input gtlabel of yolov3_loss must be Variable")
if gt_score is not None and not isinstance(gt_score, Variable):
raise TypeError("Input gtscore of yolov3_loss must be Variable")
if not isinstance(anchors, list) and not isinstance(anchors, tuple):
raise TypeError("Attr anchors of yolov3_loss must be list or tuple")
if not isinstance(anchor_mask, list) and not isinstance(anchor_mask, tuple):
raise TypeError("Attr anchor_mask of yolov3_loss must be list or tuple")
if not isinstance(class_num, int):
raise TypeError("Attr class_num of yolov3_loss must be an integer")
if not isinstance(ignore_thresh, float):
raise TypeError(
"Attr ignore_thresh of yolov3_loss must be a float number")
if not isinstance(use_label_smooth, bool):
raise TypeError(
"Attr use_label_smooth of yolov3_loss must be a bool value")
loss = helper.create_variable_for_type_inference(dtype=x.dtype)
objectness_mask = helper.create_variable_for_type_inference(dtype='int32')
gt_match_mask = helper.create_variable_for_type_inference(dtype='int32')
inputs = {
"X": x,
"GTBox": gt_box,
"GTLabel": gt_label,
}
if gt_score is not None:
inputs["GTScore"] = gt_score
attrs = {
"anchors": anchors,
"anchor_mask": anchor_mask,
"class_num": class_num,
"ignore_thresh": ignore_thresh,
"downsample_ratio": downsample_ratio,
"use_label_smooth": use_label_smooth,
"scale_x_y": scale_x_y,
}
helper.append_op(
type='yolov3_loss',
inputs=inputs,
outputs={
'Loss': loss,
'ObjectnessMask': objectness_mask,
'GTMatchMask': gt_match_mask
},
attrs=attrs)
return loss
@templatedoc(op_type="yolo_box")
def yolo_box(x,
img_size,
anchors,
class_num,
conf_thresh,
downsample_ratio,
clip_bbox=True,
name=None,
scale_x_y=1.):
"""
:alias_main: paddle.nn.functional.yolo_box
:alias: paddle.nn.functional.yolo_box,paddle.nn.functional.vision.yolo_box
:old_api: paddle.fluid.layers.yolo_box
${comment}
Args:
x (Variable): ${x_comment} The data type is float32 or float64.
img_size (Variable): ${img_size_comment} The data type is int32.
anchors (list|tuple): ${anchors_comment}
class_num (int): ${class_num_comment}
conf_thresh (float): ${conf_thresh_comment}
downsample_ratio (int): ${downsample_ratio_comment}
clip_bbox (bool): ${clip_bbox_comment}
scale_x_y (float): ${scale_x_y_comment}
name (string): The default value is None. Normally there is no need
for user to set this property. For more information,
please refer to :ref:`api_guide_Name`
Returns:
Variable: A 3-D tensor with shape [N, M, 4], the coordinates of boxes,
and a 3-D tensor with shape [N, M, :attr:`class_num`], the classification
scores of boxes.
Raises:
TypeError: Input x of yolov_box must be Variable
TypeError: Attr anchors of yolo box must be list or tuple
TypeError: Attr class_num of yolo box must be an integer
TypeError: Attr conf_thresh of yolo box must be a float number
Examples:
.. code-block:: python
import paddle.fluid as fluid
x = fluid.data(name='x', shape=[None, 255, 13, 13], dtype='float32')
img_size = fluid.data(name='img_size',shape=[None, 2],dtype='int64')
anchors = [10, 13, 16, 30, 33, 23]
boxes,scores = fluid.layers.yolo_box(x=x, img_size=img_size, class_num=80, anchors=anchors,
conf_thresh=0.01, downsample_ratio=32)
"""
helper = LayerHelper('yolo_box', **locals())
if not isinstance(x, Variable):
raise TypeError("Input x of yolo_box must be Variable")
if not isinstance(img_size, Variable):
raise TypeError("Input img_size of yolo_box must be Variable")
if not isinstance(anchors, list) and not isinstance(anchors, tuple):
raise TypeError("Attr anchors of yolo_box must be list or tuple")
if not isinstance(class_num, int):
raise TypeError("Attr class_num of yolo_box must be an integer")
if not isinstance(conf_thresh, float):
raise TypeError("Attr ignore_thresh of yolo_box must be a float number")
boxes = helper.create_variable_for_type_inference(dtype=x.dtype)
scores = helper.create_variable_for_type_inference(dtype=x.dtype)
attrs = {
"anchors": anchors,
"class_num": class_num,
"conf_thresh": conf_thresh,
"downsample_ratio": downsample_ratio,
"clip_bbox": clip_bbox,
"scale_x_y": scale_x_y,
}
helper.append_op(
type='yolo_box',
inputs={
"X": x,
"ImgSize": img_size,
},
outputs={
'Boxes': boxes,
'Scores': scores,
},
attrs=attrs)
return boxes, scores
@templatedoc()
def detection_map(detect_res,
label,
class_num,
background_label=0,
overlap_threshold=0.3,
evaluate_difficult=True,
has_state=None,
input_states=None,
out_states=None,
ap_version='integral'):
"""
${comment}
Args:
detect_res: ${detect_res_comment}
label: ${label_comment}
class_num: ${class_num_comment}
background_label: ${background_label_comment}
overlap_threshold: ${overlap_threshold_comment}
evaluate_difficult: ${evaluate_difficult_comment}
has_state: ${has_state_comment}
input_states: (tuple|None) If not None, It contains 3 elements:
(1) pos_count ${pos_count_comment}.
(2) true_pos ${true_pos_comment}.
(3) false_pos ${false_pos_comment}.
out_states: (tuple|None) If not None, it contains 3 elements.
(1) accum_pos_count ${accum_pos_count_comment}.
(2) accum_true_pos ${accum_true_pos_comment}.
(3) accum_false_pos ${accum_false_pos_comment}.
ap_version: ${ap_type_comment}
Returns:
${map_comment}
Examples:
.. code-block:: python
import paddle.fluid as fluid
from fluid.layers import detection
detect_res = fluid.data(
name='detect_res',
shape=[10, 6],
dtype='float32')
label = fluid.data(
name='label',
shape=[10, 6],
dtype='float32')
map_out = detection.detection_map(detect_res, label, 21)
"""
helper = LayerHelper("detection_map", **locals())
def __create_var(type):
return helper.create_variable_for_type_inference(dtype=type)
map_out = __create_var('float32')
accum_pos_count_out = out_states[
0] if out_states is not None else __create_var('int32')
accum_true_pos_out = out_states[
1] if out_states is not None else __create_var('float32')
accum_false_pos_out = out_states[
2] if out_states is not None else __create_var('float32')
pos_count = input_states[0] if input_states is not None else None
true_pos = input_states[1] if input_states is not None else None
false_pos = input_states[2] if input_states is not None else None
helper.append_op(
type="detection_map",
inputs={
'Label': label,
'DetectRes': detect_res,
'HasState': has_state,
'PosCount': pos_count,
'TruePos': true_pos,
'FalsePos': false_pos
},
outputs={
'MAP': map_out,
'AccumPosCount': accum_pos_count_out,
'AccumTruePos': accum_true_pos_out,
'AccumFalsePos': accum_false_pos_out
},
attrs={
'overlap_threshold': overlap_threshold,
'evaluate_difficult': evaluate_difficult,
'ap_type': ap_version,
'class_num': class_num,
})
return map_out
def bipartite_match(dist_matrix,
match_type=None,
dist_threshold=None,
name=None):
"""
:alias_main: paddle.nn.functional.bipartite_match
:alias: paddle.nn.functional.bipartite_match,paddle.nn.functional.vision.bipartite_match
:old_api: paddle.fluid.layers.bipartite_match
This operator implements a greedy bipartite matching algorithm, which is
used to obtain the matching with the maximum distance based on the input
distance matrix. For input 2D matrix, the bipartite matching algorithm can
find the matched column for each row (matched means the largest distance),
also can find the matched row for each column. And this operator only
calculate matched indices from column to row. For each instance,
the number of matched indices is the column number of the input distance
matrix. **The OP only supports CPU**.
There are two outputs, matched indices and distance.
A simple description, this algorithm matched the best (maximum distance)
row entity to the column entity and the matched indices are not duplicated
in each row of ColToRowMatchIndices. If the column entity is not matched
any row entity, set -1 in ColToRowMatchIndices.
NOTE: the input DistMat can be LoDTensor (with LoD) or Tensor.
If LoDTensor with LoD, the height of ColToRowMatchIndices is batch size.
If Tensor, the height of ColToRowMatchIndices is 1.
NOTE: This API is a very low level API. It is used by :code:`ssd_loss`
layer. Please consider to use :code:`ssd_loss` instead.
Args:
dist_matrix(Variable): This input is a 2-D LoDTensor with shape
[K, M]. The data type is float32 or float64. It is pair-wise
distance matrix between the entities represented by each row and
each column. For example, assumed one entity is A with shape [K],
another entity is B with shape [M]. The dist_matrix[i][j] is the
distance between A[i] and B[j]. The bigger the distance is, the
better matching the pairs are. NOTE: This tensor can contain LoD
information to represent a batch of inputs. One instance of this
batch can contain different numbers of entities.
match_type(str, optional): The type of matching method, should be
'bipartite' or 'per_prediction'. None ('bipartite') by default.
dist_threshold(float32, optional): If `match_type` is 'per_prediction',
this threshold is to determine the extra matching bboxes based
on the maximum distance, 0.5 by default.
name(str, optional): For detailed information, please refer
to :ref:`api_guide_Name`. Usually name is no need to set and
None by default.
Returns:
Tuple:
matched_indices(Variable): A 2-D Tensor with shape [N, M]. The data
type is int32. N is the batch size. If match_indices[i][j] is -1, it
means B[j] does not match any entity in i-th instance.
Otherwise, it means B[j] is matched to row
match_indices[i][j] in i-th instance. The row number of
i-th instance is saved in match_indices[i][j].
matched_distance(Variable): A 2-D Tensor with shape [N, M]. The data
type is float32. N is batch size. If match_indices[i][j] is -1,
match_distance[i][j] is also -1.0. Otherwise, assumed
match_distance[i][j] = d, and the row offsets of each instance
are called LoD. Then match_distance[i][j] =
dist_matrix[d+LoD[i]][j].
Examples:
>>> import paddle.fluid as fluid
>>> x = fluid.data(name='x', shape=[None, 4], dtype='float32')
>>> y = fluid.data(name='y', shape=[None, 4], dtype='float32')
>>> iou = fluid.layers.iou_similarity(x=x, y=y)
>>> matched_indices, matched_dist = fluid.layers.bipartite_match(iou)
"""
helper = LayerHelper('bipartite_match', **locals())
match_indices = helper.create_variable_for_type_inference(dtype='int32')
match_distance = helper.create_variable_for_type_inference(
dtype=dist_matrix.dtype)
helper.append_op(
type='bipartite_match',
inputs={'DistMat': dist_matrix},
attrs={
'match_type': match_type,
'dist_threshold': dist_threshold,
},
outputs={
'ColToRowMatchIndices': match_indices,
'ColToRowMatchDist': match_distance
})
return match_indices, match_distance
def target_assign(input,
matched_indices,
negative_indices=None,
mismatch_value=None,
name=None):
"""
:alias_main: paddle.nn.functional.target_assign
:alias: paddle.nn.functional.target_assign,paddle.nn.functional.extension.target_assign
:old_api: paddle.fluid.layers.target_assign
This operator can be, for given the target bounding boxes or labels,
to assign classification and regression targets to each prediction as well as
weights to prediction. The weights is used to specify which prediction would
not contribute to training loss.
For each instance, the output `out` and`out_weight` are assigned based on
`match_indices` and `negative_indices`.
Assumed that the row offset for each instance in `input` is called lod,
this operator assigns classification/regression targets by performing the
following steps:
1. Assigning all outputs based on `match_indices`:
.. code-block:: text
If id = match_indices[i][j] > 0,
out[i][j][0 : K] = X[lod[i] + id][j % P][0 : K]
out_weight[i][j] = 1.
Otherwise,
out[j][j][0 : K] = {mismatch_value, mismatch_value, ...}
out_weight[i][j] = 0.
2. Assigning outputs based on `neg_indices` if `neg_indices` is provided:
Assumed that i-th instance in `neg_indices` is called `neg_indice`,
for i-th instance:
.. code-block:: text
for id in neg_indice:
out[i][id][0 : K] = {mismatch_value, mismatch_value, ...}
out_weight[i][id] = 1.0
Args:
input (Variable): This input is a 3D LoDTensor with shape [M, P, K].
Data type should be int32 or float32.
matched_indices (Variable): The input matched indices
is 2D Tenosr<int32> with shape [N, P], If MatchIndices[i][j] is -1,
the j-th entity of column is not matched to any entity of row in
i-th instance.
negative_indices (Variable, optional): The input negative example indices
are an optional input with shape [Neg, 1] and int32 type, where Neg is
the total number of negative example indices.
mismatch_value (float32, optional): Fill this value to the mismatched
location.
name (string): The default value is None. Normally there is no need for
user to set this property. For more information, please refer
to :ref:`api_guide_Name`.
Returns:
tuple: A tuple(out, out_weight) is returned.
out (Variable): a 3D Tensor with shape [N, P, K] and same data type
with `input`, N and P is the same as they are in `matched_indices`,
K is the same as it in input of X.
out_weight (Variable): the weight for output with the shape of [N, P, 1].
Data type is float32.
Examples:
.. code-block:: python
import paddle.fluid as fluid
x = fluid.data(
name='x',
shape=[4, 20, 4],
dtype='float',
lod_level=1)
matched_id = fluid.data(
name='indices',
shape=[8, 20],
dtype='int32')
trg, trg_weight = fluid.layers.target_assign(
x,
matched_id,
mismatch_value=0)
"""
helper = LayerHelper('target_assign', **locals())
out = helper.create_variable_for_type_inference(dtype=input.dtype)
out_weight = helper.create_variable_for_type_inference(dtype='float32')
helper.append_op(
type='target_assign',
inputs={
'X': input,
'MatchIndices': matched_indices,
'NegIndices': negative_indices
},
outputs={'Out': out,
'OutWeight': out_weight},
attrs={'mismatch_value': mismatch_value})
return out, out_weight
def ssd_loss(location,
confidence,
gt_box,
gt_label,
prior_box,
prior_box_var=None,
background_label=0,
overlap_threshold=0.5,
neg_pos_ratio=3.0,
neg_overlap=0.5,
loc_loss_weight=1.0,
conf_loss_weight=1.0,
match_type='per_prediction',
mining_type='max_negative',
normalize=True,
sample_size=None):
"""
:alias_main: paddle.nn.functional.ssd_loss
:alias: paddle.nn.functional.ssd_loss,paddle.nn.functional.loss.ssd_loss
:old_api: paddle.fluid.layers.ssd_loss
**Multi-box loss layer for object detection algorithm of SSD**
This layer is to compute detection loss for SSD given the location offset
predictions, confidence predictions, prior boxes and ground-truth bounding
boxes and labels, and the type of hard example mining. The returned loss
is a weighted sum of the localization loss (or regression loss) and
confidence loss (or classification loss) by performing the following steps:
1. Find matched bounding box by bipartite matching algorithm.
1.1 Compute IOU similarity between ground-truth boxes and prior boxes.
1.2 Compute matched bounding box by bipartite matching algorithm.
2. Compute confidence for mining hard examples
2.1. Get the target label based on matched indices.
2.2. Compute confidence loss.
3. Apply hard example mining to get the negative example indices and update
the matched indices.
4. Assign classification and regression targets
4.1. Encoded bbox according to the prior boxes.
4.2. Assign regression targets.
4.3. Assign classification targets.
5. Compute the overall objective loss.
5.1 Compute confidence loss.
5.2 Compute localization loss.
5.3 Compute the overall weighted loss.
Args:
location (Variable): The location predictions are a 3D Tensor with
shape [N, Np, 4], N is the batch size, Np is total number of
predictions for each instance. 4 is the number of coordinate values,
the layout is [xmin, ymin, xmax, ymax].The data type is float32 or
float64.
confidence (Variable): The confidence predictions are a 3D Tensor
with shape [N, Np, C], N and Np are the same as they are in
`location`, C is the class number.The data type is float32 or
float64.
gt_box (Variable): The ground-truth bounding boxes (bboxes) are a 2D
LoDTensor with shape [Ng, 4], Ng is the total number of ground-truth
bboxes of mini-batch input.The data type is float32 or float64.
gt_label (Variable): The ground-truth labels are a 2D LoDTensor
with shape [Ng, 1].Ng is the total number of ground-truth bboxes of
mini-batch input, 1 is the number of class. The data type is float32
or float64.
prior_box (Variable): The prior boxes are a 2D Tensor with shape [Np, 4].
Np and 4 are the same as they are in `location`. The data type is
float32 or float64.
prior_box_var (Variable): The variance of prior boxes are a 2D Tensor
with shape [Np, 4]. Np and 4 are the same as they are in `prior_box`
background_label (int): The index of background label, 0 by default.
overlap_threshold (float): If match_type is 'per_prediction', use
'overlap_threshold' to determine the extra matching bboxes when finding \
matched boxes. 0.5 by default.
neg_pos_ratio (float): The ratio of the negative boxes to the positive
boxes, used only when mining_type is 'max_negative', 3.0 by default.
neg_overlap (float): The negative overlap upper bound for the unmatched
predictions. Use only when mining_type is 'max_negative',
0.5 by default.
loc_loss_weight (float): Weight for localization loss, 1.0 by default.
conf_loss_weight (float): Weight for confidence loss, 1.0 by default.
match_type (str): The type of matching method during training, should
be 'bipartite' or 'per_prediction', 'per_prediction' by default.
mining_type (str): The hard example mining type, should be 'hard_example'
or 'max_negative', now only support `max_negative`.
normalize (bool): Whether to normalize the SSD loss by the total number
of output locations, True by default.
sample_size (int): The max sample size of negative box, used only when
mining_type is 'hard_example'.
Returns:
Variable(Tensor): The weighted sum of the localization loss and confidence loss, \
with shape [N * Np, 1], N and Np are the same as they are in
`location`.The data type is float32 or float64.
Raises:
ValueError: If mining_type is 'hard_example', now only support mining \
type of `max_negative`.
Examples:
.. code-block:: python
import paddle.fluid as fluid
pb = fluid.data(
name='prior_box',
shape=[10, 4],
dtype='float32')
pbv = fluid.data(
name='prior_box_var',
shape=[10, 4],
dtype='float32')
loc = fluid.data(name='target_box', shape=[10, 4], dtype='float32')
scores = fluid.data(name='scores', shape=[10, 21], dtype='float32')
gt_box = fluid.data(
name='gt_box', shape=[4], lod_level=1, dtype='float32')
gt_label = fluid.data(
name='gt_label', shape=[1], lod_level=1, dtype='float32')
loss = fluid.layers.ssd_loss(loc, scores, gt_box, gt_label, pb, pbv)
"""
helper = LayerHelper('ssd_loss', **locals())
if mining_type != 'max_negative':
raise ValueError("Only support mining_type == max_negative now.")
num, num_prior, num_class = confidence.shape
conf_shape = nn.shape(confidence)
def __reshape_to_2d(var):
return nn.flatten(x=var, axis=2)
# 1. Find matched bounding box by prior box.
# 1.1 Compute IOU similarity between ground-truth boxes and prior boxes.
iou = iou_similarity(x=gt_box, y=prior_box)
# 1.2 Compute matched bounding box by bipartite matching algorithm.
matched_indices, matched_dist = bipartite_match(iou, match_type,
overlap_threshold)
# 2. Compute confidence for mining hard examples
# 2.1. Get the target label based on matched indices
gt_label = nn.reshape(
x=gt_label, shape=(len(gt_label.shape) - 1) * (0, ) + (-1, 1))
gt_label.stop_gradient = True
target_label, _ = target_assign(
gt_label, matched_indices, mismatch_value=background_label)
# 2.2. Compute confidence loss.
# Reshape confidence to 2D tensor.
confidence = __reshape_to_2d(confidence)
target_label = tensor.cast(x=target_label, dtype='int64')
target_label = __reshape_to_2d(target_label)
target_label.stop_gradient = True
conf_loss = softmax_with_cross_entropy(confidence, target_label)
# 3. Mining hard examples
actual_shape = nn.slice(conf_shape, axes=[0], starts=[0], ends=[2])
actual_shape.stop_gradient = True
# shape=(-1, 0) is set for compile-time, the correct shape is set by
# actual_shape in runtime.
conf_loss = nn.reshape(
x=conf_loss, shape=(-1, 0), actual_shape=actual_shape)
conf_loss.stop_gradient = True
neg_indices = helper.create_variable_for_type_inference(dtype='int32')
dtype = matched_indices.dtype
updated_matched_indices = helper.create_variable_for_type_inference(
dtype=dtype)
helper.append_op(
type='mine_hard_examples',
inputs={
'ClsLoss': conf_loss,
'LocLoss': None,
'MatchIndices': matched_indices,
'MatchDist': matched_dist,
},
outputs={
'NegIndices': neg_indices,
'UpdatedMatchIndices': updated_matched_indices
},
attrs={
'neg_pos_ratio': neg_pos_ratio,
'neg_dist_threshold': neg_overlap,
'mining_type': mining_type,
'sample_size': sample_size,
})
# 4. Assign classification and regression targets
# 4.1. Encoded bbox according to the prior boxes.
encoded_bbox = box_coder(
prior_box=prior_box,
prior_box_var=prior_box_var,
target_box=gt_box,
code_type='encode_center_size')
# 4.2. Assign regression targets
target_bbox, target_loc_weight = target_assign(
encoded_bbox, updated_matched_indices, mismatch_value=background_label)
# 4.3. Assign classification targets
target_label, target_conf_weight = target_assign(
gt_label,
updated_matched_indices,
negative_indices=neg_indices,
mismatch_value=background_label)
# 5. Compute loss.
# 5.1 Compute confidence loss.
target_label = __reshape_to_2d(target_label)
target_label = tensor.cast(x=target_label, dtype='int64')
conf_loss = softmax_with_cross_entropy(confidence, target_label)
target_conf_weight = __reshape_to_2d(target_conf_weight)
conf_loss = conf_loss * target_conf_weight
# the target_label and target_conf_weight do not have gradient.
target_label.stop_gradient = True
target_conf_weight.stop_gradient = True
# 5.2 Compute regression loss.
location = __reshape_to_2d(location)
target_bbox = __reshape_to_2d(target_bbox)
loc_loss = nn.smooth_l1(location, target_bbox)
target_loc_weight = __reshape_to_2d(target_loc_weight)
loc_loss = loc_loss * target_loc_weight
# the target_bbox and target_loc_weight do not have gradient.
target_bbox.stop_gradient = True
target_loc_weight.stop_gradient = True
# 5.3 Compute overall weighted loss.
loss = conf_loss_weight * conf_loss + loc_loss_weight * loc_loss
# reshape to [N, Np], N is the batch size and Np is the prior box number.
# shape=(-1, 0) is set for compile-time, the correct shape is set by
# actual_shape in runtime.
loss = nn.reshape(x=loss, shape=(-1, 0), actual_shape=actual_shape)
loss = nn.reduce_sum(loss, dim=1, keep_dim=True)
if normalize:
normalizer = nn.reduce_sum(target_loc_weight)
loss = loss / normalizer
return loss
def prior_box(input,
image,
min_sizes,
max_sizes=None,
aspect_ratios=[1.],
variance=[0.1, 0.1, 0.2, 0.2],
flip=False,
clip=False,
steps=[0.0, 0.0],
offset=0.5,
name=None,
min_max_aspect_ratios_order=False):
"""
:alias_main: paddle.nn.functional.prior_box
:alias: paddle.nn.functional.prior_box,paddle.nn.functional.vision.prior_box
:old_api: paddle.fluid.layers.prior_box
This op generates prior boxes for SSD(Single Shot MultiBox Detector) algorithm.
Each position of the input produce N prior boxes, N is determined by
the count of min_sizes, max_sizes and aspect_ratios, The size of the
box is in range(min_size, max_size) interval, which is generated in
sequence according to the aspect_ratios.
Parameters:
input(Variable): 4-D tensor(NCHW), the data type should be float32 or float64.
image(Variable): 4-D tensor(NCHW), the input image data of PriorBoxOp,
the data type should be float32 or float64.
min_sizes(list|tuple|float): the min sizes of generated prior boxes.
max_sizes(list|tuple|None): the max sizes of generated prior boxes.
Default: None.
aspect_ratios(list|tuple|float): the aspect ratios of generated
prior boxes. Default: [1.].
variance(list|tuple): the variances to be encoded in prior boxes.
Default:[0.1, 0.1, 0.2, 0.2].
flip(bool): Whether to flip aspect ratios. Default:False.
clip(bool): Whether to clip out-of-boundary boxes. Default: False.
step(list|tuple): Prior boxes step across width and height, If
step[0] equals to 0.0 or step[1] equals to 0.0, the prior boxes step across
height or weight of the input will be automatically calculated.
Default: [0., 0.]
offset(float): Prior boxes center offset. Default: 0.5
min_max_aspect_ratios_order(bool): If set True, the output prior box is
in order of [min, max, aspect_ratios], which is consistent with
Caffe. Please note, this order affects the weights order of
convolution layer followed by and does not affect the final
detection results. Default: False.
name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`
Returns:
Tuple: A tuple with two Variable (boxes, variances)
boxes(Variable): the output prior boxes of PriorBox.
4-D tensor, the layout is [H, W, num_priors, 4].
H is the height of input, W is the width of input,
num_priors is the total box count of each position of input.
variances(Variable): the expanded variances of PriorBox.
4-D tensor, the layput is [H, W, num_priors, 4].
H is the height of input, W is the width of input
num_priors is the total box count of each position of input
Examples:
.. code-block:: python
#declarative mode
import paddle.fluid as fluid
import numpy as np
input = fluid.data(name="input", shape=[None,3,6,9])
image = fluid.data(name="image", shape=[None,3,9,12])
box, var = fluid.layers.prior_box(
input=input,
image=image,
min_sizes=[100.],
clip=True,
flip=True)
place = fluid.CPUPlace()
exe = fluid.Executor(place)
exe.run(fluid.default_startup_program())
# prepare a batch of data
input_data = np.random.rand(1,3,6,9).astype("float32")
image_data = np.random.rand(1,3,9,12).astype("float32")
box_out, var_out = exe.run(fluid.default_main_program(),
feed={"input":input_data,"image":image_data},
fetch_list=[box,var],
return_numpy=True)
# print(box_out.shape)
# (6, 9, 1, 4)
# print(var_out.shape)
# (6, 9, 1, 4)
# imperative mode
import paddle.fluid.dygraph as dg
with dg.guard(place) as g:
input = dg.to_variable(input_data)
image = dg.to_variable(image_data)
box, var = fluid.layers.prior_box(
input=input,
image=image,
min_sizes=[100.],
clip=True,
flip=True)
# print(box.shape)
# [6L, 9L, 1L, 4L]
# print(var.shape)
# [6L, 9L, 1L, 4L]
"""
helper = LayerHelper("prior_box", **locals())
dtype = helper.input_dtype()
check_variable_and_dtype(
input, 'input', ['uint8', 'int8', 'float32', 'float64'], 'prior_box')
def _is_list_or_tuple_(data):
return (isinstance(data, list) or isinstance(data, tuple))
if not _is_list_or_tuple_(min_sizes):
min_sizes = [min_sizes]
if not _is_list_or_tuple_(aspect_ratios):
aspect_ratios = [aspect_ratios]
if not (_is_list_or_tuple_(steps) and len(steps) == 2):
raise ValueError('steps should be a list or tuple ',
'with length 2, (step_width, step_height).')
min_sizes = list(map(float, min_sizes))
aspect_ratios = list(map(float, aspect_ratios))
steps = list(map(float, steps))
attrs = {
'min_sizes': min_sizes,
'aspect_ratios': aspect_ratios,
'variances': variance,
'flip': flip,
'clip': clip,
'step_w': steps[0],
'step_h': steps[1],
'offset': offset,
'min_max_aspect_ratios_order': min_max_aspect_ratios_order
}
if max_sizes is not None and len(max_sizes) > 0 and max_sizes[0] > 0:
if not _is_list_or_tuple_(max_sizes):
max_sizes = [max_sizes]
attrs['max_sizes'] = max_sizes
box = helper.create_variable_for_type_inference(dtype)
var = helper.create_variable_for_type_inference(dtype)
helper.append_op(
type="prior_box",
inputs={"Input": input,
"Image": image},
outputs={"Boxes": box,
"Variances": var},
attrs=attrs, )
box.stop_gradient = True
var.stop_gradient = True
return box, var
def density_prior_box(input,
image,
densities=None,
fixed_sizes=None,
fixed_ratios=None,
variance=[0.1, 0.1, 0.2, 0.2],
clip=False,
steps=[0.0, 0.0],
offset=0.5,
flatten_to_2d=False,
name=None):
"""
:alias_main: paddle.nn.functional.density_prior_box
:alias: paddle.nn.functional.density_prior_box,paddle.nn.functional.vision.density_prior_box
:old_api: paddle.fluid.layers.density_prior_box
This op generates density prior boxes for SSD(Single Shot MultiBox Detector)
algorithm. Each position of the input produce N prior boxes, N is
determined by the count of densities, fixed_sizes and fixed_ratios.
Boxes center at grid points around each input position is generated by
this operator, and the grid points is determined by densities and
the count of density prior box is determined by fixed_sizes and fixed_ratios.
Obviously, the number of fixed_sizes is equal to the number of densities.
For densities_i in densities:
.. math::
N\_density_prior\_box = SUM(N\_fixed\_ratios * densities\_i^2)
N_density_prior_box is the number of density_prior_box and N_fixed_ratios is the number of fixed_ratios.
Parameters:
input(Variable): 4-D tensor(NCHW), the data type should be float32 of float64.
image(Variable): 4-D tensor(NCHW), the input image data of PriorBoxOp, the data type should be float32 or float64.
the layout is NCHW.
densities(list|tuple|None): The densities of generated density prior
boxes, this attribute should be a list or tuple of integers.
Default: None.
fixed_sizes(list|tuple|None): The fixed sizes of generated density
prior boxes, this attribute should a list or tuple of same
length with :attr:`densities`. Default: None.
fixed_ratios(list|tuple|None): The fixed ratios of generated density
prior boxes, if this attribute is not set and :attr:`densities`
and :attr:`fix_sizes` is set, :attr:`aspect_ratios` will be used
to generate density prior boxes.
variance(list|tuple): The variances to be encoded in density prior boxes.
Default:[0.1, 0.1, 0.2, 0.2].
clip(bool): Whether to clip out of boundary boxes. Default: False.
step(list|tuple): Prior boxes step across width and height, If
step[0] equals 0.0 or step[1] equals 0.0, the density prior boxes step across
height or weight of the input will be automatically calculated.
Default: [0., 0.]
offset(float): Prior boxes center offset. Default: 0.5
flatten_to_2d(bool): Whether to flatten output prior boxes and variance
to 2D shape, the second dim is 4. Default: False.
name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`
Returns:
Tuple: A tuple with two Variable (boxes, variances)
boxes: the output density prior boxes of PriorBox.
4-D tensor, the layout is [H, W, num_priors, 4] when flatten_to_2d is False.
2-D tensor, the layout is [H * W * num_priors, 4] when flatten_to_2d is True.
H is the height of input, W is the width of input, and num_priors is the total box count of each position of input.
variances: the expanded variances of PriorBox.
4-D tensor, the layout is [H, W, num_priors, 4] when flatten_to_2d is False.
2-D tensor, the layout is [H * W * num_priors, 4] when flatten_to_2d is True.
H is the height of input, W is the width of input, and num_priors is the total box count of each position of input.
Examples:
.. code-block:: python
#declarative mode
import paddle.fluid as fluid
import numpy as np
input = fluid.data(name="input", shape=[None,3,6,9])
image = fluid.data(name="image", shape=[None,3,9,12])
box, var = fluid.layers.density_prior_box(
input=input,
image=image,
densities=[4, 2, 1],
fixed_sizes=[32.0, 64.0, 128.0],
fixed_ratios=[1.],
clip=True,
flatten_to_2d=True)
place = fluid.CPUPlace()
exe = fluid.Executor(place)
exe.run(fluid.default_startup_program())
# prepare a batch of data
input_data = np.random.rand(1,3,6,9).astype("float32")
image_data = np.random.rand(1,3,9,12).astype("float32")
box_out, var_out = exe.run(
fluid.default_main_program(),
feed={"input":input_data,
"image":image_data},
fetch_list=[box,var],
return_numpy=True)
# print(box_out.shape)
# (1134, 4)
# print(var_out.shape)
# (1134, 4)
#imperative mode
import paddle.fluid.dygraph as dg
with dg.guard(place) as g:
input = dg.to_variable(input_data)
image = dg.to_variable(image_data)
box, var = fluid.layers.density_prior_box(
input=input,
image=image,
densities=[4, 2, 1],
fixed_sizes=[32.0, 64.0, 128.0],
fixed_ratios=[1.],
clip=True)
# print(box.shape)
# [6L, 9L, 21L, 4L]
# print(var.shape)
# [6L, 9L, 21L, 4L]
"""
helper = LayerHelper("density_prior_box", **locals())
dtype = helper.input_dtype()
check_variable_and_dtype(input, 'input', ['float32', 'float64'],
'density_prior_box')
def _is_list_or_tuple_(data):
return (isinstance(data, list) or isinstance(data, tuple))
check_type(densities, 'densities', (list, tuple), 'density_prior_box')
check_type(fixed_sizes, 'fixed_sizes', (list, tuple), 'density_prior_box')
check_type(fixed_ratios, 'fixed_ratios', (list, tuple), 'density_prior_box')
if len(densities) != len(fixed_sizes):
raise ValueError('densities and fixed_sizes length should be euqal.')
if not (_is_list_or_tuple_(steps) and len(steps) == 2):
raise ValueError('steps should be a list or tuple ',
'with length 2, (step_width, step_height).')
densities = list(map(int, densities))
fixed_sizes = list(map(float, fixed_sizes))
fixed_ratios = list(map(float, fixed_ratios))
steps = list(map(float, steps))
attrs = {
'variances': variance,
'clip': clip,
'step_w': steps[0],
'step_h': steps[1],
'offset': offset,
'densities': densities,
'fixed_sizes': fixed_sizes,
'fixed_ratios': fixed_ratios,
'flatten_to_2d': flatten_to_2d,
}
box = helper.create_variable_for_type_inference(dtype)
var = helper.create_variable_for_type_inference(dtype)
helper.append_op(
type="density_prior_box",
inputs={"Input": input,
"Image": image},
outputs={"Boxes": box,
"Variances": var},
attrs=attrs, )
box.stop_gradient = True
var.stop_gradient = True
return box, var
def multi_box_head(inputs,
image,
base_size,
num_classes,
aspect_ratios,
min_ratio=None,
max_ratio=None,
min_sizes=None,
max_sizes=None,
steps=None,
step_w=None,
step_h=None,
offset=0.5,
variance=[0.1, 0.1, 0.2, 0.2],
flip=True,
clip=False,
kernel_size=1,
pad=0,
stride=1,
name=None,
min_max_aspect_ratios_order=False):
"""
:api_attr: Static Graph
Base on SSD ((Single Shot MultiBox Detector) algorithm, generate prior boxes,
regression location and classification confidence on multiple input feature
maps, then output the concatenate results. The details of this algorithm,
please refer the section 2.2 of SSD paper `SSD: Single Shot MultiBox Detector
<https://arxiv.org/abs/1512.02325>`_ .
Args:
inputs (list(Variable)|tuple(Variable)): The list of input variables,
the format of all Variables are 4-D Tensor, layout is NCHW.
Data type should be float32 or float64.
image (Variable): The input image, layout is NCHW. Data type should be
the same as inputs.
base_size(int): the base_size is input image size. When len(inputs) > 2
and `min_size` and `max_size` are None, the `min_size` and `max_size`
are calculated by `baze_size`, 'min_ratio' and `max_ratio`. The
formula is as follows:
.. code-block:: text
min_sizes = []
max_sizes = []
step = int(math.floor(((max_ratio - min_ratio)) / (num_layer - 2)))
for ratio in six.moves.range(min_ratio, max_ratio + 1, step):
min_sizes.append(base_size * ratio / 100.)
max_sizes.append(base_size * (ratio + step) / 100.)
min_sizes = [base_size * .10] + min_sizes
max_sizes = [base_size * .20] + max_sizes
num_classes(int): The number of classes.
aspect_ratios(list(float) | tuple(float)): the aspect ratios of generated
prior boxes. The length of input and aspect_ratios must be equal.
min_ratio(int): the min ratio of generated prior boxes.
max_ratio(int): the max ratio of generated prior boxes.
min_sizes(list|tuple|None): If `len(inputs) <=2`,
min_sizes must be set up, and the length of min_sizes
should equal to the length of inputs. Default: None.
max_sizes(list|tuple|None): If `len(inputs) <=2`,
max_sizes must be set up, and the length of min_sizes
should equal to the length of inputs. Default: None.
steps(list|tuple): If step_w and step_h are the same,
step_w and step_h can be replaced by steps.
step_w(list|tuple): Prior boxes step
across width. If step_w[i] == 0.0, the prior boxes step
across width of the inputs[i] will be automatically
calculated. Default: None.
step_h(list|tuple): Prior boxes step across height, If
step_h[i] == 0.0, the prior boxes step across height of
the inputs[i] will be automatically calculated. Default: None.
offset(float): Prior boxes center offset. Default: 0.5
variance(list|tuple): the variances to be encoded in prior boxes.
Default:[0.1, 0.1, 0.2, 0.2].
flip(bool): Whether to flip aspect ratios. Default:False.
clip(bool): Whether to clip out-of-boundary boxes. Default: False.
kernel_size(int): The kernel size of conv2d. Default: 1.
pad(int|list|tuple): The padding of conv2d. Default:0.
stride(int|list|tuple): The stride of conv2d. Default:1,
name(str): The default value is None. Normally there is no need
for user to set this property. For more information, please
refer to :ref:`api_guide_Name`.
min_max_aspect_ratios_order(bool): If set True, the output prior box is
in order of [min, max, aspect_ratios], which is consistent with
Caffe. Please note, this order affects the weights order of
convolution layer followed by and does not affect the final
detection results. Default: False.
Returns:
tuple: A tuple with four Variables. (mbox_loc, mbox_conf, boxes, variances)
mbox_loc (Variable): The predicted boxes' location of the inputs. The
layout is [N, num_priors, 4], where N is batch size, ``num_priors``
is the number of prior boxes. Data type is the same as input.
mbox_conf (Variable): The predicted boxes' confidence of the inputs.
The layout is [N, num_priors, C], where ``N`` and ``num_priors``
has the same meaning as above. C is the number of Classes.
Data type is the same as input.
boxes (Variable): the output prior boxes. The layout is [num_priors, 4].
The meaning of num_priors is the same as above.
Data type is the same as input.
variances (Variable): the expanded variances for prior boxes.
The layout is [num_priors, 4]. Data type is the same as input.
Examples 1: set min_ratio and max_ratio:
.. code-block:: python
import paddle.fluid as fluid
images = fluid.data(name='data', shape=[None, 3, 300, 300], dtype='float32')
conv1 = fluid.data(name='conv1', shape=[None, 512, 19, 19], dtype='float32')
conv2 = fluid.data(name='conv2', shape=[None, 1024, 10, 10], dtype='float32')
conv3 = fluid.data(name='conv3', shape=[None, 512, 5, 5], dtype='float32')
conv4 = fluid.data(name='conv4', shape=[None, 256, 3, 3], dtype='float32')
conv5 = fluid.data(name='conv5', shape=[None, 256, 2, 2], dtype='float32')
conv6 = fluid.data(name='conv6', shape=[None, 128, 1, 1], dtype='float32')
mbox_locs, mbox_confs, box, var = fluid.layers.multi_box_head(
inputs=[conv1, conv2, conv3, conv4, conv5, conv6],
image=images,
num_classes=21,
min_ratio=20,
max_ratio=90,
aspect_ratios=[[2.], [2., 3.], [2., 3.], [2., 3.], [2.], [2.]],
base_size=300,
offset=0.5,
flip=True,
clip=True)
Examples 2: set min_sizes and max_sizes:
.. code-block:: python
import paddle.fluid as fluid
images = fluid.data(name='data', shape=[None, 3, 300, 300], dtype='float32')
conv1 = fluid.data(name='conv1', shape=[None, 512, 19, 19], dtype='float32')
conv2 = fluid.data(name='conv2', shape=[None, 1024, 10, 10], dtype='float32')
conv3 = fluid.data(name='conv3', shape=[None, 512, 5, 5], dtype='float32')
conv4 = fluid.data(name='conv4', shape=[None, 256, 3, 3], dtype='float32')
conv5 = fluid.data(name='conv5', shape=[None, 256, 2, 2], dtype='float32')
conv6 = fluid.data(name='conv6', shape=[None, 128, 1, 1], dtype='float32')
mbox_locs, mbox_confs, box, var = fluid.layers.multi_box_head(
inputs=[conv1, conv2, conv3, conv4, conv5, conv6],
image=images,
num_classes=21,
min_sizes=[60.0, 105.0, 150.0, 195.0, 240.0, 285.0],
max_sizes=[[], 150.0, 195.0, 240.0, 285.0, 300.0],
aspect_ratios=[[2.], [2., 3.], [2., 3.], [2., 3.], [2.], [2.]],
base_size=300,
offset=0.5,
flip=True,
clip=True)
"""
def _reshape_with_axis_(input, axis=1):
out = nn.flatten(x=input, axis=axis)
return out
def _is_list_or_tuple_(data):
return (isinstance(data, list) or isinstance(data, tuple))
def _is_list_or_tuple_and_equal(data, length, err_info):
if not (_is_list_or_tuple_(data) and len(data) == length):
raise ValueError(err_info)
if not _is_list_or_tuple_(inputs):
raise ValueError('inputs should be a list or tuple.')
num_layer = len(inputs)
if num_layer <= 2:
assert min_sizes is not None and max_sizes is not None
assert len(min_sizes) == num_layer and len(max_sizes) == num_layer
elif min_sizes is None and max_sizes is None:
min_sizes = []
max_sizes = []
step = int(math.floor(((max_ratio - min_ratio)) / (num_layer - 2)))
for ratio in six.moves.range(min_ratio, max_ratio + 1, step):
min_sizes.append(base_size * ratio / 100.)
max_sizes.append(base_size * (ratio + step) / 100.)
min_sizes = [base_size * .10] + min_sizes
max_sizes = [base_size * .20] + max_sizes
if aspect_ratios:
_is_list_or_tuple_and_equal(
aspect_ratios, num_layer,
'aspect_ratios should be list or tuple, and the length of inputs '
'and aspect_ratios should be the same.')
if step_h is not None:
_is_list_or_tuple_and_equal(
step_h, num_layer,
'step_h should be list or tuple, and the length of inputs and '
'step_h should be the same.')
if step_w is not None:
_is_list_or_tuple_and_equal(
step_w, num_layer,
'step_w should be list or tuple, and the length of inputs and '
'step_w should be the same.')
if steps is not None:
_is_list_or_tuple_and_equal(
steps, num_layer,
'steps should be list or tuple, and the length of inputs and '
'step_w should be the same.')
step_w = steps
step_h = steps
mbox_locs = []
mbox_confs = []
box_results = []
var_results = []
for i, input in enumerate(inputs):
min_size = min_sizes[i]
max_size = max_sizes[i]
if not _is_list_or_tuple_(min_size):
min_size = [min_size]
if not _is_list_or_tuple_(max_size):
max_size = [max_size]
aspect_ratio = []
if aspect_ratios is not None:
aspect_ratio = aspect_ratios[i]
if not _is_list_or_tuple_(aspect_ratio):
aspect_ratio = [aspect_ratio]
step = [step_w[i] if step_w else 0.0, step_h[i] if step_w else 0.0]
box, var = prior_box(input, image, min_size, max_size, aspect_ratio,
variance, flip, clip, step, offset, None,
min_max_aspect_ratios_order)
box_results.append(box)
var_results.append(var)
num_boxes = box.shape[2]
# get loc
num_loc_output = num_boxes * 4
mbox_loc = nn.conv2d(
input=input,
num_filters=num_loc_output,
filter_size=kernel_size,
padding=pad,
stride=stride)
mbox_loc = nn.transpose(mbox_loc, perm=[0, 2, 3, 1])
mbox_loc_flatten = nn.flatten(mbox_loc, axis=1)
mbox_locs.append(mbox_loc_flatten)
# get conf
num_conf_output = num_boxes * num_classes
conf_loc = nn.conv2d(
input=input,
num_filters=num_conf_output,
filter_size=kernel_size,
padding=pad,
stride=stride)
conf_loc = nn.transpose(conf_loc, perm=[0, 2, 3, 1])
conf_loc_flatten = nn.flatten(conf_loc, axis=1)
mbox_confs.append(conf_loc_flatten)
if len(box_results) == 1:
box = box_results[0]
var = var_results[0]
mbox_locs_concat = mbox_locs[0]
mbox_confs_concat = mbox_confs[0]
else:
reshaped_boxes = []
reshaped_vars = []
for i in range(len(box_results)):
reshaped_boxes.append(_reshape_with_axis_(box_results[i], axis=3))
reshaped_vars.append(_reshape_with_axis_(var_results[i], axis=3))
box = tensor.concat(reshaped_boxes)
var = tensor.concat(reshaped_vars)
mbox_locs_concat = tensor.concat(mbox_locs, axis=1)
mbox_locs_concat = nn.reshape(mbox_locs_concat, shape=[0, -1, 4])
mbox_confs_concat = tensor.concat(mbox_confs, axis=1)
mbox_confs_concat = nn.reshape(
mbox_confs_concat, shape=[0, -1, num_classes])
box.stop_gradient = True
var.stop_gradient = True
return mbox_locs_concat, mbox_confs_concat, box, var
def anchor_generator(input,
anchor_sizes=None,
aspect_ratios=None,
variance=[0.1, 0.1, 0.2, 0.2],
stride=None,
offset=0.5,
name=None):
"""
:alias_main: paddle.nn.functional.anchor_generator
:alias: paddle.nn.functional.anchor_generator,paddle.nn.functional.vision.anchor_generator
:old_api: paddle.fluid.layers.anchor_generator
**Anchor generator operator**
Generate anchors for Faster RCNN algorithm.
Each position of the input produce N anchors, N =
size(anchor_sizes) * size(aspect_ratios). The order of generated anchors
is firstly aspect_ratios loop then anchor_sizes loop.
Args:
input(Variable): 4-D Tensor with shape [N,C,H,W]. The input feature map.
anchor_sizes(float32|list|tuple, optional): The anchor sizes of generated
anchors, given in absolute pixels e.g. [64., 128., 256., 512.].
For instance, the anchor size of 64 means the area of this anchor
equals to 64**2. None by default.
aspect_ratios(float32|list|tuple, optional): The height / width ratios
of generated anchors, e.g. [0.5, 1.0, 2.0]. None by default.
variance(list|tuple, optional): The variances to be used in box
regression deltas. The data type is float32, [0.1, 0.1, 0.2, 0.2] by
default.
stride(list|tuple, optional): The anchors stride across width and height.
The data type is float32. e.g. [16.0, 16.0]. None by default.
offset(float32, optional): Prior boxes center offset. 0.5 by default.
name(str, optional): For detailed information, please refer
to :ref:`api_guide_Name`. Usually name is no need to set and None
by default.
Returns:
Tuple:
Anchors(Variable): The output anchors with a layout of [H, W, num_anchors, 4].
H is the height of input, W is the width of input,
num_anchors is the box count of each position.
Each anchor is in (xmin, ymin, xmax, ymax) format an unnormalized.
Variances(Variable): The expanded variances of anchors
with a layout of [H, W, num_priors, 4].
H is the height of input, W is the width of input
num_anchors is the box count of each position.
Each variance is in (xcenter, ycenter, w, h) format.
Examples:
.. code-block:: python
import paddle.fluid as fluid
conv1 = fluid.data(name='conv1', shape=[None, 48, 16, 16], dtype='float32')
anchor, var = fluid.layers.anchor_generator(
input=conv1,
anchor_sizes=[64, 128, 256, 512],
aspect_ratios=[0.5, 1.0, 2.0],
variance=[0.1, 0.1, 0.2, 0.2],
stride=[16.0, 16.0],
offset=0.5)
"""
helper = LayerHelper("anchor_generator", **locals())
dtype = helper.input_dtype()
def _is_list_or_tuple_(data):
return (isinstance(data, list) or isinstance(data, tuple))
if not _is_list_or_tuple_(anchor_sizes):
anchor_sizes = [anchor_sizes]
if not _is_list_or_tuple_(aspect_ratios):
aspect_ratios = [aspect_ratios]
if not (_is_list_or_tuple_(stride) and len(stride) == 2):
raise ValueError('stride should be a list or tuple ',
'with length 2, (stride_width, stride_height).')
anchor_sizes = list(map(float, anchor_sizes))
aspect_ratios = list(map(float, aspect_ratios))
stride = list(map(float, stride))
attrs = {
'anchor_sizes': anchor_sizes,
'aspect_ratios': aspect_ratios,
'variances': variance,
'stride': stride,
'offset': offset
}
anchor = helper.create_variable_for_type_inference(dtype)
var = helper.create_variable_for_type_inference(dtype)
helper.append_op(
type="anchor_generator",
inputs={"Input": input},
outputs={"Anchors": anchor,
"Variances": var},
attrs=attrs, )
anchor.stop_gradient = True
var.stop_gradient = True
return anchor, var
def roi_perspective_transform(input,
rois,
transformed_height,
transformed_width,
spatial_scale=1.0,
name=None):
"""
**The** `rois` **of this op should be a LoDTensor.**
ROI perspective transform op applies perspective transform to map each roi into an
rectangular region. Perspective transform is a type of transformation in linear algebra.
Parameters:
input (Variable): 4-D Tensor, input of ROIPerspectiveTransformOp. The format of
input tensor is NCHW. Where N is batch size, C is the
number of input channels, H is the height of the feature,
and W is the width of the feature. The data type is float32.
rois (Variable): 2-D LoDTensor, ROIs (Regions of Interest) to be transformed.
It should be a 2-D LoDTensor of shape (num_rois, 8). Given as
[[x1, y1, x2, y2, x3, y3, x4, y4], ...], (x1, y1) is the
top left coordinates, and (x2, y2) is the top right
coordinates, and (x3, y3) is the bottom right coordinates,
and (x4, y4) is the bottom left coordinates. The data type is the
same as `input`
transformed_height (int): The height of transformed output.
transformed_width (int): The width of transformed output.
spatial_scale (float): Spatial scale factor to scale ROI coords. Default: 1.0
name(str, optional): The default value is None.
Normally there is no need for user to set this property.
For more information, please refer to :ref:`api_guide_Name`
Returns:
A tuple with three Variables. (out, mask, transform_matrix)
out: The output of ROIPerspectiveTransformOp which is a 4-D tensor with shape
(num_rois, channels, transformed_h, transformed_w). The data type is the same as `input`
mask: The mask of ROIPerspectiveTransformOp which is a 4-D tensor with shape
(num_rois, 1, transformed_h, transformed_w). The data type is int32
transform_matrix: The transform matrix of ROIPerspectiveTransformOp which is
a 2-D tensor with shape (num_rois, 9). The data type is the same as `input`
Return Type:
tuple
Examples:
.. code-block:: python
import paddle.fluid as fluid
x = fluid.data(name='x', shape=[100, 256, 28, 28], dtype='float32')
rois = fluid.data(name='rois', shape=[None, 8], lod_level=1, dtype='float32')
out, mask, transform_matrix = fluid.layers.roi_perspective_transform(x, rois, 7, 7, 1.0)
"""
check_variable_and_dtype(input, 'input', ['float32'],
'roi_perspective_transform')
check_variable_and_dtype(rois, 'rois', ['float32'],
'roi_perspective_transform')
check_type(transformed_height, 'transformed_height', int,
'roi_perspective_transform')
check_type(transformed_width, 'transformed_width', int,
'roi_perspective_transform')
check_type(spatial_scale, 'spatial_scale', float,
'roi_perspective_transform')
helper = LayerHelper('roi_perspective_transform', **locals())
dtype = helper.input_dtype()
out = helper.create_variable_for_type_inference(dtype)
mask = helper.create_variable_for_type_inference(dtype="int32")
transform_matrix = helper.create_variable_for_type_inference(dtype)
out2in_idx = helper.create_variable_for_type_inference(dtype="int32")
out2in_w = helper.create_variable_for_type_inference(dtype)
helper.append_op(
type="roi_perspective_transform",
inputs={"X": input,
"ROIs": rois},
outputs={
"Out": out,
"Out2InIdx": out2in_idx,
"Out2InWeights": out2in_w,
"Mask": mask,
"TransformMatrix": transform_matrix
},
attrs={
"transformed_height": transformed_height,
"transformed_width": transformed_width,
"spatial_scale": spatial_scale
})
return out, mask, transform_matrix
def generate_proposal_labels(rpn_rois,
gt_classes,
is_crowd,
gt_boxes,
im_info,
batch_size_per_im=256,
fg_fraction=0.25,
fg_thresh=0.25,
bg_thresh_hi=0.5,
bg_thresh_lo=0.0,
bbox_reg_weights=[0.1, 0.1, 0.2, 0.2],
class_nums=None,
use_random=True,
is_cls_agnostic=False,
is_cascade_rcnn=False):
"""
:alias_main: paddle.nn.functional.generate_proposal_labels
:alias: paddle.nn.functional.generate_proposal_labels,paddle.nn.functional.vision.generate_proposal_labels
:old_api: paddle.fluid.layers.generate_proposal_labels
**Generate Proposal Labels of Faster-RCNN**
This operator can be, for given the GenerateProposalOp output bounding boxes and groundtruth,
to sample foreground boxes and background boxes, and compute loss target.
RpnRois is the output boxes of RPN and was processed by generate_proposal_op, these boxes
were combined with groundtruth boxes and sampled according to batch_size_per_im and fg_fraction,
If an instance with a groundtruth overlap greater than fg_thresh, then it was considered as a foreground sample.
If an instance with a groundtruth overlap greater than bg_thresh_lo and lower than bg_thresh_hi,
then it was considered as a background sample.
After all foreground and background boxes are chosen (so called Rois),
then we apply random sampling to make sure
the number of foreground boxes is no more than batch_size_per_im * fg_fraction.
For each box in Rois, we assign the classification (class label) and regression targets (box label) to it.
Finally BboxInsideWeights and BboxOutsideWeights are used to specify whether it would contribute to training loss.
Args:
rpn_rois(Variable): A 2-D LoDTensor with shape [N, 4]. N is the number of the GenerateProposalOp's output, each element is a bounding box with [xmin, ymin, xmax, ymax] format. The data type can be float32 or float64.
gt_classes(Variable): A 2-D LoDTensor with shape [M, 1]. M is the number of groundtruth, each element is a class label of groundtruth. The data type must be int32.
is_crowd(Variable): A 2-D LoDTensor with shape [M, 1]. M is the number of groundtruth, each element is a flag indicates whether a groundtruth is crowd. The data type must be int32.
gt_boxes(Variable): A 2-D LoDTensor with shape [M, 4]. M is the number of groundtruth, each element is a bounding box with [xmin, ymin, xmax, ymax] format.
im_info(Variable): A 2-D LoDTensor with shape [B, 3]. B is the number of input images, each element consists of im_height, im_width, im_scale.
batch_size_per_im(int): Batch size of rois per images. The data type must be int32.
fg_fraction(float): Foreground fraction in total batch_size_per_im. The data type must be float32.
fg_thresh(float): Overlap threshold which is used to chose foreground sample. The data type must be float32.
bg_thresh_hi(float): Overlap threshold upper bound which is used to chose background sample. The data type must be float32.
bg_thresh_lo(float): Overlap threshold lower bound which is used to chose background sample. The data type must be float32.
bbox_reg_weights(list|tuple): Box regression weights. The data type must be float32.
class_nums(int): Class number. The data type must be int32.
use_random(bool): Use random sampling to choose foreground and background boxes.
is_cls_agnostic(bool): bbox regression use class agnostic simply which only represent fg and bg boxes.
is_cascade_rcnn(bool): it will filter some bbox crossing the image's boundary when setting True.
Returns:
tuple:
A tuple with format``(rois, labels_int32, bbox_targets, bbox_inside_weights, bbox_outside_weights)``.
- **rois**: 2-D LoDTensor with shape ``[batch_size_per_im * batch_size, 4]``. The data type is the same as ``rpn_rois``.
- **labels_int32**: 2-D LoDTensor with shape ``[batch_size_per_im * batch_size, 1]``. The data type must be int32.
- **bbox_targets**: 2-D LoDTensor with shape ``[batch_size_per_im * batch_size, 4 * class_num]``. The regression targets of all RoIs. The data type is the same as ``rpn_rois``.
- **bbox_inside_weights**: 2-D LoDTensor with shape ``[batch_size_per_im * batch_size, 4 * class_num]``. The weights of foreground boxes' regression loss. The data type is the same as ``rpn_rois``.
- **bbox_outside_weights**: 2-D LoDTensor with shape ``[batch_size_per_im * batch_size, 4 * class_num]``. The weights of regression loss. The data type is the same as ``rpn_rois``.
Examples:
.. code-block:: python
import paddle.fluid as fluid
rpn_rois = fluid.data(name='rpn_rois', shape=[None, 4], dtype='float32')
gt_classes = fluid.data(name='gt_classes', shape=[None, 1], dtype='float32')
is_crowd = fluid.data(name='is_crowd', shape=[None, 1], dtype='float32')
gt_boxes = fluid.data(name='gt_boxes', shape=[None, 4], dtype='float32')
im_info = fluid.data(name='im_info', shape=[None, 3], dtype='float32')
rois, labels, bbox, inside_weights, outside_weights = fluid.layers.generate_proposal_labels(
rpn_rois, gt_classes, is_crowd, gt_boxes, im_info,
class_nums=10)
"""
helper = LayerHelper('generate_proposal_labels', **locals())
check_variable_and_dtype(rpn_rois, 'rpn_rois', ['float32', 'float64'],
'generate_proposal_labels')
check_variable_and_dtype(gt_classes, 'gt_classes', ['int32'],
'generate_proposal_labels')
check_variable_and_dtype(is_crowd, 'is_crowd', ['int32'],
'generate_proposal_labels')
rois = helper.create_variable_for_type_inference(dtype=rpn_rois.dtype)
labels_int32 = helper.create_variable_for_type_inference(
dtype=gt_classes.dtype)
bbox_targets = helper.create_variable_for_type_inference(
dtype=rpn_rois.dtype)
bbox_inside_weights = helper.create_variable_for_type_inference(
dtype=rpn_rois.dtype)
bbox_outside_weights = helper.create_variable_for_type_inference(
dtype=rpn_rois.dtype)
helper.append_op(
type="generate_proposal_labels",
inputs={
'RpnRois': rpn_rois,
'GtClasses': gt_classes,
'IsCrowd': is_crowd,
'GtBoxes': gt_boxes,
'ImInfo': im_info
},
outputs={
'Rois': rois,
'LabelsInt32': labels_int32,
'BboxTargets': bbox_targets,
'BboxInsideWeights': bbox_inside_weights,
'BboxOutsideWeights': bbox_outside_weights
},
attrs={
'batch_size_per_im': batch_size_per_im,
'fg_fraction': fg_fraction,
'fg_thresh': fg_thresh,
'bg_thresh_hi': bg_thresh_hi,
'bg_thresh_lo': bg_thresh_lo,
'bbox_reg_weights': bbox_reg_weights,
'class_nums': class_nums,
'use_random': use_random,
'is_cls_agnostic': is_cls_agnostic,
'is_cascade_rcnn': is_cascade_rcnn
})
rois.stop_gradient = True
labels_int32.stop_gradient = True
bbox_targets.stop_gradient = True
bbox_inside_weights.stop_gradient = True
bbox_outside_weights.stop_gradient = True
return rois, labels_int32, bbox_targets, bbox_inside_weights, bbox_outside_weights
def generate_mask_labels(im_info, gt_classes, is_crowd, gt_segms, rois,
labels_int32, num_classes, resolution):
"""
:alias_main: paddle.nn.functional.generate_mask_labels
:alias: paddle.nn.functional.generate_mask_labels,paddle.nn.functional.vision.generate_mask_labels
:old_api: paddle.fluid.layers.generate_mask_labels
**Generate Mask Labels for Mask-RCNN**
This operator can be, for given the RoIs and corresponding labels,
to sample foreground RoIs. This mask branch also has
a :math: `K \\times M^{2}` dimensional output targets for each foreground
RoI, which encodes K binary masks of resolution M x M, one for each of the
K classes. This mask targets are used to compute loss of mask branch.
Please note, the data format of groud-truth segmentation, assumed the
segmentations are as follows. The first instance has two gt objects.
The second instance has one gt object, this object has two gt segmentations.
.. code-block:: python
#[
# [[[229.14, 370.9, 229.14, 370.9, ...]],
# [[343.7, 139.85, 349.01, 138.46, ...]]], # 0-th instance
# [[[500.0, 390.62, ...],[115.48, 187.86, ...]]] # 1-th instance
#]
batch_masks = []
for semgs in batch_semgs:
gt_masks = []
for semg in semgs:
gt_segm = []
for polys in semg:
gt_segm.append(np.array(polys).reshape(-1, 2))
gt_masks.append(gt_segm)
batch_masks.append(gt_masks)
place = fluid.CPUPlace()
feeder = fluid.DataFeeder(place=place, feed_list=feeds)
feeder.feed(batch_masks)
Args:
im_info (Variable): A 2-D Tensor with shape [N, 3] and float32
data type. N is the batch size, each element is
[height, width, scale] of image. Image scale is
target_size / original_size, target_size is the size after resize,
original_size is the original image size.
gt_classes (Variable): A 2-D LoDTensor with shape [M, 1]. Data type
should be int. M is the total number of ground-truth, each
element is a class label.
is_crowd (Variable): A 2-D LoDTensor with same shape and same data type
as gt_classes, each element is a flag indicating whether a
groundtruth is crowd.
gt_segms (Variable): This input is a 2D LoDTensor with shape [S, 2] and
float32 data type, it's LoD level is 3.
Usually users do not needs to understand LoD,
The users should return correct data format in reader.
The LoD[0] represents the ground-truth objects number of
each instance. LoD[1] represents the segmentation counts of each
objects. LoD[2] represents the polygons number of each segmentation.
S the total number of polygons coordinate points. Each element is
(x, y) coordinate points.
rois (Variable): A 2-D LoDTensor with shape [R, 4] and float32 data type
float32. R is the total number of RoIs, each element is a bounding
box with (xmin, ymin, xmax, ymax) format in the range of original image.
labels_int32 (Variable): A 2-D LoDTensor in shape of [R, 1] with type
of int32. R is the same as it in `rois`. Each element represents
a class label of a RoI.
num_classes (int): Class number.
resolution (int): Resolution of mask predictions.
Returns:
mask_rois (Variable): A 2D LoDTensor with shape [P, 4] and same data
type as `rois`. P is the total number of sampled RoIs. Each element
is a bounding box with [xmin, ymin, xmax, ymax] format in range of
original image size.
mask_rois_has_mask_int32 (Variable): A 2D LoDTensor with shape [P, 1]
and int data type, each element represents the output mask RoI
index with regard to input RoIs.
mask_int32 (Variable): A 2D LoDTensor with shape [P, K * M * M] and int
data type, K is the classes number and M is the resolution of mask
predictions. Each element represents the binary mask targets.
Examples:
.. code-block:: python
import paddle.fluid as fluid
im_info = fluid.data(name="im_info", shape=[None, 3],
dtype="float32")
gt_classes = fluid.data(name="gt_classes", shape=[None, 1],
dtype="float32", lod_level=1)
is_crowd = fluid.data(name="is_crowd", shape=[None, 1],
dtype="float32", lod_level=1)
gt_masks = fluid.data(name="gt_masks", shape=[None, 2],
dtype="float32", lod_level=3)
# rois, roi_labels can be the output of
# fluid.layers.generate_proposal_labels.
rois = fluid.data(name="rois", shape=[None, 4],
dtype="float32", lod_level=1)
roi_labels = fluid.data(name="roi_labels", shape=[None, 1],
dtype="int32", lod_level=1)
mask_rois, mask_index, mask_int32 = fluid.layers.generate_mask_labels(
im_info=im_info,
gt_classes=gt_classes,
is_crowd=is_crowd,
gt_segms=gt_masks,
rois=rois,
labels_int32=roi_labels,
num_classes=81,
resolution=14)
"""
helper = LayerHelper('generate_mask_labels', **locals())
mask_rois = helper.create_variable_for_type_inference(dtype=rois.dtype)
roi_has_mask_int32 = helper.create_variable_for_type_inference(
dtype=gt_classes.dtype)
mask_int32 = helper.create_variable_for_type_inference(
dtype=gt_classes.dtype)
helper.append_op(
type="generate_mask_labels",
inputs={
'ImInfo': im_info,
'GtClasses': gt_classes,
'IsCrowd': is_crowd,
'GtSegms': gt_segms,
'Rois': rois,
'LabelsInt32': labels_int32
},
outputs={
'MaskRois': mask_rois,
'RoiHasMaskInt32': roi_has_mask_int32,
'MaskInt32': mask_int32
},
attrs={'num_classes': num_classes,
'resolution': resolution})
mask_rois.stop_gradient = True
roi_has_mask_int32.stop_gradient = True
mask_int32.stop_gradient = True
return mask_rois, roi_has_mask_int32, mask_int32
def generate_proposals(scores,
bbox_deltas,
im_info,
anchors,
variances,
pre_nms_top_n=6000,
post_nms_top_n=1000,
nms_thresh=0.5,
min_size=0.1,
eta=1.0,
name=None,
return_rois_num=False):
"""
:alias_main: paddle.nn.functional.generate_proposals
:alias: paddle.nn.functional.generate_proposals,paddle.nn.functional.vision.generate_proposals
:old_api: paddle.fluid.layers.generate_proposals
**Generate proposal Faster-RCNN**
This operation proposes RoIs according to each box with their
probability to be a foreground object and
the box can be calculated by anchors. Bbox_deltais and scores
to be an object are the output of RPN. Final proposals
could be used to train detection net.
For generating proposals, this operation performs following steps:
1. Transposes and resizes scores and bbox_deltas in size of
(H*W*A, 1) and (H*W*A, 4)
2. Calculate box locations as proposals candidates.
3. Clip boxes to image
4. Remove predicted boxes with small area.
5. Apply NMS to get final proposals as output.
Args:
scores(Variable): A 4-D Tensor with shape [N, A, H, W] represents
the probability for each box to be an object.
N is batch size, A is number of anchors, H and W are height and
width of the feature map. The data type must be float32.
bbox_deltas(Variable): A 4-D Tensor with shape [N, 4*A, H, W]
represents the difference between predicted box location and
anchor location. The data type must be float32.
im_info(Variable): A 2-D Tensor with shape [N, 3] represents origin
image information for N batch. Height and width are the input sizes
and scale is the ratio of network input size and original size.
The data type can be float32 or float64.
anchors(Variable): A 4-D Tensor represents the anchors with a layout
of [H, W, A, 4]. H and W are height and width of the feature map,
num_anchors is the box count of each position. Each anchor is
in (xmin, ymin, xmax, ymax) format an unnormalized. The data type must be float32.
variances(Variable): A 4-D Tensor. The expanded variances of anchors with a layout of
[H, W, num_priors, 4]. Each variance is in
(xcenter, ycenter, w, h) format. The data type must be float32.
pre_nms_top_n(float): Number of total bboxes to be kept per
image before NMS. The data type must be float32. `6000` by default.
post_nms_top_n(float): Number of total bboxes to be kept per
image after NMS. The data type must be float32. `1000` by default.
nms_thresh(float): Threshold in NMS. The data type must be float32. `0.5` by default.
min_size(float): Remove predicted boxes with either height or
width < min_size. The data type must be float32. `0.1` by default.
eta(float): Apply in adaptive NMS, if adaptive `threshold > 0.5`,
`adaptive_threshold = adaptive_threshold * eta` in each iteration.
return_rois_num(bool): When setting True, it will return a 1D Tensor with shape [N, ] that includes Rois's
num of each image in one batch. The N is the image's num. For example, the tensor has values [4,5] that represents
the first image has 4 Rois, the second image has 5 Rois. It only used in rcnn model.
'False' by default.
Returns:
tuple:
A tuple with format ``(rpn_rois, rpn_roi_probs)``.
- **rpn_rois**: The generated RoIs. 2-D Tensor with shape ``[N, 4]`` while ``N`` is the number of RoIs. The data type is the same as ``scores``.
- **rpn_roi_probs**: The scores of generated RoIs. 2-D Tensor with shape ``[N, 1]`` while ``N`` is the number of RoIs. The data type is the same as ``scores``.
Examples:
.. code-block:: python
import paddle.fluid as fluid
scores = fluid.data(name='scores', shape=[None, 4, 5, 5], dtype='float32')
bbox_deltas = fluid.data(name='bbox_deltas', shape=[None, 16, 5, 5], dtype='float32')
im_info = fluid.data(name='im_info', shape=[None, 3], dtype='float32')
anchors = fluid.data(name='anchors', shape=[None, 5, 4, 4], dtype='float32')
variances = fluid.data(name='variances', shape=[None, 5, 10, 4], dtype='float32')
rois, roi_probs = fluid.layers.generate_proposals(scores, bbox_deltas,
im_info, anchors, variances)
"""
helper = LayerHelper('generate_proposals', **locals())
check_variable_and_dtype(scores, 'scores', ['float32'],
'generate_proposals')
check_variable_and_dtype(bbox_deltas, 'bbox_deltas', ['float32'],
'generate_proposals')
check_variable_and_dtype(im_info, 'im_info', ['float32', 'float64'],
'generate_proposals')
check_variable_and_dtype(anchors, 'anchors', ['float32'],
'generate_proposals')
check_variable_and_dtype(variances, 'variances', ['float32'],
'generate_proposals')
rpn_rois = helper.create_variable_for_type_inference(
dtype=bbox_deltas.dtype)
rpn_roi_probs = helper.create_variable_for_type_inference(
dtype=scores.dtype)
rpn_rois_lod = helper.create_variable_for_type_inference(dtype='int32')
helper.append_op(
type="generate_proposals",
inputs={
'Scores': scores,
'BboxDeltas': bbox_deltas,
'ImInfo': im_info,
'Anchors': anchors,
'Variances': variances
},
attrs={
'pre_nms_topN': pre_nms_top_n,
'post_nms_topN': post_nms_top_n,
'nms_thresh': nms_thresh,
'min_size': min_size,
'eta': eta
},
outputs={
'RpnRois': rpn_rois,
'RpnRoiProbs': rpn_roi_probs,
'RpnRoisLod': rpn_rois_lod
})
rpn_rois.stop_gradient = True
rpn_roi_probs.stop_gradient = True
rpn_rois_lod.stop_gradient = True
if return_rois_num:
return rpn_rois, rpn_roi_probs, rpn_rois_lod
else:
return rpn_rois, rpn_roi_probs
def box_clip(input, im_info, name=None):
"""
:alias_main: paddle.nn.functional.box_clip
:alias: paddle.nn.functional.box_clip,paddle.nn.functional.vision.box_clip
:old_api: paddle.fluid.layers.box_clip
Clip the box into the size given by im_info
For each input box, The formula is given as follows:
.. code-block:: text
xmin = max(min(xmin, im_w - 1), 0)
ymin = max(min(ymin, im_h - 1), 0)
xmax = max(min(xmax, im_w - 1), 0)
ymax = max(min(ymax, im_h - 1), 0)
where im_w and im_h are computed from im_info:
.. code-block:: text
im_h = round(height / scale)
im_w = round(weight / scale)
Args:
input(Variable): The input Tensor with shape :math:`[N_1, N_2, ..., N_k, 4]`,
the last dimension is 4 and data type is float32 or float64.
im_info(Variable): The 2-D Tensor with shape [N, 3] with layout
(height, width, scale) representing the information of image.
Height and width are the input sizes and scale is the ratio of network input
size and original size. The data type is float32 or float64.
name(str, optional): For detailed information, please refer
to :ref:`api_guide_Name`. Usually name is no need to set and
None by default.
Returns:
Variable:
output(Variable): The clipped tensor with data type float32 or float64.
The shape is same as input.
Examples:
.. code-block:: python
import paddle.fluid as fluid
boxes = fluid.data(
name='boxes', shape=[None, 8, 4], dtype='float32', lod_level=1)
im_info = fluid.data(name='im_info', shape=[-1 ,3])
out = fluid.layers.box_clip(
input=boxes, im_info=im_info)
"""
check_variable_and_dtype(input, 'input', ['float32', 'float64'], 'box_clip')
check_variable_and_dtype(im_info, 'im_info', ['float32', 'float64'],
'box_clip')
helper = LayerHelper("box_clip", **locals())
output = helper.create_variable_for_type_inference(dtype=input.dtype)
inputs = {"Input": input, "ImInfo": im_info}
helper.append_op(type="box_clip", inputs=inputs, outputs={"Output": output})
return output
def retinanet_detection_output(bboxes,
scores,
anchors,
im_info,
score_threshold=0.05,
nms_top_k=1000,
keep_top_k=100,
nms_threshold=0.3,
nms_eta=1.0):
"""
**Detection Output Layer for the detector RetinaNet.**
In the detector `RetinaNet <https://arxiv.org/abs/1708.02002>`_ , many
`FPN <https://arxiv.org/abs/1612.03144>`_ levels output the category
and location predictions, this OP is to get the detection results by
performing following steps:
1. For each FPN level, decode box predictions according to the anchor
boxes from at most :attr:`nms_top_k` top-scoring predictions after
thresholding detector confidence at :attr:`score_threshold`.
2. Merge top predictions from all levels and apply multi-class non
maximum suppression (NMS) on them to get the final detections.
Args:
bboxes(List): A list of Tensors from multiple FPN levels represents
the location prediction for all anchor boxes. Each element is
a 3-D Tensor with shape :math:`[N, Mi, 4]`, :math:`N` is the
batch size, :math:`Mi` is the number of bounding boxes from
:math:`i`-th FPN level and each bounding box has four coordinate
values and the layout is [xmin, ymin, xmax, ymax]. The data type
of each element is float32 or float64.
scores(List): A list of Tensors from multiple FPN levels represents
the category prediction for all anchor boxes. Each element is a
3-D Tensor with shape :math:`[N, Mi, C]`, :math:`N` is the batch
size, :math:`C` is the class number (**excluding background**),
:math:`Mi` is the number of bounding boxes from :math:`i`-th FPN
level. The data type of each element is float32 or float64.
anchors(List): A list of Tensors from multiple FPN levels represents
the locations of all anchor boxes. Each element is a 2-D Tensor
with shape :math:`[Mi, 4]`, :math:`Mi` is the number of bounding
boxes from :math:`i`-th FPN level, and each bounding box has four
coordinate values and the layout is [xmin, ymin, xmax, ymax].
The data type of each element is float32 or float64.
im_info(Variable): A 2-D Tensor with shape :math:`[N, 3]` represents the size
information of input images. :math:`N` is the batch size, the size
information of each image is a 3-vector which are the height and width
of the network input along with the factor scaling the origin image to
the network input. The data type of :attr:`im_info` is float32.
score_threshold(float): Threshold to filter out bounding boxes
with a confidence score before NMS, default value is set to 0.05.
nms_top_k(int): Maximum number of detections per FPN layer to be
kept according to the confidences before NMS, default value is set to
1000.
keep_top_k(int): Number of total bounding boxes to be kept per image after
NMS step. Default value is set to 100, -1 means keeping all bounding
boxes after NMS step.
nms_threshold(float): The Intersection-over-Union(IoU) threshold used to
filter out boxes in NMS.
nms_eta(float): The parameter for adjusting :attr:`nms_threshold` in NMS.
Default value is set to 1., which represents the value of
:attr:`nms_threshold` keep the same in NMS. If :attr:`nms_eta` is set
to be lower than 1. and the value of :attr:`nms_threshold` is set to
be higher than 0.5, everytime a bounding box is filtered out,
the adjustment for :attr:`nms_threshold` like :attr:`nms_threshold`
= :attr:`nms_threshold` * :attr:`nms_eta` will not be stopped until
the actual value of :attr:`nms_threshold` is lower than or equal to
0.5.
**Notice**: In some cases where the image sizes are very small, it's possible
that there is no detection if :attr:`score_threshold` are used at all
levels. Hence, this OP do not filter out anchors from the highest FPN level
before NMS. And the last element in :attr:`bboxes`:, :attr:`scores` and
:attr:`anchors` is required to be from the highest FPN level.
Returns:
Variable(The data type is float32 or float64):
The detection output is a 1-level LoDTensor with shape :math:`[No, 6]`.
Each row has six values: [label, confidence, xmin, ymin, xmax, ymax].
:math:`No` is the total number of detections in this mini-batch.
The :math:`i`-th image has `LoD[i + 1] - LoD[i]` detected
results, if `LoD[i + 1] - LoD[i]` is 0, the :math:`i`-th image
has no detected results. If all images have no detected results,
LoD will be set to 0, and the output tensor is empty (None).
Examples:
.. code-block:: python
import paddle.fluid as fluid
bboxes_low = fluid.data(
name='bboxes_low', shape=[1, 44, 4], dtype='float32')
bboxes_high = fluid.data(
name='bboxes_high', shape=[1, 11, 4], dtype='float32')
scores_low = fluid.data(
name='scores_low', shape=[1, 44, 10], dtype='float32')
scores_high = fluid.data(
name='scores_high', shape=[1, 11, 10], dtype='float32')
anchors_low = fluid.data(
name='anchors_low', shape=[44, 4], dtype='float32')
anchors_high = fluid.data(
name='anchors_high', shape=[11, 4], dtype='float32')
im_info = fluid.data(
name="im_info", shape=[1, 3], dtype='float32')
nmsed_outs = fluid.layers.retinanet_detection_output(
bboxes=[bboxes_low, bboxes_high],
scores=[scores_low, scores_high],
anchors=[anchors_low, anchors_high],
im_info=im_info,
score_threshold=0.05,
nms_top_k=1000,
keep_top_k=100,
nms_threshold=0.45,
nms_eta=1.0)
"""
check_type(bboxes, 'bboxes', (list), 'retinanet_detection_output')
for i, bbox in enumerate(bboxes):
check_variable_and_dtype(bbox, 'bbox{}'.format(i),
['float32', 'float64'],
'retinanet_detection_output')
check_type(scores, 'scores', (list), 'retinanet_detection_output')
for i, score in enumerate(scores):
check_variable_and_dtype(score, 'score{}'.format(i),
['float32', 'float64'],
'retinanet_detection_output')
check_type(anchors, 'anchors', (list), 'retinanet_detection_output')
for i, anchor in enumerate(anchors):
check_variable_and_dtype(anchor, 'anchor{}'.format(i),
['float32', 'float64'],
'retinanet_detection_output')
check_variable_and_dtype(im_info, 'im_info', ['float32', 'float64'],
'retinanet_detection_output')
helper = LayerHelper('retinanet_detection_output', **locals())
output = helper.create_variable_for_type_inference(
dtype=helper.input_dtype('scores'))
helper.append_op(
type="retinanet_detection_output",
inputs={
'BBoxes': bboxes,
'Scores': scores,
'Anchors': anchors,
'ImInfo': im_info
},
attrs={
'score_threshold': score_threshold,
'nms_top_k': nms_top_k,
'nms_threshold': nms_threshold,
'keep_top_k': keep_top_k,
'nms_eta': 1.,
},
outputs={'Out': output})
output.stop_gradient = True
return output
def multiclass_nms(bboxes,
scores,
score_threshold,
nms_top_k,
keep_top_k,
nms_threshold=0.3,
normalized=True,
nms_eta=1.,
background_label=0,
name=None):
"""
:alias_main: paddle.nn.functional.multiclass_nms
:alias: paddle.nn.functional.multiclass_nms,paddle.nn.functional.extension.multiclass_nms
:old_api: paddle.fluid.layers.multiclass_nms
**Multiclass NMS**
This operator is to do multi-class non maximum suppression (NMS) on
boxes and scores.
In the NMS step, this operator greedily selects a subset of detection bounding
boxes that have high scores larger than score_threshold, if providing this
threshold, then selects the largest nms_top_k confidences scores if nms_top_k
is larger than -1. Then this operator pruns away boxes that have high IOU
(intersection over union) overlap with already selected boxes by adaptive
threshold NMS based on parameters of nms_threshold and nms_eta.
Aftern NMS step, at most keep_top_k number of total bboxes are to be kept
per image if keep_top_k is larger than -1.
See below for an example:
.. code-block:: text
if:
box1.data = (2.0, 3.0, 7.0, 5.0) format is (xmin, ymin, xmax, ymax)
box1.scores = (0.7, 0.2, 0.4) which is (label0.score=0.7, label1.score=0.2, label2.cores=0.4)
box2.data = (3.0, 4.0, 8.0, 5.0)
box2.score = (0.3, 0.3, 0.1)
nms_threshold = 0.3
background_label = 0
score_threshold = 0
Then:
iou = 4/11 > 0.3
out.data = [[1, 0.3, 3.0, 4.0, 8.0, 5.0],
[2, 0.4, 2.0, 3.0, 7.0, 5.0]]
Out format is (label, confidence, xmin, ymin, xmax, ymax)
Args:
bboxes (Variable): Two types of bboxes are supported:
1. (Tensor) A 3-D Tensor with shape
[N, M, 4 or 8 16 24 32] represents the
predicted locations of M bounding bboxes,
N is the batch size. Each bounding box has four
coordinate values and the layout is
[xmin, ymin, xmax, ymax], when box size equals to 4.
The data type is float32 or float64.
2. (LoDTensor) A 3-D Tensor with shape [M, C, 4]
M is the number of bounding boxes, C is the
class number. The data type is float32 or float64.
scores (Variable): Two types of scores are supported:
1. (Tensor) A 3-D Tensor with shape [N, C, M]
represents the predicted confidence predictions.
N is the batch size, C is the class number, M is
number of bounding boxes. For each category there
are total M scores which corresponding M bounding
boxes. Please note, M is equal to the 2nd dimension
of BBoxes.The data type is float32 or float64.
2. (LoDTensor) A 2-D LoDTensor with shape [M, C].
M is the number of bbox, C is the class number.
In this case, input BBoxes should be the second
case with shape [M, C, 4].The data type is float32 or float64.
background_label (int): The index of background label, the background
label will be ignored. If set to -1, then all
categories will be considered. Default: 0
score_threshold (float): Threshold to filter out bounding boxes with
low confidence score. If not provided,
consider all boxes.
nms_top_k (int): Maximum number of detections to be kept according to
the confidences after the filtering detections based
on score_threshold.
nms_threshold (float): The threshold to be used in NMS. Default: 0.3
nms_eta (float): The threshold to be used in NMS. Default: 1.0
keep_top_k (int): Number of total bboxes to be kept per image after NMS
step. -1 means keeping all bboxes after NMS step.
normalized (bool): Whether detections are normalized. Default: True
name(str): Name of the multiclass nms op. Default: None.
Returns:
Variable: A 2-D LoDTensor with shape [No, 6] represents the detections.
Each row has 6 values: [label, confidence, xmin, ymin, xmax, ymax]
or A 2-D LoDTensor with shape [No, 10] represents the detections.
Each row has 10 values:
[label, confidence, x1, y1, x2, y2, x3, y3, x4, y4]. No is the
total number of detections. If there is no detected boxes for all
images, lod will be set to {1} and Out only contains one value
which is -1.
(After version 1.3, when no boxes detected, the lod is changed
from {0} to {1})
Examples:
.. code-block:: python
import paddle.fluid as fluid
boxes = fluid.data(name='bboxes', shape=[None,81, 4],
dtype='float32', lod_level=1)
scores = fluid.data(name='scores', shape=[None,81],
dtype='float32', lod_level=1)
out = fluid.layers.multiclass_nms(bboxes=boxes,
scores=scores,
background_label=0,
score_threshold=0.5,
nms_top_k=400,
nms_threshold=0.3,
keep_top_k=200,
normalized=False)
"""
check_variable_and_dtype(bboxes, 'BBoxes', ['float32', 'float64'],
'multiclass_nms')
check_variable_and_dtype(scores, 'Scores', ['float32', 'float64'],
'multiclass_nms')
check_type(score_threshold, 'score_threshold', float, 'multicalss_nms')
check_type(nms_top_k, 'nums_top_k', int, 'multiclass_nms')
check_type(keep_top_k, 'keep_top_k', int, 'mutliclass_nms')
check_type(nms_threshold, 'nms_threshold', float, 'multiclass_nms')
check_type(normalized, 'normalized', bool, 'multiclass_nms')
check_type(nms_eta, 'nms_eta', float, 'multiclass_nms')
check_type(background_label, 'background_label', int, 'multiclass_nms')
helper = LayerHelper('multiclass_nms', **locals())
output = helper.create_variable_for_type_inference(dtype=bboxes.dtype)
helper.append_op(
type="multiclass_nms",
inputs={'BBoxes': bboxes,
'Scores': scores},
attrs={
'background_label': background_label,
'score_threshold': score_threshold,
'nms_top_k': nms_top_k,
'nms_threshold': nms_threshold,
'nms_eta': nms_eta,
'keep_top_k': keep_top_k,
'normalized': normalized
},
outputs={'Out': output})
output.stop_gradient = True
return output
def locality_aware_nms(bboxes,
scores,
score_threshold,
nms_top_k,
keep_top_k,
nms_threshold=0.3,
normalized=True,
nms_eta=1.,
background_label=-1,
name=None):
"""
**Local Aware NMS**
`Local Aware NMS <https://arxiv.org/abs/1704.03155>`_ is to do locality-aware non maximum
suppression (LANMS) on boxes and scores.
Firstly, this operator merge box and score according their IOU
(intersection over union). In the NMS step, this operator greedily selects a
subset of detection bounding boxes that have high scores larger than score_threshold,
if providing this threshold, then selects the largest nms_top_k confidences scores
if nms_top_k is larger than -1. Then this operator pruns away boxes that have high
IOU overlap with already selected boxes by adaptive threshold NMS based on parameters
of nms_threshold and nms_eta.
Aftern NMS step, at most keep_top_k number of total bboxes are to be kept
per image if keep_top_k is larger than -1.
Args:
bboxes (Variable): A 3-D Tensor with shape [N, M, 4 or 8 16 24 32]
represents the predicted locations of M bounding
bboxes, N is the batch size. Each bounding box
has four coordinate values and the layout is
[xmin, ymin, xmax, ymax], when box size equals to 4.
The data type is float32 or float64.
scores (Variable): A 3-D Tensor with shape [N, C, M] represents the
predicted confidence predictions. N is the batch
size, C is the class number, M is number of bounding
boxes. Now only support 1 class. For each category
there are total M scores which corresponding M bounding
boxes. Please note, M is equal to the 2nd dimension of
BBoxes. The data type is float32 or float64.
background_label (int): The index of background label, the background
label will be ignored. If set to -1, then all
categories will be considered. Default: -1
score_threshold (float): Threshold to filter out bounding boxes with
low confidence score. If not provided,
consider all boxes.
nms_top_k (int): Maximum number of detections to be kept according to
the confidences after the filtering detections based
on score_threshold.
keep_top_k (int): Number of total bboxes to be kept per image after NMS
step. -1 means keeping all bboxes after NMS step.
nms_threshold (float): The threshold to be used in NMS. Default: 0.3
nms_eta (float): The threshold to be used in NMS. Default: 1.0
normalized (bool): Whether detections are normalized. Default: True
name(str): Name of the locality aware nms op, please refer to :ref:`api_guide_Name` .
Default: None.
Returns:
Variable: A 2-D LoDTensor with shape [No, 6] represents the detections.
Each row has 6 values: [label, confidence, xmin, ymin, xmax, ymax]
or A 2-D LoDTensor with shape [No, 10] represents the detections.
Each row has 10 values:
[label, confidence, x1, y1, x2, y2, x3, y3, x4, y4]. No is the
total number of detections. If there is no detected boxes for all
images, lod will be set to {1} and Out only contains one value
which is -1.
(After version 1.3, when no boxes detected, the lod is changed
from {0} to {1}). The data type is float32 or float64.
Examples:
.. code-block:: python
import paddle.fluid as fluid
boxes = fluid.data(name='bboxes', shape=[None, 81, 8],
dtype='float32')
scores = fluid.data(name='scores', shape=[None, 1, 81],
dtype='float32')
out = fluid.layers.locality_aware_nms(bboxes=boxes,
scores=scores,
score_threshold=0.5,
nms_top_k=400,
nms_threshold=0.3,
keep_top_k=200,
normalized=False)
"""
check_variable_and_dtype(bboxes, 'bboxes', ['float32', 'float64'],
'locality_aware_nms')
check_variable_and_dtype(scores, 'scores', ['float32', 'float64'],
'locality_aware_nms')
check_type(background_label, 'background_label', int, 'locality_aware_nms')
check_type(score_threshold, 'score_threshold', float, 'locality_aware_nms')
check_type(nms_top_k, 'nms_top_k', int, 'locality_aware_nms')
check_type(nms_eta, 'nms_eta', float, 'locality_aware_nms')
check_type(nms_threshold, 'nms_threshold', float, 'locality_aware_nms')
check_type(keep_top_k, 'keep_top_k', int, 'locality_aware_nms')
check_type(normalized, 'normalized', bool, 'locality_aware_nms')
shape = scores.shape
assert len(shape) == 3, "dim size of scores must be 3"
assert shape[
1] == 1, "locality_aware_nms only support one class, Tensor score shape must be [N, 1, M]"
helper = LayerHelper('locality_aware_nms', **locals())
output = helper.create_variable_for_type_inference(dtype=bboxes.dtype)
out = {'Out': output}
helper.append_op(
type="locality_aware_nms",
inputs={'BBoxes': bboxes,
'Scores': scores},
attrs={
'background_label': background_label,
'score_threshold': score_threshold,
'nms_top_k': nms_top_k,
'nms_threshold': nms_threshold,
'nms_eta': nms_eta,
'keep_top_k': keep_top_k,
'nms_eta': nms_eta,
'normalized': normalized
},
outputs={'Out': output})
output.stop_gradient = True
return output
def matrix_nms(bboxes,
scores,
score_threshold,
post_threshold,
nms_top_k,
keep_top_k,
use_gaussian=False,
gaussian_sigma=2.,
background_label=0,
normalized=True,
return_index=False,
name=None):
"""
**Matrix NMS**
This operator does matrix non maximum suppression (NMS).
First selects a subset of candidate bounding boxes that have higher scores
than score_threshold (if provided), then the top k candidate is selected if
nms_top_k is larger than -1. Score of the remaining candidate are then
decayed according to the Matrix NMS scheme.
Aftern NMS step, at most keep_top_k number of total bboxes are to be kept
per image if keep_top_k is larger than -1.
Args:
bboxes (Variable): A 3-D Tensor with shape [N, M, 4] represents the
predicted locations of M bounding bboxes,
N is the batch size. Each bounding box has four
coordinate values and the layout is
[xmin, ymin, xmax, ymax], when box size equals to 4.
The data type is float32 or float64.
scores (Variable): A 3-D Tensor with shape [N, C, M]
represents the predicted confidence predictions.
N is the batch size, C is the class number, M is
number of bounding boxes. For each category there
are total M scores which corresponding M bounding
boxes. Please note, M is equal to the 2nd dimension
of BBoxes. The data type is float32 or float64.
score_threshold (float): Threshold to filter out bounding boxes with
low confidence score.
post_threshold (float): Threshold to filter out bounding boxes with
low confidence score AFTER decaying.
nms_top_k (int): Maximum number of detections to be kept according to
the confidences after the filtering detections based
on score_threshold.
keep_top_k (int): Number of total bboxes to be kept per image after NMS
step. -1 means keeping all bboxes after NMS step.
use_gaussian (bool): Use Gaussian as the decay function. Default: False
gaussian_sigma (float): Sigma for Gaussian decay function. Default: 2.0
background_label (int): The index of background label, the background
label will be ignored. If set to -1, then all
categories will be considered. Default: 0
normalized (bool): Whether detections are normalized. Default: True
return_index(bool): Whether return selected index. Default: False
name(str): Name of the matrix nms op. Default: None.
Returns:
A tuple with two Variables: (Out, Index) if return_index is True,
otherwise, one Variable(Out) is returned.
Out (Variable): A 2-D LoDTensor with shape [No, 6] containing the
detection results.
Each row has 6 values: [label, confidence, xmin, ymin, xmax, ymax]
(After version 1.3, when no boxes detected, the lod is changed
from {0} to {1})
Index (Variable): A 2-D LoDTensor with shape [No, 1] containing the
selected indices, which are absolute values cross batches.
Examples:
.. code-block:: python
import paddle.fluid as fluid
boxes = fluid.data(name='bboxes', shape=[None,81, 4],
dtype='float32', lod_level=1)
scores = fluid.data(name='scores', shape=[None,81],
dtype='float32', lod_level=1)
out = fluid.layers.matrix_nms(bboxes=boxes,
scores=scores,
background_label=0,
score_threshold=0.5,
post_threshold=0.1,
nms_top_k=400,
keep_top_k=200,
normalized=False)
"""
check_variable_and_dtype(bboxes, 'BBoxes', ['float32', 'float64'],
'matrix_nms')
check_variable_and_dtype(scores, 'Scores', ['float32', 'float64'],
'matrix_nms')
check_type(score_threshold, 'score_threshold', float, 'matrix_nms')
check_type(post_threshold, 'post_threshold', float, 'matrix_nms')
check_type(nms_top_k, 'nums_top_k', int, 'matrix_nms')
check_type(keep_top_k, 'keep_top_k', int, 'matrix_nms')
check_type(normalized, 'normalized', bool, 'matrix_nms')
check_type(use_gaussian, 'use_gaussian', bool, 'matrix_nms')
check_type(gaussian_sigma, 'gaussian_sigma', float, 'matrix_nms')
check_type(background_label, 'background_label', int, 'matrix_nms')
helper = LayerHelper('matrix_nms', **locals())
output = helper.create_variable_for_type_inference(dtype=bboxes.dtype)
index = helper.create_variable_for_type_inference(dtype='int')
helper.append_op(
type="matrix_nms",
inputs={'BBoxes': bboxes,
'Scores': scores},
attrs={
'background_label': background_label,
'score_threshold': score_threshold,
'post_threshold': post_threshold,
'nms_top_k': nms_top_k,
'gaussian_sigma': gaussian_sigma,
'use_gaussian': use_gaussian,
'keep_top_k': keep_top_k,
'normalized': normalized
},
outputs={'Out': output,
'Index': index})
output.stop_gradient = True
if return_index:
return output, index
else:
return output
def distribute_fpn_proposals(fpn_rois,
min_level,
max_level,
refer_level,
refer_scale,
name=None):
"""
:alias_main: paddle.nn.functional.distribute_fpn_proposals
:alias: paddle.nn.functional.distribute_fpn_proposals,paddle.nn.functional.vision.distribute_fpn_proposals
:old_api: paddle.fluid.layers.distribute_fpn_proposals
**This op only takes LoDTensor as input.** In Feature Pyramid Networks
(FPN) models, it is needed to distribute all proposals into different FPN
level, with respect to scale of the proposals, the referring scale and the
referring level. Besides, to restore the order of proposals, we return an
array which indicates the original index of rois in current proposals.
To compute FPN level for each roi, the formula is given as follows:
.. math::
roi\_scale &= \sqrt{BBoxArea(fpn\_roi)}
level = floor(&\log(\\frac{roi\_scale}{refer\_scale}) + refer\_level)
where BBoxArea is a function to compute the area of each roi.
Args:
fpn_rois(Variable): 2-D Tensor with shape [N, 4] and data type is
float32 or float64. The input fpn_rois.
min_level(int32): The lowest level of FPN layer where the proposals come
from.
max_level(int32): The highest level of FPN layer where the proposals
come from.
refer_level(int32): The referring level of FPN layer with specified scale.
refer_scale(int32): The referring scale of FPN layer with specified level.
name(str, optional): For detailed information, please refer
to :ref:`api_guide_Name`. Usually name is no need to set and
None by default.
Returns:
Tuple:
multi_rois(List) : A list of 2-D LoDTensor with shape [M, 4]
and data type of float32 and float64. The length is
max_level-min_level+1. The proposals in each FPN level.
restore_ind(Variable): A 2-D Tensor with shape [N, 1], N is
the number of total rois. The data type is int32. It is
used to restore the order of fpn_rois.
Examples:
.. code-block:: python
import paddle.fluid as fluid
fpn_rois = fluid.data(
name='data', shape=[None, 4], dtype='float32', lod_level=1)
multi_rois, restore_ind = fluid.layers.distribute_fpn_proposals(
fpn_rois=fpn_rois,
min_level=2,
max_level=5,
refer_level=4,
refer_scale=224)
"""
check_variable_and_dtype(fpn_rois, 'fpn_rois', ['float32', 'float64'],
'distribute_fpn_proposals')
helper = LayerHelper('distribute_fpn_proposals', **locals())
dtype = helper.input_dtype('fpn_rois')
num_lvl = max_level - min_level + 1
multi_rois = [
helper.create_variable_for_type_inference(dtype) for i in range(num_lvl)
]
restore_ind = helper.create_variable_for_type_inference(dtype='int32')
helper.append_op(
type='distribute_fpn_proposals',
inputs={'FpnRois': fpn_rois},
outputs={'MultiFpnRois': multi_rois,
'RestoreIndex': restore_ind},
attrs={
'min_level': min_level,
'max_level': max_level,
'refer_level': refer_level,
'refer_scale': refer_scale
})
return multi_rois, restore_ind
@templatedoc()
def box_decoder_and_assign(prior_box,
prior_box_var,
target_box,
box_score,
box_clip,
name=None):
"""
:alias_main: paddle.nn.functional.box_decoder_and_assign
:alias: paddle.nn.functional.box_decoder_and_assign,paddle.nn.functional.vision.box_decoder_and_assign
:old_api: paddle.fluid.layers.box_decoder_and_assign
${comment}
Args:
prior_box(${prior_box_type}): ${prior_box_comment}
prior_box_var(${prior_box_var_type}): ${prior_box_var_comment}
target_box(${target_box_type}): ${target_box_comment}
box_score(${box_score_type}): ${box_score_comment}
box_clip(${box_clip_type}): ${box_clip_comment}
name(str, optional): For detailed information, please refer
to :ref:`api_guide_Name`. Usually name is no need to set and
None by default.
Returns:
Tuple:
decode_box(${decode_box_type}): ${decode_box_comment}
output_assign_box(${output_assign_box_type}): ${output_assign_box_comment}
Examples:
.. code-block:: python
import paddle.fluid as fluid
pb = fluid.data(
name='prior_box', shape=[None, 4], dtype='float32')
pbv = fluid.data(
name='prior_box_var', shape=[4], dtype='float32')
loc = fluid.data(
name='target_box', shape=[None, 4*81], dtype='float32')
scores = fluid.data(
name='scores', shape=[None, 81], dtype='float32')
decoded_box, output_assign_box = fluid.layers.box_decoder_and_assign(
pb, pbv, loc, scores, 4.135)
"""
check_variable_and_dtype(prior_box, 'prior_box', ['float32', 'float64'],
'box_decoder_and_assign')
check_variable_and_dtype(target_box, 'target_box', ['float32', 'float64'],
'box_decoder_and_assign')
check_variable_and_dtype(box_score, 'box_score', ['float32', 'float64'],
'box_decoder_and_assign')
helper = LayerHelper("box_decoder_and_assign", **locals())
decoded_box = helper.create_variable_for_type_inference(
dtype=prior_box.dtype)
output_assign_box = helper.create_variable_for_type_inference(
dtype=prior_box.dtype)
helper.append_op(
type="box_decoder_and_assign",
inputs={
"PriorBox": prior_box,
"PriorBoxVar": prior_box_var,
"TargetBox": target_box,
"BoxScore": box_score
},
attrs={"box_clip": box_clip},
outputs={
"DecodeBox": decoded_box,
"OutputAssignBox": output_assign_box
})
return decoded_box, output_assign_box
def collect_fpn_proposals(multi_rois,
multi_scores,
min_level,
max_level,
post_nms_top_n,
name=None):
"""
:alias_main: paddle.nn.functional.collect_fpn_proposals
:alias: paddle.nn.functional.collect_fpn_proposals,paddle.nn.functional.vision.collect_fpn_proposals
:old_api: paddle.fluid.layers.collect_fpn_proposals
**This OP only supports LoDTensor as input**. Concat multi-level RoIs
(Region of Interest) and select N RoIs with respect to multi_scores.
This operation performs the following steps:
1. Choose num_level RoIs and scores as input: num_level = max_level - min_level
2. Concat multi-level RoIs and scores
3. Sort scores and select post_nms_top_n scores
4. Gather RoIs by selected indices from scores
5. Re-sort RoIs by corresponding batch_id
Args:
multi_rois(list): List of RoIs to collect. Element in list is 2-D
LoDTensor with shape [N, 4] and data type is float32 or float64,
N is the number of RoIs.
multi_scores(list): List of scores of RoIs to collect. Element in list
is 2-D LoDTensor with shape [N, 1] and data type is float32 or
float64, N is the number of RoIs.
min_level(int): The lowest level of FPN layer to collect
max_level(int): The highest level of FPN layer to collect
post_nms_top_n(int): The number of selected RoIs
name(str, optional): For detailed information, please refer
to :ref:`api_guide_Name`. Usually name is no need to set and
None by default.
Returns:
Variable:
fpn_rois(Variable): 2-D LoDTensor with shape [N, 4] and data type is
float32 or float64. Selected RoIs.
Examples:
.. code-block:: python
import paddle.fluid as fluid
multi_rois = []
multi_scores = []
for i in range(4):
multi_rois.append(fluid.data(
name='roi_'+str(i), shape=[None, 4], dtype='float32', lod_level=1))
for i in range(4):
multi_scores.append(fluid.data(
name='score_'+str(i), shape=[None, 1], dtype='float32', lod_level=1))
fpn_rois = fluid.layers.collect_fpn_proposals(
multi_rois=multi_rois,
multi_scores=multi_scores,
min_level=2,
max_level=5,
post_nms_top_n=2000)
"""
check_type(multi_rois, 'multi_rois', list, 'collect_fpn_proposals')
check_type(multi_scores, 'multi_scores', list, 'collect_fpn_proposals')
helper = LayerHelper('collect_fpn_proposals', **locals())
dtype = helper.input_dtype('multi_rois')
check_dtype(dtype, 'multi_rois', ['float32', 'float64'],
'collect_fpn_proposals')
num_lvl = max_level - min_level + 1
input_rois = multi_rois[:num_lvl]
input_scores = multi_scores[:num_lvl]
output_rois = helper.create_variable_for_type_inference(dtype)
output_rois.stop_gradient = True
helper.append_op(
type='collect_fpn_proposals',
inputs={
'MultiLevelRois': input_rois,
'MultiLevelScores': input_scores
},
outputs={'FpnRois': output_rois},
attrs={'post_nms_topN': post_nms_top_n})
return output_rois
| python/paddle/fluid/layers/detection.py | 174,992 | :alias_main: paddle.nn.functional.anchor_generator
:alias: paddle.nn.functional.anchor_generator,paddle.nn.functional.vision.anchor_generator
:old_api: paddle.fluid.layers.anchor_generator
**Anchor generator operator**
Generate anchors for Faster RCNN algorithm.
Each position of the input produce N anchors, N =
size(anchor_sizes) * size(aspect_ratios). The order of generated anchors
is firstly aspect_ratios loop then anchor_sizes loop.
Args:
input(Variable): 4-D Tensor with shape [N,C,H,W]. The input feature map.
anchor_sizes(float32|list|tuple, optional): The anchor sizes of generated
anchors, given in absolute pixels e.g. [64., 128., 256., 512.].
For instance, the anchor size of 64 means the area of this anchor
equals to 64**2. None by default.
aspect_ratios(float32|list|tuple, optional): The height / width ratios
of generated anchors, e.g. [0.5, 1.0, 2.0]. None by default.
variance(list|tuple, optional): The variances to be used in box
regression deltas. The data type is float32, [0.1, 0.1, 0.2, 0.2] by
default.
stride(list|tuple, optional): The anchors stride across width and height.
The data type is float32. e.g. [16.0, 16.0]. None by default.
offset(float32, optional): Prior boxes center offset. 0.5 by default.
name(str, optional): For detailed information, please refer
to :ref:`api_guide_Name`. Usually name is no need to set and None
by default.
Returns:
Tuple:
Anchors(Variable): The output anchors with a layout of [H, W, num_anchors, 4].
H is the height of input, W is the width of input,
num_anchors is the box count of each position.
Each anchor is in (xmin, ymin, xmax, ymax) format an unnormalized.
Variances(Variable): The expanded variances of anchors
with a layout of [H, W, num_priors, 4].
H is the height of input, W is the width of input
num_anchors is the box count of each position.
Each variance is in (xcenter, ycenter, w, h) format.
Examples:
.. code-block:: python
import paddle.fluid as fluid
conv1 = fluid.data(name='conv1', shape=[None, 48, 16, 16], dtype='float32')
anchor, var = fluid.layers.anchor_generator(
input=conv1,
anchor_sizes=[64, 128, 256, 512],
aspect_ratios=[0.5, 1.0, 2.0],
variance=[0.1, 0.1, 0.2, 0.2],
stride=[16.0, 16.0],
offset=0.5)
:alias_main: paddle.nn.functional.bipartite_match
:alias: paddle.nn.functional.bipartite_match,paddle.nn.functional.vision.bipartite_match
:old_api: paddle.fluid.layers.bipartite_match
This operator implements a greedy bipartite matching algorithm, which is
used to obtain the matching with the maximum distance based on the input
distance matrix. For input 2D matrix, the bipartite matching algorithm can
find the matched column for each row (matched means the largest distance),
also can find the matched row for each column. And this operator only
calculate matched indices from column to row. For each instance,
the number of matched indices is the column number of the input distance
matrix. **The OP only supports CPU**.
There are two outputs, matched indices and distance.
A simple description, this algorithm matched the best (maximum distance)
row entity to the column entity and the matched indices are not duplicated
in each row of ColToRowMatchIndices. If the column entity is not matched
any row entity, set -1 in ColToRowMatchIndices.
NOTE: the input DistMat can be LoDTensor (with LoD) or Tensor.
If LoDTensor with LoD, the height of ColToRowMatchIndices is batch size.
If Tensor, the height of ColToRowMatchIndices is 1.
NOTE: This API is a very low level API. It is used by :code:`ssd_loss`
layer. Please consider to use :code:`ssd_loss` instead.
Args:
dist_matrix(Variable): This input is a 2-D LoDTensor with shape
[K, M]. The data type is float32 or float64. It is pair-wise
distance matrix between the entities represented by each row and
each column. For example, assumed one entity is A with shape [K],
another entity is B with shape [M]. The dist_matrix[i][j] is the
distance between A[i] and B[j]. The bigger the distance is, the
better matching the pairs are. NOTE: This tensor can contain LoD
information to represent a batch of inputs. One instance of this
batch can contain different numbers of entities.
match_type(str, optional): The type of matching method, should be
'bipartite' or 'per_prediction'. None ('bipartite') by default.
dist_threshold(float32, optional): If `match_type` is 'per_prediction',
this threshold is to determine the extra matching bboxes based
on the maximum distance, 0.5 by default.
name(str, optional): For detailed information, please refer
to :ref:`api_guide_Name`. Usually name is no need to set and
None by default.
Returns:
Tuple:
matched_indices(Variable): A 2-D Tensor with shape [N, M]. The data
type is int32. N is the batch size. If match_indices[i][j] is -1, it
means B[j] does not match any entity in i-th instance.
Otherwise, it means B[j] is matched to row
match_indices[i][j] in i-th instance. The row number of
i-th instance is saved in match_indices[i][j].
matched_distance(Variable): A 2-D Tensor with shape [N, M]. The data
type is float32. N is batch size. If match_indices[i][j] is -1,
match_distance[i][j] is also -1.0. Otherwise, assumed
match_distance[i][j] = d, and the row offsets of each instance
are called LoD. Then match_distance[i][j] =
dist_matrix[d+LoD[i]][j].
Examples:
>>> import paddle.fluid as fluid
>>> x = fluid.data(name='x', shape=[None, 4], dtype='float32')
>>> y = fluid.data(name='y', shape=[None, 4], dtype='float32')
>>> iou = fluid.layers.iou_similarity(x=x, y=y)
>>> matched_indices, matched_dist = fluid.layers.bipartite_match(iou)
:alias_main: paddle.nn.functional.box_clip
:alias: paddle.nn.functional.box_clip,paddle.nn.functional.vision.box_clip
:old_api: paddle.fluid.layers.box_clip
Clip the box into the size given by im_info
For each input box, The formula is given as follows:
.. code-block:: text
xmin = max(min(xmin, im_w - 1), 0)
ymin = max(min(ymin, im_h - 1), 0)
xmax = max(min(xmax, im_w - 1), 0)
ymax = max(min(ymax, im_h - 1), 0)
where im_w and im_h are computed from im_info:
.. code-block:: text
im_h = round(height / scale)
im_w = round(weight / scale)
Args:
input(Variable): The input Tensor with shape :math:`[N_1, N_2, ..., N_k, 4]`,
the last dimension is 4 and data type is float32 or float64.
im_info(Variable): The 2-D Tensor with shape [N, 3] with layout
(height, width, scale) representing the information of image.
Height and width are the input sizes and scale is the ratio of network input
size and original size. The data type is float32 or float64.
name(str, optional): For detailed information, please refer
to :ref:`api_guide_Name`. Usually name is no need to set and
None by default.
Returns:
Variable:
output(Variable): The clipped tensor with data type float32 or float64.
The shape is same as input.
Examples:
.. code-block:: python
import paddle.fluid as fluid
boxes = fluid.data(
name='boxes', shape=[None, 8, 4], dtype='float32', lod_level=1)
im_info = fluid.data(name='im_info', shape=[-1 ,3])
out = fluid.layers.box_clip(
input=boxes, im_info=im_info)
:alias_main: paddle.nn.functional.box_coder
:alias: paddle.nn.functional.box_coder,paddle.nn.functional.vision.box_coder
:old_api: paddle.fluid.layers.box_coder
**Box Coder Layer**
Encode/Decode the target bounding box with the priorbox information.
The Encoding schema described below:
.. math::
ox = (tx - px) / pw / pxv
oy = (ty - py) / ph / pyv
ow = \log(bs(tw / pw)) / pwv
oh = \log(bs(th / ph)) / phv
The Decoding schema described below:
.. math::
ox = (pw * pxv * tx * + px) - tw / 2
oy = (ph * pyv * ty * + py) - th / 2
ow = \exp(pwv * tw) * pw + tw / 2
oh = \exp(phv * th) * ph + th / 2
where `tx`, `ty`, `tw`, `th` denote the target box's center coordinates,
width and height respectively. Similarly, `px`, `py`, `pw`, `ph` denote
the priorbox's (anchor) center coordinates, width and height. `pxv`,
`pyv`, `pwv`, `phv` denote the variance of the priorbox and `ox`, `oy`,
`ow`, `oh` denote the encoded/decoded coordinates, width and height.
During Box Decoding, two modes for broadcast are supported. Say target
box has shape [N, M, 4], and the shape of prior box can be [N, 4] or
[M, 4]. Then prior box will broadcast to target box along the
assigned axis.
Args:
prior_box(Variable): Box list prior_box is a 2-D Tensor with shape
[M, 4] holds M boxes and data type is float32 or float64. Each box
is represented as [xmin, ymin, xmax, ymax], [xmin, ymin] is the
left top coordinate of the anchor box, if the input is image feature
map, they are close to the origin of the coordinate system.
[xmax, ymax] is the right bottom coordinate of the anchor box.
prior_box_var(List|Variable|None): prior_box_var supports three types
of input. One is variable with shape [M, 4] which holds M group and
data type is float32 or float64. The second is list consist of
4 elements shared by all boxes and data type is float32 or float64.
Other is None and not involved in calculation.
target_box(Variable): This input can be a 2-D LoDTensor with shape
[N, 4] when code_type is 'encode_center_size'. This input also can
be a 3-D Tensor with shape [N, M, 4] when code_type is
'decode_center_size'. Each box is represented as
[xmin, ymin, xmax, ymax]. The data type is float32 or float64.
This tensor can contain LoD information to represent a batch of inputs.
code_type(str): The code type used with the target box. It can be
`encode_center_size` or `decode_center_size`. `encode_center_size`
by default.
box_normalized(bool): Whether treat the priorbox as a normalized box.
Set true by default.
name(str, optional): For detailed information, please refer
to :ref:`api_guide_Name`. Usually name is no need to set and
None by default.
axis(int): Which axis in PriorBox to broadcast for box decode,
for example, if axis is 0 and TargetBox has shape [N, M, 4] and
PriorBox has shape [M, 4], then PriorBox will broadcast to [N, M, 4]
for decoding. It is only valid when code type is
`decode_center_size`. Set 0 by default.
Returns:
Variable:
output_box(Variable): When code_type is 'encode_center_size', the
output tensor of box_coder_op with shape [N, M, 4] representing the
result of N target boxes encoded with M Prior boxes and variances.
When code_type is 'decode_center_size', N represents the batch size
and M represents the number of decoded boxes.
Examples:
.. code-block:: python
import paddle.fluid as fluid
# For encode
prior_box_encode = fluid.data(name='prior_box_encode',
shape=[512, 4],
dtype='float32')
target_box_encode = fluid.data(name='target_box_encode',
shape=[81, 4],
dtype='float32')
output_encode = fluid.layers.box_coder(prior_box=prior_box_encode,
prior_box_var=[0.1,0.1,0.2,0.2],
target_box=target_box_encode,
code_type="encode_center_size")
# For decode
prior_box_decode = fluid.data(name='prior_box_decode',
shape=[512, 4],
dtype='float32')
target_box_decode = fluid.data(name='target_box_decode',
shape=[512, 81, 4],
dtype='float32')
output_decode = fluid.layers.box_coder(prior_box=prior_box_decode,
prior_box_var=[0.1,0.1,0.2,0.2],
target_box=target_box_decode,
code_type="decode_center_size",
box_normalized=False,
axis=1)
:alias_main: paddle.nn.functional.box_decoder_and_assign
:alias: paddle.nn.functional.box_decoder_and_assign,paddle.nn.functional.vision.box_decoder_and_assign
:old_api: paddle.fluid.layers.box_decoder_and_assign
${comment}
Args:
prior_box(${prior_box_type}): ${prior_box_comment}
prior_box_var(${prior_box_var_type}): ${prior_box_var_comment}
target_box(${target_box_type}): ${target_box_comment}
box_score(${box_score_type}): ${box_score_comment}
box_clip(${box_clip_type}): ${box_clip_comment}
name(str, optional): For detailed information, please refer
to :ref:`api_guide_Name`. Usually name is no need to set and
None by default.
Returns:
Tuple:
decode_box(${decode_box_type}): ${decode_box_comment}
output_assign_box(${output_assign_box_type}): ${output_assign_box_comment}
Examples:
.. code-block:: python
import paddle.fluid as fluid
pb = fluid.data(
name='prior_box', shape=[None, 4], dtype='float32')
pbv = fluid.data(
name='prior_box_var', shape=[4], dtype='float32')
loc = fluid.data(
name='target_box', shape=[None, 4*81], dtype='float32')
scores = fluid.data(
name='scores', shape=[None, 81], dtype='float32')
decoded_box, output_assign_box = fluid.layers.box_decoder_and_assign(
pb, pbv, loc, scores, 4.135)
:alias_main: paddle.nn.functional.collect_fpn_proposals
:alias: paddle.nn.functional.collect_fpn_proposals,paddle.nn.functional.vision.collect_fpn_proposals
:old_api: paddle.fluid.layers.collect_fpn_proposals
**This OP only supports LoDTensor as input**. Concat multi-level RoIs
(Region of Interest) and select N RoIs with respect to multi_scores.
This operation performs the following steps:
1. Choose num_level RoIs and scores as input: num_level = max_level - min_level
2. Concat multi-level RoIs and scores
3. Sort scores and select post_nms_top_n scores
4. Gather RoIs by selected indices from scores
5. Re-sort RoIs by corresponding batch_id
Args:
multi_rois(list): List of RoIs to collect. Element in list is 2-D
LoDTensor with shape [N, 4] and data type is float32 or float64,
N is the number of RoIs.
multi_scores(list): List of scores of RoIs to collect. Element in list
is 2-D LoDTensor with shape [N, 1] and data type is float32 or
float64, N is the number of RoIs.
min_level(int): The lowest level of FPN layer to collect
max_level(int): The highest level of FPN layer to collect
post_nms_top_n(int): The number of selected RoIs
name(str, optional): For detailed information, please refer
to :ref:`api_guide_Name`. Usually name is no need to set and
None by default.
Returns:
Variable:
fpn_rois(Variable): 2-D LoDTensor with shape [N, 4] and data type is
float32 or float64. Selected RoIs.
Examples:
.. code-block:: python
import paddle.fluid as fluid
multi_rois = []
multi_scores = []
for i in range(4):
multi_rois.append(fluid.data(
name='roi_'+str(i), shape=[None, 4], dtype='float32', lod_level=1))
for i in range(4):
multi_scores.append(fluid.data(
name='score_'+str(i), shape=[None, 1], dtype='float32', lod_level=1))
fpn_rois = fluid.layers.collect_fpn_proposals(
multi_rois=multi_rois,
multi_scores=multi_scores,
min_level=2,
max_level=5,
post_nms_top_n=2000)
:alias_main: paddle.nn.functional.density_prior_box
:alias: paddle.nn.functional.density_prior_box,paddle.nn.functional.vision.density_prior_box
:old_api: paddle.fluid.layers.density_prior_box
This op generates density prior boxes for SSD(Single Shot MultiBox Detector)
algorithm. Each position of the input produce N prior boxes, N is
determined by the count of densities, fixed_sizes and fixed_ratios.
Boxes center at grid points around each input position is generated by
this operator, and the grid points is determined by densities and
the count of density prior box is determined by fixed_sizes and fixed_ratios.
Obviously, the number of fixed_sizes is equal to the number of densities.
For densities_i in densities:
.. math::
N\_density_prior\_box = SUM(N\_fixed\_ratios * densities\_i^2)
N_density_prior_box is the number of density_prior_box and N_fixed_ratios is the number of fixed_ratios.
Parameters:
input(Variable): 4-D tensor(NCHW), the data type should be float32 of float64.
image(Variable): 4-D tensor(NCHW), the input image data of PriorBoxOp, the data type should be float32 or float64.
the layout is NCHW.
densities(list|tuple|None): The densities of generated density prior
boxes, this attribute should be a list or tuple of integers.
Default: None.
fixed_sizes(list|tuple|None): The fixed sizes of generated density
prior boxes, this attribute should a list or tuple of same
length with :attr:`densities`. Default: None.
fixed_ratios(list|tuple|None): The fixed ratios of generated density
prior boxes, if this attribute is not set and :attr:`densities`
and :attr:`fix_sizes` is set, :attr:`aspect_ratios` will be used
to generate density prior boxes.
variance(list|tuple): The variances to be encoded in density prior boxes.
Default:[0.1, 0.1, 0.2, 0.2].
clip(bool): Whether to clip out of boundary boxes. Default: False.
step(list|tuple): Prior boxes step across width and height, If
step[0] equals 0.0 or step[1] equals 0.0, the density prior boxes step across
height or weight of the input will be automatically calculated.
Default: [0., 0.]
offset(float): Prior boxes center offset. Default: 0.5
flatten_to_2d(bool): Whether to flatten output prior boxes and variance
to 2D shape, the second dim is 4. Default: False.
name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`
Returns:
Tuple: A tuple with two Variable (boxes, variances)
boxes: the output density prior boxes of PriorBox.
4-D tensor, the layout is [H, W, num_priors, 4] when flatten_to_2d is False.
2-D tensor, the layout is [H * W * num_priors, 4] when flatten_to_2d is True.
H is the height of input, W is the width of input, and num_priors is the total box count of each position of input.
variances: the expanded variances of PriorBox.
4-D tensor, the layout is [H, W, num_priors, 4] when flatten_to_2d is False.
2-D tensor, the layout is [H * W * num_priors, 4] when flatten_to_2d is True.
H is the height of input, W is the width of input, and num_priors is the total box count of each position of input.
Examples:
.. code-block:: python
#declarative mode
import paddle.fluid as fluid
import numpy as np
input = fluid.data(name="input", shape=[None,3,6,9])
image = fluid.data(name="image", shape=[None,3,9,12])
box, var = fluid.layers.density_prior_box(
input=input,
image=image,
densities=[4, 2, 1],
fixed_sizes=[32.0, 64.0, 128.0],
fixed_ratios=[1.],
clip=True,
flatten_to_2d=True)
place = fluid.CPUPlace()
exe = fluid.Executor(place)
exe.run(fluid.default_startup_program())
# prepare a batch of data
input_data = np.random.rand(1,3,6,9).astype("float32")
image_data = np.random.rand(1,3,9,12).astype("float32")
box_out, var_out = exe.run(
fluid.default_main_program(),
feed={"input":input_data,
"image":image_data},
fetch_list=[box,var],
return_numpy=True)
# print(box_out.shape)
# (1134, 4)
# print(var_out.shape)
# (1134, 4)
#imperative mode
import paddle.fluid.dygraph as dg
with dg.guard(place) as g:
input = dg.to_variable(input_data)
image = dg.to_variable(image_data)
box, var = fluid.layers.density_prior_box(
input=input,
image=image,
densities=[4, 2, 1],
fixed_sizes=[32.0, 64.0, 128.0],
fixed_ratios=[1.],
clip=True)
# print(box.shape)
# [6L, 9L, 21L, 4L]
# print(var.shape)
# [6L, 9L, 21L, 4L]
${comment}
Args:
detect_res: ${detect_res_comment}
label: ${label_comment}
class_num: ${class_num_comment}
background_label: ${background_label_comment}
overlap_threshold: ${overlap_threshold_comment}
evaluate_difficult: ${evaluate_difficult_comment}
has_state: ${has_state_comment}
input_states: (tuple|None) If not None, It contains 3 elements:
(1) pos_count ${pos_count_comment}.
(2) true_pos ${true_pos_comment}.
(3) false_pos ${false_pos_comment}.
out_states: (tuple|None) If not None, it contains 3 elements.
(1) accum_pos_count ${accum_pos_count_comment}.
(2) accum_true_pos ${accum_true_pos_comment}.
(3) accum_false_pos ${accum_false_pos_comment}.
ap_version: ${ap_type_comment}
Returns:
${map_comment}
Examples:
.. code-block:: python
import paddle.fluid as fluid
from fluid.layers import detection
detect_res = fluid.data(
name='detect_res',
shape=[10, 6],
dtype='float32')
label = fluid.data(
name='label',
shape=[10, 6],
dtype='float32')
map_out = detection.detection_map(detect_res, label, 21)
:alias_main: paddle.nn.functional.detection_output
:alias: paddle.nn.functional.detection_output,paddle.nn.functional.vision.detection_output
:old_api: paddle.fluid.layers.detection_output
Given the regression locations, classification confidences and prior boxes,
calculate the detection outputs by performing following steps:
1. Decode input bounding box predictions according to the prior boxes and
regression locations.
2. Get the final detection results by applying multi-class non maximum
suppression (NMS).
Please note, this operation doesn't clip the final output bounding boxes
to the image window.
Args:
loc(Variable): A 3-D Tensor with shape [N, M, 4] represents the
predicted locations of M bounding bboxes. Data type should be
float32 or float64. N is the batch size,
and each bounding box has four coordinate values and the layout
is [xmin, ymin, xmax, ymax].
scores(Variable): A 3-D Tensor with shape [N, M, C] represents the
predicted confidence predictions. Data type should be float32
or float64. N is the batch size, C is the
class number, M is number of bounding boxes.
prior_box(Variable): A 2-D Tensor with shape [M, 4] holds M boxes,
each box is represented as [xmin, ymin, xmax, ymax]. Data type
should be float32 or float64.
prior_box_var(Variable): A 2-D Tensor with shape [M, 4] holds M group
of variance. Data type should be float32 or float64.
background_label(int): The index of background label,
the background label will be ignored. If set to -1, then all
categories will be considered. Default: 0.
nms_threshold(float): The threshold to be used in NMS. Default: 0.3.
nms_top_k(int): Maximum number of detections to be kept according
to the confidences after filtering detections based on
score_threshold and before NMS. Default: 400.
keep_top_k(int): Number of total bboxes to be kept per image after
NMS step. -1 means keeping all bboxes after NMS step. Default: 200.
score_threshold(float): Threshold to filter out bounding boxes with
low confidence score. If not provided, consider all boxes.
Default: 0.01.
nms_eta(float): The parameter for adaptive NMS. It works only when the
value is less than 1.0. Default: 1.0.
return_index(bool): Whether return selected index. Default: False
Returns:
A tuple with two Variables: (Out, Index) if return_index is True,
otherwise, a tuple with one Variable(Out) is returned.
Out (Variable): The detection outputs is a LoDTensor with shape [No, 6].
Data type is the same as input (loc). Each row has six values:
[label, confidence, xmin, ymin, xmax, ymax]. `No` is
the total number of detections in this mini-batch. For each instance,
the offsets in first dimension are called LoD, the offset number is
N + 1, N is the batch size. The i-th image has `LoD[i + 1] - LoD[i]`
detected results, if it is 0, the i-th image has no detected results.
Index (Variable): Only return when return_index is True. A 2-D LoDTensor
with shape [No, 1] represents the selected index which type is Integer.
The index is the absolute value cross batches. No is the same number
as Out. If the index is used to gather other attribute such as age,
one needs to reshape the input(N, M, 1) to (N * M, 1) as first, where
N is the batch size and M is the number of boxes.
Examples:
.. code-block:: python
import paddle.fluid as fluid
pb = fluid.data(name='prior_box', shape=[10, 4], dtype='float32')
pbv = fluid.data(name='prior_box_var', shape=[10, 4], dtype='float32')
loc = fluid.data(name='target_box', shape=[2, 21, 4], dtype='float32')
scores = fluid.data(name='scores', shape=[2, 21, 10], dtype='float32')
nmsed_outs, index = fluid.layers.detection_output(scores=scores,
loc=loc,
prior_box=pb,
prior_box_var=pbv,
return_index=True)
:alias_main: paddle.nn.functional.distribute_fpn_proposals
:alias: paddle.nn.functional.distribute_fpn_proposals,paddle.nn.functional.vision.distribute_fpn_proposals
:old_api: paddle.fluid.layers.distribute_fpn_proposals
**This op only takes LoDTensor as input.** In Feature Pyramid Networks
(FPN) models, it is needed to distribute all proposals into different FPN
level, with respect to scale of the proposals, the referring scale and the
referring level. Besides, to restore the order of proposals, we return an
array which indicates the original index of rois in current proposals.
To compute FPN level for each roi, the formula is given as follows:
.. math::
roi\_scale &= \sqrt{BBoxArea(fpn\_roi)}
level = floor(&\log(\frac{roi\_scale}{refer\_scale}) + refer\_level)
where BBoxArea is a function to compute the area of each roi.
Args:
fpn_rois(Variable): 2-D Tensor with shape [N, 4] and data type is
float32 or float64. The input fpn_rois.
min_level(int32): The lowest level of FPN layer where the proposals come
from.
max_level(int32): The highest level of FPN layer where the proposals
come from.
refer_level(int32): The referring level of FPN layer with specified scale.
refer_scale(int32): The referring scale of FPN layer with specified level.
name(str, optional): For detailed information, please refer
to :ref:`api_guide_Name`. Usually name is no need to set and
None by default.
Returns:
Tuple:
multi_rois(List) : A list of 2-D LoDTensor with shape [M, 4]
and data type of float32 and float64. The length is
max_level-min_level+1. The proposals in each FPN level.
restore_ind(Variable): A 2-D Tensor with shape [N, 1], N is
the number of total rois. The data type is int32. It is
used to restore the order of fpn_rois.
Examples:
.. code-block:: python
import paddle.fluid as fluid
fpn_rois = fluid.data(
name='data', shape=[None, 4], dtype='float32', lod_level=1)
multi_rois, restore_ind = fluid.layers.distribute_fpn_proposals(
fpn_rois=fpn_rois,
min_level=2,
max_level=5,
refer_level=4,
refer_scale=224)
:alias_main: paddle.nn.functional.generate_mask_labels
:alias: paddle.nn.functional.generate_mask_labels,paddle.nn.functional.vision.generate_mask_labels
:old_api: paddle.fluid.layers.generate_mask_labels
**Generate Mask Labels for Mask-RCNN**
This operator can be, for given the RoIs and corresponding labels,
to sample foreground RoIs. This mask branch also has
a :math: `K \times M^{2}` dimensional output targets for each foreground
RoI, which encodes K binary masks of resolution M x M, one for each of the
K classes. This mask targets are used to compute loss of mask branch.
Please note, the data format of groud-truth segmentation, assumed the
segmentations are as follows. The first instance has two gt objects.
The second instance has one gt object, this object has two gt segmentations.
.. code-block:: python
#[
# [[[229.14, 370.9, 229.14, 370.9, ...]],
# [[343.7, 139.85, 349.01, 138.46, ...]]], # 0-th instance
# [[[500.0, 390.62, ...],[115.48, 187.86, ...]]] # 1-th instance
#]
batch_masks = []
for semgs in batch_semgs:
gt_masks = []
for semg in semgs:
gt_segm = []
for polys in semg:
gt_segm.append(np.array(polys).reshape(-1, 2))
gt_masks.append(gt_segm)
batch_masks.append(gt_masks)
place = fluid.CPUPlace()
feeder = fluid.DataFeeder(place=place, feed_list=feeds)
feeder.feed(batch_masks)
Args:
im_info (Variable): A 2-D Tensor with shape [N, 3] and float32
data type. N is the batch size, each element is
[height, width, scale] of image. Image scale is
target_size / original_size, target_size is the size after resize,
original_size is the original image size.
gt_classes (Variable): A 2-D LoDTensor with shape [M, 1]. Data type
should be int. M is the total number of ground-truth, each
element is a class label.
is_crowd (Variable): A 2-D LoDTensor with same shape and same data type
as gt_classes, each element is a flag indicating whether a
groundtruth is crowd.
gt_segms (Variable): This input is a 2D LoDTensor with shape [S, 2] and
float32 data type, it's LoD level is 3.
Usually users do not needs to understand LoD,
The users should return correct data format in reader.
The LoD[0] represents the ground-truth objects number of
each instance. LoD[1] represents the segmentation counts of each
objects. LoD[2] represents the polygons number of each segmentation.
S the total number of polygons coordinate points. Each element is
(x, y) coordinate points.
rois (Variable): A 2-D LoDTensor with shape [R, 4] and float32 data type
float32. R is the total number of RoIs, each element is a bounding
box with (xmin, ymin, xmax, ymax) format in the range of original image.
labels_int32 (Variable): A 2-D LoDTensor in shape of [R, 1] with type
of int32. R is the same as it in `rois`. Each element represents
a class label of a RoI.
num_classes (int): Class number.
resolution (int): Resolution of mask predictions.
Returns:
mask_rois (Variable): A 2D LoDTensor with shape [P, 4] and same data
type as `rois`. P is the total number of sampled RoIs. Each element
is a bounding box with [xmin, ymin, xmax, ymax] format in range of
original image size.
mask_rois_has_mask_int32 (Variable): A 2D LoDTensor with shape [P, 1]
and int data type, each element represents the output mask RoI
index with regard to input RoIs.
mask_int32 (Variable): A 2D LoDTensor with shape [P, K * M * M] and int
data type, K is the classes number and M is the resolution of mask
predictions. Each element represents the binary mask targets.
Examples:
.. code-block:: python
import paddle.fluid as fluid
im_info = fluid.data(name="im_info", shape=[None, 3],
dtype="float32")
gt_classes = fluid.data(name="gt_classes", shape=[None, 1],
dtype="float32", lod_level=1)
is_crowd = fluid.data(name="is_crowd", shape=[None, 1],
dtype="float32", lod_level=1)
gt_masks = fluid.data(name="gt_masks", shape=[None, 2],
dtype="float32", lod_level=3)
# rois, roi_labels can be the output of
# fluid.layers.generate_proposal_labels.
rois = fluid.data(name="rois", shape=[None, 4],
dtype="float32", lod_level=1)
roi_labels = fluid.data(name="roi_labels", shape=[None, 1],
dtype="int32", lod_level=1)
mask_rois, mask_index, mask_int32 = fluid.layers.generate_mask_labels(
im_info=im_info,
gt_classes=gt_classes,
is_crowd=is_crowd,
gt_segms=gt_masks,
rois=rois,
labels_int32=roi_labels,
num_classes=81,
resolution=14)
:alias_main: paddle.nn.functional.generate_proposal_labels
:alias: paddle.nn.functional.generate_proposal_labels,paddle.nn.functional.vision.generate_proposal_labels
:old_api: paddle.fluid.layers.generate_proposal_labels
**Generate Proposal Labels of Faster-RCNN**
This operator can be, for given the GenerateProposalOp output bounding boxes and groundtruth,
to sample foreground boxes and background boxes, and compute loss target.
RpnRois is the output boxes of RPN and was processed by generate_proposal_op, these boxes
were combined with groundtruth boxes and sampled according to batch_size_per_im and fg_fraction,
If an instance with a groundtruth overlap greater than fg_thresh, then it was considered as a foreground sample.
If an instance with a groundtruth overlap greater than bg_thresh_lo and lower than bg_thresh_hi,
then it was considered as a background sample.
After all foreground and background boxes are chosen (so called Rois),
then we apply random sampling to make sure
the number of foreground boxes is no more than batch_size_per_im * fg_fraction.
For each box in Rois, we assign the classification (class label) and regression targets (box label) to it.
Finally BboxInsideWeights and BboxOutsideWeights are used to specify whether it would contribute to training loss.
Args:
rpn_rois(Variable): A 2-D LoDTensor with shape [N, 4]. N is the number of the GenerateProposalOp's output, each element is a bounding box with [xmin, ymin, xmax, ymax] format. The data type can be float32 or float64.
gt_classes(Variable): A 2-D LoDTensor with shape [M, 1]. M is the number of groundtruth, each element is a class label of groundtruth. The data type must be int32.
is_crowd(Variable): A 2-D LoDTensor with shape [M, 1]. M is the number of groundtruth, each element is a flag indicates whether a groundtruth is crowd. The data type must be int32.
gt_boxes(Variable): A 2-D LoDTensor with shape [M, 4]. M is the number of groundtruth, each element is a bounding box with [xmin, ymin, xmax, ymax] format.
im_info(Variable): A 2-D LoDTensor with shape [B, 3]. B is the number of input images, each element consists of im_height, im_width, im_scale.
batch_size_per_im(int): Batch size of rois per images. The data type must be int32.
fg_fraction(float): Foreground fraction in total batch_size_per_im. The data type must be float32.
fg_thresh(float): Overlap threshold which is used to chose foreground sample. The data type must be float32.
bg_thresh_hi(float): Overlap threshold upper bound which is used to chose background sample. The data type must be float32.
bg_thresh_lo(float): Overlap threshold lower bound which is used to chose background sample. The data type must be float32.
bbox_reg_weights(list|tuple): Box regression weights. The data type must be float32.
class_nums(int): Class number. The data type must be int32.
use_random(bool): Use random sampling to choose foreground and background boxes.
is_cls_agnostic(bool): bbox regression use class agnostic simply which only represent fg and bg boxes.
is_cascade_rcnn(bool): it will filter some bbox crossing the image's boundary when setting True.
Returns:
tuple:
A tuple with format``(rois, labels_int32, bbox_targets, bbox_inside_weights, bbox_outside_weights)``.
- **rois**: 2-D LoDTensor with shape ``[batch_size_per_im * batch_size, 4]``. The data type is the same as ``rpn_rois``.
- **labels_int32**: 2-D LoDTensor with shape ``[batch_size_per_im * batch_size, 1]``. The data type must be int32.
- **bbox_targets**: 2-D LoDTensor with shape ``[batch_size_per_im * batch_size, 4 * class_num]``. The regression targets of all RoIs. The data type is the same as ``rpn_rois``.
- **bbox_inside_weights**: 2-D LoDTensor with shape ``[batch_size_per_im * batch_size, 4 * class_num]``. The weights of foreground boxes' regression loss. The data type is the same as ``rpn_rois``.
- **bbox_outside_weights**: 2-D LoDTensor with shape ``[batch_size_per_im * batch_size, 4 * class_num]``. The weights of regression loss. The data type is the same as ``rpn_rois``.
Examples:
.. code-block:: python
import paddle.fluid as fluid
rpn_rois = fluid.data(name='rpn_rois', shape=[None, 4], dtype='float32')
gt_classes = fluid.data(name='gt_classes', shape=[None, 1], dtype='float32')
is_crowd = fluid.data(name='is_crowd', shape=[None, 1], dtype='float32')
gt_boxes = fluid.data(name='gt_boxes', shape=[None, 4], dtype='float32')
im_info = fluid.data(name='im_info', shape=[None, 3], dtype='float32')
rois, labels, bbox, inside_weights, outside_weights = fluid.layers.generate_proposal_labels(
rpn_rois, gt_classes, is_crowd, gt_boxes, im_info,
class_nums=10)
:alias_main: paddle.nn.functional.generate_proposals
:alias: paddle.nn.functional.generate_proposals,paddle.nn.functional.vision.generate_proposals
:old_api: paddle.fluid.layers.generate_proposals
**Generate proposal Faster-RCNN**
This operation proposes RoIs according to each box with their
probability to be a foreground object and
the box can be calculated by anchors. Bbox_deltais and scores
to be an object are the output of RPN. Final proposals
could be used to train detection net.
For generating proposals, this operation performs following steps:
1. Transposes and resizes scores and bbox_deltas in size of
(H*W*A, 1) and (H*W*A, 4)
2. Calculate box locations as proposals candidates.
3. Clip boxes to image
4. Remove predicted boxes with small area.
5. Apply NMS to get final proposals as output.
Args:
scores(Variable): A 4-D Tensor with shape [N, A, H, W] represents
the probability for each box to be an object.
N is batch size, A is number of anchors, H and W are height and
width of the feature map. The data type must be float32.
bbox_deltas(Variable): A 4-D Tensor with shape [N, 4*A, H, W]
represents the difference between predicted box location and
anchor location. The data type must be float32.
im_info(Variable): A 2-D Tensor with shape [N, 3] represents origin
image information for N batch. Height and width are the input sizes
and scale is the ratio of network input size and original size.
The data type can be float32 or float64.
anchors(Variable): A 4-D Tensor represents the anchors with a layout
of [H, W, A, 4]. H and W are height and width of the feature map,
num_anchors is the box count of each position. Each anchor is
in (xmin, ymin, xmax, ymax) format an unnormalized. The data type must be float32.
variances(Variable): A 4-D Tensor. The expanded variances of anchors with a layout of
[H, W, num_priors, 4]. Each variance is in
(xcenter, ycenter, w, h) format. The data type must be float32.
pre_nms_top_n(float): Number of total bboxes to be kept per
image before NMS. The data type must be float32. `6000` by default.
post_nms_top_n(float): Number of total bboxes to be kept per
image after NMS. The data type must be float32. `1000` by default.
nms_thresh(float): Threshold in NMS. The data type must be float32. `0.5` by default.
min_size(float): Remove predicted boxes with either height or
width < min_size. The data type must be float32. `0.1` by default.
eta(float): Apply in adaptive NMS, if adaptive `threshold > 0.5`,
`adaptive_threshold = adaptive_threshold * eta` in each iteration.
return_rois_num(bool): When setting True, it will return a 1D Tensor with shape [N, ] that includes Rois's
num of each image in one batch. The N is the image's num. For example, the tensor has values [4,5] that represents
the first image has 4 Rois, the second image has 5 Rois. It only used in rcnn model.
'False' by default.
Returns:
tuple:
A tuple with format ``(rpn_rois, rpn_roi_probs)``.
- **rpn_rois**: The generated RoIs. 2-D Tensor with shape ``[N, 4]`` while ``N`` is the number of RoIs. The data type is the same as ``scores``.
- **rpn_roi_probs**: The scores of generated RoIs. 2-D Tensor with shape ``[N, 1]`` while ``N`` is the number of RoIs. The data type is the same as ``scores``.
Examples:
.. code-block:: python
import paddle.fluid as fluid
scores = fluid.data(name='scores', shape=[None, 4, 5, 5], dtype='float32')
bbox_deltas = fluid.data(name='bbox_deltas', shape=[None, 16, 5, 5], dtype='float32')
im_info = fluid.data(name='im_info', shape=[None, 3], dtype='float32')
anchors = fluid.data(name='anchors', shape=[None, 5, 4, 4], dtype='float32')
variances = fluid.data(name='variances', shape=[None, 5, 10, 4], dtype='float32')
rois, roi_probs = fluid.layers.generate_proposals(scores, bbox_deltas,
im_info, anchors, variances)
:alias_main: paddle.nn.functional.iou_similarity
:alias: paddle.nn.functional.iou_similarity,paddle.nn.functional.loss.iou_similarity
:old_api: paddle.fluid.layers.iou_similarity
${comment}
Args:
x (Variable): ${x_comment}.The data type is float32 or float64.
y (Variable): ${y_comment}.The data type is float32 or float64.
box_normalized(bool): Whether treat the priorbox as a normalized box.
Set true by default.
Returns:
Variable: ${out_comment}.The data type is same with x.
Examples:
.. code-block:: python
import numpy as np
import paddle.fluid as fluid
use_gpu = False
place = fluid.CUDAPlace(0) if use_gpu else fluid.CPUPlace()
exe = fluid.Executor(place)
x = fluid.data(name='x', shape=[None, 4], dtype='float32')
y = fluid.data(name='y', shape=[None, 4], dtype='float32')
iou = fluid.layers.iou_similarity(x=x, y=y)
exe.run(fluid.default_startup_program())
test_program = fluid.default_main_program().clone(for_test=True)
[out_iou] = exe.run(test_program,
fetch_list=iou,
feed={'x': np.array([[0.5, 0.5, 2.0, 2.0],
[0., 0., 1.0, 1.0]]).astype('float32'),
'y': np.array([[1.0, 1.0, 2.5, 2.5]]).astype('float32')})
# out_iou is [[0.2857143],
# [0. ]] with shape: [2, 1]
**Local Aware NMS**
`Local Aware NMS <https://arxiv.org/abs/1704.03155>`_ is to do locality-aware non maximum
suppression (LANMS) on boxes and scores.
Firstly, this operator merge box and score according their IOU
(intersection over union). In the NMS step, this operator greedily selects a
subset of detection bounding boxes that have high scores larger than score_threshold,
if providing this threshold, then selects the largest nms_top_k confidences scores
if nms_top_k is larger than -1. Then this operator pruns away boxes that have high
IOU overlap with already selected boxes by adaptive threshold NMS based on parameters
of nms_threshold and nms_eta.
Aftern NMS step, at most keep_top_k number of total bboxes are to be kept
per image if keep_top_k is larger than -1.
Args:
bboxes (Variable): A 3-D Tensor with shape [N, M, 4 or 8 16 24 32]
represents the predicted locations of M bounding
bboxes, N is the batch size. Each bounding box
has four coordinate values and the layout is
[xmin, ymin, xmax, ymax], when box size equals to 4.
The data type is float32 or float64.
scores (Variable): A 3-D Tensor with shape [N, C, M] represents the
predicted confidence predictions. N is the batch
size, C is the class number, M is number of bounding
boxes. Now only support 1 class. For each category
there are total M scores which corresponding M bounding
boxes. Please note, M is equal to the 2nd dimension of
BBoxes. The data type is float32 or float64.
background_label (int): The index of background label, the background
label will be ignored. If set to -1, then all
categories will be considered. Default: -1
score_threshold (float): Threshold to filter out bounding boxes with
low confidence score. If not provided,
consider all boxes.
nms_top_k (int): Maximum number of detections to be kept according to
the confidences after the filtering detections based
on score_threshold.
keep_top_k (int): Number of total bboxes to be kept per image after NMS
step. -1 means keeping all bboxes after NMS step.
nms_threshold (float): The threshold to be used in NMS. Default: 0.3
nms_eta (float): The threshold to be used in NMS. Default: 1.0
normalized (bool): Whether detections are normalized. Default: True
name(str): Name of the locality aware nms op, please refer to :ref:`api_guide_Name` .
Default: None.
Returns:
Variable: A 2-D LoDTensor with shape [No, 6] represents the detections.
Each row has 6 values: [label, confidence, xmin, ymin, xmax, ymax]
or A 2-D LoDTensor with shape [No, 10] represents the detections.
Each row has 10 values:
[label, confidence, x1, y1, x2, y2, x3, y3, x4, y4]. No is the
total number of detections. If there is no detected boxes for all
images, lod will be set to {1} and Out only contains one value
which is -1.
(After version 1.3, when no boxes detected, the lod is changed
from {0} to {1}). The data type is float32 or float64.
Examples:
.. code-block:: python
import paddle.fluid as fluid
boxes = fluid.data(name='bboxes', shape=[None, 81, 8],
dtype='float32')
scores = fluid.data(name='scores', shape=[None, 1, 81],
dtype='float32')
out = fluid.layers.locality_aware_nms(bboxes=boxes,
scores=scores,
score_threshold=0.5,
nms_top_k=400,
nms_threshold=0.3,
keep_top_k=200,
normalized=False)
**Matrix NMS**
This operator does matrix non maximum suppression (NMS).
First selects a subset of candidate bounding boxes that have higher scores
than score_threshold (if provided), then the top k candidate is selected if
nms_top_k is larger than -1. Score of the remaining candidate are then
decayed according to the Matrix NMS scheme.
Aftern NMS step, at most keep_top_k number of total bboxes are to be kept
per image if keep_top_k is larger than -1.
Args:
bboxes (Variable): A 3-D Tensor with shape [N, M, 4] represents the
predicted locations of M bounding bboxes,
N is the batch size. Each bounding box has four
coordinate values and the layout is
[xmin, ymin, xmax, ymax], when box size equals to 4.
The data type is float32 or float64.
scores (Variable): A 3-D Tensor with shape [N, C, M]
represents the predicted confidence predictions.
N is the batch size, C is the class number, M is
number of bounding boxes. For each category there
are total M scores which corresponding M bounding
boxes. Please note, M is equal to the 2nd dimension
of BBoxes. The data type is float32 or float64.
score_threshold (float): Threshold to filter out bounding boxes with
low confidence score.
post_threshold (float): Threshold to filter out bounding boxes with
low confidence score AFTER decaying.
nms_top_k (int): Maximum number of detections to be kept according to
the confidences after the filtering detections based
on score_threshold.
keep_top_k (int): Number of total bboxes to be kept per image after NMS
step. -1 means keeping all bboxes after NMS step.
use_gaussian (bool): Use Gaussian as the decay function. Default: False
gaussian_sigma (float): Sigma for Gaussian decay function. Default: 2.0
background_label (int): The index of background label, the background
label will be ignored. If set to -1, then all
categories will be considered. Default: 0
normalized (bool): Whether detections are normalized. Default: True
return_index(bool): Whether return selected index. Default: False
name(str): Name of the matrix nms op. Default: None.
Returns:
A tuple with two Variables: (Out, Index) if return_index is True,
otherwise, one Variable(Out) is returned.
Out (Variable): A 2-D LoDTensor with shape [No, 6] containing the
detection results.
Each row has 6 values: [label, confidence, xmin, ymin, xmax, ymax]
(After version 1.3, when no boxes detected, the lod is changed
from {0} to {1})
Index (Variable): A 2-D LoDTensor with shape [No, 1] containing the
selected indices, which are absolute values cross batches.
Examples:
.. code-block:: python
import paddle.fluid as fluid
boxes = fluid.data(name='bboxes', shape=[None,81, 4],
dtype='float32', lod_level=1)
scores = fluid.data(name='scores', shape=[None,81],
dtype='float32', lod_level=1)
out = fluid.layers.matrix_nms(bboxes=boxes,
scores=scores,
background_label=0,
score_threshold=0.5,
post_threshold=0.1,
nms_top_k=400,
keep_top_k=200,
normalized=False)
:api_attr: Static Graph
Base on SSD ((Single Shot MultiBox Detector) algorithm, generate prior boxes,
regression location and classification confidence on multiple input feature
maps, then output the concatenate results. The details of this algorithm,
please refer the section 2.2 of SSD paper `SSD: Single Shot MultiBox Detector
<https://arxiv.org/abs/1512.02325>`_ .
Args:
inputs (list(Variable)|tuple(Variable)): The list of input variables,
the format of all Variables are 4-D Tensor, layout is NCHW.
Data type should be float32 or float64.
image (Variable): The input image, layout is NCHW. Data type should be
the same as inputs.
base_size(int): the base_size is input image size. When len(inputs) > 2
and `min_size` and `max_size` are None, the `min_size` and `max_size`
are calculated by `baze_size`, 'min_ratio' and `max_ratio`. The
formula is as follows:
.. code-block:: text
min_sizes = []
max_sizes = []
step = int(math.floor(((max_ratio - min_ratio)) / (num_layer - 2)))
for ratio in six.moves.range(min_ratio, max_ratio + 1, step):
min_sizes.append(base_size * ratio / 100.)
max_sizes.append(base_size * (ratio + step) / 100.)
min_sizes = [base_size * .10] + min_sizes
max_sizes = [base_size * .20] + max_sizes
num_classes(int): The number of classes.
aspect_ratios(list(float) | tuple(float)): the aspect ratios of generated
prior boxes. The length of input and aspect_ratios must be equal.
min_ratio(int): the min ratio of generated prior boxes.
max_ratio(int): the max ratio of generated prior boxes.
min_sizes(list|tuple|None): If `len(inputs) <=2`,
min_sizes must be set up, and the length of min_sizes
should equal to the length of inputs. Default: None.
max_sizes(list|tuple|None): If `len(inputs) <=2`,
max_sizes must be set up, and the length of min_sizes
should equal to the length of inputs. Default: None.
steps(list|tuple): If step_w and step_h are the same,
step_w and step_h can be replaced by steps.
step_w(list|tuple): Prior boxes step
across width. If step_w[i] == 0.0, the prior boxes step
across width of the inputs[i] will be automatically
calculated. Default: None.
step_h(list|tuple): Prior boxes step across height, If
step_h[i] == 0.0, the prior boxes step across height of
the inputs[i] will be automatically calculated. Default: None.
offset(float): Prior boxes center offset. Default: 0.5
variance(list|tuple): the variances to be encoded in prior boxes.
Default:[0.1, 0.1, 0.2, 0.2].
flip(bool): Whether to flip aspect ratios. Default:False.
clip(bool): Whether to clip out-of-boundary boxes. Default: False.
kernel_size(int): The kernel size of conv2d. Default: 1.
pad(int|list|tuple): The padding of conv2d. Default:0.
stride(int|list|tuple): The stride of conv2d. Default:1,
name(str): The default value is None. Normally there is no need
for user to set this property. For more information, please
refer to :ref:`api_guide_Name`.
min_max_aspect_ratios_order(bool): If set True, the output prior box is
in order of [min, max, aspect_ratios], which is consistent with
Caffe. Please note, this order affects the weights order of
convolution layer followed by and does not affect the final
detection results. Default: False.
Returns:
tuple: A tuple with four Variables. (mbox_loc, mbox_conf, boxes, variances)
mbox_loc (Variable): The predicted boxes' location of the inputs. The
layout is [N, num_priors, 4], where N is batch size, ``num_priors``
is the number of prior boxes. Data type is the same as input.
mbox_conf (Variable): The predicted boxes' confidence of the inputs.
The layout is [N, num_priors, C], where ``N`` and ``num_priors``
has the same meaning as above. C is the number of Classes.
Data type is the same as input.
boxes (Variable): the output prior boxes. The layout is [num_priors, 4].
The meaning of num_priors is the same as above.
Data type is the same as input.
variances (Variable): the expanded variances for prior boxes.
The layout is [num_priors, 4]. Data type is the same as input.
Examples 1: set min_ratio and max_ratio:
.. code-block:: python
import paddle.fluid as fluid
images = fluid.data(name='data', shape=[None, 3, 300, 300], dtype='float32')
conv1 = fluid.data(name='conv1', shape=[None, 512, 19, 19], dtype='float32')
conv2 = fluid.data(name='conv2', shape=[None, 1024, 10, 10], dtype='float32')
conv3 = fluid.data(name='conv3', shape=[None, 512, 5, 5], dtype='float32')
conv4 = fluid.data(name='conv4', shape=[None, 256, 3, 3], dtype='float32')
conv5 = fluid.data(name='conv5', shape=[None, 256, 2, 2], dtype='float32')
conv6 = fluid.data(name='conv6', shape=[None, 128, 1, 1], dtype='float32')
mbox_locs, mbox_confs, box, var = fluid.layers.multi_box_head(
inputs=[conv1, conv2, conv3, conv4, conv5, conv6],
image=images,
num_classes=21,
min_ratio=20,
max_ratio=90,
aspect_ratios=[[2.], [2., 3.], [2., 3.], [2., 3.], [2.], [2.]],
base_size=300,
offset=0.5,
flip=True,
clip=True)
Examples 2: set min_sizes and max_sizes:
.. code-block:: python
import paddle.fluid as fluid
images = fluid.data(name='data', shape=[None, 3, 300, 300], dtype='float32')
conv1 = fluid.data(name='conv1', shape=[None, 512, 19, 19], dtype='float32')
conv2 = fluid.data(name='conv2', shape=[None, 1024, 10, 10], dtype='float32')
conv3 = fluid.data(name='conv3', shape=[None, 512, 5, 5], dtype='float32')
conv4 = fluid.data(name='conv4', shape=[None, 256, 3, 3], dtype='float32')
conv5 = fluid.data(name='conv5', shape=[None, 256, 2, 2], dtype='float32')
conv6 = fluid.data(name='conv6', shape=[None, 128, 1, 1], dtype='float32')
mbox_locs, mbox_confs, box, var = fluid.layers.multi_box_head(
inputs=[conv1, conv2, conv3, conv4, conv5, conv6],
image=images,
num_classes=21,
min_sizes=[60.0, 105.0, 150.0, 195.0, 240.0, 285.0],
max_sizes=[[], 150.0, 195.0, 240.0, 285.0, 300.0],
aspect_ratios=[[2.], [2., 3.], [2., 3.], [2., 3.], [2.], [2.]],
base_size=300,
offset=0.5,
flip=True,
clip=True)
:alias_main: paddle.nn.functional.multiclass_nms
:alias: paddle.nn.functional.multiclass_nms,paddle.nn.functional.extension.multiclass_nms
:old_api: paddle.fluid.layers.multiclass_nms
**Multiclass NMS**
This operator is to do multi-class non maximum suppression (NMS) on
boxes and scores.
In the NMS step, this operator greedily selects a subset of detection bounding
boxes that have high scores larger than score_threshold, if providing this
threshold, then selects the largest nms_top_k confidences scores if nms_top_k
is larger than -1. Then this operator pruns away boxes that have high IOU
(intersection over union) overlap with already selected boxes by adaptive
threshold NMS based on parameters of nms_threshold and nms_eta.
Aftern NMS step, at most keep_top_k number of total bboxes are to be kept
per image if keep_top_k is larger than -1.
See below for an example:
.. code-block:: text
if:
box1.data = (2.0, 3.0, 7.0, 5.0) format is (xmin, ymin, xmax, ymax)
box1.scores = (0.7, 0.2, 0.4) which is (label0.score=0.7, label1.score=0.2, label2.cores=0.4)
box2.data = (3.0, 4.0, 8.0, 5.0)
box2.score = (0.3, 0.3, 0.1)
nms_threshold = 0.3
background_label = 0
score_threshold = 0
Then:
iou = 4/11 > 0.3
out.data = [[1, 0.3, 3.0, 4.0, 8.0, 5.0],
[2, 0.4, 2.0, 3.0, 7.0, 5.0]]
Out format is (label, confidence, xmin, ymin, xmax, ymax)
Args:
bboxes (Variable): Two types of bboxes are supported:
1. (Tensor) A 3-D Tensor with shape
[N, M, 4 or 8 16 24 32] represents the
predicted locations of M bounding bboxes,
N is the batch size. Each bounding box has four
coordinate values and the layout is
[xmin, ymin, xmax, ymax], when box size equals to 4.
The data type is float32 or float64.
2. (LoDTensor) A 3-D Tensor with shape [M, C, 4]
M is the number of bounding boxes, C is the
class number. The data type is float32 or float64.
scores (Variable): Two types of scores are supported:
1. (Tensor) A 3-D Tensor with shape [N, C, M]
represents the predicted confidence predictions.
N is the batch size, C is the class number, M is
number of bounding boxes. For each category there
are total M scores which corresponding M bounding
boxes. Please note, M is equal to the 2nd dimension
of BBoxes.The data type is float32 or float64.
2. (LoDTensor) A 2-D LoDTensor with shape [M, C].
M is the number of bbox, C is the class number.
In this case, input BBoxes should be the second
case with shape [M, C, 4].The data type is float32 or float64.
background_label (int): The index of background label, the background
label will be ignored. If set to -1, then all
categories will be considered. Default: 0
score_threshold (float): Threshold to filter out bounding boxes with
low confidence score. If not provided,
consider all boxes.
nms_top_k (int): Maximum number of detections to be kept according to
the confidences after the filtering detections based
on score_threshold.
nms_threshold (float): The threshold to be used in NMS. Default: 0.3
nms_eta (float): The threshold to be used in NMS. Default: 1.0
keep_top_k (int): Number of total bboxes to be kept per image after NMS
step. -1 means keeping all bboxes after NMS step.
normalized (bool): Whether detections are normalized. Default: True
name(str): Name of the multiclass nms op. Default: None.
Returns:
Variable: A 2-D LoDTensor with shape [No, 6] represents the detections.
Each row has 6 values: [label, confidence, xmin, ymin, xmax, ymax]
or A 2-D LoDTensor with shape [No, 10] represents the detections.
Each row has 10 values:
[label, confidence, x1, y1, x2, y2, x3, y3, x4, y4]. No is the
total number of detections. If there is no detected boxes for all
images, lod will be set to {1} and Out only contains one value
which is -1.
(After version 1.3, when no boxes detected, the lod is changed
from {0} to {1})
Examples:
.. code-block:: python
import paddle.fluid as fluid
boxes = fluid.data(name='bboxes', shape=[None,81, 4],
dtype='float32', lod_level=1)
scores = fluid.data(name='scores', shape=[None,81],
dtype='float32', lod_level=1)
out = fluid.layers.multiclass_nms(bboxes=boxes,
scores=scores,
background_label=0,
score_threshold=0.5,
nms_top_k=400,
nms_threshold=0.3,
keep_top_k=200,
normalized=False)
${comment}
Args:
input(Variable): The input with shape [batch_size, geometry_channels, height, width].
A Tensor with type float32, float64.
name(str, Optional): For details, please refer to :ref:`api_guide_Name`.
Generally, no setting is required. Default: None.
Returns:
Variable: The output with the same shape as input. A Tensor with type float32, float64.
Examples:
.. code-block:: python
import paddle.fluid as fluid
input = fluid.data(name='input', shape=[4, 10, 5, 5], dtype='float32')
out = fluid.layers.polygon_box_transform(input)
:alias_main: paddle.nn.functional.prior_box
:alias: paddle.nn.functional.prior_box,paddle.nn.functional.vision.prior_box
:old_api: paddle.fluid.layers.prior_box
This op generates prior boxes for SSD(Single Shot MultiBox Detector) algorithm.
Each position of the input produce N prior boxes, N is determined by
the count of min_sizes, max_sizes and aspect_ratios, The size of the
box is in range(min_size, max_size) interval, which is generated in
sequence according to the aspect_ratios.
Parameters:
input(Variable): 4-D tensor(NCHW), the data type should be float32 or float64.
image(Variable): 4-D tensor(NCHW), the input image data of PriorBoxOp,
the data type should be float32 or float64.
min_sizes(list|tuple|float): the min sizes of generated prior boxes.
max_sizes(list|tuple|None): the max sizes of generated prior boxes.
Default: None.
aspect_ratios(list|tuple|float): the aspect ratios of generated
prior boxes. Default: [1.].
variance(list|tuple): the variances to be encoded in prior boxes.
Default:[0.1, 0.1, 0.2, 0.2].
flip(bool): Whether to flip aspect ratios. Default:False.
clip(bool): Whether to clip out-of-boundary boxes. Default: False.
step(list|tuple): Prior boxes step across width and height, If
step[0] equals to 0.0 or step[1] equals to 0.0, the prior boxes step across
height or weight of the input will be automatically calculated.
Default: [0., 0.]
offset(float): Prior boxes center offset. Default: 0.5
min_max_aspect_ratios_order(bool): If set True, the output prior box is
in order of [min, max, aspect_ratios], which is consistent with
Caffe. Please note, this order affects the weights order of
convolution layer followed by and does not affect the final
detection results. Default: False.
name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`
Returns:
Tuple: A tuple with two Variable (boxes, variances)
boxes(Variable): the output prior boxes of PriorBox.
4-D tensor, the layout is [H, W, num_priors, 4].
H is the height of input, W is the width of input,
num_priors is the total box count of each position of input.
variances(Variable): the expanded variances of PriorBox.
4-D tensor, the layput is [H, W, num_priors, 4].
H is the height of input, W is the width of input
num_priors is the total box count of each position of input
Examples:
.. code-block:: python
#declarative mode
import paddle.fluid as fluid
import numpy as np
input = fluid.data(name="input", shape=[None,3,6,9])
image = fluid.data(name="image", shape=[None,3,9,12])
box, var = fluid.layers.prior_box(
input=input,
image=image,
min_sizes=[100.],
clip=True,
flip=True)
place = fluid.CPUPlace()
exe = fluid.Executor(place)
exe.run(fluid.default_startup_program())
# prepare a batch of data
input_data = np.random.rand(1,3,6,9).astype("float32")
image_data = np.random.rand(1,3,9,12).astype("float32")
box_out, var_out = exe.run(fluid.default_main_program(),
feed={"input":input_data,"image":image_data},
fetch_list=[box,var],
return_numpy=True)
# print(box_out.shape)
# (6, 9, 1, 4)
# print(var_out.shape)
# (6, 9, 1, 4)
# imperative mode
import paddle.fluid.dygraph as dg
with dg.guard(place) as g:
input = dg.to_variable(input_data)
image = dg.to_variable(image_data)
box, var = fluid.layers.prior_box(
input=input,
image=image,
min_sizes=[100.],
clip=True,
flip=True)
# print(box.shape)
# [6L, 9L, 1L, 4L]
# print(var.shape)
# [6L, 9L, 1L, 4L]
**Detection Output Layer for the detector RetinaNet.**
In the detector `RetinaNet <https://arxiv.org/abs/1708.02002>`_ , many
`FPN <https://arxiv.org/abs/1612.03144>`_ levels output the category
and location predictions, this OP is to get the detection results by
performing following steps:
1. For each FPN level, decode box predictions according to the anchor
boxes from at most :attr:`nms_top_k` top-scoring predictions after
thresholding detector confidence at :attr:`score_threshold`.
2. Merge top predictions from all levels and apply multi-class non
maximum suppression (NMS) on them to get the final detections.
Args:
bboxes(List): A list of Tensors from multiple FPN levels represents
the location prediction for all anchor boxes. Each element is
a 3-D Tensor with shape :math:`[N, Mi, 4]`, :math:`N` is the
batch size, :math:`Mi` is the number of bounding boxes from
:math:`i`-th FPN level and each bounding box has four coordinate
values and the layout is [xmin, ymin, xmax, ymax]. The data type
of each element is float32 or float64.
scores(List): A list of Tensors from multiple FPN levels represents
the category prediction for all anchor boxes. Each element is a
3-D Tensor with shape :math:`[N, Mi, C]`, :math:`N` is the batch
size, :math:`C` is the class number (**excluding background**),
:math:`Mi` is the number of bounding boxes from :math:`i`-th FPN
level. The data type of each element is float32 or float64.
anchors(List): A list of Tensors from multiple FPN levels represents
the locations of all anchor boxes. Each element is a 2-D Tensor
with shape :math:`[Mi, 4]`, :math:`Mi` is the number of bounding
boxes from :math:`i`-th FPN level, and each bounding box has four
coordinate values and the layout is [xmin, ymin, xmax, ymax].
The data type of each element is float32 or float64.
im_info(Variable): A 2-D Tensor with shape :math:`[N, 3]` represents the size
information of input images. :math:`N` is the batch size, the size
information of each image is a 3-vector which are the height and width
of the network input along with the factor scaling the origin image to
the network input. The data type of :attr:`im_info` is float32.
score_threshold(float): Threshold to filter out bounding boxes
with a confidence score before NMS, default value is set to 0.05.
nms_top_k(int): Maximum number of detections per FPN layer to be
kept according to the confidences before NMS, default value is set to
1000.
keep_top_k(int): Number of total bounding boxes to be kept per image after
NMS step. Default value is set to 100, -1 means keeping all bounding
boxes after NMS step.
nms_threshold(float): The Intersection-over-Union(IoU) threshold used to
filter out boxes in NMS.
nms_eta(float): The parameter for adjusting :attr:`nms_threshold` in NMS.
Default value is set to 1., which represents the value of
:attr:`nms_threshold` keep the same in NMS. If :attr:`nms_eta` is set
to be lower than 1. and the value of :attr:`nms_threshold` is set to
be higher than 0.5, everytime a bounding box is filtered out,
the adjustment for :attr:`nms_threshold` like :attr:`nms_threshold`
= :attr:`nms_threshold` * :attr:`nms_eta` will not be stopped until
the actual value of :attr:`nms_threshold` is lower than or equal to
0.5.
**Notice**: In some cases where the image sizes are very small, it's possible
that there is no detection if :attr:`score_threshold` are used at all
levels. Hence, this OP do not filter out anchors from the highest FPN level
before NMS. And the last element in :attr:`bboxes`:, :attr:`scores` and
:attr:`anchors` is required to be from the highest FPN level.
Returns:
Variable(The data type is float32 or float64):
The detection output is a 1-level LoDTensor with shape :math:`[No, 6]`.
Each row has six values: [label, confidence, xmin, ymin, xmax, ymax].
:math:`No` is the total number of detections in this mini-batch.
The :math:`i`-th image has `LoD[i + 1] - LoD[i]` detected
results, if `LoD[i + 1] - LoD[i]` is 0, the :math:`i`-th image
has no detected results. If all images have no detected results,
LoD will be set to 0, and the output tensor is empty (None).
Examples:
.. code-block:: python
import paddle.fluid as fluid
bboxes_low = fluid.data(
name='bboxes_low', shape=[1, 44, 4], dtype='float32')
bboxes_high = fluid.data(
name='bboxes_high', shape=[1, 11, 4], dtype='float32')
scores_low = fluid.data(
name='scores_low', shape=[1, 44, 10], dtype='float32')
scores_high = fluid.data(
name='scores_high', shape=[1, 11, 10], dtype='float32')
anchors_low = fluid.data(
name='anchors_low', shape=[44, 4], dtype='float32')
anchors_high = fluid.data(
name='anchors_high', shape=[11, 4], dtype='float32')
im_info = fluid.data(
name="im_info", shape=[1, 3], dtype='float32')
nmsed_outs = fluid.layers.retinanet_detection_output(
bboxes=[bboxes_low, bboxes_high],
scores=[scores_low, scores_high],
anchors=[anchors_low, anchors_high],
im_info=im_info,
score_threshold=0.05,
nms_top_k=1000,
keep_top_k=100,
nms_threshold=0.45,
nms_eta=1.0)
**Target Assign Layer for the detector RetinaNet.**
This OP finds out positive and negative samples from all anchors
for training the detector `RetinaNet <https://arxiv.org/abs/1708.02002>`_ ,
and assigns target labels for classification along with target locations for
regression to each sample, then takes out the part belonging to positive and
negative samples from category prediction( :attr:`cls_logits`) and location
prediction( :attr:`bbox_pred`) which belong to all anchors.
The searching principles for positive and negative samples are as followed:
1. Anchors are assigned to ground-truth boxes when it has the highest IoU
overlap with a ground-truth box.
2. Anchors are assigned to ground-truth boxes when it has an IoU overlap
higher than :attr:`positive_overlap` with any ground-truth box.
3. Anchors are assigned to background when its IoU overlap is lower than
:attr:`negative_overlap` for all ground-truth boxes.
4. Anchors which do not meet the above conditions do not participate in
the training process.
Retinanet predicts a :math:`C`-vector for classification and a 4-vector for box
regression for each anchor, hence the target label for each positive(or negative)
sample is a :math:`C`-vector and the target locations for each positive sample
is a 4-vector. As for a positive sample, if the category of its assigned
ground-truth box is class :math:`i`, the corresponding entry in its length
:math:`C` label vector is set to 1 and all other entries is set to 0, its box
regression targets are computed as the offset between itself and its assigned
ground-truth box. As for a negative sample, all entries in its length :math:`C`
label vector are set to 0 and box regression targets are omitted because
negative samples do not participate in the training process of location
regression.
After the assignment, the part belonging to positive and negative samples is
taken out from category prediction( :attr:`cls_logits` ), and the part
belonging to positive samples is taken out from location
prediction( :attr:`bbox_pred` ).
Args:
bbox_pred(Variable): A 3-D Tensor with shape :math:`[N, M, 4]` represents
the predicted locations of all anchors. :math:`N` is the batch size( the
number of images in a mini-batch), :math:`M` is the number of all anchors
of one image, and each anchor has 4 coordinate values. The data type of
:attr:`bbox_pred` is float32 or float64.
cls_logits(Variable): A 3-D Tensor with shape :math:`[N, M, C]` represents
the predicted categories of all anchors. :math:`N` is the batch size,
:math:`M` is the number of all anchors of one image, and :math:`C` is
the number of categories (**Notice: excluding background**). The data type
of :attr:`cls_logits` is float32 or float64.
anchor_box(Variable): A 2-D Tensor with shape :math:`[M, 4]` represents
the locations of all anchors. :math:`M` is the number of all anchors of
one image, each anchor is represented as :math:`[xmin, ymin, xmax, ymax]`,
:math:`[xmin, ymin]` is the left top coordinate of the anchor box,
:math:`[xmax, ymax]` is the right bottom coordinate of the anchor box.
The data type of :attr:`anchor_box` is float32 or float64. Please refer
to the OP :ref:`api_fluid_layers_anchor_generator`
for the generation of :attr:`anchor_box`.
anchor_var(Variable): A 2-D Tensor with shape :math:`[M,4]` represents the expanded
factors of anchor locations used in loss function. :math:`M` is number of
all anchors of one image, each anchor possesses a 4-vector expanded factor.
The data type of :attr:`anchor_var` is float32 or float64. Please refer
to the OP :ref:`api_fluid_layers_anchor_generator`
for the generation of :attr:`anchor_var`.
gt_boxes(Variable): A 1-level 2-D LoDTensor with shape :math:`[G, 4]` represents
locations of all ground-truth boxes. :math:`G` is the total number of
all ground-truth boxes in a mini-batch, and each ground-truth box has 4
coordinate values. The data type of :attr:`gt_boxes` is float32 or
float64.
gt_labels(variable): A 1-level 2-D LoDTensor with shape :math:`[G, 1]` represents
categories of all ground-truth boxes, and the values are in the range of
:math:`[1, C]`. :math:`G` is the total number of all ground-truth boxes
in a mini-batch, and each ground-truth box has one category. The data type
of :attr:`gt_labels` is int32.
is_crowd(Variable): A 1-level 1-D LoDTensor with shape :math:`[G]` which
indicates whether a ground-truth box is a crowd. If the value is 1, the
corresponding box is a crowd, it is ignored during training. :math:`G` is
the total number of all ground-truth boxes in a mini-batch. The data type
of :attr:`is_crowd` is int32.
im_info(Variable): A 2-D Tensor with shape [N, 3] represents the size
information of input images. :math:`N` is the batch size, the size
information of each image is a 3-vector which are the height and width
of the network input along with the factor scaling the origin image to
the network input. The data type of :attr:`im_info` is float32.
num_classes(int32): The number of categories for classification, the default
value is 1.
positive_overlap(float32): Minimum overlap required between an anchor
and ground-truth box for the anchor to be a positive sample, the default
value is 0.5.
negative_overlap(float32): Maximum overlap allowed between an anchor
and ground-truth box for the anchor to be a negative sample, the default
value is 0.4. :attr:`negative_overlap` should be less than or equal to
:attr:`positive_overlap`, if not, the actual value of
:attr:`positive_overlap` is :attr:`negative_overlap`.
Returns:
A tuple with 6 Variables:
**predict_scores** (Variable): A 2-D Tensor with shape :math:`[F+B, C]` represents
category prediction belonging to positive and negative samples. :math:`F`
is the number of positive samples in a mini-batch, :math:`B` is the number
of negative samples, and :math:`C` is the number of categories
(**Notice: excluding background**). The data type of :attr:`predict_scores`
is float32 or float64.
**predict_location** (Variable): A 2-D Tensor with shape :math:`[F, 4]` represents
location prediction belonging to positive samples. :math:`F` is the number
of positive samples. :math:`F` is the number of positive samples, and each
sample has 4 coordinate values. The data type of :attr:`predict_location`
is float32 or float64.
**target_label** (Variable): A 2-D Tensor with shape :math:`[F+B, 1]` represents
target labels for classification belonging to positive and negative
samples. :math:`F` is the number of positive samples, :math:`B` is the
number of negative, and each sample has one target category. The data type
of :attr:`target_label` is int32.
**target_bbox** (Variable): A 2-D Tensor with shape :math:`[F, 4]` represents
target locations for box regression belonging to positive samples.
:math:`F` is the number of positive samples, and each sample has 4
coordinate values. The data type of :attr:`target_bbox` is float32 or
float64.
**bbox_inside_weight** (Variable): A 2-D Tensor with shape :math:`[F, 4]`
represents whether a positive sample is fake positive, if a positive
sample is false positive, the corresponding entries in
:attr:`bbox_inside_weight` are set 0, otherwise 1. :math:`F` is the number
of total positive samples in a mini-batch, and each sample has 4
coordinate values. The data type of :attr:`bbox_inside_weight` is float32
or float64.
**fg_num** (Variable): A 2-D Tensor with shape :math:`[N, 1]` represents the number
of positive samples. :math:`N` is the batch size. **Notice: The number
of positive samples is used as the denominator of later loss function,
to avoid the condition that the denominator is zero, this OP has added 1
to the actual number of positive samples of each image.** The data type of
:attr:`fg_num` is int32.
Examples:
.. code-block:: python
import paddle.fluid as fluid
bbox_pred = fluid.data(name='bbox_pred', shape=[1, 100, 4],
dtype='float32')
cls_logits = fluid.data(name='cls_logits', shape=[1, 100, 10],
dtype='float32')
anchor_box = fluid.data(name='anchor_box', shape=[100, 4],
dtype='float32')
anchor_var = fluid.data(name='anchor_var', shape=[100, 4],
dtype='float32')
gt_boxes = fluid.data(name='gt_boxes', shape=[10, 4],
dtype='float32')
gt_labels = fluid.data(name='gt_labels', shape=[10, 1],
dtype='int32')
is_crowd = fluid.data(name='is_crowd', shape=[1],
dtype='int32')
im_info = fluid.data(name='im_info', shape=[1, 3],
dtype='float32')
score_pred, loc_pred, score_target, loc_target, bbox_inside_weight, fg_num = \
fluid.layers.retinanet_target_assign(bbox_pred, cls_logits, anchor_box,
anchor_var, gt_boxes, gt_labels, is_crowd, im_info, 10)
**The** `rois` **of this op should be a LoDTensor.**
ROI perspective transform op applies perspective transform to map each roi into an
rectangular region. Perspective transform is a type of transformation in linear algebra.
Parameters:
input (Variable): 4-D Tensor, input of ROIPerspectiveTransformOp. The format of
input tensor is NCHW. Where N is batch size, C is the
number of input channels, H is the height of the feature,
and W is the width of the feature. The data type is float32.
rois (Variable): 2-D LoDTensor, ROIs (Regions of Interest) to be transformed.
It should be a 2-D LoDTensor of shape (num_rois, 8). Given as
[[x1, y1, x2, y2, x3, y3, x4, y4], ...], (x1, y1) is the
top left coordinates, and (x2, y2) is the top right
coordinates, and (x3, y3) is the bottom right coordinates,
and (x4, y4) is the bottom left coordinates. The data type is the
same as `input`
transformed_height (int): The height of transformed output.
transformed_width (int): The width of transformed output.
spatial_scale (float): Spatial scale factor to scale ROI coords. Default: 1.0
name(str, optional): The default value is None.
Normally there is no need for user to set this property.
For more information, please refer to :ref:`api_guide_Name`
Returns:
A tuple with three Variables. (out, mask, transform_matrix)
out: The output of ROIPerspectiveTransformOp which is a 4-D tensor with shape
(num_rois, channels, transformed_h, transformed_w). The data type is the same as `input`
mask: The mask of ROIPerspectiveTransformOp which is a 4-D tensor with shape
(num_rois, 1, transformed_h, transformed_w). The data type is int32
transform_matrix: The transform matrix of ROIPerspectiveTransformOp which is
a 2-D tensor with shape (num_rois, 9). The data type is the same as `input`
Return Type:
tuple
Examples:
.. code-block:: python
import paddle.fluid as fluid
x = fluid.data(name='x', shape=[100, 256, 28, 28], dtype='float32')
rois = fluid.data(name='rois', shape=[None, 8], lod_level=1, dtype='float32')
out, mask, transform_matrix = fluid.layers.roi_perspective_transform(x, rois, 7, 7, 1.0)
**Target Assign Layer for region proposal network (RPN) in Faster-RCNN detection.**
This layer can be, for given the Intersection-over-Union (IoU) overlap
between anchors and ground truth boxes, to assign classification and
regression targets to each each anchor, these target labels are used for
train RPN. The classification targets is a binary class label (of being
an object or not). Following the paper of Faster-RCNN, the positive labels
are two kinds of anchors: (i) the anchor/anchors with the highest IoU
overlap with a ground-truth box, or (ii) an anchor that has an IoU overlap
higher than rpn_positive_overlap(0.7) with any ground-truth box. Note
that a single ground-truth box may assign positive labels to multiple
anchors. A non-positive anchor is when its IoU ratio is lower than
rpn_negative_overlap (0.3) for all ground-truth boxes. Anchors that are
neither positive nor negative do not contribute to the training objective.
The regression targets are the encoded ground-truth boxes associated with
the positive anchors.
Args:
bbox_pred(Variable): A 3-D Tensor with shape [N, M, 4] represents the
predicted locations of M bounding bboxes. N is the batch size,
and each bounding box has four coordinate values and the layout
is [xmin, ymin, xmax, ymax]. The data type can be float32 or float64.
cls_logits(Variable): A 3-D Tensor with shape [N, M, 1] represents the
predicted confidence predictions. N is the batch size, 1 is the
frontground and background sigmoid, M is number of bounding boxes.
The data type can be float32 or float64.
anchor_box(Variable): A 2-D Tensor with shape [M, 4] holds M boxes,
each box is represented as [xmin, ymin, xmax, ymax],
[xmin, ymin] is the left top coordinate of the anchor box,
if the input is image feature map, they are close to the origin
of the coordinate system. [xmax, ymax] is the right bottom
coordinate of the anchor box. The data type can be float32 or float64.
anchor_var(Variable): A 2-D Tensor with shape [M,4] holds expanded
variances of anchors. The data type can be float32 or float64.
gt_boxes (Variable): The ground-truth bounding boxes (bboxes) are a 2D
LoDTensor with shape [Ng, 4], Ng is the total number of ground-truth
bboxes of mini-batch input. The data type can be float32 or float64.
is_crowd (Variable): A 1-D LoDTensor which indicates groud-truth is crowd.
The data type must be int32.
im_info (Variable): A 2-D LoDTensor with shape [N, 3]. N is the batch size,
3 is the height, width and scale.
rpn_batch_size_per_im(int): Total number of RPN examples per image.
The data type must be int32.
rpn_straddle_thresh(float): Remove RPN anchors that go outside the image
by straddle_thresh pixels. The data type must be float32.
rpn_fg_fraction(float): Target fraction of RoI minibatch that is labeled
foreground (i.e. class > 0), 0-th class is background. The data type must be float32.
rpn_positive_overlap(float): Minimum overlap required between an anchor
and ground-truth box for the (anchor, gt box) pair to be a positive
example. The data type must be float32.
rpn_negative_overlap(float): Maximum overlap allowed between an anchor
and ground-truth box for the (anchor, gt box) pair to be a negative
examples. The data type must be float32.
Returns:
tuple:
A tuple(predicted_scores, predicted_location, target_label,
target_bbox, bbox_inside_weight) is returned. The predicted_scores
and predicted_location is the predicted result of the RPN.
The target_label and target_bbox is the ground truth,
respectively. The predicted_location is a 2D Tensor with shape
[F, 4], and the shape of target_bbox is same as the shape of
the predicted_location, F is the number of the foreground
anchors. The predicted_scores is a 2D Tensor with shape
[F + B, 1], and the shape of target_label is same as the shape
of the predicted_scores, B is the number of the background
anchors, the F and B is depends on the input of this operator.
Bbox_inside_weight represents whether the predicted loc is fake_fg
or not and the shape is [F, 4].
Examples:
.. code-block:: python
import paddle.fluid as fluid
bbox_pred = fluid.data(name='bbox_pred', shape=[None, 4], dtype='float32')
cls_logits = fluid.data(name='cls_logits', shape=[None, 1], dtype='float32')
anchor_box = fluid.data(name='anchor_box', shape=[None, 4], dtype='float32')
anchor_var = fluid.data(name='anchor_var', shape=[None, 4], dtype='float32')
gt_boxes = fluid.data(name='gt_boxes', shape=[None, 4], dtype='float32')
is_crowd = fluid.data(name='is_crowd', shape=[None], dtype='float32')
im_info = fluid.data(name='im_infoss', shape=[None, 3], dtype='float32')
loc, score, loc_target, score_target, inside_weight = fluid.layers.rpn_target_assign(
bbox_pred, cls_logits, anchor_box, anchor_var, gt_boxes, is_crowd, im_info)
:alias_main: paddle.nn.functional.sigmoid_focal_loss
:alias: paddle.nn.functional.sigmoid_focal_loss,paddle.nn.functional.loss.sigmoid_focal_loss
:old_api: paddle.fluid.layers.sigmoid_focal_loss
**Sigmoid Focal Loss Operator.**
`Focal Loss <https://arxiv.org/abs/1708.02002>`_ is used to address the foreground-background
class imbalance existed on the training phase of many computer vision tasks. This OP computes
the sigmoid value for each element in the input tensor :attr:`x`, after which focal loss is
measured between the sigmoid value and target label.
The focal loss is given as followed:
.. math::
\mathop{loss_{i,\,j}}\limits_{i\in\mathbb{[0,\,N-1]},\,j\in\mathbb{[0,\,C-1]}}=\left\{
\begin{array}{rcl}
- \frac{1}{fg\_num} * \alpha * {(1 - \sigma(x_{i,\,j}))}^{\gamma} * \log(\sigma(x_{i,\,j})) & & {(j +1) = label_{i,\,0}} \\
- \frac{1}{fg\_num} * (1 - \alpha) * {\sigma(x_{i,\,j})}^{ \gamma} * \log(1 - \sigma(x_{i,\,j})) & & {(j +1)!= label_{i,\,0}}
\end{array} \right.
We know that
.. math::
\sigma(x_j) = \frac{1}{1 + \exp(-x_j)}
Args:
x(Variable): A 2-D tensor with shape :math:`[N, C]` represents the predicted categories of
all samples. :math:`N` is the number of all samples responsible for optimization in
a mini-batch, for example, samples are anchor boxes for object detection and :math:`N`
is the total number of positive and negative samples in a mini-batch; Samples are images
for image classification and :math:`N` is the number of images in a mini-batch. :math:`C`
is the number of classes (**Notice: excluding background**). The data type of :attr:`x` is
float32 or float64.
label(Variable): A 2-D tensor with shape :math:`[N, 1]` represents the target labels for
classification. :math:`N` is the number of all samples responsible for optimization in a
mini-batch, each sample has one target category. The values for positive samples are in the
range of :math:`[1, C]`, and the values for negative samples are 0. The data type of :attr:`label`
is int32.
fg_num(Variable): A 1-D tensor with shape [1] represents the number of positive samples in a
mini-batch, which should be obtained before this OP. The data type of :attr:`fg_num` is int32.
gamma(int|float): Hyper-parameter to balance the easy and hard examples. Default value is
set to 2.0.
alpha(int|float): Hyper-parameter to balance the positive and negative example. Default value
is set to 0.25.
Returns:
Variable(the data type is float32 or float64):
A 2-D tensor with shape :math:`[N, C]`, which is the focal loss of each element in the input
tensor :attr:`x`.
Examples:
.. code-block:: python
import numpy as np
import paddle.fluid as fluid
num_classes = 10 # exclude background
image_width = 16
image_height = 16
batch_size = 32
max_iter = 20
def gen_train_data():
x_data = np.random.uniform(0, 255, (batch_size, 3, image_height,
image_width)).astype('float64')
label_data = np.random.randint(0, num_classes,
(batch_size, 1)).astype('int32')
return {"x": x_data, "label": label_data}
def get_focal_loss(pred, label, fg_num, num_classes):
pred = fluid.layers.reshape(pred, [-1, num_classes])
label = fluid.layers.reshape(label, [-1, 1])
label.stop_gradient = True
loss = fluid.layers.sigmoid_focal_loss(
pred, label, fg_num, gamma=2.0, alpha=0.25)
loss = fluid.layers.reduce_sum(loss)
return loss
def build_model(mode='train'):
x = fluid.data(name="x", shape=[-1, 3, -1, -1], dtype='float64')
output = fluid.layers.pool2d(input=x, pool_type='avg', global_pooling=True)
output = fluid.layers.fc(
input=output,
size=num_classes,
# Notice: size is set to be the number of target classes (excluding backgorund)
# because sigmoid activation will be done in the sigmoid_focal_loss op.
act=None)
if mode == 'train':
label = fluid.data(name="label", shape=[-1, 1], dtype='int32')
# Obtain the fg_num needed by the sigmoid_focal_loss op:
# 0 in label represents background, >=1 in label represents foreground,
# find the elements in label which are greater or equal than 1, then
# computed the numbers of these elements.
data = fluid.layers.fill_constant(shape=[1], value=1, dtype='int32')
fg_label = fluid.layers.greater_equal(label, data)
fg_label = fluid.layers.cast(fg_label, dtype='int32')
fg_num = fluid.layers.reduce_sum(fg_label)
fg_num.stop_gradient = True
avg_loss = get_focal_loss(output, label, fg_num, num_classes)
return avg_loss
else:
# During evaluating or testing phase,
# output of the final fc layer should be connected to a sigmoid layer.
pred = fluid.layers.sigmoid(output)
return pred
loss = build_model('train')
moment_optimizer = fluid.optimizer.MomentumOptimizer(
learning_rate=0.001, momentum=0.9)
moment_optimizer.minimize(loss)
place = fluid.CPUPlace()
exe = fluid.Executor(place)
exe.run(fluid.default_startup_program())
for i in range(max_iter):
outs = exe.run(feed=gen_train_data(), fetch_list=[loss.name])
print(outs)
:alias_main: paddle.nn.functional.ssd_loss
:alias: paddle.nn.functional.ssd_loss,paddle.nn.functional.loss.ssd_loss
:old_api: paddle.fluid.layers.ssd_loss
**Multi-box loss layer for object detection algorithm of SSD**
This layer is to compute detection loss for SSD given the location offset
predictions, confidence predictions, prior boxes and ground-truth bounding
boxes and labels, and the type of hard example mining. The returned loss
is a weighted sum of the localization loss (or regression loss) and
confidence loss (or classification loss) by performing the following steps:
1. Find matched bounding box by bipartite matching algorithm.
1.1 Compute IOU similarity between ground-truth boxes and prior boxes.
1.2 Compute matched bounding box by bipartite matching algorithm.
2. Compute confidence for mining hard examples
2.1. Get the target label based on matched indices.
2.2. Compute confidence loss.
3. Apply hard example mining to get the negative example indices and update
the matched indices.
4. Assign classification and regression targets
4.1. Encoded bbox according to the prior boxes.
4.2. Assign regression targets.
4.3. Assign classification targets.
5. Compute the overall objective loss.
5.1 Compute confidence loss.
5.2 Compute localization loss.
5.3 Compute the overall weighted loss.
Args:
location (Variable): The location predictions are a 3D Tensor with
shape [N, Np, 4], N is the batch size, Np is total number of
predictions for each instance. 4 is the number of coordinate values,
the layout is [xmin, ymin, xmax, ymax].The data type is float32 or
float64.
confidence (Variable): The confidence predictions are a 3D Tensor
with shape [N, Np, C], N and Np are the same as they are in
`location`, C is the class number.The data type is float32 or
float64.
gt_box (Variable): The ground-truth bounding boxes (bboxes) are a 2D
LoDTensor with shape [Ng, 4], Ng is the total number of ground-truth
bboxes of mini-batch input.The data type is float32 or float64.
gt_label (Variable): The ground-truth labels are a 2D LoDTensor
with shape [Ng, 1].Ng is the total number of ground-truth bboxes of
mini-batch input, 1 is the number of class. The data type is float32
or float64.
prior_box (Variable): The prior boxes are a 2D Tensor with shape [Np, 4].
Np and 4 are the same as they are in `location`. The data type is
float32 or float64.
prior_box_var (Variable): The variance of prior boxes are a 2D Tensor
with shape [Np, 4]. Np and 4 are the same as they are in `prior_box`
background_label (int): The index of background label, 0 by default.
overlap_threshold (float): If match_type is 'per_prediction', use
'overlap_threshold' to determine the extra matching bboxes when finding matched boxes. 0.5 by default.
neg_pos_ratio (float): The ratio of the negative boxes to the positive
boxes, used only when mining_type is 'max_negative', 3.0 by default.
neg_overlap (float): The negative overlap upper bound for the unmatched
predictions. Use only when mining_type is 'max_negative',
0.5 by default.
loc_loss_weight (float): Weight for localization loss, 1.0 by default.
conf_loss_weight (float): Weight for confidence loss, 1.0 by default.
match_type (str): The type of matching method during training, should
be 'bipartite' or 'per_prediction', 'per_prediction' by default.
mining_type (str): The hard example mining type, should be 'hard_example'
or 'max_negative', now only support `max_negative`.
normalize (bool): Whether to normalize the SSD loss by the total number
of output locations, True by default.
sample_size (int): The max sample size of negative box, used only when
mining_type is 'hard_example'.
Returns:
Variable(Tensor): The weighted sum of the localization loss and confidence loss, with shape [N * Np, 1], N and Np are the same as they are in
`location`.The data type is float32 or float64.
Raises:
ValueError: If mining_type is 'hard_example', now only support mining type of `max_negative`.
Examples:
.. code-block:: python
import paddle.fluid as fluid
pb = fluid.data(
name='prior_box',
shape=[10, 4],
dtype='float32')
pbv = fluid.data(
name='prior_box_var',
shape=[10, 4],
dtype='float32')
loc = fluid.data(name='target_box', shape=[10, 4], dtype='float32')
scores = fluid.data(name='scores', shape=[10, 21], dtype='float32')
gt_box = fluid.data(
name='gt_box', shape=[4], lod_level=1, dtype='float32')
gt_label = fluid.data(
name='gt_label', shape=[1], lod_level=1, dtype='float32')
loss = fluid.layers.ssd_loss(loc, scores, gt_box, gt_label, pb, pbv)
:alias_main: paddle.nn.functional.target_assign
:alias: paddle.nn.functional.target_assign,paddle.nn.functional.extension.target_assign
:old_api: paddle.fluid.layers.target_assign
This operator can be, for given the target bounding boxes or labels,
to assign classification and regression targets to each prediction as well as
weights to prediction. The weights is used to specify which prediction would
not contribute to training loss.
For each instance, the output `out` and`out_weight` are assigned based on
`match_indices` and `negative_indices`.
Assumed that the row offset for each instance in `input` is called lod,
this operator assigns classification/regression targets by performing the
following steps:
1. Assigning all outputs based on `match_indices`:
.. code-block:: text
If id = match_indices[i][j] > 0,
out[i][j][0 : K] = X[lod[i] + id][j % P][0 : K]
out_weight[i][j] = 1.
Otherwise,
out[j][j][0 : K] = {mismatch_value, mismatch_value, ...}
out_weight[i][j] = 0.
2. Assigning outputs based on `neg_indices` if `neg_indices` is provided:
Assumed that i-th instance in `neg_indices` is called `neg_indice`,
for i-th instance:
.. code-block:: text
for id in neg_indice:
out[i][id][0 : K] = {mismatch_value, mismatch_value, ...}
out_weight[i][id] = 1.0
Args:
input (Variable): This input is a 3D LoDTensor with shape [M, P, K].
Data type should be int32 or float32.
matched_indices (Variable): The input matched indices
is 2D Tenosr<int32> with shape [N, P], If MatchIndices[i][j] is -1,
the j-th entity of column is not matched to any entity of row in
i-th instance.
negative_indices (Variable, optional): The input negative example indices
are an optional input with shape [Neg, 1] and int32 type, where Neg is
the total number of negative example indices.
mismatch_value (float32, optional): Fill this value to the mismatched
location.
name (string): The default value is None. Normally there is no need for
user to set this property. For more information, please refer
to :ref:`api_guide_Name`.
Returns:
tuple: A tuple(out, out_weight) is returned.
out (Variable): a 3D Tensor with shape [N, P, K] and same data type
with `input`, N and P is the same as they are in `matched_indices`,
K is the same as it in input of X.
out_weight (Variable): the weight for output with the shape of [N, P, 1].
Data type is float32.
Examples:
.. code-block:: python
import paddle.fluid as fluid
x = fluid.data(
name='x',
shape=[4, 20, 4],
dtype='float',
lod_level=1)
matched_id = fluid.data(
name='indices',
shape=[8, 20],
dtype='int32')
trg, trg_weight = fluid.layers.target_assign(
x,
matched_id,
mismatch_value=0)
:alias_main: paddle.nn.functional.yolo_box
:alias: paddle.nn.functional.yolo_box,paddle.nn.functional.vision.yolo_box
:old_api: paddle.fluid.layers.yolo_box
${comment}
Args:
x (Variable): ${x_comment} The data type is float32 or float64.
img_size (Variable): ${img_size_comment} The data type is int32.
anchors (list|tuple): ${anchors_comment}
class_num (int): ${class_num_comment}
conf_thresh (float): ${conf_thresh_comment}
downsample_ratio (int): ${downsample_ratio_comment}
clip_bbox (bool): ${clip_bbox_comment}
scale_x_y (float): ${scale_x_y_comment}
name (string): The default value is None. Normally there is no need
for user to set this property. For more information,
please refer to :ref:`api_guide_Name`
Returns:
Variable: A 3-D tensor with shape [N, M, 4], the coordinates of boxes,
and a 3-D tensor with shape [N, M, :attr:`class_num`], the classification
scores of boxes.
Raises:
TypeError: Input x of yolov_box must be Variable
TypeError: Attr anchors of yolo box must be list or tuple
TypeError: Attr class_num of yolo box must be an integer
TypeError: Attr conf_thresh of yolo box must be a float number
Examples:
.. code-block:: python
import paddle.fluid as fluid
x = fluid.data(name='x', shape=[None, 255, 13, 13], dtype='float32')
img_size = fluid.data(name='img_size',shape=[None, 2],dtype='int64')
anchors = [10, 13, 16, 30, 33, 23]
boxes,scores = fluid.layers.yolo_box(x=x, img_size=img_size, class_num=80, anchors=anchors,
conf_thresh=0.01, downsample_ratio=32)
:alias_main: paddle.nn.functional.yolov3_loss
:alias: paddle.nn.functional.yolov3_loss,paddle.nn.functional.vision.yolov3_loss
:old_api: paddle.fluid.layers.yolov3_loss
${comment}
Args:
x (Variable): ${x_comment}The data type is float32 or float64.
gt_box (Variable): groud truth boxes, should be in shape of [N, B, 4],
in the third dimension, x, y, w, h should be stored.
x,y is the center coordinate of boxes, w, h are the
width and height, x, y, w, h should be divided by
input image height to scale to [0, 1].
N is the batch number and B is the max box number in
an image.The data type is float32 or float64.
gt_label (Variable): class id of ground truth boxes, should be in shape
of [N, B].The data type is int32.
anchors (list|tuple): ${anchors_comment}
anchor_mask (list|tuple): ${anchor_mask_comment}
class_num (int): ${class_num_comment}
ignore_thresh (float): ${ignore_thresh_comment}
downsample_ratio (int): ${downsample_ratio_comment}
name (string): The default value is None. Normally there is no need
for user to set this property. For more information,
please refer to :ref:`api_guide_Name`
gt_score (Variable): mixup score of ground truth boxes, should be in shape
of [N, B]. Default None.
use_label_smooth (bool): ${use_label_smooth_comment}
scale_x_y (float): ${scale_x_y_comment}
Returns:
Variable: A 1-D tensor with shape [N], the value of yolov3 loss
Raises:
TypeError: Input x of yolov3_loss must be Variable
TypeError: Input gtbox of yolov3_loss must be Variable
TypeError: Input gtlabel of yolov3_loss must be Variable
TypeError: Input gtscore of yolov3_loss must be None or Variable
TypeError: Attr anchors of yolov3_loss must be list or tuple
TypeError: Attr class_num of yolov3_loss must be an integer
TypeError: Attr ignore_thresh of yolov3_loss must be a float number
TypeError: Attr use_label_smooth of yolov3_loss must be a bool value
Examples:
.. code-block:: python
import paddle.fluid as fluid
x = fluid.data(name='x', shape=[None, 255, 13, 13], dtype='float32')
gt_box = fluid.data(name='gt_box', shape=[None, 6, 4], dtype='float32')
gt_label = fluid.data(name='gt_label', shape=[None, 6], dtype='int32')
gt_score = fluid.data(name='gt_score', shape=[None, 6], dtype='float32')
anchors = [10, 13, 16, 30, 33, 23, 30, 61, 62, 45, 59, 119, 116, 90, 156, 198, 373, 326]
anchor_mask = [0, 1, 2]
loss = fluid.layers.yolov3_loss(x=x, gt_box=gt_box, gt_label=gt_label,
gt_score=gt_score, anchors=anchors,
anchor_mask=anchor_mask, class_num=80,
ignore_thresh=0.7, downsample_ratio=32)
All layers just related to the detection neural network.
Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Assign target label to anchors Assign target label to anchors 1. Find matched bounding box by prior box. 1.1 Compute IOU similarity between ground-truth boxes and prior boxes. 1.2 Compute matched bounding box by bipartite matching algorithm. 2. Compute confidence for mining hard examples 2.1. Get the target label based on matched indices 2.2. Compute confidence loss. Reshape confidence to 2D tensor. 3. Mining hard examples shape=(-1, 0) is set for compile-time, the correct shape is set by actual_shape in runtime. 4. Assign classification and regression targets 4.1. Encoded bbox according to the prior boxes. 4.2. Assign regression targets 4.3. Assign classification targets 5. Compute loss. 5.1 Compute confidence loss. the target_label and target_conf_weight do not have gradient. 5.2 Compute regression loss. the target_bbox and target_loc_weight do not have gradient. 5.3 Compute overall weighted loss. reshape to [N, Np], N is the batch size and Np is the prior box number. shape=(-1, 0) is set for compile-time, the correct shape is set by actual_shape in runtime. get loc get conf | 112,188 | en | 0.701008 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Charts about the national vaccines data.
@author: riccardomaldini
"""
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
from data_extractors.vaccines_regions import benchmark_dict, marche_df
from data_extractors.vaccines_italy import italy_df
from data_extractors.area_names import area_names_dict
from matplotlib.dates import MonthLocator
import utils
def adm_doses_italy(save_image=False, show=False):
"""
Administration data about Italy.
"""
# plt.stackplot(data['data_somministrazione'], data['prima_dose'],data['seconda_dose'],
# labels=['Prime dosi', 'Seconde dosi'])
plt.bar(italy_df['data_somministrazione'], italy_df['prima_dose'], label='Prime dosi')
plt.bar(italy_df['data_somministrazione'], italy_df['seconda_dose'], bottom=italy_df['prima_dose'],
label='Seconde dosi')
plt.title("Somministrazioni giornaliere Italia,\ncon distinzione prima dose/richiamo\n")
plt.gca().xaxis.set_major_locator(MonthLocator())
plt.gca().xaxis.set_minor_locator(MonthLocator(bymonthday=15))
plt.gca().xaxis.set_major_formatter(utils.std_date_formatter)
plt.gca().xaxis.set_minor_formatter(utils.std_date_formatter)
plt.gcf().autofmt_xdate(which='both')
plt.grid(True, which='both', axis='both')
plt.legend(loc='upper left')
if save_image:
plt.savefig('./charts/vaccines/dosi_italia.png', dpi=300, transparent=True, bbox_inches='tight')
if show:
plt.show()
plt.close()
def adm_doses_marche(save_image=False, show=False):
"""
Administration data about Italy.
"""
plt.bar(marche_df['data_somministrazione'], marche_df['prima_dose'], label='Prime dosi')
plt.bar(marche_df['data_somministrazione'], marche_df['seconda_dose'], bottom=marche_df['prima_dose'],
label='Seconde dosi')
plt.title("Somministrazioni giornaliere Marche,\ncon distinzione prima dose/richiamo\n")
plt.gca().xaxis.set_major_locator(MonthLocator())
plt.gca().xaxis.set_minor_locator(MonthLocator(bymonthday=15))
plt.gca().xaxis.set_major_formatter(utils.std_date_formatter)
plt.gca().xaxis.set_minor_formatter(utils.std_date_formatter)
plt.gcf().autofmt_xdate(which='both')
plt.grid(True, which='both', axis='both')
plt.legend(loc='upper left')
if save_image:
plt.savefig('./charts/vaccines/dosi_marche.png', dpi=300, transparent=True, bbox_inches='tight')
if show:
plt.show()
plt.close()
def regional_doses(save_image=False, show=False):
"""
Comparation between doses administrated in various regions
"""
for area_code, region_data in benchmark_dict.items():
rolling_avg_adm = region_data['totale_per_100000_ab'].rolling(7, center=True).mean()
plt.plot(region_data['data_somministrazione'], rolling_avg_adm, label=area_names_dict[area_code])
rolling_avg_adm = italy_df['totale_per_100000_ab'].rolling(7, center=True).mean()
plt.plot(italy_df['data_somministrazione'], rolling_avg_adm, alpha=0.5, linestyle=':',
label="Italia")
plt.title('Andamento delle somministrazioni giornaliere\nper 100.000 abitanti, confronto tra le regioni del benchmark\n')
plt.gca().xaxis.set_major_locator(MonthLocator())
plt.gca().xaxis.set_minor_locator(MonthLocator(bymonthday=15))
plt.gca().xaxis.set_major_formatter(utils.std_date_formatter)
plt.gca().xaxis.set_minor_formatter(utils.std_date_formatter)
plt.gcf().autofmt_xdate(which='both')
plt.grid(True, which='both', axis='both')
plt.legend(loc='upper left')
if save_image:
plt.savefig('./charts/vaccines/dosi_per_regioni.png', dpi=300, transparent=True, bbox_inches='tight')
if show:
plt.show()
plt.close()
def immunes_percentage(save_image=False, show=False):
"""
Computes and plots relations between the population of a place and people that took the second shot.
"""
for area_code, region_data in benchmark_dict.items():
plt.plot(region_data['data_somministrazione'], region_data['seconda_dose_totale_storico_su_pop'],
label=area_names_dict[area_code])
plt.plot(italy_df['data_somministrazione'], italy_df['seconda_dose_totale_storico_su_pop'], alpha=0.5, linestyle=':',
label="Italia")
plt.title('Percentuale popolazione immunizzata,\nconfronto tra le regioni del benchmark\n')
plt.gca().yaxis.set_major_formatter(mtick.PercentFormatter(xmax=1))
plt.gca().xaxis.set_major_locator(MonthLocator())
plt.gca().xaxis.set_minor_locator(MonthLocator(bymonthday=15))
plt.gca().xaxis.set_major_formatter(utils.std_date_formatter)
plt.gca().xaxis.set_minor_formatter(utils.std_date_formatter)
plt.gcf().autofmt_xdate(which='both')
plt.grid(True, which='both', axis='both')
plt.legend(loc='upper left')
if save_image:
plt.savefig('./charts/vaccines/immunizzati.png', dpi=300, transparent=True, bbox_inches='tight')
if show:
plt.show()
plt.close()
| chart-generation/charts/vaccines.py | 5,076 | Administration data about Italy.
Administration data about Italy.
Computes and plots relations between the population of a place and people that took the second shot.
Comparation between doses administrated in various regions
Charts about the national vaccines data.
@author: riccardomaldini
!/usr/bin/env python3 -*- coding: utf-8 -*- plt.stackplot(data['data_somministrazione'], data['prima_dose'],data['seconda_dose'], labels=['Prime dosi', 'Seconde dosi']) | 475 | en | 0.782426 |
#!/usr/bin/env python
"""Create two randomly generated matrices, of the specified sizes and write them
to JSON files.
"""
import json
import numpy as np
def read(path):
with open(path, 'rb') as f:
matrix = np.fromfile(f, dtype=np.float32)
return matrix
def write(path, matrix):
with open(path, 'wb') as f:
f.write(matrix.astype(np.float32).tostring())
return matrix
| android/platforms/android/assets/www/web/node_modules/weblas/test/data/binary_matrix.py | 382 | Create two randomly generated matrices, of the specified sizes and write them
to JSON files.
!/usr/bin/env python | 114 | en | 0.580681 |
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
import parl
from parl.remote.master import Master
from parl.remote.worker import Worker
import time
import threading
from parl.remote.client import disconnect
from parl.remote import exceptions
import timeout_decorator
import subprocess
@parl.remote_class
class Actor(object):
def __init__(self, arg1=None, arg2=None):
self.arg1 = arg1
self.arg2 = arg2
def get_arg1(self):
return self.arg1
def get_arg2(self):
return self.arg2
def set_arg1(self, value):
self.arg1 = value
def set_arg2(self, value):
self.arg2 = value
def get_unable_serialize_object(self):
return UnableSerializeObject()
def add_one(self, value):
value += 1
return value
def add(self, x, y):
time.sleep(3)
return x + y
def will_raise_exception_func(self):
x = 1 / 0
class TestCluster(unittest.TestCase):
def tearDown(self):
disconnect()
#time.sleep(20)
#command = ("pkill -f remote/job.py")
#subprocess.call([command], shell=True)
def test_actor_exception(self):
master = Master(port=1235)
th = threading.Thread(target=master.run)
th.start()
time.sleep(1)
worker1 = Worker('localhost:1235', 1)
self.assertEqual(1, master.cpu_num)
parl.connect('localhost:1235')
with self.assertRaises(exceptions.RemoteError):
actor = Actor(abcd='a bug')
actor2 = Actor()
self.assertEqual(actor2.add_one(1), 2)
self.assertEqual(0, master.cpu_num)
master.exit()
worker1.exit()
@timeout_decorator.timeout(seconds=300)
def test_actor_exception(self):
master = Master(port=1236)
th = threading.Thread(target=master.run)
th.start()
time.sleep(1)
worker1 = Worker('localhost:1236', 1)
self.assertEqual(1, master.cpu_num)
parl.connect('localhost:1236')
actor = Actor()
try:
actor.will_raise_exception_func()
except:
pass
actor2 = Actor()
time.sleep(30)
self.assertEqual(actor2.add_one(1), 2)
self.assertEqual(0, master.cpu_num)
del actor
del actor2
worker1.exit()
master.exit()
def test_reset_actor(self):
# start the master
master = Master(port=1237)
th = threading.Thread(target=master.run)
th.start()
time.sleep(1)
worker1 = Worker('localhost:1237', 4)
parl.connect('localhost:1237')
for i in range(10):
actor = Actor()
ret = actor.add_one(1)
self.assertEqual(ret, 2)
del actor
time.sleep(20)
self.assertEqual(master.cpu_num, 4)
worker1.exit()
master.exit()
def test_add_worker(self):
master = Master(port=1234)
th = threading.Thread(target=master.run)
th.start()
time.sleep(1)
worker1 = Worker('localhost:1234', 4)
self.assertEqual(master.cpu_num, 4)
worker2 = Worker('localhost:1234', 4)
self.assertEqual(master.cpu_num, 8)
worker2.exit()
time.sleep(30)
self.assertEqual(master.cpu_num, 4)
master.exit()
worker1.exit()
if __name__ == '__main__':
unittest.main()
| parl/remote/tests/cluster_test.py | 3,981 | Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.time.sleep(20)command = ("pkill -f remote/job.py")subprocess.call([command], shell=True) start the master | 688 | en | 0.83132 |
'''
lanhuage: python
Descripttion:
version: beta
Author: xiaoshuyui
Date: 2020-07-10 10:33:39
LastEditors: xiaoshuyui
LastEditTime: 2021-01-05 10:21:49
'''
import glob
import os
from tqdm import tqdm
from convertmask.utils.methods import getMultiShapes
from convertmask.utils.methods.logger import logger
def getJsons(imgPath, maskPath, savePath, yamlPath=''):
"""
imgPath: origin image path \n
maskPath : mask image path \n
savePath : json file save path \n
>>> getJsons(path-to-your-imgs,path-to-your-maskimgs,path-to-your-jsonfiles)
"""
logger.info("currently, only *.jpg supported")
if os.path.isfile(imgPath):
getMultiShapes.getMultiShapes(imgPath, maskPath, savePath, yamlPath)
elif os.path.isdir(imgPath):
oriImgs = glob.glob(imgPath + os.sep + '*.jpg')
maskImgs = glob.glob(maskPath + os.sep + '*.jpg')
for i in tqdm(oriImgs):
i_mask = i.replace(imgPath, maskPath)
if os.path.exists(i_mask):
# print(i)
getMultiShapes.getMultiShapes(i, i_mask, savePath, yamlPath)
else:
logger.warning('corresponding mask image not found!')
continue
else:
logger.error('input error. got [{},{},{},{}]. file maybe missing.'.format(
imgPath, maskPath, savePath, yamlPath))
logger.info('Done! See here. {}'.format(savePath))
def getXmls(imgPath, maskPath, savePath):
logger.info("currently, only *.jpg supported")
if os.path.isfile(imgPath):
getMultiShapes.getMultiObjs_voc(imgPath, maskPath, savePath)
elif os.path.isdir(imgPath):
oriImgs = glob.glob(imgPath + os.sep + '*.jpg')
maskImgs = glob.glob(maskPath + os.sep + '*.jpg')
for i in tqdm(oriImgs):
i_mask = i.replace(imgPath, maskPath)
# print(i)
if os.path.exists(i_mask):
getMultiShapes.getMultiObjs_voc(i, i_mask, savePath)
else:
logger.warning('corresponding mask image not found!')
continue
else:
logger.error('input error. got [{},{},{}]. file maybe missing.'.format(
imgPath, maskPath, savePath))
logger.info('Done! See here. {}'.format(savePath))
| convertmask/utils/mask2json_script.py | 2,282 | imgPath: origin image path
maskPath : mask image path
savePath : json file save path
>>> getJsons(path-to-your-imgs,path-to-your-maskimgs,path-to-your-jsonfiles)
lanhuage: python
Descripttion:
version: beta
Author: xiaoshuyui
Date: 2020-07-10 10:33:39
LastEditors: xiaoshuyui
LastEditTime: 2021-01-05 10:21:49
print(i) print(i) | 338 | en | 0.623211 |
from collections import namedtuple
Vote = namedtuple('Vote', 'user post vote')
def create_vote(vote_dict, cutoff):
"""
changes the vote to the [-1, 1] range
"""
modified_vote = 1 if float(vote_dict['vote']) > cutoff else -1
return Vote(
user=str(vote_dict['user']),
post=str(vote_dict['post']),
vote=modified_vote
)
| kiwi-content/kiwi/TransferTypes.py | 367 | changes the vote to the [-1, 1] range | 37 | en | 0.762016 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import unittest
from nose.plugins.attrib import attr
import hgvs.dataproviders.uta
import hgvs.location
import hgvs.parser
from hgvs.exceptions import HGVSError
from hgvs.transcriptmapper import TranscriptMapper
@attr(tags=["quick"])
class Test_transcriptmapper(unittest.TestCase):
ref = 'GRCh37.p10'
def setUp(self):
self.hdp = hgvs.dataproviders.uta.connect()
def test_transcriptmapper_failures(self):
self.assertRaises(HGVSError, TranscriptMapper, self.hdp, tx_ac='bogus', alt_ac='NM_033089.6', alt_aln_method='splign')
self.assertRaises(HGVSError, TranscriptMapper, self.hdp, tx_ac='NM_033089.6', alt_ac='bogus', alt_aln_method='splign')
self.assertRaises(HGVSError, TranscriptMapper, self.hdp, tx_ac='NM_000051.3', alt_ac='NC_000011.9', alt_aln_method='bogus')
def test_transcriptmapper_TranscriptMapper_LCE3C_uncertain(self):
"""Use NM_178434.2 tests to test mapping with uncertain positions"""
tx_ac = 'NM_178434.2'
alt_ac = 'NC_000001.10'
tm = TranscriptMapper(self.hdp, tx_ac, alt_ac, alt_aln_method='splign')
parser = hgvs.parser.Parser()
test_cases = [
{'g': parser.parse_g_interval('(152573138)'), 'r': parser.parse_r_interval('(1)'), 'c': parser.parse_c_interval('(-70)')},
{'g': parser.parse_g_interval('(152573138_152573139)'), 'r': parser.parse_r_interval('(1_2)'), 'c': parser.parse_c_interval('(-70_-69)')},
# ? is not yet supported
# {'g': parser.parse_g_interval('(?_152573139)'), 'r': parser.parse_r_interval('(?_2)'), 'c': parser.parse_c_interval('(?_-69)')},
# {'g': parser.parse_g_interval('(152573138_?)'), 'r': parser.parse_r_interval('(1_?)'), 'c': parser.parse_c_interval('(-70_?)')},
]
self.run_cases(tm, test_cases)
def test_transcriptmapper_TranscriptMapper_LCE3C(self):
"""NM_178434.2: LCE3C single exon, strand = +1, all coordinate input/output are in HGVS"""
tx_ac = 'NM_178434.2'
alt_ac = 'NC_000001.10'
tm = TranscriptMapper(self.hdp, tx_ac, alt_ac, alt_aln_method='splign')
parser = hgvs.parser.Parser()
test_cases = [
# 5'
{'g': parser.parse_g_interval('152573138'), 'r': parser.parse_r_interval('1'), 'c': parser.parse_c_interval('-70')},
{'g': parser.parse_g_interval('152573140'), 'r': parser.parse_r_interval('3'), 'c': parser.parse_c_interval('-68')},
# cds
{'g': parser.parse_g_interval('152573207'), 'r': parser.parse_r_interval('70'), 'c': parser.parse_c_interval('-1')},
{'g': parser.parse_g_interval('152573208'), 'r': parser.parse_r_interval('71'), 'c': parser.parse_c_interval('1')},
# 3'
{'g': parser.parse_g_interval('152573492'), 'r': parser.parse_r_interval('355'), 'c': parser.parse_c_interval('285')},
{'g': parser.parse_g_interval('152573493'), 'r': parser.parse_r_interval('356'), 'c': parser.parse_c_interval('*1')},
{'g': parser.parse_g_interval('152573560'), 'r': parser.parse_r_interval('423'), 'c': parser.parse_c_interval('*68')},
{'g': parser.parse_g_interval('152573562'), 'r': parser.parse_r_interval('425'), 'c': parser.parse_c_interval('*70')},
]
self.run_cases(tm, test_cases)
def test_transcriptmapper_TranscriptMapper_HIST3H2A(self):
"""NM_033445.2: LCE3C single exon, strand = -1, all coordinate input/output are in HGVS"""
tx_ac = 'NM_033445.2'
alt_ac = 'NC_000001.10'
tm = TranscriptMapper(self.hdp, tx_ac, alt_ac, alt_aln_method='splign')
parser = hgvs.parser.Parser()
test_cases = [
# 3'
{'g': parser.parse_g_interval('228645560'), 'r': parser.parse_r_interval('1'), 'c': parser.parse_c_interval('-42')},
{'g': parser.parse_g_interval('228645558'), 'r': parser.parse_r_interval('3'), 'c': parser.parse_c_interval('-40')},
# cds
{'g': parser.parse_g_interval('228645519'), 'r': parser.parse_r_interval('42'), 'c': parser.parse_c_interval('-1')},
{'g': parser.parse_g_interval('228645518'), 'r': parser.parse_r_interval('43'), 'c': parser.parse_c_interval('1')},
# 5'
{'g': parser.parse_g_interval('228645126'), 'r': parser.parse_r_interval('435'), 'c': parser.parse_c_interval('393')},
{'g': parser.parse_g_interval('228645125'), 'r': parser.parse_r_interval('436'), 'c': parser.parse_c_interval('*1')},
{'g': parser.parse_g_interval('228645124'), 'r': parser.parse_r_interval('437'), 'c': parser.parse_c_interval('*2')},
{'g': parser.parse_g_interval('228645065'), 'r': parser.parse_r_interval('496'), 'c': parser.parse_c_interval('*61')},
]
self.run_cases(tm, test_cases)
def test_transcriptmapper_TranscriptMapper_LCE2B(self):
"""NM_014357.4: LCE2B, two exons, strand = +1, all coordinate input/output are in HGVS"""
tx_ac = 'NM_014357.4'
alt_ac = 'NC_000001.10'
tm = TranscriptMapper(self.hdp, tx_ac, alt_ac, alt_aln_method='splign')
parser = hgvs.parser.Parser()
test_cases = [
# 5'
{'g': parser.parse_g_interval('152658599'), 'r': parser.parse_r_interval('1'), 'c': parser.parse_c_interval('-54')},
{'g': parser.parse_g_interval('152658601'), 'r': parser.parse_r_interval('3'), 'c': parser.parse_c_interval('-52')},
# cds
{'g': parser.parse_g_interval('152659319'), 'r': parser.parse_r_interval('54'), 'c': parser.parse_c_interval('-1')},
{'g': parser.parse_g_interval('152659320'), 'r': parser.parse_r_interval('55'), 'c': parser.parse_c_interval('1')},
# around end of exon 1
{'g': parser.parse_g_interval('152658632'), 'r': parser.parse_r_interval('34'), 'c': parser.parse_c_interval('-21')},
{'g': parser.parse_g_interval('152658633'), 'r': parser.parse_r_interval('34+1'), 'c': parser.parse_c_interval('-21+1')},
# span
{'g': parser.parse_g_interval('152658633_152659299'), 'r': parser.parse_r_interval('34+1_35-1'), 'c': parser.parse_c_interval('-21+1_-20-1')},
# around beginning of exon 2
{'g': parser.parse_g_interval('152659300'), 'r': parser.parse_r_interval('35'), 'c': parser.parse_c_interval('-20')},
{'g': parser.parse_g_interval('152659299'), 'r': parser.parse_r_interval('35-1'), 'c': parser.parse_c_interval('-20-1')},
# around end of exon 2
{'g': parser.parse_g_interval('152659652'), 'r': parser.parse_r_interval('387'), 'c': parser.parse_c_interval('333')},
{'g': parser.parse_g_interval('152659653'), 'r': parser.parse_r_interval('388'), 'c': parser.parse_c_interval('*1')},
# span
{'g': parser.parse_g_interval('152659651_152659654'), 'r': parser.parse_r_interval('386_389'), 'c': parser.parse_c_interval('332_*2')},
# 3'
{'g': parser.parse_g_interval('152659877'), 'r': parser.parse_r_interval('612'), 'c': parser.parse_c_interval('*225')},
]
self.run_cases(tm, test_cases)
def test_transcriptmapper_TranscriptMapper_PTH2(self):
"""NM_178449.3: PTH2, two exons, strand = -1, all coordinate input/output are in HGVS"""
tx_ac = 'NM_178449.3'
alt_ac = 'NC_000019.9'
tm = TranscriptMapper(self.hdp, tx_ac, alt_ac, alt_aln_method='splign')
parser = hgvs.parser.Parser()
test_cases = [
# 3'
{'g': parser.parse_g_interval('49926698'), 'r': parser.parse_r_interval('1'), 'c': parser.parse_c_interval('-102')},
# cds
{'g': parser.parse_g_interval('49926597'), 'r': parser.parse_r_interval('102'), 'c': parser.parse_c_interval('-1')},
{'g': parser.parse_g_interval('49926596'), 'r': parser.parse_r_interval('103'), 'c': parser.parse_c_interval('1')},
# around end of exon 1
{'g': parser.parse_g_interval('49926469'), 'r': parser.parse_r_interval('230'), 'c': parser.parse_c_interval('128')},
{'g': parser.parse_g_interval('49926468'), 'r': parser.parse_r_interval('230+1'), 'c': parser.parse_c_interval('128+1')},
# span
{'g': parser.parse_g_interval('49925901_49926467'), 'r': parser.parse_r_interval('230+2_231-2'), 'c': parser.parse_c_interval('128+2_129-2')},
# around beginning of exon 2
{'g': parser.parse_g_interval('49925900'), 'r': parser.parse_r_interval('231-1'), 'c': parser.parse_c_interval('129-1')},
{'g': parser.parse_g_interval('49925899'), 'r': parser.parse_r_interval('231'), 'c': parser.parse_c_interval('129')},
# around end of exon 2
{'g': parser.parse_g_interval('49925725'), 'r': parser.parse_r_interval('405'), 'c': parser.parse_c_interval('303')},
{'g': parser.parse_g_interval('49925724'), 'r': parser.parse_r_interval('406'), 'c': parser.parse_c_interval('*1')},
{'g': parser.parse_g_interval('49925671'), 'r': parser.parse_r_interval('459'), 'c': parser.parse_c_interval('*54')},
]
self.run_cases(tm, test_cases)
def run_cases(self, tm, test_cases):
for test_case in test_cases:
self.assertEquals(tm.g_to_r(test_case['g']), test_case['r'])
self.assertEquals(tm.r_to_g(test_case['r']), test_case['g'])
self.assertEquals(tm.r_to_c(test_case['r']), test_case['c'])
self.assertEquals(tm.c_to_r(test_case['c']), test_case['r'])
self.assertEquals(tm.g_to_c(test_case['g']), test_case['c'])
self.assertEquals(tm.c_to_g(test_case['c']), test_case['g'])
if __name__ == '__main__':
unittest.main()
# TODO: Reintegrate older tests, especially those with indels
### harder tests ###
#def test_transcriptmapper_TranscriptMapper_1_ZCCHC3(self):
# """
# reece=> select * from uta.tx_info where ac='NM_033089.6';
# gene | strand | ac | cds_start_i | cds_end_i | descr | summary
# --------+--------+-------------+-------------+-----------+---------------------------------------+---------
# ZCCHC3 | 1 | NM_033089.6 | 24 | 1236 | zinc finger, CCHC domain containing 3 |
#
# reece=> select * from uta.tx_exons where ac='NM_033089.6';
# ac | ord | name | t_start_i | t_end_i | ref | g_start_i | g_end_i | cigar |
# -------------+-----+------+-----------+---------+------------+-----------+---------+-------------+------------------------
# NM_033089.6 | 1 | 1 | 0 | 2759 | GRCh37.p10 | 278203 | 280965 | 484M3D2275M | GGAGGATGCTGGGAAGGAGGTAA
# """
# # http://tinyurl.com/mattx8u
# #
# # Around the deletion
# # http://tinyurl.com/jwt3txg
# # 687 690
# # C | C G G | C
# # \___ ___/
# # C | C
# # 484
#
# ### Add one to g., r., and c. because we are returning hgvs coordinates ###
# ac = 'NM_033089.6'
# tm = TranscriptMapper(self.hdp, ac, self.ref)
# cds = 24 + 1 # hgvs
# # gs, ge = genomic start/end; rs,re = rna start/end; cs, ce = cdna start/end; so, eo = start offset/end offset
# test_cases = [
# {'gs': 278204, 'ge': 278204, 'rs': 1, 're': 1, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START, 'cs': 1-cds, 'ce': 1-cds},
# {'gs': 278214, 'ge': 278214, 'rs': 11, 're': 11, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START, 'cs': 11-cds, 'ce': 11-cds},
# {'gs': 278204, 'ge': 278214, 'rs': 1, 're': 11, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START, 'cs': 1-cds, 'ce': 11-cds},
#
# # around cds (cds can't be zero)
# {'gs': 278227, 'ge': 278227, 'rs': 24, 're': 24, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START, 'cs': 24-cds, 'ce': 24-cds},
#
# # beyond cds add 1 due to hgvs
# {'gs': 278228, 'ge': 278228, 'rs': 25, 're': 25, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START, 'cs': 25-cds+1, 'ce': 25-cds+1},
# {'gs': 278229, 'ge': 278229, 'rs': 26, 're': 26, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START, 'cs': 26-cds+1, 'ce': 26-cds+1},
# {'gs': 280966, 'ge': 280966, 'rs': 2760, 're': 2760, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START, 'cs': 2760-cds+1, 'ce': 2760-cds+1},
# {'gs': 278687, 'ge': 278687, 'rs': 484, 're': 484, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START, 'cs': 484-cds+1, 'ce': 484-cds+1},
# {'gs': 278687, 'ge': 278688, 'rs': 484, 're': 485, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START, 'cs': 484-cds+1, 'ce': 485-cds+1},
# {'gs': 278688, 'ge':278691, 'rs': 485, 're': 485, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START, 'cs': 485-cds+1, 'ce': 485-cds+1},
#
# # around cds_start (24) and cds_end (1236), mindful of *coding* del (3D)
# {'gs': 278204+24, 'ge': 278204+1236, 'rs': 25, 're': 1237-3, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START, 'cs': 25-cds+1, 'ce': 1237-cds-3+1},
# {'gs': 280956, 'ge': 280966, 'rs': 2750, 're': 2760, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START, 'cs': 2750-cds+1, 'ce': 2760-cds+1},
# ]
# self.run_cases(tm, test_cases)
#
#def test_transcriptmapper_TranscriptMapper_2_MCL1(self):
# """
# reece=> select * from uta.tx_info where ac='NM_182763.2';
# gene | strand | ac | cds_start_i | cds_end_i | descr |
# ------+--------+-------------+-------------+-----------+-------------------------------------------------+----------------
# MCL1 | -1 | NM_182763.2 | 208 | 1024 | myeloid cell leukemia sequence 1 (BCL2-related) | This gene encod
#
# reece=> select * from uta.tx_exons where ac='NM_182763.2';
# ac | ord | name | t_start_i | t_end_i | ref | g_start_i | g_end_i | cigar |
# -------------+-----+------+-----------+---------+------------+-----------+-----------+--------------+---------------------
# NM_182763.2 | 1 | 1b | 0 | 896 | GRCh37.p10 | 150551318 | 150552214 | 896M |
# NM_182763.2 | 2 | 3 | 896 | 3841 | GRCh37.p10 | 150547026 | 150549967 | 1077M4I1864M | GATGGGTTTGTGGAGTTCTT
# """
#
# ### Add one to g., r., and c. because we are returning hgvs coordinates ###
#
# ac = 'NM_182763.2'
# tm = TranscriptMapper(self.hdp, ac, self.ref)
# cds = 208 + 1 # hgvs
# test_cases = [
# {'gs': 150552215, 'ge': 150552215, 'rs': 1, 're': 1, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START , 'cs': 1-cds, 'ce': 1-cds},
# {'gs': 150552214, 'ge': 150552214, 'rs': 2, 're': 2, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START , 'cs': 2-cds, 'ce': 2-cds},
#
# # beyond cds add 1 due to hgvs
# {'gs': 150552007, 'ge': 150552007, 'rs': 209, 're': 209, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START , 'cs': 209-cds+1, 'ce': 209-cds+1},
# {'gs': 150547027, 'ge': 150547027, 'rs': 3842, 're': 3842, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START , 'cs': 3842-cds+1, 'ce': 3842-cds+1},
#
# #{'gs': 150549968, 'ge': 150549968, 'rs': 897, 're': 897, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START , 'cs': 897-cds+1, 'ce': 897-cds+1},
# {'gs': 150551318, 'ge': 150551318, 'rs': 897, 're': 897, 'so': 1, 'eo': 1, 'd': hgvs.location.SEQ_START , 'cs': 897-cds+1, 'ce': 897-cds+1},
# {'gs': 150551318, 'ge': 150551319, 'rs': 897, 're': 897, 'so': 1, 'eo': 0, 'd': hgvs.location.SEQ_START , 'cs': 897-cds+1, 'ce': 897-cds+1},
# {'gs': 150551317, 'ge': 150551318, 'rs': 897, 're': 897, 'so': 2, 'eo': 1, 'd': hgvs.location.SEQ_START , 'cs': 897-cds+1, 'ce': 897-cds+1},
# {'gs': 150549968, 'ge': 150549969, 'rs': 897, 're': 897, 'so': 0, 'eo': -1, 'd': hgvs.location.SEQ_START , 'cs': 897-cds+1, 'ce': 897-cds+1},
# {'gs': 150549969, 'ge': 150549970, 'rs': 897, 're': 897, 'so': -1, 'eo': -2, 'd': hgvs.location.SEQ_START , 'cs': 897-cds+1, 'ce': 897-cds+1},
#
# # exon 2, 4nt insertion ~ r.2760
# # See http://tinyurl.com/mwegybw
# # The coords of this indel via NW alignment differ from those at NCBI, but are the same canonicalized
# # variant. Nothing to do about that short of running Splign ourselves. Test a few examples.
# {'gs': 150548892, 'ge': 150548892, 'rs': 1973, 're': 1973, 'so': 0, 'eo':0, 'd': hgvs.location.SEQ_START , 'cs': 1973-cds+1, 'ce': 1973-cds+1},
# #? {'gs': 150548891, 'ge': 150548892, 'rs': 1972, 're': 1973, 'so': 0, 'eo':0, 'd': hgvs.location.SEQ_START , 'cs': 1972-cds+1, 'ce': 1973-cds+1},
# {'gs': 150548890, 'ge': 150548892, 'rs': 1973, 're': 1979, 'so': 0, 'eo':0, 'd': hgvs.location.SEQ_START , 'cs': 1973-cds+1, 'ce': 1979-cds+1},
# ]
# self.run_cases(tm, test_cases)
#
# ## exon 2, 4nt insertion ~ r.2760
# ## See http://tinyurl.com/mwegybw
# ## The coords of this indel via NW alignment differ from those at
# ## NCBI, but are the same canonicalized variant. Nothing to do
# ## about that short of running Splign ourselves.
# #self.assertEqual(tm.r_to_g(1972, 1972), (150548891, 150548891))
# #self.assertEqual(tm.r_to_g(1972, 1973), (150548890, 150548891))
# #self.assertEqual(tm.r_to_g(1972, 1974), (150548890, 150548891))
# #self.assertEqual(tm.r_to_g(1972, 1975), (150548890, 150548891))
# #self.assertEqual(tm.r_to_g(1972, 1976), (150548890, 150548891))
# #self.assertEqual(tm.r_to_g(1972, 1977), (150548890, 150548891))
# #self.assertEqual(tm.r_to_g(1972, 1978), (150548889, 150548891))
# #
# #self.assertEqual(tm.g_to_r(150548891, 150548891), (1972, 1972, 0, 0))
# #self.assertEqual(tm.g_to_r(150548890, 150548891), (1972, 1973, 0, 0))
# #self.assertEqual(tm.g_to_r(150548889, 150548891), (1972, 1978, 0, 0))
# #
# ## around cds_start (208) and cds_end (1024), mindful of *non-coding* ins (4I)
# ## i.e., we *don't* need to account for the 4nt insertion here
# #self.assertEquals(tm.r_to_c(208, 1024), (0, 1024 - 208, 0, 0))
# #self.assertEquals(tm.c_to_r(0, 1024 - 208), (208, 1024, 0, 0))
# #self.assertEquals(tm.g_to_c(150552214 - 208, 150552214 - 208), (0, 0, 0, 0))
# #self.assertEquals(tm.c_to_g(0, 0), (150552214 - 208, 150552214 - 208))
# ## cds_end is in 2nd exon
# #self.assertEquals(tm.g_to_c(150549967 - (1024 - 896), 150549967 - (1024 - 896)), (1024 - 208, 1024 - 208, 0, 0))
# #self.assertEquals(tm.c_to_g(1024 - 208, 1024 - 208), (150549967 - (1024 - 896), 150549967 - (1024 - 896)))
#
#
#def test_transcriptmapper_TranscriptMapper_3_IFI27L1(self):
# """
# #reece=> select * from uta.tx_info where ac='NM_145249.2';
# # gene | chr | strand | ac | cds_start_i | cds_end_i | descr | summary
# #---------+-----+--------+-------------+-------------+-----------+-----------------------------------------------+---------
# # IFI27L1 | 14 | 1 | NM_145249.2 | 254 | 569 | interferon, alpha-inducible protein 27-like 1 |
# #(1 row)
# # reece=>select * from uta.tx_exons where ac = 'NM_145249.2';
# #
# # ac | ord | name | t_start_i | t_end_i | ref | g_start_i | g_end_i | g_cigar | g_seq_a | t_seq_a
# # -------------+-----+------+-----------+---------+------------+-----------+----------+---------+---------+---------
# # NM_145249.2 | 1 | 1 | 0 | 157 | GRCh37.p10 | 94547638 | 94547795 | 157M | |
# # NM_145249.2 | 2 | 2a | 157 | 282 | GRCh37.p10 | 94563186 | 94563311 | 125M | |
# # NM_145249.2 | 3 | 3 | 282 | 315 | GRCh37.p10 | 94567084 | 94567117 | 33M | |
# # NM_145249.2 | 4 | 4 | 315 | 477 | GRCh37.p10 | 94568159 | 94568321 | 162M | |
# # NM_145249.2 | 5 | 5 | 477 | 715 | GRCh37.p10 | 94568822 | 94569060 | 238M | |
# """
#
# ### Add one to g., r., and c. because we are returning hgvs coordinates ###
#
# ac = 'NM_145249.2'
# tm = TranscriptMapper(self.hdp, ac, self.ref)
# cds = 254 + 1 # hgvs
# test_cases = [
# #{'gs': 94547639, 'ge': 94547639, 'rs': 1, 're': 1, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START, 'cs': 1-cds, 'ce': 1-cds},
# #{'gs': 94547796, 'ge': 94547796, 'rs': 158, 're': 158, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START, 'cs': 158-cds, 'ce': 158-cds},
# #{'gs': 94563185, 'ge': 94563185, 'rs': 159, 're': 159, 'so': -2, 'eo': -2, 'd': hgvs.location.SEQ_START, 'cs': 159-cds, 'ce': 159-cds},
#
# # beyond cds add 1 due to hgvs
# #{'gs': 94567118, 'ge': 94567120, 'rs': 316, 're': 316, 'so': 0, 'eo': 2, 'd': hgvs.location.SEQ_START, 'cs': 316-cds+1, 'ce': 316-cds+1},
# {'gs': 94567115, 'ge': 94567118, 'rs': 313, 're': 316, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START, 'cs': 313-cds+1, 'ce': 316-cds+1},
#
# # intron in the middle between exon 1 and 2
# #{'gs': 94555500, 'ge': 94555501, 'rs': 157, 're': 158, 'so': 7686, 'eo': -7685, 'd': hgvs.location.SEQ_START, 'cs': 157-cds+1, 'ce': 158-cds+1},
# #{'gs': 94555481, 'ge': 94555501, 'rs': 157, 're': 158, 'so': 7686, 'eo': -7685, 'd': hgvs.location.SEQ_START, 'cs': 157-cds+1, 'ce': 158-cds+1},
# ]
# self.run_cases(tm, test_cases)
### ANOTHER POSSIBLE TEST CASE ###
# reece=> select * from uta.tx_info where ac = 'NM_145171.3';
# gene | strand | ac | cds_start_i | cds_end_i | descr | summary
# -------+--------+-------------+-------------+-----------+-----------------------------+-----------------------------------
# GPHB5 | -1 | NM_145171.3 | 57 | 450 | glycoprotein hormone beta 5 | GPHB5 is a cystine knot-forming...
#
# reece=> select * from uta.tx_exons where ac = 'NM_145171.3' order by g_start_i;
# ac | ord | name | t_start_i | t_end_i | ref | g_start_i | g_end_i | cigar | g_seq_a
# -------------+-----+------+-----------+---------+------------+-----------+----------+-----------+-------------------------
# NM_145171.3 | 3 | 3 | 261 | 543 | GRCh37.p10 | 63779548 | 63779830 | 282M |
# NM_145171.3 | 2 | 2 | 56 | 261 | GRCh37.p10 | 63784360 | 63784564 | 156M1I48M | CATGAAGCTGGCATTCCTCTT...
# NM_145171.3 | 1 | 1 | 0 | 56 | GRCh37.p10 | 63785537 | 63785593 | 56M |
# def test_transcriptmapper_TranscriptMapper_GPHB5(self):
# ac = 'NM_145171.3'
# tm = TranscriptMapper(self.hdp,ac,self.ref)
# pass
## <LICENSE>
## Copyright 2014 HGVS Contributors (https://bitbucket.org/hgvs/hgvs)
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
## </LICENSE>
| tests/test_hgvs_transcriptmapper.py | 23,928 | NM_033445.2: LCE3C single exon, strand = -1, all coordinate input/output are in HGVS
NM_014357.4: LCE2B, two exons, strand = +1, all coordinate input/output are in HGVS
NM_178434.2: LCE3C single exon, strand = +1, all coordinate input/output are in HGVS
Use NM_178434.2 tests to test mapping with uncertain positions
NM_178449.3: PTH2, two exons, strand = -1, all coordinate input/output are in HGVS
-*- coding: utf-8 -*- ? is not yet supported {'g': parser.parse_g_interval('(?_152573139)'), 'r': parser.parse_r_interval('(?_2)'), 'c': parser.parse_c_interval('(?_-69)')}, {'g': parser.parse_g_interval('(152573138_?)'), 'r': parser.parse_r_interval('(1_?)'), 'c': parser.parse_c_interval('(-70_?)')}, 5' cds 3' 3' cds 5' 5' cds around end of exon 1 span around beginning of exon 2 around end of exon 2 span 3' 3' cds around end of exon 1 span around beginning of exon 2 around end of exon 2 TODO: Reintegrate older tests, especially those with indels harder tests def test_transcriptmapper_TranscriptMapper_1_ZCCHC3(self): """ reece=> select * from uta.tx_info where ac='NM_033089.6'; gene | strand | ac | cds_start_i | cds_end_i | descr | summary --------+--------+-------------+-------------+-----------+---------------------------------------+--------- ZCCHC3 | 1 | NM_033089.6 | 24 | 1236 | zinc finger, CCHC domain containing 3 | reece=> select * from uta.tx_exons where ac='NM_033089.6'; ac | ord | name | t_start_i | t_end_i | ref | g_start_i | g_end_i | cigar | -------------+-----+------+-----------+---------+------------+-----------+---------+-------------+------------------------ NM_033089.6 | 1 | 1 | 0 | 2759 | GRCh37.p10 | 278203 | 280965 | 484M3D2275M | GGAGGATGCTGGGAAGGAGGTAA """ http://tinyurl.com/mattx8u Around the deletion http://tinyurl.com/jwt3txg 687 690 C | C G G | C \___ ___/ C | C 484 Add one to g., r., and c. because we are returning hgvs coordinates ac = 'NM_033089.6' tm = TranscriptMapper(self.hdp, ac, self.ref) cds = 24 + 1 hgvs gs, ge = genomic start/end; rs,re = rna start/end; cs, ce = cdna start/end; so, eo = start offset/end offset test_cases = [ {'gs': 278204, 'ge': 278204, 'rs': 1, 're': 1, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START, 'cs': 1-cds, 'ce': 1-cds}, {'gs': 278214, 'ge': 278214, 'rs': 11, 're': 11, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START, 'cs': 11-cds, 'ce': 11-cds}, {'gs': 278204, 'ge': 278214, 'rs': 1, 're': 11, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START, 'cs': 1-cds, 'ce': 11-cds}, around cds (cds can't be zero) {'gs': 278227, 'ge': 278227, 'rs': 24, 're': 24, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START, 'cs': 24-cds, 'ce': 24-cds}, beyond cds add 1 due to hgvs {'gs': 278228, 'ge': 278228, 'rs': 25, 're': 25, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START, 'cs': 25-cds+1, 'ce': 25-cds+1}, {'gs': 278229, 'ge': 278229, 'rs': 26, 're': 26, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START, 'cs': 26-cds+1, 'ce': 26-cds+1}, {'gs': 280966, 'ge': 280966, 'rs': 2760, 're': 2760, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START, 'cs': 2760-cds+1, 'ce': 2760-cds+1}, {'gs': 278687, 'ge': 278687, 'rs': 484, 're': 484, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START, 'cs': 484-cds+1, 'ce': 484-cds+1}, {'gs': 278687, 'ge': 278688, 'rs': 484, 're': 485, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START, 'cs': 484-cds+1, 'ce': 485-cds+1}, {'gs': 278688, 'ge':278691, 'rs': 485, 're': 485, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START, 'cs': 485-cds+1, 'ce': 485-cds+1}, around cds_start (24) and cds_end (1236), mindful of *coding* del (3D) {'gs': 278204+24, 'ge': 278204+1236, 'rs': 25, 're': 1237-3, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START, 'cs': 25-cds+1, 'ce': 1237-cds-3+1}, {'gs': 280956, 'ge': 280966, 'rs': 2750, 're': 2760, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START, 'cs': 2750-cds+1, 'ce': 2760-cds+1}, ] self.run_cases(tm, test_cases)def test_transcriptmapper_TranscriptMapper_2_MCL1(self): """ reece=> select * from uta.tx_info where ac='NM_182763.2'; gene | strand | ac | cds_start_i | cds_end_i | descr | ------+--------+-------------+-------------+-----------+-------------------------------------------------+---------------- MCL1 | -1 | NM_182763.2 | 208 | 1024 | myeloid cell leukemia sequence 1 (BCL2-related) | This gene encod reece=> select * from uta.tx_exons where ac='NM_182763.2'; ac | ord | name | t_start_i | t_end_i | ref | g_start_i | g_end_i | cigar | -------------+-----+------+-----------+---------+------------+-----------+-----------+--------------+--------------------- NM_182763.2 | 1 | 1b | 0 | 896 | GRCh37.p10 | 150551318 | 150552214 | 896M | NM_182763.2 | 2 | 3 | 896 | 3841 | GRCh37.p10 | 150547026 | 150549967 | 1077M4I1864M | GATGGGTTTGTGGAGTTCTT """ Add one to g., r., and c. because we are returning hgvs coordinates ac = 'NM_182763.2' tm = TranscriptMapper(self.hdp, ac, self.ref) cds = 208 + 1 hgvs test_cases = [ {'gs': 150552215, 'ge': 150552215, 'rs': 1, 're': 1, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START , 'cs': 1-cds, 'ce': 1-cds}, {'gs': 150552214, 'ge': 150552214, 'rs': 2, 're': 2, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START , 'cs': 2-cds, 'ce': 2-cds}, beyond cds add 1 due to hgvs {'gs': 150552007, 'ge': 150552007, 'rs': 209, 're': 209, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START , 'cs': 209-cds+1, 'ce': 209-cds+1}, {'gs': 150547027, 'ge': 150547027, 'rs': 3842, 're': 3842, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START , 'cs': 3842-cds+1, 'ce': 3842-cds+1}, {'gs': 150549968, 'ge': 150549968, 'rs': 897, 're': 897, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START , 'cs': 897-cds+1, 'ce': 897-cds+1}, {'gs': 150551318, 'ge': 150551318, 'rs': 897, 're': 897, 'so': 1, 'eo': 1, 'd': hgvs.location.SEQ_START , 'cs': 897-cds+1, 'ce': 897-cds+1}, {'gs': 150551318, 'ge': 150551319, 'rs': 897, 're': 897, 'so': 1, 'eo': 0, 'd': hgvs.location.SEQ_START , 'cs': 897-cds+1, 'ce': 897-cds+1}, {'gs': 150551317, 'ge': 150551318, 'rs': 897, 're': 897, 'so': 2, 'eo': 1, 'd': hgvs.location.SEQ_START , 'cs': 897-cds+1, 'ce': 897-cds+1}, {'gs': 150549968, 'ge': 150549969, 'rs': 897, 're': 897, 'so': 0, 'eo': -1, 'd': hgvs.location.SEQ_START , 'cs': 897-cds+1, 'ce': 897-cds+1}, {'gs': 150549969, 'ge': 150549970, 'rs': 897, 're': 897, 'so': -1, 'eo': -2, 'd': hgvs.location.SEQ_START , 'cs': 897-cds+1, 'ce': 897-cds+1}, exon 2, 4nt insertion ~ r.2760 See http://tinyurl.com/mwegybw The coords of this indel via NW alignment differ from those at NCBI, but are the same canonicalized variant. Nothing to do about that short of running Splign ourselves. Test a few examples. {'gs': 150548892, 'ge': 150548892, 'rs': 1973, 're': 1973, 'so': 0, 'eo':0, 'd': hgvs.location.SEQ_START , 'cs': 1973-cds+1, 'ce': 1973-cds+1}, ? {'gs': 150548891, 'ge': 150548892, 'rs': 1972, 're': 1973, 'so': 0, 'eo':0, 'd': hgvs.location.SEQ_START , 'cs': 1972-cds+1, 'ce': 1973-cds+1}, {'gs': 150548890, 'ge': 150548892, 'rs': 1973, 're': 1979, 'so': 0, 'eo':0, 'd': hgvs.location.SEQ_START , 'cs': 1973-cds+1, 'ce': 1979-cds+1}, ] self.run_cases(tm, test_cases) exon 2, 4nt insertion ~ r.2760 See http://tinyurl.com/mwegybw The coords of this indel via NW alignment differ from those at NCBI, but are the same canonicalized variant. Nothing to do about that short of running Splign ourselves. self.assertEqual(tm.r_to_g(1972, 1972), (150548891, 150548891)) self.assertEqual(tm.r_to_g(1972, 1973), (150548890, 150548891)) self.assertEqual(tm.r_to_g(1972, 1974), (150548890, 150548891)) self.assertEqual(tm.r_to_g(1972, 1975), (150548890, 150548891)) self.assertEqual(tm.r_to_g(1972, 1976), (150548890, 150548891)) self.assertEqual(tm.r_to_g(1972, 1977), (150548890, 150548891)) self.assertEqual(tm.r_to_g(1972, 1978), (150548889, 150548891)) self.assertEqual(tm.g_to_r(150548891, 150548891), (1972, 1972, 0, 0)) self.assertEqual(tm.g_to_r(150548890, 150548891), (1972, 1973, 0, 0)) self.assertEqual(tm.g_to_r(150548889, 150548891), (1972, 1978, 0, 0)) around cds_start (208) and cds_end (1024), mindful of *non-coding* ins (4I) i.e., we *don't* need to account for the 4nt insertion here self.assertEquals(tm.r_to_c(208, 1024), (0, 1024 - 208, 0, 0)) self.assertEquals(tm.c_to_r(0, 1024 - 208), (208, 1024, 0, 0)) self.assertEquals(tm.g_to_c(150552214 - 208, 150552214 - 208), (0, 0, 0, 0)) self.assertEquals(tm.c_to_g(0, 0), (150552214 - 208, 150552214 - 208)) cds_end is in 2nd exon self.assertEquals(tm.g_to_c(150549967 - (1024 - 896), 150549967 - (1024 - 896)), (1024 - 208, 1024 - 208, 0, 0)) self.assertEquals(tm.c_to_g(1024 - 208, 1024 - 208), (150549967 - (1024 - 896), 150549967 - (1024 - 896)))def test_transcriptmapper_TranscriptMapper_3_IFI27L1(self): """ reece=> select * from uta.tx_info where ac='NM_145249.2'; gene | chr | strand | ac | cds_start_i | cds_end_i | descr | summary ---------+-----+--------+-------------+-------------+-----------+-----------------------------------------------+--------- IFI27L1 | 14 | 1 | NM_145249.2 | 254 | 569 | interferon, alpha-inducible protein 27-like 1 | (1 row) reece=>select * from uta.tx_exons where ac = 'NM_145249.2'; ac | ord | name | t_start_i | t_end_i | ref | g_start_i | g_end_i | g_cigar | g_seq_a | t_seq_a -------------+-----+------+-----------+---------+------------+-----------+----------+---------+---------+--------- NM_145249.2 | 1 | 1 | 0 | 157 | GRCh37.p10 | 94547638 | 94547795 | 157M | | NM_145249.2 | 2 | 2a | 157 | 282 | GRCh37.p10 | 94563186 | 94563311 | 125M | | NM_145249.2 | 3 | 3 | 282 | 315 | GRCh37.p10 | 94567084 | 94567117 | 33M | | NM_145249.2 | 4 | 4 | 315 | 477 | GRCh37.p10 | 94568159 | 94568321 | 162M | | NM_145249.2 | 5 | 5 | 477 | 715 | GRCh37.p10 | 94568822 | 94569060 | 238M | | """ Add one to g., r., and c. because we are returning hgvs coordinates ac = 'NM_145249.2' tm = TranscriptMapper(self.hdp, ac, self.ref) cds = 254 + 1 hgvs test_cases = [ {'gs': 94547639, 'ge': 94547639, 'rs': 1, 're': 1, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START, 'cs': 1-cds, 'ce': 1-cds}, {'gs': 94547796, 'ge': 94547796, 'rs': 158, 're': 158, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START, 'cs': 158-cds, 'ce': 158-cds}, {'gs': 94563185, 'ge': 94563185, 'rs': 159, 're': 159, 'so': -2, 'eo': -2, 'd': hgvs.location.SEQ_START, 'cs': 159-cds, 'ce': 159-cds}, beyond cds add 1 due to hgvs {'gs': 94567118, 'ge': 94567120, 'rs': 316, 're': 316, 'so': 0, 'eo': 2, 'd': hgvs.location.SEQ_START, 'cs': 316-cds+1, 'ce': 316-cds+1}, {'gs': 94567115, 'ge': 94567118, 'rs': 313, 're': 316, 'so': 0, 'eo': 0, 'd': hgvs.location.SEQ_START, 'cs': 313-cds+1, 'ce': 316-cds+1}, intron in the middle between exon 1 and 2 {'gs': 94555500, 'ge': 94555501, 'rs': 157, 're': 158, 'so': 7686, 'eo': -7685, 'd': hgvs.location.SEQ_START, 'cs': 157-cds+1, 'ce': 158-cds+1}, {'gs': 94555481, 'ge': 94555501, 'rs': 157, 're': 158, 'so': 7686, 'eo': -7685, 'd': hgvs.location.SEQ_START, 'cs': 157-cds+1, 'ce': 158-cds+1}, ] self.run_cases(tm, test_cases) ANOTHER POSSIBLE TEST CASE reece=> select * from uta.tx_info where ac = 'NM_145171.3'; gene | strand | ac | cds_start_i | cds_end_i | descr | summary -------+--------+-------------+-------------+-----------+-----------------------------+----------------------------------- GPHB5 | -1 | NM_145171.3 | 57 | 450 | glycoprotein hormone beta 5 | GPHB5 is a cystine knot-forming... reece=> select * from uta.tx_exons where ac = 'NM_145171.3' order by g_start_i; ac | ord | name | t_start_i | t_end_i | ref | g_start_i | g_end_i | cigar | g_seq_a -------------+-----+------+-----------+---------+------------+-----------+----------+-----------+------------------------- NM_145171.3 | 3 | 3 | 261 | 543 | GRCh37.p10 | 63779548 | 63779830 | 282M | NM_145171.3 | 2 | 2 | 56 | 261 | GRCh37.p10 | 63784360 | 63784564 | 156M1I48M | CATGAAGCTGGCATTCCTCTT... NM_145171.3 | 1 | 1 | 0 | 56 | GRCh37.p10 | 63785537 | 63785593 | 56M | def test_transcriptmapper_TranscriptMapper_GPHB5(self): ac = 'NM_145171.3' tm = TranscriptMapper(self.hdp,ac,self.ref) pass <LICENSE> Copyright 2014 HGVS Contributors (https://bitbucket.org/hgvs/hgvs) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. </LICENSE> | 13,784 | en | 0.317898 |
from django.test import TestCase
from django.contrib.sites.models import Site
from django.utils import unittest
from django.conf import settings
from .factories import GalleryFactory, PhotoFactory
class SitesTest(TestCase):
urls = 'photologue.tests.test_urls'
def setUp(self):
"""
Create two example sites that we can use to test what gets displayed
where.
"""
super(SitesTest, self).setUp()
self.site1, created1 = Site.objects.get_or_create(
domain="example.com", name="example.com")
self.site2, created2 = Site.objects.get_or_create(
domain="example.org", name="example.org")
with self.settings(PHOTOLOGUE_MULTISITE=True):
# Be explicit about linking Galleries/Photos to Sites."""
self.gallery1 = GalleryFactory(slug='test-gallery', sites=[self.site1])
self.gallery2 = GalleryFactory(slug='not-on-site-gallery')
self.photo1 = PhotoFactory(slug='test-photo', sites=[self.site1])
self.photo2 = PhotoFactory(slug='not-on-site-photo')
self.gallery1.photos.add(self.photo1, self.photo2)
# I'd like to use factory_boy's mute_signal decorator but that
# will only available once factory_boy 2.4 is released. So long
# we'll have to remove the site association manually
self.photo2.sites.clear()
def tearDown(self):
super(SitesTest, self).tearDown()
self.gallery1.delete()
self.gallery2.delete()
self.photo1.delete()
self.photo2.delete()
def test_basics(self):
""" See if objects were added automatically (by the factory) to the current site. """
self.assertEqual(list(self.gallery1.sites.all()), [self.site1])
self.assertEqual(list(self.photo1.sites.all()), [self.site1])
def test_auto_add_sites(self):
"""
Objects should not be automatically associated with a particular site when
``PHOTOLOGUE_MULTISITE`` is ``True``.
"""
with self.settings(PHOTOLOGUE_MULTISITE=False):
gallery = GalleryFactory()
photo = PhotoFactory()
self.assertEqual(list(gallery.sites.all()), [self.site1])
self.assertEqual(list(photo.sites.all()), [self.site1])
photo.delete()
with self.settings(PHOTOLOGUE_MULTISITE=True):
gallery = GalleryFactory()
photo = PhotoFactory()
self.assertEqual(list(gallery.sites.all()), [])
self.assertEqual(list(photo.sites.all()), [])
photo.delete()
def test_gallery_list(self):
response = self.client.get('/ptests/gallerylist/')
self.assertEqual(list(response.context['object_list']), [self.gallery1])
def test_gallery_detail(self):
response = self.client.get('/ptests/gallery/test-gallery/')
self.assertEqual(response.context['object'], self.gallery1)
response = self.client.get('/ptests/gallery/not-on-site-gallery/')
self.assertEqual(response.status_code, 404)
def test_photo_list(self):
response = self.client.get('/ptests/photolist/')
self.assertEqual(list(response.context['object_list']), [self.photo1])
def test_photo_detail(self):
response = self.client.get('/ptests/photo/test-photo/')
self.assertEqual(response.context['object'], self.photo1)
response = self.client.get('/ptests/photo/not-on-site-photo/')
self.assertEqual(response.status_code, 404)
def test_photo_archive(self):
response = self.client.get('/ptests/photo/')
self.assertEqual(list(response.context['object_list']), [self.photo1])
def test_photos_in_gallery(self):
"""
Only those photos are supposed to be shown in a gallery that are
also associated with the current site.
"""
response = self.client.get('/ptests/gallery/test-gallery/')
self.assertEqual(list(response.context['object'].public()), [self.photo1])
@unittest.skipUnless('django.contrib.sitemaps' in settings.INSTALLED_APPS,
'Sitemaps not installed in this project, nothing to test.')
def test_sitemap(self):
"""A sitemap should only show objects associated with the current site."""
response = self.client.get('/sitemap.xml')
# Check photos.
self.assertContains(response,
'<url><loc>http://example.com/ptests/photo/test-photo/</loc>'
'<lastmod>2011-12-23</lastmod></url>')
self.assertNotContains(response,
'<url><loc>http://example.com/ptests/photo/not-on-site-photo/</loc>'
'<lastmod>2011-12-23</lastmod></url>')
# Check galleries.
self.assertContains(response,
'<url><loc>http://example.com/ptests/gallery/test-gallery/</loc>'
'<lastmod>2011-12-23</lastmod></url>')
self.assertNotContains(response,
'<url><loc>http://example.com/ptests/gallery/not-on-site-gallery/</loc>'
'<lastmod>2011-12-23</lastmod></url>')
def test_orphaned_photos(self):
self.assertEqual(list(self.gallery1.orphaned_photos()), [self.photo2])
self.gallery2.photos.add(self.photo2)
self.assertEqual(list(self.gallery1.orphaned_photos()), [self.photo2])
self.gallery1.sites.clear()
self.assertEqual(list(self.gallery1.orphaned_photos()), [self.photo1, self.photo2])
self.photo1.sites.clear()
self.photo2.sites.clear()
self.assertEqual(list(self.gallery1.orphaned_photos()), [self.photo1, self.photo2])
| photologue/tests/test_sites.py | 5,750 | Create two example sites that we can use to test what gets displayed
where.
Objects should not be automatically associated with a particular site when
``PHOTOLOGUE_MULTISITE`` is ``True``.
See if objects were added automatically (by the factory) to the current site.
Only those photos are supposed to be shown in a gallery that are
also associated with the current site.
A sitemap should only show objects associated with the current site.
Be explicit about linking Galleries/Photos to Sites.""" I'd like to use factory_boy's mute_signal decorator but that will only available once factory_boy 2.4 is released. So long we'll have to remove the site association manually Check photos. Check galleries. | 703 | en | 0.91365 |
# -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Test the decompose pass"""
from sympy import pi
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.transpiler.passes import Decompose
from qiskit.converters import circuit_to_dag
from qiskit.extensions.standard import HGate
from qiskit.extensions.standard import ToffoliGate
from qiskit.test import QiskitTestCase
class TestDecompose(QiskitTestCase):
"""Tests the decompose pass."""
def test_basic(self):
"""Test decompose a single H into u2.
"""
qr = QuantumRegister(1, 'qr')
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
dag = circuit_to_dag(circuit)
pass_ = Decompose(HGate)
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 1)
self.assertEqual(op_nodes[0].name, 'u2')
def test_decompose_only_h(self):
"""Test to decompose a single H, without the rest
"""
qr = QuantumRegister(2, 'qr')
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
dag = circuit_to_dag(circuit)
pass_ = Decompose(HGate)
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 2)
for node in op_nodes:
self.assertIn(node.name, ['cx', 'u2'])
def test_decompose_toffoli(self):
"""Test decompose CCX.
"""
qr1 = QuantumRegister(2, 'qr1')
qr2 = QuantumRegister(1, 'qr2')
circuit = QuantumCircuit(qr1, qr2)
circuit.ccx(qr1[0], qr1[1], qr2[0])
dag = circuit_to_dag(circuit)
pass_ = Decompose(ToffoliGate)
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 15)
for node in op_nodes:
self.assertIn(node.name, ['h', 't', 'tdg', 'cx'])
def test_decompose_conditional(self):
"""Test decompose a 1-qubit gates with a conditional.
"""
qr = QuantumRegister(1, 'qr')
cr = ClassicalRegister(1, 'cr')
circuit = QuantumCircuit(qr, cr)
circuit.h(qr).c_if(cr, 1)
circuit.x(qr).c_if(cr, 1)
dag = circuit_to_dag(circuit)
pass_ = Decompose(HGate)
after_dag = pass_.run(dag)
ref_circuit = QuantumCircuit(qr, cr)
ref_circuit.u2(0, pi, qr[0]).c_if(cr, 1)
ref_circuit.x(qr).c_if(cr, 1)
ref_dag = circuit_to_dag(ref_circuit)
self.assertEqual(after_dag, ref_dag)
| test/python/transpiler/test_decompose.py | 2,726 | Tests the decompose pass.
Test decompose a single H into u2.
Test decompose a 1-qubit gates with a conditional.
Test to decompose a single H, without the rest
Test decompose CCX.
Test the decompose pass
-*- coding: utf-8 -*- Copyright 2018, IBM. This source code is licensed under the Apache License, Version 2.0 found in the LICENSE.txt file in the root directory of this source tree. | 423 | en | 0.84139 |
"""
ASGI config for animeDjangoApp project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'animeDjangoApp.settings')
application = get_asgi_application()
| animeDjangoApp/asgi.py | 405 | ASGI config for animeDjangoApp project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ | 220 | en | 0.676117 |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: service_method_same_name.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='service_method_same_name.proto',
package='',
syntax='proto3',
serialized_options=_b('Z\030service_method_same_name'),
serialized_pb=_b('\n\x1eservice_method_same_name.proto\"\x05\n\x03Msg2\x1c\n\x04\x45\x63ho\x12\x14\n\x04\x45\x63ho\x12\x04.Msg\x1a\x04.Msg\"\x00\x42\x1aZ\x18service_method_same_nameb\x06proto3')
)
_MSG = _descriptor.Descriptor(
name='Msg',
full_name='Msg',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=34,
serialized_end=39,
)
DESCRIPTOR.message_types_by_name['Msg'] = _MSG
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
Msg = _reflection.GeneratedProtocolMessageType('Msg', (_message.Message,), dict(
DESCRIPTOR = _MSG,
__module__ = 'service_method_same_name_pb2'
# @@protoc_insertion_point(class_scope:Msg)
))
_sym_db.RegisterMessage(Msg)
DESCRIPTOR._options = None
_ECHO = _descriptor.ServiceDescriptor(
name='Echo',
full_name='Echo',
file=DESCRIPTOR,
index=0,
serialized_options=None,
serialized_start=41,
serialized_end=69,
methods=[
_descriptor.MethodDescriptor(
name='Echo',
full_name='Echo.Echo',
index=0,
containing_service=None,
input_type=_MSG,
output_type=_MSG,
serialized_options=None,
),
])
_sym_db.RegisterServiceDescriptor(_ECHO)
DESCRIPTOR.services_by_name['Echo'] = _ECHO
# @@protoc_insertion_point(module_scope)
| internal/twirptest/service_method_same_name/service_method_same_name_pb2.py | 2,077 | Generated by the protocol buffer compiler. DO NOT EDIT! source: service_method_same_name.proto @@protoc_insertion_point(imports) @@protoc_insertion_point(class_scope:Msg) @@protoc_insertion_point(module_scope) | 210 | en | 0.553739 |
"""
Django settings for backend project.
Generated by 'django-admin startproject' using Django 3.1.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
from datetime import timedelta
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '2(iwreobf4b(-=h_p=^!obgxdgn3_*s!17=_3wc4dun9_y^q+c'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'backend.core',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'backend.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'backend.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LOGIN_URL = "/api/v1/signin"
SIMPLE_JWT = {
"ACCESS_TOKEN_LIFETIME": timedelta(minutes=60),
"REFRESH_TOKEN_LIFETIME": timedelta(days=2),
}
CORS_ORIGIN_WHITELIST = ["http://localhost:3000", "http://127.0.0.1:3000"]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": ["rest_framework_simplejwt.authentication.JWTAuthentication"],
"DEFAULT_RENDERER_CLASSES": ["rest_framework.renderers.JSONRenderer"],
"TEST_REQUEST_DEFAULT_FORMAT": "json",
"DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.DjangoModelPermissions",),
}
| backend/settings.py | 3,794 | Django settings for backend project.
Generated by 'django-admin startproject' using Django 3.1.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
Build paths inside the project like this: BASE_DIR / 'subdir'. Quick-start development settings - unsuitable for production See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ SECURITY WARNING: keep the secret key used in production secret! SECURITY WARNING: don't run with debug turned on in production! Application definition Database https://docs.djangoproject.com/en/3.1/ref/settings/databases Password validation https://docs.djangoproject.com/en/3.1/ref/settings/auth-password-validators Internationalization https://docs.djangoproject.com/en/3.1/topics/i18n/ Static files (CSS, JavaScript, Images) https://docs.djangoproject.com/en/3.1/howto/static-files/ | 981 | en | 0.697623 |
import os
import wget
import tarfile
import argparse
import subprocess
from utils import create_manifest
from tqdm import tqdm
import shutil
parser = argparse.ArgumentParser(description='Processes and downloads LibriSpeech dataset.')
parser.add_argument("--target-dir", default='LibriSpeech_dataset/', type=str, help="Directory to store the dataset.")
parser.add_argument('--sample-rate', default=16000, type=int, help='Sample rate')
parser.add_argument('--files-to-use', default="train-clean-100.tar.gz,"
"train-clean-360.tar.gz,train-other-500.tar.gz,"
"dev-clean.tar.gz,dev-other.tar.gz,"
"test-clean.tar.gz,test-other.tar.gz", type=str,
help='list of file names to download')
parser.add_argument('--min-duration', default=1, type=int,
help='Prunes training samples shorter than the min duration (given in seconds, default 1)')
parser.add_argument('--max-duration', default=15, type=int,
help='Prunes training samples longer than the max duration (given in seconds, default 15)')
parser.add_argument('--remove-tarballs', action = 'store_true')
args = parser.parse_args()
LIBRI_SPEECH_URLS = {
"train": ["http://www.openslr.org/resources/12/train-clean-100.tar.gz",
"http://www.openslr.org/resources/12/train-clean-360.tar.gz",
"http://www.openslr.org/resources/12/train-other-500.tar.gz"],
"val": ["http://www.openslr.org/resources/12/dev-clean.tar.gz",
"http://www.openslr.org/resources/12/dev-other.tar.gz"],
"test_clean": ["http://www.openslr.org/resources/12/test-clean.tar.gz"],
"test_other": ["http://www.openslr.org/resources/12/test-other.tar.gz"]
}
def _preprocess_transcript(phrase):
return phrase.strip().upper()
def _process_file(wav_dir, txt_dir, base_filename, root_dir):
full_recording_path = os.path.join(root_dir, base_filename)
assert os.path.exists(full_recording_path) and os.path.exists(root_dir)
wav_recording_path = os.path.join(wav_dir, base_filename.replace(".flac", ".wav"))
subprocess.call(["sox {} -r {} -b 16 -c 1 {}".format(full_recording_path, str(args.sample_rate),
wav_recording_path)], shell=True)
# process transcript
txt_transcript_path = os.path.join(txt_dir, base_filename.replace(".flac", ".txt"))
transcript_file = os.path.join(root_dir, "-".join(base_filename.split('-')[:-1]) + ".trans.txt")
assert os.path.exists(transcript_file), "Transcript file {} does not exist.".format(transcript_file)
transcriptions = open(transcript_file).read().strip().split("\n")
transcriptions = {t.split()[0].split("-")[-1]: " ".join(t.split()[1:]) for t in transcriptions}
with open(txt_transcript_path, "w") as f:
key = base_filename.replace(".flac", "").split("-")[-1]
assert key in transcriptions, "{} is not in the transcriptions".format(key)
f.write(_preprocess_transcript(transcriptions[key]))
f.flush()
def main():
target_dl_dir = args.target_dir
if not os.path.exists(target_dl_dir):
os.makedirs(target_dl_dir)
files_to_dl = args.files_to_use.strip().split(',')
for split_type, lst_libri_urls in LIBRI_SPEECH_URLS.items():
split_dir = os.path.join(target_dl_dir, split_type)
if not os.path.exists(split_dir):
os.makedirs(split_dir)
split_wav_dir = os.path.join(split_dir, "wav")
if not os.path.exists(split_wav_dir):
os.makedirs(split_wav_dir)
split_txt_dir = os.path.join(split_dir, "txt")
if not os.path.exists(split_txt_dir):
os.makedirs(split_txt_dir)
extracted_dir = os.path.join(split_dir, "LibriSpeech")
if os.path.exists(extracted_dir):
shutil.rmtree(extracted_dir)
for url in lst_libri_urls:
# check if we want to dl this file
dl_flag = False
for f in files_to_dl:
if url.find(f) != -1:
dl_flag = True
if not dl_flag:
print("Skipping url: {}".format(url))
continue
filename = url.split("/")[-1]
target_filename = os.path.join(split_dir, filename)
if not os.path.exists(target_filename):
wget.download(url, split_dir)
print("Unpacking {}...".format(filename))
tar = tarfile.open(target_filename)
tar.extractall(split_dir)
tar.close()
if args.remove_tarballs:
os.remove(target_filename)
print("Converting flac files to wav and extracting transcripts...")
assert os.path.exists(extracted_dir), "Archive {} was not properly uncompressed.".format(filename)
for root, subdirs, files in tqdm(os.walk(extracted_dir)):
for f in files:
if f.find(".flac") != -1:
_process_file(wav_dir=split_wav_dir, txt_dir=split_txt_dir,
base_filename=f, root_dir=root)
print("Finished {}".format(url))
shutil.rmtree(extracted_dir)
if split_type == 'train': # Prune to min/max duration
create_manifest(split_dir, 'libri_' + split_type + '_manifest.csv', args.min_duration, args.max_duration)
else:
create_manifest(split_dir, 'libri_' + split_type + '_manifest.csv')
if __name__ == "__main__":
main()
| data/librispeech.py | 5,613 | process transcript check if we want to dl this file Prune to min/max duration | 77 | en | 0.731211 |
##########################################################################
#
# pgAdmin 4 - PostgreSQL Tools
#
# Copyright (C) 2013 - 2017, The pgAdmin Development Team
# This software is released under the PostgreSQL Licence
#
##########################################################################
"""Implements the Check Constraint Module."""
import simplejson as json
from functools import wraps
import pgadmin.browser.server_groups.servers.databases as database
from flask import render_template, make_response, request, jsonify
from flask_babel import gettext as _
from pgadmin.browser.collection import CollectionNodeModule
from pgadmin.browser.server_groups.servers.databases.schemas.tables.constraints.type \
import ConstraintRegistry
from pgadmin.browser.utils import PGChildNodeView
from pgadmin.utils.ajax import make_json_response, internal_server_error, \
make_response as ajax_response, gone
from pgadmin.utils.driver import get_driver
from config import PG_DEFAULT_DRIVER
class CheckConstraintModule(CollectionNodeModule):
"""
class CheckConstraintModule(CollectionNodeModule):
This class represents The Check Constraint Module.
Methods:
-------
* __init__(*args, **kwargs)
- Initialize the Check Constraint Module.
* get_nodes(gid, sid, did, scid)
- Generate the Check Constraint collection node.
* node_inode(gid, sid, did, scid)
- Returns Check Constraint node as leaf node.
* script_load()
- Load the module script for the Check Constraint, when any of the
Check node is initialized.
"""
NODE_TYPE = 'check_constraints'
COLLECTION_LABEL = _("Check Constraints")
def __init__(self, *args, **kwargs):
super(CheckConstraintModule, self).__init__(*args, **kwargs)
self.min_ver = None
self.max_ver = None
def get_nodes(self, gid, sid, did, scid, doid):
"""
Generate the Check Constraint collection node.
"""
yield self.generate_browser_collection_node(doid)
@property
def node_inode(self):
"""
Returns Check Constraint node as leaf node.
"""
return False
@property
def script_load(self):
"""
Load the module script for the Check Constraint, when any of the
Check node is initialized.
"""
return database.DatabaseModule.NODE_TYPE
@property
def module_use_template_javascript(self):
"""
Returns whether Jinja2 template is used for generating the javascript
module.
"""
return False
@property
def csssnippets(self):
"""
Returns a snippet of css to include in the page
"""
return [
render_template(
"check_constraint/css/check_constraint.css",
node_type=self.node_type
)
]
blueprint = CheckConstraintModule(__name__)
class CheckConstraintView(PGChildNodeView):
"""
class CheckConstraintView(PGChildNodeView):
This class inherits PGChildNodeView to get the different routes for
the module.
The class is responsible to Create, Read, Update and Delete operations for
the Check Constraint.
Methods:
-------
* module_js():
- Load JS file (check-constraints.js) for this module.
* check_precondition(f):
- Works as a decorator.
- Checks database connection status.
- Attach connection object and template path.
* list(gid, sid, did, scid, doid):
- List the Check Constraints.
* nodes(gid, sid, did, scid):
- Returns all the Check Constraints to generate Nodes in the browser.
* properties(gid, sid, did, scid, doid):
- Returns the Check Constraint properties.
* create(gid, sid, did, scid):
- Creates a new Check Constraint object.
* update(gid, sid, did, scid, doid):
- Updates the Check Constraint object.
* delete(gid, sid, did, scid, doid):
- Drops the Check Constraint object.
* sql(gid, sid, did, scid, doid=None):
- Returns the SQL for the Check Constraint object.
* msql(gid, sid, did, scid, doid=None):
- Returns the modified SQL.
* get_sql(gid, sid, data, scid, tid=None):
- Generates the SQL statements to create/update the Check Constraint.
object.
* dependents(gid, sid, did, scid, tid, cid):
- Returns the dependents for the Check Constraint object.
* dependencies(gid, sid, did, scid, tid, cid):
- Returns the dependencies for the Check Constraint object.
* validate_check_constraint(gid, sid, did, scid, tid, cid):
- Validate check constraint.
"""
node_type = blueprint.node_type
parent_ids = [
{'type': 'int', 'id': 'gid'},
{'type': 'int', 'id': 'sid'},
{'type': 'int', 'id': 'did'},
{'type': 'int', 'id': 'scid'},
{'type': 'int', 'id': 'tid'}
]
ids = [
{'type': 'int', 'id': 'cid'}
]
operations = dict({
'obj': [
{'get': 'properties', 'delete': 'delete', 'put': 'update'},
{'get': 'list', 'post': 'create'}
],
'delete': [{'delete': 'delete'}],
'children': [{'get': 'children'}],
'nodes': [{'get': 'node'}, {'get': 'nodes'}],
'sql': [{'get': 'sql'}],
'msql': [{'get': 'msql'}, {'get': 'msql'}],
'stats': [{'get': 'statistics'}],
'dependency': [{'get': 'dependencies'}],
'dependent': [{'get': 'dependents'}],
'module.js': [{}, {}, {'get': 'module_js'}],
'validate': [{'get': 'validate_check_constraint'}],
})
def module_js(self):
"""
Load JS file (check_constraint.js) for this module.
"""
return make_response(
render_template(
"check_constraint/js/check_constraint.js",
_=_
),
200, {'Content-Type': 'application/x-javascript'}
)
def check_precondition(f):
"""
Works as a decorator.
Checks database connection status.
Attach connection object and template path.
"""
@wraps(f)
def wrap(*args, **kwargs):
self = args[0]
driver = get_driver(PG_DEFAULT_DRIVER)
self.manager = driver.connection_manager(kwargs['sid'])
self.conn = self.manager.connection(did=kwargs['did'])
self.qtIdent = driver.qtIdent
# Set the template path for the SQL scripts
self.template_path = 'check_constraint/sql/#{0}#'.format(self.manager.version)
SQL = render_template("/".join([self.template_path,
'get_parent.sql']),
tid=kwargs['tid'])
status, rset = self.conn.execute_2darray(SQL)
if not status:
return internal_server_error(errormsg=rset)
self.schema = rset['rows'][0]['schema']
self.table = rset['rows'][0]['table']
return f(*args, **kwargs)
return wrap
def end_transaction(self):
"""
End database transaction.
Returns:
"""
SQL = "END;"
self.conn.execute_scalar(SQL)
@check_precondition
def list(self, gid, sid, did, scid, tid, cid=None):
"""
List the Check Constraints.
Args:
gid: Server Group Id
sid: Server Id
did: Database Id
scid: Schema Id
tid: Table Id
cid: Check Id
"""
try:
res = self.get_node_list(gid, sid, did, scid, tid, cid)
return ajax_response(
response=res,
status=200
)
except Exception as e:
return internal_server_error(errormsg=str(e))
def get_node_list(self, gid, sid, did, scid, tid, cid=None):
"""
This function returns all check constraints
nodes within that collection as a list.
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
scid: Schema ID
tid: Table ID
cid: Cehck constraint ID
Returns:
"""
driver = get_driver(PG_DEFAULT_DRIVER)
self.manager = driver.connection_manager(sid)
self.conn = self.manager.connection(did=did)
self.qtIdent = driver.qtIdent
# Set the template path for the SQL scripts
self.template_path = 'check_constraint/sql/#{0}#'.format(self.manager.version)
SQL = render_template("/".join([self.template_path,
'get_parent.sql']),
tid=tid)
status, rset = self.conn.execute_2darray(SQL)
if not status:
return internal_server_error(errormsg=rset)
self.schema = rset['rows'][0]['schema']
self.table = rset['rows'][0]['table']
SQL = render_template("/".join([self.template_path, 'properties.sql']),
tid=tid)
status, res = self.conn.execute_dict(SQL)
return res['rows']
@check_precondition
def node(self, gid, sid, did, scid, tid, cid):
"""
Returns all the Check Constraints.
Args:
gid: Server Group Id
sid: Server Id
did: Database Id
scid: Schema Id
tid: Table Id
cid: Check constraint Id.
"""
SQL = render_template("/".join([self.template_path,
'nodes.sql']),
cid=cid)
status, rset = self.conn.execute_2darray(SQL)
if len(rset['rows']) == 0:
return gone(_("""Could not find the check constraint."""))
if "convalidated" in rset['rows'][0] and rset['rows'][0]["convalidated"]:
icon = "icon-check_constraints_bad"
valid = False
else:
icon = "icon-check_constraints"
valid = True
res = self.blueprint.generate_browser_node(
rset['rows'][0]['oid'],
tid,
rset['rows'][0]['name'],
icon=icon,
valid=valid
)
return make_json_response(
data=res,
status=200
)
@check_precondition
def nodes(self, gid, sid, did, scid, tid):
"""
Returns all the Check Constraints.
Args:
gid: Server Group Id
sid: Server Id
did: Database Id
scid: Schema Id
tid: Table Id
cid: Check constraint Id.
"""
res = []
SQL = render_template("/".join([self.template_path,
'nodes.sql']),
tid=tid)
status, rset = self.conn.execute_2darray(SQL)
for row in rset['rows']:
if "convalidated" in row and row["convalidated"]:
icon = "icon-check_constraints_bad"
valid = False
else:
icon = "icon-check_constraints"
valid = True
res.append(
self.blueprint.generate_browser_node(
row['oid'],
tid,
row['name'],
icon=icon,
valid=valid
))
return make_json_response(
data=res,
status=200
)
def get_nodes(self, gid, sid, did, scid, tid, cid=None):
"""
This function returns all event check constraint as a list.
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
scid: Schema ID
tid: Table ID
cid: Check constraint ID
Returns:
"""
driver = get_driver(PG_DEFAULT_DRIVER)
self.manager = driver.connection_manager(sid)
self.conn = self.manager.connection(did=did)
self.qtIdent = driver.qtIdent
# Set the template path for the SQL scripts
self.template_path = 'check_constraint/sql/#{0}#'.format(self.manager.version)
SQL = render_template("/".join([self.template_path,
'get_parent.sql']),
tid=tid)
status, rset = self.conn.execute_2darray(SQL)
if not status:
return internal_server_error(errormsg=rset)
self.schema = rset['rows'][0]['schema']
self.table = rset['rows'][0]['table']
res = []
SQL = render_template("/".join([self.template_path,
'nodes.sql']),
tid=tid)
status, rset = self.conn.execute_2darray(SQL)
for row in rset['rows']:
if "convalidated" in row and row["convalidated"]:
icon = "icon-check_constraints_bad"
valid = False
else:
icon = "icon-check_constraints"
valid = True
res.append(
self.blueprint.generate_browser_node(
row['oid'],
tid,
row['name'],
icon=icon,
valid=valid
))
return res
@check_precondition
def properties(self, gid, sid, did, scid, tid, cid):
"""
Returns the Check Constraints property.
Args:
gid: Server Group Id
sid: Server Id
did: Database Id
scid: Schema Id
tid: Check Id
cid: Check Constraint Id
"""
SQL = render_template("/".join([self.template_path,
'properties.sql']),
tid=tid, cid=cid)
status, res = self.conn.execute_dict(SQL)
if not status:
return internal_server_error(errormsg=res)
if len(res['rows']) == 0:
return gone(
_("Could not find the object on the server.")
)
data = res['rows'][0]
return ajax_response(
response=data,
status=200
)
@check_precondition
def create(self, gid, sid, did, scid, tid, cid=None):
"""
This function will create a primary key.
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
scid: Schema ID
tid: Table ID
cid: Check constraint ID
Returns:
"""
required_args = ['consrc']
data = request.form if request.form else json.loads(
request.data, encoding='utf-8'
)
for k, v in data.items():
try:
data[k] = json.loads(v, encoding='utf-8')
except (ValueError, TypeError, KeyError):
data[k] = v
for arg in required_args:
if arg not in data or data[arg] == '':
return make_json_response(
status=400,
success=0,
errormsg=_(
"Could not find the required parameter (%s)." % arg
)
)
data['schema'] = self.schema
data['table'] = self.table
try:
if 'name' not in data or data['name'] == "":
SQL = "BEGIN;"
# Start transaction.
status, res = self.conn.execute_scalar(SQL)
if not status:
self.end_transaction()
return internal_server_error(errormsg=res)
# The below SQL will execute CREATE DDL only
SQL = render_template(
"/".join([self.template_path, 'create.sql']),
data=data
)
status, msg = self.conn.execute_scalar(SQL)
if not status:
self.end_transaction()
return internal_server_error(errormsg=msg)
if 'name' not in data or data['name'] == "":
sql = render_template(
"/".join([self.template_path,
'get_oid_with_transaction.sql'],
),
tid=tid)
status, res = self.conn.execute_dict(sql)
if not status:
self.end_transaction()
return internal_server_error(errormsg=res)
self.end_transaction()
data['name'] = res['rows'][0]['name']
else:
sql = render_template("/".join([self.template_path, 'get_oid.sql']),
tid=tid,
name=data['name'])
status, res = self.conn.execute_dict(sql)
if not status:
self.end_transaction()
return internal_server_error(errormsg=res)
if "convalidated" in res['rows'][0] and res['rows'][0]["convalidated"]:
icon = "icon-check_constraints_bad"
valid = False
else:
icon = "icon-check_constraints"
valid = True
return jsonify(
node=self.blueprint.generate_browser_node(
res['rows'][0]['oid'],
tid,
data['name'],
icon=icon,
valid=valid
)
)
except Exception as e:
self.end_transaction()
return make_json_response(
status=400,
success=0,
errormsg=e
)
@check_precondition
def delete(self, gid, sid, did, scid, tid, cid):
"""
Drops the Check Constraint object.
Args:
gid: Server Group Id
sid: Server Id
did: Database Id
scid: Schema Id
tid: Check Id
cid: Check Constraint Id
"""
try:
SQL = render_template("/".join([self.template_path,
'properties.sql']),
tid=tid, cid=cid)
status, res = self.conn.execute_dict(SQL)
if not status:
return internal_server_error(errormsg=res)
if not res['rows']:
return make_json_response(
success=0,
errormsg=_(
'Error: Object not found.'
),
info=_(
'The specified check constraint could not be found.\n'
)
)
data = res['rows'][0]
SQL = render_template("/".join([self.template_path,
'delete.sql']),
data=data)
status, res = self.conn.execute_scalar(SQL)
if not status:
return internal_server_error(errormsg=res)
return make_json_response(
success=1,
info=_("Check Constraint dropped."),
data={
'id': tid,
'scid': scid,
'sid': sid,
'gid': gid,
'did': did
}
)
except Exception as e:
return internal_server_error(errormsg=str(e))
@check_precondition
def update(self, gid, sid, did, scid, tid, cid):
"""
Updates the Check Constraint object.
Args:
gid: Server Group Id
sid: Server Id
did: Database Id
scid: Schema Id
tid: Table Id
cid: Check Constraint Id
"""
data = request.form if request.form else json.loads(
request.data, encoding='utf-8'
)
try:
data['schema'] = self.schema
data['table'] = self.table
SQL, name = self.get_sql(gid, sid, data, scid, tid, cid)
if not SQL:
return name
SQL = SQL.strip('\n').strip(' ')
status, res = self.conn.execute_scalar(SQL)
if not status:
return internal_server_error(errormsg=res)
sql = render_template("/".join([self.template_path, 'get_name.sql']),
cid=cid)
status, res = self.conn.execute_dict(sql)
if not status:
return internal_server_error(errormsg=res)
if "convalidated" in res['rows'][0] and res['rows'][0]["convalidated"]:
icon = 'icon-check_constraints_bad'
valid = False
else:
icon = 'icon-check_constraints'
valid = True
return jsonify(
node=self.blueprint.generate_browser_node(
cid,
tid,
name,
icon=icon,
valid=valid
)
)
except Exception as e:
return internal_server_error(errormsg=str(e))
@check_precondition
def sql(self, gid, sid, did, scid, tid, cid=None):
"""
Returns the SQL for the Check Constraint object.
Args:
gid: Server Group Id
sid: Server Id
did: Database Id
scid: Schema Id
tid: Table Id
cid: Check Constraint Id
"""
SQL = render_template("/".join([self.template_path,
'properties.sql']),
tid=tid, cid=cid)
status, res = self.conn.execute_dict(SQL)
if not status:
return internal_server_error(errormsg=res)
if len(res['rows']) == 0:
return gone(
_("Could not find the object on the server.")
)
data = res['rows'][0]
data['schema'] = self.schema
data['table'] = self.table
SQL = render_template("/".join([self.template_path,
'create.sql']),
data=data)
sql_header = u"-- Constraint: {0}\n\n-- ".format(data['name'])
sql_header += render_template(
"/".join([self.template_path, 'delete.sql']),
data=data)
sql_header += "\n"
SQL = sql_header + SQL
return ajax_response(response=SQL)
@check_precondition
def msql(self, gid, sid, did, scid, tid, cid=None):
"""
Returns the modified SQL.
Args:
gid: Server Group Id
sid: Server Id
did: Database Id
scid: Schema Id
tid: Table Id
cid: Check Constraint Id
Returns:
Check Constraint object in json format.
"""
data = {}
for k, v in request.args.items():
try:
data[k] = json.loads(v, encoding='utf-8')
except ValueError:
data[k] = v
data['schema'] = self.schema
data['table'] = self.table
try:
sql, name = self.get_sql(gid, sid, data, scid, tid, cid)
if not sql:
return name
sql = sql.strip('\n').strip(' ')
if sql == '':
sql = "--modified SQL"
return make_json_response(
data=sql,
status=200
)
except Exception as e:
return internal_server_error(errormsg=str(e))
def get_sql(self, gid, sid, data, scid, tid, cid=None):
"""
Generates the SQL statements to create/update the Check Constraint.
Args:
gid: Server Group Id
sid: Server Id
did: Database Id
scid: Schema Id
tid: Table Id
cid: Check Constraint Id
"""
if cid is not None:
SQL = render_template("/".join([self.template_path,
'properties.sql']),
tid=tid, cid=cid)
status, res = self.conn.execute_dict(SQL)
if not status:
return False, internal_server_error(errormsg=res)
if len(res['rows']) == 0:
return False, gone(
_("Could not find the object on the server.")
)
old_data = res['rows'][0]
required_args = ['name']
for arg in required_args:
if arg not in data:
data[arg] = old_data[arg]
SQL = render_template(
"/".join([self.template_path, 'update.sql']),
data=data, o_data=old_data, conn=self.conn
)
else:
required_args = ['consrc']
for arg in required_args:
if arg not in data:
return _('-- definition incomplete')
elif isinstance(data[arg], list) and len(data[arg]) < 1:
return _('-- definition incomplete')
SQL = render_template("/".join([self.template_path,
'create.sql']),
data=data)
return SQL, data['name'] if 'name' in data else old_data['name']
@check_precondition
def dependents(self, gid, sid, did, scid, tid, cid):
"""
This function get the dependents and return ajax response
for the Check Constraint node.
Args:
gid: Server Group Id
sid: Server Id
did: Database Id
scid: Schema Id
tid: Table Id
cid: Check Constraint Id
"""
dependents_result = self.get_dependents(self.conn, cid)
return ajax_response(
response=dependents_result,
status=200
)
@check_precondition
def dependencies(self, gid, sid, did, scid, tid, cid):
"""
This function get the dependencies and return ajax response
for the Check Constraint node.
Args:
gid: Server Group Id
sid: Server Id
did: Database Id
scid: Schema Id
tid: Table Id
cid: Check Constraint Id
"""
dependencies_result = self.get_dependencies(self.conn, cid)
return ajax_response(
response=dependencies_result,
status=200
)
@check_precondition
def validate_check_constraint(self, gid, sid, did, scid, tid, cid):
"""
Validate check constraint.
Args:
gid: Server Group Id
sid: Server Id
did: Database Id
scid: Schema Id
tid: Table Id
cid: Check Constraint Id
Returns:
"""
data = {}
try:
data['schema'] = self.schema
data['table'] = self.table
sql = render_template("/".join([self.template_path, 'get_name.sql']), cid=cid)
status, res = self.conn.execute_scalar(sql)
if not status:
return internal_server_error(errormsg=res)
data['name'] = res
sql = render_template("/".join([self.template_path, 'validate.sql']), data=data)
status, res = self.conn.execute_dict(sql)
if not status:
return internal_server_error(errormsg=res)
return make_json_response(
success=1,
info=_("Check constraint updated."),
data={
'id': cid,
'tid': tid,
'scid': scid,
'did': did
}
)
except Exception as e:
return internal_server_error(errormsg=str(e))
constraint = ConstraintRegistry(
'check_constraint', CheckConstraintModule, CheckConstraintView
)
CheckConstraintView.register_node_view(blueprint)
| code/venv/lib/python3.6/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/__init__.py | 28,367 | class CheckConstraintModule(CollectionNodeModule):
This class represents The Check Constraint Module.
Methods:
-------
* __init__(*args, **kwargs)
- Initialize the Check Constraint Module.
* get_nodes(gid, sid, did, scid)
- Generate the Check Constraint collection node.
* node_inode(gid, sid, did, scid)
- Returns Check Constraint node as leaf node.
* script_load()
- Load the module script for the Check Constraint, when any of the
Check node is initialized.
class CheckConstraintView(PGChildNodeView):
This class inherits PGChildNodeView to get the different routes for
the module.
The class is responsible to Create, Read, Update and Delete operations for
the Check Constraint.
Methods:
-------
* module_js():
- Load JS file (check-constraints.js) for this module.
* check_precondition(f):
- Works as a decorator.
- Checks database connection status.
- Attach connection object and template path.
* list(gid, sid, did, scid, doid):
- List the Check Constraints.
* nodes(gid, sid, did, scid):
- Returns all the Check Constraints to generate Nodes in the browser.
* properties(gid, sid, did, scid, doid):
- Returns the Check Constraint properties.
* create(gid, sid, did, scid):
- Creates a new Check Constraint object.
* update(gid, sid, did, scid, doid):
- Updates the Check Constraint object.
* delete(gid, sid, did, scid, doid):
- Drops the Check Constraint object.
* sql(gid, sid, did, scid, doid=None):
- Returns the SQL for the Check Constraint object.
* msql(gid, sid, did, scid, doid=None):
- Returns the modified SQL.
* get_sql(gid, sid, data, scid, tid=None):
- Generates the SQL statements to create/update the Check Constraint.
object.
* dependents(gid, sid, did, scid, tid, cid):
- Returns the dependents for the Check Constraint object.
* dependencies(gid, sid, did, scid, tid, cid):
- Returns the dependencies for the Check Constraint object.
* validate_check_constraint(gid, sid, did, scid, tid, cid):
- Validate check constraint.
Works as a decorator.
Checks database connection status.
Attach connection object and template path.
This function will create a primary key.
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
scid: Schema ID
tid: Table ID
cid: Check constraint ID
Returns:
Returns a snippet of css to include in the page
Drops the Check Constraint object.
Args:
gid: Server Group Id
sid: Server Id
did: Database Id
scid: Schema Id
tid: Check Id
cid: Check Constraint Id
This function get the dependencies and return ajax response
for the Check Constraint node.
Args:
gid: Server Group Id
sid: Server Id
did: Database Id
scid: Schema Id
tid: Table Id
cid: Check Constraint Id
This function get the dependents and return ajax response
for the Check Constraint node.
Args:
gid: Server Group Id
sid: Server Id
did: Database Id
scid: Schema Id
tid: Table Id
cid: Check Constraint Id
End database transaction.
Returns:
This function returns all check constraints
nodes within that collection as a list.
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
scid: Schema ID
tid: Table ID
cid: Cehck constraint ID
Returns:
Generate the Check Constraint collection node.
This function returns all event check constraint as a list.
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
scid: Schema ID
tid: Table ID
cid: Check constraint ID
Returns:
Generates the SQL statements to create/update the Check Constraint.
Args:
gid: Server Group Id
sid: Server Id
did: Database Id
scid: Schema Id
tid: Table Id
cid: Check Constraint Id
List the Check Constraints.
Args:
gid: Server Group Id
sid: Server Id
did: Database Id
scid: Schema Id
tid: Table Id
cid: Check Id
Load JS file (check_constraint.js) for this module.
Returns whether Jinja2 template is used for generating the javascript
module.
Returns the modified SQL.
Args:
gid: Server Group Id
sid: Server Id
did: Database Id
scid: Schema Id
tid: Table Id
cid: Check Constraint Id
Returns:
Check Constraint object in json format.
Returns all the Check Constraints.
Args:
gid: Server Group Id
sid: Server Id
did: Database Id
scid: Schema Id
tid: Table Id
cid: Check constraint Id.
Returns Check Constraint node as leaf node.
Returns all the Check Constraints.
Args:
gid: Server Group Id
sid: Server Id
did: Database Id
scid: Schema Id
tid: Table Id
cid: Check constraint Id.
Returns the Check Constraints property.
Args:
gid: Server Group Id
sid: Server Id
did: Database Id
scid: Schema Id
tid: Check Id
cid: Check Constraint Id
Load the module script for the Check Constraint, when any of the
Check node is initialized.
Returns the SQL for the Check Constraint object.
Args:
gid: Server Group Id
sid: Server Id
did: Database Id
scid: Schema Id
tid: Table Id
cid: Check Constraint Id
Updates the Check Constraint object.
Args:
gid: Server Group Id
sid: Server Id
did: Database Id
scid: Schema Id
tid: Table Id
cid: Check Constraint Id
Validate check constraint.
Args:
gid: Server Group Id
sid: Server Id
did: Database Id
scid: Schema Id
tid: Table Id
cid: Check Constraint Id
Returns:
Implements the Check Constraint Module.
pgAdmin 4 - PostgreSQL Tools Copyright (C) 2013 - 2017, The pgAdmin Development Team This software is released under the PostgreSQL Licence Set the template path for the SQL scripts Set the template path for the SQL scripts Set the template path for the SQL scripts Start transaction. The below SQL will execute CREATE DDL only | 5,778 | en | 0.420776 |
import json
import subprocess
import ipaddress
import pytest
@pytest.fixture
def add_host():
def _inner(hostname, rack, rank, appliance):
cmd = f'stack add host {hostname} rack={rack} rank={rank} appliance={appliance}'
result = subprocess.run(cmd.split())
if result.returncode != 0:
pytest.fail('unable to add a dummy host')
# First use of the fixture adds backend-0-0
_inner('backend-0-0', '0', '0', 'backend')
# Then return the inner function, so we can call it inside the test
# to get more hosts added
return _inner
@pytest.fixture
def add_host_with_interface():
def _inner(hostname, rack, rank, appliance, interface):
cmd = f'stack add host {hostname} rack={rack} rank={rank} appliance={appliance}'
result = subprocess.run(cmd.split())
if result.returncode != 0:
pytest.fail('unable to add a dummy host')
cmd = f'stack add host interface {hostname} interface={interface}'
result = subprocess.run(cmd.split())
if result.returncode != 0:
pytest.fail('unable to add a dummy interface')
_inner('backend-0-0', '0', '0', 'backend', 'eth0')
return _inner
@pytest.fixture
def add_ib_switch():
def _inner(hostname, rack, rank, appliance, make, model, sw_type):
cmd = f'stack add host {hostname} rack={rack} rank={rank} appliance={appliance}'
result = subprocess.run(cmd.split())
if result.returncode != 0:
pytest.fail('unable to add a dummy host')
cmd = f'stack set host attr {hostname} attr=component.make value={make}'
result = subprocess.run(cmd.split())
if result.returncode != 0:
pytest.fail('unable to set make')
cmd = f'stack set host attr {hostname} attr=component.model value={model}'
result = subprocess.run(cmd.split())
if result.returncode != 0:
pytest.fail('unable to set model')
cmd = f'stack set host attr {hostname} attr=switch_type value={sw_type}'
result = subprocess.run(cmd.split())
if result.returncode != 0:
pytest.fail('unable to set switch type')
_inner('switch-0-0', '0', '0', 'switch', 'Mellanox', 'm7800', 'infiniband')
return _inner
@pytest.fixture
def add_ib_switch_partition():
def _inner(switch_name, partition_name, options):
cmd = f'stack add switch partition {switch_name} name={partition_name} '
if options is not None:
cmd += f'options={options}'
result = subprocess.run(cmd.split())
if result.returncode != 0:
pytest.fail('unable to add a dummy switch partition')
_inner('switch-0-0', 'Default', '')
return _inner
@pytest.fixture
def add_switch():
def _inner(hostname, rack, rank, appliance, make, model):
cmd = f'stack add host {hostname} rack={rack} rank={rank} appliance={appliance}'
result = subprocess.run(cmd.split())
if result.returncode != 0:
pytest.fail('unable to add a dummy host')
cmd = f'stack set host attr {hostname} attr=component.make value={make}'
result = subprocess.run(cmd.split())
if result.returncode != 0:
pytest.fail('unable to set make')
cmd = f'stack set host attr {hostname} attr=component.model value={model}'
result = subprocess.run(cmd.split())
if result.returncode != 0:
pytest.fail('unable to set model')
_inner('switch-0-0', '0', '0', 'switch', 'fake', 'unrl')
return _inner
@pytest.fixture
def add_appliance(host):
def _inner(name):
result = host.run(f'stack add appliance {name}')
if result.rc != 0:
pytest.fail(f'unable to add dummy appliance "{name}"')
# First use of the fixture adds appliance "test"
_inner('test')
# Then return the inner function, so we can call it inside the test
# to get more appliances added
return _inner
@pytest.fixture
def add_box(host):
def _inner(name):
result = host.run(f'stack add box {name}')
if result.rc != 0:
pytest.fail(f'unable to add dummy box "{name}"')
# First use of the fixture adds box "test"
_inner('test')
# Then return the inner function, so we can call it inside the test
# to get more boxes added
return _inner
@pytest.fixture
def add_cart(host):
def _inner(name):
result = host.run(f'stack add cart {name}')
if result.rc != 0:
pytest.fail(f'unable to add dummy cart "{name}"')
# First use of the fixture adds cart "test"
_inner('test')
# Then return the inner function, so we can call it inside the test
# to get more carts added
return _inner
@pytest.fixture
def add_environment(host):
def _inner(name):
result = host.run(f'stack add environment {name}')
if result.rc != 0:
pytest.fail(f'unable to add dummy environment "{name}"')
# First use of the fixture adds environment "test"
_inner('test')
# Then return the inner function, so we can call it inside the test
# to get more environments added
return _inner
@pytest.fixture
def add_group(host):
def _inner(name):
result = host.run(f'stack add group {name}')
if result.rc != 0:
pytest.fail(f'unable to add dummy group "{name}"')
# First use of the fixture adds group "test"
_inner('test')
# Then return the inner function, so we can call it inside the test
# to get more groups added
return _inner
@pytest.fixture
def add_network(host):
"""Adds a network to the stacki db. For historical reasons the first test network this creates is pxe=False."""
def _inner(name, address, pxe = False):
result = host.run(
f'stack add network {name} address={address} mask=255.255.255.0 pxe={pxe}'
)
if result.rc != 0:
pytest.fail(f'unable to add dummy network "{name}"')
# First use of the fixture adds network "test"
_inner('test', '192.168.0.0')
# Then return the inner function, so we can call it inside the test
# to get more networks added
return _inner
@pytest.fixture
def add_host_with_net(host, add_host_with_interface, add_network):
"""Adds a host with a network. The first network this adds defaults to pxe=True."""
def _inner(hostname, rack, rank, appliance, interface, ip, network, address, pxe):
# Add the host with an interface.
add_host_with_interface(hostname = hostname, rack = rack, rank = rank, appliance = appliance, interface = interface)
# Add the network.
add_network(name = network, address = address, pxe = pxe)
# Associate it to the interface.
result = host.run(f"stack set host interface network {hostname} network={network} interface={interface}")
assert result.rc == 0
# Set the interface IP
result = host.run(f"stack set host interface ip {hostname} ip={ip} network={network}")
assert result.rc == 0
# Add it to the frontend, because a lot of things in stacki expect backends to share networks with
# frontends.
result = host.run("stack list host interface a:frontend output-format=json")
assert result.rc == 0
# Try to figure out if the frontend has an interface on this network already.
interface_on_network = False
for frontend_interface in json.loads(result.stdout):
if frontend_interface["network"] == network:
interface_on_network = True
break
if interface_on_network:
return
# Need to add an interface to the frontend on this network. Make sure we choose the next latest
# interface name so we don't clash with other interface names.
latest_interface = max(frontend_interface["interface"] for frontend_interface in json.loads(result.stdout))
# This should be a string, so we tokenize it into characters
new_interface = list(latest_interface)
new_interface[-1] = str(int(new_interface[-1]) + 1)
new_interface = "".join(new_interface)
result = host.run(f"stack add host interface a:frontend interface={new_interface} network={network} ip={ipaddress.ip_address(ip) + 1}")
assert result.rc == 0
# First use of the add_host_with_interface fixture adds backend-0-0 with interface eth0.
# The first use of add_network adds a network called test, but that's not PXE so we don't want to use it.
# So the first call of this fixture needs to remove the test network, recreate it as a PXE network, and
# associate the network with the host's interface.
result = host.run(f"stack remove network test")
assert result.rc == 0
add_network(name = "test", address = "192.168.0.0", pxe = True)
result = host.run(f"stack set host interface network backend-0-0 network=test interface=eth0 ip=192.168.0.3")
assert result.rc == 0
# Add a frontend interface on the network.
result = host.run(f"stack add host interface a:frontend interface=eth2 network=test ip=192.168.0.2")
assert result.rc == 0
return _inner
@pytest.fixture(
params = (
("", "exec=True"),
("", "| bash -x"),
("document=", "exec=True"),
("document=", "| bash -x"),
),
ids = ("stack_load_exec", "stack_load_bash", "stack_load_document_exec", "stack_load_document_bash"),
)
def stack_load(request, host):
"""This fixture is used to run `stack load` on the host during integration tests.
There are 4 essentially equivalent ways of loading and running a dump.json. Using
this test fixture ensures that all 4 are tested. I.E:
stack load dump_file exec=True
stack load document=dump_file exec=True
stack load dump_file | bash -x
stack load document=dump_file | bash -x
"""
param_string, exec_string = request.param
def _load(dump_file, **kwargs):
if "exec" in kwargs:
raise ValueError("Cannot pass exec param to this fixture. It handles it for you.")
if "document" in kwargs:
raise ValueError("Cannot pass document param to this fixture. It handles it for you.")
kwargs_string = " ".join(f"{key}={value}" for key, value in kwargs.items())
return host.run(f"stack load {param_string}{dump_file} {exec_string} {kwargs_string}")
return _load
@pytest.fixture
def fake_local_firmware_file(tmp_path_factory):
"""Creates a fake local firmware file and returns a pathlib.Path object that points to it."""
# Add a fake piece of firmware.
fake_firmware_file = tmp_path_factory.mktemp("fake_firmware") / "foo.img"
fake_firmware_file.write_text("foofakefirmware")
return fake_firmware_file
| test-framework/test-suites/integration/tests/fixtures/add_data.py | 9,805 | Adds a host with a network. The first network this adds defaults to pxe=True.
Adds a network to the stacki db. For historical reasons the first test network this creates is pxe=False.
Creates a fake local firmware file and returns a pathlib.Path object that points to it.
This fixture is used to run `stack load` on the host during integration tests.
There are 4 essentially equivalent ways of loading and running a dump.json. Using
this test fixture ensures that all 4 are tested. I.E:
stack load dump_file exec=True
stack load document=dump_file exec=True
stack load dump_file | bash -x
stack load document=dump_file | bash -x
First use of the fixture adds backend-0-0 Then return the inner function, so we can call it inside the test to get more hosts added First use of the fixture adds appliance "test" Then return the inner function, so we can call it inside the test to get more appliances added First use of the fixture adds box "test" Then return the inner function, so we can call it inside the test to get more boxes added First use of the fixture adds cart "test" Then return the inner function, so we can call it inside the test to get more carts added First use of the fixture adds environment "test" Then return the inner function, so we can call it inside the test to get more environments added First use of the fixture adds group "test" Then return the inner function, so we can call it inside the test to get more groups added First use of the fixture adds network "test" Then return the inner function, so we can call it inside the test to get more networks added Add the host with an interface. Add the network. Associate it to the interface. Set the interface IP Add it to the frontend, because a lot of things in stacki expect backends to share networks with frontends. Try to figure out if the frontend has an interface on this network already. Need to add an interface to the frontend on this network. Make sure we choose the next latest interface name so we don't clash with other interface names. This should be a string, so we tokenize it into characters First use of the add_host_with_interface fixture adds backend-0-0 with interface eth0. The first use of add_network adds a network called test, but that's not PXE so we don't want to use it. So the first call of this fixture needs to remove the test network, recreate it as a PXE network, and associate the network with the host's interface. Add a frontend interface on the network. Add a fake piece of firmware. | 2,499 | en | 0.822155 |
#!/usr/bin/python
# Copyright (c) 2018-2019 Intel Corporation
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# GOVERNMENT LICENSE RIGHTS-OPEN SOURCE SOFTWARE
# The Government's rights to use, modify, reproduce, release, perform, display,
# or disclose this software are subject to the terms of the Apache License as
# provided in Contract No. 8F-30005.
# Any reproduction of computer software, computer software documentation, or
# portions thereof marked with this legend must also reproduce the markings.
"""
This script runs the rdb tests. From the command line the tests are run with:
server:
orterun -N 1 --report-uri /tmp/urifile -x LD_LIBRARY_PATH
daos_server -o <builddir>/utils/config/examples/daos_server_rdb_tests.yml
start -d ./ -t 1 -m vos,rdb,rsvc,mgmt,rdbt
client:
orterun --ompi-server file:/tmp/urifile <debug_cmds> -np 1 rdbt init
--group=daos_server --uuid <uuid>
orterun --ompi-server file:/tmp/urifile <debug_cmds> -np 1 rdbt test --update
--group=daos_server
orterun --ompi-server file:/tmp/urifile <debug_cmds> -np 1 rdbt test
--group=daos_server
orterun --ompi-server file:/tmp/urifile <debug_cmds> -np 1 rdbt fini
--group=daos_server
Where debug_cmds = -x D_LOG_MASK=DEBUG,RPC=ERR,MEM=ERR -x DD_SUBSYS=all
-x DD_MASK=all
This script automates the process.
"""
import subprocess
import os
import sys
import time
import signal
import shlex
import string
build_root = os.path.join(sys.path[0], "../../../")
sys.path.insert(0, os.path.join(build_root, "utils/sl"))
from build_info import BuildInfo
from env_modules import load_mpi
from distutils.spawn import find_executable
urifile = "/tmp/urifile"
pid_file = "/tmp/" + str(os.getpid()) + "_output"
# To avoid repetition of parts of the oretrun command.
client_prefix = ""
client_suffix = ""
# In case orterun has quit but the daos_server is still running, save the PID.
#daos_server = None
class ServerFailedToStart(Exception):
pass
class ServerTimedOut(Exception):
pass
def set_logfile(config, logfile):
f = open(config, "r+")
for line in f.readlines():
string.replace(line,
" log_file: /tmp/server.log",
" log_file: {}".format(logfile))
f.close()
def start_server(binfo, orterun):
"""
Start the DAOS server with an orterun command as a child process. We use
subprocess.Popen since it returns control to the calling process and
provides access to the polling feature.
"""
config_file = os.path.join(build_root, "utils", "config", "examples",
"daos_server_unittests.yml")
log_file = os.path.join(binfo.get("PREFIX"),
"TESTING",
"daos-rdb-test.log")
set_logfile(config_file, log_file) # set D_LOG_FILE through config file
print("Starting DAOS server\n")
cmd = orterun
cmd += " -N 1 --report-uri {} ".format(urifile)
cmd += "-x LD_LIBRARY_PATH "
cmd += binfo.get("PREFIX") + "/bin/daos_server "
cmd += "--debug --config {} ".format(config_file)
cmd += "start -d ./ -t 1 -m vos,rdb,rsvc,mgmt,rdbt -i --recreate-superblocks "
print("Running command:\n{}".format(cmd))
sys.stdout.flush()
try:
p = subprocess.Popen(shlex.split(cmd))
return p
except Exception as e:
raise ServerFailedToStart("Server failed to start:\n{}".format(e))
def run_client(segment_type):
"""
There are four client segments to be run, init, update, test, and fini.
The command line varies slightly for each and in some cases there is a
tail after the suffix.
"""
tail = ""
if segment_type == "init":
uuid = subprocess.check_output(['uuidgen'])
tail = " --uuid {}".format(uuid)
elif segment_type == "update":
segment_type = "test --update"
cmd = client_prefix + segment_type + client_suffix + tail
print("Running command:\n{}".format(cmd))
rc = os.system(cmd)
if rc:
raise Exception("command {} failed with return code {}\n".format(
cmd, rc))
return 0
def pid_info(output_line):
"""
Take a line of 'ps -o pid,comm' output and return the PID number and name.
The line looks something like:
9108 orterun
or
10183 daos_server
Need both items. Return a tuple (name, pid)
Note: there could be leading spaces on the pid.
"""
info = output_line.lstrip().split()
try:
return info[1], info[0]
except Exception as e:
print("Unable to retrieve PID info from {}".format(output_line))
return "", None
def find_child(parent_pid, child_name):
"""
Given a PID and a process name, see if this PID has any children with the
specified name. If is does, return the child PID. If not, return None.
ps -o pid,comm --no-headers --ppid <pid> gives output that looks like this:
41108 orterun
41519 ps
"""
child_pid = None
cmd = ['ps', '-o', 'pid,comm', '--no-headers', '--ppid', str(parent_pid)]
try:
res = subprocess.check_output(cmd)
except subprocess.CalledProcessError:
# parent_pid has no children
return None
except Exception as e:
print("ps command failed with: {}".format(e))
return None
# Get rid of the trailing blank line from subprocess.check_output
res = [s for s in res.splitlines() if s]
for line in res:
try:
current_name, current_pid = pid_info(line)
except Exception as e:
print("Unable to extract pid and process name from {}".format(
line))
continue
if current_pid is None:
return None
if current_name.startswith(child_name):
# This is the droid, uh, child we're looking for
return current_pid
child_pid = find_child(current_pid, child_name)
if child_pid is not None:
return child_pid
return child_pid
def daos_server_pid():
"""
Find the pid for the daos_server. Start drilling down from the parent
(current) process until we get output where one line contains
"daos_io_server" or "daos_server".
"""
parent_pid = os.getpid()
return find_child(parent_pid, "daos_")
def cleanup(daos_server):
""" Perform cleanup operations. Shut down the DAOS server by killing the
child processes that have been created. If the daos_server process is
killed, so are the processes for daos_io_server and orterun (theoretically).
It has been observed on occasion to go zombie until orterun itself is
killed.
"""
# Get PID of the daos server
cmd = "{} signal.SIGKILL".format(daos_server)
try:
os.kill(int(daos_server), signal.SIGKILL)
print("Shut down DAOS server with os.kill({} signal.SIGKILL)".format(
daos_server))
except Exception as e:
if daos_server is None:
print("No PID was found for the DAOS server")
elif "No such process" in e:
print("The daos_server process is no longer available"
" and could not be killed.")
else:
print("Unable to shut down DAOS server: {}".format(e))
if __name__ == "__main__":
"""
Start a DAOS server and then run the four stages of the client.
"""
print("Running rdb tests")
rc = 0
binfo = BuildInfo(os.path.join(build_root, ".build_vars.json"));
debug_cmds = "-x D_LOG_MASK=DEBUG,RPC=ERR,MEM=ERR " + \
"-x DD_SUBSYS=all -x DD_MASK=all"
load_mpi('openmpi')
orterun = find_executable('orterun')
if orterun is None:
raise ServerFailedToStart("No orterun installed")
try:
# Server operations
p = start_server(binfo, orterun)
counter = 0
daos_server = daos_server_pid()
while daos_server is None:
if counter >= 120:
raise ServerTimedOut("No DAOS server process detected before "\
"timeout")
counter += 1
time.sleep(1)
daos_server = daos_server_pid()
# Give daos_io_server some time to get ready.
time.sleep(10)
print("DAOS server started")
# Client operations
client_prefix = "{} --ompi-server " \
"file:{} {} --np 1 rdbt ".format(
orterun urifile, debug_cmds)
client_suffix = " --group=daos_server"
# orterun is called for the client four times: init, update, test,
# and fini
client_segments = ['init', 'update', 'test', 'fini']
try:
for segment in client_segments:
run_client(segment)
print("SUCCESS\nrbd tests PASSED")
except Exception as e:
print("rbd tests FAILED")
print("{}".format(e))
rc = 1
except ServerFailedToStart as e:
print("ServerFailedToStart: {}".format(e.message))
print("FAIL")
rc = 1
except ServerTimedOut as e:
print("ServerTimedOut: {}".format(e))
print("FAIL")
rc = 1
finally:
# Shut down the DAOS server when we are finished.
try:
if not p or p.poll() is not None:
# If the server is dead, somthing went very wrong
print("The server is unexpectedly absent.")
print("FAIL")
rc = 1
except NameError:
rc = 1
try:
cleanup(daos_server)
except NameError:
# The daos_server was never defined.
rc = 1
sys.exit(rc)
| src/rdb/tests/rdb_test_runner.py | 10,659 | !/usr/bin/python Copyright (c) 2018-2019 Intel Corporation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. GOVERNMENT LICENSE RIGHTS-OPEN SOURCE SOFTWARE The Government's rights to use, modify, reproduce, release, perform, display, or disclose this software are subject to the terms of the Apache License as provided in Contract No. 8F-30005. Any reproduction of computer software, computer software documentation, or portions thereof marked with this legend must also reproduce the markings. To avoid repetition of parts of the oretrun command. In case orterun has quit but the daos_server is still running, save the PID.daos_server = None set D_LOG_FILE through config file parent_pid has no children Get rid of the trailing blank line from subprocess.check_output This is the droid, uh, child we're looking for Get PID of the daos server Server operations Give daos_io_server some time to get ready. Client operations orterun is called for the client four times: init, update, test, and fini Shut down the DAOS server when we are finished. If the server is dead, somthing went very wrong The daos_server was never defined. | 2,098 | en | 0.891118 |
"""
Self-supervised learning samplers.
"""
# Authors: Hubert Banville <hubert.jbanville@gmail.com>
#
# License: BSD (3-clause)
import numpy as np
from . import RecordingSampler
class RelativePositioningSampler(RecordingSampler):
"""Sample examples for the relative positioning task from [Banville2020]_.
Sample examples as tuples of two window indices, with a label indicating
whether the windows are close or far, as defined by tau_pos and tau_neg.
Parameters
----------
metadata : pd.DataFrame
See RecordingSampler.
tau_pos : int
Size of the positive context, in samples. A positive pair contains two
windows x1 and x2 which are separated by at most `tau_pos` samples.
tau_neg : int
Size of the negative context, in samples. A negative pair contains two
windows x1 and x2 which are separated by at least `tau_neg` samples and
at most `tau_max` samples. Ignored if `same_rec_neg` is False.
n_examples : int
Number of pairs to extract.
tau_max : int | None
See `tau_neg`.
same_rec_neg : bool
If True, sample negative pairs from within the same recording. If
False, sample negative pairs from two different recordings.
random_state : None | np.RandomState | int
Random state.
References
----------
.. [Banville2020] Banville, H., Chehab, O., Hyvärinen, A., Engemann, D. A.,
& Gramfort, A. (2020). Uncovering the structure of clinical EEG
signals with self-supervised learning.
arXiv preprint arXiv:2007.16104.
"""
def __init__(self, metadata, tau_pos, tau_neg, n_examples, tau_max=None,
same_rec_neg=True, random_state=None):
super().__init__(metadata, random_state=random_state)
self.tau_pos = tau_pos
self.tau_neg = tau_neg
self.tau_max = np.inf if tau_max is None else tau_max
self.n_examples = n_examples
self.same_rec_neg = same_rec_neg
if not same_rec_neg and self.n_recordings < 2:
raise ValueError('More than one recording must be available when '
'using across-recording negative sampling.')
def _sample_pair(self):
"""Sample a pair of two windows.
"""
# Sample first window
win_ind1, rec_ind1 = self.sample_window()
ts1 = self.metadata.iloc[win_ind1]['i_start_in_trial']
ts = self.info.iloc[rec_ind1]['i_start_in_trial']
# Decide whether the pair will be positive or negative
pair_type = self.rng.binomial(1, 0.5)
win_ind2 = None
if pair_type == 0: # Negative example
if self.same_rec_neg:
mask = (
((ts <= ts1 - self.tau_neg) & (ts >= ts1 - self.tau_max)) |
((ts >= ts1 + self.tau_neg) & (ts <= ts1 + self.tau_max))
)
else:
rec_ind2 = rec_ind1
while rec_ind2 == rec_ind1:
win_ind2, rec_ind2 = self.sample_window()
elif pair_type == 1: # Positive example
mask = (ts >= ts1 - self.tau_pos) & (ts <= ts1 + self.tau_pos)
if win_ind2 is None:
mask[ts == ts1] = False # same window cannot be sampled twice
if sum(mask) == 0:
raise NotImplementedError
win_ind2 = self.rng.choice(self.info.iloc[rec_ind1]['index'][mask])
return win_ind1, win_ind2, float(pair_type)
def presample(self):
"""Presample examples.
Once presampled, the examples are the same from one epoch to another.
"""
self.examples = [self._sample_pair() for _ in range(self.n_examples)]
return self
def __iter__(self):
"""Iterate over pairs.
Yields
------
(int): position of the first window in the dataset.
(int): position of the second window in the dataset.
(float): 0 for negative pair, 1 for positive pair.
"""
for i in range(self.n_examples):
if hasattr(self, 'examples'):
yield self.examples[i]
else:
yield self._sample_pair()
def __len__(self):
return self.n_examples
| braindecode/samplers/ssl.py | 4,282 | Sample examples for the relative positioning task from [Banville2020]_.
Sample examples as tuples of two window indices, with a label indicating
whether the windows are close or far, as defined by tau_pos and tau_neg.
Parameters
----------
metadata : pd.DataFrame
See RecordingSampler.
tau_pos : int
Size of the positive context, in samples. A positive pair contains two
windows x1 and x2 which are separated by at most `tau_pos` samples.
tau_neg : int
Size of the negative context, in samples. A negative pair contains two
windows x1 and x2 which are separated by at least `tau_neg` samples and
at most `tau_max` samples. Ignored if `same_rec_neg` is False.
n_examples : int
Number of pairs to extract.
tau_max : int | None
See `tau_neg`.
same_rec_neg : bool
If True, sample negative pairs from within the same recording. If
False, sample negative pairs from two different recordings.
random_state : None | np.RandomState | int
Random state.
References
----------
.. [Banville2020] Banville, H., Chehab, O., Hyvärinen, A., Engemann, D. A.,
& Gramfort, A. (2020). Uncovering the structure of clinical EEG
signals with self-supervised learning.
arXiv preprint arXiv:2007.16104.
Iterate over pairs.
Yields
------
(int): position of the first window in the dataset.
(int): position of the second window in the dataset.
(float): 0 for negative pair, 1 for positive pair.
Sample a pair of two windows.
Presample examples.
Once presampled, the examples are the same from one epoch to another.
Self-supervised learning samplers.
Authors: Hubert Banville <hubert.jbanville@gmail.com> License: BSD (3-clause) Sample first window Decide whether the pair will be positive or negative Negative example Positive example same window cannot be sampled twice | 1,835 | en | 0.698177 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# (C)Eduardo Ribeiro - 1600820
class Contract:
id = 0
school_code = 0
school_name = ""
n_contract = 0
n_hours_per_week = 0
contract_end_date = ""
application_deadline = ""
recruitment_group = ""
county = ""
district = ""
class_project = ""
qualifications = ""
def __init__(
self,
id,
school_code,
school_name,
n_contract,
n_hours_per_week,
contract_end_date,
application_deadline,
recruitment_group,
county,
district,
class_project,
qualifications,
):
self.id = id
self.school_code = school_code
self.school_name = school_name
self.n_contract = n_contract
self.n_hours_per_week = n_hours_per_week
self.contract_end_date = contract_end_date
self.application_deadline = application_deadline
self.recruitment_group = recruitment_group
self.county = county
self.district = district
self.class_project = class_project
self.qualifications = qualifications
| sigrhe_contract.py | 1,158 | !/usr/bin/env python3 -*- coding: utf-8 -*- (C)Eduardo Ribeiro - 1600820 | 72 | en | 0.405016 |
"""
Django settings for profiles_project project.
Generated by 'django-admin startproject' using Django 3.1.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
import os
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '_q_mx#x+8x13+_m=0*vp(!di0evkomq0*!@z7^-l+7!2izak14'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = bool(int(os.environ.get('DEBUG',1)))
ALLOWED_HOSTS = [
'ec2-15-188-8-39.eu-west-3.compute.amazonaws.com',
'127.0.0.1'
]
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'profiles_api',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'profiles_project.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'profiles_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
AUTH_USER_MODEL = 'profiles_api.UserProfile'
STATIC_ROOT = 'static/' | profiles_project/settings.py | 3,349 | Django settings for profiles_project project.
Generated by 'django-admin startproject' using Django 3.1.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
Build paths inside the project like this: BASE_DIR / 'subdir'. Quick-start development settings - unsuitable for production See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ SECURITY WARNING: keep the secret key used in production secret! SECURITY WARNING: don't run with debug turned on in production! Application definition Database https://docs.djangoproject.com/en/3.1/ref/settings/databases Password validation https://docs.djangoproject.com/en/3.1/ref/settings/auth-password-validators Internationalization https://docs.djangoproject.com/en/3.1/topics/i18n/ Static files (CSS, JavaScript, Images) https://docs.djangoproject.com/en/3.1/howto/static-files/ | 990 | en | 0.69694 |
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class CbtfArgonavis(CMakePackage):
"""CBTF Argo Navis project contains the CUDA collector and supporting
libraries that was done as a result of a DOE SBIR grant.
"""
homepage = "http://sourceforge.net/p/cbtf/wiki/Home/"
git = "https://github.com/OpenSpeedShop/cbtf-argonavis.git"
version('develop', branch='master')
version('1.9.3', branch='1.9.3')
version('1.9.2', branch='1.9.2')
version('1.9.1.2', branch='1.9.1.2')
version('1.9.1.1', branch='1.9.1.1')
version('1.9.1.0', branch='1.9.1.0')
variant('cti', default=False,
description="Build MRNet with the CTI startup option")
variant('crayfe', default=False,
description="build only the FE tool using the runtime_dir \
to point to target build.")
variant('runtime', default=False,
description="build only the runtime libraries and collectors.")
variant('build_type', default='None', values=('None'),
description='CMake build type')
depends_on("cmake@3.0.2:", type='build')
# To specify ^elfutils@0.170 on the command line spack
# apparently needs/wants this dependency explicity here
# even though it is referenced downstream
depends_on("elf", type="link")
# For boost
depends_on("boost@1.66.0:1.69.0")
# For MRNet
depends_on("mrnet@5.0.1-3:+cti", when='@develop+cti', type=('build', 'link', 'run'))
depends_on("mrnet@5.0.1-3:+lwthreads", when='@develop~cti', type=('build', 'link', 'run'))
depends_on("mrnet@5.0.1-3+cti", when='@1.9.1.0:9999+cti', type=('build', 'link', 'run'))
depends_on("mrnet@5.0.1-3+lwthreads", when='@1.9.1.0:9999~cti', type=('build', 'link', 'run'))
# For CBTF
depends_on("cbtf@develop", when='@develop', type=('build', 'link', 'run'))
depends_on("cbtf@1.9.1.0:9999", when='@1.9.1.0:9999', type=('build', 'link', 'run'))
# For CBTF with cti
depends_on("cbtf@develop+cti", when='@develop+cti', type=('build', 'link', 'run'))
depends_on("cbtf@1.9.1.0:9999+cti", when='@1.9.1.0:9999+cti', type=('build', 'link', 'run'))
# For CBTF with runtime
depends_on("cbtf@develop+runtime", when='@develop+runtime', type=('build', 'link', 'run'))
depends_on("cbtf@1.9.1.0:9999+runtime", when='@1.9.1.0:9999+runtime', type=('build', 'link', 'run'))
# For libmonitor
depends_on("libmonitor@2013.02.18+krellpatch", type=('build', 'link', 'run'))
# For PAPI
depends_on("papi@5.4.1:", type=('build', 'link', 'run'))
# For CBTF-KRELL
depends_on("cbtf-krell@develop", when='@develop', type=('build', 'link', 'run'))
depends_on("cbtf-krell@1.9.1.0:9999", when='@1.9.1.0:9999', type=('build', 'link', 'run'))
depends_on('cbtf-krell@develop+cti', when='@develop+cti', type=('build', 'link', 'run'))
depends_on('cbtf-krell@1.9.1.0:9999+cti', when='@1.9.1.0:9999+cti', type=('build', 'link', 'run'))
depends_on('cbtf-krell@develop+runtime', when='@develop+runtime', type=('build', 'link', 'run'))
depends_on('cbtf-krell@1.9.1.0:9999+runtime', when='@1.9.1.0:9999+runtime', type=('build', 'link', 'run'))
# For CUDA
depends_on("cuda")
parallel = False
build_directory = 'build_cbtf_argonavis'
def cmake_args(self):
spec = self.spec
compile_flags = "-O2 -g"
cmake_args = [
'-DCMAKE_CXX_FLAGS=%s' % compile_flags,
'-DCMAKE_C_FLAGS=%s' % compile_flags,
'-DCUDA_DIR=%s' % spec['cuda'].prefix,
'-DCUDA_INSTALL_PATH=%s' % spec['cuda'].prefix,
'-DCUDA_TOOLKIT_ROOT_DIR=%s' % spec['cuda'].prefix,
'-DCUPTI_DIR=%s' % spec['cuda'].prefix.extras.CUPTI,
'-DCUPTI_ROOT=%s' % spec['cuda'].prefix.extras.CUPTI,
'-DPAPI_ROOT=%s' % spec['papi'].prefix,
'-DCBTF_DIR=%s' % spec['cbtf'].prefix,
'-DCBTF_KRELL_DIR=%s' % spec['cbtf-krell'].prefix,
'-DBOOST_ROOT=%s' % spec['boost'].prefix,
'-DBoost_DIR=%s' % spec['boost'].prefix,
'-DBOOST_LIBRARYDIR=%s' % spec['boost'].prefix.lib,
'-DMRNET_DIR=%s' % spec['mrnet'].prefix,
'-DLIBMONITOR_DIR=%s' % spec['libmonitor'].prefix,
'-DBoost_NO_SYSTEM_PATHS=ON']
return cmake_args
def setup_run_environment(self, env):
"""Set up the compile and runtime environments for a package."""
env.prepend_path(
'LD_LIBRARY_PATH',
self.spec['cuda'].prefix + '/extras/CUPTI/lib64')
def setup_build_environment(self, env):
"""Set up the compile and runtime environments for a package."""
env.prepend_path(
'LD_LIBRARY_PATH',
self.spec['cuda'].prefix + '/extras/CUPTI/lib64')
| var/spack/repos/builtin/packages/cbtf-argonavis/package.py | 4,995 | CBTF Argo Navis project contains the CUDA collector and supporting
libraries that was done as a result of a DOE SBIR grant.
Set up the compile and runtime environments for a package.
Set up the compile and runtime environments for a package.
Copyright 2013-2019 Lawrence Livermore National Security, LLC and other Spack Project Developers. See the top-level COPYRIGHT file for details. SPDX-License-Identifier: (Apache-2.0 OR MIT) To specify ^elfutils@0.170 on the command line spack apparently needs/wants this dependency explicity here even though it is referenced downstream For boost For MRNet For CBTF For CBTF with cti For CBTF with runtime For libmonitor For PAPI For CBTF-KRELL For CUDA | 696 | en | 0.856767 |
"""SentencePiece based word tokenizer module"""
from pathlib import Path
from typing import List
import sentencepiece as spm
from urduhack.stop_words import STOP_WORDS
def _is_token(pieces: list, special_symbol: str = "▁") -> List[str]:
"""
Check for stopwords and actual words in word pieces
Args:
pieces (list): word pieces returned by sentencepiece model
special_symbol (str): spm prefix special symbol for space
Returns:
List of decoded words
"""
decoded = []
for piece in pieces:
if special_symbol not in piece:
if piece in STOP_WORDS or len(piece) > 3:
piece = special_symbol + piece
decoded.append(piece)
else:
decoded.append(piece)
else:
decoded.append(piece)
return decoded
def _load_model(model_path: str) -> spm.SentencePieceProcessor:
"""
Loads pre_trained keras model and vocab file
Args:
model_path (str): Path to the spm model file
Returns:
spm model class instance
"""
spm_model = spm.SentencePieceProcessor()
spm_model.Load(model_file=model_path)
return spm_model
def _is_model_available(model_path: str) -> None:
"""
Check if the models file exist.
Args:
model_path (str): path to the tokenizer model file
Raises:
FileNotFoundError: If model_path does not exist
Returns: None
"""
if not Path(model_path).exists():
_error = "Word tokenizer Model not found!" \
"Please run 'urduhack download' in terminal." \
"Doc: https://urduhack.readthedocs.io/en/stable/installation.html#downloading-models"
raise FileNotFoundError(_error)
| urduhack/tokenization/wtk.py | 1,756 | Check if the models file exist.
Args:
model_path (str): path to the tokenizer model file
Raises:
FileNotFoundError: If model_path does not exist
Returns: None
Check for stopwords and actual words in word pieces
Args:
pieces (list): word pieces returned by sentencepiece model
special_symbol (str): spm prefix special symbol for space
Returns:
List of decoded words
Loads pre_trained keras model and vocab file
Args:
model_path (str): Path to the spm model file
Returns:
spm model class instance
SentencePiece based word tokenizer module | 569 | en | 0.750329 |
"""command line interface for mutation_origin"""
import os
import time
import pickle
from collections import defaultdict
import click
from tqdm import tqdm
import pandas
from numpy import log
from numpy.random import seed as np_seed
from scitrack import CachingLogger
from sklearn.model_selection import train_test_split
from mutation_origin.opt import (_seed, _feature_dim, _enu_path,
_germline_path, _output_path, _flank_size,
_train_size, _enu_ratio,
_numreps, _label_col, _proximal, _usegc,
_training_path, _c_values, _penalty_options,
_n_jobs, _classifier_path, _data_path,
_predictions_path, _alpha_options,
_overwrite, _verbose, _class_prior,
_strategy, _score)
from mutation_origin.preprocess import data_to_numeric
from mutation_origin.encoder import (get_scaler, inverse_transform_response,
transform_response)
from mutation_origin.classify import (logistic_regression, one_class_svm,
predict_origin, naive_bayes, xgboost)
from mutation_origin.util import (dump_json, load_predictions,
get_basename, get_classifier_label,
get_enu_germline_sizes, iter_indices,
load_classifier, open_)
from mutation_origin.postprocess import measure_performance
__author__ = "Gavin Huttley"
__copyright__ = "Copyright 2014, Gavin Huttley"
__credits__ = ["Yicheng Zhu", "Cheng Soon Ong", "Gavin Huttley"]
__license__ = "BSD"
__version__ = "0.3"
__maintainer__ = "Gavin Huttley"
__email__ = "Gavin.Huttley@anu.edu.au"
__status__ = "Development"
LOGGER = CachingLogger()
@click.group()
def main():
"""mutori -- for building and applying classifiers of mutation origin"""
pass
@main.command()
@_seed
@_enu_path
@_germline_path
@_output_path
@_train_size
@_enu_ratio
@_numreps
@_overwrite
def sample_data(enu_path, germline_path, output_path, seed,
train_size,
enu_ratio, numreps, overwrite):
"""creates train/test sample data"""
if seed is None:
seed = int(time.time())
LOGGER.log_args()
LOGGER.log_versions(['sklearn', 'numpy'])
# set the random number seed
np_seed(seed)
start_time = time.time()
os.makedirs(output_path, exist_ok=True)
logfile_path = os.path.join(output_path, "logs/data_sampling.log")
if os.path.exists(logfile_path) and not overwrite:
click.secho(f"Exists: {logfile_path}! use overwrite to force.",
fg='red')
return
LOGGER.log_file_path = logfile_path
LOGGER.input_file(enu_path)
LOGGER.input_file(germline_path)
enu = pandas.read_csv(enu_path, sep="\t", header=0)
germline = pandas.read_csv(germline_path, sep="\t", header=0)
train_size = train_size // 2
test_size = train_size
train_enu_ratio, test_enu_ratio = enu_ratio
enu_train_size, germ_train_size = get_enu_germline_sizes(train_size,
train_enu_ratio)
enu_test_size, germ_test_size = get_enu_germline_sizes(test_size,
test_enu_ratio)
assert min(enu_train_size, germ_train_size,
enu_test_size, germ_test_size) > 0
if (2 * train_size > enu.shape[0] or
2 * train_size > germline.shape[0]):
print(f"ENU data set size: {enu.shape[0]}")
print(f"Germline data set size: {germline.shape[0]}")
print(f"Train set size: {train_size}")
raise ValueError("2 x train size exceeds"
" size of training data source(s)")
for rep in range(numreps):
test_outpath = os.path.join(output_path, f"test-{rep}.tsv.gz")
train_outpath = os.path.join(output_path, f"train-{rep}.tsv.gz")
enu_training, enu_testing = train_test_split(
enu,
test_size=enu_test_size,
train_size=enu_train_size)
germ_training, germ_testing = train_test_split(
germline,
test_size=germ_test_size,
train_size=germ_train_size)
if any(map(lambda x: x.shape[0] == 0,
[enu_training, enu_testing, germ_training, germ_testing])):
raise RuntimeError("screw up in creating test/train set")
# concat the data frames
testing = pandas.concat([enu_testing, germ_testing])
training = pandas.concat([enu_training, germ_training])
# write out, separately, the ENU and Germline data for train and test
testing.to_csv(test_outpath, index=False,
sep="\t", compression='gzip')
training.to_csv(train_outpath, index=False,
sep="\t", compression='gzip')
LOGGER.output_file(test_outpath)
LOGGER.output_file(train_outpath)
duration = time.time() - start_time
LOGGER.log_message("%.2f" % (duration / 60.),
label="run duration (minutes)")
LOGGER.shutdown()
@main.command()
@_training_path
@_output_path
@_label_col
@_seed
@_score
@_flank_size
@_feature_dim
@_proximal
@_usegc
@_c_values
@_penalty_options
@_n_jobs
@_overwrite
@_verbose
def lr_train(training_path, output_path, label_col, seed, scoring,
flank_size, feature_dim, proximal,
usegc, c_values, penalty_options, n_jobs, overwrite, verbose):
"""logistic regression training, validation, dumps optimal model"""
if not seed:
seed = int(time.time())
np_seed(seed)
LOGGER.log_args()
LOGGER.log_versions(['sklearn', 'numpy'])
os.makedirs(output_path, exist_ok=True)
basename = get_basename(training_path)
outpath = os.path.join(output_path, f"{basename}-classifier-lr.pkl.gz")
if os.path.exists(outpath) and not overwrite:
if verbose > 1:
click.secho(f"Skipping. {outpath} exists. "
"use overwrite to force.",
fg='green')
return
logfile_path = os.path.join(output_path,
f"logs/{basename}-training-lr.log")
LOGGER.log_file_path = logfile_path
LOGGER.input_file(training_path)
start_time = time.time()
_, resp, feat, n_dims, names = data_to_numeric(training_path,
label_col, flank_size,
feature_dim, proximal,
usegc)
if usegc:
# we need to scale the data
scaler = get_scaler(feat)
feat = scaler.transform(feat)
classifier = logistic_regression(feat, resp, seed, scoring,
c_values,
penalty_options.split(","), n_jobs)
betas = dict(zip(names, classifier.best_estimator_.coef_.tolist()[0]))
result = dict(classifier=classifier.best_estimator_, betas=betas,
scoring=scoring)
result['feature_params'] = dict(feature_dim=feature_dim,
flank_size=flank_size, proximal=proximal,
usegc=usegc)
if usegc:
result['scaler'] = scaler
with open(outpath, 'wb') as clf_file:
pickle.dump(result, clf_file)
LOGGER.output_file(outpath)
duration = time.time() - start_time
LOGGER.log_message("%.2f" % (duration / 60.),
label="run duration (minutes)")
LOGGER.shutdown()
@main.command()
@_training_path
@_output_path
@_label_col
@_seed
@_score
@_flank_size
@_feature_dim
@_proximal
@_usegc
@_alpha_options
@_class_prior
@_n_jobs
@_overwrite
@_verbose
def nb_train(training_path, output_path, label_col, seed, scoring,
flank_size, feature_dim, proximal,
usegc, alpha_options, class_prior, n_jobs, overwrite, verbose):
"""Naive Bayes training, validation, dumps optimal model"""
if not seed:
seed = int(time.time())
np_seed(seed)
LOGGER.log_args()
LOGGER.log_versions(['sklearn', 'numpy'])
os.makedirs(output_path, exist_ok=True)
basename = get_basename(training_path)
outpath = os.path.join(output_path, f"{basename}-classifier-nb.pkl.gz")
logfile_path = os.path.join(output_path,
f"logs/{basename}-training-nb.log")
if os.path.exists(outpath) and not overwrite:
if verbose > 1:
click.secho(f"Skipping. {outpath} exists. "
"use overwrite to force.",
fg='green')
return
LOGGER.log_file_path = logfile_path
LOGGER.input_file(training_path)
start_time = time.time()
if class_prior is not None:
class_labels = list(class_prior)
encoded = transform_response(class_labels)
ordered = sorted(zip(encoded, class_labels))
class_prior = [class_prior[l] for _, l in ordered]
_, resp, feat, n_dims, names = data_to_numeric(training_path,
label_col, flank_size,
feature_dim, proximal,
usegc)
if usegc:
# we need to scale the data
scaler = get_scaler(feat)
feat = scaler.transform(feat)
classifier = naive_bayes(feat, resp, seed, alpha_options, scoring,
class_prior=class_prior, n_jobs=n_jobs)
betas = dict(zip(names, classifier.best_estimator_.coef_.tolist()[0]))
result = dict(classifier=classifier.best_estimator_, betas=betas,
scoring=scoring)
result['feature_params'] = dict(feature_dim=feature_dim,
flank_size=flank_size, proximal=proximal,
usegc=usegc)
if usegc:
result['scaler'] = scaler
with open_(outpath, 'wb') as clf_file:
pickle.dump(result, clf_file)
LOGGER.output_file(outpath)
duration = time.time() - start_time
LOGGER.log_message("%.2f" % (duration / 60.),
label="run duration (minutes)")
LOGGER.shutdown()
@main.command()
@_training_path
@_output_path
@_label_col
@_seed
@_flank_size
@_feature_dim
@_proximal
@_usegc
@_strategy
@_n_jobs
@_overwrite
@_verbose
def xgboost_train(training_path, output_path, label_col, seed,
flank_size, feature_dim, proximal,
usegc, strategy, n_jobs, overwrite, verbose):
"""Naive Bayes training, validation, dumps optimal model"""
if not seed:
seed = int(time.time())
np_seed(seed)
LOGGER.log_args()
LOGGER.log_versions(['sklearn', 'numpy'])
os.makedirs(output_path, exist_ok=True)
basename = get_basename(training_path)
outpath = os.path.join(output_path, f"{basename}-classifier-xgb.pkl.gz")
logfile_path = os.path.join(output_path,
f"logs/{basename}-training-xgb.log")
if os.path.exists(outpath) and not overwrite:
if verbose > 1:
click.secho(f"Skipping. {outpath} exists. "
"use overwrite to force.",
fg='green')
return
LOGGER.log_file_path = logfile_path
LOGGER.input_file(training_path)
start_time = time.time()
_, resp, feat, n_dims, names = data_to_numeric(training_path,
label_col, flank_size,
feature_dim, proximal,
usegc)
# hacking feature so all -1 > 0
resp = [v if v > 0 else 0 for v in resp]
if usegc:
# we need to scale the data
scaler = get_scaler(feat)
feat = scaler.transform(feat)
classifier = xgboost(feat, resp, seed, strategy, n_jobs, verbose)
result = dict(classifier=classifier)
result['feature_params'] = dict(feature_dim=feature_dim,
flank_size=flank_size, proximal=proximal,
usegc=usegc)
if usegc:
result['scaler'] = scaler
with open(outpath, 'wb') as clf_file:
pickle.dump(result, clf_file)
LOGGER.output_file(outpath)
duration = time.time() - start_time
LOGGER.log_message("%.2f" % (duration / 60.),
label="run duration (minutes)")
LOGGER.shutdown()
@main.command()
@_training_path
@_output_path
@_label_col
@_seed
@_flank_size
@_feature_dim
@_proximal
@_usegc
@_overwrite
@_verbose
def ocs_train(training_path, output_path, label_col, seed,
flank_size, feature_dim, proximal, usegc, overwrite, verbose):
"""one-class svm training for outlier detection"""
if seed is None:
seed = int(time.time())
LOGGER.log_args()
LOGGER.log_versions(['sklearn', 'numpy'])
start_time = time.time()
os.makedirs(output_path, exist_ok=True)
basename = get_basename(training_path)
outpath = os.path.join(output_path, f"{basename}-classifier-ocs.pkl.gz")
logfile_path = os.path.join(output_path,
f"logs/{basename}-training-ocs.log")
if os.path.exists(outpath) and not overwrite:
if verbose > 1:
click.secho(f"Skipping. {outpath} exists. "
"use overwrite to force.",
fg='green')
return
LOGGER.log_file_path = logfile_path
LOGGER.input_file(training_path)
start_time = time.time()
_, _, feat, n_dims, names = data_to_numeric(training_path,
label_col, flank_size,
feature_dim, proximal,
usegc=usegc,
one_class='g')
classifier = one_class_svm(feat, seed)
result = dict(classifier=classifier)
result['feature_params'] = dict(feature_dim=feature_dim,
flank_size=flank_size, proximal=proximal,
usegc=usegc)
with open(outpath, 'wb') as clf_file:
pickle.dump(result, clf_file)
LOGGER.output_file(outpath)
duration = time.time() - start_time
LOGGER.log_message("%.2f" % (duration / 60.),
label="run duration (minutes)")
LOGGER.shutdown()
@main.command()
@_classifier_path
@_data_path
@_output_path
@_label_col
@_class_prior
@_overwrite
@_verbose
def predict(classifier_path, data_path, output_path, label_col, class_prior,
overwrite, verbose):
"""predict labels for data"""
LOGGER.log_args()
LOGGER.log_versions(['sklearn', 'numpy'])
classifier, feature_params, scaler = load_classifier(classifier_path)
class_label = get_classifier_label(classifier)
if class_prior is not None and class_label == 'lr':
# https://stats.stackexchange.com/questions/117592/logistic-regression-prior-correction-at-test-time
# based on above and King and Zeng, we adjust the intercept term such
# that it is incremented by ln(p(1) / p(-1)) where p(1) is the prior
# of a 1 label, p(-1)=1-p(1)
class_labels = list(class_prior)
encoded = transform_response(class_labels)
ordered = sorted(zip(encoded, class_labels))
if 'e' in ordered[0]:
adj = log(class_prior['g'] / class_prior['e'])
else:
adj = log(class_prior['e'] / class_prior['g'])
classifier.intercept_ += adj
basename_class = get_basename(classifier_path)
basename_data = get_basename(data_path)
basename = f"{basename_class}-{basename_data}"
outpath = os.path.join(
output_path,
f"{basename}-predicted-{class_label}.json.gz")
os.makedirs(output_path, exist_ok=True)
logfile_path = os.path.join(output_path,
f"logs/{basename}-predict-{class_label}.log")
if os.path.exists(outpath) and not overwrite:
if verbose > 1:
click.secho(f"Skipping. {outpath} exists. "
"use overwrite to force.",
fg='green')
return
LOGGER.log_file_path = logfile_path
LOGGER.input_file(classifier_path)
LOGGER.input_file(data_path)
start_time = time.time()
# if NB, the score func name is different
if class_label in ("nb", "xgb"):
classifier.decision_function = classifier.predict_proba
fulldata = pandas.read_csv(data_path, sep='\t')
result = {}
result['feature_params'] = feature_params
result['classifier_label'] = class_label
result['classifier_path'] = classifier_path
result['predictions'] = defaultdict(list)
total = fulldata.shape[0] // 2000
pbar = tqdm(iter_indices(
fulldata.shape[0], block_size=2000), ncols=80, total=total)
for indices in pbar:
data = fulldata.iloc[indices]
ids, resp, feat, n_dims, names = data_to_numeric(data,
label_col=label_col,
**feature_params)
if scaler:
feat = scaler.transform(feat)
predictions, scores = predict_origin(classifier, feat)
if class_label in ("nb", "xgb"):
# each `score' is the probability of belong to either class
# reduce to just the first class
scores = scores[:, 1].tolist()
elif class_label == 'ocs':
scores = scores[:, 0].tolist()
predictions = inverse_transform_response(predictions)
result['predictions']['varid'].extend(list(ids))
result['predictions']['predicted'].extend(list(predictions))
result['predictions']['scores'].extend(list(scores))
dump_json(outpath, result)
LOGGER.output_file(outpath)
duration = time.time() - start_time
LOGGER.log_message("%.2f" % (duration / 60.),
label="run duration (minutes)")
LOGGER.shutdown()
# def performance -> produces summary stats on trained classifiers
# requires input data and the predicted results
@main.command()
@_data_path
@_predictions_path
@_output_path
@_label_col
@_overwrite
@_verbose
def performance(data_path, predictions_path, output_path, label_col,
overwrite, verbose):
"""produce measures of classifier performance"""
LOGGER.log_args()
LOGGER.log_versions(['sklearn', 'numpy'])
if not (data_path or predictions_path):
click.secho("Need data sets!", fg="red")
exit()
basename_train = get_basename(data_path)
basename_pred = get_basename(predictions_path)
basename = f"{basename_train}-{basename_pred}"
outpath = os.path.join(
output_path,
f"{basename}-performance.json.gz")
logfile_path = os.path.join(output_path,
f"logs/{basename}-performance.log")
if os.path.exists(outpath) and not overwrite:
if verbose > 1:
click.secho(f"Skipping. {outpath} exists. "
"Use overwrite to force.",
fg='green')
return
LOGGER.log_file_path = logfile_path
LOGGER.input_file(data_path)
LOGGER.input_file(predictions_path)
orig = pandas.read_csv(data_path, sep="\t")
predicted, feature_params, classifier_path, label =\
load_predictions(predictions_path)
result = measure_performance(orig, predicted,
label_col)
result["feature_params"] = feature_params
result["classifier_path"] = classifier_path
result["classifier_label"] = label
dump_json(outpath, result)
LOGGER.shutdown()
if __name__ == "__main__":
main()
| mutation_origin/cli.py | 20,002 | logistic regression training, validation, dumps optimal model
mutori -- for building and applying classifiers of mutation origin
Naive Bayes training, validation, dumps optimal model
one-class svm training for outlier detection
produce measures of classifier performance
predict labels for data
creates train/test sample data
Naive Bayes training, validation, dumps optimal model
command line interface for mutation_origin
set the random number seed concat the data frames write out, separately, the ENU and Germline data for train and test we need to scale the data we need to scale the data hacking feature so all -1 > 0 we need to scale the data https://stats.stackexchange.com/questions/117592/logistic-regression-prior-correction-at-test-time based on above and King and Zeng, we adjust the intercept term such that it is incremented by ln(p(1) / p(-1)) where p(1) is the prior of a 1 label, p(-1)=1-p(1) if NB, the score func name is different each `score' is the probability of belong to either class reduce to just the first class def performance -> produces summary stats on trained classifiers requires input data and the predicted results | 1,151 | en | 0.812313 |
"""
My first application
"""
import toga
from toga.style import Pack
from toga.style.pack import COLUMN, ROW
class HelloWorld(toga.App):
def startup(self):
"""
Construct and show the Toga application.
Usually, you would add your application to a main content box.
We then create a main window (with a name matching the app), and
show the main window.
"""
main_box = toga.Box(style=Pack(direction=COLUMN))
name_label = toga.Label(
'Your name: ',
style=Pack(padding=(0 ,5))
)
self.name_input = toga.TextInput(style=Pack(flex=1))
name_box = toga.Box(style=Pack(direction=ROW, padding=5))
name_box.add(name_label)
name_box.add(self.name_input)
button = toga.Button(
'Say Hello!',
on_press=self.say_hello,
style=Pack(padding=5)
)
main_box.add(name_box)
main_box.add(button)
self.main_window = toga.MainWindow(title=self.formal_name)
self.main_window.content = main_box
self.main_window.show()
def say_hello(self, widget):
if self.name_input.value:
name = self.name_input.value
else:
name = 'stranger'
self.main_window.info_dialog(
'Hi there!',
f"Hello, {name}"
)
def main():
return HelloWorld()
| src/helloworld/app.py | 1,427 | Construct and show the Toga application.
Usually, you would add your application to a main content box.
We then create a main window (with a name matching the app), and
show the main window.
My first application | 212 | en | 0.912014 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2015 by Gaik Tamazian
# gaik (dot) tamazian (at) gmail (dot) com
class Error(Exception):
"""
The class describes a basic error that may occur in any of the
Chromosomer-related routines.
"""
pass
class MapError(Error):
"""
The class describes an error that may occur while working with a
fragment __map object.
"""
pass
class AlignmentToMapError(Error):
"""
The class describes an error that may occur while creating a
fragment __map from alignments.
"""
pass
| chromosomer/exception.py | 588 | The class describes an error that may occur while creating a
fragment __map from alignments.
The class describes a basic error that may occur in any of the
Chromosomer-related routines.
The class describes an error that may occur while working with a
fragment __map object.
!/usr/bin/env python -*- coding: utf-8 -*- Copyright (C) 2015 by Gaik Tamazian gaik (dot) tamazian (at) gmail (dot) com | 394 | en | 0.804161 |
# coding: utf-8
import os
import numpy as np
import copy
from PyQt5.QtWidgets import (QPushButton, QScrollArea)
from PyQt5.QtCore import QThread, pyqtSignal
from multiprocessing import Process, Manager
from ..malss import MALSS
from .waiting_animation import WaitingAnimation
from .rfpimp import oob_importances
from .learning_curve_base import LearningCurveBase
class LearningCurve(LearningCurveBase):
def __init__(self, parent=None, button_func=None, params=None):
super().__init__(parent, 'LearningCurve', params)
self.button_func = button_func
path = os.path.abspath(os.path.dirname(__file__)) + '/static/'
path1 = path + 'check_curve'
text = self.get_text(path1)
if self.params.lang == 'en':
self.set_paragraph('', text=text)
else:
self.set_paragraph('', text=text)
self.plot_curve(self.params.results['algorithms'])
self.vbox.addStretch()
btn_fs = QPushButton('Try feature selection', self.inner)
btn_fs.setStyleSheet('QPushButton{font: bold; font-size: 15pt; background-color: white;};')
btn_fs.clicked.connect(self.__button_clicked)
self.btn_next = QPushButton('Continue', self.inner)
self.btn_next.setStyleSheet('QPushButton{font: bold; font-size: 15pt; background-color: white;};')
if self.params.lang == 'en':
self.btn_next.clicked.connect(lambda: self.button_func(
'Prediction'))
else:
self.btn_next.clicked.connect(lambda: self.button_func(
'予測'))
self.vbox.addWidget(btn_fs)
self.vbox.addWidget(self.btn_next)
# "parent.parent()" must be modified.
self.wait_ani = WaitingAnimation(parent.parent())
self.wait_ani.hide()
lists = ['task', 'supervised_learning', 'dummy', 'hyperparameter',
'overfitting', 'cross_validation', 'learning_curve',
'bias_variance']
if self.params.lang == 'jp':
lists = [l + '_jp' for l in lists]
else:
lists = [l + '_en' for l in lists]
self.wait_ani.set_lists(lists)
def resizeEvent(self, event):
# To be modified.
self.wait_ani.resize(self.parent().parent().size())
event.accept()
QScrollArea.resizeEvent(self, event)
def __button_clicked(self):
self.__feature_selection()
def __feature_selection(self):
self.mdl_fs = copy.deepcopy(self.params.mdl)
self.thread = FeatureSelectionWorker(self.mdl_fs)
self.thread.finSignal.connect(self.__feature_selected)
self.thread.start()
self.wait_ani.show()
def __feature_selected(self, signalData):
self.wait_ani.hide()
if 'error' in signalData:
self.params.error = signalData['error']
self.button_func('Error')
else:
if len(signalData['mdl'].data.X.columns) < len(self.params.X.columns):
# some features deleted
self.params.X_fs = signalData['mdl'].data.X
self.params.mdl_fs = signalData['mdl']
self.params.algorithms_fs = self.params.mdl_fs.get_algorithms()
if self.params.lang == 'en':
self.button_func('Feature selection')
else:
self.button_func('特徴量選択')
else:
# no features deleted
self.params.not_deleted = True
if self.params.lang == 'en':
self.button_func('Prediction')
else:
self.button_func('予測')
class LearningCurve2(LearningCurveBase):
def __init__(self, parent=None, button_func=None, params=None):
super().__init__(parent, 'LearningCurve 2', params)
self.button_func = button_func
path = os.path.abspath(os.path.dirname(__file__)) + '/static/'
path1 = path + 'learning_curve_2'
text = self.get_text(path1)
if self.params.lang == 'en':
self.set_paragraph('', text=text)
else:
self.set_paragraph('', text=text)
self.plot_curve(self.params.results_fs['algorithms'])
if self.params.lang == 'en':
text = ('Finally, MALSS output analysis results, and you can '
'predict unknown data (if you have).\n'
'Press "Next" to continue.')
self.set_paragraph('', text=text)
else:
text = ('最後に学習結果の出力と,未知データがあればその予測を'
'行いましょう.\nNextを押してください')
self.set_paragraph('', text=text)
self.vbox.addStretch()
self.btn_next = QPushButton('Next', self.inner)
self.btn_next.setStyleSheet('QPushButton{font: bold; font-size: 15pt; background-color: white;};')
if self.params.lang == 'en':
self.btn_next.clicked.connect(lambda: self.button_func(
'Prediction'))
else:
self.btn_next.clicked.connect(lambda: self.button_func(
'予測'))
self.vbox.addWidget(self.btn_next)
class FeatureSelectionWorker(QThread):
finSignal = pyqtSignal(dict)
def __init__(self, mdl):
super().__init__()
self.mdl = mdl
def run(self):
with Manager() as manager:
d = manager.dict()
job = Process(target=FeatureSelectionWorker.sub_job,
args=(self.mdl, d))
job.start()
job.join()
self.finSignal.emit(dict(d))
@staticmethod
def sub_job(mdl, d):
try:
mdl.select_features()
d['mdl'] = mdl
except Exception as e:
import traceback
d['error'] = traceback.format_exc() | malss/app/learning_curve.py | 6,063 | coding: utf-8 "parent.parent()" must be modified. To be modified. some features deleted no features deleted | 107 | en | 0.972022 |
# GENERATED BY KOMAND SDK - DO NOT EDIT
import komand
import json
class Input:
_REF = "_ref"
class Output:
_REF = "_ref"
class DeleteHostInput(komand.Input):
schema = json.loads("""
{
"type": "object",
"title": "Variables",
"properties": {
"_ref": {
"type": "string",
"title": "Ref",
"description": "Object Reference of the host to remove",
"order": 1
}
},
"required": [
"_ref"
]
}
""")
def __init__(self):
super(self.__class__, self).__init__(self.schema)
class DeleteHostOutput(komand.Output):
schema = json.loads("""
{
"type": "object",
"title": "Variables",
"properties": {
"_ref": {
"type": "string",
"title": "Ref",
"description": "Object Reference of the removed host",
"order": 1
}
},
"required": [
"_ref"
]
}
""")
def __init__(self):
super(self.__class__, self).__init__(self.schema)
| infoblox/komand_infoblox/actions/delete_host/schema.py | 961 | GENERATED BY KOMAND SDK - DO NOT EDIT | 37 | en | 0.775658 |
# coding: utf-8
from __future__ import unicode_literals
import os
import re
import sys
from .common import InfoExtractor
from .youtube import YoutubeIE
from ..compat import (
compat_etree_fromstring,
compat_str,
compat_urllib_parse_unquote,
compat_urlparse,
compat_xml_parse_error,
)
from ..utils import (
determine_ext,
ExtractorError,
float_or_none,
HEADRequest,
int_or_none,
is_html,
js_to_json,
KNOWN_EXTENSIONS,
merge_dicts,
mimetype2ext,
orderedSet,
parse_duration,
sanitized_Request,
smuggle_url,
unescapeHTML,
unified_timestamp,
unsmuggle_url,
UnsupportedError,
url_or_none,
xpath_attr,
xpath_text,
xpath_with_ns,
)
from .commonprotocols import RtmpIE
from .brightcove import (
BrightcoveLegacyIE,
BrightcoveNewIE,
)
from .nexx import (
NexxIE,
NexxEmbedIE,
)
from .nbc import NBCSportsVPlayerIE
from .ooyala import OoyalaIE
from .rutv import RUTVIE
from .tvc import TVCIE
from .sportbox import SportBoxIE
from .myvi import MyviIE
from .condenast import CondeNastIE
from .udn import UDNEmbedIE
from .senateisvp import SenateISVPIE
from .svt import SVTIE
from .pornhub import PornHubIE
from .xhamster import XHamsterEmbedIE
from .tnaflix import TNAFlixNetworkEmbedIE
from .drtuber import DrTuberIE
from .redtube import RedTubeIE
from .tube8 import Tube8IE
from .mofosex import MofosexEmbedIE
from .spankwire import SpankwireIE
from .youporn import YouPornIE
from .vimeo import (
VimeoIE,
VHXEmbedIE,
)
from .dailymotion import DailymotionIE
from .dailymail import DailyMailIE
from .onionstudios import OnionStudiosIE
from .viewlift import ViewLiftEmbedIE
from .mtv import MTVServicesEmbeddedIE
from .pladform import PladformIE
from .videomore import VideomoreIE
from .webcaster import WebcasterFeedIE
from .googledrive import GoogleDriveIE
from .jwplatform import JWPlatformIE
from .digiteka import DigitekaIE
from .arkena import ArkenaIE
from .instagram import InstagramIE
from .liveleak import LiveLeakIE
from .threeqsdn import ThreeQSDNIE
from .theplatform import ThePlatformIE
from .kaltura import KalturaIE
from .eagleplatform import EaglePlatformIE
from .facebook import FacebookIE
from .soundcloud import SoundcloudEmbedIE
from .tunein import TuneInBaseIE
from .vbox7 import Vbox7IE
from .dbtv import DBTVIE
from .piksel import PikselIE
from .videa import VideaIE
from .twentymin import TwentyMinutenIE
from .ustream import UstreamIE
from .arte import ArteTVEmbedIE
from .videopress import VideoPressIE
from .rutube import RutubeIE
from .limelight import LimelightBaseIE
from .anvato import AnvatoIE
from .washingtonpost import WashingtonPostIE
from .wistia import WistiaIE
from .mediaset import MediasetIE
from .joj import JojIE
from .megaphone import MegaphoneIE
from .vzaar import VzaarIE
from .channel9 import Channel9IE
from .vshare import VShareIE
from .mediasite import MediasiteIE
from .springboardplatform import SpringboardPlatformIE
from .yapfiles import YapFilesIE
from .vice import ViceIE
from .xfileshare import XFileShareIE
from .cloudflarestream import CloudflareStreamIE
from .peertube import PeerTubeIE
from .teachable import TeachableIE
from .indavideo import IndavideoEmbedIE
from .apa import APAIE
from .foxnews import FoxNewsIE
from .viqeo import ViqeoIE
from .expressen import ExpressenIE
from .zype import ZypeIE
from .odnoklassniki import OdnoklassnikiIE
from .kinja import KinjaEmbedIE
from .gedidigital import GediDigitalIE
from .rcs import RCSEmbedsIE
from .bitchute import BitChuteIE
from .rumble import RumbleEmbedIE
from .arcpublishing import ArcPublishingIE
from .medialaan import MedialaanIE
from .simplecast import SimplecastIE
from .wimtv import WimTVIE
class GenericIE(InfoExtractor):
IE_DESC = 'Generic downloader that works on some sites'
_VALID_URL = r'.*'
IE_NAME = 'generic'
_TESTS = [
# Direct link to a video
{
'url': 'http://media.w3.org/2010/05/sintel/trailer.mp4',
'md5': '67d406c2bcb6af27fa886f31aa934bbe',
'info_dict': {
'id': 'trailer',
'ext': 'mp4',
'title': 'trailer',
'upload_date': '20100513',
}
},
# Direct link to media delivered compressed (until Accept-Encoding is *)
{
'url': 'http://calimero.tk/muzik/FictionJunction-Parallel_Hearts.flac',
'md5': '128c42e68b13950268b648275386fc74',
'info_dict': {
'id': 'FictionJunction-Parallel_Hearts',
'ext': 'flac',
'title': 'FictionJunction-Parallel_Hearts',
'upload_date': '20140522',
},
'expected_warnings': [
'URL could be a direct video link, returning it as such.'
],
'skip': 'URL invalid',
},
# Direct download with broken HEAD
{
'url': 'http://ai-radio.org:8000/radio.opus',
'info_dict': {
'id': 'radio',
'ext': 'opus',
'title': 'radio',
},
'params': {
'skip_download': True, # infinite live stream
},
'expected_warnings': [
r'501.*Not Implemented',
r'400.*Bad Request',
],
},
# Direct link with incorrect MIME type
{
'url': 'http://ftp.nluug.nl/video/nluug/2014-11-20_nj14/zaal-2/5_Lennart_Poettering_-_Systemd.webm',
'md5': '4ccbebe5f36706d85221f204d7eb5913',
'info_dict': {
'url': 'http://ftp.nluug.nl/video/nluug/2014-11-20_nj14/zaal-2/5_Lennart_Poettering_-_Systemd.webm',
'id': '5_Lennart_Poettering_-_Systemd',
'ext': 'webm',
'title': '5_Lennart_Poettering_-_Systemd',
'upload_date': '20141120',
},
'expected_warnings': [
'URL could be a direct video link, returning it as such.'
]
},
# RSS feed
{
'url': 'http://phihag.de/2014/youtube-dl/rss2.xml',
'info_dict': {
'id': 'http://phihag.de/2014/youtube-dl/rss2.xml',
'title': 'Zero Punctuation',
'description': 're:.*groundbreaking video review series.*'
},
'playlist_mincount': 11,
},
# RSS feed with enclosure
{
'url': 'http://podcastfeeds.nbcnews.com/audio/podcast/MSNBC-MADDOW-NETCAST-M4V.xml',
'info_dict': {
'id': 'http://podcastfeeds.nbcnews.com/nbcnews/video/podcast/MSNBC-MADDOW-NETCAST-M4V.xml',
'title': 'MSNBC Rachel Maddow (video)',
'description': 're:.*her unique approach to storytelling.*',
},
'playlist': [{
'info_dict': {
'ext': 'mov',
'id': 'pdv_maddow_netcast_mov-12-03-2020-223726',
'title': 'MSNBC Rachel Maddow (video) - 12-03-2020-223726',
'description': 're:.*her unique approach to storytelling.*',
'upload_date': '20201204',
},
}],
},
# RSS feed with item with description and thumbnails
{
'url': 'https://anchor.fm/s/dd00e14/podcast/rss',
'info_dict': {
'id': 'https://anchor.fm/s/dd00e14/podcast/rss',
'title': 're:.*100% Hydrogen.*',
'description': 're:.*In this episode.*',
},
'playlist': [{
'info_dict': {
'ext': 'm4a',
'id': 'c1c879525ce2cb640b344507e682c36d',
'title': 're:Hydrogen!',
'description': 're:.*In this episode we are going.*',
'timestamp': 1567977776,
'upload_date': '20190908',
'duration': 459,
'thumbnail': r're:^https?://.*\.jpg$',
'episode_number': 1,
'season_number': 1,
'age_limit': 0,
},
}],
'params': {
'skip_download': True,
},
},
# RSS feed with enclosures and unsupported link URLs
{
'url': 'http://www.hellointernet.fm/podcast?format=rss',
'info_dict': {
'id': 'http://www.hellointernet.fm/podcast?format=rss',
'description': 'CGP Grey and Brady Haran talk about YouTube, life, work, whatever.',
'title': 'Hello Internet',
},
'playlist_mincount': 100,
},
# SMIL from http://videolectures.net/promogram_igor_mekjavic_eng
{
'url': 'http://videolectures.net/promogram_igor_mekjavic_eng/video/1/smil.xml',
'info_dict': {
'id': 'smil',
'ext': 'mp4',
'title': 'Automatics, robotics and biocybernetics',
'description': 'md5:815fc1deb6b3a2bff99de2d5325be482',
'upload_date': '20130627',
'formats': 'mincount:16',
'subtitles': 'mincount:1',
},
'params': {
'force_generic_extractor': True,
'skip_download': True,
},
},
# SMIL from http://www1.wdr.de/mediathek/video/livestream/index.html
{
'url': 'http://metafilegenerator.de/WDR/WDR_FS/hds/hds.smil',
'info_dict': {
'id': 'hds',
'ext': 'flv',
'title': 'hds',
'formats': 'mincount:1',
},
'params': {
'skip_download': True,
},
},
# SMIL from https://www.restudy.dk/video/play/id/1637
{
'url': 'https://www.restudy.dk/awsmedia/SmilDirectory/video_1637.xml',
'info_dict': {
'id': 'video_1637',
'ext': 'flv',
'title': 'video_1637',
'formats': 'mincount:3',
},
'params': {
'skip_download': True,
},
},
# SMIL from http://adventure.howstuffworks.com/5266-cool-jobs-iditarod-musher-video.htm
{
'url': 'http://services.media.howstuffworks.com/videos/450221/smil-service.smil',
'info_dict': {
'id': 'smil-service',
'ext': 'flv',
'title': 'smil-service',
'formats': 'mincount:1',
},
'params': {
'skip_download': True,
},
},
# SMIL from http://new.livestream.com/CoheedandCambria/WebsterHall/videos/4719370
{
'url': 'http://api.new.livestream.com/accounts/1570303/events/1585861/videos/4719370.smil',
'info_dict': {
'id': '4719370',
'ext': 'mp4',
'title': '571de1fd-47bc-48db-abf9-238872a58d1f',
'formats': 'mincount:3',
},
'params': {
'skip_download': True,
},
},
# XSPF playlist from http://www.telegraaf.nl/tv/nieuws/binnenland/24353229/__Tikibad_ontruimd_wegens_brand__.html
{
'url': 'http://www.telegraaf.nl/xml/playlist/2015/8/7/mZlp2ctYIUEB.xspf',
'info_dict': {
'id': 'mZlp2ctYIUEB',
'ext': 'mp4',
'title': 'Tikibad ontruimd wegens brand',
'description': 'md5:05ca046ff47b931f9b04855015e163a4',
'thumbnail': r're:^https?://.*\.jpg$',
'duration': 33,
},
'params': {
'skip_download': True,
},
},
# MPD from http://dash-mse-test.appspot.com/media.html
{
'url': 'http://yt-dash-mse-test.commondatastorage.googleapis.com/media/car-20120827-manifest.mpd',
'md5': '4b57baab2e30d6eb3a6a09f0ba57ef53',
'info_dict': {
'id': 'car-20120827-manifest',
'ext': 'mp4',
'title': 'car-20120827-manifest',
'formats': 'mincount:9',
'upload_date': '20130904',
},
'params': {
'format': 'bestvideo',
},
},
# m3u8 served with Content-Type: audio/x-mpegURL; charset=utf-8
{
'url': 'http://once.unicornmedia.com/now/master/playlist/bb0b18ba-64f5-4b1b-a29f-0ac252f06b68/77a785f3-5188-4806-b788-0893a61634ed/93677179-2d99-4ef4-9e17-fe70d49abfbf/content.m3u8',
'info_dict': {
'id': 'content',
'ext': 'mp4',
'title': 'content',
'formats': 'mincount:8',
},
'params': {
# m3u8 downloads
'skip_download': True,
},
'skip': 'video gone',
},
# m3u8 served with Content-Type: text/plain
{
'url': 'http://www.nacentapps.com/m3u8/index.m3u8',
'info_dict': {
'id': 'index',
'ext': 'mp4',
'title': 'index',
'upload_date': '20140720',
'formats': 'mincount:11',
},
'params': {
# m3u8 downloads
'skip_download': True,
},
'skip': 'video gone',
},
# google redirect
{
'url': 'http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&ved=0CCUQtwIwAA&url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DcmQHVoWB5FY&ei=F-sNU-LLCaXk4QT52ICQBQ&usg=AFQjCNEw4hL29zgOohLXvpJ-Bdh2bils1Q&bvm=bv.61965928,d.bGE',
'info_dict': {
'id': 'cmQHVoWB5FY',
'ext': 'mp4',
'upload_date': '20130224',
'uploader_id': 'TheVerge',
'description': r're:^Chris Ziegler takes a look at the\.*',
'uploader': 'The Verge',
'title': 'First Firefox OS phones side-by-side',
},
'params': {
'skip_download': False,
}
},
{
# redirect in Refresh HTTP header
'url': 'https://www.facebook.com/l.php?u=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DpO8h3EaFRdo&h=TAQHsoToz&enc=AZN16h-b6o4Zq9pZkCCdOLNKMN96BbGMNtcFwHSaazus4JHT_MFYkAA-WARTX2kvsCIdlAIyHZjl6d33ILIJU7Jzwk_K3mcenAXoAzBNoZDI_Q7EXGDJnIhrGkLXo_LJ_pAa2Jzbx17UHMd3jAs--6j2zaeto5w9RTn8T_1kKg3fdC5WPX9Dbb18vzH7YFX0eSJmoa6SP114rvlkw6pkS1-T&s=1',
'info_dict': {
'id': 'pO8h3EaFRdo',
'ext': 'mp4',
'title': 'Tripeo Boiler Room x Dekmantel Festival DJ Set',
'description': 'md5:6294cc1af09c4049e0652b51a2df10d5',
'upload_date': '20150917',
'uploader_id': 'brtvofficial',
'uploader': 'Boiler Room',
},
'params': {
'skip_download': False,
},
},
{
'url': 'http://www.hodiho.fr/2013/02/regis-plante-sa-jeep.html',
'md5': '85b90ccc9d73b4acd9138d3af4c27f89',
'info_dict': {
'id': '13601338388002',
'ext': 'mp4',
'uploader': 'www.hodiho.fr',
'title': 'R\u00e9gis plante sa Jeep',
}
},
# bandcamp page with custom domain
{
'add_ie': ['Bandcamp'],
'url': 'http://bronyrock.com/track/the-pony-mash',
'info_dict': {
'id': '3235767654',
'ext': 'mp3',
'title': 'The Pony Mash',
'uploader': 'M_Pallante',
},
'skip': 'There is a limit of 200 free downloads / month for the test song',
},
{
# embedded brightcove video
# it also tests brightcove videos that need to set the 'Referer'
# in the http requests
'add_ie': ['BrightcoveLegacy'],
'url': 'http://www.bfmtv.com/video/bfmbusiness/cours-bourse/cours-bourse-l-analyse-technique-154522/',
'info_dict': {
'id': '2765128793001',
'ext': 'mp4',
'title': 'Le cours de bourse : l’analyse technique',
'description': 'md5:7e9ad046e968cb2d1114004aba466fd9',
'uploader': 'BFM BUSINESS',
},
'params': {
'skip_download': True,
},
},
{
# embedded with itemprop embedURL and video id spelled as `idVideo`
'add_id': ['BrightcoveLegacy'],
'url': 'http://bfmbusiness.bfmtv.com/mediaplayer/chroniques/olivier-delamarche/',
'info_dict': {
'id': '5255628253001',
'ext': 'mp4',
'title': 'md5:37c519b1128915607601e75a87995fc0',
'description': 'md5:37f7f888b434bb8f8cc8dbd4f7a4cf26',
'uploader': 'BFM BUSINESS',
'uploader_id': '876450612001',
'timestamp': 1482255315,
'upload_date': '20161220',
},
'params': {
'skip_download': True,
},
},
{
# https://github.com/ytdl-org/youtube-dl/issues/2253
'url': 'http://bcove.me/i6nfkrc3',
'md5': '0ba9446db037002366bab3b3eb30c88c',
'info_dict': {
'id': '3101154703001',
'ext': 'mp4',
'title': 'Still no power',
'uploader': 'thestar.com',
'description': 'Mississauga resident David Farmer is still out of power as a result of the ice storm a month ago. To keep the house warm, Farmer cuts wood from his property for a wood burning stove downstairs.',
},
'add_ie': ['BrightcoveLegacy'],
'skip': 'video gone',
},
{
'url': 'http://www.championat.com/video/football/v/87/87499.html',
'md5': 'fb973ecf6e4a78a67453647444222983',
'info_dict': {
'id': '3414141473001',
'ext': 'mp4',
'title': 'Видео. Удаление Дзагоева (ЦСКА)',
'description': 'Онлайн-трансляция матча ЦСКА - "Волга"',
'uploader': 'Championat',
},
},
{
# https://github.com/ytdl-org/youtube-dl/issues/3541
'add_ie': ['BrightcoveLegacy'],
'url': 'http://www.kijk.nl/sbs6/leermijvrouwenkennen/videos/jqMiXKAYan2S/aflevering-1',
'info_dict': {
'id': '3866516442001',
'ext': 'mp4',
'title': 'Leer mij vrouwen kennen: Aflevering 1',
'description': 'Leer mij vrouwen kennen: Aflevering 1',
'uploader': 'SBS Broadcasting',
},
'skip': 'Restricted to Netherlands',
'params': {
'skip_download': True, # m3u8 download
},
},
{
# Brightcove video in <iframe>
'url': 'http://www.un.org/chinese/News/story.asp?NewsID=27724',
'md5': '36d74ef5e37c8b4a2ce92880d208b968',
'info_dict': {
'id': '5360463607001',
'ext': 'mp4',
'title': '叙利亚失明儿童在废墟上演唱《心跳》 呼吁获得正常童年生活',
'description': '联合国儿童基金会中东和北非区域大使、作曲家扎德·迪拉尼(Zade Dirani)在3月15日叙利亚冲突爆发7周年纪念日之际发布了为叙利亚谱写的歌曲《心跳》(HEARTBEAT),为受到六年冲突影响的叙利亚儿童发出强烈呐喊,呼吁世界做出共同努力,使叙利亚儿童重新获得享有正常童年生活的权利。',
'uploader': 'United Nations',
'uploader_id': '1362235914001',
'timestamp': 1489593889,
'upload_date': '20170315',
},
'add_ie': ['BrightcoveLegacy'],
},
{
# Brightcove with alternative playerID key
'url': 'http://www.nature.com/nmeth/journal/v9/n7/fig_tab/nmeth.2062_SV1.html',
'info_dict': {
'id': 'nmeth.2062_SV1',
'title': 'Simultaneous multiview imaging of the Drosophila syncytial blastoderm : Quantitative high-speed imaging of entire developing embryos with simultaneous multiview light-sheet microscopy : Nature Methods : Nature Research',
},
'playlist': [{
'info_dict': {
'id': '2228375078001',
'ext': 'mp4',
'title': 'nmeth.2062-sv1',
'description': 'nmeth.2062-sv1',
'timestamp': 1363357591,
'upload_date': '20130315',
'uploader': 'Nature Publishing Group',
'uploader_id': '1964492299001',
},
}],
},
{
# Brightcove with UUID in videoPlayer
'url': 'http://www8.hp.com/cn/zh/home.html',
'info_dict': {
'id': '5255815316001',
'ext': 'mp4',
'title': 'Sprocket Video - China',
'description': 'Sprocket Video - China',
'uploader': 'HP-Video Gallery',
'timestamp': 1482263210,
'upload_date': '20161220',
'uploader_id': '1107601872001',
},
'params': {
'skip_download': True, # m3u8 download
},
'skip': 'video rotates...weekly?',
},
{
# Brightcove:new type [2].
'url': 'http://www.delawaresportszone.com/video-st-thomas-more-earns-first-trip-to-basketball-semis',
'md5': '2b35148fcf48da41c9fb4591650784f3',
'info_dict': {
'id': '5348741021001',
'ext': 'mp4',
'upload_date': '20170306',
'uploader_id': '4191638492001',
'timestamp': 1488769918,
'title': 'VIDEO: St. Thomas More earns first trip to basketball semis',
},
},
{
# Alternative brightcove <video> attributes
'url': 'http://www.programme-tv.net/videos/extraits/81095-guillaume-canet-evoque-les-rumeurs-d-infidelite-de-marion-cotillard-avec-brad-pitt-dans-vivement-dimanche/',
'info_dict': {
'id': '81095-guillaume-canet-evoque-les-rumeurs-d-infidelite-de-marion-cotillard-avec-brad-pitt-dans-vivement-dimanche',
'title': "Guillaume Canet évoque les rumeurs d'infidélité de Marion Cotillard avec Brad Pitt dans Vivement Dimanche, Extraits : toutes les vidéos avec Télé-Loisirs",
},
'playlist': [{
'md5': '732d22ba3d33f2f3fc253c39f8f36523',
'info_dict': {
'id': '5311302538001',
'ext': 'mp4',
'title': "Guillaume Canet évoque les rumeurs d'infidélité de Marion Cotillard avec Brad Pitt dans Vivement Dimanche",
'description': "Guillaume Canet évoque les rumeurs d'infidélité de Marion Cotillard avec Brad Pitt dans Vivement Dimanche (France 2, 5 février 2017)",
'timestamp': 1486321708,
'upload_date': '20170205',
'uploader_id': '800000640001',
},
'only_matching': True,
}],
},
{
# Brightcove with UUID in videoPlayer
'url': 'http://www8.hp.com/cn/zh/home.html',
'info_dict': {
'id': '5255815316001',
'ext': 'mp4',
'title': 'Sprocket Video - China',
'description': 'Sprocket Video - China',
'uploader': 'HP-Video Gallery',
'timestamp': 1482263210,
'upload_date': '20161220',
'uploader_id': '1107601872001',
},
'params': {
'skip_download': True, # m3u8 download
},
},
# ooyala video
{
'url': 'http://www.rollingstone.com/music/videos/norwegian-dj-cashmere-cat-goes-spartan-on-with-me-premiere-20131219',
'md5': '166dd577b433b4d4ebfee10b0824d8ff',
'info_dict': {
'id': 'BwY2RxaTrTkslxOfcan0UCf0YqyvWysJ',
'ext': 'mp4',
'title': '2cc213299525360.mov', # that's what we get
'duration': 238.231,
},
'add_ie': ['Ooyala'],
},
{
# ooyala video embedded with http://player.ooyala.com/iframe.js
'url': 'http://www.macrumors.com/2015/07/24/steve-jobs-the-man-in-the-machine-first-trailer/',
'info_dict': {
'id': 'p0MGJndjoG5SOKqO_hZJuZFPB-Tr5VgB',
'ext': 'mp4',
'title': '"Steve Jobs: Man in the Machine" trailer',
'description': 'The first trailer for the Alex Gibney documentary "Steve Jobs: Man in the Machine."',
'duration': 135.427,
},
'params': {
'skip_download': True,
},
'skip': 'movie expired',
},
# ooyala video embedded with http://player.ooyala.com/static/v4/production/latest/core.min.js
{
'url': 'http://wnep.com/2017/07/22/steampunk-fest-comes-to-honesdale/',
'info_dict': {
'id': 'lwYWYxYzE6V5uJMjNGyKtwwiw9ZJD7t2',
'ext': 'mp4',
'title': 'Steampunk Fest Comes to Honesdale',
'duration': 43.276,
},
'params': {
'skip_download': True,
}
},
# embed.ly video
{
'url': 'http://www.tested.com/science/weird/460206-tested-grinding-coffee-2000-frames-second/',
'info_dict': {
'id': '9ODmcdjQcHQ',
'ext': 'mp4',
'title': 'Tested: Grinding Coffee at 2000 Frames Per Second',
'upload_date': '20140225',
'description': 'md5:06a40fbf30b220468f1e0957c0f558ff',
'uploader': 'Tested',
'uploader_id': 'testedcom',
},
# No need to test YoutubeIE here
'params': {
'skip_download': True,
},
},
# funnyordie embed
{
'url': 'http://www.theguardian.com/world/2014/mar/11/obama-zach-galifianakis-between-two-ferns',
'info_dict': {
'id': '18e820ec3f',
'ext': 'mp4',
'title': 'Between Two Ferns with Zach Galifianakis: President Barack Obama',
'description': 'Episode 18: President Barack Obama sits down with Zach Galifianakis for his most memorable interview yet.',
},
# HEAD requests lead to endless 301, while GET is OK
'expected_warnings': ['301'],
},
# RUTV embed
{
'url': 'http://www.rg.ru/2014/03/15/reg-dfo/anklav-anons.html',
'info_dict': {
'id': '776940',
'ext': 'mp4',
'title': 'Охотское море стало целиком российским',
'description': 'md5:5ed62483b14663e2a95ebbe115eb8f43',
},
'params': {
# m3u8 download
'skip_download': True,
},
},
# TVC embed
{
'url': 'http://sch1298sz.mskobr.ru/dou_edu/karamel_ki/filial_galleries/video/iframe_src_http_tvc_ru_video_iframe_id_55304_isplay_false_acc_video_id_channel_brand_id_11_show_episodes_episode_id_32307_frameb/',
'info_dict': {
'id': '55304',
'ext': 'mp4',
'title': 'Дошкольное воспитание',
},
},
# SportBox embed
{
'url': 'http://www.vestifinance.ru/articles/25753',
'info_dict': {
'id': '25753',
'title': 'Прямые трансляции с Форума-выставки "Госзаказ-2013"',
},
'playlist': [{
'info_dict': {
'id': '370908',
'title': 'Госзаказ. День 3',
'ext': 'mp4',
}
}, {
'info_dict': {
'id': '370905',
'title': 'Госзаказ. День 2',
'ext': 'mp4',
}
}, {
'info_dict': {
'id': '370902',
'title': 'Госзаказ. День 1',
'ext': 'mp4',
}
}],
'params': {
# m3u8 download
'skip_download': True,
},
},
# Myvi.ru embed
{
'url': 'http://www.kinomyvi.tv/news/detail/Pervij-dublirovannij-trejler--Uzhastikov-_nOw1',
'info_dict': {
'id': 'f4dafcad-ff21-423d-89b5-146cfd89fa1e',
'ext': 'mp4',
'title': 'Ужастики, русский трейлер (2015)',
'thumbnail': r're:^https?://.*\.jpg$',
'duration': 153,
}
},
# XHamster embed
{
'url': 'http://www.numisc.com/forum/showthread.php?11696-FM15-which-pumiscer-was-this-%28-vid-%29-%28-alfa-as-fuck-srx-%29&s=711f5db534502e22260dec8c5e2d66d8',
'info_dict': {
'id': 'showthread',
'title': '[NSFL] [FM15] which pumiscer was this ( vid ) ( alfa as fuck srx )',
},
'playlist_mincount': 7,
# This forum does not allow <iframe> syntaxes anymore
# Now HTML tags are displayed as-is
'skip': 'No videos on this page',
},
# Embedded TED video
{
'url': 'http://en.support.wordpress.com/videos/ted-talks/',
'md5': '65fdff94098e4a607385a60c5177c638',
'info_dict': {
'id': '1969',
'ext': 'mp4',
'title': 'Hidden miracles of the natural world',
'uploader': 'Louie Schwartzberg',
'description': 'md5:8145d19d320ff3e52f28401f4c4283b9',
}
},
# nowvideo embed hidden behind percent encoding
{
'url': 'http://www.waoanime.tv/the-super-dimension-fortress-macross-episode-1/',
'md5': '2baf4ddd70f697d94b1c18cf796d5107',
'info_dict': {
'id': '06e53103ca9aa',
'ext': 'flv',
'title': 'Macross Episode 001 Watch Macross Episode 001 onl',
'description': 'No description',
},
},
# arte embed
{
'url': 'http://www.tv-replay.fr/redirection/20-03-14/x-enius-arte-10753389.html',
'md5': '7653032cbb25bf6c80d80f217055fa43',
'info_dict': {
'id': '048195-004_PLUS7-F',
'ext': 'flv',
'title': 'X:enius',
'description': 'md5:d5fdf32ef6613cdbfd516ae658abf168',
'upload_date': '20140320',
},
'params': {
'skip_download': 'Requires rtmpdump'
},
'skip': 'video gone',
},
# francetv embed
{
'url': 'http://www.tsprod.com/replay-du-concert-alcaline-de-calogero',
'info_dict': {
'id': 'EV_30231',
'ext': 'mp4',
'title': 'Alcaline, le concert avec Calogero',
'description': 'md5:61f08036dcc8f47e9cfc33aed08ffaff',
'upload_date': '20150226',
'timestamp': 1424989860,
'duration': 5400,
},
'params': {
# m3u8 downloads
'skip_download': True,
},
'expected_warnings': [
'Forbidden'
]
},
# Condé Nast embed
{
'url': 'http://www.wired.com/2014/04/honda-asimo/',
'md5': 'ba0dfe966fa007657bd1443ee672db0f',
'info_dict': {
'id': '53501be369702d3275860000',
'ext': 'mp4',
'title': 'Honda’s New Asimo Robot Is More Human Than Ever',
}
},
# Dailymotion embed
{
'url': 'http://www.spi0n.com/zap-spi0n-com-n216/',
'md5': '441aeeb82eb72c422c7f14ec533999cd',
'info_dict': {
'id': 'k2mm4bCdJ6CQ2i7c8o2',
'ext': 'mp4',
'title': 'Le Zap de Spi0n n°216 - Zapping du Web',
'description': 'md5:faf028e48a461b8b7fad38f1e104b119',
'uploader': 'Spi0n',
'uploader_id': 'xgditw',
'upload_date': '20140425',
'timestamp': 1398441542,
},
'add_ie': ['Dailymotion'],
},
# DailyMail embed
{
'url': 'http://www.bumm.sk/krimi/2017/07/05/biztonsagi-kamera-buktatta-le-az-agg-ferfit-utlegelo-apolot',
'info_dict': {
'id': '1495629',
'ext': 'mp4',
'title': 'Care worker punches elderly dementia patient in head 11 times',
'description': 'md5:3a743dee84e57e48ec68bf67113199a5',
},
'add_ie': ['DailyMail'],
'params': {
'skip_download': True,
},
},
# YouTube embed
{
'url': 'http://www.badzine.de/ansicht/datum/2014/06/09/so-funktioniert-die-neue-englische-badminton-liga.html',
'info_dict': {
'id': 'FXRb4ykk4S0',
'ext': 'mp4',
'title': 'The NBL Auction 2014',
'uploader': 'BADMINTON England',
'uploader_id': 'BADMINTONEvents',
'upload_date': '20140603',
'description': 'md5:9ef128a69f1e262a700ed83edb163a73',
},
'add_ie': ['Youtube'],
'params': {
'skip_download': True,
}
},
# MTVServices embed
{
'url': 'http://www.vulture.com/2016/06/new-key-peele-sketches-released.html',
'md5': 'ca1aef97695ef2c1d6973256a57e5252',
'info_dict': {
'id': '769f7ec0-0692-4d62-9b45-0d88074bffc1',
'ext': 'mp4',
'title': 'Key and Peele|October 10, 2012|2|203|Liam Neesons - Uncensored',
'description': 'Two valets share their love for movie star Liam Neesons.',
'timestamp': 1349922600,
'upload_date': '20121011',
},
},
# YouTube embed via <data-embed-url="">
{
'url': 'https://play.google.com/store/apps/details?id=com.gameloft.android.ANMP.GloftA8HM',
'info_dict': {
'id': '4vAffPZIT44',
'ext': 'mp4',
'title': 'Asphalt 8: Airborne - Update - Welcome to Dubai!',
'uploader': 'Gameloft',
'uploader_id': 'gameloft',
'upload_date': '20140828',
'description': 'md5:c80da9ed3d83ae6d1876c834de03e1c4',
},
'params': {
'skip_download': True,
}
},
# YouTube <object> embed
{
'url': 'http://www.improbable.com/2017/04/03/untrained-modern-youths-and-ancient-masters-in-selfie-portraits/',
'md5': '516718101ec834f74318df76259fb3cc',
'info_dict': {
'id': 'msN87y-iEx0',
'ext': 'webm',
'title': 'Feynman: Mirrors FUN TO IMAGINE 6',
'upload_date': '20080526',
'description': 'md5:0ffc78ea3f01b2e2c247d5f8d1d3c18d',
'uploader': 'Christopher Sykes',
'uploader_id': 'ChristopherJSykes',
},
'add_ie': ['Youtube'],
},
# Camtasia studio
{
'url': 'http://www.ll.mit.edu/workshops/education/videocourses/antennas/lecture1/video/',
'playlist': [{
'md5': '0c5e352edabf715d762b0ad4e6d9ee67',
'info_dict': {
'id': 'Fenn-AA_PA_Radar_Course_Lecture_1c_Final',
'title': 'Fenn-AA_PA_Radar_Course_Lecture_1c_Final - video1',
'ext': 'flv',
'duration': 2235.90,
}
}, {
'md5': '10e4bb3aaca9fd630e273ff92d9f3c63',
'info_dict': {
'id': 'Fenn-AA_PA_Radar_Course_Lecture_1c_Final_PIP',
'title': 'Fenn-AA_PA_Radar_Course_Lecture_1c_Final - pip',
'ext': 'flv',
'duration': 2235.93,
}
}],
'info_dict': {
'title': 'Fenn-AA_PA_Radar_Course_Lecture_1c_Final',
}
},
# Flowplayer
{
'url': 'http://www.handjobhub.com/video/busty-blonde-siri-tit-fuck-while-wank-6313.html',
'md5': '9d65602bf31c6e20014319c7d07fba27',
'info_dict': {
'id': '5123ea6d5e5a7',
'ext': 'mp4',
'age_limit': 18,
'uploader': 'www.handjobhub.com',
'title': 'Busty Blonde Siri Tit Fuck While Wank at HandjobHub.com',
}
},
# Multiple brightcove videos
# https://github.com/ytdl-org/youtube-dl/issues/2283
{
'url': 'http://www.newyorker.com/online/blogs/newsdesk/2014/01/always-never-nuclear-command-and-control.html',
'info_dict': {
'id': 'always-never',
'title': 'Always / Never - The New Yorker',
},
'playlist_count': 3,
'params': {
'extract_flat': False,
'skip_download': True,
}
},
# MLB embed
{
'url': 'http://umpire-empire.com/index.php/topic/58125-laz-decides-no-thats-low/',
'md5': '96f09a37e44da40dd083e12d9a683327',
'info_dict': {
'id': '33322633',
'ext': 'mp4',
'title': 'Ump changes call to ball',
'description': 'md5:71c11215384298a172a6dcb4c2e20685',
'duration': 48,
'timestamp': 1401537900,
'upload_date': '20140531',
'thumbnail': r're:^https?://.*\.jpg$',
},
},
# Wistia embed
{
'url': 'http://study.com/academy/lesson/north-american-exploration-failed-colonies-of-spain-france-england.html#lesson',
'md5': '1953f3a698ab51cfc948ed3992a0b7ff',
'info_dict': {
'id': '6e2wtrbdaf',
'ext': 'mov',
'title': 'paywall_north-american-exploration-failed-colonies-of-spain-france-england',
'description': 'a Paywall Videos video from Remilon',
'duration': 644.072,
'uploader': 'study.com',
'timestamp': 1459678540,
'upload_date': '20160403',
'filesize': 24687186,
},
},
{
'url': 'http://thoughtworks.wistia.com/medias/uxjb0lwrcz',
'md5': 'baf49c2baa8a7de5f3fc145a8506dcd4',
'info_dict': {
'id': 'uxjb0lwrcz',
'ext': 'mp4',
'title': 'Conversation about Hexagonal Rails Part 1',
'description': 'a Martin Fowler video from ThoughtWorks',
'duration': 1715.0,
'uploader': 'thoughtworks.wistia.com',
'timestamp': 1401832161,
'upload_date': '20140603',
},
},
# Wistia standard embed (async)
{
'url': 'https://www.getdrip.com/university/brennan-dunn-drip-workshop/',
'info_dict': {
'id': '807fafadvk',
'ext': 'mp4',
'title': 'Drip Brennan Dunn Workshop',
'description': 'a JV Webinars video from getdrip-1',
'duration': 4986.95,
'timestamp': 1463607249,
'upload_date': '20160518',
},
'params': {
'skip_download': True,
}
},
# Soundcloud embed
{
'url': 'http://nakedsecurity.sophos.com/2014/10/29/sscc-171-are-you-sure-that-1234-is-a-bad-password-podcast/',
'info_dict': {
'id': '174391317',
'ext': 'mp3',
'description': 'md5:ff867d6b555488ad3c52572bb33d432c',
'uploader': 'Sophos Security',
'title': 'Chet Chat 171 - Oct 29, 2014',
'upload_date': '20141029',
}
},
# Soundcloud multiple embeds
{
'url': 'http://www.guitarplayer.com/lessons/1014/legato-workout-one-hour-to-more-fluid-performance---tab/52809',
'info_dict': {
'id': '52809',
'title': 'Guitar Essentials: Legato Workout—One-Hour to Fluid Performance | TAB + AUDIO',
},
'playlist_mincount': 7,
},
# TuneIn station embed
{
'url': 'http://radiocnrv.com/promouvoir-radio-cnrv/',
'info_dict': {
'id': '204146',
'ext': 'mp3',
'title': 'CNRV',
'location': 'Paris, France',
'is_live': True,
},
'params': {
# Live stream
'skip_download': True,
},
},
# Livestream embed
{
'url': 'http://www.esa.int/Our_Activities/Space_Science/Rosetta/Philae_comet_touch-down_webcast',
'info_dict': {
'id': '67864563',
'ext': 'flv',
'upload_date': '20141112',
'title': 'Rosetta #CometLanding webcast HL 10',
}
},
# Another Livestream embed, without 'new.' in URL
{
'url': 'https://www.freespeech.org/',
'info_dict': {
'id': '123537347',
'ext': 'mp4',
'title': 're:^FSTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
},
'params': {
# Live stream
'skip_download': True,
},
},
# LazyYT
{
'url': 'https://skiplagged.com/',
'info_dict': {
'id': 'skiplagged',
'title': 'Skiplagged: The smart way to find cheap flights',
},
'playlist_mincount': 1,
'add_ie': ['Youtube'],
},
# Cinchcast embed
{
'url': 'http://undergroundwellness.com/podcasts/306-5-steps-to-permanent-gut-healing/',
'info_dict': {
'id': '7141703',
'ext': 'mp3',
'upload_date': '20141126',
'title': 'Jack Tips: 5 Steps to Permanent Gut Healing',
}
},
# Cinerama player
{
'url': 'http://www.abc.net.au/7.30/content/2015/s4164797.htm',
'info_dict': {
'id': '730m_DandD_1901_512k',
'ext': 'mp4',
'uploader': 'www.abc.net.au',
'title': 'Game of Thrones with dice - Dungeons and Dragons fantasy role-playing game gets new life - 19/01/2015',
}
},
# embedded viddler video
{
'url': 'http://deadspin.com/i-cant-stop-watching-john-wall-chop-the-nuggets-with-th-1681801597',
'info_dict': {
'id': '4d03aad9',
'ext': 'mp4',
'uploader': 'deadspin',
'title': 'WALL-TO-GORTAT',
'timestamp': 1422285291,
'upload_date': '20150126',
},
'add_ie': ['Viddler'],
},
# Libsyn embed
{
'url': 'http://thedailyshow.cc.com/podcast/episodetwelve',
'info_dict': {
'id': '3377616',
'ext': 'mp3',
'title': "The Daily Show Podcast without Jon Stewart - Episode 12: Bassem Youssef: Egypt's Jon Stewart",
'description': 'md5:601cb790edd05908957dae8aaa866465',
'upload_date': '20150220',
},
'skip': 'All The Daily Show URLs now redirect to http://www.cc.com/shows/',
},
# jwplayer YouTube
{
'url': 'http://media.nationalarchives.gov.uk/index.php/webinar-using-discovery-national-archives-online-catalogue/',
'info_dict': {
'id': 'Mrj4DVp2zeA',
'ext': 'mp4',
'upload_date': '20150212',
'uploader': 'The National Archives UK',
'description': 'md5:8078af856dca76edc42910b61273dbbf',
'uploader_id': 'NationalArchives08',
'title': 'Webinar: Using Discovery, The National Archives’ online catalogue',
},
},
# jwplayer rtmp
{
'url': 'http://www.suffolk.edu/sjc/live.php',
'info_dict': {
'id': 'live',
'ext': 'flv',
'title': 'Massachusetts Supreme Judicial Court Oral Arguments',
'uploader': 'www.suffolk.edu',
},
'params': {
'skip_download': True,
},
'skip': 'Only has video a few mornings per month, see http://www.suffolk.edu/sjc/',
},
# Complex jwplayer
{
'url': 'http://www.indiedb.com/games/king-machine/videos',
'info_dict': {
'id': 'videos',
'ext': 'mp4',
'title': 'king machine trailer 1',
'description': 'Browse King Machine videos & audio for sweet media. Your eyes will thank you.',
'thumbnail': r're:^https?://.*\.jpg$',
},
},
{
# JWPlayer config passed as variable
'url': 'http://www.txxx.com/videos/3326530/ariele/',
'info_dict': {
'id': '3326530_hq',
'ext': 'mp4',
'title': 'ARIELE | Tube Cup',
'uploader': 'www.txxx.com',
'age_limit': 18,
},
'params': {
'skip_download': True,
}
},
{
# JWPlatform iframe
'url': 'https://www.mediaite.com/tv/dem-senator-claims-gary-cohn-faked-a-bad-connection-during-trump-call-to-get-him-off-the-phone/',
'md5': 'ca00a040364b5b439230e7ebfd02c4e9',
'info_dict': {
'id': 'O0c5JcKT',
'ext': 'mp4',
'upload_date': '20171122',
'timestamp': 1511366290,
'title': 'Dem Senator Claims Gary Cohn Faked a Bad Connection During Trump Call to Get Him Off the Phone',
},
'add_ie': [JWPlatformIE.ie_key()],
},
{
# Video.js embed, multiple formats
'url': 'http://ortcam.com/solidworks-урок-6-настройка-чертежа_33f9b7351.html',
'info_dict': {
'id': 'yygqldloqIk',
'ext': 'mp4',
'title': 'SolidWorks. Урок 6 Настройка чертежа',
'description': 'md5:baf95267792646afdbf030e4d06b2ab3',
'upload_date': '20130314',
'uploader': 'PROстое3D',
'uploader_id': 'PROstoe3D',
},
'params': {
'skip_download': True,
},
},
{
# Video.js embed, single format
'url': 'https://www.vooplayer.com/v3/watch/watch.php?v=NzgwNTg=',
'info_dict': {
'id': 'watch',
'ext': 'mp4',
'title': 'Step 1 - Good Foundation',
'description': 'md5:d1e7ff33a29fc3eb1673d6c270d344f4',
},
'params': {
'skip_download': True,
},
},
# rtl.nl embed
{
'url': 'http://www.rtlnieuws.nl/nieuws/buitenland/aanslagen-kopenhagen',
'playlist_mincount': 5,
'info_dict': {
'id': 'aanslagen-kopenhagen',
'title': 'Aanslagen Kopenhagen',
}
},
# Zapiks embed
{
'url': 'http://www.skipass.com/news/116090-bon-appetit-s5ep3-baqueira-mi-cor.html',
'info_dict': {
'id': '118046',
'ext': 'mp4',
'title': 'EP3S5 - Bon Appétit - Baqueira Mi Corazon !',
}
},
# Kaltura embed (different embed code)
{
'url': 'http://www.premierchristianradio.com/Shows/Saturday/Unbelievable/Conference-Videos/Os-Guinness-Is-It-Fools-Talk-Unbelievable-Conference-2014',
'info_dict': {
'id': '1_a52wc67y',
'ext': 'flv',
'upload_date': '20150127',
'uploader_id': 'PremierMedia',
'timestamp': int,
'title': 'Os Guinness // Is It Fools Talk? // Unbelievable? Conference 2014',
},
},
# Kaltura embed with single quotes
{
'url': 'http://fod.infobase.com/p_ViewPlaylist.aspx?AssignmentID=NUN8ZY',
'info_dict': {
'id': '0_izeg5utt',
'ext': 'mp4',
'title': '35871',
'timestamp': 1355743100,
'upload_date': '20121217',
'uploader_id': 'cplapp@learn360.com',
},
'add_ie': ['Kaltura'],
},
{
# Kaltura embedded via quoted entry_id
'url': 'https://www.oreilly.com/ideas/my-cloud-makes-pretty-pictures',
'info_dict': {
'id': '0_utuok90b',
'ext': 'mp4',
'title': '06_matthew_brender_raj_dutt',
'timestamp': 1466638791,
'upload_date': '20160622',
},
'add_ie': ['Kaltura'],
'expected_warnings': [
'Could not send HEAD request'
],
'params': {
'skip_download': True,
}
},
{
# Kaltura embedded, some fileExt broken (#11480)
'url': 'http://www.cornell.edu/video/nima-arkani-hamed-standard-models-of-particle-physics',
'info_dict': {
'id': '1_sgtvehim',
'ext': 'mp4',
'title': 'Our "Standard Models" of particle physics and cosmology',
'description': 'md5:67ea74807b8c4fea92a6f38d6d323861',
'timestamp': 1321158993,
'upload_date': '20111113',
'uploader_id': 'kps1',
},
'add_ie': ['Kaltura'],
},
{
# Kaltura iframe embed
'url': 'http://www.gsd.harvard.edu/event/i-m-pei-a-centennial-celebration/',
'md5': 'ae5ace8eb09dc1a35d03b579a9c2cc44',
'info_dict': {
'id': '0_f2cfbpwy',
'ext': 'mp4',
'title': 'I. M. Pei: A Centennial Celebration',
'description': 'md5:1db8f40c69edc46ca180ba30c567f37c',
'upload_date': '20170403',
'uploader_id': 'batchUser',
'timestamp': 1491232186,
},
'add_ie': ['Kaltura'],
},
{
# Kaltura iframe embed, more sophisticated
'url': 'http://www.cns.nyu.edu/~eero/math-tools/Videos/lecture-05sep2017.html',
'info_dict': {
'id': '1_9gzouybz',
'ext': 'mp4',
'title': 'lecture-05sep2017',
'description': 'md5:40f347d91fd4ba047e511c5321064b49',
'upload_date': '20170913',
'uploader_id': 'eps2',
'timestamp': 1505340777,
},
'params': {
'skip_download': True,
},
'add_ie': ['Kaltura'],
},
{
# meta twitter:player
'url': 'http://thechive.com/2017/12/08/all-i-want-for-christmas-is-more-twerk/',
'info_dict': {
'id': '0_01b42zps',
'ext': 'mp4',
'title': 'Main Twerk (Video)',
'upload_date': '20171208',
'uploader_id': 'sebastian.salinas@thechive.com',
'timestamp': 1512713057,
},
'params': {
'skip_download': True,
},
'add_ie': ['Kaltura'],
},
# referrer protected EaglePlatform embed
{
'url': 'https://tvrain.ru/lite/teleshow/kak_vse_nachinalos/namin-418921/',
'info_dict': {
'id': '582306',
'ext': 'mp4',
'title': 'Стас Намин: «Мы нарушили девственность Кремля»',
'thumbnail': r're:^https?://.*\.jpg$',
'duration': 3382,
'view_count': int,
},
'params': {
'skip_download': True,
},
},
# ClipYou (EaglePlatform) embed (custom URL)
{
'url': 'http://muz-tv.ru/play/7129/',
# Not checking MD5 as sometimes the direct HTTP link results in 404 and HLS is used
'info_dict': {
'id': '12820',
'ext': 'mp4',
'title': "'O Sole Mio",
'thumbnail': r're:^https?://.*\.jpg$',
'duration': 216,
'view_count': int,
},
'params': {
'skip_download': True,
},
'skip': 'This video is unavailable.',
},
# Pladform embed
{
'url': 'http://muz-tv.ru/kinozal/view/7400/',
'info_dict': {
'id': '100183293',
'ext': 'mp4',
'title': 'Тайны перевала Дятлова • 1 серия 2 часть',
'description': 'Документальный сериал-расследование одной из самых жутких тайн ХХ века',
'thumbnail': r're:^https?://.*\.jpg$',
'duration': 694,
'age_limit': 0,
},
'skip': 'HTTP Error 404: Not Found',
},
# Playwire embed
{
'url': 'http://www.cinemablend.com/new/First-Joe-Dirt-2-Trailer-Teaser-Stupid-Greatness-70874.html',
'info_dict': {
'id': '3519514',
'ext': 'mp4',
'title': 'Joe Dirt 2 Beautiful Loser Teaser Trailer',
'thumbnail': r're:^https?://.*\.png$',
'duration': 45.115,
},
},
# 5min embed
{
'url': 'http://techcrunch.com/video/facebook-creates-on-this-day-crunch-report/518726732/',
'md5': '4c6f127a30736b59b3e2c19234ee2bf7',
'info_dict': {
'id': '518726732',
'ext': 'mp4',
'title': 'Facebook Creates "On This Day" | Crunch Report',
'description': 'Amazon updates Fire TV line, Tesla\'s Model X spotted in the wild',
'timestamp': 1427237531,
'uploader': 'Crunch Report',
'upload_date': '20150324',
},
'params': {
# m3u8 download
'skip_download': True,
},
},
# Crooks and Liars embed
{
'url': 'http://crooksandliars.com/2015/04/fox-friends-says-protecting-atheists',
'info_dict': {
'id': '8RUoRhRi',
'ext': 'mp4',
'title': "Fox & Friends Says Protecting Atheists From Discrimination Is Anti-Christian!",
'description': 'md5:e1a46ad1650e3a5ec7196d432799127f',
'timestamp': 1428207000,
'upload_date': '20150405',
'uploader': 'Heather',
},
},
# Crooks and Liars external embed
{
'url': 'http://theothermccain.com/2010/02/02/video-proves-that-bill-kristol-has-been-watching-glenn-beck/comment-page-1/',
'info_dict': {
'id': 'MTE3MjUtMzQ2MzA',
'ext': 'mp4',
'title': 'md5:5e3662a81a4014d24c250d76d41a08d5',
'description': 'md5:9b8e9542d6c3c5de42d6451b7d780cec',
'timestamp': 1265032391,
'upload_date': '20100201',
'uploader': 'Heather',
},
},
# NBC Sports vplayer embed
{
'url': 'http://www.riderfans.com/forum/showthread.php?121827-Freeman&s=e98fa1ea6dc08e886b1678d35212494a',
'info_dict': {
'id': 'ln7x1qSThw4k',
'ext': 'flv',
'title': "PFT Live: New leader in the 'new-look' defense",
'description': 'md5:65a19b4bbfb3b0c0c5768bed1dfad74e',
'uploader': 'NBCU-SPORTS',
'upload_date': '20140107',
'timestamp': 1389118457,
},
'skip': 'Invalid Page URL',
},
# NBC News embed
{
'url': 'http://www.vulture.com/2016/06/letterman-couldnt-care-less-about-late-night.html',
'md5': '1aa589c675898ae6d37a17913cf68d66',
'info_dict': {
'id': 'x_dtl_oa_LettermanliftPR_160608',
'ext': 'mp4',
'title': 'David Letterman: A Preview',
'description': 'A preview of Tom Brokaw\'s interview with David Letterman as part of the On Assignment series powered by Dateline. Airs Sunday June 12 at 7/6c.',
'upload_date': '20160609',
'timestamp': 1465431544,
'uploader': 'NBCU-NEWS',
},
},
# UDN embed
{
'url': 'https://video.udn.com/news/300346',
'md5': 'fd2060e988c326991037b9aff9df21a6',
'info_dict': {
'id': '300346',
'ext': 'mp4',
'title': '中一中男師變性 全校師生力挺',
'thumbnail': r're:^https?://.*\.jpg$',
},
'params': {
# m3u8 download
'skip_download': True,
},
'expected_warnings': ['Failed to parse JSON Expecting value'],
},
# Brightcove URL in single quotes
{
'url': 'http://www.sportsnet.ca/baseball/mlb/sn-presents-russell-martin-world-citizen/',
'md5': '4ae374f1f8b91c889c4b9203c8c752af',
'info_dict': {
'id': '4255764656001',
'ext': 'mp4',
'title': 'SN Presents: Russell Martin, World Citizen',
'description': 'To understand why he was the Toronto Blue Jays’ top off-season priority is to appreciate his background and upbringing in Montreal, where he first developed his baseball skills. Written and narrated by Stephen Brunt.',
'uploader': 'Rogers Sportsnet',
'uploader_id': '1704050871',
'upload_date': '20150525',
'timestamp': 1432570283,
},
},
# Kinja embed
{
'url': 'http://www.clickhole.com/video/dont-understand-bitcoin-man-will-mumble-explanatio-2537',
'info_dict': {
'id': '106351',
'ext': 'mp4',
'title': 'Don’t Understand Bitcoin? This Man Will Mumble An Explanation At You',
'description': 'Migrated from OnionStudios',
'thumbnail': r're:^https?://.*\.jpe?g$',
'uploader': 'clickhole',
'upload_date': '20150527',
'timestamp': 1432744860,
}
},
# SnagFilms embed
{
'url': 'http://whilewewatch.blogspot.ru/2012/06/whilewewatch-whilewewatch-gripping.html',
'info_dict': {
'id': '74849a00-85a9-11e1-9660-123139220831',
'ext': 'mp4',
'title': '#whilewewatch',
}
},
# AdobeTVVideo embed
{
'url': 'https://helpx.adobe.com/acrobat/how-to/new-experience-acrobat-dc.html?set=acrobat--get-started--essential-beginners',
'md5': '43662b577c018ad707a63766462b1e87',
'info_dict': {
'id': '2456',
'ext': 'mp4',
'title': 'New experience with Acrobat DC',
'description': 'New experience with Acrobat DC',
'duration': 248.667,
},
},
# BrightcoveInPageEmbed embed
{
'url': 'http://www.geekandsundry.com/tabletop-bonus-wils-final-thoughts-on-dread/',
'info_dict': {
'id': '4238694884001',
'ext': 'flv',
'title': 'Tabletop: Dread, Last Thoughts',
'description': 'Tabletop: Dread, Last Thoughts',
'duration': 51690,
},
},
# Brightcove embed, with no valid 'renditions' but valid 'IOSRenditions'
# This video can't be played in browsers if Flash disabled and UA set to iPhone, which is actually a false alarm
{
'url': 'https://dl.dropboxusercontent.com/u/29092637/interview.html',
'info_dict': {
'id': '4785848093001',
'ext': 'mp4',
'title': 'The Cardinal Pell Interview',
'description': 'Sky News Contributor Andrew Bolt interviews George Pell in Rome, following the Cardinal\'s evidence before the Royal Commission into Child Abuse. ',
'uploader': 'GlobeCast Australia - GlobeStream',
'uploader_id': '2733773828001',
'upload_date': '20160304',
'timestamp': 1457083087,
},
'params': {
# m3u8 downloads
'skip_download': True,
},
},
{
# Brightcove embed with whitespace around attribute names
'url': 'http://www.stack.com/video/3167554373001/learn-to-hit-open-three-pointers-with-damian-lillard-s-baseline-drift-drill',
'info_dict': {
'id': '3167554373001',
'ext': 'mp4',
'title': "Learn to Hit Open Three-Pointers With Damian Lillard's Baseline Drift Drill",
'description': 'md5:57bacb0e0f29349de4972bfda3191713',
'uploader_id': '1079349493',
'upload_date': '20140207',
'timestamp': 1391810548,
},
'params': {
'skip_download': True,
},
},
# Another form of arte.tv embed
{
'url': 'http://www.tv-replay.fr/redirection/09-04-16/arte-reportage-arte-11508975.html',
'md5': '850bfe45417ddf221288c88a0cffe2e2',
'info_dict': {
'id': '030273-562_PLUS7-F',
'ext': 'mp4',
'title': 'ARTE Reportage - Nulle part, en France',
'description': 'md5:e3a0e8868ed7303ed509b9e3af2b870d',
'upload_date': '20160409',
},
},
# LiveLeak embed
{
'url': 'http://www.wykop.pl/link/3088787/',
'md5': '7619da8c820e835bef21a1efa2a0fc71',
'info_dict': {
'id': '874_1459135191',
'ext': 'mp4',
'title': 'Man shows poor quality of new apartment building',
'description': 'The wall is like a sand pile.',
'uploader': 'Lake8737',
},
'add_ie': [LiveLeakIE.ie_key()],
},
# Another LiveLeak embed pattern (#13336)
{
'url': 'https://milo.yiannopoulos.net/2017/06/concealed-carry-robbery/',
'info_dict': {
'id': '2eb_1496309988',
'ext': 'mp4',
'title': 'Thief robs place where everyone was armed',
'description': 'md5:694d73ee79e535953cf2488562288eee',
'uploader': 'brazilwtf',
},
'add_ie': [LiveLeakIE.ie_key()],
},
# Duplicated embedded video URLs
{
'url': 'http://www.hudl.com/athlete/2538180/highlights/149298443',
'info_dict': {
'id': '149298443_480_16c25b74_2',
'ext': 'mp4',
'title': 'vs. Blue Orange Spring Game',
'uploader': 'www.hudl.com',
},
},
# twitter:player:stream embed
{
'url': 'http://www.rtl.be/info/video/589263.aspx?CategoryID=288',
'info_dict': {
'id': 'master',
'ext': 'mp4',
'title': 'Une nouvelle espèce de dinosaure découverte en Argentine',
'uploader': 'www.rtl.be',
},
'params': {
# m3u8 downloads
'skip_download': True,
},
},
# twitter:player embed
{
'url': 'http://www.theatlantic.com/video/index/484130/what-do-black-holes-sound-like/',
'md5': 'a3e0df96369831de324f0778e126653c',
'info_dict': {
'id': '4909620399001',
'ext': 'mp4',
'title': 'What Do Black Holes Sound Like?',
'description': 'what do black holes sound like',
'upload_date': '20160524',
'uploader_id': '29913724001',
'timestamp': 1464107587,
'uploader': 'TheAtlantic',
},
'add_ie': ['BrightcoveLegacy'],
},
# Facebook <iframe> embed
{
'url': 'https://www.hostblogger.de/blog/archives/6181-Auto-jagt-Betonmischer.html',
'md5': 'fbcde74f534176ecb015849146dd3aee',
'info_dict': {
'id': '599637780109885',
'ext': 'mp4',
'title': 'Facebook video #599637780109885',
},
},
# Facebook <iframe> embed, plugin video
{
'url': 'http://5pillarsuk.com/2017/06/07/tariq-ramadan-disagrees-with-pr-exercise-by-imams-refusing-funeral-prayers-for-london-attackers/',
'info_dict': {
'id': '1754168231264132',
'ext': 'mp4',
'title': 'About the Imams and Religious leaders refusing to perform funeral prayers for...',
'uploader': 'Tariq Ramadan (official)',
'timestamp': 1496758379,
'upload_date': '20170606',
},
'params': {
'skip_download': True,
},
},
# Facebook API embed
{
'url': 'http://www.lothype.com/blue-stars-2016-preview-standstill-full-show/',
'md5': 'a47372ee61b39a7b90287094d447d94e',
'info_dict': {
'id': '10153467542406923',
'ext': 'mp4',
'title': 'Facebook video #10153467542406923',
},
},
# Wordpress "YouTube Video Importer" plugin
{
'url': 'http://www.lothype.com/blue-devils-drumline-stanford-lot-2016/',
'md5': 'd16797741b560b485194eddda8121b48',
'info_dict': {
'id': 'HNTXWDXV9Is',
'ext': 'mp4',
'title': 'Blue Devils Drumline Stanford lot 2016',
'upload_date': '20160627',
'uploader_id': 'GENOCIDE8GENERAL10',
'uploader': 'cylus cyrus',
},
},
{
# video stored on custom kaltura server
'url': 'http://www.expansion.com/multimedia/videos.html?media=EQcM30NHIPv',
'md5': '537617d06e64dfed891fa1593c4b30cc',
'info_dict': {
'id': '0_1iotm5bh',
'ext': 'mp4',
'title': 'Elecciones británicas: 5 lecciones para Rajoy',
'description': 'md5:435a89d68b9760b92ce67ed227055f16',
'uploader_id': 'videos.expansion@el-mundo.net',
'upload_date': '20150429',
'timestamp': 1430303472,
},
'add_ie': ['Kaltura'],
},
{
# multiple kaltura embeds, nsfw
'url': 'https://www.quartier-rouge.be/prive/femmes/kamila-avec-video-jaime-sadomie.html',
'info_dict': {
'id': 'kamila-avec-video-jaime-sadomie',
'title': "Kamila avec vídeo “J'aime sadomie”",
},
'playlist_count': 8,
},
{
# Non-standard Vimeo embed
'url': 'https://openclassrooms.com/courses/understanding-the-web',
'md5': '64d86f1c7d369afd9a78b38cbb88d80a',
'info_dict': {
'id': '148867247',
'ext': 'mp4',
'title': 'Understanding the web - Teaser',
'description': 'This is "Understanding the web - Teaser" by openclassrooms on Vimeo, the home for high quality videos and the people who love them.',
'upload_date': '20151214',
'uploader': 'OpenClassrooms',
'uploader_id': 'openclassrooms',
},
'add_ie': ['Vimeo'],
},
{
# generic vimeo embed that requires original URL passed as Referer
'url': 'http://racing4everyone.eu/2016/07/30/formula-1-2016-round12-germany/',
'only_matching': True,
},
{
'url': 'https://support.arkena.com/display/PLAY/Ways+to+embed+your+video',
'md5': 'b96f2f71b359a8ecd05ce4e1daa72365',
'info_dict': {
'id': 'b41dda37-d8e7-4d3f-b1b5-9a9db578bdfe',
'ext': 'mp4',
'title': 'Big Buck Bunny',
'description': 'Royalty free test video',
'timestamp': 1432816365,
'upload_date': '20150528',
'is_live': False,
},
'params': {
'skip_download': True,
},
'add_ie': [ArkenaIE.ie_key()],
},
{
'url': 'http://nova.bg/news/view/2016/08/16/156543/%D0%BD%D0%B0-%D0%BA%D0%BE%D1%81%D1%8A%D0%BC-%D0%BE%D1%82-%D0%B2%D0%B7%D1%80%D0%B8%D0%B2-%D0%BE%D1%82%D1%86%D0%B5%D0%BF%D0%B8%D1%85%D0%B0-%D1%86%D1%8F%D0%BB-%D0%BA%D0%B2%D0%B0%D1%80%D1%82%D0%B0%D0%BB-%D0%B7%D0%B0%D1%80%D0%B0%D0%B4%D0%B8-%D0%B8%D0%B7%D1%82%D0%B8%D1%87%D0%B0%D0%BD%D0%B5-%D0%BD%D0%B0-%D0%B3%D0%B0%D0%B7-%D0%B2-%D0%BF%D0%BB%D0%BE%D0%B2%D0%B4%D0%B8%D0%B2/',
'info_dict': {
'id': '1c7141f46c',
'ext': 'mp4',
'title': 'НА КОСЪМ ОТ ВЗРИВ: Изтичане на газ на бензиностанция в Пловдив',
},
'params': {
'skip_download': True,
},
'add_ie': [Vbox7IE.ie_key()],
},
{
# DBTV embeds
'url': 'http://www.dagbladet.no/2016/02/23/nyheter/nordlys/ski/troms/ver/43254897/',
'info_dict': {
'id': '43254897',
'title': 'Etter ett års planlegging, klaffet endelig alt: - Jeg måtte ta en liten dans',
},
'playlist_mincount': 3,
},
{
# Videa embeds
'url': 'http://forum.dvdtalk.com/movie-talk/623756-deleted-magic-star-wars-ot-deleted-alt-scenes-docu-style.html',
'info_dict': {
'id': '623756-deleted-magic-star-wars-ot-deleted-alt-scenes-docu-style',
'title': 'Deleted Magic - Star Wars: OT Deleted / Alt. Scenes Docu. Style - DVD Talk Forum',
},
'playlist_mincount': 2,
},
{
# 20 minuten embed
'url': 'http://www.20min.ch/schweiz/news/story/So-kommen-Sie-bei-Eis-und-Schnee-sicher-an-27032552',
'info_dict': {
'id': '523629',
'ext': 'mp4',
'title': 'So kommen Sie bei Eis und Schnee sicher an',
'description': 'md5:117c212f64b25e3d95747e5276863f7d',
},
'params': {
'skip_download': True,
},
'add_ie': [TwentyMinutenIE.ie_key()],
},
{
# VideoPress embed
'url': 'https://en.support.wordpress.com/videopress/',
'info_dict': {
'id': 'OcobLTqC',
'ext': 'm4v',
'title': 'IMG_5786',
'timestamp': 1435711927,
'upload_date': '20150701',
},
'params': {
'skip_download': True,
},
'add_ie': [VideoPressIE.ie_key()],
},
{
# Rutube embed
'url': 'http://magazzino.friday.ru/videos/vipuski/kazan-2',
'info_dict': {
'id': '9b3d5bee0a8740bf70dfd29d3ea43541',
'ext': 'flv',
'title': 'Магаззино: Казань 2',
'description': 'md5:99bccdfac2269f0e8fdbc4bbc9db184a',
'uploader': 'Магаззино',
'upload_date': '20170228',
'uploader_id': '996642',
},
'params': {
'skip_download': True,
},
'add_ie': [RutubeIE.ie_key()],
},
{
# ThePlatform embedded with whitespaces in URLs
'url': 'http://www.golfchannel.com/topics/shows/golftalkcentral.htm',
'only_matching': True,
},
{
# Senate ISVP iframe https
'url': 'https://www.hsgac.senate.gov/hearings/canadas-fast-track-refugee-plan-unanswered-questions-and-implications-for-us-national-security',
'md5': 'fb8c70b0b515e5037981a2492099aab8',
'info_dict': {
'id': 'govtaff020316',
'ext': 'mp4',
'title': 'Integrated Senate Video Player',
},
'add_ie': [SenateISVPIE.ie_key()],
},
{
# Limelight embeds (1 channel embed + 4 media embeds)
'url': 'http://www.sedona.com/FacilitatorTraining2017',
'info_dict': {
'id': 'FacilitatorTraining2017',
'title': 'Facilitator Training 2017',
},
'playlist_mincount': 5,
},
{
# Limelight embed (LimelightPlayerUtil.embed)
'url': 'https://tv5.ca/videos?v=xuu8qowr291ri',
'info_dict': {
'id': '95d035dc5c8a401588e9c0e6bd1e9c92',
'ext': 'mp4',
'title': '07448641',
'timestamp': 1499890639,
'upload_date': '20170712',
},
'params': {
'skip_download': True,
},
'add_ie': ['LimelightMedia'],
},
{
'url': 'http://kron4.com/2017/04/28/standoff-with-walnut-creek-murder-suspect-ends-with-arrest/',
'info_dict': {
'id': 'standoff-with-walnut-creek-murder-suspect-ends-with-arrest',
'title': 'Standoff with Walnut Creek murder suspect ends',
'description': 'md5:3ccc48a60fc9441eeccfc9c469ebf788',
},
'playlist_mincount': 4,
},
{
# WashingtonPost embed
'url': 'http://www.vanityfair.com/hollywood/2017/04/donald-trump-tv-pitches',
'info_dict': {
'id': '8caf6e88-d0ec-11e5-90d3-34c2c42653ac',
'ext': 'mp4',
'title': "No one has seen the drama series based on Trump's life \u2014 until now",
'description': 'Donald Trump wanted a weekly TV drama based on his life. It never aired. But The Washington Post recently obtained a scene from the pilot script — and enlisted actors.',
'timestamp': 1455216756,
'uploader': 'The Washington Post',
'upload_date': '20160211',
},
'add_ie': [WashingtonPostIE.ie_key()],
},
{
# Mediaset embed
'url': 'http://www.tgcom24.mediaset.it/politica/serracchiani-voglio-vivere-in-una-societa-aperta-reazioni-sproporzionate-_3071354-201702a.shtml',
'info_dict': {
'id': '720642',
'ext': 'mp4',
'title': 'Serracchiani: "Voglio vivere in una società aperta, con tutela del patto di fiducia"',
},
'params': {
'skip_download': True,
},
'add_ie': [MediasetIE.ie_key()],
},
{
# JOJ.sk embeds
'url': 'https://www.noviny.sk/slovensko/238543-slovenskom-sa-prehnala-vlna-silnych-burok',
'info_dict': {
'id': '238543-slovenskom-sa-prehnala-vlna-silnych-burok',
'title': 'Slovenskom sa prehnala vlna silných búrok',
},
'playlist_mincount': 5,
'add_ie': [JojIE.ie_key()],
},
{
# AMP embed (see https://www.ampproject.org/docs/reference/components/amp-video)
'url': 'https://tvrain.ru/amp/418921/',
'md5': 'cc00413936695987e8de148b67d14f1d',
'info_dict': {
'id': '418921',
'ext': 'mp4',
'title': 'Стас Намин: «Мы нарушили девственность Кремля»',
},
},
{
# vzaar embed
'url': 'http://help.vzaar.com/article/165-embedding-video',
'md5': '7e3919d9d2620b89e3e00bec7fe8c9d4',
'info_dict': {
'id': '8707641',
'ext': 'mp4',
'title': 'Building A Business Online: Principal Chairs Q & A',
},
},
{
# multiple HTML5 videos on one page
'url': 'https://www.paragon-software.com/home/rk-free/keyscenarios.html',
'info_dict': {
'id': 'keyscenarios',
'title': 'Rescue Kit 14 Free Edition - Getting started',
},
'playlist_count': 4,
},
{
# vshare embed
'url': 'https://youtube-dl-demo.neocities.org/vshare.html',
'md5': '17b39f55b5497ae8b59f5fbce8e35886',
'info_dict': {
'id': '0f64ce6',
'title': 'vl14062007715967',
'ext': 'mp4',
}
},
{
'url': 'http://www.heidelberg-laureate-forum.org/blog/video/lecture-friday-september-23-2016-sir-c-antony-r-hoare/',
'md5': 'aecd089f55b1cb5a59032cb049d3a356',
'info_dict': {
'id': '90227f51a80c4d8f86c345a7fa62bd9a1d',
'ext': 'mp4',
'title': 'Lecture: Friday, September 23, 2016 - Sir Tony Hoare',
'description': 'md5:5a51db84a62def7b7054df2ade403c6c',
'timestamp': 1474354800,
'upload_date': '20160920',
}
},
{
'url': 'http://www.kidzworld.com/article/30935-trolls-the-beat-goes-on-interview-skylar-astin-and-amanda-leighton',
'info_dict': {
'id': '1731611',
'ext': 'mp4',
'title': 'Official Trailer | TROLLS: THE BEAT GOES ON!',
'description': 'md5:eb5f23826a027ba95277d105f248b825',
'timestamp': 1516100691,
'upload_date': '20180116',
},
'params': {
'skip_download': True,
},
'add_ie': [SpringboardPlatformIE.ie_key()],
},
{
'url': 'https://www.yapfiles.ru/show/1872528/690b05d3054d2dbe1e69523aa21bb3b1.mp4.html',
'info_dict': {
'id': 'vMDE4NzI1Mjgt690b',
'ext': 'mp4',
'title': 'Котята',
},
'add_ie': [YapFilesIE.ie_key()],
'params': {
'skip_download': True,
},
},
{
# CloudflareStream embed
'url': 'https://www.cloudflare.com/products/cloudflare-stream/',
'info_dict': {
'id': '31c9291ab41fac05471db4e73aa11717',
'ext': 'mp4',
'title': '31c9291ab41fac05471db4e73aa11717',
},
'add_ie': [CloudflareStreamIE.ie_key()],
'params': {
'skip_download': True,
},
},
{
# PeerTube embed
'url': 'https://joinpeertube.org/fr/home/',
'info_dict': {
'id': 'home',
'title': 'Reprenez le contrôle de vos vidéos ! #JoinPeertube',
},
'playlist_count': 2,
},
{
# Indavideo embed
'url': 'https://streetkitchen.hu/receptek/igy_kell_otthon_hamburgert_sutni/',
'info_dict': {
'id': '1693903',
'ext': 'mp4',
'title': 'Így kell otthon hamburgert sütni',
'description': 'md5:f5a730ecf900a5c852e1e00540bbb0f7',
'timestamp': 1426330212,
'upload_date': '20150314',
'uploader': 'StreetKitchen',
'uploader_id': '546363',
},
'add_ie': [IndavideoEmbedIE.ie_key()],
'params': {
'skip_download': True,
},
},
{
# APA embed via JWPlatform embed
'url': 'http://www.vol.at/blue-man-group/5593454',
'info_dict': {
'id': 'jjv85FdZ',
'ext': 'mp4',
'title': '"Blau ist mysteriös": Die Blue Man Group im Interview',
'description': 'md5:d41d8cd98f00b204e9800998ecf8427e',
'thumbnail': r're:^https?://.*\.jpg$',
'duration': 254,
'timestamp': 1519211149,
'upload_date': '20180221',
},
'params': {
'skip_download': True,
},
},
{
'url': 'http://share-videos.se/auto/video/83645793?uid=13',
'md5': 'b68d276de422ab07ee1d49388103f457',
'info_dict': {
'id': '83645793',
'title': 'Lock up and get excited',
'ext': 'mp4'
},
'skip': 'TODO: fix nested playlists processing in tests',
},
{
# Viqeo embeds
'url': 'https://viqeo.tv/',
'info_dict': {
'id': 'viqeo',
'title': 'All-new video platform',
},
'playlist_count': 6,
},
{
# Squarespace video embed, 2019-08-28
'url': 'http://ootboxford.com',
'info_dict': {
'id': 'Tc7b_JGdZfw',
'title': 'Out of the Blue, at Childish Things 10',
'ext': 'mp4',
'description': 'md5:a83d0026666cf5ee970f8bd1cfd69c7f',
'uploader_id': 'helendouglashouse',
'uploader': 'Helen & Douglas House',
'upload_date': '20140328',
},
'params': {
'skip_download': True,
},
},
# {
# # Zype embed
# 'url': 'https://www.cookscountry.com/episode/554-smoky-barbecue-favorites',
# 'info_dict': {
# 'id': '5b400b834b32992a310622b9',
# 'ext': 'mp4',
# 'title': 'Smoky Barbecue Favorites',
# 'thumbnail': r're:^https?://.*\.jpe?g',
# 'description': 'md5:5ff01e76316bd8d46508af26dc86023b',
# 'upload_date': '20170909',
# 'timestamp': 1504915200,
# },
# 'add_ie': [ZypeIE.ie_key()],
# 'params': {
# 'skip_download': True,
# },
# },
{
# videojs embed
'url': 'https://video.sibnet.ru/shell.php?videoid=3422904',
'info_dict': {
'id': 'shell',
'ext': 'mp4',
'title': 'Доставщик пиццы спросил разрешения сыграть на фортепиано',
'description': 'md5:89209cdc587dab1e4a090453dbaa2cb1',
'thumbnail': r're:^https?://.*\.jpg$',
},
'params': {
'skip_download': True,
},
'expected_warnings': ['Failed to download MPD manifest'],
},
{
# DailyMotion embed with DM.player
'url': 'https://www.beinsports.com/us/copa-del-rey/video/the-locker-room-valencia-beat-barca-in-copa/1203804',
'info_dict': {
'id': 'k6aKkGHd9FJs4mtJN39',
'ext': 'mp4',
'title': 'The Locker Room: Valencia Beat Barca In Copa del Rey Final',
'description': 'This video is private.',
'uploader_id': 'x1jf30l',
'uploader': 'beIN SPORTS USA',
'upload_date': '20190528',
'timestamp': 1559062971,
},
'params': {
'skip_download': True,
},
},
# {
# # TODO: find another test
# # http://schema.org/VideoObject
# 'url': 'https://flipagram.com/f/nyvTSJMKId',
# 'md5': '888dcf08b7ea671381f00fab74692755',
# 'info_dict': {
# 'id': 'nyvTSJMKId',
# 'ext': 'mp4',
# 'title': 'Flipagram by sjuria101 featuring Midnight Memories by One Direction',
# 'description': '#love for cats.',
# 'timestamp': 1461244995,
# 'upload_date': '20160421',
# },
# 'params': {
# 'force_generic_extractor': True,
# },
# },
{
# VHX Embed
'url': 'https://demo.vhx.tv/category-c/videos/file-example-mp4-480-1-5mg-copy',
'info_dict': {
'id': '858208',
'ext': 'mp4',
'title': 'Untitled',
'uploader_id': 'user80538407',
'uploader': 'OTT Videos',
},
},
{
# ArcPublishing PoWa video player
'url': 'https://www.adn.com/politics/2020/11/02/video-senate-candidates-campaign-in-anchorage-on-eve-of-election-day/',
'md5': 'b03b2fac8680e1e5a7cc81a5c27e71b3',
'info_dict': {
'id': '8c99cb6e-b29c-4bc9-9173-7bf9979225ab',
'ext': 'mp4',
'title': 'Senate candidates wave to voters on Anchorage streets',
'description': 'md5:91f51a6511f090617353dc720318b20e',
'timestamp': 1604378735,
'upload_date': '20201103',
'duration': 1581,
},
},
{
# MyChannels SDK embed
# https://www.24kitchen.nl/populair/deskundige-dit-waarom-sommigen-gevoelig-zijn-voor-voedselallergieen
'url': 'https://www.demorgen.be/nieuws/burgemeester-rotterdam-richt-zich-in-videoboodschap-tot-relschoppers-voelt-het-goed~b0bcfd741/',
'md5': '90c0699c37006ef18e198c032d81739c',
'info_dict': {
'id': '194165',
'ext': 'mp4',
'title': 'Burgemeester Aboutaleb spreekt relschoppers toe',
'timestamp': 1611740340,
'upload_date': '20210127',
'duration': 159,
},
},
{
# Simplecast player embed
'url': 'https://www.bio.org/podcast',
'info_dict': {
'id': 'podcast',
'title': 'I AM BIO Podcast | BIO',
},
'playlist_mincount': 52,
},
{
# WimTv embed player
'url': 'http://www.msmotor.tv/wearefmi-pt-2-2021/',
'info_dict': {
'id': 'wearefmi-pt-2-2021',
'title': '#WEAREFMI – PT.2 – 2021 – MsMotorTV',
},
'playlist_count': 1,
},
]
def report_following_redirect(self, new_url):
"""Report information extraction."""
self._downloader.to_screen('[redirect] Following redirect to %s' % new_url)
def _extract_rss(self, url, video_id, doc):
playlist_title = doc.find('./channel/title').text
playlist_desc_el = doc.find('./channel/description')
playlist_desc = None if playlist_desc_el is None else playlist_desc_el.text
NS_MAP = {
'itunes': 'http://www.itunes.com/dtds/podcast-1.0.dtd',
}
entries = []
for it in doc.findall('./channel/item'):
next_url = None
enclosure_nodes = it.findall('./enclosure')
for e in enclosure_nodes:
next_url = e.attrib.get('url')
if next_url:
break
if not next_url:
next_url = xpath_text(it, 'link', fatal=False)
if not next_url:
continue
def itunes(key):
return xpath_text(
it, xpath_with_ns('./itunes:%s' % key, NS_MAP),
default=None)
duration = itunes('duration')
explicit = (itunes('explicit') or '').lower()
if explicit in ('true', 'yes'):
age_limit = 18
elif explicit in ('false', 'no'):
age_limit = 0
else:
age_limit = None
entries.append({
'_type': 'url_transparent',
'url': next_url,
'title': it.find('title').text,
'description': xpath_text(it, 'description', default=None),
'timestamp': unified_timestamp(
xpath_text(it, 'pubDate', default=None)),
'duration': int_or_none(duration) or parse_duration(duration),
'thumbnail': url_or_none(xpath_attr(it, xpath_with_ns('./itunes:image', NS_MAP), 'href')),
'episode': itunes('title'),
'episode_number': int_or_none(itunes('episode')),
'season_number': int_or_none(itunes('season')),
'age_limit': age_limit,
})
return {
'_type': 'playlist',
'id': url,
'title': playlist_title,
'description': playlist_desc,
'entries': entries,
}
def _extract_camtasia(self, url, video_id, webpage):
""" Returns None if no camtasia video can be found. """
camtasia_cfg = self._search_regex(
r'fo\.addVariable\(\s*"csConfigFile",\s*"([^"]+)"\s*\);',
webpage, 'camtasia configuration file', default=None)
if camtasia_cfg is None:
return None
title = self._html_search_meta('DC.title', webpage, fatal=True)
camtasia_url = compat_urlparse.urljoin(url, camtasia_cfg)
camtasia_cfg = self._download_xml(
camtasia_url, video_id,
note='Downloading camtasia configuration',
errnote='Failed to download camtasia configuration')
fileset_node = camtasia_cfg.find('./playlist/array/fileset')
entries = []
for n in fileset_node.getchildren():
url_n = n.find('./uri')
if url_n is None:
continue
entries.append({
'id': os.path.splitext(url_n.text.rpartition('/')[2])[0],
'title': '%s - %s' % (title, n.tag),
'url': compat_urlparse.urljoin(url, url_n.text),
'duration': float_or_none(n.find('./duration').text),
})
return {
'_type': 'playlist',
'entries': entries,
'title': title,
}
def _real_extract(self, url):
if url.startswith('//'):
return self.url_result(self.http_scheme() + url)
parsed_url = compat_urlparse.urlparse(url)
if not parsed_url.scheme:
default_search = self.get_param('default_search')
if default_search is None:
default_search = 'fixup_error'
if default_search in ('auto', 'auto_warning', 'fixup_error'):
if re.match(r'^[^\s/]+\.[^\s/]+/', url):
self.report_warning('The url doesn\'t specify the protocol, trying with http')
return self.url_result('http://' + url)
elif default_search != 'fixup_error':
if default_search == 'auto_warning':
if re.match(r'^(?:url|URL)$', url):
raise ExtractorError(
'Invalid URL: %r . Call yt-dlp like this: yt-dlp -v "https://www.youtube.com/watch?v=BaW_jenozKc" ' % url,
expected=True)
else:
self.report_warning(
'Falling back to youtube search for %s . Set --default-search "auto" to suppress this warning.' % url)
return self.url_result('ytsearch:' + url)
if default_search in ('error', 'fixup_error'):
raise ExtractorError(
'%r is not a valid URL. '
'Set --default-search "ytsearch" (or run yt-dlp "ytsearch:%s" ) to search YouTube'
% (url, url), expected=True)
else:
if ':' not in default_search:
default_search += ':'
return self.url_result(default_search + url)
url, smuggled_data = unsmuggle_url(url)
force_videoid = None
is_intentional = smuggled_data and smuggled_data.get('to_generic')
if smuggled_data and 'force_videoid' in smuggled_data:
force_videoid = smuggled_data['force_videoid']
video_id = force_videoid
else:
video_id = self._generic_id(url)
self.to_screen('%s: Requesting header' % video_id)
head_req = HEADRequest(url)
head_response = self._request_webpage(
head_req, video_id,
note=False, errnote='Could not send HEAD request to %s' % url,
fatal=False)
if head_response is not False:
# Check for redirect
new_url = head_response.geturl()
if url != new_url:
self.report_following_redirect(new_url)
if force_videoid:
new_url = smuggle_url(
new_url, {'force_videoid': force_videoid})
return self.url_result(new_url)
full_response = None
if head_response is False:
request = sanitized_Request(url)
request.add_header('Accept-Encoding', '*')
full_response = self._request_webpage(request, video_id)
head_response = full_response
info_dict = {
'id': video_id,
'title': self._generic_title(url),
'timestamp': unified_timestamp(head_response.headers.get('Last-Modified'))
}
# Check for direct link to a video
content_type = head_response.headers.get('Content-Type', '').lower()
m = re.match(r'^(?P<type>audio|video|application(?=/(?:ogg$|(?:vnd\.apple\.|x-)?mpegurl)))/(?P<format_id>[^;\s]+)', content_type)
if m:
format_id = compat_str(m.group('format_id'))
subtitles = {}
if format_id.endswith('mpegurl'):
formats, subtitles = self._extract_m3u8_formats_and_subtitles(url, video_id, 'mp4')
elif format_id == 'f4m':
formats = self._extract_f4m_formats(url, video_id)
else:
formats = [{
'format_id': format_id,
'url': url,
'vcodec': 'none' if m.group('type') == 'audio' else None
}]
info_dict['direct'] = True
self._sort_formats(formats)
info_dict['formats'] = formats
info_dict['subtitles'] = subtitles
return info_dict
if not self.get_param('test', False) and not is_intentional:
force = self.get_param('force_generic_extractor', False)
self.report_warning(
'%s on generic information extractor.' % ('Forcing' if force else 'Falling back'))
if not full_response:
request = sanitized_Request(url)
# Some webservers may serve compressed content of rather big size (e.g. gzipped flac)
# making it impossible to download only chunk of the file (yet we need only 512kB to
# test whether it's HTML or not). According to yt-dlp default Accept-Encoding
# that will always result in downloading the whole file that is not desirable.
# Therefore for extraction pass we have to override Accept-Encoding to any in order
# to accept raw bytes and being able to download only a chunk.
# It may probably better to solve this by checking Content-Type for application/octet-stream
# after HEAD request finishes, but not sure if we can rely on this.
request.add_header('Accept-Encoding', '*')
full_response = self._request_webpage(request, video_id)
first_bytes = full_response.read(512)
# Is it an M3U playlist?
if first_bytes.startswith(b'#EXTM3U'):
info_dict['formats'] = self._extract_m3u8_formats(url, video_id, 'mp4')
self._sort_formats(info_dict['formats'])
return info_dict
# Maybe it's a direct link to a video?
# Be careful not to download the whole thing!
if not is_html(first_bytes):
self.report_warning(
'URL could be a direct video link, returning it as such.')
info_dict.update({
'direct': True,
'url': url,
})
return info_dict
webpage = self._webpage_read_content(
full_response, url, video_id, prefix=first_bytes)
if '<title>DPG Media Privacy Gate</title>' in webpage:
webpage = self._download_webpage(url, video_id)
self.report_extraction(video_id)
# Is it an RSS feed, a SMIL file, an XSPF playlist or a MPD manifest?
try:
try:
doc = compat_etree_fromstring(webpage)
except compat_xml_parse_error:
doc = compat_etree_fromstring(webpage.encode('utf-8'))
if doc.tag == 'rss':
return self._extract_rss(url, video_id, doc)
elif doc.tag == 'SmoothStreamingMedia':
info_dict['formats'], info_dict['subtitles'] = self._parse_ism_formats_and_subtitles(doc, url)
self._sort_formats(info_dict['formats'])
return info_dict
elif re.match(r'^(?:{[^}]+})?smil$', doc.tag):
smil = self._parse_smil(doc, url, video_id)
self._sort_formats(smil['formats'])
return smil
elif doc.tag == '{http://xspf.org/ns/0/}playlist':
return self.playlist_result(
self._parse_xspf(
doc, video_id, xspf_url=url,
xspf_base_url=full_response.geturl()),
video_id)
elif re.match(r'(?i)^(?:{[^}]+})?MPD$', doc.tag):
info_dict['formats'], info_dict['subtitles'] = self._parse_mpd_formats_and_subtitles(
doc,
mpd_base_url=full_response.geturl().rpartition('/')[0],
mpd_url=url)
self._sort_formats(info_dict['formats'])
return info_dict
elif re.match(r'^{http://ns\.adobe\.com/f4m/[12]\.0}manifest$', doc.tag):
info_dict['formats'] = self._parse_f4m_formats(doc, url, video_id)
self._sort_formats(info_dict['formats'])
return info_dict
except compat_xml_parse_error:
pass
# Is it a Camtasia project?
camtasia_res = self._extract_camtasia(url, video_id, webpage)
if camtasia_res is not None:
return camtasia_res
# Sometimes embedded video player is hidden behind percent encoding
# (e.g. https://github.com/ytdl-org/youtube-dl/issues/2448)
# Unescaping the whole page allows to handle those cases in a generic way
# FIXME: unescaping the whole page may break URLs, commenting out for now.
# There probably should be a second run of generic extractor on unescaped webpage.
# webpage = compat_urllib_parse_unquote(webpage)
# Unescape squarespace embeds to be detected by generic extractor,
# see https://github.com/ytdl-org/youtube-dl/issues/21294
webpage = re.sub(
r'<div[^>]+class=[^>]*?\bsqs-video-wrapper\b[^>]*>',
lambda x: unescapeHTML(x.group(0)), webpage)
# it's tempting to parse this further, but you would
# have to take into account all the variations like
# Video Title - Site Name
# Site Name | Video Title
# Video Title - Tagline | Site Name
# and so on and so forth; it's just not practical
video_title = self._og_search_title(
webpage, default=None) or self._html_search_regex(
r'(?s)<title>(.*?)</title>', webpage, 'video title',
default='video')
# Try to detect age limit automatically
age_limit = self._rta_search(webpage)
# And then there are the jokers who advertise that they use RTA,
# but actually don't.
AGE_LIMIT_MARKERS = [
r'Proudly Labeled <a href="http://www\.rtalabel\.org/" title="Restricted to Adults">RTA</a>',
]
if any(re.search(marker, webpage) for marker in AGE_LIMIT_MARKERS):
age_limit = 18
# video uploader is domain name
video_uploader = self._search_regex(
r'^(?:https?://)?([^/]*)/.*', url, 'video uploader')
video_description = self._og_search_description(webpage, default=None)
video_thumbnail = self._og_search_thumbnail(webpage, default=None)
info_dict.update({
'title': video_title,
'description': video_description,
'thumbnail': video_thumbnail,
'age_limit': age_limit,
})
# Look for Brightcove Legacy Studio embeds
bc_urls = BrightcoveLegacyIE._extract_brightcove_urls(webpage)
if bc_urls:
entries = [{
'_type': 'url',
'url': smuggle_url(bc_url, {'Referer': url}),
'ie_key': 'BrightcoveLegacy'
} for bc_url in bc_urls]
return {
'_type': 'playlist',
'title': video_title,
'id': video_id,
'entries': entries,
}
# Look for Brightcove New Studio embeds
bc_urls = BrightcoveNewIE._extract_urls(self, webpage)
if bc_urls:
return self.playlist_from_matches(
bc_urls, video_id, video_title,
getter=lambda x: smuggle_url(x, {'referrer': url}),
ie='BrightcoveNew')
# Look for Nexx embeds
nexx_urls = NexxIE._extract_urls(webpage)
if nexx_urls:
return self.playlist_from_matches(nexx_urls, video_id, video_title, ie=NexxIE.ie_key())
# Look for Nexx iFrame embeds
nexx_embed_urls = NexxEmbedIE._extract_urls(webpage)
if nexx_embed_urls:
return self.playlist_from_matches(nexx_embed_urls, video_id, video_title, ie=NexxEmbedIE.ie_key())
# Look for ThePlatform embeds
tp_urls = ThePlatformIE._extract_urls(webpage)
if tp_urls:
return self.playlist_from_matches(tp_urls, video_id, video_title, ie='ThePlatform')
arc_urls = ArcPublishingIE._extract_urls(webpage)
if arc_urls:
return self.playlist_from_matches(arc_urls, video_id, video_title, ie=ArcPublishingIE.ie_key())
mychannels_urls = MedialaanIE._extract_urls(webpage)
if mychannels_urls:
return self.playlist_from_matches(
mychannels_urls, video_id, video_title, ie=MedialaanIE.ie_key())
# Look for embedded rtl.nl player
matches = re.findall(
r'<iframe[^>]+?src="((?:https?:)?//(?:(?:www|static)\.)?rtl\.nl/(?:system/videoplayer/[^"]+(?:video_)?)?embed[^"]+)"',
webpage)
if matches:
return self.playlist_from_matches(matches, video_id, video_title, ie='RtlNl')
vimeo_urls = VimeoIE._extract_urls(url, webpage)
if vimeo_urls:
return self.playlist_from_matches(vimeo_urls, video_id, video_title, ie=VimeoIE.ie_key())
vhx_url = VHXEmbedIE._extract_url(webpage)
if vhx_url:
return self.url_result(vhx_url, VHXEmbedIE.ie_key())
vid_me_embed_url = self._search_regex(
r'src=[\'"](https?://vid\.me/[^\'"]+)[\'"]',
webpage, 'vid.me embed', default=None)
if vid_me_embed_url is not None:
return self.url_result(vid_me_embed_url, 'Vidme')
# Invidious Instances
# https://github.com/yt-dlp/yt-dlp/issues/195
# https://github.com/iv-org/invidious/pull/1730
youtube_url = self._search_regex(
r'<link rel="alternate" href="(https://www\.youtube\.com/watch\?v=[0-9A-Za-z_-]{11})"',
webpage, 'youtube link', default=None)
if youtube_url:
return self.url_result(youtube_url, YoutubeIE.ie_key())
# Look for YouTube embeds
youtube_urls = YoutubeIE._extract_urls(webpage)
if youtube_urls:
return self.playlist_from_matches(
youtube_urls, video_id, video_title, ie=YoutubeIE.ie_key())
matches = DailymotionIE._extract_urls(webpage)
if matches:
return self.playlist_from_matches(matches, video_id, video_title)
# Look for embedded Dailymotion playlist player (#3822)
m = re.search(
r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?dailymotion\.[a-z]{2,3}/widget/jukebox\?.+?)\1', webpage)
if m:
playlists = re.findall(
r'list\[\]=/playlist/([^/]+)/', unescapeHTML(m.group('url')))
if playlists:
return self.playlist_from_matches(
playlists, video_id, video_title, lambda p: '//dailymotion.com/playlist/%s' % p)
# Look for DailyMail embeds
dailymail_urls = DailyMailIE._extract_urls(webpage)
if dailymail_urls:
return self.playlist_from_matches(
dailymail_urls, video_id, video_title, ie=DailyMailIE.ie_key())
# Look for Teachable embeds, must be before Wistia
teachable_url = TeachableIE._extract_url(webpage, url)
if teachable_url:
return self.url_result(teachable_url)
# Look for embedded Wistia player
wistia_urls = WistiaIE._extract_urls(webpage)
if wistia_urls:
playlist = self.playlist_from_matches(wistia_urls, video_id, video_title, ie=WistiaIE.ie_key())
for entry in playlist['entries']:
entry.update({
'_type': 'url_transparent',
'uploader': video_uploader,
})
return playlist
# Look for SVT player
svt_url = SVTIE._extract_url(webpage)
if svt_url:
return self.url_result(svt_url, 'SVT')
# Look for Bandcamp pages with custom domain
mobj = re.search(r'<meta property="og:url"[^>]*?content="(.*?bandcamp\.com.*?)"', webpage)
if mobj is not None:
burl = unescapeHTML(mobj.group(1))
# Don't set the extractor because it can be a track url or an album
return self.url_result(burl)
# Look for embedded Vevo player
mobj = re.search(
r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:cache\.)?vevo\.com/.+?)\1', webpage)
if mobj is not None:
return self.url_result(mobj.group('url'))
# Look for embedded Viddler player
mobj = re.search(
r'<(?:iframe[^>]+?src|param[^>]+?value)=(["\'])(?P<url>(?:https?:)?//(?:www\.)?viddler\.com/(?:embed|player)/.+?)\1',
webpage)
if mobj is not None:
return self.url_result(mobj.group('url'))
# Look for NYTimes player
mobj = re.search(
r'<iframe[^>]+src=(["\'])(?P<url>(?:https?:)?//graphics8\.nytimes\.com/bcvideo/[^/]+/iframe/embed\.html.+?)\1>',
webpage)
if mobj is not None:
return self.url_result(mobj.group('url'))
# Look for Libsyn player
mobj = re.search(
r'<iframe[^>]+src=(["\'])(?P<url>(?:https?:)?//html5-player\.libsyn\.com/embed/.+?)\1', webpage)
if mobj is not None:
return self.url_result(mobj.group('url'))
# Look for Ooyala videos
mobj = (re.search(r'player\.ooyala\.com/[^"?]+[?#][^"]*?(?:embedCode|ec)=(?P<ec>[^"&]+)', webpage)
or re.search(r'OO\.Player\.create\([\'"].*?[\'"],\s*[\'"](?P<ec>.{32})[\'"]', webpage)
or re.search(r'OO\.Player\.create\.apply\(\s*OO\.Player\s*,\s*op\(\s*\[\s*[\'"][^\'"]*[\'"]\s*,\s*[\'"](?P<ec>.{32})[\'"]', webpage)
or re.search(r'SBN\.VideoLinkset\.ooyala\([\'"](?P<ec>.{32})[\'"]\)', webpage)
or re.search(r'data-ooyala-video-id\s*=\s*[\'"](?P<ec>.{32})[\'"]', webpage))
if mobj is not None:
embed_token = self._search_regex(
r'embedToken[\'"]?\s*:\s*[\'"]([^\'"]+)',
webpage, 'ooyala embed token', default=None)
return OoyalaIE._build_url_result(smuggle_url(
mobj.group('ec'), {
'domain': url,
'embed_token': embed_token,
}))
# Look for multiple Ooyala embeds on SBN network websites
mobj = re.search(r'SBN\.VideoLinkset\.entryGroup\((\[.*?\])', webpage)
if mobj is not None:
embeds = self._parse_json(mobj.group(1), video_id, fatal=False)
if embeds:
return self.playlist_from_matches(
embeds, video_id, video_title,
getter=lambda v: OoyalaIE._url_for_embed_code(smuggle_url(v['provider_video_id'], {'domain': url})), ie='Ooyala')
# Look for Aparat videos
mobj = re.search(r'<iframe .*?src="(http://www\.aparat\.com/video/[^"]+)"', webpage)
if mobj is not None:
return self.url_result(mobj.group(1), 'Aparat')
# Look for MPORA videos
mobj = re.search(r'<iframe .*?src="(http://mpora\.(?:com|de)/videos/[^"]+)"', webpage)
if mobj is not None:
return self.url_result(mobj.group(1), 'Mpora')
# Look for embedded Facebook player
facebook_urls = FacebookIE._extract_urls(webpage)
if facebook_urls:
return self.playlist_from_matches(facebook_urls, video_id, video_title)
# Look for embedded VK player
mobj = re.search(r'<iframe[^>]+?src=(["\'])(?P<url>https?://vk\.com/video_ext\.php.+?)\1', webpage)
if mobj is not None:
return self.url_result(mobj.group('url'), 'VK')
# Look for embedded Odnoklassniki player
odnoklassniki_url = OdnoklassnikiIE._extract_url(webpage)
if odnoklassniki_url:
return self.url_result(odnoklassniki_url, OdnoklassnikiIE.ie_key())
# Look for embedded ivi player
mobj = re.search(r'<embed[^>]+?src=(["\'])(?P<url>https?://(?:www\.)?ivi\.ru/video/player.+?)\1', webpage)
if mobj is not None:
return self.url_result(mobj.group('url'), 'Ivi')
# Look for embedded Huffington Post player
mobj = re.search(
r'<iframe[^>]+?src=(["\'])(?P<url>https?://embed\.live\.huffingtonpost\.com/.+?)\1', webpage)
if mobj is not None:
return self.url_result(mobj.group('url'), 'HuffPost')
# Look for embed.ly
mobj = re.search(r'class=["\']embedly-card["\'][^>]href=["\'](?P<url>[^"\']+)', webpage)
if mobj is not None:
return self.url_result(mobj.group('url'))
mobj = re.search(r'class=["\']embedly-embed["\'][^>]src=["\'][^"\']*url=(?P<url>[^&]+)', webpage)
if mobj is not None:
return self.url_result(compat_urllib_parse_unquote(mobj.group('url')))
# Look for funnyordie embed
matches = re.findall(r'<iframe[^>]+?src="(https?://(?:www\.)?funnyordie\.com/embed/[^"]+)"', webpage)
if matches:
return self.playlist_from_matches(
matches, video_id, video_title, getter=unescapeHTML, ie='FunnyOrDie')
# Look for Simplecast embeds
simplecast_urls = SimplecastIE._extract_urls(webpage)
if simplecast_urls:
return self.playlist_from_matches(
simplecast_urls, video_id, video_title)
# Look for BBC iPlayer embed
matches = re.findall(r'setPlaylist\("(https?://www\.bbc\.co\.uk/iplayer/[^/]+/[\da-z]{8})"\)', webpage)
if matches:
return self.playlist_from_matches(matches, video_id, video_title, ie='BBCCoUk')
# Look for embedded RUTV player
rutv_url = RUTVIE._extract_url(webpage)
if rutv_url:
return self.url_result(rutv_url, 'RUTV')
# Look for embedded TVC player
tvc_url = TVCIE._extract_url(webpage)
if tvc_url:
return self.url_result(tvc_url, 'TVC')
# Look for embedded SportBox player
sportbox_urls = SportBoxIE._extract_urls(webpage)
if sportbox_urls:
return self.playlist_from_matches(sportbox_urls, video_id, video_title, ie=SportBoxIE.ie_key())
# Look for embedded XHamster player
xhamster_urls = XHamsterEmbedIE._extract_urls(webpage)
if xhamster_urls:
return self.playlist_from_matches(xhamster_urls, video_id, video_title, ie='XHamsterEmbed')
# Look for embedded TNAFlixNetwork player
tnaflix_urls = TNAFlixNetworkEmbedIE._extract_urls(webpage)
if tnaflix_urls:
return self.playlist_from_matches(tnaflix_urls, video_id, video_title, ie=TNAFlixNetworkEmbedIE.ie_key())
# Look for embedded PornHub player
pornhub_urls = PornHubIE._extract_urls(webpage)
if pornhub_urls:
return self.playlist_from_matches(pornhub_urls, video_id, video_title, ie=PornHubIE.ie_key())
# Look for embedded DrTuber player
drtuber_urls = DrTuberIE._extract_urls(webpage)
if drtuber_urls:
return self.playlist_from_matches(drtuber_urls, video_id, video_title, ie=DrTuberIE.ie_key())
# Look for embedded RedTube player
redtube_urls = RedTubeIE._extract_urls(webpage)
if redtube_urls:
return self.playlist_from_matches(redtube_urls, video_id, video_title, ie=RedTubeIE.ie_key())
# Look for embedded Tube8 player
tube8_urls = Tube8IE._extract_urls(webpage)
if tube8_urls:
return self.playlist_from_matches(tube8_urls, video_id, video_title, ie=Tube8IE.ie_key())
# Look for embedded Mofosex player
mofosex_urls = MofosexEmbedIE._extract_urls(webpage)
if mofosex_urls:
return self.playlist_from_matches(mofosex_urls, video_id, video_title, ie=MofosexEmbedIE.ie_key())
# Look for embedded Spankwire player
spankwire_urls = SpankwireIE._extract_urls(webpage)
if spankwire_urls:
return self.playlist_from_matches(spankwire_urls, video_id, video_title, ie=SpankwireIE.ie_key())
# Look for embedded YouPorn player
youporn_urls = YouPornIE._extract_urls(webpage)
if youporn_urls:
return self.playlist_from_matches(youporn_urls, video_id, video_title, ie=YouPornIE.ie_key())
# Look for embedded Tvigle player
mobj = re.search(
r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//cloud\.tvigle\.ru/video/.+?)\1', webpage)
if mobj is not None:
return self.url_result(mobj.group('url'), 'Tvigle')
# Look for embedded TED player
mobj = re.search(
r'<iframe[^>]+?src=(["\'])(?P<url>https?://embed(?:-ssl)?\.ted\.com/.+?)\1', webpage)
if mobj is not None:
return self.url_result(mobj.group('url'), 'TED')
# Look for embedded Ustream videos
ustream_url = UstreamIE._extract_url(webpage)
if ustream_url:
return self.url_result(ustream_url, UstreamIE.ie_key())
# Look for embedded arte.tv player
arte_urls = ArteTVEmbedIE._extract_urls(webpage)
if arte_urls:
return self.playlist_from_matches(arte_urls, video_id, video_title)
# Look for embedded francetv player
mobj = re.search(
r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?://)?embed\.francetv\.fr/\?ue=.+?)\1',
webpage)
if mobj is not None:
return self.url_result(mobj.group('url'))
# Look for embedded Myvi.ru player
myvi_url = MyviIE._extract_url(webpage)
if myvi_url:
return self.url_result(myvi_url)
# Look for embedded soundcloud player
soundcloud_urls = SoundcloudEmbedIE._extract_urls(webpage)
if soundcloud_urls:
return self.playlist_from_matches(soundcloud_urls, video_id, video_title, getter=unescapeHTML)
# Look for tunein player
tunein_urls = TuneInBaseIE._extract_urls(webpage)
if tunein_urls:
return self.playlist_from_matches(tunein_urls, video_id, video_title)
# Look for embedded mtvservices player
mtvservices_url = MTVServicesEmbeddedIE._extract_url(webpage)
if mtvservices_url:
return self.url_result(mtvservices_url, ie='MTVServicesEmbedded')
# Look for embedded yahoo player
mobj = re.search(
r'<iframe[^>]+?src=(["\'])(?P<url>https?://(?:screen|movies)\.yahoo\.com/.+?\.html\?format=embed)\1',
webpage)
if mobj is not None:
return self.url_result(mobj.group('url'), 'Yahoo')
# Look for embedded sbs.com.au player
mobj = re.search(
r'''(?x)
(?:
<meta\s+property="og:video"\s+content=|
<iframe[^>]+?src=
)
(["\'])(?P<url>https?://(?:www\.)?sbs\.com\.au/ondemand/video/.+?)\1''',
webpage)
if mobj is not None:
return self.url_result(mobj.group('url'), 'SBS')
# Look for embedded Cinchcast player
mobj = re.search(
r'<iframe[^>]+?src=(["\'])(?P<url>https?://player\.cinchcast\.com/.+?)\1',
webpage)
if mobj is not None:
return self.url_result(mobj.group('url'), 'Cinchcast')
mobj = re.search(
r'<iframe[^>]+?src=(["\'])(?P<url>https?://m(?:lb)?\.mlb\.com/shared/video/embed/embed\.html\?.+?)\1',
webpage)
if not mobj:
mobj = re.search(
r'data-video-link=["\'](?P<url>http://m\.mlb\.com/video/[^"\']+)',
webpage)
if mobj is not None:
return self.url_result(mobj.group('url'), 'MLB')
mobj = re.search(
r'<(?:iframe|script)[^>]+?src=(["\'])(?P<url>%s)\1' % CondeNastIE.EMBED_URL,
webpage)
if mobj is not None:
return self.url_result(self._proto_relative_url(mobj.group('url'), scheme='http:'), 'CondeNast')
mobj = re.search(
r'<iframe[^>]+src="(?P<url>https?://(?:new\.)?livestream\.com/[^"]+/player[^"]+)"',
webpage)
if mobj is not None:
return self.url_result(mobj.group('url'), 'Livestream')
# Look for Zapiks embed
mobj = re.search(
r'<iframe[^>]+src="(?P<url>https?://(?:www\.)?zapiks\.fr/index\.php\?.+?)"', webpage)
if mobj is not None:
return self.url_result(mobj.group('url'), 'Zapiks')
# Look for Kaltura embeds
kaltura_urls = KalturaIE._extract_urls(webpage)
if kaltura_urls:
return self.playlist_from_matches(
kaltura_urls, video_id, video_title,
getter=lambda x: smuggle_url(x, {'source_url': url}),
ie=KalturaIE.ie_key())
# Look for EaglePlatform embeds
eagleplatform_url = EaglePlatformIE._extract_url(webpage)
if eagleplatform_url:
return self.url_result(smuggle_url(eagleplatform_url, {'referrer': url}), EaglePlatformIE.ie_key())
# Look for ClipYou (uses EaglePlatform) embeds
mobj = re.search(
r'<iframe[^>]+src="https?://(?P<host>media\.clipyou\.ru)/index/player\?.*\brecord_id=(?P<id>\d+).*"', webpage)
if mobj is not None:
return self.url_result('eagleplatform:%(host)s:%(id)s' % mobj.groupdict(), 'EaglePlatform')
# Look for Pladform embeds
pladform_url = PladformIE._extract_url(webpage)
if pladform_url:
return self.url_result(pladform_url)
# Look for Videomore embeds
videomore_url = VideomoreIE._extract_url(webpage)
if videomore_url:
return self.url_result(videomore_url)
# Look for Webcaster embeds
webcaster_url = WebcasterFeedIE._extract_url(self, webpage)
if webcaster_url:
return self.url_result(webcaster_url, ie=WebcasterFeedIE.ie_key())
# Look for Playwire embeds
mobj = re.search(
r'<script[^>]+data-config=(["\'])(?P<url>(?:https?:)?//config\.playwire\.com/.+?)\1', webpage)
if mobj is not None:
return self.url_result(mobj.group('url'))
# Look for 5min embeds
mobj = re.search(
r'<meta[^>]+property="og:video"[^>]+content="https?://embed\.5min\.com/(?P<id>[0-9]+)/?', webpage)
if mobj is not None:
return self.url_result('5min:%s' % mobj.group('id'), 'FiveMin')
# Look for Crooks and Liars embeds
mobj = re.search(
r'<(?:iframe[^>]+src|param[^>]+value)=(["\'])(?P<url>(?:https?:)?//embed\.crooksandliars\.com/(?:embed|v)/.+?)\1', webpage)
if mobj is not None:
return self.url_result(mobj.group('url'))
# Look for NBC Sports VPlayer embeds
nbc_sports_url = NBCSportsVPlayerIE._extract_url(webpage)
if nbc_sports_url:
return self.url_result(nbc_sports_url, 'NBCSportsVPlayer')
# Look for NBC News embeds
nbc_news_embed_url = re.search(
r'<iframe[^>]+src=(["\'])(?P<url>(?:https?:)?//www\.nbcnews\.com/widget/video-embed/[^"\']+)\1', webpage)
if nbc_news_embed_url:
return self.url_result(nbc_news_embed_url.group('url'), 'NBCNews')
# Look for Google Drive embeds
google_drive_url = GoogleDriveIE._extract_url(webpage)
if google_drive_url:
return self.url_result(google_drive_url, 'GoogleDrive')
# Look for UDN embeds
mobj = re.search(
r'<iframe[^>]+src="(?:https?:)?(?P<url>%s)"' % UDNEmbedIE._PROTOCOL_RELATIVE_VALID_URL, webpage)
if mobj is not None:
return self.url_result(
compat_urlparse.urljoin(url, mobj.group('url')), 'UDNEmbed')
# Look for Senate ISVP iframe
senate_isvp_url = SenateISVPIE._search_iframe_url(webpage)
if senate_isvp_url:
return self.url_result(senate_isvp_url, 'SenateISVP')
# Look for Kinja embeds
kinja_embed_urls = KinjaEmbedIE._extract_urls(webpage, url)
if kinja_embed_urls:
return self.playlist_from_matches(
kinja_embed_urls, video_id, video_title)
# Look for OnionStudios embeds
onionstudios_url = OnionStudiosIE._extract_url(webpage)
if onionstudios_url:
return self.url_result(onionstudios_url)
# Look for ViewLift embeds
viewlift_url = ViewLiftEmbedIE._extract_url(webpage)
if viewlift_url:
return self.url_result(viewlift_url)
# Look for JWPlatform embeds
jwplatform_urls = JWPlatformIE._extract_urls(webpage)
if jwplatform_urls:
return self.playlist_from_matches(jwplatform_urls, video_id, video_title, ie=JWPlatformIE.ie_key())
# Look for Digiteka embeds
digiteka_url = DigitekaIE._extract_url(webpage)
if digiteka_url:
return self.url_result(self._proto_relative_url(digiteka_url), DigitekaIE.ie_key())
# Look for Arkena embeds
arkena_url = ArkenaIE._extract_url(webpage)
if arkena_url:
return self.url_result(arkena_url, ArkenaIE.ie_key())
# Look for Piksel embeds
piksel_url = PikselIE._extract_url(webpage)
if piksel_url:
return self.url_result(piksel_url, PikselIE.ie_key())
# Look for Limelight embeds
limelight_urls = LimelightBaseIE._extract_urls(webpage, url)
if limelight_urls:
return self.playlist_result(
limelight_urls, video_id, video_title, video_description)
# Look for Anvato embeds
anvato_urls = AnvatoIE._extract_urls(self, webpage, video_id)
if anvato_urls:
return self.playlist_result(
anvato_urls, video_id, video_title, video_description)
# Look for AdobeTVVideo embeds
mobj = re.search(
r'<iframe[^>]+src=[\'"]((?:https?:)?//video\.tv\.adobe\.com/v/\d+[^"]+)[\'"]',
webpage)
if mobj is not None:
return self.url_result(
self._proto_relative_url(unescapeHTML(mobj.group(1))),
'AdobeTVVideo')
# Look for Vine embeds
mobj = re.search(
r'<iframe[^>]+src=[\'"]((?:https?:)?//(?:www\.)?vine\.co/v/[^/]+/embed/(?:simple|postcard))',
webpage)
if mobj is not None:
return self.url_result(
self._proto_relative_url(unescapeHTML(mobj.group(1))), 'Vine')
# Look for VODPlatform embeds
mobj = re.search(
r'<iframe[^>]+src=(["\'])(?P<url>(?:https?:)?//(?:(?:www\.)?vod-platform\.net|embed\.kwikmotion\.com)/[eE]mbed/.+?)\1',
webpage)
if mobj is not None:
return self.url_result(
self._proto_relative_url(unescapeHTML(mobj.group('url'))), 'VODPlatform')
# Look for Mangomolo embeds
mobj = re.search(
r'''(?x)<iframe[^>]+src=(["\'])(?P<url>(?:https?:)?//
(?:
admin\.mangomolo\.com/analytics/index\.php/customers/embed|
player\.mangomolo\.com/v1
)/
(?:
video\?.*?\bid=(?P<video_id>\d+)|
(?:index|live)\?.*?\bchannelid=(?P<channel_id>(?:[A-Za-z0-9+/=]|%2B|%2F|%3D)+)
).+?)\1''', webpage)
if mobj is not None:
info = {
'_type': 'url_transparent',
'url': self._proto_relative_url(unescapeHTML(mobj.group('url'))),
'title': video_title,
'description': video_description,
'thumbnail': video_thumbnail,
'uploader': video_uploader,
}
video_id = mobj.group('video_id')
if video_id:
info.update({
'ie_key': 'MangomoloVideo',
'id': video_id,
})
else:
info.update({
'ie_key': 'MangomoloLive',
'id': mobj.group('channel_id'),
})
return info
# Look for Instagram embeds
instagram_embed_url = InstagramIE._extract_embed_url(webpage)
if instagram_embed_url is not None:
return self.url_result(
self._proto_relative_url(instagram_embed_url), InstagramIE.ie_key())
# Look for LiveLeak embeds
liveleak_urls = LiveLeakIE._extract_urls(webpage)
if liveleak_urls:
return self.playlist_from_matches(liveleak_urls, video_id, video_title)
# Look for 3Q SDN embeds
threeqsdn_url = ThreeQSDNIE._extract_url(webpage)
if threeqsdn_url:
return {
'_type': 'url_transparent',
'ie_key': ThreeQSDNIE.ie_key(),
'url': self._proto_relative_url(threeqsdn_url),
'title': video_title,
'description': video_description,
'thumbnail': video_thumbnail,
'uploader': video_uploader,
}
# Look for VBOX7 embeds
vbox7_url = Vbox7IE._extract_url(webpage)
if vbox7_url:
return self.url_result(vbox7_url, Vbox7IE.ie_key())
# Look for DBTV embeds
dbtv_urls = DBTVIE._extract_urls(webpage)
if dbtv_urls:
return self.playlist_from_matches(dbtv_urls, video_id, video_title, ie=DBTVIE.ie_key())
# Look for Videa embeds
videa_urls = VideaIE._extract_urls(webpage)
if videa_urls:
return self.playlist_from_matches(videa_urls, video_id, video_title, ie=VideaIE.ie_key())
# Look for 20 minuten embeds
twentymin_urls = TwentyMinutenIE._extract_urls(webpage)
if twentymin_urls:
return self.playlist_from_matches(
twentymin_urls, video_id, video_title, ie=TwentyMinutenIE.ie_key())
# Look for VideoPress embeds
videopress_urls = VideoPressIE._extract_urls(webpage)
if videopress_urls:
return self.playlist_from_matches(
videopress_urls, video_id, video_title, ie=VideoPressIE.ie_key())
# Look for Rutube embeds
rutube_urls = RutubeIE._extract_urls(webpage)
if rutube_urls:
return self.playlist_from_matches(
rutube_urls, video_id, video_title, ie=RutubeIE.ie_key())
# Look for WashingtonPost embeds
wapo_urls = WashingtonPostIE._extract_urls(webpage)
if wapo_urls:
return self.playlist_from_matches(
wapo_urls, video_id, video_title, ie=WashingtonPostIE.ie_key())
# Look for Mediaset embeds
mediaset_urls = MediasetIE._extract_urls(self, webpage)
if mediaset_urls:
return self.playlist_from_matches(
mediaset_urls, video_id, video_title, ie=MediasetIE.ie_key())
# Look for JOJ.sk embeds
joj_urls = JojIE._extract_urls(webpage)
if joj_urls:
return self.playlist_from_matches(
joj_urls, video_id, video_title, ie=JojIE.ie_key())
# Look for megaphone.fm embeds
mpfn_urls = MegaphoneIE._extract_urls(webpage)
if mpfn_urls:
return self.playlist_from_matches(
mpfn_urls, video_id, video_title, ie=MegaphoneIE.ie_key())
# Look for vzaar embeds
vzaar_urls = VzaarIE._extract_urls(webpage)
if vzaar_urls:
return self.playlist_from_matches(
vzaar_urls, video_id, video_title, ie=VzaarIE.ie_key())
channel9_urls = Channel9IE._extract_urls(webpage)
if channel9_urls:
return self.playlist_from_matches(
channel9_urls, video_id, video_title, ie=Channel9IE.ie_key())
vshare_urls = VShareIE._extract_urls(webpage)
if vshare_urls:
return self.playlist_from_matches(
vshare_urls, video_id, video_title, ie=VShareIE.ie_key())
# Look for Mediasite embeds
mediasite_urls = MediasiteIE._extract_urls(webpage)
if mediasite_urls:
entries = [
self.url_result(smuggle_url(
compat_urlparse.urljoin(url, mediasite_url),
{'UrlReferrer': url}), ie=MediasiteIE.ie_key())
for mediasite_url in mediasite_urls]
return self.playlist_result(entries, video_id, video_title)
springboardplatform_urls = SpringboardPlatformIE._extract_urls(webpage)
if springboardplatform_urls:
return self.playlist_from_matches(
springboardplatform_urls, video_id, video_title,
ie=SpringboardPlatformIE.ie_key())
yapfiles_urls = YapFilesIE._extract_urls(webpage)
if yapfiles_urls:
return self.playlist_from_matches(
yapfiles_urls, video_id, video_title, ie=YapFilesIE.ie_key())
vice_urls = ViceIE._extract_urls(webpage)
if vice_urls:
return self.playlist_from_matches(
vice_urls, video_id, video_title, ie=ViceIE.ie_key())
xfileshare_urls = XFileShareIE._extract_urls(webpage)
if xfileshare_urls:
return self.playlist_from_matches(
xfileshare_urls, video_id, video_title, ie=XFileShareIE.ie_key())
cloudflarestream_urls = CloudflareStreamIE._extract_urls(webpage)
if cloudflarestream_urls:
return self.playlist_from_matches(
cloudflarestream_urls, video_id, video_title, ie=CloudflareStreamIE.ie_key())
peertube_urls = PeerTubeIE._extract_urls(webpage, url)
if peertube_urls:
return self.playlist_from_matches(
peertube_urls, video_id, video_title, ie=PeerTubeIE.ie_key())
indavideo_urls = IndavideoEmbedIE._extract_urls(webpage)
if indavideo_urls:
return self.playlist_from_matches(
indavideo_urls, video_id, video_title, ie=IndavideoEmbedIE.ie_key())
apa_urls = APAIE._extract_urls(webpage)
if apa_urls:
return self.playlist_from_matches(
apa_urls, video_id, video_title, ie=APAIE.ie_key())
foxnews_urls = FoxNewsIE._extract_urls(webpage)
if foxnews_urls:
return self.playlist_from_matches(
foxnews_urls, video_id, video_title, ie=FoxNewsIE.ie_key())
sharevideos_urls = [sharevideos_mobj.group('url') for sharevideos_mobj in re.finditer(
r'<iframe[^>]+?\bsrc\s*=\s*(["\'])(?P<url>(?:https?:)?//embed\.share-videos\.se/auto/embed/\d+\?.*?\buid=\d+.*?)\1',
webpage)]
if sharevideos_urls:
return self.playlist_from_matches(
sharevideos_urls, video_id, video_title)
viqeo_urls = ViqeoIE._extract_urls(webpage)
if viqeo_urls:
return self.playlist_from_matches(
viqeo_urls, video_id, video_title, ie=ViqeoIE.ie_key())
expressen_urls = ExpressenIE._extract_urls(webpage)
if expressen_urls:
return self.playlist_from_matches(
expressen_urls, video_id, video_title, ie=ExpressenIE.ie_key())
zype_urls = ZypeIE._extract_urls(webpage)
if zype_urls:
return self.playlist_from_matches(
zype_urls, video_id, video_title, ie=ZypeIE.ie_key())
gedi_urls = GediDigitalIE._extract_urls(webpage)
if gedi_urls:
return self.playlist_from_matches(
gedi_urls, video_id, video_title, ie=GediDigitalIE.ie_key())
# Look for RCS media group embeds
rcs_urls = RCSEmbedsIE._extract_urls(webpage)
if rcs_urls:
return self.playlist_from_matches(
rcs_urls, video_id, video_title, ie=RCSEmbedsIE.ie_key())
wimtv_urls = WimTVIE._extract_urls(webpage)
if wimtv_urls:
return self.playlist_from_matches(
wimtv_urls, video_id, video_title, ie=WimTVIE.ie_key())
bitchute_urls = BitChuteIE._extract_urls(webpage)
if bitchute_urls:
return self.playlist_from_matches(
bitchute_urls, video_id, video_title, ie=BitChuteIE.ie_key())
rumble_urls = RumbleEmbedIE._extract_urls(webpage)
if len(rumble_urls) == 1:
return self.url_result(rumble_urls[0], RumbleEmbedIE.ie_key())
if rumble_urls:
return self.playlist_from_matches(
rumble_urls, video_id, video_title, ie=RumbleEmbedIE.ie_key())
# Look for HTML5 media
entries = self._parse_html5_media_entries(url, webpage, video_id, m3u8_id='hls')
if entries:
if len(entries) == 1:
entries[0].update({
'id': video_id,
'title': video_title,
})
else:
for num, entry in enumerate(entries, start=1):
entry.update({
'id': '%s-%s' % (video_id, num),
'title': '%s (%d)' % (video_title, num),
})
for entry in entries:
self._sort_formats(entry['formats'])
return self.playlist_result(entries, video_id, video_title)
jwplayer_data = self._find_jwplayer_data(
webpage, video_id, transform_source=js_to_json)
if jwplayer_data:
try:
info = self._parse_jwplayer_data(
jwplayer_data, video_id, require_title=False, base_url=url)
return merge_dicts(info, info_dict)
except ExtractorError:
# See https://github.com/ytdl-org/youtube-dl/pull/16735
pass
# Video.js embed
mobj = re.search(
r'(?s)\bvideojs\s*\(.+?\.src\s*\(\s*((?:\[.+?\]|{.+?}))\s*\)\s*;',
webpage)
if mobj is not None:
sources = self._parse_json(
mobj.group(1), video_id, transform_source=js_to_json,
fatal=False) or []
if not isinstance(sources, list):
sources = [sources]
formats = []
for source in sources:
src = source.get('src')
if not src or not isinstance(src, compat_str):
continue
src = compat_urlparse.urljoin(url, src)
src_type = source.get('type')
if isinstance(src_type, compat_str):
src_type = src_type.lower()
ext = determine_ext(src).lower()
if src_type == 'video/youtube':
return self.url_result(src, YoutubeIE.ie_key())
if src_type == 'application/dash+xml' or ext == 'mpd':
formats.extend(self._extract_mpd_formats(
src, video_id, mpd_id='dash', fatal=False))
elif src_type == 'application/x-mpegurl' or ext == 'm3u8':
formats.extend(self._extract_m3u8_formats(
src, video_id, 'mp4', entry_protocol='m3u8_native',
m3u8_id='hls', fatal=False))
else:
formats.append({
'url': src,
'ext': (mimetype2ext(src_type)
or ext if ext in KNOWN_EXTENSIONS else 'mp4'),
})
if formats:
self._sort_formats(formats)
info_dict['formats'] = formats
return info_dict
# Looking for http://schema.org/VideoObject
json_ld = self._search_json_ld(
webpage, video_id, default={}, expected_type='VideoObject')
if json_ld.get('url'):
return merge_dicts(json_ld, info_dict)
def check_video(vurl):
if YoutubeIE.suitable(vurl):
return True
if RtmpIE.suitable(vurl):
return True
vpath = compat_urlparse.urlparse(vurl).path
vext = determine_ext(vpath)
return '.' in vpath and vext not in ('swf', 'png', 'jpg', 'srt', 'sbv', 'sub', 'vtt', 'ttml', 'js', 'xml')
def filter_video(urls):
return list(filter(check_video, urls))
# Start with something easy: JW Player in SWFObject
found = filter_video(re.findall(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage))
if not found:
# Look for gorilla-vid style embedding
found = filter_video(re.findall(r'''(?sx)
(?:
jw_plugins|
JWPlayerOptions|
jwplayer\s*\(\s*["'][^'"]+["']\s*\)\s*\.setup
)
.*?
['"]?file['"]?\s*:\s*["\'](.*?)["\']''', webpage))
if not found:
# Broaden the search a little bit
found = filter_video(re.findall(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage))
if not found:
# Broaden the findall a little bit: JWPlayer JS loader
found = filter_video(re.findall(
r'[^A-Za-z0-9]?(?:file|video_url)["\']?:\s*["\'](http(?![^\'"]+\.[0-9]+[\'"])[^\'"]+)["\']', webpage))
if not found:
# Flow player
found = filter_video(re.findall(r'''(?xs)
flowplayer\("[^"]+",\s*
\{[^}]+?\}\s*,
\s*\{[^}]+? ["']?clip["']?\s*:\s*\{\s*
["']?url["']?\s*:\s*["']([^"']+)["']
''', webpage))
if not found:
# Cinerama player
found = re.findall(
r"cinerama\.embedPlayer\(\s*\'[^']+\',\s*'([^']+)'", webpage)
if not found:
# Try to find twitter cards info
# twitter:player:stream should be checked before twitter:player since
# it is expected to contain a raw stream (see
# https://dev.twitter.com/cards/types/player#On_twitter.com_via_desktop_browser)
found = filter_video(re.findall(
r'<meta (?:property|name)="twitter:player:stream" (?:content|value)="(.+?)"', webpage))
if not found:
# We look for Open Graph info:
# We have to match any number spaces between elements, some sites try to align them (eg.: statigr.am)
m_video_type = re.findall(r'<meta.*?property="og:video:type".*?content="video/(.*?)"', webpage)
# We only look in og:video if the MIME type is a video, don't try if it's a Flash player:
if m_video_type is not None:
found = filter_video(re.findall(r'<meta.*?property="og:video".*?content="(.*?)"', webpage))
if not found:
REDIRECT_REGEX = r'[0-9]{,2};\s*(?:URL|url)=\'?([^\'"]+)'
found = re.search(
r'(?i)<meta\s+(?=(?:[a-z-]+="[^"]+"\s+)*http-equiv="refresh")'
r'(?:[a-z-]+="[^"]+"\s+)*?content="%s' % REDIRECT_REGEX,
webpage)
if not found:
# Look also in Refresh HTTP header
refresh_header = head_response.headers.get('Refresh')
if refresh_header:
# In python 2 response HTTP headers are bytestrings
if sys.version_info < (3, 0) and isinstance(refresh_header, str):
refresh_header = refresh_header.decode('iso-8859-1')
found = re.search(REDIRECT_REGEX, refresh_header)
if found:
new_url = compat_urlparse.urljoin(url, unescapeHTML(found.group(1)))
if new_url != url:
self.report_following_redirect(new_url)
return {
'_type': 'url',
'url': new_url,
}
else:
found = None
if not found:
# twitter:player is a https URL to iframe player that may or may not
# be supported by yt-dlp thus this is checked the very last (see
# https://dev.twitter.com/cards/types/player#On_twitter.com_via_desktop_browser)
embed_url = self._html_search_meta('twitter:player', webpage, default=None)
if embed_url and embed_url != url:
return self.url_result(embed_url)
if not found:
raise UnsupportedError(url)
entries = []
for video_url in orderedSet(found):
video_url = unescapeHTML(video_url)
video_url = video_url.replace('\\/', '/')
video_url = compat_urlparse.urljoin(url, video_url)
video_id = compat_urllib_parse_unquote(os.path.basename(video_url))
# Sometimes, jwplayer extraction will result in a YouTube URL
if YoutubeIE.suitable(video_url):
entries.append(self.url_result(video_url, 'Youtube'))
continue
# here's a fun little line of code for you:
video_id = os.path.splitext(video_id)[0]
entry_info_dict = {
'id': video_id,
'uploader': video_uploader,
'title': video_title,
'age_limit': age_limit,
}
if RtmpIE.suitable(video_url):
entry_info_dict.update({
'_type': 'url_transparent',
'ie_key': RtmpIE.ie_key(),
'url': video_url,
})
entries.append(entry_info_dict)
continue
ext = determine_ext(video_url)
if ext == 'smil':
entry_info_dict['formats'] = self._extract_smil_formats(video_url, video_id)
elif ext == 'xspf':
return self.playlist_result(self._extract_xspf_playlist(video_url, video_id), video_id)
elif ext == 'm3u8':
entry_info_dict['formats'] = self._extract_m3u8_formats(video_url, video_id, ext='mp4')
elif ext == 'mpd':
entry_info_dict['formats'] = self._extract_mpd_formats(video_url, video_id)
elif ext == 'f4m':
entry_info_dict['formats'] = self._extract_f4m_formats(video_url, video_id)
elif re.search(r'(?i)\.(?:ism|smil)/manifest', video_url) and video_url != url:
# Just matching .ism/manifest is not enough to be reliably sure
# whether it's actually an ISM manifest or some other streaming
# manifest since there are various streaming URL formats
# possible (see [1]) as well as some other shenanigans like
# .smil/manifest URLs that actually serve an ISM (see [2]) and
# so on.
# Thus the most reasonable way to solve this is to delegate
# to generic extractor in order to look into the contents of
# the manifest itself.
# 1. https://azure.microsoft.com/en-us/documentation/articles/media-services-deliver-content-overview/#streaming-url-formats
# 2. https://svs.itworkscdn.net/lbcivod/smil:itwfcdn/lbci/170976.smil/Manifest
entry_info_dict = self.url_result(
smuggle_url(video_url, {'to_generic': True}),
GenericIE.ie_key())
else:
entry_info_dict['url'] = video_url
if entry_info_dict.get('formats'):
self._sort_formats(entry_info_dict['formats'])
entries.append(entry_info_dict)
if len(entries) == 1:
return entries[0]
else:
for num, e in enumerate(entries, start=1):
# 'url' results don't have a title
if e.get('title') is not None:
e['title'] = '%s (%d)' % (e['title'], num)
return {
'_type': 'playlist',
'entries': entries,
}
| yt_dlp/extractor/generic.py | 149,939 | Returns None if no camtasia video can be found.
Report information extraction.
coding: utf-8 Direct link to a video Direct link to media delivered compressed (until Accept-Encoding is *) Direct download with broken HEAD infinite live stream Direct link with incorrect MIME type RSS feed RSS feed with enclosure RSS feed with item with description and thumbnails RSS feed with enclosures and unsupported link URLs SMIL from http://videolectures.net/promogram_igor_mekjavic_eng SMIL from http://www1.wdr.de/mediathek/video/livestream/index.html SMIL from https://www.restudy.dk/video/play/id/1637 SMIL from http://adventure.howstuffworks.com/5266-cool-jobs-iditarod-musher-video.htm SMIL from http://new.livestream.com/CoheedandCambria/WebsterHall/videos/4719370 XSPF playlist from http://www.telegraaf.nl/tv/nieuws/binnenland/24353229/__Tikibad_ontruimd_wegens_brand__.html MPD from http://dash-mse-test.appspot.com/media.html m3u8 served with Content-Type: audio/x-mpegURL; charset=utf-8 m3u8 downloads m3u8 served with Content-Type: text/plain m3u8 downloads google redirect redirect in Refresh HTTP header bandcamp page with custom domain embedded brightcove video it also tests brightcove videos that need to set the 'Referer' in the http requests embedded with itemprop embedURL and video id spelled as `idVideo` https://github.com/ytdl-org/youtube-dl/issues/2253 https://github.com/ytdl-org/youtube-dl/issues/3541 m3u8 download Brightcove video in <iframe> Brightcove with alternative playerID key Brightcove with UUID in videoPlayer m3u8 download Brightcove:new type [2]. Alternative brightcove <video> attributes Brightcove with UUID in videoPlayer m3u8 download ooyala video that's what we get ooyala video embedded with http://player.ooyala.com/iframe.js ooyala video embedded with http://player.ooyala.com/static/v4/production/latest/core.min.js embed.ly video No need to test YoutubeIE here funnyordie embed HEAD requests lead to endless 301, while GET is OK RUTV embed m3u8 download TVC embed SportBox embed m3u8 download Myvi.ru embed XHamster embed This forum does not allow <iframe> syntaxes anymore Now HTML tags are displayed as-is Embedded TED video nowvideo embed hidden behind percent encoding arte embed francetv embed m3u8 downloads Condé Nast embed Dailymotion embed DailyMail embed YouTube embed MTVServices embed YouTube embed via <data-embed-url=""> YouTube <object> embed Camtasia studio Flowplayer Multiple brightcove videos https://github.com/ytdl-org/youtube-dl/issues/2283 MLB embed Wistia embed Wistia standard embed (async) Soundcloud embed Soundcloud multiple embeds TuneIn station embed Live stream Livestream embed Another Livestream embed, without 'new.' in URL Live stream LazyYT Cinchcast embed Cinerama player embedded viddler video Libsyn embed jwplayer YouTube jwplayer rtmp Complex jwplayer JWPlayer config passed as variable JWPlatform iframe Video.js embed, multiple formats Video.js embed, single format rtl.nl embed Zapiks embed Kaltura embed (different embed code) Kaltura embed with single quotes Kaltura embedded via quoted entry_id Kaltura embedded, some fileExt broken (11480) Kaltura iframe embed Kaltura iframe embed, more sophisticated meta twitter:player referrer protected EaglePlatform embed ClipYou (EaglePlatform) embed (custom URL) Not checking MD5 as sometimes the direct HTTP link results in 404 and HLS is used Pladform embed Playwire embed 5min embed m3u8 download Crooks and Liars embed Crooks and Liars external embed NBC Sports vplayer embed NBC News embed UDN embed m3u8 download Brightcove URL in single quotes Kinja embed SnagFilms embed AdobeTVVideo embed BrightcoveInPageEmbed embed Brightcove embed, with no valid 'renditions' but valid 'IOSRenditions' This video can't be played in browsers if Flash disabled and UA set to iPhone, which is actually a false alarm m3u8 downloads Brightcove embed with whitespace around attribute names Another form of arte.tv embed LiveLeak embed Another LiveLeak embed pattern (13336) Duplicated embedded video URLs twitter:player:stream embed m3u8 downloads twitter:player embed Facebook <iframe> embed Facebook <iframe> embed, plugin video Facebook API embed Wordpress "YouTube Video Importer" plugin video stored on custom kaltura server multiple kaltura embeds, nsfw Non-standard Vimeo embed generic vimeo embed that requires original URL passed as Referer DBTV embeds Videa embeds 20 minuten embed VideoPress embed Rutube embed ThePlatform embedded with whitespaces in URLs Senate ISVP iframe https Limelight embeds (1 channel embed + 4 media embeds) Limelight embed (LimelightPlayerUtil.embed) WashingtonPost embed Mediaset embed JOJ.sk embeds AMP embed (see https://www.ampproject.org/docs/reference/components/amp-video) vzaar embed multiple HTML5 videos on one page vshare embed CloudflareStream embed PeerTube embed Indavideo embed APA embed via JWPlatform embed Viqeo embeds Squarespace video embed, 2019-08-28 { Zype embed 'url': 'https://www.cookscountry.com/episode/554-smoky-barbecue-favorites', 'info_dict': { 'id': '5b400b834b32992a310622b9', 'ext': 'mp4', 'title': 'Smoky Barbecue Favorites', 'thumbnail': r're:^https?://.*\.jpe?g', 'description': 'md5:5ff01e76316bd8d46508af26dc86023b', 'upload_date': '20170909', 'timestamp': 1504915200, }, 'add_ie': [ZypeIE.ie_key()], 'params': { 'skip_download': True, }, }, videojs embed DailyMotion embed with DM.player { TODO: find another test http://schema.org/VideoObject 'url': 'https://flipagram.com/f/nyvTSJMKId', 'md5': '888dcf08b7ea671381f00fab74692755', 'info_dict': { 'id': 'nyvTSJMKId', 'ext': 'mp4', 'title': 'Flipagram by sjuria101 featuring Midnight Memories by One Direction', 'description': 'love for cats.', 'timestamp': 1461244995, 'upload_date': '20160421', }, 'params': { 'force_generic_extractor': True, }, }, VHX Embed ArcPublishing PoWa video player MyChannels SDK embed https://www.24kitchen.nl/populair/deskundige-dit-waarom-sommigen-gevoelig-zijn-voor-voedselallergieen Simplecast player embed WimTv embed player Check for redirect Check for direct link to a video Some webservers may serve compressed content of rather big size (e.g. gzipped flac) making it impossible to download only chunk of the file (yet we need only 512kB to test whether it's HTML or not). According to yt-dlp default Accept-Encoding that will always result in downloading the whole file that is not desirable. Therefore for extraction pass we have to override Accept-Encoding to any in order to accept raw bytes and being able to download only a chunk. It may probably better to solve this by checking Content-Type for application/octet-stream after HEAD request finishes, but not sure if we can rely on this. Is it an M3U playlist? Maybe it's a direct link to a video? Be careful not to download the whole thing! Is it an RSS feed, a SMIL file, an XSPF playlist or a MPD manifest? Is it a Camtasia project? Sometimes embedded video player is hidden behind percent encoding (e.g. https://github.com/ytdl-org/youtube-dl/issues/2448) Unescaping the whole page allows to handle those cases in a generic way FIXME: unescaping the whole page may break URLs, commenting out for now. There probably should be a second run of generic extractor on unescaped webpage. webpage = compat_urllib_parse_unquote(webpage) Unescape squarespace embeds to be detected by generic extractor, see https://github.com/ytdl-org/youtube-dl/issues/21294 it's tempting to parse this further, but you would have to take into account all the variations like Video Title - Site Name Site Name | Video Title Video Title - Tagline | Site Name and so on and so forth; it's just not practical Try to detect age limit automatically And then there are the jokers who advertise that they use RTA, but actually don't. video uploader is domain name Look for Brightcove Legacy Studio embeds Look for Brightcove New Studio embeds Look for Nexx embeds Look for Nexx iFrame embeds Look for ThePlatform embeds Look for embedded rtl.nl player Invidious Instances https://github.com/yt-dlp/yt-dlp/issues/195 https://github.com/iv-org/invidious/pull/1730 Look for YouTube embeds Look for embedded Dailymotion playlist player (3822) Look for DailyMail embeds Look for Teachable embeds, must be before Wistia Look for embedded Wistia player Look for SVT player Look for Bandcamp pages with custom domain Don't set the extractor because it can be a track url or an album Look for embedded Vevo player Look for embedded Viddler player Look for NYTimes player Look for Libsyn player Look for Ooyala videos Look for multiple Ooyala embeds on SBN network websites Look for Aparat videos Look for MPORA videos Look for embedded Facebook player Look for embedded VK player Look for embedded Odnoklassniki player Look for embedded ivi player Look for embedded Huffington Post player Look for embed.ly Look for funnyordie embed Look for Simplecast embeds Look for BBC iPlayer embed Look for embedded RUTV player Look for embedded TVC player Look for embedded SportBox player Look for embedded XHamster player Look for embedded TNAFlixNetwork player Look for embedded PornHub player Look for embedded DrTuber player Look for embedded RedTube player Look for embedded Tube8 player Look for embedded Mofosex player Look for embedded Spankwire player Look for embedded YouPorn player Look for embedded Tvigle player Look for embedded TED player Look for embedded Ustream videos Look for embedded arte.tv player Look for embedded francetv player Look for embedded Myvi.ru player Look for embedded soundcloud player Look for tunein player Look for embedded mtvservices player Look for embedded yahoo player Look for embedded sbs.com.au player Look for embedded Cinchcast player Look for Zapiks embed Look for Kaltura embeds Look for EaglePlatform embeds Look for ClipYou (uses EaglePlatform) embeds Look for Pladform embeds Look for Videomore embeds Look for Webcaster embeds Look for Playwire embeds Look for 5min embeds Look for Crooks and Liars embeds Look for NBC Sports VPlayer embeds Look for NBC News embeds Look for Google Drive embeds Look for UDN embeds Look for Senate ISVP iframe Look for Kinja embeds Look for OnionStudios embeds Look for ViewLift embeds Look for JWPlatform embeds Look for Digiteka embeds Look for Arkena embeds Look for Piksel embeds Look for Limelight embeds Look for Anvato embeds Look for AdobeTVVideo embeds Look for Vine embeds Look for VODPlatform embeds Look for Mangomolo embeds Look for Instagram embeds Look for LiveLeak embeds Look for 3Q SDN embeds Look for VBOX7 embeds Look for DBTV embeds Look for Videa embeds Look for 20 minuten embeds Look for VideoPress embeds Look for Rutube embeds Look for WashingtonPost embeds Look for Mediaset embeds Look for JOJ.sk embeds Look for megaphone.fm embeds Look for vzaar embeds Look for Mediasite embeds Look for RCS media group embeds Look for HTML5 media See https://github.com/ytdl-org/youtube-dl/pull/16735 Video.js embed Looking for http://schema.org/VideoObject Start with something easy: JW Player in SWFObject Look for gorilla-vid style embedding Broaden the search a little bit Broaden the findall a little bit: JWPlayer JS loader Flow player Cinerama player Try to find twitter cards info twitter:player:stream should be checked before twitter:player since it is expected to contain a raw stream (see https://dev.twitter.com/cards/types/playerOn_twitter.com_via_desktop_browser) We look for Open Graph info: We have to match any number spaces between elements, some sites try to align them (eg.: statigr.am) We only look in og:video if the MIME type is a video, don't try if it's a Flash player: Look also in Refresh HTTP header In python 2 response HTTP headers are bytestrings twitter:player is a https URL to iframe player that may or may not be supported by yt-dlp thus this is checked the very last (see https://dev.twitter.com/cards/types/playerOn_twitter.com_via_desktop_browser) Sometimes, jwplayer extraction will result in a YouTube URL here's a fun little line of code for you: Just matching .ism/manifest is not enough to be reliably sure whether it's actually an ISM manifest or some other streaming manifest since there are various streaming URL formats possible (see [1]) as well as some other shenanigans like .smil/manifest URLs that actually serve an ISM (see [2]) and so on. Thus the most reasonable way to solve this is to delegate to generic extractor in order to look into the contents of the manifest itself. 1. https://azure.microsoft.com/en-us/documentation/articles/media-services-deliver-content-overview/streaming-url-formats 2. https://svs.itworkscdn.net/lbcivod/smil:itwfcdn/lbci/170976.smil/Manifest 'url' results don't have a title | 12,854 | en | 0.780254 |
'''
Source code developed by DI2AG.
Thayer School of Engineering at Dartmouth College
Authors: Dr. Eugene Santos, Jr
Mr. Chase Yakaboski,
Mr. Gregory Hyde,
Dr. Keum Joo Kim
'''
import json
import argparse
import os
import sys
import pickle
import subprocess
from chp.query import Query
PASSED_JSON_FILE = '/home/cyakaboski/passed_message.json'
NODE = 'c-dell-m630-0-11'
SAVE_DIR = '/home/cyakaboski/temp'
BKB_PATHWAY_CORE_DIR = '/home/cyakaboski/src/python/projects/bkb-pathway-provider/core'
'''
PASSED_JSON_FILE = '/home/ncats/passed_message.json'
NODE = 'c-dell-m630-0-11'
SAVE_DIR = '/home/ncats/tmp'
BKB_PATHWAY_CORE_DIR = '/home/ncats/live/core'
'''
def processUiQuery(dict_):
query_dict = dict()
query_dict['name'] = dict_['name']
query_dict['evidence'] = dict_['genetic_evidence']
query_dict['targets'] = dict_['genetic_targets']
if dict_['demographic_evidence'] is not None:
query_dict['meta_evidence'] = [tuple(demo) for demo in dict_['demographic_evidence']]
else:
query_dict['meta_evidence'] = None
if dict_['demographic_targets'] is not None:
query_dict['meta_targets'] = [tuple(demo) for demo in dict_['demographic_targets']]
else:
query_dict['meta_targets'] = None
query = Query(**query_dict)
return query
def consumeJsonFile(file_name):
with open(file_name, 'r') as passed_file:
query_dict = json.load(passed_file)
os.system('rm {}'.format(file_name))
return query_dict
def runOnNode(query, node_name, save_dir):
pickle_file, json_file = query.save(save_dir)
command = ['ssh', node_name,
'python3', os.path.join(BKB_PATHWAY_CORE_DIR, 'driver.py'),
'--config_file', os.path.join(BKB_PATHWAY_CORE_DIR, 'driver.config'),
'--headless',
'--query_file', pickle_file,
'--save_dir', save_dir]
subprocess.run(command)
return json_file
def makeVariableJsonFile(save_dir, node_name):
vars_file = os.path.join(save_dir, 'bkb_variables.pk')
command = ['ssh', node_name,
'python3', os.path.join(BKB_PATHWAY_CORE_DIR, 'driver.py'),
'--config_file', os.path.join(BKB_PATHWAY_CORE_DIR, 'driver.config'),
'--get_variables', vars_file]
subprocess.run(command)
#--Collect vars_dict from vars_file
with open(vars_file, 'rb') as f_:
vars_dict = pickle.load(f_)
return vars_dict
def collectResults(query_file):
with open(query_file) as f_:
query_res_dict = json.load(f_)
return query_res_dict
def sendJson(results):
print('Begin-JSON------')
print(json.JSONEncoder().encode(results))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--f', default=None, type=str)
parser.add_argument('--get_variables', action='store_true')
args = parser.parse_args()
if args.f is not None:
#-- Consume JSON File passed by UI
query_dict = consumeJsonFile(args.f)
#-- Process the passed JSON file into recognized and runnable Query
query = processUiQuery(query_dict)
#-- Analyze the Query and run reasoning on a specified dell node.
saved_query_file = runOnNode(query, NODE, SAVE_DIR)
#-- Load JSON result file and send back over ssh
res_json = collectResults(saved_query_file)
sendJson(res_json)
elif args.get_variables:
vars_dict = makeVariableJsonFile(SAVE_DIR, NODE)
sendJson(vars_dict)
| chp/babel/bkb-service.py | 3,552 | Source code developed by DI2AG.
Thayer School of Engineering at Dartmouth College
Authors: Dr. Eugene Santos, Jr
Mr. Chase Yakaboski,
Mr. Gregory Hyde,
Dr. Keum Joo Kim
--Collect vars_dict from vars_file-- Consume JSON File passed by UI-- Process the passed JSON file into recognized and runnable Query-- Analyze the Query and run reasoning on a specified dell node.-- Load JSON result file and send back over ssh | 453 | en | 0.777485 |
# Proximal
import sys
sys.path.append('../../')
from proximal.utils.utils import *
from proximal.halide.halide import *
from proximal.lin_ops import *
import numpy as np
from scipy import signal
from scipy import ndimage
import matplotlib.pyplot as plt
############################################################
# Load image
np_img = get_test_image(2048)
print('Type ', np_img.dtype, 'Shape', np_img.shape)
imgplot = plt.imshow(np_img, interpolation='nearest', clim=(0.0, 1.0))
imgplot.set_cmap('gray')
plt.title('Numpy')
# Force recompile in local dir
tic()
Halide('A_conv', recompile=True)
Halide('At_conv', recompile=True) # Force recompile in local dir
print('Compilation took: {0:.1f}ms'.format(toc()))
# Test the runner
output = np.zeros_like(np_img)
K = get_kernel(15, len(np_img.shape))
tic()
Halide('A_conv').A_conv(np_img, K, output) # Call
print('Running took: {0:.1f}ms'.format(toc()))
plt.figure()
imgplot = plt.imshow(output, interpolation='nearest', clim=(0.0, 1.0))
imgplot.set_cmap('gray')
plt.title('Output from Halide')
tic()
output_scipy = signal.convolve2d(np_img, K, mode='same', boundary='wrap')
print('Running Scipy.convolve2d took: {0:.1f}ms'.format(toc()))
fn = conv(K, Variable(np_img.shape), implem='halide')
output_ref = np.zeros(np_img.shape, dtype=np.float32, order='F')
tic()
fn.forward([np_img], [output_ref])
print('Running conv fft convolution took: {0:.1f}ms'.format(toc()))
# Error
print('Maximum error {0}'.format(np.amax(np.abs(output_ref - output))))
plt.figure()
imgplot = plt.imshow(output_ref * 255,
interpolation='nearest',
clim=(0.0, 255.0))
imgplot.set_cmap('gray')
plt.title('Output from Scipy')
############################################################################
# Check correlation
############################################################################
output_corr = np.zeros_like(np_img)
tic()
Halide('At_conv').At_conv(np_img, K, output_corr) # Call
print('Running correlation took: {0:.1f}ms'.format(toc()))
#output_corr_ref = signal.convolve2d(np_img, np.flipud(np.fliplr(K)), mode='same', boundary='wrap')
output_corr_ref = ndimage.correlate(np_img, K, mode='wrap')
# Adjoint.
output_corr_ref = np.zeros(np_img.shape, dtype=np.float32, order='F')
tic()
fn.adjoint([np_img], [output_corr_ref])
print('Running transpose conv fft convolution took: {0:.1f}ms'.format(toc()))
# Error
print('Maximum error correlation {0}'.format(
np.amax(np.abs(output_corr_ref - output_corr))))
plt.show()
| proximal/examples/test_conv.py | 2,524 | Proximal Load image Force recompile in local dir Force recompile in local dir Test the runner Call Error Check correlation Calloutput_corr_ref = signal.convolve2d(np_img, np.flipud(np.fliplr(K)), mode='same', boundary='wrap') Adjoint. Error | 240 | en | 0.378435 |
# coding: UTF-8
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import warnings
warnings.filterwarnings("ignore")
import argparse
import numpy as np
import shutil
import PIL
import time
from imageio import imread, imsave
from googletrans import Translator
import torch
import torchvision
import torch.nn.functional as F
from torchvision import transforms as T
import clip
os.environ['KMP_DUPLICATE_LIB_OK']='True'
from clip_fft import to_valid_rgb, fft_image, resume_fft, pixel_image
from utils import slice_imgs, derivat, sim_func, slerp, basename, file_list, img_list, img_read, pad_up_to, txt_clean, latent_anima, cvshow, checkout, save_cfg, old_torch
import transforms
try: # progress bar for notebooks
get_ipython().__class__.__name__
from progress_bar import ProgressIPy as ProgressBar
except: # normal console
from progress_bar import ProgressBar
clip_models = ['ViT-B/16', 'ViT-B/32', 'RN50', 'RN50x4', 'RN50x16', 'RN101']
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--size', default='1280-720', help='Output resolution')
parser.add_argument('-t', '--in_txt', default=None, help='Text string or file to process (main topic)')
parser.add_argument('-pre', '--in_txt_pre', default=None, help='Prefix for input text')
parser.add_argument('-post', '--in_txt_post', default=None, help='Postfix for input text')
parser.add_argument('-t2', '--in_txt2', default=None, help='Text string or file to process (style)')
parser.add_argument('-t0', '--in_txt0', default=None, help='input text to subtract')
parser.add_argument('-im', '--in_img', default=None, help='input image or directory with images')
parser.add_argument('-w0', '--weight0', default=0.3, type=float, help='weight for subtraction')
parser.add_argument('-w2', '--weight2', default=0.5, type=float, help='weight for style')
parser.add_argument('-wi', '--weight_img', default=0.5, type=float, help='weight for images')
parser.add_argument('-r', '--resume', default=None, help='Resume from saved params or from an image')
parser.add_argument( '--out_dir', default='_out')
parser.add_argument('-tr', '--translate', action='store_true', help='Translate with Google Translate')
parser.add_argument( '--invert', action='store_true', help='Invert criteria')
parser.add_argument('-v', '--verbose', default=True, type=bool)
# training
parser.add_argument( '--gen', default='RGB', help='Generation (optimization) method: FFT or RGB')
parser.add_argument('-m', '--model', default='ViT-B/32', choices=clip_models, help='Select CLIP model to use')
parser.add_argument( '--steps', default=300, type=int, help='Iterations (frames) per scene (text line)')
parser.add_argument( '--samples', default=100, type=int, help='Samples to evaluate per frame')
parser.add_argument('-lr', '--lrate', default=1, type=float, help='Learning rate')
# motion
parser.add_argument('-opt', '--opt_step', default=1, type=int, help='How many optimizing steps per save/transform step')
parser.add_argument('-sm', '--smooth', action='store_true', help='Smoothen interframe jittering for FFT method')
parser.add_argument('-it', '--interpol', default=True, help='Interpolate topics? (or change by cut)')
parser.add_argument( '--fstep', default=100, type=int, help='How many frames before changing motion')
parser.add_argument( '--scale', default=0.012, type=float)
parser.add_argument( '--shift', default=10., type=float, help='in pixels')
parser.add_argument( '--angle', default=0.8, type=float, help='in degrees')
parser.add_argument( '--shear', default=0.4, type=float)
parser.add_argument( '--anima', default=True, help='Animate motion')
# tweaks
parser.add_argument('-a', '--align', default='overscan', choices=['central', 'uniform', 'overscan', 'overmax'], help='Sampling distribution')
parser.add_argument('-tf', '--transform', default='custom', choices=['none', 'custom', 'elastic'], help='use augmenting transforms?')
parser.add_argument( '--contrast', default=1.2, type=float)
parser.add_argument( '--colors', default=2, type=float)
parser.add_argument('-sh', '--sharp', default=None, type=float)
parser.add_argument('-mc', '--macro', default=0.4, type=float, help='Endorse macro forms 0..1 ')
parser.add_argument('-e', '--enforce', default=0, type=float, help='Enforce details (by boosting similarity between two parallel samples)')
parser.add_argument('-x', '--expand', default=0, type=float, help='Boosts diversity (by enforcing difference between prev/next samples)')
parser.add_argument('-n', '--noise', default=2., type=float, help='Add noise to make composition sparse (FFT only)') # 0.04
parser.add_argument( '--sim', default='mix', help='Similarity function (angular/spherical/mixed; None = cossim)')
parser.add_argument( '--rem', default=None, help='Dummy text to add to project name')
a = parser.parse_args()
if a.size is not None: a.size = [int(s) for s in a.size.split('-')][::-1]
if len(a.size)==1: a.size = a.size * 2
a.gen = a.gen.upper()
a.invert = -1. if a.invert is True else 1.
# Overriding some parameters, depending on other settings
if a.gen == 'RGB':
a.smooth = False
a.align = 'overscan'
if a.sharp is None: a.sharp = -1. if a.gen == 'RGB' else 1.
if a.model == 'ViT-B/16': a.sim = 'cossim'
return a
def frame_transform(img, size, angle, shift, scale, shear):
if old_torch(): # 1.7.1
img = T.functional.affine(img, angle, shift, scale, shear, fillcolor=0, resample=PIL.Image.BILINEAR)
img = T.functional.center_crop(img, size)
img = pad_up_to(img, size)
else: # 1.8+
img = T.functional.affine(img, angle, shift, scale, shear, fill=0, interpolation=T.InterpolationMode.BILINEAR)
img = T.functional.center_crop(img, size) # on 1.8+ also pads
return img
def main():
a = get_args()
# Load CLIP models
model_clip, _ = clip.load(a.model, jit=old_torch())
try:
a.modsize = model_clip.visual.input_resolution
except:
a.modsize = 288 if a.model == 'RN50x4' else 384 if a.model == 'RN50x16' else 224
if a.verbose is True: print(' using model', a.model)
xmem = {'ViT-B/16':0.25, 'RN50':0.5, 'RN50x4':0.16, 'RN50x16':0.06, 'RN101':0.33}
if a.model in xmem.keys():
a.samples = int(a.samples * xmem[a.model])
if a.translate:
translator = Translator()
if a.enforce != 0:
a.samples = int(a.samples * 0.5)
if 'elastic' in a.transform:
trform_f = transforms.transforms_elastic
a.samples = int(a.samples * 0.95)
elif 'custom' in a.transform:
trform_f = transforms.transforms_custom
a.samples = int(a.samples * 0.95)
else:
trform_f = transforms.normalize()
def enc_text(txt):
if a.translate:
txt = translator.translate(txt, dest='en').text
emb = model_clip.encode_text(clip.tokenize(txt).cuda()[:77])
return emb.detach().clone()
def enc_image(img_file):
img_t = torch.from_numpy(img_read(img_file)/255.).unsqueeze(0).permute(0,3,1,2).cuda()[:,:3,:,:]
in_sliced = slice_imgs([img_t], a.samples, a.modsize, transforms.normalize(), a.align)[0]
emb = model_clip.encode_image(in_sliced)
return emb.detach().clone()
# Encode inputs
count = 0
texts = []
styles = []
images = []
if a.in_txt is not None:
if os.path.isfile(a.in_txt):
with open(a.in_txt, 'r', encoding="utf-8") as f:
texts = f.readlines()
texts = [tt.strip() for tt in texts if len(tt.strip()) > 0 and tt[0] != '#']
else:
texts = [a.in_txt]
if a.in_txt_pre is not None:
texts = [' '.join([a.in_txt_pre, tt]).strip() for tt in texts]
if a.in_txt_post is not None:
texts = [' '.join([tt, a.in_txt_post]).strip() for tt in texts]
key_txt_encs = [enc_text(txt) for txt in texts]
count = max(count, len(key_txt_encs))
if a.in_txt2 is not None:
if os.path.isfile(a.in_txt2):
with open(a.in_txt2, 'r', encoding="utf-8") as f:
styles = f.readlines()
styles = [tt.strip() for tt in styles if len(tt.strip()) > 0 and tt[0] != '#']
else:
styles = [a.in_txt2]
key_styl_encs = [enc_text(style) for style in styles]
count = max(count, len(key_styl_encs))
if a.in_img is not None and os.path.exists(a.in_img):
images = file_list(a.in_img) if os.path.isdir(a.in_img) else [a.in_img]
key_img_encs = [enc_image(image) for image in images]
count = max(count, len(key_img_encs))
assert count > 0, "No inputs found!"
if a.in_txt0 is not None:
if a.verbose is True: print(' subtract text:', a.in_txt0)
if a.translate:
a.in_txt0 = translator.translate(a.in_txt0, dest='en').text
# if a.verbose is True: print(' translated to:', a.in_txt0)
anti_txt_encs = [enc_text(txt) for txt in a.in_txt0.split('.')]
if a.verbose is True: print(' samples:', a.samples)
global params_tmp
shape = [1, 3, *a.size]
if a.gen == 'RGB':
params_tmp, _, sz = pixel_image(shape, a.resume)
params_tmp = params_tmp[0].cuda().detach()
else:
params_tmp, sz = resume_fft(a.resume, shape, decay=1.5, sd=1)
if sz is not None: a.size = sz
# [glob]steps = for save/move, opt_steps = for optimization cycle
steps = a.steps
glob_steps = count * steps
opt_steps = steps * a.opt_step
if glob_steps == a.fstep: a.fstep = glob_steps // 2 # otherwise no motion
workname = basename(a.in_txt) if a.in_txt is not None else basename(a.in_img)
workname = txt_clean(workname)
workdir = os.path.join(a.out_dir, workname)
if a.rem is not None: workdir += '-%s' % a.rem
if 'RN' in a.model.upper(): workdir += '-%s' % a.model
if a.noise > 0: workdir += '-n%.2g' % a.noise
if a.macro > 0: workdir += '-m%.2g' % a.macro
if a.smooth is True: workdir += '-sm'
if a.transform != 'custom': workdir += '-tf%s' % a.transform
if a.gen == 'RGB': workdir += '-rgb'
tempdir = os.path.join(workdir, 'ttt')
os.makedirs(tempdir, exist_ok=True)
save_cfg(a, workdir)
if a.in_txt is not None and os.path.isfile(a.in_txt):
shutil.copy(a.in_txt, os.path.join(workdir, os.path.basename(a.in_txt)))
if a.in_txt2 is not None and os.path.isfile(a.in_txt2):
shutil.copy(a.in_txt2, os.path.join(workdir, os.path.basename(a.in_txt2)))
midp = 0.5
if a.anima:
if a.gen == 'RGB': # zoom in
m_scale = latent_anima([1], glob_steps, a.fstep, uniform=True, cubic=True, start_lat=[-0.3], verbose=False)
m_scale = 1 + (m_scale + 0.3) * a.scale
else:
m_scale = latent_anima([1], glob_steps, a.fstep, uniform=True, cubic=True, start_lat=[0.6], verbose=False)
m_scale = 1 - (m_scale-0.6) * a.scale
m_shift = latent_anima([2], glob_steps, a.fstep, uniform=True, cubic=True, start_lat=[midp,midp], verbose=False)
m_angle = latent_anima([1], glob_steps, a.fstep, uniform=True, cubic=True, start_lat=[midp], verbose=False)
m_shear = latent_anima([1], glob_steps, a.fstep, uniform=True, cubic=True, start_lat=[midp], verbose=False)
m_shift = (midp-m_shift) * a.shift * abs(m_scale-1) / a.scale
m_angle = (midp-m_angle) * a.angle * abs(m_scale-1) / a.scale
m_shear = (midp-m_shear) * a.shear * abs(m_scale-1) / a.scale
def get_encs(encs, num):
cnt = len(encs)
if cnt == 0: return []
enc_1 = encs[min(num, cnt-1)]
enc_2 = encs[min(num+1, cnt-1)]
return slerp(enc_1, enc_2, opt_steps)
prev_enc = 0
def process(num):
global params_tmp, opt_state, params, image_f, optimizer
if a.interpol is True: # linear topics interpolation
txt_encs = get_encs(key_txt_encs, num)
styl_encs = get_encs(key_styl_encs, num)
img_encs = get_encs(key_img_encs, num)
else: # change by cut
txt_encs = [key_txt_encs[min(num, len(key_txt_encs)-1)][0]] * opt_steps if len(key_txt_encs) > 0 else []
styl_encs = [key_styl_encs[min(num, len(key_styl_encs)-1)][0]] * opt_steps if len(key_styl_encs) > 0 else []
img_encs = [key_img_encs[min(num, len(key_img_encs)-1)][0]] * opt_steps if len(key_img_encs) > 0 else []
if a.verbose is True:
if len(texts) > 0: print(' ref text: ', texts[min(num, len(texts)-1)][:80])
if len(styles) > 0: print(' ref style: ', styles[min(num, len(styles)-1)][:80])
if len(images) > 0: print(' ref image: ', basename(images[min(num, len(images)-1)])[:80])
pbar = ProgressBar(steps)
for ii in range(opt_steps):
glob_step = num * steps + ii // a.opt_step # save/transform
loss = 0
txt_enc = txt_encs[ii % len(txt_encs)].unsqueeze(0) if len(txt_encs) > 0 else None
styl_enc = styl_encs[ii % len(styl_encs)].unsqueeze(0) if len(styl_encs) > 0 else None
img_enc = img_encs[ii % len(img_encs)].unsqueeze(0) if len(img_encs) > 0 else None
# MOTION: transform frame, reload params
if ii % a.opt_step == 0:
scale = m_scale[glob_step] if a.anima else 1 + a.scale
shift = tuple(m_shift[glob_step]) if a.anima else [0, a.shift]
angle = m_angle[glob_step][0] if a.anima else a.angle
shear = m_shear[glob_step][0] if a.anima else a.shear
if a.gen == 'RGB':
img_tmp = frame_transform(params_tmp, a.size, angle, shift, scale, shear)
params, image_f, _ = pixel_image([1, 3, *a.size], resume=img_tmp)
else: # FFT
if old_torch(): # 1.7.1
img_tmp = torch.irfft(params_tmp, 2, normalized=True, signal_sizes=a.size)
img_tmp = frame_transform(img_tmp, a.size, angle, shift, scale, shear)
params_tmp = torch.rfft(img_tmp, 2, normalized=True)
else: # 1.8+
if type(params_tmp) is not torch.complex64:
params_tmp = torch.view_as_complex(params_tmp)
img_tmp = torch.fft.irfftn(params_tmp, s=a.size, norm='ortho')
img_tmp = frame_transform(img_tmp, a.size, angle, shift, scale, shear)
params_tmp = torch.fft.rfftn(img_tmp, s=a.size, dim=[2,3], norm='ortho')
params_tmp = torch.view_as_real(params_tmp)
params, image_f, _ = fft_image([1, 3, *a.size], sd=1, resume=params_tmp)
optimizer = torch.optim.Adam(params, a.lrate)
# optimizer = torch.optim.AdamW(params, a.lrate, weight_decay=0.01, amsgrad=True)
image_f = to_valid_rgb(image_f, colors = a.colors)
del img_tmp
if a.smooth is True and num + ii > 0:
optimizer.load_state_dict(opt_state)
noise = a.noise * (torch.rand(1, 1, a.size[0], a.size[1]//2+1, 1)-0.5).cuda() if a.noise>0 else 0.
img_out = image_f(noise)
img_sliced = slice_imgs([img_out], a.samples, a.modsize, trform_f, a.align, a.macro)[0]
out_enc = model_clip.encode_image(img_sliced)
if a.gen == 'RGB': # empirical hack
loss += 1.66 * abs(img_out.mean((2,3)) - 0.45).sum() # fix brightness
loss += 1.66 * abs(img_out.std((2,3)) - 0.17).sum() # fix contrast
if txt_enc is not None:
loss -= a.invert * sim_func(txt_enc, out_enc, a.sim)
if styl_enc is not None:
loss -= a.weight2 * sim_func(styl_enc, out_enc, a.sim)
if img_enc is not None:
loss -= a.weight_img * sim_func(img_enc, out_enc, a.sim)
if a.in_txt0 is not None: # subtract text
for anti_txt_enc in anti_txt_encs:
loss += 0.3 * sim_func(anti_txt_enc, out_enc, a.sim)
if a.sharp != 0: # scharr|sobel|naive
loss -= a.sharp * derivat(img_out, mode='naive')
if a.enforce != 0:
img_sliced = slice_imgs([image_f(noise)], a.samples, a.modsize, trform_f, a.align, a.macro)[0]
out_enc2 = model_clip.encode_image(img_sliced)
loss -= a.enforce * sim_func(out_enc, out_enc2, a.sim)
del out_enc2; torch.cuda.empty_cache()
if a.expand > 0:
global prev_enc
if ii > 0:
loss += a.expand * sim_func(prev_enc, out_enc, a.sim)
prev_enc = out_enc.detach().clone()
del img_out, img_sliced, out_enc; torch.cuda.empty_cache()
optimizer.zero_grad()
loss.backward()
optimizer.step()
if ii % a.opt_step == a.opt_step-1:
params_tmp = params[0].detach().clone()
if a.smooth is True:
opt_state = optimizer.state_dict()
if ii % a.opt_step == 0:
with torch.no_grad():
img_t = image_f(contrast=a.contrast)[0].permute(1,2,0)
img = torch.clip(img_t*255, 0, 255).cpu().numpy().astype(np.uint8)
imsave(os.path.join(tempdir, '%06d.jpg' % glob_step), img, quality=95)
if a.verbose is True: cvshow(img)
del img, img_t
pbar.upd()
params_tmp = params[0].detach().clone()
glob_start = time.time()
try:
for i in range(count):
process(i)
except KeyboardInterrupt:
pass
os.system('ffmpeg -v warning -y -i %s/\%%06d.jpg "%s.mp4"' % (tempdir, os.path.join(workdir, workname)))
if __name__ == '__main__':
main()
| illustrip.py | 18,400 | coding: UTF-8 progress bar for notebooks normal console training motion tweaks 0.04 Overriding some parameters, depending on other settings 1.7.1 1.8+ on 1.8+ also pads Load CLIP models Encode inputs if a.verbose is True: print(' translated to:', a.in_txt0) [glob]steps = for save/move, opt_steps = for optimization cycle otherwise no motion zoom in linear topics interpolation change by cut save/transform MOTION: transform frame, reload params FFT 1.7.1 1.8+ optimizer = torch.optim.AdamW(params, a.lrate, weight_decay=0.01, amsgrad=True) empirical hack fix brightness fix contrast subtract text scharr|sobel|naive | 618 | en | 0.550404 |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from . import outputs
from ._inputs import *
__all__ = ['ApiOperation']
class ApiOperation(pulumi.CustomResource):
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
api_id: Optional[pulumi.Input[str]] = None,
description: Optional[pulumi.Input[str]] = None,
display_name: Optional[pulumi.Input[str]] = None,
method: Optional[pulumi.Input[str]] = None,
operation_id: Optional[pulumi.Input[str]] = None,
policies: Optional[pulumi.Input[str]] = None,
request: Optional[pulumi.Input[pulumi.InputType['RequestContractArgs']]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
responses: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ResponseContractArgs']]]]] = None,
service_name: Optional[pulumi.Input[str]] = None,
template_parameters: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ParameterContractArgs']]]]] = None,
url_template: Optional[pulumi.Input[str]] = None,
__props__=None,
__name__=None,
__opts__=None):
"""
Api Operation details.
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] api_id: API revision identifier. Must be unique in the current API Management service instance. Non-current revision has ;rev=n as a suffix where n is the revision number.
:param pulumi.Input[str] description: Description of the operation. May include HTML formatting tags.
:param pulumi.Input[str] display_name: Operation Name.
:param pulumi.Input[str] method: A Valid HTTP Operation Method. Typical Http Methods like GET, PUT, POST but not limited by only them.
:param pulumi.Input[str] operation_id: Operation identifier within an API. Must be unique in the current API Management service instance.
:param pulumi.Input[str] policies: Operation Policies
:param pulumi.Input[pulumi.InputType['RequestContractArgs']] request: An entity containing request details.
:param pulumi.Input[str] resource_group_name: The name of the resource group.
:param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ResponseContractArgs']]]] responses: Array of Operation responses.
:param pulumi.Input[str] service_name: The name of the API Management service.
:param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ParameterContractArgs']]]] template_parameters: Collection of URL template parameters.
:param pulumi.Input[str] url_template: Relative URL template identifying the target resource for this operation. May include parameters. Example: /customers/{cid}/orders/{oid}/?date={date}
"""
if __name__ is not None:
warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning)
resource_name = __name__
if __opts__ is not None:
warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning)
opts = __opts__
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = dict()
if api_id is None and not opts.urn:
raise TypeError("Missing required property 'api_id'")
__props__['api_id'] = api_id
__props__['description'] = description
if display_name is None and not opts.urn:
raise TypeError("Missing required property 'display_name'")
__props__['display_name'] = display_name
if method is None and not opts.urn:
raise TypeError("Missing required property 'method'")
__props__['method'] = method
__props__['operation_id'] = operation_id
__props__['policies'] = policies
__props__['request'] = request
if resource_group_name is None and not opts.urn:
raise TypeError("Missing required property 'resource_group_name'")
__props__['resource_group_name'] = resource_group_name
__props__['responses'] = responses
if service_name is None and not opts.urn:
raise TypeError("Missing required property 'service_name'")
__props__['service_name'] = service_name
__props__['template_parameters'] = template_parameters
if url_template is None and not opts.urn:
raise TypeError("Missing required property 'url_template'")
__props__['url_template'] = url_template
__props__['name'] = None
__props__['type'] = None
alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:apimanagement:ApiOperation"), pulumi.Alias(type_="azure-nextgen:apimanagement/latest:ApiOperation"), pulumi.Alias(type_="azure-nextgen:apimanagement/v20160707:ApiOperation"), pulumi.Alias(type_="azure-nextgen:apimanagement/v20161010:ApiOperation"), pulumi.Alias(type_="azure-nextgen:apimanagement/v20170301:ApiOperation"), pulumi.Alias(type_="azure-nextgen:apimanagement/v20180101:ApiOperation"), pulumi.Alias(type_="azure-nextgen:apimanagement/v20180601preview:ApiOperation"), pulumi.Alias(type_="azure-nextgen:apimanagement/v20190101:ApiOperation"), pulumi.Alias(type_="azure-nextgen:apimanagement/v20191201:ApiOperation"), pulumi.Alias(type_="azure-nextgen:apimanagement/v20191201preview:ApiOperation")])
opts = pulumi.ResourceOptions.merge(opts, alias_opts)
super(ApiOperation, __self__).__init__(
'azure-nextgen:apimanagement/v20200601preview:ApiOperation',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None) -> 'ApiOperation':
"""
Get an existing ApiOperation resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = dict()
return ApiOperation(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter
def description(self) -> pulumi.Output[Optional[str]]:
"""
Description of the operation. May include HTML formatting tags.
"""
return pulumi.get(self, "description")
@property
@pulumi.getter(name="displayName")
def display_name(self) -> pulumi.Output[str]:
"""
Operation Name.
"""
return pulumi.get(self, "display_name")
@property
@pulumi.getter
def method(self) -> pulumi.Output[str]:
"""
A Valid HTTP Operation Method. Typical Http Methods like GET, PUT, POST but not limited by only them.
"""
return pulumi.get(self, "method")
@property
@pulumi.getter
def name(self) -> pulumi.Output[str]:
"""
Resource name.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter
def policies(self) -> pulumi.Output[Optional[str]]:
"""
Operation Policies
"""
return pulumi.get(self, "policies")
@property
@pulumi.getter
def request(self) -> pulumi.Output[Optional['outputs.RequestContractResponse']]:
"""
An entity containing request details.
"""
return pulumi.get(self, "request")
@property
@pulumi.getter
def responses(self) -> pulumi.Output[Optional[Sequence['outputs.ResponseContractResponse']]]:
"""
Array of Operation responses.
"""
return pulumi.get(self, "responses")
@property
@pulumi.getter(name="templateParameters")
def template_parameters(self) -> pulumi.Output[Optional[Sequence['outputs.ParameterContractResponse']]]:
"""
Collection of URL template parameters.
"""
return pulumi.get(self, "template_parameters")
@property
@pulumi.getter
def type(self) -> pulumi.Output[str]:
"""
Resource type for API Management resource.
"""
return pulumi.get(self, "type")
@property
@pulumi.getter(name="urlTemplate")
def url_template(self) -> pulumi.Output[str]:
"""
Relative URL template identifying the target resource for this operation. May include parameters. Example: /customers/{cid}/orders/{oid}/?date={date}
"""
return pulumi.get(self, "url_template")
def translate_output_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
def translate_input_property(self, prop):
return _tables.SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop
| sdk/python/pulumi_azure_nextgen/apimanagement/v20200601preview/api_operation.py | 9,981 | Api Operation details.
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] api_id: API revision identifier. Must be unique in the current API Management service instance. Non-current revision has ;rev=n as a suffix where n is the revision number.
:param pulumi.Input[str] description: Description of the operation. May include HTML formatting tags.
:param pulumi.Input[str] display_name: Operation Name.
:param pulumi.Input[str] method: A Valid HTTP Operation Method. Typical Http Methods like GET, PUT, POST but not limited by only them.
:param pulumi.Input[str] operation_id: Operation identifier within an API. Must be unique in the current API Management service instance.
:param pulumi.Input[str] policies: Operation Policies
:param pulumi.Input[pulumi.InputType['RequestContractArgs']] request: An entity containing request details.
:param pulumi.Input[str] resource_group_name: The name of the resource group.
:param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ResponseContractArgs']]]] responses: Array of Operation responses.
:param pulumi.Input[str] service_name: The name of the API Management service.
:param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ParameterContractArgs']]]] template_parameters: Collection of URL template parameters.
:param pulumi.Input[str] url_template: Relative URL template identifying the target resource for this operation. May include parameters. Example: /customers/{cid}/orders/{oid}/?date={date}
Description of the operation. May include HTML formatting tags.
Operation Name.
Get an existing ApiOperation resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
A Valid HTTP Operation Method. Typical Http Methods like GET, PUT, POST but not limited by only them.
Resource name.
Operation Policies
An entity containing request details.
Array of Operation responses.
Collection of URL template parameters.
Resource type for API Management resource.
Relative URL template identifying the target resource for this operation. May include parameters. Example: /customers/{cid}/orders/{oid}/?date={date}
coding=utf-8 *** WARNING: this file was generated by the Pulumi SDK Generator. *** *** Do not edit by hand unless you're certain you know what you are doing! *** | 2,566 | en | 0.640209 |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
平安行动自动打卡
请事先安装好 lxml 和 requests 模块
pip install lxml requests
然后修改 27-31 行为自己的数据,未使用的变量保持原样即可
如有需要请自行配置 149-171 行的 SMTP 发信或 174-177 行的 Server 酱微信提醒
Created on 2020-04-13 20:20
@author: ZhangJiawei & Liu Chongpeng & Liu Lu
"""
import requests
import lxml.html
import re
import json
import random
import time
import smtplib
import traceback
myid = "STUDENTID"
mypass = "PASSWORD"
mybound = "BOUNDFIELDS"
mydata = r'FORMDATA'
# mysckey = "SCKEY"
title = ""
msg = ""
proxies = {"http": None, "https": None}
headers = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "zh-CN",
"Cache-Control": "max-age=0",
"Connection": "keep-alive",
"Content-Type": "application/x-www-form-urlencoded",
"Cookie": "MESSAGE_TICKET=%7B%22times%22%3A0%7D; ",
"Host": "cas.hrbeu.edu.cn",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18362"
}
def findStr(source, target):
return source.find(target) != -1
if __name__ == '__main__':
try:
## 登陆校园网络认证界面
url_login = 'https://cas.hrbeu.edu.cn/cas/login?'
print("============================\n[debug] Begin to login ...")
sesh = requests.session()
req = sesh.get(url_login, proxies=proxies)
html_content = req.text
login_html = lxml.html.fromstring(html_content)
hidden_inputs = login_html.xpath( r'//div[@id="main"]//input[@type="hidden"]')
user_form = {x.attrib["name"]: x.attrib["value"] for x in hidden_inputs}
user_form["username"] = myid
user_form["password"] = mypass
user_form["captcha"] = ''
user_form["submit"] = '登 录'
headers['Cookie'] = headers['Cookie'] + req.headers['Set-cookie']
req.url = f'https://cas.hrbeu.edu.cn/cas/login'
response302 = sesh.post(req.url, data=user_form, headers=headers, proxies=proxies)
## 进入平安行动界面
jkgc_response = sesh.get( "http://jkgc.hrbeu.edu.cn/infoplus/form/JSXNYQSBtest/start", proxies=proxies)
headers['Accept'] = '*/*'
headers['Cookie'] = jkgc_response.request.headers['Cookie']
headers['Host'] = 'jkgc.hrbeu.edu.cn'
headers['Referer'] = jkgc_response.url
jkgc_html = lxml.html.fromstring(jkgc_response.text)
csrfToken = jkgc_html.xpath(r'//meta[@itemscope="csrfToken"]')
csrfToken = csrfToken.pop().attrib["content"]
jkgc_form = {
'idc': 'JSXNYQSBtest',
'release': '',
'csrfToken': csrfToken,
'formData': {
'_VAR_URL': jkgc_response.url,
'_VAR_URL_Attr': {}
}
}
jkgc_form['formData'] = json.dumps(jkgc_form['formData'])
jkgc_url = 'http://jkgc.hrbeu.edu.cn/infoplus/interface/start'
response3 = sesh.post(jkgc_url, data=jkgc_form, headers=headers, proxies=proxies)
## 提交平安行动表单
form_url = json.loads(response3.text)['entities'][0]
form_response = sesh.get(form_url)
headers['Accept'] = 'application/json, text/javascript, */*; q=0.01'
headers['Referer'] = form_url
headers['X-Requested-With'] = 'XMLHttpRequest'
submit_url = 'http://jkgc.hrbeu.edu.cn/infoplus/interface/doAction'
submit_html = lxml.html.fromstring(form_response.text)
csrfToken2 = submit_html.xpath(r'//meta[@itemscope="csrfToken"]')
csrfToken2 = csrfToken2.pop().attrib["content"]
submit_form = {
'actionId': '1',
'boundFields': mybound, # boundFields 修改位置
'csrfToken': csrfToken2,
'formData': mydata, # formData 修改位置
'lang': 'zh',
'nextUsers': '{}',
'rand': str(random.random() * 999),
'remark': '',
'stepId': re.match(r'.*form/(\d*?)/', form_response.url).group(1),
'timestamp': str(int(time.time()+0.5))
}
response_end = sesh.post(submit_url, data=submit_form, headers=headers, proxies=proxies)
resJson = json.loads(response_end.text)
## 表单填写完成,返回结果
print('[debug] Form url: ', form_response.url)
print('[debug] Form Status: ', resJson['ecode'])
print('[debug] Form stJson: ', resJson)
## 生成提醒返回的标题和信息
if (resJson['errno'] == 0):
print('[info] Checkin succeed with jsoncode', resJson['ecode'])
title = f'打卡成功 <{submit_form["stepId"]}>'
msg = '\t表单地址: ' + form_response.url + '\n\n\t表单状态: \n\t\terrno:' + str(resJson['errno']) + '\n\t\tecode:' + str(
resJson['ecode']) + '\n\t\tentities:' + str(resJson['entities']) + '\n\n\n\t完整返回:' + response_end.text
else:
print('[error] Checkin error with jsoncode', resJson['ecode'])
title = f'打卡失败!校网出错'
msg = '\t表单地址: ' + form_response.url + '\n\n\t错误信息: \n\t\terrno:' + str(resJson['errno']) + '\n\t\tecode:' + str(
resJson['ecode']) + '\n\t\tentities:' + str(resJson['entities']) + '\n\n\n\t完整返回:' + response_end.text
except:
print('\n[error] :.:.:.:.: Except return :.:.:.:.:')
err = traceback.format_exc()
print('[error] Python Error: \n', err)
title = '打卡失败!脚本出错'
msg = '\t脚本报错: \n\n\t' + err + '============================\n'
finally:
print(':.:.:.:.: Finally :.:.:.:.:')
## 发送邮件
# from email.mime.text import MIMEText
# from email.header import Header
# mail_host = "smtp.qq.com" # SMTP 服务器地址
# mail_user = "sender@example.com" # SMTP 发信邮箱用户名
# mail_pass = "emailpassword" # SMTP 发信邮箱密码
# sender = 'sender@example.com' # 发信人邮箱,即 SMTP 发信邮箱用户名
# receivers = ['receiver@example.com'] # 收信人邮箱,多邮箱以数组形式写
# message = MIMEText(msg, 'plain', 'utf-8')
# message['From'] = Header("1@example.com", 'utf-8') # 发信人邮箱,仅用于显示
# message['To'] = Header("2@example.com", 'utf-8') # 收信人邮箱,仅用于显示
# subject = title
# message['Subject'] = Header(subject, 'utf-8')
# try:
# smtpObj = smtplib.SMTP_SSL(mail_host) # Python 3.7 及以上版本 SSL 加密发信
# smtpObj.connect(mail_host, 465) # Python 3.7 及以上版本 加密发信 SMTP 端口号 465
# smtpObj.login(mail_user,mail_pass)
# smtpObj.sendmail(sender, receivers, message.as_string())
# print ("[info] Success: The email was sent successfully") # 日志输出
# except smtplib.SMTPException:
# print ("[error] Error: Can not send mail") # 日志输出
## 或者发送 Server 酱的微信提醒
# wcurl = 'https://sc.ftqq.com/' + mysckey + '.send'
# wcdata = {'text': title, 'desp': msg}
# try:
# wcresult = requests.post(wcurl, wcdata)
# print('[info] Notification sended at', time.strftime("%Y-%m-%d %H:%M:%S %A", time.localtime()))
# except:
# print('[error] Failed to send notification!')
print('[info] Task Finished at', time.strftime("%Y-%m-%d %H:%M:%S %A", time.localtime()))
print('============================\n')
| Server/checkin.py | 8,098 | 平安行动自动打卡
请事先安装好 lxml 和 requests 模块
pip install lxml requests
然后修改 27-31 行为自己的数据,未使用的变量保持原样即可
如有需要请自行配置 149-171 行的 SMTP 发信或 174-177 行的 Server 酱微信提醒
Created on 2020-04-13 20:20
@author: ZhangJiawei & Liu Chongpeng & Liu Lu
!/usr/bin/env python3 -*- coding: UTF-8 -*- mysckey = "SCKEY" 登陆校园网络认证界面 进入平安行动界面 提交平安行动表单 boundFields 修改位置 formData 修改位置 表单填写完成,返回结果 生成提醒返回的标题和信息 发送邮件 from email.mime.text import MIMEText from email.header import Header mail_host = "smtp.qq.com" SMTP 服务器地址 mail_user = "sender@example.com" SMTP 发信邮箱用户名 mail_pass = "emailpassword" SMTP 发信邮箱密码 sender = 'sender@example.com' 发信人邮箱,即 SMTP 发信邮箱用户名 receivers = ['receiver@example.com'] 收信人邮箱,多邮箱以数组形式写 message = MIMEText(msg, 'plain', 'utf-8') message['From'] = Header("1@example.com", 'utf-8') 发信人邮箱,仅用于显示 message['To'] = Header("2@example.com", 'utf-8') 收信人邮箱,仅用于显示 subject = title message['Subject'] = Header(subject, 'utf-8') try: smtpObj = smtplib.SMTP_SSL(mail_host) Python 3.7 及以上版本 SSL 加密发信 smtpObj.connect(mail_host, 465) Python 3.7 及以上版本 加密发信 SMTP 端口号 465 smtpObj.login(mail_user,mail_pass) smtpObj.sendmail(sender, receivers, message.as_string()) print ("[info] Success: The email was sent successfully") 日志输出 except smtplib.SMTPException: print ("[error] Error: Can not send mail") 日志输出 或者发送 Server 酱的微信提醒 wcurl = 'https://sc.ftqq.com/' + mysckey + '.send' wcdata = {'text': title, 'desp': msg} try: wcresult = requests.post(wcurl, wcdata) print('[info] Notification sended at', time.strftime("%Y-%m-%d %H:%M:%S %A", time.localtime())) except: print('[error] Failed to send notification!') | 1,762 | en | 0.281167 |
# coding: utf-8
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401
from oci.decorators import init_model_state_from_kwargs
@init_model_state_from_kwargs
class JreUsage(object):
"""
Java Runtime usage during a specified time period. A Java Runtime is identified by its vendor and version.
"""
#: A constant which can be used with the security_status property of a JreUsage.
#: This constant has a value of "UNKNOWN"
SECURITY_STATUS_UNKNOWN = "UNKNOWN"
#: A constant which can be used with the security_status property of a JreUsage.
#: This constant has a value of "UP_TO_DATE"
SECURITY_STATUS_UP_TO_DATE = "UP_TO_DATE"
#: A constant which can be used with the security_status property of a JreUsage.
#: This constant has a value of "UPDATE_REQUIRED"
SECURITY_STATUS_UPDATE_REQUIRED = "UPDATE_REQUIRED"
#: A constant which can be used with the security_status property of a JreUsage.
#: This constant has a value of "UPGRADE_REQUIRED"
SECURITY_STATUS_UPGRADE_REQUIRED = "UPGRADE_REQUIRED"
def __init__(self, **kwargs):
"""
Initializes a new JreUsage object with values from keyword arguments.
The following keyword arguments are supported (corresponding to the getters/setters of this class):
:param id:
The value to assign to the id property of this JreUsage.
:type id: str
:param fleet_id:
The value to assign to the fleet_id property of this JreUsage.
:type fleet_id: str
:param managed_instance_id:
The value to assign to the managed_instance_id property of this JreUsage.
:type managed_instance_id: str
:param security_status:
The value to assign to the security_status property of this JreUsage.
Allowed values for this property are: "UNKNOWN", "UP_TO_DATE", "UPDATE_REQUIRED", "UPGRADE_REQUIRED", 'UNKNOWN_ENUM_VALUE'.
Any unrecognized values returned by a service will be mapped to 'UNKNOWN_ENUM_VALUE'.
:type security_status: str
:param release_date:
The value to assign to the release_date property of this JreUsage.
:type release_date: datetime
:param end_of_support_life_date:
The value to assign to the end_of_support_life_date property of this JreUsage.
:type end_of_support_life_date: datetime
:param vendor:
The value to assign to the vendor property of this JreUsage.
:type vendor: str
:param distribution:
The value to assign to the distribution property of this JreUsage.
:type distribution: str
:param version:
The value to assign to the version property of this JreUsage.
:type version: str
:param operating_systems:
The value to assign to the operating_systems property of this JreUsage.
:type operating_systems: list[oci.jms.models.OperatingSystem]
:param approximate_installation_count:
The value to assign to the approximate_installation_count property of this JreUsage.
:type approximate_installation_count: int
:param approximate_application_count:
The value to assign to the approximate_application_count property of this JreUsage.
:type approximate_application_count: int
:param approximate_managed_instance_count:
The value to assign to the approximate_managed_instance_count property of this JreUsage.
:type approximate_managed_instance_count: int
:param time_start:
The value to assign to the time_start property of this JreUsage.
:type time_start: datetime
:param time_end:
The value to assign to the time_end property of this JreUsage.
:type time_end: datetime
:param time_first_seen:
The value to assign to the time_first_seen property of this JreUsage.
:type time_first_seen: datetime
:param time_last_seen:
The value to assign to the time_last_seen property of this JreUsage.
:type time_last_seen: datetime
"""
self.swagger_types = {
'id': 'str',
'fleet_id': 'str',
'managed_instance_id': 'str',
'security_status': 'str',
'release_date': 'datetime',
'end_of_support_life_date': 'datetime',
'vendor': 'str',
'distribution': 'str',
'version': 'str',
'operating_systems': 'list[OperatingSystem]',
'approximate_installation_count': 'int',
'approximate_application_count': 'int',
'approximate_managed_instance_count': 'int',
'time_start': 'datetime',
'time_end': 'datetime',
'time_first_seen': 'datetime',
'time_last_seen': 'datetime'
}
self.attribute_map = {
'id': 'id',
'fleet_id': 'fleetId',
'managed_instance_id': 'managedInstanceId',
'security_status': 'securityStatus',
'release_date': 'releaseDate',
'end_of_support_life_date': 'endOfSupportLifeDate',
'vendor': 'vendor',
'distribution': 'distribution',
'version': 'version',
'operating_systems': 'operatingSystems',
'approximate_installation_count': 'approximateInstallationCount',
'approximate_application_count': 'approximateApplicationCount',
'approximate_managed_instance_count': 'approximateManagedInstanceCount',
'time_start': 'timeStart',
'time_end': 'timeEnd',
'time_first_seen': 'timeFirstSeen',
'time_last_seen': 'timeLastSeen'
}
self._id = None
self._fleet_id = None
self._managed_instance_id = None
self._security_status = None
self._release_date = None
self._end_of_support_life_date = None
self._vendor = None
self._distribution = None
self._version = None
self._operating_systems = None
self._approximate_installation_count = None
self._approximate_application_count = None
self._approximate_managed_instance_count = None
self._time_start = None
self._time_end = None
self._time_first_seen = None
self._time_last_seen = None
@property
def id(self):
"""
Gets the id of this JreUsage.
The internal identifier of the Java Runtime.
:return: The id of this JreUsage.
:rtype: str
"""
return self._id
@id.setter
def id(self, id):
"""
Sets the id of this JreUsage.
The internal identifier of the Java Runtime.
:param id: The id of this JreUsage.
:type: str
"""
self._id = id
@property
def fleet_id(self):
"""
Gets the fleet_id of this JreUsage.
The `OCID`__ of the related fleet. This property value is present only for /actions/listJreUsage.
__ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm
:return: The fleet_id of this JreUsage.
:rtype: str
"""
return self._fleet_id
@fleet_id.setter
def fleet_id(self, fleet_id):
"""
Sets the fleet_id of this JreUsage.
The `OCID`__ of the related fleet. This property value is present only for /actions/listJreUsage.
__ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm
:param fleet_id: The fleet_id of this JreUsage.
:type: str
"""
self._fleet_id = fleet_id
@property
def managed_instance_id(self):
"""
Gets the managed_instance_id of this JreUsage.
The `OCID`__ of the related managed instance. This property value is present only for /actions/listJreUsage.
__ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm
:return: The managed_instance_id of this JreUsage.
:rtype: str
"""
return self._managed_instance_id
@managed_instance_id.setter
def managed_instance_id(self, managed_instance_id):
"""
Sets the managed_instance_id of this JreUsage.
The `OCID`__ of the related managed instance. This property value is present only for /actions/listJreUsage.
__ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm
:param managed_instance_id: The managed_instance_id of this JreUsage.
:type: str
"""
self._managed_instance_id = managed_instance_id
@property
def security_status(self):
"""
Gets the security_status of this JreUsage.
The security status of the Java Runtime.
Allowed values for this property are: "UNKNOWN", "UP_TO_DATE", "UPDATE_REQUIRED", "UPGRADE_REQUIRED", 'UNKNOWN_ENUM_VALUE'.
Any unrecognized values returned by a service will be mapped to 'UNKNOWN_ENUM_VALUE'.
:return: The security_status of this JreUsage.
:rtype: str
"""
return self._security_status
@security_status.setter
def security_status(self, security_status):
"""
Sets the security_status of this JreUsage.
The security status of the Java Runtime.
:param security_status: The security_status of this JreUsage.
:type: str
"""
allowed_values = ["UNKNOWN", "UP_TO_DATE", "UPDATE_REQUIRED", "UPGRADE_REQUIRED"]
if not value_allowed_none_or_none_sentinel(security_status, allowed_values):
security_status = 'UNKNOWN_ENUM_VALUE'
self._security_status = security_status
@property
def release_date(self):
"""
Gets the release_date of this JreUsage.
The release date of the Java Runtime (formatted according to `RFC3339`__).
__ https://datatracker.ietf.org/doc/html/rfc3339
:return: The release_date of this JreUsage.
:rtype: datetime
"""
return self._release_date
@release_date.setter
def release_date(self, release_date):
"""
Sets the release_date of this JreUsage.
The release date of the Java Runtime (formatted according to `RFC3339`__).
__ https://datatracker.ietf.org/doc/html/rfc3339
:param release_date: The release_date of this JreUsage.
:type: datetime
"""
self._release_date = release_date
@property
def end_of_support_life_date(self):
"""
Gets the end_of_support_life_date of this JreUsage.
The End of Support Life (EOSL) date of the Java Runtime (formatted according to `RFC3339`__).
__ https://datatracker.ietf.org/doc/html/rfc3339
:return: The end_of_support_life_date of this JreUsage.
:rtype: datetime
"""
return self._end_of_support_life_date
@end_of_support_life_date.setter
def end_of_support_life_date(self, end_of_support_life_date):
"""
Sets the end_of_support_life_date of this JreUsage.
The End of Support Life (EOSL) date of the Java Runtime (formatted according to `RFC3339`__).
__ https://datatracker.ietf.org/doc/html/rfc3339
:param end_of_support_life_date: The end_of_support_life_date of this JreUsage.
:type: datetime
"""
self._end_of_support_life_date = end_of_support_life_date
@property
def vendor(self):
"""
**[Required]** Gets the vendor of this JreUsage.
The vendor of the Java Runtime.
:return: The vendor of this JreUsage.
:rtype: str
"""
return self._vendor
@vendor.setter
def vendor(self, vendor):
"""
Sets the vendor of this JreUsage.
The vendor of the Java Runtime.
:param vendor: The vendor of this JreUsage.
:type: str
"""
self._vendor = vendor
@property
def distribution(self):
"""
**[Required]** Gets the distribution of this JreUsage.
The distribution of a Java Runtime is the name of the lineage of product to which it belongs, for example _Java(TM) SE Runtime Environment_.
:return: The distribution of this JreUsage.
:rtype: str
"""
return self._distribution
@distribution.setter
def distribution(self, distribution):
"""
Sets the distribution of this JreUsage.
The distribution of a Java Runtime is the name of the lineage of product to which it belongs, for example _Java(TM) SE Runtime Environment_.
:param distribution: The distribution of this JreUsage.
:type: str
"""
self._distribution = distribution
@property
def version(self):
"""
**[Required]** Gets the version of this JreUsage.
The version of the Java Runtime.
:return: The version of this JreUsage.
:rtype: str
"""
return self._version
@version.setter
def version(self, version):
"""
Sets the version of this JreUsage.
The version of the Java Runtime.
:param version: The version of this JreUsage.
:type: str
"""
self._version = version
@property
def operating_systems(self):
"""
Gets the operating_systems of this JreUsage.
The operating systems that have this Java Runtime installed.
:return: The operating_systems of this JreUsage.
:rtype: list[oci.jms.models.OperatingSystem]
"""
return self._operating_systems
@operating_systems.setter
def operating_systems(self, operating_systems):
"""
Sets the operating_systems of this JreUsage.
The operating systems that have this Java Runtime installed.
:param operating_systems: The operating_systems of this JreUsage.
:type: list[oci.jms.models.OperatingSystem]
"""
self._operating_systems = operating_systems
@property
def approximate_installation_count(self):
"""
Gets the approximate_installation_count of this JreUsage.
The approximate count of installations that are installations of this Java Runtime.
:return: The approximate_installation_count of this JreUsage.
:rtype: int
"""
return self._approximate_installation_count
@approximate_installation_count.setter
def approximate_installation_count(self, approximate_installation_count):
"""
Sets the approximate_installation_count of this JreUsage.
The approximate count of installations that are installations of this Java Runtime.
:param approximate_installation_count: The approximate_installation_count of this JreUsage.
:type: int
"""
self._approximate_installation_count = approximate_installation_count
@property
def approximate_application_count(self):
"""
Gets the approximate_application_count of this JreUsage.
The approximate count of the applications running on this Java Runtime.
:return: The approximate_application_count of this JreUsage.
:rtype: int
"""
return self._approximate_application_count
@approximate_application_count.setter
def approximate_application_count(self, approximate_application_count):
"""
Sets the approximate_application_count of this JreUsage.
The approximate count of the applications running on this Java Runtime.
:param approximate_application_count: The approximate_application_count of this JreUsage.
:type: int
"""
self._approximate_application_count = approximate_application_count
@property
def approximate_managed_instance_count(self):
"""
Gets the approximate_managed_instance_count of this JreUsage.
The approximate count of the managed instances that report this Java Runtime.
:return: The approximate_managed_instance_count of this JreUsage.
:rtype: int
"""
return self._approximate_managed_instance_count
@approximate_managed_instance_count.setter
def approximate_managed_instance_count(self, approximate_managed_instance_count):
"""
Sets the approximate_managed_instance_count of this JreUsage.
The approximate count of the managed instances that report this Java Runtime.
:param approximate_managed_instance_count: The approximate_managed_instance_count of this JreUsage.
:type: int
"""
self._approximate_managed_instance_count = approximate_managed_instance_count
@property
def time_start(self):
"""
Gets the time_start of this JreUsage.
Lower bound of the specified time period filter. JMS provides a view of the data that is _per day_. The query uses only the date element of the parameter.
:return: The time_start of this JreUsage.
:rtype: datetime
"""
return self._time_start
@time_start.setter
def time_start(self, time_start):
"""
Sets the time_start of this JreUsage.
Lower bound of the specified time period filter. JMS provides a view of the data that is _per day_. The query uses only the date element of the parameter.
:param time_start: The time_start of this JreUsage.
:type: datetime
"""
self._time_start = time_start
@property
def time_end(self):
"""
Gets the time_end of this JreUsage.
Upper bound of the specified time period filter. JMS provides a view of the data that is _per day_. The query uses only the date element of the parameter.
:return: The time_end of this JreUsage.
:rtype: datetime
"""
return self._time_end
@time_end.setter
def time_end(self, time_end):
"""
Sets the time_end of this JreUsage.
Upper bound of the specified time period filter. JMS provides a view of the data that is _per day_. The query uses only the date element of the parameter.
:param time_end: The time_end of this JreUsage.
:type: datetime
"""
self._time_end = time_end
@property
def time_first_seen(self):
"""
Gets the time_first_seen of this JreUsage.
The date and time the resource was _first_ reported to JMS.
This is potentially _before_ the specified time period provided by the filters.
For example, a resource can be first reported to JMS before the start of a specified time period,
if it is also reported during the time period.
:return: The time_first_seen of this JreUsage.
:rtype: datetime
"""
return self._time_first_seen
@time_first_seen.setter
def time_first_seen(self, time_first_seen):
"""
Sets the time_first_seen of this JreUsage.
The date and time the resource was _first_ reported to JMS.
This is potentially _before_ the specified time period provided by the filters.
For example, a resource can be first reported to JMS before the start of a specified time period,
if it is also reported during the time period.
:param time_first_seen: The time_first_seen of this JreUsage.
:type: datetime
"""
self._time_first_seen = time_first_seen
@property
def time_last_seen(self):
"""
Gets the time_last_seen of this JreUsage.
The date and time the resource was _last_ reported to JMS.
This is potentially _after_ the specified time period provided by the filters.
For example, a resource can be last reported to JMS before the start of a specified time period,
if it is also reported during the time period.
:return: The time_last_seen of this JreUsage.
:rtype: datetime
"""
return self._time_last_seen
@time_last_seen.setter
def time_last_seen(self, time_last_seen):
"""
Sets the time_last_seen of this JreUsage.
The date and time the resource was _last_ reported to JMS.
This is potentially _after_ the specified time period provided by the filters.
For example, a resource can be last reported to JMS before the start of a specified time period,
if it is also reported during the time period.
:param time_last_seen: The time_last_seen of this JreUsage.
:type: datetime
"""
self._time_last_seen = time_last_seen
def __repr__(self):
return formatted_flat_dict(self)
def __eq__(self, other):
if other is None:
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
| src/oci/jms/models/jre_usage.py | 21,334 | Java Runtime usage during a specified time period. A Java Runtime is identified by its vendor and version.
Initializes a new JreUsage object with values from keyword arguments.
The following keyword arguments are supported (corresponding to the getters/setters of this class):
:param id:
The value to assign to the id property of this JreUsage.
:type id: str
:param fleet_id:
The value to assign to the fleet_id property of this JreUsage.
:type fleet_id: str
:param managed_instance_id:
The value to assign to the managed_instance_id property of this JreUsage.
:type managed_instance_id: str
:param security_status:
The value to assign to the security_status property of this JreUsage.
Allowed values for this property are: "UNKNOWN", "UP_TO_DATE", "UPDATE_REQUIRED", "UPGRADE_REQUIRED", 'UNKNOWN_ENUM_VALUE'.
Any unrecognized values returned by a service will be mapped to 'UNKNOWN_ENUM_VALUE'.
:type security_status: str
:param release_date:
The value to assign to the release_date property of this JreUsage.
:type release_date: datetime
:param end_of_support_life_date:
The value to assign to the end_of_support_life_date property of this JreUsage.
:type end_of_support_life_date: datetime
:param vendor:
The value to assign to the vendor property of this JreUsage.
:type vendor: str
:param distribution:
The value to assign to the distribution property of this JreUsage.
:type distribution: str
:param version:
The value to assign to the version property of this JreUsage.
:type version: str
:param operating_systems:
The value to assign to the operating_systems property of this JreUsage.
:type operating_systems: list[oci.jms.models.OperatingSystem]
:param approximate_installation_count:
The value to assign to the approximate_installation_count property of this JreUsage.
:type approximate_installation_count: int
:param approximate_application_count:
The value to assign to the approximate_application_count property of this JreUsage.
:type approximate_application_count: int
:param approximate_managed_instance_count:
The value to assign to the approximate_managed_instance_count property of this JreUsage.
:type approximate_managed_instance_count: int
:param time_start:
The value to assign to the time_start property of this JreUsage.
:type time_start: datetime
:param time_end:
The value to assign to the time_end property of this JreUsage.
:type time_end: datetime
:param time_first_seen:
The value to assign to the time_first_seen property of this JreUsage.
:type time_first_seen: datetime
:param time_last_seen:
The value to assign to the time_last_seen property of this JreUsage.
:type time_last_seen: datetime
Gets the approximate_application_count of this JreUsage.
The approximate count of the applications running on this Java Runtime.
:return: The approximate_application_count of this JreUsage.
:rtype: int
Sets the approximate_application_count of this JreUsage.
The approximate count of the applications running on this Java Runtime.
:param approximate_application_count: The approximate_application_count of this JreUsage.
:type: int
Gets the approximate_installation_count of this JreUsage.
The approximate count of installations that are installations of this Java Runtime.
:return: The approximate_installation_count of this JreUsage.
:rtype: int
Sets the approximate_installation_count of this JreUsage.
The approximate count of installations that are installations of this Java Runtime.
:param approximate_installation_count: The approximate_installation_count of this JreUsage.
:type: int
Gets the approximate_managed_instance_count of this JreUsage.
The approximate count of the managed instances that report this Java Runtime.
:return: The approximate_managed_instance_count of this JreUsage.
:rtype: int
Sets the approximate_managed_instance_count of this JreUsage.
The approximate count of the managed instances that report this Java Runtime.
:param approximate_managed_instance_count: The approximate_managed_instance_count of this JreUsage.
:type: int
**[Required]** Gets the distribution of this JreUsage.
The distribution of a Java Runtime is the name of the lineage of product to which it belongs, for example _Java(TM) SE Runtime Environment_.
:return: The distribution of this JreUsage.
:rtype: str
Sets the distribution of this JreUsage.
The distribution of a Java Runtime is the name of the lineage of product to which it belongs, for example _Java(TM) SE Runtime Environment_.
:param distribution: The distribution of this JreUsage.
:type: str
Gets the end_of_support_life_date of this JreUsage.
The End of Support Life (EOSL) date of the Java Runtime (formatted according to `RFC3339`__).
__ https://datatracker.ietf.org/doc/html/rfc3339
:return: The end_of_support_life_date of this JreUsage.
:rtype: datetime
Sets the end_of_support_life_date of this JreUsage.
The End of Support Life (EOSL) date of the Java Runtime (formatted according to `RFC3339`__).
__ https://datatracker.ietf.org/doc/html/rfc3339
:param end_of_support_life_date: The end_of_support_life_date of this JreUsage.
:type: datetime
Gets the fleet_id of this JreUsage.
The `OCID`__ of the related fleet. This property value is present only for /actions/listJreUsage.
__ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm
:return: The fleet_id of this JreUsage.
:rtype: str
Sets the fleet_id of this JreUsage.
The `OCID`__ of the related fleet. This property value is present only for /actions/listJreUsage.
__ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm
:param fleet_id: The fleet_id of this JreUsage.
:type: str
Gets the id of this JreUsage.
The internal identifier of the Java Runtime.
:return: The id of this JreUsage.
:rtype: str
Sets the id of this JreUsage.
The internal identifier of the Java Runtime.
:param id: The id of this JreUsage.
:type: str
Gets the managed_instance_id of this JreUsage.
The `OCID`__ of the related managed instance. This property value is present only for /actions/listJreUsage.
__ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm
:return: The managed_instance_id of this JreUsage.
:rtype: str
Sets the managed_instance_id of this JreUsage.
The `OCID`__ of the related managed instance. This property value is present only for /actions/listJreUsage.
__ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm
:param managed_instance_id: The managed_instance_id of this JreUsage.
:type: str
Gets the operating_systems of this JreUsage.
The operating systems that have this Java Runtime installed.
:return: The operating_systems of this JreUsage.
:rtype: list[oci.jms.models.OperatingSystem]
Sets the operating_systems of this JreUsage.
The operating systems that have this Java Runtime installed.
:param operating_systems: The operating_systems of this JreUsage.
:type: list[oci.jms.models.OperatingSystem]
Gets the release_date of this JreUsage.
The release date of the Java Runtime (formatted according to `RFC3339`__).
__ https://datatracker.ietf.org/doc/html/rfc3339
:return: The release_date of this JreUsage.
:rtype: datetime
Sets the release_date of this JreUsage.
The release date of the Java Runtime (formatted according to `RFC3339`__).
__ https://datatracker.ietf.org/doc/html/rfc3339
:param release_date: The release_date of this JreUsage.
:type: datetime
Gets the security_status of this JreUsage.
The security status of the Java Runtime.
Allowed values for this property are: "UNKNOWN", "UP_TO_DATE", "UPDATE_REQUIRED", "UPGRADE_REQUIRED", 'UNKNOWN_ENUM_VALUE'.
Any unrecognized values returned by a service will be mapped to 'UNKNOWN_ENUM_VALUE'.
:return: The security_status of this JreUsage.
:rtype: str
Sets the security_status of this JreUsage.
The security status of the Java Runtime.
:param security_status: The security_status of this JreUsage.
:type: str
Gets the time_end of this JreUsage.
Upper bound of the specified time period filter. JMS provides a view of the data that is _per day_. The query uses only the date element of the parameter.
:return: The time_end of this JreUsage.
:rtype: datetime
Sets the time_end of this JreUsage.
Upper bound of the specified time period filter. JMS provides a view of the data that is _per day_. The query uses only the date element of the parameter.
:param time_end: The time_end of this JreUsage.
:type: datetime
Gets the time_first_seen of this JreUsage.
The date and time the resource was _first_ reported to JMS.
This is potentially _before_ the specified time period provided by the filters.
For example, a resource can be first reported to JMS before the start of a specified time period,
if it is also reported during the time period.
:return: The time_first_seen of this JreUsage.
:rtype: datetime
Sets the time_first_seen of this JreUsage.
The date and time the resource was _first_ reported to JMS.
This is potentially _before_ the specified time period provided by the filters.
For example, a resource can be first reported to JMS before the start of a specified time period,
if it is also reported during the time period.
:param time_first_seen: The time_first_seen of this JreUsage.
:type: datetime
Gets the time_last_seen of this JreUsage.
The date and time the resource was _last_ reported to JMS.
This is potentially _after_ the specified time period provided by the filters.
For example, a resource can be last reported to JMS before the start of a specified time period,
if it is also reported during the time period.
:return: The time_last_seen of this JreUsage.
:rtype: datetime
Sets the time_last_seen of this JreUsage.
The date and time the resource was _last_ reported to JMS.
This is potentially _after_ the specified time period provided by the filters.
For example, a resource can be last reported to JMS before the start of a specified time period,
if it is also reported during the time period.
:param time_last_seen: The time_last_seen of this JreUsage.
:type: datetime
Gets the time_start of this JreUsage.
Lower bound of the specified time period filter. JMS provides a view of the data that is _per day_. The query uses only the date element of the parameter.
:return: The time_start of this JreUsage.
:rtype: datetime
Sets the time_start of this JreUsage.
Lower bound of the specified time period filter. JMS provides a view of the data that is _per day_. The query uses only the date element of the parameter.
:param time_start: The time_start of this JreUsage.
:type: datetime
**[Required]** Gets the vendor of this JreUsage.
The vendor of the Java Runtime.
:return: The vendor of this JreUsage.
:rtype: str
Sets the vendor of this JreUsage.
The vendor of the Java Runtime.
:param vendor: The vendor of this JreUsage.
:type: str
**[Required]** Gets the version of this JreUsage.
The version of the Java Runtime.
:return: The version of this JreUsage.
:rtype: str
Sets the version of this JreUsage.
The version of the Java Runtime.
:param version: The version of this JreUsage.
:type: str
coding: utf-8 Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. noqa: F401: A constant which can be used with the security_status property of a JreUsage.: This constant has a value of "UNKNOWN": A constant which can be used with the security_status property of a JreUsage.: This constant has a value of "UP_TO_DATE": A constant which can be used with the security_status property of a JreUsage.: This constant has a value of "UPDATE_REQUIRED": A constant which can be used with the security_status property of a JreUsage.: This constant has a value of "UPGRADE_REQUIRED" | 11,938 | en | 0.778658 |
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import collections
import functools
from functools import partial
import itertools
import operator
from typing import cast, Optional
import unittest
from unittest import SkipTest
import warnings
from absl.testing import absltest
from absl.testing import parameterized
import numpy as onp
import jax
import jax.ops
from jax import api
from jax import lax
from jax import linear_util
from jax import numpy as jnp
from jax import test_util as jtu
from jax import dtypes
from jax import tree_util
from jax.interpreters import partial_eval, xla
from jax.test_util import check_grads
from jax.config import config
config.parse_flags_with_absl()
FLAGS = config.FLAGS
nonempty_nonscalar_array_shapes = [(4,), (3, 4), (3, 1), (1, 4), (2, 1, 4), (2, 3, 4)]
nonempty_array_shapes = [()] + nonempty_nonscalar_array_shapes
one_dim_array_shapes = [(1,), (6,), (12,)]
empty_array_shapes = [(0,), (0, 4), (3, 0),]
scalar_shapes = [jtu.NUMPY_SCALAR_SHAPE, jtu.PYTHON_SCALAR_SHAPE]
array_shapes = nonempty_array_shapes + empty_array_shapes
nonzerodim_shapes = nonempty_nonscalar_array_shapes + empty_array_shapes
nonempty_shapes = scalar_shapes + nonempty_array_shapes
all_shapes = scalar_shapes + array_shapes
def supported_dtypes(dtypes):
return [t for t in dtypes if t in jtu.supported_dtypes()]
float_dtypes = supported_dtypes([jnp.bfloat16, onp.float16, onp.float32,
onp.float64])
complex_dtypes = [onp.complex64, onp.complex128]
int_dtypes = [onp.int32, onp.int64]
uint_dtypes = [onp.uint32, onp.uint64]
unsigned_dtypes = [onp.uint32, onp.uint64]
bool_dtypes = [onp.bool_]
default_dtypes = float_dtypes + int_dtypes
inexact_dtypes = float_dtypes + complex_dtypes
number_dtypes = float_dtypes + complex_dtypes + int_dtypes
all_dtypes = number_dtypes + bool_dtypes
python_scalar_dtypes = [jnp.bool_, jnp.int_, jnp.float_, jnp.complex_]
def _valid_dtypes_for_shape(shape, dtypes):
# Not all (shape, dtype) pairs are valid. In particular, Python scalars only
# have one type in each category (float, bool, etc.)
if shape is jtu.PYTHON_SCALAR_SHAPE:
return [t for t in dtypes if t in python_scalar_dtypes]
return dtypes
def _shape_and_dtypes(shapes, dtypes):
for shape in shapes:
for dtype in _valid_dtypes_for_shape(shape, dtypes):
yield (shape, dtype)
OpRecord = collections.namedtuple(
"OpRecord",
["name", "nargs", "dtypes", "shapes", "rng_factory", "diff_modes",
"test_name", "check_dtypes", "tolerance", "inexact"])
def op_record(name, nargs, dtypes, shapes, rng_factory, diff_modes,
test_name=None, check_dtypes=True, tolerance=None, inexact=False):
test_name = test_name or name
return OpRecord(name, nargs, dtypes, shapes, rng_factory, diff_modes,
test_name, check_dtypes, tolerance, inexact)
JAX_ONE_TO_ONE_OP_RECORDS = [
op_record("abs", 1, number_dtypes, all_shapes, jtu.rand_default, ["rev"]),
op_record("add", 2, all_dtypes, all_shapes, jtu.rand_default, ["rev"]),
op_record("ceil", 1, float_dtypes, all_shapes, jtu.rand_default, []),
op_record("conj", 1, number_dtypes, all_shapes, jtu.rand_default, ["rev"]),
op_record("equal", 2, all_dtypes, all_shapes, jtu.rand_some_equal, []),
op_record("exp", 1, number_dtypes, all_shapes, jtu.rand_default, ["rev"],
inexact=True),
op_record("fabs", 1, float_dtypes, all_shapes, jtu.rand_default, ["rev"]),
op_record("float_power", 2, inexact_dtypes, all_shapes,
partial(jtu.rand_default, scale=1), ["rev"],
tolerance={jnp.bfloat16: 1e-2, onp.float32: 1e-3,
onp.float64: 1e-12, onp.complex64: 2e-4,
onp.complex128: 1e-12}, check_dtypes=False),
op_record("floor", 1, float_dtypes, all_shapes, jtu.rand_default, []),
op_record("greater", 2, all_dtypes, all_shapes, jtu.rand_some_equal, []),
op_record("greater_equal", 2, all_dtypes, all_shapes, jtu.rand_some_equal, []),
op_record("less", 2, all_dtypes, all_shapes, jtu.rand_some_equal, []),
op_record("less_equal", 2, all_dtypes, all_shapes, jtu.rand_some_equal, []),
op_record("log", 1, number_dtypes, all_shapes, jtu.rand_positive, ["rev"],
inexact=True),
op_record("logical_and", 2, all_dtypes, all_shapes, jtu.rand_bool, []),
op_record("logical_not", 1, all_dtypes, all_shapes, jtu.rand_bool, []),
op_record("logical_or", 2, all_dtypes, all_shapes, jtu.rand_bool, []),
op_record("logical_xor", 2, all_dtypes, all_shapes, jtu.rand_bool, []),
op_record("maximum", 2, all_dtypes, all_shapes, jtu.rand_some_inf, []),
op_record("minimum", 2, all_dtypes, all_shapes, jtu.rand_some_inf, []),
op_record("multiply", 2, all_dtypes, all_shapes, jtu.rand_default, ["rev"]),
op_record("negative", 1, number_dtypes, all_shapes, jtu.rand_default, ["rev"]),
op_record("nextafter", 2, [f for f in float_dtypes if f != jnp.bfloat16],
all_shapes, jtu.rand_default, ["rev"], inexact=True, tolerance=0),
op_record("not_equal", 2, all_dtypes, all_shapes, jtu.rand_some_equal, ["rev"]),
op_record("array_equal", 2, number_dtypes, all_shapes, jtu.rand_some_equal, ["rev"]),
op_record("reciprocal", 1, inexact_dtypes, all_shapes, jtu.rand_default, []),
op_record("subtract", 2, number_dtypes, all_shapes, jtu.rand_default, ["rev"]),
op_record("signbit", 1, default_dtypes + bool_dtypes, all_shapes,
jtu.rand_some_inf_and_nan, ["rev"]),
op_record("trunc", 1, float_dtypes, all_shapes, jtu.rand_some_inf_and_nan, []),
op_record("sin", 1, number_dtypes, all_shapes, jtu.rand_default, ["rev"],
inexact=True),
op_record("cos", 1, number_dtypes, all_shapes, jtu.rand_default, ["rev"],
inexact=True),
op_record("tan", 1, number_dtypes, all_shapes,
partial(jtu.rand_uniform, -1.5, 1.5), ["rev"], inexact=True),
op_record("sinh", 1, number_dtypes, all_shapes, jtu.rand_default, ["rev"],
inexact=True),
op_record("cosh", 1, number_dtypes, all_shapes, jtu.rand_default, ["rev"],
inexact=True),
# TODO(b/142975473): on CPU, tanh for complex128 is only accurate to
# ~float32 precision.
# TODO(b/143135720): on GPU, tanh has only ~float32 precision.
op_record("tanh", 1, number_dtypes, all_shapes, jtu.rand_default, ["rev"],
tolerance={onp.float64: 1e-7, onp.complex128: 1e-7},
inexact=True),
op_record("arcsin", 1, float_dtypes, all_shapes, jtu.rand_small, ["rev"],
inexact=True),
op_record("arccos", 1, float_dtypes, all_shapes, jtu.rand_small, ["rev"],
inexact=True),
op_record("arctan", 1, float_dtypes, all_shapes, jtu.rand_small, ["rev"],
inexact=True),
op_record("arctan2", 2, float_dtypes, all_shapes, jtu.rand_small, ["rev"],
inexact=True),
op_record("arcsinh", 1, number_dtypes, all_shapes, jtu.rand_positive, ["rev"],
inexact=True),
op_record("arccosh", 1, number_dtypes, all_shapes, jtu.rand_positive, ["rev"],
inexact=True),
op_record("arctanh", 1, number_dtypes, all_shapes, jtu.rand_small, ["rev"],
inexact=True),
]
JAX_COMPOUND_OP_RECORDS = [
# angle has inconsistent 32/64-bit return types across numpy versions.
op_record("angle", 1, number_dtypes, all_shapes, jtu.rand_default, [],
check_dtypes=False, inexact=True),
op_record("atleast_1d", 1, default_dtypes, all_shapes, jtu.rand_default, []),
op_record("atleast_2d", 1, default_dtypes, all_shapes, jtu.rand_default, []),
op_record("atleast_3d", 1, default_dtypes, all_shapes, jtu.rand_default, []),
op_record("cbrt", 1, default_dtypes, all_shapes, jtu.rand_default, ["rev"],
inexact=True),
op_record("conjugate", 1, number_dtypes, all_shapes, jtu.rand_default, ["rev"]),
op_record("deg2rad", 1, float_dtypes, all_shapes, jtu.rand_default, []),
op_record("divide", 2, number_dtypes, all_shapes, jtu.rand_nonzero, ["rev"],
inexact=True),
op_record("divmod", 2, int_dtypes + float_dtypes, all_shapes,
jtu.rand_nonzero, []),
op_record("exp2", 1, number_dtypes, all_shapes, jtu.rand_default, ["rev"],
tolerance={jnp.bfloat16: 2e-2, onp.float16: 1e-2}, inexact=True),
# TODO(b/142975473): on CPU, expm1 for float64 is only accurate to ~float32
# precision.
op_record("expm1", 1, number_dtypes, all_shapes, jtu.rand_positive, [],
test_name="expm1_large", tolerance={onp.float64: 1e-8}, inexact=True),
op_record("expm1", 1, number_dtypes, all_shapes, jtu.rand_small_positive,
[], tolerance={onp.float64: 1e-8}, inexact=True),
op_record("fix", 1, float_dtypes, all_shapes, jtu.rand_default, []),
op_record("floor_divide", 2, number_dtypes, all_shapes,
jtu.rand_nonzero, ["rev"]),
op_record("floor_divide", 2, uint_dtypes, all_shapes,
jtu.rand_nonzero, ["rev"]),
op_record("heaviside", 2, default_dtypes, all_shapes, jtu.rand_default, [],
inexact=True),
op_record("hypot", 2, default_dtypes, all_shapes, jtu.rand_default, [],
inexact=True),
op_record("kron", 2, number_dtypes, nonempty_shapes, jtu.rand_default, []),
op_record("outer", 2, number_dtypes, all_shapes, jtu.rand_default, []),
op_record("imag", 1, number_dtypes, all_shapes, jtu.rand_some_inf, []),
op_record("iscomplex", 1, number_dtypes, all_shapes, jtu.rand_some_inf, []),
op_record("isfinite", 1, inexact_dtypes, all_shapes, jtu.rand_some_inf_and_nan, []),
op_record("isinf", 1, inexact_dtypes, all_shapes, jtu.rand_some_inf_and_nan, []),
op_record("isnan", 1, inexact_dtypes, all_shapes, jtu.rand_some_inf_and_nan, []),
op_record("isneginf", 1, float_dtypes, all_shapes, jtu.rand_some_inf_and_nan, []),
op_record("isposinf", 1, float_dtypes, all_shapes, jtu.rand_some_inf_and_nan, []),
op_record("isreal", 1, number_dtypes, all_shapes, jtu.rand_some_inf, []),
op_record("isrealobj", 1, number_dtypes, all_shapes, jtu.rand_some_inf, []),
op_record("log2", 1, number_dtypes, all_shapes, jtu.rand_positive, ["rev"],
inexact=True),
op_record("log10", 1, number_dtypes, all_shapes, jtu.rand_positive, ["rev"],
inexact=True),
op_record("log1p", 1, number_dtypes, all_shapes, jtu.rand_positive, [],
test_name="log1p_large", tolerance={onp.float64: 1e-12},
inexact=True),
op_record("log1p", 1, number_dtypes, all_shapes, jtu.rand_small_positive, [],
tolerance={onp.float64: 1e-12}, inexact=True),
op_record("logaddexp", 2, float_dtypes, all_shapes,
jtu.rand_some_inf_and_nan, ["rev"],
tolerance={onp.float64: 1e-12}, inexact=True),
op_record("logaddexp2", 2, float_dtypes, all_shapes,
jtu.rand_some_inf_and_nan, ["rev"],
tolerance={onp.float16: 1e-2}, inexact=True),
op_record("polyval", 2, number_dtypes, nonempty_nonscalar_array_shapes,
jtu.rand_default, [], check_dtypes=False,
tolerance={onp.float16: 1e-2, onp.float64: 1e-12}),
op_record("positive", 1, number_dtypes, all_shapes, jtu.rand_default, ["rev"]),
op_record("power", 2, number_dtypes, all_shapes, jtu.rand_positive, ["rev"],
tolerance={onp.complex128: 1e-14}),
op_record("rad2deg", 1, float_dtypes, all_shapes, jtu.rand_default, []),
op_record("ravel", 1, all_dtypes, all_shapes, jtu.rand_default, ["rev"]),
op_record("real", 1, number_dtypes, all_shapes, jtu.rand_some_inf, []),
op_record("remainder", 2, default_dtypes, all_shapes, jtu.rand_nonzero, [],
tolerance={onp.float16: 1e-2}),
op_record("mod", 2, default_dtypes, all_shapes, jtu.rand_nonzero, []),
op_record("sign", 1, number_dtypes + uint_dtypes, all_shapes,
jtu.rand_some_inf_and_nan, []),
op_record('copysign', 2, default_dtypes, all_shapes, jtu.rand_some_inf_and_nan, [],
check_dtypes=False),
op_record("sinc", 1, [t for t in number_dtypes if t != jnp.bfloat16],
all_shapes, jtu.rand_default, ["rev"],
tolerance={onp.complex64: 1e-5}, inexact=True,
check_dtypes=False),
op_record("square", 1, number_dtypes, all_shapes, jtu.rand_default, ["rev"]),
op_record("sqrt", 1, number_dtypes, all_shapes, jtu.rand_positive, ["rev"],
inexact=True),
op_record("transpose", 1, all_dtypes, all_shapes, jtu.rand_default, ["rev"],
check_dtypes=False),
op_record("true_divide", 2, all_dtypes, all_shapes, jtu.rand_nonzero,
["rev"], inexact=True),
op_record("diff", 1, number_dtypes, nonzerodim_shapes, jtu.rand_default, ["rev"]),
]
JAX_BITWISE_OP_RECORDS = [
op_record("bitwise_and", 2, int_dtypes + unsigned_dtypes, all_shapes,
jtu.rand_bool, []),
op_record("bitwise_not", 1, int_dtypes + unsigned_dtypes, all_shapes,
jtu.rand_bool, []),
op_record("bitwise_or", 2, int_dtypes + unsigned_dtypes, all_shapes,
jtu.rand_bool, []),
op_record("bitwise_xor", 2, int_dtypes + unsigned_dtypes, all_shapes,
jtu.rand_bool, []),
]
JAX_REDUCER_RECORDS = [
op_record("mean", 1, number_dtypes, nonempty_shapes, jtu.rand_default, [],
inexact=True),
op_record("prod", 1, all_dtypes, all_shapes, jtu.rand_small_positive, []),
op_record("sum", 1, all_dtypes, all_shapes, jtu.rand_default, []),
op_record("nanmean", 1, inexact_dtypes, nonempty_shapes, jtu.rand_some_nan,
[], inexact=True),
op_record("nanprod", 1, inexact_dtypes, all_shapes, jtu.rand_some_nan, []),
op_record("nansum", 1, number_dtypes, all_shapes, jtu.rand_some_nan, []),
]
JAX_REDUCER_NO_DTYPE_RECORDS = [
op_record("all", 1, all_dtypes, all_shapes, jtu.rand_some_zero, []),
op_record("any", 1, all_dtypes, all_shapes, jtu.rand_some_zero, []),
op_record("max", 1, all_dtypes, nonempty_shapes, jtu.rand_default, []),
op_record("min", 1, all_dtypes, nonempty_shapes, jtu.rand_default, []),
op_record("var", 1, all_dtypes, nonempty_shapes, jtu.rand_default, [],
inexact=True),
op_record("std", 1, all_dtypes, nonempty_shapes, jtu.rand_default, [],
inexact=True),
]
JAX_ARGMINMAX_RECORDS = [
op_record("argmin", 1, all_dtypes, nonempty_shapes, jtu.rand_some_equal, []),
op_record("argmax", 1, all_dtypes, nonempty_shapes, jtu.rand_some_equal, []),
]
JAX_OPERATOR_OVERLOADS = [
op_record("__add__", 2, number_dtypes, all_shapes, jtu.rand_default, []),
op_record("__sub__", 2, number_dtypes, all_shapes, jtu.rand_default, []),
op_record("__mul__", 2, number_dtypes, all_shapes, jtu.rand_default, []),
op_record("__eq__", 2, number_dtypes, all_shapes, jtu.rand_default, []),
op_record("__ne__", 2, number_dtypes, all_shapes, jtu.rand_default, []),
op_record("__lt__", 2, default_dtypes, all_shapes, jtu.rand_default, []),
op_record("__le__", 2, default_dtypes, all_shapes, jtu.rand_default, []),
op_record("__gt__", 2, default_dtypes, all_shapes, jtu.rand_default, []),
op_record("__ge__", 2, default_dtypes, all_shapes, jtu.rand_default, []),
op_record("__pos__", 1, number_dtypes, all_shapes, jtu.rand_default, []),
op_record("__neg__", 1, number_dtypes, all_shapes, jtu.rand_default, []),
op_record("__pow__", 2, inexact_dtypes, all_shapes, jtu.rand_positive, [],
tolerance={onp.float32: 2e-4, onp.complex64: 2e-4, onp.complex128: 1e-14}),
op_record("__mod__", 2, default_dtypes, all_shapes, jtu.rand_nonzero, [],
tolerance={onp.float16: 1e-1}),
op_record("__floordiv__", 2, default_dtypes, all_shapes,
jtu.rand_nonzero, []),
op_record("__truediv__", 2, number_dtypes, all_shapes, jtu.rand_nonzero, [],
inexact=True),
op_record("__abs__", 1, number_dtypes, all_shapes, jtu.rand_default, []),
# TODO(mattjj): __invert__ fails on bool dtypes because ~True == -2
op_record("__invert__", 1, int_dtypes, all_shapes, jtu.rand_default, []),
# TODO(mattjj): investigate these failures
# op_record("__or__", 2, number_dtypes, all_shapes, jtu.rand_bool, []),
# op_record("__and__", 2, number_dtypes, all_shapes, jtu.rand_default, []),
# op_record("__xor__", 2, number_dtypes, all_shapes, jtu.rand_bool, []),
# op_record("__divmod__", 2, number_dtypes, all_shapes, jtu.rand_nonzero, []),
# TODO(mattjj): lshift, rshift
]
JAX_RIGHT_OPERATOR_OVERLOADS = [
op_record("__radd__", 2, number_dtypes, all_shapes, jtu.rand_default, []),
op_record("__rsub__", 2, number_dtypes, all_shapes, jtu.rand_default, []),
op_record("__rmul__", 2, number_dtypes, all_shapes, jtu.rand_default, []),
op_record("__rpow__", 2, inexact_dtypes, all_shapes, jtu.rand_positive, [],
tolerance={onp.float32: 2e-4, onp.complex64: 1e-3}),
op_record("__rmod__", 2, default_dtypes, all_shapes, jtu.rand_nonzero, [],
tolerance={onp.float16: 1e-1}),
op_record("__rfloordiv__", 2, default_dtypes, all_shapes,
jtu.rand_nonzero, []),
op_record("__rtruediv__", 2, number_dtypes, all_shapes, jtu.rand_nonzero, [],
inexact=True),
# op_record("__ror__", 2, number_dtypes, all_shapes, jtu.rand_bool, []),
# op_record("__rand__", 2, number_dtypes, all_shapes, jtu.rand_default, []),
# op_record("__rxor__", 2, number_dtypes, all_shapes, jtu.rand_bool, []),
# op_record("__rdivmod__", 2, number_dtypes, all_shapes, jtu.rand_nonzero, []),
]
class _OverrideEverything(object):
pass
for rec in JAX_OPERATOR_OVERLOADS + JAX_RIGHT_OPERATOR_OVERLOADS:
if rec.nargs == 2:
setattr(_OverrideEverything, rec.name, lambda self, other: self)
class _OverrideNothing(object):
pass
for rec in JAX_OPERATOR_OVERLOADS + JAX_RIGHT_OPERATOR_OVERLOADS:
if rec.nargs == 2:
setattr(_OverrideNothing, rec.name, lambda self, other: NotImplemented)
numpy_version = tuple(map(int, onp.version.version.split('.')))
if numpy_version >= (1, 15):
JAX_COMPOUND_OP_RECORDS += [
op_record("isclose", 2, [t for t in all_dtypes if t != jnp.bfloat16],
all_shapes, jtu.rand_small_positive, []),
op_record("gcd", 2, int_dtypes, all_shapes, jtu.rand_default, []),
op_record("lcm", 2, int_dtypes, all_shapes, jtu.rand_default, []),
]
JAX_REDUCER_NO_DTYPE_RECORDS += [
op_record("ptp", 1, number_dtypes, nonempty_shapes, jtu.rand_default, []),
]
CombosWithReplacement = itertools.combinations_with_replacement
def _dtypes_are_compatible_for_bitwise_ops(args):
if len(args) <= 1:
return True
is_signed = lambda dtype: jnp.issubdtype(dtype, onp.signedinteger)
width = lambda dtype: jnp.iinfo(dtype).bits
x, y = args
if width(x) > width(y):
x, y = y, x
# The following condition seems a little ad hoc, but seems to capture what
# numpy actually implements.
return (
is_signed(x) == is_signed(y)
or (width(x) == 32 and width(y) == 32)
or (width(x) == 32 and width(y) == 64 and is_signed(y)))
def _shapes_are_broadcast_compatible(shapes):
accumulator = onp.zeros([])
for shape in shapes:
try:
accumulator = accumulator + onp.zeros(shape)
except ValueError:
return False
return True
def _shapes_are_equal_length(shapes):
return all(len(shape) == len(shapes[0]) for shape in shapes[1:])
def _promote_like_jnp(fun, inexact=False):
"""Decorator that promotes the arguments of `fun` to `jnp.result_type(*args)`.
jnp and onp have different type promotion semantics; this decorator allows
tests make an onp reference implementation act more like an jnp
implementation.
"""
def wrapper(*args, **kw):
flat_args = tree_util.tree_leaves(args)
if inexact and not any(jnp.issubdtype(jnp.result_type(x), jnp.inexact)
for x in flat_args):
dtype = jnp.result_type(jnp.float_, *flat_args)
else:
dtype = jnp.result_type(*flat_args)
args = tree_util.tree_map(lambda a: onp.asarray(a, dtype), args)
return fun(*args, **kw)
return wrapper
class LaxBackedNumpyTests(jtu.JaxTestCase):
"""Tests for LAX-backed Numpy implementation."""
def _GetArgsMaker(self, rng, shapes, dtypes, onp_arrays=True):
def f():
out = [rng(shape, dtype or jnp.float_)
for shape, dtype in zip(shapes, dtypes)]
if onp_arrays:
return out
return [jnp.asarray(a) if isinstance(a, (onp.ndarray, onp.generic)) else a
for a in out]
return f
@parameterized.named_parameters(itertools.chain.from_iterable(
jtu.cases_from_list(
{"testcase_name": jtu.format_test_name_suffix(rec.test_name, shapes,
dtypes),
"rng_factory": rec.rng_factory, "shapes": shapes, "dtypes": dtypes,
"onp_op": getattr(onp, rec.name), "jnp_op": getattr(jnp, rec.name),
"check_dtypes": rec.check_dtypes, "tolerance": rec.tolerance,
"inexact": rec.inexact}
for shapes in filter(
_shapes_are_broadcast_compatible,
CombosWithReplacement(rec.shapes, rec.nargs))
for dtypes in itertools.product(
*(_valid_dtypes_for_shape(s, rec.dtypes) for s in shapes)))
for rec in itertools.chain(JAX_ONE_TO_ONE_OP_RECORDS,
JAX_COMPOUND_OP_RECORDS)))
def testOp(self, onp_op, jnp_op, rng_factory, shapes, dtypes, check_dtypes,
tolerance, inexact):
if onp_op is onp.float_power:
onp_op = jtu.ignore_warning(category=RuntimeWarning,
message="invalid value.*")(onp_op)
rng = rng_factory()
args_maker = self._GetArgsMaker(rng, shapes, dtypes, onp_arrays=False)
tol = max(jtu.tolerance(dtype, tolerance) for dtype in dtypes)
tol = functools.reduce(jtu.join_tolerance,
[tolerance, tol, jtu.default_tolerance()])
self._CheckAgainstNumpy(_promote_like_jnp(onp_op, inexact), jnp_op,
args_maker, check_dtypes=check_dtypes, tol=tol)
self._CompileAndCheck(jnp_op, args_maker, check_dtypes=check_dtypes,
atol=tol, rtol=tol)
@parameterized.named_parameters(itertools.chain.from_iterable(
jtu.cases_from_list(
{"testcase_name": jtu.format_test_name_suffix(rec.test_name, shapes,
dtypes),
"rng_factory": rec.rng_factory, "shapes": shapes, "dtypes": dtypes, "name": rec.name,
"tol": rec.tolerance}
for shapes in filter(
_shapes_are_broadcast_compatible,
CombosWithReplacement(rec.shapes, rec.nargs))
for dtypes in itertools.product(
*(_valid_dtypes_for_shape(s, rec.dtypes) for s in shapes)))
for rec in JAX_OPERATOR_OVERLOADS))
def testOperatorOverload(self, name, rng_factory, shapes, dtypes, tol):
rng = rng_factory()
# onp and jnp arrays have different type promotion rules; force the use of
# jnp arrays.
args_maker = self._GetArgsMaker(rng, shapes, dtypes, onp_arrays=False)
fun = lambda *xs: getattr(operator, name.strip('_'))(*xs)
scalar_arg = (jtu.PYTHON_SCALAR_SHAPE in shapes or
jtu.NUMPY_SCALAR_SHAPE in shapes or
() in shapes)
empty_shape = any(isinstance(s, tuple) and 0 in s for s in shapes)
self._CompileAndCheck(
fun, args_maker, check_dtypes=True, #not scalar_arg and not empty_shape,
atol=tol, rtol=tol)
@parameterized.named_parameters(itertools.chain.from_iterable(
jtu.cases_from_list(
{"testcase_name": jtu.format_test_name_suffix(rec.test_name, shapes,
dtypes),
"rng_factory": rec.rng_factory, "shapes": shapes, "dtypes": dtypes, "name": rec.name,
"op_tolerance": rec.tolerance}
for shapes in filter(
_shapes_are_broadcast_compatible,
CombosWithReplacement(rec.shapes, rec.nargs))
for dtypes in itertools.product(
*(_valid_dtypes_for_shape(s, rec.dtypes) for s in shapes)))
for rec in JAX_RIGHT_OPERATOR_OVERLOADS))
def testRightOperatorOverload(self, name, rng_factory, shapes, dtypes,
op_tolerance):
if shapes[1] is jtu.PYTHON_SCALAR_SHAPE:
raise SkipTest("scalars not implemented") # TODO(mattjj): clean up
rng = rng_factory()
args_maker = self._GetArgsMaker(rng, shapes, dtypes, onp_arrays=False)
fun = lambda fst, snd: getattr(snd, name)(fst)
tol = max(jtu.tolerance(dtype, op_tolerance) for dtype in dtypes)
scalar_arg = (jtu.PYTHON_SCALAR_SHAPE in shapes or
jtu.NUMPY_SCALAR_SHAPE in shapes or
() in shapes)
empty_shape = any(isinstance(s, tuple) and 0 in s for s in shapes)
self._CompileAndCheck(
fun, args_maker, check_dtypes=True, # not scalar_arg and not empty_shape,
atol=tol, rtol=tol)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": rec.test_name + "_{}".format(dtype),
"rng_factory": rec.rng_factory,
"op_name": rec.name, "dtype": dtype}
for rec in JAX_OPERATOR_OVERLOADS if rec.nargs == 2
for dtype in rec.dtypes))
def testBinaryOperatorDefers(self, op_name, rng_factory, dtype):
rng = rng_factory()
arg = jax.device_put(rng((), dtype))
op = getattr(operator, op_name)
other = _OverrideEverything()
assert op(other, arg) is other
assert op(arg, other) is other
other = _OverrideNothing()
if op_name == "__eq__":
assert op(other, arg) is False
assert op(arg, other) is False
elif op_name == "__ne__":
assert op(other, arg) is True
assert op(arg, other) is True
else:
with self.assertRaises(TypeError):
op(other, arg)
with self.assertRaises(TypeError):
op(arg, other)
@parameterized.named_parameters(itertools.chain.from_iterable(
jtu.cases_from_list(
{"testcase_name": jtu.format_test_name_suffix(
rec.test_name, shapes, dtypes),
"rng_factory": rec.rng_factory, "shapes": shapes, "dtypes": dtypes,
"onp_op": getattr(onp, rec.name), "jnp_op": getattr(jnp, rec.name)}
for shapes in filter(
_shapes_are_broadcast_compatible,
CombosWithReplacement(rec.shapes, rec.nargs))
for dtypes in filter(
_dtypes_are_compatible_for_bitwise_ops,
CombosWithReplacement(rec.dtypes, rec.nargs)))
for rec in JAX_BITWISE_OP_RECORDS))
def testBitwiseOp(self, onp_op, jnp_op, rng_factory, shapes, dtypes):
rng = rng_factory()
if not FLAGS.jax_enable_x64 and any(
jnp.iinfo(dtype).bits == 64 for dtype in dtypes):
self.skipTest("x64 types are disabled by jax_enable_x64")
args_maker = self._GetArgsMaker(rng, shapes, dtypes)
self._CheckAgainstNumpy(onp_op, jnp_op, args_maker,
check_dtypes=jtu.PYTHON_SCALAR_SHAPE not in shapes)
self._CompileAndCheck(jnp_op, args_maker, check_dtypes=True)
@parameterized.named_parameters(itertools.chain.from_iterable(
jtu.cases_from_list(
{"testcase_name": "{}_inshape={}_axis={}_dtype={}_keepdims={}".format(
rec.test_name.capitalize(),
jtu.format_shape_dtype_string(shape, dtype), axis,
"None" if out_dtype is None else onp.dtype(out_dtype).name, keepdims),
"rng_factory": rec.rng_factory, "shape": shape, "dtype": dtype, "out_dtype": out_dtype,
"onp_op": getattr(onp, rec.name), "jnp_op": getattr(jnp, rec.name),
"axis": axis, "keepdims": keepdims, "inexact": rec.inexact}
for shape in rec.shapes for dtype in rec.dtypes
for out_dtype in [None] + rec.dtypes
for axis in list(range(-len(shape), len(shape))) + [None]
for keepdims in [False, True])
for rec in JAX_REDUCER_RECORDS))
def testReducer(self, onp_op, jnp_op, rng_factory, shape, dtype, out_dtype,
axis, keepdims, inexact):
rng = rng_factory()
@jtu.ignore_warning(category=onp.ComplexWarning)
@jtu.ignore_warning(category=RuntimeWarning,
message="mean of empty slice.*")
def onp_fun(x):
x_cast = x if dtype != jnp.bfloat16 else x.astype(onp.float32)
t = out_dtype if out_dtype != jnp.bfloat16 else onp.float32
return onp_op(x_cast, axis, dtype=t, keepdims=keepdims)
onp_fun = _promote_like_jnp(onp_fun, inexact)
jnp_fun = lambda x: jnp_op(x, axis, dtype=out_dtype, keepdims=keepdims)
jnp_fun = jtu.ignore_warning(category=jnp.ComplexWarning)(jnp_fun)
args_maker = lambda: [rng(shape, dtype)]
tol_spec = {onp.float16: 1e-2, onp.float32: 1e-3, onp.complex64: 1e-3,
onp.float64: 1e-5, onp.complex128: 1e-5}
tol = jtu.tolerance(dtype, tol_spec)
tol = max(tol, jtu.tolerance(out_dtype, tol_spec)) if out_dtype else tol
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker,
check_dtypes=jnp.bfloat16 not in (dtype, out_dtype),
tol=tol)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True, atol=tol,
rtol=tol)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "{}_inshape={}_axis={}_keepdims={}".format(
rec.test_name.capitalize(),
jtu.format_shape_dtype_string(shape, dtype), axis, keepdims),
"rng_factory": rec.rng_factory, "shape": shape, "dtype": dtype,
"onp_op": getattr(onp, rec.name), "jnp_op": getattr(jnp, rec.name),
"axis": axis, "keepdims": keepdims, "inexact": rec.inexact}
for rec in JAX_REDUCER_NO_DTYPE_RECORDS
for shape in rec.shapes for dtype in rec.dtypes
for axis in list(range(-len(shape), len(shape))) + [None]
for keepdims in [False, True]))
def testReducerNoDtype(self, onp_op, jnp_op, rng_factory, shape, dtype, axis,
keepdims, inexact):
rng = rng_factory()
onp_fun = lambda x: onp_op(x, axis, keepdims=keepdims)
onp_fun = _promote_like_jnp(onp_fun, inexact)
onp_fun = jtu.ignore_warning(category=onp.ComplexWarning)(onp_fun)
jnp_fun = lambda x: jnp_op(x, axis, keepdims=keepdims)
jnp_fun = jtu.ignore_warning(category=jnp.ComplexWarning)(jnp_fun)
args_maker = lambda: [rng(shape, dtype)]
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_shape={}_axis={}".format(
jtu.format_shape_dtype_string(shape, dtype), axis),
"shape": shape, "dtype": dtype, "axis": axis}
for shape in all_shapes for dtype in all_dtypes
for axis in list(range(-len(shape), len(shape))) + [None]))
def testCountNonzero(self, shape, dtype, axis):
rng = jtu.rand_some_zero()
onp_fun = lambda x: onp.count_nonzero(x, axis)
jnp_fun = lambda x: jnp.count_nonzero(x, axis)
args_maker = lambda: [rng(shape, dtype)]
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=False)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_shape={}".format(
jtu.format_shape_dtype_string(shape, dtype)),
"shape": shape, "dtype": dtype}
for shape in all_shapes for dtype in all_dtypes))
def testNonzero(self, shape, dtype):
rng = jtu.rand_some_zero()
onp_fun = lambda x: onp.nonzero(x)
onp_fun = jtu.ignore_warning(
category=DeprecationWarning,
message="Calling nonzero on 0d arrays.*")(onp_fun)
jnp_fun = lambda x: jnp.nonzero(x)
args_maker = lambda: [rng(shape, dtype)]
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=False)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "{}_inshape={}_axis={}".format(
rec.test_name.capitalize(),
jtu.format_shape_dtype_string(shape, dtype), axis),
"rng_factory": rec.rng_factory, "shape": shape, "dtype": dtype,
"onp_op": getattr(onp, rec.name), "jnp_op": getattr(jnp, rec.name),
"axis": axis}
for rec in JAX_ARGMINMAX_RECORDS
for shape, dtype in _shape_and_dtypes(rec.shapes, rec.dtypes)
for axis in range(-len(shape), len(shape))))
def testArgMinMax(self, onp_op, jnp_op, rng_factory, shape, dtype, axis):
rng = rng_factory()
if dtype == onp.complex128 and jtu.device_under_test() == "gpu":
raise unittest.SkipTest("complex128 reductions not supported on GPU")
def onp_fun(array_to_reduce):
return onp_op(array_to_reduce, axis).astype(jnp.int_)
def jnp_fun(array_to_reduce):
return jnp_op(array_to_reduce, axis)
args_maker = lambda: [rng(shape, dtype)]
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_{}_{}_{}".format(
jtu.format_shape_dtype_string(lhs_shape, lhs_dtype),
jtu.format_shape_dtype_string(rhs_shape, rhs_dtype),
axes),
"lhs_shape": lhs_shape, "lhs_dtype": lhs_dtype,
"rhs_shape": rhs_shape, "rhs_dtype": rhs_dtype,
"axes": axes, "rng_factory": rng_factory}
for rng_factory in [jtu.rand_default]
for lhs_shape, rhs_shape, axes in [
[(2,), (2,), (-1, -1, -1, None)], # scalar output
[(2, 4), (2, 4), (-1, -1, -1, 0)], # 2D vectors
[(3, 4), (3, 4), (-1, -1, -1, 0)], # 3D vectors
[(3, 4), (3, 6, 5, 4), (-1, -1, -1, 0)], # broadcasting
[(4, 3), (3, 6, 5, 4), (1, 0, -1, None)], # different axes
[(6, 1, 3), (5, 3), (-1, -1, -1, None)], # more broadcasting
[(6, 1, 2), (5, 3), (-1, -1, -1, None)], # mixed 2D and 3D vectors
[(10, 5, 2, 8), (1, 5, 1, 3), (-2, -1, -3, None)], # axes/broadcasting
[(4, 5, 2), (4, 5, 2), (-1, -1, 0, None)], # axisc should do nothing
[(4, 5, 2), (4, 5, 2), (-1, -1, -1, None)] # same as before
]
for lhs_dtype, rhs_dtype in CombosWithReplacement(number_dtypes, 2)))
def testCross(self, lhs_shape, lhs_dtype, rhs_shape, rhs_dtype, axes, rng_factory):
rng = rng_factory()
args_maker = lambda: [rng(lhs_shape, lhs_dtype), rng(rhs_shape, rhs_dtype)]
axisa, axisb, axisc, axis = axes
jnp_fun = lambda a, b: jnp.cross(a, b, axisa, axisb, axisc, axis)
def onp_fun(a, b):
a = a.astype(onp.float32) if lhs_dtype == jnp.bfloat16 else a
b = b.astype(onp.float32) if rhs_dtype == jnp.bfloat16 else b
out = onp.cross(a, b, axisa, axisb, axisc, axis)
return out.astype(jnp.promote_types(lhs_dtype, rhs_dtype))
tol_spec = {dtypes.bfloat16: 3e-1, onp.float16: 0.15}
tol = max(jtu.tolerance(lhs_dtype, tol_spec),
jtu.tolerance(rhs_dtype, tol_spec))
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True,
tol=tol)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True, atol=tol,
rtol=tol)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_{}_{}_{}".format(
name,
jtu.format_shape_dtype_string(lhs_shape, lhs_dtype),
jtu.format_shape_dtype_string(rhs_shape, rhs_dtype)),
"lhs_shape": lhs_shape, "lhs_dtype": lhs_dtype,
"rhs_shape": rhs_shape, "rhs_dtype": rhs_dtype,
"rng_factory": rng_factory}
for rng_factory in [jtu.rand_default]
for name, lhs_shape, rhs_shape in [
("matrix-scalar", (3, 3), ()),
("scalar-matrix", (), (3, 3)),
("matrix-vector", (4, 5), (5,)),
("vector-matrix", (6,), (6, 4)),
("matrix-matrix", (3, 4), (4, 5)),
("tensor-vector", (4, 3, 2), (2,)),
("vector-tensor", (2,), (3, 2, 4)),
("tensor-matrix", (4, 3, 2), (2, 5)),
("matrix-tensor", (5, 2), (3, 2, 4)),
("tensor-tensor", (2, 3, 4), (5, 4, 1))]
for lhs_dtype, rhs_dtype in CombosWithReplacement(number_dtypes, 2)))
def testDot(self, lhs_shape, lhs_dtype, rhs_shape, rhs_dtype, rng_factory):
rng = rng_factory()
args_maker = lambda: [rng(lhs_shape, lhs_dtype), rng(rhs_shape, rhs_dtype)]
tol = {onp.float16: 1e-2, onp.float32: 1e-5, onp.float64: 1e-14,
onp.complex128: 1e-14}
if jtu.device_under_test() == "tpu":
tol[onp.float32] = tol[onp.complex64] = 2e-1
def onp_dot(x, y):
x = x.astype(onp.float32) if lhs_dtype == jnp.bfloat16 else x
y = y.astype(onp.float32) if rhs_dtype == jnp.bfloat16 else y
return onp.dot(x, y).astype(jnp.promote_types(lhs_dtype, rhs_dtype))
self._CheckAgainstNumpy(onp_dot, jnp.dot, args_maker, check_dtypes=True,
tol=tol)
self._CompileAndCheck(jnp.dot, args_maker, check_dtypes=True, atol=tol,
rtol=tol)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_{}_{}_{}".format(
name,
jtu.format_shape_dtype_string(lhs_shape, lhs_dtype),
jtu.format_shape_dtype_string(rhs_shape, rhs_dtype)),
"lhs_shape": lhs_shape, "lhs_dtype": lhs_dtype,
"rhs_shape": rhs_shape, "rhs_dtype": rhs_dtype,
"rng_factory": rng_factory}
for rng_factory in [jtu.rand_default]
for name, lhs_shape, rhs_shape in [
("vector-vector", (3,), (3,)),
("matrix-vector", (3, 3), (3,)),
("vector-matrix", (3,), (3, 3)),
("matrix-matrix", (3, 3), (3, 3)),
("vector-tensor", (3,), (5, 3, 2)),
("tensor-vector", (5, 3, 2), (2,)),
("matrix-tensor", (5, 2), (3, 2, 4)),
("tensor-matrix", (5, 2, 3), (3, 2)),
("tensor-tensor", (5, 3, 4), (5, 4, 1)),
("tensor-tensor-broadcast", (3, 1, 3, 4), (5, 4, 1))]
for lhs_dtype, rhs_dtype in CombosWithReplacement(number_dtypes, 2)))
def testMatmul(self, lhs_shape, lhs_dtype, rhs_shape, rhs_dtype, rng_factory):
rng = rng_factory()
def onp_fun(x, y):
dtype = jnp.promote_types(lhs_dtype, rhs_dtype)
return onp.matmul(x, y).astype(dtype)
args_maker = lambda: [rng(lhs_shape, lhs_dtype), rng(rhs_shape, rhs_dtype)]
tol = {onp.float16: 1e-2, onp.float32: 2e-2, onp.float64: 1e-12,
onp.complex128: 1e-12}
if jtu.device_under_test() == "tpu":
tol[onp.float32] = tol[onp.complex64] = 4e-2
self._CheckAgainstNumpy(onp_fun, jnp.matmul, args_maker,
check_dtypes=True, tol=tol)
self._CompileAndCheck(jnp.matmul, args_maker, check_dtypes=True, atol=tol,
rtol=tol)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_{}_{}_{}".format(
jtu.format_shape_dtype_string(lhs_shape, lhs_dtype),
jtu.format_shape_dtype_string(rhs_shape, rhs_dtype),
axes),
"lhs_shape": lhs_shape, "lhs_dtype": lhs_dtype,
"rhs_shape": rhs_shape, "rhs_dtype": rhs_dtype,
"axes": axes, "rng_factory": rng_factory}
for rng_factory in [jtu.rand_default]
for lhs_shape, rhs_shape, axes in [
[(3,), (), 0],
[(2, 3, 4), (5, 6, 7), 0], # from issue #740
[(2, 3, 4), (3, 4, 5, 6), 2],
[(2, 3, 4), (5, 4, 3, 6), [1, 2]],
[(2, 3, 4), (5, 4, 3, 6), [[1, 2], [2, 1]]],
[(1, 2, 3, 4), (4, 5, 3, 6), [[2, 3], [2, 0]]],
]
for lhs_dtype, rhs_dtype in CombosWithReplacement(number_dtypes, 2)))
def testTensordot(self, lhs_shape, lhs_dtype, rhs_shape, rhs_dtype, axes, rng_factory):
rng = rng_factory()
args_maker = lambda: [rng(lhs_shape, lhs_dtype), rng(rhs_shape, rhs_dtype)]
jnp_fun = lambda a, b: jnp.tensordot(a, b, axes)
def onp_fun(a, b):
a = a if lhs_dtype != jnp.bfloat16 else a.astype(onp.float32)
b = b if rhs_dtype != jnp.bfloat16 else b.astype(onp.float32)
dtype = jnp.promote_types(lhs_dtype, rhs_dtype)
return onp.tensordot(a, b, axes).astype(dtype)
tol = {onp.float16: 1e-1, onp.float32: 1e-3, onp.float64: 1e-12,
onp.complex64: 1e-3, onp.complex128: 1e-12}
if jtu.device_under_test() == "tpu":
tol[onp.float32] = tol[onp.complex64] = 2e-1
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True,
tol=tol)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)
def testTensordotErrors(self):
a = onp.random.random((3, 2, 2))
b = onp.random.random((2,))
self.assertRaisesRegex(
TypeError, "Number of tensordot axes.*exceeds input ranks.*",
lambda: jnp.tensordot(a, b, axes=2))
self.assertRaisesRegex(
TypeError, "tensordot requires axes lists to have equal length.*",
lambda: jnp.tensordot(a, b, axes=([0], [0, 1])))
self.assertRaisesRegex(
TypeError, "tensordot requires both axes lists to be either ints, tuples or lists.*",
lambda: jnp.tensordot(a, b, axes=('bad', 'axes')))
self.assertRaisesRegex(
TypeError, "tensordot axes argument must be an int, a pair of ints, or a pair of lists.*",
lambda: jnp.tensordot(a, b, axes='badaxes'))
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_{}_{}".format(
jtu.format_shape_dtype_string(lhs_shape, lhs_dtype),
jtu.format_shape_dtype_string(rhs_shape, rhs_dtype)),
"lhs_shape": lhs_shape, "lhs_dtype": lhs_dtype,
"rhs_shape": rhs_shape, "rhs_dtype": rhs_dtype,
"rng_factory": jtu.rand_default}
# TODO(phawkins): support integer dtypes too.
for lhs_shape, lhs_dtype in _shape_and_dtypes(all_shapes, inexact_dtypes)
for rhs_shape, rhs_dtype in _shape_and_dtypes(all_shapes, inexact_dtypes)
if len(jtu._dims_of_shape(lhs_shape)) == 0
or len(jtu._dims_of_shape(rhs_shape)) == 0
or lhs_shape[-1] == rhs_shape[-1]))
def testInner(self, lhs_shape, lhs_dtype, rhs_shape, rhs_dtype, rng_factory):
rng = rng_factory()
args_maker = lambda: [rng(lhs_shape, lhs_dtype), rng(rhs_shape, rhs_dtype)]
def onp_fun(lhs, rhs):
lhs = lhs if lhs_dtype != jnp.bfloat16 else lhs.astype(onp.float32)
rhs = rhs if rhs_dtype != jnp.bfloat16 else rhs.astype(onp.float32)
dtype = jnp.promote_types(lhs_dtype, rhs_dtype)
return onp.inner(lhs, rhs).astype(dtype)
jnp_fun = lambda lhs, rhs: jnp.inner(lhs, rhs)
tol_spec = {onp.float16: 1e-2, onp.float32: 1e-5, onp.float64: 1e-13}
if jtu.device_under_test() == "tpu":
tol_spec[onp.float32] = tol_spec[onp.complex64] = 2e-1
tol = max(jtu.tolerance(lhs_dtype, tol_spec),
jtu.tolerance(rhs_dtype, tol_spec))
# TODO(phawkins): there are float32/float64 disagreements for some inputs.
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=False,
tol=tol)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=False, atol=tol,
rtol=tol)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_{}_amin={}_amax={}".format(
jtu.format_shape_dtype_string(shape, dtype), a_min, a_max),
"shape": shape, "dtype": dtype, "a_min": a_min, "a_max": a_max,
"rng_factory": jtu.rand_default}
for shape in all_shapes for dtype in number_dtypes
for a_min, a_max in [(-1, None), (None, 1), (-1, 1),
(-onp.ones(1), None),
(None, onp.ones(1)),
(-onp.ones(1), onp.ones(1))]))
def testClipStaticBounds(self, shape, dtype, a_min, a_max, rng_factory):
rng = rng_factory()
onp_fun = lambda x: onp.clip(x, a_min=a_min, a_max=a_max)
jnp_fun = lambda x: jnp.clip(x, a_min=a_min, a_max=a_max)
args_maker = lambda: [rng(shape, dtype)]
# TODO(phawkins): the promotion behavior changed in Numpy 1.17.
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=False)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)
def testClipError(self):
with self.assertRaisesRegex(ValueError, "At most one of a_min and a_max.*"):
jnp.clip(jnp.zeros((3,)))
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_{}_decimals={}".format(
jtu.format_shape_dtype_string(shape, dtype), decimals),
"shape": shape, "dtype": dtype, "decimals": decimals,
"rng_factory": jtu.rand_default}
for shape, dtype in _shape_and_dtypes(all_shapes, number_dtypes)
for decimals in [0, 1, -2]))
def testRoundStaticDecimals(self, shape, dtype, decimals, rng_factory):
rng = rng_factory()
if jnp.issubdtype(dtype, onp.integer) and decimals < 0:
self.skipTest("Integer rounding with decimals < 0 not implemented")
onp_fun = lambda x: onp.round(x, decimals=decimals)
jnp_fun = lambda x: jnp.round(x, decimals=decimals)
args_maker = lambda: [rng(shape, dtype)]
tol = {jnp.bfloat16: 5e-2, onp.float16: 1e-2}
check_dtypes = shape is not jtu.PYTHON_SCALAR_SHAPE
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker,
check_dtypes=check_dtypes, tol=tol)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=check_dtypes,
atol=tol, rtol=tol)
def testOperatorRound(self):
self.assertAllClose(round(onp.float32(7.532), 1),
round(jnp.float32(7.5), 1), check_dtypes=True)
self.assertAllClose(round(onp.float32(1.234), 2),
round(jnp.float32(1.234), 2), check_dtypes=True)
self.assertAllClose(round(onp.float32(1.234)),
round(jnp.float32(1.234)), check_dtypes=False)
self.assertAllClose(round(onp.float32(7.532), 1),
round(jnp.array(7.5, jnp.float32), 1), check_dtypes=True)
self.assertAllClose(round(onp.float32(1.234), 2),
round(jnp.array(1.234, jnp.float32), 2), check_dtypes=True)
self.assertAllClose(round(onp.float32(1.234)),
round(jnp.array(1.234, jnp.float32)),
check_dtypes=False)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_shape={}_mode={}_rpadwidth={}_rconstantvalues={}".format(
jtu.format_shape_dtype_string(shape, dtype), mode, pad_width_rank,
constant_values_rank),
"shape": shape, "dtype": dtype, "mode": mode,
"pad_width_rank": pad_width_rank,
"constant_values_rank": constant_values_rank,
"rng_factory": jtu.rand_default,
"irng_factory": partial(jtu.rand_int, 3)}
for mode, constant_values_rank, shapes in [
('constant', 0, all_shapes),
('constant', 1, all_shapes),
('constant', 2, all_shapes),
('symmetric', None, nonempty_shapes),
('reflect', None, nonempty_shapes),
('wrap', None, nonempty_shapes),
('edge', None, nonempty_shapes),
]
for shape, dtype in _shape_and_dtypes(shapes, all_dtypes)
for pad_width_rank in range(3)))
def testPad(self, shape, dtype, mode, pad_width_rank, constant_values_rank,
rng_factory, irng_factory):
rng = rng_factory()
irng = irng_factory()
pad_width = irng([len(shape), 2][2 - pad_width_rank:], onp.int32)
def onp_fun(x, kwargs):
if pad_width.size == 0:
return x
return onp.pad(x, pad_width, mode=mode, **kwargs)
def jnp_fun(x, kwargs):
return jnp.pad(x, pad_width, mode=mode, **kwargs)
def args_maker():
kwargs = {}
if constant_values_rank:
kwargs["constant_values"] = rng(
[len(shape), 2][2 - constant_values_rank:], dtype)
return rng(shape, dtype), kwargs
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker,
check_dtypes=shape is not jtu.PYTHON_SCALAR_SHAPE)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_shape=[{}]_reps={}".format(
jtu.format_shape_dtype_string(shape, dtype), reps),
"shape": shape, "dtype": dtype, "reps": reps,
"rng_factory": jtu.rand_default}
for reps in [(), (2,), (3, 4), (2, 3, 4)]
for shape, dtype in _shape_and_dtypes(all_shapes, default_dtypes)
))
def testTile(self, shape, dtype, reps, rng_factory):
rng = rng_factory()
onp_fun = lambda arg: onp.tile(arg, reps)
jnp_fun = lambda arg: jnp.tile(arg, reps)
args_maker = lambda: [rng(shape, dtype)]
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker,
check_dtypes=shape is not jtu.PYTHON_SCALAR_SHAPE)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_axis={}_baseshape=[{}]_dtypes=[{}]".format(
axis, ",".join(str(d) for d in base_shape),
",".join(onp.dtype(dtype).name for dtype in arg_dtypes)),
"axis": axis, "base_shape": base_shape, "arg_dtypes": arg_dtypes,
"rng_factory": jtu.rand_default}
for num_arrs in [3]
for arg_dtypes in CombosWithReplacement(default_dtypes, num_arrs)
for base_shape in [(4,), (3, 4), (2, 3, 4)]
for axis in range(-len(base_shape)+1, len(base_shape))))
def testConcatenate(self, axis, base_shape, arg_dtypes, rng_factory):
rng = rng_factory()
wrapped_axis = axis % len(base_shape)
shapes = [base_shape[:wrapped_axis] + (size,) + base_shape[wrapped_axis+1:]
for size, _ in zip(itertools.cycle([3, 1, 4]), arg_dtypes)]
def onp_fun(*args):
args = [x if x.dtype != jnp.bfloat16 else x.astype(onp.float32)
for x in args]
dtype = functools.reduce(jnp.promote_types, arg_dtypes)
return onp.concatenate(args, axis=axis).astype(dtype)
jnp_fun = lambda *args: jnp.concatenate(args, axis=axis)
def args_maker():
return [rng(shape, dtype) for shape, dtype in zip(shapes, arg_dtypes)]
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_axis={}_baseshape=[{}]_dtypes=[{}]".format(
axis, ",".join(str(d) for d in base_shape),
",".join(onp.dtype(dtype).name for dtype in arg_dtypes)),
"axis": axis, "base_shape": base_shape, "arg_dtypes": arg_dtypes,
"rng_factory": jtu.rand_default}
for arg_dtypes in CombosWithReplacement(default_dtypes, 2)
for base_shape in [(4,), (3, 4), (2, 3, 4)]
for axis in range(-len(base_shape)+1, len(base_shape))))
def testAppend(self, axis, base_shape, arg_dtypes, rng_factory):
rng = rng_factory()
wrapped_axis = axis % len(base_shape)
shapes = [base_shape[:wrapped_axis] + (size,) + base_shape[wrapped_axis+1:]
for size, _ in zip(itertools.cycle([3, 1, 4]), arg_dtypes)]
def onp_fun(arr, values):
arr = arr.astype(onp.float32) if arr.dtype == jnp.bfloat16 else arr
values = (values.astype(onp.float32) if values.dtype == jnp.bfloat16
else values)
out = onp.append(arr, values, axis=axis)
return out.astype(jnp.promote_types(*arg_dtypes))
jnp_fun = lambda arr, values: jnp.append(arr, values, axis=axis)
def args_maker():
return [rng(shape, dtype) for shape, dtype in zip(shapes, arg_dtypes)]
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_shape=[{}]_axis={}_repeats={}".format(
jtu.format_shape_dtype_string(shape, dtype), axis, repeats),
"axis": axis, "shape": shape, "dtype": dtype, "repeats": repeats,
"rng_factory": jtu.rand_default}
for repeats in [0, 1, 2]
for shape, dtype in _shape_and_dtypes(all_shapes, default_dtypes)
for axis in [None] + list(range(-len(shape), len(shape)))))
def testRepeat(self, axis, shape, dtype, repeats, rng_factory):
rng = rng_factory()
onp_fun = lambda arg: onp.repeat(arg, repeats=repeats, axis=axis)
onp_fun = _promote_like_jnp(onp_fun)
jnp_fun = lambda arg: jnp.repeat(arg, repeats=repeats, axis=axis)
args_maker = lambda: [rng(shape, dtype)]
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)
def testIssue1233(self):
'''
Following numpy test suite from `test_repeat` at https://github.com/numpy/numpy/blob/master/numpy/core/tests/test_multiarray.py
'''
tol = 1e-5
def test_single(m, args_maker, repeats, axis):
lax_ans = jnp.repeat(m, repeats, axis)
numpy_ans = onp.repeat(m, repeats, axis)
self.assertAllClose(lax_ans, numpy_ans, check_dtypes=True, rtol=tol, atol=tol)
jnp_fun = lambda arg: jnp.repeat(arg, repeats = repeats, axis=axis)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)
m = jnp.array([1,2,3,4,5,6])
args_maker = lambda: [m]
for repeats in [2, [1,3,2,1,1,2], [1,3,0,1,1,2], [2], jnp.array([1,3,2,1,1,2]), jnp.array([2])]:
test_single(m, args_maker, repeats, None)
m_rect = m.reshape((2,3))
args_maker = lambda: [m_rect]
for repeats in [2, [2,1], [2], jnp.array([2,1]), jnp.array([2])]:
test_single(m_rect, args_maker, repeats, axis=0)
for repeats in [2, [1,3,2], [2], jnp.array([1,3,2]), jnp.array([2])]:
test_single(m_rect, args_maker, repeats, axis=1)
def testIssue2330(self):
'''
Make sure return value of jnp.concatenate is a jax.ndarray and is side-effect save
'''
def attempt_sideeffect(x):
x = [x]
x = jnp.concatenate(x)
x -= 1.
return x
onp_input = onp.ones((1))
jnp_input = jnp.ones((1))
expected_onp_input_after_call = onp.ones((1))
expected_jnp_input_after_call = jnp.ones((1))
self.assertIs(type(jnp.concatenate([onp_input])), jnp.DeviceArray)
attempt_sideeffect(onp_input)
attempt_sideeffect(jnp_input)
self.assertAllClose(onp_input, expected_onp_input_after_call, check_dtypes=True)
self.assertAllClose(jnp_input, expected_jnp_input_after_call, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "op={}_xshape=[{}]_yshape=[{}]_mode={}".format(
op,
jtu.format_shape_dtype_string(xshape, dtype),
jtu.format_shape_dtype_string(yshape, dtype),
mode),
"xshape": xshape, "yshape": yshape, "dtype": dtype, "mode": mode,
"rng_factory": jtu.rand_default,
"jnp_op": getattr(jnp, op),
"onp_op": getattr(onp, op)}
for mode in ['full', 'same', 'valid']
for op in ['convolve', 'correlate']
for dtype in default_dtypes
for xshape in one_dim_array_shapes
for yshape in one_dim_array_shapes))
def testConvolutions(self, xshape, yshape, dtype, mode, rng_factory, jnp_op, onp_op):
rng = rng_factory()
args_maker = lambda: [rng(xshape, dtype), rng(yshape, dtype)]
onp_fun = partial(onp_op, mode=mode)
jnp_fun = partial(jnp_op, mode=mode)
tol = 1e-2 if jtu.device_under_test() != "tpu" else 0.5
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=False, tol=tol)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "op={}_shape=[{}]_axis={}_out_dtype={}".format(
op, jtu.format_shape_dtype_string(shape, dtype), axis,
out_dtype.__name__),
"axis": axis, "shape": shape, "dtype": dtype, "out_dtype": out_dtype,
"rng_factory": jtu.rand_default, "jnp_op": getattr(jnp, op),
"onp_op": getattr(onp, op)}
for op in ["cumsum", "cumprod"]
for dtype in all_dtypes
for out_dtype in default_dtypes
for shape in all_shapes
for axis in [None] + list(range(-len(shape), len(shape)))))
def testCumSumProd(self, axis, shape, dtype, out_dtype, onp_op, jnp_op, rng_factory):
rng = rng_factory()
onp_fun = lambda arg: onp_op(arg, axis=axis, dtype=out_dtype)
onp_fun = jtu.ignore_warning(category=onp.ComplexWarning)(onp_fun)
jnp_fun = lambda arg: jnp_op(arg, axis=axis, dtype=out_dtype)
jnp_fun = jtu.ignore_warning(category=jnp.ComplexWarning)(jnp_fun)
args_maker = lambda: [rng(shape, dtype)]
tol = max(jtu.tolerance(dtype), jtu.tolerance(out_dtype))
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True,
tol=tol)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_dtype={}_m={}_n={}_k={}".format(
onp.dtype(dtype).name, m, n, k),
"m": m, "n": n, "k": k, "dtype": dtype, "rng_factory": jtu.rand_default}
for dtype in default_dtypes
for n in [0, 4]
for m in [None, 0, 1, 3, 4]
for k in list(range(-4, 4))))
def testTri(self, m, n, k, dtype, rng_factory):
rng = rng_factory()
onp_fun = lambda: onp.tri(n, M=m, k=k, dtype=dtype)
jnp_fun = lambda: jnp.tri(n, M=m, k=k, dtype=dtype)
args_maker = lambda: []
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_op={}_shape={}_k={}".format(
op, jtu.format_shape_dtype_string(shape, dtype), k),
"dtype": dtype, "shape": shape, "op": op, "k": k,
"rng_factory": jtu.rand_default}
for dtype in default_dtypes
for shape in [shape for shape in all_shapes if len(shape) >= 2]
for op in ["tril", "triu"]
for k in list(range(-3, 3))))
def testTriLU(self, dtype, shape, op, k, rng_factory):
rng = rng_factory()
onp_fun = lambda arg: getattr(onp, op)(arg, k=k)
jnp_fun = lambda arg: getattr(jnp, op)(arg, k=k)
args_maker = lambda: [rng(shape, dtype)]
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_ndim={}_n={}".format(ndim, n),
"ndim": ndim, "n": n}
for ndim in [0, 1, 4]
for n in [0, 1, 7]))
def testDiagIndices(self, ndim, n):
onp.testing.assert_equal(onp.diag_indices(n, ndim),
jnp.diag_indices(n, ndim))
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_shape={}_k={}".format(
jtu.format_shape_dtype_string(shape, dtype), k),
"dtype": dtype, "shape": shape, "k": k, "rng_factory": jtu.rand_default}
for dtype in default_dtypes
for shape in [shape for shape in all_shapes if len(shape) in (1, 2)]
for k in list(range(-4, 4))))
def testDiag(self, shape, dtype, k, rng_factory):
rng = rng_factory()
onp_fun = lambda arg: onp.diag(arg, k)
jnp_fun = lambda arg: jnp.diag(arg, k)
args_maker = lambda: [rng(shape, dtype)]
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_shape={}_offset={}_axis1={}_axis2={}".format(
jtu.format_shape_dtype_string(shape, dtype), offset, axis1, axis2),
"dtype": dtype, "shape": shape, "offset": offset, "axis1": axis1,
"axis2": axis2, "rng_factory": jtu.rand_default}
for dtype in default_dtypes
for shape in [shape for shape in all_shapes if len(shape) >= 2]
for axis1 in range(-len(shape), len(shape))
for axis2 in [a for a in range(-len(shape), len(shape))
if a % len(shape) != axis1 % len(shape)]
for offset in list(range(-4, 4))))
def testDiagonal(self, shape, dtype, offset, axis1, axis2, rng_factory):
rng = rng_factory()
onp_fun = lambda arg: onp.diagonal(arg, offset, axis1, axis2)
jnp_fun = lambda arg: jnp.diagonal(arg, offset, axis1, axis2)
args_maker = lambda: [rng(shape, dtype)]
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_shape={}_n={}".format(onp.dtype(dtype).name, n),
"dtype": dtype, "n": n}
for dtype in default_dtypes
for n in list(range(4))))
def testIdentity(self, n, dtype):
onp_fun = lambda: onp.identity(n, dtype)
jnp_fun = lambda: jnp.identity(n, dtype)
args_maker = lambda: []
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_x1={}_x2={}_x1_rng={}".format(
jtu.format_shape_dtype_string(x1_shape, x1_dtype),
jtu.format_shape_dtype_string(x2_shape, onp.int32),
x1_rng_factory_id),
"x1_shape": x1_shape, "x1_dtype": x1_dtype,
"x2_shape": x2_shape, "x1_rng_factory": x1_rng_factory,
"x2_rng_factory": x2_rng_factory}
for x1_rng_factory_id, x1_rng_factory in
enumerate([jtu.rand_some_inf_and_nan, jtu.rand_some_zero])
for x2_rng_factory in [partial(jtu.rand_int, -1075, 1024)]
for x1_shape, x2_shape in filter(_shapes_are_broadcast_compatible,
CombosWithReplacement(array_shapes, 2))
for x1_dtype in default_dtypes))
@jtu.skip_on_devices("tpu") # TODO(b/153053081)
def testLdexp(self, x1_shape, x1_dtype, x2_shape, x1_rng_factory, x2_rng_factory):
# integer types are converted to float64 in numpy's implementation
if (x1_dtype not in [jnp.bfloat16, onp.float16, onp.float32]
and not FLAGS.jax_enable_x64):
self.skipTest("Only run float64 testcase when float64 is enabled.")
x1_rng = x1_rng_factory()
x2_rng = x2_rng_factory()
onp_fun = lambda x1, x2: onp.ldexp(x1, x2)
onp_fun = jtu.ignore_warning(category=RuntimeWarning,
message="overflow.*")(onp_fun)
jnp_fun = lambda x1, x2: jnp.ldexp(x1, x2)
args_maker = lambda: [x1_rng(x1_shape, x1_dtype),
x2_rng(x2_shape, onp.int32)]
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_x={}_rng_factory={}".format(
jtu.format_shape_dtype_string(shape, dtype), rng_factory_id),
"shape": shape, "dtype": dtype, "rng_factory": rng_factory}
for rng_factory_id, rng_factory in enumerate([
jtu.rand_some_inf_and_nan,
jtu.rand_some_zero,
partial(jtu.rand_not_small, offset=1e8),
])
for shape in all_shapes
for dtype in default_dtypes))
@jtu.skip_on_devices("tpu")
def testFrexp(self, shape, dtype, rng_factory):
# integer types are converted to float64 in numpy's implementation
if (dtype not in [jnp.bfloat16, onp.float16, onp.float32]
and not FLAGS.jax_enable_x64):
self.skipTest("Only run float64 testcase when float64 is enabled.")
rng = rng_factory()
onp_fun = lambda x: onp.frexp(x)
jnp_fun = lambda x: jnp.frexp(x)
args_maker = lambda: [rng(shape, dtype)]
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_shape={}_dtype_{}_offset={}_axis1={}_axis2={}".format(
jtu.format_shape_dtype_string(shape, dtype),
out_dtype, offset, axis1, axis2),
"dtype": dtype, "out_dtype": out_dtype, "shape": shape, "offset": offset,
"axis1": axis1, "axis2": axis2, "rng_factory": jtu.rand_default}
for dtype in default_dtypes
for out_dtype in [None] + number_dtypes
for shape in [shape for shape in all_shapes if len(shape) >= 2]
for axis1 in range(-len(shape), len(shape))
for axis2 in range(-len(shape), len(shape))
if (axis1 % len(shape)) != (axis2 % len(shape))
for offset in list(range(-4, 4))))
def testTrace(self, shape, dtype, out_dtype, offset, axis1, axis2, rng_factory):
rng = rng_factory()
def onp_fun(arg):
if out_dtype == jnp.bfloat16:
return onp.trace(arg, offset, axis1, axis2, onp.float32).astype(jnp.bfloat16)
else:
return onp.trace(arg, offset, axis1, axis2, out_dtype)
jnp_fun = lambda arg: jnp.trace(arg, offset, axis1, axis2, out_dtype)
args_maker = lambda: [rng(shape, dtype)]
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_{}_axis={}".format(
jtu.format_test_name_suffix("", [shape] * len(dtypes), dtypes), axis),
"shape": shape, "axis": axis, "dtypes": dtypes, "rng_factory": rng_factory}
for dtypes in [
[onp.float32],
[onp.float32, onp.float32],
[onp.float32, onp.int32, onp.float32],
[onp.float32, onp.int64, onp.float32],
[onp.float32, onp.int32, onp.float64],
]
for shape in [(), (2,), (3, 4), (1, 100)]
for axis in range(-len(shape), len(shape) + 1)
for rng_factory in [jtu.rand_default]))
def testStack(self, shape, axis, dtypes, rng_factory):
rng = rng_factory()
args_maker = lambda: [[rng(shape, dtype) for dtype in dtypes]]
onp_fun = _promote_like_jnp(partial(onp.stack, axis=axis))
jnp_fun = partial(jnp.stack, axis=axis)
self._CheckAgainstNumpy(jnp_fun, onp_fun, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_op={}_{}".format(
op, jtu.format_test_name_suffix("", [shape] * len(dtypes), dtypes)),
"shape": shape, "op": op, "dtypes": dtypes, "rng_factory": rng_factory}
for op in ["hstack", "vstack", "dstack"]
for dtypes in [
[onp.float32],
[onp.float32, onp.float32],
[onp.float32, onp.int32, onp.float32],
[onp.float32, onp.int64, onp.float32],
[onp.float32, onp.int32, onp.float64],
]
for shape in [(), (2,), (3, 4), (1, 100), (2, 3, 4)]
for rng_factory in [jtu.rand_default]))
def testHVDStack(self, shape, op, dtypes, rng_factory):
rng = rng_factory()
args_maker = lambda: [[rng(shape, dtype) for dtype in dtypes]]
onp_fun = _promote_like_jnp(getattr(onp, op))
jnp_fun = getattr(jnp, op)
self._CheckAgainstNumpy(jnp_fun, onp_fun, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_inshape={}_outdtype={}".format(
jtu.format_shape_dtype_string(shape, fill_value_dtype),
onp.dtype(out_dtype).name if out_dtype else "None"),
"shape": shape, "fill_value_dtype": fill_value_dtype,
"out_dtype": out_dtype, "rng_factory": jtu.rand_default}
for shape in array_shapes + [3, onp.array(7, dtype=onp.int32)]
for fill_value_dtype in default_dtypes
for out_dtype in [None] + default_dtypes))
def testFull(self, shape, fill_value_dtype, out_dtype, rng_factory):
rng = rng_factory()
onp_fun = lambda fill_value: onp.full(shape, fill_value, dtype=out_dtype)
jnp_fun = lambda fill_value: jnp.full(shape, fill_value, dtype=out_dtype)
args_maker = lambda: [rng((), fill_value_dtype)]
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)
@parameterized.named_parameters(
jtu.cases_from_list(
{"testcase_name": ("_op={}_shape={}_dtype={}").format(op, shape, dtype),
"onp_op": getattr(onp, op), "jnp_op": getattr(jnp, op),
"shape": shape, "dtype": dtype}
for op in ["zeros", "ones"]
for shape in [2, (), (2,), (3, 0), onp.array((4, 5, 6), dtype=onp.int32),
onp.array(4, dtype=onp.int32)]
for dtype in all_dtypes))
def testZerosOnes(self, onp_op, jnp_op, shape, dtype):
rng = jtu.rand_default()
def args_maker(): return []
onp_op = partial(onp_op, shape, dtype)
jnp_op = partial(jnp_op, shape, dtype)
self._CheckAgainstNumpy(onp_op, jnp_op, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_op, args_maker, check_dtypes=True)
def testOnesWithInvalidShape(self):
with self.assertRaises(TypeError):
jnp.ones((-1, 1))
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_inshape={}_filldtype={}_outdtype={}".format(
jtu.format_shape_dtype_string(shape, in_dtype),
onp.dtype(fill_value_dtype).name,
onp.dtype(out_dtype).name),
"shape": shape, "in_dtype": in_dtype,
"fill_value_dtype": fill_value_dtype, "out_dtype": out_dtype,
"rng_factory": jtu.rand_default}
for shape in array_shapes
for in_dtype in default_dtypes
for fill_value_dtype in default_dtypes
for out_dtype in default_dtypes))
def testFullLike(self, shape, in_dtype, fill_value_dtype, out_dtype, rng_factory):
rng = rng_factory()
onp_fun = lambda x, fill_value: onp.full_like(x, fill_value, dtype=out_dtype)
jnp_fun = lambda x, fill_value: jnp.full_like(x, fill_value, dtype=out_dtype)
args_maker = lambda: [rng(shape, in_dtype), rng((), fill_value_dtype)]
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_{}_axis={}_{}sections".format(
jtu.format_shape_dtype_string(shape, dtype), axis, num_sections),
"shape": shape, "num_sections": num_sections, "axis": axis,
"dtype": dtype, "rng_factory": jtu.rand_default}
for shape, axis, num_sections in [
((3,), 0, 3), ((12,), 0, 3), ((12, 4), 0, 4), ((12, 4), 1, 2),
((2, 3, 4), -1, 2), ((2, 3, 4), -2, 3)]
for dtype in default_dtypes))
def testSplitStaticInt(self, shape, num_sections, axis, dtype, rng_factory):
rng = rng_factory()
onp_fun = lambda x: onp.split(x, num_sections, axis=axis)
jnp_fun = lambda x: jnp.split(x, num_sections, axis=axis)
args_maker = lambda: [rng(shape, dtype)]
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_{}_axis={}_{}sections".format(
jtu.format_shape_dtype_string(shape, dtype), axis, num_sections),
"shape": shape, "num_sections": num_sections, "axis": axis,
"dtype": dtype, "rng_factory": jtu.rand_default}
for shape, axis, num_sections in [
((12, 4), 0, 4), ((12, 4), 1, 2),
((2, 3, 4), 2, 2), ((4, 3, 4), 0, 2)]
for dtype in default_dtypes))
def testHVDSplit(self, shape, num_sections, axis, dtype, rng_factory):
rng = rng_factory()
def fn(module, axis):
if axis == 0:
return module.vsplit
elif axis == 1:
return module.hsplit
else:
assert axis == 2
return module.dsplit
onp_fun = lambda x: fn(onp, axis)(x, num_sections)
jnp_fun = lambda x: fn(jnp, axis)(x, num_sections)
args_maker = lambda: [rng(shape, dtype)]
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_inshape={}_outshape={}_order={}".format(
jtu.format_shape_dtype_string(arg_shape, dtype),
jtu.format_shape_dtype_string(out_shape, dtype),
order),
"arg_shape": arg_shape, "out_shape": out_shape, "dtype": dtype,
"order": order, "rng_factory": jtu.rand_default}
for dtype in default_dtypes
for order in ["C", "F"]
for arg_shape, out_shape in [
(jtu.NUMPY_SCALAR_SHAPE, (1, 1, 1)),
((), (1, 1, 1)),
((7, 0), (0, 42, 101)),
((3, 4), 12),
((3, 4), (12,)),
((3, 4), -1),
((2, 1, 4), (-1,)),
((2, 2, 4), (2, 8))
]))
def testReshape(self, arg_shape, out_shape, dtype, order, rng_factory):
rng = rng_factory()
onp_fun = lambda x: onp.reshape(x, out_shape, order=order)
jnp_fun = lambda x: jnp.reshape(x, out_shape, order=order)
args_maker = lambda: [rng(arg_shape, dtype)]
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_inshape={}_outshape={}".format(
jtu.format_shape_dtype_string(arg_shape, dtype),
jtu.format_shape_dtype_string(out_shape, dtype)),
"arg_shape": arg_shape, "out_shape": out_shape, "dtype": dtype,
"rng_factory": jtu.rand_default}
for dtype in default_dtypes
for arg_shape, out_shape in [
((7, 0), (0, 42, 101)),
((2, 1, 4), (-1,)),
((2, 2, 4), (2, 8))
]))
def testReshapeMethod(self, arg_shape, out_shape, dtype, rng_factory):
rng = rng_factory()
onp_fun = lambda x: onp.reshape(x, out_shape)
jnp_fun = lambda x: x.reshape(*out_shape)
args_maker = lambda: [rng(arg_shape, dtype)]
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_inshape={}_expanddim={}".format(
jtu.format_shape_dtype_string(arg_shape, dtype), dim),
"arg_shape": arg_shape, "dtype": dtype, "dim": dim,
"rng_factory": jtu.rand_default}
for arg_shape in [(), (3,), (3, 4)]
for dtype in default_dtypes
for dim in range(-len(arg_shape)+1, len(arg_shape))))
def testExpandDimsStaticDim(self, arg_shape, dtype, dim, rng_factory):
rng = rng_factory()
onp_fun = lambda x: onp.expand_dims(x, dim)
jnp_fun = lambda x: jnp.expand_dims(x, dim)
args_maker = lambda: [rng(arg_shape, dtype)]
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_inshape={}_axes=({},{})".format(
jtu.format_shape_dtype_string(arg_shape, dtype), ax1, ax2),
"arg_shape": arg_shape, "dtype": dtype, "ax1": ax1, "ax2": ax2,
"rng_factory": jtu.rand_default}
for arg_shape, ax1, ax2 in [
((3, 4), 0, 1), ((3, 4), 1, 0), ((3, 4, 5), 1, 2),
((3, 4, 5), -1, -2), ((3, 4, 5), 0, 1)]
for dtype in default_dtypes))
def testSwapAxesStaticAxes(self, arg_shape, dtype, ax1, ax2, rng_factory):
rng = rng_factory()
onp_fun = lambda x: onp.swapaxes(x, ax1, ax2)
jnp_fun = lambda x: jnp.swapaxes(x, ax1, ax2)
args_maker = lambda: [rng(arg_shape, dtype)]
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_inshape={}_axis={}".format(
jtu.format_shape_dtype_string(arg_shape, dtype), ax),
"arg_shape": arg_shape, "dtype": dtype, "ax": ax,
"rng_factory": jtu.rand_default}
for arg_shape, ax in [
((3, 1), None),
((3, 1), 1),
((1, 3, 1), (0, 2)),
((1, 4, 1), (0,))]
for dtype in default_dtypes))
def testSqueeze(self, arg_shape, dtype, ax, rng_factory):
rng = rng_factory()
onp_fun = lambda x: onp.squeeze(x, ax)
jnp_fun = lambda x: jnp.squeeze(x, ax)
args_maker = lambda: [rng(arg_shape, dtype)]
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_inshape={}_axis={}".format(
jtu.format_shape_dtype_string(arg_shape, dtype), ax),
"arg_shape": arg_shape, "dtype": dtype, "ax": ax,
"rng_factory": jtu.rand_default}
for arg_shape, ax in [
((3,), 0),
((1, 3), 1),
((1, 3, 1), (0, 1))]
for dtype in default_dtypes))
def testSqueezeFailsOnNonsingletonAxis(self, arg_shape, dtype, ax,
rng_factory):
rng = rng_factory()
x = jnp.zeros(arg_shape, dtype=dtype)
fun = lambda: jnp.squeeze(x, ax)
self.assertRaisesRegex(ValueError, "cannot select an axis to squeeze", fun)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_shape={}_axis={}_weights={}_returned={}".format(
jtu.format_shape_dtype_string(shape, dtype),
axis,
(None if weights_shape is None else jtu.format_shape_dtype_string(weights_shape, dtype)),
returned),
"rng_factory": jtu.rand_default, "shape": shape, "dtype": dtype, "axis": axis,
"weights_shape": weights_shape, "returned": returned}
for shape, dtype in _shape_and_dtypes(nonempty_shapes, number_dtypes)
for axis in list(range(-len(shape), len(shape))) + [None]
# `weights_shape` is either `None`, same as the averaged axis, or same as
# that of the input
for weights_shape in ([None, shape] if axis is None or len(shape) == 1
else [None, (shape[axis],), shape])
for returned in [False, True]))
def testAverage(self, shape, dtype, axis, weights_shape, returned, rng_factory):
rng = rng_factory()
if weights_shape is None:
onp_fun = lambda x: onp.average(x, axis, returned=returned)
jnp_fun = lambda x: jnp.average(x, axis, returned=returned)
args_maker = lambda: [rng(shape, dtype)]
else:
onp_fun = lambda x, weights: onp.average(x, axis, weights, returned)
jnp_fun = lambda x, weights: jnp.average(x, axis, weights, returned)
args_maker = lambda: [rng(shape, dtype), rng(weights_shape, dtype)]
onp_fun = _promote_like_jnp(onp_fun, inexact=True)
tol = {onp.float16: 1e-2, onp.float32: 1e-6, onp.float64: 1e-12,}
check_dtypes = shape is not jtu.PYTHON_SCALAR_SHAPE
try:
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker,
check_dtypes=check_dtypes, tol=tol)
except ZeroDivisionError:
self.skipTest("don't support checking for ZeroDivisionError")
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=check_dtypes,
rtol=tol, atol=tol)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_arg{}_ndmin={}".format(i, ndmin),
"arg": arg, "ndmin": ndmin, "dtype": dtype}
for i, (arg, dtype) in enumerate([
([True, False, True], jnp.bool_),
(3., jnp.float_),
([1, 2, 3], jnp.int_),
([1., 2., 3.], jnp.float_),
([[1, 2], [3, 4], [5, 6]], jnp.int_),
([[1, 2.], [3, 4], [5, 6]], jnp.float_),
([[1., 2j], [3., 4.], [5., 6.]], jnp.complex_),
([[3, onp.array(2, dtype=jnp.float_), 1],
onp.arange(3., dtype=jnp.float_)], jnp.float_),
])
for ndmin in [None, onp.ndim(arg), onp.ndim(arg) + 1, onp.ndim(arg) + 2]))
def testArray(self, arg, ndmin, dtype):
args_maker = lambda: [arg]
dtype = dtypes.canonicalize_dtype(dtype)
if ndmin is not None:
onp_fun = partial(onp.array, ndmin=ndmin, dtype=dtype)
jnp_fun = partial(jnp.array, ndmin=ndmin)
else:
onp_fun = partial(onp.array, dtype=dtype)
jnp_fun = jnp.array
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)
def testIssue121(self):
assert not onp.isscalar(jnp.array(3))
def testArrayMethod(self):
class arraylike(object):
dtype = onp.float32
def __array__(self, dtype=None):
return 3.
a = arraylike()
ans = jnp.array(a)
assert ans == 3.
@jtu.skip_on_devices("tpu") # TODO(b/32368900): TPUs don't support uint8 yet.
def testMemoryView(self):
ans = jnp.array(bytearray(b'\x2a'))
self.assertAllClose(
ans,
onp.array([0x2a], dtype=onp.uint8),
check_dtypes=True)
def testIsClose(self):
c_isclose = api.jit(jnp.isclose)
c_isclose_nan = api.jit(partial(jnp.isclose, equal_nan=True))
n = 2
rng = onp.random.RandomState(0)
x = rng.randn(n, 1)
y = rng.randn(n, 1)
inf = onp.asarray(n * [onp.inf]).reshape([n, 1])
nan = onp.asarray(n * [onp.nan]).reshape([n, 1])
args = [x, y, inf, -inf, nan]
for arg0 in args:
for arg1 in args:
result_np = onp.isclose(arg0, arg1)
result_jax = jnp.isclose(arg0, arg1)
result_jit = c_isclose(arg0, arg1)
self.assertTrue(jnp.all(jnp.equal(result_np, result_jax)))
self.assertTrue(jnp.all(jnp.equal(result_np, result_jit)))
result_np = onp.isclose(arg0, arg1, equal_nan=True)
result_jax = jnp.isclose(arg0, arg1, equal_nan=True)
result_jit = c_isclose_nan(arg0, arg1)
self.assertTrue(jnp.all(jnp.equal(result_np, result_jax)))
self.assertTrue(jnp.all(jnp.equal(result_np, result_jit)))
def testAllClose(self):
rng = onp.random.RandomState(0)
x = rng.randn(2, 2)
y = rng.randn(2)
def same(list1, list2):
allclose = functools.partial(jnp.allclose, atol=1e-3, rtol=1e-3)
elements_close = list(map(allclose, list1, list2))
return jnp.all(jnp.array(elements_close))
csame = api.jit(same)
a1 = same((x, y), (x, y))
a2 = csame((x, y), (x, y))
a3 = csame((x, y), (x, 2 * y))
self.assertTrue(a1)
self.assertTrue(a2)
self.assertFalse(a3)
@jtu.skip_on_devices("tpu") # TODO(mattjj): investigate this failure
def testOnesBroadcastingConstantHandler(self):
# TODO(mattjj): update this test for jax3
self.skipTest("test needs jax3 update")
def fun(x):
ones = jnp.ones((3, 4))
assert isinstance(ones, onp.ndarray) and ones.strides == (0, 0)
# To check that the constant handler generates a Broadcast for stride-zero
# arrays, we monkey-patch the client instance.
# TODO(mattjj): once we have better HLO dumping and inspecting facilities,
# we can check the HLO more directly.
c = x._node.c
Broadcast = c.Broadcast # pylint: disable=invalid-name
was_called = []
c.Broadcast = lambda *args: was_called.append(True) or Broadcast(*args)
out = x + ones # the ndarray constant handler should call Broadcast here
assert was_called, "Broadcast was not called."
return out
fun = api.jit(fun)
out_val = fun(jnp.ones(4))
self.assertAllClose(out_val, onp.full((3, 4), 2.), check_dtypes=False)
def testZeroStridesConstantHandler(self):
raw_const = onp.random.RandomState(0).randn(1, 2, 1, 1, 5, 1)
const = onp.broadcast_to(raw_const, (3, 2, 3, 4, 5, 6))
def fun(x):
return x * const
fun = api.jit(fun)
out_val = fun(3.)
self.assertAllClose(out_val, 3. * const, check_dtypes=False)
def testIsInstanceNdarrayDuringTracing(self):
arr = onp.ones(3)
@api.jit
def f(x):
self.assertIsInstance(x, jnp.ndarray)
return jnp.sum(x)
f(arr)
def testNonArrayErrorMessage(self):
x = [1., 2.]
y = onp.array([3., 4.])
def g(x, y):
return jnp.add(x, y)
def f(x, y):
return jnp.dot(x, y)
self.assertRaises(TypeError, lambda: g(x, y))
self.assertRaises(TypeError, lambda: f(x, y))
self.assertRaises(TypeError, lambda: api.jit(g)(x, y))
self.assertRaises(TypeError, lambda: api.jit(f)(x, y))
def testAbstractionErrorMessage(self):
@api.jit
def f(x, n):
for _ in range(n):
x = x * x
return x
self.assertRaises(TypeError, lambda: f(3., 3))
@api.jit
def g(x):
if x > 0.:
return x * 2
else:
return x + 2
self.assertRaises(TypeError, lambda: g(3.))
def testTracingPrimitiveWithNoTranslationErrorMessage(self):
# TODO(mattjj): update this for jax3
self.skipTest("test needs jax3 update")
foo = jnp._not_implemented(lambda x: x)
# No error if there's no tracing.
foo(onp.arange(3))
cfoo = api.jit(foo)
self.assertRaises(NotImplementedError, lambda: cfoo(onp.arange(3)))
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_{}_axis={}".format(
jtu.format_shape_dtype_string(shape, dtype), axis),
"rng_factory": rng_factory, "shape": shape, "dtype": dtype, "axis": axis}
for shape in [(3,), (2, 3)]
for dtype in default_dtypes
for axis in list(range(-len(shape), len(shape))) + [None] # Test negative axes
for rng_factory in [jtu.rand_default]))
def testFlip(self, shape, dtype, axis, rng_factory):
rng = rng_factory()
args_maker = self._GetArgsMaker(rng, [shape], [dtype])
jnp_op = lambda x: jnp.flip(x, axis)
onp_op = lambda x: onp.flip(x, axis)
self._CheckAgainstNumpy(onp_op, jnp_op, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_op, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_{}".format(
jtu.format_shape_dtype_string(shape, dtype)),
"rng_factory": rng_factory, "shape": shape, "dtype": dtype}
for shape in [(3,), (2, 3), (3, 2, 4)]
for dtype in default_dtypes
for rng_factory in [jtu.rand_default]))
def testFlipud(self, shape, dtype, rng_factory):
rng = rng_factory()
args_maker = self._GetArgsMaker(rng, [shape], [dtype])
jnp_op = lambda x: jnp.flipud(x)
onp_op = lambda x: onp.flipud(x)
self._CheckAgainstNumpy(onp_op, jnp_op, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_op, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_{}".format(
jtu.format_shape_dtype_string(shape, dtype)),
"rng_factory": rng_factory, "shape": shape, "dtype": dtype}
for shape in [(3, 2), (2, 3), (3, 2, 4)]
for dtype in default_dtypes
for rng_factory in [jtu.rand_default]))
def testFliplr(self, shape, dtype, rng_factory):
rng = rng_factory()
args_maker = self._GetArgsMaker(rng, [shape], [dtype])
jnp_op = lambda x: jnp.fliplr(x)
onp_op = lambda x: onp.fliplr(x)
self._CheckAgainstNumpy(onp_op, jnp_op, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_op, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_{}_k={}_axes={}".format(
jtu.format_shape_dtype_string(shape, dtype), k, axes),
"rng_factory": rng_factory, "shape": shape, "dtype": dtype, "k": k, "axes": axes}
for shape, axes in [
[(2, 3), (0, 1)],
[(2, 3), (1, 0)],
[(4, 3, 2), (0, 2)],
[(4, 3, 2), (2, 1)],
]
for k in range(-3, 4)
for dtype in default_dtypes
for rng_factory in [jtu.rand_default]))
def testRot90(self, shape, dtype, k, axes, rng_factory):
rng = rng_factory()
args_maker = self._GetArgsMaker(rng, [shape], [dtype])
jnp_op = lambda x: jnp.rot90(x, k, axes)
onp_op = lambda x: onp.rot90(x, k, axes)
self._CheckAgainstNumpy(onp_op, jnp_op, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_op, args_maker, check_dtypes=True)
# TODO(mattjj): test infix operator overrides
def testRavel(self):
rng = onp.random.RandomState(0)
args_maker = lambda: [rng.randn(3, 4).astype("float32")]
self._CompileAndCheck(lambda x: x.ravel(), args_maker, check_dtypes=True)
def testAstype(self):
rng = onp.random.RandomState(0)
args_maker = lambda: [rng.randn(3, 4).astype("float32")]
op = lambda x: x.astype(jnp.int32)
self._CheckAgainstNumpy(op, op, args_maker, check_dtypes=True)
self._CompileAndCheck(op, args_maker, check_dtypes=True)
# TODO(mattjj): test other ndarray-like method overrides
def testOnpMean(self):
# from https://github.com/google/jax/issues/125
x = lax.add(jnp.eye(3, dtype=jnp.float_), 0.)
ans = onp.mean(x)
self.assertAllClose(ans, onp.array(1./3), check_dtypes=False)
def testArangeOnFloats(self):
# from https://github.com/google/jax/issues/145
expected = onp.arange(0.0, 1.0, 0.1, dtype=jnp.float_)
ans = jnp.arange(0.0, 1.0, 0.1)
self.assertAllClose(expected, ans, check_dtypes=True)
def testSortManually(self):
# manual tests for sort are nice because we don't have to worry about ties.
# lax.sort is tested combinatorially.
ans = jnp.sort(onp.array([16, 15, 23, 42, 8, 4]))
expected = onp.array([4, 8, 15, 16, 23, 42])
self.assertAllClose(expected, ans, check_dtypes=True)
a = onp.array([[1, 4], [3, 1]])
ans = jnp.sort(a, axis=None)
expected = onp.array([1, 1, 3, 4])
self.assertAllClose(expected, ans, check_dtypes=True)
a = onp.array([[1, 4], [3, 1]])
ans = jnp.sort(a) # last axis
expected = onp.array([[1, 4], [1, 3]])
self.assertAllClose(expected, ans, check_dtypes=True)
a = onp.array([[1, 4], [3, 1]])
ans = jnp.sort(a, axis=0)
expected = onp.array([[1, 1], [3, 4]])
self.assertAllClose(expected, ans, check_dtypes=True)
def testArgsortManually(self):
x = onp.array([16, 15, 23, 42, 8, 4])
ans = jnp.argsort(x)
expected = onp.argsort(x)
self.assertAllClose(expected, ans, check_dtypes=False)
x = onp.array([[16, 15, 23], [42, 8, 4]])
ans = jnp.argsort(x, axis=0)
expected = onp.argsort(x, axis=0)
self.assertAllClose(expected, ans, check_dtypes=False)
x = onp.array([[16, 15, 23], [42, 8, 4]])
ans = jnp.argsort(x, axis=1)
expected = onp.argsort(x, axis=1)
self.assertAllClose(expected, ans, check_dtypes=False)
x = onp.array([[16, 15, 23], [42, 8, 4]])
ans = jnp.argsort(x, axis=None)
expected = onp.argsort(x, axis=None)
self.assertAllClose(expected, ans, check_dtypes=False)
x = onp.array([[16, 15, 23], [42, 8, 4]])
ans = jnp.argsort(x)
expected = onp.argsort(x)
self.assertAllClose(expected, ans, check_dtypes=False)
def testMsortManually(self):
args_maker = lambda: [onp.random.randint(50, size=(5 ,5))]
jnp_op = lambda x: jnp.msort(x)
onp_op = lambda x: onp.msort(x)
self._CheckAgainstNumpy(jnp_op, onp_op, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_op, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_{}_shifts={}_axis={}".format(
jtu.format_shape_dtype_string(shape, dtype),
shifts, axis),
"rng_factory": rng_factory, "shape": shape, "dtype": dtype, "shifts": shifts,
"axis": axis}
for dtype in all_dtypes
for shape in [(3, 4), (3, 4, 5), (7, 4, 0)]
for shifts, axis in [
(3, None),
(1, 1),
((3,), (0,)),
((-2,), (-2,)),
((1, 2), (0, -1)),
((4, 2, 5, 5, 2, 4), None),
(100, None),
]
for rng_factory in [jtu.rand_default]))
def testRoll(self, shape, dtype, shifts, axis, rng_factory):
rng = rng_factory()
args_maker = lambda: [rng(shape, dtype), onp.array(shifts)]
jnp_op = partial(jnp.roll, axis=axis)
onp_op = partial(onp.roll, axis=axis)
self._CheckAgainstNumpy(jnp_op, onp_op, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_op, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_{}_axis={}_start={}".format(
jtu.format_shape_dtype_string(shape, dtype),
axis, start),
"rng_factory": rng_factory, "shape": shape, "dtype": dtype, "axis": axis,
"start": start}
for dtype in all_dtypes
for shape in [(1, 2, 3, 4)]
for axis in [-3, 0, 2, 3]
for start in [-4, -1, 2, 4]
for rng_factory in [jtu.rand_default]))
def testRollaxis(self, shape, dtype, start, axis, rng_factory):
rng = rng_factory()
args_maker = lambda: [rng(shape, dtype)]
jnp_op = partial(jnp.rollaxis, axis=axis, start=start)
onp_op = partial(onp.rollaxis, axis=axis, start=start)
self._CheckAgainstNumpy(jnp_op, onp_op, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_op, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_{}_axis={}_bitorder={}".format(
jtu.format_shape_dtype_string(shape, dtype), axis, bitorder),
"rng_factory": rng_factory, "shape": shape, "dtype": dtype, "axis": axis,
"bitorder": bitorder}
for dtype in [onp.uint8, onp.bool_]
for bitorder in ['big', 'little']
for shape in [(1, 2, 3, 4)]
for axis in [None, 0, 1, -2, -1]
for rng_factory in [jtu.rand_some_zero]))
def testPackbits(self, shape, dtype, axis, bitorder, rng_factory):
if numpy_version < (1, 17, 0):
raise SkipTest("bitorder arg added in numpy 1.17.0")
rng = rng_factory()
args_maker = lambda: [rng(shape, dtype)]
jnp_op = partial(jnp.packbits, axis=axis, bitorder=bitorder)
onp_op = partial(onp.packbits, axis=axis, bitorder=bitorder)
self._CheckAgainstNumpy(jnp_op, onp_op, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_op, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_{}_axis={}_bitorder={}_count={}".format(
jtu.format_shape_dtype_string(shape, dtype), axis, bitorder, count),
"rng_factory": rng_factory, "shape": shape, "dtype": dtype, "axis": axis,
"bitorder": bitorder, "count": count}
for dtype in [onp.uint8]
for bitorder in ['big', 'little']
for shape in [(1, 2, 3, 4)]
for axis in [None, 0, 1, -2, -1]
for count in [None, 20]
for rng_factory in [jtu.rand_int]))
def testUnpackbits(self, shape, dtype, axis, bitorder, count, rng_factory):
if numpy_version < (1, 17, 0):
raise SkipTest("bitorder arg added in numpy 1.17.0")
rng = rng_factory(0, 256)
args_maker = lambda: [rng(shape, dtype)]
jnp_op = partial(jnp.unpackbits, axis=axis, bitorder=bitorder)
onp_op = partial(onp.unpackbits, axis=axis, bitorder=bitorder)
self._CheckAgainstNumpy(jnp_op, onp_op, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_op, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_{}_index={}_axis={}_mode={}".format(
jtu.format_shape_dtype_string(shape, dtype),
jtu.format_shape_dtype_string(index_shape, index_dtype),
axis, mode),
"rng_factory": rng_factory, "rng_indices_factory": rng_indices_factory,
"shape": shape, "index_shape": index_shape, "dtype": dtype,
"index_dtype": index_dtype, "axis": axis, "mode": mode}
for shape in [(3,), (3, 4), (3, 4, 5)]
for index_shape in scalar_shapes + [(3,), (2, 1, 3)]
for axis in itertools.chain(range(-len(shape), len(shape)),
[cast(Optional[int], None)])
for dtype in all_dtypes
for index_dtype in int_dtypes
for mode in ['wrap', 'clip']
for rng_factory in [jtu.rand_default]
for rng_indices_factory in [partial(jtu.rand_int, -5, 5)]))
def testTake(self, shape, dtype, index_shape, index_dtype, axis, mode,
rng_factory, rng_indices_factory):
def args_maker():
x = rng(shape, dtype)
i = rng_indices(index_shape, index_dtype)
return x, i
rng = rng_factory()
rng_indices = rng_indices_factory()
jnp_op = lambda x, i: jnp.take(x, i, axis=axis, mode=mode)
onp_op = lambda x, i: onp.take(x, i, axis=axis, mode=mode)
self._CheckAgainstNumpy(jnp_op, onp_op, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_op, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_{}_ishape={}_axis={}".format(
jtu.format_shape_dtype_string(x_shape, dtype), i_shape, axis),
"rng_factory": rng_factory, "x_shape": x_shape, "i_shape": i_shape, "dtype": dtype,
"axis": axis}
for x_shape, i_shape in filter(
_shapes_are_equal_length,
filter(_shapes_are_broadcast_compatible,
CombosWithReplacement(nonempty_nonscalar_array_shapes, 2)))
for axis in itertools.chain(range(len(x_shape)), [-1],
[cast(Optional[int], None)])
for dtype in default_dtypes
for rng_factory in [jtu.rand_default]))
def testTakeAlongAxis(self, x_shape, i_shape, dtype, axis, rng_factory):
rng = rng_factory()
i_shape = onp.array(i_shape)
if axis is None:
i_shape = [onp.prod(i_shape, dtype=onp.int64)]
else:
# Test the case where the size of the axis doesn't necessarily broadcast.
i_shape[axis] *= 3
i_shape = list(i_shape)
def args_maker():
x = rng(x_shape, dtype)
n = onp.prod(x_shape, dtype=onp.int32) if axis is None else x_shape[axis]
i = rng(i_shape, onp.int32) % (2 * n - 1) - (n - 1)
return x, i
jnp_op = lambda x, i: jnp.take_along_axis(x, i, axis=axis)
if hasattr(onp, "take_along_axis"):
onp_op = lambda x, i: onp.take_along_axis(x, i, axis=axis)
self._CheckAgainstNumpy(jnp_op, onp_op, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_op, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_shape={}_n={}_increasing={}".format(
jtu.format_shape_dtype_string([shape], dtype),
n, increasing),
"dtype": dtype, "shape": shape, "n": n, "increasing": increasing,
"rng_factory": jtu.rand_default}
for dtype in inexact_dtypes
for shape in [0, 5]
for n in [2, 4]
for increasing in [False, True]))
def testVander(self, shape, dtype, n, increasing, rng_factory):
rng = rng_factory()
def onp_fun(arg):
arg = arg.astype(onp.float32) if dtype == jnp.bfloat16 else arg
return onp.vander(arg, N=n, increasing=increasing)
jnp_fun = lambda arg: jnp.vander(arg, N=n, increasing=increasing)
args_maker = lambda: [rng([shape], dtype)]
# np.vander seems to return float64 for all floating types. We could obey
# those semantics, but they seem like a bug.
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=False,
tol={onp.float32: 1e-3})
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=False)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": jtu.format_test_name_suffix("nan_to_num", [shape],
[dtype]),
"rng_factory": jtu.rand_some_inf_and_nan, "shape": shape,
"dtype": dtype}
for shape in all_shapes
for dtype in inexact_dtypes))
def testNanToNum(self, rng_factory, shape, dtype):
rng = rng_factory()
dtype = onp.dtype(dtypes.canonicalize_dtype(dtype)).type
def onp_fun(x):
if dtype == jnp.bfloat16:
x = onp.where(onp.isnan(x), dtype(0), x)
x = onp.where(onp.isposinf(x), jnp.finfo(dtype).max, x)
x = onp.where(onp.isneginf(x), jnp.finfo(dtype).min, x)
return x
else:
return onp.nan_to_num(x).astype(dtype)
args_maker = lambda: [rng(shape, dtype)]
check_dtypes = shape is not jtu.PYTHON_SCALAR_SHAPE
self._CheckAgainstNumpy(onp_fun, jnp.nan_to_num, args_maker,
check_dtypes=check_dtypes)
self._CompileAndCheck(jnp.nan_to_num, args_maker,
check_dtypes=check_dtypes)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": jtu.format_test_name_suffix("ix_", shapes, dtypes),
"rng_factory": jtu.rand_default, "shapes": shapes, "dtypes": dtypes}
for shapes, dtypes in (
((), ()),
(((7,),), (onp.int32,)),
(((3,), (4,)), (onp.int32, onp.int32)),
(((3,), (1,), (4,)), (onp.int32, onp.int32, onp.int32)),
)))
def testIx_(self, rng_factory, shapes, dtypes):
rng = rng_factory()
args_maker = lambda: [rng(shape, dtype)
for shape, dtype in zip(shapes, dtypes)]
self._CheckAgainstNumpy(onp.ix_, jnp.ix_, args_maker,
check_dtypes=True)
self._CompileAndCheck(jnp.ix_, args_maker, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name":
"_op={}_a_shape={}_q_shape={}_axis={}_keepdims={}_interpolation={}".format(
op,
jtu.format_shape_dtype_string(a_shape, a_dtype),
jtu.format_shape_dtype_string(q_shape, q_dtype),
axis, keepdims, interpolation),
"a_rng": jtu.rand_default(), "q_rng": q_rng, "op": op,
"a_shape": a_shape, "a_dtype": a_dtype,
"q_shape": q_shape, "q_dtype": q_dtype, "axis": axis,
"keepdims": keepdims,
"interpolation": interpolation}
for (op, q_rng) in (
("percentile", jtu.rand_uniform(low=0., high=100.)),
("quantile", jtu.rand_uniform(low=0., high=1.)),
)
for a_dtype in float_dtypes
for a_shape, axis in (
((7,), None),
((47, 7), 0),
((4, 101), 1),
)
for q_dtype in [onp.float32]
for q_shape in scalar_shapes + [(4,)]
for keepdims in [False, True]
for interpolation in ['linear', 'lower', 'higher', 'nearest', 'midpoint']))
def testQuantile(self, op, a_rng, q_rng, a_shape, a_dtype, q_shape, q_dtype,
axis, keepdims, interpolation):
if op == "quantile" and numpy_version < (1, 15):
raise SkipTest("Numpy < 1.15 does not have np.quantile")
args_maker = lambda: [a_rng(a_shape, a_dtype), q_rng(q_shape, q_dtype)]
def onp_fun(*args):
args = [x if jnp.result_type(x) != jnp.bfloat16 else
onp.asarray(x, onp.float32) for x in args]
return getattr(onp, op)(*args, axis=axis, keepdims=keepdims,
interpolation=interpolation)
jnp_fun = partial(getattr(jnp, op), axis=axis, keepdims=keepdims,
interpolation=interpolation)
# TODO(phawkins): we currently set dtype=False because we aren't as
# aggressive about promoting to float64. It's not clear we want to mimic
# Numpy here.
tol_spec = {onp.float32: 2e-4, onp.float64: 5e-6}
tol = max(jtu.tolerance(a_dtype, tol_spec),
jtu.tolerance(q_dtype, tol_spec))
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=False,
tol=tol)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True, rtol=tol)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name":
"_a_shape={}_axis={}_keepdims={}".format(
jtu.format_shape_dtype_string(a_shape, a_dtype),
axis, keepdims),
"a_rng": jtu.rand_default(),
"a_shape": a_shape, "a_dtype": a_dtype,
"axis": axis,
"keepdims": keepdims}
for a_dtype in float_dtypes
for a_shape, axis in (
((7,), None),
((47, 7), 0),
((4, 101), 1),
)
for keepdims in [False, True]))
def testMedian(self, a_rng, a_shape, a_dtype, axis, keepdims):
args_maker = lambda: [a_rng(a_shape, a_dtype)]
def onp_fun(*args):
args = [x if jnp.result_type(x) != jnp.bfloat16 else
onp.asarray(x, onp.float32) for x in args]
return onp.median(*args, axis=axis, keepdims=keepdims)
jnp_fun = partial(jnp.median, axis=axis, keepdims=keepdims)
# TODO(phawkins): we currently set dtype=False because we aren't as
# aggressive about promoting to float64. It's not clear we want to mimic
# Numpy here.
tol_spec = {onp.float32: 2e-4, onp.float64: 5e-6}
tol = jtu.tolerance(a_dtype, tol_spec)
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=False,
tol=tol)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True, rtol=tol)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_shape={}".format(
jtu.format_shape_dtype_string(shape, dtype)),
"shape": shape, "dtype": dtype}
for shape in all_shapes for dtype in all_dtypes))
def testWhereOneArgument(self, shape, dtype):
rng = jtu.rand_some_zero()
onp_fun = lambda x: onp.where(x)
onp_fun = jtu.ignore_warning(
category=DeprecationWarning,
message="Calling nonzero on 0d arrays.*")(onp_fun)
jnp_fun = lambda x: jnp.where(x)
args_maker = lambda: [rng(shape, dtype)]
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=False)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_{}".format("_".join(
jtu.format_shape_dtype_string(shape, dtype)
for shape, dtype in zip(shapes, dtypes))),
"rng_factory": jtu.rand_default, "shapes": shapes, "dtypes": dtypes}
for shapes in filter(_shapes_are_broadcast_compatible,
CombosWithReplacement(all_shapes, 3))
for dtypes in CombosWithReplacement(all_dtypes, 3)))
def testWhereThreeArgument(self, rng_factory, shapes, dtypes):
rng = rng_factory()
args_maker = self._GetArgsMaker(rng_factory(), shapes, dtypes)
def onp_fun(cond, x, y):
return _promote_like_jnp(partial(onp.where, cond))(x, y)
self._CheckAgainstNumpy(onp_fun, jnp.where, args_maker,
check_dtypes=True)
self._CompileAndCheck(jnp.where, args_maker, check_dtypes=True)
def testWhereScalarPromotion(self):
x = jnp.where(jnp.array([True, False]), 3,
jnp.ones((2,), dtype=jnp.float32))
self.assertEqual(x.dtype, onp.dtype(onp.float32))
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": jtu.format_test_name_suffix("", shapes,
(onp.bool_,) * n + dtypes),
"rng_factory": jtu.rand_default, "shapes": shapes, "dtypes": dtypes}
for n in range(0, 3)
for shapes in filter(
_shapes_are_broadcast_compatible,
CombosWithReplacement(all_shapes, 2 * n + 1))
for dtypes in CombosWithReplacement(all_dtypes, n + 1)))
def testSelect(self, rng_factory, shapes, dtypes):
rng = rng_factory()
n = len(dtypes) - 1
def args_maker():
condlist = [rng(shape, onp.bool_) for shape in shapes[:n]]
choicelist = [rng(shape, dtype)
for shape, dtype in zip(shapes[n:-1], dtypes[:n])]
default = rng(shapes[-1], dtypes[-1])
return condlist, choicelist, default
# TODO(phawkins): float32/float64 type mismatches
def onp_fun(condlist, choicelist, default):
choicelist = [x if jnp.result_type(x) != jnp.bfloat16
else x.astype(onp.float32) for x in choicelist]
dtype = jnp.result_type(default, *choicelist)
return onp.select(condlist,
[onp.asarray(x, dtype=dtype) for x in choicelist],
onp.asarray(default, dtype=dtype))
self._CheckAgainstNumpy(onp_fun, jnp.select, args_maker,
check_dtypes=False)
self._CompileAndCheck(jnp.select, args_maker, check_dtypes=True,
rtol={onp.float64: 1e-7, onp.complex128: 1e-7})
def testIssue330(self):
x = jnp.full((1, 1), jnp.array([1])[0]) # doesn't crash
self.assertEqual(x[0, 0], 1)
def testScalarDtypePromotion(self):
orig_numpy_result = (1 + onp.eye(1, dtype=onp.float32)).dtype
jax_numpy_result = (1 + jnp.eye(1, dtype=jnp.float32)).dtype
self.assertEqual(orig_numpy_result, jax_numpy_result)
def testSymmetrizeDtypePromotion(self):
x = onp.eye(3, dtype=onp.float32)
orig_numpy_result = ((x + x.T) / 2).dtype
x = jnp.eye(3, dtype=jnp.float32)
jax_numpy_result = ((x + x.T) / 2).dtype
self.assertEqual(orig_numpy_result, jax_numpy_result)
# NOTE(mattjj): I disabled this test when removing lax._safe_mul because
# introducing the convention 0 * inf = 0 leads to silently wrong results in
# some cases. See this comment for details:
# https://github.com/google/jax/issues/1052#issuecomment-514083352
# def testIssue347(self):
# # https://github.com/google/jax/issues/347
# def test_fail(x):
# x = jnp.sqrt(jnp.sum(x ** 2, axis=1))
# ones = jnp.ones_like(x)
# x = jnp.where(x > 0.5, x, ones)
# return jnp.sum(x)
# x = jnp.array([[1, 2], [3, 4], [0, 0]], dtype=jnp.float64)
# result = api.grad(test_fail)(x)
# assert not onp.any(onp.isnan(result))
def testIssue453(self):
# https://github.com/google/jax/issues/453
a = onp.arange(6) + 1
ans = jnp.reshape(a, (3, 2), order='F')
expected = onp.reshape(a, (3, 2), order='F')
self.assertAllClose(ans, expected, check_dtypes=True)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": "_op={}_dtype={}".format(op, pytype.__name__),
"pytype": pytype, "dtype": dtype, "op": op}
for pytype, dtype in [(int, jnp.int_), (float, jnp.float_),
(bool, jnp.bool_), (complex, jnp.complex_)]
for op in ["atleast_1d", "atleast_2d", "atleast_3d"]))
def testAtLeastNdLiterals(self, pytype, dtype, op):
# Fixes: https://github.com/google/jax/issues/634
onp_fun = lambda arg: getattr(onp, op)(arg).astype(dtype)
jnp_fun = lambda arg: getattr(jnp, op)(arg)
args_maker = lambda: [pytype(2)]
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)
@parameterized.named_parameters(*jtu.cases_from_list(
{"testcase_name": "_case={}".format(i),
"input": input}
for i, input in enumerate([
3,
[3],
[onp.array(3)],
[onp.array([3])],
[[onp.array(3)]],
[[onp.array([3])]],
[3, 4, 5],
[
[onp.eye(2, dtype=onp.int32) * 2, onp.zeros((2, 3), dtype=onp.int32)],
[onp.ones((3, 2), dtype=onp.int32), onp.eye(3, dtype=onp.int32) * 3],
],
[onp.array([1, 2, 3]), onp.array([2, 3, 4]), 10],
[onp.ones((2, 2), dtype=onp.int32), onp.zeros((2, 2), dtype=onp.int32)],
[[onp.array([1, 2, 3])], [onp.array([2, 3, 4])]],
])))
def testBlock(self, input):
args_maker = lambda: [input]
self._CheckAgainstNumpy(onp.block, jnp.block, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp.block, args_maker, check_dtypes=True)
def testLongLong(self):
self.assertAllClose(onp.int64(7), api.jit(lambda x: x)(onp.longlong(7)),
check_dtypes=True)
def testArange(self):
# test cases inspired by dask tests at
# https://github.com/dask/dask/blob/master/dask/array/tests/test_creation.py#L92
self.assertAllClose(jnp.arange(77),
onp.arange(77, dtype=jnp.int_), check_dtypes=True)
self.assertAllClose(jnp.arange(2, 13),
onp.arange(2, 13, dtype=jnp.int_), check_dtypes=True)
self.assertAllClose(jnp.arange(4, 21, 9),
onp.arange(4, 21, 9, dtype=jnp.int_), check_dtypes=True)
self.assertAllClose(jnp.arange(53, 5, -3),
onp.arange(53, 5, -3, dtype=jnp.int_),
check_dtypes=True)
self.assertAllClose(jnp.arange(77, dtype=float),
onp.arange(77, dtype=float), check_dtypes=True)
self.assertAllClose(jnp.arange(2, 13, dtype=int),
onp.arange(2, 13, dtype=int), check_dtypes=True)
self.assertAllClose(jnp.arange(0, 1, -0.5),
onp.arange(0, 1, -0.5, dtype=jnp.float_),
check_dtypes=True)
self.assertRaises(TypeError, lambda: jnp.arange())
# test that jnp.arange(N) doesn't instantiate an ndarray
self.assertNotEqual(type(jnp.arange(77)), type(onp.arange(77)))
self.assertEqual(type(jnp.arange(77)), type(lax.iota(onp.int32, 77)))
# test that jnp.arange(N, dtype=int32) doesn't instantiate an ndarray
self.assertNotEqual(type(jnp.arange(77, dtype=jnp.int32)),
type(onp.arange(77, dtype=onp.int32)))
self.assertEqual(type(jnp.arange(77, dtype=jnp.int32)),
type(lax.iota(onp.int32, 77)))
# test laziness for int dtypes
self.assertTrue(xla.is_device_constant(jnp.arange(77)))
self.assertTrue(xla.is_device_constant(jnp.arange(77, dtype=jnp.int32)))
def testIssue830(self):
a = jnp.arange(4, dtype=jnp.complex64)
self.assertEqual(a.dtype, jnp.complex64)
def testIssue728(self):
assert jnp.allclose(jnp.eye(5000), onp.eye(5000))
self.assertEqual(0, onp.sum(jnp.eye(1050) - onp.eye(1050)))
def testIssue746(self):
jnp.arange(12).reshape(3, 4) # doesn't crash
def testIssue764(self):
x = jnp.linspace(190, 200, 4)
f = api.grad(lambda x: jnp.sum(jnp.tanh(x)))
# Expected values computed with autograd in float64 precision.
expected = onp.array([3.71669453e-165, 4.72999108e-168, 6.01954653e-171,
7.66067839e-174], onp.float64)
self.assertAllClose(f(x), expected, check_dtypes=False)
def testIssue776(self):
"""Tests that the scatter-add transpose rule instantiates symbolic zeros."""
def f(u):
y = jax.ops.index_add(onp.ones(10,), [2, 4, 5], u)
# The transpose rule for lax.tie_in returns a symbolic zero for its first
# argument.
return lax.tie_in(y, 7.)
self.assertAllClose(onp.zeros(3,), api.grad(f)(onp.ones(3,)),
check_dtypes=True)
# NOTE(mattjj): I disabled this test when removing lax._safe_mul because this
# is a numerical stability issue that should be solved with a custom jvp rule
# of the sigmoid function being differentiated here, not by safe_mul.
# def testIssue777(self):
# x = jnp.linspace(-200, 0, 4, dtype=onp.float32)
# f = api.grad(lambda x: jnp.sum(1 / (1 + jnp.exp(-x))))
# self.assertAllClose(f(x), onp.array([0., 0., 0., 0.25], dtype=onp.float32),
# check_dtypes=True)
@parameterized.named_parameters(
jtu.cases_from_list(
{"testcase_name": jtu.format_test_name_suffix(op, [()], [dtype]),
"dtype": dtype, "op": op}
for dtype in float_dtypes
for op in ("sqrt", "arccos", "arcsin", "arctan", "sin", "cos", "tan",
"sinh", "cosh", "tanh", "arccosh", "arcsinh", "arctanh", "exp",
"log", "expm1", "log1p")))
def testMathSpecialFloatValues(self, op, dtype):
onp_op = getattr(onp, op)
onp_op = jtu.ignore_warning(category=RuntimeWarning,
message="invalid value.*")(onp_op)
onp_op = jtu.ignore_warning(category=RuntimeWarning,
message="divide by zero.*")(onp_op)
onp_op = jtu.ignore_warning(category=RuntimeWarning,
message="overflow.*")(onp_op)
jnp_op = getattr(jnp, op)
dtype = onp.dtype(dtypes.canonicalize_dtype(dtype)).type
for x in (onp.nan, -onp.inf, -100., -2., -1., 0., 1., 2., 100., onp.inf,
jnp.finfo(dtype).max, onp.sqrt(jnp.finfo(dtype).max),
onp.sqrt(jnp.finfo(dtype).max) * 2.):
if onp.isnan(x) and op in ("sinh", "cosh", "expm1", "exp"):
# TODO(b/133842876, b/133842870): these return wrong outputs on CPU for
# NaN inputs.
continue
if (op in ("sin", "cos", "tan", "arctan") and
jtu.device_under_test() == "tpu"):
continue # TODO(b/132196789, b/134175194): fix and reenable.
x = dtype(x)
expected = onp_op(x)
actual = jnp_op(x)
tol = jtu.tolerance(dtype, {onp.float32: 1e-3, onp.float64: 1e-7})
self.assertAllClose(expected, actual, check_dtypes=True, atol=tol,
rtol=tol)
def testIssue883(self):
# from https://github.com/google/jax/issues/883
@partial(api.jit, static_argnums=(1,))
def f(x, v):
return x
x = jnp.ones((10, 10))
v = jnp.array([1, 2, 3])
first_call = f(x, v)
second_call = f(x, v) # doesn't crash
def testReductionOfOutOfBoundsAxis(self): # Issue 888
x = jnp.ones((3, 4))
self.assertRaises(ValueError, lambda: jnp.sum(x, axis=2))
def testIssue956(self):
self.assertRaises(TypeError, lambda: jnp.ndarray((1, 1)))
@parameterized.named_parameters(
jtu.cases_from_list(
{"testcase_name":
"_shape={}_dtype={}_out_dtype={}_axis={}_ddof={}_keepdims={}"
.format(shape, dtype, out_dtype, axis, ddof, keepdims),
"shape": shape, "dtype": dtype, "out_dtype": out_dtype, "axis": axis,
"ddof": ddof, "keepdims": keepdims, "rng_factory": rng_factory}
for shape in [(5,), (10, 5)]
for dtype in all_dtypes
for out_dtype in inexact_dtypes
for axis in [None, 0, -1]
for ddof in [0, 1, 2]
for keepdims in [False, True]
for rng_factory in [jtu.rand_default]))
def testVar(self, shape, dtype, out_dtype, axis, ddof, keepdims, rng_factory):
rng = rng_factory()
args_maker = self._GetArgsMaker(rng, [shape], [dtype])
def onp_fun(x):
out = onp.var(x.astype(jnp.promote_types(onp.float32, dtype)),
axis=axis, ddof=ddof, keepdims=keepdims)
return out.astype(out_dtype)
jnp_fun = partial(jnp.var, dtype=out_dtype, axis=axis, ddof=ddof, keepdims=keepdims)
tol = jtu.tolerance(out_dtype, {onp.float16: 1e-1, onp.float32: 1e-3,
onp.float64: 1e-3, onp.complex128: 1e-6})
self._CheckAgainstNumpy(onp_fun, jnp_fun, args_maker, check_dtypes=True,
tol=tol)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True, rtol=tol,
atol=tol)
@parameterized.named_parameters(
jtu.cases_from_list(
{"testcase_name": "_shape={}_dtype={}_rowvar={}_ddof={}_bias={}".format(
shape, dtype, rowvar, ddof, bias),
"shape": shape, "dtype": dtype, "rowvar": rowvar, "ddof": ddof,
"bias": bias, "rng_factory": rng_factory}
for shape in [(5,), (10, 5), (5, 10)]
for dtype in all_dtypes
for rowvar in [True, False]
for bias in [True, False]
for ddof in [None, 2, 3]
for rng_factory in [jtu.rand_default]))
@jtu.skip_on_devices("gpu") # TODO(b/138003641): test fails on GPU.
def testCov(self, shape, dtype, rowvar, ddof, bias, rng_factory):
rng = rng_factory()
args_maker = self._GetArgsMaker(rng, [shape], [dtype])
onp_fun = partial(onp.cov, rowvar=rowvar, ddof=ddof, bias=bias)
jnp_fun = partial(jnp.cov, rowvar=rowvar, ddof=ddof, bias=bias)
tol = {onp.float32: 1e-5, onp.float64: 1e-13, onp.complex128: 1e-13}
tol = 7e-2 if jtu.device_under_test() == "tpu" else tol
tol = jtu.join_tolerance(tol, jtu.tolerance(dtype))
self._CheckAgainstNumpy(
onp_fun, jnp_fun, args_maker, check_dtypes=False, tol=tol)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True, atol=tol,
rtol=tol)
def testIssue967(self):
self.assertRaises(TypeError, lambda: jnp.zeros(1.5))
@parameterized.named_parameters(
jtu.cases_from_list(
{"testcase_name": "_shape={}_dtype={}_rowvar={}".format(
shape, dtype, rowvar),
"shape": shape, "dtype": dtype, "rowvar": rowvar,
"rng_factory": rng_factory}
for shape in [(5,), (10, 5), (3, 10)]
for dtype in number_dtypes
for rowvar in [True, False]
for rng_factory in [jtu.rand_default]))
def testCorrCoef(self, shape, dtype, rowvar, rng_factory):
rng = rng_factory()
args_maker = self._GetArgsMaker(rng, [shape], [dtype])
mat = onp.asarray([rng(shape, dtype)])
onp_fun = partial(onp.corrcoef, rowvar=rowvar)
jnp_fun = partial(jnp.corrcoef, rowvar=rowvar)
if not onp.any(onp.isclose(onp.std(mat), 0.0)):
self._CheckAgainstNumpy(
onp_fun, jnp_fun, args_maker, check_dtypes=False,
tol=1e-2 if jtu.device_under_test() == "tpu" else None)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)
@parameterized.named_parameters(
jtu.cases_from_list(
{"testcase_name": "_shapes={}_dtype={}_indexing={}_sparse={}".format(
shapes, dtype, indexing, sparse),
"shapes": shapes, "dtype": dtype, "indexing": indexing,
"sparse": sparse, "rng_factory": rng_factory}
for shapes in [(), (5,), (5, 3)]
for dtype in number_dtypes
for indexing in ['xy', 'ij']
for sparse in [True, False]
for rng_factory in [jtu.rand_default]))
def testMeshGrid(self, shapes, dtype, indexing, sparse, rng_factory):
rng = rng_factory()
args_maker = self._GetArgsMaker(rng, [(x,) for x in shapes],
[dtype] * len(shapes))
onp_fun = partial(onp.meshgrid, indexing=indexing, sparse=sparse)
jnp_fun = partial(jnp.meshgrid, indexing=indexing, sparse=sparse)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)
@parameterized.named_parameters(
jtu.cases_from_list(
{"testcase_name": ("_start_shape={}_stop_shape={}_num={}_endpoint={}"
"_retstep={}_dtype={}").format(
start_shape, stop_shape, num, endpoint, retstep, dtype),
"start_shape": start_shape, "stop_shape": stop_shape,
"num": num, "endpoint": endpoint, "retstep": retstep,
"dtype": dtype, "rng_factory": rng_factory}
for start_shape in [(), (2,), (2, 2)]
for stop_shape in [(), (2,), (2, 2)]
for num in [0, 1, 2, 5, 20]
for endpoint in [True, False]
for retstep in [True, False]
for dtype in number_dtypes + [None,]
for rng_factory in [jtu.rand_default]))
def testLinspace(self, start_shape, stop_shape, num, endpoint,
retstep, dtype, rng_factory):
if num == 1 and not endpoint and numpy_version < (1, 17, 5):
raise SkipTest("Numpy < 1.17.5 has a linspace bug.")
rng = rng_factory()
# relax default tolerances slightly
tol = jtu.tolerance(dtype if dtype else onp.float32) * 10
args_maker = self._GetArgsMaker(rng,
[start_shape, stop_shape],
[dtype, dtype])
start, stop = args_maker()
ndim = len(onp.shape(start + stop))
for axis in range(-ndim, ndim):
jnp_op = lambda start, stop: jnp.linspace(
start, stop, num,
endpoint=endpoint, retstep=retstep, dtype=dtype, axis=axis)
onp_op = lambda start, stop: onp.linspace(
start, stop, num,
endpoint=endpoint, retstep=retstep, dtype=dtype, axis=axis)
self._CheckAgainstNumpy(onp_op, jnp_op, args_maker,
check_dtypes=False, tol=tol)
# floating-point compute between jitted platforms and non-jit + rounding
# cause unavoidable variation in integer truncation for some inputs.
if dtype in (inexact_dtypes + [None,]):
self._CompileAndCheck(jnp_op, args_maker,
check_dtypes=False, atol=tol, rtol=tol)
@parameterized.named_parameters(
jtu.cases_from_list(
{"testcase_name": ("_start_shape={}_stop_shape={}_num={}_endpoint={}"
"_base={}_dtype={}").format(
start_shape, stop_shape, num, endpoint, base,
dtype.__name__ if dtype else "None"),
"start_shape": start_shape,
"stop_shape": stop_shape,
"num": num, "endpoint": endpoint, "base": base,
"dtype": dtype, "rng_factory": rng_factory}
for start_shape in [(), (2,), (2, 2)]
for stop_shape in [(), (2,), (2, 2)]
for num in [0, 1, 2, 5, 20]
for endpoint in [True, False]
for base in [10.0, 2, onp.e]
for dtype in inexact_dtypes + [None,]
for rng_factory in [jtu.rand_default]))
def testLogspace(self, start_shape, stop_shape, num,
endpoint, base, dtype, rng_factory):
if (dtype in int_dtypes and
jtu.device_under_test() in ("gpu", "tpu") and
not FLAGS.jax_enable_x64):
raise unittest.SkipTest("GPUx32 truncated exponentiation"
" doesn't exactly match other platforms.")
rng = rng_factory()
# relax default tolerances slightly
tol = {onp.float16: 2e-2, onp.float32: 1e-2, onp.float64: 1e-6,
onp.complex64: 1e-3, onp.complex128: 1e-6}
args_maker = self._GetArgsMaker(rng,
[start_shape, stop_shape],
[dtype, dtype])
start, stop = args_maker()
ndim = len(onp.shape(start + stop))
for axis in range(-ndim, ndim):
jnp_op = lambda start, stop: jnp.logspace(
start, stop, num, endpoint=endpoint, base=base, dtype=dtype, axis=axis)
onp_op = lambda start, stop: onp.logspace(
start, stop, num, endpoint=endpoint, base=base, dtype=dtype, axis=axis)
self._CheckAgainstNumpy(onp_op, jnp_op, args_maker,
check_dtypes=False, tol=tol)
if dtype in (inexact_dtypes + [None,]):
# Why do compiled and op-by-op float16 np.power numbers differ
# slightly more than expected?
atol = {onp.float16: 1e-2}
self._CompileAndCheck(jnp_op, args_maker,
check_dtypes=False, atol=atol, rtol=tol)
@parameterized.named_parameters(
jtu.cases_from_list(
{"testcase_name": ("_start_shape={}_stop_shape={}_num={}_endpoint={}"
"_dtype={}").format(
start_shape, stop_shape, num, endpoint, dtype),
"start_shape": start_shape,
"stop_shape": stop_shape,
"num": num, "endpoint": endpoint,
"dtype": dtype, "rng_factory": rng_factory}
for start_shape in [(), (2,), (2, 2)]
for stop_shape in [(), (2,), (2, 2)]
for num in [0, 1, 2, 5, 20]
for endpoint in [True, False]
# NB: numpy's geomspace gives nonsense results on integer types
for dtype in inexact_dtypes + [None,]
for rng_factory in [jtu.rand_default]))
def testGeomspace(self, start_shape, stop_shape, num,
endpoint, dtype, rng_factory):
rng = rng_factory()
# relax default tolerances slightly
tol = {onp.float16: 4e-3, onp.float32: 2e-3, onp.complex128: 1e-14}
def args_maker():
"""Test the set of inputs onp.geomspace is well-defined on."""
start, stop = self._GetArgsMaker(rng,
[start_shape, stop_shape],
[dtype, dtype])()
# onp.geomspace can't handle differently ranked tensors
# w. negative numbers!
start, stop = jnp.broadcast_arrays(start, stop)
if dtype in complex_dtypes:
return start, stop
# to avoid NaNs, non-complex start and stop cannot
# differ in sign, elementwise
start = start * jnp.sign(start) * jnp.sign(stop)
return start, stop
start, stop = args_maker()
ndim = len(onp.shape(start + stop))
for axis in range(-ndim, ndim):
def jnp_op(start, stop):
return jnp.geomspace(start, stop, num, endpoint=endpoint, dtype=dtype,
axis=axis)
def onp_op(start, stop):
start = start.astype(onp.float32) if dtype == jnp.bfloat16 else start
stop = stop.astype(onp.float32) if dtype == jnp.bfloat16 else stop
return onp.geomspace(
start, stop, num, endpoint=endpoint,
dtype=dtype if dtype != jnp.bfloat16 else onp.float32,
axis=axis).astype(dtype)
self._CheckAgainstNumpy(onp_op, jnp_op, args_maker,
check_dtypes=False, tol=tol)
if dtype in (inexact_dtypes + [None,]):
self._CompileAndCheck(jnp_op, args_maker,
check_dtypes=False, atol=tol, rtol=tol)
def testDisableNumpyRankPromotionBroadcasting(self):
try:
prev_flag = FLAGS.jax_numpy_rank_promotion
FLAGS.jax_numpy_rank_promotion = "allow"
jnp.ones(2) + jnp.ones((1, 2)) # works just fine
finally:
FLAGS.jax_numpy_rank_promotion = prev_flag
try:
prev_flag = FLAGS.jax_numpy_rank_promotion
FLAGS.jax_numpy_rank_promotion = "raise"
self.assertRaises(ValueError, lambda: jnp.ones(2) + jnp.ones((1, 2)))
finally:
FLAGS.jax_numpy_rank_promotion = prev_flag
try:
prev_flag = FLAGS.jax_numpy_rank_promotion
FLAGS.jax_numpy_rank_promotion = "warn"
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
jnp.ones(2) + jnp.ones((1, 2))
assert len(w) > 0
msg = str(w[-1].message)
expected_msg = ("Following NumPy automatic rank promotion for add on "
"shapes (2,) (1, 2).")
self.assertEqual(msg[:len(expected_msg)], expected_msg)
prev_len = len(w)
jnp.ones(2) + 3
self.assertEqual(len(w), prev_len) # don't want to warn for scalars
finally:
FLAGS.jax_numpy_rank_promotion = prev_flag
def testStackArrayArgument(self):
# tests https://github.com/google/jax/issues/1271
@api.jit
def foo(x):
return jnp.stack(x)
foo(onp.zeros(2)) # doesn't crash
@api.jit
def foo(x):
return jnp.concatenate(x)
foo(onp.zeros((2, 2))) # doesn't crash
def testReluGradientConstants(self):
# This is a regression test that verifies that constants associated with the
# gradient of np.maximum (from lax._balanced_eq) aren't hoisted into the
# outermost jaxpr. This was producing some large materialized constants for
# every relu activation in a model.
def body(i, xy):
x, y = xy
y = y + jax.grad(lambda z: jnp.sum(jnp.maximum(z, 0.)))(x)
return x, y
f = lambda y: lax.fori_loop(0, 5, body, (y, y))
wrapped = linear_util.wrap_init(f)
pv = partial_eval.PartialVal.unknown(jax.ShapedArray((3, 4), onp.float32))
_, _, consts = partial_eval.trace_to_jaxpr(wrapped, [pv])
self.assertFalse(
any(onp.array_equal(x, onp.full((3, 4), 2., dtype=onp.float32))
for x in consts))
@parameterized.named_parameters(
{"testcase_name": "_from={}_to={}".format(from_shape, to_shape),
"rng_factory": rng_factory, "from_shape": from_shape, "to_shape": to_shape}
for from_shape, to_shape in [
[(1, 3), (4, 3)],
[(3,), (2, 1, 3)],
[(3,), (3, 3)],
[(1,), (3,)],
]
for rng_factory in [jtu.rand_default])
def testBroadcastTo(self, from_shape, to_shape, rng_factory):
rng = rng_factory()
args_maker = self._GetArgsMaker(rng, [from_shape], [onp.float32])
onp_op = lambda x: onp.broadcast_to(x, to_shape)
jnp_op = lambda x: jnp.broadcast_to(x, to_shape)
self._CheckAgainstNumpy(onp_op, jnp_op, args_maker, check_dtypes=True)
self._CompileAndCheck(jnp_op, args_maker, check_dtypes=True)
def testBroadcastToIssue1522(self):
self.assertRaisesRegex(
ValueError, "Incompatible shapes for broadcasting: .*",
lambda: jnp.broadcast_to(onp.ones((2, 3)), (1, 3)))
def testBroadcastToIntIssue1548(self):
self.assertAllClose(jnp.broadcast_to(1, (3, 2)), onp.ones((3, 2)),
check_dtypes=False)
def testBroadcastToOnScalar(self):
self.assertIsInstance(jnp.broadcast_to(10.0, ()), jnp.ndarray)
self.assertIsInstance(onp.broadcast_to(10.0, ()), onp.ndarray)
def testPrecision(self):
ones_1d = onp.ones((2,))
ones_2d = onp.ones((2, 2))
ones_3d = onp.ones((2, 2, 2))
HIGHEST = lax.Precision.HIGHEST
jtu.assert_dot_precision(None, jnp.dot, ones_1d, ones_1d)
jtu.assert_dot_precision(
HIGHEST,
partial(jnp.dot, precision=HIGHEST),
ones_1d, ones_1d)
jtu.assert_dot_precision(
HIGHEST,
partial(jnp.dot, precision=HIGHEST),
ones_3d, ones_3d)
jtu.assert_dot_precision(
HIGHEST,
partial(jnp.matmul, precision=HIGHEST),
ones_2d, ones_2d)
jtu.assert_dot_precision(
HIGHEST,
partial(jnp.vdot, precision=HIGHEST),
ones_1d, ones_1d)
jtu.assert_dot_precision(
HIGHEST,
partial(jnp.tensordot, axes=2, precision=HIGHEST),
ones_2d, ones_2d)
jtu.assert_dot_precision(
HIGHEST,
partial(jnp.tensordot, axes=(0, 0), precision=HIGHEST),
ones_1d, ones_1d)
jtu.assert_dot_precision(
HIGHEST,
partial(jnp.tensordot, axes=((0,), (0,)), precision=HIGHEST),
ones_1d, ones_1d)
jtu.assert_dot_precision(
HIGHEST,
partial(jnp.einsum, 'i,i', precision=HIGHEST),
ones_1d, ones_1d)
jtu.assert_dot_precision(
HIGHEST,
partial(jnp.einsum, 'ij,ij', precision=HIGHEST),
ones_2d, ones_2d)
jtu.assert_dot_precision(
HIGHEST,
partial(jnp.inner, precision=HIGHEST),
ones_1d, ones_1d)
@parameterized.named_parameters(
jtu.cases_from_list(
{"testcase_name": ("_shape={}_axis={}_dtype={}").format(shape, axis, dtype),
"shape": shape,
"axis": axis,
"dtype": dtype, "rng_factory": rng_factory}
for shape in [(10,), (10, 15), (10, 15, 20)]
for _num_axes in range(len(shape))
for axis in itertools.combinations(range(len(shape)), _num_axes)
for dtype in inexact_dtypes
for rng_factory in [jtu.rand_default]))
def testGradient(self, shape, axis, dtype, rng_factory):
rng = rng_factory()
args_maker = self._GetArgsMaker(rng, [shape], [dtype])
jnp_fun = lambda y: jnp.gradient(y, axis=axis)
onp_fun = lambda y: onp.gradient(y, axis=axis)
self._CheckAgainstNumpy(
onp_fun, jnp_fun, args_maker, check_dtypes=False)
self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)
def testZerosShapeErrors(self):
# see https://github.com/google/jax/issues/1822
self.assertRaisesRegex(
TypeError,
"Shapes must be 1D sequences of concrete values of integer type.*",
lambda: jnp.zeros(1.))
self.assertRaisesRegex(
TypeError,
"Shapes must be 1D sequences of concrete values of integer type.*\n"
"If using `jit`, try using `static_argnums` or applying `jit` to smaller subfunctions.",
lambda: api.jit(jnp.zeros)(2))
def testTraceMethod(self):
x = onp.random.randn(3, 4).astype(jnp.float_)
self.assertAllClose(x.trace(), jnp.array(x).trace(), check_dtypes=True)
self.assertAllClose(x.trace(), api.jit(lambda y: y.trace())(x),
check_dtypes=True)
# Most grad tests are at the lax level (see lax_test.py), but we add some here
# as needed for e.g. particular compound ops of interest.
GradTestSpec = collections.namedtuple(
"GradTestSpec",
["op", "nargs", "order", "rng_factory", "dtypes", "name", "tol"])
def grad_test_spec(op, nargs, order, rng_factory, dtypes, name=None, tol=None):
return GradTestSpec(
op, nargs, order, rng_factory, dtypes, name or op.__name__, tol)
GRAD_TEST_RECORDS = [
grad_test_spec(jnp.arcsinh, nargs=1, order=2,
rng_factory=jtu.rand_positive,
dtypes=[onp.float64, onp.complex64], tol=1e-4),
grad_test_spec(jnp.arccosh, nargs=1, order=2,
rng_factory=jtu.rand_positive,
dtypes=[onp.float64, onp.complex64], tol=1e-4),
grad_test_spec(jnp.arctanh, nargs=1, order=2,
rng_factory=partial(jtu.rand_uniform, -0.9, 0.9),
dtypes=[onp.float64, onp.complex64], tol=1e-4),
grad_test_spec(jnp.logaddexp, nargs=2, order=1,
rng_factory=partial(jtu.rand_uniform, -0.9, 0.9),
dtypes=[onp.float64], tol=1e-4),
grad_test_spec(jnp.logaddexp2, nargs=2, order=2,
rng_factory=partial(jtu.rand_uniform, -0.9, 0.9),
dtypes=[onp.float64], tol=1e-4),
]
GradSpecialValuesTestSpec = collections.namedtuple(
"GradSpecialValuesTestSpec", ["op", "values", "order"])
GRAD_SPECIAL_VALUE_TEST_RECORDS = [
GradSpecialValuesTestSpec(jnp.arcsinh, [0., 1000.], 2),
GradSpecialValuesTestSpec(jnp.arccosh, [1000.], 2),
GradSpecialValuesTestSpec(jnp.arctanh, [0.], 2),
GradSpecialValuesTestSpec(jnp.sinc, [0.], 1),
]
def num_float_bits(dtype):
return jnp.finfo(dtypes.canonicalize_dtype(dtype)).bits
class NumpyGradTests(jtu.JaxTestCase):
@parameterized.named_parameters(itertools.chain.from_iterable(
jtu.cases_from_list(
{"testcase_name": jtu.format_test_name_suffix(
rec.name, shapes, itertools.repeat(dtype)),
"op": rec.op, "rng_factory": rec.rng_factory, "shapes": shapes, "dtype": dtype,
"order": rec.order, "tol": rec.tol}
for shapes in CombosWithReplacement(nonempty_shapes, rec.nargs)
for dtype in rec.dtypes)
for rec in GRAD_TEST_RECORDS))
def testOpGrad(self, op, rng_factory, shapes, dtype, order, tol):
rng = rng_factory()
tol = {onp.float32: 1e-1, onp.complex64: 1e-1}
args = tuple(rng(shape, dtype) for shape in shapes)
check_grads(op, args, order, ["fwd", "rev"], tol, tol)
@parameterized.named_parameters(itertools.chain.from_iterable(
jtu.cases_from_list(
{"testcase_name": "_{}_{}".format(rec.op.__name__, special_value),
"op": rec.op, "special_value": special_value, "order": rec.order}
for special_value in rec.values)
for rec in GRAD_SPECIAL_VALUE_TEST_RECORDS))
def testOpGradSpecialValue(self, op, special_value, order):
check_grads(op, (special_value,), order, ["fwd", "rev"],
atol={onp.float32: 3e-3})
def testTakeAlongAxisIssue1521(self):
# https://github.com/google/jax/issues/1521
idx = jnp.repeat(jnp.arange(3), 10).reshape((30, 1))
def f(x):
y = x * jnp.arange(3.).reshape((1, 3))
return jnp.take_along_axis(y, idx, -1).sum()
check_grads(f, (1.,), order=1)
if __name__ == "__main__":
absltest.main()
| tests/lax_numpy_test.py | 140,061 | Tests for LAX-backed Numpy implementation.
Decorator that promotes the arguments of `fun` to `jnp.result_type(*args)`.
jnp and onp have different type promotion semantics; this decorator allows
tests make an onp reference implementation act more like an jnp
implementation.
Test the set of inputs onp.geomspace is well-defined on.
Following numpy test suite from `test_repeat` at https://github.com/numpy/numpy/blob/master/numpy/core/tests/test_multiarray.py
Make sure return value of jnp.concatenate is a jax.ndarray and is side-effect save
Tests that the scatter-add transpose rule instantiates symbolic zeros.
Copyright 2018 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Not all (shape, dtype) pairs are valid. In particular, Python scalars only have one type in each category (float, bool, etc.) TODO(b/142975473): on CPU, tanh for complex128 is only accurate to ~float32 precision. TODO(b/143135720): on GPU, tanh has only ~float32 precision. angle has inconsistent 32/64-bit return types across numpy versions. TODO(b/142975473): on CPU, expm1 for float64 is only accurate to ~float32 precision. TODO(mattjj): __invert__ fails on bool dtypes because ~True == -2 TODO(mattjj): investigate these failures op_record("__or__", 2, number_dtypes, all_shapes, jtu.rand_bool, []), op_record("__and__", 2, number_dtypes, all_shapes, jtu.rand_default, []), op_record("__xor__", 2, number_dtypes, all_shapes, jtu.rand_bool, []), op_record("__divmod__", 2, number_dtypes, all_shapes, jtu.rand_nonzero, []), TODO(mattjj): lshift, rshift op_record("__ror__", 2, number_dtypes, all_shapes, jtu.rand_bool, []), op_record("__rand__", 2, number_dtypes, all_shapes, jtu.rand_default, []), op_record("__rxor__", 2, number_dtypes, all_shapes, jtu.rand_bool, []), op_record("__rdivmod__", 2, number_dtypes, all_shapes, jtu.rand_nonzero, []), The following condition seems a little ad hoc, but seems to capture what numpy actually implements. onp and jnp arrays have different type promotion rules; force the use of jnp arrays.not scalar_arg and not empty_shape, TODO(mattjj): clean up not scalar_arg and not empty_shape, scalar output 2D vectors 3D vectors broadcasting different axes more broadcasting mixed 2D and 3D vectors axes/broadcasting axisc should do nothing same as before from issue 740 TODO(phawkins): support integer dtypes too. TODO(phawkins): there are float32/float64 disagreements for some inputs. TODO(phawkins): the promotion behavior changed in Numpy 1.17. TODO(b/153053081) integer types are converted to float64 in numpy's implementation integer types are converted to float64 in numpy's implementation `weights_shape` is either `None`, same as the averaged axis, or same as that of the input TODO(b/32368900): TPUs don't support uint8 yet. TODO(mattjj): investigate this failure TODO(mattjj): update this test for jax3 To check that the constant handler generates a Broadcast for stride-zero arrays, we monkey-patch the client instance. TODO(mattjj): once we have better HLO dumping and inspecting facilities, we can check the HLO more directly. pylint: disable=invalid-name the ndarray constant handler should call Broadcast here TODO(mattjj): update this for jax3 No error if there's no tracing. Test negative axes TODO(mattjj): test infix operator overrides TODO(mattjj): test other ndarray-like method overrides from https://github.com/google/jax/issues/125 from https://github.com/google/jax/issues/145 manual tests for sort are nice because we don't have to worry about ties. lax.sort is tested combinatorially. last axis Test the case where the size of the axis doesn't necessarily broadcast. np.vander seems to return float64 for all floating types. We could obey those semantics, but they seem like a bug. TODO(phawkins): we currently set dtype=False because we aren't as aggressive about promoting to float64. It's not clear we want to mimic Numpy here. TODO(phawkins): we currently set dtype=False because we aren't as aggressive about promoting to float64. It's not clear we want to mimic Numpy here. TODO(phawkins): float32/float64 type mismatches doesn't crash NOTE(mattjj): I disabled this test when removing lax._safe_mul because introducing the convention 0 * inf = 0 leads to silently wrong results in some cases. See this comment for details: https://github.com/google/jax/issues/1052issuecomment-514083352 def testIssue347(self): https://github.com/google/jax/issues/347 def test_fail(x): x = jnp.sqrt(jnp.sum(x ** 2, axis=1)) ones = jnp.ones_like(x) x = jnp.where(x > 0.5, x, ones) return jnp.sum(x) x = jnp.array([[1, 2], [3, 4], [0, 0]], dtype=jnp.float64) result = api.grad(test_fail)(x) assert not onp.any(onp.isnan(result)) https://github.com/google/jax/issues/453 Fixes: https://github.com/google/jax/issues/634 test cases inspired by dask tests at https://github.com/dask/dask/blob/master/dask/array/tests/test_creation.pyL92 test that jnp.arange(N) doesn't instantiate an ndarray test that jnp.arange(N, dtype=int32) doesn't instantiate an ndarray test laziness for int dtypes doesn't crash Expected values computed with autograd in float64 precision. The transpose rule for lax.tie_in returns a symbolic zero for its first argument. NOTE(mattjj): I disabled this test when removing lax._safe_mul because this is a numerical stability issue that should be solved with a custom jvp rule of the sigmoid function being differentiated here, not by safe_mul. def testIssue777(self): x = jnp.linspace(-200, 0, 4, dtype=onp.float32) f = api.grad(lambda x: jnp.sum(1 / (1 + jnp.exp(-x)))) self.assertAllClose(f(x), onp.array([0., 0., 0., 0.25], dtype=onp.float32), check_dtypes=True) TODO(b/133842876, b/133842870): these return wrong outputs on CPU for NaN inputs. TODO(b/132196789, b/134175194): fix and reenable. from https://github.com/google/jax/issues/883 doesn't crash Issue 888 TODO(b/138003641): test fails on GPU. relax default tolerances slightly floating-point compute between jitted platforms and non-jit + rounding cause unavoidable variation in integer truncation for some inputs. relax default tolerances slightly Why do compiled and op-by-op float16 np.power numbers differ slightly more than expected? NB: numpy's geomspace gives nonsense results on integer types relax default tolerances slightly onp.geomspace can't handle differently ranked tensors w. negative numbers! to avoid NaNs, non-complex start and stop cannot differ in sign, elementwise works just fine don't want to warn for scalars tests https://github.com/google/jax/issues/1271 doesn't crash doesn't crash This is a regression test that verifies that constants associated with the gradient of np.maximum (from lax._balanced_eq) aren't hoisted into the outermost jaxpr. This was producing some large materialized constants for every relu activation in a model. see https://github.com/google/jax/issues/1822 Most grad tests are at the lax level (see lax_test.py), but we add some here as needed for e.g. particular compound ops of interest. https://github.com/google/jax/issues/1521 | 7,540 | en | 0.813467 |
# -*- coding: utf-8 -*-
from .. import OratorTestCase
from lorator.support.collection import Collection
class CollectionTestCase(OratorTestCase):
def test_first_returns_first_item_in_collection(self):
c = Collection(["foo", "bar"])
self.assertEqual("foo", c.first())
def test_last_returns_last_item_in_collection(self):
c = Collection(["foo", "bar"])
self.assertEqual("bar", c.last())
def test_pop_removes_and_returns_last_item_or_specified_index(self):
c = Collection(["foo", "bar"])
self.assertEqual("bar", c.pop())
self.assertEqual("foo", c.last())
c = Collection(["foo", "bar"])
self.assertEqual("foo", c.pop(0))
self.assertEqual("bar", c.first())
def test_shift_removes_and_returns_first_item(self):
c = Collection(["foo", "bar"])
self.assertEqual("foo", c.shift())
self.assertEqual("bar", c.first())
def test_empty_collection_is_empty(self):
c = Collection()
c2 = Collection([])
self.assertTrue(c.is_empty())
self.assertTrue(c2.is_empty())
def test_collection_is_constructed(self):
c = Collection("foo")
self.assertEqual(["foo"], c.all())
c = Collection(2)
self.assertEqual([2], c.all())
c = Collection(False)
self.assertEqual([False], c.all())
c = Collection(None)
self.assertEqual([], c.all())
c = Collection()
self.assertEqual([], c.all())
def test_offset_access(self):
c = Collection(["foo", "bar"])
self.assertEqual("bar", c[1])
c[1] = "baz"
self.assertEqual("baz", c[1])
del c[0]
self.assertEqual("baz", c[0])
def test_forget(self):
c = Collection(["foo", "bar", "boom"])
c.forget(0)
self.assertEqual("bar", c[0])
c.forget(0, 1)
self.assertTrue(c.is_empty())
def test_get_avg_items_from_collection(self):
c = Collection([{"foo": 10}, {"foo": 20}])
self.assertEqual(15, c.avg("foo"))
c = Collection([1, 2, 3, 4, 5])
self.assertEqual(3, c.avg())
c = Collection()
self.assertIsNone(c.avg())
def test_collapse(self):
obj1 = object()
obj2 = object()
c = Collection([[obj1], [obj2]])
self.assertEqual([obj1, obj2], c.collapse().all())
def test_collapse_with_nested_collection(self):
c = Collection([Collection([1, 2, 3]), Collection([4, 5, 6])])
self.assertEqual([1, 2, 3, 4, 5, 6], c.collapse().all())
def test_contains(self):
c = Collection([1, 3, 5])
self.assertTrue(c.contains(1))
self.assertFalse(c.contains(2))
self.assertTrue(c.contains(lambda x: x < 5))
self.assertFalse(c.contains(lambda x: x > 5))
self.assertIn(3, c)
c = Collection([{"v": 1}, {"v": 3}, {"v": 5}])
self.assertTrue(c.contains("v", 1))
self.assertFalse(c.contains("v", 2))
obj1 = type("lamdbaobject", (object,), {})()
obj1.v = 1
obj2 = type("lamdbaobject", (object,), {})()
obj2.v = 3
obj3 = type("lamdbaobject", (object,), {})()
obj3.v = 5
c = Collection([{"v": 1}, {"v": 3}, {"v": 5}])
self.assertTrue(c.contains("v", 1))
self.assertFalse(c.contains("v", 2))
def test_countable(self):
c = Collection(["foo", "bar"])
self.assertEqual(2, c.count())
self.assertEqual(2, len(c))
def test_diff(self):
c = Collection(["foo", "bar"])
self.assertEqual(["foo"], c.diff(Collection(["bar", "baz"])).all())
def test_each(self):
original = ["foo", "bar", "baz"]
c = Collection(original)
result = []
c.each(lambda x: result.append(x))
self.assertEqual(result, original)
self.assertEqual(original, c.all())
def test_every(self):
c = Collection([1, 2, 3, 4, 5, 6])
self.assertEqual([1, 3, 5], c.every(2).all())
self.assertEqual([2, 4, 6], c.every(2, 1).all())
def test_filter(self):
c = Collection([{"id": 1, "name": "hello"}, {"id": 2, "name": "world"}])
self.assertEqual(
[{"id": 2, "name": "world"}], c.filter(lambda item: item["id"] == 2).all()
)
c = Collection(["", "hello", "", "world"])
self.assertEqual(["hello", "world"], c.filter().all())
def test_where(self):
c = Collection([{"v": 1}, {"v": 3}, {"v": 2}, {"v": 3}, {"v": 4}])
self.assertEqual([{"v": 3}, {"v": 3}], c.where("v", 3).all())
def test_implode(self):
obj1 = type("lamdbaobject", (object,), {})()
obj1.name = "john"
obj1.email = "foo"
c = Collection(
[{"name": "john", "email": "foo"}, {"name": "jane", "email": "bar"}]
)
self.assertEqual("foobar", c.implode("email"))
self.assertEqual("foo,bar", c.implode("email", ","))
c = Collection(["foo", "bar"])
self.assertEqual("foobar", c.implode(""))
self.assertEqual("foo,bar", c.implode(","))
def test_lists(self):
obj1 = type("lamdbaobject", (object,), {})()
obj1.name = "john"
obj1.email = "foo"
c = Collection([obj1, {"name": "jane", "email": "bar"}])
self.assertEqual({"john": "foo", "jane": "bar"}, c.lists("email", "name"))
self.assertEqual(["foo", "bar"], c.pluck("email").all())
def test_map(self):
c = Collection([1, 2, 3, 4, 5])
self.assertEqual([3, 4, 5, 6, 7], c.map(lambda x: x + 2).all())
def test_merge(self):
c = Collection([1, 2, 3])
c.merge([4, 5, 6])
self.assertEqual([1, 2, 3, 4, 5, 6], c.all())
c = Collection(Collection([1, 2, 3]))
c.merge([4, 5, 6])
self.assertEqual([1, 2, 3, 4, 5, 6], c.all())
def test_for_page(self):
c = Collection([1, 2, 3, 4, 5, 6])
self.assertEqual([4, 5, 6], c.for_page(2, 3).all())
self.assertEqual([5, 6], c.for_page(2, 4).all())
def test_prepend(self):
c = Collection([4, 5, 6])
c.prepend(3)
self.assertEqual([3, 4, 5, 6], c.all())
def test_append(self):
c = Collection([3, 4, 5])
c.append(6)
self.assertEqual([3, 4, 5, 6], c.all())
def test_pull(self):
c = Collection([1, 2, 3, 4])
c.pull(2)
self.assertEqual([1, 2, 4], c.all())
def test_put(self):
c = Collection([1, 2, 4])
c.put(2, 3)
self.assertEqual([1, 2, 3], c.all())
def test_reject(self):
c = Collection([1, 2, 3, 4, 5, 6])
self.assertEqual([1, 2, 3], c.reject(lambda x: x > 3).all())
def test_reverse(self):
c = Collection([1, 2, 3, 4])
self.assertEqual([4, 3, 2, 1], c.reverse().all())
def test_sort(self):
c = Collection([5, 3, 1, 2, 4])
sorted = c.sort(lambda x: x)
self.assertEqual([1, 2, 3, 4, 5], sorted.all())
def test_take(self):
c = Collection([1, 2, 3, 4, 5, 6])
self.assertEqual([1, 2, 3], c.take(3).all())
self.assertEqual([4, 5, 6], c.take(-3).all())
def test_transform(self):
c = Collection([1, 2, 3, 4])
c.transform(lambda x: x + 2)
self.assertEqual([3, 4, 5, 6], c.all())
def test_zip(self):
c = Collection([1, 2, 3])
self.assertEqual([(1, 4), (2, 5), (3, 6)], c.zip([4, 5, 6]).all())
def test_only(self):
c = Collection([1, 2, 3, 4, 5])
self.assertEqual([2, 4], c.only(1, 3).all())
def test_without(self):
c = Collection([1, 2, 3, 4, 5])
self.assertEqual([1, 3, 5], c.without(1, 3).all())
self.assertEqual([1, 2, 3, 4, 5], c.all())
def test_flatten(self):
c = Collection({"foo": [5, 6], "bar": 7, "baz": {"boom": [1, 2, 3, 4]}})
self.assertEqual([1, 2, 3, 4, 5, 6, 7], c.flatten().sort().all())
c = Collection([1, [2, 3], 4])
self.assertEqual([1, 2, 3, 4], c.flatten().all())
| tests/support/test_collection.py | 8,037 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
#!/usr/bin/env python
#
# Copyright (c) 2018 SAP SE
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
# this script checks for volume attachments of already deleted volumes in the cinder db
import argparse
import configparser
import datetime
import logging
import os
import sys
from openstack import connection, exceptions
from sqlalchemy import and_, MetaData, select, Table, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
log = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO, format='%(asctime)-15s %(message)s')
# get all instances from nova
def get_nova_instances(conn):
nova_instances = dict()
# get all instance from nova
try:
for nova_instance in conn.compute.servers(details=False, all_projects=1):
nova_instances[nova_instance.id] = nova_instance
if not nova_instances:
raise RuntimeError('- PLEASE CHECK MANUALLY - did not get any nova instances back from the nova api - this should in theory never happen ...')
except exceptions.HttpException as e:
log.warn("- PLEASE CHECK MANUALLY - got an http exception connecting to openstack: %s", str(e))
sys.exit(1)
except exceptions.SDKException as e:
log.warn("- PLEASE CHECK MANUALLY - got an sdk exception connecting to openstack: %s", str(e))
sys.exit(1)
#for i in nova_instances:
# print nova_instances[i].id
if not nova_instances:
raise RuntimeError('Did not get any nova instances back.')
return nova_instances
# get all volume attachments for volumes
def get_orphan_volume_attachments(meta):
orphan_volume_attachments = {}
orphan_volume_attachment_t = Table('volume_attachment', meta, autoload=True)
columns = [orphan_volume_attachment_t.c.id, orphan_volume_attachment_t.c.instance_uuid]
orphan_volume_attachment_q = select(columns=columns, whereclause=and_(orphan_volume_attachment_t.c.deleted == 0))
# return a dict indexed by orphan_volume_attachment_id and with the value nova_instance_uuid for non deleted orphan_volume_attachments
for (orphan_volume_attachment_id, nova_instance_uuid) in orphan_volume_attachment_q.execute():
orphan_volume_attachments[orphan_volume_attachment_id] = nova_instance_uuid
return orphan_volume_attachments
# get all the volume attachments in the cinder db for already deleted instances in nova
def get_wrong_orphan_volume_attachments(nova_instances, orphan_volume_attachments):
wrong_orphan_volume_attachments = {}
for orphan_volume_attachment_id in orphan_volume_attachments:
if nova_instances.get(orphan_volume_attachments[orphan_volume_attachment_id]) is None:
wrong_orphan_volume_attachments[orphan_volume_attachment_id] = orphan_volume_attachments[orphan_volume_attachment_id]
return wrong_orphan_volume_attachments
# delete volume attachments in the cinder db for already deleted instances in nova
def fix_wrong_orphan_volume_attachments(meta, wrong_orphan_volume_attachments, fix_limit):
if len(wrong_orphan_volume_attachments) <= int(fix_limit):
orphan_volume_attachment_t = Table('volume_attachment', meta, autoload=True)
for orphan_volume_attachment_id in wrong_orphan_volume_attachments:
log.info ("-- action: deleting orphan volume attachment id: %s", orphan_volume_attachment_id)
now = datetime.datetime.utcnow()
delete_orphan_volume_attachment_q = orphan_volume_attachment_t.update().\
where(orphan_volume_attachment_t.c.id == orphan_volume_attachment_id).values(updated_at=now, deleted_at=now, deleted=1)
delete_orphan_volume_attachment_q.execute()
else:
log.warn("- PLEASE CHECK MANUALLY - too many (more than %s) wrong orphan volume attachments - denying to fix them automatically", str(fix_limit))
# get all the volumes in state "error_deleting"
def get_error_deleting_volumes(meta):
error_deleting_volumes = []
volumes_t = Table('volumes', meta, autoload=True)
error_deleting_volumes_q = select(columns=[volumes_t.c.id]).where(and_(volumes_t.c.status == "error_deleting",volumes_t.c.deleted == 0))
# convert the query result into a list
for i in error_deleting_volumes_q.execute():
error_deleting_volumes.append(i[0])
return error_deleting_volumes
# delete all the volumes in state "error_deleting"
def fix_error_deleting_volumes(meta, error_deleting_volumes):
volumes_t = Table('volumes', meta, autoload=True)
volume_attachment_t = Table('volume_attachment', meta, autoload=True)
volume_metadata_t = Table('volume_metadata', meta, autoload=True)
volume_admin_metadata_t = Table('volume_admin_metadata', meta, autoload=True)
for error_deleting_volumes_id in error_deleting_volumes:
now = datetime.datetime.utcnow()
log.info("-- action: deleting possible volume admin metadata for volume id: %s", error_deleting_volumes_id)
delete_volume_admin_metadata_q = volume_admin_metadata_t.update().\
where(volume_admin_metadata_t.c.volume_id == error_deleting_volumes_id).values(updated_at=now, deleted_at=now, deleted=1)
delete_volume_admin_metadata_q.execute()
log.info("-- action: deleting possible volume metadata for volume id: %s", error_deleting_volumes_id)
delete_volume_metadata_q = volume_metadata_t.update().\
where(volume_metadata_t.c.volume_id == error_deleting_volumes_id).values(updated_at=now, deleted_at=now, deleted=1)
delete_volume_metadata_q.execute()
log.info("-- action: deleting possible volume attachments for volume id: %s", error_deleting_volumes_id)
delete_volume_attachment_q = volume_attachment_t.update().\
where(volume_attachment_t.c.volume_id == error_deleting_volumes_id).values(updated_at=now, deleted_at=now, deleted=1)
delete_volume_attachment_q.execute()
log.info("-- action: deleting volume id: %s", error_deleting_volumes_id)
delete_volume_q = volumes_t.update().\
where(volumes_t.c.id == error_deleting_volumes_id).values(updated_at=now, deleted_at=now, deleted=1)
delete_volume_q.execute()
# get all the snapshots in state "error_deleting"
def get_error_deleting_snapshots(meta):
error_deleting_snapshots = []
snapshots_t = Table('snapshots', meta, autoload=True)
error_deleting_snapshots_q = select(columns=[snapshots_t.c.id]).where(and_(snapshots_t.c.status == "error_deleting",snapshots_t.c.deleted == 0))
# convert the query result into a list
for i in error_deleting_snapshots_q.execute():
error_deleting_snapshots.append(i[0])
return error_deleting_snapshots
# delete all the snapshots in state "error_deleting"
def fix_error_deleting_snapshots(meta, error_deleting_snapshots):
snapshots_t = Table('snapshots', meta, autoload=True)
for error_deleting_snapshots_id in error_deleting_snapshots:
log.info("-- action: deleting snapshot id: %s", error_deleting_snapshots_id)
now = datetime.datetime.utcnow()
delete_snapshot_q = snapshots_t.update().\
where(snapshots_t.c.id == error_deleting_snapshots_id).values(updated_at=now, deleted_at=now, deleted=1)
delete_snapshot_q.execute()
# get all the rows with a volume_admin_metadata still defined where the corresponding volume is already deleted
def get_wrong_volume_admin_metadata(meta):
wrong_admin_metadata = {}
volume_admin_metadata_t = Table('volume_admin_metadata', meta, autoload=True)
volumes_t = Table('volumes', meta, autoload=True)
admin_metadata_join = volume_admin_metadata_t.join(volumes_t,volume_admin_metadata_t.c.volume_id == volumes_t.c.id)
columns = [volumes_t.c.id, volumes_t.c.deleted, volume_admin_metadata_t.c.id, volume_admin_metadata_t.c.deleted]
wrong_volume_admin_metadata_q = select(columns=columns).select_from(admin_metadata_join).\
where(and_(volumes_t.c.deleted == 1, volume_admin_metadata_t.c.deleted == 0))
# return a dict indexed by volume_admin_metadata_id and with the value volume_id for non deleted volume_admin_metadata
for (volume_id, volume_deleted, volume_admin_metadata_id, volume_admin_metadata_deleted) in wrong_volume_admin_metadata_q.execute():
wrong_admin_metadata[volume_admin_metadata_id] = volume_id
return wrong_admin_metadata
# delete volume_admin_metadata still defined where the corresponding volume is already deleted
def fix_wrong_volume_admin_metadata(meta, wrong_admin_metadata):
volume_admin_metadata_t = Table('volume_admin_metadata', meta, autoload=True)
for volume_admin_metadata_id in wrong_admin_metadata:
log.info("-- action: deleting volume_admin_metadata id: %s", volume_admin_metadata_id)
now = datetime.datetime.utcnow()
delete_volume_admin_metadata_q = volume_admin_metadata_t.update().\
where(volume_admin_metadata_t.c.id == volume_admin_metadata_id).values(updated_at=now, deleted_at=now, deleted=1)
delete_volume_admin_metadata_q.execute()
# get all the rows with a volume_glance_metadata still defined where the corresponding volume is already deleted
def get_wrong_volume_glance_metadata(meta):
wrong_glance_metadata = {}
volume_glance_metadata_t = Table('volume_glance_metadata', meta, autoload=True)
volumes_t = Table('volumes', meta, autoload=True)
glance_metadata_join = volume_glance_metadata_t.join(volumes_t,volume_glance_metadata_t.c.volume_id == volumes_t.c.id)
columns = [volumes_t.c.id, volumes_t.c.deleted, volume_glance_metadata_t.c.id, volume_glance_metadata_t.c.deleted]
wrong_volume_glance_metadata_q = select(columns=columns).select_from(glance_metadata_join).\
where(and_(volumes_t.c.deleted == 1, volume_glance_metadata_t.c.deleted == 0))
# return a dict indexed by volume_glance_metadata_id and with the value volume_id for non deleted volume_glance_metadata
for (volume_id, volume_deleted, volume_glance_metadata_id, volume_glance_metadata_deleted) in wrong_volume_glance_metadata_q.execute():
wrong_glance_metadata[volume_glance_metadata_id] = volume_id
return wrong_glance_metadata
# delete volume_glance_metadata still defined where the corresponding volume is already deleted
def fix_wrong_volume_glance_metadata(meta, wrong_glance_metadata):
volume_glance_metadata_t = Table('volume_glance_metadata', meta, autoload=True)
for volume_glance_metadata_id in wrong_glance_metadata:
log.info("-- action: deleting volume_glance_metadata id: %s", volume_glance_metadata_id)
now = datetime.datetime.utcnow()
delete_volume_glance_metadata_q = volume_glance_metadata_t.update().\
where(volume_glance_metadata_t.c.id == volume_glance_metadata_id).values(updated_at=now, deleted_at=now, deleted=1)
delete_volume_glance_metadata_q.execute()
# get all the rows with a volume_metadata still defined where the corresponding volume is already deleted
def get_wrong_volume_metadata(meta):
wrong_metadata = {}
volume_metadata_t = Table('volume_metadata', meta, autoload=True)
volumes_t = Table('volumes', meta, autoload=True)
metadata_join = volume_metadata_t.join(volumes_t,volume_metadata_t.c.volume_id == volumes_t.c.id)
columns = [volumes_t.c.id, volumes_t.c.deleted, volume_metadata_t.c.id, volume_metadata_t.c.deleted]
wrong_volume_metadata_q = select(columns=columns).select_from(metadata_join).\
where(and_(volumes_t.c.deleted == 1, volume_metadata_t.c.deleted == 0))
# return a dict indexed by volume_metadata_id and with the value volume_id for non deleted volume_metadata
for (volume_id, volume_deleted, volume_metadata_id, volume_metadata_deleted) in wrong_volume_metadata_q.execute():
wrong_metadata[volume_metadata_id] = volume_id
return wrong_metadata
# delete volume_metadata still defined where the corresponding volume is already deleted
def fix_wrong_volume_metadata(meta, wrong_metadata):
volume_metadata_t = Table('volume_metadata', meta, autoload=True)
for volume_metadata_id in wrong_metadata:
log.info("-- action: deleting volume_metadata id: %s", volume_metadata_id)
now = datetime.datetime.utcnow()
delete_volume_metadata_q = volume_metadata_t.update().\
where(volume_metadata_t.c.id == volume_metadata_id).values(updated_at=now, deleted_at=now, deleted=1)
delete_volume_metadata_q.execute()
# get all the rows with a volume attachment still defined where the corresponding volume is already deleted
def get_wrong_volume_attachments(meta):
wrong_attachments = {}
volume_attachment_t = Table('volume_attachment', meta, autoload=True)
volumes_t = Table('volumes', meta, autoload=True)
attachment_join = volume_attachment_t.join(volumes_t,volume_attachment_t.c.volume_id == volumes_t.c.id)
columns = [volumes_t.c.id, volumes_t.c.deleted, volume_attachment_t.c.id, volume_attachment_t.c.deleted]
wrong_volume_attachment_q = select(columns=columns).select_from(attachment_join).\
where(and_(volumes_t.c.deleted == 1, volume_attachment_t.c.deleted == 0))
# return a dict indexed by volume_attachment_id and with the value volume_id for non deleted volume_attachments
for (volume_id, volume_deleted, volume_attachment_id, volume_attachment_deleted) in wrong_volume_attachment_q.execute():
wrong_attachments[volume_attachment_id] = volume_id
return wrong_attachments
# delete volume attachment still defined where the corresponding volume is already deleted
def fix_wrong_volume_attachments(meta, wrong_attachments, fix_limit):
if len(wrong_attachments) <= int(fix_limit):
volume_attachment_t = Table('volume_attachment', meta, autoload=True)
for volume_attachment_id in wrong_attachments:
log.info("-- action: deleting volume attachment id: %s", volume_attachment_id)
now = datetime.datetime.utcnow()
delete_volume_attachment_q = volume_attachment_t.update().\
where(volume_attachment_t.c.id == volume_attachment_id).values(updated_at=now, deleted_at=now, deleted=1)
delete_volume_attachment_q.execute()
else:
log.warn("- PLEASE CHECK MANUALLY - too many (more than %s) wrong volume attachments - denying to fix them automatically", str(fix_limit))
# get all the rows, which have the deleted flag set, but not the delete_at column
def get_missing_deleted_at(meta, table_names):
missing_deleted_at = {}
for t in table_names:
a_table_t = Table(t, meta, autoload=True)
a_table_select_deleted_at_q = a_table_t.select().where(
and_(a_table_t.c.deleted == 1, a_table_t.c.deleted_at == None))
for row in a_table_select_deleted_at_q.execute():
missing_deleted_at[row.id] = t
return missing_deleted_at
# set deleted_at to updated_at value if not set for marked as deleted rows
def fix_missing_deleted_at(meta, table_names):
now = datetime.datetime.utcnow()
for t in table_names:
a_table_t = Table(t, meta, autoload=True)
log.info("- action: fixing columns with missing deleted_at times in the %s table", t)
a_table_set_deleted_at_q = a_table_t.update().where(
and_(a_table_t.c.deleted == 1, a_table_t.c.deleted_at == None)).values(
deleted_at=now)
a_table_set_deleted_at_q.execute()
# get all the rows with a service still defined where the corresponding volume is already deleted
def get_deleted_services_still_used_in_volumes(meta):
deleted_services_still_used_in_volumes = {}
services_t = Table('services', meta, autoload=True)
volumes_t = Table('volumes', meta, autoload=True)
services_volumes_join = services_t.join(volumes_t,services_t.c.uuid == volumes_t.c.service_uuid)
columns = [services_t.c.uuid, services_t.c.deleted, volumes_t.c.id, volumes_t.c.deleted]
deleted_services_still_used_in_volumes_q = select(columns=columns).select_from(services_volumes_join).\
where(and_(volumes_t.c.deleted == 0, services_t.c.deleted == 1))
# return a dict indexed by service_uuid and with the value volume_id for deleted but still referenced services
for (service_uuid, service_deleted, volume_id, volume_deleted) in deleted_services_still_used_in_volumes_q.execute():
deleted_services_still_used_in_volumes[service_uuid] = volume_id
return deleted_services_still_used_in_volumes
# delete services still defined where the corresponding volume is already deleted
def fix_deleted_services_still_used_in_volumes(meta, deleted_services_still_used_in_volumes):
services_t = Table('services', meta, autoload=True)
for deleted_services_still_used_in_volumes_id in deleted_services_still_used_in_volumes:
log.info("-- action: undeleting service uuid: %s", deleted_services_still_used_in_volumes_id)
undelete_services_q = services_t.update().where(services_t.c.uuid == deleted_services_still_used_in_volumes_id).values(deleted=0,deleted_at=None)
undelete_services_q.execute()
# establish an openstack connection
def makeOsConnection():
try:
conn = connection.Connection(auth_url=os.getenv('OS_AUTH_URL'),
project_name=os.getenv('OS_PROJECT_NAME'),
project_domain_name=os.getenv('OS_PROJECT_DOMAIN_NAME'),
username=os.getenv('OS_USERNAME'),
user_domain_name=os.getenv('OS_USER_DOMAIN_NAME'),
password=os.getenv('OS_PASSWORD'),
identity_api_version="3")
except Exception as e:
log.warn("- PLEASE CHECK MANUALLY - problems connecting to openstack: %s",
str(e))
sys.exit(1)
return conn
# establish a database connection and return the handle
def makeConnection(db_url):
engine = create_engine(db_url)
engine.connect()
Session = sessionmaker(bind=engine)
thisSession = Session()
metadata = MetaData()
metadata.bind = engine
Base = declarative_base()
return thisSession, metadata, Base
# return the database connection string from the config file
def get_db_url(config_file):
parser = configparser.SafeConfigParser()
try:
parser.read(config_file)
db_url = parser.get('database', 'connection', raw=True)
except:
log.info("ERROR: Check Cinder configuration file.")
sys.exit(2)
return db_url
# cmdline handling
def parse_cmdline_args():
parser = argparse.ArgumentParser()
parser.add_argument("--config",
default='./cinder.conf',
help='configuration file')
parser.add_argument("--dry-run",
action="store_true",
help='print only what would be done without actually doing it')
parser.add_argument("--fix-limit",
default=25,
help='maximum number of inconsistencies to fix automatically - if there are more, automatic fixing is denied')
return parser.parse_args()
def main():
try:
args = parse_cmdline_args()
except Exception as e:
log.error("Check command line arguments (%s)", e.strerror)
# connect to openstack
conn = makeOsConnection()
# connect to the DB
db_url = get_db_url(args.config)
cinder_session, cinder_metadata, cinder_Base = makeConnection(db_url)
# fixing volume attachments at no longer existing instances
orphan_volume_attachments = get_orphan_volume_attachments(cinder_metadata)
nova_instances = get_nova_instances(conn)
wrong_orphan_volume_attachments = get_wrong_orphan_volume_attachments(nova_instances, orphan_volume_attachments)
if len(wrong_orphan_volume_attachments) != 0:
log.info("- orphan volume attachments found:")
# print out what we would delete
for orphan_volume_attachment_id in wrong_orphan_volume_attachments:
log.info("-- orphan volume attachment (id in cinder db: %s) for non existent instance in nova: %s", orphan_volume_attachment_id,
orphan_volume_attachments[orphan_volume_attachment_id])
if not args.dry_run:
log.info("- deleting orphan volume attachment inconsistencies found")
fix_wrong_orphan_volume_attachments(cinder_metadata, wrong_orphan_volume_attachments, args.fix_limit)
else:
log.info("- no orphan volume attachments found")
# fixing possible volumes in state "error-deleting"
error_deleting_volumes = get_error_deleting_volumes(cinder_metadata)
if len(error_deleting_volumes) != 0:
log.info("- volumes in state error_deleting found")
# print out what we would delete
for error_deleting_volumes_id in error_deleting_volumes:
log.info("-- volume id: %s", error_deleting_volumes_id)
if not args.dry_run:
log.info("- deleting volumes in state error_deleting")
fix_error_deleting_volumes(cinder_metadata, error_deleting_volumes)
else:
log.info("- no volumes in state error_deleting found")
# fixing possible snapshots in state "error-deleting"
error_deleting_snapshots = get_error_deleting_snapshots(cinder_metadata)
if len(error_deleting_snapshots) != 0:
log.info("- snapshots in state error_deleting found")
# print out what we would delete
for error_deleting_snapshots_id in error_deleting_snapshots:
log.info("-- snapshot id: %s", error_deleting_snapshots_id)
if not args.dry_run:
log.info("- deleting snapshots in state error_deleting")
fix_error_deleting_snapshots(cinder_metadata, error_deleting_snapshots)
else:
log.info("- no snapshots in state error_deleting found")
# fixing possible wrong admin_metadata entries
wrong_admin_metadata = get_wrong_volume_admin_metadata(cinder_metadata)
if len(wrong_admin_metadata) != 0:
log.info("- volume_admin_metadata inconsistencies found")
# print out what we would delete
for volume_admin_metadata_id in wrong_admin_metadata:
log.info("-- volume_admin_metadata id: %s - deleted volume id: %s", volume_admin_metadata_id, wrong_admin_metadata[volume_admin_metadata_id])
if not args.dry_run:
log.info("- removing volume_admin_metadata inconsistencies found")
fix_wrong_volume_admin_metadata(cinder_metadata, wrong_admin_metadata)
else:
log.info("- volume_admin_metadata entries are consistent")
# fixing possible wrong glance_metadata entries
wrong_glance_metadata = get_wrong_volume_glance_metadata(cinder_metadata)
if len(wrong_glance_metadata) != 0:
log.info("- volume_glance_metadata inconsistencies found")
# print out what we would delete
for volume_glance_metadata_id in wrong_glance_metadata:
log.info("-- volume_glance_metadata id: %s - deleted volume id: %s", volume_glance_metadata_id, wrong_glance_metadata[volume_glance_metadata_id])
if not args.dry_run:
log.info("- removing volume_glance_metadata inconsistencies found")
fix_wrong_volume_glance_metadata(cinder_metadata, wrong_glance_metadata)
else:
log.info("- volume_glance_metadata entries are consistent")
# fixing possible wrong metadata entries
wrong_metadata = get_wrong_volume_metadata(cinder_metadata)
if len(wrong_metadata) != 0:
log.info("- volume_metadata inconsistencies found")
# print out what we would delete
for volume_metadata_id in wrong_metadata:
log.info("-- volume_metadata id: %s - deleted volume id: %s", volume_metadata_id, wrong_metadata[volume_metadata_id])
if not args.dry_run:
log.info("- removing volume_metadata inconsistencies found")
fix_wrong_volume_metadata(cinder_metadata, wrong_metadata)
else:
log.info("- volume_metadata entries are consistent")
# fixing possible wrong attachment entries
wrong_attachments = get_wrong_volume_attachments(cinder_metadata)
if len(wrong_attachments) != 0:
log.info("- volume attachment inconsistencies found")
# print out what we would delete
for volume_attachment_id in wrong_attachments:
log.info("-- volume attachment id: %s - deleted volume id: %s", volume_attachment_id, wrong_attachments[volume_attachment_id])
if not args.dry_run:
log.info("- removing volume attachment inconsistencies found")
fix_wrong_volume_attachments(cinder_metadata, wrong_attachments, args.fix_limit)
else:
log.info("- volume attachments are consistent")
# fixing possible missing deleted_at timestamps in some tables
# tables which sometimes have missing deleted_at values
table_names = [ 'snapshots', 'volume_attachment' ]
missing_deleted_at = get_missing_deleted_at(cinder_metadata, table_names)
if len(missing_deleted_at) != 0:
log.info("- missing deleted_at values found:")
# print out what we would delete
for missing_deleted_at_id in missing_deleted_at:
log.info("--- id %s of the %s table is missing deleted_at time", missing_deleted_at_id, missing_deleted_at[missing_deleted_at_id])
if not args.dry_run:
log.info("- setting missing deleted_at values")
fix_missing_deleted_at(cinder_metadata, table_names)
else:
log.info("- no missing deleted_at values")
deleted_services_still_used_in_volumes = get_deleted_services_still_used_in_volumes(cinder_metadata)
if len(deleted_services_still_used_in_volumes) != 0:
log.info("- deleted services still used in volumes found:")
# print out what we would delete
for deleted_services_still_used_in_volumes_id in deleted_services_still_used_in_volumes:
log.info("--- deleted service uuid %s still used in volumes table entry %s", deleted_services_still_used_in_volumes_id, deleted_services_still_used_in_volumes[deleted_services_still_used_in_volumes_id])
if not args.dry_run:
log.info("- undeleting service uuid still used in volumes table")
fix_deleted_services_still_used_in_volumes(cinder_metadata, deleted_services_still_used_in_volumes)
else:
log.info("- deleted services still used in volumes")
if __name__ == "__main__":
main()
| scripts/cinder-consistency.py | 27,184 | !/usr/bin/env python Copyright (c) 2018 SAP SE All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. this script checks for volume attachments of already deleted volumes in the cinder db get all instances from nova get all instance from novafor i in nova_instances: print nova_instances[i].id get all volume attachments for volumes return a dict indexed by orphan_volume_attachment_id and with the value nova_instance_uuid for non deleted orphan_volume_attachments get all the volume attachments in the cinder db for already deleted instances in nova delete volume attachments in the cinder db for already deleted instances in nova get all the volumes in state "error_deleting" convert the query result into a list delete all the volumes in state "error_deleting" get all the snapshots in state "error_deleting" convert the query result into a list delete all the snapshots in state "error_deleting" get all the rows with a volume_admin_metadata still defined where the corresponding volume is already deleted return a dict indexed by volume_admin_metadata_id and with the value volume_id for non deleted volume_admin_metadata delete volume_admin_metadata still defined where the corresponding volume is already deleted get all the rows with a volume_glance_metadata still defined where the corresponding volume is already deleted return a dict indexed by volume_glance_metadata_id and with the value volume_id for non deleted volume_glance_metadata delete volume_glance_metadata still defined where the corresponding volume is already deleted get all the rows with a volume_metadata still defined where the corresponding volume is already deleted return a dict indexed by volume_metadata_id and with the value volume_id for non deleted volume_metadata delete volume_metadata still defined where the corresponding volume is already deleted get all the rows with a volume attachment still defined where the corresponding volume is already deleted return a dict indexed by volume_attachment_id and with the value volume_id for non deleted volume_attachments delete volume attachment still defined where the corresponding volume is already deleted get all the rows, which have the deleted flag set, but not the delete_at column set deleted_at to updated_at value if not set for marked as deleted rows get all the rows with a service still defined where the corresponding volume is already deleted return a dict indexed by service_uuid and with the value volume_id for deleted but still referenced services delete services still defined where the corresponding volume is already deleted establish an openstack connection establish a database connection and return the handle return the database connection string from the config file cmdline handling connect to openstack connect to the DB fixing volume attachments at no longer existing instances print out what we would delete fixing possible volumes in state "error-deleting" print out what we would delete fixing possible snapshots in state "error-deleting" print out what we would delete fixing possible wrong admin_metadata entries print out what we would delete fixing possible wrong glance_metadata entries print out what we would delete fixing possible wrong metadata entries print out what we would delete fixing possible wrong attachment entries print out what we would delete fixing possible missing deleted_at timestamps in some tables tables which sometimes have missing deleted_at values print out what we would delete print out what we would delete | 4,030 | en | 0.917885 |
"""
Evrything Docs
https://dashboard.evrythng.com/documentation/api/actiontypes
"""
from evrythng import assertions, utils
field_specs = {
'datatypes': {
'name': 'str',
'customFields': 'dict',
'tags': 'dict_of_str',
'scopes': 'dict',
},
'required': ('name',),
'readonly': ('id', 'createdAt', 'updatedAt'),
'writable': ('customFields', 'tags', 'scopes'),
}
def create_action_type(name, customFields=None, tags=None, scopes=None,
api_key=None, request_kwargs=None):
"""Create an Action Type"""
kwargs = locals()
del kwargs['request_kwargs']
api_key = kwargs.pop('api_key', None)
assertions.validate_field_specs(kwargs, field_specs)
return utils.request('POST', '/actions', data=kwargs, api_key=api_key,
**(request_kwargs or {}))
def delete_action_type(name, api_key=None, request_kwargs=None):
"""Delete an Action Type"""
assertions.datatype_str('name', name)
url = '/actions/{}'.format(name)
return utils.request('DELETE', url, api_key=api_key, **(request_kwargs or {}))
def update_action_type(name, customFields=None, tags=None, scopes=None,
api_key=None, request_kwargs=None):
"""Update an Action Type"""
kwargs = locals()
del kwargs['request_kwargs']
api_key = kwargs.pop('api_key', None)
assertions.validate_field_specs(kwargs, field_specs)
url = '/actions/{}'.format(name)
return utils.request('POST', '/actions', data=kwargs, api_key=api_key,
**(request_kwargs or {}))
def list_action_types(api_key=None, request_kwargs=None):
"""List Action Types"""
url = '/actions'
return utils.request('GET', url, api_key=api_key, **(request_kwargs or {}))
| src/evrythng/entities/action_types.py | 1,787 | Create an Action Type
Delete an Action Type
List Action Types
Update an Action Type
Evrything Docs
https://dashboard.evrythng.com/documentation/api/actiontypes | 159 | en | 0.547064 |
import json
# try:
# redis_connection = redis.Redis(host='dorresteinappshub.ucsd.edu', port=6378, db=0)
# except:
# redis_connection = None
redis_connection = None
def acquire_motifdb(db_list):
db_list_key = json.dumps(db_list)
if redis_connection is not None:
if redis_connection.exists(db_list_key):
cached_data = json.loads(redis_connection.get(db_list_key))
return cached_data["motifdb_spectra"], cached_data["motifdb_metadata"], set(cached_data["motifdb_features"])
client = requests.session()
token_output = client.get(server_url + 'initialise_api/').json()
token = token_output['token']
data = {'csrfmiddlewaretoken': token}
data['motifset_id_list'] = db_list
data['filter'] = 'True'
output = client.post(server_url + 'get_motifset/', data=data).json()
motifdb_spectra = output['motifs']
motifdb_metadata = output['metadata']
motifdb_features = set()
for m, spec in motifdb_spectra.items():
for f in spec:
motifdb_features.add(f)
# Trying to cache
if redis_connection is not None:
data_cache = {}
data_cache["motifdb_spectra"] = motifdb_spectra
data_cache["motifdb_metadata"] = motifdb_metadata
data_cache["motifdb_features"] = list(motifdb_features)
redis_connection.set(db_list_key, json.dumps(data_cache))
return motifdb_spectra, motifdb_metadata, motifdb_features
"""Grabbing the latest Motifs from MS2LDA"""
import requests
server_url = 'http://ms2lda.org/motifdb/'
server_url = 'http://localhost:8000/motifdb/'
motifset_dict = requests.get(server_url + 'list_motifsets/').json()
# db_list = ['gnps_binned_005'] # Can update this later with multiple motif sets
db_list = []
# db_list.append(2)
# db_list.append(4)
# db_list.append(1)
# db_list.append(3)
# db_list.append(5)
# db_list.append(6)
# db_list.append(16)
db_list = list(set(db_list))
# Acquire motifset from MS2LDA.org
motifdb_spectra, motifdb_metadata, motifdb_features = acquire_motifdb(db_list)
| lda/offline_analysis/ms2lda_runfull_test.py | 2,048 | try: redis_connection = redis.Redis(host='dorresteinappshub.ucsd.edu', port=6378, db=0) except: redis_connection = None Trying to cache db_list = ['gnps_binned_005'] Can update this later with multiple motif sets db_list.append(2) db_list.append(4) db_list.append(1) db_list.append(3) db_list.append(5) db_list.append(6) db_list.append(16) Acquire motifset from MS2LDA.org | 382 | en | 0.43725 |
"""
Mapping from iana timezones to windows timezones and vice versa
"""
from datetime import tzinfo
import pytz
# noinspection SpellCheckingInspection
IANA_TO_WIN = {
"Africa/Abidjan": "Greenwich Standard Time",
"Africa/Accra": "Greenwich Standard Time",
"Africa/Addis_Ababa": "E. Africa Standard Time",
"Africa/Algiers": "W. Central Africa Standard Time",
"Africa/Asmara": "E. Africa Standard Time",
"Africa/Asmera": "E. Africa Standard Time",
"Africa/Bamako": "Greenwich Standard Time",
"Africa/Bangui": "W. Central Africa Standard Time",
"Africa/Banjul": "Greenwich Standard Time",
"Africa/Bissau": "Greenwich Standard Time",
"Africa/Blantyre": "South Africa Standard Time",
"Africa/Brazzaville": "W. Central Africa Standard Time",
"Africa/Bujumbura": "South Africa Standard Time",
"Africa/Cairo": "Egypt Standard Time",
"Africa/Casablanca": "Morocco Standard Time",
"Africa/Ceuta": "Romance Standard Time",
"Africa/Conakry": "Greenwich Standard Time",
"Africa/Dakar": "Greenwich Standard Time",
"Africa/Dar_es_Salaam": "E. Africa Standard Time",
"Africa/Djibouti": "E. Africa Standard Time",
"Africa/Douala": "W. Central Africa Standard Time",
"Africa/El_Aaiun": "Morocco Standard Time",
"Africa/Freetown": "Greenwich Standard Time",
"Africa/Gaborone": "South Africa Standard Time",
"Africa/Harare": "South Africa Standard Time",
"Africa/Johannesburg": "South Africa Standard Time",
"Africa/Juba": "E. Africa Standard Time",
"Africa/Kampala": "E. Africa Standard Time",
"Africa/Khartoum": "Sudan Standard Time",
"Africa/Kigali": "South Africa Standard Time",
"Africa/Kinshasa": "W. Central Africa Standard Time",
"Africa/Lagos": "W. Central Africa Standard Time",
"Africa/Libreville": "W. Central Africa Standard Time",
"Africa/Lome": "Greenwich Standard Time",
"Africa/Luanda": "W. Central Africa Standard Time",
"Africa/Lubumbashi": "South Africa Standard Time",
"Africa/Lusaka": "South Africa Standard Time",
"Africa/Malabo": "W. Central Africa Standard Time",
"Africa/Maputo": "South Africa Standard Time",
"Africa/Maseru": "South Africa Standard Time",
"Africa/Mbabane": "South Africa Standard Time",
"Africa/Mogadishu": "E. Africa Standard Time",
"Africa/Monrovia": "Greenwich Standard Time",
"Africa/Nairobi": "E. Africa Standard Time",
"Africa/Ndjamena": "W. Central Africa Standard Time",
"Africa/Niamey": "W. Central Africa Standard Time",
"Africa/Nouakchott": "Greenwich Standard Time",
"Africa/Ouagadougou": "Greenwich Standard Time",
"Africa/Porto-Novo": "W. Central Africa Standard Time",
"Africa/Sao_Tome": "Sao Tome Standard Time",
"Africa/Timbuktu": "Greenwich Standard Time",
"Africa/Tripoli": "Libya Standard Time",
"Africa/Tunis": "W. Central Africa Standard Time",
"Africa/Windhoek": "Namibia Standard Time",
"America/Adak": "Aleutian Standard Time",
"America/Anchorage": "Alaskan Standard Time",
"America/Anguilla": "SA Western Standard Time",
"America/Antigua": "SA Western Standard Time",
"America/Araguaina": "Tocantins Standard Time",
"America/Argentina/Buenos_Aires": "Argentina Standard Time",
"America/Argentina/Catamarca": "Argentina Standard Time",
"America/Argentina/ComodRivadavia": "Argentina Standard Time",
"America/Argentina/Cordoba": "Argentina Standard Time",
"America/Argentina/Jujuy": "Argentina Standard Time",
"America/Argentina/La_Rioja": "Argentina Standard Time",
"America/Argentina/Mendoza": "Argentina Standard Time",
"America/Argentina/Rio_Gallegos": "Argentina Standard Time",
"America/Argentina/Salta": "Argentina Standard Time",
"America/Argentina/San_Juan": "Argentina Standard Time",
"America/Argentina/San_Luis": "Argentina Standard Time",
"America/Argentina/Tucuman": "Argentina Standard Time",
"America/Argentina/Ushuaia": "Argentina Standard Time",
"America/Aruba": "SA Western Standard Time",
"America/Asuncion": "Paraguay Standard Time",
"America/Atikokan": "SA Pacific Standard Time",
"America/Atka": "Aleutian Standard Time",
"America/Bahia": "Bahia Standard Time",
"America/Bahia_Banderas": "Central Standard Time (Mexico)",
"America/Barbados": "SA Western Standard Time",
"America/Belem": "SA Eastern Standard Time",
"America/Belize": "Central America Standard Time",
"America/Blanc-Sablon": "SA Western Standard Time",
"America/Boa_Vista": "SA Western Standard Time",
"America/Bogota": "SA Pacific Standard Time",
"America/Boise": "Mountain Standard Time",
"America/Buenos_Aires": "Argentina Standard Time",
"America/Cambridge_Bay": "Mountain Standard Time",
"America/Campo_Grande": "Central Brazilian Standard Time",
"America/Cancun": "Eastern Standard Time (Mexico)",
"America/Caracas": "Venezuela Standard Time",
"America/Catamarca": "Argentina Standard Time",
"America/Cayenne": "SA Eastern Standard Time",
"America/Cayman": "SA Pacific Standard Time",
"America/Chicago": "Central Standard Time",
"America/Chihuahua": "Mountain Standard Time (Mexico)",
"America/Coral_Harbour": "SA Pacific Standard Time",
"America/Cordoba": "Argentina Standard Time",
"America/Costa_Rica": "Central America Standard Time",
"America/Creston": "US Mountain Standard Time",
"America/Cuiaba": "Central Brazilian Standard Time",
"America/Curacao": "SA Western Standard Time",
"America/Danmarkshavn": "UTC",
"America/Dawson": "Pacific Standard Time",
"America/Dawson_Creek": "US Mountain Standard Time",
"America/Denver": "Mountain Standard Time",
"America/Detroit": "Eastern Standard Time",
"America/Dominica": "SA Western Standard Time",
"America/Edmonton": "Mountain Standard Time",
"America/Eirunepe": "SA Pacific Standard Time",
"America/El_Salvador": "Central America Standard Time",
"America/Ensenada": "Pacific Standard Time (Mexico)",
"America/Fort_Nelson": "US Mountain Standard Time",
"America/Fort_Wayne": "US Eastern Standard Time",
"America/Fortaleza": "SA Eastern Standard Time",
"America/Glace_Bay": "Atlantic Standard Time",
"America/Godthab": "Greenland Standard Time",
"America/Goose_Bay": "Atlantic Standard Time",
"America/Grand_Turk": "Turks And Caicos Standard Time",
"America/Grenada": "SA Western Standard Time",
"America/Guadeloupe": "SA Western Standard Time",
"America/Guatemala": "Central America Standard Time",
"America/Guayaquil": "SA Pacific Standard Time",
"America/Guyana": "SA Western Standard Time",
"America/Halifax": "Atlantic Standard Time",
"America/Havana": "Cuba Standard Time",
"America/Hermosillo": "US Mountain Standard Time",
"America/Indiana/Indianapolis": "US Eastern Standard Time",
"America/Indiana/Knox": "Central Standard Time",
"America/Indiana/Marengo": "US Eastern Standard Time",
"America/Indiana/Petersburg": "Eastern Standard Time",
"America/Indiana/Tell_City": "Central Standard Time",
"America/Indiana/Vevay": "US Eastern Standard Time",
"America/Indiana/Vincennes": "Eastern Standard Time",
"America/Indiana/Winamac": "Eastern Standard Time",
"America/Indianapolis": "US Eastern Standard Time",
"America/Inuvik": "Mountain Standard Time",
"America/Iqaluit": "Eastern Standard Time",
"America/Jamaica": "SA Pacific Standard Time",
"America/Jujuy": "Argentina Standard Time",
"America/Juneau": "Alaskan Standard Time",
"America/Kentucky/Louisville": "Eastern Standard Time",
"America/Kentucky/Monticello": "Eastern Standard Time",
"America/Knox_IN": "Central Standard Time",
"America/Kralendijk": "SA Western Standard Time",
"America/La_Paz": "SA Western Standard Time",
"America/Lima": "SA Pacific Standard Time",
"America/Los_Angeles": "Pacific Standard Time",
"America/Louisville": "Eastern Standard Time",
"America/Lower_Princes": "SA Western Standard Time",
"America/Maceio": "SA Eastern Standard Time",
"America/Managua": "Central America Standard Time",
"America/Manaus": "SA Western Standard Time",
"America/Marigot": "SA Western Standard Time",
"America/Martinique": "SA Western Standard Time",
"America/Matamoros": "Central Standard Time",
"America/Mazatlan": "Mountain Standard Time (Mexico)",
"America/Mendoza": "Argentina Standard Time",
"America/Menominee": "Central Standard Time",
"America/Merida": "Central Standard Time (Mexico)",
"America/Metlakatla": "Alaskan Standard Time",
"America/Mexico_City": "Central Standard Time (Mexico)",
"America/Miquelon": "Saint Pierre Standard Time",
"America/Moncton": "Atlantic Standard Time",
"America/Monterrey": "Central Standard Time (Mexico)",
"America/Montevideo": "Montevideo Standard Time",
"America/Montreal": "Eastern Standard Time",
"America/Montserrat": "SA Western Standard Time",
"America/Nassau": "Eastern Standard Time",
"America/New_York": "Eastern Standard Time",
"America/Nipigon": "Eastern Standard Time",
"America/Nome": "Alaskan Standard Time",
"America/Noronha": "UTC-02",
"America/North_Dakota/Beulah": "Central Standard Time",
"America/North_Dakota/Center": "Central Standard Time",
"America/North_Dakota/New_Salem": "Central Standard Time",
"America/Ojinaga": "Mountain Standard Time",
"America/Panama": "SA Pacific Standard Time",
"America/Pangnirtung": "Eastern Standard Time",
"America/Paramaribo": "SA Eastern Standard Time",
"America/Phoenix": "US Mountain Standard Time",
"America/Port-au-Prince": "Haiti Standard Time",
"America/Port_of_Spain": "SA Western Standard Time",
"America/Porto_Acre": "SA Pacific Standard Time",
"America/Porto_Velho": "SA Western Standard Time",
"America/Puerto_Rico": "SA Western Standard Time",
"America/Punta_Arenas": "Magallanes Standard Time",
"America/Rainy_River": "Central Standard Time",
"America/Rankin_Inlet": "Central Standard Time",
"America/Recife": "SA Eastern Standard Time",
"America/Regina": "Canada Central Standard Time",
"America/Resolute": "Central Standard Time",
"America/Rio_Branco": "SA Pacific Standard Time",
"America/Rosario": "Argentina Standard Time",
"America/Santa_Isabel": "Pacific Standard Time (Mexico)",
"America/Santarem": "SA Eastern Standard Time",
"America/Santiago": "Pacific SA Standard Time",
"America/Santo_Domingo": "SA Western Standard Time",
"America/Sao_Paulo": "E. South America Standard Time",
"America/Scoresbysund": "Azores Standard Time",
"America/Shiprock": "Mountain Standard Time",
"America/Sitka": "Alaskan Standard Time",
"America/St_Barthelemy": "SA Western Standard Time",
"America/St_Johns": "Newfoundland Standard Time",
"America/St_Kitts": "SA Western Standard Time",
"America/St_Lucia": "SA Western Standard Time",
"America/St_Thomas": "SA Western Standard Time",
"America/St_Vincent": "SA Western Standard Time",
"America/Swift_Current": "Canada Central Standard Time",
"America/Tegucigalpa": "Central America Standard Time",
"America/Thule": "Atlantic Standard Time",
"America/Thunder_Bay": "Eastern Standard Time",
"America/Tijuana": "Pacific Standard Time (Mexico)",
"America/Toronto": "Eastern Standard Time",
"America/Tortola": "SA Western Standard Time",
"America/Vancouver": "Pacific Standard Time",
"America/Virgin": "SA Western Standard Time",
"America/Whitehorse": "Pacific Standard Time",
"America/Winnipeg": "Central Standard Time",
"America/Yakutat": "Alaskan Standard Time",
"America/Yellowknife": "Mountain Standard Time",
"Antarctica/Casey": "W. Australia Standard Time",
"Antarctica/Davis": "SE Asia Standard Time",
"Antarctica/DumontDUrville": "West Pacific Standard Time",
"Antarctica/Macquarie": "Central Pacific Standard Time",
"Antarctica/Mawson": "West Asia Standard Time",
"Antarctica/McMurdo": "New Zealand Standard Time",
"Antarctica/Palmer": "Magallanes Standard Time",
"Antarctica/Rothera": "SA Eastern Standard Time",
"Antarctica/South_Pole": "New Zealand Standard Time",
"Antarctica/Syowa": "E. Africa Standard Time",
"Antarctica/Vostok": "Central Asia Standard Time",
"Arctic/Longyearbyen": "W. Europe Standard Time",
"Asia/Aden": "Arab Standard Time",
"Asia/Almaty": "Central Asia Standard Time",
"Asia/Amman": "Jordan Standard Time",
"Asia/Anadyr": "Russia Time Zone 11",
"Asia/Aqtau": "West Asia Standard Time",
"Asia/Aqtobe": "West Asia Standard Time",
"Asia/Ashgabat": "West Asia Standard Time",
"Asia/Ashkhabad": "West Asia Standard Time",
"Asia/Atyrau": "West Asia Standard Time",
"Asia/Baghdad": "Arabic Standard Time",
"Asia/Bahrain": "Arab Standard Time",
"Asia/Baku": "Azerbaijan Standard Time",
"Asia/Bangkok": "SE Asia Standard Time",
"Asia/Barnaul": "Altai Standard Time",
"Asia/Beirut": "Middle East Standard Time",
"Asia/Bishkek": "Central Asia Standard Time",
"Asia/Brunei": "Singapore Standard Time",
"Asia/Calcutta": "India Standard Time",
"Asia/Chita": "Transbaikal Standard Time",
"Asia/Choibalsan": "Ulaanbaatar Standard Time",
"Asia/Chongqing": "China Standard Time",
"Asia/Chungking": "China Standard Time",
"Asia/Colombo": "Sri Lanka Standard Time",
"Asia/Dacca": "Bangladesh Standard Time",
"Asia/Damascus": "Syria Standard Time",
"Asia/Dhaka": "Bangladesh Standard Time",
"Asia/Dili": "Tokyo Standard Time",
"Asia/Dubai": "Arabian Standard Time",
"Asia/Dushanbe": "West Asia Standard Time",
"Asia/Famagusta": "GTB Standard Time",
"Asia/Gaza": "West Bank Standard Time",
"Asia/Harbin": "China Standard Time",
"Asia/Hebron": "West Bank Standard Time",
"Asia/Ho_Chi_Minh": "SE Asia Standard Time",
"Asia/Hong_Kong": "China Standard Time",
"Asia/Hovd": "W. Mongolia Standard Time",
"Asia/Irkutsk": "North Asia East Standard Time",
"Asia/Istanbul": "Turkey Standard Time",
"Asia/Jakarta": "SE Asia Standard Time",
"Asia/Jayapura": "Tokyo Standard Time",
"Asia/Jerusalem": "Israel Standard Time",
"Asia/Kabul": "Afghanistan Standard Time",
"Asia/Kamchatka": "Kamchatka Standard Time",
"Asia/Karachi": "Pakistan Standard Time",
"Asia/Kashgar": "Central Asia Standard Time",
"Asia/Kathmandu": "Nepal Standard Time",
"Asia/Katmandu": "Nepal Standard Time",
"Asia/Khandyga": "Yakutsk Standard Time",
"Asia/Kolkata": "India Standard Time",
"Asia/Krasnoyarsk": "North Asia Standard Time",
"Asia/Kuala_Lumpur": "Singapore Standard Time",
"Asia/Kuching": "Singapore Standard Time",
"Asia/Kuwait": "Arab Standard Time",
"Asia/Macao": "China Standard Time",
"Asia/Macau": "China Standard Time",
"Asia/Magadan": "Magadan Standard Time",
"Asia/Makassar": "Singapore Standard Time",
"Asia/Manila": "Singapore Standard Time",
"Asia/Muscat": "Arabian Standard Time",
"Asia/Nicosia": "GTB Standard Time",
"Asia/Novokuznetsk": "North Asia Standard Time",
"Asia/Novosibirsk": "N. Central Asia Standard Time",
"Asia/Omsk": "Omsk Standard Time",
"Asia/Oral": "West Asia Standard Time",
"Asia/Phnom_Penh": "SE Asia Standard Time",
"Asia/Pontianak": "SE Asia Standard Time",
"Asia/Pyongyang": "North Korea Standard Time",
"Asia/Qatar": "Arab Standard Time",
"Asia/Qostanay": "Central Asia Standard Time",
"Asia/Qyzylorda": "Qyzylorda Standard Time",
"Asia/Rangoon": "Myanmar Standard Time",
"Asia/Riyadh": "Arab Standard Time",
"Asia/Saigon": "SE Asia Standard Time",
"Asia/Sakhalin": "Sakhalin Standard Time",
"Asia/Samarkand": "West Asia Standard Time",
"Asia/Seoul": "Korea Standard Time",
"Asia/Shanghai": "China Standard Time",
"Asia/Singapore": "Singapore Standard Time",
"Asia/Srednekolymsk": "Russia Time Zone 10",
"Asia/Taipei": "Taipei Standard Time",
"Asia/Tashkent": "West Asia Standard Time",
"Asia/Tbilisi": "Georgian Standard Time",
"Asia/Tehran": "Iran Standard Time",
"Asia/Tel_Aviv": "Israel Standard Time",
"Asia/Thimbu": "Bangladesh Standard Time",
"Asia/Thimphu": "Bangladesh Standard Time",
"Asia/Tokyo": "Tokyo Standard Time",
"Asia/Tomsk": "Tomsk Standard Time",
"Asia/Ujung_Pandang": "Singapore Standard Time",
"Asia/Ulaanbaatar": "Ulaanbaatar Standard Time",
"Asia/Ulan_Bator": "Ulaanbaatar Standard Time",
"Asia/Urumqi": "Central Asia Standard Time",
"Asia/Ust-Nera": "Vladivostok Standard Time",
"Asia/Vientiane": "SE Asia Standard Time",
"Asia/Vladivostok": "Vladivostok Standard Time",
"Asia/Yakutsk": "Yakutsk Standard Time",
"Asia/Yangon": "Myanmar Standard Time",
"Asia/Yekaterinburg": "Ekaterinburg Standard Time",
"Asia/Yerevan": "Caucasus Standard Time",
"Atlantic/Azores": "Azores Standard Time",
"Atlantic/Bermuda": "Atlantic Standard Time",
"Atlantic/Canary": "GMT Standard Time",
"Atlantic/Cape_Verde": "Cape Verde Standard Time",
"Atlantic/Faeroe": "GMT Standard Time",
"Atlantic/Faroe": "GMT Standard Time",
"Atlantic/Jan_Mayen": "W. Europe Standard Time",
"Atlantic/Madeira": "GMT Standard Time",
"Atlantic/Reykjavik": "Greenwich Standard Time",
"Atlantic/South_Georgia": "UTC-02",
"Atlantic/St_Helena": "Greenwich Standard Time",
"Atlantic/Stanley": "SA Eastern Standard Time",
"Australia/ACT": "AUS Eastern Standard Time",
"Australia/Adelaide": "Cen. Australia Standard Time",
"Australia/Brisbane": "E. Australia Standard Time",
"Australia/Broken_Hill": "Cen. Australia Standard Time",
"Australia/Canberra": "AUS Eastern Standard Time",
"Australia/Currie": "Tasmania Standard Time",
"Australia/Darwin": "AUS Central Standard Time",
"Australia/Eucla": "Aus Central W. Standard Time",
"Australia/Hobart": "Tasmania Standard Time",
"Australia/LHI": "Lord Howe Standard Time",
"Australia/Lindeman": "E. Australia Standard Time",
"Australia/Lord_Howe": "Lord Howe Standard Time",
"Australia/Melbourne": "AUS Eastern Standard Time",
"Australia/NSW": "AUS Eastern Standard Time",
"Australia/North": "AUS Central Standard Time",
"Australia/Perth": "W. Australia Standard Time",
"Australia/Queensland": "E. Australia Standard Time",
"Australia/South": "Cen. Australia Standard Time",
"Australia/Sydney": "AUS Eastern Standard Time",
"Australia/Tasmania": "Tasmania Standard Time",
"Australia/Victoria": "AUS Eastern Standard Time",
"Australia/West": "W. Australia Standard Time",
"Australia/Yancowinna": "Cen. Australia Standard Time",
"Brazil/Acre": "SA Pacific Standard Time",
"Brazil/DeNoronha": "UTC-02",
"Brazil/East": "E. South America Standard Time",
"Brazil/West": "SA Western Standard Time",
"CET": "Romance Standard Time",
"CST6CDT": "Central Standard Time",
"Canada/Atlantic": "Atlantic Standard Time",
"Canada/Central": "Central Standard Time",
"Canada/East-Saskatchewan": "Canada Central Standard Time",
"Canada/Eastern": "Eastern Standard Time",
"Canada/Mountain": "Mountain Standard Time",
"Canada/Newfoundland": "Newfoundland Standard Time",
"Canada/Pacific": "Pacific Standard Time",
"Canada/Saskatchewan": "Canada Central Standard Time",
"Canada/Yukon": "Pacific Standard Time",
"Chile/Continental": "Pacific SA Standard Time",
"Chile/EasterIsland": "Easter Island Standard Time",
"Cuba": "Cuba Standard Time",
"EET": "GTB Standard Time",
"EST": "SA Pacific Standard Time",
"EST5EDT": "Eastern Standard Time",
"Egypt": "Egypt Standard Time",
"Eire": "GMT Standard Time",
"Etc/GMT": "UTC",
"Etc/GMT+0": "UTC",
"Etc/GMT+1": "Cape Verde Standard Time",
"Etc/GMT+10": "Hawaiian Standard Time",
"Etc/GMT+11": "UTC-11",
"Etc/GMT+12": "Dateline Standard Time",
"Etc/GMT+2": "Mid-Atlantic Standard Time",
"Etc/GMT+3": "SA Eastern Standard Time",
"Etc/GMT+4": "SA Western Standard Time",
"Etc/GMT+5": "SA Pacific Standard Time",
"Etc/GMT+6": "Central America Standard Time",
"Etc/GMT+7": "US Mountain Standard Time",
"Etc/GMT+8": "UTC-08",
"Etc/GMT+9": "UTC-09",
"Etc/GMT-0": "UTC",
"Etc/GMT-1": "W. Central Africa Standard Time",
"Etc/GMT-10": "West Pacific Standard Time",
"Etc/GMT-11": "Central Pacific Standard Time",
"Etc/GMT-12": "UTC+12",
"Etc/GMT-13": "UTC+13",
"Etc/GMT-14": "Line Islands Standard Time",
"Etc/GMT-2": "South Africa Standard Time",
"Etc/GMT-3": "E. Africa Standard Time",
"Etc/GMT-4": "Arabian Standard Time",
"Etc/GMT-5": "West Asia Standard Time",
"Etc/GMT-6": "Central Asia Standard Time",
"Etc/GMT-7": "SE Asia Standard Time",
"Etc/GMT-8": "Singapore Standard Time",
"Etc/GMT-9": "Tokyo Standard Time",
"Etc/GMT0": "UTC",
"Etc/Greenwich": "UTC",
"Etc/UCT": "UTC",
"Etc/UTC": "UTC",
"Etc/Universal": "UTC",
"Etc/Zulu": "UTC",
"Europe/Amsterdam": "W. Europe Standard Time",
"Europe/Andorra": "W. Europe Standard Time",
"Europe/Astrakhan": "Astrakhan Standard Time",
"Europe/Athens": "GTB Standard Time",
"Europe/Belfast": "GMT Standard Time",
"Europe/Belgrade": "Central European Standard Time",
"Europe/Berlin": "W. Europe Standard Time",
"Europe/Bratislava": "Central Europe Standard Time",
"Europe/Brussels": "Romance Standard Time",
"Europe/Bucharest": "GTB Standard Time",
"Europe/Budapest": "Central Europe Standard Time",
"Europe/Busingen": "W. Europe Standard Time",
"Europe/Chisinau": "E. Europe Standard Time",
"Europe/Copenhagen": "Romance Standard Time",
"Europe/Dublin": "GMT Standard Time",
"Europe/Gibraltar": "W. Europe Standard Time",
"Europe/Guernsey": "GMT Standard Time",
"Europe/Helsinki": "FLE Standard Time",
"Europe/Isle_of_Man": "GMT Standard Time",
"Europe/Istanbul": "Turkey Standard Time",
"Europe/Jersey": "GMT Standard Time",
"Europe/Kaliningrad": "Kaliningrad Standard Time",
"Europe/Kiev": "FLE Standard Time",
"Europe/Kirov": "Russian Standard Time",
"Europe/Lisbon": "GMT Standard Time",
"Europe/Ljubljana": "Central European Standard Time",
"Europe/London": "GMT Standard Time",
"Europe/Luxembourg": "W. Europe Standard Time",
"Europe/Madrid": "Romance Standard Time",
"Europe/Malta": "W. Europe Standard Time",
"Europe/Mariehamn": "FLE Standard Time",
"Europe/Minsk": "Belarus Standard Time",
"Europe/Monaco": "W. Europe Standard Time",
"Europe/Moscow": "Russian Standard Time",
"Europe/Nicosia": "GTB Standard Time",
"Europe/Oslo": "W. Europe Standard Time",
"Europe/Paris": "Romance Standard Time",
"Europe/Podgorica": "Central European Standard Time",
"Europe/Prague": "Central Europe Standard Time",
"Europe/Riga": "FLE Standard Time",
"Europe/Rome": "W. Europe Standard Time",
"Europe/Samara": "Russia Time Zone 3",
"Europe/San_Marino": "W. Europe Standard Time",
"Europe/Sarajevo": "Central European Standard Time",
"Europe/Saratov": "Saratov Standard Time",
"Europe/Simferopol": "Russian Standard Time",
"Europe/Skopje": "Central European Standard Time",
"Europe/Sofia": "FLE Standard Time",
"Europe/Stockholm": "W. Europe Standard Time",
"Europe/Tallinn": "FLE Standard Time",
"Europe/Tirane": "Central Europe Standard Time",
"Europe/Tiraspol": "E. Europe Standard Time",
"Europe/Ulyanovsk": "Astrakhan Standard Time",
"Europe/Uzhgorod": "FLE Standard Time",
"Europe/Vaduz": "W. Europe Standard Time",
"Europe/Vatican": "W. Europe Standard Time",
"Europe/Vienna": "W. Europe Standard Time",
"Europe/Vilnius": "FLE Standard Time",
"Europe/Volgograd": "Volgograd Standard Time",
"Europe/Warsaw": "Central European Standard Time",
"Europe/Zagreb": "Central European Standard Time",
"Europe/Zaporozhye": "FLE Standard Time",
"Europe/Zurich": "W. Europe Standard Time",
"GB": "GMT Standard Time",
"GB-Eire": "GMT Standard Time",
"GMT": "UTC",
"GMT+0": "UTC",
"GMT-0": "UTC",
"GMT0": "UTC",
"Greenwich": "UTC",
"HST": "Hawaiian Standard Time",
"Hongkong": "China Standard Time",
"Iceland": "Greenwich Standard Time",
"Indian/Antananarivo": "E. Africa Standard Time",
"Indian/Chagos": "Central Asia Standard Time",
"Indian/Christmas": "SE Asia Standard Time",
"Indian/Cocos": "Myanmar Standard Time",
"Indian/Comoro": "E. Africa Standard Time",
"Indian/Kerguelen": "West Asia Standard Time",
"Indian/Mahe": "Mauritius Standard Time",
"Indian/Maldives": "West Asia Standard Time",
"Indian/Mauritius": "Mauritius Standard Time",
"Indian/Mayotte": "E. Africa Standard Time",
"Indian/Reunion": "Mauritius Standard Time",
"Iran": "Iran Standard Time",
"Israel": "Israel Standard Time",
"Jamaica": "SA Pacific Standard Time",
"Japan": "Tokyo Standard Time",
"Kwajalein": "UTC+12",
"Libya": "Libya Standard Time",
"MET": "W. Europe Standard Time",
"MST": "US Mountain Standard Time",
"MST7MDT": "Mountain Standard Time",
"Mexico/BajaNorte": "Pacific Standard Time (Mexico)",
"Mexico/BajaSur": "Mountain Standard Time (Mexico)",
"Mexico/General": "Central Standard Time (Mexico)",
"NZ": "New Zealand Standard Time",
"NZ-CHAT": "Chatham Islands Standard Time",
"Navajo": "Mountain Standard Time",
"PRC": "China Standard Time",
"PST8PDT": "Pacific Standard Time",
"Pacific/Apia": "Samoa Standard Time",
"Pacific/Auckland": "New Zealand Standard Time",
"Pacific/Bougainville": "Bougainville Standard Time",
"Pacific/Chatham": "Chatham Islands Standard Time",
"Pacific/Chuuk": "West Pacific Standard Time",
"Pacific/Easter": "Easter Island Standard Time",
"Pacific/Efate": "Central Pacific Standard Time",
"Pacific/Enderbury": "UTC+13",
"Pacific/Fakaofo": "UTC+13",
"Pacific/Fiji": "Fiji Standard Time",
"Pacific/Funafuti": "UTC+12",
"Pacific/Galapagos": "Central America Standard Time",
"Pacific/Gambier": "UTC-09",
"Pacific/Guadalcanal": "Central Pacific Standard Time",
"Pacific/Guam": "West Pacific Standard Time",
"Pacific/Honolulu": "Hawaiian Standard Time",
"Pacific/Johnston": "Hawaiian Standard Time",
"Pacific/Kiritimati": "Line Islands Standard Time",
"Pacific/Kosrae": "Central Pacific Standard Time",
"Pacific/Kwajalein": "UTC+12",
"Pacific/Majuro": "UTC+12",
"Pacific/Marquesas": "Marquesas Standard Time",
"Pacific/Midway": "UTC-11",
"Pacific/Nauru": "UTC+12",
"Pacific/Niue": "UTC-11",
"Pacific/Norfolk": "Norfolk Standard Time",
"Pacific/Noumea": "Central Pacific Standard Time",
"Pacific/Pago_Pago": "UTC-11",
"Pacific/Palau": "Tokyo Standard Time",
"Pacific/Pitcairn": "UTC-08",
"Pacific/Pohnpei": "Central Pacific Standard Time",
"Pacific/Ponape": "Central Pacific Standard Time",
"Pacific/Port_Moresby": "West Pacific Standard Time",
"Pacific/Rarotonga": "Hawaiian Standard Time",
"Pacific/Saipan": "West Pacific Standard Time",
"Pacific/Samoa": "UTC-11",
"Pacific/Tahiti": "Hawaiian Standard Time",
"Pacific/Tarawa": "UTC+12",
"Pacific/Tongatapu": "Tonga Standard Time",
"Pacific/Truk": "West Pacific Standard Time",
"Pacific/Wake": "UTC+12",
"Pacific/Wallis": "UTC+12",
"Pacific/Yap": "West Pacific Standard Time",
"Poland": "Central European Standard Time",
"Portugal": "GMT Standard Time",
"ROC": "Taipei Standard Time",
"ROK": "Korea Standard Time",
"Singapore": "Singapore Standard Time",
"Turkey": "Turkey Standard Time",
"UCT": "UTC",
"US/Alaska": "Alaskan Standard Time",
"US/Aleutian": "Aleutian Standard Time",
"US/Arizona": "US Mountain Standard Time",
"US/Central": "Central Standard Time",
"US/East-Indiana": "US Eastern Standard Time",
"US/Eastern": "Eastern Standard Time",
"US/Hawaii": "Hawaiian Standard Time",
"US/Indiana-Starke": "Central Standard Time",
"US/Michigan": "Eastern Standard Time",
"US/Mountain": "Mountain Standard Time",
"US/Pacific": "Pacific Standard Time",
"US/Pacific-New": "Pacific Standard Time",
"US/Samoa": "UTC-11",
"UTC": "UTC",
"Universal": "UTC",
"W-SU": "Russian Standard Time",
"WET": "GMT Standard Time",
"Zulu": "UTC"
}
# when converting to Iana, only consider for win UTC the value Iana UTC
WIN_TO_IANA = {v: k for k, v in IANA_TO_WIN.items() if v != 'UTC' or (v == 'UTC' and k == 'UTC')}
def get_iana_tz(windows_tz):
""" Returns a valid pytz TimeZone (Iana/Olson Timezones) from a given
windows TimeZone
:param windows_tz: windows format timezone usually returned by
microsoft api response
:return:
:rtype:
"""
timezone = WIN_TO_IANA.get(windows_tz)
if timezone is None:
# Nope, that didn't work. Try adding "Standard Time",
# it seems to work a lot of times:
timezone = WIN_TO_IANA.get(windows_tz + ' Standard Time')
# Return what we have.
if timezone is None:
raise pytz.UnknownTimeZoneError(
"Can't find Windows TimeZone " + windows_tz)
return timezone
def get_windows_tz(iana_tz):
""" Returns a valid windows TimeZone from a given pytz TimeZone
(Iana/Olson Timezones)
Note: Windows Timezones are SHIT!... no ... really THEY ARE
HOLY FUCKING SHIT!.
"""
timezone = IANA_TO_WIN.get(
iana_tz.zone if isinstance(iana_tz, tzinfo) else iana_tz)
if timezone is None:
raise pytz.UnknownTimeZoneError(
"Can't find Iana TimeZone " + iana_tz.zone)
return timezone
| O365/utils/windows_tz.py | 29,985 | Returns a valid pytz TimeZone (Iana/Olson Timezones) from a given
windows TimeZone
:param windows_tz: windows format timezone usually returned by
microsoft api response
:return:
:rtype:
Returns a valid windows TimeZone from a given pytz TimeZone
(Iana/Olson Timezones)
Note: Windows Timezones are SHIT!... no ... really THEY ARE
HOLY FUCKING SHIT!.
Mapping from iana timezones to windows timezones and vice versa
noinspection SpellCheckingInspection when converting to Iana, only consider for win UTC the value Iana UTC Nope, that didn't work. Try adding "Standard Time", it seems to work a lot of times: Return what we have. | 629 | en | 0.677821 |
# pip install freegames
# Click on screen to control ball
# import modules
from random import *
import turtle as t
from freegames import vector
# Set window title, color and icon
t.title("Flappy Ball")
root = t.Screen()._root
root.iconbitmap("logo-ico.ico")
t.bgcolor('#80ffd4')
bird = vector(0, 0)
balls = []
# Functions
# Move bird up in response to screen tap
def tap(x, y):
up = vector(0, 30)
bird.move(up)
# Return True if point on screen
def inside(point):
return -200 < point.x < 200 and -200 < point.y < 200
# Draw screen objects
def draw(alive):
t.clear()
t.goto(bird.x, bird.y)
if alive:
t.dot(13, 'green')
else:
t.dot(13, 'red')
for ball in balls:
t.goto(ball.x, ball.y)
t.dot(20, '#862d2d')
t.update()
def move():
# Update object positions
bird.y -= 5
for ball in balls:
ball.x -= 3
if randrange(10) == 0:
y = randrange(-199, 199)
ball = vector(199, y)
balls.append(ball)
while len(balls) > 0 and not inside(balls[0]):
balls.pop(0)
if not inside(bird):
draw(False)
return
for ball in balls:
if abs(ball - bird) < 15:
draw(False)
return
draw(True)
t.ontimer(move, 50)
t.setup(420, 420, 370, 0)
t.hideturtle()
t.up()
t.tracer(False)
t.onscreenclick(tap)
move()
t.done()
| games/Flappy.py | 1,397 | pip install freegames Click on screen to control ball import modules Set window title, color and icon Functions Move bird up in response to screen tap Return True if point on screen Draw screen objects Update object positions | 225 | en | 0.630688 |
"""Base test cases for RBTools unit tests."""
from __future__ import unicode_literals
import os
import re
import shutil
import sys
import tempfile
import unittest
from contextlib import contextmanager
import six
from rbtools.utils.filesystem import cleanup_tempfiles, make_tempdir
import kgb
from rbtools.utils.filesystem import make_tempfile
class TestCase(unittest.TestCase):
"""The base class for RBTools test cases.
This provides helpful utility functions, environment management, and
better docstrings to help craft unit tests for RBTools functionality.
All RBTools unit tests should use this this class or a subclass of it
as the base class.
"""
ws_re = re.compile(r'\s+')
default_text_editor = '%s %s' % (
sys.executable,
os.path.abspath(os.path.join(os.path.dirname(__file__),
'scripts', 'editor.py'))
)
maxDiff = 10000
#: Whether individual unit tests need a new temporary HOME directory.
#:
#: If set, a directory will be created at test startup, and will be
#: set as the home directory.
#:
#: Version Added:
#: 3.0
needs_temp_home = False
@classmethod
def setUpClass(cls):
super(TestCase, cls).setUpClass()
cls._cls_old_cwd = os.getcwd()
@classmethod
def tearDownClass(cls):
os.chdir(cls._cls_old_cwd)
super(TestCase, cls).tearDownClass()
def setUp(self):
super(TestCase, self).setUp()
self._old_cwd = os.getcwd()
self.old_home = self.get_user_home()
if self.needs_temp_home:
self.set_user_home(make_tempdir())
os.environ[str('RBTOOLS_EDITOR')] = str(self.default_text_editor)
def tearDown(self):
super(TestCase, self).tearDown()
os.chdir(self._old_cwd)
cleanup_tempfiles()
if self.old_home:
self.set_user_home(self.old_home)
def shortDescription(self):
"""Returns the description of the current test.
This changes the default behavior to replace all newlines with spaces,
allowing a test description to span lines. It should still be kept
short, though.
Returns:
unicode:
The descriptive text for the current unit test.
"""
doc = self._testMethodDoc
if doc is not None:
doc = doc.split('\n\n', 1)[0]
doc = self.ws_re.sub(' ', doc).strip()
return doc
def get_user_home(self):
"""Return the user's current home directory.
Version Added:
3.0
Returns:
unicode:
The current home directory.
"""
return os.environ['HOME']
def set_user_home(self, path):
"""Set the user's current home directory.
This will be unset when the unit test has finished.
Version Added:
3.0
Args:
path (unicode):
The new home directory.
"""
os.environ['HOME'] = path
def chdir_tmp(self):
"""Create a temporary directory and set it as the working directory.
The directory will be deleted after the test has finished.
Version Added:
3.0
Returns:
unicode:
The path to the temp directory.
"""
dirname = make_tempdir()
os.chdir(dirname)
return dirname
def precreate_tempfiles(self, count):
"""Pre-create a specific number of temporary files.
This will call :py:func:`~rbtools.utils.filesystem.make_tempfile`
the specified number of times, returning the list of generated temp
file paths, and will then spy that function to return those temp
files.
Once each pre-created temp file is used up, any further calls to
:py:func:`~rbtools.utils.filesystem.make_tempfile` will result in
an error, failing the test.
This is useful in unit tests that need to script a series of
expected calls using :py:mod:`kgb` (such as through
:py:class:`kgb.ops.SpyOpMatchInOrder`) that need to know the names
of temporary filenames up-front.
Unit test suites that use this must mix in :py:class:`kgb.SpyAgency`.
Args:
count (int):
The number of temporary filenames to pre-create.
Raises:
AssertionError:
The test suite class did not mix in :py:class:`kgb.SpyAgency`.
"""
assert hasattr(self, 'spy_on'), (
'%r must mix in kgb.SpyAgency in order to call this method.'
% self.__class__)
tmpfiles = [
make_tempfile()
for i in range(count)
]
self.spy_on(make_tempfile, op=kgb.SpyOpReturnInOrder(tmpfiles))
return tmpfiles
def assertDiffEqual(self, diff, expected_diff):
"""Assert that two diffs are equal.
Args:
diff (bytes):
The generated diff.
expected_diff (bytes):
The expected diff.
Raises:
AssertionError:
The diffs aren't equal or of the right type.
"""
self.assertIsInstance(diff, bytes)
self.assertIsInstance(expected_diff, bytes)
self.assertEqual(diff.splitlines(), expected_diff.splitlines())
def assertRaisesMessage(self, expected_exception, expected_message):
"""Assert that a call raises an exception with the given message.
Args:
expected_exception (type):
The type of exception that's expected to be raised.
expected_message (unicode):
The expected exception message.
Raises:
AssertionError:
The assertion failure, if the exception and message isn't
raised.
"""
return self.assertRaisesRegexp(expected_exception,
re.escape(expected_message))
@contextmanager
def reviewboardrc(self, config, use_temp_dir=False):
"""Populate a temporary .reviewboardrc file.
This will create a :file:`.reviewboardrc` file, either in the current
directory or in a new temporary directory (if ``use_temp_dir`` is set).
The file will contain the provided configuration.
Version Added:
3.0
Args:
config (dict):
A dictionary of key-value pairs to write into the
:file:`.reviewboardrc` file.
A best effort attempt will be made to write each configuration
to the file.
use_temp_dir (bool, optional):
Whether a temporary directory should be created and set as
the current directory. If set, the file will be written there,
and the directory will be removed after the context manager
finishes.
Context:
The code being run will have a :file:`.reviewboardrc` in the
current directory.
"""
if use_temp_dir:
temp_dir = tempfile.mkdtemp()
cwd = os.getcwd()
os.chdir(temp_dir)
with open('.reviewboardrc', 'w') as fp:
for key, value in six.iteritems(config):
fp.write('%s = %r\n' % (key, value))
try:
yield
finally:
if use_temp_dir:
os.chdir(cwd)
shutil.rmtree(temp_dir)
| rbtools/testing/testcase.py | 7,565 | The base class for RBTools test cases.
This provides helpful utility functions, environment management, and
better docstrings to help craft unit tests for RBTools functionality.
All RBTools unit tests should use this this class or a subclass of it
as the base class.
Assert that two diffs are equal.
Args:
diff (bytes):
The generated diff.
expected_diff (bytes):
The expected diff.
Raises:
AssertionError:
The diffs aren't equal or of the right type.
Assert that a call raises an exception with the given message.
Args:
expected_exception (type):
The type of exception that's expected to be raised.
expected_message (unicode):
The expected exception message.
Raises:
AssertionError:
The assertion failure, if the exception and message isn't
raised.
Create a temporary directory and set it as the working directory.
The directory will be deleted after the test has finished.
Version Added:
3.0
Returns:
unicode:
The path to the temp directory.
Return the user's current home directory.
Version Added:
3.0
Returns:
unicode:
The current home directory.
Pre-create a specific number of temporary files.
This will call :py:func:`~rbtools.utils.filesystem.make_tempfile`
the specified number of times, returning the list of generated temp
file paths, and will then spy that function to return those temp
files.
Once each pre-created temp file is used up, any further calls to
:py:func:`~rbtools.utils.filesystem.make_tempfile` will result in
an error, failing the test.
This is useful in unit tests that need to script a series of
expected calls using :py:mod:`kgb` (such as through
:py:class:`kgb.ops.SpyOpMatchInOrder`) that need to know the names
of temporary filenames up-front.
Unit test suites that use this must mix in :py:class:`kgb.SpyAgency`.
Args:
count (int):
The number of temporary filenames to pre-create.
Raises:
AssertionError:
The test suite class did not mix in :py:class:`kgb.SpyAgency`.
Populate a temporary .reviewboardrc file.
This will create a :file:`.reviewboardrc` file, either in the current
directory or in a new temporary directory (if ``use_temp_dir`` is set).
The file will contain the provided configuration.
Version Added:
3.0
Args:
config (dict):
A dictionary of key-value pairs to write into the
:file:`.reviewboardrc` file.
A best effort attempt will be made to write each configuration
to the file.
use_temp_dir (bool, optional):
Whether a temporary directory should be created and set as
the current directory. If set, the file will be written there,
and the directory will be removed after the context manager
finishes.
Context:
The code being run will have a :file:`.reviewboardrc` in the
current directory.
Set the user's current home directory.
This will be unset when the unit test has finished.
Version Added:
3.0
Args:
path (unicode):
The new home directory.
Returns the description of the current test.
This changes the default behavior to replace all newlines with spaces,
allowing a test description to span lines. It should still be kept
short, though.
Returns:
unicode:
The descriptive text for the current unit test.
Base test cases for RBTools unit tests.
: Whether individual unit tests need a new temporary HOME directory.:: If set, a directory will be created at test startup, and will be: set as the home directory.:: Version Added:: 3.0 | 3,558 | en | 0.840669 |
#!/usr/bin/env python
'''
Pull random words from http://world.std.com/~reinhold/diceware.wordlist.asc
Written 2013 Hal Canary.
Dedicated to the public domain.
'''
import random,math,sys,os
useDevRandom = True
dicewareWordlist = '~/Downloads/diceware.wordlist.asc'
with open(os.path.expanduser(dicewareWordlist)) as f:
WordList = [line.split()[1]
for nu,line in enumerate(f) if 2 <= nu < 7778]
def GetRandom():
if useDevRandom:
with open('/dev/random', 'rb') as f:
random.seed(f.read(16))
return random
else:
return random.SystemRandom()
required_entropy = 128
numwords = int(math.ceil(required_entropy / math.log(len(WordList),2)))
s = ' '.join(GetRandom().choice(WordList) for i in xrange(numwords))
sys.stdout.write(s)
sys.stdout.flush()
sys.stderr.write('\n')
| RandomWords.py | 780 | Pull random words from http://world.std.com/~reinhold/diceware.wordlist.asc
Written 2013 Hal Canary.
Dedicated to the public domain.
!/usr/bin/env python | 155 | en | 0.642213 |
from django.conf.urls import url
from . import views
urlpatterns = [
# 商品列表页
url(r'^list/(?P<category_id>\d+)/(?P<page_num>\d+)/$', views.ListView.as_view(), name='list'),
# 热销排行数据
url(r'^hot/(?P<category_id>\d+)/$', views.HotGoodsView.as_view()),
# 商品详情页
url(r'^detail/(?P<sku_id>\d+)/$', views.DetailView.as_view(), name='detail'),
# 统计分类商品访问量
url(r'^detail/visit/(?P<category_id>\d+)/$', views.DetailVisitView.as_view()),
# 浏览记录
url(r'^browse_histories/$', views.UserBrowseHistory.as_view()),
]
| E_business_project/apps/goods/urls.py | 598 | 商品列表页 热销排行数据 商品详情页 统计分类商品访问量 浏览记录 | 33 | zh | 0.999546 |
import asyncio
import discord
from discord.ext import commands
from discord.commands import slash_command, Option
import wavelink
import json
from dotenv import load_dotenv
import os
load_dotenv()
# Initiate json
file = open("config.json")
data = json.load(file)
# Public variables
guildID = data["guildID"][0]
class musicPlay(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_wavelink_node_ready(self, node: wavelink.Node):
wavelink.NodePool.get_node(identifier=node.identifier)
@commands.Cog.listener()
async def on_wavelink_track_end(
self, player: wavelink.Player, track: wavelink.Track, reason
):
"""When a track ends, check if there is another one in the queue."""
await asyncio.sleep(5)
if not player.queue.is_empty:
next_track = player.queue.get()
await player.play(next_track)
@slash_command(guild_ids=[guildID], description="Play a song!")
async def play(
self, ctx, value: Option(str, required=True, description="Search for the song!")
):
track = await wavelink.YouTubeTrack.search(query=value, return_first=True)
if not ctx.user.voice:
await ctx.respond("You must be in a voice channel to use music commands!")
else:
if not ctx.voice_client:
vc: wavelink.Player = await ctx.author.voice.channel.connect(
cls=wavelink.Player
)
else:
vc: wavelink.Player = ctx.voice_client
if vc.is_playing():
await vc.queue.put_wait(track)
await ctx.respond(
f"{track.title} has been added to queue! Check the queue status using /queue!"
)
else:
await vc.play(track)
await ctx.respond(f"Now playing: {track.title}")
@play.error
async def play_error(self, ctx, error):
await ctx.respond(f"`{error}`")
def setup(bot):
bot.add_cog(musicPlay(bot))
| Music/play.py | 2,081 | Initiate json Public variables | 30 | en | 0.273592 |
import timeit
mapx = 512
mapy = 512
# Good seeds:
# 772855 Spaced out continents
# 15213 Tight continents
# 1238 What I've been working with, for the most part
# 374539 Sparse continents
# 99999
seed = 773202
sea_level = 0.6
DEBUG = 0
GFXDEBUG = 0
setup_time = timeit.default_timer()
tiles = [[None] * mapx for _ in range(mapy)]
lands = []
towns = []
countries = []
have_savefile = False
class Clock():
def __init__(self,t):
self.time_minutes = t
def inc(self,t):
self.time_minutes += t
self.time_minutes = self.time_minutes % (60*24)
def fmt_time(self):
m = self.time_minutes % 60
h = self.time_minutes // 60
return ("%02d%02dZ" % (h, m))
clock = Clock(9*60) # 9 AM | ginit.py | 691 | Good seeds: 772855 Spaced out continents 15213 Tight continents 1238 What I've been working with, for the most part 374539 Sparse continents 99999 9 AM | 151 | en | 0.803054 |
import sympy
import antlr4
from antlr4.error.ErrorListener import ErrorListener
from sympy.core.operations import AssocOp
try:
from gen.PSParser import PSParser
from gen.PSLexer import PSLexer
from gen.PSListener import PSListener
except Exception:
from .gen.PSParser import PSParser
from .gen.PSLexer import PSLexer
from .gen.PSListener import PSListener
from sympy.printing.str import StrPrinter
from sympy.parsing.sympy_parser import parse_expr
import hashlib
VARIABLE_VALUES = {}
def process_sympy(sympy, variable_values={}):
# variable values
global VARIABLE_VALUES
if len(variable_values) > 0:
VARIABLE_VALUES = variable_values
else:
VARIABLE_VALUES = {}
# setup listener
matherror = MathErrorListener(sympy)
# stream input
stream = antlr4.InputStream(sympy)
lex = PSLexer(stream)
lex.removeErrorListeners()
lex.addErrorListener(matherror)
tokens = antlr4.CommonTokenStream(lex)
parser = PSParser(tokens)
# remove default console error listener
parser.removeErrorListeners()
parser.addErrorListener(matherror)
# process the input
return_data = None
math = parser.math()
# if a list
if math.relation_list():
return_data = []
# go over list items
relation_list = math.relation_list().relation_list_content()
for list_item in relation_list.relation():
expr = convert_relation(list_item)
return_data.append(expr)
# if not, do default
else:
relation = math.relation()
return_data = convert_relation(relation)
return return_data
class MathErrorListener(ErrorListener):
def __init__(self, src):
super(ErrorListener, self).__init__()
self.src = src
def syntaxError(self, recog, symbol, line, col, msg, e):
fmt = "%s\n%s\n%s"
marker = "~" * col + "^"
if msg.startswith("missing"):
err = fmt % (msg, self.src, marker)
elif msg.startswith("no viable"):
err = fmt % ("I expected something else here", self.src, marker)
elif msg.startswith("mismatched"):
names = PSParser.literalNames
expected = [names[i] for i in e.getExpectedTokens() if i < len(names)]
if len(expected) < 10:
expected = " ".join(expected)
err = (fmt % ("I expected one of these: " + expected,
self.src, marker))
else:
err = (fmt % ("I expected something else here", self.src, marker))
else:
err = fmt % ("I don't understand this", self.src, marker)
raise Exception(err)
def convert_relation(rel):
if rel.expr():
return convert_expr(rel.expr())
lh = convert_relation(rel.relation(0))
rh = convert_relation(rel.relation(1))
if rel.LT():
return sympy.StrictLessThan(lh, rh, evaluate=False)
elif rel.LTE():
return sympy.LessThan(lh, rh, evaluate=False)
elif rel.GT():
return sympy.StrictGreaterThan(lh, rh, evaluate=False)
elif rel.GTE():
return sympy.GreaterThan(lh, rh, evaluate=False)
elif rel.EQUAL():
return sympy.Eq(lh, rh, evaluate=False)
elif rel.UNEQUAL():
return sympy.Ne(lh, rh, evaluate=False)
def convert_expr(expr):
if expr.additive():
return convert_add(expr.additive())
def convert_matrix(matrix):
# build matrix
row = matrix.matrix_row()
tmp = []
rows = 0
for r in row:
tmp.append([])
for expr in r.expr():
tmp[rows].append(convert_expr(expr))
rows = rows + 1
# return the matrix
return sympy.Matrix(tmp)
def add_flat(lh, rh):
if hasattr(lh, 'is_Add') and lh.is_Add or hasattr(rh, 'is_Add') and rh.is_Add:
args = []
if hasattr(lh, 'is_Add') and lh.is_Add:
args += list(lh.args)
else:
args += [lh]
if hasattr(rh, 'is_Add') and rh.is_Add:
args = args + list(rh.args)
else:
args += [rh]
return sympy.Add(*args, evaluate=False)
else:
return sympy.Add(lh, rh, evaluate=False)
def mat_add_flat(lh, rh):
if hasattr(lh, 'is_MatAdd') and lh.is_MatAdd or hasattr(rh, 'is_MatAdd') and rh.is_MatAdd:
args = []
if hasattr(lh, 'is_MatAdd') and lh.is_MatAdd:
args += list(lh.args)
else:
args += [lh]
if hasattr(rh, 'is_MatAdd') and rh.is_MatAdd:
args = args + list(rh.args)
else:
args += [rh]
return sympy.MatAdd(*args, evaluate=False)
else:
return sympy.MatAdd(lh, rh, evaluate=False)
def mul_flat(lh, rh):
if hasattr(lh, 'is_Mul') and lh.is_Mul or hasattr(rh, 'is_Mul') and rh.is_Mul:
args = []
if hasattr(lh, 'is_Mul') and lh.is_Mul:
args += list(lh.args)
else:
args += [lh]
if hasattr(rh, 'is_Mul') and rh.is_Mul:
args = args + list(rh.args)
else:
args += [rh]
return sympy.Mul(*args, evaluate=False)
else:
return sympy.Mul(lh, rh, evaluate=False)
def mat_mul_flat(lh, rh):
if hasattr(lh, 'is_MatMul') and lh.is_MatMul or hasattr(rh, 'is_MatMul') and rh.is_MatMul:
args = []
if hasattr(lh, 'is_MatMul') and lh.is_MatMul:
args += list(lh.args)
else:
args += [lh]
if hasattr(rh, 'is_MatMul') and rh.is_MatMul:
args = args + list(rh.args)
else:
args += [rh]
return sympy.MatMul(*args, evaluate=False)
else:
return sympy.MatMul(lh, rh, evaluate=False)
def convert_add(add):
if add.ADD():
lh = convert_add(add.additive(0))
rh = convert_add(add.additive(1))
if lh.is_Matrix or rh.is_Matrix:
return mat_add_flat(lh, rh)
else:
return add_flat(lh, rh)
elif add.SUB():
lh = convert_add(add.additive(0))
rh = convert_add(add.additive(1))
if lh.is_Matrix or rh.is_Matrix:
return mat_add_flat(lh, mat_mul_flat(-1, rh))
else:
# If we want to force ordering for variables this should be:
# return Sub(lh, rh, evaluate=False)
if not rh.is_Matrix and rh.func.is_Number:
rh = -rh
else:
rh = mul_flat(-1, rh)
return add_flat(lh, rh)
else:
return convert_mp(add.mp())
def convert_mp(mp):
if hasattr(mp, 'mp'):
mp_left = mp.mp(0)
mp_right = mp.mp(1)
else:
mp_left = mp.mp_nofunc(0)
mp_right = mp.mp_nofunc(1)
if mp.MUL() or mp.CMD_TIMES() or mp.CMD_CDOT():
lh = convert_mp(mp_left)
rh = convert_mp(mp_right)
if lh.is_Matrix or rh.is_Matrix:
return mat_mul_flat(lh, rh)
else:
return mul_flat(lh, rh)
elif mp.DIV() or mp.CMD_DIV() or mp.COLON():
lh = convert_mp(mp_left)
rh = convert_mp(mp_right)
if lh.is_Matrix or rh.is_Matrix:
return sympy.MatMul(lh, sympy.Pow(rh, -1, evaluate=False), evaluate=False)
else:
return sympy.Mul(lh, sympy.Pow(rh, -1, evaluate=False), evaluate=False)
elif mp.CMD_MOD():
lh = convert_mp(mp_left)
rh = convert_mp(mp_right)
if rh.is_Matrix:
raise Exception("Cannot perform modulo operation with a matrix as an operand")
else:
return sympy.Mod(lh, rh, evaluate=False)
else:
if hasattr(mp, 'unary'):
return convert_unary(mp.unary())
else:
return convert_unary(mp.unary_nofunc())
def convert_unary(unary):
if hasattr(unary, 'unary'):
nested_unary = unary.unary()
else:
nested_unary = unary.unary_nofunc()
if hasattr(unary, 'postfix_nofunc'):
first = unary.postfix()
tail = unary.postfix_nofunc()
postfix = [first] + tail
else:
postfix = unary.postfix()
if unary.ADD():
return convert_unary(nested_unary)
elif unary.SUB():
tmp_convert_nested_unary = convert_unary(nested_unary)
if tmp_convert_nested_unary.is_Matrix:
return mat_mul_flat(-1, tmp_convert_nested_unary, evaluate=False)
else:
if tmp_convert_nested_unary.func.is_Number:
return -tmp_convert_nested_unary
else:
return mul_flat(-1, tmp_convert_nested_unary)
elif postfix:
return convert_postfix_list(postfix)
def convert_postfix_list(arr, i=0):
if i >= len(arr):
raise Exception("Index out of bounds")
res = convert_postfix(arr[i])
if isinstance(res, sympy.Expr) or isinstance(res, sympy.Matrix) or res is sympy.S.EmptySet:
if i == len(arr) - 1:
return res # nothing to multiply by
else:
# multiply by next
rh = convert_postfix_list(arr, i + 1)
if res.is_Matrix or rh.is_Matrix:
return mat_mul_flat(res, rh)
else:
return mul_flat(res, rh)
else: # must be derivative
wrt = res[0]
if i == len(arr) - 1:
raise Exception("Expected expression for derivative")
else:
expr = convert_postfix_list(arr, i + 1)
return sympy.Derivative(expr, wrt)
def do_subs(expr, at):
if at.expr():
at_expr = convert_expr(at.expr())
syms = at_expr.atoms(sympy.Symbol)
if len(syms) == 0:
return expr
elif len(syms) > 0:
sym = next(iter(syms))
return expr.subs(sym, at_expr)
elif at.equality():
lh = convert_expr(at.equality().expr(0))
rh = convert_expr(at.equality().expr(1))
return expr.subs(lh, rh)
def convert_postfix(postfix):
if hasattr(postfix, 'exp'):
exp_nested = postfix.exp()
else:
exp_nested = postfix.exp_nofunc()
exp = convert_exp(exp_nested)
for op in postfix.postfix_op():
if op.BANG():
if isinstance(exp, list):
raise Exception("Cannot apply postfix to derivative")
exp = sympy.factorial(exp, evaluate=False)
elif op.eval_at():
ev = op.eval_at()
at_b = None
at_a = None
if ev.eval_at_sup():
at_b = do_subs(exp, ev.eval_at_sup())
if ev.eval_at_sub():
at_a = do_subs(exp, ev.eval_at_sub())
if at_b is not None and at_a is not None:
exp = add_flat(at_b, mul_flat(at_a, -1))
elif at_b is not None:
exp = at_b
elif at_a is not None:
exp = at_a
return exp
def convert_exp(exp):
if hasattr(exp, 'exp'):
exp_nested = exp.exp()
else:
exp_nested = exp.exp_nofunc()
if exp_nested:
base = convert_exp(exp_nested)
if isinstance(base, list):
raise Exception("Cannot raise derivative to power")
if exp.atom():
exponent = convert_atom(exp.atom())
elif exp.expr():
exponent = convert_expr(exp.expr())
return sympy.Pow(base, exponent, evaluate=False)
else:
if hasattr(exp, 'comp'):
return convert_comp(exp.comp())
else:
return convert_comp(exp.comp_nofunc())
def convert_comp(comp):
if comp.group():
return convert_expr(comp.group().expr())
elif comp.abs_group():
return sympy.Abs(convert_expr(comp.abs_group().expr()), evaluate=False)
elif comp.floor_group():
return handle_floor(convert_expr(comp.floor_group().expr()))
elif comp.ceil_group():
return handle_ceil(convert_expr(comp.ceil_group().expr()))
elif comp.atom():
return convert_atom(comp.atom())
elif comp.frac():
return convert_frac(comp.frac())
elif comp.binom():
return convert_binom(comp.binom())
elif comp.matrix():
return convert_matrix(comp.matrix())
elif comp.func():
return convert_func(comp.func())
def convert_atom(atom):
if atom.LETTER_NO_E():
subscriptName = ''
s = atom.LETTER_NO_E().getText()
if s == "I":
return sympy.I
if atom.subexpr():
subscript = None
if atom.subexpr().expr(): # subscript is expr
subscript = convert_expr(atom.subexpr().expr())
else: # subscript is atom
subscript = convert_atom(atom.subexpr().atom())
subscriptName = '_{' + StrPrinter().doprint(subscript) + '}'
return sympy.Symbol(atom.LETTER_NO_E().getText() + subscriptName, real=True)
elif atom.GREEK_LETTER():
s = atom.GREEK_LETTER().getText()[1:]
if atom.subexpr():
subscript = None
if atom.subexpr().expr(): # subscript is expr
subscript = convert_expr(atom.subexpr().expr())
else: # subscript is atom
subscript = convert_atom(atom.subexpr().atom())
subscriptName = StrPrinter().doprint(subscript)
s += '_{' + subscriptName + '}'
return sympy.Symbol(s, real=True)
elif atom.accent():
# get name for accent
name = atom.accent().start.text[1:]
# exception: check if bar or overline which are treated both as bar
if name in ["bar", "overline"]:
name = "bar"
# get the base (variable)
base = atom.accent().base.getText()
# set string to base+name
s = base + name
if atom.subexpr():
subscript = None
if atom.subexpr().expr(): # subscript is expr
subscript = convert_expr(atom.subexpr().expr())
else: # subscript is atom
subscript = convert_atom(atom.subexpr().atom())
subscriptName = StrPrinter().doprint(subscript)
s += '_{' + subscriptName + '}'
return sympy.Symbol(s, real=True)
elif atom.SYMBOL():
s = atom.SYMBOL().getText().replace("\\$", "").replace("\\%", "")
if s == "\\infty":
return sympy.oo
elif s == '\\pi':
return sympy.pi
elif s == '\\emptyset':
return sympy.S.EmptySet
else:
raise Exception("Unrecognized symbol")
elif atom.NUMBER():
s = atom.NUMBER().getText().replace(",", "")
try:
sr = sympy.Rational(s)
return sr
except (TypeError, ValueError):
return sympy.Number(s)
elif atom.E_NOTATION():
s = atom.E_NOTATION().getText().replace(",", "")
try:
sr = sympy.Rational(s)
return sr
except (TypeError, ValueError):
return sympy.Number(s)
elif atom.DIFFERENTIAL():
var = get_differential_var(atom.DIFFERENTIAL())
return sympy.Symbol('d' + var.name, real=True)
elif atom.mathit():
text = rule2text(atom.mathit().mathit_text())
return sympy.Symbol(text, real=True)
elif atom.VARIABLE():
text = atom.VARIABLE().getText()
is_percent = text.endswith("\\%")
trim_amount = 3 if is_percent else 1
name = text[10:]
name = name[0:len(name) - trim_amount]
# add hash to distinguish from regular symbols
# hash = hashlib.md5(name.encode()).hexdigest()
# symbol_name = name + hash
symbol_name = name
# replace the variable for already known variable values
if name in VARIABLE_VALUES:
# if a sympy class
if isinstance(VARIABLE_VALUES[name], tuple(sympy.core.all_classes)):
symbol = VARIABLE_VALUES[name]
# if NOT a sympy class
else:
symbol = parse_expr(str(VARIABLE_VALUES[name]))
else:
symbol = sympy.Symbol(symbol_name, real=True)
if is_percent:
return sympy.Mul(symbol, sympy.Pow(100, -1, evaluate=False), evaluate=False)
# return the symbol
return symbol
elif atom.PERCENT_NUMBER():
text = atom.PERCENT_NUMBER().getText().replace("\\%", "").replace(",", "")
try:
number = sympy.Rational(text)
except (TypeError, ValueError):
number = sympy.Number(text)
percent = sympy.Rational(number, 100)
return percent
def rule2text(ctx):
stream = ctx.start.getInputStream()
# starting index of starting token
startIdx = ctx.start.start
# stopping index of stopping token
stopIdx = ctx.stop.stop
return stream.getText(startIdx, stopIdx)
def convert_frac(frac):
diff_op = False
partial_op = False
lower_itv = frac.lower.getSourceInterval()
lower_itv_len = lower_itv[1] - lower_itv[0] + 1
if (frac.lower.start == frac.lower.stop and
frac.lower.start.type == PSLexer.DIFFERENTIAL):
wrt = get_differential_var_str(frac.lower.start.text)
diff_op = True
elif (lower_itv_len == 2 and
frac.lower.start.type == PSLexer.SYMBOL and
frac.lower.start.text == '\\partial' and
(frac.lower.stop.type == PSLexer.LETTER_NO_E or frac.lower.stop.type == PSLexer.SYMBOL)):
partial_op = True
wrt = frac.lower.stop.text
if frac.lower.stop.type == PSLexer.SYMBOL:
wrt = wrt[1:]
if diff_op or partial_op:
wrt = sympy.Symbol(wrt, real=True)
if (diff_op and frac.upper.start == frac.upper.stop and
frac.upper.start.type == PSLexer.LETTER_NO_E and
frac.upper.start.text == 'd'):
return [wrt]
elif (partial_op and frac.upper.start == frac.upper.stop and
frac.upper.start.type == PSLexer.SYMBOL and
frac.upper.start.text == '\\partial'):
return [wrt]
upper_text = rule2text(frac.upper)
expr_top = None
if diff_op and upper_text.startswith('d'):
expr_top = process_sympy(upper_text[1:])
elif partial_op and frac.upper.start.text == '\\partial':
expr_top = process_sympy(upper_text[len('\\partial'):])
if expr_top:
return sympy.Derivative(expr_top, wrt)
expr_top = convert_expr(frac.upper)
expr_bot = convert_expr(frac.lower)
if expr_top.is_Matrix or expr_bot.is_Matrix:
return sympy.MatMul(expr_top, sympy.Pow(expr_bot, -1, evaluate=False), evaluate=False)
else:
return sympy.Mul(expr_top, sympy.Pow(expr_bot, -1, evaluate=False), evaluate=False)
def convert_binom(binom):
expr_top = convert_expr(binom.upper)
expr_bot = convert_expr(binom.lower)
return sympy.binomial(expr_top, expr_bot)
def convert_func(func):
if func.func_normal_single_arg():
if func.L_PAREN(): # function called with parenthesis
arg = convert_func_arg(func.func_single_arg())
else:
arg = convert_func_arg(func.func_single_arg_noparens())
name = func.func_normal_single_arg().start.text[1:]
# change arc<trig> -> a<trig>
if name in ["arcsin", "arccos", "arctan", "arccsc", "arcsec",
"arccot"]:
name = "a" + name[3:]
expr = getattr(sympy.functions, name)(arg, evaluate=False)
elif name in ["arsinh", "arcosh", "artanh"]:
name = "a" + name[2:]
expr = getattr(sympy.functions, name)(arg, evaluate=False)
elif name in ["arcsinh", "arccosh", "arctanh"]:
name = "a" + name[3:]
expr = getattr(sympy.functions, name)(arg, evaluate=False)
elif name == "operatorname":
operatorname = func.func_normal_single_arg().func_operator_name.getText()
if operatorname in ["arsinh", "arcosh", "artanh"]:
operatorname = "a" + operatorname[2:]
expr = getattr(sympy.functions, operatorname)(arg, evaluate=False)
elif operatorname in ["arcsinh", "arccosh", "arctanh"]:
operatorname = "a" + operatorname[3:]
expr = getattr(sympy.functions, operatorname)(arg, evaluate=False)
elif operatorname == "floor":
expr = handle_floor(arg)
elif operatorname == "ceil":
expr = handle_ceil(arg)
elif name in ["log", "ln"]:
if func.subexpr():
if func.subexpr().atom():
base = convert_atom(func.subexpr().atom())
else:
base = convert_expr(func.subexpr().expr())
elif name == "log":
base = 10
elif name == "ln":
base = sympy.E
expr = sympy.log(arg, base, evaluate=False)
elif name in ["exp", "exponentialE"]:
expr = sympy.exp(arg)
elif name == "floor":
expr = handle_floor(arg)
elif name == "ceil":
expr = handle_ceil(arg)
func_pow = None
should_pow = True
if func.supexpr():
if func.supexpr().expr():
func_pow = convert_expr(func.supexpr().expr())
else:
func_pow = convert_atom(func.supexpr().atom())
if name in ["sin", "cos", "tan", "csc", "sec", "cot", "sinh", "cosh", "tanh"]:
if func_pow == -1:
name = "a" + name
should_pow = False
expr = getattr(sympy.functions, name)(arg, evaluate=False)
if func_pow and should_pow:
expr = sympy.Pow(expr, func_pow, evaluate=False)
return expr
elif func.func_normal_multi_arg():
if func.L_PAREN(): # function called with parenthesis
args = func.func_multi_arg().getText().split(",")
else:
args = func.func_multi_arg_noparens().split(",")
args = list(map(lambda arg: process_sympy(arg, VARIABLE_VALUES), args))
name = func.func_normal_multi_arg().start.text[1:]
if name == "operatorname":
operatorname = func.func_normal_multi_arg().func_operator_name.getText()
if operatorname in ["gcd", "lcm"]:
expr = handle_gcd_lcm(operatorname, args)
elif name in ["gcd", "lcm"]:
expr = handle_gcd_lcm(name, args)
elif name in ["max", "min"]:
name = name[0].upper() + name[1:]
expr = getattr(sympy.functions, name)(*args, evaluate=False)
func_pow = None
should_pow = True
if func.supexpr():
if func.supexpr().expr():
func_pow = convert_expr(func.supexpr().expr())
else:
func_pow = convert_atom(func.supexpr().atom())
if func_pow and should_pow:
expr = sympy.Pow(expr, func_pow, evaluate=False)
return expr
# elif func.LETTER_NO_E() or func.SYMBOL():
# print('LETTER_NO_E or symbol')
# if func.LETTER_NO_E():
# fname = func.LETTER_NO_E().getText()
# elif func.SYMBOL():
# fname = func.SYMBOL().getText()[1:]
# fname = str(fname) # can't be unicode
# if func.subexpr():
# subscript = None
# if func.subexpr().expr(): # subscript is expr
# subscript = convert_expr(func.subexpr().expr())
# else: # subscript is atom
# subscript = convert_atom(func.subexpr().atom())
# subscriptName = StrPrinter().doprint(subscript)
# fname += '_{' + subscriptName + '}'
# input_args = func.args()
# output_args = []
# while input_args.args(): # handle multiple arguments to function
# output_args.append(convert_expr(input_args.expr()))
# input_args = input_args.args()
# output_args.append(convert_expr(input_args.expr()))
# return sympy.Function(fname)(*output_args)
elif func.FUNC_INT():
return handle_integral(func)
elif func.FUNC_SQRT():
expr = convert_expr(func.base)
if func.root:
r = convert_expr(func.root)
return sympy.Pow(expr, 1 / r, evaluate=False)
else:
return sympy.Pow(expr, sympy.S.Half, evaluate=False)
elif func.FUNC_SUM():
return handle_sum_or_prod(func, "summation")
elif func.FUNC_PROD():
return handle_sum_or_prod(func, "product")
elif func.FUNC_LIM():
return handle_limit(func)
elif func.EXP_E():
return handle_exp(func)
def convert_func_arg(arg):
if hasattr(arg, 'expr'):
return convert_expr(arg.expr())
else:
return convert_mp(arg.mp_nofunc())
def handle_integral(func):
if func.additive():
integrand = convert_add(func.additive())
elif func.frac():
integrand = convert_frac(func.frac())
else:
integrand = 1
int_var = None
if func.DIFFERENTIAL():
int_var = get_differential_var(func.DIFFERENTIAL())
else:
for sym in integrand.atoms(sympy.Symbol):
s = str(sym)
if len(s) > 1 and s[0] == 'd':
if s[1] == '\\':
int_var = sympy.Symbol(s[2:], real=True)
else:
int_var = sympy.Symbol(s[1:], real=True)
int_sym = sym
if int_var:
integrand = integrand.subs(int_sym, 1)
else:
# Assume dx by default
int_var = sympy.Symbol('x', real=True)
if func.subexpr():
if func.subexpr().atom():
lower = convert_atom(func.subexpr().atom())
else:
lower = convert_expr(func.subexpr().expr())
if func.supexpr().atom():
upper = convert_atom(func.supexpr().atom())
else:
upper = convert_expr(func.supexpr().expr())
return sympy.Integral(integrand, (int_var, lower, upper))
else:
return sympy.Integral(integrand, int_var)
def handle_sum_or_prod(func, name):
val = convert_mp(func.mp())
iter_var = convert_expr(func.subeq().equality().expr(0))
start = convert_expr(func.subeq().equality().expr(1))
if func.supexpr().expr(): # ^{expr}
end = convert_expr(func.supexpr().expr())
else: # ^atom
end = convert_atom(func.supexpr().atom())
if name == "summation":
return sympy.Sum(val, (iter_var, start, end))
elif name == "product":
return sympy.Product(val, (iter_var, start, end))
def handle_limit(func):
sub = func.limit_sub()
if sub.LETTER_NO_E():
var = sympy.Symbol(sub.LETTER_NO_E().getText(), real=True)
elif sub.GREEK_LETTER():
var = sympy.Symbol(sub.GREEK_LETTER().getText()[1:], real=True)
else:
var = sympy.Symbol('x', real=True)
if sub.SUB():
direction = "-"
else:
direction = "+"
approaching = convert_expr(sub.expr())
content = convert_mp(func.mp())
return sympy.Limit(content, var, approaching, direction)
def handle_exp(func):
if func.supexpr():
if func.supexpr().expr(): # ^{expr}
exp_arg = convert_expr(func.supexpr().expr())
else: # ^atom
exp_arg = convert_atom(func.supexpr().atom())
else:
exp_arg = 1
return sympy.exp(exp_arg)
def handle_gcd_lcm(f, args):
"""
Return the result of gcd() or lcm(), as UnevaluatedExpr
f: str - name of function ("gcd" or "lcm")
args: List[Expr] - list of function arguments
"""
args = tuple(map(sympy.nsimplify, args))
# gcd() and lcm() don't support evaluate=False
return sympy.UnevaluatedExpr(getattr(sympy, f)(args))
def handle_floor(expr):
"""
Apply floor() then return the floored expression.
expr: Expr - sympy expression as an argument to floor()
"""
return sympy.functions.floor(expr, evaluate=False)
def handle_ceil(expr):
"""
Apply ceil() then return the ceil-ed expression.
expr: Expr - sympy expression as an argument to ceil()
"""
return sympy.functions.ceiling(expr, evaluate=False)
def get_differential_var(d):
text = get_differential_var_str(d.getText())
return sympy.Symbol(text, real=True)
def get_differential_var_str(text):
for i in range(1, len(text)):
c = text[i]
if not (c == " " or c == "\r" or c == "\n" or c == "\t"):
idx = i
break
text = text[idx:]
if text[0] == "\\":
text = text[1:]
return text
| latex2sympy.py | 28,709 | Apply ceil() then return the ceil-ed expression.
expr: Expr - sympy expression as an argument to ceil()
Apply floor() then return the floored expression.
expr: Expr - sympy expression as an argument to floor()
Return the result of gcd() or lcm(), as UnevaluatedExpr
f: str - name of function ("gcd" or "lcm")
args: List[Expr] - list of function arguments
variable values setup listener stream input remove default console error listener process the input if a list go over list items if not, do default build matrix return the matrix If we want to force ordering for variables this should be: return Sub(lh, rh, evaluate=False) nothing to multiply by multiply by next must be derivative subscript is expr subscript is atom subscript is expr subscript is atom get name for accent exception: check if bar or overline which are treated both as bar get the base (variable) set string to base+name subscript is expr subscript is atom add hash to distinguish from regular symbols hash = hashlib.md5(name.encode()).hexdigest() symbol_name = name + hash replace the variable for already known variable values if a sympy class if NOT a sympy class return the symbol starting index of starting token stopping index of stopping token function called with parenthesis change arc<trig> -> a<trig> function called with parenthesis elif func.LETTER_NO_E() or func.SYMBOL(): print('LETTER_NO_E or symbol') if func.LETTER_NO_E(): fname = func.LETTER_NO_E().getText() elif func.SYMBOL(): fname = func.SYMBOL().getText()[1:] fname = str(fname) can't be unicode if func.subexpr(): subscript = None if func.subexpr().expr(): subscript is expr subscript = convert_expr(func.subexpr().expr()) else: subscript is atom subscript = convert_atom(func.subexpr().atom()) subscriptName = StrPrinter().doprint(subscript) fname += '_{' + subscriptName + '}' input_args = func.args() output_args = [] while input_args.args(): handle multiple arguments to function output_args.append(convert_expr(input_args.expr())) input_args = input_args.args() output_args.append(convert_expr(input_args.expr())) return sympy.Function(fname)(*output_args) Assume dx by default ^{expr} ^atom ^{expr} ^atom gcd() and lcm() don't support evaluate=False | 2,426 | en | 0.423612 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRequest, HttpResponse
from azure.mgmt.core.exceptions import ARMErrorFormat
from .. import models as _models
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
class ResourceSkusOperations(object):
"""ResourceSkusOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.compute.v2021_07_01.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
def list(
self,
filter=None, # type: Optional[str]
include_extended_locations=None, # type: Optional[str]
**kwargs # type: Any
):
# type: (...) -> Iterable["_models.ResourceSkusResult"]
"""Gets the list of Microsoft.Compute SKUs available for your Subscription.
:param filter: The filter to apply on the operation. Only **location** filter is supported
currently.
:type filter: str
:param include_extended_locations: To Include Extended Locations information or not in the
response.
:type include_extended_locations: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ResourceSkusResult or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.compute.v2021_07_01.models.ResourceSkusResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ResourceSkusResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2021-07-01"
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
if filter is not None:
query_parameters['$filter'] = self._serialize.query("filter", filter, 'str')
if include_extended_locations is not None:
query_parameters['includeExtendedLocations'] = self._serialize.query("include_extended_locations", include_extended_locations, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
def extract_data(pipeline_response):
deserialized = self._deserialize('ResourceSkusResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Compute/skus'} # type: ignore
| sdk/compute/azure-mgmt-compute/azure/mgmt/compute/v2021_07_01/operations/_resource_skus_operations.py | 5,835 | ResourceSkusOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.compute.v2021_07_01.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
Gets the list of Microsoft.Compute SKUs available for your Subscription.
:param filter: The filter to apply on the operation. Only **location** filter is supported
currently.
:type filter: str
:param include_extended_locations: To Include Extended Locations information or not in the
response.
:type include_extended_locations: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ResourceSkusResult or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.compute.v2021_07_01.models.ResourceSkusResult]
:raises: ~azure.core.exceptions.HttpResponseError
coding=utf-8 -------------------------------------------------------------------------- Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. Code generated by Microsoft (R) AutoRest Code Generator. Changes may cause incorrect behavior and will be lost if the code is regenerated. -------------------------------------------------------------------------- pylint: disable=unused-import,ungrouped-imports type: Optional[str] type: Optional[str] type: Any type: (...) -> Iterable["_models.ResourceSkusResult"] type: ClsType["_models.ResourceSkusResult"] Construct headers type: Dict[str, Any] Construct URL type: ignore Construct parameters type: Dict[str, Any] type: Dict[str, Any] type: ignore | 1,959 | en | 0.581253 |
import os
import signal
import sys
from builtins import id as identifier
from toga.command import CommandSet
from toga.handlers import wrapped_handler
from toga.icons import Icon
from toga.platform import get_platform_factory
from toga.window import Window
class MainWindow(Window):
_WINDOW_CLASS = 'MainWindow'
def __init__(self, id=None, title=None, position=(100, 100), size=(640, 480), factory=None):
super().__init__(id=id, title=title, position=position, size=size, factory=factory)
class App:
""" The App is the top level of any GUI program. It is the manager of all
the other bits of the GUI app: the main window and events that window
generates like user input.
When you create an App you need to provide it a name, an id for uniqueness
(by convention, the identifier is a "reversed domain name".) and an
optional startup function which should run once the App has initialised.
The startup function typically constructs some initial user interface.
Once the app is created you should invoke the main_loop() method, which
will hand over execution of your program to Toga to make the App interface
do its thing.
Args:
name (str): Is the name of the application.
app_id (str): The unique application identifier, the reversed domain name, e.g. 'org.beeware.me'
icon (str): Path to the icon for the application.
id (str): The DOM identifier for the app (optional)
startup(``callable``): The callback method before starting the app, typically to add the components.
Must be a ``callable`` that expects a single argument of :class:`toga.App`.
factory (:obj:`module`): A python module that is capable to return a
implementation of this class with the same name. (optional & normally not needed)
Examples:
>>> # Here is the absolute minimum App::
>>> app = toga.App('Empty App', 'org.beeware.empty')
>>> app.main_loop()
"""
app = None
def __init__(self, name, app_id,
id=None, icon=None, startup=None, on_exit=None, factory=None):
self.factory = get_platform_factory(factory)
# Keep an accessible copy of the app instance
App.app = self
App.app_module = self.__module__.split('.')[0]
App.app_dir = os.path.dirname(sys.modules[App.app_module].__file__)
self.name = name
self._app_id = app_id
self._id = id if id else identifier(self)
self.commands = CommandSet(factory=self.factory)
self._startup_method = startup
self.default_icon = Icon('tiberius', system=True)
self.icon = icon
self._main_window = None
self._on_exit = None
self._full_screen_windows = None
self._impl = self._create_impl()
self.on_exit = on_exit
def _create_impl(self):
return self.factory.App(interface=self)
@property
def app_id(self):
""" The identifier for the app.
This is the reversed domain name, often used for targetting resources, etc.
Returns:
The identifier as a ``str``.
"""
return self._app_id
@property
def id(self):
""" The DOM identifier for the app. This id can be used to target CSS directives.
Returns:
The identifier for the app as a ``str``.
"""
return self._id
@property
def icon(self):
""" The Icon for the app. On setting, the icon is loaded automatically.
Returns:
The icon of the app ``toga.Icon``.
"""
return self._icon
@icon.setter
def icon(self, name):
self._icon = Icon.load(name, default=self.default_icon)
@property
def main_window(self):
"""The main Windows for the app.
Returns:
The main Window of the app.
"""
return self._main_window
@main_window.setter
def main_window(self, window):
self._main_window = window
window.app = self
@property
def current_window(self):
"""Return the currently active content window"""
return self._impl.current_window().interface
@property
def is_full_screen(self):
"""Is the app currently in full screen mode?"""
return self._full_screen_windows is not None
def set_full_screen(self, *windows):
"""Make one or more windows full screen.
Full screen is not the same as "maximized"; full screen mode
is when all window borders and other chrome is no longer
visible.
Args:
windows: The list of windows to go full screen,
in order of allocation to screens. If the number of
windows exceeds the number of available displays,
those windows will not be visible. If no windows
are specified, the app will exit full screen mode.
"""
if not windows:
self.exit_full_screen()
else:
self._impl.enter_full_screen(windows)
self._full_screen_windows = windows
def exit_full_screen(self):
"""Exit full screen mode."""
if self.is_full_screen:
self._impl.exit_full_screen(self._full_screen_windows)
self._full_screen_windows = None
def show_cursor(self):
"""Show cursor."""
self._impl.show_cursor()
def hide_cursor(self):
"""Hide cursor from view."""
self._impl.hide_cursor()
def startup(self):
""" Create and show the main window for the application
"""
self.main_window = MainWindow(title=self.name, factory=self.factory)
if self._startup_method:
self.main_window.content = self._startup_method(self)
self.main_window.show()
def main_loop(self):
""" Invoke the application to handle user input.
This method typically only returns once the application is exiting.
"""
# Modify signal handlers to make sure Ctrl-C is caught and handled.
signal.signal(signal.SIGINT, signal.SIG_DFL)
self._impl.main_loop()
def exit(self):
""" Quit the application gracefully.
"""
self._impl.exit()
@property
def on_exit(self):
"""The handler to invoke before the application exits.
Returns:
The function ``callable`` that is called on application exit.
"""
return self._on_exit
@on_exit.setter
def on_exit(self, handler):
"""Set the handler to invoke before the app exits.
Args:
handler (:obj:`callable`): The handler to invoke before the app exits.
"""
self._on_exit = wrapped_handler(self, handler)
self._impl.set_on_exit(self._on_exit)
class DocumentApp(App):
"""
A document-based application.
Definition and arguments are the same as a base App, plus the following:
Args:
document_types (:obj:`list` of :obj:`str`): Document types.
"""
def __init__(self, name, app_id,
id=None, icon=None, startup=None, document_types=None, on_exit=None, factory=None):
self.document_types = document_types
self._documents = []
super().__init__(name, app_id,
id=id, icon=icon, startup=startup, on_exit=on_exit, factory=factory)
def _create_impl(self):
return self.factory.DocumentApp(interface=self)
@property
def documents(self):
""" Return the list of documents associated with this app.
Returns:
A ``list`` of ``str``.
"""
return self._documents
| src/core/toga/app.py | 7,707 | The App is the top level of any GUI program. It is the manager of all
the other bits of the GUI app: the main window and events that window
generates like user input.
When you create an App you need to provide it a name, an id for uniqueness
(by convention, the identifier is a "reversed domain name".) and an
optional startup function which should run once the App has initialised.
The startup function typically constructs some initial user interface.
Once the app is created you should invoke the main_loop() method, which
will hand over execution of your program to Toga to make the App interface
do its thing.
Args:
name (str): Is the name of the application.
app_id (str): The unique application identifier, the reversed domain name, e.g. 'org.beeware.me'
icon (str): Path to the icon for the application.
id (str): The DOM identifier for the app (optional)
startup(``callable``): The callback method before starting the app, typically to add the components.
Must be a ``callable`` that expects a single argument of :class:`toga.App`.
factory (:obj:`module`): A python module that is capable to return a
implementation of this class with the same name. (optional & normally not needed)
Examples:
>>> # Here is the absolute minimum App::
>>> app = toga.App('Empty App', 'org.beeware.empty')
>>> app.main_loop()
A document-based application.
Definition and arguments are the same as a base App, plus the following:
Args:
document_types (:obj:`list` of :obj:`str`): Document types.
The identifier for the app.
This is the reversed domain name, often used for targetting resources, etc.
Returns:
The identifier as a ``str``.
Return the currently active content window
Return the list of documents associated with this app.
Returns:
A ``list`` of ``str``.
Quit the application gracefully.
Exit full screen mode.
Hide cursor from view.
The Icon for the app. On setting, the icon is loaded automatically.
Returns:
The icon of the app ``toga.Icon``.
The DOM identifier for the app. This id can be used to target CSS directives.
Returns:
The identifier for the app as a ``str``.
Is the app currently in full screen mode?
Invoke the application to handle user input.
This method typically only returns once the application is exiting.
The main Windows for the app.
Returns:
The main Window of the app.
The handler to invoke before the application exits.
Returns:
The function ``callable`` that is called on application exit.
Set the handler to invoke before the app exits.
Args:
handler (:obj:`callable`): The handler to invoke before the app exits.
Make one or more windows full screen.
Full screen is not the same as "maximized"; full screen mode
is when all window borders and other chrome is no longer
visible.
Args:
windows: The list of windows to go full screen,
in order of allocation to screens. If the number of
windows exceeds the number of available displays,
those windows will not be visible. If no windows
are specified, the app will exit full screen mode.
Show cursor.
Create and show the main window for the application
Keep an accessible copy of the app instance Modify signal handlers to make sure Ctrl-C is caught and handled. | 3,296 | en | 0.831589 |
# this file is deprecated and will soon be folded into all.py
from collections import namedtuple
from pycoin.serialize import h2b
NetworkValues = namedtuple('NetworkValues',
('network_name', 'subnet_name', 'code', 'wif', 'address',
'pay_to_script', 'prv32', 'pub32'))
NETWORKS = (
# VIA viacoin mainnet : xprv/xpub
NetworkValues("Viacoin", "mainnet", "VIA", b'\xc7', b'\x47', b'\x21', h2b('0488ADE4'), h2b('0488B21E')),
# VIA viacoin testnet : tprv/tpub
NetworkValues("Viacoin", "testnet", "TVI", b'\xff', b'\x7f', b'\xc4', h2b('04358394'), h2b('043587CF')),
# FTC feathercoin mainnet : xprv/xpub
NetworkValues(
"Feathercoin", "mainnet", "FTC", b'\x8e', b'\x0e', b'\x60', h2b('0488ADE4'), h2b('0488B21E')),
# FTC feathercoin testnet : tprv/tpub
NetworkValues(
"Feathercoin", "testnet", "FTX", b'\xC1', b'\x41', b'\xc4', h2b('04358394'), h2b('043587CF')),
# DOGE Dogecoin mainnet : dogv/dogp
NetworkValues(
"Dogecoin", "mainnet", "DOGE", b'\x9e', b'\x1e', b'\x16', h2b("02FD3955"), h2b("02FD3929")),
# DOGE Dogecoin testnet : tgpv/tgub
NetworkValues(
"Dogecoin", "testnet", "XDT", b'\xf1', b'\x71', b'\xc4', h2b("0432a9a8"), h2b("0432a243")),
# BC BlackCoin mainnet : bcpv/bcpb
NetworkValues("Blackcoin", "mainnet", "BC", b'\x99', b'\x19', None, h2b("02cfbf60"), h2b("02cfbede")),
# DRK Dash mainnet : drkv/drkp
NetworkValues(
"Dash", "mainnet", "DASH", b'\xcc', b'\x4c', b'\x10', h2b("02fe52f8"), h2b("02fe52cc")),
# DRK Dash testnet : DRKV/DRKP
NetworkValues(
"Dash", "testnet", "tDASH", b'\xef', b'\x8c', b'\x13', h2b("3a8061a0"), h2b("3a805837")),
# MEC Megacoin mainnet : mecv/mecp
NetworkValues("Megacoin", "mainnet", "MEC", b'\xb2', b'\x32', None, h2b("03a04db7"), h2b("03a04d8b")),
NetworkValues(
"Myriadcoin", "mainnet", "MYR", b'\xb2', b'\x32', b'\x09', h2b('0488ADE4'), h2b('0488B21E')),
NetworkValues(
"Unobtanium", "mainnet", "UNO", b'\xe0', b'\x82', b'\x1e', h2b('0488ADE4'), h2b('0488B21E')),
# JBS Jumbucks mainnet : jprv/jpub
NetworkValues("Jumbucks", "mainnet", "JBS", b'\xab', b'\x2b', None, h2b('037a6460'), h2b('037a689a')),
# MZC Mazacoin mainnet: xprv/xpub
NetworkValues("Mazacoin", "mainnet", "MZC", b'\xe0', b'\x32', b'\9', h2b("0488ADE4"), h2b("0488B21E")),
NetworkValues(
"Riecoin", "mainnet", "RIC", b'\x80', b'\x3c', b'\x05', h2b('0488ADE4'), h2b('0488B21E')),
# DFC Defcoin mainnet: dfcv/dfcp
NetworkValues("DEFCOIN", "mainnet", "DFC", b'\x9e', b'\x1e', b'\5', h2b("02FA54D7"), h2b("02FA54AD")),
# FAI faircoin mainnet : xprv/xpub
NetworkValues(
"Faircoin", "mainnet", "FAI", b'\xdf', b'\x5f', b'\x24', h2b("0488ADE4"), h2b("0488B21E")),
# ARG argentum mainnet : xprv/xpub
NetworkValues("Argentum", "mainnet", "ARG", b'\x97', b'\x17', b'\5', h2b("0488ADE4"), h2b("0488B21E")),
# ZEC Zcash mainnet : xprv/xpub
NetworkValues("Zcash", "mainnet", "ZEC", b'\x80', b'\x1C\xB8',
b'\x1C\xBD', h2b("0488ADE4"), h2b("0488B21E")),
# BTCD BitcoinDark mainnet : xprv/xpub
NetworkValues("BitcoinDark", "mainnet", "BTCD", b'\x44', b'\x3C', b'\55', h2b('0488ADE4'), h2b('0488B21E')),
# DCR Decred mainnet : dprv/dpub
NetworkValues("Decred", "mainnet", "DCR", b'\x22\xDE', b'\x07\x3F', b'\x07\x1A', h2b('02FDA4E8'), h2b('02FDA926')),
# DCR Decred testnet : tprv/tpub
NetworkValues("Decred", "testnet", "DCRT", b'\x23\x0E', b'\x0F\x21', b'\x0E\x6C', h2b('04358397'), h2b('043587D1')),
)
| pycoin/networks/legacy_networks.py | 3,640 | this file is deprecated and will soon be folded into all.py VIA viacoin mainnet : xprv/xpub VIA viacoin testnet : tprv/tpub FTC feathercoin mainnet : xprv/xpub FTC feathercoin testnet : tprv/tpub DOGE Dogecoin mainnet : dogv/dogp DOGE Dogecoin testnet : tgpv/tgub BC BlackCoin mainnet : bcpv/bcpb DRK Dash mainnet : drkv/drkp DRK Dash testnet : DRKV/DRKP MEC Megacoin mainnet : mecv/mecp JBS Jumbucks mainnet : jprv/jpub MZC Mazacoin mainnet: xprv/xpub DFC Defcoin mainnet: dfcv/dfcp FAI faircoin mainnet : xprv/xpub ARG argentum mainnet : xprv/xpub ZEC Zcash mainnet : xprv/xpub BTCD BitcoinDark mainnet : xprv/xpub DCR Decred mainnet : dprv/dpub DCR Decred testnet : tprv/tpub | 678 | en | 0.339948 |
# -*- coding: utf-8 -*-
__title__ = "Universal Notifications"
__version__ = "1.5.0"
__author__ = "Pawel Krzyzaniak"
__license__ = "MIT"
__copyright__ = "Copyright 2017-2018 Arabella; 2018+ Ro"
# Version synonym
VERSION = __version__
| universal_notifications/__init__.py | 234 | -*- coding: utf-8 -*- Version synonym | 37 | en | 0.933493 |
#
# The OpenDiamond Platform for Interactive Search
#
# Copyright (c) 2009-2019 Carnegie Mellon University
# All rights reserved.
#
# This software is distributed under the terms of the Eclipse Public
# License, Version 1.0 which can be found in the file named LICENSE.
# ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS SOFTWARE CONSTITUTES
# RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT
#
from django.conf.urls import url
from . import views
app_name = 'mirage'
urlpatterns = [
url('^$', views.index, name='index'),
]
| opendiamond/scopeserver/mirage/urls.py | 526 | The OpenDiamond Platform for Interactive Search Copyright (c) 2009-2019 Carnegie Mellon University All rights reserved. This software is distributed under the terms of the Eclipse Public License, Version 1.0 which can be found in the file named LICENSE. ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS SOFTWARE CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT | 367 | en | 0.877803 |
#!/usr/bin/env python3
# Copyright (c) 2016-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test compact blocks (BIP 152).
Version 1 compact blocks are pre-segwit (txids)
Version 2 compact blocks are post-segwit (wtxids)
"""
import random
from test_framework.blocktools import create_block, create_coinbase, add_witness_commitment
from test_framework.messages import BlockTransactions, BlockTransactionsRequest, calculate_shortid, CBlock, CBlockHeader, CInv, COutPoint, CTransaction, CTxIn, CTxInWitness, CTxOut, FromHex, HeaderAndShortIDs, msg_no_witness_block, msg_no_witness_blocktxn, msg_cmpctblock, msg_getblocktxn, msg_getdata, msg_getheaders, msg_headers, msg_inv, msg_sendcmpct, msg_sendheaders, msg_tx, msg_block, msg_blocktxn, MSG_WITNESS_FLAG, NODE_NETWORK, P2PHeaderAndShortIDs, PrefilledTransaction, ser_uint256, ToHex
from test_framework.mininode import mininode_lock, P2PInterface
from test_framework.script import CScript, OP_TRUE, OP_DROP
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal, wait_until, softfork_active
# TestP2PConn: A peer we use to send messages to bitcoind, and store responses.
class TestP2PConn(P2PInterface):
def __init__(self, cmpct_version):
super().__init__()
self.last_sendcmpct = []
self.block_announced = False
# Store the hashes of blocks we've seen announced.
# This is for synchronizing the p2p message traffic,
# so we can eg wait until a particular block is announced.
self.announced_blockhashes = set()
self.cmpct_version = cmpct_version
def on_sendcmpct(self, message):
self.last_sendcmpct.append(message)
def on_cmpctblock(self, message):
self.block_announced = True
self.last_message["cmpctblock"].header_and_shortids.header.calc_sha256()
self.announced_blockhashes.add(self.last_message["cmpctblock"].header_and_shortids.header.sha256)
def on_headers(self, message):
self.block_announced = True
for x in self.last_message["headers"].headers:
x.calc_sha256()
self.announced_blockhashes.add(x.sha256)
def on_inv(self, message):
for x in self.last_message["inv"].inv:
if x.type == 2:
self.block_announced = True
self.announced_blockhashes.add(x.hash)
# Requires caller to hold mininode_lock
def received_block_announcement(self):
return self.block_announced
def clear_block_announcement(self):
with mininode_lock:
self.block_announced = False
self.last_message.pop("inv", None)
self.last_message.pop("headers", None)
self.last_message.pop("cmpctblock", None)
def get_headers(self, locator, hashstop):
msg = msg_getheaders()
msg.locator.vHave = locator
msg.hashstop = hashstop
self.send_message(msg)
def send_header_for_blocks(self, new_blocks):
headers_message = msg_headers()
headers_message.headers = [CBlockHeader(b) for b in new_blocks]
self.send_message(headers_message)
def request_headers_and_sync(self, locator, hashstop=0):
self.clear_block_announcement()
self.get_headers(locator, hashstop)
wait_until(self.received_block_announcement, timeout=30, lock=mininode_lock)
self.clear_block_announcement()
# Block until a block announcement for a particular block hash is
# received.
def wait_for_block_announcement(self, block_hash, timeout=30):
def received_hash():
return (block_hash in self.announced_blockhashes)
wait_until(received_hash, timeout=timeout, lock=mininode_lock)
def send_await_disconnect(self, message, timeout=30):
"""Sends a message to the node and wait for disconnect.
This is used when we want to send a message into the node that we expect
will get us disconnected, eg an invalid block."""
self.send_message(message)
wait_until(lambda: not self.is_connected, timeout=timeout, lock=mininode_lock)
class CompactBlocksTest(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
self.extra_args = [[
"-acceptnonstdtxn=1",
]]
self.utxos = []
def skip_test_if_missing_module(self):
self.skip_if_no_wallet()
def build_block_on_tip(self, node, segwit=False):
height = node.getblockcount()
tip = node.getbestblockhash()
mtp = node.getblockheader(tip)['mediantime']
block = create_block(int(tip, 16), create_coinbase(height + 1), mtp + 1)
block.nVersion = 4
if segwit:
add_witness_commitment(block)
block.solve()
return block
# Create 10 more anyone-can-spend utxo's for testing.
def make_utxos(self):
block = self.build_block_on_tip(self.nodes[0])
self.segwit_node.send_and_ping(msg_no_witness_block(block))
assert int(self.nodes[0].getbestblockhash(), 16) == block.sha256
self.nodes[0].generatetoaddress(100, self.nodes[0].getnewaddress(address_type="bech32"))
total_value = block.vtx[0].vout[0].nValue
out_value = total_value // 10
tx = CTransaction()
tx.vin.append(CTxIn(COutPoint(block.vtx[0].sha256, 0), b''))
for i in range(10):
tx.vout.append(CTxOut(out_value, CScript([OP_TRUE])))
tx.rehash()
block2 = self.build_block_on_tip(self.nodes[0])
block2.vtx.append(tx)
block2.hashMerkleRoot = block2.calc_merkle_root()
block2.solve()
self.segwit_node.send_and_ping(msg_no_witness_block(block2))
assert_equal(int(self.nodes[0].getbestblockhash(), 16), block2.sha256)
self.utxos.extend([[tx.sha256, i, out_value] for i in range(10)])
# Test "sendcmpct" (between peers preferring the same version):
# - No compact block announcements unless sendcmpct is sent.
# - If sendcmpct is sent with version > preferred_version, the message is ignored.
# - If sendcmpct is sent with boolean 0, then block announcements are not
# made with compact blocks.
# - If sendcmpct is then sent with boolean 1, then new block announcements
# are made with compact blocks.
# If old_node is passed in, request compact blocks with version=preferred-1
# and verify that it receives block announcements via compact block.
def test_sendcmpct(self, test_node, old_node=None):
preferred_version = test_node.cmpct_version
node = self.nodes[0]
# Make sure we get a SENDCMPCT message from our peer
def received_sendcmpct():
return (len(test_node.last_sendcmpct) > 0)
wait_until(received_sendcmpct, timeout=30, lock=mininode_lock)
with mininode_lock:
# Check that the first version received is the preferred one
assert_equal(test_node.last_sendcmpct[0].version, preferred_version)
# And that we receive versions down to 1.
assert_equal(test_node.last_sendcmpct[-1].version, 1)
test_node.last_sendcmpct = []
tip = int(node.getbestblockhash(), 16)
def check_announcement_of_new_block(node, peer, predicate):
peer.clear_block_announcement()
block_hash = int(node.generate(1)[0], 16)
peer.wait_for_block_announcement(block_hash, timeout=30)
assert peer.block_announced
with mininode_lock:
assert predicate(peer), (
"block_hash={!r}, cmpctblock={!r}, inv={!r}".format(
block_hash, peer.last_message.get("cmpctblock", None), peer.last_message.get("inv", None)))
# We shouldn't get any block announcements via cmpctblock yet.
check_announcement_of_new_block(node, test_node, lambda p: "cmpctblock" not in p.last_message)
# Try one more time, this time after requesting headers.
test_node.request_headers_and_sync(locator=[tip])
check_announcement_of_new_block(node, test_node, lambda p: "cmpctblock" not in p.last_message and "inv" in p.last_message)
# Test a few ways of using sendcmpct that should NOT
# result in compact block announcements.
# Before each test, sync the headers chain.
test_node.request_headers_and_sync(locator=[tip])
# Now try a SENDCMPCT message with too-high version
sendcmpct = msg_sendcmpct()
sendcmpct.version = preferred_version + 1
sendcmpct.announce = True
test_node.send_and_ping(sendcmpct)
check_announcement_of_new_block(node, test_node, lambda p: "cmpctblock" not in p.last_message)
# Headers sync before next test.
test_node.request_headers_and_sync(locator=[tip])
# Now try a SENDCMPCT message with valid version, but announce=False
sendcmpct.version = preferred_version
sendcmpct.announce = False
test_node.send_and_ping(sendcmpct)
check_announcement_of_new_block(node, test_node, lambda p: "cmpctblock" not in p.last_message)
# Headers sync before next test.
test_node.request_headers_and_sync(locator=[tip])
# Finally, try a SENDCMPCT message with announce=True
sendcmpct.version = preferred_version
sendcmpct.announce = True
test_node.send_and_ping(sendcmpct)
check_announcement_of_new_block(node, test_node, lambda p: "cmpctblock" in p.last_message)
# Try one more time (no headers sync should be needed!)
check_announcement_of_new_block(node, test_node, lambda p: "cmpctblock" in p.last_message)
# Try one more time, after turning on sendheaders
test_node.send_and_ping(msg_sendheaders())
check_announcement_of_new_block(node, test_node, lambda p: "cmpctblock" in p.last_message)
# Try one more time, after sending a version-1, announce=false message.
sendcmpct.version = preferred_version - 1
sendcmpct.announce = False
test_node.send_and_ping(sendcmpct)
check_announcement_of_new_block(node, test_node, lambda p: "cmpctblock" in p.last_message)
# Now turn off announcements
sendcmpct.version = preferred_version
sendcmpct.announce = False
test_node.send_and_ping(sendcmpct)
check_announcement_of_new_block(node, test_node, lambda p: "cmpctblock" not in p.last_message and "headers" in p.last_message)
if old_node is not None:
# Verify that a peer using an older protocol version can receive
# announcements from this node.
sendcmpct.version = preferred_version - 1
sendcmpct.announce = True
old_node.send_and_ping(sendcmpct)
# Header sync
old_node.request_headers_and_sync(locator=[tip])
check_announcement_of_new_block(node, old_node, lambda p: "cmpctblock" in p.last_message)
# This test actually causes bitcoind to (reasonably!) disconnect us, so do this last.
def test_invalid_cmpctblock_message(self):
self.nodes[0].generate(101)
block = self.build_block_on_tip(self.nodes[0])
cmpct_block = P2PHeaderAndShortIDs()
cmpct_block.header = CBlockHeader(block)
cmpct_block.prefilled_txn_length = 1
# This index will be too high
prefilled_txn = PrefilledTransaction(1, block.vtx[0])
cmpct_block.prefilled_txn = [prefilled_txn]
self.segwit_node.send_await_disconnect(msg_cmpctblock(cmpct_block))
assert_equal(int(self.nodes[0].getbestblockhash(), 16), block.hashPrevBlock)
# Compare the generated shortids to what we expect based on BIP 152, given
# bitcoind's choice of nonce.
def test_compactblock_construction(self, test_node, use_witness_address=True):
version = test_node.cmpct_version
node = self.nodes[0]
# Generate a bunch of transactions.
node.generate(101)
num_transactions = 25
address = node.getnewaddress()
segwit_tx_generated = False
for i in range(num_transactions):
txid = node.sendtoaddress(address, 0.1)
hex_tx = node.gettransaction(txid)["hex"]
tx = FromHex(CTransaction(), hex_tx)
if not tx.wit.is_null():
segwit_tx_generated = True
if use_witness_address:
assert segwit_tx_generated # check that our test is not broken
# Wait until we've seen the block announcement for the resulting tip
tip = int(node.getbestblockhash(), 16)
test_node.wait_for_block_announcement(tip)
# Make sure we will receive a fast-announce compact block
self.request_cb_announcements(test_node)
# Now mine a block, and look at the resulting compact block.
test_node.clear_block_announcement()
block_hash = int(node.generate(1)[0], 16)
# Store the raw block in our internal format.
block = FromHex(CBlock(), node.getblock("%064x" % block_hash, False))
for tx in block.vtx:
tx.calc_sha256()
block.rehash()
# Wait until the block was announced (via compact blocks)
wait_until(test_node.received_block_announcement, timeout=30, lock=mininode_lock)
# Now fetch and check the compact block
header_and_shortids = None
with mininode_lock:
assert "cmpctblock" in test_node.last_message
# Convert the on-the-wire representation to absolute indexes
header_and_shortids = HeaderAndShortIDs(test_node.last_message["cmpctblock"].header_and_shortids)
self.check_compactblock_construction_from_block(version, header_and_shortids, block_hash, block)
# Now fetch the compact block using a normal non-announce getdata
with mininode_lock:
test_node.clear_block_announcement()
inv = CInv(4, block_hash) # 4 == "CompactBlock"
test_node.send_message(msg_getdata([inv]))
wait_until(test_node.received_block_announcement, timeout=30, lock=mininode_lock)
# Now fetch and check the compact block
header_and_shortids = None
with mininode_lock:
assert "cmpctblock" in test_node.last_message
# Convert the on-the-wire representation to absolute indexes
header_and_shortids = HeaderAndShortIDs(test_node.last_message["cmpctblock"].header_and_shortids)
self.check_compactblock_construction_from_block(version, header_and_shortids, block_hash, block)
def check_compactblock_construction_from_block(self, version, header_and_shortids, block_hash, block):
# Check that we got the right block!
header_and_shortids.header.calc_sha256()
assert_equal(header_and_shortids.header.sha256, block_hash)
# Make sure the prefilled_txn appears to have included the coinbase
assert len(header_and_shortids.prefilled_txn) >= 1
assert_equal(header_and_shortids.prefilled_txn[0].index, 0)
# Check that all prefilled_txn entries match what's in the block.
for entry in header_and_shortids.prefilled_txn:
entry.tx.calc_sha256()
# This checks the non-witness parts of the tx agree
assert_equal(entry.tx.sha256, block.vtx[entry.index].sha256)
# And this checks the witness
wtxid = entry.tx.calc_sha256(True)
if version == 2:
assert_equal(wtxid, block.vtx[entry.index].calc_sha256(True))
else:
# Shouldn't have received a witness
assert entry.tx.wit.is_null()
# Check that the cmpctblock message announced all the transactions.
assert_equal(len(header_and_shortids.prefilled_txn) + len(header_and_shortids.shortids), len(block.vtx))
# And now check that all the shortids are as expected as well.
# Determine the siphash keys to use.
[k0, k1] = header_and_shortids.get_siphash_keys()
index = 0
while index < len(block.vtx):
if (len(header_and_shortids.prefilled_txn) > 0 and
header_and_shortids.prefilled_txn[0].index == index):
# Already checked prefilled transactions above
header_and_shortids.prefilled_txn.pop(0)
else:
tx_hash = block.vtx[index].sha256
if version == 2:
tx_hash = block.vtx[index].calc_sha256(True)
shortid = calculate_shortid(k0, k1, tx_hash)
assert_equal(shortid, header_and_shortids.shortids[0])
header_and_shortids.shortids.pop(0)
index += 1
# Test that bitcoind requests compact blocks when we announce new blocks
# via header or inv, and that responding to getblocktxn causes the block
# to be successfully reconstructed.
# Post-segwit: upgraded nodes would only make this request of cb-version-2,
# NODE_WITNESS peers. Unupgraded nodes would still make this request of
# any cb-version-1-supporting peer.
def test_compactblock_requests(self, test_node, segwit=True):
version = test_node.cmpct_version
node = self.nodes[0]
# Try announcing a block with an inv or header, expect a compactblock
# request
for announce in ["inv", "header"]:
block = self.build_block_on_tip(node, segwit=segwit)
with mininode_lock:
test_node.last_message.pop("getdata", None)
if announce == "inv":
test_node.send_message(msg_inv([CInv(2, block.sha256)]))
wait_until(lambda: "getheaders" in test_node.last_message, timeout=30, lock=mininode_lock)
test_node.send_header_for_blocks([block])
else:
test_node.send_header_for_blocks([block])
wait_until(lambda: "getdata" in test_node.last_message, timeout=30, lock=mininode_lock)
assert_equal(len(test_node.last_message["getdata"].inv), 1)
assert_equal(test_node.last_message["getdata"].inv[0].type, 4)
assert_equal(test_node.last_message["getdata"].inv[0].hash, block.sha256)
# Send back a compactblock message that omits the coinbase
comp_block = HeaderAndShortIDs()
comp_block.header = CBlockHeader(block)
comp_block.nonce = 0
[k0, k1] = comp_block.get_siphash_keys()
coinbase_hash = block.vtx[0].sha256
if version == 2:
coinbase_hash = block.vtx[0].calc_sha256(True)
comp_block.shortids = [calculate_shortid(k0, k1, coinbase_hash)]
test_node.send_and_ping(msg_cmpctblock(comp_block.to_p2p()))
assert_equal(int(node.getbestblockhash(), 16), block.hashPrevBlock)
# Expect a getblocktxn message.
with mininode_lock:
assert "getblocktxn" in test_node.last_message
absolute_indexes = test_node.last_message["getblocktxn"].block_txn_request.to_absolute()
assert_equal(absolute_indexes, [0]) # should be a coinbase request
# Send the coinbase, and verify that the tip advances.
if version == 2:
msg = msg_blocktxn()
else:
msg = msg_no_witness_blocktxn()
msg.block_transactions.blockhash = block.sha256
msg.block_transactions.transactions = [block.vtx[0]]
test_node.send_and_ping(msg)
assert_equal(int(node.getbestblockhash(), 16), block.sha256)
# Create a chain of transactions from given utxo, and add to a new block.
def build_block_with_transactions(self, node, utxo, num_transactions):
block = self.build_block_on_tip(node)
for i in range(num_transactions):
tx = CTransaction()
tx.vin.append(CTxIn(COutPoint(utxo[0], utxo[1]), b''))
tx.vout.append(CTxOut(utxo[2] - 1000, CScript([OP_TRUE, OP_DROP] * 15 + [OP_TRUE])))
tx.rehash()
utxo = [tx.sha256, 0, tx.vout[0].nValue]
block.vtx.append(tx)
block.hashMerkleRoot = block.calc_merkle_root()
block.solve()
return block
# Test that we only receive getblocktxn requests for transactions that the
# node needs, and that responding to them causes the block to be
# reconstructed.
def test_getblocktxn_requests(self, test_node):
version = test_node.cmpct_version
node = self.nodes[0]
with_witness = (version == 2)
def test_getblocktxn_response(compact_block, peer, expected_result):
msg = msg_cmpctblock(compact_block.to_p2p())
peer.send_and_ping(msg)
with mininode_lock:
assert "getblocktxn" in peer.last_message
absolute_indexes = peer.last_message["getblocktxn"].block_txn_request.to_absolute()
assert_equal(absolute_indexes, expected_result)
def test_tip_after_message(node, peer, msg, tip):
peer.send_and_ping(msg)
assert_equal(int(node.getbestblockhash(), 16), tip)
# First try announcing compactblocks that won't reconstruct, and verify
# that we receive getblocktxn messages back.
utxo = self.utxos.pop(0)
block = self.build_block_with_transactions(node, utxo, 5)
self.utxos.append([block.vtx[-1].sha256, 0, block.vtx[-1].vout[0].nValue])
comp_block = HeaderAndShortIDs()
comp_block.initialize_from_block(block, use_witness=with_witness)
test_getblocktxn_response(comp_block, test_node, [1, 2, 3, 4, 5])
msg_bt = msg_no_witness_blocktxn()
if with_witness:
msg_bt = msg_blocktxn() # serialize with witnesses
msg_bt.block_transactions = BlockTransactions(block.sha256, block.vtx[1:])
test_tip_after_message(node, test_node, msg_bt, block.sha256)
utxo = self.utxos.pop(0)
block = self.build_block_with_transactions(node, utxo, 5)
self.utxos.append([block.vtx[-1].sha256, 0, block.vtx[-1].vout[0].nValue])
# Now try interspersing the prefilled transactions
comp_block.initialize_from_block(block, prefill_list=[0, 1, 5], use_witness=with_witness)
test_getblocktxn_response(comp_block, test_node, [2, 3, 4])
msg_bt.block_transactions = BlockTransactions(block.sha256, block.vtx[2:5])
test_tip_after_message(node, test_node, msg_bt, block.sha256)
# Now try giving one transaction ahead of time.
utxo = self.utxos.pop(0)
block = self.build_block_with_transactions(node, utxo, 5)
self.utxos.append([block.vtx[-1].sha256, 0, block.vtx[-1].vout[0].nValue])
test_node.send_and_ping(msg_tx(block.vtx[1]))
assert block.vtx[1].hash in node.getrawmempool()
# Prefill 4 out of the 6 transactions, and verify that only the one
# that was not in the mempool is requested.
comp_block.initialize_from_block(block, prefill_list=[0, 2, 3, 4], use_witness=with_witness)
test_getblocktxn_response(comp_block, test_node, [5])
msg_bt.block_transactions = BlockTransactions(block.sha256, [block.vtx[5]])
test_tip_after_message(node, test_node, msg_bt, block.sha256)
# Now provide all transactions to the node before the block is
# announced and verify reconstruction happens immediately.
utxo = self.utxos.pop(0)
block = self.build_block_with_transactions(node, utxo, 10)
self.utxos.append([block.vtx[-1].sha256, 0, block.vtx[-1].vout[0].nValue])
for tx in block.vtx[1:]:
test_node.send_message(msg_tx(tx))
test_node.sync_with_ping()
# Make sure all transactions were accepted.
mempool = node.getrawmempool()
for tx in block.vtx[1:]:
assert tx.hash in mempool
# Clear out last request.
with mininode_lock:
test_node.last_message.pop("getblocktxn", None)
# Send compact block
comp_block.initialize_from_block(block, prefill_list=[0], use_witness=with_witness)
test_tip_after_message(node, test_node, msg_cmpctblock(comp_block.to_p2p()), block.sha256)
with mininode_lock:
# Shouldn't have gotten a request for any transaction
assert "getblocktxn" not in test_node.last_message
# Incorrectly responding to a getblocktxn shouldn't cause the block to be
# permanently failed.
def test_incorrect_blocktxn_response(self, test_node):
version = test_node.cmpct_version
node = self.nodes[0]
utxo = self.utxos.pop(0)
block = self.build_block_with_transactions(node, utxo, 10)
self.utxos.append([block.vtx[-1].sha256, 0, block.vtx[-1].vout[0].nValue])
# Relay the first 5 transactions from the block in advance
for tx in block.vtx[1:6]:
test_node.send_message(msg_tx(tx))
test_node.sync_with_ping()
# Make sure all transactions were accepted.
mempool = node.getrawmempool()
for tx in block.vtx[1:6]:
assert tx.hash in mempool
# Send compact block
comp_block = HeaderAndShortIDs()
comp_block.initialize_from_block(block, prefill_list=[0], use_witness=(version == 2))
test_node.send_and_ping(msg_cmpctblock(comp_block.to_p2p()))
absolute_indexes = []
with mininode_lock:
assert "getblocktxn" in test_node.last_message
absolute_indexes = test_node.last_message["getblocktxn"].block_txn_request.to_absolute()
assert_equal(absolute_indexes, [6, 7, 8, 9, 10])
# Now give an incorrect response.
# Note that it's possible for bitcoind to be smart enough to know we're
# lying, since it could check to see if the shortid matches what we're
# sending, and eg disconnect us for misbehavior. If that behavior
# change was made, we could just modify this test by having a
# different peer provide the block further down, so that we're still
# verifying that the block isn't marked bad permanently. This is good
# enough for now.
msg = msg_no_witness_blocktxn()
if version == 2:
msg = msg_blocktxn()
msg.block_transactions = BlockTransactions(block.sha256, [block.vtx[5]] + block.vtx[7:])
test_node.send_and_ping(msg)
# Tip should not have updated
assert_equal(int(node.getbestblockhash(), 16), block.hashPrevBlock)
# We should receive a getdata request
wait_until(lambda: "getdata" in test_node.last_message, timeout=10, lock=mininode_lock)
assert_equal(len(test_node.last_message["getdata"].inv), 1)
assert test_node.last_message["getdata"].inv[0].type == 2 or test_node.last_message["getdata"].inv[0].type == 2 | MSG_WITNESS_FLAG
assert_equal(test_node.last_message["getdata"].inv[0].hash, block.sha256)
# Deliver the block
if version == 2:
test_node.send_and_ping(msg_block(block))
else:
test_node.send_and_ping(msg_no_witness_block(block))
assert_equal(int(node.getbestblockhash(), 16), block.sha256)
def test_getblocktxn_handler(self, test_node):
version = test_node.cmpct_version
node = self.nodes[0]
# bitcoind will not send blocktxn responses for blocks whose height is
# more than 10 blocks deep.
MAX_GETBLOCKTXN_DEPTH = 10
chain_height = node.getblockcount()
current_height = chain_height
while (current_height >= chain_height - MAX_GETBLOCKTXN_DEPTH):
block_hash = node.getblockhash(current_height)
block = FromHex(CBlock(), node.getblock(block_hash, False))
msg = msg_getblocktxn()
msg.block_txn_request = BlockTransactionsRequest(int(block_hash, 16), [])
num_to_request = random.randint(1, len(block.vtx))
msg.block_txn_request.from_absolute(sorted(random.sample(range(len(block.vtx)), num_to_request)))
test_node.send_message(msg)
wait_until(lambda: "blocktxn" in test_node.last_message, timeout=10, lock=mininode_lock)
[tx.calc_sha256() for tx in block.vtx]
with mininode_lock:
assert_equal(test_node.last_message["blocktxn"].block_transactions.blockhash, int(block_hash, 16))
all_indices = msg.block_txn_request.to_absolute()
for index in all_indices:
tx = test_node.last_message["blocktxn"].block_transactions.transactions.pop(0)
tx.calc_sha256()
assert_equal(tx.sha256, block.vtx[index].sha256)
if version == 1:
# Witnesses should have been stripped
assert tx.wit.is_null()
else:
# Check that the witness matches
assert_equal(tx.calc_sha256(True), block.vtx[index].calc_sha256(True))
test_node.last_message.pop("blocktxn", None)
current_height -= 1
# Next request should send a full block response, as we're past the
# allowed depth for a blocktxn response.
block_hash = node.getblockhash(current_height)
msg.block_txn_request = BlockTransactionsRequest(int(block_hash, 16), [0])
with mininode_lock:
test_node.last_message.pop("block", None)
test_node.last_message.pop("blocktxn", None)
test_node.send_and_ping(msg)
with mininode_lock:
test_node.last_message["block"].block.calc_sha256()
assert_equal(test_node.last_message["block"].block.sha256, int(block_hash, 16))
assert "blocktxn" not in test_node.last_message
def test_compactblocks_not_at_tip(self, test_node):
node = self.nodes[0]
# Test that requesting old compactblocks doesn't work.
MAX_CMPCTBLOCK_DEPTH = 5
new_blocks = []
for i in range(MAX_CMPCTBLOCK_DEPTH + 1):
test_node.clear_block_announcement()
new_blocks.append(node.generate(1)[0])
wait_until(test_node.received_block_announcement, timeout=30, lock=mininode_lock)
test_node.clear_block_announcement()
test_node.send_message(msg_getdata([CInv(4, int(new_blocks[0], 16))]))
wait_until(lambda: "cmpctblock" in test_node.last_message, timeout=30, lock=mininode_lock)
test_node.clear_block_announcement()
node.generate(1)
wait_until(test_node.received_block_announcement, timeout=30, lock=mininode_lock)
test_node.clear_block_announcement()
with mininode_lock:
test_node.last_message.pop("block", None)
test_node.send_message(msg_getdata([CInv(4, int(new_blocks[0], 16))]))
wait_until(lambda: "block" in test_node.last_message, timeout=30, lock=mininode_lock)
with mininode_lock:
test_node.last_message["block"].block.calc_sha256()
assert_equal(test_node.last_message["block"].block.sha256, int(new_blocks[0], 16))
# Generate an old compactblock, and verify that it's not accepted.
cur_height = node.getblockcount()
hashPrevBlock = int(node.getblockhash(cur_height - 5), 16)
block = self.build_block_on_tip(node)
block.hashPrevBlock = hashPrevBlock
block.solve()
comp_block = HeaderAndShortIDs()
comp_block.initialize_from_block(block)
test_node.send_and_ping(msg_cmpctblock(comp_block.to_p2p()))
tips = node.getchaintips()
found = False
for x in tips:
if x["hash"] == block.hash:
assert_equal(x["status"], "headers-only")
found = True
break
assert found
# Requesting this block via getblocktxn should silently fail
# (to avoid fingerprinting attacks).
msg = msg_getblocktxn()
msg.block_txn_request = BlockTransactionsRequest(block.sha256, [0])
with mininode_lock:
test_node.last_message.pop("blocktxn", None)
test_node.send_and_ping(msg)
with mininode_lock:
assert "blocktxn" not in test_node.last_message
def test_end_to_end_block_relay(self, listeners):
node = self.nodes[0]
utxo = self.utxos.pop(0)
block = self.build_block_with_transactions(node, utxo, 10)
[l.clear_block_announcement() for l in listeners]
# ToHex() won't serialize with witness, but this block has no witnesses
# anyway. TODO: repeat this test with witness tx's to a segwit node.
node.submitblock(ToHex(block))
for l in listeners:
wait_until(lambda: l.received_block_announcement(), timeout=30, lock=mininode_lock)
with mininode_lock:
for l in listeners:
assert "cmpctblock" in l.last_message
l.last_message["cmpctblock"].header_and_shortids.header.calc_sha256()
assert_equal(l.last_message["cmpctblock"].header_and_shortids.header.sha256, block.sha256)
# Test that we don't get disconnected if we relay a compact block with valid header,
# but invalid transactions.
def test_invalid_tx_in_compactblock(self, test_node, use_segwit=True):
node = self.nodes[0]
assert len(self.utxos)
utxo = self.utxos[0]
block = self.build_block_with_transactions(node, utxo, 5)
del block.vtx[3]
block.hashMerkleRoot = block.calc_merkle_root()
if use_segwit:
# If we're testing with segwit, also drop the coinbase witness,
# but include the witness commitment.
add_witness_commitment(block)
block.vtx[0].wit.vtxinwit = []
block.solve()
# Now send the compact block with all transactions prefilled, and
# verify that we don't get disconnected.
comp_block = HeaderAndShortIDs()
comp_block.initialize_from_block(block, prefill_list=[0, 1, 2, 3, 4], use_witness=use_segwit)
msg = msg_cmpctblock(comp_block.to_p2p())
test_node.send_and_ping(msg)
# Check that the tip didn't advance
assert int(node.getbestblockhash(), 16) is not block.sha256
test_node.sync_with_ping()
# Helper for enabling cb announcements
# Send the sendcmpct request and sync headers
def request_cb_announcements(self, peer):
node = self.nodes[0]
tip = node.getbestblockhash()
peer.get_headers(locator=[int(tip, 16)], hashstop=0)
msg = msg_sendcmpct()
msg.version = peer.cmpct_version
msg.announce = True
peer.send_and_ping(msg)
def test_compactblock_reconstruction_multiple_peers(self, stalling_peer, delivery_peer):
node = self.nodes[0]
assert len(self.utxos)
def announce_cmpct_block(node, peer):
utxo = self.utxos.pop(0)
block = self.build_block_with_transactions(node, utxo, 5)
cmpct_block = HeaderAndShortIDs()
cmpct_block.initialize_from_block(block)
msg = msg_cmpctblock(cmpct_block.to_p2p())
peer.send_and_ping(msg)
with mininode_lock:
assert "getblocktxn" in peer.last_message
return block, cmpct_block
block, cmpct_block = announce_cmpct_block(node, stalling_peer)
for tx in block.vtx[1:]:
delivery_peer.send_message(msg_tx(tx))
delivery_peer.sync_with_ping()
mempool = node.getrawmempool()
for tx in block.vtx[1:]:
assert tx.hash in mempool
delivery_peer.send_and_ping(msg_cmpctblock(cmpct_block.to_p2p()))
assert_equal(int(node.getbestblockhash(), 16), block.sha256)
self.utxos.append([block.vtx[-1].sha256, 0, block.vtx[-1].vout[0].nValue])
# Now test that delivering an invalid compact block won't break relay
block, cmpct_block = announce_cmpct_block(node, stalling_peer)
for tx in block.vtx[1:]:
delivery_peer.send_message(msg_tx(tx))
delivery_peer.sync_with_ping()
cmpct_block.prefilled_txn[0].tx.wit.vtxinwit = [CTxInWitness()]
cmpct_block.prefilled_txn[0].tx.wit.vtxinwit[0].scriptWitness.stack = [ser_uint256(0)]
cmpct_block.use_witness = True
delivery_peer.send_and_ping(msg_cmpctblock(cmpct_block.to_p2p()))
assert int(node.getbestblockhash(), 16) != block.sha256
msg = msg_no_witness_blocktxn()
msg.block_transactions.blockhash = block.sha256
msg.block_transactions.transactions = block.vtx[1:]
stalling_peer.send_and_ping(msg)
assert_equal(int(node.getbestblockhash(), 16), block.sha256)
def run_test(self):
# Setup the p2p connections
self.segwit_node = self.nodes[0].add_p2p_connection(TestP2PConn(cmpct_version=2))
self.old_node = self.nodes[0].add_p2p_connection(TestP2PConn(cmpct_version=1), services=NODE_NETWORK)
self.additional_segwit_node = self.nodes[0].add_p2p_connection(TestP2PConn(cmpct_version=2))
# We will need UTXOs to construct transactions in later tests.
self.make_utxos()
assert softfork_active(self.nodes[0], "segwit")
self.log.info("Testing SENDCMPCT p2p message... ")
self.test_sendcmpct(self.segwit_node, old_node=self.old_node)
self.test_sendcmpct(self.additional_segwit_node)
self.log.info("Testing compactblock construction...")
self.test_compactblock_construction(self.old_node)
self.test_compactblock_construction(self.segwit_node)
self.log.info("Testing compactblock requests (segwit node)... ")
self.test_compactblock_requests(self.segwit_node)
self.log.info("Testing getblocktxn requests (segwit node)...")
self.test_getblocktxn_requests(self.segwit_node)
self.log.info("Testing getblocktxn handler (segwit node should return witnesses)...")
self.test_getblocktxn_handler(self.segwit_node)
self.test_getblocktxn_handler(self.old_node)
self.log.info("Testing compactblock requests/announcements not at chain tip...")
self.test_compactblocks_not_at_tip(self.segwit_node)
self.test_compactblocks_not_at_tip(self.old_node)
self.log.info("Testing handling of incorrect blocktxn responses...")
self.test_incorrect_blocktxn_response(self.segwit_node)
self.log.info("Testing reconstructing compact blocks from all peers...")
self.test_compactblock_reconstruction_multiple_peers(self.segwit_node, self.additional_segwit_node)
# Test that if we submitblock to node1, we'll get a compact block
# announcement to all peers.
# (Post-segwit activation, blocks won't propagate from node0 to node1
# automatically, so don't bother testing a block announced to node0.)
self.log.info("Testing end-to-end block relay...")
self.request_cb_announcements(self.old_node)
self.request_cb_announcements(self.segwit_node)
self.test_end_to_end_block_relay([self.segwit_node, self.old_node])
self.log.info("Testing handling of invalid compact blocks...")
self.test_invalid_tx_in_compactblock(self.segwit_node)
self.test_invalid_tx_in_compactblock(self.old_node)
self.log.info("Testing invalid index in cmpctblock message...")
self.test_invalid_cmpctblock_message()
if __name__ == '__main__':
CompactBlocksTest().main()
| test/functional/p2p_compactblocks.py | 39,816 | Sends a message to the node and wait for disconnect.
This is used when we want to send a message into the node that we expect
will get us disconnected, eg an invalid block.
Test compact blocks (BIP 152).
Version 1 compact blocks are pre-segwit (txids)
Version 2 compact blocks are post-segwit (wtxids)
!/usr/bin/env python3 Copyright (c) 2016-2019 The Bitcoin Core developers Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. TestP2PConn: A peer we use to send messages to bitcoind, and store responses. Store the hashes of blocks we've seen announced. This is for synchronizing the p2p message traffic, so we can eg wait until a particular block is announced. Requires caller to hold mininode_lock Block until a block announcement for a particular block hash is received. Create 10 more anyone-can-spend utxo's for testing. Test "sendcmpct" (between peers preferring the same version): - No compact block announcements unless sendcmpct is sent. - If sendcmpct is sent with version > preferred_version, the message is ignored. - If sendcmpct is sent with boolean 0, then block announcements are not made with compact blocks. - If sendcmpct is then sent with boolean 1, then new block announcements are made with compact blocks. If old_node is passed in, request compact blocks with version=preferred-1 and verify that it receives block announcements via compact block. Make sure we get a SENDCMPCT message from our peer Check that the first version received is the preferred one And that we receive versions down to 1. We shouldn't get any block announcements via cmpctblock yet. Try one more time, this time after requesting headers. Test a few ways of using sendcmpct that should NOT result in compact block announcements. Before each test, sync the headers chain. Now try a SENDCMPCT message with too-high version Headers sync before next test. Now try a SENDCMPCT message with valid version, but announce=False Headers sync before next test. Finally, try a SENDCMPCT message with announce=True Try one more time (no headers sync should be needed!) Try one more time, after turning on sendheaders Try one more time, after sending a version-1, announce=false message. Now turn off announcements Verify that a peer using an older protocol version can receive announcements from this node. Header sync This test actually causes bitcoind to (reasonably!) disconnect us, so do this last. This index will be too high Compare the generated shortids to what we expect based on BIP 152, given bitcoind's choice of nonce. Generate a bunch of transactions. check that our test is not broken Wait until we've seen the block announcement for the resulting tip Make sure we will receive a fast-announce compact block Now mine a block, and look at the resulting compact block. Store the raw block in our internal format. Wait until the block was announced (via compact blocks) Now fetch and check the compact block Convert the on-the-wire representation to absolute indexes Now fetch the compact block using a normal non-announce getdata 4 == "CompactBlock" Now fetch and check the compact block Convert the on-the-wire representation to absolute indexes Check that we got the right block! Make sure the prefilled_txn appears to have included the coinbase Check that all prefilled_txn entries match what's in the block. This checks the non-witness parts of the tx agree And this checks the witness Shouldn't have received a witness Check that the cmpctblock message announced all the transactions. And now check that all the shortids are as expected as well. Determine the siphash keys to use. Already checked prefilled transactions above Test that bitcoind requests compact blocks when we announce new blocks via header or inv, and that responding to getblocktxn causes the block to be successfully reconstructed. Post-segwit: upgraded nodes would only make this request of cb-version-2, NODE_WITNESS peers. Unupgraded nodes would still make this request of any cb-version-1-supporting peer. Try announcing a block with an inv or header, expect a compactblock request Send back a compactblock message that omits the coinbase Expect a getblocktxn message. should be a coinbase request Send the coinbase, and verify that the tip advances. Create a chain of transactions from given utxo, and add to a new block. Test that we only receive getblocktxn requests for transactions that the node needs, and that responding to them causes the block to be reconstructed. First try announcing compactblocks that won't reconstruct, and verify that we receive getblocktxn messages back. serialize with witnesses Now try interspersing the prefilled transactions Now try giving one transaction ahead of time. Prefill 4 out of the 6 transactions, and verify that only the one that was not in the mempool is requested. Now provide all transactions to the node before the block is announced and verify reconstruction happens immediately. Make sure all transactions were accepted. Clear out last request. Send compact block Shouldn't have gotten a request for any transaction Incorrectly responding to a getblocktxn shouldn't cause the block to be permanently failed. Relay the first 5 transactions from the block in advance Make sure all transactions were accepted. Send compact block Now give an incorrect response. Note that it's possible for bitcoind to be smart enough to know we're lying, since it could check to see if the shortid matches what we're sending, and eg disconnect us for misbehavior. If that behavior change was made, we could just modify this test by having a different peer provide the block further down, so that we're still verifying that the block isn't marked bad permanently. This is good enough for now. Tip should not have updated We should receive a getdata request Deliver the block bitcoind will not send blocktxn responses for blocks whose height is more than 10 blocks deep. Witnesses should have been stripped Check that the witness matches Next request should send a full block response, as we're past the allowed depth for a blocktxn response. Test that requesting old compactblocks doesn't work. Generate an old compactblock, and verify that it's not accepted. Requesting this block via getblocktxn should silently fail (to avoid fingerprinting attacks). ToHex() won't serialize with witness, but this block has no witnesses anyway. TODO: repeat this test with witness tx's to a segwit node. Test that we don't get disconnected if we relay a compact block with valid header, but invalid transactions. If we're testing with segwit, also drop the coinbase witness, but include the witness commitment. Now send the compact block with all transactions prefilled, and verify that we don't get disconnected. Check that the tip didn't advance Helper for enabling cb announcements Send the sendcmpct request and sync headers Now test that delivering an invalid compact block won't break relay Setup the p2p connections We will need UTXOs to construct transactions in later tests. Test that if we submitblock to node1, we'll get a compact block announcement to all peers. (Post-segwit activation, blocks won't propagate from node0 to node1 automatically, so don't bother testing a block announced to node0.) | 7,297 | en | 0.911786 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.