text string | size int64 | token_count int64 |
|---|---|---|
"""Read database information from Django models and create a HTML table for the
documentation.
"""
import collections
import os
import sys
import django
from loguru import logger
DOCS_DIR = os.path.dirname(os.path.abspath(__file__))
BASE_DIR = os.path.dirname(DOCS_DIR)
sys.path.insert(0, BASE_DIR)
os.environ["DJANGO_SETTINGS_MODULE"] = "app.settings"
django.setup()
from django_extensions.management.modelviz import generate_graph_data # noqa: E402
from database_tables_config import ( # noqa: E402
APP_LABELS,
HTML_TOP,
HTML_BOTTOM,
FILENAME,
)
def tabulate(head, rows, head_classes=None, row_classes=None):
head_classes = head_classes or {}
row_classes = row_classes or {}
th = []
for i, item in enumerate(head):
attrs = []
if i in head_classes:
attrs.append(f'class="{head_classes[i]}"')
th.append(f"<th{' ' if attrs else ''}{' '.join(attrs)}>{item}</th>")
tr = []
for row in rows:
td = []
for i, item in enumerate(row):
attrs = []
if i in row_classes:
attrs.append(f'class="{row_classes[i]}"')
td.append(f"<td{' ' if attrs else ''}{' '.join(attrs)}>{item}</td>")
tr.append(f"<tr>{' '.join(td)}</tr>")
head_html = f"<thead><tr>{' '.join(th)}</tr></thead>"
body_html = "<tbody>" + "\n".join(tr) + "</tbody>"
return f"<table>{head_html}\n{body_html}</table>"
def build_html( # noqa: C901
app_labels: list = APP_LABELS,
html_top: str = HTML_TOP,
html_bottom: str = HTML_BOTTOM,
) -> str:
"""Create an HTML page with a series of html tables for each table in the database.
Args:
app_labels (list): List of Django apps to include in HTML page. Defaults to APP_LABELS.
html_top (str): HTML code to insert above generated table. Defaults to HTML_TOP.
html_bottom (str): HTML code to insert below generated table. Defaults to HTML_BOTTOM.
Returns:
str: HTML page.
"""
# generate a dict with the table names as keys
output_table_dict = {}
for label in app_labels:
# read basic data with django_extensions.management.modelviz
data = generate_graph_data([label])
for db_table in data["graphs"][0]["models"]:
# generate data for each table (include help_text if present, if not use verbose_name)
table_fields = []
for field in db_table["fields"]:
if field["help_text"]:
description = field["help_text"]
else:
description = field["verbose_name"]
data_type = f'<code>{field["db_type"]}</code>'
if field["relation"]:
field_type = field["internal_type"]
field_type = field_type.replace("ForeignKey", "FK")
data_type = f"{data_type} (<b>{field_type}</b>)"
# elif field["type"] == "AutoField":
# data_type = f'{data_type}<br/><b>{field["type"]}</b>'
nullable = "✅" if field["null"] else "❌"
unique = "✅" if field["unique"] else "❌"
table_fields.append(
[
f"<code>{field['column_name']}</code>",
data_type,
unique,
nullable,
description,
]
)
# only include tables that are stored in db
if (
db_table["fields"][0]["name"] == "id"
and db_table["fields"][0]["type"] == "AutoField"
):
# create table info text from docstring
docstring_html = db_table["docstring"].replace("\n\n", "<br />\n")
info_text = f"<p>{docstring_html}</p>"
# if table uses foreign keys: create a list of foreign keys with links
if db_table["relations"]:
relation_text = ""
for relation in db_table["relations"]:
if relation["type"] == "ForeignKey":
relation_text += f'<li><a href="#{relation["target"]}"><code>{relation["target_table_name"]}</code></a> via <code>{relation["column_name"]}</code></li>'
# elif relation["type"] == "ManyToManyField":
# relation_text += f'<li><code>{relation["column_name"]}</code> aus der Tabelle <a href="#{relation["target"]}">{relation["target_table_name"]}</a> (ManyToMany)</li>'
if relation_text:
if db_table["is_m2m_table"]:
info_text += "<p>Sie verbindet die folgenden Tabellen:</p>"
else:
info_text += "<p>Diese Tabelle hat folgende Relationen zu anderen Tabellen:</p>"
info_text += "<ul>"
info_text += relation_text
info_text += "</ul>"
if db_table["unique_together"]:
info_text += "Für die Tabelle sind die folgenden <code>UNIQUE</code> Constraints definiert: <ul>"
for tup in db_table["unique_together"]:
info_text += f"<li>{', '.join(f'<code>{field}</code>' for field in tup)}</li>"
info_text += "</ul>"
# combine table name, table info text, table fields, and Django model name
output_table_dict[db_table["db_table_name"]] = [
info_text,
table_fields,
db_table["name"],
]
# sort dict of database tables alphabetically
output_sorted = collections.OrderedDict(sorted(output_table_dict.items()))
# collect HTML items in a string
html_tables = ""
for table_name, table_infos in output_sorted.items():
# convert output table to HTML
html_tables += f"<a name='{table_infos[2]}'></a>" # For backwards compatibility
html_tables += (
f"<h3><a name='{table_name}' href='#{table_name}'>{table_name}</a></h3>"
+ f"<div class='docstring'>{table_infos[0]}</div>"
+ "\n"
+ tabulate(
["Name", "Type", "UNIQUE", "NULL", "Beschreibung"],
table_infos[1],
head_classes={2: "mono", 3: "mono"},
row_classes={2: "hcenter vcenter", 3: "hcenter vcenter"},
)
+ "\n"
)
return str(html_top + html_tables + html_bottom)
if __name__ == "__main__":
# generate html page (based on constants from database_tables_config)
html_page = build_html(APP_LABELS, HTML_TOP, HTML_BOTTOM)
# write output to file
filepath = os.path.join(DOCS_DIR, FILENAME)
with open(filepath, "wt") as output_file:
output_file.write(html_page)
logger.success("Data written to {}", filepath)
| 7,009 | 2,086 |
"""
Django settings for LibraryManagementSystem project.
Generated by 'django-admin startproject' using Django 3.2.9.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
import os
from pathlib import Path
from decouple import config
# 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.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config('DEBUG', cast=bool)
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# My App
'library.apps.LibraryConfig',
# Form widget tweaks
'widget_tweaks',
# Django Social loigin
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.google',
# RESTFull API
'rest_framework',
'rest_framework_simplejwt'
]
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',
]
# Added for Google auth
SITE_ID = 2
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
ROOT_URLCONF = 'LibraryManagementSystem.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, 'templates', 'accounts')],
'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',
],
},
},
]
LOGIN_REDIRECT_URL = '/dashboard'
WSGI_APPLICATION = 'LibraryManagementSystem.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': config("DATABASE_NAME"),
'USER': config("DATABASE_USER"),
'PASSWORD': config("DATABASE_PASSWORD"),
'HOST': config("DATABASE_HOST"),
'PORT': config("DATABASE_PORT", cast=int),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/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.2/topics/i18n/
LANGUAGE_CODE = 'en-in'
TIME_ZONE = 'Asia/Kolkata'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# added manually
STATICFILES_DIRS = [
BASE_DIR / "static",
]
AUTH_USER_MODEL = 'library.User'
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend',
]
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = config('EMAIL_HOST')
EMAIL_USE_TLS = config('EMAIL_USE_TLS', cast=bool)
EMAIL_PORT = config('EMAIL_PORT', cast=int)
EMAIL_HOST_USER = config('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD')
SOCIALACCOUNT_PROVIDERS = {
'google': {
'SCOPE': [
'profile',
'email',
],
'AUTH_PARAMS': {
'access_type': 'online',
}
},
}
SESSION_COOKIE_AGE = 1000
SESSION_SAVE_EVERY_REQUEST = False
ACCOUNT_LOGOUT_ON_PASSWORD_CHANGE = True
# django-allauth registraion settings
ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 1
ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 5
# 1 day
ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = 86400
# or any other page
ACCOUNT_LOGOUT_REDIRECT_URL = '/accounts/login/'
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
],
'DEFAULT_RENDERER_CLASSES': [
'rest_framework.renderers.JSONRenderer'
],
} | 5,454 | 1,890 |
import json
import logging
import os
import sys
import threading
import time
import paho.mqtt.client as paho
import paho.mqtt.publish as paho_publish
from baseline_device.util.config import config
from baseline_device.util.mqtt import MqttLoggingHandler
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__file__)
client_id = os.environ['BASELINE_CLIENT_ID']
program = 'sample2'
connected = threading.Event()
def on_connect(client: paho.Client, userdata: dict, flags: dict, rc: int) -> None:
# The value of rc determines success or not:
# 0: Connection successful
# 1: Connection refused - incorrect protocol version
# 2: Connection refused - invalid client identifier
# 3: Connection refused - server unavailable
# 4: Connection refused - bad username or password
# 5: Connection refused - not authorised
# 6-255: Currently unused.
if rc == 0: connected.set()
client = None
job_id = None
try:
with open(f'/tmp/{config.app_name}/jobs/{program}', 'r') as f:
execution = json.load(f)
job_id = execution['jobId']
client = paho.Client(clean_session=True)
client.on_connect = on_connect
client.enable_logger(logger)
logger.addHandler(MqttLoggingHandler(client, f'$aws/rules/{config.topic_prefix}/things/{client_id}/log'))
client.connect_async('localhost')
client.loop_start()
while not connected.is_set():
time.sleep(1)
logger.info('Job started!')
time.sleep(30)
logger.info('Job complete!')
client.publish(f'$aws/things/{client_id}/jobs/{job_id}/update', qos=2, payload=json.dumps({
'status': 'SUCCEEDED',
'expectedVersion': execution['versionNumber'],
'executionNumber': execution['executionNumber']
}))
sys.exit(0)
except SystemExit as e:
raise e
except:
logger.critical('Fatal shutdown...', exc_info=True)
if job_id:
try:
client_publish = client.publish if client.is_connected() else paho_publish.single
client_publish(f'$aws/things/{client_id}/jobs/{job_id}/update', qos=2, payload=json.dumps({
'status': 'FAILED',
'expectedVersion': execution['versionNumber'],
'executionNumber': execution['executionNumber']
}))
except:
logger.warning('Unable to send job status as FAILED', exc_info=True)
sys.exit(1)
finally:
if client:
client.loop_stop()
client.disconnect()
| 2,497 | 782 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests import Form
from odoo.tests.common import TransactionCase
class TestOnchangeProductId(TransactionCase):
"""Test that when an included tax is mapped by a fiscal position, the included tax must be
subtracted to the price of the product.
"""
def setUp(self):
super(TestOnchangeProductId, self).setUp()
self.fiscal_position_model = self.env['account.fiscal.position']
self.fiscal_position_tax_model = self.env['account.fiscal.position.tax']
self.tax_model = self.env['account.tax']
self.so_model = self.env['sale.order']
self.po_line_model = self.env['sale.order.line']
self.res_partner_model = self.env['res.partner']
self.product_tmpl_model = self.env['product.template']
self.product_model = self.env['product.product']
self.product_uom_model = self.env['uom.uom']
self.supplierinfo_model = self.env["product.supplierinfo"]
self.pricelist_model = self.env['product.pricelist']
def test_onchange_product_id(self):
uom_id = self.product_uom_model.search([('name', '=', 'Units')])[0]
pricelist = self.pricelist_model.search([('name', '=', 'Public Pricelist')])[0]
partner_id = self.res_partner_model.create(dict(name="George"))
tax_include_id = self.tax_model.create(dict(name="Include tax",
amount='21.00',
price_include=True,
type_tax_use='sale'))
tax_exclude_id = self.tax_model.create(dict(name="Exclude tax",
amount='0.00',
type_tax_use='sale'))
product_tmpl_id = self.product_tmpl_model.create(dict(name="Voiture",
list_price=121,
taxes_id=[(6, 0, [tax_include_id.id])]))
product_id = product_tmpl_id.product_variant_id
fp_id = self.fiscal_position_model.create(dict(name="fiscal position", sequence=1))
fp_tax_id = self.fiscal_position_tax_model.create(dict(position_id=fp_id.id,
tax_src_id=tax_include_id.id,
tax_dest_id=tax_exclude_id.id))
# Create the SO with one SO line and apply a pricelist and fiscal position on it
order_form = Form(self.env['sale.order'].with_context(tracking_disable=True))
order_form.partner_id = partner_id
order_form.pricelist_id = pricelist
order_form.fiscal_position_id = fp_id
with order_form.order_line.new() as line:
line.name = product_id.name
line.product_id = product_id
line.product_uom_qty = 1.0
line.product_uom = uom_id
sale_order = order_form.save()
# Check the unit price of SO line
self.assertEquals(100, sale_order.order_line[0].price_unit, "The included tax must be subtracted to the price")
def test_pricelist_application(self):
""" Test different prices are correctly applied based on dates """
support_product = self.env.ref('product.product_product_2')
support_product.list_price = 100
partner = self.res_partner_model.create(dict(name="George"))
christmas_pricelist = self.env['product.pricelist'].create({
'name': 'Christmas pricelist',
'item_ids': [(0, 0, {
'date_start': "2017-12-01",
'date_end': "2017-12-24",
'compute_price': 'percentage',
'base': 'list_price',
'percent_price': 20,
'applied_on': '3_global',
'name': 'Pre-Christmas discount'
}), (0, 0, {
'date_start': "2017-12-25",
'date_end': "2017-12-31",
'compute_price': 'percentage',
'base': 'list_price',
'percent_price': 50,
'applied_on': '3_global',
'name': 'Post-Christmas super-discount'
})]
})
# Create the SO with pricelist based on date
order_form = Form(self.env['sale.order'].with_context(tracking_disable=True))
order_form.partner_id = partner
order_form.date_order = '2017-12-20'
order_form.pricelist_id = christmas_pricelist
with order_form.order_line.new() as line:
line.product_id = support_product
so = order_form.save()
# Check the unit price and subtotal of SO line
self.assertEqual(so.order_line[0].price_unit, 80, "First date pricelist rule not applied")
self.assertEquals(so.order_line[0].price_subtotal, so.order_line[0].price_unit * so.order_line[0].product_uom_qty, 'Total of SO line should be a multiplication of unit price and ordered quantity')
# Change order date of the SO and check the unit price and subtotal of SO line
with Form(so) as order:
order.date_order = '2017-12-30'
with order.order_line.edit(0) as line:
line.product_id = support_product
self.assertEqual(so.order_line[0].price_unit, 50, "Second date pricelist rule not applied")
self.assertEquals(so.order_line[0].price_subtotal, so.order_line[0].price_unit * so.order_line[0].product_uom_qty, 'Total of SO line should be a multiplication of unit price and ordered quantity')
def test_pricelist_uom_discount(self):
""" Test prices and discounts are correctly applied based on date and uom"""
computer_case = self.env.ref('product.product_product_16')
computer_case.list_price = 100
partner = self.res_partner_model.create(dict(name="George"))
categ_unit_id = self.ref('uom.product_uom_categ_unit')
goup_discount_id = self.ref('product.group_discount_per_so_line')
self.env.user.write({'groups_id': [(4, goup_discount_id, 0)]})
new_uom = self.env['uom.uom'].create({
'name': '10 units',
'factor_inv': 10,
'uom_type': 'bigger',
'rounding': 1.0,
'category_id': categ_unit_id
})
christmas_pricelist = self.env['product.pricelist'].create({
'name': 'Christmas pricelist',
'discount_policy': 'without_discount',
'item_ids': [(0, 0, {
'date_start': "2017-12-01",
'date_end': "2017-12-30",
'compute_price': 'percentage',
'base': 'list_price',
'percent_price': 10,
'applied_on': '3_global',
'name': 'Christmas discount'
})]
})
so = self.env['sale.order'].create({
'partner_id': partner.id,
'date_order': '2017-12-20',
'pricelist_id': christmas_pricelist.id,
})
order_line = self.env['sale.order.line'].new({
'order_id': so.id,
'product_id': computer_case.id,
})
# force compute uom and prices
order_line.product_id_change()
order_line.product_uom_change()
order_line._onchange_discount()
self.assertEqual(order_line.price_subtotal, 90, "Christmas discount pricelist rule not applied")
self.assertEqual(order_line.discount, 10, "Christmas discount not equalt to 10%")
order_line.product_uom = new_uom
order_line.product_uom_change()
order_line._onchange_discount()
self.assertEqual(order_line.price_subtotal, 900, "Christmas discount pricelist rule not applied")
self.assertEqual(order_line.discount, 10, "Christmas discount not equalt to 10%")
def test_pricelist_based_on_other(self):
""" Test price and discount are correctly applied with a pricelist based on an other one"""
computer_case = self.env.ref('product.product_product_16')
computer_case.list_price = 100
partner = self.res_partner_model.create(dict(name="George"))
goup_discount_id = self.ref('product.group_discount_per_so_line')
self.env.user.write({'groups_id': [(4, goup_discount_id, 0)]})
first_pricelist = self.env['product.pricelist'].create({
'name': 'First pricelist',
'discount_policy': 'without_discount',
'item_ids': [(0, 0, {
'compute_price': 'percentage',
'base': 'list_price',
'percent_price': 10,
'applied_on': '3_global',
'name': 'First discount'
})]
})
second_pricelist = self.env['product.pricelist'].create({
'name': 'Second pricelist',
'discount_policy': 'without_discount',
'item_ids': [(0, 0, {
'compute_price': 'formula',
'base': 'pricelist',
'base_pricelist_id': first_pricelist.id,
'price_discount': 10,
'applied_on': '3_global',
'name': 'Second discount'
})]
})
so = self.env['sale.order'].create({
'partner_id': partner.id,
'date_order': '2018-07-11',
'pricelist_id': second_pricelist.id,
})
order_line = self.env['sale.order.line'].new({
'order_id': so.id,
'product_id': computer_case.id,
})
# force compute uom and prices
order_line.product_id_change()
order_line._onchange_discount()
self.assertEqual(order_line.price_subtotal, 81, "Second pricelist rule not applied")
self.assertEqual(order_line.discount, 19, "Second discount not applied")
def test_pricelist_with_other_currency(self):
""" Test prices are correctly applied with a pricelist with an other currency"""
computer_case = self.env.ref('product.product_product_16')
computer_case.list_price = 100
partner = self.res_partner_model.create(dict(name="George"))
categ_unit_id = self.ref('uom.product_uom_categ_unit')
other_currency = self.env['res.currency'].create({'name': 'other currency',
'symbol': 'other'})
self.env['res.currency.rate'].create({'name': '2018-07-11',
'rate': 2.0,
'currency_id': other_currency.id,
'company_id': self.env.company.id})
self.env['res.currency.rate'].search(
[('currency_id', '=', self.env.company.currency_id.id)]
).unlink()
new_uom = self.env['uom.uom'].create({
'name': '10 units',
'factor_inv': 10,
'uom_type': 'bigger',
'rounding': 1.0,
'category_id': categ_unit_id
})
# This pricelist doesn't show the discount
first_pricelist = self.env['product.pricelist'].create({
'name': 'First pricelist',
'currency_id': other_currency.id,
'discount_policy': 'with_discount',
'item_ids': [(0, 0, {
'compute_price': 'percentage',
'base': 'list_price',
'percent_price': 10,
'applied_on': '3_global',
'name': 'First discount'
})]
})
so = self.env['sale.order'].create({
'partner_id': partner.id,
'date_order': '2018-07-12',
'pricelist_id': first_pricelist.id,
})
order_line = self.env['sale.order.line'].new({
'order_id': so.id,
'product_id': computer_case.id,
})
# force compute uom and prices
order_line.product_id_change()
self.assertEqual(order_line.price_unit, 180, "First pricelist rule not applied")
order_line.product_uom = new_uom
order_line.product_uom_change()
self.assertEqual(order_line.price_unit, 1800, "First pricelist rule not applied")
| 12,183 | 3,882 |
from epics import caput
from IEX_29id.utils.exp import Check_run, BL_Mode_Set, BL_ioc
from IEX_29id.mda.file import MDA_CurrentDirectory
from IEX_29id.mda.file import MDA_CurrentRun
import os
import re
def Make_DataFolder(run,folder,UserName,scanIOC,ftp): #JM was here ->print full crontab command and change permissions on kip -still needs work!
"""
Creates the User Folder on the dserv
if ftp = True: creates the folders on kip (ftp server) and modifies the cronjob
"""
crontime={
'mda2ascii':'0,30 * * * * ',
'chmod':'1,31 * * * * ',
'data_other':'2,32 * * * * ',
'notebook':'*/3 * * * * ',
}
if (folder == 'c'or folder == 'd'):
if ftp:
print('-------------------------------------------------------------')
#mda2ascii
MyPath_kip_run='/net/kip/sftp/pub/29id'+folder+'ftp/files/'+run+'/'
MyPath_kip='/net/kip/sftp/pub/29id'+folder+'ftp/files/'+run+'/'+UserName+'/'
cmd_mda2ascii=crontime['mda2ascii']+' /net/s29dserv/APSshare/bin/mda2ascii -d '+MyPath_kip+'ascii '+MyPath_kip+'mda/*.mda'
print(cmd_mda2ascii)
#chmode
cmd_chmod=crontime['chmod']+' chmod 664 '+MyPath_kip+'ascii/*.asc'
print(cmd_chmod)
#notebooks
cmd_notebook=crontime['notebook']+' /usr/bin/rsync -av --exclude=core /home/beams22/29IDUSER/Documents/User_Folders/'+UserName+'/* kip:'+MyPath_kip+'notebook > /home/beams22/29ID/cronfiles/cptoftp-currrun-d-User.log 2>&1'
print(cmd_notebook)
print('-------------------------------------------------------------\n\n')
#making folders
print("\n\n")
print(MyPath_kip)
print(MyPath_kip+"ascii")
if not (os.path.exists(MyPath_kip_run)):
os.mkdir(MyPath_kip_run)
os.chmod(MyPath_kip_run, 0o775)
if not (os.path.exists(MyPath_kip)):
os.mkdir(MyPath_kip)
os.chmod(MyPath_kip, 0o775)
if not (os.path.exists(MyPath_kip+"ascii")):
os.mkdir(MyPath_kip+'ascii')
os.chmod(MyPath_kip+'ascii', 0o775)
if not (os.path.exists(MyPath_kip+"notebook")):
os.mkdir(MyPath_kip+"notebook")
os.chmod(MyPath_kip+"notebook", 0o775)
else:
print("To create ftp folders & update contrab, you need to run the following as 29id:")
print("\tFolder_"+str(scanIOC)+"('"+str(run)+"','"+str(UserName)+"',ftp=True)")
MyPath_File='/home/beams/29IDUSER/Documents/User_Folders/'+UserName
UserName = "/"+UserName
if not (os.path.exists(MyPath_File)):
os.mkdir(MyPath_File)
#if folder == 'd':
#MyPath_File_hkl='/home/beams/29IDUSER/Documents/User_Folders/'+UserName+'/hkl'
#if not(os.path.exists(MyPath_File_hkl)):
# os.mkdir(MyPath_File_hkl)
if folder == 'b':
UserName = ''
#MyPath_run='/net/s29data/export/data_29id'+folder+'/'+run
MyPath_run=os.path.dirname(_userDataFolder(UserName,scanIOC))
if not (os.path.exists(MyPath_run)):
os.mkdir(MyPath_run)
#MyPath_Data=MyPath_run+UserName
MyPath_Data=_userDataFolder(UserName,scanIOC)
if not (os.path.exists(MyPath_Data)):
os.mkdir(MyPath_Data)
def _userDataFolder(userName,scanIOC,**kwargs):
"""
Returns the path to a user folder
dataFolder='/net/s29data/export/data_29id'+folder+'/'+run+'/'+userName
kwargs:
run: Check_run(); unless specified
BLmode: Staff / User; based on userName unless specified
folder: determined by UserName and scanIOC
folder = b (Staff)
folder = c (User and ARPES)
folder = d (User and Kappa)
"""
kwargs.setdefault('run',Check_run())
folder=""
run=kwargs['run']
if userName == 'Staff':
folder="b"
if "BLmode" in kwargs:
BL_Mode_Set(kwargs["BLmode"])
else:
BL_Mode_Set("Staff")
else:
BL_Mode_Set("User")
if scanIOC=="ARPES":
folder="c"
if scanIOC=="Kappa":
folder="d"
dataFolder='/net/s29data/export/data_29id'+folder+'/'+run+'/'+userName
return dataFolder
def _filename_key(filename):
return (len(filename), filename)
def Folder_mda(run,folder,UserName,scanIOC):
"""
For Staff: folder='b', UserName='Staff'
For ARPES: folder ='c'
For Kappa or RSoXS: folder = 'd'
"""
FilePrefix=scanIOC
if UserName == 'Staff':
UserName=""
else:
UserName=UserName+"/"
MyPath="/net/s29data/export/data_29id"+folder+"/"+run+"/"+UserName+"mda"
print("\nMDA folder: " + MyPath)
if not (os.path.exists(MyPath)):
os.mkdir(MyPath)
FileNumber=1
else:
FileNumber=getNextFileNumber(MyPath,FilePrefix)
if scanIOC=="Test" or scanIOC=="Kappa" or scanIOC=="ARPES" or scanIOC=="RSoXS":
caput("29id"+scanIOC+":saveData_fileSystem","/net/s29data/export/data_29id"+folder+"/"+run)
os.sleep(0.25) #needed so that it has time to write
caput("29id"+scanIOC+":saveData_subDir","/"+UserName+"mda")
else:
caput("29id"+scanIOC+":saveData_fileSystem","//s29data/export/data_29id"+folder+"/"+run)
os.sleep(0.25)
caput("29id"+scanIOC+":saveData_subDir",UserName+"mda")
caput("29id"+scanIOC+":saveData_baseName",FilePrefix+"_")
caput("29id"+scanIOC+":saveData_scanNumber",FileNumber)
def getNextFileNumber(data_dir, file_prefix,**kwargs):
"""
gets the next file number for the pattern
data_dir/file_prefix_filenum
kwargs:
debug = False (default); if True then print lo
q = True (default); if False then prints next file number
"""
kwargs.setdefault("debug",False)
kwargs.setdefault("q",True)
onlyfiles = [f for f in os.listdir(data_dir) if os.isfile(os.join(data_dir, f)) and f[:len(file_prefix)] == file_prefix]
sortedfiles = sorted(onlyfiles, key=_filename_key)
pattern = re.compile('(.*)_(.*)\.(.*)')
try:
lastFile = sortedfiles[-1]
except IndexError as errObj:
nextFileNumber = 1
if kwargs["debug"]:
print("Data directory = ", data_dir)
print("File prefix =", file_prefix)
print("File number =", None)
print("File extension =", "TBD")
print("Next File number =", nextFileNumber)
else:
matchObj = pattern.match(lastFile)
nextFileNumber = int(matchObj.group(2)) + 1
if kwargs["debug"]:
print("Data directory = ", data_dir)
print("File prefix =", matchObj.group(1))
print("File number =", matchObj.group(2))
print("File extension =", matchObj.group(3))
print("Next File number =", nextFileNumber)
if kwargs["q"] == False:
print("Next File Number: ",nextFileNumber)
return nextFileNumber
def Check_Staff_Directory(**kwargs):
"""
Switchs to the staff directory
Uses Fold
"""
kwargs.setdefault("scanIOC",BL_ioc())
kwargs.setdefault("run",Check_run())
scanIOC=kwargs["scanIOC"]
run= kwargs["run"]
directory = MDA_CurrentDirectory(scanIOC)
current_run = MDA_CurrentRun(scanIOC)
if directory.find('data_29idb') < 1 or current_run != run:
print('You are not currently saving in the Staff directory and/or the desired run - REPLY "yes" to switch folder.\nThis will only work if the run directory already exists.\nOtherwise, you must open ipython as 29id to create a new run directory using:\n\tFolder_'+scanIOC+'(run,\'Staff\')')
foo=input('\nAre you ready to switch to the '+run+' Staff directory? >')
if foo == 'Y' or foo == 'y' or foo == 'yes'or foo == 'YES':
print('Switching directory...')
if scanIOC=='ARPES':
Folder_ARPES('Staff',mdaOnly=True,**kwargs)
elif scanIOC=='Kappa':
Folder_Kappa('Staff',create_only=False)
else:
print('\nFolder not set.')
else:
print('Staff directory OK.')
directory = MDA_CurrentDirectory(scanIOC)
print('\nCurrent directory: '+directory)
| 8,390 | 2,871 |
# -*- coding: utf-8 -*-
'''
Starts a Firfox headless brower to see if movies on your watchlist are playing
at any of your favorite theaters.
Favorite theaters are taken from a txt file (extracted from "theaters.txt").
These showtimes are compared to a watchlist (extracted from "watchlist.txt")
-samuel mignot-
'''
# ------------------- #
# imports #
# ------------------- #
import configparser
import os
from os import listdir
from os.path import isfile, join
# internal
import file_helpers
# ------------------- #
# constants #
# ------------------- #
THIS_DIRECTORY = os.path.abspath(os.path.dirname(__file__))
DATA_DIR = '/data'
WATCHLIST_DIR = '/watchlists'
OSCARS_WATCHLIST = 'oscar-winners-watchlist.txt'
ERROR_MESSAGE = {
"watchlist_select": "response must be an integer in the range 1-{max_show}",
"yes_no": "response must be one of the following: 'yes', 'y', 'no', 'n'"
}
def robert_easter_eggers(original_choice):
res = get_input(
f"Are you sure you want to set your default watchlist to...the oscars..? [y/n]: ",
{'y', 'yes', 'no', 'n'},
ERROR_MESSAGE['yes_no']
)
if res in {'y', 'yes'}:
res = get_input(
f"The awards that gave Best Picture to Forrest Gump over Pulp fiction..? [y/n]: ",
{'y', 'yes', 'no', 'n'},
ERROR_MESSAGE['yes_no']
)
if res in {'y', 'yes'}:
print('... Aight...')
return original_choice
if res in {'n', 'no'}:
return set_watchlist(no_oscars=True)
def get_watchlists():
mypath = THIS_DIRECTORY+DATA_DIR+WATCHLIST_DIR
return [f for f in listdir(mypath) if isfile(join(mypath, f))]
def get_input(question, response_format, error_message):
''' loops until a response that is in response_format is met'''
while True:
res = input(question)
if res in response_format:
return res
print(error_message)
def set_watchlist(no_oscars=False):
'''for each movie left filtering, asks the user if they want to watch it and provides showtimes to pick from'''
watchlist_files = get_watchlists()
if(no_oscars): watchlist_files = list(filter(lambda x: x!=OSCARS_WATCHLIST, watchlist_files))
for i, watchlist in enumerate(watchlist_files, start=1):
print(f"[{i}]: {watchlist}")
res = get_input(
f"select your watchlist [1-{len(watchlist_files)} or n to cancel]: ",
set(map(str, range(1, len(watchlist_files)+1)))|{'n', 'no'},
ERROR_MESSAGE['watchlist_select'].format(max_show=str(len(watchlist_files)))
)
print()
if res in {'n', 'no'}:
return None
chosen_watchlist = watchlist_files[int(res)-1]
if(not no_oscars):
if chosen_watchlist == OSCARS_WATCHLIST:
chosen_watchlist = robert_easter_eggers(chosen_watchlist)
return chosen_watchlist
if __name__ == "__main__":
set_watchlist()
| 2,932 | 964 |
from app import app, drinks
from flask import render_template, session, redirect, request
@app.route('/')
def index():
return render_template('index.html', drinks=drinks)
| 177 | 52 |
#Misc
import os, time, argparse
import h5py, json
import glob, fnmatch,pdb
from tqdm import tqdm
import multiprocessing
#Base
import numpy as np
import pandas as pd
import scipy.stats as st
from sklearn.model_selection import StratifiedKFold
#Plotting
import matplotlib
matplotlib.use('Agg')
import seaborn as sns
from matplotlib import pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.gridspec as gridspec
#State-Space Modeling
#S.Linderman
import ssm
#M.Johnson
from pyhsmm.util.text import progprint_xrange
from pybasicbayes.distributions import Gaussian, AutoRegression
import autoregressive.models as pyhmm
#User Modules
import utilities as util
import plotting_YAA as plots_YAA
##===== Run Command =====##
# OMP_NUM_THREADS=1 python olfactory_search_xval.py --model_type "ARHMM_MJ" --Kmin 12 --Kmax 20
##===== ============================ =====##
##===== Parse Command Line Arguments =====##
parser = argparse.ArgumentParser(description='ARHMM Mouse')
parser.add_argument('--save',type=bool, default=1,
help='Save Results?')
parser.add_argument('--json_dir', type=str,
help='Directory Path of model parameter json file; not required if using other arguments')
##===== Data Options =====##
parser.add_argument('--mID',type=str, default='all_mice',
help='mouse to fit model to')
parser.add_argument('--condition', type=str, default='all_conds',
help='trial condition type')
parser.add_argument('--data_type', type=str, default='BHNx',
help='BHNx vs BHNxv vs EgoAllo_xv')
parser.add_argument('--HMM_inputs', type=str, default='BHNx',
help='BHNx vs BHNxv')
parser.add_argument('--x_units', type=str, default='pixels',
help='pixels or arena_length')
##===== Model Type =====##
parser.add_argument('--model_type', type=str, default='ARHMM_MJ',
help='ARHMM_SL or ARHMM_MJ')
parser.add_argument('--robust', type=bool, default=0,
help='autoregressive(0) or robust_autoregressive(1)')
parser.add_argument('--sticky', type=bool, default=0,
help='standard(0) or sticky(1) ARHMM')
parser.add_argument('--inputdriven', type=bool, default=0,
help='HMM transitions dependent on some input in addition to previous HMM state')
##===== Model Parameters =====##
parser.add_argument('--kappa', type=float, default=1e5,
help='sticky arhmm kappa')
parser.add_argument('--AR_lags', type=str, default=1,
help='Autoregressive lags')
parser.add_argument('--l2_penalty_A', type=float, default=0,
help='AR l2_penalty_A')
parser.add_argument('--l2_penalty_b', type=float, default=0,
help='AR l2_penalty_b')
parser.add_argument('--l2_penalty_V', type=float, default=0,
help='AR l2_penalty_V')
parser.add_argument('--MAP_threshold', type=float, default=0.80,
help='MAP threshold')
parser.add_argument('--nGibbs', type=int, default=200,
help='number of iterations to run the Gibbs sampler')
parser.add_argument('--burn_fraction', type=float, default=0.66,
help='Calculate MAP sequence with the last 37.5% of samples; of nGibbs = 400, 250 samples are burned')
##===== Run Options =====##
parser.add_argument('--Kmin', type=int, default=80,
help='minimum number of HMM states')
parser.add_argument('--Kmax', type=int, default=100,
help='maximum number of HMM states')
parser.add_argument('--kXval', type=int, default=5,
help='number of kfold')
parser.add_argument('--EM_tolerance', type=float, default=1e-5,
help='SSM EM algorithm tolerance')
parser.add_argument('--EM_iters', type=int, default=200,
help='EM Iterations')
parser.add_argument('--max_processes', type=int, default=18,
help='max # of parallel processes to run')
args = parser.parse_args()
def set_arhmm_hyperparams(opt,K):
D_obs = opt['D_obs']
Mobs = 0
#Autoregressive keyword arguments
ar_kwargs = dict(
# l2_penalty_A= args_dic['l2_penalty_A'],
# l2_penalty_b= args_dic['l2_penalty_b'],
# l2_penalty_V= args_dic['l2_penalty_V'],
lags = opt['AR_lags']
)
#HMM Transition parameters
trans_kwargs = dict(
# alpha= args_dic['alpha'],
)
#Gaussian or t-distribution
if not opt['robust']:
observation_type = "autoregressive"
else:
observation_type = "robust_autoregressive"
#What model are we going to run?
if not opt['inputdriven']:
M = 0
if not opt['sticky']:
if opt['model_type'] == 'ARHMM_MJ':
print('Bayesian ARHMM')
else:
print('Vanilla ARHMM')
transition_type = "standard"
else:
print('sticky ARHMM')
transition_type = "sticky"
trans_kwargs['kappa'] = opt['kappa']
else:
M = D_obs
# trans_kwargs['l2_penalty'] = args_dic['l2_penalty_W'] #coeff of l2-regul penalty on W (weights of logistic regression)
transition_type = "inputdriven"
if not opt['sticky']:
print('input-driven ARHMM')
else:
print('input-driven sticky ARHMM')
trans_kwargs['kappa'] = opt['kappa']
#If we're using matt Johnsons code, most of the above parameters don't matter
#Initialize Observation distribution and set it to ar_kwargs
if opt['model_type'] == 'ARHMM_MJ':
affine = True
dynamics_hypparams = \
dict(nu_0=D_obs + 2,
S_0=np.eye(D_obs),
M_0=np.hstack((np.eye(D_obs), np.zeros((D_obs,int(affine))))),
K_0=np.eye(D_obs + affine),
affine=affine)
# Initialize a list of autorgressive objects given the size of the
# observations and number of max discrete states
ar_kwargs = [AutoRegression(A=np.column_stack((0.99 * np.eye(D_obs),\
np.zeros((D_obs, int(affine))))),sigma=np.eye(D_obs),\
**dynamics_hypparams) for _ in range(K)]
return D_obs, M, Mobs, observation_type, ar_kwargs, transition_type, trans_kwargs
def make_hyperparams_dic(opt, K, M, trans_kwargs, ar_kwargs):
hyperparams = opt.copy()
del hyperparams['Kmin'], hyperparams['Kmax']
hyperparams['K'] = K
hyperparams['M'] = M
# hyperparams['Mobs'] = Mobs
hyperparams['trans_kwargs'] = trans_kwargs
if opt['model_type'] == 'ARHMM_SL':
hyperparams['ar_kwargs'] = ar_kwargs
return hyperparams
def arhmm_bayesian_fit(arhmm, data_train, data_test, opt, i_fold):
# Add test data to ARHMM
for data in data_train:
# Add data per trial
arhmm.add_data(data)
#Create data structures to contain gibb samples
nGibbs = opt['nGibbs']
nTrials = len(data_train)
K = arhmm.num_states; D_obs = arhmm.D;
stateseq_smpls = [[] for i in range(nTrials)]
AB_smpls = np.zeros((nGibbs,K,D_obs,D_obs+1))
sqrt_sigmas_smpls = np.zeros((nGibbs,K,D_obs,D_obs))
trans_matrix_smpls = np.zeros((nGibbs,K,K))
GibbsLLs = np.zeros((nGibbs))
# Loop over samples
for iSample in tqdm(range(nGibbs)):
# Sample Model
arhmm.resample_model()
#keep track of model log_likelihood's as a check for "convergence"
GibbsLLs[iSample] = arhmm.log_likelihood()
# Append each Gibbs sample for each trial
for iTrial in range(len(arhmm.states_list)):
stateseq_smpls[iTrial].append(arhmm.states_list[iTrial].stateseq.copy())
# Append the ARHMM matrix A and transition matrix for this sample
for state in range(K):
AB_smpls[iSample,state] = arhmm.obs_distns[state].A.copy()
sqrt_sigmas_smpls[iSample,state] = np.linalg.cholesky(arhmm.obs_distns[state].sigma)
trans_matrix_smpls[iSample] = arhmm.trans_distn.trans_matrix.copy()
# Calculate the mean A, B, and transition matrix for all
burn = opt['burn_fraction']
ABs_mean = np.mean(AB_smpls[int(burn*nGibbs):],axis=0)
As = ABs_mean[:,:,:D_obs]; Bs = ABs_mean[:,:,D_obs]
sqrt_Sigmas = np.mean(sqrt_sigmas_smpls[int(burn*nGibbs):],axis=0)
obs = {'ABs': ABs_mean, 'As': As,'Bs': Bs, 'sqrt_Sigmas': sqrt_Sigmas}
log_mean_transition_matrix = np.log(np.mean(trans_matrix_smpls[int(burn*nGibbs):,:,:],axis=0))
trans = {'log_Ps': log_mean_transition_matrix}
init = {'P0': arhmm.init_state_distn.pi_0}
param_dict = {}
param_dict['transitions'] = trans
param_dict['observations'] = obs
param_dict['init_state_distn'] = init
#llhood of heldout
ll_heldout = arhmm.log_likelihood(data=data_test)
state_usage = arhmm.state_usages
#Lists to contain import stuffff
trMAPs = []
trPosteriors = []
trMasks = []
#Plot convergence here
SaveDir, fname_sffx = util.make_sub_dir(K, opt, i_fold)
plots_YAA.plot_model_convergence(stateseq_smpls, AB_smpls, trans_matrix_smpls, GibbsLLs, sorted(arhmm.used_states), SaveDir, fname='-'.join(('Model_convergence',fname_sffx))+'.pdf')
#All of the data has been used to fit the model
#All of the data is contained with the ARHMM object already
if i_fold == -1:
#Calculate the MAP estimate
for iTrial in range(nTrials):
# Take the gibbs samples after the burn fraction to construct MAP
z_smpls = np.array(stateseq_smpls[iTrial][int(burn*nGibbs):])
state_probs_trial = []
for state in range(K):
state_occurances = np.isin(z_smpls,state)
state_probs_trial.append(np.sum(state_occurances,axis=0)/z_smpls.shape[0])
#Save the maximum posterior probability for each time step
pprob = np.vstack((np.zeros((1,K)),np.array(state_probs_trial).T))
trPosteriors.append(pprob)
mask = np.max(pprob,axis=1) < opt['MAP_threshold']
trMasks.append(mask)
#Use the maximum posterior probability to determine a robust MAP State sequence
MAP = np.hstack(([-1],np.ndarray.flatten(st.mode(z_smpls)[0])))
#Add MAP to list
trMAPs.append(MAP)
ll_heldout
#Else this is a fold of the x-validation
else:
#Get the state sequences and state marginal distributions of the heldout data
for data in data_test:
#Get state marginals
state_marginals = arhmm.heldout_state_marginals(data)
trPosteriors.append(state_marginals)
#Create mask
mask = np.max(state_marginals,axis=1) < opt['MAP_threshold']
trMasks.append(mask)
#Get the state sequence with the max probability
stateseq = np.argmax(state_marginals,axis=1)
trMAPs.append(stateseq)
return trMAPs, trPosteriors, trMasks, state_usage, ll_heldout, param_dict, GibbsLLs
def map_seq_n_usage(arhmm, data_test, opt, inputs=None):
"""
Compute the local MAP state (arg-max of marginal state probabilities at each time step)
and overall state usages.
thresh: if marginal probability of MAP state is below threshold, replace with np.nan
(or rather output a mask array with nan's in those time steps)
Also output average state usages and the marginal state probabilities
"""
T = 0; ll_heldout = 0
state_usage = np.zeros(arhmm.K)
trMAPs = []
trPosteriors = []
trMasks = []
#Loop over data to obtain MAP sequence for each trial
for index, data in enumerate(data_test):
#Get state probabilities and log-likelihood
if opt['inputdriven']:
inputdata = inputs[index]
Ez, _, ll = arhmm.expected_states(data,input=inputdata)
else:
Ez, _, ll = arhmm.expected_states(data)
#Update number of data points, state usage, and llood of data
T += Ez.shape[0]
state_usage += Ez.sum(axis=0)
ll_heldout += ll
#maximum a posteriori probability estimate of states
map_seq = np.argmax(Ez,axis=1)
max_prob = Ez[np.r_[0:Ez.shape[0]],map_seq]
#Save sequences
trMAPs.append(map_seq)
trPosteriors.append(Ez)
trMasks.append(max_prob < opt['MAP_threshold'])
#Normalize
state_usage /= T
#Get parameters from ARHMM object
param_dict = util.params_to_dict(arhmm.params, HMM_INPUTS = opt['inputdriven'], ROBUST = opt['robust'])
return trMAPs, trPosteriors, trMasks, state_usage, ll_heldout, param_dict
def fit_arhmm_get_llhood(data_list, trsum, K, opt, train_inds=None, test_inds=None, i_fold=-1):
#Go!
startTime = time.time()
#Separate the data into a training and test set based on the indices given
if train_inds is not None and test_inds is not None:
data_train = [data_list[ii] for ii in train_inds]
data_test = [data_list[ii] for ii in test_inds]
trsum_test = trsum.iloc[test_inds]
else:
#fit model on all data
data_train = data_list
data_test = data_list
trsum_test = trsum
#adding 10 so i_fold == -1 case doesn't give error
np.random.seed(10+i_fold)
# set hyperparameters
D_obs, M, Mobs, observation_type, ar_kwargs, transition_type, trans_kwargs = set_arhmm_hyperparams(opt,K)
##===== Create the ARHMM object either from Scott's package =====##
if opt['model_type'] == 'ARHMM_SL':
arhmm = ssm.HMM(K, D_obs, M=M,
observations=observation_type, observation_kwargs=ar_kwargs,
transitions=transition_type, transition_kwargs=trans_kwargs)
if opt['inputdriven']:
#Separate inputs from the data_list into training and test sets
raise Exception('TODO: Separate inputs from the data_list into training and test sets')
else:
inputs_train = None
inputs_test = None
##===== Fit on training data =====##
model_convergence = arhmm.fit(data_train, inputs=inputs_train, method="em", num_em_iters=opt['EM_iters'], tolerance=opt['EM_tolerance'])
#Get MAP sequences for heldout data (or all of the data if this isn't part of the xval)
trMAPs, trPosteriors, trMasks, state_usage, ll_heldout_old, param_dict = map_seq_n_usage(arhmm, data_test, opt, inputs_test)
#Calculate loglikehood of the test and training data
ll_heldout = arhmm.log_likelihood(data_test)
ll_training = arhmm.log_likelihood(data_train, inputs=inputs_train)
##===== Or from Matt Johnson's packages =====##
else:
#Sticky or Standard ARHMM
if opt['sticky']:
# Create AR-HDP-HMM Object
arhmm = pyhmm.ARWeakLimitStickyHDPHMM(
init_state_distn='uniform',
init_emission_distn=init_distn,
obs_distns=ar_kwargs,
alpha=1.0, kappa=opt['kappa'], gamma=3.0)
else:
#Vanilla ARHMM
arhmm = pyhmm.ARHMM(
alpha=4.,
init_state_distn='uniform',
obs_distns=ar_kwargs)
##===== Fit on training data =====##
trMAPs, trPosteriors, trMasks, state_usage, ll_heldout, param_dict, model_convergence = \
arhmm_bayesian_fit(arhmm, data_train, data_test, opt, i_fold)
#Calculate loglikehood of training data
ll_training = arhmm.log_likelihood()
#Sort based on state-usage
trMAPs, trPosteriors, state_usage, state_perm = util.sort_states_by_usage(state_usage, trMAPs, trPosteriors)
##===== Calculate Log-likelihood =====##
#Count total number of time steps in data
tTest = sum(map(len, data_test))
ll_heldout_perstep = ll_heldout/tTest
#For Training
tTrain = sum(map(len, data_train))
ll_training_perstep = ll_training/tTrain
llhood_tuple = (ll_heldout,ll_heldout_perstep,ll_training,ll_training_perstep)
##===== Save & Plot =====##
#Create subdirectory under base directory for kfold
SaveDir, fname_sffx = util.make_sub_dir(K, opt, i_fold)
#Convert hyperparameters into dictionary for save process
hyperparams = make_hyperparams_dic(opt, K, M, trans_kwargs, ar_kwargs)
RunTime = time.perf_counter() - startTime
#Plot model parameters
plots_YAA.save_plot_parameters(SaveDir, fname_sffx, llhood_tuple, state_usage, hyperparams, param_dict, state_perm, model_convergence, RunTime)
#if this is fit on all data (which i_fold==-1 signifies) plot and save MAP seqs (and state-posteriors)
# if i_fold == -1:
# plots_YAA.save_plot_MAPseqs(SaveDir, fname_sffx, trsum, trMAPs, trPosteriors, trMasks, state_usage, opt, K, state_perm)
return ll_training_perstep, ll_heldout_perstep, K
##===== ===== =====##
##===== Start =====##
if __name__ == "__main__":
#GO!
startTime = time.time()
#Convert arguments into dictionary; opt <-> options
opt = args.__dict__
#Create base folder for saved results
SaveDirRoot = util.make_base_dir(opt['model_type'],opt['data_type'],opt['mID'])
#Save script options in JSON file
opt['SaveDirRoot'] = SaveDirRoot
opt['json_dir'] = SaveDirRoot
js_fname = 'ARHMM_hyperparameters.json'
if opt['save']:
with open(os.path.join(SaveDirRoot, js_fname), 'w') as jsfile:
json.dump(opt, jsfile, indent=4)
##====== ======================== ======##
##====== Read in Observation Data ======##
data_list, trsum, angle_list = util.read_data(opt['mID'],opt['condition'],opt['data_type'])
# Number of obserations per time step
D_obs = data_list[0].shape[1]
opt.update(D_obs = D_obs)
# Total Trials
nTrials = len(trsum)
#Save which trials are being used to fit the ARHMM
if opt['save']:
trsum.to_csv(os.path.join(SaveDirRoot,'inputted_trials.txt'),header=False,index=False,sep='\t',float_format='%.4f')
##===== ==================== =====##
##===== Perform X-validation =====##
k_fold = StratifiedKFold(n_splits=opt['kXval'])
#Stratify data per mice and per condition for kfolds
include = ['{}_C{}'.format(i,j) for i,j in zip(list(trsum['mID']),list(trsum['cond']))]
# Creates parallel processes
pool = multiprocessing.Pool(processes=opt['max_processes'])
#Preallocate matrix for cross-validation llhood values
Ks = np.arange(opt['Kmin'],opt['Kmax']+1,10)
ll_heldout = np.zeros((len(Ks),opt['kXval']+1))
ll_training = np.zeros((len(Ks),opt['kXval']+1))
model_fullfit = []
process_outputs = []
#Loop over number of HMM states
for index, K in enumerate(np.arange(opt['Kmin'],opt['Kmax']+1,20)):
#Fit the model to all of the data, and then for each kfold of x-validation
model_fullfit.append(pool.apply_async(fit_arhmm_get_llhood, args=(data_list,trsum,K,opt)))
#Loop over kfolds
kfold_outputs = []
for iK, (train_indices, test_indices) in enumerate(k_fold.split(data_list, include)):
kfold_outputs.append(pool.apply_async(fit_arhmm_get_llhood, args= \
(data_list, trsum, K, opt, train_indices, test_indices, iK)))
process_outputs.append(kfold_outputs)
##===== =========== =====##
##===== Get results =====##
#Extract log_likelihood results from parallel kfold processing
for index, results in enumerate(process_outputs):
ll_training[index,:-1] = np.array([iFold.get()[0] for iFold in results])
ll_heldout[index,:-1] = np.array([iFold.get()[1] for iFold in results])
Ks[index] = results[0].get()[2]
time
#For full fit
Ks_ff = Ks.copy()
for index, results in enumerate(model_fullfit):
ll_training[index,-1] = results.get()[0]
ll_heldout[index,-1] = results.get()[1]
Ks_ff = results.get()[2]
#Close Parallel pool
pool.close()
#Total Run Time
RunTime = time.perf_counter() - startTime
opt.update(RunTime = RunTime)
hrs=int(RunTime//3600); mins=int((RunTime%3600)//60); secs=int(RunTime - hrs*3600 - mins*60)
print('\tTotal run time = {:02d}:{:02d}:{:02d} for {} total trials and {} K\'s\n'.format(hrs,mins,secs,nTrials,opt['Kmax']+1-opt['Kmin']))
# Save summary data of all x-validation results
plots_YAA.save_plot_xval_lls(ll_training, ll_heldout, Ks,opt)
| 21,143 | 7,145 |
# Copyright 2019 PyEFF developers
#
# 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 numpy as np
def write_cfg(f_name,types,chemical_symbols,spins,x):
# write a new cfg file based on the x vector
o = open(f_name,'w')
o.write('@params\n')
o.write('calc = minimize\n')
o.write('@nuclei\n')
idx = 0
for p in range(len(types)):
if types[p] == 'nuclei':
o.write(str(x[idx+0])+' '+str(x[idx+1])+' '+str(x[idx+2])+' '+str(chemical_symbols[p])+'\n')
idx = idx + 3
o.write('@electrons\n')
for p in range(len(types)):
if types[p] == 'electron':
o.write(str(x[idx+0])+' '+str(x[idx+1])+' '+str(x[idx+2])+' '+str(spins[p])+' '+str(np.exp(x[idx+3]))+'\n')
idx = idx +4
o.close()
| 1,402 | 483 |
from collections import namedtuple
SubDocument = namedtuple("SubDocument", ["path_prefix", "mapping"])
NumericOperation = namedtuple("NumericOperation", ["path_prefix", "field", "operation"])
JoinOperation = namedtuple("JoinOperation", ["paths", "separator"])
MAPPING = {
"_id": "details/id",
"intro": {
"isnotdeclaration": "",
"declaration_year": "details/year"
},
"general": {
"full_name": "full_name",
"last_name": "last_name",
"name": "first_name",
"patronymic": "second_name",
"name_hidden": "",
"name_unclear": "",
"last_name_hidden": "",
"last_name_unclear": "",
"patronymic_hidden": "",
"patronymic_unclear": "",
"inn": "",
"addresses": [
{
"place": "",
"place_district": "",
"place_city": "",
"place_city_type": "",
"place_address": "",
"place_address_type": ""
}
],
"addresses_raw": "",
"addresses_raw_hidden": "",
"post": {
"region": "office/region",
"office": "office/office",
"post": "office/position"
},
"post_raw": "office/position",
"family": SubDocument(
"details/fields/4.0/items",
{
"relations": "",
"family_name": "family_member",
"inn": ""
}
),
"family_raw": ""
},
"income": {
"5": {
"value": "details/fields/5.0/items/0/value",
"comment": "",
"family": "details/fields/5.1/items/0/value",
"family_comment": ""
},
"6": {
"value": "details/fields/6.0/items/0/value",
"comment": "",
"family": "details/fields/6.1/items/0/value",
"family_comment": ""
},
"7": {
"value": "details/fields/7.0/items/0/value",
"comment": "",
"family": "details/fields/7.1/items/0/value",
"family_comment": "",
"source_name": "details/fields/7.0/items/0/comment"
},
"8": {
"value": "details/fields/8.0/items/0/value",
"comment": "",
"family": "details/fields/8.1/items/0/value",
"family_comment": ""
},
"9": {
"value": "details/fields/9.0/items/0/value",
"comment": "",
"family": "details/fields/9.1/items/0/value",
"family_comment": ""
},
"10": {
"value": "details/fields/10.0/items/0/value",
"comment": "",
"family": "details/fields/10.1/items/0/value",
"family_comment": ""
},
"11": {
"value": "details/fields/11.0/items/0/value",
"comment": "",
"family": "details/fields/11.1/items/0/value",
"family_comment": ""
},
"12": {
"value": "details/fields/12.0/items/0/value",
"comment": "",
"family": "details/fields/12.1/items/0/value",
"family_comment": ""
},
"13": {
"value": "details/fields/13.0/items/0/value",
"comment": "",
"family": "details/fields/13.1/items/0/value",
"family_comment": ""
},
"14": {
"value": "details/fields/14.0/items/0/value",
"comment": "",
"family": "details/fields/14.1/items/0/value",
"family_comment": ""
},
"15": {
"value": "details/fields/15.0/items/0/value",
"comment": "",
"family": "details/fields/15.1/items/0/value",
"family_comment": ""
},
"16": {
"value": "details/fields/16.0/items/0/value",
"comment": "",
"family": "details/fields/16.1/items/0/value",
"family_comment": ""
},
"17": {
"value": "details/fields/17.0/items/0/value",
"comment": "",
"family": "details/fields/17.1/items/0/value",
"family_comment": ""
},
"18": {
"value": "details/fields/18.0/items/0/value",
"comment": "",
"family": "details/fields/18.1/items/0/value",
"family_comment": ""
},
"19": {
"value": "details/fields/19.0/items/0/value",
"comment": "",
"family": "details/fields/19.1/items/0/value",
"family_comment": ""
},
"20": {
"value": "details/fields/20.0/items/0/value",
"comment": "",
"family": "details/fields/20.1/items/0/value",
"family_comment": ""
},
"21": SubDocument(
"details/fields/21.0/items",
{
"country": "",
"country_comment": "",
"cur": "",
"uah_equal": "value"
}
),
"22": SubDocument(
"details/fields/22.0/items",
{
"country": "",
"country_comment": "",
"cur": "",
"uah_equal": "value"
}
)
},
"estate": {
"23": SubDocument(
"details/fields/23.0/items",
{
"location_raw": "comment",
"region": "",
"address": "",
"space": "value",
"space_units": "",
"space_comment": "",
"costs": "purchase",
"costs_comment": "",
"costs_rent": "rent",
"costs_rent_comment": ""
}
),
"24": SubDocument(
"details/fields/24.0/items",
{
"location_raw": "comment",
"region": "",
"address": "",
"space": "value",
"space_units": "",
"space_comment": "",
"costs": "purchase",
"costs_comment": "",
"costs_rent": "rent",
"costs_rent_comment": ""
}
),
"25": SubDocument(
"details/fields/25.0/items",
{
"location_raw": "comment",
"region": "",
"address": "",
"space": "value",
"space_units": "",
"space_comment": "",
"costs": "purchase",
"costs_comment": "",
"costs_rent": "rent",
"costs_rent_comment": ""
}
),
"26": SubDocument(
"details/fields/26.0/items",
{
"location_raw": "comment",
"region": "",
"address": "",
"space": "value",
"space_units": "",
"space_comment": "",
"costs": "purchase",
"costs_comment": "",
"costs_rent": "rent",
"costs_rent_comment": ""
}
),
"27": SubDocument(
"details/fields/27.0/items",
{
"location_raw": "comment",
"region": "",
"address": "",
"space": "value",
"space_units": "",
"space_comment": "",
"costs": "purchase",
"costs_comment": "",
"costs_rent": "rent",
"costs_rent_comment": ""
}
),
"28": SubDocument(
"details/fields/28.0/items",
{
"location_raw": "comment",
"region": "",
"address": "",
"space": "value",
"space_units": "",
"space_comment": "",
"costs": "purchase",
"costs_comment": "",
"costs_rent": "rent",
"costs_rent_comment": ""
}
),
"29": SubDocument(
"details/fields/29.0/items",
{
"location_raw": "comment",
"region": "",
"address": "",
"space": "value",
"space_units": "",
"space_comment": "",
"costs_property": "purchase",
"costs_property_comment": "",
"costs_rent": "rent",
"costs_rent_comment": ""
}
),
"30": SubDocument(
"details/fields/30.0/items",
{
"location_raw": "comment",
"region": "",
"address": "",
"space": "value",
"space_units": "",
"space_comment": "",
"costs_property": "purchase",
"costs_property_comment": "",
"costs_rent": "rent",
"costs_rent_comment": ""
}
),
"31": SubDocument(
"details/fields/31.0/items",
{
"location_raw": "comment",
"region": "",
"address": "",
"space": "value",
"space_units": "",
"space_comment": "",
"costs_property": "purchase",
"costs_property_comment": "",
"costs_rent": "rent",
"costs_rent_comment": ""
}
),
"32": SubDocument(
"details/fields/32.0/items",
{
"location_raw": "comment",
"region": "",
"address": "",
"space": "value",
"space_units": "",
"space_comment": "",
"costs_property": "purchase",
"costs_property_comment": "",
"costs_rent": "rent",
"costs_rent_comment": ""
}
),
"33": SubDocument(
"details/fields/33.0/items",
{
"location_raw": "comment",
"region": "",
"address": "",
"space": "value",
"space_units": "",
"space_comment": "",
"costs_property": "purchase",
"costs_property_comment": "",
"costs_rent": "rent",
"costs_rent_comment": ""
}
),
"34": SubDocument(
"details/fields/34.0/items",
{
"location_raw": "comment",
"region": "",
"address": "",
"space": "value",
"space_units": "",
"space_comment": "",
"costs_property": "purchase",
"costs_property_comment": "",
"costs_rent": "rent",
"costs_rent_comment": ""
}
)
},
"vehicle": {
"35": SubDocument(
"details/fields/35.0/items",
{
"brand": JoinOperation(("mark", "model", "description"), ' '),
"brand_info": "",
"year": "year",
"sum": "purchase",
"sum_comment": "",
"sum_rent": "rent",
"sum_rent_comment": "",
"brand_hidden": ""
}
),
"36": SubDocument(
"details/fields/36.0/items",
{
"brand": JoinOperation(("mark", "model", "description"), ' '),
"brand_info": "",
"year": "year",
"sum": "purchase",
"sum_comment": "",
"sum_rent": "rent",
"sum_rent_comment": "",
"brand_hidden": ""
}
),
"37": SubDocument(
"details/fields/37.0/items",
{
"brand": JoinOperation(("mark", "model", "description"), ' '),
"brand_info": "",
"year": "year",
"sum": "purchase",
"sum_comment": "",
"sum_rent": "rent",
"sum_rent_comment": "",
"brand_hidden": ""
}
),
"38": SubDocument(
"details/fields/38.0/items",
{
"brand": JoinOperation(("mark", "model", "description"), ' '),
"brand_info": "",
"year": "year",
"sum": "purchase",
"sum_comment": "",
"sum_rent": "rent",
"sum_rent_comment": "",
"brand_hidden": ""
}
),
"39": SubDocument(
"details/fields/39.0/items",
{
"brand": JoinOperation(("mark", "model", "description"), ' '),
"brand_info": "",
"year": "year",
"sum": "purchase",
"sum_comment": "",
"sum_rent": "rent",
"sum_rent_comment": "",
"brand_hidden": ""
}
),
"40": SubDocument(
"details/fields/40.0/items",
{
"brand": JoinOperation(("mark", "model", "description"), ' '),
"brand_info": "",
"year": "year",
"sum": "purchase",
"sum_comment": "",
"sum_rent": "rent",
"sum_rent_comment": "",
"brand_hidden": ""
}
),
"41": SubDocument(
"details/fields/41.0/items",
{
"brand": JoinOperation(("mark", "model", "description"), ' '),
"brand_info": "",
"year": "year",
"sum": "purchase",
"sum_comment": "",
"sum_rent": "rent",
"sum_rent_comment": "",
"brand_hidden": ""
}
),
"42": SubDocument(
"details/fields/42.0/items",
{
"brand": JoinOperation(("mark", "model", "description"), ' '),
"brand_info": "",
"year": "year",
"sum": "purchase",
"sum_comment": "",
"sum_rent": "rent",
"sum_rent_comment": "",
"brand_hidden": ""
}
),
"43": SubDocument(
"details/fields/43.0/items",
{
"brand": JoinOperation(("mark", "model", "description"), ' '),
"brand_info": "",
"year": "year",
"sum": "purchase",
"sum_comment": "",
"sum_rent": "rent",
"sum_rent_comment": "",
"brand_hidden": ""
}
),
"44": SubDocument(
"details/fields/44.0/items",
{
"brand": JoinOperation(("mark", "model", "description"), ' '),
"brand_info": "",
"year": "year",
"sum": "purchase",
"sum_comment": "",
"sum_rent": "rent",
"sum_rent_comment": "",
"brand_hidden": ""
}
)
},
"banks": {
"45": [{
"sum": NumericOperation("details/fields/45.0/items", "value", sum),
"sum_units": "details/fields/45.0/units",
"sum_comment": "",
"sum_foreign": NumericOperation("details/fields/45.1/items", "value", sum),
"sum_foreign_units": "details/fields/45.1/units",
"sum_foreign_comment": ""
}],
"46": [{
"sum": NumericOperation("details/fields/46.0/items", "value", sum),
"sum_units": "details/fields/46.0/units",
"sum_comment": "",
"sum_foreign": NumericOperation("details/fields/46.1/items", "value", sum),
"sum_foreign_units": "details/fields/46.1/units",
"sum_foreign_comment": ""
}],
"47": [{
"sum": NumericOperation("details/fields/47.0/items", "value", sum),
"sum_units": "details/fields/47.0/units",
"sum_comment": "",
"sum_foreign": NumericOperation("details/fields/47.1/items", "value", sum),
"sum_foreign_units": "details/fields/47.1/units",
"sum_foreign_comment": ""
}],
"48": [{
"sum": NumericOperation("details/fields/48.0/items", "value", sum),
"sum_units": "details/fields/48.0/units",
"sum_comment": "",
"sum_foreign": NumericOperation("details/fields/48.1/items", "value", sum),
"sum_foreign_units": "details/fields/48.1/units",
"sum_foreign_comment": ""
}],
"49": [{
"sum": NumericOperation("details/fields/49.0/items", "value", sum),
"sum_units": "details/fields/49.0/units",
"sum_comment": "",
"sum_foreign": NumericOperation("details/fields/49.1/items", "value", sum),
"sum_foreign_units": "details/fields/49.1/units",
"sum_foreign_comment": ""
}],
"50": [{
"sum": NumericOperation("details/fields/50.0/items", "value", sum),
"sum_units": "details/fields/50.0/units",
"sum_comment": "",
"sum_foreign": NumericOperation("details/fields/50.1/items", "value", sum),
"sum_foreign_units": "details/fields/50.1/units",
"sum_foreign_comment": ""
}],
"51": [{
"sum": NumericOperation("details/fields/51.0/items", "value", sum),
"sum_units": "details/fields/51.0/units",
"sum_comment": "",
"sum_foreign": NumericOperation("details/fields/51.1/items", "value", sum),
"sum_foreign_units": "details/fields/51.1/units",
"sum_foreign_comment": ""
}],
"52": [{
"sum": NumericOperation("details/fields/52.0/items", "value", sum),
"sum_units": "details/fields/52.0/units",
"sum_comment": "",
"sum_foreign": NumericOperation("details/fields/52.1/items", "value", sum),
"sum_foreign_units": "details/fields/52.1/units",
"sum_foreign_comment": ""
}],
"53": [{
"sum": NumericOperation("details/fields/53.0/items", "value", sum),
"sum_units": "details/fields/53.0/units",
"sum_comment": "",
"sum_foreign": NumericOperation("details/fields/53.1/items", "value", sum),
"sum_foreign_units": "details/fields/53.1/units",
"sum_foreign_comment": ""
}]
},
"liabilities": {
"54": {
"sum": NumericOperation("details/fields/54.0/items", "value", sum),
"sum_comment": "",
"sum_foreign": NumericOperation("details/fields/54.1/items", "value", sum),
"sum_foreign_comment": ""
},
"55": {
"sum": NumericOperation("details/fields/55.0/items", "value", sum),
"sum_comment": "",
"sum_foreign": NumericOperation("details/fields/55.1/items", "value", sum),
"sum_foreign_comment": ""
},
"56": {
"sum": NumericOperation("details/fields/56.0/items", "value", sum),
"sum_comment": "",
"sum_foreign": NumericOperation("details/fields/56.1/items", "value", sum),
"sum_foreign_comment": ""
},
"57": {
"sum": NumericOperation("details/fields/57.0/items", "value", sum),
"sum_comment": "",
"sum_foreign": NumericOperation("details/fields/57.1/items", "value", sum),
"sum_foreign_comment": ""
},
"58": {
"sum": NumericOperation("details/fields/58.0/items", "value", sum),
"sum_comment": "",
"sum_foreign": NumericOperation("details/fields/58.1/items", "value", sum),
"sum_foreign_comment": ""
},
"59": {
"sum": NumericOperation("details/fields/59.0/items", "value", sum),
"sum_comment": "",
"sum_foreign": NumericOperation("details/fields/59.1/items", "value", sum),
"sum_foreign_comment": ""
},
"60": {
"sum": NumericOperation("details/fields/60.0/items", "value", sum),
"sum_comment": "",
"sum_foreign": NumericOperation("details/fields/60.1/items", "value", sum),
"sum_foreign_comment": ""
},
"61": {
"sum": NumericOperation("details/fields/61.0/items", "value", sum),
"sum_comment": "",
"sum_foreign": NumericOperation("details/fields/61.1/items", "value", sum),
"sum_foreign_comment": ""
},
"62": {
"sum": NumericOperation("details/fields/62.0/items", "value", sum),
"sum_comment": "",
"sum_foreign": NumericOperation("details/fields/62.1/items", "value", sum),
"sum_foreign_comment": ""
},
"63": {
"sum": NumericOperation("details/fields/63.0/items", "value", sum),
"sum_comment": "",
"sum_foreign": NumericOperation("details/fields/63.1/items", "value", sum),
"sum_foreign_comment": ""
},
"64": {
"sum": NumericOperation("details/fields/64.0/items", "value", sum),
"sum_comment": "",
"sum_foreign": NumericOperation("details/fields/64.1/items", "value", sum),
"sum_foreign_comment": ""
}
},
"declaration": {
"date": "",
"notfull": "",
"notfull_lostpages": "",
"additional_info": "details/comment",
"additional_info_text": "details/comment",
"needs_scancopy_check": "",
"url": "details/url",
"link": "details/link",
"source": "%CHESNO%"
}
}
| 22,196 | 6,449 |
# !/usr/bin/env python
# -*- coding:utf-8 -*-
import queue
import threading
import traceback
from data.config import *
from common.log.log_util import LogUtil as log
logger = log.getLogger(__name__)
class ThreadPool(object):
def __init__(self):
self.task_queue = queue.Queue()
self.threads = []
self.__init_thread_pool(THREAD_NUMBER)
def __init_thread_pool(self, thread_num):
"""
the number of workers means the number of parallel running threads
"""
for i in range(thread_num):
worker = Worker(self.task_queue)
worker.setDaemon(True) # comment this line to avoid the main thread was end before subthread
worker.start()
self.threads.append(worker)
# logger.debug('constructed a thread pool with %d workers', len(self.threads))
def add_task(self, func, *args):
"""
add a task to task queue
"""
self.task_queue.put((func, args))
def wait_all_complete(self):
"""
this will block the thread until the task queue was empty
"""
self.task_queue.join()
self._terminate_workers()
def force_complete(self):
self.clear_tasks()
self._terminate_workers()
def clear_tasks(self):
# logger.info('there are %d tasks in the queue that will be removed' % self.task_queue.qsize())
while not self.task_queue.empty():
self.task_queue.get_nowait()
self.task_queue.task_done()
# logger.debug('removed a task and %d remains' % self.task_queue.qsize())
# logger.info('task queue was cleared and the size=%d' % self.task_queue.qsize())
def _terminate_workers(self):
# logger.debug('will terminate %d workers in thread pool', len(self.threads))
for worker in self.threads:
worker.terminate()
class Worker(threading.Thread):
def __init__(self, task_queue):
super(Worker, self).__init__()
self.task_queue = task_queue
self.stop = False
def run(self):
max_len = 64
while not self.stop:
try:
do, args = self.task_queue.get(timeout=1)
args_desc = str(args)
if len(args_desc) > max_len:
args_desc = '%s...' % args_desc[0:max_len]
# logger.debug('get a task(function=%s, params=%s) and there are %d in queue' %
# (do, args_desc, self.task_queue.qsize()))
try:
do(*args)
except:
logger.warn(traceback.format_exc())
# logger.debug('finish a task(function=%s, params=%s) and there are %d in queue' %
# (do, args_desc, self.task_queue.qsize()))
if self.stop:
# logger.info('the worker in thread pool was terminated')
pass
self.task_queue.task_done()
except:
pass
def terminate(self):
self.stop = True
| 3,179 | 894 |
from time import sleep
from selenium.webdriver.common.keys import Keys
from os import path
from .tool import *
from .error import BadPathError
import traceback
def change_group_description(self, description: str):
"""Changes the group description
Args:
description (str): New group description
"""
try:
# Abre as informações do grupo
self.driver.find_element_by_xpath('//*[@id="main"]/header/div[2]').click()
if not is_admin(self):
print("You are not a group admin!")
return
self.driver.find_element_by_xpath(
'//*[@id="app"]/div[1]/div[1]/div[2]/div[3]/span/div[1]/span/div[1]/div/section/div[2]/div[2]/div/div/span[2]/div'
).click() # Tenta clicar na caneta de edição da descrição
description_dom = self.driver.find_element_by_xpath(
'//*[@id="app"]/div[1]/div[1]/div[2]/div[3]/span/div[1]/span/div[1]/div/section/div[2]/div[2]/div/div[1]/div/div[2]'
) # Seleciona a descrição para editar
description_dom.clear() # Limpa
if description.find("\n"): # Escreve
for line in description.split("\n"):
description_dom.send_keys(line)
description_dom.send_keys(Keys.SHIFT + Keys.ENTER)
description_dom.send_keys(Keys.ENTER)
else:
description_dom.send_keys(description)
except:
error_log(traceback.format_exc())
try: # Fecha as informações do grupo
self.driver.find_element_by_xpath(
'//*[@id="app"]/div[1]/div[1]/div[2]/div[3]/span/div[1]/span/div[1]/header/div/div[1]/button'
).click()
except:
pass
def change_group_name(self, name: str):
"""Changes the group name
Args:
name (str): New group name
"""
try:
# Abre as informações do grupo
self.driver.find_element_by_xpath('//*[@id="main"]/header/div[2]').click()
if not is_admin(self):
print("You are not a group admin!")
return
# Clica para editar o nome do grupo
self.driver.find_element_by_xpath(
'//*[@id="app"]/div[1]/div[1]/div[2]/div[3]/span/div[1]/span/div[1]/div/section/div[1]/div[2]/div[1]/span[2]/div'
).click()
group_name_dom = self.driver.find_element_by_xpath(
'//*[@id="app"]/div[1]/div[1]/div[2]/div[3]/span/div[1]/span/div[1]/div/section/div[1]/div[2]/div[1]/div/div[2]'
) # Seleciona o texto do nome do grupo
group_name_dom.clear() # Limpa
group_name_dom.send_keys(name + Keys.ENTER) # Escreve
except:
error_log(traceback.format_exc())
try:
self.driver.find_element_by_xpath(
'//*[@id="app"]/div[1]/div[1]/div[2]/div[3]/span/div[1]/span/div[1]/header/div/div[1]/button'
).click() # Fecha as informações do grupo
except:
pass
def change_group_pfp(self, file_path: str):
try:
if not path.isabs(file_path):
raise BadPathError("The file path is not absolute")
# Abre as informações do grupo
self.driver.find_element_by_xpath('//*[@id="main"]/header/div[2]').click()
if not is_admin(self):
print("You are not a group admin!")
return
self.driver.find_element_by_xpath(
'//*[@id="app"]/div[1]/div[1]/div[2]/div[3]/span/div[1]/span/div[1]/div/section/div[1]/div[1]/div/input'
).send_keys(file_path) # Envia a foto
sleep(1)
self.driver.find_element_by_xpath(
'//*[@id="app"]/div[1]/span[2]/div[1]/div/div/div/div/div/span/div[1]/div/div[2]/span/div'
).click() # Confima
except:
error_log(traceback.format_exc())
try:
self.driver.find_element_by_xpath(
'//*[@id="app"]/div[1]/div[1]/div[2]/div[3]/span/div[1]/span/div[1]/header/div/div[1]/button'
).click() # Fecha as informações do grupo
except:
pass
def leave_group(self):
"""Leaves the group you are"""
# Abre as informações do grupo
self.driver.find_element_by_xpath('//*[@id="main"]/header/div[2]').click()
self.driver.find_element_by_xpath(
'//*[@id="app"]/div[1]/div[1]/div[2]/div[3]/span/div[1]/span/div[1]/div/section/div[6]/div'
).click()
self.driver.find_element_by_xpath(
'//*[@id="app"]/div[1]/span[2]/div[1]/div/div/div/div/div/div[2]/div[2]'
).click()
| 4,431 | 1,595 |
from http.server import HTTPServer, SimpleHTTPRequestHandler
import sys
ip = '127.0.0.1'
port = 8000
addr = (ip, port)
httpd = HTTPServer(addr, SimpleHTTPRequestHandler)
Servip, Servport = httpd.socket.getsockname()
try:
httpd.serve_forever()
except KeyboardInterrupt:
print('Keyboard interrupt received, exiting.')
httpd.server_close()
sys.exit(0) | 365 | 130 |
"""Day 10: Adapter Array"""
from collections import Counter
from collections import defaultdict
from aoc import Solution
class Day10(Solution):
"""Solution to day 10 of the 2020 Advent of Code"""
def __init__(self) -> None:
super().__init__(2020, 10, "Adapter Array")
@property
def max_joltage(self) -> int:
"""The last element in the data plus 3"""
return self.data[-1] + 3
def _part_one(self) -> int:
counts = Counter(
val - prev for val, prev in zip(self.data, [0, *self.data[:-1]])
)
return counts[1] * (counts[3] + 1)
def _part_two(self) -> int:
counts = defaultdict(int, {0: 1})
for value in self.data:
counts[value] = counts[value - 1] + counts[value - 2] + counts[value - 3]
return counts[self.max_joltage - 3]
def _get_data(self) -> list[int]:
return sorted(self.input.as_list(int))
| 935 | 329 |
import numpy as np
import pickle
from sklearn.model_selection import train_test_split
from sklearn import svm
from sklearn import metrics
import pandas as pd
with open('data/dataframe.pickle', 'rb') as handle:
df = pickle.load(handle)
data = df.copy()
data.drop('alphabet', axis=1)
target = df.alphabet
X_train, X_test, y_train, y_test = train_test_split(data, target, test_size=0.4,random_state=109) # 70% training and 30% test
#Create a svm Classifier
clf = svm.SVC(kernel='linear') # Linear Kernel
#Train the model using the training sets
clf.fit(X_train, y_train)
#Predict the response for test dataset
y_pred = clf.predict(X_test)
# Model Accuracy: how often is the classifier correct?
print("Accuracy:",metrics.accuracy_score(y_test, y_pred))
with open('data/classifier_SVM.pickle', 'wb') as handle:
pickle.dump(clf, handle, protocol=pickle.HIGHEST_PROTOCOL) | 874 | 320 |
from pyee import EventEmitter
dispatch = EventEmitter()
| 56 | 18 |
from toolz import curry
from dataclasses_serialization.serializer_base.errors import DeserializationError
from dataclasses_serialization.serializer_base.noop import noop_deserialization
from dataclasses_serialization.serializer_base.typing import (
dataclass_field_types,
isinstance,
)
__all__ = ["dict_to_dataclass"]
@curry
def dict_to_dataclass(cls, dct, deserialization_func=noop_deserialization):
if not isinstance(dct, dict):
raise DeserializationError(
"Cannot deserialize {} {!r} using {}".format(
type(dct), dct, dict_to_dataclass
)
)
try:
fld_types = dataclass_field_types(cls, require_bound=True)
except TypeError:
raise DeserializationError("Cannot deserialize unbound generic {}".format(cls))
try:
return cls(
**{
fld.name: deserialization_func(fld_type, dct[fld.name])
for fld, fld_type in fld_types
if fld.name in dct
}
)
except TypeError:
raise DeserializationError(
"Missing one or more required fields to deserialize {!r} as {}".format(
dct, cls
)
)
| 1,217 | 366 |
from functools import wraps
def check_optional_module(_func=None,
*,
has_module: bool,
exception_message: str):
def decorator_check_optional_module(func):
@wraps(func)
def wrapper_check_optional_module(*args, **kwargs):
if not has_module:
raise ModuleNotFoundError(exception_message)
return func(*args, **kwargs)
return wrapper_check_optional_module
if _func is None:
return decorator_check_optional_module
else:
return decorator_check_optional_module(_func)
def track_calls(func):
@wraps(func)
def wrapper_track_calls(*args, **kwargs):
wrapper_track_calls.has_been_called_ids.append(id(args[0]))
return func(*args, **kwargs)
wrapper_track_calls.has_been_called_ids = []
return wrapper_track_calls
| 905 | 261 |
from django.apps import AppConfig
class DjversionConfig(AppConfig):
name = 'djversion'
| 93 | 28 |
'''
#################################################################################################
# author wudong
# date 20190812
# 功能
# 实现各类算法,Srasa(0),Sarsa(λ),Q-learning,DQN
#################################################################################################
'''
from random import random, choice
from gym import Env, spaces
import gym
import numpy as np
from core import Transition, Experience, Agent
from utils import str_key, set_dict, get_dict
from utils import epsilon_greedy_pi, epsilon_greedy_policy
from utils import greedy_policy, learning_curve
from approximator import NetApproximator
class SarsaAgent(Agent):
def __init__(self, env:Env, capacity:int = 20000):
super(SarsaAgent, self).__init__(env, capacity)
self.Q = {} #增加Q字典存储行为价值
def policy(self, A, s, Q, epsilon): #重写基类的policy函数
'''
使用ε-greedy策略
return
a 策略得到的行为
'''
return epsilon_greedy_policy(A, s, Q, epsilon)
def learning_method(self, gamma = 0.9, alpha = 0.1, epsilon = 1e-5, display = False, lambda_ = None):
'''重写基类的函数
遍历一个episode
'''
self.state = self.env.reset() #个体当前的状态
s0 = self.state
if display:
self.env.render()
a0 = self.perform_policy(s0, epsilon) #执行策略,生成动作
time_in_episode, total_reward = 0, 0
is_done = False
while not is_done:
# add code here
s1, r1, is_done, info, total_reward = self.act(a0)
if display:
self.env.render()
a1 = self.perform_policy(s1, epsilon)
old_q = get_dict(self.Q, s0, a0)
q_prime = get_dict(self.Q, s1, a1)
td_target = r1 + gamma * q_prime
new_q = old_q + alpha * (td_target - old_q)
set_dict(self.Q, new_q, s0, a0)
s0, a0 = s1, a1
time_in_episode += 1
if display:
print(self.experience.last_episode)
return time_in_episode, total_reward
class SarsaLambdaAgent(Agent):
def __init__(self, env:Env, capacity:int = 20000):
super(SarsaLambdaAgent, self).__init__(env, capacity)
self.Q = {}
def policy(self, A, s, Q, epsilon):
return epsilon_greedy_policy(A, s, Q, epsilon)
def learning_method(self, lambda_ = 0.9, gamma = 0.9, alpha = 0.1, epsilon = 1e-5, display = False):
self.state = self.env.reset()
s0 = self.state
if display:
self.env.render()
a0 = self.perform_policy(s0, epsilon)
# print(self.action_t.name)
time_in_episode, total_reward = 0, 0
is_done = False
E = {}
while not is_done:
# add code here
s1, r1, is_done, info, total_reward = self.act(a0)
if display:
self.env.render()
a1 = self.perform_policy(s1, epsilon)
q = get_dict(self.Q, s0, a0)
q_prime = get_dict(self.Q, s1, a1)
delta = r1 + gamma * q_prime - q
e = get_dict(E, s0, a0)
e += 1
set_dict(E, e, s0, a0)
for s in self.S:
for a in self.A:
e_value = get_dict(E, s, a)
old_q = get_dict(self.Q, s, a)
new_q = old_q + alpha * delta * e_value
new_e = gamma * lambda_ * e_value
set_dict(self.Q, new_q, s, a)
set_dict(E, new_e, s, a)
s0, a0 = s1, a1
time_in_episode += 1
if display:
print(self.experience.last_episode)
return time_in_episode, total_reward
class QAgent(Agent):
def __init__(self, env:Env, capacity:int = 20000):
super(QAgent, self).__init__(env, capacity)
self.Q = {}
def policy(self, A, s, Q, epsilon):
return epsilon_greedy_policy(A, s, Q, epsilon)
def learning_method(self, gamma = 0.9, alpha = 0.1, epsilon = 1e-5, display = False, lambda_ = None):
self.state = self.env.reset()
s0 = self.state
if display:
self.env.render()
time_in_episode, total_reward = 0, 0
is_done = False
while not is_done:
# add code here
a0 = self.perform_policy(s0, epsilon) #使用ε-greedy
s1, r1, is_done, info, total_reward = self.act(a0)
if display:
self.env.render()
self.policy = greedy_policy
a1 = greedy_policy(self.A, s1, self.Q) #使用完全贪婪策略
old_q = get_dict(self.Q, s0, a0)
q_prime = get_dict(self.Q, s1, a1)
td_target = r1 + gamma * q_prime
new_q = old_q + alpha * (td_target - old_q)
set_dict(self.Q, new_q, s0, a0)
s0 = s1
time_in_episode += 1
if display:
print(self.experience.last_episode)
return time_in_episode, total_reward
class DQNAgent(Agent):
'''使用近似的价值函数(全连接网络)实现的DQN
'''
def __init__(self, env: Env = None,
capacity = 20000,
hidden_dim: int = 32,
batch_size = 128,
epochs = 2):
if env is None:
raise "agent should have an environment"
super(DQNAgent, self).__init__(env, capacity)
self.input_dim = env.observation_space.shape[0] # 状态连续,输入维度
self.output_dim = env.action_space.n # 行为离散,输出维度
self.hidden_dim = hidden_dim #隐藏层的维度
# 行为网络,该网络用来计算产生行为,以及对应的Q值,每次更新
self.behavior_Q = NetApproximator(input_dim = self.input_dim,
output_dim = self.output_dim,
hidden_dim = self.hidden_dim)
self.target_Q = self.behavior_Q.clone() # 计算价值目标的Q,不定期更新
self.batch_size = batch_size # 批学习一次状态转换数量
self.epochs = epochs # 统一批状态转换学习的次数
return
def _update_target_Q(self):
'''将更新策略的Q网络(连带其参数)复制给输出目标Q值的网络
'''
self.target_Q = self.behavior_Q.clone() # 更新计算价值目标的Q网络
def policy(self, A, s, Q = None, epsilon = None):
'''依据更新策略的价值函数(网络)产生一个行为,遵循greedy或ε-greedy
'''
Q_s = self.behavior_Q(s) # 行为价值函数,预测得到Q
rand_value = random()
if epsilon is not None and rand_value < epsilon:
return self.env.action_space.sample()
else:
return int(np.argmax(Q_s)) #返回得到最大Q值的动作a
def _learn_from_memory(self, gamma, learning_rate):
'''从记忆中进行学习,(experience-episode-transmition)
'''
trans_pieces = self.sample(self.batch_size) # 随机获取记忆里的Transmition,取batch_size个
states_0 = np.vstack([x.s0 for x in trans_pieces])
actions_0 = np.array([x.a0 for x in trans_pieces])
reward_1 = np.array([x.reward for x in trans_pieces])
is_done = np.array([x.is_done for x in trans_pieces])
states_1 = np.vstack([x.s1 for x in trans_pieces])
X_batch = states_0
y_batch = self.target_Q(states_0) # 得到numpy格式的预测结果
Q_target = reward_1 + gamma * np.max(self.target_Q(states_1), axis=1)*\
(~ is_done) # is_done则Q_target==reward_1
# switch this on will make DQN to DDQN
# 行为a'从行为价值网络中得到
#a_prime = np.argmax(self.behavior_Q(states_1), axis=1).reshape(-1)
# (s',a')的价值从目标价值网络中得到
#Q_states_1 = self.target_Q(states_1)
#temp_Q = Q_states_1[np.arange(len(Q_states_1)), a_prime]
# (s,a)的目标价值根据贝尔曼方程得到
#Q_target = reward_1 + gamma * temp_Q * (~ is_done) # is_done则Q_target==reward_1
## end of DDQN part
y_batch[np.arange(len(X_batch)), actions_0] = Q_target #作为目标值、监督值
# 训练行为价值网络,更新其参数
loss = self.behavior_Q.fit(x = X_batch, #行为价值网络,利用X_batch生成预测值,与y_batch计算损失
y = y_batch,
learning_rate = learning_rate,
epochs = self.epochs)
mean_loss = loss.sum() / self.batch_size
# 可根据需要设定一定的目标价值网络参数的更新频率
self._update_target_Q()
return mean_loss
def learning_method(self, gamma = 0.9, alpha = 0.1, epsilon = 1e-5,
display = False, lambda_ = None):
'''遍历单个eposide
'''
self.state = self.env.reset()
s0 = self.state
if display:
self.env.render()
time_in_episode, total_reward = 0, 0
is_done = False
loss = 0
while not is_done:
# add code here
s0 = self.state
a0 = self.perform_policy(s0, epsilon) #行为价值网络behavior产生动作a0
s1, r1, is_done, info, total_reward = self.act(a0) #执行动作,得到观测值
if display:
self.env.render()
# 当经历里有足够大小的transition时,开始启用基于experience的学习
if self.total_trans > self.batch_size:
loss += self._learn_from_memory(gamma, alpha)
# s0 = s1
time_in_episode += 1
loss /= time_in_episode
if display:
print("epsilon:{:3.2f},loss:{:3.2f},{}".format(epsilon,loss,self.experience.last_episode))
return time_in_episode, total_reward
| 9,359 | 3,662 |
#!/usr/bin/python
# -*- coding:utf-8 -*-
import numpy as np
from sklearn import svm
import matplotlib.colors
import matplotlib.pyplot as plt
from PIL import Image
from sklearn.metrics import accuracy_score
import pandas as pd
import os
import csv
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.ensemble import RandomForestClassifier
from time import time
from pprint import pprint
def save_image(im, i):
im = 255 - im.values.reshape(28, 28)
a = im.astype(np.uint8)
output_path = '.\\HandWritten'
if not os.path.exists(output_path):
os.mkdir(output_path)
Image.fromarray(a).save(output_path + ('\\%d.png' % i))
def save_result(model):
data_test_pred = model.predict(data_test)
data_test['Label'] = data_test_pred
data_test.to_csv('Prediction.csv', header=True, index=True, columns=['Label'])
if __name__ == "__main__":
classifier_type = 'RF'
print('载入训练数据...')
t = time()
data = pd.read_csv('MNIST.train.csv', header=0, dtype=np.int)
print('载入完成,耗时%f秒' % (time() - t))
x, y = data.iloc[:, 1:], data['label']
x_train, x_valid, y_train, y_valid = train_test_split(x, y, test_size=0.2, random_state=1)
print(x.shape, x_valid.shape)
print('图片个数:%d,图片像素数目:%d' % x.shape)
print('载入测试数据...')
t = time()
data_test = pd.read_csv('MNIST.test.csv', header=0, dtype=np.int)
print('载入完成,耗时%f秒' % (time() - t))
matplotlib.rcParams['font.sans-serif'] = ['SimHei']
matplotlib.rcParams['axes.unicode_minus'] = False
plt.figure(figsize=(15, 9), facecolor='w')
for index in range(16):
image = x.iloc[index, :]
plt.subplot(4, 8, index + 1)
plt.imshow(image.values.reshape(28, 28), cmap=plt.cm.gray_r, interpolation='nearest')
plt.title('训练图片: %i' % y[index])
for index in range(16):
image = data_test.iloc[index, :]
plt.subplot(4, 8, index + 17)
plt.imshow(image.values.reshape(28, 28), cmap=plt.cm.gray_r, interpolation='nearest')
save_image(image.copy(), index)
plt.title('测试图片')
plt.tight_layout(2)
plt.show()
if classifier_type == 'SVM':
model = svm.SVC(C=1000, kernel='rbf', gamma=1e-10)
print('SVM开始训练...')
else:
model = RandomForestClassifier(100, criterion='gini', min_samples_split=2, min_impurity_decrease=1e-10)
print('随机森林开始训练...')
t = time()
model.fit(x_train, y_train)
t = time() - t
print('%s训练结束,耗时%d分钟%.3f秒' % (classifier_type, int(t/60), t - 60*int(t/60)))
t = time()
y_train_pred = model.predict(x_train)
t = time() - t
print('%s训练集准确率:%.3f%%,耗时%d分钟%.3f秒' % (classifier_type, accuracy_score(y_train, y_train_pred)*100, int(t/60), t - 60*int(t/60)))
t = time()
y_valid_pred = model.predict(x_valid)
t = time() - t
print('%s测试集准确率:%.3f%%,耗时%d分钟%.3f秒' % (classifier_type, accuracy_score(y_valid, y_valid_pred)*100, int(t/60), t - 60*int(t/60)))
save_result(model)
err = (y_valid != y_valid_pred)
err_images = x_valid[err]
err_y_hat = y_valid_pred[err]
err_y = y_valid[err]
print(err_y_hat)
print(err_y)
plt.figure(figsize=(10, 8), facecolor='w')
for index in range(12):
image = err_images.iloc[index, :]
plt.subplot(3, 4, index + 1)
plt.imshow(image.values.reshape(28, 28), cmap=plt.cm.gray_r, interpolation='nearest')
plt.title('错分为:%i,真实值:%i' % (err_y_hat[index], err_y.values[index]), fontsize=12)
plt.suptitle('数字图片手写体识别:分类器%s' % classifier_type, fontsize=15)
plt.tight_layout(rect=(0, 0, 1, 0.95))
plt.show()
| 3,649 | 1,609 |
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.animation as animation
import matplotlib.colors as mcolors
from scipy.interpolate import interp1d
from scipy.integrate import solve_ivp
import os
import re
import numpy as np
import h5py
import sys
from os.path import dirname, realpath
pypath = dirname(dirname(dirname(realpath(__file__)))) + '/python/'
sys.path.insert(1, pypath)
import utils
from odes import car2
dirpath = dirname(realpath(__file__))
transfile = '/abstfull_0.2-0.2-0.2.h5'
labelfile = '/labels_dba1_abstfull_0.2-0.2-0.2.h5'
ctlrfile = '/controller_dba1_0.2-0.2-0.2.h5'
specfile = '/dba1.txt'
# # Simulation of static motion planning
tau, X, eta, _, winids, controller = \
utils.read_controller_abst_from_h5(dirpath+ctlrfile)
# # Compute the percentage of winning set on the state space
winset = controller.xgrid[winids, :]
print("\nWinning set coverage:")
winper = "{:.2%}".format(winids.size/controller.xgrid.shape[0])
print(winper)
# # Load specification
dba = utils.read_spec_from_txt(dirpath+specfile)
# # Simulation
Tsim = 50
num_acc = 3
x0 = np.array([1.0, 1.0, np.pi/3.])
i0 = utils.index_in_grid(x0, controller.xgrid)
if(not np.any(winids == i0)):
sys.exit("The initial condition is not in the winning set.\n")
xsim, usim, qsim, tsim = utils.simulate_abstbased_dba_control(
tau, Tsim, num_acc, x0, car2, dba, controller)
# # Display workspace
fig = plt.figure()
ax = plt.axes()
ax.set_xlim(0,10)
ax.set_ylim(0,10)
xgrid = np.array([])
eta = np.array([])
labels = np.array([])
obs = np.array([])
with h5py.File(dirpath+transfile, 'r') as ft,\
h5py.File(dirpath+labelfile, 'r') as fl:
eta = ft['eta'][...]
xgrid = ft['xgrid'][...]
obs = ft['obs'][...]
labels = fl['labels'][...]
oset = xgrid[obs, :]
ax.add_collection(
utils.polycoll_grid_array(oset, eta, True, 'gray', 0.7)
)
gset = xgrid[np.where(labels>0),:].squeeze()
ax.add_collection(
utils.polycoll_grid_array(gset, eta, True, 'palegreen', 0.7)
)
obstacles = [[0.0, 0.5, 5.0, 6.0],
[2.4, 2.6, 0.0, 3.2],
[3.9, 4.1, 9.0, 10.0], #[3.9, 4.1, 8.0, 10.0]
[5.9, 6.1, 0.0, 0.6],
[5.9, 6.1, 3.8, 5.1], # [5.9, 6.1, 3.8, 6.1],
[6.1, 10.0, 4.9, 5.1]] # [6.1, 10.0, 5.9, 6.1]
rects_obs = [patches.Rectangle((obstacles[i][0], obstacles[i][2]),
obstacles[i][1]-obstacles[i][0],
obstacles[i][3]-obstacles[i][2],
linewidth=1,edgecolor='k',facecolor='k')
for i in range(len(obstacles))]
goals = [[0.5, 2.0, 7.5, 9.5], # a
[7.5, 9.5, 0.8, 3.0]] # d
rects_gs = [patches.Rectangle((goals[i][0], goals[i][2]),
goals[i][1]-goals[i][0],
goals[i][3]-goals[i][2],
linewidth=1,edgecolor='y',fill=False)
for i in range(len(goals))]
circ_gs = patches.Circle([8.0, 8.0], radius=0.8, linewidth=1,
edgecolor='y', fill=False)
for rect in rects_obs:
ax.add_patch(rect)
for rect in rects_gs:
ax.add_patch(rect)
ax.add_patch(circ_gs)
ax.text((goals[0][0]+goals[0][1])/2.0-0.5, (goals[0][2]+goals[0][3])/2.0, "pickup")
ax.text((goals[1][0]+goals[1][1])/2.0-0.5, (goals[1][2]+goals[1][3])/2.0, "drop")
ax.text(7.8, 7.8, "count")
# # # Plot winning set in 2D plane
# ax.add_collection(
# utils.polycoll_grid_array(winset, eta, True, 'palegoldenrod', 0.7)
# )
# # Plot closed-loop trajectoryies
colors = list(mcolors.TABLEAU_COLORS.keys())
qdiff = np.diff(np.insert(qsim, 0, dba.q0))
qchks = np.argwhere(qdiff != 0).squeeze()
qchks = np.insert(qchks, 0, 0)
qchks = np.append(qchks, qsim.size)
q = dba.q0
for k in range(qchks.size-1):
q = q + qdiff[qchks[k]]
xs = xsim[qchks[k]:qchks[k+1]+1, :]
ax.plot(xs[:, 0], xs[:, 1], color=colors[q])
ax.plot(xsim[0, 0], xsim[0, 1], marker='^',
markerfacecolor='r', markeredgecolor='r')
ax.plot(xsim[-1, 0], xsim[-1, 1], marker='v',
markerfacecolor='g', markeredgecolor='g')
plt.show()
| 4,122 | 1,813 |
#-*- coding:utf-8 -*-
import os
import re
class folder():
def __init__(self,path):
self.path = path
if path[-1] != '/':
self.path += '/'
self.filelist = []
self.get_filelist()
def get_filelist(self):
tmp = os.listdir(self.path)
for test in tmp:
test = self.path + test
if os.path.isfile(test):
self.filelist.append(test)
print 'There are %d files in "%s" folder.' %(len(self.filelist), self.path)
class file():
def __init__(self,filename):
self.filename = filename
with open(filename,'r') as f:
self.raw_data = f.read()
self.hex_data = self.raw_data.encode('hex')
self.SOIMARKER = self.get_OIMARKER('\xff\xd8')
self.EOIMARKER = self.get_OIMARKER('\xff\xd9')
def check_OI(self):
len_SOI = len(re.findall('\xff\xd8',self.raw_data))
len_EOI = len(re.findall('\xff\xd9',self.raw_data))
print "=" * 0x34
print "'%s' has %d SOIMARKER & %d EOIMARKER" %(self.filename, len_SOI, len_EOI)
return len_SOI
def get_OIMARKER(self,sig):
markers = []
OIMARKER = re.finditer(sig,self.raw_data)
for i in OIMARKER: markers.append(i.start())
return markers
if __name__ == "__main__":
import sys
#path = './pictures/'
#folder = folder(path)
folder = folder(sys.argv[1])
path, filelist = folder.path, folder.filelist
markers = ['ffc','ffd','ffe','fff']
JPG = []
if not os.path.isdir('output'):
os.makedirs('output/')
for filename in filelist:
pic = file(filename)
output = filename.split('/')[-1].split('.')[0]
if pic.check_OI():
with open('output/%s.txt' % output,'w') as txt:
fd = pic.SOIMARKER[0]
txt.write("%s => %s\n" %(pic.raw_data[fd:fd+2].encode('hex'), hex(fd)))
start, end = fd * 2 + 4, fd * 2 + 8
while pic.hex_data[start:end-1] in markers:
marker = pic.hex_data[start:end]
txt.write("%s => %s\n" %(marker, hex(start/2)))
start, end = start + 4, end + 4
index = int(pic.hex_data[start:end],16)
start, end = start + index * 2, end + index * 2
if marker == "ffda":
marker = pic.EOIMARKER[0]
if marker < end: marker = pic.EOIMARKER[1]
txt.write("%s => %s\n" %('ffd9', hex(marker)))
print "'%s' is JPG" % filename
JPG.append(filename)
with open('output/%s.jpg' % output, 'w') as restore:
restore.write(pic.raw_data[fd:marker])
else: print "'%s' is JPG but broken"
else: print "'%s' is not JPG" % filename
print "\n",JPG
| 2,394 | 1,111 |
__author__ = 'Scott'
import os
import pygame
SCREEN_WIDTH = 1280
SCREEN_HEIGHT = 720
GAME_TITLE = "Project Infinity"
MAP_COLLISION_LAYER = 2
MAP_DEATH_LAYER = 3
MAP_BACKGROUND_LAYER = 0
MAP_FORGROUND_LAYER = 1
MAP_ENDOFLEVEL_LAYER = 5
MAP_ITEM_LAYER = 4
BACKGROUND_COLOR = (20, 20, 20)
screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
LAST_LEVEL = 1
#Main Character Licensed to Scott Weaver
#Platform tiles CC0
#background music CC0
#Jump Sounds Credit: dklon
pygame.mixer.init()
jump1 = pygame.mixer.Sound('data/audio/jump_01.wav')
jump2 = pygame.mixer.Sound('data/audio/jump_03.wav')
heart = pygame.mixer.Sound('data/audio/upshort.wav')
PLAYERPATH = 'data/ninja/'
IMAGE_PATH =\
{
'playerIdle': [],
'playerDie': [],
'playerFlip': [],
'playerJump': [],
'playerRun': [],
'playerSlide': [],
'playerStun': [],
'playerWallGrab': [],
'playerProjectile': [],
'playerLives': []
}
for i in range(1, 6):
IMAGE_PATH['playerIdle'].append(os.path.join(PLAYERPATH, "idle_0%d.png" %i))
for i in range(1, 5):
IMAGE_PATH['playerDie'].append(os.path.join(PLAYERPATH, "die_0%d.png" %i))
for i in range(1, 7):
IMAGE_PATH['playerFlip'].append(os.path.join(PLAYERPATH, "flip_0%d.png" %i))
for i in range(1, 8):
IMAGE_PATH['playerRun'].append(os.path.join(PLAYERPATH, "run_0%d.png" %i))
for i in range(1, 4):
IMAGE_PATH['playerStun'].append(os.path.join(PLAYERPATH, "stunned_0%d.png" %i))
IMAGE_PATH['playerJump'].append(os.path.join(PLAYERPATH, "jumpDown.png"))
IMAGE_PATH['playerJump'].append(os.path.join(PLAYERPATH, "jumpUp.png"))
IMAGE_PATH['playerWallGrab'].append(os.path.join(PLAYERPATH, "wallGrab.png"))
IMAGE_PATH['playerSlide'].append(os.path.join(PLAYERPATH, "slideDuck.png"))
IMAGE_PATH['playerProjectile'].append(os.path.join(PLAYERPATH, "knife.png"))
IMAGE_PATH['playerLives'].append(os.path.join(PLAYERPATH, "heart.png"))
DATA = \
{
'playerIdle': [],
'playerDie': [],
'playerFlip': [],
'playerJump': [],
'playerRun': [],
'playerSlide':[],
'playerStun':[],
'playerWallGrab':[],
'playerProjectile':[],
'playerLives': []
}
def load_images():
for i in range(0, 5):
DATA['playerIdle'].append(pygame.image.load(IMAGE_PATH['playerIdle'][i]).convert_alpha())
for i in range(0, 4):
DATA['playerDie'].append(pygame.image.load(IMAGE_PATH['playerDie'][i]).convert_alpha())
for i in range(0, 6):
DATA['playerFlip'].append(pygame.image.load(IMAGE_PATH['playerFlip'][i]).convert_alpha())
for i in range(0, 7):
DATA['playerRun'].append(pygame.image.load(IMAGE_PATH['playerRun'][i]).convert_alpha())
for i in range(0, 3):
DATA['playerStun'].append(pygame.image.load(IMAGE_PATH['playerStun'][i]).convert_alpha())
DATA['playerJump'].append(pygame.image.load(IMAGE_PATH['playerJump'][0]).convert_alpha())
DATA['playerJump'].append(pygame.image.load(IMAGE_PATH['playerJump'][1]).convert_alpha())
DATA['playerWallGrab'].append(pygame.image.load(IMAGE_PATH['playerWallGrab'][0]).convert_alpha())
DATA['playerSlide'].append(pygame.image.load(IMAGE_PATH['playerSlide'][0]).convert_alpha())
DATA['playerProjectile'].append(pygame.image.load(IMAGE_PATH['playerProjectile'][0]).convert_alpha())
DATA['playerProjectile'].append(pygame.transform.flip(DATA['playerProjectile'][0], True, False))
DATA['playerLives'].append(pygame.image.load(IMAGE_PATH['playerLives'][0]).convert_alpha())
print "DEBUG IMAGES:", DATA
def get_image(name, frame):
return DATA[name][frame] | 3,656 | 1,427 |
#!/usr/bin/env python
"""
Artificial Intelligence for Humans
Volume 3: Deep Learning and Neural Networks
Python Version
http://www.aifh.org
http://www.jeffheaton.com
Code repository:
https://github.com/jeffheaton/aifh
Copyright 2015 by Jeff Heaton
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.
For more information on Heaton Research copyrights, licenses
and trademarks visit:
http://www.heatonresearch.com/copyright
"""
import scipy.spatial
import numpy as np
import scipy as sp
import sys
class SelfOrganizingMap:
"""
The weights of the output neurons base on the input from the input
neurons.
"""
def __init__(self, input_count, output_count):
"""
The constructor.
:param input_count: Number of input neurons
:param output_count: Number of output neurons
:return:
"""
self.input_count = input_count
self.output_count = output_count
self.weights = np.zeros([self.output_count, self.input_count])
self.distance = sp.spatial.distance.euclidean
def calculate_error(self, data):
bmu = BestMatchingUnit(self)
bmu.reset()
# Determine the BMU for each training element.
for input in data:
bmu.calculate_bmu(input)
# update the error
return bmu.worst_distance / 100.0
def classify(self, input):
if len(input) > self.input_count:
raise Exception("Can't classify SOM with input size of {} "
"with input data of count {}".format(self.input_count, len(input)))
min_dist = sys.maxfloat
result = -1
for i in range(self.output_count):
dist = self.distance.calculate(input, self.weights[i])
if dist < min_dist:
min_dist = dist
result = i
return result
def reset(self):
self.weights = (np.random.rand(self.weights.shape[0], self.weights.shape[1]) * 2.0) - 1
class BestMatchingUnit:
"""
The "Best Matching Unit" or BMU is a very important concept in the training
for a SOM. The BMU is the output neuron that has weight connections to the
input neurons that most closely match the current input vector. This neuron
(and its "neighborhood") are the neurons that will receive training.
This class also tracks the worst distance (of all BMU's). This gives some
indication of how well the network is trained, and thus becomes the "error"
of the entire network.
"""
def __init__(self, som):
"""
Construct a BestMatchingUnit class. The training class must be provided.
:param som: The SOM to evaluate.
"""
# The owner of this class.
self.som = som
# What is the worst BMU distance so far, this becomes the error for the
# entire SOM.
self.worst_distance = 0
def calculate_bmu(self, input):
"""
Calculate the best matching unit (BMU). This is the output neuron that
has the lowest Euclidean distance to the input vector.
:param input: The input vector.
:return: The output neuron number that is the BMU.
"""
result = 0
if len(input) > self.som.input_count:
raise Exception(
"Can't train SOM with input size of {} with input data of count {}.".format(self.som.input_count,
len(input)))
# Track the lowest distance so far.
lowest_distance = float("inf")
for i in range(self.som.output_count):
distance = self.calculate_euclidean_distance(self.som.weights, input, i)
# Track the lowest distance, this is the BMU.
if distance < lowest_distance:
lowest_distance = distance
result = i
# Track the worst distance, this is the error for the entire network.
if lowest_distance > self.worst_distance:
self.worst_distance = lowest_distance
return result
def calculate_euclidean_distance(self, matrix, input, output_neuron):
"""
Calculate the Euclidean distance for the specified output neuron and the
input vector. This is the square root of the squares of the differences
between the weight and input vectors.
:param matrix: The matrix to get the weights from.
:param input: The input vector.
:param outputNeuron: The neuron we are calculating the distance for.
:return: The Euclidean distance.
"""
result = 0
# Loop over all input data.
diff = input - matrix[output_neuron]
return np.sqrt(sum(diff*diff))
class BasicTrainSOM:
"""
This class implements competitive training, which would be used in a
winner-take-all neural network, such as the self organizing map (SOM). This
is an unsupervised training method, no ideal data is needed on the training
set. If ideal data is provided, it will be ignored.
Training is done by looping over all of the training elements and calculating
a "best matching unit" (BMU). This BMU output neuron is then adjusted to
better "learn" this pattern. Additionally, this training may be applied to
other "nearby" output neurons. The degree to which nearby neurons are update
is defined by the neighborhood function.
A neighborhood function is required to determine the degree to which
neighboring neurons (to the winning neuron) are updated by each training
iteration.
Because this is unsupervised training, calculating an error to measure
progress by is difficult. The error is defined to be the "worst", or longest,
Euclidean distance of any of the BMU's. This value should be minimized, as
learning progresses.
Because only the BMU neuron and its close neighbors are updated, you can end
up with some output neurons that learn nothing. By default these neurons are
not forced to win patterns that are not represented well. This spreads out
the workload among all output neurons. This feature is not used by default,
but can be enabled by setting the "forceWinner" property.
"""
def __init__(self, network, learning_rate, training, neighborhood):
# The neighborhood function to use to determine to what degree a neuron
# should be "trained".
self.neighborhood = neighborhood
# The learning rate. To what degree should changes be applied.
self.learning_rate = learning_rate
# The network being trained.
self.network = network
# How many neurons in the input layer.
self.input_neuron_count = network.input_count
# How many neurons in the output layer.
self.output_neuron_count = network.output_count
# Utility class used to determine the BMU.
self.bmu_util = BestMatchingUnit(network)
# Correction matrix.
self.correction_matrix = np.zeros([network.output_count, network.input_count])
# True is a winner is to be forced, see class description, or forceWinners
# method. By default, this is true.
self.force_winner = False
# When used with autodecay, this is the starting learning rate.
self.start_rate = 0
# When used with autodecay, this is the ending learning rate.
self.end_rate = 0
# When used with autodecay, this is the starting radius.
self.start_radius = 0
# When used with autodecay, this is the ending radius.
self.end_radius = 0
# This is the current autodecay learning rate.
self.auto_decay_rate = 0
# This is the current autodecay radius.
self.auto_decay_radius = 0
# The current radius.
self.radius = 0
# Training data.
self.training = training
def _apply_correction(self):
"""
Loop over the synapses to be trained and apply any corrections that were
determined by this training iteration.
"""
np.copyto(self.network.weights, self.correction_matrix)
def auto_decay(self):
"""
Should be called each iteration if autodecay is desired.
"""
if self.radius > self.end_radius:
self.radius += self.auto_decay_radius
if self.learning_rate > self.end_rate:
self.learning_rate += self.auto_decay_rate
self.neighborhood.radius = self.radius
def copy_input_pattern(self, matrix, output_neuron, input):
"""
Copy the specified input pattern to the weight matrix. This causes an
output neuron to learn this pattern "exactly". This is useful when a
winner is to be forced.
:param matrix: The matrix that is the target of the copy.
:param output_neuron: The output neuron to set.
:param input: The input pattern to copy.
"""
matrix[output_neuron, :] = input
def decay(self, decay_rate, decay_radius):
"""
Decay the learning rate and radius by the specified amount.
:param decay_rate: The percent to decay the learning rate by.
:param decay_radius: The percent to decay the radius by.
"""
self.radius *= (1.0 - decay_radius)
self.learning_rate *= (1.0 - decay_rate)
self.neighborhood.radius = self.radius
def _determine_new_weight(self, weight, input, currentNeuron, bmu):
"""
Determine the weight adjustment for a single neuron during a training
iteration.
:param weight: The starting weight.
:param input: The input to this neuron.
:param currentNeuron: The neuron who's weight is being updated.
:param bmu: The neuron that "won", the best matching unit.
:return: The new weight value.
"""
return weight \
+ (self.neighborhood.fn(currentNeuron, bmu) \
* self.learning_rate * (input - weight))
def _force_winners(self, matrix, won, least_represented):
"""
Force any neurons that did not win to off-load patterns from overworked
neurons.
:param matrix: An array that specifies how many times each output neuron has "won".
:param won: The training pattern that is the least represented by this neural network.
:param least_represented: The synapse to modify.
:return: True if a winner was forced.
"""
max_activation = float("-inf")
max_activation_neuron = -1
output = self.compute(self.network, self.least_represented)
# Loop over all of the output neurons. Consider any neurons that were
# not the BMU (winner) for any pattern. Track which of these
# non-winning neurons had the highest activation.
for output_neuron in range(len(won)):
# Only consider neurons that did not "win".
if won[output_neuron] == 0:
if (max_activation_neuron == -1) \
or (output[output_neuron] > max_activation):
max_activation = output[output_neuron]
max_activation_neuron = output_neuron
# If a neurons was found that did not activate for any patterns, then
# force it to "win" the least represented pattern.
if max_activation_neuron != -1:
self.copy_input_pattern(matrix, max_activation_neuron, least_represented)
return True
else:
return False
def iteration(self):
"""
Perform one training iteration.
"""
# Reset the BMU and begin this iteration.
self.bmu_util.reset()
won = [0] * self.output_neuron_count
least_represented_activation = float("inf")
least_represented = None
# Reset the correction matrix for this synapse and iteration.
self.correctionMatrix.clear()
# Determine the BMU for each training element.
for input in self.training:
bmu = self.bmu_util.calculate_bmu(input)
won[bmu] += 1
# If we are to force a winner each time, then track how many
# times each output neuron becomes the BMU (winner).
if self.force_winner:
# Get the "output" from the network for this pattern. This
# gets the activation level of the BMU.
output = self.compute(self.network, input)
# Track which training entry produces the least BMU. This
# pattern is the least represented by the network.
if output[bmu] < least_represented_activation:
least_represented_activation = output[bmu]
least_represented = input.getInput()
self.train(bmu, self.network.getWeights(), input.getInput())
if self.force_winner:
# force any non-winning neurons to share the burden somewhat
if not self.force_winners(self.network.weights, won, least_represented):
self.apply_correction()
else:
self.apply_correction()
def set_auto_decay(self, planned_iterations, start_rate, end_rate, start_radius, end_radius):
"""
Setup autodecay. This will decrease the radius and learning rate from the
start values to the end values.
:param planned_iterations: The number of iterations that are planned. This allows the
decay rate to be determined.
:param start_rate: The starting learning rate.
:param end_rate: The ending learning rate.
:param start_radius: The starting radius.
:param end_radius: The ending radius.
"""
self.start_rate = start_rate
self.end_rate = end_rate
self.start_radius = start_radius
self.end_radius = end_radius
self.auto_decay_radius = (end_radius - start_radius) / planned_iterations
self.auto_decay_rate = (end_rate - start_rate) / planned_iterations
self.set_params(self.start_rate, self.start_radius)
def set_params(self, rate, radius):
"""
Set the learning rate and radius.
:param rate: The new learning rate.
:param radius:
:return: The new radius.
"""
self.radius = radius
self.learning_rate = rate
self.neighborhood.radius = radius
def get_status(self):
"""
:return: A string display of the status.
"""
result = "Rate="
result += str(self.learning_rate)
result += ", Radius="
result += str(self.radius)
return result
def _train(self, bmu, matrix, input):
"""
Train for the specified synapse and BMU.
:param bmu: The best matching unit for this input.
:param matrix: The synapse to train.
:param input: The input to train for.
:return:
"""
# adjust the weight for the BMU and its neighborhood
for output_neuron in range(self.output_neuron_count):
self._train_pattern(matrix, input, output_neuron, bmu)
def _train_pattern(self, matrix, input, current, bmu):
"""
Train for the specified pattern.
:param matrix: The synapse to train.
:param input: The input pattern to train for.
:param current: The current output neuron being trained.
:param bmu: The best matching unit, or winning output neuron.
"""
for input_neuron in range(self.input_neuron_count):
current_weight = matrix[current][input_neuron]
input_value = input[input_neuron]
new_weight = self._determine_new_weight(current_weight,
input_value, current, bmu)
self.correction_matrix[current][input_neuron] = new_weight
def train_single_pattern(self, pattern):
"""
Train the specified pattern. Find a winning neuron and adjust all neurons
according to the neighborhood function.
:param pattern: The pattern to train.
"""
bmu = self.bmu_util.calculate_bmu(pattern)
self._train(bmu, self.network.weights, pattern)
self._apply_correction()
def compute(self, som, input):
"""
Calculate the output of the SOM, for each output neuron. Typically,
you will use the classify method instead of calling this method.
:param som: The input pattern.
:param input: The output activation of each output neuron.
:return:
"""
result = np.zeros(som.output_count)
for i in range(som.output_count):
optr = som.weights[i]
matrix_a = np.zeros([input.length,1])
for j in range(len(input)):
matrix_a[0][j] = input[j]
matrix_b = np.zeros(1,input.length)
for j in range(len(optr)):
matrix_b[0][j] = optr[j]
result[i] = np.dot(matrix_a, matrix_b)
return result
| 17,655 | 4,806 |
import logging
import asyncio
from aiogram import Bot, Dispatcher
from aiogram.contrib.fsm_storage.memory import MemoryStorage
import config
loop = asyncio.get_event_loop()
bot = Bot(token=config.token, parse_mode='HTML')
storage = MemoryStorage()
dp = Dispatcher(bot, storage=storage)
logging.basicConfig(format=u'%(filename)s [LINE:%(lineno)d] #%(levelname)-8s [%(asctime)s] %(message)s',
level=logging.INFO,
)
| 458 | 152 |
import math
from animator.entity import Entity
from animator.constant import *
__all__ = ["Circle", "Ellipse", "Rect", "Square", "Poly"]
class Circle(Entity):
"""
Draws a circle on the scene.
:param r:
The radius of the circle. Default is 0
"""
def __init__(self, r=UNIT, **kwargs):
super(Circle, self).__init__(**kwargs)
self.r = r
def on_draw(self):
self.scene.ctx.arc(0, 0, self.r, 0, TWO_PI)
# TODO: How to handle transformation?
def _get_bounding_box(self, transformed=True):
r = self.r
return super()._get_bounding_box() if transformed else (r, r, r, r)
def _get_length(self):
return TWO_PI * self.r
class Ellipse(Entity):
def __init__(self, rx=UNIT, ry=None, **kwargs):
super(Ellipse, self).__init__(**kwargs)
if ry is None:
ry = rx
self.rx, self.ry = rx, ry
def on_draw(self):
self.scene.ctx.save()
self.scene.ctx.scale(1, self.ry / self.rx)
self.scene.ctx.arc(0, 0, self.rx, 0, TWO_PI)
self.scene.ctx.restore()
# TODO: How to handle transformation?
def _get_bounding_box(self, transformed=True):
rx, ry = self.rx, self.ry
return super()._get_bounding_box() if transformed else (rx, ry, rx, ry)
def _get_length(self):
a, b = self.rx, self.ry
h = 3 * ((a - b) / (a + b)) ** 2
return PI * (a + b) * (1 + h / (10 + math.sqrt(4 - h)))
class Rect(Entity):
def __init__(self, w=2 * UNIT, h=None, **kwargs):
super(Rect, self).__init__(**kwargs)
if h is None:
h = w
self.w = w
self.h = h
def on_draw(self):
self.scene.ctx.rectangle(-self.w / 2, -self.h / 2, self.w, self.h)
# TODO: How to handle transformation?
def _get_bounding_box(self, transformed=True):
w, h = self.w / 2, self.h / 2
return super()._get_bounding_box() if transformed else (w, h, w, h)
def _get_length(self):
return 2 * (self.w + self.h)
class Square(Rect):
def __init__(self, s=2 * UNIT, **kwargs):
super(Square, self).__init__(s, s, **kwargs)
class Poly(Entity):
def __init__(self, n=3, r=UNIT, inradius=False, **kwargs):
super(Poly, self).__init__(**kwargs)
if inradius:
r /= math.cos(PI / n)
self.n, self.r = n, r
self.points = []
max_x, max_y = 0, 0
dt = -PI * (1 / n + 0.5 - (n % 2) / n)
for i in range(n):
x, y = math.cos(TWO_PI / n * i + dt) * r, math.sin(TWO_PI / n * i + dt) * r
max_x, max_y = max(max_x, x), max(max_y, y)
self.points.append([x, y])
self.mx, self.my = max_x, max_y
def on_draw(self):
self.scene.ctx.move_to(*self.points[0])
for i in range(1, self.n):
self.scene.ctx.line_to(*self.points[i])
self.scene.ctx.close_path()
# TODO: How to handle transformation?
def _get_bounding_box(self, transformed=True):
return super()._get_bounding_box() if transformed else (self.mx, self.my, self.mx, self.my)
def _get_length(self):
return 2 * self.n * self.r * math.sin(PI / self.n)
# TODO: Implement Star?
# class Star(Entity):
# def __init__(self, n=5, outradius=UNIT, inradius=None, **kwargs):
# super(Star, self).__init__(**kwargs)
# if inradius is None:
# ct = math.cos(HALF_PI / n * ((n - 1) // 2))
# inradius = outradius * (2 * ct - 1 / ct)
# self.n, self.out_r, self.in_r = n, outradius, inradius
# self.points = []
# max_x, max_y = 0, 0
# dt = -PI * (1 / n + 0.5 - (n % 2) / n)
# for i in range(n):
# x, y = math.cos(TWO_PI / n * i + dt) * outradius, math.sin(TWO_PI / n * i + dt) * outradius
# max_x, max_y = max(max_x, x), max(max_y, y)
# self.points.append([x, y])
# x, y = math.cos(TWO_PI / n * (i + .5) + dt) * inradius, math.sin(TWO_PI / n * (i + .5) + dt) * inradius
# self.points.append([x, y])
# self.mx, self.my = max_x, max_y
#
# def on_draw(self):
# self.scene.ctx.move_to(*self.points[0])
# for i in range(1, 2 * self.n):
# self.scene.ctx.line_to(*self.points[i])
# self.scene.ctx.close_path()
#
# # TODO: How to handle transformation?
# def _get_bounding_box(self, transformed=True):
# return super()._get_bounding_box() if transformed else (self.mx, self.my, self.mx, self.my)
#
# def _get_length(self):
# return 2 * self.n * math.sqrt(self.in_r ** 2 + self.out_r ** 2 -
# 2 * self.in_r * self.out_r * math.cos(PI / self.n))
| 4,729 | 1,789 |
from Tkinter import *
from hard_coded_texts import get_project_name
class Header(Frame):
"""
Generic header template class which is used for construction of different screens
"""
def __init__(self, parent_window):
Frame.__init__(self, parent_window)
# Configure the window
self.configure(background="white")
# Create the header
header = Label(self, text=get_project_name(), width=55, font=("Arial", 20), height=5)
header.grid()
header.configure(background="white")
class CustomButton(Button):
"""
Generic button template to use them throughout the screens
"""
def __init__(self, parent_window, text, _function, row, columnspan=None, sticky=None, column=None, height=2,
foreground="black"):
Button.__init__(self, parent_window, command=_function, text=text, font=("Arial", 15), borderwidth=0,
height=height, highlightthickness=0, background="white", foreground=foreground)
self.grid(row=row, columnspan=columnspan, sticky=sticky, column=column)
class CustomLabel(Label):
"""
Generic label template to use them throughout the screens
"""
def __init__(self, parent_window, text, row, column, rowspan=None, columnspan=None, sticky=None):
Label.__init__(self, parent_window, text=text, font=("Arial", 15))
self.grid(row=row, column=column, rowspan=rowspan, columnspan=columnspan, sticky=sticky)
class CustomRadiobutton(Radiobutton):
"""
Generic radio button template to use them throughout the screens
"""
def __init__(self, parent_window, text, row, column, sticky, variable, value):
Radiobutton.__init__(self, parent_window, text=text, font=("Arial", 13), variable=variable, value=value)
self.grid(row=row, column=column, sticky=sticky)
| 1,855 | 538 |
#!python
def linear_search(array, item):
"""return the first index of item in array or None if item is not found"""
# implement linear_search_iterative and linear_search_recursive below, then
# change this to call your implementation to verify it passes all tests
# return linear_search_iterative(array, item)
return linear_search_recursive(array, item)
def linear_search_iterative(array, item):
# loop over all array values until item is found
for index, value in enumerate(array):
if item == value:
return index # found
return None # not found
def linear_search_recursive(array, item, index=0):
# TODO: implement linear search recursively here
''' Time complexity is O(n) '''
# check if item is in array
if array[index] == item:
return index
# if item is not in array retun NONE
if index == len(array) -1 and array[index] != item:
return None
index += 1
return linear_search_recursive(array, item, index)
# save the index to a variable
# create a condition to check if array[index] == item
# if yes return index
#otherwise call the function again and update the index
# create another condition to check if the index is at the last item in the list
# once implemented, change linear_search to call linear_search_recursive
# to verify that your recursive implementation passes all tests
def binary_search(array, item):
"""return the index of item in sorted array or None if item is not found"""
# # implement binary_search_iterative and binary_search_recursive below, then
# # change this to call your implementation to verify it passes all tests
# return binary_search_iterative(array, item)
return binary_search_recursive(array, item)
def binary_search_iterative(array, item):
# TODO: implement binary search iteratively here
''' Time complexity is O(log n) '''
# Sort the array
array = sorted(array)
# set the left value to the first index of the list which is zero
left = 0
# set the right to the last index in the array
right = len(array) - 1
while left <= right:
# get the middle index of the array
middle_value = (left + right) // 2
# if the middle value is less than item than move to the left index to the right once
if array[middle_value] < item:
left = middle_value + 1
# if the item is greater than the middle index move the right to the left once
if array[middle_value] > item:
right = middle_value - 1
# if the middle value == the target value return the middle value index
if array[middle_value] == item:
return middle_value
# if the item is not in the array return NONE
return None
# reasign array to sorted array
# only sort once
# create a variable named median and set it to int(len(array) / 2)
# once implemented, change binary_search to call binary_search_iterative
# to verify that your iterative implementation passes all tests
def binary_search_recursive(array, item, left=None, right=None):
# TODO: implement binary search recursively here
''' Time complexity is O(log n) '''
# Sort the array
array = sorted(array)
# get the middle index of the array
if left == None and right == None:
left = 0
right = len(array) -1
middle_value = (left + right) // 2
print('MIDDLE VALUE', middle_value)
if left > right:
return None
# if the middle value == the target value return the middle value index
if array[middle_value] == item:
print('---MIDDLE Value ---',middle_value)
return middle_value
# if the middle value is less than item than move to the left index to the right once
if array[middle_value] < item:
left = middle_value + 1
print('---LEFT----', left)
return binary_search_recursive(array, item, left, right)
# if the item is greater than the middle index move the right to the left once
if array[middle_value] > item:
right = middle_value - 1
print('----RIGHT 1----', right)
return binary_search_recursive(array, item, left, right)
# once implemented, change binary_search to call binary_search_recursive
# to verify that your recursive implementation passes all tests
| 4,479 | 1,232 |
import unittest
from collections import Counter
import copy
import flask
import json
from panoptes_aggregation.reducers.survey_reducer import process_data, survey_reducer
from panoptes_aggregation.reducers.test_utils import extract_in_data
extracted_data = [
{'answers_howmanyanimalsdoyousee': {'1': 1.0}, 'answers_whatistheanimalsdoing': {'grooming': 1.0}, 'choice': 'raccoon'},
{'answers_howmanyanimalsdoyousee': {'1': 1.0}, 'answers_whatistheanimalsdoing': {'standing': 1.0}, 'choice': 'raccoon'},
{'answers_howmanyanimalsdoyousee': {'1': 1.0}, 'answers_whatistheanimalsdoing': {'standing': 1.0}, 'answers_clickwowifthisasanespeciallyawesomephoto': {'wow': 1.0}, 'choice': 'raccoon'},
{'answers_howmanyanimalsdoyousee': {'1': 1.0}, 'answers_whatistheanimalsdoing': {'standing': 1.0}, 'choice': 'raccoon'},
{'answers_howmanyanimalsdoyousee': {'1': 1.0}, 'answers_whatistheanimalsdoing': {'interacting': 1.0, 'grooming': 1.0}, 'answers_clickwowifthisasanespeciallyawesomephoto': {'wow': 1.0}, 'choice': 'blackbear'},
{'answers_howmanyanimalsdoyousee': {'1': 1.0}, 'answers_whatistheanimalsdoing': {'standing': 1.0}, 'choice': 'blackbear'},
{'answers_howmanyanimalsdoyousee': {'1': 1.0}, 'answers_whatistheanimalsdoing': {'standing': 1.0}, 'answers_clickwowifthisasanespeciallyawesomephoto': {'wow': 1.0}, 'choice': 'blackbear'},
{'answers_howmanyanimalsdoyousee': {'1': 1.0}, 'answers_whatistheanimalsdoing': {'grooming': 1.0}, 'choice': 'blackbear'}
]
processed_data = {
'blackbear': [
{
'answers_clickwowifthisasanespeciallyawesomephoto': Counter({'wow': 1}),
'answers_howmanyanimalsdoyousee': Counter({'1': 1}),
'answers_whatistheanimalsdoing': Counter({'interacting': 1, 'grooming': 1})
},
{
'answers_howmanyanimalsdoyousee': Counter({'1': 1}),
'answers_whatistheanimalsdoing': Counter({'standing': 1})
},
{
'answers_clickwowifthisasanespeciallyawesomephoto': Counter({'wow': 1}),
'answers_howmanyanimalsdoyousee': Counter({'1': 1}),
'answers_whatistheanimalsdoing': Counter({'standing': 1})
},
{
'answers_howmanyanimalsdoyousee': Counter({'1': 1}),
'answers_whatistheanimalsdoing': Counter({'grooming': 1})
}
],
'raccoon': [
{
'answers_howmanyanimalsdoyousee': Counter({'1': 1}),
'answers_whatistheanimalsdoing': Counter({'grooming': 1})
},
{
'answers_howmanyanimalsdoyousee': Counter({'1': 1}),
'answers_whatistheanimalsdoing': Counter({'standing': 1})
},
{
'answers_clickwowifthisasanespeciallyawesomephoto': Counter({'wow': 1}),
'answers_howmanyanimalsdoyousee': Counter({'1': 1}),
'answers_whatistheanimalsdoing': Counter({'standing': 1})
},
{
'answers_howmanyanimalsdoyousee': Counter({'1': 1}),
'answers_whatistheanimalsdoing': Counter({'standing': 1})
}
]
}
reduced_data = [
{
'choice': 'raccoon',
'total_vote_count': 8,
'choice_count': 4,
'answers_howmanyanimalsdoyousee': {
'1': 4
},
'answers_whatistheanimalsdoing': {
'standing': 3,
'grooming': 1
},
'answers_clickwowifthisasanespeciallyawesomephoto': {
'wow': 1
}
},
{
'choice': 'blackbear',
'total_vote_count': 8,
'choice_count': 4,
'answers_howmanyanimalsdoyousee': {
'1': 4
},
'answers_whatistheanimalsdoing': {
'standing': 2,
'grooming': 2,
'interacting': 1
},
'answers_clickwowifthisasanespeciallyawesomephoto': {
'wow': 2
}
}
]
class TestCountSurvey(unittest.TestCase):
def setUp(self):
self.maxDiff = None
self.extracted_data = copy.deepcopy(extracted_data)
self.processed_data = copy.deepcopy(processed_data)
self.reduced_data = copy.deepcopy(reduced_data)
def test_process_data(self):
result_data, result_count = process_data(self.extracted_data)
self.assertEqual(result_count, len(self.extracted_data))
self.assertDictEqual(result_data, self.processed_data)
def test_count_vote(self):
result = survey_reducer._original((self.processed_data, len(self.extracted_data)))
self.assertCountEqual(result, self.reduced_data)
def test_survey_reducer(self):
result = survey_reducer(self.extracted_data)
self.assertCountEqual(result, self.reduced_data)
def test_survey_reducer_request(self):
app = flask.Flask(__name__)
request_kwargs = {
'data': json.dumps(extract_in_data(self.extracted_data)),
'content_type': 'application/json'
}
with app.test_request_context(**request_kwargs):
result = survey_reducer(flask.request)
self.assertCountEqual(result, self.reduced_data)
if __name__ == '__main__':
unittest.main()
| 5,155 | 1,831 |
import numpy as np
from ... import Globals
from .ReadData import ReadData
import os
import RecarrayTools as RT
def _DateStrToDateUT(s):
'''
convert date on the format YYYY-MM-DDThh:mm:ss.sss to an integer date
and a floating point time.
'''
Y = np.array([np.int32(x[0:4]) for x in s])
M = np.array([np.int32(x[5:7]) for x in s])
D = np.array([np.int32(x[8:10]) for x in s])
h = np.array([np.float32(x[11:13]) for x in s])
m = np.array([np.float32(x[14:16]) for x in s])
s = np.array([np.float32(x[17:]) for x in s])
Date = (Y*10000 + M*100 + D).astype('int32')
ut = (h + m/60.0 + s/3600.0).astype('float32')
return Date,ut
def ConvertData():
'''
Convert the James et al 2020 data to binaries
'''
#create the output dtype
dtype = [ ('Date','int32'),
('ut','float32'),
('nk','float32'),
('tk','float32'),
('K','float32'),
('SplitProb','float32',(8,)),
('Prob','float32'),
('SplitClass','int8',(8,)),
('Class','int8')]
#read in the data file
data = ReadData()
#create a recarray
out = np.recarray(data.size,dtype=dtype)
#convert dates and times
out.Date,out.ut = _DateStrToDateUT(data.UT)
#copy the other fields across
out.nk = data.Density
out.tk = data.Temperature
out.K = data.Kappa
for i in range(0,8):
out.SplitProb[:,i] = data['P{:d}'.format(i)].astype('float32')
out.SplitClass[:,i] = data['Class{:d}'.format(i)].astype('int8')
out.Prob = data.P
out.Class = data.Class
#find the unique dates
ud = np.unique(out.Date)
#create the output directory
outdir = Globals.MessPath + 'FIPS/ANN/bin/'
if not os.path.isdir(outdir):
os.system('mkdir -pv '+outdir)
#file name format
fnfmt = outdir + '{:08d}.bin'
#loop through dates, saving a recarray file for each one
for i in range(ud.size):
use = np.where(out.Date == ud[i])[0]
fname = fnfmt.format(ud[i])
RT.SaveRecarray(out[use],fname)
| 1,898 | 870 |
# Generated by Django 2.2.8 on 2020-01-23 06:58
from django.conf import settings
from django.db import migrations, models
import tinymce.models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('libapp', '0009_comment'),
]
operations = [
migrations.CreateModel(
name='Notification',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=200)),
('notification', tinymce.models.HTMLField()),
('user', models.ManyToManyField(blank=True, related_name='notification', to=settings.AUTH_USER_MODEL)),
],
),
]
| 812 | 244 |
import csv
import matplotlib.pyplot as plt
import numpy as np
def index_sizes():
fp = open("./index_size.csv")
x = csv.reader(fp, delimiter='\t')
sizes = []
for line in x:
size = float(line[0].strip()[:-1])
sizes.append(size)
temp = sorted(sizes[:-1])
nodes = [i for i in range(100, 5001, 100)]
f = plt.figure()
plt.xlabel("Number of node-color pairs stored")
plt.ylabel("Size of partial index(in MBs)")
plt.plot(nodes, temp)
plt.show()
f.savefig("../figures/index_sizes.pdf", bbox_inches='tight')
def MC_size_dependence():
fp = open("./MC_analysis.csv", 'r')
x = csv.reader(fp)
times = [int(i[1]) for i in x]
p = []
for i in range(0, len(times), 100):
p.append(np.mean(times[i:i + 100]))
parts = [i for i in range(10, 501, 10)]
print(p)
plt.plot(parts, p)
plt.xlabel("Number of pairs stored")
plt.ylabel("Average time in ms")
plt.title("Variation of query times with size of index stored")
plt.show()
def pre_process_time():
fp1 = open("./TC_pre_pro.txt", 'r')
fp2 = open("./MC_pre_pro.txt", 'r')
nodes = [i for i in range(10, 21, 2)]
f1 = csv.reader(fp1)
f2 = csv.reader(fp2)
p2 = [[]] * 5
p1 = [int(i[0]) for i in f1]
p2_temp = [int(i[0]) for i in f2]
print(p2_temp)
for i in range(5):
p2[i] = [p2_temp[j] / 20 for j in range(i, len(p2_temp), 5)]
f = plt.figure()
plt.plot(nodes, p1, label="Complete transitive closure")
for i in range(5):
plt.plot(nodes, p2[i], label=str((i + 1) * 10) + "% pairs computed")
plt.xlabel("|V|(in thousands)")
plt.ylabel("Time taken to build table(in ms)")
plt.title("Comparision of pre-processing times for Algorithm 1 & 3")
plt.legend()
plt.show()
f.savefig("../figures/pre_pro_10iter_MC.pdf", bbox_inches='tight')
def hits_vs_miss():
fp = csv.reader(open("./MC_size_dependence.csv", 'r'))
tmp = list(fp)
lines = [i for i in tmp if i[0].find("Time") == -1]
T = []
H = []
M = []
for i in range(0, len(lines), 5):
times = [int(lines[i + j][1]) for j in range(5)]
T.append(sum(times) / 5)
hits = [int(lines[i + j][2]) for j in range(5)]
H.append(sum(hits) / 5)
misses = [int(lines[i + j][3]) for j in range(5)]
M.append(sum(misses) / 5)
# print(T)
# print(H)
# print(M)
X = [6000, 12000, 18000, 24000, 30000]
plt.subplot(1, 2, 1)
plt.plot(X, H, label="Hits")
plt.plot(X, M, label="Misses")
plt.xlabel("Number of node-color pairs stored")
plt.ylabel("Number of hits/misses")
plt.legend()
plt.subplot(1, 2, 2)
plt.plot(X, T, label="Query Times")
plt.xlabel("Number of node-color pairs stored")
plt.ylabel("Time in ms")
plt.title("Query times")
plt.show()
def f(r):
timings = []
x = []
count = 0
for line in r:
x.append(int(line[1]))
count += 1
if count == 20:
timings.append(sum(x) / 20)
x = []
count = 0
return timings
def edge_size():
f1 = open("./data_algo1.csv", 'r')
f2 = open("./data_algo2.csv", 'r')
f3 = open("./data_algo3.csv", 'r')
r1 = csv.reader(f1)
r2 = csv.reader(f2)
r3 = csv.reader(f3)
x1 = f(r1)
x2 = f(r2)
x3 = f(r3)
x1[3] = x1[3] / 100
print(x1)
print(x2)
print(x3)
x = [2, 3, 4, 5, 6]
fig = plt.figure()
plt.plot(x, x1, label="Full Transitive Closure")
plt.plot(x, x2, label="Partial Transitive Closure")
plt.plot(x[:3], x3[:3], label="BFS")
plt.legend()
plt.xlabel("Edge-Node Ratio")
plt.ylabel("Average Time taken for query in milliseconds")
plt.show()
fig.savefig("../figures/edge_variation.pdf")
# pre_process_time()
# hits_vs_miss()
# MC_size_dependence()
# edge_size()
index_sizes()
| 3,891 | 1,639 |
# https://github.com/JonathanNickerson/talon_voice_user_scripts
# jsc added indent/outdent and simplified jolt
from talon.voice import Key, press, Str, Context
ctx = Context('generic_editor') # , bundle='com.microsoft.VSCode')
numeral_map = dict((str(n), n) for n in range(0, 20))
for n in [20, 30, 40, 50, 60, 70, 80, 90]:
numeral_map[str(n)] = n
numeral_map["oh"] = 0 # synonym for zero
numerals = ' (' + ' | '.join(sorted(numeral_map.keys())) + ')+'
optional_numerals = ' (' + ' | '.join(sorted(numeral_map.keys())) + ')*'
def text_to_number(words):
tmp = [str(s).lower() for s in words]
words = [parse_word(word) for word in tmp]
result = 0
factor = 1
for word in reversed(words):
if word not in numerals:
raise Exception('not a number')
result = result + factor * int(numeral_map[word])
factor = 10 * factor
return result
def parse_word(word):
word = word.lstrip('\\').split('\\', 1)[0]
return word
def jump_to_bol(m):
line = text_to_number(m)
press('cmd-l')
Str(str(line))(None)
press('enter')
def jump_to_end_of_line():
press('cmd-right')
def jump_to_beginning_of_text():
press('cmd-left')
def jump_to_nearly_end_of_line():
press('left')
def jump_to_bol_and(then):
def fn(m):
if len(m._words) > 1:
jump_to_bol(m._words[1:])
else:
press('ctrl-a')
press('cmd-left')
then()
return fn
def jump_to_eol_and(then):
def fn(m):
if len(m._words) > 1:
jump_to_bol(m._words[1:])
press('cmd-right')
then()
return fn
def toggle_comments():
# works in VSCode with Finnish keyboard layout
# press('cmd-shift-7')
# does not work in VSCode, see https://github.com/talonvoice/talon/issues/3
press('cmd-/')
def snipline():
press('shift-cmd-right')
press('delete')
press('delete')
press('ctrl-a')
press('cmd-left')
keymap = {
'sprinkle' + optional_numerals: jump_to_bol,
'spring' + optional_numerals: jump_to_eol_and(jump_to_beginning_of_text),
'dear' + optional_numerals: jump_to_eol_and(lambda: None),
'smear' + optional_numerals: jump_to_eol_and(jump_to_nearly_end_of_line),
'trundle' + optional_numerals: jump_to_bol_and(toggle_comments),
'jolt': Key('ctrl-a cmd-left shift-down cmd-c down cmd-v' ), # jsc simplified
'snipline' + optional_numerals: jump_to_bol_and(snipline),
# NB these do not work properly if there is a selection
'snipple': Key('shift-cmd-left delete'),
'snipper': Key('shift-cmd-right delete'),
'shackle': Key('cmd-right shift-cmd-left'),
'bracken': [Key('cmd-shift-ctrl-right')],
'shockey': Key('ctrl-a cmd-left enter up'),
'shockoon': Key('cmd-right enter'),
'sprinkoon' + numerals: jump_to_eol_and(lambda: press('enter')),
'olly': Key('cmd-a'),
# jsc added
'(indent | shabble)': Key('cmd-['),
'(outdent | shabber)': Key('cmd-]'),
}
ctx.keymap(keymap)
| 3,022 | 1,149 |
# setup.py
# Author: Thomas MINIER - MIT License 2017-2018
from setuptools import setup, Extension
from os import listdir
import pybind11
import distutils
import platform
__pyhdt_version__ = "1.2.1"
with open('README.rst') as file:
long_description = file.read()
def list_files(path, extension=".cpp", exclude="S.cpp"):
"""List paths to all files that ends with a given extension"""
return ["%s/%s" % (path, f) for f in listdir(path) if f.endswith(extension) and (not f.endswith(exclude))]
# pyHDT source files
sources = [
"src/hdt.cpp",
"src/hdt_document.cpp",
"src/triple_iterator.cpp",
"src/tripleid_iterator.cpp",
"src/join_iterator.cpp"
]
# HDT source files
sources += list_files("serd-0.30.0/src/", extension=".c")
sources += list_files("hdt-cpp-1.3.2/libcds/src/static/bitsequence")
sources += list_files("hdt-cpp-1.3.2/libcds/src/static/coders")
sources += list_files("hdt-cpp-1.3.2/libcds/src/static/mapper")
sources += list_files("hdt-cpp-1.3.2/libcds/src/static/sequence")
sources += list_files("hdt-cpp-1.3.2/libcds/src/static/permutation")
sources += list_files("hdt-cpp-1.3.2/libcds/src/utils")
sources += list_files("hdt-cpp-1.3.2/libhdt/src/bitsequence")
sources += list_files("hdt-cpp-1.3.2/libhdt/src/dictionary")
sources += list_files("hdt-cpp-1.3.2/libhdt/src/hdt")
sources += list_files("hdt-cpp-1.3.2/libhdt/src/header")
sources += list_files("hdt-cpp-1.3.2/libhdt/src/huffman")
sources += list_files("hdt-cpp-1.3.2/libhdt/src/libdcs")
sources += list_files("hdt-cpp-1.3.2/libhdt/src/libdcs/fmindex")
sources += list_files("hdt-cpp-1.3.2/libhdt/src/rdf")
sources += list_files("hdt-cpp-1.3.2/libhdt/src/sequence")
sources += list_files("hdt-cpp-1.3.2/libhdt/src/triples")
sources += list_files("hdt-cpp-1.3.2/libhdt/src/util")
sources += list_files("hdt-cpp-1.3.2/libhdt/src/sparql")
# pybind11 + pyHDT + libcds + HDT-lib headers
include_dirs = [
pybind11.get_include(),
pybind11.get_include(True),
"include/",
"hdt-cpp-1.3.2/libhdt/include/",
"hdt-cpp-1.3.2/libhdt/src/dictionary/",
"hdt-cpp-1.3.2/libhdt/src/sparql/",
"hdt-cpp-1.3.2/libcds/include/",
"hdt-cpp-1.3.2/libcds/src/static/bitsequence",
"hdt-cpp-1.3.2/libcds/src/static/coders",
"hdt-cpp-1.3.2/libcds/src/static/mapper",
"hdt-cpp-1.3.2/libcds/src/static/permutation",
"hdt-cpp-1.3.2/libcds/src/static/sequence",
"hdt-cpp-1.3.2/libcds/src/utils",
"serd-0.30.0"
]
# Need to build in c++11 minimum
# TODO add a check to use c++14 or c++17 if available
extra_compile_args_macos = ["-std=c++11", "-DHAVE_SERD", "-DHAVE_POSIX_MEMALIGN"]
extra_compile_args_win = ["-DHAVE_SERD", "-DWIN32", "-D_AMD64_", "-DUNICODE"]
plaf = platform.system()
if plaf == "Windows":
extra_compile_args = extra_compile_args_win
elif plaf == "Darwin":
extra_compile_args = extra_compile_args_macos
else:
extra_compile_args = ["-std=c++11", "-DHAVE_SERD", "-DHAVE_POSIX_MEMALIGN"]
# build HDT extension
hdt_extension = Extension("hdt", sources=sources, include_dirs=include_dirs,
extra_compile_args=extra_compile_args, language='c++')
# monkey patch the distutils compiler to enable compilation of the Serd parser source
# it is C, and the C++11 compile argument is incompatible
c = distutils.ccompiler.new_compiler
def wrapped_new_compiler_fn(*args, **kwargs):
compiler = c(*args, **kwargs)
c_c = compiler._compile
def wrapped_compiler_compile(obj, src, ext, cc_args, extra_postargs, pp_opts):
if ext == ".c":
return c_c(obj, src, ext, cc_args, [ "-DHAVE_SERD", "-std=c99" ], pp_opts)
else:
return c_c(obj, src, ext, cc_args, extra_postargs, pp_opts)
compiler._compile = wrapped_compiler_compile
return compiler
distutils.ccompiler.new_compiler = wrapped_new_compiler_fn
setup(
name="hdt",
version=__pyhdt_version__,
author="Thomas Minier",
author_email="thomas.minier@univ-nantes.fr",
url="https://github.com/Callidon/pyHDT",
description="Read and query HDT document with ease in Python",
long_description=long_description,
keywords=["hdt", "rdf", "semantic web", "search"],
license="MIT",
install_requires=['pybind11==2.2.4'],
ext_modules=[hdt_extension]
)
| 4,260 | 1,757 |
import time
import sys
import urllib3
from time import sleep
import json
import csv
import datetime
import requests
from datetime import datetime
import subprocess # just for changing file ownership at the end of script
http = urllib3.PoolManager()
###############################################################################
DURATION = 2000 # How many timestamps you want? it 100 takes 10s
TIMES = 10 # How many times per sec you want the timestamp
###############################################################################
### define filename to save timestamps (coords3.csv)
with open('coords.csv', mode='w') as csvfile: # open the csv file
writer = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
writer.writerow(["X", "Y", "orientation","timestamp"])
print ("Coord queries running, wait"),
print(DURATION/TIMES),
print ("s")
def main():
#######################################################################
### change the url localhost to match actual addrest for REST API calls
#######################################################################
url = 'http://192.168.12.20/api/v2.0.0/status' # url where to call the rest api
error=0
response = http.request('GET', url) # response values from REST API
### get the values from response jason object x,y,orientation ###
try:
x = json.loads(response.data)['position']['x']
y = json.loads(response.data)['position']['y']
orientation = json.loads(response.data)['position']['orientation']
except KeyError as error:
error=1
### get the timestamp %f')[:-3] gives second with 3 digits ###
timestamp = datetime.now().strftime('%Y/%m/%d %H:%M:%S.%f')[:-3]
### write the REST API values into csv file
if error != 1:
writer.writerow([x,y,orientation,timestamp])
else:
error=0
if __name__ == '__main__':
time_start = time.time()
i = 1
while True:
time_current = time.time()
if time_current > time_start + i / float(TIMES):
# print('{}: {}'.format(i, time_current))
main() # execute main function after every 100ms
i += 1
if i > DURATION: # break the prog when duration reached
break
print ("Coord queries done, have a nice day!")
################################################################################
### If issues with ownership of the file u can use subprocess.call function to
### execute shell commands such as:
### subprocess.call(['chown', '[user]:root','/home/user/Documents/coords3.csv'])
### change [user] to match username and the file path to correct folder
################################################################################
| 2,880 | 749 |
def main():
# problem1()
# problem2()
# problem3()
# problem4()
# problem5()
def problem1():
awesomePeeps = ["kenn", "Kevin", "Erin", "Meka"] #made an array
print(awesomePeeps[2]) #printing the second element
print(len(awesomePeeps)) #printing the length and how many inside
awesomePeeps.remove("Kevin") #removing kevin
print(awesomePeeps[2])
#
# Create a function with the variable below. After you create the variable do the instructions below that.
# ```
# arrayForProblem2 = ["Kenn", "Kevin", "Erin", "Meka"]
# ```
# a) Print the 3rd element of the numberList.
#
# b) Print the size of the array
#
# c) Delete the second element.
#
# d) Print the 3rd element.
def problem2():
userInput = "" #making a blank input
while(userInput != 'q'): #if its not equal to q it will continue to ask
userInput = input("Enter something")
def problem3():
nickNames = { #this is my dictionary
"johnathan" : "John",
"Micheal":"Mike",
"William":"Bill",
"RObert":"Rob"
}
print(nickNames) #printing all the objects
print(nickNames["William"]) #printing william nick name
# Create a function that contains a collection of information for the following. After you create the collection do the instructions below that.
# ```
# Jonathan/John
# Michael/Mike
# William/Bill
# Robert/Rob
# ```
# a) Print the collection
#
# b) Print William's nickname
def problem4():
rando = [23,34,45,7,89] #my rando arrAay
for elements in range(len(rando)-1,-1,-1): #making it go backwards
print(rando[elements]) #printing the elements
# Create an array of 5 numbers.
# <strong>Using a loop</strong>, print the elements in the array reverse order.
# <strong>Do not use a function</strong>
#
#
#
#
def problem5():
higher = 0
lower = 0 #setting my variables to zero
equal = 0
pickaNumber = [2,4,5,7,8] #made my array
userinput=int(input("Enter a number"))
for eachEl in range(0,len(pickaNumber)-1,1): #calling each number in the array
if(userinput>pickaNumber[eachEl]):
lower+=1
elif(userinput==pickaNumber[eachEl]): #comparing them to if its lkarger or maller
equal+=1
elif(userinput<pickaNumber[eachEl]):
higher+=1
print(higher)
print(lower) #printing each function
print(equal)
#
# Create a function that will have a hard coded array then ask the user for a number.
# Use the userInput to state how many numbers in an array are higher, lower, or equal to it.
#
#
if __name__ == '__main__':
main() | 2,704 | 877 |
from durations import Duration
from typing import Any, Dict, Optional
from timeeval import Algorithm, TrainingType, InputDimensionality
from timeeval.adapters import DockerAdapter
from timeeval.params import ParameterConfig
import numpy as np
import numpy as np
from timeeval.utils.window import ReverseWindowing
# post-processing for MSCRED
def post_mscred(scores: np.ndarray, args: dict) -> np.ndarray:
ds_length = args.get("dataset_details").length # type: ignore
gap_time = args.get("hyper_params", {}).get("gap_time", 10)
window_size = args.get("hyper_params", {}).get("window_size", 5)
max_window_size = max(args.get("hyper_params", {}).get("windows", [10, 30, 60]))
offset = (ds_length - (max_window_size - 1)) % gap_time
image_scores = ReverseWindowing(window_size=window_size).fit_transform(scores)
return np.concatenate([np.repeat(image_scores[:-offset], gap_time), image_scores[-offset:]])
_mscred_parameters: Dict[str, Dict[str, Any]] = {
"batch_size": {
"defaultValue": 32,
"description": "Number of instances trained at the same time",
"name": "batch_size",
"type": "int"
},
"early_stopping_delta": {
"defaultValue": 0.05,
"description": "If 1 - (loss / last_loss) is less than `delta` for `patience` epochs, stop",
"name": "early_stopping_delta",
"type": "float"
},
"early_stopping_patience": {
"defaultValue": 10,
"description": "If 1 - (loss / last_loss) is less than `delta` for `patience` epochs, stop",
"name": "early_stopping_patience",
"type": "int"
},
"epochs": {
"defaultValue": 1,
"description": "Number of training iterations over entire dataset",
"name": "epochs",
"type": "int"
},
"gap_time": {
"defaultValue": 10,
"description": "Number of points to skip over between the generation of signature matrices",
"name": "gap_time",
"type": "int"
},
"learning_rate": {
"defaultValue": 0.001,
"description": "Learning rate for Adam optimizer",
"name": "learning_rate",
"type": "float"
},
"random_state": {
"defaultValue": 42,
"description": "Seed for the random number generator",
"name": "random_state",
"type": "int"
},
"split": {
"defaultValue": 0.8,
"description": "Train-validation split for early stopping",
"name": "split",
"type": "float"
},
"test_batch_size": {
"defaultValue": 256,
"description": "Number of instances used for validation and testing at the same time",
"name": "test_batch_size",
"type": "int"
},
"window_size": {
"defaultValue": 5,
"description": "Size of the sliding windows",
"name": "window_size",
"type": "int"
},
"windows": {
"defaultValue": [
10,
30,
60
],
"description": "Number and size of different signature matrices (correlation matrices) to compute as a preprocessing step",
"name": "windows",
"type": "List[int]"
}
}
def mscred(params: ParameterConfig = None, skip_pull: bool = False, timeout: Optional[Duration] = None) -> Algorithm:
return Algorithm(
name="MSCRED",
main=DockerAdapter(
image_name="registry.gitlab.hpi.de/akita/i/mscred",
skip_pull=skip_pull,
timeout=timeout,
group_privileges="akita",
),
preprocess=None,
postprocess=post_mscred,
param_schema=_mscred_parameters,
param_config=params or ParameterConfig.defaults(),
data_as_file=True,
training_type=TrainingType.SEMI_SUPERVISED,
input_dimensionality=InputDimensionality("multivariate")
)
| 3,511 | 1,192 |
from typing import Optional
import numpy as np
from sklearn.feature_selection import RFE
from sklearn.linear_model import LinearRegression, LogisticRegression
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
from fedot.core.data.data import OutputData
from fedot.core.operations.evaluation.operation_implementations.implementation_interfaces import \
DataOperationImplementation
class FeatureSelectionImplementation(DataOperationImplementation):
""" Class for applying feature selection operations on tabular data """
def __init__(self, **params: Optional[dict]):
super().__init__()
self.inner_model = None
self.operation = None
self.is_not_fitted = None
# Number of columns in features table
self.features_columns_number = None
# Bool mask where True - remain column and False - drop it
self.remain_features_mask = None
def fit(self, input_data):
""" Method for fit feature selection
:param input_data: data with features, target and ids to process
:return operation: trained operation (optional output)
"""
features = input_data.features
target = input_data.target
# Define number of columns in the features table
if len(features.shape) == 1:
self.features_columns_number = 1
else:
self.features_columns_number = features.shape[1]
if self.features_columns_number > 1:
if self._is_input_data_one_dimensional(features):
self.is_not_fitted = True
return self.operation
try:
self.operation.fit(features, target)
except ValueError:
# For time series forecasting not available multi-targets
self.operation.fit(features, target[:, 0])
else:
self.is_not_fitted = True
return self.operation
def transform(self, input_data, is_fit_pipeline_stage: Optional[bool]):
""" Method for making prediction
:param input_data: data with features, target and ids to process
:param is_fit_pipeline_stage: is this fit or predict stage for pipeline
:return output_data: filtered input data by columns
"""
if self.is_not_fitted:
return self._convert_to_output(input_data, input_data.features)
features = input_data.features
source_features_shape = features.shape
transformed_features = self._make_new_table(features)
# Update features
output_data = self._convert_to_output(input_data,
transformed_features)
self._update_column_types(source_features_shape, output_data)
return output_data
def get_params(self):
return self.operation.get_params()
def _update_column_types(self, source_features_shape, output_data: OutputData):
""" Update column types after applying feature selection operations """
if len(source_features_shape) < 2:
return output_data
else:
if self.features_columns_number > 1:
cols_number_removed = source_features_shape[1] - output_data.predict.shape[1]
if cols_number_removed > 0:
# There are several columns, which were dropped
col_types = output_data.supplementary_data.column_types['features']
# Calculate
remained_column_types = np.array(col_types)[self.remain_features_mask]
output_data.supplementary_data.column_types['features'] = list(remained_column_types)
def _make_new_table(self, features):
"""
The method creates a table based on transformed data and source boolean
features
:param features: tabular data for processing
:return transformed_features: transformed features table
"""
# Bool vector - mask for columns
self.remain_features_mask = self.operation.support_
transformed_features = features[:, self.remain_features_mask]
return transformed_features
@staticmethod
def _is_input_data_one_dimensional(features_to_process: np.array):
""" Check if features table contain only one column """
return features_to_process.shape[1] == 1
class LinearRegFSImplementation(FeatureSelectionImplementation):
"""
Class for feature selection based on Recursive Feature Elimination (RFE) and
LinearRegression as core model
Task type - regression
"""
def __init__(self, **params: Optional[dict]):
super().__init__()
self.inner_model = LinearRegression(normalize=True)
if not params:
# Default parameters
self.operation = RFE(estimator=self.inner_model)
else:
# Checking the appropriate params are using or not
rfe_params = {k: params[k] for k in
['n_features_to_select', 'step']}
self.operation = RFE(estimator=self.inner_model, **rfe_params)
self.params = params
class NonLinearRegFSImplementation(FeatureSelectionImplementation):
"""
Class for feature selection based on Recursive Feature Elimination (RFE) and
DecisionTreeRegressor as core model
Task type - regression
"""
def __init__(self, **params: Optional[dict]):
super().__init__()
self.inner_model = DecisionTreeRegressor()
if not params:
# Default parameters
self.operation = RFE(estimator=self.inner_model)
else:
# Checking the appropriate params are using or not
rfe_params = {k: params[k] for k in
['n_features_to_select', 'step']}
self.operation = RFE(estimator=self.inner_model, **rfe_params)
self.params = params
class LinearClassFSImplementation(FeatureSelectionImplementation):
"""
Class for feature selection based on Recursive Feature Elimination (RFE) and
LogisticRegression as core model
Task type - classification
"""
def __init__(self, **params: Optional[dict]):
super().__init__()
self.inner_model = LogisticRegression()
if not params:
# Default parameters
self.operation = RFE(estimator=self.inner_model)
else:
# Checking the appropriate params are using or not
rfe_params = {k: params[k] for k in
['n_features_to_select', 'step']}
self.operation = RFE(estimator=self.inner_model, **rfe_params)
self.params = params
class NonLinearClassFSImplementation(FeatureSelectionImplementation):
"""
Class for feature selection based on Recursive Feature Elimination (RFE) and
DecisionTreeClassifier as core model
Task type - classification
"""
def __init__(self, **params: Optional[dict]):
super().__init__()
self.inner_model = DecisionTreeClassifier()
if not params:
# Default parameters
self.operation = RFE(estimator=self.inner_model)
else:
# Checking the appropriate params are using or not
rfe_params = {k: params[k] for k in
['n_features_to_select', 'step']}
self.operation = RFE(estimator=self.inner_model, **rfe_params)
self.params = params
| 7,470 | 1,945 |
# -*- coding: utf-8 -*-
#
# Copyright 2017 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.
"""Budou, an automatic CJK line break organizer."""
from __future__ import print_function
from .cachefactory import load_cache
import collections
from xml.etree import ElementTree as ET
import html5lib
import re
import six
import unicodedata
cache = load_cache()
class Chunk(object):
"""Chunk object. This represents a unit for word segmentation.
Attributes:
word: Surface word of the chunk. (str)
pos: Part of speech. (str)
label: Label information. (str)
dependency: Dependency to neighbor words. None for no dependency, True for
dependency to the following word, and False for the dependency to the
previous word. (bool or None)
"""
SPACE_POS = 'SPACE'
BREAK_POS = 'BREAK'
DEPENDENT_LABEL = (
'P', 'SNUM', 'PRT', 'AUX', 'SUFF', 'AUXPASS', 'RDROP', 'NUMBER', 'NUM',
'PREF')
def __init__(self, word, pos=None, label=None, dependency=None):
self.word = word
self.pos = pos
self.label = label
self.dependency = dependency
self._add_dependency_if_punct()
def __repr__(self):
return 'Chunk(%s, %s, %s, %s)' % (
repr(self.word), self.pos, self.label, self.dependency)
@classmethod
def space(cls):
"""Creates space Chunk."""
chunk = cls(u' ', cls.SPACE_POS)
return chunk
@classmethod
def breakline(cls):
"""Creates breakline Chunk."""
chunk = cls(u'\n', cls.BREAK_POS)
return chunk
def is_space(self):
"""Checks if this is space Chunk."""
return self.pos == self.SPACE_POS
def has_cjk(self):
"""Checks if the word of the chunk contains CJK characters
Using range from
https://github.com/nltk/nltk/blob/develop/nltk/tokenize/util.py#L149
"""
for char in self.word:
if any([start <= ord(char) <= end for start, end in
[(4352, 4607), (11904, 42191), (43072, 43135), (44032, 55215),
(63744, 64255), (65072, 65103), (65381, 65500),
(131072, 196607)]
]):
return True
return False
def update_word(self, word):
"""Updates the word of the chunk."""
self.word = word
def serialize(self):
"""Returns serialized chunk data in dictionary."""
return {
'word': self.word,
'pos': self.pos,
'label': self.label,
'dependency': self.dependency,
'has_cjk': self.has_cjk(),
}
def maybe_add_dependency(self, default_dependency_direction):
"""Adds dependency if any dependency is not assigned yet."""
if self.dependency is None and self.label in self.DEPENDENT_LABEL:
self.dependency = default_dependency_direction
def _add_dependency_if_punct(self):
"""Adds dependency if the chunk is punctuation."""
if self.pos == 'PUNCT':
try:
# Getting unicode category to determine the direction.
# Concatenates to the following if it belongs to Ps or Pi category.
# Ps: Punctuation, open (e.g. opening bracket characters)
# Pi: Punctuation, initial quote (e.g. opening quotation mark)
# Otherwise, concatenates to the previous word.
# See also https://en.wikipedia.org/wiki/Unicode_character_property
category = unicodedata.category(self.word)
self.dependency = category in ('Ps', 'Pi')
except:
pass
class ChunkList(list):
"""Chunk list. """
def get_overlaps(self, offset, length):
"""Returns chunks overlapped with the given range.
Args:
offset: Begin offset of the range. (int)
length: Length of the range. (int)
Returns:
Overlapped chunks. (list of Chunk)
"""
# In case entity's offset points to a space just before the entity.
if ''.join([chunk.word for chunk in self])[offset] == ' ':
offset += 1
index = 0
result = []
for chunk in self:
if offset < index + len(chunk.word) and index < offset + length:
result.append(chunk)
index += len(chunk.word)
return result
def swap(self, old_chunks, new_chunk):
"""Swaps old consecutive chunks with new chunk.
Args:
old_chunks: List of consecutive Chunks to be removed. (list of Chunk)
new_chunk: A Chunk to be inserted. (Chunk)
"""
indexes = [self.index(chunk) for chunk in old_chunks]
del self[indexes[0]:indexes[-1] + 1]
self.insert(indexes[0], new_chunk)
class Budou(object):
"""A parser for CJK line break organizer.
Attributes:
service: A Resource object with methods for interacting with the service.
(googleapiclient.discovery.Resource)
"""
DEFAULT_CLASS_NAME = 'ww'
def __init__(self, service):
self.service = service
@classmethod
def authenticate(cls, json_path=None):
"""Authenticates for Cloud Natural Language API and returns a parser.
If a service account private key file is not given, it tries to authenticate
with default credentials.
Args:
json_path: A file path to a service account's JSON private keyfile.
(str, optional)
Returns:
Budou parser. (Budou)
"""
import google_auth_httplib2
from googleapiclient import discovery
scope = ['https://www.googleapis.com/auth/cloud-platform']
if json_path:
try:
from google.oauth2 import service_account
credentials = service_account.Credentials.from_service_account_file(
json_path)
scoped_credentials = credentials.with_scopes(scope)
except ImportError:
print('''Failed to load google.oauth2.service_account module.
If you are running this script in Google App Engine environment,
please call `authenticate` method with empty argument to
authenticate with default credentials.''')
else:
import google.auth
scoped_credentials, project = google.auth.default(scope)
authed_http = google_auth_httplib2.AuthorizedHttp(scoped_credentials)
service = discovery.build('language', 'v1beta2', http=authed_http)
return cls(service)
def parse(self, source, attributes=None, use_cache=True, language=None,
max_length=None, use_entity=False, classname=None):
"""Parses input HTML code into word chunks and organized code.
Args:
source: Text to be processed. (str)
attributes: A key-value mapping for attributes of output elements.
(dictionary, optional)
**This argument used to accept a string or a list of strings to
specify class names of the output chunks, but this designation method
is now deprecated. Please use a dictionary to designate attributes.**
use_cache: Whether to use caching. (bool, optional)
language: A language used to parse text. (str, optional)
max_length: Maximum length of span enclosed chunk. (int, optional)
use_entity: Whether to use entities Entity Analysis results. Note that it
makes additional request to API, which may incur additional cost.
(bool, optional)
classname: A class name of output elements. (str, optional)
**This argument is deprecated. Please use attributes argument
instead.**
Returns:
A dictionary with the list of word chunks and organized HTML code.
For example:
{
'chunks': [
{'dependency': None, 'label': 'NSUBJ', 'pos': 'NOUN', 'word': '今日も'},
{'dependency': None, 'label': 'ROOT', 'pos': 'VERB', 'word': '食べる'}
],
'html_code': '<span class="ww">今日も</span><span class="ww">食べる</span>'
}
"""
if use_cache:
result_value = cache.get(source, language)
if result_value: return result_value
input_text = self._preprocess(source)
if language == 'ko':
# Korean has spaces between words, so this simply parses words by space
# and wrap them as chunks.
chunks = self._get_chunks_per_space(input_text)
else:
chunks, tokens, language = self._get_chunks_with_api(
input_text, language, use_entity)
attributes = self._get_attribute_dict(attributes, classname)
html_code = self._html_serialize(chunks, attributes, max_length)
result_value = {
'chunks': [chunk.serialize() for chunk in chunks],
'html_code': html_code,
'language': language,
'tokens': tokens,
}
if use_cache:
cache.set(source, language, result_value)
return result_value
def _get_chunks_per_space(self, input_text):
"""Returns a chunk list by separating words by spaces.
Args:
input_text: String to parse. (str)
Returns:
A chunk list. (ChunkList)
"""
chunks = ChunkList()
words = input_text.split()
for i, word in enumerate(words):
chunks.append(Chunk(word))
if i < len(words) - 1: # Add no space after the last word.
chunks.append(Chunk.space())
return chunks
def _get_chunks_with_api(self, input_text, language=None, use_entity=False):
"""Returns a chunk list by using Google Cloud Natural Language API.
Args:
input_text: String to parse. (str)
language: A language code. 'ja' and 'ko' are supported. (str, optional)
use_entity: Whether to use entities in Natural Language API response.
(bool, optional)
Returns:
A chunk list. (ChunkList)
"""
chunks, tokens, language = self._get_source_chunks(input_text, language)
if use_entity:
entities = self._get_entities(input_text, language)
chunks = self._group_chunks_by_entities(chunks, entities)
chunks = self._resolve_dependency(chunks)
chunks = self._insert_breakline(chunks)
return chunks, tokens, language
def _get_attribute_dict(self, attributes, classname=None):
"""Returns a dictionary of HTML element attributes.
Args:
attributes: If a dictionary, it should be a map of name-value pairs for
attributes of output elements. If a string, it should be a class name of
output elements. (dict or str)
classname: Optional class name. (str, optional)
Returns:
An attribute dictionary. (dict of (str, str))
"""
if attributes and isinstance(attributes, six.string_types):
return {
'class': attributes
}
if not attributes:
attributes = {}
if not classname:
classname = self.DEFAULT_CLASS_NAME
attributes.setdefault('class', classname)
return attributes
def _preprocess(self, source):
"""Removes unnecessary break lines and white spaces.
Args:
source: HTML code to be processed. (str)
Returns:
Preprocessed HTML code. (str)
"""
doc = html5lib.parseFragment(source)
source = ET.tostring(doc, encoding='utf-8', method='text').decode('utf-8')
source = source.replace(u'\n', u'').strip()
source = re.sub(r'\s\s+', u' ', source)
return source
def _get_source_chunks(self, input_text, language=None):
"""Returns a chunk list retrieved from Syntax Analysis results.
Args:
input_text: Text to annotate. (str)
language: Language of the text. 'ja' and 'ko' are supported.
(str, optional)
Returns:
A chunk list. (ChunkList)
"""
chunks = ChunkList()
sentence_length = 0
tokens, language = self._get_annotations(input_text, language)
for i, token in enumerate(tokens):
word = token['text']['content']
begin_offset = token['text']['beginOffset']
label = token['dependencyEdge']['label']
pos = token['partOfSpeech']['tag']
if begin_offset > sentence_length:
chunks.append(Chunk.space())
sentence_length = begin_offset
chunk = Chunk(word, pos, label)
# Determining default concatenating direction based on syntax dependency.
chunk.maybe_add_dependency(
i < token['dependencyEdge']['headTokenIndex'])
chunks.append(chunk)
sentence_length += len(word)
return chunks, tokens, language
def _group_chunks_by_entities(self, chunks, entities):
"""Groups chunks by entities retrieved from NL API Entity Analysis.
Args:
chunks: The list of chunks to be processed. (ChunkList)
entities: List of entities. (list of dict)
Returns:
A chunk list. (ChunkList)
"""
for entity in entities:
chunks_to_concat = chunks.get_overlaps(
entity['beginOffset'], len(entity['content']))
if not chunks_to_concat: continue
new_chunk_word = u''.join([chunk.word for chunk in chunks_to_concat])
new_chunk = Chunk(new_chunk_word)
chunks.swap(chunks_to_concat, new_chunk)
return chunks
def _html_serialize(self, chunks, attributes, max_length):
"""Returns concatenated HTML code with SPAN tag.
Args:
chunks: The list of chunks to be processed. (ChunkList)
attributes: If a dictionary, it should be a map of name-value pairs for
attributes of output SPAN tags. If a string, it should be a class name
of output SPAN tags. If an array, it should be a list of class names
of output SPAN tags. (str or dict or list of str)
max_length: Maximum length of span enclosed chunk. (int, optional)
Returns:
The organized HTML code. (str)
"""
doc = ET.Element('span')
for chunk in chunks:
if chunk.is_space():
if doc.getchildren():
if doc.getchildren()[-1].tail is None:
doc.getchildren()[-1].tail = ' '
else:
doc.getchildren()[-1].tail += ' '
else:
if doc.text is not None:
# We want to preserve space in cases like "Hello 你好"
# But the space in " 你好" can be discarded.
doc.text += ' '
else:
if chunk.has_cjk() and not (max_length and len(chunk.word) > max_length):
ele = ET.Element('span')
ele.text = chunk.word
for k, v in attributes.items():
ele.attrib[k] = v
doc.append(ele)
else:
# add word without span tag for non-CJK text (e.g. English)
# by appending it after the last element
if doc.getchildren():
if doc.getchildren()[-1].tail is None:
doc.getchildren()[-1].tail = chunk.word
else:
doc.getchildren()[-1].tail += chunk.word
else:
if doc.text is None:
doc.text = chunk.word
else:
doc.text += chunk.word
result = ET.tostring(doc, encoding='utf-8').decode('utf-8')
result = html5lib.serialize(
html5lib.parseFragment(result), sanitize=True,
quote_attr_values="always")
return result
def _resolve_dependency(self, chunks):
"""Resolves chunk dependency by concatenating them.
Args:
chunks: a chink list. (ChunkList)
Returns:
A chunk list. (ChunkList)
"""
chunks = self._concatenate_inner(chunks, True)
chunks = self._concatenate_inner(chunks, False)
return chunks
def _concatenate_inner(self, chunks, direction):
"""Concatenates chunks based on each chunk's dependency.
Args:
direction: Direction of concatenation process. True for forward. (bool)
Returns:
A chunk list. (ChunkList)
"""
tmp_bucket = []
source_chunks = chunks if direction else chunks[::-1]
target_chunks = ChunkList()
for chunk in source_chunks:
if (
# if the chunk has matched dependency, do concatenation.
chunk.dependency == direction or
# if the chunk is SPACE, concatenate to the previous chunk.
(direction == False and chunk.is_space())
):
tmp_bucket.append(chunk)
continue
tmp_bucket.append(chunk)
if not direction: tmp_bucket = tmp_bucket[::-1]
new_word = ''.join([tmp_chunk.word for tmp_chunk in tmp_bucket])
chunk.update_word(new_word)
target_chunks.append(chunk)
tmp_bucket = []
if tmp_bucket: target_chunks += tmp_bucket
return target_chunks if direction else target_chunks[::-1]
def _insert_breakline(self, chunks):
"""Inserts a breakline instead of a trailing space if the chunk is in CJK.
Args:
chunks: a chunk list. (ChunkList)
Returns:
A chunk list. (ChunkList)
"""
target_chunks = ChunkList()
for chunk in chunks:
if chunk.word[-1] == ' ' and chunk.has_cjk():
chunk_to_add = Chunk(
chunk.word[:-1], chunk.pos, chunk.label, chunk.dependency)
target_chunks.append(chunk_to_add)
target_chunks.append(chunk.breakline())
else:
target_chunks.append(chunk)
return target_chunks
def _get_annotations(self, text, language='', encoding='UTF32'):
"""Returns the list of annotations from the given text."""
body = {
'document': {
'type': 'PLAIN_TEXT',
'content': text,
},
'features': {
'extract_syntax': True,
},
'encodingType': encoding,
}
if language:
body['document']['language'] = language
request = self.service.documents().annotateText(body=body)
response = request.execute()
tokens = response.get('tokens', [])
language = response.get('language')
return tokens, language
def _get_entities(self, text, language='', encoding='UTF32'):
"""Returns the list of annotations from the given text."""
body = {
'document': {
'type': 'PLAIN_TEXT',
'content': text,
},
'encodingType': encoding,
}
if language:
body['document']['language'] = language
request = self.service.documents().analyzeEntities(body=body)
response = request.execute()
result = []
for entity in response.get('entities', []):
mentions = entity.get('mentions', [])
if not mentions: continue
entity_text = mentions[0]['text']
offset = entity_text['beginOffset']
for word in entity_text['content'].split():
result.append({'content': word, 'beginOffset': offset})
offset += len(word)
return result
| 18,595 | 5,617 |
from django.contrib import admin
#if ENVIRONMENT == 'PROD':
# from api.models import *
#else:
from api.models import *
# Register your models here.
admin.site.register(Event, EventAdmin)
admin.site.register(ApiKey, ApiKeyAdmin)
admin.site.register(PlayerProfile)
admin.site.register(Group)
admin.site.register(Game)
| 318 | 104 |
from lpd.enums import Phase, State
from lpd.callbacks.callback_base import CallbackBase
from lpd.callbacks.callback_context import CallbackContext
from typing import Union, List
class CollectOutputs(CallbackBase):
"""
This callback will collect outputs per each state, (it is currently used in trainer.predict() method.)
It will collect the numpy outputs in the defined states to a dictionary (state->outputs)
Methods:
get_outputs_for_state - for a given state, returns the collected outputs
Args:
apply_on_phase - see in CallbackBase
apply_on_states - see in CallbackBase
"""
def __init__(self,
apply_on_phase: Phase,
apply_on_states: Union[State, List[State]]):
super(CollectOutputs, self).__init__(apply_on_phase, apply_on_states)
self.state_to_outputs = {}
def get_outputs_for_state(self, state: State):
return [data.cpu().numpy() for data in self.state_to_outputs[state]]
def __call__(self, callback_context: CallbackContext):
c = callback_context #READABILITY DOWN THE ROAD
state = c.trainer_state
if self.should_apply_on_state(c):
if state not in self.state_to_outputs:
self.state_to_outputs[state] = []
last_outputs = c.trainer._last_data[state].outputs.data
self.state_to_outputs[state].append(last_outputs)
| 1,456 | 425 |
from decouple import config
DATABASE_URL = config("DATABASE_URL")
LOG_LEVEL = config("LOG_LEVEL", "INFO")
| 107 | 40 |
'Game1'
'''
x.type são os seguintes
(Tudo em Capslock)
quit
atctiveevent
keydown
keyup
mousemotion
mousebuttonup
mousebuttondown
videioresize
'''
#40pygame
import pygame_textinput
import pygame
import random
width=800
height=600
bsize=20
thick=20
fps=60
direction = 270
wall = 10
pygame.init()
gdisplay=pygame.display.set_mode((width,height))
pygame.display.update()
pygame.display.set_caption('SNAKE PL')
colors={'red':(128,0,0),'black':(0,0,0),'white':(255,255,255),'green':(0,155,0),'blue':(0,0,155),'yellow':(255,170,0),'darkblue':(51,102,204),'darkgreen':(51,102,0),
'violet':(102,0,102),'brown':(77,38,0),'pink':(255,204,255)}
'music = pygame.mixer.Sound('')'
def music1():
pygame.mixer.music.stop()
pygame.mixer.music.load('assets/music/reloaded.ogg')
pygame.mixer.music.play(-1)
def music2():
pygame.mixer.music.stop()
pygame.mixer.music.load('assets/music/lionel.ogg')
pygame.mixer.music.play(-1)
def music3():
pygame.mixer.music.stop()
pygame.mixer.music.load('assets/music/lana.ogg')
pygame.mixer.music.play()
def music4():
pygame.mixer.music.stop()
pygame.mixer.music.load('assets/music/george.ogg')
pygame.mixer.music.play()
icon = pygame.image.load('assets/img/s32.png')
snakepng = pygame.image.load('assets/img/snakehead20.png')
applepng = pygame.image.load('assets/img/apple20.png')
pygame.display.set_icon(icon)
textinput = pygame_textinput.TextInput()
clock=pygame.time.Clock()
smallfont = pygame.font.SysFont('impact', 30)
medfont = pygame.font.SysFont('impact', 60)
largefont = pygame.font.SysFont('impact', 90)
introfont = pygame.font.SysFont('Impact', 150)
def snake(bsize,snakelist,x):
head = pygame.transform.rotate(snakepng,direction)
gdisplay.blit(head, (snakelist[-1][0], snakelist[-1][1]))
for xy in snakelist[:-1]:
pygame.draw.rect(gdisplay,colors['green'],[xy[0],xy[1],bsize,bsize])
def text_objetcts(text,color,size):
textsurface = size.render(text, True,color)
return textsurface, textsurface.get_rect()
def msm(msg,color,change=0,size=medfont):
text1,text2 = text_objetcts(msg,color,size)
text2.center = (width/2),((height/2)+change)
gdisplay.blit(text1,text2)
def score(score):
text = smallfont.render('Score: ' + str(score), True, colors['black'])
gdisplay.blit(text,(bsize,bsize))
def pause():
pause = True
pygame.mixer.music.pause()
gdisplay.fill(colors['darkblue'])
msm('PAUSE',colors['black'],-100,largefont)
msm('(C) to Continue (Q) to Quit',colors['black'],0,smallfont)
msm('New music press from (1 to 4)',colors['black'],50,smallfont)
pygame.display.update()
while pause:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
pygame.quit()
quit()
if event.key == pygame.K_c:
pygame.mixer.music.unpause()
pause = False
if event.key == pygame.K_1:
music1()
if event.key == pygame.K_2:
music2()
if event.key == pygame.K_3:
music3()
if event.key == pygame.K_4:
music4()
clock.tick(5)
def introg():
music1()
pygame.display.update()
intro = True
while intro:
gdisplay.fill(colors['darkgreen'])
msm("SNAKE PL",colors['violet'],-100,introfont)
msm('Simple Snake Game', colors['black'],0,smallfont)
msm('Press (S) to Start (P) to Pause (Q) to Quit',colors['blue'],height/2-100,smallfont)
pygame.display.update()
clock.tick(fps)
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_s:
intro = False
gameloop()
if event.key == pygame.QUIT:
pygame.quit()
quit()
if event.key == pygame.K_q:
pygame.quit()
quit()
def inputed():
inpute = True
while inpute:
gdisplay.fill(colors['darkblue'])
msm('|Place Player Name|',colors['yellow'],0,largefont)
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
return textinput.get_text()
inpute = False
# Feed it with events every frame
textinput.update(events)
# Blit its surface onto the screen
gdisplay.blit(textinput.get_surface(), (10, 10))
pygame.display.update()
clock.tick(30)
def topscore(score,name):
eva = True
pre = ["?","meh"]
pos = ["crazy","veryStack"]
listz = []
while eva:
with open('db/topscore.txt','r') as fd:
lines = [x.split() for x in fd.readlines()]
check = False
for line in lines:
if (score > int(line[1]) ) and (not check):
#Save current value
pre[0] = line[0]
pre[1] = line[1]
#Insert New score
line[1] = score
line[0] = name
listz.append(line)
check = True
elif check:
#Position Value
pos[0] = line[0]
pos[1] = line[1]
#Player that got downgraded
line[1] = pre[1]
line[0] = pre[0]
#Player that will get downgraded
pre[0] = pos[0]
pre[1] = pos[1]
listz.append(line)
else:
listz.append(line)
x = [x for x in listz]
with open('db/topscore.txt','w') as fd:
for i in range(len(x)):
if i == 0:
fd.write('%s %s\n'%(x[i][0],x[i][1]))
elif 0<i<9:
fd.write('%s %s\n'%(x[i][0],x[i][1]))
elif i == 9:
fd.write('%s %s'%(x[i][0],x[i][1]))
eva = False
'''fd = open('top10.txt',a)
'Nome de Jogador | score '
fd.close()
'''
def final():
fin = True
while fin:
with open('db/topscore.txt','r') as fd:
lines = [line.split() for line in fd.readlines()]
gdisplay.fill(colors['darkblue'])
msm('TOP SCORES',colors['yellow'],-250,medfont)
msm(str('%s:%s'%(lines[0][0],lines[0][1])),colors['black'],-200,smallfont)
msm(str('%s:%s'%(lines[1][0],lines[1][1])),colors['black'],-150,smallfont)
msm(str('%s:%s'%(lines[2][0],lines[2][1])),colors['black'],-100,smallfont)
msm(str('%s:%s'%(lines[3][0],lines[3][1])),colors['black'],-50,smallfont)
msm(str('%s:%s'%(lines[4][0],lines[4][1])),colors['black'],0,smallfont)
msm(str('%s:%s'%(lines[5][0],lines[5][1])),colors['black'],50,smallfont)
msm(str('%s:%s'%(lines[6][0],lines[6][1])),colors['black'],100,smallfont)
msm(str('%s:%s'%(lines[7][0],lines[7][1])),colors['black'],150,smallfont)
msm(str('%s:%s'%(lines[8][0],lines[8][1])),colors['black'],200,smallfont)
msm(str('%s:%s'%(lines[9][0],lines[9][1])),colors['black'],250,smallfont)
text = smallfont.render('Q (Quit) B (Start Screen)', True, colors['black'])
gdisplay.blit(text,(width-300,height-50))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
pygame.quit()
quit()
fin == False
if event.key == pygame.K_b:
introg()
def walls():
left = pygame.draw.rect(gdisplay,colors['pink'],[0,0,wall,height])
right = pygame.draw.rect(gdisplay,colors['pink'],[width-wall,0,wall,height])
up = pygame.draw.rect(gdisplay,colors['pink'],[0,0,width,wall])
down = pygame.draw.rect(gdisplay,colors['pink'],[0,height-wall,width,wall])
def butt(snakelist,snakehead,direction):
for i in snakelist[:-1]:
if direction == 270:
if [snakehead[0]+10.0,snakehead[1]] == i:
return True
if direction == 90:
if [snakehead[0]-10.0,snakehead[1]] == i:
return True
if direction == 0:
if [snakehead[0],snakehead[1]-10.0] == i:
return True
if direction == 180:
if [snakehead[0],snakehead[1]+10.0] == i:
return True
return False
def gameloop():
global direction
exitg = False
overg = False
x_lead=width/2 #incio
y_lead=height/2
xclead,yclead=bsize,0
snakehead = []
snakelist = []
snakelen = 1
xapple = int(random.randrange(bsize,width-thick,bsize))
yapple = int(random.randrange(bsize,height-thick,bsize))
while not exitg:
while overg == True:
gdisplay.fill(colors['darkblue'])
msm('GAME OVER',colors['red'],-100,largefont)
msm('Press C (Repeat) Q (Quit) B (Music Selection) T (Scores)',colors['yellow'],height/2-100,smallfont)
msm('Your score is %d'%(snakelen-1), colors['black'], 50)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
exitg = True
overg = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
gameloop()
if event.key == pygame.K_q:
exitg = True
overg = False
if event.key == pygame.K_b:
introg()
if event.key == pygame.K_t:
playername = inputed()
topscore(snakelen-1,playername)
final()
'''if event.key == pygame.K_t:
topscore(snakelen-1,playername)
'''
if (x_lead > xapple):
if direction == 270 and (not butt(snakelist,snakehead,270)):#(right)
if (y_lead < yapple) and (not butt(snakelist,snakehead,180)):
direction = 180
yclead = bsize
xclead = 0
#faker
if (y_lead < yapple) and (not butt(snakelist,snakehead,0)):
direction = 0
yclead = -bsize
xclead = 0
if (y_lead > yapple) and (not butt(snakelist,snakehead,0)):
direction = 0
yclead = -bsize
xclead = 0
#faker
if (y_lead > yapple)and (not butt(snakelist,snakehead,180)):
direction = 180
yclead = bsize
xclead = 0
elif (not butt(snakelist,snakehead,90)):
direction = 90
xclead = -bsize
yclead = 0
print(not butt(snakelist,snakehead,90))
if (x_lead < xapple):
if direction == 90 and (not butt(snakelist,snakehead,90)):#(left)
if (y_lead < yapple) and (not butt(snakelist,snakehead,180)):
direction = 180
yclead = bsize
xclead = 0
#faker
if (y_lead < yapple) and (not butt(snakelist,snakehead,0)):
direction = 0
yclead = -bsize
xclead = 0
if (y_lead > yapple)and (not butt(snakelist,snakehead,0)):
direction = 0
yclead = -bsize
xclead = 0
#faker
if (y_lead > yapple)and (not butt(snakelist,snakehead,180)):
direction = 180
yclead = bsize
xclead = 0
elif (not butt(snakelist,snakehead,270)):
direction = 270
xclead = bsize
yclead = 0
if (x_lead == xapple):
if (not butt(snakelist,snakehead,180)) and (y_lead < yapple):#(left)
direction = 180
yclead = bsize
xclead = 0
elif (not butt(snakelist,snakehead,0)) and (y_lead > yapple):
direction = 0
yclead = -bsize
xclead = 0
elif (not butt(snakelist,snakehead,90)):
direction = 90
yclead = 0
xclead = -bsize
elif (not butt(snakelist,snakehead,270)):
direction = 270
yclead = 0
xclead = bsize
if x_lead > width-wall-bsize or x_lead < wall or y_lead < wall or y_lead > height-wall-bsize:
overg = True
'''if event.type == pygame.KEYUP: #só move quando pressionado o butão
if event.key == pygame.K_RIGHT or event.key == pygame.K_LEFT:
xclead = 0
elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
yclear=0
'''
dt = clock.tick(fps)
x_lead+=xclead /2
y_lead+=yclead /2
if x_lead+bsize > xapple and x_lead < xapple+thick:
if y_lead+bsize > yapple and y_lead < yapple+thick:
xapple = int(random.randrange(bsize,width-bsize,bsize))
yapple = int(random.randrange(bsize,height-bsize,bsize))
snakelen+=1
'''for i in colors:
gdisplay.fill(colors[i])
pygame.display.update()
'''
gdisplay.fill(colors['brown'])
gdisplay.blit(applepng,(xapple,yapple))
snakehead = []
snakehead.append(x_lead)
snakehead.append(y_lead)
snakelist.append(snakehead)
if len(snakelist) > snakelen:
del snakelist[0]
for i in snakelist[:-1]:
if snakehead == i:
overg = True
snake(bsize,snakelist,direction)
walls()
#gdisplay.fill(colors[''], rect=[x,y,w,h])
score(snakelen-1)
pygame.display.update()
#pygame.draw.rect(local,cor,[x,y,w,h])
clock.tick(fps)
pygame.quit()
quit()
introg()
gameloop()
| 15,022 | 5,074 |
"""
simplemap.html_render
~~~~~~~~~~~~~~~~~~~~~
This module contains everything related to Jinja2 HTML rendering.
"""
from jinja2 import Undefined
class SilentUndefined(Undefined):
""" Allow Jinja2 to continue rendering if undefined tag is parsed """
def _fail_with_undefined_error(self, *args, **kwargs):
return None | 327 | 99 |
import sys
def reducer():
aadhaar_generated = 0
old_key = None
#Cycle through the list of key-value pairs emitted
#by your mapper, and print out each key once,
#along with the total number of Aadhaar generated,
#separated by a tab. Assume that the list of key-
#value pairs will be ordered by key. Make sure
#each key-value pair is formatted correctly!
#Here's a sample final key-value pair: "Gujarat\t5.0"
# your code here
reducer() | 487 | 155 |
expected_output = {
'vrf': {
'default': {
'address_family': {
'ipv4': {
'instance': {
'rip-1': {
'routes': {
'2001:10:12:120::/64': {
'best_route': False,
'index': {
1: {
'expire_time': '00:02:58',
'interface': 'Ethernet1/2.120',
'metric': 2,
'next_hop': 'fe80::f816:3eff:fe8f:fbd9',
'tag': 0,
},
},
'next_hops': 1,
},
'2001:10:13:120::/64': {
'best_route': True,
'index': {
1: {
'interface': 'Ethernet1/2.120',
'metric': 1,
'next_hop': '2001:10:13:120::3',
'route_type': 'connected',
'tag': 0,
},
},
'next_hops': 0,
},
'2001:10:23:120::/64': {
'best_route': True,
'index': {
1: {
'interface': 'Ethernet1/1.120',
'metric': 1,
'next_hop': '2001:10:23:120::3',
'route_type': 'connected',
'tag': 0,
},
},
'next_hops': 0,
},
'2001:1:1:1::1/128': {
'best_route': False,
'index': {
1: {
'expire_time': '00:02:58',
'interface': 'Ethernet1/2.120',
'metric': 2,
'next_hop': 'fe80::f816:3eff:fe8f:fbd9',
'tag': 0,
},
},
'next_hops': 1,
},
'2001:3:3:3::3/128': {
'best_route': True,
'index': {
1: {
'interface': 'loopback0',
'metric': 1,
'next_hop': '2001:3:3:3::3',
'route_type': 'connected',
'tag': 0,
},
},
'next_hops': 0,
},
},
},
},
},
},
},
},
}
| 3,999 | 882 |
#!/usr/bin/env python
import os
import sys
import cdat_info
class VCSTestRunner(cdat_info.TestRunnerBase):
def _prep_nose_options(self):
opt = super(VCSTestRunner, self)._prep_nose_options()
if self.args.no_vtk_ui:
opt += ["-A", "not vtk_ui"]
if self.args.vtk is not None:
cdat_info.run_command(
"conda install -f -y -c {} vtk-cdat".format(self.args.vtk))
return opt
test_suite_name = 'vcs'
workdir = os.getcwd()
runner = VCSTestRunner(test_suite_name, options=["--no-vtk-ui", "--vtk"],
options_files=["tests/vcs_runtests.json"],
get_sample_data=True,
test_data_files_info="share/test_data_files.txt")
ret_code = runner.run(workdir)
sys.exit(ret_code)
| 804 | 287 |
# -*- coding: utf-8 -*-
import random
import six
# SciPy Stack
import numpy as np
# Torch
import torch
###############################################################################
def initialize_seed(seed):
"""Initializes the seed of different PRNGs.
:param seed: Value to initialize the PRNGs.
"""
np.random.seed(seed)
random.seed(seed)
torch.manual_seed(seed)
def evaluate(agent, env, max_steps, render):
"""Evaluates the given agent on an environment.
:return: A numpy array with the reward of each step taken by the agent.
"""
rewards = []
infos = []
done = False
state = env.reset()
for _ in six.moves.range(max_steps):
action = agent.compute_action(state)
next_state, reward, done, info = env.step(action)
if render:
env.render()
state = next_state
rewards.append(reward)
infos.append(info)
if done:
break
return np.array(rewards), infos, done
| 1,007 | 307 |
import sys
import os
sys.path.append(os.path.abspath("."))
sys.dont_write_bytecode = True
__author__ = "COSAL"
from utils.lib import O
class ContestMeta(O):
def __init__(self, **kwargs):
O.__init__(self, **kwargs)
self.submission_id = None
self.contest_type = None
self.contest_id = None
self.problem_id = None
self.exec_time = None
self.code_size = None
def to_bson(self):
bson = {
"submissionId": self.submission_id
}
if self.contest_type is not None:
bson["contestType"] = self.contest_type
if self.contest_id is not None:
bson["contestId"] = self.contest_id
if self.problem_id is not None:
bson["problemId"] = self.problem_id
if self.code_size is not None:
bson["codeSize"] = self.code_size
if self.exec_time is not None:
bson["execTime"] = self.exec_time
return bson
@staticmethod
def from_bson(bson):
block = ContestMeta()
block.submission_id = bson["submissionId"]
if "contestType" in bson:
block.contest_type = bson["contestType"]
if "contestId" in bson:
block.contest_id = bson["contestId"]
else:
block.contest_id = 0
if "problemId" in bson:
block.problem_id = bson["problemId"]
else:
block.problem_id = 0
if "codeSize" in bson:
block.code_size = bson["codeSize"]
if "execTime" in bson:
block.exec_time = bson["execTime"]
return block
def make_key(self):
return "C:%d-P:%d" % (self.contest_id, self.problem_id)
| 1,522 | 565 |
"""Product Model."""
from config.database import Model
from orator.orm import belongs_to, belongs_to_many, has_many, has_one
class Product(Model):
"""Product Model."""
__fillable__ = ['name', 'category_id', 'price', 'description', 'image_folder', 'detail', 'note']
@belongs_to('category_id', 'id')
def category(self):
from app.Product_category import Product_category
return Product_category
@belongs_to_many()
def materials(self):
from app.Material import Material
return Material
@belongs_to_many('products_related', 'product_id', 'related_id')
# this somehow magically works - stores Product.id into product_id and related_products[Product].id into related_id
def related_products(self):
# referenced products
from app.Product import Product
return Product
@belongs_to_many
def orders(self):
from app.Order import Order
return Order
@belongs_to
def availability(self):
from app.Availability import Availability
return Availability
@has_many
def variants(self):
from app.Variant import Variant
return Variant.order_by('id')
@has_one
def top_product(self):
from app.TopProduct import TopProduct
return TopProduct
| 1,312 | 367 |
from PIL import Image
import json
import numpy as np
from tqdm import tqdm
with open('../../../coco/MSCOCO_train_val_Korean.json', 'r', encoding='utf-8') as f:
info = json.load(f)
# print(info[0]['file_path'])
img_path = '../../../coco/'
img_size = 64
images = np.empty((len(info), img_size, img_size, 3), dtype=np.uint8)
for i in tqdm(range(len(info))):
img = Image.open(img_path + info[i]['file_path']).convert('RGB')
img = img.resize((img_size, img_size))
img_arr = np.array(img)
images[i] = img_arr
np.save('coco_images.npy', images)
| 562 | 226 |
class Node:
def __init__(self, value):
self.value = value
self.nextnode = None
def cycle_check(node):
if not node:
return False
head = node
node = node.nextnode
while node:
if node == head:
return True
node = node.nextnode
return False
if __name__ == '__main__':
# CREATE CYCLE LIST
a = Node(1)
b = Node(2)
c = Node(3)
a.nextnode = b
b.nextnode = c
c.nextnode = a # Cycle Here!
# CREATE NON CYCLE LIST
x = Node(1)
y = Node(2)
z = Node(3)
x.nextnode = y
y.nextnode = z
print(cycle_check(a))
| 630 | 233 |
from nonebot import on_command, CommandSession
from nonebot import on_natural_language, NLPSession, IntentCommand
from jieba import posseg
@on_command("sushe", aliases=("宿舍", "寝室"), only_to_me=False)
async def sushe(session: CommandSession):
if session.event.group_id == 818278353:
await session.send("""一般都是6人间,上下铺,桌子一侧排,有空调,另外租(租比较贵,就这两年,跟舍友商量好要不要租)。
男生一般都是十里铺,也就是校外宿舍,当然还有三里屯之类的,就认准在十里铺就好)""")
@on_command("sushe_img", aliases=("宿舍照片", "寝室照片"), only_to_me=False)
async def suzheimg(session: CommandSession):
if session.event.group_id == 818278353:
await session.send("""[CQ:image,file=https://s1.ax1x.com/2020/07/27/aPVaff.jpg]""")
@on_natural_language(keywords={"宿舍", "寝室"}, only_to_me=False)
async def _(session: NLPSession):
stripped_msg = session.msg_text.strip()
words = posseg.lcut(stripped_msg)
for word in words:
if word.word == "照片":
return IntentCommand(60.0, 'sushe_img')
if word.word == "洗澡":
return IntentCommand(60.0, 'xizao')
return IntentCommand(61.0, 'sushe')
@on_command('xizao', aliases="洗澡", only_to_me=False)
async def xizao(session: CommandSession):
if session.event.group_id == 818278353:
await session.send("""男生宿舍有洗澡间,女生在校内澡堂,不过只有2楼可以洗热水澡,需要刷单独洗澡卡,可以好几个人同时洗有问题请联系:[CQ:at,qq=331456218]""")
@on_natural_language(keywords="洗澡", only_to_me=False)
async def _(session: NLPSession):
return IntentCommand(60.0, 'xizao')
@on_command("kaixue", only_to_me=False, aliases="开学")
async def kaixue(session: CommandSession):
if session.event.group_id == 818278353:
await session.send("""具体开学时候还未确定,一般9月份,咱学校有病例,估计9月份开不了学,会延期或不开学。
有问题请联系:[CQ:at,qq=331456218]""")
@on_natural_language(keywords={"开学"}, only_to_me=False)
async def _(session: NLPSession):
return IntentCommand(60.0, 'kaixue')
@on_command("zuidifen", aliases="最低分", only_to_me=False)
async def zuidifen(session: CommandSession):
if session.event.group_id == 818278353:
await session.send("""按最低分是不能考虑能不能上的,应该以你的专业招生的院校排名和人数拉一个单子,依次累加,根据你的排名来算,你可以问我如何算排名。
有问题请联系:[CQ:at,qq=331456218]""")
@on_natural_language(keywords={"最低分", "多少分"}, only_to_me=False)
async def _(session: NLPSession):
return IntentCommand(60.0, "zuidifen")
@on_command("whoisgood", aliases="哪个好", only_to_me=False)
async def whoisgood(session: CommandSession):
if session.event.group_id == 818278353:
await session.send("""河南省近几年大量扩招专升本的学生,说明对专升本学生更加重视,也说明确实对省内本科教育越来越看中,同时也为河南学子争取本科权益。
当然,河南省内本科都差不多,如果考虑普通高考中的普通二本来对比专升本哪个学校好,其实省内院校都一样的,无需纠结,因为都是省内,又不是郑大那种特别好的学校,出门人家看的是学历
有问题请联系:[CQ:at,qq=331456218]""")
@on_natural_language(keywords={"哪个好"}, only_to_me=False)
async def _(session: NLPSession):
return IntentCommand(60.0, "whoisgood")
@on_command("yonon", aliases="能不能上", only_to_me=False)
async def yonon(session: CommandSession):
if session.event.group_id == 818278353:
await session.send("[CQ:image,file=https://s1.ax1x.com/2020/07/27/aPnGgf.jpg]")
@on_natural_language(keywords={"能不能", "能"}, only_to_me=False)
async def _(session: NLPSession):
stripped_msg = session.msg_text.strip()
words = posseg.lcut(stripped_msg)
for word in words:
if word.word == "上":
return IntentCommand(60.0, "yonon")
@on_command("spm", aliases="算排名", only_to_me=False)
async def spm(session: CommandSession):
if session.event.group_id == 818278353:
await session.send("[CQ:image,file=https://s1.ax1x.com/2020/07/27/aPQAde.jpg]")
@on_natural_language(keywords={"算排名", "排名"}, only_to_me=False)
async def _(session: NLPSession):
return IntentCommand(60.0, "spm") | 3,619 | 1,946 |
# -*- coding: utf-8 -*-
"""
calculatorapi
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
from calculatorapi.decorators import lazy_property
from calculatorapi.configuration import Configuration
from calculatorapi.controllers.simple_calculator_controller import SimpleCalculatorController
class CalculatorapiClient(object):
config = Configuration
@lazy_property
def simple_calculator(self):
return SimpleCalculatorController()
| 500 | 139 |
#!/usr/bin/env python3
# MIT License
#
# Copyright (c) 2020 FABRIC Testbed
#
# 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.
#
#
# Author: Komal Thareja (kthare10@renci.org)
from datetime import datetime, timezone
from fabric_cf.actor.core.common.constants import Constants
from fabric_cf.actor.core.common.exceptions import BrokerException
from fabric_cf.actor.core.kernel.broker_query_model_publisher import BrokerQueryModelPublisher
from fabric_cf.actor.core.manage.management_utils import ManagementUtils
class BrokerKernel:
"""
Class responsible for starting Broker Periodic; also holds Management Actor
"""
def __init__(self):
from fabric_cf.actor.core.container.globals import GlobalsSingleton
self.logger = GlobalsSingleton.get().get_logger()
self.broker = GlobalsSingleton.get().get_container().get_actor()
self.producer = GlobalsSingleton.get().get_simple_kafka_producer()
self.kafka_topic = GlobalsSingleton.get().get_config().get_global_config().get_bqm_config().get(
Constants.KAFKA_TOPIC, None)
self.publish_interval = GlobalsSingleton.get().get_config().get_global_config().get_bqm_config().get(
Constants.PUBLISH_INTERVAL, None)
self.last_query_time = None
def do_periodic(self):
"""
Periodically publish BQM to a Kafka Topic to be consumed by Portal
"""
if self.kafka_topic is not None and self.publish_interval is not None and self.producer is not None:
current_time = datetime.now(timezone.utc)
if self.last_query_time is None or (current_time - self.last_query_time).seconds > self.publish_interval:
bqm = BrokerQueryModelPublisher(broker=self.broker, logger=self.logger,
kafka_topic=self.kafka_topic, producer=self.producer)
bqm.execute()
self.last_query_time = datetime.now(timezone.utc)
class BrokerKernelSingleton:
__instance = None
def __init__(self):
if self.__instance is not None:
raise BrokerException(msg="Singleton can't be created twice !")
def get(self):
"""
Actually create an instance
"""
if self.__instance is None:
self.__instance = BrokerKernel()
return self.__instance
get = classmethod(get) | 3,387 | 1,035 |
# Generated by Django 4.0 on 2021-12-17 08:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('account', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='user',
options={},
),
migrations.AlterModelManagers(
name='user',
managers=[
],
),
migrations.RemoveField(
model_name='user',
name='date_joined',
),
migrations.RemoveField(
model_name='user',
name='first_name',
),
migrations.RemoveField(
model_name='user',
name='groups',
),
migrations.RemoveField(
model_name='user',
name='is_active',
),
migrations.RemoveField(
model_name='user',
name='is_staff',
),
migrations.RemoveField(
model_name='user',
name='is_superuser',
),
migrations.RemoveField(
model_name='user',
name='last_name',
),
migrations.RemoveField(
model_name='user',
name='user_permissions',
),
migrations.RemoveField(
model_name='user',
name='username',
),
migrations.AlterField(
model_name='user',
name='email',
field=models.CharField(max_length=255, unique=True),
),
]
| 1,539 | 425 |
#!/usr/bin/env python
#-*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*-
import unittest
from bes.hardware.Ftdi import Ftdi
class TestFtdi(unittest.TestCase):
def test_find_devices(self):
devices = Ftdi.find_devices()
for device in devices:
print('DEVICE: ', device)
if __name__ == "__main__":
unittest.main()
| 372 | 145 |
import os
import random
from itertools import cycle
import cv2
import matplotlib.pyplot as plt
import numpy as np
from scipy import interp
from skimage import exposure
from skimage.feature import hog
from sklearn import metrics
from sklearn.decomposition import PCA
from sklearn.preprocessing import label_binarize
from sklearn.svm import SVC
def read_data():
img_size = (200, 200)
train_all = []
test_all = []
current_base = os.path.abspath('.')
train_path = os.path.join(current_base, "train")
test_path = os.path.join(current_base, "test")
# read train
for dir_name in os.listdir(train_path):
dir_path = os.path.join(train_path, dir_name)
class_id = int(dir_name)
for img_name in os.listdir(dir_path):
img_path = os.path.join(dir_path, img_name)
img_vec = cv2.imread(img_path, flags=1)
# print img_vec.shape
# res = cv2.resize(img_vec, (int(img_vec.shape[0]*0.5), int(img_vec.shape[1]*0.5)), interpolation=cv2.INTER_CUBIC)
res = cv2.resize(img_vec, img_size, interpolation=cv2.INTER_CUBIC)
nor_res = np.zeros_like(res)
nor_res = cv2.normalize(src=res, dst=nor_res, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)
# print nor_res.shape
nor_res = nor_res.reshape(nor_res.shape[0] * nor_res.shape[1] * nor_res.shape[2], )
train_all.append((class_id, nor_res))
# read test
for dir_name in os.listdir(test_path):
dir_path = os.path.join(test_path, dir_name)
class_id = int(dir_name)
for img_name in os.listdir(dir_path):
img_path = os.path.join(dir_path, img_name)
img_vec = cv2.imread(img_path, flags=1)
# print img_vec.shape
# res = cv2.resize(img_vec, (int(img_vec.shape[0]*0.5), int(img_vec.shape[1]*0.5)), interpolation=cv2.INTER_CUBIC)
res = cv2.resize(img_vec, img_size, interpolation=cv2.INTER_CUBIC)
nor_res = np.zeros_like(res)
nor_res = cv2.normalize(src=res, dst=nor_res, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)
nor_res = nor_res.reshape(nor_res.shape[0] * nor_res.shape[1] * nor_res.shape[2], )
test_all.append((class_id, nor_res))
return train_all, test_all
def show_hog(img):
fd, hog_img = hog(img, orientations=9, pixels_per_cell=(8, 8), cells_per_block=(1, 1), feature_vector=True,
visualise=True)
h = hog(img, orientations=9, pixels_per_cell=(16, 16), cells_per_block=(3, 3), feature_vector=True,
visualise=False)
print fd.shape
print hog_img.shape
print h.shape
print hog_img
hog_image_rescaled = exposure.rescale_intensity(hog_img, in_range=(0, 0.02))
print hog_image_rescaled
cv2.imshow("ori", img)
cv2.imshow("hog", hog_image_rescaled)
cv2.waitKey()
def draw_multi_ROC(y_test, decf, score):
y_test_bin = label_binarize(y_test, classes=[(i+1) for i in xrange(n_classes)])
# Compute macro-average ROC curve and ROC area
fpr = dict()
tpr = dict()
roc_auc = dict()
for i in range(n_classes):
fpr[i], tpr[i], _ = metrics.roc_curve(y_test_bin[:, i], decf[:, i])
roc_auc[i] = metrics.auc(fpr[i], tpr[i])
# Compute micro-average ROC curve and ROC area
fpr["micro"], tpr["micro"], _ = metrics.roc_curve(y_test_bin.ravel(), decf.ravel())
roc_auc["micro"] = metrics.auc(fpr["micro"], tpr["micro"])
# First aggregate all false positive rates
all_fpr = np.unique(np.concatenate([fpr[i] for i in range(n_classes)]))
# Then interpolate all ROC curves at this points
mean_tpr = np.zeros_like(all_fpr)
# print mean_tpr
for i in range(n_classes):
# print interp(all_fpr, fpr[i], tpr[i])
mean_tpr += interp(all_fpr, fpr[i], tpr[i])
# Finally average it and compute AUC
mean_tpr /= n_classes
fpr["macro"] = all_fpr
tpr["macro"] = mean_tpr
roc_auc["macro"] = metrics.auc(fpr["macro"], tpr["macro"])
# Plot all ROC curves
plt.figure(figsize=(20,10))
plt.title("Score: " + str(score))
plt.plot(fpr["micro"], tpr["micro"],
label='micro-average ROC curve (area = {0:0.2f})'
''.format(roc_auc["micro"]),
color='deeppink', linestyle=':', linewidth=4)
plt.plot(fpr["macro"], tpr["macro"],
label='macro-average ROC curve (area = {0:0.2f})'
''.format(roc_auc["macro"]),
color='navy', linestyle=':', linewidth=4)
lw = 2
colors = cycle([ ((round(random.uniform(0.0, 1.0), 2)), (round(random.uniform(0.0, 1.0), 2)), (round(random.uniform(0.0, 1.0), 2)))
for i in xrange(n_classes) ])
for i, color in zip(range(n_classes), colors):
plt.plot(fpr[i], tpr[i], color=color, lw=lw,
label='ROC curve of class {0} (area = {1:0.2f})'
''.format(i, roc_auc[i]))
plt.plot([0, 1], [0, 1], 'k--', lw=lw)
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
# plt.title('Some extension of Receiver operating characteristic to multi-class')
plt.legend(loc='lower right')
if os.path.exists("task3"):
os.mkdir("task3")
plt.savefig("task3/"+'pca_svm.png')
plt.show()
# plt.close()
if __name__ == "__main__":
train_all, test_all = read_data()
X_train = [ i[1] for i in train_all ]
y_train = [ i[0] for i in train_all ]
X_test = [ i[1] for i in test_all ]
y_test = [ i[0] for i in test_all ]
pca = PCA(n_components=0.95)
pca.fit(X_train)
X_pca_train = pca.transform(X_train)
X_pca_test = pca.transform(X_test)
n_classes = len(set(y_train))
svm = SVC()
svm.fit(X_pca_train, y_train)
predict = svm.predict(X_pca_test)
score = svm.score(X_pca_test, y_test)
svm.decision_function_shape = "ovr"
decf = svm.decision_function(X_pca_test)
draw_multi_ROC(y_test, decf, score)
# pix_cell += 1 | 6,097 | 2,390 |
import torch.nn as nn
import torch.nn.functional as F
from torch.optim import SGD
import torch as t
from scipy import constants
import numpy as np
import pandas as pd
from pyhdx.models import Protein
class DeltaGFit(nn.Module):
def __init__(self, deltaG):
super(DeltaGFit, self).__init__()
self.deltaG = deltaG
def forward(self, temperature, X, k_int, timepoints):
"""
# inputs, list of:
temperatures: scalar (1,)
X (N_peptides, N_residues)
k_int: (N_peptides, 1)
"""
pfact = t.exp(self.deltaG / (constants.R * temperature))
uptake = 1 - t.exp(-t.matmul((k_int / (1 + pfact)), timepoints))
return t.matmul(X, uptake)
def estimate_errors(series, deltaG): #todo refactor to data_obj
# boolean array to select residues which are exchanging (ie no nterminal resiudes, no prolines, no regions without coverage)
bools = series.coverage['exchanges'].to_numpy()
r_number = series.coverage.r_number[bools] # Residue number which exchange
deltaG = t.tensor(deltaG[bools], dtype=t.float64)
tensors = series.get_tensors(exchanges=True)
def calc_loss(deltaG_input):
criterion = t.nn.MSELoss(reduction='sum')
pfact = t.exp(deltaG_input.unsqueeze(-1) / (constants.R * tensors['temperature']))
uptake = 1 - t.exp(-t.matmul((tensors['k_int'] / (1 + pfact)), tensors['timepoints']))
output = t.matmul(tensors['X'], uptake)
loss = criterion(output, tensors['uptake'])
return loss
hessian = t.autograd.functional.hessian(calc_loss, deltaG)
hessian_inverse = t.inverse(-hessian)
covariance = np.sqrt(np.abs(np.diagonal(hessian_inverse)))
#todo return pd series?
return Protein({'covariance': covariance, 'r_number': r_number}, index='r_number')
class TorchFitResult(object):
def __init__(self, fit_object, model, **metadata):
self.fit_object = fit_object
self.model = model
self.metadata = metadata
@property
def mse_loss(self):
"""obj:`float`: Losses from mean squared error part of Lagrangian"""
mse_loss = self.metadata['mse_loss'][-1]
return mse_loss
@property
def total_loss(self):
"""obj:`float`: Total loss value of the Lagrangian"""
total_loss = self.metadata['total_loss'][-1]
return total_loss
@property
def reg_loss(self):
"""obj:`float`: Losses from regularization part of Lagrangian"""
return self.total_loss - self.mse_loss
@property
def regularization_percentage(self):
"""obj:`float`: Percentage part of the total loss that is regularization loss"""
return (self.reg_loss / self.total_loss) * 100
@property
def deltaG(self):
return self.model.deltaG.detach().numpy().squeeze()
class TorchSingleFitResult(TorchFitResult):
#todo perhaps pass KineticsFitting object (which includes temperature) (yes do then it can also have methods which return inputs)
def __init__(self, *args, **kwargs):
super(TorchSingleFitResult, self).__init__(*args, **kwargs)
#todo refactor series
@property
def series(self):
return self.fit_object
@property
def temperature(self):
return self.series.temperature
@property
def output(self):
out_dict = {}
out_dict['r_number'] = self.series.coverage.r_number
out_dict['sequence'] = self.series.coverage['sequence'].to_numpy()
out_dict['_deltaG'] = self.deltaG
out_dict['deltaG'] = out_dict['_deltaG'].copy()
out_dict['deltaG'][~self.series.coverage['exchanges']] = np.nan
if self.temperature is not None:
pfact = np.exp(out_dict['deltaG'] / (constants.R * self.temperature))
out_dict['pfact'] = pfact
#todo add possibility to add append series to protein?
#todo update order of columns
protein = Protein(out_dict, index='r_number')
protein_cov = estimate_errors(self.fit_object, self.deltaG)
protein = protein.join(protein_cov)
return protein
def __call__(self, timepoints):
"""output: Np x Nt array"""
#todo fix and tests
with t.no_grad():
#tensors = self.series.get_tensors()
temperature = t.Tensor([self.temperature])
X = t.Tensor(self.series.coverage.X) # Np x Nr
k_int = t.Tensor(self.series.coverage['k_int'].to_numpy()).unsqueeze(-1) # Nr x 1
timepoints = t.Tensor(timepoints).unsqueeze(0) # 1 x Nt
inputs = [temperature, X, k_int, timepoints]
output = self.model(*inputs)
return output.detach().numpy()
class TorchBatchFitResult(TorchFitResult):
def __init__(self, *args, **kwargs):
super(TorchBatchFitResult, self).__init__(*args, **kwargs)
@property
def output(self):
#todo directly create dataframe
quantities = ['_deltaG', 'deltaG', 'covariance', 'pfact']
names = [data_obj.name or data_obj.state for data_obj in self.fit_object.data_objs]
iterables = [names, quantities]
col_index = pd.MultiIndex.from_product(iterables, names=['State', 'Quantity'])
output_data = np.zeros((self.fit_object.Nr, self.fit_object.Ns * len(quantities)))
g_values = self.deltaG
g_values_nan = g_values.copy()
g_values_nan[~self.fit_object.exchanges] = np.nan
pfact = np.exp(g_values / (constants.R * self.fit_object.temperature[:, np.newaxis]))
output_data[:, 0::len(quantities)] = g_values.T
output_data[:, 1::len(quantities)] = g_values_nan.T
for i, data_obj in enumerate(self.fit_object.data_objs):
#todo this could use some pandas
i0 = data_obj.coverage.interval[0] - self.fit_object.interval[0]
i1 = data_obj.coverage.interval[1] - self.fit_object.interval[0]
cov = estimate_errors(data_obj, g_values[i, i0:i1]) # returns a protein? should be series
pd_series = cov['covariance']
pd_series = pd_series.reindex(self.fit_object.r_number)
output_data[:, 2+i*len(quantities)] = pd_series.to_numpy()
output_data[:, 3::len(quantities)] = pfact.T
df = pd.DataFrame(output_data, index=self.fit_object.r_number, columns=col_index)
return Protein(df)
# use multi index df: https://stackoverflow.com/questions/24290495/constructing-3d-pandas-dataframe | 6,504 | 2,160 |
from django.contrib.auth.models import User
from django.db import models
import uuid
# Create your models here.
from django.db.models import CASCADE
class Plan(models.Model):
name = models.CharField(max_length=128)
content_image = models.FileField(upload_to="content", blank=True, default='')
content_json = models.JSONField(blank=True, default=dict)
user = models.ForeignKey(User, on_delete=CASCADE, null=True, blank=True)
uuid = models.UUIDField(default=uuid.uuid4, editable=False)
def __str__(self):
if self.user:
return "{} - {}".format(self.user.username, self.name)
else:
return self.name | 665 | 211 |
# -*- coding: utf-8 -*-
from .jinja2_error import ErrorExtension
__author__ = 'Robin Hu'
__email__ = 'given.hubin@gmail.com'
__version__ = '0.1.0'
__all__ = ['ErrorExtension'] | 179 | 76 |
import collections
class MaxQueue(object):
"""
MaxQueue provides a base queue API and tracks the largest item contained
in the queue.
"""
def __init__(self):
self.items = []
self.peaks = []
def enqueue(self, x):
self.items.append(x)
while len(self.peaks) > 0 and self.peaks[-1] < x:
self.peaks.pop(-1)
self.peaks.append(x)
def dequeue(self):
if self.empty():
return None
x = self.items.pop(0)
if x == self.peaks[0]:
self.peaks.pop(0)
return x
def max(self):
return self.peaks[0] if not self.empty() else None
def empty(self):
return len(self.items) == 0
TimestampValue = collections.namedtuple('TimestampValue', ['timestamp', 'value'])
def max_rolling_window(points, window_length):
q = MaxQueue()
maxima = []
t = 0
tail = 0
head = 0
while t <= points[-1].timestamp:
while head < len(points) and points[head].timestamp <= t:
q.enqueue(points[head].value)
head += 1
while points[tail].timestamp < t - window_length:
q.dequeue()
tail += 1
maxima.append(TimestampValue(
timestamp=t,
value=q.max(),
))
t += 1
return maxima
def test():
"""
test example from figure 9.4
"""
points = [
1.3, None, 2.5, 3.7,
None, 1.4, 2.6, None,
2.2, 1.7, None, None,
None, None, 1.7
]
maxima = [
1.3, 1.3, 2.5, 3.7,
3.7, 3.7, 3.7, 2.6,
2.6, 2.6, 2.2, 2.2,
1.7, None, 1.7,
]
timestamped_points = []
for t, p in enumerate(points):
if p is not None:
timestamped_points.append(TimestampValue(
timestamp=t,
value=p,
))
results = max_rolling_window(timestamped_points, 3)
for t, r in enumerate(results):
assert r.timestamp == t
assert maxima[t] == r.value
print 'pass'
def main():
test()
if __name__ == '__main__':
main()
| 2,165 | 726 |
"""tags and base with unique
Revision ID: 035e7209663c
Revises:
Create Date: 2022-04-16 11:22:34.040818
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '035e7209663c'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('tags',
sa.Column('id', sa.BigInteger(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.Column('user_rel', sa.String(length=64), nullable=True),
sa.Column('title', sa.String(length=128), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('title', 'user_rel', name='uniq_title_user_rel')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('tags')
# ### end Alembic commands ###
| 992 | 367 |
from __future__ import annotations
from bot.config import Config
from bot.data import command
from bot.data import esc
from bot.data import format_msg
from bot.message import Message
@command('!bongo')
async def cmd_bongo(config: Config, msg: Message) -> str:
_, _, rest = msg.msg.partition(' ')
rest = rest.strip()
if rest:
rest = f'{rest} '
return format_msg(
msg,
f'awcBongo awcBongo awcBongo {esc(rest)}awcBongo awcBongo awcBongo',
)
| 486 | 161 |
"""
This module holds some utility functions used as part of the man command to format
text from CLI commands into consistent man pages that respond to the terminal
width.
"""
import curses
from recline.arg_types.positional import Positional
from recline.arg_types.remainder import Remainder
from recline.commands.cli_command import get_annotation_type
def wrapped_string(text, screen_width, prefix=0):
"""This function will take a string and make sure it can fit within the
given screen_width.
If the string is too long to fit, it will be broken on word boundaries
(specifically the ' ' character) if it can or the word will be split with
a '-' character and the second half moved to the next line.
If a prefix is given, the line(s) will be prefixed with that many ' '
characters, including any wrapped lines.
If the given string includes embeded newline characters, then each line
will be evaluated according to the rules above including breaking on word
boundaries and injecting a prefix.
"""
if not text:
return ''
new_text = ''
# if we have multiple paragraphs, then wrap each one as if it were a single line
lines = text.split('\n')
if len(lines) > 1:
for index, line in enumerate(lines):
if index > 0:
new_text += ' ' * prefix
new_text += wrapped_string(line, screen_width, prefix=prefix) + '\n'
return new_text.rstrip()
if len(text) + prefix < screen_width:
return text
words = text.split(' ')
current_line = ''
for word in words:
if prefix + len(current_line) + len(word) + 1 < screen_width:
# if word fits on line, just add it
current_line += word + ' '
else:
space_left = screen_width - (prefix + len(current_line))
if space_left < 3 or len(word) - space_left < 3:
# if not much room, move whole word to the next line
new_text += '%s\n' % current_line.rstrip()
current_line = '%s%s ' % (' ' * prefix, word)
else:
# split the word across lines with a hyphen
current_line += word[:space_left - 1] + '-'
new_text += current_line.rstrip() + "\n"
current_line = ' ' * prefix + word[space_left - 1:] + ' '
new_text += current_line.rstrip()
return new_text
def generate_help_text(screen_width, command_class):
"""Generates lines of help text which are formatted using the curses library.
The final document resembles a typical Linux-style manpage. See here:
https://www.tldp.org/HOWTO/Man-Page/q3.html
"""
# generate styled man page, one section at a time
help_text = []
indent = ' '
# command name and short description
help_text.append(('NAME\n', curses.A_BOLD))
help_text.append((indent,))
help_text.append((command_class.name, curses.A_BOLD))
help_text.append((' -- ',))
description = wrapped_string(
command_class.docstring.short_description, screen_width,
prefix=(len(command_class.name) + len(indent) + 4),
)
for line in description.split('\n'):
help_text.append(('%s\n' % line,))
help_text.append(('\n',))
# command usage details
help_text.append(('SYNOPSIS\n', curses.A_BOLD))
help_text.append((indent,))
description = wrapped_string(
command_class.get_command_usage(), screen_width, prefix=len(indent),
)
for line in description.split('\n'):
help_text.append(('%s\n' % line,))
help_text.append(('\n',))
# command detailed description
if command_class.docstring.long_description:
help_text.append(('DESCRIPTION\n', curses.A_BOLD))
help_text.append((indent,))
description = wrapped_string(
command_class.docstring.long_description, screen_width,
prefix=len(indent),
)
for line in description.split('\n'):
help_text.append(('%s\n' % line,))
help_text.append(('\n',))
# each command parameter with description, constraints, and defaults
if command_class.docstring.params:
def print_arg(arg):
meta = command_class.get_arg_metavar(arg)
description = command_class.get_arg_description(arg, indent=None)
annotation_type = get_annotation_type(arg)
positional = '' if issubclass(annotation_type, (Remainder, Positional)) else '-'
arg_name = '' if issubclass(annotation_type, Positional) else '%s ' % arg.name
prefix = '%s %s%s%s ' % (indent, positional, arg_name, meta)
help_text.append((prefix,))
description = wrapped_string(
description, screen_width, prefix=len(prefix)
)
for line in description.split('\n'):
help_text.append(('%s\n' % line,))
help_text.append(('\n'),)
help_text.append(('OPTIONS\n', curses.A_BOLD))
if command_class.required_args:
help_text.append((indent,))
help_text.append(('Required:\n', curses.A_UNDERLINE))
for arg in command_class.required_args:
print_arg(arg)
if command_class.optional_args:
help_text.append((indent,))
help_text.append(('Optional:\n', curses.A_UNDERLINE))
for arg in command_class.optional_args:
print_arg(arg)
# each command example
if command_class.docstring.examples:
help_text.append(('EXAMPLES\n', curses.A_BOLD))
for example in command_class.docstring.examples:
prefix = indent + ' '
help_text.append((indent,))
help_text.append(('%s:' % (example.name), curses.A_UNDERLINE))
help_text.append(('\n%s' % prefix,))
description = wrapped_string(
example.description, screen_width, prefix=len(prefix),
)
for line in description.split('\n'):
help_text.append(('%s\n' % line,))
return help_text
| 6,079 | 1,779 |
# -*- coding: utf-8 -*-
#
# Copyright 2017-2022 BigML
#
# 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 json
import os
from nose.tools import eq_, assert_almost_equal
from .world import world, res_filename
#@step(r'I create a local forecast for "(.*)"')
def i_create_a_local_forecast(step, input_data):
input_data = json.loads(input_data)
world.local_forecast = world.local_time_series.forecast(input_data)
#@step(r'the local forecast is "(.*)"')
def the_local_forecast_is(step, local_forecasts):
local_forecasts = json.loads(local_forecasts)
attrs = ["point_forecast", "model"]
for field_id in local_forecasts:
forecast = world.local_forecast[field_id]
local_forecast = local_forecasts[field_id]
eq_(len(forecast), len(local_forecast), "forecast: %s" % forecast)
for index in range(len(forecast)):
for attr in attrs:
if isinstance(forecast[index][attr], list):
for pos, item in enumerate(forecast[index][attr]):
assert_almost_equal(local_forecast[index][attr][pos],
item, places=5)
else:
eq_(forecast[index][attr], local_forecast[index][attr])
| 1,759 | 548 |
import pandas as pd
import streamlit as st
import openai
import os
import jsonlines
import pickle
from rank_bm25 import BM25Okapi
openai.organization = "org-eiJyreiRZUtpiu8pm6LIIA8B"
openai.api_key = st.secrets['API_KEY']
"""
# Data Science Institute x Disability Research Network: A UTS HASS-DSI Research Project
The project involves preprocessing textual data from the Royal Commission into "Aged Care Quality and Safety", and "Violence, Abuse, Neglect and Exploitation of People with Disability" and utilising natural language processing (NLP) techniques to improve document search functionality. Initial attempts were made to create a document-fetching algorithm designed to minimise the amount of time a user may spend searching relevant information.
Please upload a file in the correct data format below; otherwise you may use an existing, preprocessed file by selecting the below box.
"""
#Load documents
input = st.file_uploader('')
if input is None:
st.write("Or use sample dataset to try the application")
sample = st.checkbox("Download sample data from GitHub")
try:
if sample:
st.markdown("""[download_link](https://gist.github.com/roupenminassian/0a17d0bf8a6410dbb1b9d3f42462c063)""")
except:
pass
else:
with open("test_final.txt","rb") as fp:# Unpickling
contents = pickle.load(fp)
#Preparing model
tokenized_corpus = [doc.split(" ") for doc in contents]
bm25 = BM25Okapi(tokenized_corpus)
user_input = st.text_input('Please Enter a Query:')
corpus_selected = st.slider("Select the number of relevant documents to present:", min_value=0, max_value=5, step=1)
temperature_selected = st.slider("Set the temperature (controls how much randomness is in the output):", min_value=0.0, max_value=1.0, step=0.05)
if user_input is None:
st.write('Please enter a query above.')
else:
tokenized_query = user_input.split(" ")
doc_scores = bm25.get_scores(tokenized_query)
if st.button('Generate Text'):
generated_text = bm25.get_top_n(tokenized_query, contents, n=corpus_selected)
for i in range(corpus_selected):
st.write(generated_text[i])
GPT_text = openai.Answer.create(
search_model="davinci",
model="davinci",
question=user_input,
documents=["test.jsonl"],
#file = "file-nYWFf5V4zKtZMv82WyakRZme",
examples_context="In 2017, U.S. life expectancy was 78.6 years.",
examples=[["What is human life expectancy in the United States?","78 years."]],
max_tokens=50,
temperature = temperature_selected,
stop=["\n", "<|endoftext|>"],
)
st.write('GPT-3 Answer: ' + GPT_text['answers'][0])
| 2,749 | 893 |
from seleniumbase import BaseCase
class MyTestClass(BaseCase):
def test_bootstrap_tour(self):
self.open("https://xkcd.com/1117/")
self.assert_element('img[alt="My Sky"]')
self.create_bootstrap_tour()
self.add_tour_step("Welcome to XKCD!")
self.add_tour_step("This is the XKCD logo.", "#masthead img")
self.add_tour_step("Here's the daily webcomic.", "#comic img")
self.add_tour_step("This is the title.", "#ctitle", alignment="top")
self.add_tour_step("Click here for the next comic.", 'a[rel="next"]')
self.add_tour_step("Click here for the previous one.", 'a[rel="prev"]')
self.add_tour_step("Learn about the author here.", 'a[rel="author"]')
self.add_tour_step("Click for a random comic.", 'a[href*="/random/"]')
self.add_tour_step("Thanks for taking this tour!")
self.export_tour(filename="bootstrap_xkcd_tour.js") # Exports the tour
self.play_tour() # Plays the tour
@pytest.fixture
def default_context(self):
return {"extra_context": {}}
@pytest.fixture(
params=[
{"author": "alice"},
{"project_slug": "helloworld"},
{"author": "bob", "project_slug": "foobar"},
]
)
def extra_context(request):
return {"extra_context": request.param}
@pytest.fixture(params=["default", "extra"])
def context(request):
if request.param == "default":
return request.getfuncargvalue("default_context")
else:
return request.getfuncargvalue("extra_context")
def test_generate_project(cookies, context):
"""Call the cookiecutter API to generate a new project from a
template.
"""
result = cookies.bake(extra_context=context)
assert result.exit_code == 0
assert result.exception is None
assert result.project.isdir()
@pytest.mark.parametrize(
"test_input,expected",
[
("3+5", 8),
pytest.param("1+7", 8, marks=pytest.mark.basic),
pytest.param("2+4", 6, marks=pytest.mark.basic, id="basic_2+4"),
pytest.param(
"6*9", 42, marks=[pytest.mark.basic, pytest.mark.xfail], id="basic_6*9"
),
],
)
def test_eval(self, test_input, expected):
assert eval(test_input) == expected
# studying git branching & merging
# chautran: git checkout v1.0.24
| 2,468 | 793 |
from strawpoll import StrawpollAPIReader
from random import randrange
import requests
# Setup test fixtures for poll id `id`
id = randrange(1, 1000)
BASE_URL = 'https://strawpoll.me'
API_PATH = 'api/v2/polls'
json = requests.get('/'.join([BASE_URL, API_PATH, str(id)]))
sp = dict(json=json.text, api=StrawpollAPIReader.from_apiv2(id), url=StrawpollAPIReader.from_url('/'.join([BASE_URL, str(id)])))
# I feel these are redundant since we only need to test URL vs JSON
# to actually verify if everything is working due to how this is layered
def test_json_and_api_return_same_data():
assert(StrawpollAPIReader.from_json(sp['json']) == sp['api'])
# @with_setup(setup, teardown)
def test_api_and_url_return_same_data():
assert(sp['api'] == sp['url'])
# @with_setup(setup, teardown)
def test_json_and_url_return_same_data():
assert(StrawpollAPIReader.from_json(sp['json']) == sp['url'])
| 899 | 329 |
from aioresponses import aioresponses
from server import app as sanic_app
async def test_success_multiple_classics(test_cli):
"""Test entry data with an array of classic leagues.
Args:
test_cli (obj): The test event loop.
"""
with aioresponses(passthrough=['http://127.0.0.1:']) as m:
with open(
'tests/functional/data/'
'entry_response_multiple_classic_leagues.json'
) as f:
entry_data = f.read()
with open(
'tests/functional/data/'
'league_response_less_than_fifty.json'
) as f:
league_data = f.read()
m.get(
sanic_app.config.FPL_URL + sanic_app.config.ENTRY_DATA.format(
entry_id=123
),
status=200,
body=entry_data
)
m.get(
sanic_app.config.FPL_URL + sanic_app.config.LEAGUE_DATA.format(
league_id=1
),
status=200,
body=league_data
)
m.get(
sanic_app.config.FPL_URL + sanic_app.config.LEAGUE_DATA.format(
league_id=2
),
status=200,
body=league_data
)
resp = await test_cli.get(
'/entry_data/123?player_cookie=456'
)
assert resp.status == 200
resp_json = await resp.json()
assert resp_json == {
"name": "TEAM A",
"leagues": [
{
"id": 1,
"name": "LEAGUE A",
},
{
"id": 2,
"name": "LEAGUE B",
}
]
}
async def test_success_multiple_classics_some_more_than_fifty(test_cli):
"""Test entry data with an array of classic leagues some with more than
fifty entries.
Args:
test_cli (obj): The test event loop.
"""
with aioresponses(passthrough=['http://127.0.0.1:']) as m:
with open(
'tests/functional/data/'
'entry_response_multiple_classic_leagues.json'
) as f:
entry_data = f.read()
with open(
'tests/functional/data/'
'league_response_less_than_fifty.json'
) as f:
league_data_less_than_fifty = f.read()
with open(
'tests/functional/data/'
'league_response_more_than_fifty.json'
) as f:
league_data_more_than_fifty = f.read()
m.get(
sanic_app.config.FPL_URL + sanic_app.config.ENTRY_DATA.format(
entry_id=123
),
status=200,
body=entry_data
)
m.get(
sanic_app.config.FPL_URL + sanic_app.config.LEAGUE_DATA.format(
league_id=1
),
status=200,
body=league_data_less_than_fifty
)
m.get(
sanic_app.config.FPL_URL + sanic_app.config.LEAGUE_DATA.format(
league_id=2
),
status=200,
body=league_data_more_than_fifty
)
resp = await test_cli.get(
'/entry_data/123?player_cookie=456'
)
assert resp.status == 200
resp_json = await resp.json()
assert resp_json == {
"name": "TEAM A",
"leagues": [
{
"id": 1,
"name": "LEAGUE A",
}
]
}
async def test_league_api_bad_response(test_cli):
"""Test entry data with a bad response from league API.
Args:
test_cli (obj): The test event loop.
"""
with aioresponses(passthrough=['http://127.0.0.1:']) as m:
with open(
'tests/functional/data/'
'entry_response_single_classic_league.json'
) as f:
entry_data = f.read()
with open(
'tests/functional/data/'
'bad_response.json'
) as f:
league_data = f.read()
m.get(
sanic_app.config.FPL_URL + sanic_app.config.ENTRY_DATA.format(
entry_id=123
),
status=200,
body=entry_data
)
m.get(
sanic_app.config.FPL_URL + sanic_app.config.LEAGUE_DATA.format(
league_id=1
),
status=200,
body=league_data
)
resp = await test_cli.get(
'/entry_data/123?player_cookie=456'
)
assert resp.status == 500
resp_json = await resp.json()
assert resp_json == {
"error": "THERE WAS A PROBLEM WITH THE DATA RETURNED FROM FPL"
}
async def test_success_single_classics(test_cli):
"""Test entry data with a single classic league.
Args:
test_cli (obj): The test event loop.
"""
with aioresponses(passthrough=['http://127.0.0.1:']) as m:
with open(
'tests/functional/data/'
'entry_response_single_classic_league.json'
) as f:
entry_data = f.read()
with open(
'tests/functional/data/'
'league_response_less_than_fifty.json'
) as f:
league_data = f.read()
m.get(
sanic_app.config.FPL_URL + sanic_app.config.ENTRY_DATA.format(
entry_id=123
),
status=200,
body=entry_data
)
m.get(
sanic_app.config.FPL_URL + sanic_app.config.LEAGUE_DATA.format(
league_id=1
),
status=200,
body=league_data
)
resp = await test_cli.get(
'/entry_data/123?player_cookie=456'
)
assert resp.status == 200
resp_json = await resp.json()
assert resp_json == {
"name": "TEAM A",
"leagues": [
{
"id": 1,
"name": "LEAGUE A",
}
]
}
async def test_no_leagues(test_cli):
"""Test entry data with no leagues.
Args:
test_cli (obj): The test event loop.
"""
with aioresponses(passthrough=['http://127.0.0.1:']) as m:
with open(
'tests/functional/data/entry_response_no_leagues.json'
) as f:
fpl_data = f.read()
m.get(
sanic_app.config.FPL_URL + sanic_app.config.ENTRY_DATA.format(
entry_id=123
),
status=200,
body=fpl_data
)
resp = await test_cli.get(
'/entry_data/123?player_cookie=456'
)
assert resp.status == 200
resp_json = await resp.json()
assert resp_json == {
"name": "TEAM A",
"leagues": []
}
async def test_no_name(test_cli):
"""Test entry data with no name.
Args:
test_cli (obj): The test event loop.
"""
with aioresponses(passthrough=['http://127.0.0.1:']) as m:
with open(
'tests/functional/data/entry_response_no_name.json'
) as f:
entry_data = f.read()
with open(
'tests/functional/data/'
'league_response_less_than_fifty.json'
) as f:
league_data = f.read()
m.get(
sanic_app.config.FPL_URL + sanic_app.config.ENTRY_DATA.format(
entry_id=123
),
status=200,
body=entry_data
)
m.get(
sanic_app.config.FPL_URL + sanic_app.config.LEAGUE_DATA.format(
league_id=1
),
status=200,
body=league_data
)
resp = await test_cli.get(
'/entry_data/123?player_cookie=456'
)
assert resp.status == 200
resp_json = await resp.json()
assert resp_json == {
"name": None,
"leagues": [
{
"id": 1,
"name": "LEAGUE A",
}
]
}
async def test_no_player_cookie(test_cli):
"""Test entry data with no player_cookie.
Args:
test_cli (obj): The test event loop.
"""
resp = await test_cli.get(
'/entry_data/123?player_cookie='
)
assert resp.status == 400
resp_json = await resp.json()
assert resp_json == {
"error": "PARAMETERS REQUIRED: player_cookie"
}
async def test_fpl_error_response(test_cli):
"""Test entry data with an error response from FPL.
Args:
test_cli (obj): The test event loop.
"""
with aioresponses(passthrough=['http://127.0.0.1:']) as m:
m.get(
sanic_app.config.FPL_URL + sanic_app.config.ENTRY_DATA.format(
entry_id=123
),
status=500,
body=None
)
resp = await test_cli.get(
'/entry_data/123?player_cookie=456'
)
assert resp.status == 500
resp_json = await resp.json()
assert resp_json == {
"error": "ERROR CONNECTING TO THE FANTASY API"
}
| 9,267 | 2,971 |
import numpy as np
from ..core.derivative import Derivative
class AsianCallOption(Derivative):
def __init__(self, S, K, T, r, sigma, steps, **kwargs):
super().__init__(S_0=S, T=T, r=r, sigma=sigma, steps=steps, **kwargs)
self.S = S
self.K = K
self.T = T
self.r = r
self.sigma = sigma
def payoff(self, underlyingAssetPath, **kwargs):
return max(underlyingAssetPath.mean() - self.K, 0) * np.exp(-self.r * self.T)
class AsianPutOption(Derivative):
def __init__(self, S, K, T, r, sigma, steps, **kwargs):
super().__init__(S_0=S, T=T, r=r, sigma=sigma, steps=steps, **kwargs)
self.S = S
self.K = K
self.T = T
self.r = r
self.sigma = sigma
def payoff(self, underlyingAssetPath, **kwargs):
return max(self.K - underlyingAssetPath.mean(), 0) * np.exp(-self.r * self.T)
| 916 | 331 |
#!/usr/bin/env python3
"""Annotate the output of ReQTL as cis or trans
Created on Aug, 29 2020
@author: Nawaf Alomran
This module annotates the output of ReQTL as cis or trans based on whether the
SNVs resides within its paired gene.
Input + Options
----------------
+ -r: the path to the ReQTL analysis result file
+ -ga: the path to the file gene location annotations
+ -o: the prefix for the output annotated result
Output
------
+ a file with the ReQTLs annotated as cis or trans
How to Run
----------
python -m PyReQTL.annotate \
-r output/ReQTL_test_all_ReQTLs.txt \
-ga data/gene_locations_hg38.txt \
-o ReQTL_test \
-c True
* Python runtime via time command 8.19s user 0.61s system 112% cpu 7.838 total
* R time command line 3.15s user 0.22s system 99% cpu 3.383 total
* Note that the speed after the importr statements Python is faster than than R
"""
import argparse
import sys
from datetime import datetime
import numpy as np # type: ignore
import pandas as pd # type: ignore
import rpy2.robjects.packages as rpackages # type: ignore
from rpy2.robjects import pandas2ri # type: ignore
from rpy2.robjects.packages import importr # type: ignore
try:
from common import (create_output_dir, output_filename_generator,
bool_conv_args)
except ModuleNotFoundError:
from PyReQTL.common import (create_output_dir, output_filename_generator,
bool_conv_args)
# install the R package GenomicFeatures from within Python
if not rpackages.isinstalled('GenomicFeatures'):
print("installing GenomicFeatures package ...")
bioc_manager = rpackages.importr('BiocManager')
bioc_manager.install('GenomicFeatures')
print("Done installing the package.")
# importing the following required R packages to be used within Python
print("Kindly wait for the required R packages to be imported into Python...")
g_ranges = importr('GenomicRanges')
print("GenomicRanges package is imported.")
g_alignments = importr('GenomicAlignments')
print("GenomicAlignments package is imported.")
iranges = importr('IRanges')
print("IRanges package is imported.")
print("Done importing.")
# This needs to be activated in order to perform pandas conversion
pandas2ri.activate()
def cis_trans_annotator(rqt_rst: str,
gene_ann: str,
out_prefx: str,
cli: bool = False) -> None:
"""Annotate the output of ReQTL as cis or trans based on whether the
SNVs resides within its paired gene
Parameter
---------
rqt_rst: the path to the ReQTL analysis result file
gene_ann: the path to the file gene location annotation
out_prefx: the prefix for the output annotated result
cli: Whether the function is been executed with the command line.
Default is False.
Return
------
reqtl_reslt_arranged: dataframe ReQTLs annotated as cis or trans
Output
------
- file with the ReQTLs annotated as cis or trans
"""
start_time = datetime.now()
# reading the ReQTL result file from run_matrix_ReQTL
reqtl_result = pd.read_table(rqt_rst, sep="\t")
# ------------------------------------------------------------------------#
# ------------------------------------------------------------------------#
# -----------------annotate which gene harbors the snp--------------------#
# classify ReQTLs in which the two members of the pair are in the same----#
# gene as cis and classify all others as trans----------------------------#
# ------------------------------------------------------------------------#
# ------------------------------------------------------------------------#
reqtl_reslt_arranged = reqtl_result.assign(new_SNP=reqtl_result.SNP)
# split them into four columns based on the pattern "[:_>]"
reqtl_reslt_arranged = reqtl_reslt_arranged.new_SNP.str.split('[:_>]',
expand=True)
reqtl_reslt_arranged.columns = ['chrom', 'start', 'ref', 'alt']
# concatenating the re-arranged dataframe with the original dataframe
reqtl_reslt_arranged = pd.concat([reqtl_result, reqtl_reslt_arranged],
axis=1)
# making the new end column the same as the start column
reqtl_reslt_arranged = reqtl_reslt_arranged.assign(
end=reqtl_reslt_arranged.start)
# convert Python Pandas DataFrame to R-dataframe
reqtl_result_df_r = pandas2ri.py2rpy(reqtl_reslt_arranged)
# read gene location file and then convert to R dataframe
gene_locs_py_df = pd.read_table(gene_ann, sep="\t")
gene_locs_df_r = pandas2ri.py2rpy(gene_locs_py_df)
# storing the location of genomic features for both R dataframes
reqtl_reslt_granges_r = g_ranges.GRanges(reqtl_result_df_r)
gene_loc_granges_r = g_ranges.GRanges(gene_locs_df_r)
# finding the overlap between the ranges
overlaps = iranges.findOverlaps(reqtl_reslt_granges_r,
gene_loc_granges_r,
select="last",
type="within")
# ignore the Pycharm warning later
overlaps = np.where(overlaps == -2147483648, None, overlaps)
overlaps = overlaps.tolist()
# reindex the gene_locs dataframe by the overlaps
genes_snp = gene_locs_py_df.ensembl_gene.reindex(overlaps)
reqtl_reslt_arranged['genes_snp'] = pd.Series(genes_snp.values.tolist())
# if genes_snp == gene in reqtl_reslt_arranged dataframe then it cis
# otherwise it will be trans
reqtl_reslt_arranged['class'] = np.where(
reqtl_reslt_arranged.genes_snp == reqtl_reslt_arranged.gene,
'cis',
'trans')
reqtl_reslt_arranged.loc[reqtl_reslt_arranged['genes_snp'].isna(),
'class'] = reqtl_reslt_arranged['genes_snp']
# drop the unneeded columns
reqtl_reslt_arranged.drop(
['chrom',
'end',
'ref',
'alt',
'start'], axis=1, inplace=True)
out_dir = create_output_dir("output")
annotated_file = output_filename_generator(out_dir,
out_prefx,
"_ReQTLs_cistrans_ann.txt")
reqtl_reslt_arranged.to_csv(annotated_file, sep="\t", index=False,
na_rep='NULL')
print(f"\nCis/trans annotated ReQTLs saved in {annotated_file}\n")
if cli:
print(f"Analysis took after importing the required packages "
f"{(datetime.now() - start_time).total_seconds()} sec")
else:
return reqtl_reslt_arranged
def main() -> None:
"""Parses the command line arguments entered by the user
Parameters
---------
None
Return
-------
None
"""
USAGE = """Annotate the output of ReQTL as cis or trans based on whether
the SNV resides within its paired gene"""
parser = argparse.ArgumentParser(description=USAGE)
parser.add_argument('-r',
dest="rqt_rst",
required=True,
help="the path to the ReQTL analysis result file")
parser.add_argument('-ga',
dest='gene_ann',
required=True,
help="the path to the file gene location annotations")
parser.add_argument('-o',
dest="out_prefx",
required=True,
help="the prefix for the output annotated result")
parser.add_argument("-c",
dest="cli",
default=False,
type=bool_conv_args,
help="""Whether the function is been executed with the
command line. Default is False!""")
args = parser.parse_args()
rqt_rst = args.rqt_rst
gene_ann = args.gene_ann
out_prefx = args.out_prefx
cli = args.cli
try:
cis_trans_annotator(rqt_rst, gene_ann, out_prefx, cli)
except KeyboardInterrupt:
sys.exit('\nthe user ends the program')
if __name__ == '__main__':
main()
| 8,283 | 2,505 |
#!/usr/bin/env python
"""
Import a Firefox bookmarks file into a single json list
"""
import json
import pprint
def walk(struct, depth=0):
children = struct.get('children')
if children:
for child in children:
if child.get('type') == 'text/x-moz-place':
title = child.get('title')
uri = child.get('uri')
tags = child.get('tags')
if tags:
tag_l = [tag for tag in tags.split(',')]
else:
tag_l = []
out_dict = {'title': title,
'uri': uri,
'tags': tag_l
}
if out_dict not in my_marks:
my_marks.append(out_dict)
walk(child)
with open("bmarks") as f:
my_marks = []
j = json.load(f)
walk(j)
print(json.dumps(my_marks, indent=2))
| 940 | 270 |
# Generated by Django 2.0.5 on 2021-10-05 00:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('common', '0004_photos'),
('devices', '0002_auto_20201017_2132'),
]
operations = [
migrations.AddField(
model_name='device',
name='photos',
field=models.ManyToManyField(to='common.Photo'),
),
]
| 429 | 158 |
# ------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# ------------------------------------------------------------------------------
from collections import deque
import cv2
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from models import *
from models.decode import mot_decode
from models.model import create_model, load_model
from models.utils import _tranpose_and_gather_feat, _tranpose_and_gather_feat_expand
from tracker import matching
from tracking_utils.kalman_filter import KalmanFilter
from tracking_utils.log import logger
from tracking_utils.utils import *
from utils.post_process import ctdet_post_process
from cython_bbox import bbox_overlaps as bbox_ious
from .basetrack import BaseTrack, TrackState
from scipy.optimize import linear_sum_assignment
import random
import pickle
import copy
class GaussianBlurConv(nn.Module):
def __init__(self, channels=3):
super(GaussianBlurConv, self).__init__()
self.channels = channels
kernel = [[0.00078633, 0.00655965, 0.01330373, 0.00655965, 0.00078633],
[0.00655965, 0.05472157, 0.11098164, 0.05472157, 0.00655965],
[0.01330373, 0.11098164, 0.22508352, 0.11098164, 0.01330373],
[0.00655965, 0.05472157, 0.11098164, 0.05472157, 0.00655965],
[0.00078633, 0.00655965, 0.01330373, 0.00655965, 0.00078633]]
kernel = torch.FloatTensor(kernel).unsqueeze(0).unsqueeze(0)
kernel = np.repeat(kernel, self.channels, axis=0)
self.weight = nn.Parameter(data=kernel, requires_grad=False)
def __call__(self, x):
x = F.conv2d(x, self.weight, padding=2, groups=self.channels)
return x
gaussianBlurConv = GaussianBlurConv().cuda()
seed = 0
random.seed(seed)
np.random.seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
# Remove randomness (may be slower on Tesla GPUs)
# https://pytorch.org/docs/stable/notes/randomness.html
if seed == 0:
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
smoothL1 = torch.nn.SmoothL1Loss()
mse = torch.nn.MSELoss()
td_ = {}
def bbox_dis(bbox1, bbox2):
center1 = (bbox1[:, :2] + bbox1[:, 2:]) / 2
center2 = (bbox2[:, :2] + bbox2[:, 2:]) / 2
center1 = np.repeat(center1.reshape(-1, 1, 2), len(bbox2), axis=1)
center2 = np.repeat(center2.reshape(1, -1, 2), len(bbox1), axis=0)
dis = np.sqrt(np.sum((center1 - center2) ** 2, axis=-1))
return dis
class STrack(BaseTrack):
shared_kalman = KalmanFilter()
shared_kalman_ = KalmanFilter()
def __init__(self, tlwh, score, temp_feat, buffer_size=30):
# wait activate
self._tlwh = np.asarray(tlwh, dtype=np.float)
self.kalman_filter = None
self.mean, self.covariance = None, None
self.is_activated = False
self.score = score
self.tracklet_len = 0
self.exist_len = 1
self.smooth_feat = None
self.smooth_feat_ad = None
self.update_features(temp_feat)
self.features = deque([], maxlen=buffer_size)
self.alpha = 0.9
self.curr_tlbr = self.tlwh_to_tlbr(self._tlwh)
self.det_dict = {}
def get_v(self):
return self.mean[4:6] if self.mean is not None else None
def update_features_ad(self, feat):
feat /= np.linalg.norm(feat)
if self.smooth_feat_ad is None:
self.smooth_feat_ad = feat
else:
self.smooth_feat_ad = self.alpha * self.smooth_feat_ad + (1 - self.alpha) * feat
self.smooth_feat_ad /= np.linalg.norm(self.smooth_feat_ad)
def update_features(self, feat):
feat /= np.linalg.norm(feat)
self.curr_feat = feat
if self.smooth_feat is None:
self.smooth_feat = feat
else:
self.smooth_feat = self.alpha * self.smooth_feat + (1 - self.alpha) * feat
self.features.append(feat)
self.smooth_feat /= np.linalg.norm(self.smooth_feat)
def predict(self):
mean_state = self.mean.copy()
if self.state != TrackState.Tracked:
mean_state[7] = 0
self.mean, self.covariance = self.kalman_filter.predict(mean_state, self.covariance)
@staticmethod
def multi_predict(stracks):
if len(stracks) > 0:
multi_mean = np.asarray([st.mean.copy() for st in stracks])
multi_covariance = np.asarray([st.covariance for st in stracks])
for i, st in enumerate(stracks):
if st.state != TrackState.Tracked:
multi_mean[i][7] = 0
multi_mean, multi_covariance = STrack.shared_kalman.multi_predict(multi_mean, multi_covariance)
for i, (mean, cov) in enumerate(zip(multi_mean, multi_covariance)):
stracks[i].mean = mean
stracks[i].covariance = cov
@staticmethod
def multi_predict_(stracks):
if len(stracks) > 0:
multi_mean = np.asarray([st.mean.copy() for st in stracks])
multi_covariance = np.asarray([st.covariance for st in stracks])
for i, st in enumerate(stracks):
if st.state != TrackState.Tracked:
multi_mean[i][7] = 0
multi_mean, multi_covariance = STrack.shared_kalman_.multi_predict(multi_mean, multi_covariance)
for i, (mean, cov) in enumerate(zip(multi_mean, multi_covariance)):
stracks[i].mean = mean
stracks[i].covariance = cov
def activate(self, kalman_filter, frame_id, track_id=None):
"""Start a new tracklet"""
self.kalman_filter = kalman_filter
if track_id:
self.track_id = track_id['track_id']
track_id['track_id'] += 1
else:
self.track_id = self.next_id()
self.mean, self.covariance = self.kalman_filter.initiate(self.tlwh_to_xyah(self._tlwh))
self.tracklet_len = 0
self.state = TrackState.Tracked
self.is_activated = True
self.frame_id = frame_id
self.start_frame = frame_id
def activate_(self, kalman_filter, frame_id, track_id=None):
"""Start a new tracklet"""
self.kalman_filter = kalman_filter
if track_id:
self.track_id = track_id['track_id']
track_id['track_id'] += 1
else:
self.track_id = self.next_id_()
self.mean, self.covariance = self.kalman_filter.initiate(self.tlwh_to_xyah(self._tlwh))
self.tracklet_len = 0
self.state = TrackState.Tracked
self.is_activated = True
self.frame_id = frame_id
self.start_frame = frame_id
def re_activate(self, new_track, frame_id, new_id=False):
self.curr_tlbr = self.tlwh_to_tlbr(new_track.tlwh)
self.mean, self.covariance = self.kalman_filter.update(
self.mean, self.covariance, self.tlwh_to_xyah(new_track.tlwh)
)
self.update_features(new_track.curr_feat)
self.tracklet_len = 0
self.exist_len += 1
self.state = TrackState.Tracked
self.is_activated = True
self.frame_id = frame_id
if new_id:
self.track_id = self.next_id()
def re_activate_(self, new_track, frame_id, new_id=False):
self.curr_tlbr = self.tlwh_to_tlbr(new_track.tlwh)
self.mean, self.covariance = self.kalman_filter.update(
self.mean, self.covariance, self.tlwh_to_xyah(new_track.tlwh)
)
self.update_features(new_track.curr_feat)
self.tracklet_len = 0
self.exist_len += 1
self.state = TrackState.Tracked
self.is_activated = True
self.frame_id = frame_id
if new_id:
self.track_id = self.next_id_()
def update(self, new_track, frame_id, update_feature=True):
"""
Update a matched track
:type new_track: STrack
:type frame_id: int
:type update_feature: bool
:return:
"""
self.frame_id = frame_id
self.tracklet_len += 1
self.exist_len += 1
self.curr_tlbr = self.tlwh_to_tlbr(new_track.tlwh)
new_tlwh = new_track.tlwh
self.mean, self.covariance = self.kalman_filter.update(
self.mean, self.covariance, self.tlwh_to_xyah(new_tlwh))
self.state = TrackState.Tracked
self.is_activated = True
self.score = new_track.score
if update_feature:
self.update_features(new_track.curr_feat)
@property
# @jit(nopython=True)
def tlwh(self):
"""Get current position in bounding box format `(top left x, top left y,
width, height)`.
"""
if self.mean is None:
return self._tlwh.copy()
ret = self.mean[:4].copy()
ret[2] *= ret[3]
ret[:2] -= ret[2:] / 2
return ret
@property
# @jit(nopython=True)
def tlbr(self):
"""Convert bounding box to format `(min x, min y, max x, max y)`, i.e.,
`(top left, bottom right)`.
"""
ret = self.tlwh.copy()
ret[2:] += ret[:2]
return ret
@staticmethod
# @jit(nopython=True)
def tlwh_to_xyah(tlwh):
"""Convert bounding box to format `(center x, center y, aspect ratio,
height)`, where the aspect ratio is `width / height`.
"""
ret = np.asarray(tlwh).copy()
ret[:2] += ret[2:] / 2
ret[2] /= ret[3]
return ret
def to_xyah(self):
return self.tlwh_to_xyah(self.tlwh)
@staticmethod
# @jit(nopython=True)
def tlbr_to_tlwh(tlbr):
ret = np.asarray(tlbr).copy()
ret[2:] -= ret[:2]
return ret
@staticmethod
# @jit(nopython=True)
def tlwh_to_tlbr(tlwh):
ret = np.asarray(tlwh).copy()
ret[2:] += ret[:2]
return ret
def __repr__(self):
return 'OT_{}_({}-{})'.format(self.track_id, self.start_frame, self.end_frame)
class JDETracker(object):
def __init__(
self,
opt,
frame_rate=30,
tracked_stracks=[],
lost_stracks=[],
removed_stracks=[],
frame_id=0,
ad_last_info={},
model=None
):
self.opt = opt
print('Creating model...')
if model:
self.model = model
else:
self.model = create_model(opt.arch, opt.heads, opt.head_conv)
self.model = load_model(self.model, opt.load_model).cuda()
self.model.eval()
self.log_index = []
self.unconfirmed_ad_iou = None
self.tracked_stracks_ad_iou = None
self.strack_pool_ad_iou = None
self.tracked_stracks = copy.deepcopy(tracked_stracks) # type: list[STrack]
self.lost_stracks = copy.deepcopy(lost_stracks) # type: list[STrack]
self.removed_stracks = copy.deepcopy(removed_stracks) # type: list[STrack]
self.tracked_stracks_ad = copy.deepcopy(tracked_stracks) # type: list[STrack]
self.lost_stracks_ad = copy.deepcopy(lost_stracks) # type: list[STrack]
self.removed_stracks_ad = copy.deepcopy(removed_stracks) # type: list[STrack]
self.tracked_stracks_ = copy.deepcopy(tracked_stracks) # type: list[STrack]
self.lost_stracks_ = copy.deepcopy(lost_stracks) # type: list[STrack]
self.removed_stracks_ = copy.deepcopy(removed_stracks) # type: list[STrack]
self.frame_id = frame_id
self.frame_id_ = frame_id
self.frame_id_ad = frame_id
self.det_thresh = opt.conf_thres
self.buffer_size = int(frame_rate / 30.0 * opt.track_buffer)
self.max_time_lost = self.buffer_size
self.max_per_image = 128
self.kalman_filter = KalmanFilter()
self.kalman_filter_ad = KalmanFilter()
self.kalman_filter_ = KalmanFilter()
self.attacked_ids = set([])
self.low_iou_ids = set([])
self.ATTACK_IOU_THR = opt.iou_thr
self.attack_iou_thr = self.ATTACK_IOU_THR
self.ad_last_info = copy.deepcopy(ad_last_info)
self.FRAME_THR = 10
self.temp_i = 0
self.multiple_ori_ids = {}
self.multiple_att_ids = {}
self.multiple_ori2att = {}
self.multiple_att_freq = {}
# hijacking attack
self.ad_bbox = True
self.ad_ids = set([])
def post_process(self, dets, meta):
dets = dets.detach().cpu().numpy()
dets = dets.reshape(1, -1, dets.shape[2])
dets = ctdet_post_process(
dets.copy(), [meta['c']], [meta['s']],
meta['out_height'], meta['out_width'], self.opt.num_classes)
for j in range(1, self.opt.num_classes + 1):
dets[0][j] = np.array(dets[0][j], dtype=np.float32).reshape(-1, 5)
return dets[0]
def merge_outputs(self, detections):
results = {}
for j in range(1, self.opt.num_classes + 1):
results[j] = np.concatenate(
[detection[j] for detection in detections], axis=0).astype(np.float32)
scores = np.hstack(
[results[j][:, 4] for j in range(1, self.opt.num_classes + 1)])
if len(scores) > self.max_per_image:
kth = len(scores) - self.max_per_image
thresh = np.partition(scores, kth)[kth]
for j in range(1, self.opt.num_classes + 1):
keep_inds = (results[j][:, 4] >= thresh)
results[j] = results[j][keep_inds]
return results
@staticmethod
def recoverImg(im_blob, img0):
height = 608
width = 1088
im_blob = im_blob.cpu() * 255.0
shape = img0.shape[:2] # shape = [height, width]
ratio = min(float(height) / shape[0], float(width) / shape[1])
new_shape = (round(shape[1] * ratio), round(shape[0] * ratio)) # new_shape = [width, height]
dw = (width - new_shape[0]) / 2 # width padding
dh = (height - new_shape[1]) / 2 # height padding
top, bottom = round(dh - 0.1), round(dh + 0.1)
left, right = round(dw - 0.1), round(dw + 0.1)
im_blob = im_blob.squeeze().permute(1, 2, 0)[top:height - bottom, left:width - right, :].numpy().astype(
np.uint8)
im_blob = cv2.cvtColor(im_blob, cv2.COLOR_RGB2BGR)
h, w, _ = img0.shape
im_blob = cv2.resize(im_blob, (w, h))
return im_blob
def recoverNoise(self, noise, img0):
height = 608
width = 1088
shape = img0.shape[:2] # shape = [height, width]
ratio = min(float(height) / shape[0], float(width) / shape[1])
new_shape = (round(shape[1] * ratio), round(shape[0] * ratio)) # new_shape = [width, height]
dw = (width - new_shape[0]) / 2 # width padding
dh = (height - new_shape[1]) / 2 # height padding
top, bottom = round(dh - 0.1), round(dh + 0.1)
left, right = round(dw - 0.1), round(dw + 0.1)
noise = noise[:, :, top:height - bottom, left:width - right]
h, w, _ = img0.shape
# noise = self.resizeTensor(noise, h, w).cpu().squeeze().permute(1, 2, 0).numpy()
noise = noise.cpu().squeeze().permute(1, 2, 0).numpy()
noise = (noise[:, :, ::-1] * 255).astype(np.int)
return noise
@staticmethod
def resizeTensor(tensor, height, width):
h = torch.linspace(-1, 1, height).view(-1, 1).repeat(1, width).to(tensor.device)
w = torch.linspace(-1, 1, width).repeat(height, 1).to(tensor.device)
grid = torch.cat((h.unsqueeze(2), w.unsqueeze(2)), dim=2)
grid = grid.unsqueeze(0)
output = F.grid_sample(tensor, grid=grid, mode='bilinear', align_corners=True)
return output
@staticmethod
def processIoUs(ious):
h, w = ious.shape
assert h == w
ious = np.tril(ious, -1)
index = np.argsort(-ious.reshape(-1))
indSet = set([])
for ind in index:
i = ind // h
j = ind % w
if ious[i, j] == 0:
break
if i in indSet or j in indSet:
ious[i, j] = 0
else:
indSet.add(i)
indSet.add(j)
return ious
def attack_sg_hj(
self,
im_blob,
img0,
dets,
inds,
remain_inds,
last_info,
outputs_ori,
attack_id,
attack_ind,
ad_bbox,
track_v
):
noise = torch.zeros_like(im_blob)
im_blob_ori = im_blob.clone().data
outputs = outputs_ori
H, W = outputs_ori['hm'].size()[2:]
hm_index = inds[0][remain_inds]
hm_index_att = hm_index[attack_ind].item()
index = list(range(hm_index.size(0)))
index.pop(attack_ind)
wh_ori = outputs['wh'].clone().data
reg_ori = outputs['reg'].clone().data
i = 0
while True:
i += 1
loss = 0
hm_index_att_lst = [hm_index_att]
loss -= ((outputs['hm'].view(-1)[hm_index_att_lst].sigmoid()) ** 2).mean()
if ad_bbox:
assert track_v is not None
hm_index_gen = hm_index_att_lst[0]
hm_index_gen += -(np.sign(track_v[0]) + W * np.sign(track_v[1]))
loss -= ((1 - outputs['hm'].view(-1)[[hm_index_gen]].sigmoid()) ** 2).mean()
loss -= smoothL1(outputs['wh'].view(2, -1)[:, [hm_index_gen]].T,
wh_ori.view(2, -1)[:, hm_index_att_lst].T)
loss -= smoothL1(outputs['reg'].view(2, -1)[:, [hm_index_gen]].T,
reg_ori.view(2, -1)[:, hm_index_att_lst].T)
loss.backward()
grad = im_blob.grad
grad /= (grad ** 2).sum().sqrt() + 1e-8
noise += grad * 2
im_blob = torch.clip(im_blob_ori + noise, min=0, max=1).data
outputs, suc, _ = self.forwardFeatureDet(
im_blob,
img0,
dets,
[attack_ind],
thr=1 if ad_bbox else 0,
vs=[track_v] if ad_bbox else []
)
if suc:
break
if i > 60:
break
return noise, i, suc
def attack_sg_det(
self,
im_blob,
img0,
dets,
inds,
remain_inds,
last_info,
outputs_ori,
attack_id,
attack_ind
):
noise = torch.zeros_like(im_blob)
im_blob_ori = im_blob.clone().data
outputs = outputs_ori
H, W = outputs_ori['hm'].size()[2:]
hm_index = inds[0][remain_inds]
hm_index_att = hm_index[attack_ind].item()
index = list(range(hm_index.size(0)))
index.pop(attack_ind)
i = 0
while True:
i += 1
loss = 0
hm_index_att_lst = [hm_index_att]
# for n_i in range(3):
# for n_j in range(3):
# hm_index_att_ = hm_index_att + (n_i - 1) * W + (n_j - 1)
# hm_index_att_ = max(0, min(H * W - 1, hm_index_att_))
# hm_index_att_lst.append(hm_index_att_)
loss -= ((outputs['hm'].view(-1)[hm_index_att_lst].sigmoid()) ** 2).mean()
# loss += ((outputs['hm'].view(-1)[hm_index_att_lst].sigmoid()) ** 2 *
# torch.log(1 - outputs['hm'].view(-1)[hm_index_att_lst].sigmoid())).mean()
loss.backward()
grad = im_blob.grad
grad /= (grad ** 2).sum().sqrt() + 1e-8
noise += grad * 2
im_blob = torch.clip(im_blob_ori + noise, min=0, max=1).data
outputs, suc, _ = self.forwardFeatureDet(
im_blob,
img0,
dets,
[attack_ind]
)
if suc:
break
if i > 60:
break
return noise, i, suc
def attack_mt_hj(
self,
im_blob,
img0,
dets,
inds,
remain_inds,
last_info,
outputs_ori,
attack_ids,
attack_inds,
ad_ids,
track_vs
):
img0_h, img0_w = img0.shape[:2]
H, W = outputs_ori['hm'].size()[2:]
r_w, r_h = img0_w / W, img0_h / H
r_max = max(r_w, r_h)
noise = torch.zeros_like(im_blob)
im_blob_ori = im_blob.clone().data
outputs = outputs_ori
wh_ori = outputs['wh'].clone().data
reg_ori = outputs['reg'].clone().data
i = 0
hm_index = inds[0][remain_inds]
hm_index_att_lst = hm_index[attack_inds].cpu().numpy().tolist()
best_i = None
best_noise = None
best_fail = np.inf
while True:
i += 1
loss = 0
loss -= ((outputs['hm'].view(-1)[hm_index_att_lst].sigmoid()) ** 2).mean()
hm_index_att_lst_ = [hm_index_att_lst[j] for j in range(len(hm_index_att_lst))
if attack_ids[j] not in ad_ids]
if len(hm_index_att_lst_):
assert len(track_vs) == len(hm_index_att_lst_)
hm_index_gen_lst = []
for index in range(len(hm_index_att_lst_)):
track_v = track_vs[index]
hm_index_gen = hm_index_att_lst_[index]
hm_index_gen += -(np.sign(track_v[0]) + W * np.sign(track_v[1]))
hm_index_gen_lst.append(hm_index_gen)
loss -= ((1 - outputs['hm'].view(-1)[hm_index_gen_lst].sigmoid()) ** 2).mean()
loss -= smoothL1(outputs['wh'].view(2, -1)[:, hm_index_gen_lst].T,
wh_ori.view(2, -1)[:, hm_index_att_lst_].T)
loss -= smoothL1(outputs['reg'].view(2, -1)[:, hm_index_gen_lst].T,
reg_ori.view(2, -1)[:, hm_index_att_lst_].T)
loss.backward()
grad = im_blob.grad
grad /= (grad ** 2).sum().sqrt() + 1e-8
noise += grad
thrs = [0 for j in range(len(attack_inds))]
for j in range(len(thrs)):
if attack_ids[j] not in ad_ids:
thrs[j] = 0.9
im_blob = torch.clip(im_blob_ori + noise, min=0, max=1).data
outputs, suc, fail_ids = self.forwardFeatureDet(
im_blob,
img0,
dets,
attack_inds.tolist(),
thr=thrs
)
if fail_ids is not None:
if fail_ids == 0:
break
elif fail_ids <= best_fail:
best_fail = fail_ids
best_i = i
best_noise = noise.clone()
if i > 60:
if self.opt.no_f_noise:
return None, i, False
else:
if best_i is not None:
noise = best_noise
i = best_i
return noise, i, False
return noise, i, True
def attack_mt_det(
self,
im_blob,
img0,
dets,
inds,
remain_inds,
last_info,
outputs_ori,
attack_ids,
attack_inds
):
img0_h, img0_w = img0.shape[:2]
H, W = outputs_ori['hm'].size()[2:]
r_w, r_h = img0_w / W, img0_h / H
r_max = max(r_w, r_h)
noise = torch.zeros_like(im_blob)
im_blob_ori = im_blob.clone().data
outputs = outputs_ori
wh_ori = outputs['wh'].clone().data
reg_ori = outputs['reg'].clone().data
i = 0
hm_index = inds[0][remain_inds]
hm_index_att_lst = hm_index[attack_inds].cpu().numpy().tolist()
best_i = None
best_noise = None
best_fail = np.inf
while True:
i += 1
loss = 0
loss -= ((outputs['hm'].view(-1)[hm_index_att_lst].sigmoid()) ** 2).mean()
loss.backward()
grad = im_blob.grad
grad /= (grad ** 2).sum().sqrt() + 1e-8
noise += grad
im_blob = torch.clip(im_blob_ori + noise, min=0, max=1).data
outputs, suc, fail_ids = self.forwardFeatureDet(
im_blob,
img0,
dets,
attack_inds.tolist()
)
if fail_ids is not None:
if fail_ids == 0:
break
elif fail_ids <= best_fail:
best_fail = fail_ids
best_i = i
best_noise = noise.clone()
if i > 60:
if self.opt.no_f_noise:
return None, i, False
else:
if best_i is not None:
noise = best_noise
i = best_i
return noise, i, False
return noise, i, True
def attack_sg_feat(
self,
im_blob,
img0,
id_features,
dets,
inds,
remain_inds,
last_info,
outputs_ori,
attack_id,
attack_ind,
target_id,
target_ind
):
noise = torch.zeros_like(im_blob)
im_blob_ori = im_blob.clone().data
last_ad_id_features = [None for _ in range(len(id_features[0]))]
for i in range(len(id_features)):
id_features[i] = id_features[i][[attack_ind, target_ind]]
i = 0
suc = True
while True:
i += 1
loss = 0
loss_feat = 0
for id_i, id_feature in enumerate(id_features):
if last_ad_id_features[attack_ind] is not None:
last_ad_id_feature = torch.from_numpy(last_ad_id_features[attack_ind]).unsqueeze(0).cuda()
sim_1 = torch.mm(id_feature[0:0 + 1], last_ad_id_feature.T).squeeze()
sim_2 = torch.mm(id_feature[1:1 + 1], last_ad_id_feature.T).squeeze()
loss_feat += sim_2 - sim_1
if last_ad_id_features[target_ind] is not None:
last_ad_id_feature = torch.from_numpy(last_ad_id_features[target_ind]).unsqueeze(0).cuda()
sim_1 = torch.mm(id_feature[1:1 + 1], last_ad_id_feature.T).squeeze()
sim_2 = torch.mm(id_feature[0:0 + 1], last_ad_id_feature.T).squeeze()
loss_feat += sim_2 - sim_1
if last_ad_id_features[attack_ind] is None and last_ad_id_features[target_ind] is None:
loss_feat += torch.mm(id_feature[0:0 + 1], id_feature[1:1 + 1].T).squeeze()
loss += loss_feat / len(id_features)
loss.backward()
grad = im_blob.grad
grad /= (grad ** 2).sum().sqrt() + 1e-8
noise += grad
im_blob = torch.clip(im_blob_ori + noise, min=0, max=1).data
id_features_, outputs_, ae_attack_id, ae_target_id, hm_index_ = self.forwardFeatureSg(
im_blob,
img0,
dets,
inds,
remain_inds,
attack_id,
attack_ind,
target_id,
target_ind,
last_info
)
if id_features_ is not None:
id_features = id_features_
if ae_attack_id != attack_id and ae_attack_id is not None:
break
if i > 60:
suc = False
break
return noise, i, suc
def attack_sg_cl(
self,
im_blob,
img0,
id_features,
dets,
inds,
remain_inds,
last_info,
outputs_ori,
attack_id,
attack_ind,
target_id,
target_ind
):
img0_h, img0_w = img0.shape[:2]
H, W = outputs_ori['hm'].size()[2:]
r_w, r_h = img0_w / W, img0_h / H
r_max = max(r_w, r_h)
noise = torch.zeros_like(im_blob)
im_blob_ori = im_blob.clone().data
outputs = outputs_ori
wh_ori = outputs['wh'].clone().data
reg_ori = outputs['reg'].clone().data
last_ad_id_features = [None for _ in range(len(id_features[0]))]
strack_pool = copy.deepcopy(last_info['last_strack_pool'])
last_attack_det = None
last_target_det = None
STrack.multi_predict(strack_pool)
for strack in strack_pool:
if strack.track_id == attack_id:
last_ad_id_features[attack_ind] = strack.smooth_feat
last_attack_det = torch.from_numpy(strack.tlbr).cuda().float()
last_attack_det[[0, 2]] = (last_attack_det[[0, 2]] - 0.5 * W * (r_w - r_max)) / r_max
last_attack_det[[1, 3]] = (last_attack_det[[1, 3]] - 0.5 * H * (r_h - r_max)) / r_max
elif strack.track_id == target_id:
last_ad_id_features[target_ind] = strack.smooth_feat
last_target_det = torch.from_numpy(strack.tlbr).cuda().float()
last_target_det[[0, 2]] = (last_target_det[[0, 2]] - 0.5 * W * (r_w - r_max)) / r_max
last_target_det[[1, 3]] = (last_target_det[[1, 3]] - 0.5 * H * (r_h - r_max)) / r_max
last_attack_det_center = torch.round(
(last_attack_det[:2] + last_attack_det[2:]) / 2) if last_attack_det is not None else None
last_target_det_center = torch.round(
(last_target_det[:2] + last_target_det[2:]) / 2) if last_target_det is not None else None
hm_index = inds[0][remain_inds]
for i in range(len(id_features)):
id_features[i] = id_features[i][[attack_ind, target_ind]]
i = 0
j = -1
suc = True
ori_hm_index = hm_index[[attack_ind, target_ind]].clone()
ori_hm_index_re = hm_index[[target_ind, attack_ind]].clone()
att_hm_index = None
noise_0 = None
i_0 = None
noise_1 = None
i_1 = None
while True:
i += 1
loss = 0
loss_feat = 0
# for id_i, id_feature in enumerate(id_features):
# if last_ad_id_features[attack_ind] is not None:
# last_ad_id_feature = torch.from_numpy(last_ad_id_features[attack_ind]).unsqueeze(0).cuda()
# sim_1 = torch.mm(id_feature[0:0 + 1], last_ad_id_feature.T).squeeze()
# sim_2 = torch.mm(id_feature[1:1 + 1], last_ad_id_feature.T).squeeze()
# loss_feat += sim_2 - sim_1
# if last_ad_id_features[target_ind] is not None:
# last_ad_id_feature = torch.from_numpy(last_ad_id_features[target_ind]).unsqueeze(0).cuda()
# sim_1 = torch.mm(id_feature[1:1 + 1], last_ad_id_feature.T).squeeze()
# sim_2 = torch.mm(id_feature[0:0 + 1], last_ad_id_feature.T).squeeze()
# loss_feat += sim_2 - sim_1
# if last_ad_id_features[attack_ind] is None and last_ad_id_features[target_ind] is None:
# loss_feat += torch.mm(id_feature[0:0 + 1], id_feature[1:1 + 1].T).squeeze()
# loss += loss_feat / len(id_features)
if i in [1, 10, 20, 30, 35, 40, 45, 50, 55]:
attack_det_center = torch.stack([hm_index[attack_ind] % W, hm_index[attack_ind] // W]).float()
target_det_center = torch.stack([hm_index[target_ind] % W, hm_index[target_ind] // W]).float()
if last_target_det_center is not None:
attack_center_delta = attack_det_center - last_target_det_center
if torch.max(torch.abs(attack_center_delta)) > 1:
attack_center_delta /= torch.max(torch.abs(attack_center_delta))
attack_det_center = torch.round(attack_det_center - attack_center_delta).int()
hm_index[attack_ind] = attack_det_center[0] + attack_det_center[1] * W
if last_attack_det_center is not None:
target_center_delta = target_det_center - last_attack_det_center
if torch.max(torch.abs(target_center_delta)) > 1:
target_center_delta /= torch.max(torch.abs(target_center_delta))
target_det_center = torch.round(target_det_center - target_center_delta).int()
hm_index[target_ind] = target_det_center[0] + target_det_center[1] * W
att_hm_index = hm_index[[attack_ind, target_ind]].clone()
if att_hm_index is not None:
n_att_hm_index = []
n_ori_hm_index_re = []
for hm_ind in range(len(att_hm_index)):
for n_i in range(3):
for n_j in range(3):
att_hm_ind = att_hm_index[hm_ind].item()
att_hm_ind = att_hm_ind + (n_i - 1) * W + (n_j - 1)
att_hm_ind = max(0, min(H*W-1, att_hm_ind))
n_att_hm_index.append(att_hm_ind)
ori_hm_ind = ori_hm_index_re[hm_ind].item()
ori_hm_ind = ori_hm_ind + (n_i - 1) * W + (n_j - 1)
ori_hm_ind = max(0, min(H * W - 1, ori_hm_ind))
n_ori_hm_index_re.append(ori_hm_ind)
# print(n_att_hm_index, n_ori_hm_index_re)
loss += ((1 - outputs['hm'].view(-1).sigmoid()[n_att_hm_index]) ** 2 *
torch.log(outputs['hm'].view(-1).sigmoid()[n_att_hm_index])).mean()
loss += ((outputs['hm'].view(-1).sigmoid()[n_ori_hm_index_re]) ** 2 *
torch.log(1 - outputs['hm'].view(-1).sigmoid()[n_ori_hm_index_re])).mean()
loss -= smoothL1(outputs['wh'].view(2, -1)[:, n_att_hm_index].T, wh_ori.view(2, -1)[:, n_ori_hm_index_re].T)
loss -= smoothL1(outputs['reg'].view(2, -1)[:, n_att_hm_index].T, reg_ori.view(2, -1)[:, n_ori_hm_index_re].T)
loss.backward()
grad = im_blob.grad
grad /= (grad ** 2).sum().sqrt() + 1e-8
noise += grad
im_blob = torch.clip(im_blob_ori + noise, min=0, max=1).data
id_features_, outputs_, ae_attack_id, ae_target_id, hm_index_ = self.forwardFeatureSg(
im_blob,
img0,
dets,
inds,
remain_inds,
attack_id,
attack_ind,
target_id,
target_ind,
last_info
)
if id_features_ is not None:
id_features = id_features_
if outputs_ is not None:
outputs = outputs_
# if hm_index_ is not None:
# hm_index = hm_index_
if ae_attack_id != attack_id and ae_attack_id is not None:
break
if i > 60:
if noise_0 is not None:
return noise_0, i_0, suc
elif noise_1 is not None:
return noise_1, i_1, suc
if self.opt.no_f_noise:
return None, i, False
else:
suc = False
break
return noise, i, suc
def attack_sg_random(
self,
im_blob,
img0,
id_features,
dets,
inds,
remain_inds,
last_info,
outputs_ori,
attack_id,
attack_ind,
target_id,
target_ind
):
im_blob_ori = im_blob.clone().data
suc = False
noise = torch.rand(im_blob_ori.size()).to(im_blob_ori.device)
noise /= (noise**2).sum().sqrt()
noise *= random.uniform(2, 8)
im_blob = torch.clip(im_blob_ori + noise, min=0, max=1).data
id_features_, outputs_, ae_attack_id, ae_target_id, hm_index_ = self.forwardFeatureSg(
im_blob,
img0,
dets,
inds,
remain_inds,
attack_id,
attack_ind,
target_id,
target_ind,
last_info,
grad=False
)
if ae_attack_id != attack_id and ae_attack_id is not None:
suc = True
return noise, 1, suc
def attack_mt_random(
self,
im_blob,
img0,
id_features,
dets,
inds,
remain_inds,
last_info,
outputs_ori,
attack_ids,
attack_inds,
target_ids,
target_inds
):
im_blob_ori = im_blob.clone().data
suc = False
noise = torch.rand(im_blob_ori.size()).to(im_blob_ori.device)
noise /= (noise ** 2).sum().sqrt()
noise *= random.uniform(2, 8)
im_blob = torch.clip(im_blob_ori + noise, min=0, max=1).data
id_features, outputs, fail_ids = self.forwardFeatureMt(
im_blob,
img0,
dets,
inds,
remain_inds,
attack_ids,
attack_inds,
target_ids,
target_inds,
last_info,
grad=False
)
if fail_ids == 0:
suc = True
return noise, 1, suc
def attack_sg(
self,
im_blob,
img0,
id_features,
dets,
inds,
remain_inds,
last_info,
outputs_ori,
attack_id,
attack_ind,
target_id,
target_ind
):
img0_h, img0_w = img0.shape[:2]
H, W = outputs_ori['hm'].size()[2:]
r_w, r_h = img0_w / W, img0_h / H
r_max = max(r_w, r_h)
noise = torch.zeros_like(im_blob)
im_blob_ori = im_blob.clone().data
outputs = outputs_ori
wh_ori = outputs['wh'].clone().data
reg_ori = outputs['reg'].clone().data
last_ad_id_features = [None for _ in range(len(id_features[0]))]
strack_pool = copy.deepcopy(last_info['last_strack_pool'])
last_attack_det = None
last_target_det = None
STrack.multi_predict(strack_pool)
for strack in strack_pool:
if strack.track_id == attack_id:
last_ad_id_features[attack_ind] = strack.smooth_feat
last_attack_det = torch.from_numpy(strack.tlbr).cuda().float()
last_attack_det[[0, 2]] = (last_attack_det[[0, 2]] - 0.5 * W * (r_w - r_max)) / r_max
last_attack_det[[1, 3]] = (last_attack_det[[1, 3]] - 0.5 * H * (r_h - r_max)) / r_max
elif strack.track_id == target_id:
last_ad_id_features[target_ind] = strack.smooth_feat
last_target_det = torch.from_numpy(strack.tlbr).cuda().float()
last_target_det[[0, 2]] = (last_target_det[[0, 2]] - 0.5 * W * (r_w - r_max)) / r_max
last_target_det[[1, 3]] = (last_target_det[[1, 3]] - 0.5 * H * (r_h - r_max)) / r_max
last_attack_det_center = torch.round(
(last_attack_det[:2] + last_attack_det[2:]) / 2) if last_attack_det is not None else None
last_target_det_center = torch.round(
(last_target_det[:2] + last_target_det[2:]) / 2) if last_target_det is not None else None
hm_index = inds[0][remain_inds]
for i in range(len(id_features)):
id_features[i] = id_features[i][[attack_ind, target_ind]]
i = 0
j = -1
suc = True
ori_hm_index = hm_index[[attack_ind, target_ind]].clone()
ori_hm_index_re = hm_index[[target_ind, attack_ind]].clone()
att_hm_index = None
noise_0 = None
i_0 = None
noise_1 = None
i_1 = None
while True:
i += 1
loss = 0
loss_feat = 0
for id_i, id_feature in enumerate(id_features):
if last_ad_id_features[attack_ind] is not None:
last_ad_id_feature = torch.from_numpy(last_ad_id_features[attack_ind]).unsqueeze(0).cuda()
sim_1 = torch.mm(id_feature[0:0 + 1], last_ad_id_feature.T).squeeze()
sim_2 = torch.mm(id_feature[1:1 + 1], last_ad_id_feature.T).squeeze()
loss_feat += sim_2 - sim_1
if last_ad_id_features[target_ind] is not None:
last_ad_id_feature = torch.from_numpy(last_ad_id_features[target_ind]).unsqueeze(0).cuda()
sim_1 = torch.mm(id_feature[1:1 + 1], last_ad_id_feature.T).squeeze()
sim_2 = torch.mm(id_feature[0:0 + 1], last_ad_id_feature.T).squeeze()
loss_feat += sim_2 - sim_1
if last_ad_id_features[attack_ind] is None and last_ad_id_features[target_ind] is None:
loss_feat += torch.mm(id_feature[0:0 + 1], id_feature[1:1 + 1].T).squeeze()
loss += loss_feat / len(id_features)
if i in [10, 20, 30, 35, 40, 45, 50, 55]:
attack_det_center = torch.stack([hm_index[attack_ind] % W, hm_index[attack_ind] // W]).float()
target_det_center = torch.stack([hm_index[target_ind] % W, hm_index[target_ind] // W]).float()
if last_target_det_center is not None:
attack_center_delta = attack_det_center - last_target_det_center
if torch.max(torch.abs(attack_center_delta)) > 1:
attack_center_delta /= torch.max(torch.abs(attack_center_delta))
attack_det_center = torch.round(attack_det_center - attack_center_delta).int()
hm_index[attack_ind] = attack_det_center[0] + attack_det_center[1] * W
if last_attack_det_center is not None:
target_center_delta = target_det_center - last_attack_det_center
if torch.max(torch.abs(target_center_delta)) > 1:
target_center_delta /= torch.max(torch.abs(target_center_delta))
target_det_center = torch.round(target_det_center - target_center_delta).int()
hm_index[target_ind] = target_det_center[0] + target_det_center[1] * W
att_hm_index = hm_index[[attack_ind, target_ind]].clone()
if att_hm_index is not None:
n_att_hm_index = []
n_ori_hm_index_re = []
for hm_ind in range(len(att_hm_index)):
for n_i in range(3):
for n_j in range(3):
att_hm_ind = att_hm_index[hm_ind].item()
att_hm_ind = att_hm_ind + (n_i - 1) * W + (n_j - 1)
att_hm_ind = max(0, min(H*W-1, att_hm_ind))
n_att_hm_index.append(att_hm_ind)
ori_hm_ind = ori_hm_index_re[hm_ind].item()
ori_hm_ind = ori_hm_ind + (n_i - 1) * W + (n_j - 1)
ori_hm_ind = max(0, min(H * W - 1, ori_hm_ind))
n_ori_hm_index_re.append(ori_hm_ind)
# print(n_att_hm_index, n_ori_hm_index_re)
loss += ((1 - outputs['hm'].view(-1).sigmoid()[n_att_hm_index]) ** 2 *
torch.log(outputs['hm'].view(-1).sigmoid()[n_att_hm_index])).mean()
loss += ((outputs['hm'].view(-1).sigmoid()[n_ori_hm_index_re]) ** 2 *
torch.log(1 - outputs['hm'].view(-1).sigmoid()[n_ori_hm_index_re])).mean()
loss -= smoothL1(outputs['wh'].view(2, -1)[:, n_att_hm_index].T, wh_ori.view(2, -1)[:, n_ori_hm_index_re].T)
loss -= smoothL1(outputs['reg'].view(2, -1)[:, n_att_hm_index].T, reg_ori.view(2, -1)[:, n_ori_hm_index_re].T)
loss.backward()
grad = im_blob.grad
grad /= (grad ** 2).sum().sqrt() + 1e-8
noise += grad
im_blob = torch.clip(im_blob_ori + noise, min=0, max=1).data
id_features_, outputs_, ae_attack_id, ae_target_id, hm_index_ = self.forwardFeatureSg(
im_blob,
img0,
dets,
inds,
remain_inds,
attack_id,
attack_ind,
target_id,
target_ind,
last_info
)
if id_features_ is not None:
id_features = id_features_
if outputs_ is not None:
outputs = outputs_
# if hm_index_ is not None:
# hm_index = hm_index_
if ae_attack_id != attack_id and ae_attack_id is not None:
break
if i > 60:
if noise_0 is not None:
return noise_0, i_0, suc
elif noise_1 is not None:
return noise_1, i_1, suc
if self.opt.no_f_noise:
return None, i, False
else:
suc = False
break
return noise, i, suc
def attack_mt(
self,
im_blob,
img0,
id_features,
dets,
inds,
remain_inds,
last_info,
outputs_ori,
attack_ids,
attack_inds,
target_ids,
target_inds
):
img0_h, img0_w = img0.shape[:2]
H, W = outputs_ori['hm'].size()[2:]
r_w, r_h = img0_w / W, img0_h / H
r_max = max(r_w, r_h)
noise = torch.zeros_like(im_blob)
im_blob_ori = im_blob.clone().data
outputs = outputs_ori
wh_ori = outputs['wh'].clone().data
reg_ori = outputs['reg'].clone().data
i = 0
j = -1
last_ad_id_features = [None for _ in range(len(id_features[0]))]
strack_pool = copy.deepcopy(last_info['last_strack_pool'])
ad_attack_ids = [self.multiple_ori2att[attack_id] for attack_id in attack_ids]
ad_target_ids = [self.multiple_ori2att[target_id] for target_id in target_ids]
last_attack_dets = [None] * len(ad_attack_ids)
last_target_dets = [None] * len(ad_target_ids)
STrack.multi_predict(strack_pool)
for strack in strack_pool:
if strack.track_id in ad_attack_ids:
index = ad_attack_ids.index(strack.track_id)
last_ad_id_features[attack_inds[index]] = strack.smooth_feat
last_attack_dets[index] = torch.from_numpy(strack.tlbr).cuda().float()
last_attack_dets[index][[0, 2]] = (last_attack_dets[index][[0, 2]] - 0.5 * W * (r_w - r_max)) / r_max
last_attack_dets[index][[1, 3]] = (last_attack_dets[index][[1, 3]] - 0.5 * H * (r_h - r_max)) / r_max
if strack.track_id in ad_target_ids:
index = ad_target_ids.index(strack.track_id)
last_ad_id_features[target_inds[index]] = strack.smooth_feat
last_target_dets[index] = torch.from_numpy(strack.tlbr).cuda().float()
last_target_dets[index][[0, 2]] = (last_target_dets[index][[0, 2]] - 0.5 * W * (r_w - r_max)) / r_max
last_target_dets[index][[1, 3]] = (last_target_dets[index][[1, 3]] - 0.5 * H * (r_h - r_max)) / r_max
last_attack_dets_center = []
for det in last_attack_dets:
if det is None:
last_attack_dets_center.append(None)
else:
last_attack_dets_center.append((det[:2] + det[2:]) / 2)
last_target_dets_center = []
for det in last_target_dets:
if det is None:
last_target_dets_center.append(None)
else:
last_target_dets_center.append((det[:2] + det[2:]) / 2)
hm_index = inds[0][remain_inds]
ori_hm_index_re_lst = []
for ind in range(len(attack_ids)):
attack_ind = attack_inds[ind]
target_ind = target_inds[ind]
ori_hm_index_re_lst.append(hm_index[[target_ind, attack_ind]].clone())
att_hm_index_lst = []
best_i = None
best_noise = None
best_fail = np.inf
while True:
i += 1
loss = 0
loss_feat = 0
for index, attack_id in enumerate(attack_ids):
target_id = target_ids[index]
attack_ind = attack_inds[index]
target_ind = target_inds[index]
for id_i, id_feature in enumerate(id_features):
if last_ad_id_features[attack_ind] is not None:
last_ad_id_feature = torch.from_numpy(last_ad_id_features[attack_ind]).unsqueeze(0).cuda()
sim_1 = torch.mm(id_feature[attack_ind:attack_ind + 1], last_ad_id_feature.T).squeeze()
sim_2 = torch.mm(id_feature[target_ind:target_ind + 1], last_ad_id_feature.T).squeeze()
if self.opt.hard_sample > 0:
loss_feat += torch.clamp(sim_2 - sim_1, max=self.opt.hard_sample)
else:
loss_feat += sim_2 - sim_1
if last_ad_id_features[target_ind] is not None:
last_ad_id_feature = torch.from_numpy(last_ad_id_features[target_ind]).unsqueeze(0).cuda()
sim_1 = torch.mm(id_feature[target_ind:target_ind + 1], last_ad_id_feature.T).squeeze()
sim_2 = torch.mm(id_feature[attack_ind:attack_ind + 1], last_ad_id_feature.T).squeeze()
if self.opt.hard_sample > 0:
loss_feat += torch.clamp(sim_2 - sim_1, max=self.opt.hard_sample)
else:
loss_feat += sim_2 - sim_1
if last_ad_id_features[attack_ind] is None and last_ad_id_features[target_ind] is None:
loss_feat += torch.mm(id_feature[attack_ind:attack_ind + 1],
id_feature[target_ind:target_ind + 1].T).squeeze()
if i in [10, 20, 30, 35, 40, 45, 50, 55]:
attack_det_center = torch.stack([hm_index[attack_ind] % W, hm_index[attack_ind] // W]).float()
target_det_center = torch.stack([hm_index[target_ind] % W, hm_index[target_ind] // W]).float()
if last_target_dets_center[index] is not None:
attack_center_delta = attack_det_center - last_target_dets_center[index]
if torch.max(torch.abs(attack_center_delta)) > 1:
attack_center_delta /= torch.max(torch.abs(attack_center_delta))
attack_det_center = torch.round(attack_det_center - attack_center_delta).int()
hm_index[attack_ind] = attack_det_center[0] + attack_det_center[1] * W
if last_attack_dets_center[index] is not None:
target_center_delta = target_det_center - last_attack_dets_center[index]
if torch.max(torch.abs(target_center_delta)) > 1:
target_center_delta /= torch.max(torch.abs(target_center_delta))
target_det_center = torch.round(target_det_center - target_center_delta).int()
hm_index[target_ind] = target_det_center[0] + target_det_center[1] * W
if index == 0:
att_hm_index_lst = []
att_hm_index_lst.append(hm_index[[attack_ind, target_ind]].clone())
loss += loss_feat / len(id_features)
if len(att_hm_index_lst):
assert len(att_hm_index_lst) == len(ori_hm_index_re_lst)
n_att_hm_index_lst = []
n_ori_hm_index_re_lst = []
for lst_ind in range(len(att_hm_index_lst)):
for hm_ind in range(len(att_hm_index_lst[lst_ind])):
for n_i in range(3):
for n_j in range(3):
att_hm_ind = att_hm_index_lst[lst_ind][hm_ind].item()
att_hm_ind = att_hm_ind + (n_i - 1) * W + (n_j - 1)
att_hm_ind = max(0, min(H*W-1, att_hm_ind))
n_att_hm_index_lst.append(att_hm_ind)
ori_hm_ind = ori_hm_index_re_lst[lst_ind][hm_ind].item()
ori_hm_ind = ori_hm_ind + (n_i - 1) * W + (n_j - 1)
ori_hm_ind = max(0, min(H * W - 1, ori_hm_ind))
n_ori_hm_index_re_lst.append(ori_hm_ind)
# print(n_att_hm_index, n_ori_hm_index_re)
loss += ((1 - outputs['hm'].view(-1).sigmoid()[n_att_hm_index_lst]) ** 2 *
torch.log(outputs['hm'].view(-1).sigmoid()[n_att_hm_index_lst])).mean()
loss += ((outputs['hm'].view(-1).sigmoid()[n_ori_hm_index_re_lst]) ** 2 *
torch.log(1 - outputs['hm'].view(-1).sigmoid()[n_ori_hm_index_re_lst])).mean()
loss -= smoothL1(outputs['wh'].view(2, -1)[:, n_att_hm_index_lst].T, wh_ori.view(2, -1)[:, n_ori_hm_index_re_lst].T)
loss -= smoothL1(outputs['reg'].view(2, -1)[:, n_att_hm_index_lst].T, reg_ori.view(2, -1)[:, n_ori_hm_index_re_lst].T)
loss.backward()
grad = im_blob.grad
grad /= (grad ** 2).sum().sqrt() + 1e-8
noise += grad
im_blob = torch.clip(im_blob_ori + noise, min=0, max=1).data
id_features, outputs, fail_ids = self.forwardFeatureMt(
im_blob,
img0,
dets,
inds,
remain_inds,
attack_ids,
attack_inds,
target_ids,
target_inds,
last_info
)
if fail_ids is not None:
if fail_ids == 0:
break
elif fail_ids <= best_fail:
best_fail = fail_ids
best_i = i
best_noise = noise.clone()
if i > 60:
if self.opt.no_f_noise:
return None, i, False
else:
if best_i is not None:
noise = best_noise
i = best_i
return noise, i, False
return noise, i, True
def forwardFeatureDet(self, im_blob, img0, dets_, attack_inds, thr=0, vs=[]):
width = img0.shape[1]
height = img0.shape[0]
inp_height = im_blob.shape[2]
inp_width = im_blob.shape[3]
c = np.array([width / 2., height / 2.], dtype=np.float32)
s = max(float(inp_width) / float(inp_height) * height, width) * 1.0
meta = {'c': c, 's': s,
'out_height': inp_height // self.opt.down_ratio,
'out_width': inp_width // self.opt.down_ratio}
im_blob.requires_grad = True
self.model.zero_grad()
output = self.model(im_blob)[-1]
hm = output['hm'].sigmoid()
wh = output['wh']
reg = output['reg'] if self.opt.reg_offset else None
dets_raw, inds = mot_decode(hm, wh, reg=reg, cat_spec_wh=self.opt.cat_spec_wh, K=self.opt.K)
dets = self.post_process(dets_raw.clone(), meta)
dets = self.merge_outputs([dets])[1]
remain_inds = dets[:, 4] > self.opt.conf_thres
dets = dets[remain_inds]
ious = bbox_ious(np.ascontiguousarray(dets_[:, :4], dtype=np.float),
np.ascontiguousarray(dets[:, :4], dtype=np.float))
row_inds, col_inds = linear_sum_assignment(-ious)
if not isinstance(thr, list):
thr = [thr for _ in range(len(attack_inds))]
fail_n = 0
for i in range(len(row_inds)):
if row_inds[i] in attack_inds:
if ious[row_inds[i], col_inds[i]] > thr[attack_inds.index(row_inds[i])]:
fail_n += 1
elif len(vs):
d_o = dets_[row_inds[i], :4]
d_a = dets[col_inds[i], :4]
c_o = (d_o[[0, 1]] + d_o[[2, 3]]) / 2
c_a = (d_a[[0, 1]] + d_a[[2, 3]]) / 2
c_d = ((c_a - c_o) / 4).astype(np.int) * vs[0]
if c_d[0] >= 0 or c_d[1] >= 0:
fail_n += 1
return output, fail_n == 0, fail_n
def forwardFeatureSg(self, im_blob, img0, dets_, inds_, remain_inds_, attack_id, attack_ind, target_id, target_ind,
last_info, grad=True):
width = img0.shape[1]
height = img0.shape[0]
inp_height = im_blob.shape[2]
inp_width = im_blob.shape[3]
c = np.array([width / 2., height / 2.], dtype=np.float32)
s = max(float(inp_width) / float(inp_height) * height, width) * 1.0
meta = {'c': c, 's': s,
'out_height': inp_height // self.opt.down_ratio,
'out_width': inp_width // self.opt.down_ratio}
im_blob.requires_grad = True
self.model.zero_grad()
if grad:
output = self.model(im_blob)[-1]
else:
with torch.no_grad():
output = self.model(im_blob)[-1]
hm = output['hm'].sigmoid()
wh = output['wh']
id_feature = output['id']
id_feature = F.normalize(id_feature, dim=1)
reg = output['reg'] if self.opt.reg_offset else None
dets_raw, inds = mot_decode(hm, wh, reg=reg, cat_spec_wh=self.opt.cat_spec_wh, K=self.opt.K)
dets = self.post_process(dets_raw.clone(), meta)
dets = self.merge_outputs([dets])[1]
remain_inds = dets[:, 4] > self.opt.conf_thres
dets = dets[remain_inds]
if target_ind is None:
ious = bbox_ious(np.ascontiguousarray(dets_[[attack_ind], :4], dtype=np.float),
np.ascontiguousarray(dets[:, :4], dtype=np.float))
else:
ious = bbox_ious(np.ascontiguousarray(dets_[[attack_ind, target_ind], :4], dtype=np.float),
np.ascontiguousarray(dets[:, :4], dtype=np.float))
# det_ind = np.argmax(ious, axis=1)
row_inds, col_inds = linear_sum_assignment(-ious)
match = True
if target_ind is None:
if ious[row_inds[0], col_inds[0]] < 0.8:
dets = dets_
inds = inds_
remain_inds = remain_inds_
match = False
else:
if len(col_inds) < 2 or ious[row_inds[0], col_inds[0]] < 0.6 or ious[row_inds[1], col_inds[1]] < 0.6:
dets = dets_
inds = inds_
remain_inds = remain_inds_
match = False
# assert match
id_features = []
for i in range(3):
for j in range(3):
id_feature_exp = _tranpose_and_gather_feat_expand(id_feature, inds, bias=(i - 1, j - 1)).squeeze(0)
id_features.append(id_feature_exp)
for i in range(len(id_features)):
id_features[i] = id_features[i][remain_inds]
ae_attack_id = None
ae_target_id = None
if not match:
for i in range(len(id_features)):
if target_ind is not None:
id_features[i] = id_features[i][[attack_ind, target_ind]]
else:
id_features[i] = id_features[i][[attack_ind]]
return id_features, output, ae_attack_id, ae_target_id, None
if row_inds[0] == 0:
ae_attack_ind = col_inds[0]
ae_target_ind = col_inds[1] if target_ind is not None else None
else:
ae_attack_ind = col_inds[1]
ae_target_ind = col_inds[0] if target_ind is not None else None
# ae_attack_ind = det_ind[0]
# ae_target_ind = det_ind[1] if target_ind is not None else None
hm_index = None
# if target_ind is not None:
# hm_index[[attack_ind, target_ind]] = hm_index[[ae_attack_ind, ae_target_ind]]
id_features_ = [None for _ in range(len(id_features))]
for i in range(len(id_features)):
if target_ind is None:
id_features_[i] = id_features[i][[ae_attack_ind]]
else:
try:
id_features_[i] = id_features[i][[ae_attack_ind, ae_target_ind]]
except:
import pdb; pdb.set_trace()
id_feature = _tranpose_and_gather_feat_expand(id_feature, inds)
id_feature = id_feature.squeeze(0)
id_feature = id_feature[remain_inds]
id_feature = id_feature.detach().cpu().numpy()
if len(dets) > 0:
'''Detections'''
detections = [STrack(STrack.tlbr_to_tlwh(tlbrs[:4]), tlbrs[4], f, 30) for
(tlbrs, f) in zip(dets[:, :5], id_feature)]
else:
detections = []
unconfirmed = copy.deepcopy(last_info['last_unconfirmed'])
strack_pool = copy.deepcopy(last_info['last_strack_pool'])
kalman_filter = copy.deepcopy(last_info['kalman_filter'])
STrack.multi_predict(strack_pool)
dists = matching.embedding_distance(strack_pool, detections)
dists = matching.fuse_motion(kalman_filter, dists, strack_pool, detections)
matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.7)
for itracked, idet in matches:
track = strack_pool[itracked]
det = detections[idet]
if idet == ae_attack_ind:
ae_attack_id = track.track_id
elif idet == ae_target_ind:
ae_target_id = track.track_id
# if ae_attack_id is not None and ae_target_id is not None:
# return id_features_, output, ae_attack_id, ae_target_id
''' Step 3: Second association, with IOU'''
for i, idet in enumerate(u_detection):
if idet == ae_attack_ind:
ae_attack_ind = i
elif idet == ae_target_ind:
ae_target_ind = i
detections = [detections[i] for i in u_detection]
r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked]
dists = matching.iou_distance(r_tracked_stracks, detections)
matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.5)
for itracked, idet in matches:
track = r_tracked_stracks[itracked]
det = detections[idet]
if idet == ae_attack_ind:
ae_attack_id = track.track_id
elif idet == ae_target_ind:
ae_target_id = track.track_id
# if ae_attack_id is not None and ae_target_id is not None:
# return id_features_, output, ae_attack_id, ae_target_id
'''Deal with unconfirmed tracks, usually tracks with only one beginning frame'''
for i, idet in enumerate(u_detection):
if idet == ae_attack_ind:
ae_attack_ind = i
elif idet == ae_target_ind:
ae_target_ind = i
detections = [detections[i] for i in u_detection]
dists = matching.iou_distance(unconfirmed, detections)
matches, u_unconfirmed, u_detection = matching.linear_assignment(dists, thresh=0.7)
for itracked, idet in matches:
track = unconfirmed[itracked]
if idet == ae_attack_ind:
ae_attack_id = track.track_id
elif idet == ae_target_ind:
ae_target_id = track.track_id
return id_features_, output, ae_attack_id, ae_target_id, hm_index
def forwardFeatureMt(self, im_blob, img0, dets_, inds_, remain_inds_, attack_ids, attack_inds, target_ids,
target_inds, last_info, grad=True):
width = img0.shape[1]
height = img0.shape[0]
inp_height = im_blob.shape[2]
inp_width = im_blob.shape[3]
c = np.array([width / 2., height / 2.], dtype=np.float32)
s = max(float(inp_width) / float(inp_height) * height, width) * 1.0
meta = {'c': c, 's': s,
'out_height': inp_height // self.opt.down_ratio,
'out_width': inp_width // self.opt.down_ratio}
im_blob.requires_grad = True
self.model.zero_grad()
if grad:
output = self.model(im_blob)[-1]
else:
with torch.no_grad():
output = self.model(im_blob)[-1]
hm = output['hm'].sigmoid()
wh = output['wh']
id_feature = output['id']
id_feature = F.normalize(id_feature, dim=1)
reg = output['reg'] if self.opt.reg_offset else None
dets_raw, inds = mot_decode(hm, wh, reg=reg, cat_spec_wh=self.opt.cat_spec_wh, K=self.opt.K)
dets = self.post_process(dets_raw.clone(), meta)
dets = self.merge_outputs([dets])[1]
dets_index = [i for i in range(len(dets))]
remain_inds = dets[:, 4] > self.opt.conf_thres
dets = dets[remain_inds]
ious = bbox_ious(np.ascontiguousarray(dets_[:, :4], dtype=np.float64),
np.ascontiguousarray(dets[:, :4], dtype=np.float64))
row_inds, col_inds = linear_sum_assignment(-ious)
match = True
if target_inds is not None:
for index, attack_ind in enumerate(attack_inds):
target_ind = target_inds[index]
if attack_ind not in row_inds or target_ind not in row_inds:
match = False
break
att_index = row_inds.tolist().index(attack_ind)
tar_index = row_inds.tolist().index(target_ind)
if ious[attack_ind, col_inds[att_index]] < 0.6 or ious[target_ind, col_inds[tar_index]] < 0.6:
match = False
break
else:
for index, attack_ind in enumerate(attack_inds):
if attack_ind not in row_inds:
match = False
break
att_index = row_inds.tolist().index(attack_ind)
if ious[attack_ind, col_inds[att_index]] < 0.8:
match = False
break
if not match:
dets = dets_
inds = inds_
remain_inds = remain_inds_
# assert match
id_features = []
for i in range(3):
for j in range(3):
id_feature_exp = _tranpose_and_gather_feat_expand(id_feature, inds, bias=(i - 1, j - 1)).squeeze(0)
id_features.append(id_feature_exp)
for i in range(len(id_features)):
id_features[i] = id_features[i][remain_inds]
fail_ids = 0
if not match:
return id_features, output, None
ae_attack_inds = []
ae_attack_ids = []
for i in range(len(row_inds)):
if ious[row_inds[i], col_inds[i]] > 0.6:
if row_inds[i] in attack_inds:
ae_attack_inds.append(col_inds[i])
index = attack_inds.tolist().index(row_inds[i])
ae_attack_ids.append(self.multiple_ori2att[attack_ids[index]])
# ae_attack_inds = [col_inds[row_inds == attack_ind] for attack_ind in attack_inds]
# ae_attack_inds = np.concatenate(ae_attack_inds)
id_features_ = [torch.zeros([len(dets_), id_features[0].size(1)]).to(id_features[0].device) for _ in range(len(id_features))]
for i in range(9):
id_features_[i][row_inds] = id_features[i][col_inds]
id_feature = _tranpose_and_gather_feat_expand(id_feature, inds)
id_feature = id_feature.squeeze(0)
id_feature = id_feature[remain_inds]
id_feature = id_feature.detach().cpu().numpy()
if len(dets) > 0:
'''Detections'''
detections = [STrack(STrack.tlbr_to_tlwh(tlbrs[:4]), tlbrs[4], f, 30) for
(tlbrs, f) in zip(dets[:, :5], id_feature)]
else:
detections = []
unconfirmed = copy.deepcopy(last_info['last_unconfirmed'])
strack_pool = copy.deepcopy(last_info['last_strack_pool'])
kalman_filter = copy.deepcopy(last_info['kalman_filter'])
STrack.multi_predict(strack_pool)
dists = matching.embedding_distance(strack_pool, detections)
dists = matching.fuse_motion(kalman_filter, dists, strack_pool, detections)
matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.7)
for itracked, idet in matches:
track = strack_pool[itracked]
det = detections[idet]
if dets_index[idet] in ae_attack_inds:
index = ae_attack_inds.index(dets_index[idet])
if track.track_id == ae_attack_ids[index]:
fail_ids += 1
''' Step 3: Second association, with IOU'''
dets_index = [dets_index[i] for i in u_detection]
detections = [detections[i] for i in u_detection]
r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked]
dists = matching.iou_distance(r_tracked_stracks, detections)
matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.5)
for itracked, idet in matches:
track = r_tracked_stracks[itracked]
det = detections[idet]
if dets_index[idet] in ae_attack_inds:
index = ae_attack_inds.index(dets_index[idet])
if track.track_id == ae_attack_ids[index]:
fail_ids += 1
'''Deal with unconfirmed tracks, usually tracks with only one beginning frame'''
dets_index = [dets_index[i] for i in u_detection]
detections = [detections[i] for i in u_detection]
dists = matching.iou_distance(unconfirmed, detections)
matches, u_unconfirmed, u_detection = matching.linear_assignment(dists, thresh=0.7)
for itracked, idet in matches:
track = unconfirmed[itracked]
if dets_index[idet] in ae_attack_inds:
index = ae_attack_inds.index(dets_index[idet])
if track.track_id == ae_attack_ids[index]:
fail_ids += 1
return id_features_, output, fail_ids
def CheckFit(self, dets, id_feature, attack_ids, attack_inds):
ad_attack_ids_ = [self.multiple_ori2att[attack_id] for attack_id in attack_ids] \
if self.opt.attack == 'multiple' else attack_ids
attack_dets = dets[attack_inds, :4]
ad_attack_dets = []
ad_attack_ids = []
if len(dets) > 0:
'''Detections'''
detections = [STrack(STrack.tlbr_to_tlwh(tlbrs[:4]), tlbrs[4], f, 30) for
(tlbrs, f) in zip(dets[:, :5], id_feature)]
else:
detections = []
unconfirmed = copy.deepcopy(self.ad_last_info['last_unconfirmed'])
strack_pool = copy.deepcopy(self.ad_last_info['last_strack_pool'])
kalman_filter = copy.deepcopy(self.ad_last_info['kalman_filter'])
STrack.multi_predict(strack_pool)
dists = matching.embedding_distance(strack_pool, detections)
dists = matching.fuse_motion(kalman_filter, dists, strack_pool, detections)
matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.7)
for itracked, idet in matches:
track = strack_pool[itracked]
det = detections[idet]
if track.track_id in ad_attack_ids_:
ad_attack_dets.append(det.tlbr)
ad_attack_ids.append(track.track_id)
''' Step 3: Second association, with IOU'''
detections = [detections[i] for i in u_detection]
r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked]
dists = matching.iou_distance(r_tracked_stracks, detections)
matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.5)
for itracked, idet in matches:
track = r_tracked_stracks[itracked]
det = detections[idet]
if track.track_id in ad_attack_ids_:
ad_attack_dets.append(det.tlbr)
ad_attack_ids.append(track.track_id)
'''Deal with unconfirmed tracks, usually tracks with only one beginning frame'''
detections = [detections[i] for i in u_detection]
dists = matching.iou_distance(unconfirmed, detections)
matches, u_unconfirmed, u_detection = matching.linear_assignment(dists, thresh=0.7)
for itracked, idet in matches:
track = unconfirmed[itracked]
det = detections[idet]
if track.track_id in ad_attack_ids_:
ad_attack_dets.append(det.tlbr)
ad_attack_ids.append(track.track_id)
if len(ad_attack_dets) == 0:
return []
ori_dets = np.array(attack_dets)
ad_dets = np.array(ad_attack_dets)
ious = bbox_ious(ori_dets.astype(np.float64), ad_dets.astype(np.float64))
row_ind, col_ind = linear_sum_assignment(-ious)
attack_index = []
for i in range(len(row_ind)):
if self.opt.attack == 'multiple':
if ious[row_ind[i], col_ind[i]] > 0.9 and self.multiple_ori2att[attack_ids[row_ind[i]]] == ad_attack_ids[col_ind[i]]:
attack_index.append(row_ind[i])
else:
if ious[row_ind[i], col_ind[i]] > 0.9:
attack_index.append(row_ind[i])
return attack_index
def update_attack_sg(self, im_blob, img0, **kwargs):
self.frame_id_ += 1
attack_id = kwargs['attack_id']
self_track_id_ori = kwargs.get('track_id', {}).get('origin', None)
self_track_id_att = kwargs.get('track_id', {}).get('attack', None)
activated_starcks = []
refind_stracks = []
lost_stracks = []
removed_stracks = []
width = img0.shape[1]
height = img0.shape[0]
inp_height = im_blob.shape[2]
inp_width = im_blob.shape[3]
c = np.array([width / 2., height / 2.], dtype=np.float32)
s = max(float(inp_width) / float(inp_height) * height, width) * 1.0
meta = {'c': c, 's': s,
'out_height': inp_height // self.opt.down_ratio,
'out_width': inp_width // self.opt.down_ratio}
''' Step 1: Network forward, get detections & embeddings'''
# with torch.no_grad():
im_blob.requires_grad = True
self.model.zero_grad()
output = self.model(im_blob)[-1]
hm = output['hm'].sigmoid()
wh = output['wh']
id_feature = output['id']
id_feature = F.normalize(id_feature, dim=1)
reg = output['reg'] if self.opt.reg_offset else None
dets_raw, inds = mot_decode(hm, wh, reg=reg, cat_spec_wh=self.opt.cat_spec_wh, K=self.opt.K)
id_features = []
for i in range(3):
for j in range(3):
id_feature_exp = _tranpose_and_gather_feat_expand(id_feature, inds, bias=(i - 1, j - 1)).squeeze(0)
id_features.append(id_feature_exp)
id_feature = _tranpose_and_gather_feat_expand(id_feature, inds)
id_feature = id_feature.squeeze(0)
dets = self.post_process(dets_raw.clone(), meta)
dets = self.merge_outputs([dets])[1]
remain_inds = dets[:, 4] > self.opt.conf_thres
dets = dets[remain_inds]
id_feature = id_feature[remain_inds]
for i in range(len(id_features)):
id_features[i] = id_features[i][remain_inds]
id_feature = id_feature.detach().cpu().numpy()
last_id_features = [None for _ in range(len(dets))]
last_ad_id_features = [None for _ in range(len(dets))]
dets_index = [i for i in range(len(dets))]
dets_ids = [None for _ in range(len(dets))]
tracks_ad = []
# import pdb; pdb.set_trace()
# vis
'''
for i in range(0, dets.shape[0]):
bbox = dets[i][0:4]
cv2.rectangle(img0, (bbox[0], bbox[1]),
(bbox[2], bbox[3]),
(0, 255, 0), 2)
cv2.imshow('dets', img0)
cv2.waitKey(0)
id0 = id0-1
'''
if len(dets) > 0:
'''Detections'''
detections = [STrack(STrack.tlbr_to_tlwh(tlbrs[:4]), tlbrs[4], f, 30) for
(tlbrs, f) in zip(dets[:, :5], id_feature)]
else:
detections = []
''' Add newly detected tracklets to tracked_stracks'''
unconfirmed = []
tracked_stracks = [] # type: list[STrack]
for track in self.tracked_stracks_:
if not track.is_activated:
unconfirmed.append(track)
else:
tracked_stracks.append(track)
''' Step 2: First association, with embedding'''
strack_pool = joint_stracks(tracked_stracks, self.lost_stracks_)
STrack.multi_predict(strack_pool)
dists = matching.embedding_distance(strack_pool, detections)
# dists = matching.gate_cost_matrix(self.kalman_filter, dists, strack_pool, detections)
dists = matching.fuse_motion(self.kalman_filter_, dists, strack_pool, detections)
matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.7)
# import pdb; pdb.set_trace()
for itracked, idet in matches:
track = strack_pool[itracked]
det = detections[idet]
assert last_id_features[dets_index[idet]] is None
assert last_ad_id_features[dets_index[idet]] is None
last_id_features[dets_index[idet]] = track.smooth_feat
last_ad_id_features[dets_index[idet]] = track.smooth_feat_ad
tracks_ad.append((track, dets_index[idet]))
if track.state == TrackState.Tracked:
track.update(detections[idet], self.frame_id_)
activated_starcks.append(track)
else:
track.re_activate_(det, self.frame_id_, new_id=False)
refind_stracks.append(track)
dets_ids[dets_index[idet]] = track.track_id
''' Step 3: Second association, with IOU'''
dets_index = [dets_index[i] for i in u_detection]
detections = [detections[i] for i in u_detection]
r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked]
dists = matching.iou_distance(r_tracked_stracks, detections)
matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.5)
for itracked, idet in matches:
track = r_tracked_stracks[itracked]
det = detections[idet]
assert last_id_features[dets_index[idet]] is None
assert last_ad_id_features[dets_index[idet]] is None
last_id_features[dets_index[idet]] = track.smooth_feat
last_ad_id_features[dets_index[idet]] = track.smooth_feat_ad
tracks_ad.append((track, dets_index[idet]))
if track.state == TrackState.Tracked:
track.update(det, self.frame_id_)
activated_starcks.append(track)
else:
track.re_activate_(det, self.frame_id_, new_id=False)
refind_stracks.append(track)
dets_ids[dets_index[idet]] = track.track_id
for it in u_track:
track = r_tracked_stracks[it]
if not track.state == TrackState.Lost:
track.mark_lost()
lost_stracks.append(track)
'''Deal with unconfirmed tracks, usually tracks with only one beginning frame'''
dets_index = [dets_index[i] for i in u_detection]
detections = [detections[i] for i in u_detection]
dists = matching.iou_distance(unconfirmed, detections)
matches, u_unconfirmed, u_detection = matching.linear_assignment(dists, thresh=0.7)
for itracked, idet in matches:
assert last_id_features[dets_index[idet]] is None
assert last_ad_id_features[dets_index[idet]] is None
last_id_features[dets_index[idet]] = unconfirmed[itracked].smooth_feat
last_ad_id_features[dets_index[idet]] = unconfirmed[itracked].smooth_feat_ad
tracks_ad.append((unconfirmed[itracked], dets_index[idet]))
unconfirmed[itracked].update(detections[idet], self.frame_id_)
activated_starcks.append(unconfirmed[itracked])
dets_ids[dets_index[idet]] = unconfirmed[itracked].track_id
for it in u_unconfirmed:
track = unconfirmed[it]
track.mark_removed()
removed_stracks.append(track)
""" Step 4: Init new stracks"""
for inew in u_detection:
track = detections[inew]
if track.score < self.det_thresh:
continue
track.activate_(self.kalman_filter_, self.frame_id_, track_id=self_track_id_ori)
activated_starcks.append(track)
dets_ids[dets_index[inew]] = track.track_id
""" Step 5: Update state"""
for track in self.lost_stracks_:
if self.frame_id_ - track.end_frame > self.max_time_lost:
track.mark_removed()
removed_stracks.append(track)
# print('Ramained match {} s'.format(t4-t3))
self.tracked_stracks_ = [t for t in self.tracked_stracks_ if t.state == TrackState.Tracked]
self.tracked_stracks_ = joint_stracks(self.tracked_stracks_, activated_starcks)
self.tracked_stracks_ = joint_stracks(self.tracked_stracks_, refind_stracks)
self.lost_stracks_ = sub_stracks(self.lost_stracks_, self.tracked_stracks_)
self.lost_stracks_.extend(lost_stracks)
self.lost_stracks_ = sub_stracks(self.lost_stracks_, self.removed_stracks_)
self.removed_stracks_.extend(removed_stracks)
self.tracked_stracks_, self.lost_stracks_ = remove_duplicate_stracks(self.tracked_stracks_, self.lost_stracks_)
# get scores of lost tracks
output_stracks_ori = [track for track in self.tracked_stracks_ if track.is_activated]
logger.debug('===========Frame {}=========='.format(self.frame_id_))
logger.debug('Activated: {}'.format([track.track_id for track in activated_starcks]))
logger.debug('Refind: {}'.format([track.track_id for track in refind_stracks]))
logger.debug('Lost: {}'.format([track.track_id for track in lost_stracks]))
logger.debug('Removed: {}'.format([track.track_id for track in removed_stracks]))
noise = None
suc = 0
for attack_ind, track_id in enumerate(dets_ids):
if track_id == attack_id:
if self.opt.attack_id > 0:
if not hasattr(self, f'frames_{attack_id}'):
setattr(self, f'frames_{attack_id}', 0)
if getattr(self, f'frames_{attack_id}') < self.FRAME_THR:
setattr(self, f'frames_{attack_id}', getattr(self, f'frames_{attack_id}') + 1)
break
fit = self.CheckFit(dets, id_feature, [attack_id], [attack_ind])
ious = bbox_ious(np.ascontiguousarray(dets[:, :4], dtype=np.float64),
np.ascontiguousarray(dets[:, :4], dtype=np.float64))
ious[range(len(dets)), range(len(dets))] = 0
dis = bbox_dis(np.ascontiguousarray(dets[:, :4], dtype=np.float64),
np.ascontiguousarray(dets[:, :4], dtype=np.float64))
dis[range(len(dets)), range(len(dets))] = np.inf
target_ind = np.argmax(ious[attack_ind])
if ious[attack_ind][target_ind] >= self.attack_iou_thr:
if ious[attack_ind][target_ind] == 0:
target_ind = np.argmin(dis[attack_ind])
target_id = dets_ids[target_ind]
if fit:
if self.opt.rand:
noise, attack_iter, suc = self.attack_sg_random(
im_blob,
img0,
id_features,
dets,
inds,
remain_inds,
last_info=self.ad_last_info,
outputs_ori=output,
attack_id=attack_id,
attack_ind=attack_ind,
target_id=target_id,
target_ind=target_ind
)
else:
noise, attack_iter, suc = self.attack_sg(
im_blob,
img0,
id_features,
dets,
inds,
remain_inds,
last_info=self.ad_last_info,
outputs_ori=output,
attack_id=attack_id,
attack_ind=attack_ind,
target_id=target_id,
target_ind=target_ind
)
self.attack_iou_thr = 0
if suc:
suc = 1
print(
f'attack id: {attack_id}\tattack frame {self.frame_id_}: SUCCESS\tl2 distance: {(noise ** 2).sum().sqrt().item()}\titeration: {attack_iter}')
else:
suc = 2
print(
f'attack id: {attack_id}\tattack frame {self.frame_id_}: FAIL\tl2 distance: {(noise ** 2).sum().sqrt().item() if noise is not None else None}\titeration: {attack_iter}')
else:
suc = 3
if ious[attack_ind][target_ind] == 0:
self.temp_i += 1
if self.temp_i >= 10:
self.attack_iou_thr = self.ATTACK_IOU_THR
else:
self.temp_i = 0
else:
self.attack_iou_thr = self.ATTACK_IOU_THR
if fit:
suc = 2
if noise is not None:
l2_dis = (noise ** 2).sum().sqrt().item()
adImg = torch.clip(im_blob + noise, min=0, max=1)
noise = self.recoverNoise(noise, img0)
# adImg = np.clip(img0 + noise, a_min=0, a_max=255)
# noise = adImg - img0
noise = (noise - np.min(noise)) / (np.max(noise) - np.min(noise))
noise = (noise * 255).astype(np.uint8)
else:
l2_dis = None
adImg = im_blob
output_stracks_att = self.update(adImg, img0, track_id=self_track_id_att)
adImg = self.recoverNoise(adImg.detach(), img0)
return output_stracks_ori, output_stracks_att, adImg, noise, l2_dis, suc
def update_attack_mt(self, im_blob, img0, **kwargs):
self.frame_id_ += 1
activated_starcks = []
refind_stracks = []
lost_stracks = []
removed_stracks = []
width = img0.shape[1]
height = img0.shape[0]
inp_height = im_blob.shape[2]
inp_width = im_blob.shape[3]
c = np.array([width / 2., height / 2.], dtype=np.float32)
s = max(float(inp_width) / float(inp_height) * height, width) * 1.0
meta = {'c': c, 's': s,
'out_height': inp_height // self.opt.down_ratio,
'out_width': inp_width // self.opt.down_ratio}
''' Step 1: Network forward, get detections & embeddings'''
# with torch.no_grad():
im_blob.requires_grad = True
self.model.zero_grad()
output = self.model(im_blob)[-1]
hm = output['hm'].sigmoid()
wh = output['wh']
id_feature = output['id']
id_feature = F.normalize(id_feature, dim=1)
reg = output['reg'] if self.opt.reg_offset else None
dets_raw, inds = mot_decode(hm, wh, reg=reg, cat_spec_wh=self.opt.cat_spec_wh, K=self.opt.K)
id_features = []
for i in range(3):
for j in range(3):
id_feature_exp = _tranpose_and_gather_feat_expand(id_feature, inds, bias=(i - 1, j - 1)).squeeze(0)
id_features.append(id_feature_exp)
id_feature = _tranpose_and_gather_feat_expand(id_feature, inds)
id_feature = id_feature.squeeze(0)
dets = self.post_process(dets_raw.clone(), meta)
dets = self.merge_outputs([dets])[1]
remain_inds = dets[:, 4] > self.opt.conf_thres
dets = dets[remain_inds]
id_feature = id_feature[remain_inds]
for i in range(len(id_features)):
id_features[i] = id_features[i][remain_inds]
id_feature = id_feature.detach().cpu().numpy()
last_id_features = [None for _ in range(len(dets))]
last_ad_id_features = [None for _ in range(len(dets))]
dets_index = [i for i in range(len(dets))]
dets_ids = [None for _ in range(len(dets))]
tracks_ad = []
# import pdb; pdb.set_trace()
# vis
'''
for i in range(0, dets.shape[0]):
bbox = dets[i][0:4]
cv2.rectangle(img0, (bbox[0], bbox[1]),
(bbox[2], bbox[3]),
(0, 255, 0), 2)
cv2.imshow('dets', img0)
cv2.waitKey(0)
id0 = id0-1
'''
if len(dets) > 0:
'''Detections'''
detections = [STrack(STrack.tlbr_to_tlwh(tlbrs[:4]), tlbrs[4], f, 30) for
(tlbrs, f) in zip(dets[:, :5], id_feature)]
else:
detections = []
''' Add newly detected tracklets to tracked_stracks'''
unconfirmed = []
tracked_stracks = [] # type: list[STrack]
for track in self.tracked_stracks_:
if not track.is_activated:
unconfirmed.append(track)
else:
tracked_stracks.append(track)
''' Step 2: First association, with embedding'''
strack_pool = joint_stracks(tracked_stracks, self.lost_stracks_)
STrack.multi_predict(strack_pool)
dists = matching.embedding_distance(strack_pool, detections)
dists = matching.fuse_motion(self.kalman_filter_, dists, strack_pool, detections)
matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.7)
# import pdb; pdb.set_trace()
for itracked, idet in matches:
track = strack_pool[itracked]
det = detections[idet]
assert last_id_features[dets_index[idet]] is None
assert last_ad_id_features[dets_index[idet]] is None
last_id_features[dets_index[idet]] = track.smooth_feat
last_ad_id_features[dets_index[idet]] = track.smooth_feat_ad
tracks_ad.append((track, dets_index[idet]))
if track.state == TrackState.Tracked:
track.update(detections[idet], self.frame_id_)
activated_starcks.append(track)
else:
track.re_activate_(det, self.frame_id_, new_id=False)
refind_stracks.append(track)
dets_ids[dets_index[idet]] = track.track_id
''' Step 3: Second association, with IOU'''
dets_index = [dets_index[i] for i in u_detection]
detections = [detections[i] for i in u_detection]
r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked]
dists = matching.iou_distance(r_tracked_stracks, detections)
matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.5)
for itracked, idet in matches:
track = r_tracked_stracks[itracked]
det = detections[idet]
assert last_id_features[dets_index[idet]] is None
assert last_ad_id_features[dets_index[idet]] is None
last_id_features[dets_index[idet]] = track.smooth_feat
last_ad_id_features[dets_index[idet]] = track.smooth_feat_ad
tracks_ad.append((track, dets_index[idet]))
if track.state == TrackState.Tracked:
track.update(det, self.frame_id_)
activated_starcks.append(track)
else:
track.re_activate_(det, self.frame_id_, new_id=False)
refind_stracks.append(track)
dets_ids[dets_index[idet]] = track.track_id
for it in u_track:
track = r_tracked_stracks[it]
if not track.state == TrackState.Lost:
track.mark_lost()
lost_stracks.append(track)
'''Deal with unconfirmed tracks, usually tracks with only one beginning frame'''
dets_index = [dets_index[i] for i in u_detection]
detections = [detections[i] for i in u_detection]
dists = matching.iou_distance(unconfirmed, detections)
matches, u_unconfirmed, u_detection = matching.linear_assignment(dists, thresh=0.7)
for itracked, idet in matches:
assert last_id_features[dets_index[idet]] is None
assert last_ad_id_features[dets_index[idet]] is None
last_id_features[dets_index[idet]] = unconfirmed[itracked].smooth_feat
last_ad_id_features[dets_index[idet]] = unconfirmed[itracked].smooth_feat_ad
tracks_ad.append((unconfirmed[itracked], dets_index[idet]))
unconfirmed[itracked].update(detections[idet], self.frame_id_)
activated_starcks.append(unconfirmed[itracked])
dets_ids[dets_index[idet]] = unconfirmed[itracked].track_id
for it in u_unconfirmed:
track = unconfirmed[it]
track.mark_removed()
removed_stracks.append(track)
""" Step 4: Init new stracks"""
for inew in u_detection:
track = detections[inew]
if track.score < self.det_thresh:
continue
track.activate_(self.kalman_filter_, self.frame_id_)
activated_starcks.append(track)
dets_ids[dets_index[inew]] = track.track_id
""" Step 5: Update state"""
for track in self.lost_stracks_:
if self.frame_id_ - track.end_frame > self.max_time_lost:
track.mark_removed()
removed_stracks.append(track)
# print('Ramained match {} s'.format(t4-t3))
self.tracked_stracks_ = [t for t in self.tracked_stracks_ if t.state == TrackState.Tracked]
self.tracked_stracks_ = joint_stracks(self.tracked_stracks_, activated_starcks)
self.tracked_stracks_ = joint_stracks(self.tracked_stracks_, refind_stracks)
self.lost_stracks_ = sub_stracks(self.lost_stracks_, self.tracked_stracks_)
self.lost_stracks_.extend(lost_stracks)
self.lost_stracks_ = sub_stracks(self.lost_stracks_, self.removed_stracks_)
self.removed_stracks_.extend(removed_stracks)
self.tracked_stracks_, self.lost_stracks_ = remove_duplicate_stracks(self.tracked_stracks_, self.lost_stracks_)
# get scores of lost tracks
output_stracks_ori = [track for track in self.tracked_stracks_ if track.is_activated]
id_set = set([track.track_id for track in output_stracks_ori])
for i in range(len(dets_ids)):
if dets_ids[i] is not None and dets_ids[i] not in id_set:
dets_ids[i] = None
output_stracks_ori_ind = []
for ind, track in enumerate(output_stracks_ori):
if track.track_id not in self.multiple_ori_ids:
self.multiple_ori_ids[track.track_id] = 0
self.multiple_ori_ids[track.track_id] += 1
if self.multiple_ori_ids[track.track_id] <= self.FRAME_THR:
output_stracks_ori_ind.append(ind)
logger.debug('===========Frame {}=========='.format(self.frame_id_))
logger.debug('Activated: {}'.format([track.track_id for track in activated_starcks]))
logger.debug('Refind: {}'.format([track.track_id for track in refind_stracks]))
logger.debug('Lost: {}'.format([track.track_id for track in lost_stracks]))
logger.debug('Removed: {}'.format([track.track_id for track in removed_stracks]))
attack_ids = []
target_ids = []
attack_inds = []
target_inds = []
noise = None
if len(dets) > 0:
ious = bbox_ious(np.ascontiguousarray(dets[:, :4], dtype=np.float64),
np.ascontiguousarray(dets[:, :4], dtype=np.float64))
ious[range(len(dets)), range(len(dets))] = 0
ious_inds = np.argmax(ious, axis=1)
dis = bbox_dis(np.ascontiguousarray(dets[:, :4], dtype=np.float64),
np.ascontiguousarray(dets[:, :4], dtype=np.float64))
dis[range(len(dets)), range(len(dets))] = np.inf
dis_inds = np.argmin(dis, axis=1)
for attack_ind, track_id in enumerate(dets_ids):
if track_id is None or self.multiple_ori_ids[track_id] <= self.FRAME_THR \
or dets_ids[ious_inds[attack_ind]] not in self.multiple_ori2att \
or track_id not in self.multiple_ori2att:
continue
if ious[attack_ind, ious_inds[attack_ind]] > self.ATTACK_IOU_THR or (
track_id in self.low_iou_ids and ious[attack_ind, ious_inds[attack_ind]] > 0
):
attack_ids.append(track_id)
target_ids.append(dets_ids[ious_inds[attack_ind]])
attack_inds.append(attack_ind)
target_inds.append(ious_inds[attack_ind])
if hasattr(self, f'temp_i_{track_id}'):
self.__setattr__(f'temp_i_{track_id}', 0)
elif ious[attack_ind, ious_inds[attack_ind]] == 0 and track_id in self.low_iou_ids:
if hasattr(self, f'temp_i_{track_id}'):
self.__setattr__(f'temp_i_{track_id}', self.__getattribute__(f'temp_i_{track_id}') + 1)
else:
self.__setattr__(f'temp_i_{track_id}', 1)
if self.__getattribute__(f'temp_i_{track_id}') > 10:
self.low_iou_ids.remove(track_id)
elif dets_ids[dis_inds[attack_ind]] in self.multiple_ori2att:
attack_ids.append(track_id)
target_ids.append(dets_ids[dis_inds[attack_ind]])
attack_inds.append(attack_ind)
target_inds.append(dis_inds[attack_ind])
fit_index = self.CheckFit(dets, id_feature, attack_ids, attack_inds) if len(attack_ids) else []
if fit_index:
attack_ids = np.array(attack_ids)[fit_index]
target_ids = np.array(target_ids)[fit_index]
attack_inds = np.array(attack_inds)[fit_index]
target_inds = np.array(target_inds)[fit_index]
if self.opt.rand:
noise, attack_iter, suc = self.attack_mt_random(
im_blob,
img0,
id_features,
dets,
inds,
remain_inds,
last_info=self.ad_last_info,
outputs_ori=output,
attack_ids=attack_ids,
attack_inds=attack_inds,
target_ids=target_ids,
target_inds=target_inds
)
else:
noise, attack_iter, suc = self.attack_mt(
im_blob,
img0,
id_features,
dets,
inds,
remain_inds,
last_info=self.ad_last_info,
outputs_ori=output,
attack_ids=attack_ids,
attack_inds=attack_inds,
target_ids=target_ids,
target_inds=target_inds
)
self.low_iou_ids.update(set(attack_ids))
if suc:
self.attacked_ids.update(set(attack_ids))
print(
f'attack ids: {attack_ids}\tattack frame {self.frame_id_}: SUCCESS\tl2 distance: {(noise ** 2).sum().sqrt().item()}\titeration: {attack_iter}')
else:
print(f'attack ids: {attack_ids}\tattack frame {self.frame_id_}: FAIL\tl2 distance: {(noise ** 2).sum().sqrt().item() if noise is not None else None}\titeration: {attack_iter}')
if noise is not None:
l2_dis = (noise ** 2).sum().sqrt().item()
adImg = torch.clip(im_blob + noise, min=0, max=1)
noise = self.recoverNoise(noise, img0)
noise = (noise - np.min(noise)) / (np.max(noise) - np.min(noise))
noise = (noise * 255).astype(np.uint8)
else:
l2_dis = None
adImg = im_blob
output_stracks_att = self.update(adImg, img0)
adImg = self.recoverNoise(adImg.detach(), img0)
output_stracks_att_ind = []
for ind, track in enumerate(output_stracks_att):
if track.track_id not in self.multiple_att_ids:
self.multiple_att_ids[track.track_id] = 0
self.multiple_att_ids[track.track_id] += 1
if self.multiple_att_ids[track.track_id] <= self.FRAME_THR:
output_stracks_att_ind.append(ind)
if len(output_stracks_ori_ind) and len(output_stracks_att_ind):
ori_dets = [track.curr_tlbr for i, track in enumerate(output_stracks_ori) if i in output_stracks_ori_ind]
att_dets = [track.curr_tlbr for i, track in enumerate(output_stracks_att) if i in output_stracks_att_ind]
ori_dets = np.stack(ori_dets).astype(np.float64)
att_dets = np.stack(att_dets).astype(np.float64)
ious = bbox_ious(ori_dets, att_dets)
row_ind, col_ind = linear_sum_assignment(-ious)
for i in range(len(row_ind)):
if ious[row_ind[i], col_ind[i]] > 0.9:
ori_id = output_stracks_ori[output_stracks_ori_ind[row_ind[i]]].track_id
att_id = output_stracks_att[output_stracks_att_ind[col_ind[i]]].track_id
self.multiple_ori2att[ori_id] = att_id
return output_stracks_ori, output_stracks_att, adImg, noise, l2_dis
def update_attack_sg_feat(self, im_blob, img0, **kwargs):
self.frame_id_ += 1
attack_id = kwargs['attack_id']
self_track_id_ori = kwargs.get('track_id', {}).get('origin', None)
self_track_id_att = kwargs.get('track_id', {}).get('attack', None)
activated_starcks = []
refind_stracks = []
lost_stracks = []
removed_stracks = []
width = img0.shape[1]
height = img0.shape[0]
inp_height = im_blob.shape[2]
inp_width = im_blob.shape[3]
c = np.array([width / 2., height / 2.], dtype=np.float32)
s = max(float(inp_width) / float(inp_height) * height, width) * 1.0
meta = {'c': c, 's': s,
'out_height': inp_height // self.opt.down_ratio,
'out_width': inp_width // self.opt.down_ratio}
''' Step 1: Network forward, get detections & embeddings'''
# with torch.no_grad():
im_blob.requires_grad = True
self.model.zero_grad()
output = self.model(im_blob)[-1]
hm = output['hm'].sigmoid()
wh = output['wh']
id_feature = output['id']
id_feature = F.normalize(id_feature, dim=1)
reg = output['reg'] if self.opt.reg_offset else None
dets_raw, inds = mot_decode(hm, wh, reg=reg, cat_spec_wh=self.opt.cat_spec_wh, K=self.opt.K)
id_features = []
for i in range(3):
for j in range(3):
id_feature_exp = _tranpose_and_gather_feat_expand(id_feature, inds, bias=(i - 1, j - 1)).squeeze(0)
id_features.append(id_feature_exp)
id_feature = _tranpose_and_gather_feat_expand(id_feature, inds)
id_feature = id_feature.squeeze(0)
dets = self.post_process(dets_raw.clone(), meta)
dets = self.merge_outputs([dets])[1]
remain_inds = dets[:, 4] > self.opt.conf_thres
dets = dets[remain_inds]
id_feature = id_feature[remain_inds]
for i in range(len(id_features)):
id_features[i] = id_features[i][remain_inds]
id_feature = id_feature.detach().cpu().numpy()
last_id_features = [None for _ in range(len(dets))]
last_ad_id_features = [None for _ in range(len(dets))]
dets_index = [i for i in range(len(dets))]
dets_ids = [None for _ in range(len(dets))]
tracks_ad = []
# import pdb; pdb.set_trace()
# vis
'''
for i in range(0, dets.shape[0]):
bbox = dets[i][0:4]
cv2.rectangle(img0, (bbox[0], bbox[1]),
(bbox[2], bbox[3]),
(0, 255, 0), 2)
cv2.imshow('dets', img0)
cv2.waitKey(0)
id0 = id0-1
'''
if len(dets) > 0:
'''Detections'''
detections = [STrack(STrack.tlbr_to_tlwh(tlbrs[:4]), tlbrs[4], f, 30) for
(tlbrs, f) in zip(dets[:, :5], id_feature)]
else:
detections = []
''' Add newly detected tracklets to tracked_stracks'''
unconfirmed = []
tracked_stracks = [] # type: list[STrack]
for track in self.tracked_stracks_:
if not track.is_activated:
unconfirmed.append(track)
else:
tracked_stracks.append(track)
''' Step 2: First association, with embedding'''
strack_pool = joint_stracks(tracked_stracks, self.lost_stracks_)
STrack.multi_predict(strack_pool)
dists = matching.embedding_distance(strack_pool, detections)
# dists = matching.gate_cost_matrix(self.kalman_filter, dists, strack_pool, detections)
dists = matching.fuse_motion(self.kalman_filter_, dists, strack_pool, detections)
matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.7)
# import pdb; pdb.set_trace()
for itracked, idet in matches:
track = strack_pool[itracked]
det = detections[idet]
assert last_id_features[dets_index[idet]] is None
assert last_ad_id_features[dets_index[idet]] is None
last_id_features[dets_index[idet]] = track.smooth_feat
last_ad_id_features[dets_index[idet]] = track.smooth_feat_ad
tracks_ad.append((track, dets_index[idet]))
if track.state == TrackState.Tracked:
track.update(detections[idet], self.frame_id_)
activated_starcks.append(track)
else:
track.re_activate_(det, self.frame_id_, new_id=False)
refind_stracks.append(track)
dets_ids[dets_index[idet]] = track.track_id
''' Step 3: Second association, with IOU'''
dets_index = [dets_index[i] for i in u_detection]
detections = [detections[i] for i in u_detection]
r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked]
dists = matching.iou_distance(r_tracked_stracks, detections)
matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.5)
for itracked, idet in matches:
track = r_tracked_stracks[itracked]
det = detections[idet]
assert last_id_features[dets_index[idet]] is None
assert last_ad_id_features[dets_index[idet]] is None
last_id_features[dets_index[idet]] = track.smooth_feat
last_ad_id_features[dets_index[idet]] = track.smooth_feat_ad
tracks_ad.append((track, dets_index[idet]))
if track.state == TrackState.Tracked:
track.update(det, self.frame_id_)
activated_starcks.append(track)
else:
track.re_activate_(det, self.frame_id_, new_id=False)
refind_stracks.append(track)
dets_ids[dets_index[idet]] = track.track_id
for it in u_track:
track = r_tracked_stracks[it]
if not track.state == TrackState.Lost:
track.mark_lost()
lost_stracks.append(track)
'''Deal with unconfirmed tracks, usually tracks with only one beginning frame'''
dets_index = [dets_index[i] for i in u_detection]
detections = [detections[i] for i in u_detection]
dists = matching.iou_distance(unconfirmed, detections)
matches, u_unconfirmed, u_detection = matching.linear_assignment(dists, thresh=0.7)
for itracked, idet in matches:
assert last_id_features[dets_index[idet]] is None
assert last_ad_id_features[dets_index[idet]] is None
last_id_features[dets_index[idet]] = unconfirmed[itracked].smooth_feat
last_ad_id_features[dets_index[idet]] = unconfirmed[itracked].smooth_feat_ad
tracks_ad.append((unconfirmed[itracked], dets_index[idet]))
unconfirmed[itracked].update(detections[idet], self.frame_id_)
activated_starcks.append(unconfirmed[itracked])
dets_ids[dets_index[idet]] = unconfirmed[itracked].track_id
for it in u_unconfirmed:
track = unconfirmed[it]
track.mark_removed()
removed_stracks.append(track)
""" Step 4: Init new stracks"""
for inew in u_detection:
track = detections[inew]
if track.score < self.det_thresh:
continue
track.activate_(self.kalman_filter_, self.frame_id_, track_id=self_track_id_ori)
activated_starcks.append(track)
dets_ids[dets_index[inew]] = track.track_id
""" Step 5: Update state"""
for track in self.lost_stracks_:
if self.frame_id_ - track.end_frame > self.max_time_lost:
track.mark_removed()
removed_stracks.append(track)
# print('Ramained match {} s'.format(t4-t3))
self.tracked_stracks_ = [t for t in self.tracked_stracks_ if t.state == TrackState.Tracked]
self.tracked_stracks_ = joint_stracks(self.tracked_stracks_, activated_starcks)
self.tracked_stracks_ = joint_stracks(self.tracked_stracks_, refind_stracks)
self.lost_stracks_ = sub_stracks(self.lost_stracks_, self.tracked_stracks_)
self.lost_stracks_.extend(lost_stracks)
self.lost_stracks_ = sub_stracks(self.lost_stracks_, self.removed_stracks_)
self.removed_stracks_.extend(removed_stracks)
self.tracked_stracks_, self.lost_stracks_ = remove_duplicate_stracks(self.tracked_stracks_, self.lost_stracks_)
# get scores of lost tracks
output_stracks_ori = [track for track in self.tracked_stracks_ if track.is_activated]
logger.debug('===========Frame {}=========='.format(self.frame_id_))
logger.debug('Activated: {}'.format([track.track_id for track in activated_starcks]))
logger.debug('Refind: {}'.format([track.track_id for track in refind_stracks]))
logger.debug('Lost: {}'.format([track.track_id for track in lost_stracks]))
logger.debug('Removed: {}'.format([track.track_id for track in removed_stracks]))
noise = None
suc = 0
for attack_ind, track_id in enumerate(dets_ids):
if track_id == attack_id:
if self.opt.attack_id > 0:
if not hasattr(self, f'frames_{attack_id}'):
setattr(self, f'frames_{attack_id}', 0)
if getattr(self, f'frames_{attack_id}') < self.FRAME_THR:
setattr(self, f'frames_{attack_id}', getattr(self, f'frames_{attack_id}') + 1)
break
fit = self.CheckFit(dets, id_feature, [attack_id], [attack_ind])
ious = bbox_ious(np.ascontiguousarray(dets[:, :4], dtype=np.float64),
np.ascontiguousarray(dets[:, :4], dtype=np.float64))
ious[range(len(dets)), range(len(dets))] = 0
dis = bbox_dis(np.ascontiguousarray(dets[:, :4], dtype=np.float64),
np.ascontiguousarray(dets[:, :4], dtype=np.float64))
dis[range(len(dets)), range(len(dets))] = np.inf
target_ind = np.argmax(ious[attack_ind])
if ious[attack_ind][target_ind] >= self.attack_iou_thr:
if ious[attack_ind][target_ind] == 0:
target_ind = np.argmin(dis[attack_ind])
target_id = dets_ids[target_ind]
if fit:
noise, attack_iter, suc = self.attack_sg_feat(
im_blob,
img0,
id_features,
dets,
inds,
remain_inds,
last_info=self.ad_last_info,
outputs_ori=output,
attack_id=attack_id,
attack_ind=attack_ind,
target_id=target_id,
target_ind=target_ind
)
self.attack_iou_thr = 0
if suc:
suc = 1
print(
f'attack id: {attack_id}\tattack frame {self.frame_id_}: SUCCESS\tl2 distance: {(noise ** 2).sum().sqrt().item()}\titeration: {attack_iter}')
else:
suc = 2
print(
f'attack id: {attack_id}\tattack frame {self.frame_id_}: FAIL\tl2 distance: {(noise ** 2).sum().sqrt().item()}\titeration: {attack_iter}')
else:
suc = 3
if ious[attack_ind][target_ind] == 0:
self.temp_i += 1
if self.temp_i >= 10:
self.attack_iou_thr = self.ATTACK_IOU_THR
else:
self.temp_i = 0
else:
self.attack_iou_thr = self.ATTACK_IOU_THR
if fit:
suc = 2
if noise is not None:
l2_dis = (noise ** 2).sum().sqrt().item()
adImg = torch.clip(im_blob + noise, min=0, max=1)
noise = self.recoverNoise(noise, img0)
noise = (noise - np.min(noise)) / (np.max(noise) - np.min(noise))
noise = (noise * 255).astype(np.uint8)
else:
l2_dis = None
adImg = im_blob
output_stracks_att = self.update(adImg, img0, track_id=self_track_id_att)
adImg = self.recoverNoise(adImg.detach(), img0)
return output_stracks_ori, output_stracks_att, adImg, noise, l2_dis, suc
def update_attack_sg_cl(self, im_blob, img0, **kwargs):
self.frame_id_ += 1
attack_id = kwargs['attack_id']
self_track_id_ori = kwargs.get('track_id', {}).get('origin', None)
self_track_id_att = kwargs.get('track_id', {}).get('attack', None)
activated_starcks = []
refind_stracks = []
lost_stracks = []
removed_stracks = []
width = img0.shape[1]
height = img0.shape[0]
inp_height = im_blob.shape[2]
inp_width = im_blob.shape[3]
c = np.array([width / 2., height / 2.], dtype=np.float32)
s = max(float(inp_width) / float(inp_height) * height, width) * 1.0
meta = {'c': c, 's': s,
'out_height': inp_height // self.opt.down_ratio,
'out_width': inp_width // self.opt.down_ratio}
''' Step 1: Network forward, get detections & embeddings'''
# with torch.no_grad():
im_blob.requires_grad = True
self.model.zero_grad()
output = self.model(im_blob)[-1]
hm = output['hm'].sigmoid()
wh = output['wh']
id_feature = output['id']
id_feature = F.normalize(id_feature, dim=1)
reg = output['reg'] if self.opt.reg_offset else None
dets_raw, inds = mot_decode(hm, wh, reg=reg, cat_spec_wh=self.opt.cat_spec_wh, K=self.opt.K)
id_features = []
for i in range(3):
for j in range(3):
id_feature_exp = _tranpose_and_gather_feat_expand(id_feature, inds, bias=(i - 1, j - 1)).squeeze(0)
id_features.append(id_feature_exp)
id_feature = _tranpose_and_gather_feat_expand(id_feature, inds)
id_feature = id_feature.squeeze(0)
dets = self.post_process(dets_raw.clone(), meta)
dets = self.merge_outputs([dets])[1]
remain_inds = dets[:, 4] > self.opt.conf_thres
dets = dets[remain_inds]
id_feature = id_feature[remain_inds]
for i in range(len(id_features)):
id_features[i] = id_features[i][remain_inds]
id_feature = id_feature.detach().cpu().numpy()
last_id_features = [None for _ in range(len(dets))]
last_ad_id_features = [None for _ in range(len(dets))]
dets_index = [i for i in range(len(dets))]
dets_ids = [None for _ in range(len(dets))]
tracks_ad = []
# import pdb; pdb.set_trace()
# vis
'''
for i in range(0, dets.shape[0]):
bbox = dets[i][0:4]
cv2.rectangle(img0, (bbox[0], bbox[1]),
(bbox[2], bbox[3]),
(0, 255, 0), 2)
cv2.imshow('dets', img0)
cv2.waitKey(0)
id0 = id0-1
'''
if len(dets) > 0:
'''Detections'''
detections = [STrack(STrack.tlbr_to_tlwh(tlbrs[:4]), tlbrs[4], f, 30) for
(tlbrs, f) in zip(dets[:, :5], id_feature)]
else:
detections = []
''' Add newly detected tracklets to tracked_stracks'''
unconfirmed = []
tracked_stracks = [] # type: list[STrack]
for track in self.tracked_stracks_:
if not track.is_activated:
unconfirmed.append(track)
else:
tracked_stracks.append(track)
''' Step 2: First association, with embedding'''
strack_pool = joint_stracks(tracked_stracks, self.lost_stracks_)
STrack.multi_predict(strack_pool)
dists = matching.embedding_distance(strack_pool, detections)
# dists = matching.gate_cost_matrix(self.kalman_filter, dists, strack_pool, detections)
dists = matching.fuse_motion(self.kalman_filter_, dists, strack_pool, detections)
matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.7)
# import pdb; pdb.set_trace()
for itracked, idet in matches:
track = strack_pool[itracked]
det = detections[idet]
assert last_id_features[dets_index[idet]] is None
assert last_ad_id_features[dets_index[idet]] is None
last_id_features[dets_index[idet]] = track.smooth_feat
last_ad_id_features[dets_index[idet]] = track.smooth_feat_ad
tracks_ad.append((track, dets_index[idet]))
if track.state == TrackState.Tracked:
track.update(detections[idet], self.frame_id_)
activated_starcks.append(track)
else:
track.re_activate_(det, self.frame_id_, new_id=False)
refind_stracks.append(track)
dets_ids[dets_index[idet]] = track.track_id
''' Step 3: Second association, with IOU'''
dets_index = [dets_index[i] for i in u_detection]
detections = [detections[i] for i in u_detection]
r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked]
dists = matching.iou_distance(r_tracked_stracks, detections)
matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.5)
for itracked, idet in matches:
track = r_tracked_stracks[itracked]
det = detections[idet]
assert last_id_features[dets_index[idet]] is None
assert last_ad_id_features[dets_index[idet]] is None
last_id_features[dets_index[idet]] = track.smooth_feat
last_ad_id_features[dets_index[idet]] = track.smooth_feat_ad
tracks_ad.append((track, dets_index[idet]))
if track.state == TrackState.Tracked:
track.update(det, self.frame_id_)
activated_starcks.append(track)
else:
track.re_activate_(det, self.frame_id_, new_id=False)
refind_stracks.append(track)
dets_ids[dets_index[idet]] = track.track_id
for it in u_track:
track = r_tracked_stracks[it]
if not track.state == TrackState.Lost:
track.mark_lost()
lost_stracks.append(track)
'''Deal with unconfirmed tracks, usually tracks with only one beginning frame'''
dets_index = [dets_index[i] for i in u_detection]
detections = [detections[i] for i in u_detection]
dists = matching.iou_distance(unconfirmed, detections)
matches, u_unconfirmed, u_detection = matching.linear_assignment(dists, thresh=0.7)
for itracked, idet in matches:
assert last_id_features[dets_index[idet]] is None
assert last_ad_id_features[dets_index[idet]] is None
last_id_features[dets_index[idet]] = unconfirmed[itracked].smooth_feat
last_ad_id_features[dets_index[idet]] = unconfirmed[itracked].smooth_feat_ad
tracks_ad.append((unconfirmed[itracked], dets_index[idet]))
unconfirmed[itracked].update(detections[idet], self.frame_id_)
activated_starcks.append(unconfirmed[itracked])
dets_ids[dets_index[idet]] = unconfirmed[itracked].track_id
for it in u_unconfirmed:
track = unconfirmed[it]
track.mark_removed()
removed_stracks.append(track)
""" Step 4: Init new stracks"""
for inew in u_detection:
track = detections[inew]
if track.score < self.det_thresh:
continue
track.activate_(self.kalman_filter_, self.frame_id_, track_id=self_track_id_ori)
activated_starcks.append(track)
dets_ids[dets_index[inew]] = track.track_id
""" Step 5: Update state"""
for track in self.lost_stracks_:
if self.frame_id_ - track.end_frame > self.max_time_lost:
track.mark_removed()
removed_stracks.append(track)
# print('Ramained match {} s'.format(t4-t3))
self.tracked_stracks_ = [t for t in self.tracked_stracks_ if t.state == TrackState.Tracked]
self.tracked_stracks_ = joint_stracks(self.tracked_stracks_, activated_starcks)
self.tracked_stracks_ = joint_stracks(self.tracked_stracks_, refind_stracks)
self.lost_stracks_ = sub_stracks(self.lost_stracks_, self.tracked_stracks_)
self.lost_stracks_.extend(lost_stracks)
self.lost_stracks_ = sub_stracks(self.lost_stracks_, self.removed_stracks_)
self.removed_stracks_.extend(removed_stracks)
self.tracked_stracks_, self.lost_stracks_ = remove_duplicate_stracks(self.tracked_stracks_, self.lost_stracks_)
# get scores of lost tracks
output_stracks_ori = [track for track in self.tracked_stracks_ if track.is_activated]
logger.debug('===========Frame {}=========='.format(self.frame_id_))
logger.debug('Activated: {}'.format([track.track_id for track in activated_starcks]))
logger.debug('Refind: {}'.format([track.track_id for track in refind_stracks]))
logger.debug('Lost: {}'.format([track.track_id for track in lost_stracks]))
logger.debug('Removed: {}'.format([track.track_id for track in removed_stracks]))
noise = None
suc = 0
for attack_ind, track_id in enumerate(dets_ids):
if track_id == attack_id:
if self.opt.attack_id > 0:
if not hasattr(self, f'frames_{attack_id}'):
setattr(self, f'frames_{attack_id}', 0)
if getattr(self, f'frames_{attack_id}') < self.FRAME_THR:
setattr(self, f'frames_{attack_id}', getattr(self, f'frames_{attack_id}') + 1)
break
fit = self.CheckFit(dets, id_feature, [attack_id], [attack_ind])
ious = bbox_ious(np.ascontiguousarray(dets[:, :4], dtype=np.float64),
np.ascontiguousarray(dets[:, :4], dtype=np.float64))
ious[range(len(dets)), range(len(dets))] = 0
dis = bbox_dis(np.ascontiguousarray(dets[:, :4], dtype=np.float64),
np.ascontiguousarray(dets[:, :4], dtype=np.float64))
dis[range(len(dets)), range(len(dets))] = np.inf
target_ind = np.argmax(ious[attack_ind])
if ious[attack_ind][target_ind] >= self.attack_iou_thr:
if ious[attack_ind][target_ind] == 0:
target_ind = np.argmin(dis[attack_ind])
target_id = dets_ids[target_ind]
if fit:
noise, attack_iter, suc = self.attack_sg_cl(
im_blob,
img0,
id_features,
dets,
inds,
remain_inds,
last_info=self.ad_last_info,
outputs_ori=output,
attack_id=attack_id,
attack_ind=attack_ind,
target_id=target_id,
target_ind=target_ind
)
self.attack_iou_thr = 0
if suc:
suc = 1
print(
f'attack id: {attack_id}\tattack frame {self.frame_id_}: SUCCESS\tl2 distance: {(noise ** 2).sum().sqrt().item()}\titeration: {attack_iter}')
else:
suc = 2
print(
f'attack id: {attack_id}\tattack frame {self.frame_id_}: FAIL\tl2 distance: {(noise ** 2).sum().sqrt().item() if noise is not None else None}\titeration: {attack_iter}')
else:
suc = 3
if ious[attack_ind][target_ind] == 0:
self.temp_i += 1
if self.temp_i >= 10:
self.attack_iou_thr = self.ATTACK_IOU_THR
else:
self.temp_i = 0
else:
self.attack_iou_thr = self.ATTACK_IOU_THR
if fit:
suc = 2
if noise is not None:
l2_dis = (noise ** 2).sum().sqrt().item()
adImg = torch.clip(im_blob + noise, min=0, max=1)
noise = self.recoverNoise(noise, img0)
# adImg = np.clip(img0 + noise, a_min=0, a_max=255)
# noise = adImg - img0
noise = (noise - np.min(noise)) / (np.max(noise) - np.min(noise))
noise = (noise * 255).astype(np.uint8)
else:
l2_dis = None
adImg = im_blob
output_stracks_att = self.update(adImg, img0, track_id=self_track_id_att)
adImg = self.recoverNoise(adImg.detach(), img0)
return output_stracks_ori, output_stracks_att, adImg, noise, l2_dis, suc
def update_attack_sg_det(self, im_blob, img0, **kwargs):
self.frame_id_ += 1
attack_id = kwargs['attack_id']
self_track_id_ori = kwargs.get('track_id', {}).get('origin', None)
self_track_id_att = kwargs.get('track_id', {}).get('attack', None)
activated_starcks = []
refind_stracks = []
lost_stracks = []
removed_stracks = []
width = img0.shape[1]
height = img0.shape[0]
inp_height = im_blob.shape[2]
inp_width = im_blob.shape[3]
c = np.array([width / 2., height / 2.], dtype=np.float32)
s = max(float(inp_width) / float(inp_height) * height, width) * 1.0
meta = {'c': c, 's': s,
'out_height': inp_height // self.opt.down_ratio,
'out_width': inp_width // self.opt.down_ratio}
''' Step 1: Network forward, get detections & embeddings'''
# with torch.no_grad():
im_blob.requires_grad = True
self.model.zero_grad()
output = self.model(im_blob)[-1]
hm = output['hm'].sigmoid()
wh = output['wh']
id_feature = output['id']
id_feature = F.normalize(id_feature, dim=1)
reg = output['reg'] if self.opt.reg_offset else None
dets_raw, inds = mot_decode(hm, wh, reg=reg, cat_spec_wh=self.opt.cat_spec_wh, K=self.opt.K)
id_features = []
for i in range(3):
for j in range(3):
id_feature_exp = _tranpose_and_gather_feat_expand(id_feature, inds, bias=(i - 1, j - 1)).squeeze(0)
id_features.append(id_feature_exp)
id_feature = _tranpose_and_gather_feat_expand(id_feature, inds)
id_feature = id_feature.squeeze(0)
dets = self.post_process(dets_raw.clone(), meta)
dets = self.merge_outputs([dets])[1]
remain_inds = dets[:, 4] > self.opt.conf_thres
dets = dets[remain_inds]
id_feature = id_feature[remain_inds]
for i in range(len(id_features)):
id_features[i] = id_features[i][remain_inds]
id_feature = id_feature.detach().cpu().numpy()
last_id_features = [None for _ in range(len(dets))]
last_ad_id_features = [None for _ in range(len(dets))]
dets_index = [i for i in range(len(dets))]
dets_ids = [None for _ in range(len(dets))]
tracks_ad = []
# import pdb; pdb.set_trace()
# vis
'''
for i in range(0, dets.shape[0]):
bbox = dets[i][0:4]
cv2.rectangle(img0, (bbox[0], bbox[1]),
(bbox[2], bbox[3]),
(0, 255, 0), 2)
cv2.imshow('dets', img0)
cv2.waitKey(0)
id0 = id0-1
'''
if len(dets) > 0:
'''Detections'''
detections = [STrack(STrack.tlbr_to_tlwh(tlbrs[:4]), tlbrs[4], f, 30) for
(tlbrs, f) in zip(dets[:, :5], id_feature)]
else:
detections = []
''' Add newly detected tracklets to tracked_stracks'''
unconfirmed = []
tracked_stracks = [] # type: list[STrack]
for track in self.tracked_stracks_:
if not track.is_activated:
unconfirmed.append(track)
else:
tracked_stracks.append(track)
''' Step 2: First association, with embedding'''
strack_pool = joint_stracks(tracked_stracks, self.lost_stracks_)
STrack.multi_predict(strack_pool)
dists = matching.embedding_distance(strack_pool, detections)
# dists = matching.gate_cost_matrix(self.kalman_filter, dists, strack_pool, detections)
dists = matching.fuse_motion(self.kalman_filter_, dists, strack_pool, detections)
matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.7)
# import pdb; pdb.set_trace()
for itracked, idet in matches:
track = strack_pool[itracked]
det = detections[idet]
assert last_id_features[dets_index[idet]] is None
assert last_ad_id_features[dets_index[idet]] is None
last_id_features[dets_index[idet]] = track.smooth_feat
last_ad_id_features[dets_index[idet]] = track.smooth_feat_ad
tracks_ad.append((track, dets_index[idet]))
if track.state == TrackState.Tracked:
track.update(detections[idet], self.frame_id_)
activated_starcks.append(track)
else:
track.re_activate_(det, self.frame_id_, new_id=False)
refind_stracks.append(track)
dets_ids[dets_index[idet]] = track.track_id
''' Step 3: Second association, with IOU'''
dets_index = [dets_index[i] for i in u_detection]
detections = [detections[i] for i in u_detection]
r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked]
dists = matching.iou_distance(r_tracked_stracks, detections)
matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.5)
for itracked, idet in matches:
track = r_tracked_stracks[itracked]
det = detections[idet]
assert last_id_features[dets_index[idet]] is None
assert last_ad_id_features[dets_index[idet]] is None
last_id_features[dets_index[idet]] = track.smooth_feat
last_ad_id_features[dets_index[idet]] = track.smooth_feat_ad
tracks_ad.append((track, dets_index[idet]))
if track.state == TrackState.Tracked:
track.update(det, self.frame_id_)
activated_starcks.append(track)
else:
track.re_activate_(det, self.frame_id_, new_id=False)
refind_stracks.append(track)
dets_ids[dets_index[idet]] = track.track_id
for it in u_track:
track = r_tracked_stracks[it]
if not track.state == TrackState.Lost:
track.mark_lost()
lost_stracks.append(track)
'''Deal with unconfirmed tracks, usually tracks with only one beginning frame'''
dets_index = [dets_index[i] for i in u_detection]
detections = [detections[i] for i in u_detection]
dists = matching.iou_distance(unconfirmed, detections)
matches, u_unconfirmed, u_detection = matching.linear_assignment(dists, thresh=0.7)
for itracked, idet in matches:
assert last_id_features[dets_index[idet]] is None
assert last_ad_id_features[dets_index[idet]] is None
last_id_features[dets_index[idet]] = unconfirmed[itracked].smooth_feat
last_ad_id_features[dets_index[idet]] = unconfirmed[itracked].smooth_feat_ad
tracks_ad.append((unconfirmed[itracked], dets_index[idet]))
unconfirmed[itracked].update(detections[idet], self.frame_id_)
activated_starcks.append(unconfirmed[itracked])
dets_ids[dets_index[idet]] = unconfirmed[itracked].track_id
for it in u_unconfirmed:
track = unconfirmed[it]
track.mark_removed()
removed_stracks.append(track)
""" Step 4: Init new stracks"""
for inew in u_detection:
track = detections[inew]
if track.score < self.det_thresh:
continue
track.activate_(self.kalman_filter_, self.frame_id_, track_id=self_track_id_ori)
activated_starcks.append(track)
dets_ids[dets_index[inew]] = track.track_id
""" Step 5: Update state"""
for track in self.lost_stracks_:
if self.frame_id_ - track.end_frame > self.max_time_lost:
track.mark_removed()
removed_stracks.append(track)
# print('Ramained match {} s'.format(t4-t3))
self.tracked_stracks_ = [t for t in self.tracked_stracks_ if t.state == TrackState.Tracked]
self.tracked_stracks_ = joint_stracks(self.tracked_stracks_, activated_starcks)
self.tracked_stracks_ = joint_stracks(self.tracked_stracks_, refind_stracks)
self.lost_stracks_ = sub_stracks(self.lost_stracks_, self.tracked_stracks_)
self.lost_stracks_.extend(lost_stracks)
self.lost_stracks_ = sub_stracks(self.lost_stracks_, self.removed_stracks_)
self.removed_stracks_.extend(removed_stracks)
self.tracked_stracks_, self.lost_stracks_ = remove_duplicate_stracks(self.tracked_stracks_, self.lost_stracks_)
# get scores of lost tracks
output_stracks_ori = [track for track in self.tracked_stracks_ if track.is_activated]
logger.debug('===========Frame {}=========='.format(self.frame_id_))
logger.debug('Activated: {}'.format([track.track_id for track in activated_starcks]))
logger.debug('Refind: {}'.format([track.track_id for track in refind_stracks]))
logger.debug('Lost: {}'.format([track.track_id for track in lost_stracks]))
logger.debug('Removed: {}'.format([track.track_id for track in removed_stracks]))
noise = None
suc = 0
for attack_ind, track_id in enumerate(dets_ids):
if track_id == attack_id:
if self.opt.attack_id > 0:
if not hasattr(self, f'frames_{attack_id}'):
setattr(self, f'frames_{attack_id}', 0)
if getattr(self, f'frames_{attack_id}') < self.FRAME_THR:
setattr(self, f'frames_{attack_id}', getattr(self, f'frames_{attack_id}') + 1)
break
ious = bbox_ious(np.ascontiguousarray(dets[:, :4], dtype=np.float64),
np.ascontiguousarray(dets[:, :4], dtype=np.float64))
ious = self.processIoUs(ious)
ious = ious + ious.T
target_ind = np.argmax(ious[attack_ind])
if ious[attack_ind][target_ind] >= self.attack_iou_thr:
fit = self.CheckFit(dets, id_feature, [attack_id], [attack_ind])
if fit:
noise, attack_iter, suc = self.attack_sg_det(
im_blob,
img0,
dets,
inds,
remain_inds,
last_info=self.ad_last_info,
outputs_ori=output,
attack_id=attack_id,
attack_ind=attack_ind
)
self.attack_iou_thr = 0
if suc:
suc = 1
print(
f'attack id: {attack_id}\tattack frame {self.frame_id_}: SUCCESS\tl2 distance: {(noise ** 2).sum().sqrt().item()}\titeration: {attack_iter}')
else:
suc = 2
print(
f'attack id: {attack_id}\tattack frame {self.frame_id_}: FAIL\tl2 distance: {(noise ** 2).sum().sqrt().item()}\titeration: {attack_iter}')
else:
suc = 3
if ious[attack_ind][target_ind] == 0:
self.temp_i += 1
if self.temp_i >= 10:
self.attack_iou_thr = self.ATTACK_IOU_THR
else:
self.temp_i = 0
else:
self.attack_iou_thr = self.ATTACK_IOU_THR
break
if noise is not None:
l2_dis = (noise ** 2).sum().sqrt().item()
adImg = torch.clip(im_blob + noise, min=0, max=1)
noise = self.recoverNoise(noise, img0)
noise = (noise - np.min(noise)) / (np.max(noise) - np.min(noise))
noise = (noise * 255).astype(np.uint8)
else:
l2_dis = None
adImg = im_blob
output_stracks_att = self.update(adImg, img0, track_id=self_track_id_att)
adImg = self.recoverNoise(adImg.detach(), img0)
return output_stracks_ori, output_stracks_att, adImg, noise, l2_dis, suc
def update_attack_sg_hj(self, im_blob, img0, **kwargs):
self.frame_id_ += 1
attack_id = kwargs['attack_id']
self_track_id_ori = kwargs.get('track_id', {}).get('origin', None)
self_track_id_att = kwargs.get('track_id', {}).get('attack', None)
activated_starcks = []
refind_stracks = []
lost_stracks = []
removed_stracks = []
width = img0.shape[1]
height = img0.shape[0]
inp_height = im_blob.shape[2]
inp_width = im_blob.shape[3]
c = np.array([width / 2., height / 2.], dtype=np.float32)
s = max(float(inp_width) / float(inp_height) * height, width) * 1.0
meta = {'c': c, 's': s,
'out_height': inp_height // self.opt.down_ratio,
'out_width': inp_width // self.opt.down_ratio}
''' Step 1: Network forward, get detections & embeddings'''
# with torch.no_grad():
im_blob.requires_grad = True
self.model.zero_grad()
output = self.model(im_blob)[-1]
hm = output['hm'].sigmoid()
wh = output['wh']
id_feature = output['id']
id_feature = F.normalize(id_feature, dim=1)
reg = output['reg'] if self.opt.reg_offset else None
dets_raw, inds = mot_decode(hm, wh, reg=reg, cat_spec_wh=self.opt.cat_spec_wh, K=self.opt.K)
id_features = []
for i in range(3):
for j in range(3):
id_feature_exp = _tranpose_and_gather_feat_expand(id_feature, inds, bias=(i - 1, j - 1)).squeeze(0)
id_features.append(id_feature_exp)
id_feature = _tranpose_and_gather_feat_expand(id_feature, inds)
id_feature = id_feature.squeeze(0)
dets = self.post_process(dets_raw.clone(), meta)
dets = self.merge_outputs([dets])[1]
remain_inds = dets[:, 4] > self.opt.conf_thres
dets = dets[remain_inds]
id_feature = id_feature[remain_inds]
for i in range(len(id_features)):
id_features[i] = id_features[i][remain_inds]
id_feature = id_feature.detach().cpu().numpy()
last_id_features = [None for _ in range(len(dets))]
last_ad_id_features = [None for _ in range(len(dets))]
dets_index = [i for i in range(len(dets))]
dets_ids = [None for _ in range(len(dets))]
tracks_ad = []
# import pdb; pdb.set_trace()
# vis
'''
for i in range(0, dets.shape[0]):
bbox = dets[i][0:4]
cv2.rectangle(img0, (bbox[0], bbox[1]),
(bbox[2], bbox[3]),
(0, 255, 0), 2)
cv2.imshow('dets', img0)
cv2.waitKey(0)
id0 = id0-1
'''
if len(dets) > 0:
'''Detections'''
detections = [STrack(STrack.tlbr_to_tlwh(tlbrs[:4]), tlbrs[4], f, 30) for
(tlbrs, f) in zip(dets[:, :5], id_feature)]
else:
detections = []
''' Add newly detected tracklets to tracked_stracks'''
unconfirmed = []
tracked_stracks = [] # type: list[STrack]
for track in self.tracked_stracks_:
if not track.is_activated:
unconfirmed.append(track)
else:
tracked_stracks.append(track)
''' Step 2: First association, with embedding'''
strack_pool = joint_stracks(tracked_stracks, self.lost_stracks_)
STrack.multi_predict(strack_pool)
dists = matching.embedding_distance(strack_pool, detections)
# dists = matching.gate_cost_matrix(self.kalman_filter, dists, strack_pool, detections)
dists = matching.fuse_motion(self.kalman_filter_, dists, strack_pool, detections)
matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.7)
# import pdb; pdb.set_trace()
for itracked, idet in matches:
track = strack_pool[itracked]
det = detections[idet]
assert last_id_features[dets_index[idet]] is None
assert last_ad_id_features[dets_index[idet]] is None
last_id_features[dets_index[idet]] = track.smooth_feat
last_ad_id_features[dets_index[idet]] = track.smooth_feat_ad
tracks_ad.append((track, dets_index[idet]))
if track.state == TrackState.Tracked:
track.update(detections[idet], self.frame_id_)
activated_starcks.append(track)
else:
track.re_activate_(det, self.frame_id_, new_id=False)
refind_stracks.append(track)
dets_ids[dets_index[idet]] = track.track_id
''' Step 3: Second association, with IOU'''
dets_index = [dets_index[i] for i in u_detection]
detections = [detections[i] for i in u_detection]
r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked]
dists = matching.iou_distance(r_tracked_stracks, detections)
matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.5)
for itracked, idet in matches:
track = r_tracked_stracks[itracked]
det = detections[idet]
assert last_id_features[dets_index[idet]] is None
assert last_ad_id_features[dets_index[idet]] is None
last_id_features[dets_index[idet]] = track.smooth_feat
last_ad_id_features[dets_index[idet]] = track.smooth_feat_ad
tracks_ad.append((track, dets_index[idet]))
if track.state == TrackState.Tracked:
track.update(det, self.frame_id_)
activated_starcks.append(track)
else:
track.re_activate_(det, self.frame_id_, new_id=False)
refind_stracks.append(track)
dets_ids[dets_index[idet]] = track.track_id
for it in u_track:
track = r_tracked_stracks[it]
if not track.state == TrackState.Lost:
track.mark_lost()
lost_stracks.append(track)
'''Deal with unconfirmed tracks, usually tracks with only one beginning frame'''
dets_index = [dets_index[i] for i in u_detection]
detections = [detections[i] for i in u_detection]
dists = matching.iou_distance(unconfirmed, detections)
matches, u_unconfirmed, u_detection = matching.linear_assignment(dists, thresh=0.7)
for itracked, idet in matches:
assert last_id_features[dets_index[idet]] is None
assert last_ad_id_features[dets_index[idet]] is None
last_id_features[dets_index[idet]] = unconfirmed[itracked].smooth_feat
last_ad_id_features[dets_index[idet]] = unconfirmed[itracked].smooth_feat_ad
tracks_ad.append((unconfirmed[itracked], dets_index[idet]))
unconfirmed[itracked].update(detections[idet], self.frame_id_)
activated_starcks.append(unconfirmed[itracked])
dets_ids[dets_index[idet]] = unconfirmed[itracked].track_id
for it in u_unconfirmed:
track = unconfirmed[it]
track.mark_removed()
removed_stracks.append(track)
""" Step 4: Init new stracks"""
for inew in u_detection:
track = detections[inew]
if track.score < self.det_thresh:
continue
track.activate_(self.kalman_filter_, self.frame_id_, track_id=self_track_id_ori)
activated_starcks.append(track)
dets_ids[dets_index[inew]] = track.track_id
""" Step 5: Update state"""
for track in self.lost_stracks_:
if self.frame_id_ - track.end_frame > self.max_time_lost:
track.mark_removed()
removed_stracks.append(track)
# print('Ramained match {} s'.format(t4-t3))
self.tracked_stracks_ = [t for t in self.tracked_stracks_ if t.state == TrackState.Tracked]
self.tracked_stracks_ = joint_stracks(self.tracked_stracks_, activated_starcks)
self.tracked_stracks_ = joint_stracks(self.tracked_stracks_, refind_stracks)
self.lost_stracks_ = sub_stracks(self.lost_stracks_, self.tracked_stracks_)
self.lost_stracks_.extend(lost_stracks)
self.lost_stracks_ = sub_stracks(self.lost_stracks_, self.removed_stracks_)
self.removed_stracks_.extend(removed_stracks)
self.tracked_stracks_, self.lost_stracks_ = remove_duplicate_stracks(self.tracked_stracks_, self.lost_stracks_)
# get scores of lost tracks
output_stracks_ori = [track for track in self.tracked_stracks_ if track.is_activated]
logger.debug('===========Frame {}=========='.format(self.frame_id_))
logger.debug('Activated: {}'.format([track.track_id for track in activated_starcks]))
logger.debug('Refind: {}'.format([track.track_id for track in refind_stracks]))
logger.debug('Lost: {}'.format([track.track_id for track in lost_stracks]))
logger.debug('Removed: {}'.format([track.track_id for track in removed_stracks]))
noise = None
suc = 0
att_tracker = None
if self.ad_bbox:
for t in output_stracks_ori:
if t.track_id == attack_id:
att_tracker = t
for attack_ind, track_id in enumerate(dets_ids):
if track_id == attack_id:
if self.opt.attack_id > 0:
if not hasattr(self, f'frames_{attack_id}'):
setattr(self, f'frames_{attack_id}', 0)
if getattr(self, f'frames_{attack_id}') < self.FRAME_THR:
setattr(self, f'frames_{attack_id}', getattr(self, f'frames_{attack_id}') + 1)
break
ious = bbox_ious(np.ascontiguousarray(dets[:, :4], dtype=np.float64),
np.ascontiguousarray(dets[:, :4], dtype=np.float64))
ious = self.processIoUs(ious)
ious = ious + ious.T
target_ind = np.argmax(ious[attack_ind])
if ious[attack_ind][target_ind] >= self.attack_iou_thr:
fit = self.CheckFit(dets, id_feature, [attack_id], [attack_ind])
if fit:
noise, attack_iter, suc = self.attack_sg_hj(
im_blob,
img0,
dets,
inds,
remain_inds,
last_info=self.ad_last_info,
outputs_ori=output,
attack_id=attack_id,
attack_ind=attack_ind,
ad_bbox=self.ad_bbox,
track_v=att_tracker.get_v() if att_tracker is not None else None
)
self.attack_iou_thr = 0
if suc:
suc = 1
print(
f'attack id: {attack_id}\tattack frame {self.frame_id_}: SUCCESS\tl2 distance: {(noise ** 2).sum().sqrt().item()}\titeration: {attack_iter}')
else:
suc = 2
print(
f'attack id: {attack_id}\tattack frame {self.frame_id_}: FAIL\tl2 distance: {(noise ** 2).sum().sqrt().item()}\titeration: {attack_iter}')
else:
suc = 3
if ious[attack_ind][target_ind] == 0:
self.temp_i += 1
if self.temp_i >= 10:
self.attack_iou_thr = self.ATTACK_IOU_THR
else:
self.temp_i = 0
else:
self.attack_iou_thr = self.ATTACK_IOU_THR
break
if noise is not None:
self.ad_bbox = False
l2_dis = (noise ** 2).sum().sqrt().item()
adImg = torch.clip(im_blob + noise, min=0, max=1)
noise = self.recoverNoise(noise, img0)
noise = (noise - np.min(noise)) / (np.max(noise) - np.min(noise))
noise = (noise * 255).astype(np.uint8)
else:
l2_dis = None
adImg = im_blob
output_stracks_att = self.update(adImg, img0, track_id=self_track_id_att)
adImg = self.recoverNoise(adImg.detach(), img0)
return output_stracks_ori, output_stracks_att, adImg, noise, l2_dis, suc
def update_attack_mt_det(self, im_blob, img0, **kwargs):
self.frame_id_ += 1
activated_starcks = []
refind_stracks = []
lost_stracks = []
removed_stracks = []
width = img0.shape[1]
height = img0.shape[0]
inp_height = im_blob.shape[2]
inp_width = im_blob.shape[3]
c = np.array([width / 2., height / 2.], dtype=np.float32)
s = max(float(inp_width) / float(inp_height) * height, width) * 1.0
meta = {'c': c, 's': s,
'out_height': inp_height // self.opt.down_ratio,
'out_width': inp_width // self.opt.down_ratio}
''' Step 1: Network forward, get detections & embeddings'''
# with torch.no_grad():
im_blob.requires_grad = True
self.model.zero_grad()
output = self.model(im_blob)[-1]
hm = output['hm'].sigmoid()
wh = output['wh']
id_feature = output['id']
id_feature = F.normalize(id_feature, dim=1)
reg = output['reg'] if self.opt.reg_offset else None
dets_raw, inds = mot_decode(hm, wh, reg=reg, cat_spec_wh=self.opt.cat_spec_wh, K=self.opt.K)
id_features = []
for i in range(3):
for j in range(3):
id_feature_exp = _tranpose_and_gather_feat_expand(id_feature, inds, bias=(i - 1, j - 1)).squeeze(0)
id_features.append(id_feature_exp)
id_feature = _tranpose_and_gather_feat_expand(id_feature, inds)
id_feature = id_feature.squeeze(0)
dets = self.post_process(dets_raw.clone(), meta)
dets = self.merge_outputs([dets])[1]
remain_inds = dets[:, 4] > self.opt.conf_thres
dets = dets[remain_inds]
id_feature = id_feature[remain_inds]
for i in range(len(id_features)):
id_features[i] = id_features[i][remain_inds]
id_feature = id_feature.detach().cpu().numpy()
last_id_features = [None for _ in range(len(dets))]
last_ad_id_features = [None for _ in range(len(dets))]
dets_index = [i for i in range(len(dets))]
dets_ids = [None for _ in range(len(dets))]
tracks_ad = []
# import pdb; pdb.set_trace()
# vis
'''
for i in range(0, dets.shape[0]):
bbox = dets[i][0:4]
cv2.rectangle(img0, (bbox[0], bbox[1]),
(bbox[2], bbox[3]),
(0, 255, 0), 2)
cv2.imshow('dets', img0)
cv2.waitKey(0)
id0 = id0-1
'''
if len(dets) > 0:
'''Detections'''
detections = [STrack(STrack.tlbr_to_tlwh(tlbrs[:4]), tlbrs[4], f, 30) for
(tlbrs, f) in zip(dets[:, :5], id_feature)]
else:
detections = []
''' Add newly detected tracklets to tracked_stracks'''
unconfirmed = []
tracked_stracks = [] # type: list[STrack]
for track in self.tracked_stracks_:
if not track.is_activated:
unconfirmed.append(track)
else:
tracked_stracks.append(track)
''' Step 2: First association, with embedding'''
strack_pool = joint_stracks(tracked_stracks, self.lost_stracks_)
STrack.multi_predict(strack_pool)
dists = matching.embedding_distance(strack_pool, detections)
dists = matching.fuse_motion(self.kalman_filter_, dists, strack_pool, detections)
matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.7)
# import pdb; pdb.set_trace()
for itracked, idet in matches:
track = strack_pool[itracked]
det = detections[idet]
assert last_id_features[dets_index[idet]] is None
assert last_ad_id_features[dets_index[idet]] is None
last_id_features[dets_index[idet]] = track.smooth_feat
last_ad_id_features[dets_index[idet]] = track.smooth_feat_ad
tracks_ad.append((track, dets_index[idet]))
if track.state == TrackState.Tracked:
track.update(detections[idet], self.frame_id_)
activated_starcks.append(track)
else:
track.re_activate_(det, self.frame_id_, new_id=False)
refind_stracks.append(track)
dets_ids[dets_index[idet]] = track.track_id
''' Step 3: Second association, with IOU'''
dets_index = [dets_index[i] for i in u_detection]
detections = [detections[i] for i in u_detection]
r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked]
dists = matching.iou_distance(r_tracked_stracks, detections)
matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.5)
for itracked, idet in matches:
track = r_tracked_stracks[itracked]
det = detections[idet]
assert last_id_features[dets_index[idet]] is None
assert last_ad_id_features[dets_index[idet]] is None
last_id_features[dets_index[idet]] = track.smooth_feat
last_ad_id_features[dets_index[idet]] = track.smooth_feat_ad
tracks_ad.append((track, dets_index[idet]))
if track.state == TrackState.Tracked:
track.update(det, self.frame_id_)
activated_starcks.append(track)
else:
track.re_activate_(det, self.frame_id_, new_id=False)
refind_stracks.append(track)
dets_ids[dets_index[idet]] = track.track_id
for it in u_track:
track = r_tracked_stracks[it]
if not track.state == TrackState.Lost:
track.mark_lost()
lost_stracks.append(track)
'''Deal with unconfirmed tracks, usually tracks with only one beginning frame'''
dets_index = [dets_index[i] for i in u_detection]
detections = [detections[i] for i in u_detection]
dists = matching.iou_distance(unconfirmed, detections)
matches, u_unconfirmed, u_detection = matching.linear_assignment(dists, thresh=0.7)
for itracked, idet in matches:
assert last_id_features[dets_index[idet]] is None
assert last_ad_id_features[dets_index[idet]] is None
last_id_features[dets_index[idet]] = unconfirmed[itracked].smooth_feat
last_ad_id_features[dets_index[idet]] = unconfirmed[itracked].smooth_feat_ad
tracks_ad.append((unconfirmed[itracked], dets_index[idet]))
unconfirmed[itracked].update(detections[idet], self.frame_id_)
activated_starcks.append(unconfirmed[itracked])
dets_ids[dets_index[idet]] = unconfirmed[itracked].track_id
for it in u_unconfirmed:
track = unconfirmed[it]
track.mark_removed()
removed_stracks.append(track)
""" Step 4: Init new stracks"""
for inew in u_detection:
track = detections[inew]
if track.score < self.det_thresh:
continue
track.activate_(self.kalman_filter_, self.frame_id_)
activated_starcks.append(track)
dets_ids[dets_index[inew]] = track.track_id
""" Step 5: Update state"""
for track in self.lost_stracks_:
if self.frame_id_ - track.end_frame > self.max_time_lost:
track.mark_removed()
removed_stracks.append(track)
# print('Ramained match {} s'.format(t4-t3))
self.tracked_stracks_ = [t for t in self.tracked_stracks_ if t.state == TrackState.Tracked]
self.tracked_stracks_ = joint_stracks(self.tracked_stracks_, activated_starcks)
self.tracked_stracks_ = joint_stracks(self.tracked_stracks_, refind_stracks)
self.lost_stracks_ = sub_stracks(self.lost_stracks_, self.tracked_stracks_)
self.lost_stracks_.extend(lost_stracks)
self.lost_stracks_ = sub_stracks(self.lost_stracks_, self.removed_stracks_)
self.removed_stracks_.extend(removed_stracks)
self.tracked_stracks_, self.lost_stracks_ = remove_duplicate_stracks(self.tracked_stracks_, self.lost_stracks_)
# get scores of lost tracks
output_stracks_ori = [track for track in self.tracked_stracks_ if track.is_activated]
id_set = set([track.track_id for track in output_stracks_ori])
for i in range(len(dets_ids)):
if dets_ids[i] is not None and dets_ids[i] not in id_set:
dets_ids[i] = None
output_stracks_ori_ind = []
for ind, track in enumerate(output_stracks_ori):
if track.track_id not in self.multiple_ori_ids:
self.multiple_ori_ids[track.track_id] = 0
self.multiple_ori_ids[track.track_id] += 1
if self.multiple_ori_ids[track.track_id] <= self.FRAME_THR:
output_stracks_ori_ind.append(ind)
logger.debug('===========Frame {}=========='.format(self.frame_id_))
logger.debug('Activated: {}'.format([track.track_id for track in activated_starcks]))
logger.debug('Refind: {}'.format([track.track_id for track in refind_stracks]))
logger.debug('Lost: {}'.format([track.track_id for track in lost_stracks]))
logger.debug('Removed: {}'.format([track.track_id for track in removed_stracks]))
attack_ids = []
target_ids = []
attack_inds = []
target_inds = []
noise = None
if len(dets) > 0:
ious = bbox_ious(np.ascontiguousarray(dets[:, :4], dtype=np.float64),
np.ascontiguousarray(dets[:, :4], dtype=np.float64))
ious[range(len(dets)), range(len(dets))] = 0
ious_inds = np.argmax(ious, axis=1)
dis = bbox_dis(np.ascontiguousarray(dets[:, :4], dtype=np.float64),
np.ascontiguousarray(dets[:, :4], dtype=np.float64))
dis[range(len(dets)), range(len(dets))] = np.inf
dis_inds = np.argmin(dis, axis=1)
for attack_ind, track_id in enumerate(dets_ids):
if track_id is None or self.multiple_ori_ids[track_id] <= self.FRAME_THR \
or dets_ids[ious_inds[attack_ind]] not in self.multiple_ori2att \
or track_id not in self.multiple_ori2att:
continue
if ious[attack_ind, ious_inds[attack_ind]] > self.ATTACK_IOU_THR or (
track_id in self.low_iou_ids and ious[attack_ind, ious_inds[attack_ind]] > 0
):
attack_ids.append(track_id)
target_ids.append(dets_ids[ious_inds[attack_ind]])
attack_inds.append(attack_ind)
target_inds.append(ious_inds[attack_ind])
if hasattr(self, f'temp_i_{track_id}'):
self.__setattr__(f'temp_i_{track_id}', 0)
elif ious[attack_ind, ious_inds[attack_ind]] == 0 and track_id in self.low_iou_ids:
if hasattr(self, f'temp_i_{track_id}'):
self.__setattr__(f'temp_i_{track_id}', self.__getattribute__(f'temp_i_{track_id}') + 1)
else:
self.__setattr__(f'temp_i_{track_id}', 1)
if self.__getattribute__(f'temp_i_{track_id}') > 10:
self.low_iou_ids.remove(track_id)
elif dets_ids[dis_inds[attack_ind]] in self.multiple_ori2att:
attack_ids.append(track_id)
target_ids.append(dets_ids[dis_inds[attack_ind]])
attack_inds.append(attack_ind)
target_inds.append(dis_inds[attack_ind])
fit_index = self.CheckFit(dets, id_feature, attack_ids, attack_inds) if len(attack_ids) else []
if fit_index:
attack_ids = np.array(attack_ids)[fit_index]
target_ids = np.array(target_ids)[fit_index]
attack_inds = np.array(attack_inds)[fit_index]
target_inds = np.array(target_inds)[fit_index]
noise, attack_iter, suc = self.attack_mt_det(
im_blob,
img0,
dets,
inds,
remain_inds,
last_info=self.ad_last_info,
outputs_ori=output,
attack_ids=attack_ids,
attack_inds=attack_inds
)
self.low_iou_ids.update(set(attack_ids))
if suc:
self.attacked_ids.update(set(attack_ids))
print(
f'attack ids: {attack_ids}\tattack frame {self.frame_id_}: SUCCESS\tl2 distance: {(noise ** 2).sum().sqrt().item()}\titeration: {attack_iter}')
else:
print(f'attack ids: {attack_ids}\tattack frame {self.frame_id_}: FAIL\tl2 distance: {(noise ** 2).sum().sqrt().item() if noise is not None else None}\titeration: {attack_iter}')
if noise is not None:
l2_dis = (noise ** 2).sum().sqrt().item()
adImg = torch.clip(im_blob + noise, min=0, max=1)
noise = self.recoverNoise(noise, img0)
noise = (noise - np.min(noise)) / (np.max(noise) - np.min(noise))
noise = (noise * 255).astype(np.uint8)
else:
l2_dis = None
adImg = im_blob
output_stracks_att = self.update(adImg, img0)
adImg = self.recoverNoise(adImg.detach(), img0)
output_stracks_att_ind = []
for ind, track in enumerate(output_stracks_att):
if track.track_id not in self.multiple_att_ids:
self.multiple_att_ids[track.track_id] = 0
self.multiple_att_ids[track.track_id] += 1
if self.multiple_att_ids[track.track_id] <= self.FRAME_THR:
output_stracks_att_ind.append(ind)
if len(output_stracks_ori_ind) and len(output_stracks_att_ind):
ori_dets = [track.curr_tlbr for i, track in enumerate(output_stracks_ori) if i in output_stracks_ori_ind]
att_dets = [track.curr_tlbr for i, track in enumerate(output_stracks_att) if i in output_stracks_att_ind]
ori_dets = np.stack(ori_dets).astype(np.float64)
att_dets = np.stack(att_dets).astype(np.float64)
ious = bbox_ious(ori_dets, att_dets)
row_ind, col_ind = linear_sum_assignment(-ious)
for i in range(len(row_ind)):
if ious[row_ind[i], col_ind[i]] > 0.9:
ori_id = output_stracks_ori[output_stracks_ori_ind[row_ind[i]]].track_id
att_id = output_stracks_att[output_stracks_att_ind[col_ind[i]]].track_id
self.multiple_ori2att[ori_id] = att_id
return output_stracks_ori, output_stracks_att, adImg, noise, l2_dis
def update_attack_mt_hj(self, im_blob, img0, **kwargs):
self.frame_id_ += 1
activated_starcks = []
refind_stracks = []
lost_stracks = []
removed_stracks = []
width = img0.shape[1]
height = img0.shape[0]
inp_height = im_blob.shape[2]
inp_width = im_blob.shape[3]
c = np.array([width / 2., height / 2.], dtype=np.float32)
s = max(float(inp_width) / float(inp_height) * height, width) * 1.0
meta = {'c': c, 's': s,
'out_height': inp_height // self.opt.down_ratio,
'out_width': inp_width // self.opt.down_ratio}
''' Step 1: Network forward, get detections & embeddings'''
# with torch.no_grad():
im_blob.requires_grad = True
self.model.zero_grad()
output = self.model(im_blob)[-1]
hm = output['hm'].sigmoid()
wh = output['wh']
id_feature = output['id']
id_feature = F.normalize(id_feature, dim=1)
reg = output['reg'] if self.opt.reg_offset else None
dets_raw, inds = mot_decode(hm, wh, reg=reg, cat_spec_wh=self.opt.cat_spec_wh, K=self.opt.K)
id_features = []
for i in range(3):
for j in range(3):
id_feature_exp = _tranpose_and_gather_feat_expand(id_feature, inds, bias=(i - 1, j - 1)).squeeze(0)
id_features.append(id_feature_exp)
id_feature = _tranpose_and_gather_feat_expand(id_feature, inds)
id_feature = id_feature.squeeze(0)
dets = self.post_process(dets_raw.clone(), meta)
dets = self.merge_outputs([dets])[1]
remain_inds = dets[:, 4] > self.opt.conf_thres
dets = dets[remain_inds]
id_feature = id_feature[remain_inds]
for i in range(len(id_features)):
id_features[i] = id_features[i][remain_inds]
id_feature = id_feature.detach().cpu().numpy()
last_id_features = [None for _ in range(len(dets))]
last_ad_id_features = [None for _ in range(len(dets))]
dets_index = [i for i in range(len(dets))]
dets_ids = [None for _ in range(len(dets))]
tracks_ad = []
# import pdb; pdb.set_trace()
# vis
'''
for i in range(0, dets.shape[0]):
bbox = dets[i][0:4]
cv2.rectangle(img0, (bbox[0], bbox[1]),
(bbox[2], bbox[3]),
(0, 255, 0), 2)
cv2.imshow('dets', img0)
cv2.waitKey(0)
id0 = id0-1
'''
if len(dets) > 0:
'''Detections'''
detections = [STrack(STrack.tlbr_to_tlwh(tlbrs[:4]), tlbrs[4], f, 30) for
(tlbrs, f) in zip(dets[:, :5], id_feature)]
else:
detections = []
''' Add newly detected tracklets to tracked_stracks'''
unconfirmed = []
tracked_stracks = [] # type: list[STrack]
for track in self.tracked_stracks_:
if not track.is_activated:
unconfirmed.append(track)
else:
tracked_stracks.append(track)
''' Step 2: First association, with embedding'''
strack_pool = joint_stracks(tracked_stracks, self.lost_stracks_)
STrack.multi_predict(strack_pool)
dists = matching.embedding_distance(strack_pool, detections)
dists = matching.fuse_motion(self.kalman_filter_, dists, strack_pool, detections)
matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.7)
# import pdb; pdb.set_trace()
for itracked, idet in matches:
track = strack_pool[itracked]
det = detections[idet]
assert last_id_features[dets_index[idet]] is None
assert last_ad_id_features[dets_index[idet]] is None
last_id_features[dets_index[idet]] = track.smooth_feat
last_ad_id_features[dets_index[idet]] = track.smooth_feat_ad
tracks_ad.append((track, dets_index[idet]))
if track.state == TrackState.Tracked:
track.update(detections[idet], self.frame_id_)
activated_starcks.append(track)
else:
track.re_activate_(det, self.frame_id_, new_id=False)
refind_stracks.append(track)
dets_ids[dets_index[idet]] = track.track_id
''' Step 3: Second association, with IOU'''
dets_index = [dets_index[i] for i in u_detection]
detections = [detections[i] for i in u_detection]
r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked]
dists = matching.iou_distance(r_tracked_stracks, detections)
matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.5)
for itracked, idet in matches:
track = r_tracked_stracks[itracked]
det = detections[idet]
assert last_id_features[dets_index[idet]] is None
assert last_ad_id_features[dets_index[idet]] is None
last_id_features[dets_index[idet]] = track.smooth_feat
last_ad_id_features[dets_index[idet]] = track.smooth_feat_ad
tracks_ad.append((track, dets_index[idet]))
if track.state == TrackState.Tracked:
track.update(det, self.frame_id_)
activated_starcks.append(track)
else:
track.re_activate_(det, self.frame_id_, new_id=False)
refind_stracks.append(track)
dets_ids[dets_index[idet]] = track.track_id
for it in u_track:
track = r_tracked_stracks[it]
if not track.state == TrackState.Lost:
track.mark_lost()
lost_stracks.append(track)
'''Deal with unconfirmed tracks, usually tracks with only one beginning frame'''
dets_index = [dets_index[i] for i in u_detection]
detections = [detections[i] for i in u_detection]
dists = matching.iou_distance(unconfirmed, detections)
matches, u_unconfirmed, u_detection = matching.linear_assignment(dists, thresh=0.7)
for itracked, idet in matches:
assert last_id_features[dets_index[idet]] is None
assert last_ad_id_features[dets_index[idet]] is None
last_id_features[dets_index[idet]] = unconfirmed[itracked].smooth_feat
last_ad_id_features[dets_index[idet]] = unconfirmed[itracked].smooth_feat_ad
tracks_ad.append((unconfirmed[itracked], dets_index[idet]))
unconfirmed[itracked].update(detections[idet], self.frame_id_)
activated_starcks.append(unconfirmed[itracked])
dets_ids[dets_index[idet]] = unconfirmed[itracked].track_id
for it in u_unconfirmed:
track = unconfirmed[it]
track.mark_removed()
removed_stracks.append(track)
""" Step 4: Init new stracks"""
for inew in u_detection:
track = detections[inew]
if track.score < self.det_thresh:
continue
track.activate_(self.kalman_filter_, self.frame_id_)
activated_starcks.append(track)
dets_ids[dets_index[inew]] = track.track_id
""" Step 5: Update state"""
for track in self.lost_stracks_:
if self.frame_id_ - track.end_frame > self.max_time_lost:
track.mark_removed()
removed_stracks.append(track)
# print('Ramained match {} s'.format(t4-t3))
self.tracked_stracks_ = [t for t in self.tracked_stracks_ if t.state == TrackState.Tracked]
self.tracked_stracks_ = joint_stracks(self.tracked_stracks_, activated_starcks)
self.tracked_stracks_ = joint_stracks(self.tracked_stracks_, refind_stracks)
self.lost_stracks_ = sub_stracks(self.lost_stracks_, self.tracked_stracks_)
self.lost_stracks_.extend(lost_stracks)
self.lost_stracks_ = sub_stracks(self.lost_stracks_, self.removed_stracks_)
self.removed_stracks_.extend(removed_stracks)
self.tracked_stracks_, self.lost_stracks_ = remove_duplicate_stracks(self.tracked_stracks_, self.lost_stracks_)
# get scores of lost tracks
output_stracks_ori = [track for track in self.tracked_stracks_ if track.is_activated]
id_set = set([track.track_id for track in output_stracks_ori])
for i in range(len(dets_ids)):
if dets_ids[i] is not None and dets_ids[i] not in id_set:
dets_ids[i] = None
output_stracks_ori_ind = []
for ind, track in enumerate(output_stracks_ori):
if track.track_id not in self.multiple_ori_ids:
self.multiple_ori_ids[track.track_id] = 0
self.multiple_ori_ids[track.track_id] += 1
if self.multiple_ori_ids[track.track_id] <= self.FRAME_THR:
output_stracks_ori_ind.append(ind)
logger.debug('===========Frame {}=========='.format(self.frame_id_))
logger.debug('Activated: {}'.format([track.track_id for track in activated_starcks]))
logger.debug('Refind: {}'.format([track.track_id for track in refind_stracks]))
logger.debug('Lost: {}'.format([track.track_id for track in lost_stracks]))
logger.debug('Removed: {}'.format([track.track_id for track in removed_stracks]))
attack_ids = []
target_ids = []
attack_inds = []
target_inds = []
noise = None
if len(dets) > 0:
ious = bbox_ious(np.ascontiguousarray(dets[:, :4], dtype=np.float64),
np.ascontiguousarray(dets[:, :4], dtype=np.float64))
ious[range(len(dets)), range(len(dets))] = 0
ious_inds = np.argmax(ious, axis=1)
dis = bbox_dis(np.ascontiguousarray(dets[:, :4], dtype=np.float64),
np.ascontiguousarray(dets[:, :4], dtype=np.float64))
dis[range(len(dets)), range(len(dets))] = np.inf
dis_inds = np.argmin(dis, axis=1)
for attack_ind, track_id in enumerate(dets_ids):
if track_id is None or self.multiple_ori_ids[track_id] <= self.FRAME_THR \
or dets_ids[ious_inds[attack_ind]] not in self.multiple_ori2att \
or track_id not in self.multiple_ori2att:
continue
if ious[attack_ind, ious_inds[attack_ind]] > self.ATTACK_IOU_THR or (
track_id in self.low_iou_ids and ious[attack_ind, ious_inds[attack_ind]] > 0
):
attack_ids.append(track_id)
target_ids.append(dets_ids[ious_inds[attack_ind]])
attack_inds.append(attack_ind)
target_inds.append(ious_inds[attack_ind])
if hasattr(self, f'temp_i_{track_id}'):
self.__setattr__(f'temp_i_{track_id}', 0)
elif ious[attack_ind, ious_inds[attack_ind]] == 0 and track_id in self.low_iou_ids:
if hasattr(self, f'temp_i_{track_id}'):
self.__setattr__(f'temp_i_{track_id}', self.__getattribute__(f'temp_i_{track_id}') + 1)
else:
self.__setattr__(f'temp_i_{track_id}', 1)
if self.__getattribute__(f'temp_i_{track_id}') > 10:
self.low_iou_ids.remove(track_id)
elif dets_ids[dis_inds[attack_ind]] in self.multiple_ori2att:
attack_ids.append(track_id)
target_ids.append(dets_ids[dis_inds[attack_ind]])
attack_inds.append(attack_ind)
target_inds.append(dis_inds[attack_ind])
fit_index = self.CheckFit(dets, id_feature, attack_ids, attack_inds) if len(attack_ids) else []
if fit_index:
attack_ids = np.array(attack_ids)[fit_index]
target_ids = np.array(target_ids)[fit_index]
attack_inds = np.array(attack_inds)[fit_index]
target_inds = np.array(target_inds)[fit_index]
att_trackers = []
for attack_id in attack_ids:
if attack_id not in self.ad_ids:
for t in output_stracks_ori:
if t.track_id == attack_id:
att_trackers.append(t)
noise, attack_iter, suc = self.attack_mt_hj(
im_blob,
img0,
dets,
inds,
remain_inds,
last_info=self.ad_last_info,
outputs_ori=output,
attack_ids=attack_ids,
attack_inds=attack_inds,
ad_ids=self.ad_ids,
track_vs=[t.get_v() for t in att_trackers]
)
self.ad_ids.update(attack_ids)
self.low_iou_ids.update(set(attack_ids))
if suc:
self.attacked_ids.update(set(attack_ids))
print(
f'attack ids: {attack_ids}\tattack frame {self.frame_id_}: SUCCESS\tl2 distance: {(noise ** 2).sum().sqrt().item()}\titeration: {attack_iter}')
else:
print(f'attack ids: {attack_ids}\tattack frame {self.frame_id_}: FAIL\tl2 distance: {(noise ** 2).sum().sqrt().item() if noise is not None else None}\titeration: {attack_iter}')
if noise is not None:
l2_dis = (noise ** 2).sum().sqrt().item()
adImg = torch.clip(im_blob + noise, min=0, max=1)
noise = self.recoverNoise(noise, img0)
noise = (noise - np.min(noise)) / (np.max(noise) - np.min(noise))
noise = (noise * 255).astype(np.uint8)
else:
l2_dis = None
adImg = im_blob
output_stracks_att = self.update(adImg, img0)
adImg = self.recoverNoise(adImg.detach(), img0)
output_stracks_att_ind = []
for ind, track in enumerate(output_stracks_att):
if track.track_id not in self.multiple_att_ids:
self.multiple_att_ids[track.track_id] = 0
self.multiple_att_ids[track.track_id] += 1
if self.multiple_att_ids[track.track_id] <= self.FRAME_THR:
output_stracks_att_ind.append(ind)
if len(output_stracks_ori_ind) and len(output_stracks_att_ind):
ori_dets = [track.curr_tlbr for i, track in enumerate(output_stracks_ori) if i in output_stracks_ori_ind]
att_dets = [track.curr_tlbr for i, track in enumerate(output_stracks_att) if i in output_stracks_att_ind]
ori_dets = np.stack(ori_dets).astype(np.float64)
att_dets = np.stack(att_dets).astype(np.float64)
ious = bbox_ious(ori_dets, att_dets)
row_ind, col_ind = linear_sum_assignment(-ious)
for i in range(len(row_ind)):
if ious[row_ind[i], col_ind[i]] > 0.9:
ori_id = output_stracks_ori[output_stracks_ori_ind[row_ind[i]]].track_id
att_id = output_stracks_att[output_stracks_att_ind[col_ind[i]]].track_id
self.multiple_ori2att[ori_id] = att_id
return output_stracks_ori, output_stracks_att, adImg, noise, l2_dis
def update(self, im_blob, img0, **kwargs):
self.frame_id += 1
self_track_id = kwargs.get('track_id', None)
activated_starcks = []
refind_stracks = []
lost_stracks = []
removed_stracks = []
width = img0.shape[1]
height = img0.shape[0]
inp_height = im_blob.shape[2]
inp_width = im_blob.shape[3]
c = np.array([width / 2., height / 2.], dtype=np.float32)
s = max(float(inp_width) / float(inp_height) * height, width) * 1.0
meta = {'c': c, 's': s,
'out_height': inp_height // self.opt.down_ratio,
'out_width': inp_width // self.opt.down_ratio}
''' Step 1: Network forward, get detections & embeddings'''
with torch.no_grad():
output = self.model(im_blob)[-1]
hm = output['hm'].sigmoid_()
wh = output['wh']
id_feature = output['id']
id_feature = F.normalize(id_feature, dim=1)
reg = output['reg'] if self.opt.reg_offset else None
dets, inds = mot_decode(hm, wh, reg=reg, cat_spec_wh=self.opt.cat_spec_wh, K=self.opt.K)
id_feature_ = id_feature.permute(0, 2, 3, 1).view(-1, 512)
id_feature = _tranpose_and_gather_feat(id_feature, inds)
id_feature = id_feature.squeeze(0)
id_feature = id_feature.detach().cpu().numpy()
dets = self.post_process(dets, meta)
dets = self.merge_outputs([dets])[1]
remain_inds = dets[:, 4] > self.opt.conf_thres
dets = dets[remain_inds]
id_feature = id_feature[remain_inds]
# import pdb; pdb.set_trace()
dets_index = inds[0][remain_inds].tolist()
# vis
'''
for i in range(0, dets.shape[0]):
bbox = dets[i][0:4]
cv2.rectangle(img0, (bbox[0], bbox[1]),
(bbox[2], bbox[3]),
(0, 255, 0), 2)
cv2.imshow('dets', img0)
cv2.waitKey(0)
id0 = id0-1
'''
if len(dets) > 0:
'''Detections'''
detections = [STrack(STrack.tlbr_to_tlwh(tlbrs[:4]), tlbrs[4], f, 30) for
(tlbrs, f) in zip(dets[:, :5], id_feature)]
else:
detections = []
''' Add newly detected tracklets to tracked_stracks'''
unconfirmed = []
tracked_stracks = [] # type: list[STrack]
for track in self.tracked_stracks:
if not track.is_activated:
unconfirmed.append(track)
else:
tracked_stracks.append(track)
''' Step 2: First association, with embedding'''
strack_pool = joint_stracks(tracked_stracks, self.lost_stracks)
# Predict the current location with KF
# for strack in strack_pool:
# strack.predict()
STrack.multi_predict(strack_pool)
dists = matching.embedding_distance(strack_pool, detections)
dists = matching.fuse_motion(self.kalman_filter, dists, strack_pool, detections)
matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.7)
for itracked, idet in matches:
track = strack_pool[itracked]
det = detections[idet]
if track.state == TrackState.Tracked:
track.update(detections[idet], self.frame_id)
activated_starcks.append(track)
else:
track.re_activate(det, self.frame_id, new_id=False)
refind_stracks.append(track)
''' Step 3: Second association, with IOU'''
dets_index = [dets_index[i] for i in u_detection]
detections = [detections[i] for i in u_detection]
r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked]
dists = matching.iou_distance(r_tracked_stracks, detections)
matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.5)
for itracked, idet in matches:
track = r_tracked_stracks[itracked]
det = detections[idet]
if track.state == TrackState.Tracked:
track.update(det, self.frame_id)
activated_starcks.append(track)
else:
track.re_activate(det, self.frame_id, new_id=False)
refind_stracks.append(track)
for it in u_track:
track = r_tracked_stracks[it]
if not track.state == TrackState.Lost:
track.mark_lost()
lost_stracks.append(track)
'''Deal with unconfirmed tracks, usually tracks with only one beginning frame'''
dets_index = [dets_index[i] for i in u_detection]
detections = [detections[i] for i in u_detection]
dists = matching.iou_distance(unconfirmed, detections)
matches, u_unconfirmed, u_detection = matching.linear_assignment(dists, thresh=0.7)
for itracked, idet in matches:
unconfirmed[itracked].update(detections[idet], self.frame_id)
activated_starcks.append(unconfirmed[itracked])
for it in u_unconfirmed:
track = unconfirmed[it]
track.mark_removed()
removed_stracks.append(track)
""" Step 4: Init new stracks"""
for inew in u_detection:
track = detections[inew]
if track.score < self.det_thresh:
continue
track.activate(self.kalman_filter, self.frame_id, track_id=self_track_id)
activated_starcks.append(track)
""" Step 5: Update state"""
for track in self.lost_stracks:
if self.frame_id - track.end_frame > self.max_time_lost:
track.mark_removed()
removed_stracks.append(track)
# print('Ramained match {} s'.format(t4-t3))
self.tracked_stracks = [t for t in self.tracked_stracks if t.state == TrackState.Tracked]
self.tracked_stracks = joint_stracks(self.tracked_stracks, activated_starcks)
self.tracked_stracks = joint_stracks(self.tracked_stracks, refind_stracks)
self.lost_stracks = sub_stracks(self.lost_stracks, self.tracked_stracks)
self.lost_stracks.extend(lost_stracks)
self.lost_stracks = sub_stracks(self.lost_stracks, self.removed_stracks)
self.removed_stracks.extend(removed_stracks)
self.tracked_stracks, self.lost_stracks = remove_duplicate_stracks(self.tracked_stracks, self.lost_stracks)
# get scores of lost tracks
output_stracks = [track for track in self.tracked_stracks if track.is_activated]
logger.debug('===========Frame {}=========='.format(self.frame_id))
logger.debug('Activated: {}'.format([track.track_id for track in activated_starcks]))
logger.debug('Refind: {}'.format([track.track_id for track in refind_stracks]))
logger.debug('Lost: {}'.format([track.track_id for track in lost_stracks]))
logger.debug('Removed: {}'.format([track.track_id for track in removed_stracks]))
unconfirmed = []
tracked_stracks = [] # type: list[STrack]
for track in self.tracked_stracks:
if not track.is_activated:
unconfirmed.append(track)
else:
tracked_stracks.append(track)
''' Step 2: First association, with embedding'''
strack_pool = joint_stracks(tracked_stracks, self.lost_stracks)
self.ad_last_info = {
'last_strack_pool': copy.deepcopy(strack_pool),
'last_unconfirmed': copy.deepcopy(unconfirmed),
'kalman_filter': copy.deepcopy(self.kalman_filter_)
}
return output_stracks
def _nms(self, heat, kernel=3):
pad = (kernel - 1) // 2
hmax = nn.functional.max_pool2d(
heat, (kernel, kernel), stride=1, padding=pad)
keep = (hmax == heat).float
return keep
def computer_targets(self, boxes, gt_box):
an_ws = boxes[:, 2]
an_hs = boxes[:, 3]
ctr_x = boxes[:, 0]
ctr_y = boxes[:, 1]
gt_ws = gt_box[:, 2]
gt_hs = gt_box[:, 3]
gt_ctr_x = gt_box[:, 0]
gt_ctr_y = gt_box[:, 1]
targets_dx = (gt_ctr_x - ctr_x) / an_ws
targets_dy = (gt_ctr_y - ctr_y) / an_hs
targets_dw = np.log(gt_ws / an_ws)
targets_dh = np.log(gt_hs / an_hs)
targets = np.vstack((targets_dx, targets_dy, targets_dw, targets_dh)).T
return targets
def joint_stracks(tlista, tlistb):
exists = {}
res = []
for t in tlista:
exists[t.track_id] = 1
res.append(t)
for t in tlistb:
tid = t.track_id
if not exists.get(tid, 0):
exists[tid] = 1
res.append(t)
return res
def sub_stracks(tlista, tlistb):
stracks = {}
for t in tlista:
stracks[t.track_id] = t
for t in tlistb:
tid = t.track_id
if stracks.get(tid, 0):
del stracks[tid]
return list(stracks.values())
def remove_duplicate_stracks(stracksa, stracksb):
pdist = matching.iou_distance(stracksa, stracksb)
pairs = np.where(pdist < 0.15)
dupa, dupb = list(), list()
for p, q in zip(*pairs):
timep = stracksa[p].frame_id - stracksa[p].start_frame
timeq = stracksb[q].frame_id - stracksb[q].start_frame
if timep > timeq:
dupb.append(q)
else:
dupa.append(p)
resa = [t for i, t in enumerate(stracksa) if not i in dupa]
resb = [t for i, t in enumerate(stracksb) if not i in dupb]
return resa, resb
def save(obj, name):
with open(f'/home/derry/Desktop/{name}.pth', 'wb') as f:
pickle.dump(obj, f)
def load(name):
with open(f'/home/derry/Desktop/{name}.pth', 'rb') as f:
obj = pickle.load(f)
return obj
| 194,948 | 65,449 |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
.. module:: database
:platform: Unix
:synopsis: the top-level submodule of T_System that contains the functions and classes related to T_System's database and table creation ability. Powered by TinyDB.
.. moduleauthor:: Cem Baybars GÜÇLÜ <cem.baybars@gmail.com>
"""
from tinydb import TinyDB # TinyDB is a lightweight document oriented database
class DBFetcher:
"""Class to define an database handler with given folder and table name. It's only job creating databases or tables and returning them.
This class provides necessary initiations and functions named :func:`t_system.database.Database.get`
for return TinyDB database object.
"""
def __init__(self, folder, name, table=None, cache_size=None):
"""Initialization method of :class:`t_system.database.Database` class.
Args:
folder (str) Folder that contains database.
name (str) Name of the database.
table (str): Current working table name.
cache_size (int): TinyDB caches query result for performance.
"""
self.folder = folder
self.name = name
self.table = table
self.cache_size = cache_size
def fetch(self):
"""Method to return database. If there is a table name method creates a table and returns that. Otherwise returns all db.
Returns:
TinyDB: database object.
"""
db = TinyDB(f'{self.folder}/{self.name}.json')
if self.table:
return self.__set_table(db, self.table, self.cache_size)
return db
@staticmethod
def __set_table(db, table_name, cache_size=None):
"""Method to set database by table name.
Args:
db (TinyDB): TinyDB object.
table_name (str): Current working table name.
cache_size (int): TinyDB caches query result for performance.
"""
return db.table(table_name, cache_size=cache_size)
| 2,130 | 572 |
# Copied from cellSNP, https://github.com/single-cell-genetics/cellSNP/blob/purePython/cellSNP/utils/pileup_regions.py
# Utilility functions for pileup SNPs across regions
# originally in from pileup_utils.py
# Author: Yuanhua Huang
# Date: 21/05/2018
# Modified by: Xianjie Huang
from .pileup import *
from .sam import get_query_bases, get_query_qualities
## ealier high error in pileup whole genome might come from
## using _read.query_sequence, which has only partially aligned
## pileupread.query_position is based on the full length of the reads
## _read.qqual is based on aligned reads segment
# def pileup_bases(pileupColumn):
# """ pileup all reads mapped to the genome position.
# """
# base_list, read_list, qual_list = [], [], []
# for pileupread in pileupColumn.pileups:
# # query position is None if is_del or is_refskip is set.
# if pileupread.is_del or pileupread.is_refskip:
# continue
# #query_POS = pileupread.query_position
# query_POS = pileupread.query_position
# _read = pileupread.alignment
# try:
# _base = _read.query_sequence[query_POS - 1].upper()
# _qual = _read.qqual[query_POS - 1]
# except:
# print("warnings: a read fails to give _base or _qual.",
# query_POS, len(_read.qqual), len(_read.qual), len(_read.query_sequence))
# print(_read.qqual)
# continue
# #_qual = "J"
# read_list.append(_read)
# base_list.append(_base)
# qual_list.append(_qual)
# return base_list, qual_list, read_list
def pileup_bases(pileupColumn, real_POS, cell_tag, UMI_tag, min_MAPQ,
max_FLAG, min_LEN):
"""
Pileup all reads mapped to the genome position.
Filtering is also applied, including cell and UMI tags and read mapping
quality.
"""
base_list, qual_list, UMIs_list, cell_list = [], [], [], []
for pileupread in pileupColumn.pileups:
# query position is None if is_del or is_refskip is set.
if pileupread.is_del or pileupread.is_refskip:
continue
_read = pileupread.alignment
if real_POS is not None:
try:
idx = _read.positions.index(real_POS-1)
except:
continue
_qual = get_query_qualities(_read)[idx]
_base = get_query_bases(_read)[idx].upper()
else:
query_POS = pileupread.query_position
_qual = _read.query_qualities[query_POS - 1]
_base = _read.query_sequence[query_POS - 1].upper()
## filtering reads
if (_read.mapq < min_MAPQ or _read.flag > max_FLAG or
len(_read.positions) < min_LEN):
continue
if cell_tag is not None and _read.has_tag(cell_tag) == False:
continue
if UMI_tag is not None and _read.has_tag(UMI_tag) == False:
continue
if UMI_tag is not None:
UMIs_list.append(fmt_umi_tag(_read, cell_tag, UMI_tag))
if cell_tag is not None:
cell_list.append(_read.get_tag(cell_tag))
base_list.append(_base)
qual_list.append(_qual)
return base_list, qual_list, UMIs_list, cell_list
def pileup_regions(samFile, barcodes, out_file=None, chrom=None, cell_tag="CR",
UMI_tag="UR", min_COUNT=20, min_MAF=0.1, min_MAPQ=20,
max_FLAG=255, min_LEN=30, doublet_GL=False, verbose=True):
"""Pileup allelic specific expression for a whole chromosome in sam file.
TODO: 1) multiple sam files, e.g., bulk samples; 2) optional cell barcode
"""
samFile, chrom = check_pysam_chrom(samFile, chrom)
if out_file is not None:
fid = open(out_file, "w")
fid.writelines(VCF_HEADER + CONTIG)
if barcodes is not None:
fid.writelines("\t".join(VCF_COLUMN + barcodes) + "\n")
else:
fid.writelines("\t".join(VCF_COLUMN + ["sample0"]) + "\n")
POS_CNT = 0
vcf_lines_all = []
for pileupcolumn in samFile.pileup(contig=chrom):
POS_CNT += 1
if verbose and POS_CNT % 1000000 == 0:
print("%s: %dM positions processed." %(chrom, POS_CNT/1000000))
if pileupcolumn.n < min_COUNT:
continue
base_list, qual_list, UMIs_list, cell_list = pileup_bases(pileupcolumn,
pileupcolumn.pos + 1, cell_tag, UMI_tag, min_MAPQ, max_FLAG, min_LEN)
if len(base_list) < min_COUNT:
continue
base_merge, base_cells, qual_cells = map_barcodes(base_list, qual_list,
cell_list, UMIs_list, barcodes)
vcf_line = get_vcf_line(base_merge, base_cells, qual_cells,
pileupcolumn.reference_name, pileupcolumn.pos + 1, min_COUNT, min_MAF,
doublet_GL = doublet_GL)
if vcf_line is not None:
if out_file is None:
vcf_lines_all.append(vcf_line)
else:
fid.writelines(vcf_line)
if out_file is not None:
fid.close()
return vcf_lines_all
| 5,153 | 1,753 |
import importlib
# from scrapy_framework.config.settings import SPIDERS
#
#
# for data in SPIDERS:
# print(data)
# path=data.rsplit(".",1)[0]
# cls_name=data.rsplit(".",1)[1]
# module=importlib.import_module(path)
# cls=getattr(module, cls_name)
# print(cls)
d = {'a':1,'b':4,'c':2}
c=sorted(d.items(), key=lambda x: x[1], reverse=False)
print(c) | 374 | 156 |
from django.urls import path
from .views import LibraryView, PhotosView, AlbumsView, PhotoView, AlbumView
from .views import PhotoCreateView, AlbumCreateView, PhotoEditView, AlbumEditView
urlpatterns = [
path('library/', LibraryView.as_view(), name='library'),
path('photos/', PhotosView.as_view(), name='photos'),
path('photos/<int:pk>', PhotoView.as_view(), name='photo'),
path('photos/<int:pk>/edit', PhotoEditView.as_view(), name='photo_edit'),
path('albums/', AlbumsView.as_view(), name='albums'),
path('albums/<int:pk>', AlbumView.as_view(), name='album'),
path('albums/<int:pk>/edit', AlbumEditView.as_view(), name='album_edit'),
path('photos/add', PhotoCreateView.as_view(), name='photo_create'),
path('albums/add', AlbumCreateView.as_view(), name='album_create')
]
| 812 | 273 |
class Solution:
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
result = collections.defaultdict(list)
for s in strs:
key = "".join(sorted(s))
result[key].append(s)
return result.values()
| 310 | 96 |
from django.urls import path
from app import views
app_name = 'poll'
urlpatterns = [
path('', views.home, name='home'),
path('register', views.register, name='register'),
path('login', views.admin_login, name='login'),
path('create_poll/', views.create_poll, name='create_poll'),
path('show_polls/', views.show_poll, name='show_polls'),
path('show_polls/<slug:username>/', views.show_polls, name='show_polls'),
path('save_poll/', views.save_poll, name='save_poll'),
path('polling/<uuid:id>/', views.polling, name='polling'),
path('logout/', views.admin_logout, name='logout'),
path('poll_result/<uuid:id>/', views.poll_result, name='poll_result'),
path('get_data/<uuid:id>/', views.get_data, name='get_data'),
]
| 758 | 279 |
class Solution:
def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
results = []
mini = 1000000000
arr.sort()
for a,b in zip(arr,arr[1:]):
diff = abs(a-b)
if diff == mini:
results.append([a,b])
#print("ppp",results)
elif diff < mini:
mini = diff
results = [(a,b)]
#print("sss",results)
return results
| 501 | 147 |
import torch
import torch.nn as nn
class SEBlock(nn.Module):
def __init__(self, in_c, kernel_size, r, dummy_x) -> None:
super().__init__()
self.in_c = in_c
self.conv1 = nn.Conv1d(in_channels=self.in_c,
out_channels=self.in_c, kernel_size=kernel_size, padding=int(kernel_size//2))
self.fc1 = nn.Linear(in_features=self.in_c,
out_features=int(self.in_c/r))
self.fc2 = nn.Linear(in_features=int(
self.in_c/r), out_features=self.in_c)
self.relu = nn.ReLU()
self.sigmoid = nn.Sigmoid()
dumm_y = self.conv1(dummy_x)
self.L = dumm_y.shape[-1]
def forward(self, x_in):
x_res = self.conv1(x_in) # (-1,C,L)
x = self.global_avg_pooling(x_res) # (-1,C,1)
x = x.view(-1, self.in_c) # (-1,C)
x = self.fc1(x) # (-1,C/r)
x = self.relu(x) # (-1,C/r)
x = self.fc2(x) # (-1,C)
x = self.sigmoid(x) # (-1,C)
x = x.view(-1, self.in_c, 1) # (-1,C,1)
x = self.scale(x_res, x) # (-1,C,L)
x = x_in + x # (-1,C,L)
return x # (-1,C,L)
def global_avg_pooling(self, x):
net = nn.AvgPool1d(kernel_size=self.L)
return net(x) # (-1,c,1)
def scale(self, x_res, x):
return torch.mul(x_res, x)
if __name__ == "__main__":
in_c = 5
r = 4
kernel_size = 7
dummy_x = torch.randn((2, in_c, 128))
senet = SEBlock(in_c=in_c, r=r, kernel_size=kernel_size, dummy_x=dummy_x)
out = senet(dummy_x)
print(out.shape)
| 1,588 | 710 |
import numpy as np
from otk import rii
def test_rii():
pages = rii.search('Eimerl-o', 'BaB2O4')
assert len(pages) == 1
entry = rii.load_page(pages[0])
index = rii.parse_entry(entry)
assert (abs(index(220e-9) - 1.8284) < 1e-3)
def test_lookup_index():
assert (abs(rii.lookup_index('Malitson', 'SiO2')(800e-9) - 1.4533) < 1e-3)
assert np.isclose(rii.lookup_index('Li-293K', 'Si')(1.3e-6), 3.5016, atol=1e-4)
assert np.isclose(rii.lookup_index('Vuye-250C', 'Si')(0.5e-6), 4.4021 + 0.04j, atol=1e-4)
| 532 | 273 |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('motech', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='requestlog',
name='payload_id',
field=models.CharField(blank=True, max_length=126, null=True),
),
]
| 355 | 109 |
from . import base
from revibe._helpers import const, status
# -----------------------------------------------------------------------------
class ParameterMissingError(base.ExpectationFailedError):
default_detail = "missing paramter, please check the docs for request requirements"
class SerializerValidationError(base.ExpectationFailedError):
default_detail = "misc. serializer error, please try again"
class TooManyObjectsReturnedError(base.ProgramError):
default_detail = "Too many objects found, please try again"
class ObjectAlreadyExists(base.AlreadyReportedError):
default_detail = "The request object already exists"
class NoKeysError(base.ServiceUnavailableError):
default_detail = "Could not find any valid keys"
| 754 | 189 |
import os
from datetime import datetime
def list_sub_dirs(dir_path):
if not os.path.exists(dir_path):
raise RuntimeError("invalid dir path.")
if not os.path.isdir(dir_path):
raise RuntimeError("invalid dir path.")
sub_dirs = []
sub_files = os.listdir(dir_path)
for sub_file_name in sub_files:
sub_file_path = os.path.join(dir_path, sub_file_name)
if not os.path.isdir(sub_file_path):
continue
sub_dirs.append(sub_file_path)
return sub_dirs
def flatten_dir_path(dir_path):
sub_dirs = list_sub_dirs(dir_path)
for sub_dir_path in sub_dirs:
sub_sub_dirs = list_sub_dirs(sub_dir_path)
for sub_sub_dir_path in sub_sub_dirs:
sub_sub_dir_name = os.path.basename(sub_sub_dir_path)
target_dir_path = '_'.join([sub_dir_path, sub_sub_dir_name])
print(f"move: {sub_sub_dir_path} -> {target_dir_path}")
os.renames(sub_sub_dir_path, target_dir_path)
def create_dir(dir_path):
if not os.path.exists(dir_path):
os.makedirs(dir_path)
return dir_path
return create_dir(dir_path + "." + datetime.now().strftime("%Y%m%d%H%M%S"))
| 1,188 | 439 |
#Clean Code for Picture uploader for social media platform
import praw
import random
import pandas as pd
import config
from openpyxl import load_workbook
import requests
import json
#Reddit Creds
r = praw.Reddit(
client_id= "Enter Info Here",
client_secret= "Enter Info Here",
user_agent= "Enter Info Here",
username= "Enter Info Here",
password= "Enter Info Here",
)
#SubReddit List
reddit_list = config.subreddit_list
#Praw Scrape
pics = []
Reddit_Scrapper = True
while Reddit_Scrapper:
subreddit = r.subreddit(random.choice(reddit_list))
for submission in subreddit.hot(limit=10):
try:
if 'jpg' not in submission.url:
continue
if submission.stickied:
continue
pic_tittle = submission.title
url = submission.url
un_id = submission.id
pics.append((pic_tittle, url, un_id))
except:
pass
#Check if post was already posted
#If it doesnt exist in Excel then continue
df = pd.read_excel(r'subrreddit_history.xlsx')
checker = True
while checker:
if len(pics) == 0:
checker = False
if pics[0][2] in df.values:
pics.pop(0)
if len(pics) == 0:
checker = False
else:
checker = False
if len(pics) > 1:
Reddit_Scrapper = False
# If data doesnt exist then append row
df = pd.DataFrame({'un_id': [pics[0][2]],
'pic_tittle': [pics[0][0]]})
writer = pd.ExcelWriter('subrreddit_history.xlsx', engine='openpyxl')
# try to open an existing workbook
writer.book = load_workbook('subrreddit_history.xlsx')
# copy existing sheets
writer.sheets = dict((ws.title, ws) for ws in writer.book.worksheets)
# read existing file
reader = pd.read_excel(r'subrreddit_history.xlsx')
# write out the new sheet
df.to_excel(writer,index=False,header=False,startrow=len(reader)+1)
writer.close()
#this will get the Tittle of the post split it and add #s ad the beggining of each word for Tags.
def fb_descript():
tags = []
s = ' '
for x in pics[0][0].split():
tags.append('#' + x)
s = s.join(tags)
return ''' {a}
{c}
{c}
{c}
{c}
{c}
{c}
{c}
{c}
{c}
{c}
{b}'''.format(a=pics[0][0], b=s, c='.' *5)
#FB Credits and Photo Post
#INstagram Post Def
def postInstagramPic():
#Post the Image
image_location_1 = pics[0][1]
post_url = 'https://graph.facebook.com/v10.0/{}/media'.format(config.inst_id)
payload = {
'image_url': image_location_1,
'caption': fb_descript(),
'access_token': config.inst_acc_token,
}
r = requests.post(post_url, data=payload)
print(r.text)
#Instagram for some reason will need to convert the responde ID to a publish request.
result = json.loads(r.text)
if 'id' in result:
creation_id = result['id']
second_url = 'https://graph.facebook.com/v10.0/{}/media_publish'.format(config.inst_id)
second_payload = {
'creation_id': creation_id,
'access_token': config.inst_acc_token,
}
r = requests.post(second_url, data=second_payload)
print('--------Just posted to instagram--------')
print(r.text)
else:
pass
postInstagramPic()
#Facebook Picture Def
def post_FBpage():
image_url = 'https://graph.facebook.com/{}/photos'.format(config.fb_page_id)
image_location = pics[0][1]
msg = fb_descript()
img_payload = {
'message': msg,
'url': image_location,
'access_token': config.fb_acc_token
}
#Send the POST request
r = requests.post(image_url, data=img_payload)
print('--------Just posted to Facebook--------')
print(r.text)
post_FBpage() | 3,885 | 1,277 |
"""
Contains classes and functions useful to interact with the `Jpl Horizons
service`_ from NASA.
.. _`Jpl Horizons service`: https://ssd.jpl.nasa.gov/?horizons
"""
import requests
from astropy.table import QTable
from .util import addparams2url, wrap
from .config import read_config
from .models import BaseMap
from .horizons import JPL_ENDPOINT, transform_key, transform
from .parsers import parse, get_sections
class JplReq(BaseMap):
"""
A requests to Jpl Horizons service.
It can be thought as a :class:`dict` where key-value pairs
represents Jpl Horizons parameters. Jpl parameters can be also set
as attributes of the :class:`JplReq` instance. Furthermore, keys and
values are adjusted to match Jpl Horizons interface in order to
enhance readability and usability.
"""
def __getattr__(self, key):
key = transform_key(key)
return super(self.__class__, self).__getattr__(key)
def __setattr__(self, key, value):
k, v = transform(key, value)
super(self.__class__, self).__setattr__(k, v)
def __delattr__(self, key):
key = transform_key(key)
super(self.__class__, self).__delattr__(key)
def read(self, filename, section='DEFAULT'):
"""
Reads configurations parameters from an ini file.
Reads the `section` section of the ini config file `filename` and set all parameters
for the Jpl request.
Args:
filename (str): the config file to be read.
section (str): the section of the ini config file to be read.
Returns:
:class:`JplReq`: the object itself.
"""
params = read_config(filename, section)
return self.set(params)
def url(self):
"""
Calculate the Jpl Horizons url corresponding to the :class:`JplReq`
object.
Returns:
str: the url with the Jpl parameters encoded in the query string.
"""
return addparams2url(JPL_ENDPOINT,
{k: wrap(str(v)) for k, v in self.items()})
def query(self):
"""
Performs the query to the Jpl Horizons service.
Returns:
:class:`JplRes`: the response from Jpl Horizons service.
Raises:
:class:`ConnectionError`
"""
try:
http_response = requests.get(self.url())
except requests.exceptions.ConnectionError as e:
raise ConnectionError(e.__str__())
return JplRes(http_response)
class JplRes(object):
"""A response from the Jpl Horizons service."""
def __init__(self, http_response):
"""
Initialize a :class:`JplRes` object from a `requests`_ http response
object.
Args:
http_response: the http response from Jpl Horizons service.
.. _`requests`: http://docs.python-requests.org/en/master/
"""
self.http_response = http_response
def raw(self):
"""Returns the content of the Jpl Horizons http response as is."""
return self.http_response.text
def get_header(self):
header, ephem, footer = get_sections(self.raw())
return header
def get_data(self):
header, data, footer = get_sections(self.raw())
return data
def get_footer(self):
header, ephemeris, footer = get_sections(self.raw())
return footer
def parse(self, target=QTable):
"""
Parse the http response from Jpl Horizons and return, according to
target.
* an `astropy.table.Table`_ object.
* an `astropy.table.QTable`_ object.
.. _`astropy.table.Table`: http://docs.astropy.org/en/stable/table/
.. _`astropy.table.QTable`: http://docs.astropy.org/en/stable/table/
"""
return parse(self.raw(), target=target)
def __str__(self):
return self.raw()
| 3,914 | 1,143 |
from .autoregister import autoregister
autoregister('pokedex')
| 64 | 21 |
from django.template import Library, Node, TemplateSyntaxError, Variable, VariableDoesNotExist
from django.template.base import render_value_in_context
from django.utils.safestring import SafeData, mark_safe
register = Library()
class FormattedTranslateNode(Node):
def __init__(self, filter_expression, noop, formatvalues, asvar=None,
message_context=None):
self.noop = noop
self.formatvalues = formatvalues
self.asvar = asvar
self.message_context = message_context
self.filter_expression = filter_expression
if isinstance(self.filter_expression.var, str):
self.filter_expression.var = Variable("'%s'" %
self.filter_expression.var)
def render(self, context):
self.filter_expression.var.translate = not self.noop
if self.message_context:
self.filter_expression.var.message_context = (
self.message_context.resolve(context))
output = self.filter_expression.resolve(context)
value = render_value_in_context(output, context)
# Restore percent signs. Percent signs in template text are doubled
# so they are not interpreted as string format flags.
is_safe = isinstance(value, SafeData)
value = value.replace('%%', '%')
formatvalues = []
for formatvalue in self.formatvalues:
try:
variable = Variable(formatvalue)
formatvalues.append(variable.resolve(context))
except VariableDoesNotExist:
formatvalues.append(formatvalue)
value = value.format(*formatvalues)
value = mark_safe(value) if is_safe else value
if self.asvar:
context[self.asvar] = value
return ''
else:
return value
@register.tag('transformat')
def do_translate_format(parser, token):
"""
This tag is a modified version of the trans tag. In addition to doing all the things the trans tag does, it also
performs a str.format() on the translation. The values for the format call can be added to the tag as additional
parameters.
"""
bits = token.split_contents()
if len(bits) < 2:
raise TemplateSyntaxError("'%s' takes at least one argument" % bits[0])
message_string = parser.compile_filter(bits[1])
remaining = bits[2:]
noop = False
asvar = None
message_context = None
seen = set()
invalid_context = {'as', 'noop'}
formatvalues = []
while remaining:
option = remaining.pop(0)
if option in seen:
raise TemplateSyntaxError(
"The '%s' option was specified more than once." % option,
)
elif option == 'noop':
noop = True
elif option == 'context':
try:
value = remaining.pop(0)
except IndexError:
raise TemplateSyntaxError(
"No argument provided to the '%s' tag for the context option." % bits[0]
)
if value in invalid_context:
raise TemplateSyntaxError(
"Invalid argument '%s' provided to the '%s' tag for the context option" % (value, bits[0]),
)
message_context = parser.compile_filter(value)
elif option == 'as':
try:
value = remaining.pop(0)
except IndexError:
raise TemplateSyntaxError(
"No argument provided to the '%s' tag for the as option." % bits[0]
)
asvar = value
else:
formatvalues.append(option)
seen.add(option)
return FormattedTranslateNode(message_string, noop, formatvalues, asvar, message_context)
| 3,834 | 975 |
from rest_framework import response, viewsets
from .serializers import LoginSerializer
class LoginViewSet(viewsets.GenericViewSet):
serializer_class = LoginSerializer
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
token = serializer.save()
return response.Response({'token': token.key})
| 422 | 116 |
import os
import numpy as np
import tensorflow as tf
from .rnn import model_tensorflow
import re
import pickle
DIR = os.path.dirname(os.path.abspath(__file__))
def generate_tensorflow(process_path=DIR + '/model/poem/poem.pkl',
model_path=DIR + '/model/poem/train',
maxlen=80,
newline=True
):
'''
:param process_path: 训预处理模型路径
:param model_path: 网络参数路径
:param maxlen: maxlen创作最大长度
:return:
'''
with open(process_path, mode='rb') as f:
data_process = pickle.load(f)
word_index = data_process.word_index
input_data = tf.placeholder(tf.int32, [None, None])
output_targets = tf.placeholder(tf.int32, [None, None])
tensors = model_tensorflow(input_data=input_data,
output_targets=output_targets,
num_words=data_process.num_words,
num_units=data_process.num_units,
num_layers=data_process.num_layers,
batchsize=1)
saver = tf.train.Saver(tf.global_variables())
initializer = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(initializer)
checkpoint = tf.train.latest_checkpoint(model_path)
saver.restore(sess, checkpoint)
while True:
print('创作前请确保有模型。输入开头,quit=离开;\n请输入命令:')
start_word = input()
if start_word == 'quit':
print('\n再见!')
break
if start_word == '':
words = list(word_index.keys())
# 随机初始不能是标点和终止符
for i in ['。', '?', '!', 'E']:
words.remove(i)
start_word = np.random.choice(words, 1)
try:
print('开始创作')
input_index = []
for i in start_word:
index_next = word_index[i]
input_index.append(index_next)
input_index = input_index[:-1]
# 原则上不会出现0,保险起见还是加上去
while index_next not in [0, word_index['E']]:
input_index.append(index_next)
y_predict = sess.run(tensors['prediction'],
feed_dict={input_data: np.array([input_index])})
y_predict = y_predict[-1]
index_next = np.random.choice(np.arange(len(y_predict)), p=y_predict)
if len(input_index) > maxlen:
break
index_word = {word_index[i]: i for i in word_index}
text = [index_word[i] for i in input_index]
text = ''.join(text)
except Exception as e:
print(e)
text = '不能识别%s' % start_word
finally:
print('创作完成:\n')
if newline:
text_list = re.findall(pattern='[^。?!]*[。?!]', string=text)
for i in text_list:
print(i)
else:
print(text)
print('\n------------我是分隔符------------\n')
if __name__ == '__main__':
generate_tensorflow(process_path=DIR + '/model/poem/poem.pkl',
model_path=DIR + '/model/poem/train',
maxlen=100)
| 3,425 | 1,065 |
from datetime import datetime
from sqlalchemy import (
Boolean,
Column,
DateTime,
Float,
Integer,
String,
Text,
UniqueConstraint,
)
from app.config import settings
from app.db.base_class import Base
class Model(Base):
__tablename__ = "model"
id = Column(Integer, primary_key=True, index=True, autoincrement=True)
hash = Column(String(settings.HASH_LEN_LIMIT), index=True)
name = Column(String(settings.NAME_LEN_LIMIT), index=True)
state = Column(Integer, index=True)
map = Column(Float)
parameters = Column(Text(settings.PARA_LEN_LIMIT))
task_id = Column(Integer, index=True)
user_id = Column(Integer, index=True)
is_deleted = Column(Boolean, default=False)
create_datetime = Column(DateTime, default=datetime.utcnow, nullable=False)
update_datetime = Column(
DateTime,
default=datetime.utcnow,
onupdate=datetime.utcnow,
nullable=False,
)
__table_args__ = (UniqueConstraint("user_id", "hash", name="uniq_user_hash"),)
| 1,042 | 335 |
#######################################################################################
# 重写 PaymentMethodView 提供多种支付方法的选择,
# 重写 PaymentDetailsView 支付细节在具体支付方法包(例如alipay)中实现
#######################################################################################
from oscar.apps.checkout.views import PaymentMethodView,PaymentDetailsView as OscarPaymentDetailsView
from alipay.warrant.views import AlipayHandle
from django.http import HttpResponseRedirect
from .mixins import RedirectSessionMixin
from oscar.core.loading import get_class, get_classes, get_model
OrderPlacementMixin = get_class('checkout.mixins', 'OrderPlacementMixin')
class MultiPaymentMethodView(PaymentMethodView):
template_name = 'oscar/checkout/payment_method.html'
def get(self, request, *args, **kwargs):
# By default we redirect straight onto the payment details view. Shops
# that require a choice of payment method may want to override this
# method to implement their specific logic.
context = self.get_context_data(**kwargs)
return self.render_to_response(context)
class MultiPaymentDetailsView(RedirectSessionMixin,OscarPaymentDetailsView):
template_name = 'oscar/checkout/payment_details.html'
template_name_preview = 'oscar/checkout/preview.html'
paymentsource_name={
'alipay_warrant':"支付宝担保",
}
paymentsource_method={
'alipay_warrant':AlipayHandle
}
def get_context_data(self, **kwargs):
context=super(PaymentDetailsView,self).get_context_data(**kwargs)
context['paymethod']=self.paymentsource_name[self.get_paymethod()]
return context
def get(self, request, *args, **kwargs):
if kwargs.get('paymethod'):
self.save_paymethod(kwargs.get('paymethod'))
return HttpResponseRedirect('/checkout/preview')
return super(PaymentDetailsView,self).get(self,request, *args, **kwargs)
def handle_payment(self, order_number, order_total, **kwargs):
'''
处理支付请求
:param order_number:
:param total_incl_tax:
:param kwargs:
:return:
'''
self.set_order_number(order_number)
self.set_info()
paymethod=self.paymentsource_method[self.get_paymethod()]
paymethod(self,order_number, **kwargs)
from oscar.apps.checkout.views import * | 2,348 | 702 |
import numpy as np
import matplotlib.pyplot as plt
from keras.models import Sequential, Model
from keras.layers import Dense, Activation, Input, Dropout, Flatten, Reshape, \
Conv2D, MaxPooling2D, concatenate, GlobalMaxPooling2D
from keras.datasets import cifar100
from keras.callbacks import EarlyStopping
from keras.utils import to_categorical, plot_model
from keras.optimizers import Adam
from keras.applications.vgg16 import VGG16
from skimage import transform, color
(X_train, y_train), (X_test, y_test) = cifar100.load_data(label_mode='fine')
| 553 | 187 |
import numpy
import torch
import scipy
import scipy.sparse as sp
import logging
from six.moves import xrange
from collections import OrderedDict
import sys
import pdb
from sklearn import metrics
import torch.nn.functional as F
from torch.autograd import Variable
def compute_metrics(predictions, targets):
pred=predictions.numpy()
targets=targets.numpy()
R2,p=scipy.stats.pearsonr(numpy.squeeze(targets),numpy.squeeze(pred))
MSE=metrics.mean_squared_error(targets, pred)
return MSE, R2
| 497 | 175 |
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from scrapy_ffxiv.items import FfxivGatheringNode
"""
Spider to gather info from `www.ffxiv-gathering.com`
"""
class GatheringSpider(CrawlSpider):
name = 'ff14-gathering'
allowed_domains = [
'ffxiv-gathering.com',
]
start_urls = [
'https://www.ffxiv-gathering.com/all.php',
]
rules = (
Rule(LinkExtractor(allow=('ff14fish.carbuncleplushy.com/index.html')), callback='parse_fishing_nodes'),
)
def parse_start_url(self, response):
nodes = response.selector.xpath("//table[contains(@id, 'myTable')]/tbody/tr")
for node in nodes:
yield FfxivGatheringNode(name=node.xpath(".//td[1]/text()").get(),
location=node.xpath(".//td[4]/text()").get(),
time=node.xpath(".//td[6]/text()").get(),
gclass=node.xpath(".//td[7]/text()").get())
def parse_fishing_node(self, response):
nodes = response.selector.xpath("//table[@id='fishes/tbody/tr[contains(@class, 'fish-entry')]")
for node in nodes:
yield {
'item': node.xpath(".//td//a[@class='fish-name']/text()").get(),
'level': '1',
'location': node.xpath(".//td//a[@class='location-name']/text()").get() + ' - ' + node.xpath(".//td//span[@class='zone-name']/text()").get(),
'time': 'Anytime',
'class': 'Fishing',
}
| 1,585 | 512 |
import pytest
@pytest.mark.parametrize("name", [
("openstack-dashboard"),
("httpd"),
("memcached"),
])
def test_packages(host, name):
pkg = host.package(name)
assert pkg.is_installed
@pytest.mark.parametrize("name,port", [
("httpd","80"),
("httpd-ssl","443"),
("memcached","11211"),
])
def test_listening_interfaces(host, name, port):
sckt = host.socket("tcp://0.0.0.0:" + port)
assert sckt.is_listening
@pytest.mark.parametrize("process,enabled", [
("httpd", True),
("memcached", True),
])
def test_services(host, process, enabled):
svc = host.service(process)
assert svc.is_running
if enabled:
assert svc.is_enabled
@pytest.mark.parametrize("service,conf_file", [
("openstack-dashboard", "local_settings"),
])
def test_main_services_files(host, service, conf_file):
_file = host.file("/etc/" + service + "/" + conf_file)
assert _file.exists
| 927 | 344 |